query
stringlengths
9
34k
document
stringlengths
8
5.39M
negatives
sequencelengths
19
20
metadata
dict
Sets up labels and controls of all options of the currently selected category.
function displayOptions() { // Hide all controls for (let body of Engine.GetGUIObjectByName("option_controls").children) { body.hidden = true; for (let control of body.children) control.hidden = true; } // Initialize label and control of each option for this category for (let i = 0; i < g_Options[g_TabCategorySelected].options.length; ++i) { // Position vertically let body = Engine.GetGUIObjectByName("option_control[" + i + "]"); let bodySize = body.size; bodySize.top = g_OptionControlOffset + i * (g_OptionControlHeight + g_OptionControlDist); bodySize.bottom = bodySize.top + g_OptionControlHeight; body.size = bodySize; body.hidden = false; // Load option data let option = g_Options[g_TabCategorySelected].options[i]; let optionType = g_OptionType[option.type]; let value = optionType.configToValue(Engine.ConfigDB_GetValue("user", option.config)); // Setup control let control = Engine.GetGUIObjectByName("option_control_" + option.type + "[" + i + "]"); control.tooltip = option.tooltip + (optionType.tooltip ? "\n" + optionType.tooltip(value, option) : ""); control.hidden = false; if (optionType.initGUI) optionType.initGUI(option, control); control[optionType.guiSetter] = function() {}; optionType.valueToGui(value, control); if (optionType.sanitizeValue) optionType.sanitizeValue(value, control, option); control[optionType.guiSetter] = function() { let value = optionType.guiToValue(control); if (optionType.sanitizeValue) optionType.sanitizeValue(value, control, option); control.tooltip = option.tooltip + (optionType.tooltip ? "\n" + optionType.tooltip(value, option) : ""); Engine.ConfigDB_CreateValue("user", option.config, String(value)); Engine.ConfigDB_SetChanges("user", true); if (option.function) Engine[option.function](value); if (option.callback) g_CloseCallbacks.add(option.callback); enableButtons(); }; // Setup label let label = Engine.GetGUIObjectByName("option_label[" + i + "]"); label.caption = option.label; label.tooltip = option.tooltip; label.hidden = false; let labelSize = label.size; labelSize.left = option.dependencies ? g_DependentLabelIndentation : 0; labelSize.rright = control.size.rleft; label.size = labelSize; } enableButtons(); }
[ "init() {\n const defaultCat = controller.getCat(0);\n controller.setCurrentCat(0);\n this.displayCat(defaultCat);\n }", "function writeCategories() {\n for (i = 0; i < 4; i++) {\n var ranNum = makeUniqueRandom(selectCategory.length, uniqueCategory);\n var isDisabled = $(\"#categoryBtn-\" + i).attr(\"disabled\");\n if (!isDisabled) {\n $(\"#categoryBtn-\" + i).attr(\"value\", selectCategory[ranNum]);\n $(\"#categoryBtn-\" + i).text(selectCategory[ranNum]);\n }\n }\n removeUnderscores();\n }", "function setOptionLabels(mthis) {\n var products = [];\n var optVal = mthis.val();\n var attrId = parseInt(mthis.prop(\"id\").replace(/[^\\d.]/g, \"\"));\n var data = JSON.parse(getAllData());\n var options = data.attributes[attrId].options;\n options.forEach(function (cObj) {\n if (cObj.id == optVal) {\n cObj.products.forEach(function (cPro) {\n var selectIndex = jQuery(\"select\").index(mthis);\n if (selectIndex > 0) {\n var prevSelect = jQuery(\"select\").eq(selectIndex - 1);\n var prevSelectAttrId = parseInt(\n prevSelect.prop(\"id\").replace(/[^\\d.]/g, \"\")\n );\n if (!isNaN(prevSelectAttrId)) {\n var prevSelectOptions = data.attributes[prevSelectAttrId].options;\n prevSelectOptions.forEach(function (subObj) {\n if (subObj.id == prevSelect.val()) {\n if (subObj.products.indexOf(cPro) != -1) {\n products.push(cPro);\n }\n }\n });\n }\n } else {\n products.push(cPro);\n }\n });\n }\n });\n var selectIndex = jQuery(\".input-box select\").index(mthis);\n var nextSelect = jQuery(\".input-box select\").eq(selectIndex + 1);\n if (nextSelect.length > 0) {\n var nextSelectAttrId = parseInt(\n nextSelect.prop(\"id\").replace(/[^\\d.]/g, \"\")\n );\n var nextSelectOptions = data.attributes[nextSelectAttrId].options;\n nextSelect.empty();\n nextSelect.append(\"<option value>Choose an Option...</option>\");\n nextSelect.removeAttr(\"disabled\");\n nextSelectOptions.forEach(function (cObj) {\n cObj.products.forEach(function (cPro) {\n if (products.indexOf(cPro) != -1) {\n if (jQuery(\"option[value=\" + cObj.id + \"]\").length <= 0) {\n nextSelect.append(\n '<option value=\"' + cObj.id + '\">' + cObj.label + \"</option>\"\n );\n }\n }\n });\n });\n }\n}", "function setCorrectLabels() {\n var data = JSON.parse(getAllData());\n var lastPrice = data.basePrice;\n jQuery(\"select\").each(function () {\n var attrId = parseInt(\n jQuery(this)\n .prop(\"id\")\n .replace(/[^\\d.]/g, \"\")\n );\n\n if (jQuery(this).val() != \"\" && jQuery(this).val() != data.chooseText) {\n var optionPrice =\n data.attributes[attrId].options[jQuery(this)[0].selectedIndex - 1]\n .price;\n lastPrice = parseFloat(lastPrice) + parseFloat(optionPrice);\n }\n var code = data.attributes[attrId].code;\n if (!jQuery(this).is(\":visible\")) {\n var cSelect = jQuery(this);\n var options = data.attributes[attrId].options;\n jQuery(\"#\" + attrId).remove();\n cSelect.parent().append('<div id=\"' + attrId + '\"></div>');\n options.forEach(function (cObj) {\n if (jQuery(\"option[value=\" + cObj.id + \"]\").length > 0) {\n if (cSelect.val() == cObj.id) {\n jQuery(\"#\" + attrId).append(\n '<div title=\"' +\n cObj.label +\n '\" ><img style=\"outline: 4px solid #FDBA3E;\" id=\"' +\n cObj.id +\n '\" class=\"colors\" src=\"' +\n getBaseDir() +\n \"colorswatch/\" +\n attrId +\n \"/\" +\n cObj.id +\n '/img\" alt=\"' +\n cObj.label +\n '\"/></div>'\n );\n } else {\n jQuery(\"#\" + attrId).append(\n '<div title=\"' +\n cObj.label +\n '\" ><img id=\"' +\n cObj.id +\n '\" class=\"colors\" src=\"' +\n getBaseDir() +\n \"colorswatch/\" +\n attrId +\n \"/\" +\n cObj.id +\n '/img\" alt=\"' +\n cObj.label +\n '\"/></div>'\n );\n }\n } else {\n jQuery(\"#\" + attrId).append(\n '<div><img class=\"invalidOptions\" id=\"' +\n cObj.id +\n '\"src=\"' +\n getBaseDir() +\n \"colorswatch/\" +\n attrId +\n \"/\" +\n cObj.id +\n '/img\" alt=\"' +\n cObj.label +\n '\"/></div>'\n );\n }\n });\n jQuery(\"#\" + attrId).append(\"<br><br><br>\");\n }\n });\n var currency = jQuery(\".regular-price\").children(\"span\").text();\n jQuery(\n jQuery(\".regular-price\")\n .children(\"span\")\n .text(currency[0] + lastPrice)\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 updateCat() {\n\tfunction getCatCallback(event) {\n\t\tvar jsonData = JSON.parse(event.target.responseText);\n\t\tfor(var c in jsonData) {\n\t\t\tvar newCatDiv = document.createElement(\"div\");\n\t\t\tvar label = document.createElement(\"label\");\n\t\t\tvar input = document.createElement(\"input\");\n\t\t\tlabel.appendChild(document.createTextNode(jsonData[c]));\n\t\t\tlabel.setAttribute(\"for\", (jsonData[c]+\"checkbox\"));\n\t\t\tnewCatDiv.appendChild(label);\n\t\t\tinput.setAttribute(\"type\", \"checkbox\");\n\t\t\tinput.setAttribute(\"value\", jsonData[c]);\n\t\t\tinput.setAttribute(\"id\", (jsonData[c]+\"checkbox\"));\n\t\t\tinput.setAttribute(\"checked\", \"checked\");\n\t\t\tnewCatDiv.appendChild(input);\n\t\t\tcatDivPt1.appendChild(newCatDiv);\n\t\t\tdocument.getElementById(jsonData[c]+\"checkbox\").addEventListener(\"click\", updateCatDisplays, false);\n\n\t\t\tvar newOption = document.createElement(\"option\");\n\t\t\tnewOption.appendChild(document.createTextNode(jsonData[c]));\n\t\t\teditCatSelect.appendChild(newOption);\n\n\t\t\tnewOption = document.createElement(\"option\");\n\t\t\tnewOption.appendChild(document.createTextNode(jsonData[c]));\n\t\t\tcategorySelect.appendChild(newOption);\n\t\t}\n\t\tvar newCatDiv = document.createElement(\"div\");\n\t\tvar label = document.createElement(\"label\");\n\t\tvar input = document.createElement(\"input\");\n\t\tlabel.appendChild(document.createTextNode(\"uncategorized\"));\n\t\tlabel.setAttribute(\"for\", \"uncategorizedcheckbox\");\n\t\tnewCatDiv.appendChild(label);\n\t\tinput.setAttribute(\"type\", \"checkbox\");\n\t\tinput.setAttribute(\"value\", \"uncategorized\");\n\t\tinput.setAttribute(\"id\", \"uncategorizedcheckbox\");\n\t\tinput.setAttribute(\"checked\", \"checked\");\n\t\tnewCatDiv.appendChild(input);\n\t\tcatDivPt1.appendChild(newCatDiv);\n\t\tdocument.getElementById(\"uncategorizedcheckbox\").addEventListener(\"click\", updateCatDisplays, false);\n\n\t\t// lists categories in the drop-down menus \n\t\t// in the popup and in the edit category section\n\t\tvar newOption = document.createElement(\"option\");\n\t\tnewOption.appendChild(document.createTextNode(\"none\"));\n\t\tnewOption.setAttribute(\"selected\", \"selected\");\n\t\tcategorySelect.appendChild(newOption);\n\t\t\n\t\tcatDivPt1.style.display = \"block\";\n\t\tcatDivPt2.style.display = \"block\";\n\n\t\tupdateCatDisplays();\n\t}\n\n\t// clears all category checkboxes\n\twhile (catDivPt1.firstChild) {\n\t\tcatDivPt1.firstChild.removeEventListener(\"click\", updateCatDisplays);\n\t catDivPt1.removeChild(catDivPt1.firstChild);\n\t}\n\t// clears all categories listed in edit category section\n\twhile (editCatSelect.firstChild) {\n\t editCatSelect.removeChild(editCatSelect.firstChild);\n\t}\n\t// clears all categories listed in popup\n\twhile (categorySelect.firstChild) {\n\t categorySelect.removeChild(categorySelect.firstChild);\n\t}\n\t// if a user is currently logged in, loads categories that user has\n\tif(currentUser != \"\") {\n\t\tvar secXmlHttp = new XMLHttpRequest();\n\t\tsecXmlHttp.open(\"POST\", \"getcategories_ajax.php\", true);\n\t\tsecXmlHttp.setRequestHeader(\"Content-Type\", \"application/x-www-form-urlencoded\");\n\t\tsecXmlHttp.addEventListener(\"load\", getCatCallback, false);\n\t\tsecXmlHttp.send();\n\t}\n\telse {\n\t\tcatDivPt1.style.display = \"none\";\n\t\tcatDivPt2.style.display = \"none\";\n\t}\n}", "function selectCategoryOptionValue(event) {\t\n\t\tvar text = $(event.currentTarget).text();\n var value = $(event.currentTarget).attr('data-attr-value');\n\t\tprocessCategoryOption(value, text);\n\n //accessiblity\n $('#category').attr('aria-expanded','false');\n $('.categoryOption').attr('aria-hidden', 'true');\n\n\t}", "function initializeCurvetypes(root) {\n var curvetype_list = root.append('div').classed('labels', true).selectAll('.curvetype').data(DATA.curvetypes)\n\n // Add checkboxes to control the toggled state of the labels\n curvetype_list.enter()\n .append('input')\n .attr('type', 'checkbox')\n .attr('id', function (d) { return d.name })\n .classed('curvetype--toggle', true)\n\n // Add nice looking labels for the user to click on\n var labels = curvetype_list.enter()\n .append('label')\n .classed('curvetype', true)\n .attr('for', function (d) { return d.name })\n\n // If the curvetype has modifyable arguments, then this function adds markup\n // to allow users to fiddle with them\n var generateArgs = function (d, i, n) {\n if (d.args) {\n var args_container = d3.select(this).append('div').classed('curvetype--args', true);\n for (var k = 0; k < d.args.length; k++) { // Using k because I need the i parameter\n var unique_id = d.args[k].name + '-' + i;\n args_container.append('span').text(d.args[k].name);\n args_container.append('input')\n .attr('id', unique_id)\n .attr('type', 'number')\n .attr('step', '0.01')\n .attr('min', 0)\n .attr('max', 1)\n .attr('value', d.args[k].default)\n }\n return args_container;\n }\n }\n\n labels.append('h4').text(function (d) { return 'd3.curve' + d.name })\n labels.each(generateArgs)\n\n // Add a select all button\n root.datum(DATA.curvetypes)\n .append('button')\n .text('Select All')\n .on('click', function (d) {\n root.selectAll('.curvetype--toggle').property('checked', true)\n root.selectAll('.curvetype').classed('selected', true)\n callSubs() // Need to do this manually to ensure correct order\n })\n\n // Add a select none button\n root.datum(DATA.curvetypes)\n .append('button')\n .text('Select None')\n .on('click', function (d) {\n root.selectAll('.curvetype--toggle').property('checked', false)\n root.selectAll('.curvetype').classed('selected', false)\n callSubs() // Need to do this manually to ensure correct order\n })\n\n // Add an event listener to toggle label styles depending on checkbox values\n root.selectAll('.curvetype--toggle').on('change.updateLabel', function (d, i, n) {\n root.select('.curvetype[for=' + this.id + ']').classed('selected', this.checked)\n })\n\n // A function to pull the relevant info out of the UI\n var getCurvetypeState = function () {\n var state = [];\n var toggles = root.selectAll('.labels > input[type=checkbox]');\n var beforeHyphen = function (string) {\n return string.match(/[^-]*/)[0] // Matches anything before the first hyphen\n }\n\n toggles.each(function (d) {\n var obj = {}\n obj.name = d.name\n obj.active = this.checked\n\n obj.args = [];\n root.select('label[for=' + d.name + ']').select('.curvetype--args input')\n .each(function (d) {\n // Note that we assume a format of name-1234 and a value which is a number\n obj.args.push({ name: beforeHyphen(this.id), value: parseFloat(this.value) })\n })\n\n state.push(obj)\n })\n\n return state\n }\n\n var subscribers = [];\n var callSubs = function () {\n for (var i = 0; i < subscribers.length; i++) {\n subscribers[i].call(this, getCurvetypeState())\n }\n }\n\n root.on('change.notifySubscribers', callSubs)\n\n var subscribe = function (callback) {\n subscribers.push(callback)\n }\n\n // Set up the defaults\n var default_curves = []\n\n return { subscribe: subscribe, default: default_curves };\n}", "function createFormControlLabels() {\n let sectionLabels = [\n 'arts', 'automobiles', 'books', 'business', 'fashion', 'food', 'health', 'home', 'insider', 'magazine', \n 'movies', 'ny region', 'obituaries', 'opinion', 'politics', 'real estate', 'science', 'sports', 'sunday review', \n 'technology', 'theater', 't-magazine', 'travel', 'upshot', 'us', 'world'\n ]\n\n const sectionValues = sectionLabels.map(section => {\n const sectionArr = section.split(' ');\n if (sectionArr.length > 1) {\n section = sectionArr.join('');\n console.log('joining section:', section);\n }\n return section;\n })\n\n /** capitalize each word in selction lables */\n sectionLabels = sectionLabels.map( section => {\n // debugger;\n section = section.split(' ');\n let updatedSection = section.map( item => {\n let firstLetter = item.charAt(0).toUpperCase();\n let remainder = item.slice(1);\n item = firstLetter + remainder;\n return item;\n })\n updatedSection = updatedSection.join(' ');\n return updatedSection;\n })\n\n /** Creating the form labels */\n const formLabels = sectionValues.map( (section, index) => (\n <FormControlLabel\n key={section}\n value={section}\n control={<Radio />}\n label={sectionLabels[index]}\n />\n ))\n\n return formLabels;\n }", "function cleanupOnCategoryReselect(category) {\n\t// Reset parents list\n\tparentList = [];\n\t\n\t// Hide select boxes for all the categories and containing members\n\t$.each(categoryToParentMap, function(category, parentCategory) {\n\t\t$(\"#\" + category).hide();\n\t});\n\t\n\t// Empty all the fields from the old form and show select existing members view (selectExistingMembers.jsp)\n\t$('#memberForm').hide();\n\t$('#result').hide();\n\t$('#memberFields').empty();\n}", "function loadSubCategory() {\n\tvar categorySelect = document.getElementById('categorySelect');\n\tselectedCategory = categorySelect.options[categorySelect.selectedIndex].value;\n\tselectedCategoryText = categorySelect.options[categorySelect.selectedIndex].text;\n\tif (selectedCategory != 0) {\n\t\tdocument.getElementById('subCategory' + selectedCategory).style.display = 'block';\n\t}\n\tfor ( var i = 1; i < 9; i++) {\n\t\tvar id = 'subCategory' + i;\n\t\tif (i == selectedCategory) {\n\t\t\tcontinue;\n\t\t}\n\t\tdocument.getElementById(id).style.display = 'none';\n\t}\n}", "static updateChoices() {\n\t\t// Get rid of the choices that are there already\n\t\tthis.resetChoices();\n\t\t// Add each choice\n\t\tstoryData.story.scene.choices.forEach(function(choice) {\n\t\t\t// DEBUG: show choice text and internal name\n\t\t\tconsole.log(\n\t\t\t\t`%c${choice.text}\\n%c(${choice.name}) \\u27f6 ${choice.nextScene}${choice.hasOwnProperty(\"requirement\") ? \"\\nRequirement: %c\"+choice.requirement : \"%c\"}`,\n\t\t\t\tconsoleStyles.choice, consoleStyles.debug, Parser.parseJS(choice.requirement) ? consoleStyles.trueVal : consoleStyles.falseVal\n\t\t\t);\n\t\t\tUI.addChoice(choice);\n\t\t});\n\t}", "function showCat() {\n const kittycat = sliderData[currentSlide];\n sliderImg.src = kittycat.img_data;\n sliderName.textContent = kittycat.name_data;\n sliderJobTitle.textContent = kittycat.job_title_data;\n sliderDescription.textContent = kittycat.text_data;\n}", "async function setCategoryButtons() {\n const categories = await fetchCategoriesFromAPI();\n const buttonList = document.getElementById('buttons');\n\n for (const category of categories) {\n const button = document.createElement('button');\n const text = document.createTextNode(category.name);\n button.setAttribute('id', category.id);\n button.classList.add('btn');\n button.appendChild(text);\n buttonList.appendChild(button);\n button.addEventListener('click', () => categoryButtonEventHandler(button));\n }\n}", "afterCreateControlAdaptionHook() {\n\t\t//nothing to do here\n\t}", "function setPresetsInScope(category) {\n $scope.presets = [];\n $scope.presets = [];\n //Get the member of the chosen category = presets\n var members = categories[category].members || [];\n members.forEach(function(member) {\n $scope.presets.push(presets[member]);\n });\n\n }", "function setOptions( e ) {\n\t\t\n\t\t\tif ( !e ) { e = window.event; }\n\t\t\n\t\t\tvar i,\n\t\t\t\tthisClicked = e.target.value;\n\t\t\t\n\t\t\tif ( thisClicked !== 0 ) {\n\t\t\t\t\t\n\t\t\t\tfor ( i = 0; i < this.options_list.length; i++ ) {\n\t\t\t\t\tthis.options_list_elements[i].style.display = \"none\";\n\t\t\t\t\t\n\t\t\t\t\tif ( thisClicked === this.options_list[i] ) {\n\t\t\t\t\t\tthis.options_list_elements[i].style.display = \"block\";\n\t\t\t\t\t}\t\t\t\t\n\t\t\t\t}\n\t\t\t}\t\t\t\n\t\t}", "function pegaCategoria(e) {\n if (e.target.value === 'Alcóolico') {\n setCategoria(['Alcoholic', 'Non Alcoholic']);\n } else if (e.target.value === 'Categoria') {\n setCategoria([\n 'Ordinary Drink',\n 'Cocktail',\n 'Cocoa',\n 'Shot',\n 'Milk / Float / Shake',\n 'Other / Unknown',\n 'Coffee / Tea',\n 'Homemade Liqueur',\n 'Punch / Party Drink',\n 'Beer',\n 'Soft Drink / Soda',\n ]);\n } else if (e.target.value === 'Copo') {\n setCategoria([\n 'Highball glass',\n 'Cocktail glass',\n 'Old-fashioned glass',\n 'Collins glass',\n ]);\n }\n }", "function setActiveCategory(selectedCategoryOfSingleGuide) {\n\t\t\n\t\t\n\t\twindow.selectedCategory = selectedCategoryOfSingleGuide;\n\t\n\t\t$(\".btn-group > .btn\").removeClass(\"active\");\n\n\t\tif (selectedCategoryOfSingleGuide == 0)\n\t\t\t$(\".btn_0\").addClass(\"active\");\n\t\telse if (selectedCategoryOfSingleGuide == 1)\n\t\t\t$(\".btn_1\").addClass(\"active\");\n\t\telse if (selectedCategoryOfSingleGuide == 2)\n\t\t\t$(\".btn_2\").addClass(\"active\");\n\t\telse if (selectedCategoryOfSingleGuide == 3)\n\t\t\t$(\".btn_3\").addClass(\"active\");\n\t\telse if (selectedCategoryOfSingleGuide == 4)\n\t\t\t$(\".btn_4\").addClass(\"active\");\n\t\telse if (selectedCategoryOfSingleGuide == 5)\n\t\t\t$(\".btn_5\").addClass(\"active\");\n\t\telse if (selectedCategoryOfSingleGuide == 6)\n\t\t\t$(\".btn_6\").addClass(\"active\");\n\t\telse $(\".btn-group > .btn\").removeClass(\"active\");\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generate a named graph from a set of mappings
function generateNamedGraph(gconf) { var targetFileBaseName = targetDir + "/" + gconf.graph; var mdFilePath = targetFileBaseName + "-meta.json"; var lastDumpMetadata; if (fs.exists(mdFilePath)) { lastDumpMetadata = JSON.parse(fs.read(mdFilePath)); if (lastDumpMetadata.mapVersion != null) { console.info("Comparing last dump version: "+lastDumpMetadata.mapVersion+ " with current: " + gconf.mapVersion); if (lastDumpMetadata.mapVersion == gconf.mapVersion) { console.info("Identical - will not redump"); return; } else { if (lastDumpMetadata.mapVersion > gconf.mapVersion) { console.warn("Kind of weird; lastDumpMetadata.mapVersion > gconf.mapVersion"); } } } } else { console.log("Cannot find "+mdFilePath+ " -- assuming this is initial dump"); } // globals ahoy numTriplesDumped = 0; numAxiomsDumped = 0; // write each NG to its own turtle file var io = fs.open(targetFileBaseName + ".ttl", {write: true}); // HEADER emitPrefixes(io); // OBJECTS if (gconf.objects != null) { gconf.objects.forEach(function(obj) { var id = mapRdfResource(obj.id); for (var k in obj) { if (k == 'id') { } else { emit(io, id, mapRdfResource(k), mapRdfResource(obj[k])); } } }); } var colNames = gconf.columns.map(function(c) { return c.name }); var cmap = {}; // create index mapping column names to column metadata gconf.columns.forEach(function(c) { cmap[c.name] = c }); // don't use derived columns in queries var queryColNames = colNames.filter( function(c) { return cmap[c].derivedFrom == null } ); var derivedColNames = colNames.filter( function(c) { return cmap[c].derivedFrom != null } ); // Federation REST API does not allow extraction of // all data in one query, so we iterate through rows // in chunks, starting with offset = 0 var offset = 0; var done = false; var seenMap = {}; var nDupes = 0; var numSourceRows; while (!done) { var qopts = {offset : offset}; if (options.apikey != null) { qopts[apikey] = options.apikey; } // Federation query var resultObj = engine.fetchDataFromResource(null, gconf.view, null, queryColNames, gconf.filter, maxLimit, null, qopts); numSourceRows = resultObj.resultCount; console.info(offset + " / "+ numSourceRows + " rows"); offset += maxLimit; if (offset >= numSourceRows) { done = true; } else { } var iter = 0; var results = resultObj.results; for (var k in results) { var r = results[k]; derivedColNames.forEach( function(c) { var dc = cmap[c].derivedFrom; r[c] = r[dc]; }); // generate a primary key for entire row. // we have no way to SELECT DISTINCT so to avoid // writing duplicate triples we check if the set of requested // column values is unique var key = colNames.map(function(cn) { return r[cn] }).join("-"); if (seenMap[key]) { nDupes ++; continue; } // crude way to keep cache small; cost of occasional dupes is low if (iter > 10) { seenMap = {}; iter = 0; } iter++; seenMap[key] = true; if (colNames.indexOf('v_uuid') > -1 && r.v_uuid == null) { // HACK - see https://support.crbs.ucsd.edu/browse/NIF-10231 r.v_uuid = colNames.map(function(cn) { return safeify(r[cn]) }).join("-"); } // Each n-ary Row in the Solr view can be mapped to multiple 3-ary triples for (var j in gconf.mappings) { var mapping = gconf.mappings[j]; // map each element of triple var sv = mapColumn(mapping.subject, r, cmap); var pv = mapColumn(mapping.predicate, r, cmap); var ov = mapColumn(mapping.object, r, cmap); emit(io, sv, pv, ov, mapping); } } console.log("nDupes = "+nDupes); } io.close(); var mdObj = { sourceView : gconf.view, mapVersion : gconf.mapVersion, numSourceRows : numSourceRows, numTriplesDumped : numTriplesDumped, numAxiomsDumped : numAxiomsDumped, }; fs.write(mdFilePath, JSON.stringify(mdObj)); }
[ "function createGraph(edges) {\n \n let roots = new Map();\n \n for (let i = 0; i < edges.length; i++) {\n const first = edges[i][0];\n const second = edges[i][1];\n if (!roots.get(first)) {\n roots.set(first, new Set());\n }\n if (!roots.get(second)) {\n roots.set(second, new Set());\n }\n \n roots.get(first).add(second);\n roots.get(second).add(first);\n }\n \n return roots;\n }", "function generate_canonical_map ( mod ) {\n var map = scope.make ( );\n function add_secondary_name ( obj, name ) {\n if ( obj.secondary_names !== undefined ) {\n obj.secondary_names = [];\n }\n obj.secondary_names.push ( name );\n }\n // We want the alphabetically first (\"smallest\") name.\n function add_new_name ( obj, name ) {\n if ( obj.canonical_name !== undefined ) {\n if ( obj.canonical_name > name ) {\n add_secondary_name ( obj, obj.canonical_name );\n obj.canonical_name = name;\n }\n else {\n add_secondary_name ( obj, name );\n }\n }\n else {\n obj.canonical_name = name;\n }\n }\n function gen_text ( scop, path, obj ) {\n scop.set_text ( path, obj );\n add_new_name ( obj, path );\n if ( obj.scope !== undefined ) {\n var named = [];\n misc.assert ( obj.objects !== undefined );\n obj.scope.each_text ( function ( key, child ) {\n if ( child.assignments.length === 1 ) {\n child = get_canonical_value ( child );\n if ( obj.objects.indexOf ( child ) !== -1 ) {\n gen_text ( scop, path + '.' + key, child );\n named.push ( child );\n }\n }\n } );\n for ( var i in obj.objects ) {\n var child = obj.objects[i];\n var name = path + '#' + i;\n add_secondary_name ( child, name );\n scop.set_text ( name, child );\n if ( named.indexOf ( child ) === -1 ) {\n // This object is not named.\n gen_text ( scop, path + '#' + i, child );\n child.canonical_name = name;\n }\n }\n }\n }\n mod.globals.each_text ( function ( key, glob ) {\n gen_text ( map, key, get_canonical_value ( glob ) );\n } );\n return map;\n }", "function buildGraph(edges) {\r\n let graph = Object.create(null); // graph is created as a null Object\r\n function addEdge(from, to) {\r\n if(graph[from] == null) { // if there is no key named graph[from]\r\n graph[from] = [to]; // create a new key/value pair (ex : graph[Alice's House] = [\"Bob's House\"])\r\n } else { // it'll look like : {\"alice's\": [\"bob's\", \"cabin\"], \"bob's\": [\"townHall\"], and so on ..... }\r\n graph[from].push(to); // if the key already exist, add the value to the array where the key is named graph[from]\r\n }\r\n }\r\n for(let [from, to] of edges.map(r => r.split(\"-\"))) { // split the roads array into a table of tables of 2 elements\r\n addEdge(from, to); // add or modify a key/value pair of the graph object : graph[from] = [to] or graph[from].push(to)\r\n addEdge(to, from); // add or modify a key/value pair of the graph object : graph[to] = [from] or graph[to].push(from)\r\n }\r\n return graph; // return the completed object\r\n}", "function _processNameScope() {\n processedGraph.root = {id: '', children: [], stacked: false};\n const {nodeMap, root} = processedGraph;\n\n for (const id of nameScopeIds) {\n const nameScope = _createNameScope(id);\n nodeMap[id] = nameScope;\n const parent = nameScope.parent ? nodeMap[nameScope.parent] : root;\n parent.children.push(id);\n }\n}", "function _processHierarchy() {\n const {nodeMap, parameterMap, constMap, root} = processedGraph;\n const nodes = Object.values(nodeMap);\n const usedAuxiliaryNodes = {parameter: {}, const: {}};\n\n // record the input and output of all nodes\n for (const node of nodes) {\n if (node.type === NODE_TYPE.name_scope) continue;\n const parent = node.parent ? nodeMap[node.parent] : root;\n parent.children.push(node.id);\n\n for (const inputId of node.input) {\n const source =\n nodeMap[inputId] || parameterMap[inputId] || constMap[inputId];\n if (!source) continue;\n if (\n source.type === NODE_TYPE.parameter ||\n source.type === NODE_TYPE.const\n ) {\n source.parent = parent.id;\n node[source.type + 's'][source.id] = source;\n usedAuxiliaryNodes[source.type][source.id] = source;\n } else {\n if (\n node.parent &&\n !source.scope.startsWith(node.parent)\n ) {\n nodeMap[node.parent].input.push(inputId);\n }\n if (\n source.parent &&\n !node.scope.startsWith(source.parent)\n ) {\n nodeMap[source.parent].output.push(node.id);\n }\n }\n }\n }\n processedGraph.parameterMap = usedAuxiliaryNodes.parameter;\n processedGraph.constMap = usedAuxiliaryNodes.const;\n\n // record the input and output of namescopes\n for (let len = nameScopeIds.length - 1, i = len; i >= 0; i--) {\n const id = nameScopeIds[i];\n const nameScope = nodeMap[id];\n nameScope.children = Array.from(new Set(nameScope.children));\n nameScope.input = Array.from(new Set(nameScope.input));\n nameScope.output = Array.from(new Set(nameScope.output));\n\n if (!nameScope.parent) continue;\n const parent = nodeMap[nameScope.parent];\n parent.input = parent.input.concat(\n Object.values(_filterIOData(nameScope.input, parent.id)),\n );\n parent.output = parent.output.concat(\n Object.values(_filterIOData(nameScope.output, parent.id)),\n );\n }\n}", "convertDataToGraph() {\n let graph = {nodes: [], links: [], nodeLabelsMap: {}}\n\n if (this.state.data == null) {\n return graph;\n }\n // To ensure we do not render duplicates, we build sets of nodes, relationships and labels.\n let nodesMap = {}\n let nodeLabelsMap = {}\n let linksMap = {}\n\n // First, iterate over the result rows to collect the unique nodes.\n // We handle different types of return objects in different ways.\n // These types are single nodes, arrays of nodes and paths.\n // This also handles finding all unique node labels we have in the entire result set.\n this.state.data.forEach(row => {\n Object.values(row).forEach(value => {\n // single nodes\n if (value && value[\"labels\"] && value[\"identity\"] && value[\"properties\"]) {\n this.extractNodeInfo(value, nodeLabelsMap, nodesMap);\n }\n // arrays of nodes\n if (value && Array.isArray(value)) {\n value.forEach(item => {\n if (item[\"labels\"] && item[\"identity\"] && item[\"properties\"]) {\n this.extractNodeInfo(item, nodeLabelsMap, nodesMap);\n }\n })\n }\n // paths\n if (value && value[\"start\"] && value[\"end\"] && value[\"segments\"] && value[\"length\"]) {\n this.extractNodeInfo(value.start, nodeLabelsMap, nodesMap);\n value.segments.forEach(segment => {\n this.extractNodeInfo(segment.end, nodeLabelsMap, nodesMap);\n });\n }\n })\n });\n\n // Then, also extract the relationships from the result set.\n // We store only unique relationships. where uniqueness is defined by the tuple [startNode, endNode, relId].\n\n // As a preprocessing step, we first sort the relationships in groups that share the same start/end nodes.\n // This is done by building a dictionary where the key is the tuple [startNodeId, endNodeId], and the value\n // is the relationship ID.\n\n // Additionally, preprocess the relationships and sort them such that startNode is always the lowest ID.\n\n // We also store a seperate dict with [startNodeId, endNodeId] as the key, and directions as values.\n\n let relsVisited = {}\n let relsVisitedDirections = {}\n this.state.data.forEach(row => {\n Object.values(row).forEach(value => {\n // single rel\n if (value && value[\"type\"] && value[\"start\"] && value[\"end\"] && value[\"identity\"] && value[\"properties\"]) {\n this.preprocessVisitedRelationships(value, relsVisited, relsVisitedDirections);\n }\n // arrays of rel\n if (value && Array.isArray(value)) {\n value.forEach(item => {\n if (item[\"type\"] && item[\"start\"] && item[\"end\"] && item[\"identity\"] && item[\"properties\"]) {\n this.preprocessVisitedRelationships(item, relsVisited, relsVisitedDirections);\n }\n })\n }\n // paths\n if (value && value[\"start\"] && value[\"end\"] && value[\"segments\"] && value[\"length\"]) {\n value.segments.forEach(segment => {\n this.preprocessVisitedRelationships(segment.relationship, relsVisited, relsVisitedDirections);\n });\n }\n });\n })\n\n // Now, we use the preprocessed relationship data as well as the built nodesMap.\n // With this data, we can build a graph.nodesMap and graph.linksMap object that D3 can work with.\n this.state.data.forEach(row => {\n Object.values(row).forEach(value => {\n // single rel\n if (value && value[\"type\"] && value[\"start\"] && value[\"end\"] && value[\"identity\"] && value[\"properties\"]) {\n this.extractRelInfo(value, nodesMap, linksMap, relsVisited, relsVisitedDirections);\n }\n // arrays of rel\n if (value && Array.isArray(value)) {\n value.forEach(item => {\n if (item[\"type\"] && item[\"start\"] && item[\"end\"] && item[\"identity\"] && item[\"properties\"]) {\n this.extractRelInfo(item, nodesMap, linksMap, relsVisited, relsVisitedDirections);\n }\n })\n }\n // paths\n if (value && value[\"start\"] && value[\"end\"] && value[\"segments\"] && value[\"length\"]) {\n // this.extractNodeInfo(value.start, nodeLabelsMap, nodesMap);\n value.segments.forEach(segment => {\n this.extractRelInfo(segment.relationship, nodesMap, linksMap, relsVisited, relsVisitedDirections);\n });\n }\n });\n })\n\n graph.nodes = Object.values(nodesMap)\n graph.links = Object.values(linksMap)\n graph.nodeLabels = Object.keys(nodeLabelsMap)\n\n\n // Trigger a refresh of the graph visualization.\n this.props.onNodeLabelUpdate(nodeLabelsMap)\n return graph\n }", "buildVeteransMapping(veterans) {\n let mapping = {};\n veterans.forEach(veteran => {\n mapping[veteran.id] = veteran;\n });\n return mapping;\n }", "function nodesInSaga(nodes,saga){\n i=0\n nameToIndex = {}\n nodesSaga = [];\n nodes.forEach(node => {\n if(node.saga <= saga){\n nodesSaga.push(node)\n nameToIndex[node.name] = i\n i++\n }\n });\n return nodesSaga;\n}", "function load_graph_to_map(results){\n load_markers(results.locations);\n //draw_lines(results);\n draw_spanning_tree(results);\n\n}", "_getGraphs(graph) {\n if (!isString(graph)) return this._graphs;\n const graphs = {};\n graphs[graph] = this._graphs[graph];\n return graphs;\n }", "function generatePaths(numberofNodes, nodes) {\n // console.log(numberofNodes);\n // console.log(nodes);\n // Init a map to represent a given node as the key and list of connected nodes as the value\n const pathMap = {};\n for (let i = 0; i < numberofNodes; i++) {\n pathMap[i] = [];\n }\n \n // Populate the pathMap with the connected nodes\n for (let i = 0; i < nodes.length; i++) {\n const [source, destination] = nodes[i].replace(' ', '').split(',');\n pathMap[source].push(destination); \n }\n \n // console.log(pathMap);\n \n // Recursively generate the paths\n\n // Recursive helper function\n function generateNodePath(root) {\n const paths = pathMap[root];\n // Base case\n if (paths.length === 0) return root;\n \n // Generate paths for all connected nodes\n for (let i = 0; i < paths.length; i++) {\n // TODO: This only returns the path for the first item completely.\n // Need to save the result and only return once all paths for each\n // node in the loop is generated.\n return root.toString() + '->' + generateNodePath(paths[i]);\n }\n }\n \n const pathMapKeys = Object.keys(pathMap);\n for (let i = 0; i < pathMapKeys.length; i++) {\n const path = generateNodePath(pathMapKeys[i]);\n console.log(path);\n }\n}", "function createNetwork(definitions) {\n let input = definitions.split(\"\\n\")\n let nodes = new Set()\n let groups = new Map()\n let nodesMap = new Map()\n let linksMap = new Map() // used to complete back links without re iterating over nodes.\n \n function addForwardsLinks(node, linksArray) {\n let tag = node.tag\n let forwardsLink = new Set()\n let i = 0\n\n while (i < linksArray.length) {\n let link = linksArray[i].replace(space, \"\") // removes spaces from tags\n forwardsLink.add(link)\n\n if (linksMap.has(link)) {\n linksMap.set(link, linksMap.get(link).add(tag))\n } else {\n linksMap.set(link, new Set([tag]))\n }\n i++\n }\n\n return forwardsLink\n }\n \n for (let i = 0; i < input.length; i++) {\n let stringMatch = regex.exec(input[i])\n if (stringMatch !== null && stringMatch.length > 1) {\n let rowType = stringMatch[1]\n let rowData = stringMatch[2].split(\",\")\n\n switch (rowType) {\n case skillRowTag:\n let node = new SkillNode(rowData[0], rowData[1], rowData[2])\n node.forwardsLink = addForwardsLinks(node, rowData.slice(3))\n nodes.add(node)\n break\n case groupRowTag:\n let group = new Group(rowData[0], new Set(rowData.slice(1)))\n groups.set(group.name, group)\n break\n }\n }\n }\n\n // fills back links and maps tags to nodes and creates all skills group\n let allSkills = new Set()\n for (let node of nodes) {\n allSkills.add(node.tag)\n \n if (linksMap.has(node.tag)) {\n node.backwardsLink = linksMap.get(node.tag)\n }\n\n nodesMap.set(node.tag, node)\n }\n \n groups.set(\"allSkills\", new Group(\"allSkills\", allSkills))\n \n return new SkillNetwork ({\n nodes: nodes,\n nodesMap: nodesMap,\n groups: groups, // used to filter network\n })\n}", "function asMapFactory(groups) {\n return () => {\n const map = new Map();\n for (const group of groups) {\n map.set(group.key, group.items);\n }\n return map;\n };\n}", "async scopeGraphs(ids, thisScope) {\n const groupedIds = this._groupByScopeName(ids);\n\n const graphsP = Object.keys(groupedIds).map(async scopeName => {\n const remote = await this.resolve(scopeName, thisScope);\n const dependencyGraph = await remote.graph();\n dependencyGraph.setScopeName(scopeName);\n return dependencyGraph;\n });\n return Promise.all(graphsP);\n }", "reallocateNames(claimgraph) {\n const blanks = allBlanks(claimgraph);\n const renames = {};\n for (const name of blanks) {\n renames[name] = this.next();\n }\n for (const claim of claimgraph) {\n for (let i = 0; i < claim.length; i++) {\n if (claim[i].Blank !== undefined) {\n claim[i] = renames[claim[i].Blank];\n }\n }\n }\n }", "function BrowsingGraph() {\n this.urls = new Set();\n this.adj = new Map(); // id -> [id]\n this.utoi = new Map(); // url -> id\n this.itou = new Map(); // id -> url\n var _d3groups = [0];\n var id = 0;\n\n Array.prototype.copy = function () {\n var copy = new Array();\n this.forEach(function (elem) {\n copy.push(elem); \n });\n return copy;\n }\n\n this.getUrls = function () {\n return Array.from(this.urls).copy();\n }\n\n this.getNodes = function () {\n return Array.from(this.itou.entries()).map(function (kv) {\n return {id: kv[0], url: kv[1], group: 0};\n });\n };\n\n this.getLinks = function () {\n var links = [];\n this.adj.forEach(function (ts, s) {\n ts.forEach(function (t) {\n links.push({source: s, target: t, value: 1});\n });\n });\n return links;\n };\n\n this.getGroups = function () {\n return _d3groups.copy();\n };\n \n this.toJSON = function() {\n return {\n nodes: this.getNodes(), \n links: this.getLinks(),\n groups: this.getGroups()\n };\n };\n\n this.addNode = function(url) {\n if (!this.urls.has(url)) {\n this.urls.add(url);\n this.utoi.set(url,id);\n this.itou.set(id, url);\n id++;\n }\n };\n\n this.addLink = function(url_from, url_to) {\n this.addNode(url_from);\n this.addNode(url_to);\n var src = this.utoi.get(url_from);\n var dest = this.utoi.get(url_to);\n if (!this.adj.has(src)) {\n this.adj.set(src, new Set([dest]))\n } else {\n this.adj.get(src).add(dest);\n }\n };\n\n this.removeNode = function (url) {\n this.adj.delete(this.utoi.get(url));\n this.itou.delete(this.utoi.get(url));\n this.utoi.delete(url);\n this.urls.delete(url);\n };\n\n this.removeLink = function (from, to) {\n var f = this.utoi.get(from);\n var t = this.utoi.get(to);\n var newval = this.adj.get(f).filter(function (i) {\n return i != t;\n });\n this.adj.set(f, newval);\n };\n\n // Produces a json with nodes grouped by their old graphs\n this.mergeJSON = function(graphs) {\n graphs.push(this);\n var new_groups = new Map();\n graphs.forEach(function (g) {\n new_groups.set(g, new Map());\n });\n var g_ids = new Set();\n var new_id = 0;\n var _utoi = new Map();\n \n // Make unique group ids\n graphs.forEach(function (g) {\n var groups = new_groups.get(g);\n g.getGroups().forEach(function (g_id) {\n var key = 0;\n while (g_ids.has(key)) {\n key++;\n }\n g_ids.add(key);\n groups.set(g_id, key);\n });\n });\n\n // Rebuild nodes and ids\n var nodes = [];\n graphs.forEach(function (g) {\n g.getNodes().forEach(function (n) {\n _utoi.set(n.url, new_id);\n var group = new_groups.get(g).get(n.group);\n nodes.push({\n url: n.url, \n id: new_id++, \n group: group\n });\n });\n });\n\n // Rebuild links and ids\n var links = [];\n graphs.forEach(function (g) {\n g.getLinks().forEach(function (l) {\n var s = _utoi.get(g.itou.get(l.source));\n var t = _utoi.get(g.itou.get(l.target));\n links.push({\n source: s,\n target: t,\n value: 1\n });\n });\n });\n\n return {groups: Array.from(g_ids), nodes: nodes, links: links};\n };\n}", "function createGraphJSON(title)\n{\n console.log(\"Nodes JSON: \");\n console.log(nodes);\n console.log(\"Edges JSON: \");\n console.log(edges);\n var i;\n var g = {\"label\": title,\n \"nodes\": [], //no nodes\n\n \"edges\": [] //no edges\n };\n \n for (i = 0; i < nodes.length; i++) g.nodes.push(nodes[i].n);\n //for (i = 0; i < nodes.length; i++) g.edges.push(edges[i]); \n\n return g; \n}", "function compileMappings(oldMappings) {\n\t var mappings = oldMappings.slice(0);\n\t\n\t mappings.sort(function(map1, map2) {\n\t if (!map1.attribute) return 1;\n\t if (!map2.attribute) return -1;\n\t\n\t if (map1.attribute !== map2.attribute) {\n\t return map1.attribute < map2.attribute ? -1 : 1;\n\t }\n\t if (map1.value !== map2.value) {\n\t return map1.value < map2.value ? -1 : 1;\n\t }\n\t if (! ('replace' in map1) && ! ('replace' in map2)) {\n\t throw new Error('Conflicting mappings for attribute ' + map1.attribute + ' and value ' + map1.value);\n\t }\n\t if (map1.replace) {\n\t return 1;\n\t }\n\t return -1;\n\t });\n\t\n\t return mappings;\n\t }", "function createMap(actor_list, actor, actors_map) {\n var actorListWithout = actor_list.filter(function (item) {\n return item !== actor;\n });\n if (actors_map[actor] !== undefined) {\n for (var y = 0; y < actorListWithout.length; y++) {\n if (!mapping_actors(actors_map, actor, actorListWithout[y])) {\n actors_map[actor].push(actorListWithout[y]);\n }\n }\n }\n else {\n actors_map[actor] = actorListWithout;\n }\n return {actorListWithout: actorListWithout, y: y};\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
true/false: if the text contents are too long to fit the shape, automatically shrink the text to fit note: autoFit and shrinkText are mutually exclusive doesn't make sense for both to be true (either one is true, or both are false)
shrinkText(value) { // FIXME: TODO: for some strange reason PowerPoint doens't auto-shrink/fit the text in a shape when you first open the pptx. You must click // on the properties of any shape, change any "fit" property (Format Shape->Text Box->Autofit), and then ALL shapes get their auto-fit // attributes applied. Not sure if all PowerPoint versions have this bug. Will need to investigate later... this.options.shrinkText = value; return this; }
[ "function resizeText(pixels) {\r\n\r\n}", "static validateShortTextExceedsLength(pageClientAPI, dict) {\n\n //New short text length must be <= global maximum\n let max = libCom.getAppParam(pageClientAPI, 'MEASURINGPOINT', 'ShortTextLength');\n\n if (libThis.evalShortTextLengthWithinLimit(dict, max)) {\n return Promise.resolve(true);\n } else {\n let dynamicParams = [max];\n let message = pageClientAPI.localizeText('validation_maximum_field_length', dynamicParams);\n libCom.setInlineControlError(pageClientAPI, libCom.getControlProxy(pageClientAPI, 'ShortTextNote'), message);\n dict.InlineErrorsExist = true;\n return Promise.reject(false);\n }\n }", "function scaleTextSize(ts)\n{\n // The textSize is dynamically computed based on the number of items ;)\n // Make the text the biggest possible but make sure everything fits inside the canvas\n textSize(ts);\n\n // Horizontally we have to leave minimum 25% of the space for the arrow\n if (tListStart[1] + items.length*ts > canvas_size[1] || tListStart[0] + getMaxWidth(items) > 0.75*canvas_size[0])\n {\n return scaleTextSize(ts-1)\n }\n else\n {\n return ts;\n }\n}", "function bigText() {\n if ($(window).width() < 768) {\n var productInfoWrapper = $(\".product-info-wrapper\");\n if (productInfoWrapper.length) {\n productInfoWrapper.find(\".name\").fitText();\n }\n }\n }", "function comprobarTextoSin(campo, size){\r\n\t//Obtenemos el valor que contiene el campo\r\n\tvar valor = campo.value;\r\n\t//Comprobamos que el campo sea texto y no tenga espacios en blanco\r\n\tif( valor.length>size || /\\s/.test(valor)) {\r\n\t elementoInvalido(campo);\r\n\t return false;\r\n\t \r\n\t}\r\n\t//Si cumple las condiciones anteriores es texto sin espacios retornamos true\r\n\telse{\r\n\t elementoValido(campo);\r\n\t return true;\r\n\t}\r\n\t\r\n}", "function limitText(){\n\t\tvar str = primaryOutput.innerHTML;\n\t\tvar textLimit = 17;\n\t\tstr.split(\"\");\n\t\t\n\t\t//If text exceeds limit and is less than 4 extra, reduce font size\n\t\t//If text exceeds limit between 5 and 9 characters reduce font size more\n\t\t//If text exceeds limit by more than 9 characters print message to screen\n\t\tif (str.length > textLimit && str.length <= (textLimit + 3)){\n\t\t\tprimaryOutput.style.fontSize = \".9em\";\n\t\t} else if (str.length > (textLimit + 3) && str.length <= (textLimit + 8)){\n\t\t\tprimaryOutput.style.fontSize = \".7em\";\n\t\t} else if (str.length > (textLimit + 8)){\n\t\t\tprimaryOutput.innerHTML = \"Exceeded limit\";\n\t\t}\n\t}", "generateSmallDescription(text){\r\n\t if(text){\r\n\t\tif(text.length > 120){\r\n\t\t text= text.slice(0,120) + '...';\r\n\t\t return text;\r\n\t\t}\r\n\t\telse{\r\n\t\t return text;\r\n\t\t}\r\n\t }\r\n\t}", "function replaceDetailsText(arrText, isTitle){\n\tvar detailsWrite = detailsBodyText;\n\tvar detailsDelete = detailsTitleText;\n\tvar detailsBoxWidth = d3.select(\"#svgDetailsBox\").attr(\"width\");\n\n\tif (isTitle){\n\t\tdetailsWrite = detailsTitleText;\n\t\tdetailsDelete = detailsBodyText;\n\t}\n\tfor (var i=0; i<3; i++){\n\t\tdetailsWrite[i].text(\"\");\n\t}\n\tfor (var i=0; i<Math.min(arrText.length,detailsWrite.length); i++){\n\t\tvar text = arrText[i];\n\t\tdetailsWrite[i].text(arrText[i]);\n\t\tvar element = document.getElementById(detailsWrite[i].attr(\"id\"));\n\t\tvar textWidth = element.getComputedTextLength();\n\t\t//alert(detailsBoxWidth+\", \"+textWidth);\n\t\tif (textWidth > detailsBoxWidth){\n\t\t\twhile (textWidth > detailsBoxWidth){\n\t\t\t\ttext = text.substring(0,text.length-1);\n\t\t\t\tdetailsWrite[i].text(text);\n\t\t\t\telement = document.getElementById(detailsWrite[i].attr(\"id\"));\n\t\t\t\ttextWidth = element.getComputedTextLength();\n\t\t\t}\n\t\t\ttext = text.substring(0,text.length-4)+\"...\";\n\t\t\tdetailsWrite[i].text(text);\n\t\t}\n\t\t\n\t\t\n\t}\n\tfor (var i=0; i<3; i++){\n\t\tdetailsDelete[i].text(\"\");\n\t}\n}", "checkForcedWidth() {\n var maximum_string_width = 0;\n\n for(var i=0;i<this.dispatcher.split_words.length;i++) {\n var block = this.dispatcher.split_words[i];\n if(block.match(/^\\s+$/)) { // только строка из пробелов совершает word-break, так что её не проверяем\n continue;\n }\n if(maximum_string_width < this.getStringWidth(block)) {\n maximum_string_width = this.getStringWidth(block);\n }\n }\n\n for(var i=0;i<99;i++) {\n var proposed_width = i * this.border_size;\n if(proposed_width > maximum_string_width) {\n this.forced_width = i;\n break;\n }\n }\n }", "function detectFontChange(_options) {\n var options = {}; // option processing\n\n Object.keys(_options).concat(Object.keys(DEFAULTS)).forEach(function (key) {\n options[key] = _options[key] != null ? _options[key] : DEFAULTS[key];\n });\n var multipleFonts = options.font.split(',');\n\n if (multipleFonts.length > 1) {\n var result = false;\n multipleFonts.forEach(function (fontName) {\n options.font = fontName.trim();\n\n if (detectFontChange(options)) {\n // Return true if at least one font is not already loaded.\n result = true;\n }\n });\n return result;\n } // Construct compact form that is expected by canvas.\n\n\n var font = options.weight + ' ' + FONT_SIZE + 'px ' + options.font;\n\n if (fontLoaded[font]) {\n // Font already loaded.\n return false;\n }\n\n if (!loading[font]) {\n loading[font] = {\n bitmap: null,\n pollingInterval: null,\n changeCallbacks: []\n };\n }\n\n if (options.onchange) {\n loading[font].changeCallbacks.push(options.onchange);\n }\n\n if (!loading[font].pollingInterval) {\n loading[font].pollingInterval = window.setInterval(fontChecker(font, Date.now(), options.timeout), options.interval);\n }\n\n return true;\n}", "function isShrinkToFit( parentWidth ) {\n var pm = this.GetPM();\n var placeHolder = pm.Get(\"GetPlaceholder\");\n var totalcolumnWidth = 0;\n var listOfColumns = pm.Get(\"ListOfColumns\");\n \n var listLength = listOfColumns.length;\n for (var i = 0; i < listLength; i++) {\n totalcolumnWidth = Number(totalcolumnWidth) + Number(listOfColumns[i].control.GetWidth());\n }\n if (parentWidth < totalcolumnWidth) {\n return false;\n }\n\n return true;\n }", "function isLineOverlong(text) {\n\t\tvar checktext;\n\t\tif (text.indexOf(\"\\n\") != -1) { // Multi-line message\n\t\t\tvar lines = text.split(\"\\n\");\n\t\t\tif (lines.length > MAX_MULTILINES)\n\t\t\t\treturn true;\n\t\t\tfor (var i = 0; i < lines.length; i++) {\n\t\t\t\tif (utilsModule.countUtf8Bytes(lines[i]) > MAX_BYTES_PER_MESSAGE)\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t} else if (text.startsWith(\"//\")) // Message beginning with slash\n\t\t\tchecktext = text.substring(1);\n\t\telse if (!text.startsWith(\"/\")) // Ordinary message\n\t\t\tchecktext = text;\n\t\telse { // Slash-command\n\t\t\tvar parts = text.split(\" \");\n\t\t\tvar cmd = parts[0].toLowerCase();\n\t\t\tif ((cmd == \"/kick\" || cmd == \"/msg\") && parts.length >= 3)\n\t\t\t\tchecktext = utilsModule.nthRemainingPart(text, 2);\n\t\t\telse if ((cmd == \"/me\" || cmd == \"/topic\") && parts.length >= 2)\n\t\t\t\tchecktext = utilsModule.nthRemainingPart(text, 1);\n\t\t\telse\n\t\t\t\tchecktext = text;\n\t\t}\n\t\treturn utilsModule.countUtf8Bytes(checktext) > MAX_BYTES_PER_MESSAGE;\n\t}", "updateTextAreaSize(text) {\n var textSettings = this.currentText.getTextSettings();\n\n // Setting the font and size of the text\n this.textAreaElement.css(\"font-size\", textSettings.pixels + \"px\");\n this.textAreaElement.css(\"font-family\", textSettings.fontType);\n\n //TODO: resize text area.\n }", "function verifyDataLabelOverflow(overflow) {\n var center = this.center, options = this.options, centerOption = options.center, minSize = options.minSize || 80, newSize = minSize, \n // If a size is set, return true and don't try to shrink the pie\n // to fit the labels.\n ret = options.size !== null;\n if (!ret) {\n // Handle horizontal size and center\n if (centerOption[0] !== null) { // Fixed center\n newSize = Math.max(center[2] -\n Math.max(overflow[1], overflow[3]), minSize);\n }\n else { // Auto center\n newSize = Math.max(\n // horizontal overflow\n center[2] - overflow[1] - overflow[3], minSize);\n // horizontal center\n center[0] += (overflow[3] - overflow[1]) / 2;\n }\n // Handle vertical size and center\n if (centerOption[1] !== null) { // Fixed center\n newSize = clamp(newSize, minSize, center[2] - Math.max(overflow[0], overflow[2]));\n }\n else { // Auto center\n newSize = clamp(newSize, minSize, \n // vertical overflow\n center[2] - overflow[0] - overflow[2]);\n // vertical center\n center[1] += (overflow[0] - overflow[2]) / 2;\n }\n // If the size must be decreased, we need to run translate and\n // drawDataLabels again\n if (newSize < center[2]) {\n center[2] = newSize;\n center[3] = Math.min(// #3632\n options.thickness ?\n Math.max(0, newSize - options.thickness * 2) :\n Math.max(0, relativeLength(options.innerSize || 0, newSize)), newSize); // #6647\n this.translate(center);\n if (this.drawDataLabels) {\n this.drawDataLabels();\n }\n // Else, return true to indicate that the pie and its labels is\n // within the plot area\n }\n else {\n ret = true;\n }\n }\n return ret;\n }", "function verifyDataLabelOverflow(overflow) {\n var center = this.center, options = this.options, centerOption = options.center, minSize = options.minSize || 80, newSize = minSize, \n // If a size is set, return true and don't try to shrink the pie\n // to fit the labels.\n ret = options.size !== null;\n if (!ret) {\n // Handle horizontal size and center\n if (centerOption[0] !== null) { // Fixed center\n newSize = Math.max(center[2] -\n Math.max(overflow[1], overflow[3]), minSize);\n }\n else { // Auto center\n newSize = Math.max(\n // horizontal overflow\n center[2] - overflow[1] - overflow[3], minSize);\n // horizontal center\n center[0] += (overflow[3] - overflow[1]) / 2;\n }\n // Handle vertical size and center\n if (centerOption[1] !== null) { // Fixed center\n newSize = clamp(newSize, minSize, center[2] - Math.max(overflow[0], overflow[2]));\n }\n else { // Auto center\n newSize = clamp(newSize, minSize, \n // vertical overflow\n center[2] - overflow[0] - overflow[2]);\n // vertical center\n center[1] += (overflow[0] - overflow[2]) / 2;\n }\n // If the size must be decreased, we need to run translate and\n // drawDataLabels again\n if (newSize < center[2]) {\n center[2] = newSize;\n center[3] = Math.min(// #3632\n relativeLength(options.innerSize || 0, newSize), newSize);\n this.translate(center);\n if (this.drawDataLabels) {\n this.drawDataLabels();\n }\n // Else, return true to indicate that the pie and its labels is\n // within the plot area\n }\n else {\n ret = true;\n }\n }\n return ret;\n }", "function wrapText(game, text, x, y, maxWidth, lineHeight) {\n var cars = text.split(\"\\n\");\n game.ctx.font = \"bold 80pt Helvetica\";\n game.ctx.textAlign = 'center';\n game.ctx.fillStyle = 'black';\n\n for (var ii = 0; ii < cars.length; ii++) {\n\n var line = \"\";\n var words = cars[ii].split(\" \");\n\n for (var n = 0; n < words.length; n++) {\n var testLine = line + words[n] + \" \";\n var metrics = game.ctx.measureText(testLine);\n var testWidth = metrics.width;\n\n if (testWidth > maxWidth) {\n game.ctx.fillText(line, x, y);\n line = words[n] + \" \";\n y += lineHeight;\n }\n else {\n line = testLine;\n }\n }\n game.ctx.fillText(line, x, y);\n y += lineHeight;\n }\n}", "function checkOperationLength() {\n if (displayEl.textContent.length > 10) {return false;}\n}", "havingSize(size) {\n if (this.size === size && this.textSize === size) {\n return this;\n } else {\n return this.extend({\n style: this.style.text(),\n size: size,\n textSize: size,\n sizeMultiplier: sizeMultipliers[size - 1]\n });\n }\n }", "get canExpand() {\n return this._hasChildren && !this.node.singleTextChild;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts ranking options from .env file (via process.env) and returns them in an object that can be spread into the ranking options.
static rankingOptionsFromEnv() { return process.env.RANKING_ENABLE_VIS_PANEL == null ? {} : { enableVisPanel: JSON.parse(process.env.RANKING_ENABLE_VIS_PANEL) }; }
[ "function parseENV() {\n var _a;\n logSettings_1.logger.info('\"parseENV\" got called');\n const options = {\n globalOptions: {},\n options: {\n allowMixed: process.env.TG_ALLOW_MIXED && process.env.TG_ALLOW_MIXED in constants_1.Severity\n ? mapValueToSeverity(process.env.TG_ALLOW_MIXED)\n : (_a = data_1.globalOptions.options) === null || _a === void 0 ? void 0 : _a.allowMixed,\n },\n };\n setGlobalOptions(options);\n}", "loadEnvVarsForLocal() {\n const defaultEnvVars = {\n IS_LOCAL: 'true',\n };\n\n _.merge(process.env, defaultEnvVars);\n\n // Turn zero or more --env options into an array\n // ...then split --env NAME=value and put into process.env.\n _.concat(this.options.env || []).forEach(itm => {\n const splitItm = _.split(itm, '=');\n process.env[splitItm[0]] = splitItm[1] || '';\n });\n\n return BbPromise.resolve();\n }", "function rankOption(queryTerms, context) {\n\t\tconst string = [\n\t\t// option-related strings\n\t\tcontext.optionKey, context.title, context.description, ...context.keywords,\n\t\t// module-related strings\n\t\tcontext.moduleID, context.moduleName, context.category].join('~');\n\t\treturn rankString(queryTerms, string);\n\t}", "function loadConfig() {\n var config = JSON.parse(require('fs').readFileSync(__dirname + '/defaults.json', 'utf-8'));\n for (var i in config) {\n config[i] = process.env[i.toUpperCase()] || config[i];\n }\n return config;\n}", "loadEnv() {\n let env = dotenvExtended.load({\n silent: false,\n path: path.join(this.getProjectDir(), \".env\"),\n defaults: path.join(this.getProjectDir(), \".env.defaults\")\n });\n\n const options = minimist(process.argv);\n for (let option in options) {\n if (option[0] === \"-\") {\n let value = options[option];\n option = option.slice(1);\n if (option in env) {\n env[option] = value.toString();\n }\n }\n }\n env = dotenvParseVariables(env);\n env = dotenvExpand(env);\n\n this.env = { ...env, project_dir: this.getProjectDir() };\n }", "function loadRank() {\n let resolvedRankString = [];\n let rowRankString = getCookie('rank');\n if (rowRankString) {\n rowRankString = rowRankString.split('&')\n for (let pairs of rowRankString) {\n pairs = pairs.split('@');\n resolvedRankString.push(pairs);\n }\n rank = resolvedRankString;\n }\n}", "function getNodeEnvFromProcess() {\n var nodeEnv = (process.env[NODE_ENV_KEY] || '').toUpperCase(),\n available = false;\n\n if (nodeEnv) {\n /* make sure the nodeEnv is an available value */\n available = nodeEnv in NODE_ENV;\n\n if (!available) {\n logger.warn('[NODE_ENV] %s is not an available NODE_ENV value, ' +\n ', currently only accept the following values: %s', nodeEnv,\n Object.keys(NODE_ENV).map(function(key) {\n return NODE_ENV[key];\n }).join(', '));\n\n /* if not known, fallback to default value. */\n nodeEnv = DEFAULT_NODE_ENV;\n } else {\n nodeEnv = NODE_ENV[nodeEnv];\n }\n } else {\n logger.warn('Failed to find NODE_ENV value' +\n ', fallback to default value: %s.', DEFAULT_NODE_ENV);\n\n nodeEnv = DEFAULT_NODE_ENV;\n }\n\n /* update prcoess.env with new value */\n updateProcessEnv(NODE_ENV_KEY, nodeEnv);\n\n return nodeEnv;\n}", "function getTypeormConfig() {\n const envConfig = {};\n envConfig.TYPEORM_DATABASE = process.env.DB_NAME;\n envConfig.TYPEORM_USERNAME = process.env.DB_USER;\n envConfig.TYPEORM_PASSWORD = process.env.DB_PASS;\n envConfig.TYPEORM_HOST = process.env.DB_HOST;\n envConfig.TYPEORM_PORT = process.env.DB_PORT;\n return Object.keys(envConfig)\n .map((key) => `${key}=${envConfig[key]}`)\n .join('\\n');\n}", "function parseConfig() {\n const { config } = state_1.getStore();\n const parsedConfig = {};\n const envConfig = config[exports.configEnvKey];\n if (envConfig) {\n const envObject = JSON.parse(envConfig);\n for (const k of Object.keys(envObject)) {\n parsedConfig[cleanKey(k)] = envObject[k];\n }\n }\n return parsedConfig;\n}", "function retrieveOptions(options) {\n let serverOptions = {};\n // Note: can use for loop with array\n serverOptions.mongodb = options.mongodb\n return serverOptions;\n}", "function getSettings() {\n\taiTurn = gameSettings.getOrSet('aiTurn', 'second');\n\tponder = gameSettings.getOrSet('ponder', false);\n\tdrawWeights = gameSettings.getOrSet('drawWeights', false);\n\tanti = gameSettings.getOrSet('anti', false);\n\ttie = gameSettings.getOrSet('tie', false);\n\ttimeToThink = gameSettings.getOrSet('timeToThink', 1);\n}", "function getEnvVarsFromFile(envFile) {\n const envVars = Object.assign({}, process.env)\n if (process.env.APPDATA) {\n envVars.APPDATA = process.env.APPDATA\n }\n\n // Read from the JSON file.\n const jsonString = fs.readFileSync(path.resolve(process.cwd(), envFile), {\n encoding: \"utf8\"\n })\n\n const varsFromFile = JSON.parse(jsonString)\n\n Object.assign(envVars, flattenVars(varsFromFile))\n\n return envVars\n}", "function setupEnvironmentVariables(args) {\n shell.env['ELIFE_INSTALL_FOLDER'] = shell.pwd()\n let nn = \"0\"\n if(shell.env['ELIFE_NODE_NUM']) nn = shell.env['ELIFE_NODE_NUM']\n if(args['node-num']) nn = args['node-num']\n if(isNaN(parseInt(nn))) {\n shell.echo(`node-num ${nn} is not a valid integer`)\n shell.exit(1)\n }\n shell.env[\"ELIFE_NODE_NUM\"] = nn\n shell.env['COTE_ENV'] = partitionParam()\n shell.env['ELIFE_HOME'] = u.homeLoc()\n\n setup_port_vars_1()\n\n function setup_port_vars_1() {\n process.env[\"SSB_PORT\"] = u.adjustPort(8191)\n process.env[\"SSB_WS_PORT\"] = u.adjustPort(8192)\n process.env[\"QWERT_PORT\"] = u.adjustPort(8193)\n process.env[\"EBRAIN_AIML_PORT\"] = u.adjustPort(8194)\n process.env[\"AIARTIST_PORT\"] = u.adjustPort(8195)\n }\n}", "askForBaseOptions() {\n\t\treturn {\n\t\t\taskForBaseName: basePrompts.askForBaseName,\n\t\t\taskForBasicOptionsFormat: basePrompts.askForBasicOptionsFormat,\n\t\t\taskForUserInput: basePrompts.askForUserInput\n\t\t}\n\t}", "function getCliConfig(): RNConfig {\n const cliArgs = minimist(process.argv.slice(2));\n const config = cliArgs.config != null\n ? Config.loadFile(path.resolve(__dirname, cliArgs.config))\n : Config.findOptional(__dirname);\n\n return {...defaultConfig, ...config};\n}", "function getDefaultConfig() {\n\tvar config = {};\n\t\n\tvar configZen = CSScomb.getConfig('zen');\n\t\n\t// Copy only sort-order data:\n\tconfig['sort-order'] = configZen['sort-order'];\n\t\n\t// If sort-order is separated into sections, add an empty section at top:\n\tif (config['sort-order'].length > 1) {\n\t\tconfig['sort-order'].unshift([]);\n\t}\n\t\n\t// Add sort-order info for SCSS, Sass and Less functions into the first section:\n\tconfig['sort-order'][0].unshift('$variable', '$include', '$import');\n\t\n\t// Add configuration that mimics most of the settings from Espresso:\n\tconfig['block-indent'] = process.env.EDITOR_TAB_STRING;\n\tconfig['strip-spaces'] = true;\n\tconfig['always-semicolon'] = true;\n\tconfig['vendor-prefix-align'] = true;\n\tconfig['unitless-zero'] = true;\n\tconfig['leading-zero'] = true;\n\tconfig['quotes'] = 'double';\n\tconfig['color-case'] = 'lower';\n\tconfig['color-shorthand'] = false;\n\tconfig['space-before-colon'] = '';\n\tconfig['space-after-colon'] = ' ';\n\tconfig['space-before-combinator'] = ' ';\n\tconfig['space-after-combinator'] = ' ';\n\tconfig['space-before-opening-brace'] = ' ';\n\tconfig['space-after-opening-brace'] = process.env.EDITOR_LINE_ENDING_STRING;\n\tconfig['space-before-closing-brace'] = process.env.EDITOR_LINE_ENDING_STRING;\n\tconfig['space-before-selector-delimiter'] = '';\n\tconfig['space-after-selector-delimiter'] = process.env.EDITOR_LINE_ENDING_STRING;\n\tconfig['space-between-declarations'] = process.env.EDITOR_LINE_ENDING_STRING;\n\t\n\treturn config;\n}", "options (config = {}) {\n return session.options(CUSTOMER_REVIEW, config)\n }", "function separateEnvironmentVariablesSet() {\n var varsToFind = [EnvironmentVariables.AZURE_SERVICEBUS_NAMESPACE,\n EnvironmentVariables.AZURE_SERVICEBUS_ACCESS_KEY];\n return varsToFind.every(function (v) { return !!process.env[v]; });\n}", "function loadOptions() {\n\t\t\tvar userOptions = {};\n\n\t\t\tif (supported('localStorage')) {\n\t\t\t\tuserOptions = JSON.parse(localStorage.getItem('ADI.options')) || {};\n\t\t\t}\n\n\t\t\t// merge with defaults\n\t\t\tfor (var opt in userOptions) {\n\t\t\t\toptions[opt] = userOptions[opt];\n\t\t\t}\n\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Visit a parse tree produced by PlSqlParserfetch_statement.
visitFetch_statement(ctx) { return this.visitChildren(ctx); }
[ "function parse_StatementList(){\n\t\n\n\t\n\n\tvar tempDesc = tokenstreamCOPY[parseCounter][0]; //check desc of token\n\tvar tempType = tokenstreamCOPY[parseCounter][1]; //check type of token\n\n\tif (tempDesc == ' print' || tempType == 'identifier' || tempType == 'type' || tempDesc == ' while' || tempDesc == ' if' || tempDesc == '{' ){ //if next token is a statment\n\t\tdocument.getElementById(\"tree\").value += \"PARSER: parse_StatementList()\" + '\\n';\n\t\tCSTREE.addNode('StatementList', 'branch');\n\t\t\n\t\t\n\t\tparse_Statement(); \n\t\n\t\tparse_StatementList();\n\t\t\n\t\tCSTREE.endChildren();\n\t\n\t\t\n\t\t\n\t}\n\telse{\n\t\t\n\t\t\n\t\t//e production\n\t}\n\n\n\n\n\t\n\t\n}", "visitData_manipulation_language_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function parse_PrintStatement(){\n\tdocument.getElementById(\"tree\").value += \"PARSER: parse_PrintStatement()\" + '\\n';\n\tCSTREE.addNode('PrintStatment', 'branch');\n\n\t\n\tmatchSpecChars(' print',parseCounter);\n\t\n\tparseCounter = parseCounter + 1;\n\t\n\t\n\tmatchSpecChars('(',parseCounter);\n\t\n\tparseCounter = parseCounter + 1;\n\t\n\t\n\tparse_Expr(); \n\t\n\t\n\t\n\tmatchSpecChars (')',parseCounter);\n\t\n\tCSTREE.endChildren();\n\n\tparseCounter = parseCounter + 1;\n\t\n\t\n}", "visitSmall_stmt(ctx) {\r\n console.log(\"visitSmall_stmt\");\r\n if (ctx.expr_stmt() !== null) {\r\n return this.visit(ctx.expr_stmt());\r\n } else if (ctx.del_stmt() !== null) {\r\n return this.visit(ctx.del_stmt());\r\n } else if (ctx.pass_stmt() !== null) {\r\n return this.visit(ctx.pass_stmt());\r\n } else if (ctx.flow_stmt() !== null) {\r\n return this.visit(ctx.flow_stmt());\r\n } else if (ctx.import_stmt() !== null) {\r\n return this.visit(ctx.import_stmt());\r\n } else if (ctx.global_stmt() !== null) {\r\n return this.visit(ctx.global_stmt());\r\n } else if (ctx.nonlocal_stmt() !== null) {\r\n return this.visit(ctx.nonlocal_stmt());\r\n } else if (ctx.assert_stmt() !== null) {\r\n return this.visit(ctx.assert_stmt());\r\n }\r\n }", "visitOpen_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitSelect_only_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitLoop_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitExpr_stmt(ctx) {\r\n console.log(\"visitExpr_stmt\");\r\n if (ctx.augassign() !== null) {\r\n return {\r\n type: \"AugAssign\",\r\n left: this.visit(ctx.testlist_star_expr(0)),\r\n right: this.visit(ctx.getChild(2)),\r\n };\r\n } else {\r\n let length = ctx.getChildCount();\r\n let right = this.visit(ctx.getChild(length - 1));\r\n for (var i = length; i > 1; i = i - 2) {\r\n let temp_left = this.visit(ctx.getChild(i - 3));\r\n right = {\r\n type: \"Assignment\",\r\n left: temp_left,\r\n right: right,\r\n };\r\n }\r\n return right;\r\n }\r\n }", "visitSql_operation(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitSeq_of_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitFetch_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitPipe_row_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function selectStatement4( machine )\n {\n order = machine.popToken();\n machine.checkToken(\"by\");\n machine.checkToken(\"order\");\n where = machine.popToken();\n machine.checkToken(\"where\");\n tables = machine.popToken();\n machine.checkToken(\"from\");\n columns = machine.popToken();\n machine.checkToken(\"select\");\n machine.pushToken( new selectStatement( columns, tables, where.expression, order.expression ) );\n }", "visitCursor_manipulation_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function generateStatementList(node)\n\t{\n\t\tfor(var i = 0; i < node.children.length; i++)\n\t\t{\n\t\t\tgenerateStatement(node.children[i]);\n\t\t}\n\t}", "visitForall_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitFlow_stmt(ctx) {\r\n console.log(\"visitFlow_stmt\");\r\n if (ctx.break_stmt() !== null) {\r\n return this.visit(ctx.break_stmt());\r\n } else if (ctx.continue_stmt() !== null) {\r\n return this.visit(ctx.continue_stmt());\r\n } else if (ctx.return_stmt() !== null) {\r\n return this.visit(ctx.return_stmt());\r\n } else if (ctx.raise_stmt() !== null) {\r\n return this.visit(ctx.raise_stmt());\r\n } else if (ctx.yield_stmt() !== null) {\r\n return this.visit(ctx.yield_stmt());\r\n }\r\n }", "visitGlobal_stmt(ctx) {\r\n console.log(\"visitGlobal_stmt\");\r\n let globallist = [];\r\n for (var i = 0; i < ctx.NAME().length; i++) {\r\n globallist.push(this.visit(ctx.NAME(i)));\r\n }\r\n return { type: \"GlobalStatement\", globallist: globallist };\r\n }", "parse_statement() {\n let values = this.find_some(this.parse_base_expr, tk.COMMA, tk.BAR); \n return Ex(pr.Statement, values);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Define a function, doToArray that accepts an array and a callback. Call .forEach() on the array, passing the callback as the forEach callback.
function doToArray(array, callback){ array.forEach(callback) }
[ "function iterate(callback){\n let array = [\"dog\", \"cat\", \"squirrel\"]\n array.forEach(callback)\n return array\n}", "function procesar (unArray, callback) {\n return callback (unArray)\n}", "function myFilter(array, callback) {\n return callback(array);\n}", "function tap(arr, callback){\n callback(arr); \n return arr;\n}", "function caonimabzheshiyigewozijixiedeForEach2(arr, fn){\n var newArr = [];\n for(var i = 0; i < arr.length; i++){\n newArr.push(fn(arr[i]));\n }\n return newArr;\n}", "function operate(array, func) {\r\n if (array) {\r\n for (var n=0; n<array.length; n++) {\r\n func(array[n], n);\r\n }\r\n }\r\n return array;\r\n}", "function filter(arr, callback){\n var newArr = [];\n for (let i=0; i<arr.length; i++){\n if (callback(arr[i])) newArr.push(arr[i]);\n }\n return newArr;\n}", "forEach(cb) {\n for (var item = this._head; item; item = item.next) {\n cb(item.data);\n }\n }", "function each( a, f ){\n\t\tfor( var i = 0 ; i < a.length ; i ++ ){\n\t\t\tf(a[i])\n\t\t}\n\t}", "function forEach(arr1, func1){\n for(var i=0; i < arr1.length; i++){\n // printName(addressBook[i])\n func1(arr1[i]);\n }\n}", "function iterate(arr) {\n arr.forEach((el) => {\n if (Array.isArray(el)) {\n iterate(el);\n } else {\n result.push(el);\n }\n })\n }", "function every(array, callback){\n for (let i = 0; i < arr.length; i++){\n if (!callback(arr[i], i, arr)) return false;\n }\n return true;\n}", "static iterate(f, first_args, length) {\n let l = length || 0xffff,\n arr = [],\n c = 0;\n\n while (c < l) {\n arr.push((c === 0) ? first_args : f(arr[c - 1]));\n c = c + 1;\n }\n return arr;\n }", "convertArray (array, Type) {\n const Type0 = array.constructor\n // return array if already same Type\n if (Type0 === Type) return array\n // If Type is Array, convert via typedArrayToArray\n if (Type === Array) return this.typedArrayToArray(array)\n return new Type(array) // Use standard TypedArray constructor\n }", "function iterateArray(arr){\n for (var i = 0; i < arr.length; i++){\n console.log(arr[i]);\n }\n}", "function invoke(arr, methodName, var_args){\n var args = Array.prototype.slice.call(arguments, 2);\n forEach(arr, function(item){\n item[methodName].apply(item, args);\n });\n return arr;\n }", "function asyncArray(inputs) {\n return new AsyncArrayOps(inputs);\n}", "function for_each(){\n var param_len = arguments[0].length;\n var proc = arguments[0];\n while(!is_empty_list(arguments[1])){\n var params = [];\n for(var j = 1; j < 1+param_len; j++) {\n params.push(head(arguments[j]));\n arguments[j] = tail(arguments[j]);\n }\n proc.apply(proc, params);\n\t}\n}", "function command_executor(arr, light_constructor){\n command_array = command_array_creator(arr);\n light_array = light_array_creator(light_constructor);\n command_array.forEach( command => {\n cmd = command[0],\n [x1, y1] = command[1],\n [x2, y2] = command[2];\n\n for( i = x1; i <= x2; i++){\n for( j = y1; j <= y2; j++){\n light_array[i][j][cmd]();\n }\n }\n })\n return light_array\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pagination and Home Content
function homeContent() { $('#main-nav li').removeClass('current'); $('#home-btn').parent().addClass('current'); performGetRequest(serviceRootUrl + 'page' + pageNO() + videoLibraryCount(), onVideoLibrariesPerPageLoadSuccess, videoLibrariesErrorMessage); }
[ "function page(){\n ///djahgjkhg \n\n $(\"#page\").pagination({\n pageIndex: 0,\n pageSize: 10,\n total: 100,\n debug: true,\n showInfo: true,\n showJump: true,\n showPageSizes: true,\n loadFirstPage: true,\n firstBtnText: '首页',\n lastBtnText: '尾页',\n prevBtnText: '上一页',\n nextBtnText: '下一页',\n totalName: 'total',\n jumpBtnText: '跳转',\n infoFormat: '{start} ~ {end}条,共{total}条',\n remote: {\n url:'allHistory.action' ,\n params: null,\n success: function(data) {\n htdata = data;\n var pageindex = $(\"#page\").pagination('getPageIndex');\n var pagesize = $(\"#page\").pagination('getPageSize');\n $(\"#eventLog\").empty();\n var start = pageindex * pagesize;\n var end = (pageindex + 1) * pagesize < htdata.historyList.length ? (pageindex + 1) * pagesize : htdata.historyList.length;\n updatePaper(start, end);\n }\n }\n });\n}", "function paginate() {\n var prev = document.querySelector(\"link[rel=prev]\");\n var next = document.querySelector(\"link[rel=next]\");\n var nav = document.createElement(\"nav\");\n nav.id = \"pagination\";\n if (prev)\n nav.innerHTML = \"<a class=prev href=\" + prev.href + \">\" + prev.title + \"</a>\";\n if (next)\n nav.innerHTML += \"<a class=next href=\" + next.href + \">\" + next.title + \"</a>\";\n if (prev || next)\n document.body.appendChild(nav);\n}", "function makePagination(taskLists) {\n var numberPages = Math.ceil(taskLists.length / numberRecord);\n $(\".pagination\").html(\"\");\n if(numberPages <= 1){\n $(\".pagination\").append('');\n }else{\n for (var i = 1; i <= numberPages; i++) {\n $(\".pagination\").append('<li class=\"page-item\"><a class=\"page-link\" href=\"#\">' + i + '</a></li>');\n }\n }\n}", "function initPaging() {\n vm.pageLinks = [\n {text: \"Prev\", val: vm.pageIndex - 1},\n {text: \"Next\", val: vm.pageIndex + 1}\n ];\n vm.prevPageLink = {text: \"Prev\", val: vm.pageIndex - 1};\n vm.nextPageLink = {text: \"Next\", val: vm.pageIndex + 1};\n }", "function pageContentRouter(){\n if (window.location.hash === \"#concerts\"){\n pageContentConcerts();\n } else if (window.location.hash === \"#carpools\"){\n pageContentCarpools();\n } else if (window.location.hash === \"#flights\"){\n pageContentFlights();\n } else {\n window.location.hash = \"#home\";\n pageContentHome();\n };\n}", "buildSearchPage() {\n const myBooks = this.books.getMyBooks();\n if (this.searchedBooks === undefined) {\n return;\n }\n this.booksView.buildBookListing(this.searchedBooks, this.displayBook, myBooks);\n this.booksView.buildPagination(this.totalBooks, 100, this.currentPage, this.gotoPage, \"topPagination\");\n this.booksView.buildPagination(this.totalBooks, 100, this.currentPage, this.gotoPage, \"bottomPagination\");\n }", "function Pager(){\n\tthis.routes = {};\n\n\tthis.ctx = new PageContext();\n\n\tthis.start();\n\n\tbindEvents();\n}", "function displayPetals() {\n const start = (currentPage - 1)\n}", "function loadRecent() {\n \n if (paginationOptions.pageFirst > 0) {\n paginationOptions.pageFirst = 0;\n }\n viewsOptions.page = paginationOptions.pageFirst;\n\n return retreiveArticles(viewsOptions);\n }", "function appendPageLinks(list) {\n // determine how many pages for this student list \n var pages = Math.ceil(list.length/10);\n // create a page link section unobtrusively\n var link = '<div class=\"pagination\"><ul>';\n var pageArr = [];\n // “for” every page\n for (var i = 1; i <= pages; i++) {\n // add a page link to the page link section\n link += '<li><a href=\"#\">' + i + '</a></li>';\n pageArr.push(i);\n };\n link+='</ul></div>';\n\n // remove the old page link section from the site\n //$('.pagination ul li').remove();\n // append our new page link section to the site\n $('.page').append(link);\n // define what happens when you click a link\n $('.pagination ul li').click(function() {\n // Use the showPage function to display the page for the link clicked\n showPage($(this).text(),list);\n // mark that link as “active”\n $('.pagination ul li').removeClass('active');\n $(this).addClass('active');\n }); \n}", "function preparePage() {\n links = [];\n\n $(\".js-scroll-indicator\").each(function(index, link) {\n prepareIndicator( $(link) );\n });\n }", "function paginator(){\n\t$('.paginator').click(function(e){\n\t\tvar id = $(this).attr('data-id');\n\t\tvar bid = $(this).attr('data-bid');\n\t\tvar rel = $(this).attr('data-rel');\n\t\tvar view = $(this).attr('data-view');\n\t\tshowLoader();\n\t\turl = encodeURI(\"index.php?page=\"+rel+\"&action=\"+bid+\"&pageNum=\"+id+\"&id=\"+view);\n\t\twindow.location.replace(url);\n\t});\n}", "function primeraPagina(){\n\tif(pagina_actual!=1){\n\t\t\n\t\tpagina_actual = 1;\n\t\tconsole.log('Moviendonos a la página '+pagina_actual+\"...\");\n\t\tborrar_recetas_index();\n\t\tlet pagina = pagina_actual-1;\n\t\tpeticionRecetas(\"./rest/receta/?pag=\"+pagina+\"&lpag=6\");\n\t\tModificar_botonera_Index();\n\t}\n}", "function load() {\n numOfPages();\n loadList();\n}", "previousPage(currentPage) {\n if (currentPage > 1) {\n this.getArticles(currentPage-1);\n }\n }", "function show_page_of_products(url, page, numberOfItemsPerPage)\n{\n \n var $target= $('#center-items-container');\n\n $.ajax({\n type: \"POST\",\n data: {page: page, articles_per_page: numberOfItemsPerPage},\n url: url,\n cache: false,\n beforeSend:function(){\n },\n success: function(data){\n \n $target.empty().html(data);\n show_article_listener();\n product_hover_listener();\n \n },\n complete:function(){\n },\n }); \n return false;\n\n }", "function changeNav(total,startpage) {\r\n\tif (total > noi) {//results does not fit into one page\r\n\t\tvar html = \"\";\r\n\t\tvar startNum = cachePageNum-Math.floor(nop/2);\r\n\t\tvar totalPage = Math.ceil(total/noi);\r\n var displayTargetPage=\"\";\r\n if(document.getElementById('live_updateArea'))\r\n displayTargetPage=\"result-cached.html\";\r\n else\r\n displayTargetPage=\"result-offline.html\";\r\n\r\n\t\tif (startNum < 1)\r\n\t\t\tstartNum = 1;\r\n\t\tfor (var i = startNum; i < Math.min(nop+startNum,totalPage+1); i++) {\r\n\t\t\tif (i != cachePageNum)\r\n\t\t\t\thtml += ' <a href=\"'+displayTargetPage+'?cp='+i+'&lp='+livePageNum+'&s='+searchString+'\">'+i+'</a> ';\r\n\t\t\telse\r\n\t\t\t\thtml += ' '+i+' ';\r\n\t\t}\r\n\t\tif (cachePageNum != 1)\r\n\t\t\thtml='<a href=\"'+displayTargetPage+'?cp='+(cachePageNum-1)+'&lp='+livePageNum+'&s='+searchString+'\">Previous</a> &nbsp; &nbsp; &nbsp; &nbsp; '+html;\r\n\t\tif (cachePageNum != totalPage)\r\n\t\t\thtml += '&nbsp; &nbsp; &nbsp; &nbsp; <a href=\"'+displayTargetPage+'?cp='+(cachePageNum+1)+'&lp='+livePageNum+'&s='+searchString+'\">Next</a>';\r\n\t\tdocument.getElementById('nav').innerHTML=html;\r\n\t}\r\n}", "buildPaginationInfo() {\n var table = this.table;\n var data = table.pagination,\n reg = this.getReg(),\n page = data.page,\n totalPageCount = data.totalPageCount,\n resultsPerPage = data.resultsPerPage,\n firstObjectNumber = data.firstObjectNumber,\n lastObjectNumber = data.lastObjectNumber,\n totalItemsCount = data.totalItemsCount,\n dataAnchorTime = table.getFormattedAnchorTime(),\n isNum = _.isNumber;\n // render simply pagination information,\n // since event handlers are out of the scope of this class\n var s = \"\", sep = \" - \";\n if (isNum(page)) {\n s += reg.page + SPACE + page;\n\n if (isNum(totalPageCount) && totalPageCount > 0) {\n s += SPACE + reg.of + SPACE + totalPageCount;\n }\n\n if (isNum(firstObjectNumber) && isNum(lastObjectNumber) && lastObjectNumber > 0) {\n s += sep + reg.results + ` ${firstObjectNumber} - ${lastObjectNumber}`;\n if (isNum(totalItemsCount)) {\n s += ` ${reg.of} - ${totalItemsCount}`\n }\n }\n }\n if (dataAnchorTime && table.options.showAnchorTimestamp) {\n s += sep + `${reg.anchorTime} ${dataAnchorTime}`;\n }\n var paginationInfo = new VHtmlElement(\"span\", {\n \"class\": \"pagination-info\"\n }, new VTextElement(s));\n return paginationInfo;\n }", "loadMoreHomestays(event) {\n let pageCount = Session.get('homestayCount')\n if(pageCount) {\n pageCount = pageCount+1;\n Session.set('homestayCount', pageCount)\n } \n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
END UPDATE MINCUT ADD EXCLUDE FROM MINCUT / excludeFromMincut excludes a valve from mincut
function excludeFromMincut(valve_id, mincut_id, device, cb) { try { _self.emit("log", "mincut.js", "excludeFromMincut(" + valve_id + "," + mincut_id + "," + device + ")", "info"); var dataToSend = {}; dataToSend.valve_id = valve_id; dataToSend.mincut_id = mincut_id; dataToSend.device = device; dataToSend.token = _token; dataToSend.what = 'EXCLUDE_FROM_MINCUT'; dataToSend.expected_api_version = _expected_api_version; axios.post(_baseHref + '/ajax.sewernet.php', dataToSend).then(function (response) { if (response.data.status === "Accepted") { _self.emit("log", "mincut.js", "excludeFromMincut response", "success", response.data.message); cb(null, response.data.message); } else { cb(response.data.message, response.data.message); } })["catch"](function (error) { _self.emit("log", "mincut.js", "excludeFromMincut", "error", error); }); } catch (e) { _self.emit("log", "mincut.js", "excludeFromMincut", "error", e); cb(e, false); } }
[ "function setExcludingMincut(bool) {\n _excludingMincut = bool;\n }", "function getMincut(x, y, epsg, mincut_id_arg, id_name, cb) {\n try {\n _self.emit(\"log\", \"mincut.js\", \"getMincut(\" + x + \",\" + y + \",\" + epsg + \",\" + mincut_id_arg + \",\" + id_name + \")\", \"info\");\n\n var dataToSend = {};\n dataToSend.x = x;\n dataToSend.y = y;\n dataToSend.epsg = epsg;\n dataToSend.mincut_id_arg = mincut_id_arg;\n dataToSend.id_name = id_name;\n dataToSend.device = _device;\n dataToSend.token = _token;\n dataToSend.what = 'GET_MINCUT';\n dataToSend.expected_api_version = _expected_api_version;\n axios.post(_baseHref + '/ajax.sewernet.php', dataToSend).then(function (response) {\n if (response.data.status === \"Accepted\") {\n _self.emit(\"log\", \"mincut.js\", \"getMincut response\", \"success\", response.data.message);\n\n processGetMincut(response.data.message, cb);\n } else {\n cb(response.data.message, response.data.message);\n }\n })[\"catch\"](function (error) {\n _self.emit(\"log\", \"mincut.js\", \"getMincut\", \"error\", error);\n });\n } catch (e) {\n _self.emit(\"log\", \"mincut.js\", \"getMincut error\", \"error\", e);\n\n cb(e, false);\n }\n }", "addMinimapCutout(posX, posY, minimapWidth, minimapHeight) {\n let cutout = new Phaser.GameObjects.Graphics(this);\n cutout.fillRect(posX, posY, minimapWidth, minimapHeight);\n // let mask = new Phaser.Display.Masks.GeometryMask(this, cutout);\n let mask = new Phaser.Display.Masks.BitmapMask(this, cutout);\n // mask.invertAlpha = true;\n // lowerPanel.mask = mask;\n this.lowerPanelBackground.setMask(mask);\n this.lowerPanelBackground.mask.invertAlpha = true;\n }", "function minEleonchange(evt) {\n var uig = getg(this);\n uig.sliderEle.min = this.value*1;\n genedefs[uig.name].min = this.value*1;\n}", "function setDataMin(x)\n{\n\tdataMin = x;\n}", "function setDataInputMin(x)\n{\n\tdataInputMin = x;\n}", "function getcutoffs(){\n var inp = document.getElementById(\"cutoffinput\");\n min_cutoffs = inp.value.split(',');\n cutoffs = min_cutoffs.map(i => i*60);\n mapRedraw();\n}", "function keepWithin(value, min, max) {\n if (value < min) value = min;\n if (value > max) value = max;\n return value;\n }", "setDistanceMin(distance_min) {\n this.distance_min = Math.max(distance_min, this.distance_min_limit);\n this.zoom(0); // update, to ensure new minimum\n }", "minMaxConditionsHandler() {\n if (\n (this.min || this.min === 0) &&\n (this.value < this.min || this._previousValue < this.min)\n ) {\n this._value = this.min;\n }\n if (\n this.max &&\n (this.value > this.max || this._previousValue > this.max)\n ) {\n this._value = this.max;\n }\n }", "function processGetMincut(obj, cb) {\n _self.emit(\"log\", \"mincut.js\", \"processGetMincut response\", \"info\", obj);\n\n var retorno = {};\n\n if (typeof obj.formTabs != \"undefined\") {\n retorno = obj.formTabs;\n\n for (var i = 0; i < retorno.length; i++) {\n for (var f = 0; f < retorno[i].fields.length; f++) {\n if (retorno[i].fields[f]) {\n if (retorno[i].fields[f].type === \"combo\") {\n retorno[i].fields[f].comboValues = _assignValuesToCombo(retorno[i].fields[f]);\n } else if (retorno[i].fields[f].type === \"button\") {\n retorno[i].fields[f].buttonAction = _assignActionsToButton(retorno[i].fields[f]);\n }\n }\n }\n }\n\n var activeTabIndex = _getActiveTab(obj.formTabs);\n\n obj.activeTab = obj.formTabs[activeTabIndex];\n obj.activeTab.activeTabIndex = activeTabIndex;\n obj.formTabs = retorno;\n cb(null, obj);\n } else {\n cb(\"no fields\", \"no fields\");\n }\n } //****************************************************************", "set minLines(value) {}", "function upsertMincut(mincut_id, x, y, srid, device, id_name, pol_id, formData, cb) {\n _self.emit(\"log\", \"mincut.js\", \"upsertMincut(\" + mincut_id + \",\" + x + \",\" + y + \",\" + srid + \",\" + device + \",\" + id_name + \",\" + pol_id + \")\", \"info\", formData);\n\n var dataToSend = {};\n dataToSend.mincut_id = mincut_id;\n dataToSend.x = x;\n dataToSend.y = y;\n dataToSend.device = device;\n dataToSend.id_name = id_name;\n dataToSend.pol_id = pol_id;\n dataToSend.srid = srid; //dynamic attributes\n\n for (var k in formData) {\n if (k) {\n if (formData.hasOwnProperty(k)) {\n if (formData[k] != \"\") {\n dataToSend[k] = formData[k];\n } else if (formData[k] === 0) {\n dataToSend[k] = \"0\";\n }\n }\n }\n }\n\n dataToSend.token = _token;\n dataToSend.what = 'UPSERT_MINCUT';\n dataToSend.expected_api_version = _expected_api_version;\n axios.post(_baseHref + '/ajax.sewernet.php', dataToSend).then(function (response) {\n if (response.data.status === \"Accepted\") {\n _self.emit(\"log\", \"mincut.js\", \"upsertMincut response\", \"success\", response.data.message);\n\n cb(null, response.data.message);\n } else {\n _self.emit(\"log\", \"mincut.js\", \"upsertMincut\", \"error\", response.data.message);\n\n cb(response.data.message, response.data.message);\n }\n })[\"catch\"](function (error) {\n _self.emit(\"log\", \"mincut.js\", \"upsertMincut\", \"error\", error);\n\n cb(error, false);\n return false;\n });\n }", "function exclude_individual (i) {\n\n\t// check for shift key (to exclude a single point)\n\tif (selections.shift_key()) {\n\n\t\t// default to active subset\n\t\tvar subset_flag = true;\n\n\t\t// remove point from subset\n\t\tmds_subset[i] = 0;\n\n\t\t// check that we didn't just remove the last point\n\t\tif (!mds_subset.some(item => item !== 0)) {\n\n\t\t\t// otherwise reset subset\n\t\t\tfor (var i = 0; i < mds_coords.length; i++) {\n\t\t\t\tmds_subset[i] = 1;\n\n\t\t\t}\n\t\t\tsubset_flag = false;\n\n\t\t}\n\n\t\t// fire subset changed event\n\t\tvar subsetEvent = new CustomEvent(\"DACSubsetChanged\", { detail: {\n\t\t\t\t\t\t\t\t\t\t\tnew_subset: mds_subset,\n\t\t\t\t\t\t\t\t\t\t\tsubset_flag: subset_flag} });\n\t\tdocument.body.dispatchEvent(subsetEvent);\n\n\t// otherwise it's a focus event\n\t} else {\n\n\t\tselections.change_focus(i);\n\t}\n\n}", "get _itemsWillBeCutAndPaste() {\n return this._cuttingItems.filter(\n (i) =>\n i.span.id !==\n (this._selectionModel.span.single &&\n this._selectionModel.span.single.id)\n )\n }", "function minMaxSet() {\n min = parseInt(minRange.value);\n max = parseInt(maxRange.value);\n}", "function restrictToRange(val,min,max) {\r\n if (val < min) return min;\r\n if (val > max) return max;\r\n return val;\r\n }", "trimLists() {\n let quota = {};\n for (let type of Object.keys(this.max)) {\n quota[type] = this.max[type];\n }\n for (let i = this.finished.length-1; i >= 0; i--) {\n let obj = this.finished[i];\n if (obj.answer) {\n if (obj instanceof Point) {\n if (quota[\"point\"] != undefined) {\n if (quota[\"point\"] > 0) {\n quota[\"point\"] -= 1;\n } else {\n this.finished.splice(this.finished.indexOf(obj),1);\n }\n }\n } else if (obj instanceof Line) {\n if (quota[\"line\"] != undefined) {\n if (quota[\"line\"] > 0) {\n quota[\"line\"] -= 1;\n } else {\n this.finished.splice(this.finished.indexOf(obj),1);\n }\n }\n }\n }\n }\n }", "function minimumLessonsValidation(your, needed, row) {\r\n if (Number(your) >= Number(needed)) { \r\n row.style.border = \"none\";\r\n validationTotalErr.classList.add('hide');\r\n } else {\r\n row.style.border = '3px red solid';\r\n validationTotalErr.classList.remove('hide');\r\n console.log('fix it');\r\n }\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the APPEND_POSTFIX already exists, if it does the user is promted with the option to overwrite. If not, the function will create a new document with the APPEND_POSTFIX postfix.
function saveNewPostFix(doc, docPath){ //postfix file exists //if the user has already chosen to overwrite all //only display once if this is the case! if (OVERWRITE_ALL == true){ //just overwrite the file overwrite(doc,docPath); } // this is the first case else { if (fl.fileExists(docPath) == true){ var dialog = displaySaveDialog(docPath); //make an updated _ft version of the FLA // SINGLE OVEWRITE // if dialog choice was to overwrite OR overwrite all was chosen in the past if (shouldOverwrite(dialog) == "single"){ //overwrite the new postfix overwrite(doc,docPath); //UNCOMMENT if you want to open back up the FLA without the postfix //fl.openDocument("file://" + oldPath); } // if user chooses overwrite ALL else if(shouldOverwrite(dialog) == "all"){ //set the flag to access the SINGLE OVERWRITE loop fl.trace("Overwriting all postfix files..."); //set to avoid multiple dialogs OVERWRITE_ALL = true; //save the new postfix as if the user selected overwrite overwrite(doc,docPath); } //user chose to save as.. else{ fl.saveDocumentAs(true); fl.trace("User Saved..."); } } else{ //save a new copy with added POSTFIX doc.saveAsCopy(docPath); //close the non-postfix document fl.saveDocument(doc); fl.closeDocument(doc); //open the new postfix document fl.openDocument(docPath); fl.trace("New file Saved..." + getFileName(docPath)); } } return doc; }
[ "function overwrite(doc,docPath){\n\t\n\t//keep the location of the old FLA\n\toldPath = String(doc.pathURI);\n\t\n\t//save the new postfix FLA\n\tfl.saveDocument(doc, docPath);\n\tfl.trace(\"Saved...\" + doc.name);\n}", "function containsPostExt(path, ext){\n\treturn (path.indexOf(String(APPEND_POSTFIX + ext)) != -1);\n}", "function removeAppendixEntry(doc) {\n if ($('table[name=table_appendix][data-id=' + doc.refers_to + '] > tbody > tr[data-id=' + doc._id + ']').length > 0 ) {\n $('table[name=table_appendix][data-id=' + doc.refers_to + '] > tbody > tr[data-id=' + doc._id + ']').remove();\n }\n}", "async detectNew() {\n const existing = await self.db.countDocuments();\n return !existing;\n }", "function DocEdit_processForApply(index)\n{\n this.mergeDelims = null;\n if (!this.dontMerge)\n {\n this.mergeDelims = docEdits.canMergeBlock(this.text);\n }\n\n this.bDontMergeTop = false;\n this.bDontMergeBottom = false;\n\n this.formatForMerge();\n\n if (this.priorNode) //if node was already there, replace it\n {\n //DEBUG alert(\"priorNode = \" + dwscripts.getOuterHTML(this.priorNode));\n\n this.processPriorNodeEdit(index);\n\n }\n else if (this.text && this.text != null) //if no prior node, and something to insert\n {\n //DEBUG alert(\"inserting item with weight \"+editObj.weight+\", type=:\"+editObj.weightType+\":\\n:\"+editObj.text+\":\");\n\n this.processNewEdit(index);\n\n }\n}", "function isDocumentNew(doc){\n\t// assumes doc is the activeDocument\n\tcTID = function(s) { return app.charIDToTypeID(s); }\n\tvar ref = new ActionReference();\n\tref.putEnumerated( cTID(\"Dcmn\"),\n\tcTID(\"Ordn\"),\n\tcTID(\"Trgt\") ); //activeDoc\n\tvar desc = executeActionGet(ref);\n\tvar rc = true;\n\t\tif (desc.hasKey(cTID(\"FilR\"))) { //FileReference\n\t\tvar path = desc.getPath(cTID(\"FilR\"));\n\t\t\n\t\tif (path) {\n\t\t\trc = (path.absoluteURI.length == 0);\n\t\t}\n\t}\n\treturn rc;\n}", "function is_predef_app(name) {\n var rule = get_predefined_rules(name);\n\n if(rule.length) {\n rule = rule.split(\"\\x02\");\n if(rule[_category] == CATEGORY_APP) {\n return true;\n }\n }\n return false;\n}", "function overwriteNo(okCallback, cancelCallback) {\n showModalDialog('Save diagram as',\n true, Data.SavedDiagramTitle,\n 'OK', () => saveOK(okCallback),\n undefined, undefined,\n 'Cancel', cancelCallback);\n}", "function upsert(endpoint, doc) {\n var http = require('http');\n var url = require('url');\n var parts = url.parse(endpoint);\n var options = {\n host: parts.hostname,\n path: parts.path,\n port: parts.port,\n method: 'POST'\n };\n console.log(options);\n\n var req = http.request(options, function(res) {\n console.log('STATUS: ' + res.statusCode);\n console.log('HEADERS: ' + JSON.stringify(res.headers));\n res.setEncoding('utf8');\n res.on('data', function (chunk) {\n console.log('BODY: ' + chunk);\n });\n });\n req.write(JSON.stringify(doc));\n req.end();\n}", "async addNotification(subscriptionId, notification) {\n const exists = await this.db.notifications.get(notification.id);\n if (exists) {\n return false;\n }\n try {\n // sw.js duplicates this logic, so if you change it here, change it there too\n await this.db.notifications.add({\n ...notification,\n subscriptionId,\n // New marker (used for bubble indicator); cannot be boolean; Dexie index limitation\n new: 1,\n }); // FIXME consider put() for double tab\n await this.db.subscriptions.update(subscriptionId, {\n last: notification.id,\n });\n } catch (e) {\n console.error(`[SubscriptionManager] Error adding notification`, e);\n }\n return true;\n }", "function insertJournalAction(doc) {\n // If the entry already exist, we remove it first to hinder duplicates.\n removeAppendixEntry(doc);\n \n var html = '';\n html += '<tr data-id=\"' + doc._id + '\" data-solved=\"' + doc.solved + '\">';\n html += '<td>' + escapeHtml(doc.author) + '</td>';\n html += '<td>' + escapeHtml(doc.content) + '</td>';\n html += '<td>' + (doc.solved_by_username == null? '&nbsp;' : escapeHtml(doc.solved_by_username)) + '</td>';\n html += '<td>' + moment(doc.deadline).format('YYYY/MM/DD HH:mm:ss ZZ') + '</td>';\n html += '<td nowrap>' + moment(doc.added_timestamp_local).format('YYYY/MM/DD HH:mm:ss ZZ');\n \n // If the doc doesn't have Internet time, then we display \"N/A\" in the offset\n if (doc.added_timestamp_external) {\n offset = getTimeOffset(doc.added_timestamp_external, doc.added_timestamp_local);\n html += ' (' + (offset >= 0? '+' :'') + Math.round(offset / 1000) + ')';\n } else {\n html += ' (N/A)';\n }\n\n html += '</td>';\n html += '<td><a name=\"journal_entry_goto_action\" href=\"\" data-id=\"' + doc._id + '\"><span style=\"color:#333333;\" class=\"glyphicon glyphicon-hand-right\"></span></a></td>';\n html += '</tr>';\n\n if ($('table[name=table_appendix][data-id=' + doc.refers_to + '] > tbody').length == 0) {\n console.log(\"Could not insert html. 'table[name=table_appendix][data-id=' + doc.refers_to + '] > tbody' does not exist\");\n } else {\n $('table[name=table_appendix][data-id=' + doc.refers_to + '] > tbody').append(html);\n }\n}", "async existsInDB() {\n let result = {\n dataValues: null\n };\n try {\n const tmpResult = await db.appModel.findOne({\n where: {\n appId: this.appId\n }\n });\n\n if (tmpResult) {\n result = tmpResult;\n this.setApp(result.dataValues);\n return true;\n }\n } catch (err) {\n new ErrorInfo({\n appId: this.appId,\n message: err.message,\n func: this.existsInDB.name,\n file: constants.SRC_FILES_NAMES.APP\n }).addToDB();\n }\n return false;\n }", "function appendToDef(def, entry) {\n if (!entry)\n return def;\n if (typeof entry === 'string') {\n def[entry] = false;\n return def;\n }\n if (Array.isArray(entry)) {\n const [key, ...sugs] = entry.map((s) => s.trim());\n if (!key)\n return def;\n const s = sugs.map((s) => s.trim()).filter((s) => !!s);\n def[key] = !s.length ? false : s.length === 1 ? s[0] : s;\n return def;\n }\n Object.assign(def, entry);\n return def;\n}", "function moduleappend()\n{\n if(appending == false) {\n appending = true;\n new Zikula.Ajax.Request(\n Zikula.Config.baseURL + \"ajax.php?module=doctastic&func=createoverride\",\n {\n onComplete: moduleappend_response\n });\n }\n}", "exists() {\n return null !== this._document;\n }", "function saveDocument() {\n if (current.id) {\n console.log(\"saveDocument(old) started\");\n var isUpdateSupported = current.resources.self && $.inArray('PUT', current.resources.self.allowed) != -1;\n if (!isUpdateSupported) {\n alert(\"You are not allowed to update this document\");\n return;\n }\n showMessage(\"Updating existing document ...\");\n current.subject = $(\"#document-subject\").val();\n current.content.text = $(\"#document-text\").val();\n current.update().execute(function(response) {\n console.log(\"Update response = \" + JSON.stringify(response));\n loadDocuments();\n });\n }\n else {\n console.log(\"saveDocument(new) started\");\n showMessage(\"Saving new document ...\");\n current.subject = $(\"#new-document-subject\").val();\n current.html = $(\"#new-document-html\").val();\n user.privateDocuments.create(current).execute(function(response) {\n console.log(\"saveDocument(new) response = \" + JSON.stringify(response));\n loadDocuments();\n });\n }\n}", "function dynamicShortcutExists() {\n\n\tif (!appShortcuts) {\n\t\treturn alert('This device does not support Force Touch');\n\t}\n\n\tvar res = appShortcuts.dynamicShortcutExists('details');\n\n\tlog.args('Ti.UI.iOS.ApplicationShortcuts.dynamicShortcutExists', 'details', res);\n\n\t// If don't have it, explain how to create it\n\tif (!res) {\n\t\tTi.UI.createAlertDialog({\n\t\t\ttitle: 'Does not exist',\n\t\t\tmessage: 'Open a picture to create a dynamic shortcut.'\n\t\t}).show();\n\t}\n}", "exitPostIncrementExpression_lf_postfixExpression(ctx) {\n\t}", "function docEdits_apply()\n{\n // DEBUG var DEBUG_FILE = dw.getSiteRoot() + \"dwscripts_DEBUG.txt\";\n // DEBUG DWfile.write(DEBUG_FILE,\"docEdits_apply()\\n-----------------\\n\");\n var maintainSelection = arguments[0] || false; //optional: if true we will attempt maintain the current selection\n var dontReformatHTML = arguments[1] || false; //optional: if true we will prevent the code reformatter from running\n var tagSelection = null;\n\n var dom = dw.getDocumentDOM();\n\n docEdits.allSrc = dom.documentElement.outerHTML;\n docEdits.strNewlinePref = dwscripts.getNewline();\n \n try\n {\n if (maintainSelection)\n {\n tagSelection = extUtils.getTagSelection();\n }\n\n // Make sure weights are in order\n docEdits.sortWeights();\n\n // Process the queued edits\n for (var i=0; i < docEdits.editList.length; i++) //with each object with something to insert\n {\n var editObj = docEdits.editList[i];\n\n // set the properties of the DocEdit object needed for apply\n editObj.processForApply(i);\n \n } // end loop\n\n // We are now ready to create the new outerHTML string\n\n if (docEdits.editList.length > 0)\n {\n // Make sure our edits are in order\n docEdits.sortInserts();\n\n dw.useTranslatedSource(false);\n\n newSrc = new Array();\n\n var info = new Object();\n info.lastInsert = 0;\n info.bPendingMerge = false;\n info.bDoMergeNow = false;\n\n for (var i=0; i < docEdits.editList.length; i++)\n {\n // DEBUG DWfile.write(DEBUG_FILE,\"docEdits.editList[\" + i + \"] = \" + docEdits.editList[i].toString() + \"\\n--\\n\",\"append\");\n // DEBUG DWfile.write(DEBUG_FILE,\"docEdits.editList[\" + i + \"].weight = \" + docEdits.editList[i].weight + \"\\n--\\n\",\"append\");\n\n if (docEdits.editList[i].insertPos != null)\n {\n // DEBUG DWfile.write(DEBUG_FILE,\"insert at \"+info.lastInsert+\",\"+docEdits.editList[i].insertPos+\":\"+docEdits.allSrc.substring(info.lastInsert, docEdits.editList[i].insertPos)+\": plus :\"+ docEdits.editList[i].text+ \"\\n\\ndontPreprocessText = \" + docEdits.editList[i].dontPreprocessText + \"\\n\\n--\\n\",\"append\");\n\n if (docEdits.editList[i].insertPos > info.lastInsert)\n {\n // add the text between the end of the last edit, and our new edit\n var betweenEditsStr = docEdits.allSrc.substring(info.lastInsert, docEdits.editList[i].insertPos);\n \n // if we deleted all the content of a table cell, add &nbsp; back in.\n var oldMultiline = RegExp.multiline;\n RegExp.multiline = false;\n if ((newSrc.length > 0) && (betweenEditsStr.search(/^\\s*<\\/td>/i) != -1))\n {\n var prevSource = \"\";\n for (var j = newSrc.length - 1; j >= 0 && prevSource == \"\"; --j)\n {\n if (newSrc[j].search(/^\\s*$/) == -1)\n {\n prevSource = newSrc[j];\n }\n }\n\n if (prevSource.search(/<td>\\s*$/i) != -1)\n {\n newSrc.push(\"&nbsp;\");\n }\n }\n RegExp.multiline = oldMultiline;\n\n newSrc.push(betweenEditsStr);\n\n if (info.bPendingMerge)\n {\n // merge the last two source blocks added to newSrc\n docEdits.mergeCodeBlocks(newSrc, docEdits.editList[info.iPendingMerge].mergeDelims[0], docEdits.editList[info.iPendingMerge].mergeDelims[1]);\n info.bPendingMerge = false;\n }\n }\n\n if (!docEdits.editList[i].text && docEdits.editList[i].mergeDelims)\n {\n info.bDoMergeNow = false;\n\n docEdits.deleteCodeBlock(newSrc, docEdits.editList[i]);\n }\n else\n {\n // set the bPendingMerge and bDoMergeNow flags\n docEdits.analyzeMerge(info, i);\n }\n\n\n if (docEdits.editList[i].text.length > 0)\n {\n // When inserting HTML along with server markup, attempt to\n // convert to XHTML if necessary. The \"if necessary\" part is \n // determined by four criteria, each of which must be met:\n // 1. The doctype of the user's document is XHTML Transitional\n // or XHTML Strict;\n // The weight of the edit we're performing:\n // 2. Must NOT be aboveHTML;\n // 3. Must NOT be nodeAttribute;\n // 4. Must NOT be belowHTML.\n // (Any of the above weights indicates server code, which must\n // not be converted because characters such as \" will be entity-\n // encoded.)\n \n // Get the weight of the edit\n var weight = docEdits.editList[i].weight;\n if (!weight) weight = \"\";\n \n // Sometimes it's a word that follows the plus\n // sign, not a number. Check for that case.\n var plus = weight.indexOf('+');\n if (plus != -1)\n weight = weight.substring(0,plus);\n \n // Do a final check for any digits or + signs (e.g., \"aboveHTML+30\"\n // will become \"aboveHTML\")\n var weightType = weight.replace(/[\\d\\+]/g,\"\");\n\n //DEBUG DWfile.write(DEBUG_FILE,\"\\n--\\ndocEdits.editList[i].weight = \" + docEdits.editList[i].weight + \"\\nweightType = \" + weightType + \"\\n--\\n\",\"append\"); \n if (newSrc.length == 0)\n {\n var oldMultiline = RegExp.multiline;\n RegExp.multiline = false;\n // if we are adding the first text to newSrc, then remove\n // any newlines from the start of the text.\n var insertStr = docEdits.editList[i].text.replace(/^[\\r\\n]+/, \"\");\n //DEBUG DWfile.write(DEBUG_FILE,\"\\ninsertStr [before conversion] = '\" +insertStr + \"'\",\"append\"); \n if (dom.getIsXHTMLDocument() && weightType != \"aboveHTML\" && weightType != \"nodeAttribute\" && weightType != \"belowHTML\")\n {\n // DEBUG DWfile.write(DEBUG_FILE,\"\\ninsertStr [after conversion] = '\" + dwscripts.convertStringToXHTML(insertStr, null, false) + \"'\",\"append\"); \n // convert the string to XHTML *without converting entities*\n newSrc.push(dwscripts.convertStringToXHTML(insertStr, null, false));\n }\n else\n newSrc.push(insertStr);\n RegExp.multiline = oldMultiline;\n }\n else\n {\n var insertStr = docEdits.editList[i].text;\n // DEBUG DWfile.write(DEBUG_FILE,\"\\ninsertStr [before conversion] = '\" + insertStr + \"'\",\"append\"); \n if (dom.getIsXHTMLDocument() && weightType != \"aboveHTML\" && weightType != \"nodeAttribute\" && weightType != \"belowHTML\")\n {\n //DEBUG DWfile.write(DEBUG_FILE,\"\\ninsertStr [after conversion] = '\" + dwscripts.convertStringToXHTML(insertStr, null, false) + \"'\",\"append\"); \n // convert the string to XHTML *without converting entities*\n newSrc.push(dwscripts.convertStringToXHTML(insertStr, null, false));\n }\n else\n newSrc.push(insertStr);\n }\n }\n\n\n if (info.bDoMergeNow)\n {\n docEdits.mergeCodeBlocks(newSrc, docEdits.editList[i].mergeDelims[0], docEdits.editList[i].mergeDelims[1]);\n }\n\n if (docEdits.editList[i].replacePos)\n {\n info.lastInsert = docEdits.editList[i].replacePos;\n }\n else\n {\n info.lastInsert = docEdits.editList[i].insertPos;\n }\n }\n\n } // end loop\n\n if (info.lastInsert < docEdits.allSrc.length)\n {\n // add the rest of the original source\n var restOrigSource = docEdits.allSrc.substring(info.lastInsert);\n\n // if we deleted all the content of a table cell, add &nbsp; back in.\n var oldMultiline = RegExp.multiline;\n RegExp.multiline = false;\n if ((newSrc.length > 0) && (restOrigSource.search(/^\\s*<\\/td>/i) != -1))\n {\n var prevSource = \"\";\n for (var j = newSrc.length - 1; j >= 0 && prevSource == \"\"; --j)\n {\n if (newSrc[j].search(/^\\s*$/) == -1)\n {\n prevSource = newSrc[j];\n }\n }\n \n if (prevSource.search(/<td>\\s*$/i) != -1)\n {\n newSrc.push(\"&nbsp;\");\n }\n }\n RegExp.multiline = oldMultiline;\n\n newSrc.push(restOrigSource);\n\n \n if (info.bPendingMerge)\n {\n // merge the last two source blocks added to newSrc\n docEdits.mergeCodeBlocks(newSrc, docEdits.editList[info.iPendingMerge].mergeDelims[0], docEdits.editList[info.iPendingMerge].mergeDelims[1]);\n }\n }\n \n // DEBUG\n // alert(\"The new document source is:\\n\\n\" + newSrc.join(\"\"));\n \n //dom.documentElement.outerHTML = newSrc.join(\"\");\n if (dontReformatHTML)\n dom.setOuterHTML(newSrc.join(\"\"), false);\n else\n\t\tdom.setOuterHTML(newSrc.join(\"\"), true);\n\n\n // alert(\"After source formatting:\\n\\n\" + dom.documentElement.outerHTML );\n\n if (tagSelection)\n {\n extUtils.setTagSelection(tagSelection);\n }\n }\n }\n finally\n {\n // The commit of edits is complete or we encountered an exception. In either case,\n // clear out the class members to prepare for the next set of edits.\n docEdits.clearAll();\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function changeEmployee function changeEmployer Take action when the user changes the value of the OwnAcct field. Input: this element containing a flag
function changeEmployer() { let form = this.form; let row = this.name.substring(this.name.length - 2); if (this.value == '1') this.value = 'Y'; if (this.value.toUpperCase() == 'Y') { if (form.elements["Employee" + row]) form.elements["Employee" + row].value = "N"; if (form.elements["OwnAct" + row] && form.elements["OwnAct" + row].value == "") form.elements["OwnAct" + row].value = "N"; if (form.elements["NumHands" + row]) { // number of hands field present let numHands = form.elements["NumHands" + row]; if (numHands.value == "") { // set default numHands.value = "0"; numHands.checkfunc(); } // set default } // number of hands field present } // validate the contents of the field if (this.checkfunc) this.checkfunc(); }
[ "function changeEmployee()\n{\n let form = this.form;\n let row = this.name.substring(this.name.length - 2);\n if (this.value == '1')\n this.value = 'Y';\n if (this.value.toUpperCase() == 'Y')\n {\n if (form.elements[\"Employer\" + row])\n form.elements[\"Employer\" + row].value = \"N\";\n if (form.elements[\"OwnAcct\" + row])\n form.elements[\"OwnAcct\" + row].value = \"N\";\n }\n\n // validate the contents of the field\n if (this.checkfunc)\n this.checkfunc();\n}", "function changeSelfEmployed()\n{\n let form = this.form;\n let row = this.name.substring(this.name.length - 2);\n if (this.value == '1')\n this.value = 'Y';\n if (this.value.toUpperCase() == 'Y')\n {\n if (form.elements[\"Employee\" + row])\n form.elements[\"Employee\" + row].value = \"N\";\n if (form.elements[\"Employer\" + row] &&\n form.elements[\"Employer\" + row].value == \"\")\n form.elements[\"Employer\" + row].value = \"N\";\n }\n\n // validate the contents of the field\n if (this.checkfunc)\n this.checkfunc();\n}", "function changeOccupation()\n{\n changeElt(this); // espand abbreviations and fold value to upper case\n let occupation = this.value;\n let form = this.form;\n let censusId = form.Census.value;\n let censusYear = censusId.substring(censusId.length - 4);\n let lineNum = this.name.substring(10);\n let whereElement = form.elements['EmpWhere' + lineNum];\n let eeElement = form.elements['Employee' + lineNum];\n let oaElement = form.elements['OwnAcct' + lineNum];\n\n // fill in default values in other columns\n if (oaElement &&\n occupation == 'Farmer')\n {\n oaElement.value = 'Y';\n evt = new Event('change',{'bubbles':true});\n oaElement.dispatchEvent(evt);\n }\n\n if (eeElement &&\n (occupation == 'Farm Laborer' ||\n occupation == 'Laborer'))\n {\n eeElement.value = 'Y';\n evt = new Event('change',{'bubbles':true});\n eeElement.dispatchEvent(evt);\n }\n\n if (whereElement &&\n ((occupation == 'Farmer' && censusYear > 1911) ||\n occupation == 'Farm Laborer'))\n whereElement.value = \"Farm\";\n\n // validate the contents of the field\n if (this.checkfunc)\n this.checkfunc();\n}", "function changeEmpType()\n{\n changeElt(this); // fold value to upper case if required\n let form = this.form;\n let empType = this.value;\n let occElement = form.elements['Occupation' + this.name.substring(7)];\n let whereElement = form.elements['EmpWhere' + this.name.substring(7)];\n let occupation = occElement.value;\n if (whereElement && empType == 'O' && occupation == 'Farmer')\n whereElement.value = \"Own Farm\";\n\n // validate the contents of the field\n if (this.checkfunc)\n this.checkfunc();\n}", "function modifyMgrMgrSel(empl) {\n const employee = empl;\n db.query(\n \"SELECT id, first_name, last_name FROM employee\",\n function (err, res) {\n inquirer\n .prompt([\n {\n type: \"list\",\n message: \"And who will be their new leader?\",\n name: \"modifyMgrChangedM\",\n choices: function () {\n const choiceArrayMgr = [];\n for (let i = 0; i < res.length; i++) {\n choiceArrayMgr.push(\n `${res[i].id} | ${res[i].first_name} ${res[i].last_name}`\n );\n }\n return choiceArrayMgr;\n },\n },\n ])\n .then(function (people) {\n const mgr = parseInt(people.modifyMgrChangedM.slice(0, 5));\n const changingEmpl = employee;\n\n if (mgr === changingEmpl) {\n console.log(\n `Looks like you have the same manager and employee id. Please try again.`\n );\n modifyMgrEmplSel();\n } else {\n db.query(\n \"UPDATE employee SET manager_id = ? WHERE id = ?\",\n [mgr, changingEmpl],\n function (err, res) {\n if (err) {\n } else {\n console.log(`All set, thanks!`);\n firstQ();\n }\n }\n );\n }\n });\n }\n );\n}", "function MDEC_ExamperiodCheckboxChange(el_input) {\n console.log( \"===== MDEC_ExamperiodCheckboxChange ========= \");\n console.log( \"el_input\", el_input);\n\n if (el_input.checked) {\n mod_MEX_dict.examperiod = get_attr_from_el_int(el_input, \"data-field\")\n };\n const form_elements = el_MDEC_form_controls.querySelectorAll(\".awp_input_checkbox\")\n if (form_elements){\n for (let i = 0, el; el = form_elements[i]; i++) {\n const ep_int = get_attr_from_el_int(el, \"data-field\");\n el.checked = (ep_int === mod_MEX_dict.examperiod);\n };\n };\n\n MEX_set_headertext1_examperiod();\n\n MDEC_enable_btn_save();\n }", "function assignToCompanyForm(ev, user)\n {\n vm.employeeAssignFormData.employeeId = user.id;\n vm.employeeAssignFormData.employeeUsername = user.username;\n }", "function stateSetApprover() {\n var FlowState = w2ui.propertyForm.record.FlowState;\n var si = getCurrentStateInfo();\n var uid = 0;\n\n if (si == null) {\n console.log('Could not determine the current stateInfo object');\n return;\n }\n if (typeof w2ui.stateChangeForm.record.ApproverName == \"object\" && w2ui.stateChangeForm.record.ApproverName != null) {\n if (w2ui.stateChangeForm.record.ApproverName.length > 0) {\n uid = w2ui.stateChangeForm.record.ApproverName[0].UID;\n }\n }\n if (uid == 0) {\n w2ui.stateChangeForm.error('ERROR: You must select a valid user');\n return;\n }\n si.ApproverUID = uid;\n si.Reason = \"\";\n var x = document.getElementById(\"smApproverReason\");\n if (x != null) {\n si.Reason = x.value;\n }\n if (si.Reason.length < 2) {\n w2ui.stateChangeForm.error('ERROR: You must supply a reason');\n return;\n }\n finishStateChange(si,\"setapprover\");\n}", "function changeLeadType(leadid,account)\r\n{\r\nvar accountName=$(\"#\"+account).val();\r\nvar leadidaccount=$(\"#\"+leadid).val();\r\n\r\n$(\"#name_account\").val(accountName);\r\n$(\"#leadid_account\").val(leadidaccount);\r\n$(\"#account_action\").val(\"addlead\");\r\n\r\n}", "function viewEmpModalAction() {\n if (userRole === \"Admin\" || userRole === \"Employee\") {\n dropdown_content.style.visibility =\"hidden\";\n viewEmpModal.className += \" visible\";\n employeeSelectViewEmployee.value = \"\";\n startDatePicker.value = \"0000-00-00\";\n toDatePicker.value = \"0000-00-00\";\n empTotalHours.value = \"\";\n }\n}", "function ApplyBusinessRulesForRespondee(stage, status, securityRequestOwner, currentEmployeeNo) {\n\n if ((securityRequestOwner === undefined) || (securityRequestOwner === null)) {\n\n return;\n }\n\n if ((currentEmployeeNo === undefined) || (currentEmployeeNo === null)) {\n\n return;\n }\n\n var isInternetExplorer11OrAbove = !!(navigator.userAgent.match(/Trident/) && !navigator.userAgent.match(/MSIE/));\n\n if (securityRequestOwner === currentEmployeeNo) {\n\n // provide read/write access for the security owner\n\n if (stage === 'Create / Edit') {\n\n if ((status === 'Request Started') ||\n (status === 'Awaiting Business Solutions Approval') ||\n (status == 'Submit for Business Solutions Approval') ||\n (status === 'Approval Received From Business Solutions')) {\n\n try {\n\n if (isInternetExplorer11OrAbove == false) {\n\n // display the respondee detail section as read-write mode.\n\n SetReadOnlyForRespondee(document.getElementById('divRespondeeDetails').all('ddlRespondeeType'), false);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeDetails').all('txtRespondeeReferenceNo'), false);\n\n // display the respondee response section as read-only mode.\n\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all.item('ddlRespondeeResponse'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all.item('txtArticleNumber'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all.item('ddlPostedTo'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all.item('txtThirdPartyName'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all.item('txtThirdPartyAddress'), true);\n\n // hide the respondee response section\n document.getElementById('divRespondeeResponse').style.display = 'none';\n\n // display the financial institution section as read-write mode.\n\n var ddlFinancialInstitution = document.getElementById('divFinancialInstitution').all('ddlFinancialInstitution');\n\n if ((ddlFinancialInstitution !== undefined) && (ddlFinancialInstitution != null)) {\n\n SetReadOnlyForRespondee(ddlFinancialInstitution, false);\n\n ddlFinancialInstitution.onchange = function () {\n\n if (typeof (OnChangeFinancialInstitution) == 'function') {\n\n OnChangeFinancialInstitution(this);\n }\n\n if (typeof (stopEventBubbling) == 'function') {\n\n stopEventBubbling(window.event);\n }\n\n return false;\n };\n }\n\n // display the discharge of mortgage section as read-write mode.\n\n SetReadOnlyForRespondee(document.getElementById('divMortgageDischarge').all('chkMortgageDischargeReceived'), false);\n SetReadOnlyForRespondee(document.getElementById('divMortgageDischarge').all(getRespondeeControlId('gvMortgageDischarge')), false);\n\n } else {\n\n // display the respondee detail section as read-write mode.\n\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeDetails', 'ddlRespondeeType'), false);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeDetails', 'txtRespondeeReferenceNo'), false);\n\n // display the respondee response section as read-only mode.\n\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'ddlRespondeeResponse'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtArticleNumber'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'ddlPostedTo'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtThirdPartyName'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtThirdPartyAddress'), true);\n\n // hide the respondee response section\n document.getElementById('divRespondeeResponse').style.display = 'none';\n\n // display the financial institution section as read-write mode.\n\n var ddlFinancialInstitution = getRespondeeControl('divFinancialInstitution', 'ddlFinancialInstitution');\n\n if ((ddlFinancialInstitution !== undefined) && (ddlFinancialInstitution != null)) {\n\n SetReadOnlyForRespondee(ddlFinancialInstitution, false);\n\n ddlFinancialInstitution.onchange = function () {\n\n if (typeof (OnChangeFinancialInstitution) == 'function') {\n\n OnChangeFinancialInstitution(this);\n }\n\n if (typeof (stopEventBubbling) == 'function') {\n\n stopEventBubbling(window.event);\n }\n\n return false;\n };\n }\n\n // display the discharge of mortgage section as read-write mode.\n\n SetReadOnlyForRespondee(getRespondeeControl('divMortgageDischarge', 'chkMortgageDischargeReceived'), false);\n SetReadOnlyForRespondee(getRespondeeControl('divMortgageDischarge', 'gvMortgageDischarge'), false);\n\n }\n\n } catch (err) {\n\n alert(RespondeeScriptFileName + '. Function: ApplyBusinessRulesForRespondee. Event: Initialize. Error: ' + err.description);\n }\n\n } else if (status === 'Awaiting Additional Info') {\n\n try {\n\n if (isInternetExplorer11OrAbove == false) {\n\n // display the respondee detail section as read-only mode.\n\n SetReadOnlyForRespondee(document.getElementById('divRespondeeDetails').all('ddlRespondeeType'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeDetails').all('txtRespondeeReferenceNo'), true);\n\n // display the respondee response section as read-only mode.\n\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('ddlRespondeeResponse'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('txtArticleNumber'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('ddlPostedTo'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('txtThirdPartyName'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('txtThirdPartyAddress'), true);\n\n // hide the respondee response section\n document.getElementById('divRespondeeResponse').style.display = 'none';\n\n // display the financial institution section as read-write mode.\n\n var ddlFinancialInstitution = document.getElementById('divFinancialInstitution').all('ddlFinancialInstitution');\n\n if ((ddlFinancialInstitution !== undefined) && (ddlFinancialInstitution != null)) {\n\n SetReadOnlyForRespondee(ddlFinancialInstitution, false);\n\n ddlFinancialInstitution.onchange = function () {\n\n if (typeof (OnChangeFinancialInstitution) == 'function') {\n\n OnChangeFinancialInstitution(this);\n }\n\n if (typeof (stopEventBubbling) == 'function') {\n\n stopEventBubbling(window.event);\n }\n\n return false;\n };\n }\n\n // display the discharge of mortgage section as read-only mode.\n\n SetReadOnlyForRespondee(document.getElementById('divMortgageDischarge').all('chkMortgageDischargeReceived'), true);\n SetReadOnlyForRespondee(document.getElementById('divMortgageDischarge').all(getRespondeeControlId('gvMortgageDischarge')), true);\n\n } else {\n\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeDetails', 'ddlRespondeeType'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeDetails', 'txtRespondeeReferenceNo'), true);\n\n // display the respondee response section as read-only mode.\n\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'ddlRespondeeResponse'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtArticleNumber'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'ddlPostedTo'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtThirdPartyName'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtThirdPartyAddress'), true);\n\n // hide the respondee response section\n document.getElementById('divRespondeeResponse').style.display = 'none';\n\n // display the financial institution section as read-write mode.\n\n var ddlFinancialInstitution = getRespondeeControl('divFinancialInstitution', 'ddlFinancialInstitution');\n\n if ((ddlFinancialInstitution !== undefined) && (ddlFinancialInstitution != null)) {\n\n SetReadOnlyForRespondee(ddlFinancialInstitution, false);\n\n ddlFinancialInstitution.onchange = function () {\n\n if (typeof (OnChangeFinancialInstitution) == 'function') {\n\n OnChangeFinancialInstitution(this);\n }\n\n if (typeof (stopEventBubbling) == 'function') {\n\n stopEventBubbling(window.event);\n }\n\n return false;\n };\n }\n\n // display the discharge of mortgage section as read-only mode.\n\n SetReadOnlyForRespondee(getRespondeeControl('divMortgageDischarge', 'chkMortgageDischargeReceived'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divMortgageDischarge', 'gvMortgageDischarge'), true);\n\n }\n\n } catch (err) {\n\n alert(RespondeeScriptFileName + '. Function: ApplyBusinessRulesForRespondee. Event: Initialize. Error: ' + err.description);\n }\n\n } else if (status === 'Additional Info Received') {\n\n try {\n\n if (isInternetExplorer11OrAbove == false) {\n\n // display the respondee detail section as read-only mode.\n\n SetReadOnlyForRespondee(document.getElementById('divRespondeeDetails').all('ddlRespondeeType'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeDetails').all('txtRespondeeReferenceNo'), true);\n\n // display the respondee response section as read-only mode.\n\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('ddlRespondeeResponse'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('txtArticleNumber'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('ddlPostedTo'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('txtThirdPartyName'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('txtThirdPartyAddress'), true);\n\n // hide the respondee response section\n document.getElementById('divRespondeeResponse').style.display = 'none';\n\n // display the financial institution section as read-only mode.\n\n var ddlFinancialInstitution = document.getElementById('divFinancialInstitution').all('ddlFinancialInstitution');\n\n if ((ddlFinancialInstitution !== null) && (ddlFinancialInstitution != null)) {\n\n SetReadOnlyForRespondee(ddlFinancialInstitution, true);\n\n if ((typeof (ddlFinancialInstitution.hasAttribute) == 'function') && (ddlFinancialInstitution.hasAttribute('onchange') != null)) {\n\n var fn = function () {\n\n if (typeof (OnChangeFinancialInstitution) == 'function') {\n\n OnChangeFinancialInstitution(this);\n }\n\n if (typeof (stopEventBubbling) == 'function') {\n\n stopEventBubbling(window.event);\n }\n\n return false;\n };\n\n if (ddlFinancialInstitution.hasAttribute('onchange') == true) {\n\n if (typeof (ddlFinancialInstitution.removeEventListener) == 'function') {\n\n ddlFinancialInstitution.removeEventListener('onchange', fn);\n }\n }\n }\n\n }\n\n // display the discharge of mortgage section as read-write mode.\n\n SetReadOnlyForRespondee(document.getElementById('divMortgageDischarge').all('chkMortgageDischargeReceived'), false);\n SetReadOnlyForRespondee(document.getElementById('divMortgageDischarge').all(getRespondeeControlId('gvMortgageDischarge')), false);\n\n } else {\n\n // display the respondee detail section as read-only mode.\n\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeDetails', 'ddlRespondeeType'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeDetails', 'txtRespondeeReferenceNo'), true);\n\n // display the respondee response section as read-only mode.\n\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'ddlRespondeeResponse'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtArticleNumber'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'ddlPostedTo'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtThirdPartyName'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtThirdPartyAddress'), true);\n\n // hide the respondee response section\n document.getElementById('divRespondeeResponse').style.display = 'none';\n\n // display the financial institution section as read-only mode.\n\n var ddlFinancialInstitution = getRespondeeControl('divFinancialInstitution', 'ddlFinancialInstitution');\n\n if ((ddlFinancialInstitution !== null) && (ddlFinancialInstitution != null)) {\n\n SetReadOnlyForRespondee(ddlFinancialInstitution, true);\n\n if ((typeof (ddlFinancialInstitution.hasAttribute) == 'function') && (ddlFinancialInstitution.hasAttribute('onchange') != null)) {\n\n var fn = function () {\n\n if (typeof (OnChangeFinancialInstitution) == 'function') {\n\n OnChangeFinancialInstitution(this);\n }\n\n if (typeof (stopEventBubbling) == 'function') {\n\n stopEventBubbling(window.event);\n }\n\n return false;\n };\n\n if (ddlFinancialInstitution.hasAttribute('onchange') == true) {\n\n if (typeof (ddlFinancialInstitution.removeEventListener) == 'function') {\n\n ddlFinancialInstitution.removeEventListener('onchange', fn);\n }\n }\n }\n\n }\n\n // display the discharge of mortgage section as read-write mode.\n\n SetReadOnlyForRespondee(getRespondeeControl('divMortgageDischarge', 'chkMortgageDischargeReceived'), false);\n SetReadOnlyForRespondee(getRespondeeControl('divMortgageDischarge', 'gvMortgageDischarge'), false);\n\n }\n\n } catch (err) {\n\n alert(RespondeeScriptFileName + '. Function: ApplyBusinessRulesForRespondee. Event: Initialize. Error: ' + err.description);\n\n }\n\n } else {\n\n try {\n\n if (isInternetExplorer11OrAbove == false) {\n\n // display the respondee detail section as read-write mode.\n\n SetReadOnlyForRespondee(document.getElementById('divRespondeeDetails').all('ddlRespondeeType'), false);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeDetails').all('txtRespondeeReferenceNo'), false);\n\n // display the respondee response section as read-only mode.\n\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('ddlRespondeeResponse'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('txtArticleNumber'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('ddlPostedTo'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('txtThirdPartyName'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('txtThirdPartyAddress'), true);\n\n // hide the respondee response section\n document.getElementById('divRespondeeResponse').style.display = 'none';\n\n // display the financial institution section as read-write mode.\n\n var ddlFinancialInstitution = document.getElementById('divFinancialInstitution').all('ddlFinancialInstitution');\n\n if ((ddlFinancialInstitution !== undefined) && (ddlFinancialInstitution != null)) {\n\n SetReadOnlyForRespondee(ddlFinancialInstitution, false);\n\n ddlFinancialInstitution.onchange = function () {\n\n if (typeof (OnChangeFinancialInstitution) == 'function') {\n\n OnChangeFinancialInstitution(this);\n }\n\n if (typeof (stopEventBubbling) == 'function') {\n\n stopEventBubbling(window.event);\n }\n\n return false;\n };\n }\n\n // display the discharge of mortgage section as read-write mode.\n\n SetReadOnlyForRespondee(document.getElementById('divMortgageDischarge').all('chkMortgageDischargeReceived'), false);\n SetReadOnlyForRespondee(document.getElementById('divMortgageDischarge').all(getRespondeeControlId('gvMortgageDischarge')), false);\n\n } else {\n\n // display the respondee detail section as read-write mode.\n\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeDetails', 'ddlRespondeeType'), false);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeDetails', 'txtRespondeeReferenceNo'), false);\n\n // display the respondee response section as read-only mode.\n\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'ddlRespondeeResponse'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtArticleNumber'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'ddlPostedTo'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtThirdPartyName'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtThirdPartyAddress'), true);\n\n // hide the respondee response section\n document.getElementById('divRespondeeResponse').style.display = 'none';\n\n // display the financial institution section as read-write mode.\n\n var ddlFinancialInstitution = getRespondeeControl('divFinancialInstitution', 'ddlFinancialInstitution');\n\n if ((ddlFinancialInstitution !== undefined) && (ddlFinancialInstitution != null)) {\n\n SetReadOnlyForRespondee(ddlFinancialInstitution, false);\n\n ddlFinancialInstitution.onchange = function () {\n\n if (typeof (OnChangeFinancialInstitution) == 'function') {\n\n OnChangeFinancialInstitution(this);\n }\n\n if (typeof (stopEventBubbling) == 'function') {\n\n stopEventBubbling(window.event);\n }\n\n return false;\n };\n }\n\n // display the discharge of mortgage section as read-write mode.\n\n SetReadOnlyForRespondee(getRespondeeControl('divMortgageDischarge', 'chkMortgageDischargeReceived'), false);\n SetReadOnlyForRespondee(getRespondeeControl('divMortgageDischarge', 'gvMortgageDischarge'), false);\n\n }\n\n } catch (err) {\n\n alert(RespondeeScriptFileName + '. Function: ApplyBusinessRulesForRespondee. Event: Initialize. Error: ' + err.description);\n\n }\n\n }\n\n\n } else if (stage === 'Settlement Booking') {\n\n if ((status === 'Redemptions Confirmed') ||\n (status === 'Awaiting Supervisor Approval') ||\n (status === 'Ready for Settlement') ||\n (status === 'Request Settled')) {\n\n try {\n\n if (isInternetExplorer11OrAbove == false) {\n\n // display the respondee detail section as read-only mode.\n\n SetReadOnlyForRespondee(document.getElementById('divRespondeeDetails').all('ddlRespondeeType'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeDetails').all('txtRespondeeReferenceNo'), true);\n\n // display the respondee response section as read-write mode.\n\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('ddlRespondeeResponse'), false);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('txtArticleNumber'), false);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('ddlPostedTo'), false);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('txtThirdPartyName'), false);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('txtThirdPartyAddress'), false);\n\n // display the financial institution section as read-only mode.\n\n var ddlFinancialInstitution = document.getElementById('divFinancialInstitution').all('ddlFinancialInstitution');\n\n if ((ddlFinancialInstitution !== null) && (ddlFinancialInstitution != null)) {\n\n SetReadOnlyForRespondee(ddlFinancialInstitution, true);\n\n if ((typeof (ddlFinancialInstitution.hasAttribute) == 'function') && (ddlFinancialInstitution.hasAttribute('onchange') != null)) {\n\n var fn = function () {\n\n if (typeof (OnChangeFinancialInstitution) == 'function') {\n\n OnChangeFinancialInstitution(this);\n }\n\n if (typeof (stopEventBubbling) == 'function') {\n\n stopEventBubbling(window.event);\n }\n\n return false;\n };\n\n if (ddlFinancialInstitution.hasAttribute('onchange') == true) {\n\n if (typeof (ddlFinancialInstitution.removeEventListener) == 'function') {\n\n ddlFinancialInstitution.removeEventListener('onchange', fn);\n\n }\n }\n }\n\n }\n\n // display the discharge of mortgage section as read-only mode.\n\n SetReadOnlyForRespondee(document.getElementById('divMortgageDischarge').all('chkMortgageDischargeReceived'), true);\n SetReadOnlyForRespondee(document.getElementById('divMortgageDischarge').all(getRespondeeControlId('gvMortgageDischarge')), true);\n\n } else {\n\n // display the respondee detail section as read-only mode.\n\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeDetails', 'ddlRespondeeType'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeDetails', 'txtRespondeeReferenceNo'), true);\n\n // display the respondee response section as read-write mode.\n\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'ddlRespondeeResponse'), false);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtArticleNumber'), false);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'ddlPostedTo'), false);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtThirdPartyName'), false);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtThirdPartyAddress'), false);\n\n // display the financial institution section as read-only mode.\n\n var ddlFinancialInstitution = getRespondeeControl('divFinancialInstitution', 'ddlFinancialInstitution');\n\n if ((ddlFinancialInstitution !== null) && (ddlFinancialInstitution != null)) {\n\n SetReadOnlyForRespondee(ddlFinancialInstitution, true);\n\n if ((typeof (ddlFinancialInstitution.hasAttribute) == 'function') && (ddlFinancialInstitution.hasAttribute('onchange') != null)) {\n\n var fn = function () {\n\n if (typeof (OnChangeFinancialInstitution) == 'function') {\n\n OnChangeFinancialInstitution(this);\n }\n\n if (typeof (stopEventBubbling) == 'function') {\n\n stopEventBubbling(window.event);\n }\n\n return false;\n };\n\n if (ddlFinancialInstitution.hasAttribute('onchange') == true) {\n\n if (typeof (ddlFinancialInstitution.removeEventListener) == 'function') {\n\n ddlFinancialInstitution.removeEventListener('onchange', fn);\n\n }\n }\n }\n\n }\n\n // display the discharge of mortgage section as read-only mode.\n\n SetReadOnlyForRespondee(getRespondeeControl('divMortgageDischarge', 'chkMortgageDischargeReceived'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divMortgageDischarge', 'gvMortgageDischarge'), true);\n\n }\n\n\n } catch (err) {\n\n alert(RespondeeScriptFileName + '. Function: ApplyBusinessRulesForRespondee. Event: Initialize. Error: ' + err.description);\n\n }\n\n } else {\n\n try {\n\n if (isInternetExplorer11OrAbove == false) {\n\n // display the respondee detail section as read-only mode.\n\n SetReadOnlyForRespondee(document.getElementById('divRespondeeDetails').all('ddlRespondeeType'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeDetails').all('txtRespondeeReferenceNo'), true);\n\n // display the respondee response section as read-only mode.\n\n document.getElementById('divRespondeeResponse').style.display = 'block';\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('ddlRespondeeResponse'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('txtArticleNumber'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('ddlPostedTo'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('txtThirdPartyName'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('txtThirdPartyAddress'), true);\n\n // display the financial institution section as read-only mode.\n\n var ddlFinancialInstitution = document.getElementById('divFinancialInstitution').all('ddlFinancialInstitution');\n\n if ((ddlFinancialInstitution !== null) && (ddlFinancialInstitution != null)) {\n\n SetReadOnlyForRespondee(ddlFinancialInstitution, true);\n\n if ((typeof (ddlFinancialInstitution.hasAttribute) == 'function') && (ddlFinancialInstitution.hasAttribute('onchange') != null)) {\n\n var fn = function () {\n\n if (typeof (OnChangeFinancialInstitution) == 'function') {\n\n OnChangeFinancialInstitution(this);\n }\n\n if (typeof (stopEventBubbling) == 'function') {\n\n stopEventBubbling(window.event);\n }\n\n return false;\n };\n\n if (ddlFinancialInstitution.hasAttribute('onchange') == true) {\n\n if (typeof (ddlFinancialInstitution.removeEventListener) == 'function') {\n\n ddlFinancialInstitution.removeEventListener('onchange', fn);\n }\n\n }\n }\n\n }\n\n // display the discharge of mortgage section as read-only mode.\n\n SetReadOnlyForRespondee(document.getElementById('divMortgageDischarge').all('chkMortgageDischargeReceived'), true);\n SetReadOnlyForRespondee(document.getElementById('divMortgageDischarge').all(getRespondeeControlId('gvMortgageDischarge')), true);\n\n } else {\n\n // display the respondee detail section as read-only mode.\n\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeDetails', 'ddlRespondeeType'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeDetails', 'txtRespondeeReferenceNo'), true);\n\n // display the respondee response section as read-only mode.\n\n document.getElementById('divRespondeeResponse').style.display = 'block';\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'ddlRespondeeResponse'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtArticleNumber'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'ddlPostedTo'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtThirdPartyName'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtThirdPartyAddress'), true);\n\n // display the financial institution section as read-only mode.\n\n var ddlFinancialInstitution = getRespondeeControl('divFinancialInstitution', 'ddlFinancialInstitution');\n\n if ((ddlFinancialInstitution !== null) && (ddlFinancialInstitution != null)) {\n\n SetReadOnlyForRespondee(ddlFinancialInstitution, true);\n\n if ((typeof (ddlFinancialInstitution.hasAttribute) == 'function') && (ddlFinancialInstitution.hasAttribute('onchange') != null)) {\n\n var fn = function () {\n\n if (typeof (OnChangeFinancialInstitution) == 'function') {\n\n OnChangeFinancialInstitution(this);\n }\n\n if (typeof (stopEventBubbling) == 'function') {\n\n stopEventBubbling(window.event);\n }\n\n return false;\n };\n\n if (ddlFinancialInstitution.hasAttribute('onchange') == true) {\n\n if (typeof (ddlFinancialInstitution.removeEventListener) == 'function') {\n\n ddlFinancialInstitution.removeEventListener('onchange', fn);\n }\n\n }\n }\n\n }\n\n // display the discharge of mortgage section as read-only mode.\n\n SetReadOnlyForRespondee(getRespondeeControl('divMortgageDischarge', 'chkMortgageDischargeReceived'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divMortgageDischarge', 'gvMortgageDischarge'), true);\n\n }\n\n } catch (err) {\n\n alert(RespondeeScriptFileName + '. Function: ApplyBusinessRulesForRespondee. Event: Initialize. Error: ' + err.description);\n\n }\n\n }\n\n } else {\n\n try {\n\n if (isInternetExplorer11OrAbove == false) {\n\n // display the respondee detail section as read-write mode.\n\n SetReadOnlyForRespondee(document.getElementById('divRespondeeDetails').all('ddlRespondeeType'), false);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeDetails').all('txtRespondeeReferenceNo'), false);\n\n // display the respondee response section as read-only mode.\n\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('ddlRespondeeResponse'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('txtArticleNumber'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('ddlPostedTo'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('txtThirdPartyName'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('txtThirdPartyAddress'), true);\n\n // hide the respondee response section\n document.getElementById('divRespondeeResponse').style.display = 'none';\n\n // display the financial institution section as read-write mode.\n\n var ddlFinancialInstitution = document.getElementById('divFinancialInstitution').all('ddlFinancialInstitution');\n\n if ((ddlFinancialInstitution !== undefined) && (ddlFinancialInstitution != null)) {\n\n SetReadOnlyForRespondee(ddlFinancialInstitution, false);\n\n ddlFinancialInstitution.onchange = function () {\n\n if (typeof (OnChangeFinancialInstitution) == 'function') {\n\n OnChangeFinancialInstitution(this);\n }\n\n if (typeof (stopEventBubbling) == 'function') {\n\n stopEventBubbling(window.event);\n }\n\n return false;\n };\n }\n\n // display the discharge of mortgage section as read-write mode.\n\n SetReadOnlyForRespondee(document.getElementById('divMortgageDischarge').all('chkMortgageDischargeReceived'), false);\n SetReadOnlyForRespondee(document.getElementById('divMortgageDischarge').all(getRespondeeControlId('gvMortgageDischarge')), false);\n\n } else {\n\n // display the respondee detail section as read-write mode.\n\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeDetails', 'ddlRespondeeType'), false);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeDetails', 'txtRespondeeReferenceNo'), false);\n\n // display the respondee response section as read-only mode.\n\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'ddlRespondeeResponse'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtArticleNumber'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'ddlPostedTo'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtThirdPartyName'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtThirdPartyAddress'), true);\n\n // hide the respondee response section\n document.getElementById('divRespondeeResponse').style.display = 'none';\n\n // display the financial institution section as read-write mode.\n\n var ddlFinancialInstitution = getRespondeeControl('divFinancialInstitution', 'ddlFinancialInstitution');\n\n if ((ddlFinancialInstitution !== undefined) && (ddlFinancialInstitution != null)) {\n\n SetReadOnlyForRespondee(ddlFinancialInstitution, false);\n\n ddlFinancialInstitution.onchange = function () {\n\n if (typeof (OnChangeFinancialInstitution) == 'function') {\n\n OnChangeFinancialInstitution(this);\n }\n\n if (typeof (stopEventBubbling) == 'function') {\n\n stopEventBubbling(window.event);\n }\n\n return false;\n };\n }\n\n // display the discharge of mortgage section as read-write mode.\n\n SetReadOnlyForRespondee(document.getElementById('divMortgageDischarge').all('chkMortgageDischargeReceived'), false);\n SetReadOnlyForRespondee(document.getElementById('divMortgageDischarge').all(getRespondeeControlId('gvMortgageDischarge')), false);\n\n }\n\n } catch (err) {\n\n alert(RespondeeScriptFileName + '. Function: ApplyBusinessRulesForRespondee. Event: Initialize. Error: ' + err.description);\n\n }\n\n }\n\n\n } else {\n\n // provide read-access only for non-security owners\n\n // display the respondee detail section as read-only mode.\n\n try {\n\n if (isInternetExplorer11OrAbove == false) {\n\n SetReadOnlyForRespondee(document.getElementById('divRespondeeDetails').all('ddlRespondeeType'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeDetails').all('txtRespondeeReferenceNo'), true);\n\n // display the respondee response section as read-only mode.\n\n document.getElementById('divRespondeeResponse').style.display = 'block';\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('ddlRespondeeResponse'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('txtArticleNumber'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('ddlPostedTo'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('txtThirdPartyName'), true);\n SetReadOnlyForRespondee(document.getElementById('divRespondeeResponse').all('txtThirdPartyAddress'), true);\n\n // display the financial institution section as read-only mode.\n\n var ddlFinancialInstitution = document.getElementById('divFinancialInstitution').all('ddlFinancialInstitution');\n\n if ((ddlFinancialInstitution !== null) && (ddlFinancialInstitution != null)) {\n\n SetReadOnlyForRespondee(ddlFinancialInstitution, true);\n\n if ((typeof (ddlFinancialInstitution.hasAttribute) == 'function') && (ddlFinancialInstitution.hasAttribute('onchange') != null)) {\n\n var fn = function () {\n\n if (typeof (OnChangeFinancialInstitution) == 'function') {\n\n OnChangeFinancialInstitution(this);\n }\n\n if (typeof (stopEventBubbling) == 'function') {\n\n stopEventBubbling(window.event);\n }\n\n return false;\n };\n\n if (ddlFinancialInstitution.hasAttribute('onchange') == true) {\n\n if (typeof (ddlFinancialInstitution.removeEventListener) == 'function') {\n\n ddlFinancialInstitution.removeEventListener('onchange', fn);\n }\n\n }\n }\n\n }\n\n // display the discharge of mortgage section as read-only mode.\n\n SetReadOnlyForRespondee(document.getElementById('divMortgageDischarge').all('chkMortgageDischargeReceived'), true);\n SetReadOnlyForRespondee(document.getElementById('divMortgageDischarge').all(getRespondeeControlId('gvMortgageDischarge')), true);\n\n } else {\n\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeDetails', 'ddlRespondeeType'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeDetails', 'txtRespondeeReferenceNo'), true);\n\n // display the respondee response section as read-only mode.\n\n document.getElementById('divRespondeeResponse').style.display = 'block';\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'ddlRespondeeResponse'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtArticleNumber'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'ddlPostedTo'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtThirdPartyName'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divRespondeeResponse', 'txtThirdPartyAddress'), true);\n\n // display the financial institution section as read-only mode.\n\n var ddlFinancialInstitution = getRespondeeControl('divFinancialInstitution', 'ddlFinancialInstitution');\n\n if ((ddlFinancialInstitution !== null) && (ddlFinancialInstitution != null)) {\n\n SetReadOnlyForRespondee(ddlFinancialInstitution, true);\n\n if ((typeof (ddlFinancialInstitution.hasAttribute) == 'function') && (ddlFinancialInstitution.hasAttribute('onchange') != null)) {\n\n var fn = function () {\n\n if (typeof (OnChangeFinancialInstitution) == 'function') {\n\n OnChangeFinancialInstitution(this);\n }\n\n if (typeof (stopEventBubbling) == 'function') {\n\n stopEventBubbling(window.event);\n }\n\n return false;\n };\n\n if (ddlFinancialInstitution.hasAttribute('onchange') == true) {\n\n if (typeof (ddlFinancialInstitution.removeEventListener) == 'function') {\n\n ddlFinancialInstitution.removeEventListener('onchange', fn);\n }\n\n }\n }\n\n }\n\n // display the discharge of mortgage section as read-only mode.\n\n SetReadOnlyForRespondee(getRespondeeControl('divMortgageDischarge', 'chkMortgageDischargeReceived'), true);\n SetReadOnlyForRespondee(getRespondeeControl('divMortgageDischarge', 'gvMortgageDischarge'), true);\n\n }\n\n } catch (err) {\n\n alert(RespondeeScriptFileName + '. Function: ApplyBusinessRulesForRespondee. Event: Initialize. Error: ' + err.description);\n\n }\n }\n\n if (document.getElementById('hdnIsMortgageDischargeRequestRcvd').value == 'true') {\n var trMortgageDischarge = document.getElementById('trMortgageDischarge');\n\n if ((trMortgageDischarge !== null)) {\n\n trMortgageDischarge.style.display = 'inline-block';\n\n }\n\n document.getElementById('chkMortgageDischargeReceived').checked = true;\n }\n}", "function ChangeDefault(index,action)\n{\n\tif (UPDATING)\n\t\treturn;\n\n\tvar thisCtry = Accounts.Hash[Employee.work_country]\n\tvar Accts = thisCtry.OpenAccounts\n\n\tvar FoundDefault = false\n\tOldDefault = new Object()\n\tNewDefault = new Object()\n\tFormValuesCopy = new Object()\n\tOldDefaultCopy = new Object()\n\tNewDefaultCopy = new Object()\n\n\tif (action == \"AddDefault\")\n\t{\n\t\tADDNEWDEFAULT = true\n\t\tif (thisCtry.defaultAcctPtr == -1)\n\t\t\tthisCtry.defaultAcctPtr = Accts[index].ach_dist_nbr\n\t\ti = index\n\t}\n\telse\n\t{\n\t\t// Find the old default account.\n\t\tfor (var i=0;i<Accts.length;i++)\n\t\t{\n\t\t\tif (Accts[i].default_flag == \"Y\")\n\t\t\t{\n\t\t\t\tif(!NonSpace(Accts[i].end_date)||(formjsDate(Accts[i].end_date) > ymdtoday))\n\t\t\t\t\t{\n\t\t\t\t\t\tFoundDefault = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (thisCtry.openCount == 2)\n\t\t{\n\t\t\t// Find the new default account.\n\t\t\tfor (var j=0;j<Accts.length;j++)\n\t\t\t{\n\t\t\t\tif (Accts[j].default_flag == \"N\")\n\t\t\t\t{\n\t\t\t\t\tif(!NonSpace(Accts[j].end_date)||(formjsDate(Accts[j].end_date) > ymdtoday))\n\t\t\t\t\t{\n\t\t\t\t\t\tindex = j\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tFormValuesCopy = null\n\tif (FoundDefault)\n\t\tSaveAccountInfo(OldDefaultCopy,i)\n\telse OldDefaultCopy = null\n\tSaveAccountInfo(NewDefaultCopy,index)\n\n\t// If the account to be changed has a net percentage, subtract it from the total\n\t// distribution percentage, since the new amount will be added in after the\n\t// database change is effective.\n\tif (NonSpace(Accts[index].net_percent))\n\t{\n\t\tthisCtry.addBackPercent = Accts[index].net_percent;\n\t}\n\telse\n\t{\n\t\tthisCtry.addBackPercent = 0;\n\t}\n\n\t// Make sure the new default account has distribution percentage 100.\n\t//NewDefault = Accts[index]\n\tSaveAccountInfo(NewDefault,index)\n\tNewDefault.default_flag = \"Y\"\n\tNewDefault.amt_type = \"P\"\n\tNewDefault.deposit_amt = 100\n\tif (!Accts[index].isNew)\n\t\tNewDefault.isNew = false\n\telse NewDefault.isNew = true\n\tNewDefault.isTouched = true\n\n\tif (action != \"AddDefault\" && FoundDefault)\n\t{\n\t\tNewDefault.print_rcpt = Accts[i].print_rcpt\n\t\tSaveAccountInfo(OldDefault,i)\n\t\tOldDefault.default_flag = \"N\"\n\t\tOldDefault.print_rcpt = \" \"\n\t\tif (!Accts[i].isNew)\n\t\t\tOldDefault.isNew = false\n\t\telse OldDefault.isNew = true\n\t\tOldDefault.isTouched = true\n\t}\n\n\tif (Rules.partial_ach==\"Y\" && action == \"AddDefault\")\n\t\tautoDepositFlag = \"Y\";\n\telse\n\t\tautoDepositFlag = \"\";\n\n\tif (action == \"AddDefault\")\n\t{\n\t\tif (PrepAccount(NewDefault))\n\t\t{\n\t\t\tUPDATING = true\n\t\t\tADDEDACCOUNT = true\n\t\t\tUpdateQueue = new Array()\n\t\t\tUpdateQueue[UpdateQueue.length] = NewDefault\n\n\t\t\tif (Rules.notify == \"Y\" || Rules.notifyee == \"Y\")\n\t\t\t{\n\t\t\t\tMailEvent = \"Add\"\n\t\t\t\tMailQueue = new Array()\n\t\t\t\tMailQueue[MailQueue.length] = NewDefault\n\t\t\t}\n\t\t\t\n\t\t\tUpdate(UpdateQueue,0)\n\t\t}\n\t}\n\t// If we have more than one account, go off the user-selected one.\n\telse\n\t{\n\t\t// Authorize the user.\n\t\tif (Employee.work_country != \"UK\" && !AUTHORIZED)\n\t\t\tOpenAuthWindow(i,action,\"CHG\")\n\t\telse\n\t\t{\n\t\t\t// Proceed to open a window to allow changes to this account.\n\t\t\tPaintChangeWindow(i,action)\n\t\t}\n\t}\n}", "on_change(ev){\r\n\t\tthis.val = this.get_value();\r\n\t\t// hack to get around change events not bubbling through the shadow dom\r\n\t\tthis.dispatchEvent(new CustomEvent('pion_change', { \r\n\t\t\tbubbles: true,\r\n\t\t\tcomposed: true\r\n\t\t}));\r\n\t\t\r\n\t\tif(!this.hasAttribute(\"noupdate\")){ //Send value to server\t\t\r\n\t\t\tsend_update(this, this.getAttribute(\"item_name\"), new Value(this.val));\t\t\t\r\n\t\t}\r\n\t\t\r\n\t}", "function fireAddrSuitelet_OnFieldChange(type, name)\n{\t\n\t//var formID = 0; //1.0.7\n\tvar scriptID = 0;\n\tvar context = nlapiGetContext();\n\tvar chkAddress = '';\n\n\t//1.0.3 changed trigger to Change Addresses checkbox\n\tif (name == 'custevent_sl_changeaddresses') \n\t{\n\t\t//only run if form is DM Service Case Form (FHL)\n\t\tformID = nlapiGetFieldValue('customform');\n\t\t\n\t\t//if (formID == '54') //1.0.7\n\t\t//{\n\t\t\t//1.0.3 only run if Change Addresses flag is true\n\t\t\tchkAddress = nlapiGetFieldValue(name);\n\t\t\n\t\t\tif (chkAddress == 'T')\n\t\t\t{\t\n\t\t\t\t//get customer ID\n\t\t\t\tcustomerID = nlapiGetFieldValue('company');\n\t\t\t\t\n\t\t\t\t//1.0.3 fire suitelet if customer is selected\n\t\t\t\tif (customerID.length > 0)\n\t\t\t\t{\n\t\t\t\t\t//get script ID parameter from deployment\n\t\t\t\t\tscriptID = context.getSetting('SCRIPT', 'custscript_addrsuitelet_intid');\n\t\t\t\t\t\n\t\t\t\t\t//pass parameters to the popup function\n\t\t\t\t\taddrPopup(scriptID, customerID);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\t\n\t\t\t\t\talert('A customer must be chosen before any addresses can be selected.');\n\t\t\t\t\tnlapiSetFieldValue('custevent_sl_changeaddresses', 'F');\n\t\t\t\t}\n\t\t\t}\n\t\t//}\n\t}\n\telse if (name == 'company') //1.0.5\n\t{\n\t\tnlapiSetFieldValue('custevent_sl_changeaddresses', 'F', false, true);\n\t\tnlapiSetFieldValue('custevent_sl_shippingaddress', '', false, true);\n\t\tnlapiSetFieldValue('custevent_sl_billingaddress', '', false, true);\n\n\t\t//1.0.6\t\n\t\tcustomerID = nlapiGetFieldValue(name);\n\n\t\tif (customerID != 0) //1.0.9\n\t\t{\n\t\t\tgetDefaultAddresses();\n\t\t}\n\t}\n}", "function changeSchoolMons()\n{\n changeElt(this); // perform common functions\n let form = this.form;\n let schoolMons = this.value;\n let occElement = form.elements['Occupation' + this.name.substring(10)];\n if (occElement)\n { // occupation column present\n if (schoolMons.length > 0)\n occElement.value = 'Student';\n else\n occElement.value = '';\n } // occupation column present\n\n // validate number of months\n if (this.checkfunc)\n this.checkfunc();\n}", "function _highlightAssignedEmployee(employeeID) {\r\n $(\".curr-assigned-employee\").removeClass(\"curr-assigned-employee\");\r\n $(\"#\" + employeeID).addClass(\"curr-assigned-employee\");\r\n }", "switchPayee($event, transaction) {\n\t\tthis.switchTo($event, \"payees.payee\", transaction.payee.id, transaction);\n\t}", "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 }", "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}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Date stuff that doesn't belong in datelib core given a timed range, computes an allday range that has the same exact duration, but whose start time is aligned with the start of the day.
function computeAlignedDayRange(timedRange) { var dayCnt = Math.floor(diffDays(timedRange.start, timedRange.end)) || 1; var start = startOfDay(timedRange.start); var end = addDays(start, dayCnt); return { start: start, end: end }; }
[ "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 calculateRecurDates(rule, from /* utc millis */, to /* utc millis */) {\n var dates = []; /* array of utc millis (number) */\n var runDate = new Date(from);\n var i;\n\n var candidate = null;\n var counter = 0;\n // (open) loop to collect recurrences\n while (counter < 100) {\n counter++;\n // stop collecting when we reach the end of the period specified\n if (candidate && candidate.getTime() > to) {\n break;\n }\n\n var candidates = calculateCandidates(rule, runDate.clone());\n for (i=0; i < candidates.length; i++) {\n candidate = candidates[i];\n // only use candidates that lie in the given period\n if (candidate.getTime() >= from && candidate.getTime() <= to) {\n dates.push(candidate.getTime());\n }\n }\n\n runDate = increment(rule, runDate);\n }\n return dates;\n }", "function resampleDates(data) {\r\n const startDate = d3.min(data, d => d.key)\r\n const finishDate = d3.max(data, d => d.key)\r\n const dateRange = d3.timeDay.range(startDate, d3.timeDay.offset(finishDate,1), 1)\r\n return dateRange.map(day => {\r\n return data.find(d => d.key >= day && d.key < d3.timeHour.offset(day,1)) || {'key':day, 'value':0}\r\n })\r\n}", "function create_time_range_inputs(input_args) {\n //\n // defining static inputs\n var date_range_onclick = \"toggle_view_element_button('show_date_range','date_range','Hide Date Range','Show Date Ranage'); toggle_disabled('time-range,st-day,st-month,st-year,en-day,en-month,en-year');\";\n var st_img_onclick = \"create_calander('calander','0','st-day','st-month','st-year'); show_hide('calander');\";\n var end_img_onclick = \"create_calander('calander','0','en-day','en-month','en-year'); show_hide('calander');\";\n //\n // initializing variable inputs\n var time_range_onchange = '';\n var day_onkeyup = '';\n var month_onchange = '';\n var year_onchange = '';\n //\n // creating date objects for time range inputs\n var today = new Date();\n var first = new Date(today.getFullYear(),today.getMonth(),1);\n var curr_wk = [new Date(today.getFullYear(),today.getMonth(),(today.getDate()-today.getDay()))];\n curr_wk[1] = new Date(curr_wk[0].getFullYear(),curr_wk[0].getMonth(),(curr_wk[0].getDate()+6))\n var last_2wk = [new Date(today.getFullYear(),today.getMonth(),(today.getDate()-today.getDay()-7)),curr_wk[1]];\n var last_4wk = [new Date(today.getFullYear(),today.getMonth(),(today.getDate()-today.getDay()-21)),curr_wk[1]];\n var curr_mth = [new Date(first.getFullYear(),first.getMonth(),(first.getDate()-first.getDay()))];\n curr_mth[1] = new Date(first.getFullYear(),first.getMonth()+1,1);\n curr_mth[1] = new Date(curr_mth[1].getFullYear(),curr_mth[1].getMonth(),(curr_mth[1].getDate()+(6-curr_mth[1].getDay())));\n var curr_pp = new Date(CONSTANTS.FIRST_BUSINESS_DAY[0],+CONSTANTS.FIRST_BUSINESS_DAY[1]-1,CONSTANTS.FIRST_BUSINESS_DAY[2]);\n var test_date = curr_pp;\n curr_pp = [curr_pp]\n for (var w = 0; w < 60; w+=2) {\n test_date = new Date(test_date.getFullYear(),test_date.getMonth(),(test_date.getDate()+14));\n curr_pp[1] = new Date(test_date.getFullYear(),test_date.getMonth(),(test_date.getDate()-1));\n if (test_date > today) {break;}\n curr_pp = [test_date];\n }\n var prev_pp = [new Date(curr_pp[0].getFullYear(),curr_pp[0].getMonth(),(curr_pp[0].getDate()-14))];\n prev_pp[1] = new Date(curr_pp[0].getFullYear(),curr_pp[0].getMonth(),(curr_pp[0].getDate()-1));\n curr_wk = curr_wk[0].yyyymmdd()+ '|' +curr_wk[1].yyyymmdd();\n last_2wk = last_2wk[0].yyyymmdd()+'|' +last_2wk[1].yyyymmdd();\n last_4wk = last_4wk[0].yyyymmdd()+'|' +last_4wk[1].yyyymmdd();\n curr_mth = curr_mth[0].yyyymmdd()+'|' +curr_mth[1].yyyymmdd();\n curr_pp = curr_pp[0].yyyymmdd()+ '|' +curr_pp[1].yyyymmdd();\n prev_pp = prev_pp[0].yyyymmdd()+ '|' +prev_pp[1].yyyymmdd();\n //\n // processing input args\n if (!!(input_args.time_range_onchange)) {time_range_onchange = input_args.time_range_onchange;}\n if (!!(input_args.day_onkeyup)) {day_onkeyup = input_args.day_onkeyup;}\n if (!!(input_args.month_onchange)) {month_onchange = input_args.month_onchange;}\n if (!!(input_args.year_onchange)) {year_onchange = input_args.year_onchange;}\n if (!!(input_args.add_date_range_onclick)) {date_range_onclick += input_args.add_date_range_onclick;}\n if (!!(input_args.add_st_img_onclick)) {st_img_onclick += input_args.st_img_onclick;}\n if (!!(input_args.add_end_img_onclick)) {end_img_onclick += input_args.add_end_img_onclick;}\n //\n // creating output fields\n var output = ''+\n '<label class=\"label\">Time Range:</label>'+\n '<select id=\"time-range\" class=\"dropbox-input\" name=\"time-range\" onchange=\"'+time_range_onchange+'\">'+\n '<option value=\"'+curr_wk+'\">Current Week</option>'+\n '<option value=\"'+curr_pp+'\">Current Pay Period</option>'+\n '<option value=\"'+prev_pp+'\">Previous Pay Period</option>'+\n '<option value=\"'+last_2wk+'\">Last 2 Weeks</option>'+\n '<option value=\"'+last_4wk+'\">Last 4 Weeks</option>'+\n '<option value=\"'+curr_mth+'\">Current Month</option>'+\n '</select>'+\n '&nbsp;&nbsp;'+\n '<button id=\"show_date_range\" type=\"button\" name=\"show_date_range\" onclick=\"'+date_range_onclick+'\">Show Date Range</button>'+\n '<div id=\"date_range\" class=\"hidden-elm\" name=\"date_range\">'+\n '<span id=\"calander\" class=\"cal-span hidden-elm\"></span>'+\n '<label class=\"label-4em\">From:</label>'+\n '<input id=\"st-day\" class=\"text-input-xsmall\" type=\"text\" name=\"st-day\" maxlength=2 value=\"01\" onkeyup=\"'+day_onkeyup+'\" disabled>'+\n '&nbsp;'+\n '<select id=\"st-month\" class=\"dropbox-input\" name=\"st-month\" onchange=\"'+month_onchange+'\" disabled>'+\n '<option id=\"1\" value=\"01\">January</option>'+\n '<option id=\"2\" value=\"02\">February</option>'+\n '<option id=\"3\" value=\"03\">March</option>'+\n '<option id=\"4\" value=\"04\">April</option>'+\n '<option id=\"5\" value=\"05\">May</option>'+\n '<option id=\"6\" value=\"06\">June</option>'+\n '<option id=\"7\" value=\"07\">July</option>'+\n '<option id=\"8\" value=\"08\">August</option>'+\n '<option id=\"9\" value=\"09\">September</option>'+\n '<option id=\"10\" value=\"10\">October</option>'+\n '<option id=\"11\" value=\"11\">November</option>'+\n '<option id=\"12\" value=\"12\">December</option>'+\n '</select>'+\n '&nbsp;'+\n '<select id=\"st-year\" class=\"dropbox-input\" name=\"st-year\" onchange=\"'+year_onchange+'\" disabled>'+\n '</select>'+\n '&nbsp;&nbsp;&nbsp;&nbsp;'+\n '<a onclick=\"'+st_img_onclick+'\"><image id=\"cal_st_image\" class=\"cal-image\" src=\"http://www.afwendling.com/operations/images/calander.png\"></a>'+\n '<br>'+\n '<label class=\"label-4em\">To:</label>'+\n '<input id=\"en-day\" class=\"text-input-xsmall\" type=\"text\" name=\"en-day\" maxlength=2 value=\"01\" onkeyup=\"'+day_onkeyup+'\" disabled>'+\n '&nbsp;'+\n '<select id=\"en-month\" class=\"dropbox-input\" name=\"en-month\" onchange=\"'+month_onchange+'\" disabled>'+\n '<option id =\"1\" value=\"01\">January</option>'+\n '<option id =\"2\" value=\"02\">February</option>'+\n '<option id =\"3\" value=\"03\">March</option>'+\n '<option id =\"4\" value=\"04\">April</option>'+\n '<option id =\"5\" value=\"05\">May</option>'+\n '<option id =\"6\" value=\"06\">June</option>'+\n '<option id =\"7\" value=\"07\">July</option>'+\n '<option id =\"8\" value=\"08\">August</option>'+\n '<option id =\"9\" value=\"09\">September</option>'+\n '<option id =\"10\" value=\"10\">October</option>'+\n '<option id =\"11\" value=\"11\">November</option>'+\n '<option id =\"12\" value=\"12\">December</option>'+\n '</select>'+\n '&nbsp;'+\n '<select id=\"en-year\" class=\"dropbox-input\" name=\"en-year\" onchange=\"'+year_onchange+'\" disabled>'+\n '</select>'+\n '&nbsp;&nbsp;&nbsp;&nbsp;'+\n '<a onclick=\"'+end_img_onclick+'\"><image id=\"cal_en_image\" class=\"cal-image\" src=\"http://www.afwendling.com/operations/images/calander.png\"></a>'+\n '';\n //\n document.getElementById(input_args.output_id).innerHTML = output;\n //\n populate_year_dropboxes('st-year');\n populate_year_dropboxes('en-year');\n}", "function expandDateToRange(date, unit) {\n return moment.range(\n moment(date).startOf(unit),\n moment(date).startOf(unit).add(1, unit));\n}", "function ensureVisibleEventRange(range) {\n\t\t\tvar allDay;\n\t\n\t\t\tif (!range.end) {\n\t\n\t\t\t\tallDay = range.allDay; // range might be more event-ish than we think\n\t\t\t\tif (allDay == null) {\n\t\t\t\t\tallDay = !range.start.hasTime();\n\t\t\t\t}\n\t\n\t\t\t\trange = $.extend({}, range); // make a copy, copying over other misc properties\n\t\t\t\trange.end = t.getDefaultEventEnd(allDay, range.start);\n\t\t\t}\n\t\t\treturn range;\n\t\t}", "getFoodRange(date1,date2){\n let temp = [];\n let total = 0;\n let start= new Date(date1);\n let end=new Date(date2);\n for(var i = 0; i< this.foodLog.length; i++){\n if(this.foodLog[i].date >= start && this.foodLog[i].date <= end){\n temp.push(this.foodLog[i]);\n total += this.foodLog[i].calories;\n }\n }\n return {foods: temp, calories: total};\n }", "function find_pay_period(date) {\n var start_ts,end_ts\n var ts_arr = [false,false]\n //\n if (date instanceof Array) {\n if (date.length < 3) { console.log('Error in date array: ',date); return ts_arr;}\n date = new Date(Number(date[0]),Number(date[1])-1,Number(date[2]));\n }\n else if ((typeof date == 'string') || (date instanceof String)) {\n var date_arr = date.match(/(\\d+).(\\d+).(\\d+)/)\n if (date_arr.length < 4) { console.log('Error in date string: ',date); return ts_arr;}\n date = new Date(Number(date_arr[1]),Number(date_arr[2])-1,Number(date_arr[3]));\n }\n //\n var st_pp = new Date(CONSTANTS.FIRST_BUSINESS_DAY[0],+CONSTANTS.FIRST_BUSINESS_DAY[1]-1,CONSTANTS.FIRST_BUSINESS_DAY[2]);\n var test_date = st_pp;\n ts_arr = [st_pp]\n if (date < st_pp) {\n while (true) {\n ts_arr[1] = new Date(test_date.getFullYear(),test_date.getMonth(),(test_date.getDate()));\n test_date = new Date(test_date.getFullYear(),test_date.getMonth(),(test_date.getDate()-14));\n ts_arr[0] = test_date;\n if ((date >= ts_arr[0]) && (date <= ts_arr[1])) {break;}\n if (date >= ts_arr[0]) { break;}\n }\n }\n else {\n while (true) {\n test_date = new Date(test_date.getFullYear(),test_date.getMonth(),(test_date.getDate()+14));\n ts_arr[1] = new Date(test_date.getFullYear(),test_date.getMonth(),(test_date.getDate()-1));\n if (test_date >= date) { break;}\n ts_arr = [test_date];\n }\n }\n //\n ts_arr[0] = ts_arr[0].yyyymmdd();\n ts_arr[1] = ts_arr[1].yyyymmdd();\n //\n return ts_arr;\n}", "function flatoutDateRange(startDate, endDate) {\n var flatoutResult = [],\n flatoutDate = startDate;\n while (flatoutDate <= endDate) {\n key = Math.floor(flatoutDate.getTime() / 1000) + '';\n flatoutResult.push(key);\n flatoutDate.setDate(flatoutDate.getDate() + 1);\n }\n return flatoutResult;\n }", "getReportRange(date1,date2){\n let d1= new Date(date1);\n let d2 = new Date(date2);\n let days = (d2.getTime() - d1.getTime()) / (1000*60*60*24)\n let goal = this.gCals() * days;\n let eaten = this.getFoodRange(date1,date2).calories;\n let burned = this.getActivitiesRange(date1,date2).caloriesBurned;\n let calRemaining = goal - eaten + burned;\n return {eaten: eaten, burned: burned, goal: goal, \n remaining: calRemaining};\n }", "splitDateRange(begin, end, step) {\n const beginDate = moment(begin);\n const endDate = moment(end);\n if (!beginDate.isValid() || !endDate.isValid() || beginDate.isAfter(endDate)) {\n throw new Error('invalid date range');\n }\n\n const format = 'YYYY-MM-DD';\n const ranges = [];\n while (!beginDate.isAfter(endDate)) {\n const beginDateString = beginDate.format(format);\n beginDate.add(step - 1, 'days');\n const minDate = moment.min(beginDate, endDate);\n const endDateString = minDate.format(format);\n ranges.push([beginDateString, endDateString]);\n beginDate.add(1, 'days');\n }\n return ranges;\n }", "getActivitiesRange(date1, date2){\n let temp=[];\n let start = new Date(date1);\n let end = new Date(date2);\n let calBurned = 0;\n for(var i=0; i< this.activitiesLog.length; i++){\n if(this.activitiesLog[i].date >= start && this.activitiesLog[i].date <=end){\n temp.push(this.activitiesLog[i]);\n calBurned += this.activitiesLog[i].calories;\n }\n }\n return {activities: temp, caloriesBurned: calBurned};\n }", "function getCombinedDateRange() {\n var datasets = ocean.variables[ocean.variable].plots[ocean.plottype][ocean.period];\n var minDate = Number.MAX_VALUE;\n var maxDate = Number.MIN_VALUE;\n\n $.each(datasets, function(i, datasetid) {\n var range = getDateRange(datasetid, ocean.variable, ocean.period);\n\n if (!range)\n return; /* continue */\n\n /* 726: ww3 hourly data is available until July 2014 whereas monthly data is available until 2009*/\n if (datasetid == \"ww3\" && ocean.period == \"hourly\" && ocean.plottype == \"map\"){\n range.max = new Date(2016, 0, 31);\n }\n\n minDate = Math.min(minDate, range.min);\n maxDate = Math.max(maxDate, range.max);\n });\n\n return { min: new Date(minDate), max: new Date(maxDate) };\n}", "function buildRecurrenceRule() {\n\tvar recurrenceRule = CalendarApp.newRecurrence();\n\tvar dates = getDates(2020);\n\tfor (var i = 0; i < dates.length; i++) {\n\t\trecurrenceRule.addDate(dates[i]); // for each date, add a new date to the recurrence rule\n\t}\n\treturn recurrenceRule;\n}", "getSelectedRange() {\n let range;\n if (!Object(_syncfusion_ej2_base__WEBPACK_IMPORTED_MODULE_0__[\"isNullOrUndefined\"])(this.startValue) && !Object(_syncfusion_ej2_base__WEBPACK_IMPORTED_MODULE_0__[\"isNullOrUndefined\"])(this.endValue)) {\n range = (Math.round(Math.abs((this.removeTimeValueFromDate(this.startValue).getTime() -\n this.removeTimeValueFromDate(this.endValue).getTime()) / (1000 * 60 * 60 * 24))) + 1);\n this.disabledDateRender();\n if (!Object(_syncfusion_ej2_base__WEBPACK_IMPORTED_MODULE_0__[\"isNullOrUndefined\"])(this.disabledDayCnt)) {\n range = range - this.disabledDayCnt;\n this.disabledDayCnt = null;\n }\n }\n else {\n range = 0;\n }\n return { startDate: this.startValue, endDate: this.endValue, daySpan: range };\n }", "function getDates(req) {\n let start = 0;\n let end = Date.now();\n if (req.query.start) start = parseInt(req.query.start);\n if (req.query.end) end = parseInt(req.query.end);\n if (isNaN(start) || isNaN(end)) throw \"Bad date format, unix timestamp expected\";\n //range of completion dates\n return { start: start, end: end };\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 range(start, end) {\n\tvar startDate = new Date(start);\n\tvar endDate = new Date(end);\n\t// retrieve a subarray of the hour buckets within the hour range\n\tvar slicedBuckets = hourBuckets.slice(startDate.getHours(), endDate.getHours() + 1);\n\tvar result = new Array(0);\n\t// make sure they are within the dates\n\tfor (i = 0; i < slicedBuckets.length; i++) {\n\t\tfor (j = 0; j < slicedBuckets[i].length; j+= 3) {\n\t\t\tvar currDate = new Date(slicedBuckets[i][j]);\n\t\t\tif ((currDate.getTime() >= startDate.getTime()) && (currDate.getTime() <= endDate.getTime())) {\n\t\t\t\tresult.push(slicedBuckets[i][j], slicedBuckets[i][j+1], slicedBuckets[i][j+2]);\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}", "function visibleFullCalDates() {\r\n startDate = $fullCal.fullCalendar('getView').start.format('YYYY-MM-DD');\r\n endDate = $fullCal.fullCalendar('getView').end.format('YYYY-MM-DD');\r\n visibleDatesList = _enumerateDaysBetweenDates(startDate, endDate);\r\n\r\n var visibleDatesObj = {};\r\n\r\n for(var i=0; i<visibleDatesList.length; i++) {\r\n visibleDatesObj[visibleDatesList[i]] = [];\r\n }\r\n\r\n return visibleDatesObj;\r\n }", "function setCalendarDayFills(weeksIntoFuture){\n\t\n\tvar daysInAdvance = weeksIntoFuture * 7;\n\t\n\tvar theDay = today.getDay();\n\t//theDay = 0; //Just for testing\n\t\n\t//Shift the days over so Monday is 0 instead of Sunday\n\ttheDay -= 1;\n\tif(theDay == -1){theDay = 6;}\n\t\n\t//Variables for fill\n\tvar fillMO = fillTU = fillWE = fillTH = fillFR = fillSA = fillSU = 0;\n\t\n\t//Variables for day numbers\n\tvar numMO = numTU = numWE = numTH = numFR = numSA = numSU = 0;\n\t\n\t//Set day fills and day numbers\n\tif(weeksIntoFuture == 0){\n\t\tfor(i=theDay;i<7;i++){\n\t\t\tif(dateSpan[i]){\n\t\t\t\tif(i == 0){\n\t\t\t\t\tfillMO = (dateSpan[i-theDay].capacity > 0) ? (dateSpan[i-theDay].fill / dateSpan[i-theDay].capacity * 100) : 0;\n\t\t\t\t\tnumMO = new Date(dateSpan[i-theDay].date).getDate();\n\t\t\t\t}\n\t\t\t\tif(i == 1){\n\t\t\t\t\tfillTU = (dateSpan[i-theDay].capacity > 0) ? (dateSpan[i-theDay].fill / dateSpan[i-theDay].capacity * 100) : 0;\n\t\t\t\t\tnumMO = new Date(new Date(dateSpan[i-theDay].date).getTime() - 86400000).getDate();\n\t\t\t\t\tnumTU = new Date(dateSpan[i-theDay].date).getDate();\n\t\t\t\t}\n\t\t\t\tif(i == 2){\n\t\t\t\t\tfillWE = (dateSpan[i-theDay].capacity > 0) ? (dateSpan[i-theDay].fill / dateSpan[i-theDay].capacity * 100) : 0;\n\t\t\t\t\tnumMO = new Date(new Date(dateSpan[i-theDay].date).getTime() - 172800000).getDate();\n\t\t\t\t\tnumTU = new Date(new Date(dateSpan[i-theDay].date).getTime() - 86400000).getDate();\n\t\t\t\t\tnumWE = new Date(dateSpan[i-theDay].date).getDate();\n\t\t\t\t}\n\t\t\t\tif(i == 3){\n\t\t\t\t\tfillTH = (dateSpan[i-theDay].capacity > 0) ? (dateSpan[i-theDay].fill / dateSpan[i-theDay].capacity * 100) : 0;\n\t\t\t\t\tnumMO = new Date(new Date(dateSpan[i-theDay].date).getTime() - 259200000).getDate();\n\t\t\t\t\tnumTU = new Date(new Date(dateSpan[i-theDay].date).getTime() - 172800000).getDate();\n\t\t\t\t\tnumWE = new Date(new Date(dateSpan[i-theDay].date).getTime() - 86400000).getDate();\n\t\t\t\t\tnumTH = new Date(dateSpan[i-theDay].date).getDate();\n\t\t\t\t}\n\t\t\t\tif(i == 4){\n\t\t\t\t\tfillFR = (dateSpan[i-theDay].capacity > 0) ? (dateSpan[i-theDay].fill / dateSpan[i-theDay].capacity * 100) : 0;\n\t\t\t\t\tnumMO = new Date(new Date(dateSpan[i-theDay].date).getTime() - 345600000).getDate();\n\t\t\t\t\tnumTU = new Date(new Date(dateSpan[i-theDay].date).getTime() - 259200000).getDate();\n\t\t\t\t\tnumWE = new Date(new Date(dateSpan[i-theDay].date).getTime() - 172800000).getDate();\n\t\t\t\t\tnumTH = new Date(new Date(dateSpan[i-theDay].date).getTime() - 86400000).getDate();\n\t\t\t\t\tnumFR = new Date(dateSpan[i-theDay].date).getDate();\n\t\t\t\t}\n\t\t\t\tif(i == 5){\n\t\t\t\t\tfillSA = (dateSpan[i-theDay].capacity > 0) ? (dateSpan[i-theDay].fill / dateSpan[i-theDay].capacity * 100) : 0;\n\t\t\t\t\tnumMO = new Date(new Date(dateSpan[i-theDay].date).getTime() - 432000000).getDate();\n\t\t\t\t\tnumTU = new Date(new Date(dateSpan[i-theDay].date).getTime() - 345600000).getDate();\n\t\t\t\t\tnumWE = new Date(new Date(dateSpan[i-theDay].date).getTime() - 259200000).getDate();\n\t\t\t\t\tnumTH = new Date(new Date(dateSpan[i-theDay].date).getTime() - 172800000).getDate();\n\t\t\t\t\tnumFR = new Date(new Date(dateSpan[i-theDay].date).getTime() - 86400000).getDate();\n\t\t\t\t\tnumSA = new Date(dateSpan[i-theDay].date).getDate();\n\t\t\t\t}\n\t\t\t\tif(i == 6){\n\t\t\t\t\tfillSU = (dateSpan[i-theDay].capacity > 0) ? (dateSpan[i-theDay].fill / dateSpan[i-theDay].capacity * 100) : 0;\n\t\t\t\t\tnumMO = new Date(new Date(dateSpan[i-theDay].date).getTime() - 518400000).getDate();\n\t\t\t\t\tnumTU = new Date(new Date(dateSpan[i-theDay].date).getTime() - 432000000).getDate();\n\t\t\t\t\tnumWE = new Date(new Date(dateSpan[i-theDay].date).getTime() - 345600000).getDate();\n\t\t\t\t\tnumTH = new Date(new Date(dateSpan[i-theDay].date).getTime() - 259200000).getDate();\n\t\t\t\t\tnumFR = new Date(new Date(dateSpan[i-theDay].date).getTime() - 172800000).getDate();\n\t\t\t\t\tnumSA = new Date(new Date(dateSpan[i-theDay].date).getTime() - 86400000).getDate();\n\t\t\t\t\tnumSU = new Date(dateSpan[i-theDay].date).getDate();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t//Gray out the past days\n\t\tswitch(theDay){\n\t\t\tcase 1: grayOutDays('mo'); break;\n\t\t\tcase 2: grayOutDays('mo','tu'); break;\n\t\t\tcase 3: grayOutDays('mo','tu','we'); break;\n\t\t\tcase 4: grayOutDays('mo','tu','we','th'); break;\n\t\t\tcase 5: grayOutDays('mo','tu','we','th','fr'); break;\n\t\t\tcase 6: grayOutDays('mo','tu','we','th','fr','sa'); break;\n\t\t\n\t\t}\n\t\t\n\t}else{\n\t\t//Recolor grayed out days\n\t\trecolorGrayDays();\n\t\t\t\n\t\t//Set day fills\n\t\tif((dateSpan[daysInAdvance-theDay]) && (dateSpan[daysInAdvance-theDay].capacity > 0)){\n\t\t\tfillMO = (dateSpan[daysInAdvance-theDay].fill / dateSpan[daysInAdvance-theDay].capacity * 100);\n\t\t}else{fillMO = 0;}\n\t\tif((dateSpan[(daysInAdvance-theDay)+1]) && (dateSpan[daysInAdvance-theDay].capacity > 0)){\n\t\t\tfillTU = (dateSpan[(daysInAdvance-theDay)+1].fill / dateSpan[(daysInAdvance-theDay)+1].capacity * 100);\n\t\t}else{fillTU = 0;}\n\t\tif((dateSpan[(daysInAdvance-theDay)+2]) && (dateSpan[daysInAdvance-theDay].capacity > 0)){\n\t\t\tfillWE = (dateSpan[(daysInAdvance-theDay)+2].fill / dateSpan[(daysInAdvance-theDay)+1].capacity * 100);\n\t\t}else{fillWE = 0;}\n\t\tif((dateSpan[(daysInAdvance-theDay)+3]) && (dateSpan[daysInAdvance-theDay].capacity > 0)){\n\t\t\tfillTH = (dateSpan[(daysInAdvance-theDay)+3].fill / dateSpan[(daysInAdvance-theDay)+1].capacity * 100);\n\t\t}else{fillTH = 0;}\n\t\tif((dateSpan[(daysInAdvance-theDay)+4]) && (dateSpan[daysInAdvance-theDay].capacity > 0)){\n\t\t\tfillFR = (dateSpan[(daysInAdvance-theDay)+4].fill / dateSpan[(daysInAdvance-theDay)+1].capacity * 100);\n\t\t}else{fillFR = 0;}\n\t\tif((dateSpan[(daysInAdvance-theDay)+5]) && (dateSpan[daysInAdvance-theDay].capacity > 0)){\n\t\t\tfillSA = (dateSpan[(daysInAdvance-theDay)+5].fill / dateSpan[(daysInAdvance-theDay)+1].capacity * 100);\n\t\t}else{fillSA = 0;}\n\t\tif((dateSpan[(daysInAdvance-theDay)+6]) && (dateSpan[daysInAdvance-theDay].capacity > 0)){\n\t\t\tfillSU = (dateSpan[(daysInAdvance-theDay)+6].fill / dateSpan[(daysInAdvance-theDay)+1].capacity * 100);\n\t\t}else{fillSU = 0;}\n\t\t\n\t\t//Set day numbers\n\t\tnumMO = new Date(dateSpan[daysInAdvance-theDay].date).getDate();\n\t\tnumTU = new Date(new Date(dateSpan[daysInAdvance-theDay].date).getTime() + 86400000).getDate();\n\t\tnumWE = new Date(new Date(dateSpan[daysInAdvance-theDay].date).getTime() + 172800000).getDate();\n\t\tnumTH = new Date(new Date(dateSpan[daysInAdvance-theDay].date).getTime() + 259200000).getDate();\n\t\tnumFR = new Date(new Date(dateSpan[daysInAdvance-theDay].date).getTime() + 345600000).getDate();\n\t\tnumSA = new Date(new Date(dateSpan[daysInAdvance-theDay].date).getTime() + 432000000).getDate();\n\t\tnumSU = new Date(new Date(dateSpan[daysInAdvance-theDay].date).getTime() + 518400000).getDate();\n\t\t\n\t}\n\t\n\t//Use the results to animate the day fill divs\n\t$(\"#calendarDayFill-mo\").animate({height: fillMO + \"%\"}, 1000, \"easeOutElastic\");\n\t$(\"#calendarDayFill-tu\").animate({height: fillTU + \"%\"}, 1000, \"easeOutElastic\");\n\t$(\"#calendarDayFill-we\").animate({height: fillWE + \"%\"}, 1000, \"easeOutElastic\");\n\t$(\"#calendarDayFill-th\").animate({height: fillTH + \"%\"}, 1000, \"easeOutElastic\");\n\t$(\"#calendarDayFill-fr\").animate({height: fillFR + \"%\"}, 1000, \"easeOutElastic\");\n\t$(\"#calendarDayFill-sa\").animate({height: fillSA + \"%\"}, 1000, \"easeOutElastic\");\n\t$(\"#calendarDayFill-su\").animate({height: fillSU + \"%\"}, 1000, \"easeOutElastic\");\n\t\n\t//...and set the day numbers\n\t$(\"#calendarDayNumber-mo\")[0].innerHTML = numMO;\n\t$(\"#calendarDayNumber-tu\")[0].innerHTML = numTU;\n\t$(\"#calendarDayNumber-we\")[0].innerHTML = numWE;\n\t$(\"#calendarDayNumber-th\")[0].innerHTML = numTH;\n\t$(\"#calendarDayNumber-fr\")[0].innerHTML = numFR;\n\t$(\"#calendarDayNumber-sa\")[0].innerHTML = numSA;\n\t$(\"#calendarDayNumber-su\")[0].innerHTML = numSU;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parseString takes in a specialString and returns the right / wrong version of the string as well as the concept code
function parseString(str, isCorrect) { if ((str.indexOf("+") || str.indexOf("-") || str.indexOf("{") || str.indexOf("}") || str.indexOf("|")) < 0) { return {"value": str, "code": null}; } //weird cases: {+Plantations.-plantations. / Plantations.|508} //have to remove /Plantations. if (str.indexOf('/') > -1) { let toRemove = "/ " + str.match(/\+(.*)\-/)[1]; str = str.replace(toRemove, ''); } //removing whitespace... necessary? // str = str.replace(/^\s+|\s+$/g,''); //if + comes before - if (str.indexOf('+') < str.indexOf('-')){ value = isCorrect ? str.match(/\+(.*)\-/).pop() : str.match(/\-(.*)\|/).pop(); } else { //if - comes before + value = isCorrect ? str.match(/\-(.*)\+/).pop() : str.match(/\+(.*)\|/).pop(); } let code = str.match(/\|(.*)/)[1]; storeConceptCode(str, code); return {"value": value, "code": code}; }
[ "parse(string) {\n this._string = string;\n this._tokenizer.init(string);\n\n // Prime the tokenizer to obtain the first\n // token which is our lookahead. The lookahead is\n // used for predictive parsing.\n this._lookahead = this._tokenizer.getNextToken();\n\n return this.Program();\n }", "function parse_StringExpr(){\n\tdocument.getElementById(\"tree\").value += \"PARSER: parse_StringExpr()\" + '\\n';\n\tCSTREE.addNode('StringExpr', 'branch');\n\t\n\tmatchSpecChars(' \"',parseCounter);\n\t\n\tparseCounter = parseCounter + 1;\n\t\n\tparse_CharList();\n\n\t\n\tmatchSpecChars(' \"',parseCounter);\n\t\n\t\n\t\n\tparseCounter = parseCounter + 1;\n\t\n}", "function parse(str) {\n\tif (str[0] !== '=') {\n\t\treturn;\n\t}\n\ttry {\n\t\tvar list = parser(str.slice(1).trim());\n\t\treturn {\n\t\t\tweights: pluck(list, 0),\n\t\t\tgenes: pluck(list, 1)\n\t\t};\n\t} catch (e) {\n\t\tconsole.log('parsing error', e);\n\t}\n\treturn;\n}", "function validateType(tstr){\n let retVal = Type.NOT_A_TYPE;\n if(tstr != Type.NOT_A_TYPE){\n for(const t in Type){\n // If a valid type (not NOT_A_TYPE) and symbol string matches given string:\n if(Type[t] && String(Type[t]).slice(7, -1) == tstr){\n retVal = Type[t];\n break;\n }\n }\n }\n\n return retVal;\n} // #validateType", "function parsestr (c, s) {\n var encodeUtf8 = function (s) {\n return unescape(encodeURIComponent(s));\n };\n var decodeUtf8 = function (s) {\n return decodeURIComponent(escape(s));\n };\n var decodeEscape = function (s, quote) {\n var d3;\n var d2;\n var d1;\n var d0;\n var c;\n var i;\n var len = s.length;\n var ret = \"\";\n for (i = 0; i < len; ++i) {\n c = s.charAt(i);\n if (c === \"\\\\\") {\n ++i;\n c = s.charAt(i);\n if (c === \"n\") {\n ret += \"\\n\";\n }\n else if (c === \"\\\\\") {\n ret += \"\\\\\";\n }\n else if (c === \"t\") {\n ret += \"\\t\";\n }\n else if (c === \"r\") {\n ret += \"\\r\";\n }\n else if (c === \"b\") {\n ret += \"\\b\";\n }\n else if (c === \"f\") {\n ret += \"\\f\";\n }\n else if (c === \"v\") {\n ret += \"\\v\";\n }\n else if (c === \"0\") {\n ret += \"\\0\";\n }\n else if (c === '\"') {\n ret += '\"';\n }\n else if (c === '\\'') {\n ret += '\\'';\n }\n else if (c === \"\\n\") /* escaped newline, join lines */ {\n }\n else if (c === \"x\") {\n d0 = s.charAt(++i);\n d1 = s.charAt(++i);\n ret += String.fromCharCode(parseInt(d0 + d1, 16));\n }\n else if (c === \"u\" || c === \"U\") {\n d0 = s.charAt(++i);\n d1 = s.charAt(++i);\n d2 = s.charAt(++i);\n d3 = s.charAt(++i);\n ret += String.fromCharCode(parseInt(d0 + d1, 16), parseInt(d2 + d3, 16));\n }\n else {\n // Leave it alone\n ret += \"\\\\\" + c;\n // goog.asserts.fail(\"unhandled escape: '\" + c.charCodeAt(0) + \"'\");\n }\n }\n else {\n ret += c;\n }\n }\n return ret;\n };\n\n //print(\"parsestr\", s);\n\n var quote = s.charAt(0);\n var rawmode = false;\n var unicode = false;\n\n // treats every sequence as unicodes even if they are not treated with uU prefix\n // kinda hacking though working for most purposes\n if((c.c_flags & Parser.CO_FUTURE_UNICODE_LITERALS || Sk.python3 === true)) {\n unicode = true;\n }\n\n if (quote === \"u\" || quote === \"U\") {\n s = s.substr(1);\n quote = s.charAt(0);\n unicode = true;\n }\n else if (quote === \"r\" || quote === \"R\") {\n s = s.substr(1);\n quote = s.charAt(0);\n rawmode = true;\n }\n goog.asserts.assert(quote !== \"b\" && quote !== \"B\", \"todo; haven't done b'' strings yet\");\n\n goog.asserts.assert(quote === \"'\" || quote === '\"' && s.charAt(s.length - 1) === quote);\n s = s.substr(1, s.length - 2);\n if (unicode) {\n s = encodeUtf8(s);\n }\n\n if (s.length >= 4 && s.charAt(0) === quote && s.charAt(1) === quote) {\n goog.asserts.assert(s.charAt(s.length - 1) === quote && s.charAt(s.length - 2) === quote);\n s = s.substr(2, s.length - 4);\n }\n\n if (rawmode || s.indexOf(\"\\\\\") === -1) {\n return strobj(decodeUtf8(s));\n }\n return strobj(decodeEscape(s, quote));\n}", "function splitTacticsData(stringTacticsData) {\n if(DEBUG==true) { console.log(\"sbc-pf1 | Parsing tactics data\") };\n \n let splitTacticsData = stringTacticsData.replace(/^ | $|^\\n*/,\"\");\n \n splitTacticsData = splitTacticsData.replace(/\\n/gm,\" \"); \n // Check for Keywords \"During Combat, Before Combat and Morale\"\n if(splitTacticsData.search(/Before Combat/m) !== -1) {\n let splitTacticsBeforeCombat = splitTacticsData.match(/Before Combat .+?(?=Morale|During|Base Statistics|$)/);\n formattedInput.tactics.before_combat = splitTacticsBeforeCombat;\n }\n \n if(splitTacticsData.search(/During Combat/mi) !== -1) {\n let splitTacticsDuringCombat = splitTacticsData.match(/During Combat .+?(?=Morale|Before|Base Statistics|$)/)[0].replace(/During Combat /,\"\");\n formattedInput.tactics.during_combat = splitTacticsDuringCombat;\n }\n \n if(splitTacticsData.search(/Morale/m) !== -1) {\n let splitTacticsMorale = splitTacticsData.match(/Morale .+?(?=(Base Statistics)|$)/)[0].replace(/Morale /,\"\");\n formattedInput.tactics.morale = splitTacticsMorale;\n }\n \n if(splitTacticsData.search(/Base Statistics/m) !== -1) {\n let splitTacticsBaseStatistics = splitTacticsData.match(/Base Statistics .+?(?=$)/)[0].replace(/Base Statistics /,\"\");\n formattedInput.tactics.base_statistics = splitTacticsBaseStatistics;\n }\n \n if(splitTacticsData.search(/Before Combat|During Combat|Morale/m) == -1) {\n formattedInput.tactics.default = splitTacticsData.replace(/\\n/,\"\");\n }\n \n if(DEBUG==true) { console.log(\"sbc-pf1 | DONE parsing tactics data\") };\n}", "function splitGeneralData(stringGeneralData) {\n if(DEBUG==true) { console.log(\"sbc-pf1 | Parsing general data\") };\n // Separate Name and Challenge Rating\n \n let splitGeneralData = stringGeneralData.replace(/\\n/gm,\"\");\n splitGeneralData = splitGeneralData.replace(/defense$|defenses$/i,\"\");\n \n // Name (every char until \"CR\" is found)\n let splitName = splitGeneralData.match(/.+?(?=CR)/)[0];\n \n // CR\n let splitCR = splitGeneralData.match(/(1\\/\\d|\\d+)/)[0];\n \n // XP\n let splitXP =0;\n if (splitGeneralData.search(/(\\s*XP\\s*)/im) !== -1) {\n splitXP = splitGeneralData.match(/(?:XP\\s*)([\\d,.]+)/)[1].replace(/([\\D]|[,?]|[\\.?])/g,\"\");\n }\n \n //Alignment\n let splitAlignment = \"\";\n if (splitGeneralData.search(/(\\*A|LG|LN|LE|NG|N|NE|CG|CN|CE) /) !== -1) {\n splitAlignment = splitGeneralData.match(/(\\*A|LG|LN|LE|NG|N|NE|CG|CN|CE) /)[0].replace(/\\s+?/,\"\");\n }\n \n // Size, Space and Reach\n let splitSize = splitGeneralData.match(new RegExp(enumSizes.join(\"|\"), \"i\"))[0].replace(/\\s+?/,\"\");\n let splitSpace = \"\";\n let splitReach = \"\";\n\n switch(splitSize) {\n case \"Fine\": splitSpace = \"0.5 ft.\"; splitReach = \"0 ft.\"; break;\n case \"Diminutive\": splitSpace = \"1 ft.\"; splitReach = \"0 ft.\"; break;\n case \"Tiny\": splitSpace = \"2.5 ft.\"; splitReach = \"0 ft.\"; break;\n case \"Small\": splitSpace = \"5 ft.\"; splitReach = \"5 ft.\"; break;\n case \"Medium\": splitSpace = \"5 ft.\"; splitReach = \"5 ft.\"; break;\n case \"Large\": splitSpace = \"10 ft.\"; splitReach = \"5-10 ft.\"; break;\n case \"Huge\": splitSpace = \"15 ft.\"; splitReach = \"10-15 ft.\"; break;\n case \"Gargantuan\": splitSpace = \"20 ft.\"; splitReach = \"15-20 ft.\"; break;\n case \"Colossal\": splitSpace = \"30 ft.\"; splitReach = \"20-30 ft.\"; break;\n default: break;\n }\n \n // Split Classes, if available\n // Special Case: (Medium)(?: \\d+?) \n let regExClassesAndLevel = new RegExp(\"(\\\\b\".concat(enumClasses.join(\"\\\\b|\\\\b\")).concat(\")(?:\\\\s*\\\\d+)\"), \"gi\");\n let regExClasses = new RegExp(\"(\\\\b\".concat(enumClasses.join(\"\\\\b|\\\\b\")).concat(\")\"), \"gi\");\n let splitClasses = splitGeneralData.match(regExClassesAndLevel);\n \n // If there are classes, get them, their level and the race / gender as well\n if ( (splitClasses !== null) && (splitClasses !== \"\") ) {\n // Set Flag\n dataInputHasClasses = true;\n // Get Class(es)\n splitClasses.forEach( function(item, index) {\n \n if ( item !== undefined ) {\n \n // Check for className (first for classes with two words e.g. vampire hunter)\n let classNameAndLevel = \"\";\n let className = \"\";\n let classNameSuffix = \"\";\n let classLevel = \"\";\n\n // Get Classlevel and words in between class an level\n //let regExClassAndLevel = new RegExp(\"(\" + item + \")\" + \"(?:[\\\\s]*?)([\\\\w\\\\s()]*?)(?:[\\\\s]*?)(\\\\d+)\", \"ig\");\n \n //classNameAndLevel = splitGeneralData.match(regExClassAndLevel);\n classNameAndLevel = item;\n \n if (item.search(/Medium/i) !== -1) {\n className = \"Medium\";\n } else {\n className = classNameAndLevel.split(/[\\s](?:\\d)/)[0].match(regExClasses);\n }\n classNameSuffix = classNameAndLevel.split(/[\\s](?:\\d)/)[0].replace(regExClasses, \"\").replace(/^ | $/, \"\");\n classLevel = classNameAndLevel.match(/(\\d+?)/)[0];\n\n // If it's an NPC Class, add Npc to the Name\n // Because thats the notation used in the gameSystem\n if (className[0].search(/(adept)|(commoner)|(expert)|(warrior)|(aristocrat)/i) !== -1 ) {\n className = className[0].concat(\"Npc\");\n }\n \n if (className[0].search(/necromancer|diviner|evoker|illusionist|transmuter|abjurer|conjurer|enchanter/i) === -1) {\n formattedInput.classes[className] = {\n \"name\" : className[0],\n \"nameSuffix\" : classNameSuffix,\n \"level\" : +classLevel\n }\n } else {\n formattedInput.classes.wizard = {\n \"name\" : \"wizard\",\n \"nameSuffix\" : \"(\" + className[0] + \")\",\n \"level\" : +classLevel\n }\n }\n \n \n }\n\n });\n \n // Get Gender and Race if available\n let regExGenderAndRace = new RegExp(\"(?:[0-9]*?)([^0-9]*)(?:\" + enumClasses.join(\"|\") + \")(?:\\\\s+\\\\d+)\", \"ig\");\n\n // Search if there is info before the class to evaluate\n if (splitGeneralData.split(regExGenderAndRace)[1]) {\n \n let stringGenderAndRace = splitGeneralData.split(regExGenderAndRace)[1];\n \n // Get Gender\n let regExGender = new RegExp(\"(\" + enumGender.join(\"|\") + \")\", \"i\");\n let foundGender = \"\";\n \n if (stringGenderAndRace.search(regExGender) !== -1) {\n foundGender = stringGenderAndRace.match(regExGender)[0];\n }\n \n // Get Race, check first if there is a playable race\n let regExPlayableRace = new RegExp(\"(\" + enumRaces.join(\"|\") + \")\", \"i\");\n let regExNonPlayableRace = new RegExp(\"(?:\" + enumGender.join(\"|\") + \")(?:[\\\\s]*?)([^0-9]*)\", \"gi\");\n \n let foundRace = \"\";\n \n if (stringGenderAndRace.search(regExPlayableRace) !== -1) {\n // Test playable Races\n foundRace = stringGenderAndRace.match(regExPlayableRace)[0];\n dataInputHasPlayableRace = true;\n \n // FOR NOW JUST USE EVERYTHING AS NONPLAYABLE\n //foundRace = stringGenderAndRace.split(regExNonPlayableRace).join(\"\").replace(/^ | $/, \"\");\n //dataInputHasNonPlayableRace = true;\n } else {\n // If no playable Race is found, simply remove the gender(s) and use the rest as race\n foundRace = stringGenderAndRace.split(regExNonPlayableRace).join(\"\").replace(/^ | $/, \"\");\n dataInputHasNonPlayableRace = true;\n }\n \n formattedInput.gender = foundGender;\n formattedInput.race = capitalize(foundRace);\n } \n \n }\n \n // Creature Type and Subtype(s)\n let splitType = splitGeneralData.match(new RegExp(enumTypes.join(\"|\"), \"i\"))[0];\n \n // Subtypes\n let splitSubtypes = \"\";\n let regExSubtypes = new RegExp(enumSubtypes.join(\"|\"), \"ig\");\n\n // Test only on strings in parenthesis\n let splitGeneralDataInBrackets = splitGeneralData.match(/\\(([^)]+)\\)/g);\n \n if (splitGeneralDataInBrackets !== null) {\n\n // Check each match for valid Subtypes\n // !!! ??? Potential Error Point: Takes only the last match found\n splitGeneralDataInBrackets.forEach( function (item,index) {\n let foundSubtypes = item.match(regExSubtypes);\n if(foundSubtypes !== null) {\n splitSubtypes = foundSubtypes;\n }\n }, splitGeneralDataInBrackets);\n \n }\n \n // Initiative (positive and negative)\n let splitInit = splitGeneralData.match(/(?:Init\\s*)(\\+\\d+|-\\d+|\\d+)/)[1];\n \n // Senses\n let splitSenses = \"\";\n if (splitGeneralData.search(/\\bSenses\\b/gmi) !== -1) {\n splitSenses = splitGeneralData.match(/(?:\\bSenses\\b\\s*)(.*?)(?:\\n|$|\\s*Aura)/igm)[0].replace(/\\bSenses\\b\\s*|\\s*Aura\\b/g,\"\");\n }\n \n // Aura\n let splitAura = \"\";\n if (splitGeneralData.search(/Aura\\b/igm) !== -1) {\n splitAura = splitGeneralData.match(/(?:Aura\\s*)(.*?)(?:;|\\n|$)/igm)[0].replace(/Aura\\s*/,\"\");\n }\n \n // Save the found entries into formattedInput\n formattedInput.name = splitName;\n \n // Save the Challenge Rating as a number\n if (splitCR.search(\"/\") !== -1) {\n let nominator = 1;\n let denominator = splitCR.match(/\\/(\\d)/)[1];\n if (denominator == 3) {\n formattedInput.cr = 0.3375;\n } else if (denominator == 6) {\n formattedInput.cr = 0.1625;\n } else {\n formattedInput.cr = +nominator / +denominator;\n }\n } else {\n formattedInput.cr = splitCR;\n }\n \n // For now, use cr as level\n formattedInput.level = splitCR;\n \n formattedInput.xp = splitXP;\n formattedInput.alignment = splitAlignment;\n formattedInput.size = splitSize;\n formattedInput.space = splitSpace;\n formattedInput.reach = splitReach;\n \n console.log(\"reach: \" + formattedInput.reach);\n \n formattedInput.creature_type = splitType;\n formattedInput.creature_subtype = splitSubtypes;\n formattedInput.initiative = splitInit;\n formattedInput.senses = splitSenses;\n formattedInput.aura = splitAura;\n \n if(DEBUG==true) { console.log(\"sbc-pf1 | DONE parsing general data\") };\n}", "parseFormat(dateString){\n\t\tlet format;\n\t\tlet validFormats = new Set(Object.getOwnPropertyNames(FORMAT));\n\t\tvalidFormats.forEach(valid => {\n\t\t\tlet regex = new RegExp(FORMAT[valid]['regex'], 'g');\n\t\t\tif(regex.test(dateString)){\n\t\t\t\tformat = valid;\n\t\t\t}\n\t\t});\n\t\tif(! format) \n\t\t\tthrow new Error(`Invalid Format: The given \"${dateString}\" does not conform to acceptable formats.`);\n\n\t\treturn format ; \n\t}", "function parse(string){\n var pairs = breakAtSingleTildes(string);\n for (var i=0; i<pairs.length; i++){\n //first determine if this is an array or a singular value\n //the character following the first tilde makes the determination\n //\"=\" means single \"*\" means array\n var index = pairs[i].indexOf(\"~\");\n var name = pairs[i].substr(0,index);\n if (pairs[i].charAt(index+1)==\"=\"){ //handle single value\n var value = pairs[i].substr(index+2);\n storage[name] = ig_cookie_decode(value);\n\n } else if (pairs[i].charAt(index+1)==\"*\"){ //handles array\n var valuestring = pairs[i].substr(index+2);\n var values = new Array();\n var array_index=0;\n var value_index=0;\n while ((value_index = valuestring.indexOf(\"~*\",value_index)) > -1){ //values are separated by a \"~*\" so we need to find one\n //if (value_index==0 || valuestring.charAt(value_index-1)!=\"~\"){ //not preceaded by a tilde\n if (value_index==0 || preceededByEvenNumberOfTildes(valuestring,value_index)){ //not preceaded by a tilde\n //we found a value end\n var value = valuestring.substr(0,value_index);\n values[array_index++] = ig_cookie_decode(value);\n valuestring = valuestring.substr(value_index+2);\n value_index=0;\n } else { //its a false seperator. skip it\n value_index++;\n }\n }\n values[array_index++]=ig_cookie_decode(valuestring);\n storage[name]=values;\n } else if (pairs[i].charAt(index+1)==\"0\"){ //handles empty array\n storage[name]= new Array();\n } else {\n throw \"error parsing value. Expeced ~=, ~* or ~0 to separate name from value\";\n }\n\n }\n\n }", "function myParseInt(str) {\n\n var newString= str.replace(/ /g, '');\n var isFloat=newString.indexOf('.') != -1\n var isValidNumber=!isNaN(newString);\n var hasLetters=(newString.match(/[a-z]/i));\n var specialCharacters=!(/[~`!#$%\\^&*+=\\-\\[\\]\\\\';,/{}|\\\\\":<>\\?]/g.test(newString));\n \n if (isValidNumber && !isFloat && !hasLetters && specialCharacters){\n // Convert to number the string\n return Number(newString);\n }else{\n return \"NaN\";\n }\n}", "function getTokens(characters){\n var tokenPointer = 0;\n while (tokenPointer < characters.length){\n if (characters[tokenPointer] == \" \") {\n tokenPointer+=1;\n }\n else if (characters[tokenPointer] == \"-\") {\n tokens.push(\"neg\");\n tokenPointer+=1;\n }\n else if (characters[tokenPointer] == \"*\") {\n tokens.push(\"and\");\n tokenPointer+=1;\n }\n else if (characters[tokenPointer] == \"V\") {\n tokens.push(\"or\");\n tokenPointer+=1;\n }\n else if (characters[tokenPointer] == \"(\" || characters[tokenPointer] == \"[\") {\n if (tokenPointer+4<characters.length && characters[tokenPointer+1]==\"U\"\n && characters[tokenPointer+2]==\"Q\" && characters[tokenPointer+3]\n != characters[tokenPointer+3].toUpperCase() && characters[tokenPointer+4] == \")\"){\n tokens.push(\"uq\");\n tokenPointer += 5;\n }\n else if (tokenPointer+4<characters.length && characters[tokenPointer+1]==\"E\"\n && characters[tokenPointer+2]==\"Q\" && characters[tokenPointer+3]\n != characters[tokenPointer+3].toUpperCase() && characters[tokenPointer+4] == \")\"){\n tokens.push(\"eq\");\n tokenPointer += 5;\n }\n else {\n tokens.push(\"lp\")\n tokenPointer+=1\n }\n }\n else if (characters[tokenPointer] == \")\" || characters[tokenPointer] == \"]\") {\n tokens.push(\"rp\");\n tokenPointer+=1;\n }\n else if (characters[tokenPointer] != characters[tokenPointer].toLowerCase()) {\n if(tokenPointer+1<characters.length && characters[tokenPointer+1]\n != characters[tokenPointer+1].toUpperCase()){\n tokens.push(\"pred\");\n tokenPointer += 1;\n while(tokenPointer<characters.length && characters[tokenPointer]\n != characters[tokenPointer].toUpperCase()){\n tokenPointer+=1;\n }\n }\n else {\n tokens.push(\"error\");\n break;\n }\n }\n else if (characters[tokenPointer] != characters[tokenPointer].toUpperCase()){\n tokens.push(\"sentLet\");\n tokenPointer+= 1;\n }\n else if (characters[tokenPointer] == \"<\") {\n if(tokenPointer+2<characters.length && characters[tokenPointer+1]==\"=\"\n && characters[tokenPointer+2]==\">\"){\n tokens.push(\"bicond\");\n tokenPointer += 3;\n }\n }\n else if (characters[tokenPointer] == \"=\") {\n if(tokenPointer+1<characters.length && characters[tokenPointer+1]==\">\"){\n tokens.push(\"cond\");\n tokenPointer += 2;\n }\n else {\n tokens.push(\"eqOp\");\n tokenPointer += 1;\n }\n }\n else if (characters[tokenPointer] == \"!\") {\n if(tokenPointer+1<characters.length && characters[tokenPointer+1]==\"=\"){\n tokens.push(\"notEqOp\");\n tokenPointer += 2;\n }\n else{\n tokens.push(\"error\");\n break;\n }\n }\n else {\n tokens.push(\"error\");\n break;\n }\n }\n}", "function decodeGrammar(productionString) {\n var duo, nonterminal, replacementString;\n var replacements = [];\n var productions = {};\n var blocks = productionString.split(';');\n initialNonterminal_ = blocks[0].split(':')[0].trim();\n for (let blockIndex=0; blockIndex < blocks.length; blockIndex++) {\n if (blocks[blockIndex].trim() == '') {\n continue;\n }\n duo = blocks[blockIndex].split(':');\n if (duo.length != 2) {\n console.error(\"Invalid syntax for given grammar productions: \" + blocks[blockIndex]);\n continue;\n }\n nonterminal = duo[0].trim();\n replacementString = duo[1];\n replacements = (interpretReplacementStrings(replacementString.split('|')));\n productions[nonterminal] = replacements;\n }\n return productions;\n}", "function htmlToPassage(raw, isCorrect) {\n convertedPassage = '';\n\n for (let i = 0; i < raw.length; i ++) {\n if(raw[i] != '{') {\n convertedPassage += raw[i];\n } else {\n let string = getSpecialString(raw.substring(i)).specialString;\n convertedPassage += parseString(string, isCorrect).value;\n //change value of i to skip to the end of the parsed string\n i += getSpecialString(raw.substring(i)).charIndex;\n }\n }\n return convertedPassage;\n}", "function jsParseSpChr(argString) {\n var parsedString = argString.replace(/[']/g,\"\\'\");\n parsedString = argString.replace(/[\"]/g,\"\\\"\");\n return parsedString;\n }", "function parseTurnType(text) {\n var turnType = TurnType.Unknown,\n rules = TurnTypeRules;\n \n // run the text through the manuever rules\n for (var ii = 0; ii < rules.length; ii++) {\n rules[ii].regex.lastIndex = -1;\n \n var matches = rules[ii].regex.exec(text);\n if (matches) {\n // if we have a custom check defined for the rule, then pass the text in \n // for the manuever result\n if (rules[ii].customCheck) {\n turnType = rules[ii].customCheck(text, matches);\n }\n // otherwise, take the manuever provided by the rule\n else {\n turnType = rules[ii].turnType;\n } // if..else\n \n break;\n } // if\n } // for\n \n return turnType;\n } // parseTurnType", "function manipulateString(string) {\n\t//alertrnf(\"from backup in manipulateString(): string received = \" + string);\n\t//alertrnf(\"renamedFileName = \" + renamedFileName);\nif(budgetSheet && !(renamedFileName.includes(\"bs\"))) {\n//restore.bs to filename //if backing up a budgetsheet after edit renamedFileName might already end in .bs\nrenamedFileName = renamedFileName + \".bs\";\n//protocolFileName = renamedFileName + \".bs\";\n//protocolFileName = renamedFileName + \".bs\";\n}//end if(budgetSheet) {\n\tposition = string.indexOf(\"_os\");\n\t//alertrnf(\"position = \" + position);\n\tpart = string.slice(position);\n\t//alertrnf(\"part = \" + part);\n\t//newPartString = \"{\\\"\" + protocolFileName;\n\tnewPartString = \"{\\\"\" + renamedFileName;\n\t//alertrnf(\"newPartString = \" + newPartString);\n\t//string.splice position = 17\n\t//string = \"This is a test of rename db filename!\"\n\tstring = newPartString+part;\n\t//alertrnf(\"Now string = \" + string);\n\t// dbTitle.textContent = renamedFileName;\n\t return string;\n}//end function manipulateString", "function applyRules( languageNode, contextNode, sString, parsedCodeNode)\n{\n\tvar regExp, arr,sRegExp;\n\tvar ruleNode,newNode, newCDATANode;\n\n\t// building regExp \n\tsRegExp=contextNode.attributes.getNamedItem(\"regexp\").value;\n\tvar regExp = new RegExp( sRegExp, \"m\" );\n\n\twhile (sString.length > 0)\n\t{\n\t\t// apply\n\t\tarr = regExp.exec( sString );\n\t\tif (arr == null)\n\t\t{\n\t\t\taddChildCDATAElem( parsedCodeNode,\n\t\t\t\t\t\t\tcontextNode.attributes.getNamedItem(\"attribute\").value, \n\t\t\t\t\t\t\tsString );\n\t\t\t\n\t\t\t// finished parsing\n\t\t\tregExp=null;\n\t\t\treturn null;\n\t\t}\n\t\telse\n\t\t{\n\t\t//alert( contextNode.attributes.getNamedItem(\"attribute\").nodeTypedValue ) ;\n\t\t\t// adding text\n\t\t\taddChildCDATAElem(parsedCodeNode, \n\t\t\t\t\t\t\tcontextNode.attributes.getNamedItem(\"attribute\").value,\n\t\t\t\t\t\t\tsString.substring(0, arr.index ) );\n\t\t\t\n\t\t\t// find rule...\n\t\t\truleNode = findRule( languageNode, contextNode, arr[0] );\n\t\t\tif (ruleNode == null)\n\t\t\t\tthrow \"Didn't matching rule, regular expression false ? ( context: \" + contextNode.attributes.getNamedItem(\"id\").value;\n\t\t\t\n\t\t\t// check if rule nees to be added to result...\n\t\t\tattributeNode=ruleNode.attributes.getNamedItem(\"attribute\");\n\t\t\tif (attributeNode != null && attributeNode.value!=\"hidden\" )\n\t\t\t{\n\t\t\t\taddChildCDATAElem(parsedCodeNode,\n\t\t\t\t\t\t\t\truleNode.attributes.getNamedItem(\"attribute\").value ,\n\t\t\t\t\t\t\t\tarr[0]);\n\t\t\t}\n\t\t\t\n\t\t\t// update context if necessary\n\t\t\tif ( contextNode.attributes.getNamedItem(\"id\").value != ruleNode.attributes.getNamedItem(\"context\").value )\n\t\t\t{\n\t\t\t\t// return new context \n\t\t\t\tvar xpContext = \"contexts/context[@id=\\\"\" \n\t\t\t\t\t\t\t\t+ ruleNode.attributes.getNamedItem(\"context\").value\n\t\t\t\t\t\t\t\t+ \"\\\"]\";\n\t\t\t\tcontextNode = languageNode.selectSingleNode( xpContext);\n\t\t\t\tif (contextNode == null)\n\t\t\t\t\tthrow \"Didn't matching context, error in xml specification ?\";\n\t\t\t\t\t\n\t\t\t\t// build new regular expression\n\t\t\t\tsRegExp=contextNode.attributes.getNamedItem(\"regexp\").value;\n\t\t\t\tregExp = new RegExp( sRegExp, \"m\" );\n\t\t\t}\n\t\t\tsString = sString.substring(arr.index+arr[0].length, sString.length);\t\t\t\n\t\t}\n\t}\n\tregExp = null;\n}", "function getLinkRewriteFromString(str)\n\t{\n\t\tstr = str.toUpperCase();\n\t\tstr = str.toLowerCase();\n\t\t\n\t\t/* Lowercase */\n\t\tstr = str.replace(/[\\u00E0\\u00E1\\u00E2\\u00E3\\u00E4\\u00E5\\u0101\\u0103\\u0105\\u0430]/g, 'a');\n str = str.replace(/[\\u0431]/g, 'b');\n\t\tstr = str.replace(/[\\u00E7\\u0107\\u0109\\u010D\\u0446]/g, 'c');\n\t\tstr = str.replace(/[\\u010F\\u0111\\u0434]/g, 'd');\n\t\tstr = str.replace(/[\\u00E8\\u00E9\\u00EA\\u00EB\\u0113\\u0115\\u0117\\u0119\\u011B\\u0435\\u044D]/g, 'e');\n str = str.replace(/[\\u0444]/g, 'f');\n\t\tstr = str.replace(/[\\u011F\\u0121\\u0123\\u0433\\u0491]/g, 'g');\n\t\tstr = str.replace(/[\\u0125\\u0127]/g, 'h');\n\t\tstr = str.replace(/[\\u00EC\\u00ED\\u00EE\\u00EF\\u0129\\u012B\\u012D\\u012F\\u0131\\u0438\\u0456]/g, 'i');\n\t\tstr = str.replace(/[\\u0135\\u0439]/g, 'j');\n\t\tstr = str.replace(/[\\u0137\\u0138\\u043A]/g, 'k');\n\t\tstr = str.replace(/[\\u013A\\u013C\\u013E\\u0140\\u0142\\u043B]/g, 'l');\n str = str.replace(/[\\u043C]/g, 'm');\n\t\tstr = str.replace(/[\\u00F1\\u0144\\u0146\\u0148\\u0149\\u014B\\u043D]/g, 'n');\n\t\tstr = str.replace(/[\\u00F2\\u00F3\\u00F4\\u00F5\\u00F6\\u00F8\\u014D\\u014F\\u0151\\u043E]/g, 'o');\n str = str.replace(/[\\u043F]/g, 'p');\n\t\tstr = str.replace(/[\\u0155\\u0157\\u0159\\u0440]/g, 'r');\n\t\tstr = str.replace(/[\\u015B\\u015D\\u015F\\u0161\\u0441]/g, 's');\n\t\tstr = str.replace(/[\\u00DF]/g, 'ss');\n\t\tstr = str.replace(/[\\u0163\\u0165\\u0167\\u0442]/g, 't');\n\t\tstr = str.replace(/[\\u00F9\\u00FA\\u00FB\\u00FC\\u0169\\u016B\\u016D\\u016F\\u0171\\u0173\\u0443]/g, 'u');\n str = str.replace(/[\\u0432]/g, 'v');\n\t\tstr = str.replace(/[\\u0175]/g, 'w');\n\t\tstr = str.replace(/[\\u00FF\\u0177\\u00FD\\u044B]/g, 'y');\n\t\tstr = str.replace(/[\\u017A\\u017C\\u017E\\u0437]/g, 'z');\n\t\tstr = str.replace(/[\\u00E6]/g, 'ae');\n str = str.replace(/[\\u0447]/g, 'ch');\n str = str.replace(/[\\u0445]/g, 'kh');\n\t\tstr = str.replace(/[\\u0153]/g, 'oe');\n str = str.replace(/[\\u0448]/g, 'sh');\n str = str.replace(/[\\u0449]/g, 'ssh');\n str = str.replace(/[\\u044F]/g, 'ya');\n str = str.replace(/[\\u0454]/g, 'ye');\n str = str.replace(/[\\u0457]/g, 'yi');\n str = str.replace(/[\\u0451]/g, 'yo');\n str = str.replace(/[\\u044E]/g, 'yu');\n str = str.replace(/[\\u0436]/g, 'zh');\n\n\t\t/* Uppercase */\n\t\tstr = str.replace(/[\\u0100\\u0102\\u0104\\u00C0\\u00C1\\u00C2\\u00C3\\u00C4\\u00C5\\u0410]/g, 'A');\n str = str.replace(/[\\u0411]/g, 'B');\n\t\tstr = str.replace(/[\\u00C7\\u0106\\u0108\\u010A\\u010C\\u0426]/g, 'C');\n\t\tstr = str.replace(/[\\u010E\\u0110\\u0414]/g, 'D');\n\t\tstr = str.replace(/[\\u00C8\\u00C9\\u00CA\\u00CB\\u0112\\u0114\\u0116\\u0118\\u011A\\u0415\\u042D]/g, 'E');\n str = str.replace(/[\\u0424]/g, 'F');\n\t\tstr = str.replace(/[\\u011C\\u011E\\u0120\\u0122\\u0413\\u0490]/g, 'G');\n\t\tstr = str.replace(/[\\u0124\\u0126]/g, 'H');\n\t\tstr = str.replace(/[\\u0128\\u012A\\u012C\\u012E\\u0130\\u0418\\u0406]/g, 'I');\n\t\tstr = str.replace(/[\\u0134\\u0419]/g, 'J');\n\t\tstr = str.replace(/[\\u0136\\u041A]/g, 'K');\n\t\tstr = str.replace(/[\\u0139\\u013B\\u013D\\u0139\\u0141\\u041B]/g, 'L');\n str = str.replace(/[\\u041C]/g, 'M');\n\t\tstr = str.replace(/[\\u00D1\\u0143\\u0145\\u0147\\u014A\\u041D]/g, 'N');\n\t\tstr = str.replace(/[\\u00D3\\u014C\\u014E\\u0150\\u041E]/g, 'O');\n str = str.replace(/[\\u041F]/g, 'P');\n\t\tstr = str.replace(/[\\u0154\\u0156\\u0158\\u0420]/g, 'R');\n\t\tstr = str.replace(/[\\u015A\\u015C\\u015E\\u0160\\u0421]/g, 'S');\n\t\tstr = str.replace(/[\\u0162\\u0164\\u0166\\u0422]/g, 'T');\n\t\tstr = str.replace(/[\\u00D9\\u00DA\\u00DB\\u00DC\\u0168\\u016A\\u016C\\u016E\\u0170\\u0172\\u0423]/g, 'U');\n str = str.replace(/[\\u0412]/g, 'V');\n\t\tstr = str.replace(/[\\u0174]/g, 'W');\n\t\tstr = str.replace(/[\\u0176\\u042B]/g, 'Y');\n\t\tstr = str.replace(/[\\u0179\\u017B\\u017D\\u0417]/g, 'Z');\n\t\tstr = str.replace(/[\\u00C6]/g, 'AE');\n str = str.replace(/[\\u0427]/g, 'CH');\n str = str.replace(/[\\u0425]/g, 'KH');\n\t\tstr = str.replace(/[\\u0152]/g, 'OE');\n str = str.replace(/[\\u0428]/g, 'SH');\n str = str.replace(/[\\u0429]/g, 'SHH');\n str = str.replace(/[\\u042F]/g, 'YA');\n str = str.replace(/[\\u0404]/g, 'YE');\n str = str.replace(/[\\u0407]/g, 'YI');\n str = str.replace(/[\\u0401]/g, 'YO');\n str = str.replace(/[\\u042E]/g, 'YU');\n str = str.replace(/[\\u0416]/g, 'ZH');\n\n\t\tstr = str.toLowerCase();\n\n\t\tstr = str.replace(/[^a-z0-9\\s\\'\\:\\/\\[\\]-]/g,'');\n\t\t\n\t\tstr = str.replace(/[\\u0028\\u0029\\u0021\\u003F\\u002E\\u0026\\u005E\\u007E\\u002B\\u002A\\u002F\\u003A\\u003B\\u003C\\u003D\\u003E]/g, '');\n\t\tstr = str.replace(/[\\s\\'\\:\\/\\[\\]-]+/g, ' ');\n\n\t\t// Add special char not used for url rewrite\n\t\tstr = str.replace(/[ ]/g, '-');\n\t\tstr = str.replace(/[\\/\\\\\"'|,;%]*/g, '');\n\n\t\treturn str;\n\t}", "function parseExpression(program) {\n program = skipSpace(program);\n let match, expr;\n // using 3 regex to spot either strings, #s or words\n if (match = /^\"([^\"]*)\"/.exec(program)) {\n expr = {type: \"value\", value: match[1]};\n } else if (match = /^\\d+\\b/.exec(program)) {\n expr = {type: \"value\", value: Number(match[0])};\n } else if (match = /^[^\\s(),#\"]+/.exec(program)) {\n expr = {type: \"word\", name: match[0]};\n } else {\n // if the input does not match any of the above 3 forms, it's not a valid expression\n // throw an error, specifically Syntax Error\n throw new SyntaxError(\"Unexpected syntax: \" + program);\n }\n// return what is matched and pass it along w/ the object for the expression to parseApply\n return parseApply(expr, program.slice(match[0].length));\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`applyProjectionRecursive` performs operation on the projection specified by `action` (insert, detach, destroy) Inserting a projection requires us to locate the projected nodes from the parent component. The complication is that those nodes themselves could be reprojected from their parent component.
function applyProjectionRecursive(renderer, action, lView, tProjectionNode, renderParent, beforeNode) { var componentLView = lView[DECLARATION_COMPONENT_VIEW]; var componentNode = componentLView[T_HOST]; ngDevMode && assertEqual(typeof tProjectionNode.projection, 'number', 'expecting projection index'); var nodeToProjectOrRNodes = componentNode.projection[tProjectionNode.projection]; if (Array.isArray(nodeToProjectOrRNodes)) { // This should not exist, it is a bit of a hack. When we bootstrap a top level node and we // need to support passing projectable nodes, so we cheat and put them in the TNode // of the Host TView. (Yes we put instance info at the T Level). We can get away with it // because we know that that TView is not shared and therefore it will not be a problem. // This should be refactored and cleaned up. for (var i = 0; i < nodeToProjectOrRNodes.length; i++) { var rNode = nodeToProjectOrRNodes[i]; applyToElementOrContainer(action, renderer, renderParent, rNode, beforeNode); } } else { var nodeToProject = nodeToProjectOrRNodes; var projectedComponentLView = componentLView[PARENT]; applyNodes(renderer, action, nodeToProject, projectedComponentLView, renderParent, beforeNode, true); } }
[ "function zoom(root, p) {\r\n if (document.documentElement.__transition__) return;\r\n\r\n // Rescale outside angles to match the new layout.\r\n var enterArc,\r\n exitArc,\r\n outsideAngle = d3.scale.linear().domain([0, 2 * Math.PI]);\r\n\r\n function insideArc(d) {\r\n return p.key > d.key\r\n ? {depth: d.depth - 1, x: 0, dx: 0} : p.key < d.key\r\n ? {depth: d.depth - 1, x: 2 * Math.PI, dx: 0}\r\n : {depth: 0, x: 0, dx: 2 * Math.PI};\r\n }\r\n\r\n function outsideArc(d) {\r\n return {depth: d.depth + 1, x: outsideAngle(d.x), dx: outsideAngle(d.x + d.dx) - outsideAngle(d.x)};\r\n }\r\n\r\n center.datum(root);\r\n\r\n // When zooming in, arcs enter from the outside and exit to the inside.\r\n // Entering outside arcs start from the old layout.\r\n if (root === p) enterArc = outsideArc, exitArc = insideArc, outsideAngle.range([p.x, p.x + p.dx]);\r\n\r\n\t var new_data=partition.nodes(root).slice(1)\r\n\r\n path = path.data(new_data, function(d) { return d.key; });\r\n\r\n\t // When zooming out, arcs enter from the inside and exit to the outside.\r\n // Exiting outside arcs transition to the new layout.\r\n if (root !== p) enterArc = insideArc, exitArc = outsideArc, outsideAngle.range([p.x, p.x + p.dx]);\r\n\r\n d3.transition().duration(d3.event.altKey ? 7500 : 750).each(function() {\r\n path.exit().transition()\r\n .style(\"fill-opacity\", function(d) { return d.depth === 1 + (root === p) ? 1 : 0; })\r\n .attrTween(\"d\", function(d) { return arcTween.call(this, exitArc(d)); })\r\n .remove();\r\n\r\n path.enter().append(\"path\")\r\n .style(\"fill-opacity\", function(d) { return d.depth === 2 - (root === p) ? 1 : 0; })\r\n .style(\"fill\", function(d) { return d.fill; })\r\n .on(\"click\", zoomIn)\r\n\t\t\t .on(\"mouseover\", mouseOverArc)\r\n .on(\"mousemove\", mouseMoveArc)\r\n \t.on(\"mouseout\", mouseOutArc)\r\n .each(function(d) { this._current = enterArc(d); });\r\n\r\n\r\n path.transition()\r\n .style(\"fill-opacity\", 1)\r\n .attrTween(\"d\", function(d) { return arcTween.call(this, updateArc(d)); });\r\n\r\n\r\n });\r\n\r\n\r\n\t texts = texts.data(new_data, function(d) { return d.key; })\r\n\r\n texts.exit()\r\n\t .remove()\r\n texts.enter()\r\n .append(\"text\")\r\n\r\n texts.style(\"opacity\", 0)\r\n .attr(\"transform\", function(d) {\r\n var r = computeTextRotation(d);\r\n return \"rotate(\" + r.global + \")\"\r\n + \"translate(\" + radius / 3 * d.depth + \",0)\"\r\n + \"rotate(\" + -r.correction + \")\";\r\n })\r\n .style(\"font-weight\", \"bold\")\r\n .style(\"text-anchor\", \"middle\")\r\n\t\t .attr(\"dx\", function(d) {return isRotated(d) ? \"-85\" : \"85\"}) //margin\r\n .attr(\"dy\", \".35em\") // vertical-align\r\n .filter(filter_min_arc_size_text)\r\n .on(\"click\", zoomIn)\r\n .text(function(d,i) {return d.name})\r\n\t\t .transition().delay(750).style(\"opacity\", 1)\r\n\r\n }", "transform(path, operation) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n return fn$4(path, p => {\n var {\n affinity = 'forward'\n } = options; // PERF: Exit early if the operation is guaranteed not to have an effect.\n\n if (path.length === 0) {\n return;\n }\n\n switch (operation.type) {\n case 'insert_node':\n {\n var {\n path: op\n } = operation;\n\n if (Path.equals(op, p) || Path.endsBefore(op, p) || Path.isAncestor(op, p)) {\n p[op.length - 1] += 1;\n }\n\n break;\n }\n\n case 'remove_node':\n {\n var {\n path: _op\n } = operation;\n\n if (Path.equals(_op, p) || Path.isAncestor(_op, p)) {\n return null;\n } else if (Path.endsBefore(_op, p)) {\n p[_op.length - 1] -= 1;\n }\n\n break;\n }\n\n case 'merge_node':\n {\n var {\n path: _op2,\n position\n } = operation;\n\n if (Path.equals(_op2, p) || Path.endsBefore(_op2, p)) {\n p[_op2.length - 1] -= 1;\n } else if (Path.isAncestor(_op2, p)) {\n p[_op2.length - 1] -= 1;\n p[_op2.length] += position;\n }\n\n break;\n }\n\n case 'split_node':\n {\n var {\n path: _op3,\n position: _position\n } = operation;\n\n if (Path.equals(_op3, p)) {\n if (affinity === 'forward') {\n p[p.length - 1] += 1;\n } else if (affinity === 'backward') ; else {\n return null;\n }\n } else if (Path.endsBefore(_op3, p)) {\n p[_op3.length - 1] += 1;\n } else if (Path.isAncestor(_op3, p) && path[_op3.length] >= _position) {\n p[_op3.length - 1] += 1;\n p[_op3.length] -= _position;\n }\n\n break;\n }\n\n case 'move_node':\n {\n var {\n path: _op4,\n newPath: onp\n } = operation; // If the old and new path are the same, it's a no-op.\n\n if (Path.equals(_op4, onp)) {\n return;\n }\n\n if (Path.isAncestor(_op4, p) || Path.equals(_op4, p)) {\n var copy = onp.slice();\n\n if (Path.endsBefore(_op4, onp) && _op4.length < onp.length) {\n copy[_op4.length - 1] -= 1;\n }\n\n return copy.concat(p.slice(_op4.length));\n } else if (Path.isSibling(_op4, onp) && (Path.isAncestor(onp, p) || Path.equals(onp, p))) {\n if (Path.endsBefore(_op4, p)) {\n p[_op4.length - 1] -= 1;\n } else {\n p[_op4.length - 1] += 1;\n }\n } else if (Path.endsBefore(onp, p) || Path.equals(onp, p) || Path.isAncestor(onp, p)) {\n if (Path.endsBefore(_op4, p)) {\n p[_op4.length - 1] -= 1;\n }\n\n p[onp.length - 1] += 1;\n } else if (Path.endsBefore(_op4, p)) {\n if (Path.equals(onp, p)) {\n p[onp.length - 1] += 1;\n }\n\n p[_op4.length - 1] -= 1;\n }\n\n break;\n }\n }\n });\n }", "visitMerge_insert_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitMerge_update_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "prune(callback) {\n if (_.isArray(this.contents)) {\n const length = this.contents.length;\n\n if ((this.type === \"REPEAT\" && length > 0) || (this.type === \"REPEAT1\" && length > 1)) {\n // Any subtree may be removed\n for (let i = 0; i < length; i++) {\n const tree = _.cloneDeep(this);\n tree.contents.splice(i, 1);\n if (!callback(tree)) {\n return;\n }\n }\n }\n\n for (let i = 0; i < length; i++) {\n let callbackResult = true;\n\n this.contents[i].prune(t => {\n const tree = _.cloneDeep(this);\n tree.contents[i] = t;\n callbackResult = callback(tree);\n return callbackResult;\n });\n\n if (!callbackResult) {\n return;\n }\n }\n }\n }", "function refresh_all_action_items() {\n\tconsole.log(\"now refreshing\");\n\t$(\"div#projects div.project\").each( function() {\n\t\trefresh_action_items(this);\n\t});\n}", "transform(point, op) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n return fn$4(point, p => {\n var {\n affinity = 'forward'\n } = options;\n var {\n path,\n offset\n } = p;\n\n switch (op.type) {\n case 'insert_node':\n case 'move_node':\n {\n p.path = Path.transform(path, op, options);\n break;\n }\n\n case 'insert_text':\n {\n if (Path.equals(op.path, path) && op.offset <= offset) {\n p.offset += op.text.length;\n }\n\n break;\n }\n\n case 'merge_node':\n {\n if (Path.equals(op.path, path)) {\n p.offset += op.position;\n }\n\n p.path = Path.transform(path, op, options);\n break;\n }\n\n case 'remove_text':\n {\n if (Path.equals(op.path, path) && op.offset <= offset) {\n p.offset -= Math.min(offset - op.offset, op.text.length);\n }\n\n break;\n }\n\n case 'remove_node':\n {\n if (Path.equals(op.path, path) || Path.isAncestor(op.path, path)) {\n return null;\n }\n\n p.path = Path.transform(path, op, options);\n break;\n }\n\n case 'split_node':\n {\n if (Path.equals(op.path, path)) {\n if (op.position === offset && affinity == null) {\n return null;\n } else if (op.position < offset || op.position === offset && affinity === 'forward') {\n p.offset -= op.position;\n p.path = Path.transform(path, op, _objectSpread$3(_objectSpread$3({}, options), {}, {\n affinity: 'forward'\n }));\n }\n } else {\n p.path = Path.transform(path, op, options);\n }\n\n break;\n }\n }\n });\n }", "performReduction() {\n //console.log(\"called performReduction\");\n var reduced_expr = this.reduce();\n if (reduced_expr !== undefined && reduced_expr != this) { // Only swap if reduction returns something > null.\n\n console.warn('performReduction with ', this, reduced_expr);\n\n if (!this.stage) return Promise.reject();\n\n this.stage.saveState();\n Logger.log('state-save', this.stage.toString());\n\n // Log the reduction.\n let reduced_expr_str;\n if (reduced_expr === null)\n reduced_expr_str = '()';\n else if (Array.isArray(reduced_expr))\n reduced_expr_str = reduced_expr.reduce((prev,curr) => (prev + curr.toString() + ' '), '').trim();\n else reduced_expr_str = reduced_expr.toString();\n Logger.log('reduction', { 'before':this.toString(), 'after':reduced_expr_str });\n\n var parent = this.parent ? this.parent : this.stage;\n if (reduced_expr) reduced_expr.ignoreEvents = this.ignoreEvents; // the new expression should inherit whatever this expression was capable of as input\n parent.swap(this, reduced_expr);\n\n // Check if parent expression is now reducable.\n if (reduced_expr && reduced_expr.parent) {\n var try_reduce = reduced_expr.parent.reduceCompletely();\n if (try_reduce != reduced_expr.parent && try_reduce !== null) {\n Animate.blink(reduced_expr.parent, 400, [0,1,0], 1);\n }\n }\n\n if (reduced_expr)\n reduced_expr.update();\n\n return Promise.resolve(reduced_expr);\n }\n return Promise.resolve(this);\n }", "function update(source, transition) {\r\n selectNode(source);\r\n if(source == root){\r\n if (root.children) {\r\n root.children.forEach(function(child) {\r\n collapseTree(child);\r\n });\r\n }\r\n }\r\n // console.log(flag)\r\n // var duration = transition ?\r\n // (event && event.altKey ? DURATION * 4 : DURATION) : 0;\r\n var duration = 2\r\n\r\n // Compute the new tree layout.\r\n\r\n var nodes = tree(source).descendants();\r\n var links = tree(source).links();\r\n svgGroup.transition().duration(duration)\r\n .attr('transform',\r\n 'rotate(' + curR + ' ' + curX + ' ' + curY +\r\n ')translate(' + curX + ' ' + curY +\r\n ')scale(' + curZ + ')');\r\n\r\n // Update the nodes…\r\n var node = svgGroup.selectAll('g.node')\r\n .data(nodes, function(d) {\r\n return d.id || (d.id = ++counter);\r\n });\r\n\r\n function wrap(text, width) {\r\n text.each(function() {\r\n\r\n var text = d3.select(this),\r\n words = text.text().split(/\\s+/).reverse(),\r\n word,\r\n line = [],\r\n lineNumber = 0,\r\n lineHeight = 1.1, // ems\r\n y = text.attr(\"y\"),\r\n dy = parseFloat('.35em')/2,\r\n tspan = text.text(null).append(\"tspan\").attr(\"x\", 0).attr(\"y\", y).attr(\"dy\", dy + \"em\");\r\n // console.log(words, y, text.attr(\"dy\"))\r\n while (word = words.pop()) {\r\n line.push(word);\r\n tspan.text(line.join(\" \"));\r\n if (tspan.node().getComputedTextLength() > width) {\r\n line.pop();\r\n tspan.text(line.join(\" \"));\r\n line = [word];\r\n tspan = text.append(\"tspan\").attr(\"x\", 0).attr(\"y\", y).attr(\"dy\", lineHeight + dy + \"em\").text(word);\r\n }\r\n }\r\n });\r\n }\r\n\r\n // Enter any new nodes at the parent's previous position\r\n var nodeEnter = node.enter().insert('g', ':first-child')\r\n .attr('class', 'node')\r\n // .attr('transform', 'rotate(' + (source.x0 - 90) + ')translate(' + source.y0 + ')')\r\n .on('click', click)\r\n .on('dblclick', dblclick)\r\n // .on('mousedown', suppress);\r\n\r\n nodeEnter.append('circle')\r\n .attr('r', 1e-6)\r\n .style('fill', function(d) {\r\n return d._children ? HAS_CHILDREN_COLOR : 'white';\r\n });\r\n\r\n nodeEnter.append('text')\r\n // .text(function(d) { if(d.name.length > 10) { return wordwrap(d.name, 10, '<br>') } } )\r\n .text(function(d) {\r\n return d.id.substring(d.id.lastIndexOf(\"\\\\\") + 1);\r\n // return d.data.name;\r\n })\r\n .style('opacity', 0.9)\r\n .style('fill-opacity', 0)\r\n .attr('transform', function() {\r\n return ((source.x0 + curR) % 360 <= 180 ?\r\n 'translate(8)scale(' :\r\n 'rotate(180)translate(-8)scale('\r\n ) + reduceZ() + ')';\r\n });\r\n\r\n // update existing graph nodes\r\n\r\n // Change the circle fill depending on whether it has children and is collapsed\r\n node.select('circle')\r\n .attr('r', NODE_DIAMETER * reduceZ())\r\n .style('fill', function(d) {\r\n return d._children ? HAS_CHILDREN_COLOR : 'white';\r\n }).attr('stroke', function(d) {\r\n return d.selected ? SELECTED_COLOR : 'steelblue';\r\n }).attr('stroke-width', function(d) {\r\n return d.selected ? 3 : 1.5;\r\n });\r\n\r\n node.select('text')\r\n .attr('text-anchor', function(d) {\r\n return (d.x + curR) % 360 <= 180 ? 'start' : 'end';\r\n }).attr('transform', function(d) {\r\n return ((d.x + curR) % 360 <= 180 ?\r\n 'translate(8)scale(' :\r\n 'rotate(180)translate(-8)scale('\r\n ) + reduceZ() +')';\r\n }).attr('fill', function(d) {\r\n return d.selected ? SELECTED_COLOR : 'black';\r\n }).attr('dy', '.35em');\r\n\r\n var nodeUpdate = node.merge(nodeEnter).transition().duration(duration)\r\n .delay( transition ? function(d, i) {\r\n return i * STAGGERN +\r\n Math.abs(d.depth - curNode.depth) * STAGGERD; } : 0)\r\n .attr('transform', function(d) {\r\n return 'rotate(' + (d.x - 90) + ')translate(' + d.y + ')';\r\n });\r\n\r\n nodeUpdate.select('circle')\r\n .attr('r', NODE_DIAMETER * reduceZ());\r\n // .style('fill', function(d) {\r\n // return d._children ? HAS_CHILDREN_COLOR : 'white';\r\n // });\r\n\r\n nodeUpdate.select('text')\r\n .style('fill-opacity', 1);\r\n nodeUpdate.select(\"text\").call(wrap, 100);\r\n\r\n // Transition exiting nodes to the parent's new position and remove\r\n var nodeExit = node.exit().transition().duration(duration)\r\n .delay( transition ? function(d, i) {\r\n return i * STAGGERN; } : 0)\r\n .attr('transform', function() {\r\n return 'rotate(' + (source.x - 90) +')translate(' + source.y + ')';\r\n }).remove();\r\n\r\n nodeExit.select('circle').attr('r', 0);\r\n nodeExit.select('text').style('fill-opacity', 0);\r\n\r\n // Update the links...\r\n var link = svgGroup.selectAll('path.link')\r\n .data(links, function(d) {\r\n return d.target.id;\r\n });\r\n\r\n// Enter any new links at the parent's previous position\r\n link.enter().insert('path', 'g')\r\n .attr('class', 'link')\r\n .attr(\"d\", function(d) {\r\n return \"M\" + project(d.target.x, d.target.y)\r\n + \"C\" + project(d.target.x, (d.target.y + d.source.y) / 2)\r\n + \" \" + project(d.source.x, (d.target.y + d.source.y) / 2)\r\n + \" \" + project(d.source.x, d.source.y);\r\n })\r\n\r\n // Transition links to their new position\r\n link.transition().duration(duration)\r\n .delay( transition ? function(d, i) {\r\n return i * STAGGERN +\r\n Math.abs(d.source.depth - curNode.depth) * STAGGERD;\r\n // Math.max(0, d.source.depth - curNode.depth) * STAGGERD;\r\n } : 0)\r\n .attr(\"d\", function(d) {\r\n return \"M\" + project(d.target.x, d.target.y)\r\n + \"C\" + project(d.target.x, (d.target.y + d.source.y) / 2)\r\n + \" \" + project(d.source.x, (d.target.y + d.source.y) / 2)\r\n + \" \" + project(d.source.x, d.source.y);\r\n })\r\n\r\n // Transition exiting nodes to the parent's new position\r\n link.exit().transition().duration(duration)\r\n .attr(\"d\", function(d) {\r\n return \"M\" + project(d.target.x, d.target.y)\r\n + \"C\" + project(d.target.x, (d.target.y + d.source.y) / 2)\r\n + \" \" + project(d.source.x, (d.target.y + d.source.y) / 2)\r\n + \" \" + project(d.source.x, d.source.y);\r\n }).remove();\r\n\r\n // Stash the old positions for transition\r\n nodes.forEach(function(d) {\r\n d.x0 = d.x;\r\n d.y0 = d.y;\r\n });\r\n } // end update", "function recollectNodeTree(node, unmountOnly) {\n\t// @TODO: Need to make a call on whether Preact should remove nodes not created by itself.\n\t// Currently it *does* remove them. Discussion: https://github.com/developit/preact/issues/39\n\t//if (!node[ATTR_KEY]) return;\n\n\tvar component = node._component;\n\tif (component) {\n\t\tunmountComponent(component, !unmountOnly);\n\t} else {\n\t\tif (node[ATTR_KEY] && node[ATTR_KEY].ref) node[ATTR_KEY].ref(null);\n\n\t\tif (!unmountOnly) {\n\t\t\tcollectNode(node);\n\t\t}\n\n\t\tif (node.childNodes && node.childNodes.length) {\n\t\t\tremoveOrphanedChildren(node.childNodes, unmountOnly);\n\t\t}\n\t}\n}", "updateSelfAndChildren(stateUpdate, options = {}) {\n if (!this.initialized) {\n return;\n }\n\n const {store, cascade} = options;\n Object.assign(this[store], stateUpdate);\n if (store !== `state` || this.shouldComponentUpdate(null, this[store])) {\n this.domPatcher.update(this.state);\n\n if (cascade) {\n for (const child of this.$panelChildren) {\n if (options.exclude !== child) {\n child.updateSelfAndChildren(stateUpdate, options);\n }\n }\n }\n }\n }", "function moveSubtree(subtree, xmove, ymove) {\n proccesByLevel(subtree, function(node) {\n move(node, xmove, ymove);\n });\n}", "function map_crud(croot, dest_obj, curr_path=[])\n\t{\n\t\tif (croot !== crud_root)\n\t\t{\n\t\t\tcurr_path = [...curr_path, croot.id]\n\t\t\tdest_obj[croot.id] = curr_path;\n\t\t}\n\n\t\tObject.values(croot.children).forEach(crud => map_crud(crud, dest_obj, curr_path));\n\t\treturn dest_obj;\n\t}", "assignPosition(node, position) {\n node.position = position \n if (node.children.length){\n for (let child_node of node.children){\n position = this.assignPosition(child_node, position)\n }\n }else{\n position++;\n }\n return position\n }", "function collapseAll(){\n function recurse(node){\n if (node.children) node.children.forEach(recurse); // recurse to bottom of tree\n if (node.children){ // hide children in _children then remove\n node._children = node.children;\n node.children = null;\n } \n }\n\n recurse(root);\n update();\n}", "function execute(selection) {\n selection.items.forEach(node => {\n goTurtleGo(node, selection);\n });\n}", "function recursivelyMapChildren(children, callback) {\n return React.Children.toArray(children).map((child, index) => {\n if (!React.isValidElement(child)) return child\n child = callback(child, child.key || index)\n if (child.props.children) {\n const newKids = recursivelyMapChildren(child.props.children, callback)\n if (newKids !== child.props.children)\n child = React.cloneElement(child, { key: child.key || index, children: newKids })\n }\n return child\n })\n}", "function updateReps(ex, action) {\n let n = ui.updateReps(ex, action);\n let id = ex.parentNode.parentNode.id;\n id = parseInt(id);\n\n exercise.updateRep(id, n);\n }", "visitMerge_update_delete_part(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "_postUpdate(updateParams, forceUpdate) {\n // @ts-ignore (TS2531) this method is only called internally when internalState is defined\n let subLayers = this.internalState.subLayers;\n const shouldUpdate = !subLayers || this.needsUpdate();\n\n if (shouldUpdate) {\n const subLayersList = this.renderLayers(); // Flatten the returned array, removing any null, undefined or false\n // this allows layers to render sublayers conditionally\n // (see CompositeLayer.renderLayers docs)\n\n subLayers = Object(_utils_flatten__WEBPACK_IMPORTED_MODULE_2__[\"flatten\"])(subLayersList, Boolean); // @ts-ignore (TS2531) this method is only called internally when internalState is defined\n\n this.internalState.subLayers = subLayers;\n }\n\n Object(_debug__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(TRACE_RENDER_LAYERS, this, shouldUpdate, subLayers); // populate reference to parent layer (this layer)\n // NOTE: needs to be done even when reusing layers as the parent may have changed\n\n for (const layer of subLayers) {\n layer.parent = this;\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes shipping selection from radio buttons
function getRadioSelection() { var selection = document.getElementsByTagName('input'); for (i = 0; i < selection.length; i++) { if (selection[i].checked) { shippingValue = selection[i].value; } } }
[ "function checkShippingMethod() {\n return $('#shipping-options option:selected').val();\n\n}", "static set radioButton(value) {}", "function setDefaultShippingMethod(){\n nlapiSetFieldValue(\"shipmethod\", \"4774\") // set default shipping method to Freight Other\n}", "function checkShipToAddress() {\n updateSelectedCheckboxView($.ship_to_address_checkbox);\n}", "function checkShipToStore() {\n updateSelectedCheckboxView($.ship_to_current_store_checkbox);\n}", "static get radioButton() {}", "function validateSwitch() {\n const radioChecked = document.querySelector('input[name=\"amount\"]:checked');\n const radioSwitchId = document.querySelector('input[name=\"view\"]:checked').id;\n\n\n if (radioChecked) {\n document.getElementById('switch').className = radioSwitchId;\n document.getElementById('radio-answer').innerHTML = \"You chose to donate \" + radioChecked.value + \" € \" + radioSwitchId;\n document.getElementById('radio-answer').style.color = \"\";\n } else {\n document.getElementById('radio-answer').innerHTML = \"Please chose an amount\";\n document.getElementById('radio-answer').style.color = \"red\";\n }\n}", "function defaultRadioButton(){\n var radioButton1 = document.getElementById(\"list-option-1\");\n radioButton1.checked = true;\n \n var radioButton2 = document.getElementById(\"list-option-2\");\n radioButton2.checked = false;\n \n var radioButton3 = document.getElementById(\"list-option-3\");\n radioButton2.checked = false;\n }", "radioSelectedHandler(e) {\r\n this.radioSelect = e.detail;\r\n }", "function updateRadio() {\n if (component.property !== undefined) {\n var value = model.get(component.property);\n\n for (var i = 0, len = options.length; i < len; i++) {\n if (options[i].value === value) {\n $inputs[i].attr(\"checked\", true);\n $options[i].addClass('checked');\n } else {\n $inputs[i].removeAttr(\"checked\");\n $options[i].removeClass('checked');\n }\n }\n }\n }", "function tiendaDisableShippingAddressControls(checkbox, form)\r\n{\r\n \r\n\tvar disable = false;\r\n if (checkbox.checked){\r\n disable = true;\r\n tiendaGetShippingRates( 'onCheckoutShipping_wrapper', form );\r\n }\r\n \r\n var fields = \"address_name;address_id;title;first_name;middle_name;last_name;company;tax_number;address_1;address_2;city;country_id;zone_id;postal_code;phone_1;phone_2;fax\";\r\n var fieldList = fields.split(';');\r\n\r\n// for(var index=0;index<fieldList.length;index++){\r\n// shippingControl = document.getElementById('shipping_input_'+fieldList[index]);\r\n// if(shippingControl != null){\r\n// shippingControl.disabled = disable;\r\n// }\r\n// }\r\n \r\n for(var index=0;index<fieldList.length;index++){\r\n \tbillingControl = document.getElementById('billing_input_'+fieldList[index]);\r\n shippingControl = document.getElementById('shipping_input_'+fieldList[index]);\r\n if(shippingControl != null){\r\n \t\tshippingControl.disabled = disable; \r\n if(billingControl != null)\r\n {\r\n \tif( fieldList[index] == 'zone_id' ) // special care for zones\r\n \t{\r\n \t\tif( disable )\r\n \t\t\ttiendaDoTask( 'index.php?option=com_tienda&format=raw&controller=checkout&task=getzones&prefix=shipping_input_&disabled=1&country_id='+document.getElementById('billing_input_country_id').value+'&zone_id='+document.getElementById('billing_input_zone_id').value, 'shipping_input_zones_wrapper', '');\r\n \t\telse\r\n \t\t\tshippingControl.disabled = false;\r\n \t}\r\n \telse // the rest of fields is OK the way they are handled now\r\n \t\t{\r\n \t\t\tif( shippingControl.getAttribute( 'type' ) != 'hidden' )\r\n \t\t\t\tshippingControl.value = disable ? billingControl.value : ''; \t\t\r\n \t\t}\r\n }\r\n }\r\n }\r\n \r\n tiendaDeleteGrayDivs();\r\n}", "function onShipSelected(event)\n{\n\t// Save selected starship model to User Variables\n\tvar shipModelUV = new SFS2X.SFSUserVariable(UV_MODEL, event.getUserData().model);\n\tsfs.send( new SFS2X.SetUserVariablesRequest([shipModelUV]) );\n\n\t// Show solar system selection scene, passing the room list to display the corresponding sprites\n\t// (see /src/scenes/solar-system-selection.js)\n\t// NOTE: the list was received automatically upon login\n\tcc.director.runScene(new SolarSystemSelectionScene(sfs.getRoomList()));\n}", "function modifyCurrentSelected(curSelected, curSection) {\n\n var topCurrentDisplay = document.getElementById(curSection.concat(\"1\")).getElementsByClassName('select-box-top__input');\n var middleCurrentDisplay = document.getElementById(curSection.concat(\"2\")).getElementsByClassName('select-box-middle__input');\n var lowerCurrentDisplay = document.getElementById(curSection.concat(\"3\")).getElementsByClassName('select-box-lower__input');\n var orderElementVar = [lowerCurrentDisplay, middleCurrentDisplay, topCurrentDisplay];\n\n //console.log(topCurrentDisplay);\n //console.log(middleCurrentDisplay);\n //console.log(lowerCurrentDisplay);\n\n // clear all previous selections in current display\n for (i = 0; i < topCurrentDisplay.length; i++) {\n topCurrentDisplay[i].checked = false;\n middleCurrentDisplay[i].checked = false;\n lowerCurrentDisplay[i].checked = false;\n }\n // get current section item order\n curOrder = api.parameters.get({name: curSection.concat(\" items\")}, \"CommPlugin_1\").data[0].value;\n curOrderArr = curOrder.split(',');\n // Update shapediver with new set of parameters and change current option for radio\n if (curSelected == \"alchol\") {\n topCurrentDisplay[0].checked = true; // top\n middleCurrentDisplay[2].checked = true; // middle\n lowerCurrentDisplay[2].checked = true; // lower\n var newOrder = \"1,1,100\";\n api.parameters.updateAsync({\n name: curSection.concat(\" items\"),\n value: newOrder\n });\n } else if (curSelected == \"phone\") {\n topCurrentDisplay[3].checked = true; // top\n middleCurrentDisplay[1].checked = true; // middle\n lowerCurrentDisplay[4].checked = true; // lower\n var newOrder = \"2,3,1\";\n api.parameters.updateAsync({\n name: curSection.concat(\" items\"),\n value: newOrder\n });\n } else if (curSelected == \"snacks\") {\n topCurrentDisplay[0].checked = true; // top\n middleCurrentDisplay[5].checked = true; // middle\n lowerCurrentDisplay[5].checked = true; // lower\n var newOrder = \"1,1,100\";\n api.parameters.updateAsync({\n name: curSection.concat(\" items\"),\n value: newOrder\n });\n }\n}", "function getMapStyleUI() {\n if ($(\"#rad1\")[0].checked) {\n return 'satellite';\n } else if ($(\"#rad2\")[0].checked) {\n return 'hybrid';\n } else if ($(\"#rad3\")[0].checked) {\n return 'terrain';\n } else if ($(\"#rad4\")[0].checked) {\n return 'roadmap';\n } \n }", "buildPaymentRequest(cart) {\n // Supported payment instruments\n const supportedInstruments = [{\n supportedMethods: (PAYMENT_METHODS)\n }];\n\n // Payment options\n const paymentOptions = {\n requestShipping: true,\n requestPayerEmail: true,\n requestPayerPhone: true\n };\n\n let shippingOptions = [];\n let selectedOption = null;\n\n let details = this.buildPaymentDetails(cart, shippingOptions, selectedOption);\n\n // Initialize\n let request = new window.PaymentRequest(supportedInstruments, details, paymentOptions);\n\n // When user selects a shipping address, add shipping options to match\n request.addEventListener('shippingaddresschange', e => {\n e.updateWith(_ => {\n // Get the shipping options and select the least expensive\n shippingOptions = this.optionsForCountry(request.shippingAddress.country);\n selectedOption = shippingOptions[0].id;\n let details = this.buildPaymentDetails(cart, shippingOptions, selectedOption);\n return Promise.resolve(details);\n });\n });\n\n // When user selects a shipping option, update cost, etc. to match\n request.addEventListener('shippingoptionchange', e => {\n e.updateWith(_ => {\n selectedOption = request.shippingOption;\n let details = this.buildPaymentDetails(cart, shippingOptions, selectedOption);\n return Promise.resolve(details);\n });\n });\n\n return request;\n }", "function onSelectionChange(){\n if (ui.amountBox.value > 0 && ui.icosBox.selectedIndex != 0 && ui.roundBox.selectedIndex != 0 && ui.currencyBox != 0) {\n onCalculateClick();\n }\n }", "function studentSelected() {\n userType = \"student\";\n sessionStorage.setItem(\"selection\", JSON.stringify({ \"studentRadio\": \"checked\" }));\n hideKeyElements();\n}", "function LoadSaveOption(source,opt,opt2,from) {\n if (source.checked == true) {\n $('input[name=\"'+opt2+from+'Sel\"]').each(function() {\n $(this).prop('checked',true);\n $(this).parent().parent().addClass('highlight');\n var dev = $(this).val();\n enableRow1(opt2+from,dev);\n });\n } else {\n $('input[name=\"'+opt2+from+'Sel\"]').each(function() {\n $(this).parent().parent().removeClass('highlight');\n $(this).prop('checked',false);\n var dev = $(this).val();\n enableRow1(opt2+from,dev);\n });\n }\n}", "function setSwitch() {\r\n if (document.getElementById(\"rb5\").checked) {\r\n legend.switchType = \"x\";\r\n } else {\r\n legend.switchType = \"v\";\r\n }\r\n legend.validateNow();\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fonction viderTable() vide les valeurs des cellules du tableau et appelle la fonction changerCouleur()
function viderTable() { var numRows = document.getElementById("table").rows.length; var numColumns = document.getElementById("table").rows[0].cells.length; for (var i = 0; i < numRows; i++) { for (var j = 0; j < numColumns; j++) { if (document.getElementById("table").rows[i].cells[j].innerHTML != '') { document.getElementById("table").rows[i].cells[j].innerHTML = ''; changerCouleur(i,j); } } } }
[ "function llenar_tabla_vistas_observaciones() {\n $(\"#modal_vista_observaciones\").show()\n $(\"#tabla_vistas_observaciones tr\").remove()\n\n var cuestionario, pregunta, indice_cues, indice_preg = 1;\n $.each(datos_mostrar, function (index, item) {\n //*********aqui se va a usar pendiente \n var fillas = $(\"<tr></tr>\")\n if (item.folio > 0) {\n //recorre las incidencias corregidas para reasignar la respuesta\n $.each(insidencias_corregidas, function (i, t) {\n if (t.insidencias == item.folio) {\n item.respuesta = t.solucionadas;\n }\n })\n if (index == 0) {\n cuestionario = item.cuestionario\n pregunta = item.pregunta\n \n $(\"#tabla_vistas_observaciones\").append(\n $(\"<tr>\").append(\n $(\"<th colspan='2'>\").append(cuestionario).css({ \"background-color\": \"#c5cfcb\" }))\n , $(\"<tr>\").append(\n $(\"<td >\").append(indice_preg).css({ \"background-color\": \"#c5cfaf\" })\n , $(\"<td >\").append(pregunta).css({ \"background-color\": \"#c5cfaf\" }))\n )\n indice_preg++\n }\n if (cuestionario == item.cuestionario) {\n\n if (pregunta != item.pregunta) {\n cuestionario = item.cuestionario\n pregunta = item.pregunta\n\n $(\"#tabla_vistas_observaciones\").append(\n $(\"<tr>\").append(\n $(\"<td>\").append(indice_preg).css({ \"background-color\": \"#c5cfaf\" })\n , $(\"<td>\").append(pregunta).css({ \"background-color\": \"#c5cfaf\" })\n ))\n indice_preg++\n }\n } else if (cuestionario != item.cuestionario) {\n cuestionario = item.cuestionario\n pregunta = item.pregunta\n $(\"#tabla_vistas_observaciones\").append(\n $(\"<tr>\").append(\n $(\"<th colspan='2'>\").append(cuestionario).css({ \"background-color\": \"#c5cfcb\" }))\n ,$(\"<tr>\").append(\n $(\"<td colspan='1'>\").append(indice_preg).css({ \"background-color\": \"#c5cfaf\" })\n , $(\"<td colspan='1'>\").append(pregunta).css({ \"background-color\": \"#c5cfaf\" }))\n )\n indice_preg++\n }\n $(\"#tabla_vistas_observaciones\").append(\n $(\"<tr>\").append(\n $(\"<td>\").append((index + 1)).css({ width: \"50px\", \"text-align\": \"center\" })\n , $(\"<td>\").append(item.observaciones).css({ \"background-color\": bg_estado(item.respuesta) })\n ))}\n })\n function bg_estado(valor) {\n if (valor == 1) { return \"rgb(149, 251, 0)\" }\n else if (valor == 0) { return \"red\" }\n else return \"\"\n }\n }", "function mostrarCursosCarreraQueImparte(){\n let listaCursosCarrera = getListaCursos();\n let sede = getSedeVisualizar();\n let nombreSede = sede[0];\n let cuerpoTabla = document.querySelector('#tblCursosCarrera tbody');\n cuerpoTabla.innerHTML = '';\n\n for (let i = 0; i < listaCursosCarrera.length; i++) {\n\n let sedeAsociada = listaCursosCarrera[i][7];\n\n for (let j = 0; j < sedeAsociada.length; j++) {\n\n if (sedeAsociada[j][0] == nombreSede) {\n let fila = cuerpoTabla.insertRow();\n let cCursoCarrera = fila.insertCell();\n let sCursoCarrera = document.createTextNode(listaCursosCarrera[i][1]);\n cCursoCarrera.appendChild(sCursoCarrera);\n\n }\n }\n\n }\n}", "function crearTablero(){\n //Inicializa el tablero\n for (f = 0; f < alt; f++){\n for (c = 0; c < anc; c++){\n tablero[f][c] = 0;\n visible[f][c] = 0;\n }\n }\n estado = 0;\n casillasVistas = 0;\n\n //Poner 99 minas\n for (mina = 0; mina < 99; mina++){\n //Busca una posicion aleatoria donde no haya mina\n var f;\n var c;\n do{\n f = Math.trunc((Math.random()*(15+1)));\n c = Math.trunc((Math.random()*(29+1)));\n //System.out.println(\"Coor(\" + f + \",\" + c +\")\");\n }while(tablero[f][c] == 9);\n //Pone la mina\n tablero[f][c] = 9;\n //Recorre el contorno de la mina e incrementa los contadores\n for (f2 = max(0, f-1); f2 < min(alt,f+2); f2++){\n for (c2 = max(0,c-1); c2 < min(anc,c+2); c2++){\n if (tablero[f2][c2] != 9){ //Si no es bomba\n tablero[f2][c2]++; //Incrementa el contador\n }\n }\n }\n }\n tableroConsola();\n}", "function mostrarCursosActiiQueImparte(){\n let listaCursosActii = getListaCursosActii();\n let sede = getSedeVisualizar();\n let nombreSede = sede[0];\n let cuerpoTabla = document.querySelector('#tblCursosActii tbody');\n cuerpoTabla.innerHTML = '';\n\n for (let i = 0; i < listaCursosActii.length; i++) {\n\n let sedeAsociada = listaCursosActii[i][5];\n\n for (let j = 0; j < sedeAsociada.length; j++) {\n \n if (sedeAsociada[j] == nombreSede) {\n let fila = cuerpoTabla.insertRow();\n\n let cCodigo = fila.insertCell();\n let cCursoActii = fila.insertCell();\n let sCodigo = document.createTextNode(listaCursosActii[i][0]);\n let sCursoActii = document.createTextNode(listaCursosActii[i][1]);\n cCodigo.appendChild(sCodigo);\n cCursoActii.appendChild(sCursoActii);\n\n }\n }\n\n }\n}", "function M_table(collection, tipo_tabla, ubicacion_html, headers, rows, types) {\n var objetivo = document.getElementById(ubicacion_html);\n\n var tbl = document.getElementById('tabla_automatica'); //Limpiar tabla antes de agregar la nueva.//\n if (tbl) tbl.parentNode.removeChild(tbl);\n\n var tabla = '<table id=\"tabla_automatica\" class=\"striped responsive-table centered\">';\n //Head.//\n tabla += '<thead>';\n tabla += '<tr>';\n headers.forEach(data => {\n tabla += '<th>' + data + '</th>';\n });\n tabla += '</tr>';\n tabla += '</thead>';\n //Body.//\n tabla += '<tbody id=\"tabla_dinamica_body\">';\n tabla += '</tbody>';\n tabla += '</table>';\n tabla += '<div class=\"progress col s8 offset-s2\"><div class=\"indeterminate\"></div ></div >'; //Loader\n\n objetivo.innerHTML = tabla;\n\n setTimeout(function () { \n document.getElementsByClassName('progress')[0].style.display = 'none';\n\n //Generar rows de la tabla.//\n if (tipo_tabla === 0) { //Si la coleccion es directa de firestore.//\n collection.forEach(doc => {\n var contador = 0;\n var body = '<tr>';\n rows.forEach(data => {\n if (types && types.length > 0) {\n switch (types[contador]) {\n case 'id':\n body += '<td><b>' + doc.data()[data] + '</b></td>';\n break;\n case 'money':\n body += '<td>$' + doc.data()[data] + '</td>';\n break;\n case 'date':\n var fecha = M_toMexDate(doc.data()[data]); //Convertir fechas a formato es-MEX\n body += '<td>' + fecha + '</td>';\n break;\n default:\n body += '<td>' + doc.data()[data] + '</td>';\n break;\n }\n } else {\n body += '<td>' + doc[data] + '</td>';\n }\n contador++;\n });\n /*body += '<td>' + doc.data().folio + '</td>';*/\n body += '</tr>';\n document.getElementById('tabla_dinamica_body').insertRow(0);\n document.getElementById('tabla_dinamica_body').rows[0].innerHTML = body;\n });\n } else if (tipo_tabla === 1) { //Si es un arreglo creado manualmente con M_objeto.//\n collection.forEach(doc => {\n var contador = 0;\n var body = '<tr>';\n rows.forEach(data => {\n if (types && types.length > 0) {\n switch (types[contador]) {\n case 'id':\n body += '<td><b>' + doc[data] + '</b></td>';\n break;\n case 'money':\n body += '<td>$' + doc[data] + '</td>';\n break;\n case 'date':\n var fecha = M_toMexDate(doc[data]); //Convertir fechas a formato es-MEX\n body += '<td>' + fecha + '</td>';\n\n break;\n default:\n body += '<td>' + doc[data] + '</td>';\n break;\n }\n } else {\n body += '<td>' + doc[data] + '</td>';\n }\n contador++;\n });\n body += '</tr>';\n document.getElementById('tabla_dinamica_body').insertRow(0);\n document.getElementById('tabla_dinamica_body').rows[0].innerHTML = body;\n });\n }\n }, 3000);\n\n\n\n /*collection.forEach(doc => {\n console.log(doc.data()); //<=== Crear una tabla html en la clase .vista-reporte y ver como llega a data\n });*/\n}", "function initTable() {\n \n var nbLignes = $(\"#nbLignes\").val();\n var nbColonnes = $(\"#nbColonnes\").val();\n var URL = $(\"#URL\").val();\n \n /* charger l'image en mémoire, puis une fois chargé, commencer a construire le tableau de canvas */\n var image = _loadImage(URL);\n \n image.onload = function() { \n \n _onImageLoad(nbLignes,nbColonnes,image); \n \n /* ajouter les ecouteurs de cliques sur les canvas et les bouttons ainsi les touches de clavier */\n var jeu = new Jeu(nbLignes,nbColonnes);\n _addAllListeners(jeu);\n \n };\n \n}", "function caricaTabellaRitenute(lista, flagEditabilitaRitenute) {\n var options = {\n bServerSide: false,\n bPaginate: false,\n bLengthChange: false,\n iDisplayLength: 5,\n bSort: false,\n bInfo: true,\n bAutoWidth: true,\n bFilter: false,\n bProcessing: true,\n aaData: lista,\n bDestroy: true,\n oLanguage: {\n sInfo: \"_START_ - _END_ di _MAX_ risultati\",\n sInfoEmpty: \"0 risultati\",\n sProcessing: \"Attendere prego...\",\n sZeroRecords: \"Non sono presenti oneri associati\",\n oPaginate: {\n sFirst: \"inizio\",\n sLast: \"fine\",\n sNext: \"succ.\",\n sPrevious: \"prec.\",\n sEmptyTable: \"Nessun dato disponibile\"\n }\n },\n aoColumnDefs: [\n {aTargets: [0], mData: function(source){\n return source.tipoOnere && source.tipoOnere.naturaOnere && source.tipoOnere.naturaOnere.codice + \" - \" + source.tipoOnere.naturaOnere.descrizione || \"\";\n }},\n {aTargets: [1], mData: function(source) {\n return source.tipoOnere && source.tipoOnere.codice + \" - \" + source.tipoOnere.descrizione || \"\";\n }},\n {aTargets: [2], mData: function(source) {\n return source.ordinativo && source.ordinativo.codice || \"\";\n }},\n {aTargets: [3], mData: function(source) {\n var importo = source.importoImponibile || 0;\n return importo.formatMoney();\n }, fnCreatedCell: function(nTd) {\n $(nTd).addClass(\"tab_Right\");\n }},\n {aTargets: [4], mData: function(source) {\n var aliquota = source.tipoOnere && source.tipoOnere.aliquotaCaricoSoggetto || 0;\n return aliquota.formatMoney();\n }, fnCreatedCell: function(nTd) {\n $(nTd).addClass(\"tab_Right\");\n }},\n {aTargets: [5], mData: function(source) {\n var importo = source.importoCaricoSoggetto || 0;\n return importo.formatMoney();\n }, fnCreatedCell: function(nTd) {\n $(nTd).addClass(\"tab_Right\");\n }},\n {aTargets: [6], mData: function(source) {\n var aliquota = source.tipoOnere && source.tipoOnere.aliquotaCaricoEnte || 0;\n return aliquota.formatMoney();\n }, fnCreatedCell: function(nTd) {\n $(nTd).addClass(\"tab_Right\");\n }},\n {aTargets: [7], mData: function(source) {\n var importo = source.importoCaricoEnte || 0;\n return importo.formatMoney();\n }, fnCreatedCell: function(nTd) {\n $(nTd).addClass(\"tab_Right\");\n }},\n {aTargets: [8], mData: function(source) {\n var importo = source.sommaNonSoggetta || 0;\n return importo.formatMoney();\n }, fnCreatedCell: function(nTd) {\n $(nTd).addClass(\"tab_Right\");\n }}\n ]\n };\n\n // Se posso editare le ritenute, allora aggiungo le opzioni\n if(flagEditabilitaRitenute) {\n options.aoColumnDefs[9] = {aTargets: [9], mData: function(source) {\n if(!source.azioni) {\n source.azioni = \"<div class='btn-group'>\" +\n \"<button data-toggle='dropdown' class='btn dropdown-toggle'>Azioni<span class='caret'></span></button>\" +\n \"<ul class='dropdown-menu pull-right'>\" +\n \"<li><a href='#' class='aggiornaRitenuta'>aggiorna</a></li>\" +\n \"<li><a href='#' class='eliminaRitenuta'>elimina</a></li>\" +\n \"</ul>\" +\n \"</div>\";\n }\n return source.azioni;\n }, fnCreatedCell: function(nTd, sData, oData, iRow) {\n $(nTd).find(\".aggiornaRitenuta\")\n .substituteHandler(\"click\", function(e) {\n apriModaleAggiornaRitenuta(e, oData, nTd);\n })\n .end()\n .find(\".eliminaRitenuta\")\n .substituteHandler(\"click\", function(e) {\n apriModaleEliminaRitenuta(e, iRow, oData);\n })\n .end()\n .addClass(\"tab_Right\");\n }};\n }else{\n \t options.aoColumnDefs[9] = {aTargets:[9], mData: function() {\n return \"\";\n }};\n }\n options.aoColumnDefs[10] = {aTargets:[10], mData: function() {\n return \"<td><i class=\\\"icon icon-spin icon-refresh spinner icon-2x\\\"></i>\";\n }};\n \n \n\n $(\"#tabellaRitenute\").dataTable(options);\n fieldsToKeep.keepOriginalValues();\n var campiInTesta = $(\"#importoCassaPensioniRitenuteDocumentoDocumento, #importoRivalsaRitenuteDocumentoDocumento, #importoIVARitenuteDocumentoDocumento\");\n if(flagEditabilitaRitenute){\n \t$(\"#pulsanteRitenute\").removeClass(\"hide\");\n \t$(\"#divInserimentoOnere\").removeClass(\"hide\");\n \t$(\"#modaleAggiornamentoRitenuteContainer\").removeClass(\"hide\");\n \tcampiInTesta.attr(\"readOnly\", false);\n }else{\n \t$(\"#pulsanteRitenute\").addClass(\"hide\");\n \t$(\"#divInserimentoOnere\").addClass(\"hide\");\n \t$(\"#modaleAggiornamentoRitenuteContainer\").addClass(\"hide\");\n \tcampiInTesta.attr(\"readOnly\", true);\n }\n }", "function reglas(tablero, x, y, contador) {\n\t\tvar celda = 0;\n\n\t\t// Si esta muerta y tiene 3 vecinas vivas\n\t\tif(tablero[x][y] === 0 && contador === 3) {\n\t\t\tcelda = 1;\n\t\t}\n\t\t//si esta viva y tiene 2 o 3 vecinas vivas sobrevive \n\t\telse if(tablero[x][y] === 1 && (contador <= 3 && contador > 1)) {\n\t\t\tcelda = 1;\n\t\t}\n\t\treturn celda;\n\t}", "function tableruler(){\n\tvar selectBug=false; // firefox 1.5.0.1. bug\n\tif(navigator.userAgent.indexOf(\"Firefox\")!=-1){\n\t\tvar userAgentBits=navigator.userAgent.split(\"Firefox/\");\n\t\tvar userAgentBits2=userAgentBits[1].split(\" \");\n\t\tvar ffNumber=userAgentBits2[0];\n\t\tvar ffNumberArray=ffNumber.split(\".\");\n\t\tvar realNumber= ffNumberArray[0]+\".\"+ffNumberArray[1]+ffNumberArray[2];\n\t\tif(ffNumberArray[3]<10){\n\t\t\trealNumber = realNumber+\"0\"+ffNumberArray[3];\n\t\t}\n\t\telse{\n\t\t\trealNumber = realNumber+ffNumberArray[3];\n\t\t}\n\t\tif(realNumber<1.5005){\n\t\t\tselectBug=true;\n\t\t}\n\t}\n\tif(selectBug==false){\n\t\tvar tables=document.getElementsByTagName('table');\n\t\tfor (var i=0; i<tables.length; i++) {\n\t\t\tif( (tables[i].className=='contenttable') || (tables[i].className=='contenttable_lmenu') || (tables[i].className=='summarytable') || (tables[i].className=='contenttable_max') || (tables[i].className=='monthtable')){\n\t\t\t\tvar trs=tables[i].getElementsByTagName('tr');\n\t\t\t\tfor(var j=0;j<trs.length;j++){\n\t\t\t\t\ttrs[j].onmouseover=function(){\n\t\t\t\t\t\tif(this.className){\n\t\t\t\t\t\t\tthis.oldClassName=this.className;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tthis.oldClassName='';\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.className='ruled';\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\ttrs[j].onmouseout=function(){\n\t\t\t\t\t\tif(this.oldClassName){\n\t\t\t\t\t\t\tthis.className=this.oldClassName;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tthis.className='';\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\t}\n}", "function calcularTotalComprobacion(){\r\n\t\tvar totalComprobacion = 0;\r\n\t\t\r\n\t\tvar eur = $(\"#valorDivisaEUR\").val();\r\n\t\tvar usd = $(\"#valorDivisaUSD\").val();\r\n\t\t\r\n\t\tvar tablaLength = obtenTablaLength(\"comprobacion_table\");\r\n\t\t\r\n\t\tfor(var i = 1; i <= tablaLength; i++){\r\n\t\t\tvar divisa = parseInt($(\"#row_divisa\"+i).val());\r\n\t\t\tswitch(divisa){\r\n\t\t\t\tcase 2:\r\n\t\t\t\t\ttotalComprobacion+= (limpiaCantidad($(\"#row_totalPartida\"+i).val()) * usd);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase 3:\r\n\t\t\t\t\ttotalComprobacion+= (limpiaCantidad($(\"#row_totalPartida\"+i).val()) * eur);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tdefault:\r\n\t\t\t\t\ttotalComprobacion+= (limpiaCantidad($(\"#row_totalPartida\"+i).val()));\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tasignaVal(\"totalComprobacion\", totalComprobacion);\r\n\t\t\r\n\t\tasignaText(\"span_totalComprobacion\", totalComprobacion,\"number\");\r\n\t}", "function criarItensTabela(dados) {\n\n\tconst linha = tabela.insertRow()\n\n\tconst colunaClienteNome = linha.insertCell(0)\n\tconst colunaPedidoDados = linha.insertCell(1)\n\tconst colunaPedidoHora = linha.insertCell(2)\n\n\tconst dados_pedido = dados.pedido_dados.substr(0, 10) + \" ...\"\n\n\tcolunaClienteNome.appendChild(document.createTextNode(dados.cliente_nome))\n\tcolunaPedidoDados.appendChild(document.createTextNode(dados_pedido.replace(/<br>/g, \" \")))\n\n\tconst data = new Date(Number(dados.pedido_data))\n\tconst date = moment(data).format('HH:mm:ss')\n\tcolunaPedidoHora.appendChild(document.createTextNode(date))\n\n\tcolunaClienteNome.style = \"text-align: center\"\n\tcolunaPedidoDados.style = \"text-align: center\"\n\tcolunaPedidoHora.style = \"text-align: center\"\n\n\tcriarBotoesTabela(linha, dados)\n\n\t//ordemCrescente()\n}", "function Table({\n integrantes,\n borrarIntegrante,\n editarIntegrante,\n imprimirImagen,\n}) {\n return (\n <div className=\"mx-2\">\n <table className=\"table mt-5 table-striped table-bordered text-center\">\n <thead>\n <tr>\n {/*Se nombran las columnas a usar en la tabla*/}\n <th scope=\"col\">#</th>\n <th scope=\"col\">Nombre</th>\n <th scope=\"col\">Acción</th>\n </tr>\n </thead>\n {/*Mediante el cuerpo de la tabla*/}\n <tbody>\n {/*Recorremos el arreglo si no se encuentra vacio*/}\n {integrantes.length > 0 ? (\n integrantes.map((integrante) => {\n return (\n //Declaramos un identificador unico para cada integrante\n <tr key={integrante.id}>\n <th scope=\"row\">{integrante.id}</th>\n <td className=\"text-capitalize text-primary\">\n {/*Mostramos Cuando recibamos el evento clic usaremos el metodo imrpimir para generar una imagen aleatoria sobre el ID de integrante seleccionado*/}\n <div\n onClick={() => imprimirImagen(integrante.id)}\n style={{ cursor: \"pointer\" }}\n >\n <u>{integrante.nombre}</u>\n </div>\n </td>\n {/*Agregamos un boton para borrar y a su vez esperamos un evento clic para ejecutar la funcion borrar Integrante con parametro ID de integrante registrado*/}\n <td className=\"d-flex justify-content-around\">\n <button\n type=\"button\"\n className=\"btn btn-danger btn-sm d-flex\"\n onClick={() => borrarIntegrante(integrante.id)}\n >\n {/*Importamos un icono para el boton*/}\n <i className=\"material-icons\" style={{ fontSize: 20 }}>\n delete_forever\n </i>\n </button>\n {/*Creamos un boton para la accion editar y le damos su icono correspondiente*/}\n <button\n type=\"button\"\n className=\"btn btn-warning btn-sm d-flex\"\n onClick={() => editarIntegrante(integrante.id)}\n >\n <i className=\"material-icons\" style={{ fontSize: 20 }}>\n edit\n </i>\n </button>\n </td>\n </tr>\n );\n })\n ) : (\n //Si se encuentran vacio los integrantes con tamaño de 3 columnas informamos que se encuentra vacio\n <tr>\n <td colSpan=\"3\">Vacio</td>\n </tr>\n )}\n </tbody>\n </table>\n </div>\n );\n}", "function initColtura() {\n for (var i = 0; i < vm.user.colture.length; i++) {\n if (vm.user.colture[i].sensore == vm.numSensore) {\n vm.colturaCorrente = vm.user.colture[i];\n break;\n }\n }\n for (var i = 0; i < vm.user.sensori.length; i++) {\n if (vm.user.sensori[i].idSensore == vm.numSensore) {\n vm.sensoreCorrente = vm.user.sensori[i];\n break;\n }\n }\n\n }", "function User_Insert_Type_de_couche_Type_de_couches0(Compo_Maitre)\n{\n\n/*\n***** INFOS ******\n\nNbr d'esclaves = 4\n\nId dans le tab: 96;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 97;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 98;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\nId dans le tab: 99;\nsimple\nNbr Jointure: PAS DE JOINTURE;\n\n******************\n*/\n\n var Table=\"typecouche\";\n var CleMaitre = TAB_COMPO_PPTES[93].NewCle;\n var NomCleMaitre = DePrefixerChamp(Compo_Maitre.getCle());\n var tc_nom=GetValAt(96);\n if (!ValiderChampsObligatoire(Table,\"tc_nom\",TAB_GLOBAL_COMPO[96],tc_nom,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tc_nom\",TAB_GLOBAL_COMPO[96],tc_nom))\n \treturn -1;\n var note=GetValAt(97);\n if (!ValiderChampsObligatoire(Table,\"note\",TAB_GLOBAL_COMPO[97],note,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"note\",TAB_GLOBAL_COMPO[97],note))\n \treturn -1;\n var couleur=GetValAt(98);\n if (!ValiderChampsObligatoire(Table,\"couleur\",TAB_GLOBAL_COMPO[98],couleur,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"couleur\",TAB_GLOBAL_COMPO[98],couleur))\n \treturn -1;\n var tc_sansilots=GetValAt(99);\n if (!ValiderChampsObligatoire(Table,\"tc_sansilots\",TAB_GLOBAL_COMPO[99],tc_sansilots,false))\n \treturn -1;\n if (!ValiderChampsType(Table,\"tc_sansilots\",TAB_GLOBAL_COMPO[99],tc_sansilots))\n \treturn -1;\n var Req=\"insert into \"+Table+\" \";\nvar TabInsertionEnPlus=new Array();\n Req+=\"(\"+NomCleMaitre+\",tc_nom,note,couleur,tc_sansilots\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[0]:\"\")+\")\";\n Req+=\" values (\"+CleMaitre+\",\"+(tc_nom==\"\" ? \"null\" : \"'\"+ValiderChaine(tc_nom)+\"'\" )+\",\"+(note==\"\" ? \"null\" : \"'\"+ValiderChaine(note)+\"'\" )+\",\"+(couleur==null ? \"null\" : \"'\"+ValiderChaine(couleur)+\"'\" )+\",\"+(tc_sansilots==\"\" ? \"null\" : \"'\"+ValiderChaine(tc_sansilots)+\"'\" )+\"\"+(TabInsertionEnPlus.length!=0?\",\"+TabInsertionEnPlus[1]:\"\")+\")\";\n\n if (pgsql_update(Req)==0)\n\talert(\"Echec lors de l'insertion\");\nreturn CleMaitre;\n\n}", "function changeProductMarketTable() {\r\n\r\n\t\t$( \".dataTable\" ).find( \"input[type='text']\" ).addClass( \"inputTextTable\" );\r\n\t\tvar submit = $( \".dataTable\" ).find( \"input[type='submit']\" ).addClass( \"inputSubmitTable\" );\r\n\r\n\t\t// Add buy all button\r\n\t\tvar buyAll = $( \"<input class='buyAllSubmit' type='submit' value='All' />\" );\r\n\t\tbuyAll.bind( \"click\", function() {\r\n\t\t\tvar v = $(this).parent().parent().prev().prev().text();\r\n\t\t\t$(this).parent().children( \"input[type='text']\" ).val( v );\r\n\t\t\treturn( false );\r\n\t\t});\r\n\t\tbuyAll.insertBefore( submit );\r\n\r\n\t\t// Hide buyAs select\r\n\t\t$( \".dataTable\" ).find( \"select\" ).each( function() {\r\n\t\t\tvar cell = $(this).parent();\r\n\t\t\tvar buyAs = $( \"<div class='toRemove buyAsTable'>Buy as Citizen</div>\" );\r\n\r\n\t\t\tif( getValue( \"configProductMarketSelection\" ) == \"true\" ) {\r\n\t\t\t\tbuyAs.insertBefore( cell.children().first() );\r\n\t\t\t\tcell.parent().css({ \"background-color\" : \"#ecffec\" });\r\n\t\t\t\tcell.contents().eq(0).remove();\r\n\t\t\t\tcell.children( \"br\" ).remove();\r\n\t\t\t\t$(this).hide();\r\n\r\n\t\t\t} else $(this).addClass( \"customSelectList\" );\r\n\t\t});\r\n\r\n\t\t// Add help message\r\n\t\tvar divT = $( \"<div class='helpFlagMessage'>Click on country flag to open the monetary market (only price column)</div>\" );\r\n\t\tdivT.insertBefore( \".dataTable\" );\r\n\r\n\t\t// Resize table\r\n\t\t$( \".dataTable\" ).addClass( \"dataTableMod\" );\r\n\r\n\t\t// Redesign table\r\n\t\t// Headers\r\n\t\t$( \".dataTable > tbody > tr:first-child > td\" ).addClass( \"dataTableHeaders\" );\r\n\t\tvar trHead = $( \".dataTable\" ).find( \"tr\" ).eq(0).children();\r\n\t\ttrHead.eq(0).css({ \"width\" : \"70px\" });\r\n\t\ttrHead.eq(1).css({ \"width\" : \"180px\" });\r\n\t\ttrHead.eq(2).css({ \"width\" : \"50px\" });\r\n\t\ttrHead.eq(3).css({ \"width\" : \"85px\" });\r\n\r\n\t\t// Product list\r\n\t\t$( \".dataTable\" ).find( \".product\" ).each( function() {\r\n\t\t\tvar cell = $(this).parent();\r\n\t\t\tvar img = cell.find( \"img\" );\r\n\t\t\tcell.children().remove()\r\n\r\n\t\t\tcell.append( \"<img class='blockProduct 'src='\"+ IMGPRODBG +\"' />\" );\r\n\t\t\tcell.append( img.eq(0).addClass( \"productImage\" ) );\r\n\t\t\tif( img.length > 1 ) { cell.append( img.eq(1).addClass( \"productQuality\" ) ); }\r\n\t\t});\r\n\r\n\t\t// Name list and total price\r\n\t\t$( \".dataTable\" ).find( \"a\" ).each( function() {\r\n\r\n\t\t\t// Name redesign\r\n\t\t\tvar cell = $(this).parent();\r\n\t\t\tcell.children( \".currencyFlag\" ).next().remove(); // Remove BR\r\n\t\t\tcell.children( \".currencyFlag\" ).addClass( \"dataTableNameFlag\" );\r\n\r\n\t\t\tvar div = $( \"<div class='blockSeller'></div>\" );\r\n\t\t\tvar imgSeller = cell.children( \"img\" ).eq(1);\r\n\t\t\timgSeller.addClass( \"dataTableSeller\" );\r\n\t\t\tdiv.append( imgSeller );\r\n\r\n\t\t\tvar playerName = $( \"<div class='playerName'></div>\" ).append( cell.children( \":lt(2)\" ) );\r\n\t\t\tdiv.append( playerName );\r\n\t\t\tif( cell.children().length > 0 ) {\r\n\t\t\t\tplayerName.css({ \"margin-top\" :\"3px\" });\r\n\r\n\t\t\t\tcell.children().eq(0).remove();\r\n\t\t\t\tvar stockName = $( \"<div class='stockName'></div>\" ).append( cell.children().eq(0) );\r\n\t\t\t\tdiv.append( stockName );\r\n\t\t\t}\r\n\t\t\tcell.append( div );\r\n\r\n\t\t\tvar nextCell = cell.next().next();\r\n\t\t\tvar flag = nextCell.children( \"img\" );\r\n\t\t\tflag.addClass( \"monetaryMarketFlag\" );\r\n\r\n\t\t\t// Add link to monetary market\r\n\t\t\tvar url = getCurrentServer() + URLMonetaryMarket + \"?buyerCurrencyId=\"+ IDByImageCountry( flag.attr( \"src\" ) ) +\"&sellerCurrencyId=0\";\r\n\t\t\tvar link = $( \"<a class='linkMonetaryMarket' href='\"+ url +\"' target='_blank'></a>\" );\r\n\t\t\tlink.insertBefore( flag );\r\n\t\t\tlink.append( flag );\r\n\r\n\t\t\t// Total price\r\n\t\t\tvar priceItem = parseFloat( nextCell.children( \"b\" ).text() );\r\n\t\t\tvar n = ( parseInt( parseInt( cell.next().text() ) * priceItem * 100 ) )/100;\r\n\t\t\tvar money = nextCell.contents().last().text();\r\n\t\t\tnextCell.append( \"<div class='totalPriceProductMarket'>\"+ n +\" \"+ money +\"</div>\" );\r\n\t\t});\r\n\t}", "function createStyledTable(){\r\n if (!validateMode()) return;\r\n\r\n if (cl!=null)\r\n { \r\n if (cl.tagName==\"TD\")\r\n obj = cl.parentElement.parentElement.parentElement;\r\n }else{\r\n elem=getEl(\"TABLE\",Composition.document.selection.createRange().parentElement());\r\n\tif(elem!=null) obj = elem;\r\n }\r\n \r\n if (!obj)\r\n {\r\n alert(\"Установите курсор в ячееку таблицы!\");\r\n\r\n }else{\r\n\tdtbl = showModalDialog(\"/images/mifors/ws/w_stable.htm\", tables,\"dialogWidth:250px; dialogHeight:200px; center:1; help:0; resizable:0; status:0\");\r\n\tif(dtbl==null) return;\r\n\tvar xsltTable = new ActiveXObject(\"Microsoft.XMLDOM\");\r\n\txsltTable.async = false;\r\n\txsltTable.load(dtbl);\r\n\tif (xsltTable.parseError.errorCode != 0) {\r\n\t var myErr = xsltTable.parseError;\r\n\t alert(\"You have error \" + myErr.reason);\r\n\treturn;\r\n\t} \r\n\tvar sxmlDoc = new ActiveXObject(\"Microsoft.XMLDOM\");\r\n\tsxmlDoc.async=false;\r\n\ttra=new String(obj.outerHTML);\r\n\tstate=0;\r\n\tout=\"\";\r\n\tfor(i=0;i<tra.length;i++){\r\n\t\tch=tra.charAt(i);\r\n\t\tswitch (state){\r\n\t\t\tcase 0:if(ch=='<') state=1; break;\r\n\t\t\tcase 1:if(ch=='>') state=0;\r\n\t\t\t\tif(ch=='=') state=2;break;\r\n\t\t\tcase 2:if(ch!='\"'){ out+='\"'; state=4} else state=3;break;\r\n\t\t\tcase 3:if(ch=='\"') state=1;break;\r\n\t\t\tcase 4:if(ch==' ') {out+='\"';state=1}\r\n\t\t\t\tif(ch=='>') {out+='\"';state=0};break\r\n\t\t}\r\n\t\tout+=ch;\r\n\t}\r\n\tsxmlDoc.loadXML(out);\r\n\tif (sxmlDoc.parseError.errorCode != 0) {\r\n\t var myErr = sxmlDoc.parseError;\r\n\t alert(\"You have error \" + myErr.reason);\r\n\treturn;\r\n\t} \r\n\treplacement=sxmlDoc.transformNode(xsltTable);\r\n\tobj.outerHTML=replacement;\r\n\tComposition.document.recalc();\r\n\tComposition.focus();\r\n }\r\n}", "function LlenarTablaCategoria() {\n\ttable = $('#table_categoria').DataTable({\n\t\tpageLength: 10,\n\t\tresponsive: true,\n\t\tprocessing: true,\n\t\tajax: \"../controller/CategoriaController.php?operador=listar_categoria\",\n\t\tcolumns: [\n\t\t\t{ data: 'op' },\n\t\t\t{ data: 'id' },\n\t\t\t{ data: 'nombre' },\n\t\t\t{ data: 'descripcion' },\n\t\t\t{ data: 'estado' }\n\t\t]\n\t});\n}", "function createTable() {\n let table = [];\n adeudo = 0;\n importe = 0;\n\n let num_orders = pagosTicket.length;\n if (num_orders !== 0) {\n total = parseFloat(pagosTicket[0].monto);\n importe = 0;\n for (let i = 0; i < num_orders; i++) {\n let children = [];\n children.push(<td hidden>{pagosTicket[i].id_pago}</td>);\n children.push(<td>${pagosTicket[i].abono}</td>);\n children.push(<td>{pagosTicket[i].fecha_pago}</td>);\n children.push(<td>{pagosTicket[i].asesor}</td>);\n children.push(<td><button className=\"btn btn-success btn-ticket\" onClick={() => printTicket(pagosTicket[i].id_pago)}>Ticket</button></td>);\n table.push(<tr>{children}</tr>);\n\n importe += Number(pagosTicket[i].abono);\n }\n\n importe = parseFloat(toFixedTrunc(importe, 2));\n\n adeudo = total - importe;\n } else {\n adeudo = total;\n }\n\n adeudo = parseFloat(adeudo);\n console.log('ADEUDO', adeudo);\n if (adeudo > 1) adeudo = parseFloat(adeudo.toFixed(2));\n\n return table;\n}", "function prepareDecorationTable(table, assets)\n{\n jq.each(table, function(item) {\n if(table[item].type == \"pattern\")\n {\n table[item].fill = assets.getResult(table[item].fill_id);\n }\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
isDirty returns a boolean value depending on whether the model instance attributes have been changed or not. Dirty model instances can be used to determine if such an instance should be saved.
function isDirty(){ return this.__isDirty__; }
[ "_checkEmberModelsOnDirty() {\n let checkresult = false;\n\n let editformIsDirty = this.get('model.editform.hasDirtyAttributes');\n\n let dataobject = this.get('model.dataobject');\n\n let attributes = dataobject.get('attributes');\n let changedAttributes = attributes.filterBy('hasDirtyAttributes');\n let attributesIsDirty = changedAttributes.length > 0 ? true : false;\n\n let association = this.get('store').peekAll('fd-dev-association');\n let changedAssociations = association.filterBy('hasDirtyAttributes');\n let associationIsDirty = changedAssociations.length > 0 ? true : false;\n\n let aggregation = this.get('store').peekAll('fd-dev-aggregation');\n let changedAggregation = aggregation.filterBy('hasDirtyAttributes');\n let aggregationIsDirty = changedAggregation.length > 0 ? true : false;\n\n if (editformIsDirty || attributesIsDirty || associationIsDirty || aggregationIsDirty) {\n checkresult = true;\n }\n\n return checkresult;\n }", "_checkIfDirty(){\n if (this._isDirty === true){\n this._isDirty = false;\n this._refresh();\n }\n }", "isDirty(slot, addr) {\n return this.sets[addr.idx][slot].dirty;\n }", "checkDirty() {\n\t\tif (this.input.value && this.input.value.length > 0) {\n\t\t\tthis.el.classList.add(this.cssClasses.IS_DIRTY)\n\t\t} else {\n\t\t\tthis.el.classList.remove(this.cssClasses.IS_DIRTY)\n\t\t}\n\t}", "function isModified() {\n\tif (is_modified)\n\t\tif (!confirm('Data on this page has been modified.\\nIf you proceed, changes wont\\'t be saved.\\nProceed anyway?'))\n\t\t\treturn false;\n\treturn true;\n}", "getIsNewMark() {\n return this.__isNew === true;\n }", "haveChanges() {\n return this.code !== this.codeFromTableau;\n }", "function GetFormDirtyFields(executionContext) {\n try {\n //Get the form context\n var formContext = executionContext.getFormContext();\n var attributes = formContext.data.entity.attributes.get()\n for (var i in attributes) {\n var attribute = attributes[i];\n if (attribute.getIsDirty()) {\n Xrm.Utility.alertDialog(\"Attribute dirty: \" + attribute.getName());\n }\n }\n }\n catch (e) {\n Xrm.Utility.alertDialog(e.message);\n }\n}", "shouldUpdateState(params) {\n return params.changeFlags.propsOrDataChanged;\n }", "function getFormModifiedState (){\n\t\treturn formModified;\n\t}", "function hasObjectChanged(value, state) {\n var json = angular.toJson(value || \"\");\n var oldJson = state.json;\n state.json = json;\n return !oldJson || json !== oldJson;\n }", "modelVerification(model) {\n if (model && model.constructor === RestBaseModel.constructor) {\n this.state.modelClass = model;\n this.state.modelConfig = this.state.modelClass[`${this.state.modelClass.name}_config`];\n this.state.addUpdateModel = new this.state.modelClass();\n return true;\n }\n return false;\n }", "isNew() {\n return this.getIsNewMark();\n }", "get isCompleteUpdate() {\n // XXX: Bug 514040: _ums.isCompleteUpdate doesn't work at the moment\n if (this.activeUpdate.patchCount > 1) {\n var patch1 = this.activeUpdate.getPatchAt(0);\n var patch2 = this.activeUpdate.getPatchAt(1);\n\n return (patch1.URL == patch2.URL);\n } else {\n return (this.activeUpdate.getPatchAt(0).type == \"complete\");\n }\n }", "function isEditable() {\n return (current && current.isOwner && !current.frozen);\n}", "function checkFormState (){\n\t\tif (formModified && showUnsavedChangesPopup)\n\t\t\treturn 'There are unsaved changes';\n\t}", "dirty() {\n this.signal();\n }", "function eq(vm) {\n\tvar observerData = vm._mobxObserver;\n\n\tif (observerData.stale)\n\t\treturn false;\t// Re-render.\n\telse if (observerData.eq)\n\t\treturn observerData.eq.apply(this, arguments); // Let diff() choose.\n\telse\n\t\treturn true;\t// By default: no re-render.\n}", "function checkUnsavedChanges()\n{\n\tif(store.dirty)\n\t\t{\n\t\tif(confirm(config.messages.unsavedChangesWarning))\n\t\t\tsaveChanges();\n\t\t}\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure all props option syntax are normalized into the Objectbased format.
function normalizeProps (options, vm) { var props = options.props; if (!props) { return } var res = {}; var i, val, name; if (Array.isArray(props)) { i = props.length; while (i--) { val = props[i]; if (typeof val === 'string') { name = camelize(val); res[name] = { type: null }; } else { warn('props must be strings when using array syntax.'); } } } else if (isPlainObject(props)) { for (var key in props) { val = props[key]; name = camelize(key); res[name] = isPlainObject(val) ? val : { type: val }; } } else { warn( "Invalid value for option \"props\": expected an Array or an Object, " + "but got " + (toRawType(props)) + ".", vm ); } options.props = res; }
[ "function normalizeOptions(options) {\n options = options || {};\n return {\n concatMessages: options.concatMessages === undefined ? true : Boolean(options.concatMessages),\n format: options.format === undefined ? isomorphic_node_1.format\n : (typeof options.format === \"function\" ? options.format : false),\n };\n}", "function normaliseOpenOptions(options) {\n var _a, _b;\n // Validate `encoding`.\n let encoding = (_a = options === null || options === void 0 ? void 0 : options.encoding) !== null && _a !== void 0 ? _a : 'ISO-8859-1';\n assertValidEncoding(encoding);\n // Validate `readMode`.\n let readMode = (_b = options === null || options === void 0 ? void 0 : options.readMode) !== null && _b !== void 0 ? _b : 'strict';\n if (readMode !== 'strict' && readMode !== 'loose') {\n throw new Error(`Invalid read mode ${readMode}`);\n }\n // Return a new normalised options object.\n return { encoding, readMode };\n}", "function normalizeOptions(options) {\n try {\n options.schemeDefinition = getSchemeDefinition(options);\n }\n catch (e) {\n console.error(e.message);\n throw e; // rethrow to stop process\n }\n}", "function validateObjectArgument(vObj){\n if(!(typeof vObj === 'object')) throw 'superSelect Requires an object argument';\n var keyCount = 0, objAryCount = 0, arys = [];\n for (keyCount; keyCount < Object.keys(vObj).length; keyCount++){\n if(Array.isArray(obj[Object.keys(vObj)[keyCount]])){\n arys.push(obj[Object.keys(vObj)[keyCount]]);\n objAryCount ++;\n }\n }\n if (objAryCount < 2) throw 'object argument requires two array properties';\n //Check arrays for object contents\n var arraysOfobjectOnlyCount = 0;\n arys.forEach(function(element, idx, ary){\n element.forEach(function(el, idx2, sary){\n\n }\n )\n });\n }", "function normaliseCreateOptions(options) {\n var _a, _b;\n // Validate `fileVersion`.\n let fileVersion = (_a = options === null || options === void 0 ? void 0 : options.fileVersion) !== null && _a !== void 0 ? _a : 0x03;\n if (!file_version_1.isValidFileVersion(fileVersion))\n throw new Error(`Invalid file version ${fileVersion}`);\n // Validate `encoding`.\n let encoding = (_b = options === null || options === void 0 ? void 0 : options.encoding) !== null && _b !== void 0 ? _b : 'ISO-8859-1';\n assertValidEncoding(encoding);\n // Return a new normalised options object.\n return { fileVersion, encoding };\n}", "_mergeOptions(oldOptions, newOptions) {\n const origKeys = new Set(Object.keys(oldOptions))\n const mergedOptions = { ...oldOptions, ...newOptions }\n\n Object.keys(mergedOptions).forEach( (key) => {\n if (!origKeys.has(key)) {\n console.error(`Unexpected options parameter \"${key}\" will be removed. This should never happen - please investigate.`) // this should not happen\n }\n const value = mergedOptions[key]\n if (!origKeys.has(key) || !value || (Array.isArray(value) && value.length == 0)) delete mergedOptions[key];\n })\n return mergedOptions\n }", "function _sanitizeOption(options, defaults, property, predicate) {\n // set the property to the default value if the predicate returned false\n if (!predicate(options[property])) {\n options[property] = defaults[property];\n }\n }", "_getPartialProperties(props) {\n const options = this.get(); // remove attributes from the prop that are not in the partial\n\n Object.keys(options).forEach(name => {\n if ((0, _TypeCheck.isUndef)(props[name])) {\n delete options[name];\n }\n });\n return options;\n }", "function standardizeValidationObj(validation = {}) {\n const output = {};\n const customKeys = Object.keys(validation).filter(\n key => validatorKeys.indexOf(key) < 0\n );\n customKeys.forEach(key => {\n output[key] = validation[key];\n });\n\n validatorsArray.forEach(validator => {\n const { key, showKey, otherKeys, buildConfig, configKeys = [] } = validator;\n const currentValue = validation[key];\n if (!currentValue) {\n return;\n }\n let outputValue = {};\n // if current value is a function, assume custom implementation and skip buildConfig\n if (currentValue instanceof Function) {\n output[key] = currentValue;\n return;\n }\n // or has keys associated with a config object, use this\n if (isConfigObj(currentValue, configKeys)) {\n outputValue = currentValue;\n } else {\n outputValue.valid = currentValue;\n }\n\n if (showKey && typeof validation[showKey] !== \"undefined\") {\n const showValue = validation[showKey];\n if (isValidationObj(showValue)) {\n output[showKey] = showValue;\n } else {\n outputValue.show = validation[showKey];\n }\n }\n if (otherKeys) {\n (Array.isArray(otherKeys) ? otherKeys : [otherKeys]).forEach(otherKey => {\n if (otherKey && typeof validation[otherKey] !== \"undefined\") {\n const otherValue = validation[otherKey];\n (isValidationObj(otherValue) ? output : outputValue)[\n otherKey\n ] = otherValue;\n }\n });\n }\n output[key] = buildConfig ? buildConfig(outputValue) : outputValue;\n });\n\n return output;\n}", "static vsamValidateOptions(options) {\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options, ZosFiles_messages_1.ZosFilesMessages.missingFilesCreateOptions.message);\n /* If our caller does not supply these options, we supply default values for them,\n * so they should exist at this point.\n */\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options.dsorg, ZosFiles_messages_1.ZosFilesMessages.missingVsamOption.message + \"dsorg\");\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options.alcunit, ZosFiles_messages_1.ZosFilesMessages.missingVsamOption.message + \"alcunit\");\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options.primary, ZosFiles_messages_1.ZosFilesMessages.missingVsamOption.message + \"primary\");\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options.secondary, ZosFiles_messages_1.ZosFilesMessages.missingVsamOption.message + \"secondary\");\n // validate specific options\n for (const option in options) {\n if (options.hasOwnProperty(option)) {\n switch (option) {\n case \"dsorg\":\n if (!ZosFiles_constants_1.ZosFilesConstants.VSAM_DSORG_CHOICES.includes(options.dsorg.toUpperCase())) {\n throw new imperative_1.ImperativeError({\n msg: ZosFiles_messages_1.ZosFilesMessages.invalidDsorgOption.message + options.dsorg\n });\n }\n break;\n case \"alcunit\":\n if (!ZosFiles_constants_1.ZosFilesConstants.VSAM_ALCUNIT_CHOICES.includes(options.alcunit.toUpperCase())) {\n throw new imperative_1.ImperativeError({\n msg: ZosFiles_messages_1.ZosFilesMessages.invalidAlcunitOption.message + options.alcunit\n });\n }\n break;\n case \"primary\":\n case \"secondary\":\n // Validate maximum allocation quantity\n if (options[option] > ZosFiles_constants_1.ZosFilesConstants.MAX_ALLOC_QUANTITY) {\n throw new imperative_1.ImperativeError({\n msg: ZosFiles_messages_1.ZosFilesMessages.maximumAllocationQuantityExceeded.message + \" \" +\n ZosFiles_messages_1.ZosFilesMessages.commonFor.message + \" '\" + option + \"' \" + ZosFiles_messages_1.ZosFilesMessages.commonWithValue.message +\n \" = \" + options[option] + \".\"\n });\n }\n break;\n case \"retainFor\":\n if (options[option] < ZosFiles_constants_1.ZosFilesConstants.MIN_RETAIN_DAYS ||\n options[option] > ZosFiles_constants_1.ZosFilesConstants.MAX_RETAIN_DAYS) {\n throw new imperative_1.ImperativeError({\n msg: imperative_1.TextUtils.formatMessage(ZosFiles_messages_1.ZosFilesMessages.valueOutOfBounds.message, {\n optionName: option,\n value: options[option],\n minValue: ZosFiles_constants_1.ZosFilesConstants.MIN_RETAIN_DAYS,\n maxValue: ZosFiles_constants_1.ZosFilesConstants.MAX_RETAIN_DAYS\n })\n });\n }\n break;\n case \"retainTo\":\n case \"volumes\":\n case \"storclass\":\n case \"mgntclass\":\n case \"dataclass\":\n case \"responseTimeout\":\n // no validation at this time\n break;\n default:\n throw new imperative_1.ImperativeError({ msg: ZosFiles_messages_1.ZosFilesMessages.invalidFilesCreateOption.message + option });\n } // end switch\n }\n } // end for\n }", "function validateExtraPropsFunctionality(instance, partialProps) {\n if (partialProps === void 0) {\n partialProps = {};\n }\n\n var extraProps = ['followCursor'];\n extraProps.forEach(function (prop) {\n if (popper.hasOwnProperty(partialProps, prop) && !instance.__extraProps[prop]) {\n warnWhen(prop === 'followCursor', FOLLOW_CURSOR_WARNING);\n }\n });\n}", "_validateAndParseCommandArguments() {\n const validationErrors = this._validateCommandArguments();\n\n if (validationErrors.length > 0) {\n _forEach(validationErrors, (error) => {\n throw error;\n });\n }\n }", "function normalizeRules(rules) {\n // if falsy value return an empty object.\n var acc = {};\n Object.defineProperty(acc, '_$$isNormalized', {\n value: true,\n writable: false,\n enumerable: false,\n configurable: false\n });\n if (!rules) {\n return acc;\n }\n // Object is already normalized, skip.\n if (isObject(rules) && rules._$$isNormalized) {\n return rules;\n }\n if (isObject(rules)) {\n return Object.keys(rules).reduce(function (prev, curr) {\n var params = [];\n var preserveArrayParams = false;\n if (rules[curr] === true) {\n params = [];\n }\n else if (Array.isArray(rules[curr])) {\n params = rules[curr];\n preserveArrayParams = true;\n }\n else if (isObject(rules[curr])) {\n params = rules[curr];\n }\n else {\n params = [rules[curr]];\n }\n if (rules[curr] !== false) {\n prev[curr] = buildParams(curr, params, preserveArrayParams);\n }\n return prev;\n }, acc);\n }\n /* istanbul ignore if */\n if (typeof rules !== 'string') {\n warn('rules must be either a string or an object.');\n return acc;\n }\n return rules.split('|').reduce(function (prev, rule) {\n var parsedRule = parseRule(rule);\n if (!parsedRule.name) {\n return prev;\n }\n prev[parsedRule.name] = buildParams(parsedRule.name, parsedRule.params);\n return prev;\n }, acc);\n}", "static get parseOptionTypes() {\n return {\n ...super.parseOptionTypes,\n ext: 'Array',\n };\n }", "function cleanOptions(content, options) {\n\t\tvar lines = content.match(/[^\\r\\n]+/g);\n\t\tvar output = options;\n\t\tvar setlist = [\"\"];\n\t\tvar optionsets = {};\n\t\toptionsets[\"\"] = {};\n\t\tvar i;\n\n\t\tfor (i=0; i<lines.length; i++) {\n\t\t\tvar matches = lines[i].match(/^!!!verovio([^\\s]*):\\s*(.*)\\s*$/);\n\t\t\tif (!matches) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (matches[1] == \"-parameter-group\") {\n\t\t\t\tsetlist.push(matches[2]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvar mm = matches[2].match(/^\\s*([^\\s]+)\\s+(.*)\\s*$/);\n\t\t\tif (!mm) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvar m = matches[1].match(/^-([^\\s]+)\\s*$/);\n\t\t\tvar set = \"\";\n\t\t\tif (m) {\n\t\t\t\tset = m[1];\n\t\t\t}\n\t\t\tif (typeof optionsets[set] === 'undefined') {\n\t\t\t\toptionsets[set] = {};\n\t\t\t}\n\t\t\toptionsets[set][mm[1]] = mm[2];\n\t\t}\n\n\t\tfor (i=0; i<setlist.length; i++) {\n\t\t\tif (!optionsets[setlist[i]]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvar keys = Object.keys(optionsets[setlist[i]]);\n\t\t\tvar j;\n\t\t\tvar key;\n\t\t\tfor (j=0; j<keys.length; j++) {\n\t\t\t\tif (typeof output[keys[j]] !== 'undefined') {\n\t\t\t\t\tdelete output[keys[j]];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn output;\n\t}", "checkUnknownOptions() {\n const { rawOptions, globalCommand } = this.cli;\n if (!this.config.allowUnknownOptions) {\n for (const name of Object.keys(rawOptions)) {\n if (name !== '--' &&\n !this.hasOption(name) &&\n !globalCommand.hasOption(name)) {\n console.error(`error: Unknown option \\`${name.length > 1 ? `--${name}` : `-${name}`}\\``);\n process.exit(1);\n }\n }\n }\n }", "convert(propTypes, attrName, attrValue) {\n const propName = Object.keys(propTypes)\n .find(key => key.toLowerCase() == attrName);\n let value = attrValue;\n if (attrValue === 'true' || attrValue === 'false')\n value = attrValue == 'true';\n else if (!isNaN(attrValue) && attrValue !== '')\n value = +attrValue;\n else if (/^{.*}/.exec(attrValue))\n value = JSON.parse(attrValue);\n return {\n name: propName ? propName : attrName,\n value: value\n };\n }", "function set_object_props(obj, from, whitelist) {\n\tvar wl = whitelist.split(\",\");\n\tfor(var i=0; i<wl.length; i++) {\n\t\tvar prop = wl[i];\n\t\tif (undefined !== obj[prop] && undefined !== from[prop]) {\n\t\t\t//console.log(\"WL update prop %s obj:%s -> to %s\", prop, obj[prop], from[prop]);\n\t\t\tobj[prop] = from[prop];\n\t\t}\n\t}\n}", "function isPropValid()\n{\n\n}", "function process(shema, obj) {\n\n\t\t\tvar\tpropName = shema.inputProp || shema.outputProp,\n\t\t\t\tobjC = obj[propName],\n\t\t\t\totype = _.type(objC);\n\n\t\t\tif(shema.type === 'object') {\n\t\t\t\tif(otype.is('object')) {\n\t\t\t\t\tfor(var prop in shema.value) {\n\t\t\t\t\t\tif(shema.value.hasOwnProperty(prop)) {\n\t\t\t\t\t\t\tif(!process(shema.value[prop], objC)) {\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}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t_this.emitError('obj', obj);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(shema.type === 'obj-template') {\n\t\t\t\tif(!otype.is('object')) {\n\t\t\t\t\t_this.emitError('obj', obj);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tfor(var prop in obj) {\n\t\t\t\t\tif(obj.hasOwnProperty(prop)) {\n\t\t\t\t\t\tif(!process(shema.value[0], obj[prop])) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(shema.type === 'array') {\n\t\t\t\tif(!otype.is('array')) {\n\t\t\t\t\t_this.emitError('arr', obj);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tfor(var prop in shema.value) {\n\t\t\t\t\tif(shema.value.hasOwnProperty(prop)) {\n\t\t\t\t\t\tif(!process(shema.value[prop], obj[prop])) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(shema.type === 'arr-template') {\n\t\t\t\tif(!otype.is('array')) {\n\t\t\t\t\t_this.emitError('arr', obj);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tfor(var prop in obj) {\n\t\t\t\t\tif(obj.hasOwnProperty(prop)) {\n\t\t\t\t\t\tif(!process(shema.value[0], obj[prop])) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(shema.type === 'embedded') {\n\n\t\t\t\tvar toleranceFlag = true;\n\n\t\t\t\tif(shema.value === 'I') {\n\t\t\t\t\tobj = parseInt(obj);\n\t\t\t\t\tshema.value = i;\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 'F') {\n\t\t\t\t\tobj = parseFloat(obj);\n\t\t\t\t\tshema.value = f;\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 'D') {\n\t\t\t\t\tobj = +obj;\n\t\t\t\t\tshema.value = d;\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 'B') {\n\t\t\t\t\tobj = !!obj;\n\t\t\t\t\tshema.value = b;\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 'U') {\n\t\t\t\t\tobj = undefined;\n\t\t\t\t\tshema.value = u;\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 'S') {\n\t\t\t\t\tobj += '';\n\t\t\t\t\tshema.value = s;\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 'N') {\n\t\t\t\t\tobj = null;\n\t\t\t\t\tshema.value = n;\n\t\t\t\t}\n\n\t\t\t\tif(shema.value === 'i') {\n\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 'f') {\n\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 'd') {\n\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 'b') {\n\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 'u') {\n\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 's') {\n\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 'n') {\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t\telse {\n\t\t\t\t_this.error.wtf();\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Separates an array of objects into three subgroups of inputtype objects (switch and buttons), outputtype objects (LEDs), and other components.
function separateGroup(group) { var inputs = []; var components = []; var outputs = []; for (var i = 0; i < group.length; i++) { var object = group[i]; if (object instanceof Switch || object instanceof Button || object instanceof Clock) inputs.push(object); else if (object instanceof LED) outputs.push(object); else components.push(object); } return {inputs:inputs, components:components, outputs:outputs}; }
[ "function command_array_creator(arr){\n let new_arr = [];\n arr.forEach(str => {\n new_arr.push(command_extractor(str));\n })\n return new_arr;\n //if ['turn off 812,389 through 865,874', 'toggle 205,417 through 703,826'] was given as input\n //the function would return [ [ 'turnoff', [ 812, 389 ], [ 865, 874 ] ], [ 'toggle', [ 205, 417 ], [ 703, 826 ] ] ]\n}", "function convert(array) {\n return array.reduce((acc, layer) => {\n //console.log(layer.getProperties().group);\n acc.push({\n layer: layer,\n name: layer.getProperties().name,\n title: layer.getProperties().title,\n visibility: layer.getProperties().visible,\n group: layer.getProperties().group\n });\n return acc;\n }, []);\n}", "splitRows() {\n let rows = [];\n const shields = this.state.shields;\n\n for(var i = 0; i < shields.length; i+=6) {\n let oneRow = [];\n oneRow.push(shields.slice(i, i+6).map( (shield, idx) => {\n return (\n <div className=\"two columns\" key={i + idx} >\n <Shield\n shieldColor={shield.value.shieldColor}\n partition={shield.value.partition}\n partitionColor={shield.value.partitionColor}\n piece={shield.value.piece}\n pieceColor={shield.value.pieceColor}\n meubles={shield.value.meubles}\n />\n </div> )\n }));\n rows.push(oneRow.map(itm => {\n return <div className=\"row\" key={'r'+i}>{itm}</div>\n }))\n }\n return rows;\n }", "split() {\n\n\t\tconst min = this.min;\n\t\tconst mid = this.getCenter(c);\n\t\tconst halfSize = this.size * 0.5;\n\n\t\tconst children = this.children = [\n\n\t\t\tnull, null,\n\t\t\tnull, null,\n\t\t\tnull, null,\n\t\t\tnull, null\n\n\t\t];\n\n\t\tlet i, combination;\n\n\t\tfor(i = 0; i < 8; ++i) {\n\n\t\t\tcombination = pattern[i];\n\n\t\t\tchildren[i] = new this.constructor(\n\n\t\t\t\tnew Vector3(\n\t\t\t\t\t(combination[0] === 0) ? min.x : mid.x,\n\t\t\t\t\t(combination[1] === 0) ? min.y : mid.y,\n\t\t\t\t\t(combination[2] === 0) ? min.z : mid.z\n\t\t\t\t),\n\n\t\t\t\thalfSize\n\n\t\t\t);\n\n\t\t}\n\n\t}", "function addSplitsJoins(module)\n{\n var allInputs = [];\n var allOutputs = [];\n module.nodes.forEach(function(n)\n {\n n.inputPorts.forEach(function(i)\n {\n allInputs.push(',' + i.value.join() + ',');\n });\n n.outputPorts.forEach(function(i)\n {\n allOutputs.push(',' + i.value.join() + ',');\n });\n });\n\n var allInputsCopy = allInputs.slice();\n var splits = {};\n var joins = {};\n allInputs.forEach(function(input) {\n gather(\n allOutputs,\n allInputsCopy,\n input,\n 0,\n input.length,\n splits,\n joins);\n });\n\n for (var join in joins) {\n var signals = join.slice(1, -1).split(',');\n for (var i in signals) {\n signals[i] = Number(signals[i]);\n }\n var outPorts = [{'key': 'Y', 'value': signals}];\n var inPorts = [];\n joins[join].forEach(function(name) {\n var value = getBits(signals, name);\n inPorts.push({'key': name, 'value': value});\n });\n module.nodes.push({'key': '$join$' + join,\n 'hide_name': 1,\n 'type': '$_join_',\n 'inputPorts': inPorts,\n 'outputPorts': outPorts});\n }\n\n for (var split in splits) {\n signals = split.slice(1, -1).split(',');\n for (var i in signals) {\n signals[i] = Number(signals[i]);\n }\n var inPorts = [{'key': 'A', 'value': signals}];\n var outPorts = [];\n splits[split].forEach(function(name) {\n var value = getBits(signals, name);\n outPorts.push({'key': name, 'value': value});\n });\n module.nodes.push({'key': '$split$' + split,\n 'hide_name': 1,\n 'type': '$_split_',\n 'inputPorts': inPorts,\n 'outputPorts': outPorts});\n }\n}", "function makeInstruments(){\n if(colorIsSet === true){\n switch(mode){\n case \"1\":\n makeBlock();\n break;\n \n case \"2\":\n makeArch();\n break;\n \n case \"3\":\n makeBall();\n break;\n \n case \"4\":\n makeRippler();\n break;\n \n case \"5\":\n makeBubbler();\n break;\n \n case \"6\":\n makeSpinner();\n break;\n }\n }\n}", "function make_filters_ux(){\n const ret = [];\n ret.push(T('label', {}, 'Filter:'));\n console.log('in make filters ux', this.state);\n Object.entries(this.state.filter_btns).forEach(([field, value]) => {\n console.log('mapping with ', field, value);\n ret.push(T('select', {\n key: field,\n value,\n onChange: (ev) => this.filter_ids(null, field, ev.target.value),\n },\n T('option', {value: ''}, `<${field}>`),\n CFG.filter_options[field].map(name => T('option', {key: name, value: name}, name)),\n ));\n });\n ret.push(T('input', {\n type: 'text',\n size: 40,\n value: this.state.filter_text,\n onChange: (ev) => this.filter_ids(ev.target.value)\n }));\n return ret;\n}", "function changeTypes(arr) {\n\tconst a = [];\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tif(typeof arr[i] === \"number\") (arr[i] % 2 === 0) ? a.push(arr[i] + 1) : a.push(arr[i]);\n\t\tif (typeof arr[i] === \"string\") a.push(arr[i].slice(0, 1).toUpperCase() + arr[i].slice(1) + \"!\");\n\t\tif (typeof arr[i] === \"boolean\") (!arr[i]) ? a.push(true) : a.push(false);\t\n\t}\n\treturn a;\n}", "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 }", "function splitConnectedComponents(volume, label_struct) {\n if(!label_struct) {\n label_struct = labelConnectedComponents(volume);\n }\n var count = label_struct.count\n , labels = label_struct.labels\n , components = new Array(count);\n for(var i=0; i<count; ++i) {\n components[i] = new core.DynamicVolume();\n }\n for(var iter=core.beginStencil(volume, stencils.CROSS_STENCIL); iter.hasNext(); iter.next()) {\n var idx = iter.ptrs[0];\n var label = labels[idx];\n var phase = volume.phases[idx];\n var distance = volume.distances[idx];\n if(label < 0) {\n for(var i=1; i<7; ++i) {\n if(labels[iter.ptrs[i]] >= 0) {\n components[labels[iter.ptrs[i]]].push(iter.coord[0], iter.coord[1], iter.coord[2], distance, 0);\n }\n }\n } else {\n components[label].push(iter.coord[0], iter.coord[1], iter.coord[2], distance, phase);\n }\n }\n for(var i=0; i<count; ++i) {\n components[i] = repair.removeDuplicates(components[i]);\n }\n return components;\n}", "function AlgorithmForSliders( elements , type_attrb , type , criteria) {\n\t// console.clear()\n\t// console.log( \"\\t - - - - - AlgorithmForSliders - - - - -\" )\n\t// console.log( \"\" )\n\t// console.log( \"elements:\" )\n\t// console.log( elements )\n\t// console.log( \"type_attrb: \" + type_attrb )\n\t// console.log( \"type: \"+type )\n\t// console.log( \"criteria: \"+criteria )\n\n\t// // ( 1 )\n // // get visible sigma nodes|edges\n if(isUndef(elements)) return {\"steps\":0 , \"finalarray\":[]};\n \n var elems = [];/*=elements.filter(function(e) {\n return e[type_attrb]==type;\n });*/\n\n for(var e in elements) {\n if( elements[e][type_attrb]==type ) {\n if(getGraphElement(e)) {\n elems.push(elements[e])\n } \n }\n }\n if(elems.length==0) return {\"steps\":0 , \"finalarray\":[]};\n\n // identifying if you received nodes or edges\n var edgeflag = ( !isNaN(elems.slice(-1)[0].id) || elems.slice(-1)[0].id.split(\";\").length>1)? true : false;\n // // ( 2 )\n // // extract [ \"edgeID\" : edgeWEIGHT ] | [ \"nodeID\" : nodeSIZE ] \n // // and save this into edges_weight | nodes_size\n var elem_attrb=[]\n for (var i in elems) {\n e = elems[i]\n id = e.id\n elem_attrb[id]=e[criteria]\n // pr(id+\"\\t:\\t\"+e[criteria])\n }\n // pr(\"{ id : size|weight } \")\n // pr(elem_attrb)\n\n // // ( 3 )\n // // order dict edges_weight by edge weight | nodes_size by node size\n var result = ArraySortByValue(elem_attrb, function(a,b){\n return a-b\n //ASCENDENT\n });\n // pr(result.length)\n // // ( 4 )\n // // printing ordered ASC by weigth\n // for (var i in result) {\n // r = result[i]\n // idid = r.key\n // elemattrb = r.value\n // pr(idid+\"\\t:\\t\"+elemattrb)\n // // e = result[i]\n // // pr(e[criteria])\n // }\n var N = result.length\n // var magnitude = (\"\"+N).length //order of magnitude of edges|nodes\n // var exponent = magnitude - 1\n // var steps = Math.pow(10,exponent) // #(10 ^ magnit-1) steps\n // var stepsize = Math.round(N/steps)// ~~(visibledges / #steps)\n\n\n //var roundsqrtN = Math.round( Math.sqrt( N ) );\n var steps = Math.round( Math.sqrt( N ) );\n var stepsize = Math.round( N / steps );\n\n // pr(\"-----------------------------------\")\n // pr(\"number of visible nodes|edges: \"+N); \n \n // pr(\"number of steps : \"+steps)\n // pr(\"size of one step : \"+stepsize)\n // pr(\"-----------------------------------\")\n \n\n var finalarray = []\n var counter=0\n for(var i = 0; i < steps*2; i++) {\n // pr(i)\n var IDs = []\n for(var j = 0; j < stepsize; j++) {\n if(!isUndef(result[counter])) {\n k = result[counter].key\n // w = result[counter].value\n // pr(\"\\t[\"+counter+\"] : \"+w)\n IDs.push(k)\n }\n counter++;\n }\n if(IDs.length==0) break;\n \n finalarray[i] = (edgeflag)? IDs : IDs.map(Number);\n }\n // pr(\"finalarray: \")\n return {\"steps\":finalarray.length,\"finalarray\":finalarray}\n}", "function forAllGroupInputs (handleInput, options) {\n options = options || {}\n _.find(options.inputGroups || _.compact(ractive.get('inputGroups')), function (group, groupIndex) {\n return _.find(_.compact(group.inputs), function (input, inputIndex) {\n if (input.subInputs) {\n if (options.handleInputGroups) {\n handleInput(input, groupIndex, inputIndex)\n }\n return _.find(input.subInputs, function (subInput, subInputIndex) {\n return handleInput(subInput.input, groupIndex, inputIndex, subInputIndex)\n })\n } else {\n return handleInput(input, groupIndex, inputIndex)\n }\n })\n })\n }", "function splitObjectIntoGrid() {\n\n for (let j = 0; j < obj.numRows; j++) {\n for (let i = 0; i < obj.numCols; i++) {\n\n let moleculeCollection = molecules.filter(molecule =>\n molecule.position.x > (i * colWidth) &&\n molecule.position.x < ((i + 1) * colWidth) &&\n molecule.position.y > j * rowHeight &&\n molecule.position.y < (j + 1) * rowHeight\n ).map(molecule => molecule.index);\n\n checkIntersections(moleculeCollection);\n }\n }\n}", "function convert(sample, dataset) {\n let points = [[], [], []];\n if (dataset == \"SHREC2019\") {\n //Code for unistroke mutlipath gestures \n sample.paths[\"Palm\"].strokes.forEach((point, stroke_id) => { \n points[PLANE_XY].push(new Point(point.x, point.y, point.t, point.stroke_id));\n points[PLANE_YZ].push(new Point(point.y, point.z, point.t, point.stroke_id));\n points[PLANE_ZX].push(new Point(point.z, point.x, point.t, point.stroke_id));\n });\n //Code for Unistroke unipath gestures\n } else { \n sample.strokes.forEach((point, stroke_id) => { \n points[PLANE_XY].push(new Point(point.x, point.y, point.t, point.stroke_id));\n points[PLANE_YZ].push(new Point(point.y, point.z, point.t, point.stroke_id));\n points[PLANE_ZX].push(new Point(point.z, point.x, point.t, point.stroke_id));\n });\n }\n return points;\n }", "function command_executor(arr, light_constructor){\n command_array = command_array_creator(arr);\n light_array = light_array_creator(light_constructor);\n command_array.forEach( command => {\n cmd = command[0],\n [x1, y1] = command[1],\n [x2, y2] = command[2];\n\n for( i = x1; i <= x2; i++){\n for( j = y1; j <= y2; j++){\n light_array[i][j][cmd]();\n }\n }\n })\n return light_array\n}", "function createPluginsList(ssid, plugins) {\n var widgets = []\n for (var i in plugins) {\n widgets.push({\n type: 'panel',\n mode: 'horizontal',\n label: false,\n scroll: false,\n padding: 0,\n height: 20,\n alphaStroke: 0,\n innerPadding: false,\n widgets: [\n {\n type: 'button',\n mode: 'toggle',\n padding: -1,\n width: 20,\n value: plugins[i].active,\n alphaStroke: 0,\n alphaFillOff: 0.15,\n alphaFillOn: 0.15,\n id: `strip_${ssid}_plugin_${plugins[i].id}_active`,\n label: '^circle',\n css: '--color-text: var(--color-background); --color-text-on: var(--color-widget);',\n address: '/strip/plugin/activate',\n preArgs: [ssid, plugins[i].id],\n typeTags: 'i'\n },\n {\n type: 'button',\n mode: 'tap',\n padding: -1,\n expand: true,\n alphaStroke: 0,\n alphaFillOff: 0.15,\n linkId: '>> plugin_modal',\n id: `strip_${ssid}_plugin_${plugins[i].id}`,\n label: plugins[i].name,\n address: '/strip/plugin/descriptor',\n preArgs: ssid,\n doubleClick: true,\n on: plugins[i].id\n }\n ]\n })\n\n }\n\n _receive('/EDIT', 'plugins_' + ssid, {\n widgets: widgets,\n })\n\n}", "function divideFeaturesByType(shapes, properties, types) {\n var typeSet = utils.uniq(types);\n var layers = typeSet.map(function(geoType) {\n var p = [],\n s = [],\n dataNulls = 0,\n rec;\n\n for (var i=0, n=shapes.length; i<n; i++) {\n if (types[i] != geoType) continue;\n if (geoType) s.push(shapes[i]);\n rec = properties[i];\n p.push(rec);\n if (!rec) dataNulls++;\n }\n return {\n geometry_type: geoType,\n shapes: s,\n data: dataNulls < p.length ? new DataTable(p) : null\n };\n });\n return layers;\n}", "function switchButton(panels, symbol, state) {\n for (const panel of panels) {\n for (const button of panel.buttons) {\n if (button.symbol === symbol) {\n if (button instanceof LightButton) {\n button.switch(state);\n }\n }\n }\n }\n}", "function setActions () {\n let rem = document.getElementsByClassName('remove');\n let ch = document.getElementsByClassName('switch');\n for(let y = 0; y < ch.length; y++){\n ch[y].addEventListener('click', change);\n }\n for(let i = 0; i < rem.length; i++){\n rem[i].addEventListener('click', remove);\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build Top down hierarchy from root category to category of member to be created
function buildCategoryParentList (category) { var parentCategory = categoryToParentMap[category]; /* * Push hierarchical parents of selected category, including itself on stack * (bottom up from category of member to be created) */ parentList.push(category); while(!jQuery.isEmptyObject(parentCategory)) { parentList.push(parentCategory); parentCategory = categoryToParentMap[parentCategory]; } // Build Top down hierarchy from root hierarchy to category of member to be created parentList.reverse(); }
[ "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 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}", "function cgAddChild(tree, ul, cgn) {\n var li = document.createElement(\"li\");\n ul.appendChild(li);\n li.className = \"closed\";\n\n var code = document.createElement(\"code\");\n\n if (cgn.Callees != null) {\n $(li).addClass(\"expandable\");\n\n // Event handlers and innerHTML updates don't play nicely together,\n // hence all this explicit DOM manipulation.\n var hitarea = document.createElement(\"div\");\n hitarea.className = \"hitarea expandable-hitarea\";\n li.appendChild(hitarea);\n\n li.appendChild(code);\n\n var childUL = document.createElement(\"ul\");\n li.appendChild(childUL);\n childUL.setAttribute('style', \"display: none;\");\n\n var onClick = function() {\n document.cgAddChildren(tree, childUL, cgn.Callees);\n hitarea.removeEventListener('click', onClick)\n };\n hitarea.addEventListener('click', onClick);\n\n } else {\n li.appendChild(code);\n }\n code.innerHTML += \"&nbsp;\" + makeAnchor(cgn.Func);\n return li\n}", "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 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 }", "build() {\n\t\tconst self = this;\n\n\t\tself.buildTags();\n\t\tself.buildTree();\n\t}", "function createMainCategory() {\r\n var id = document.getElementById(\"main-category\");\r\n id.innerHTML = \"\";\r\n for (var i = 0; i < dict.mainCategory.length; i++) {\r\n id.appendChild(createMainCategoryButton(dict.mainCategory[i]));\r\n }\r\n id.firstChild.classList.add(\"menu-first-category-box\");\r\n updateViewMainCategory();\r\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 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 }", "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 }", "getDropdownCategories() {\n if (!this.state.category.itemCategory.name) {\n // category breadcrumb was erased\n let newCategory = this.state.category;\n newCategory.dropdown = newCategory.categoryList;\n\n this.setState({\n category: newCategory\n });\n return;\n }\n\n const apiUrl = `/category_descendant_tree/${\n this.state.category.itemCategory.id\n }`;\n\n service\n .get(apiUrl)\n .then(response => {\n let descendantTree = response.data;\n\n let dropdown_list = descendantTree.map(descendant => {\n return {\n key: descendant.id,\n value: descendant.name,\n text: descendant.name\n };\n });\n\n let newCategory = this.state.category;\n newCategory.dropdown = dropdown_list;\n\n this.setState({\n category: newCategory\n });\n })\n .catch(e => {\n throw e;\n });\n }", "constructChildren() {\n\t\t\n\t\t// this.children.push();\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}", "getItemCategoryBreadcrumb() {\n const apiUrl = `/category_tree/${this.state.category.itemCategory.id}`;\n\n service\n .get(apiUrl)\n .then(response => {\n //set item category\n let categoryTree = response.data;\n\n let breadcrumb = [];\n for (let i = categoryTree.length - 1; i >= 0; i--) {\n breadcrumb[categoryTree.length - 1 - i] = categoryTree[i];\n }\n\n let newCategory = this.state.category;\n newCategory.breadcrumb = breadcrumb;\n\n this.setState({\n category: newCategory\n });\n })\n .catch(e => {\n throw e;\n });\n }", "function setChildrenAndParents() {\n\tif(relations) {\n\t\trelations.forEach(function(r) {\n\t\t\tvar target = document.getElementById(r.target.entity.name + \"_\" + r.target.name)\n\t\t\tappendClass(target, \"child_to_\" + r.source.entity.name + \"_\" + r.source.name)\n\n\t\t\tvar source = document.getElementById(r.source.entity.name + \"_\" + r.source.name)\n\t\t\tappendClass(source, \"parent_to_\" + r.target.entity.name + \"_\" + r.target.name)\n\n\t\t\tvar targetAsset = document.getElementById('asset_' + r.target.entity.name)\n\t\t\tappendClass(targetAsset, \"child_to_\" + r.source.entity.name + \"_\" + r.source.name)\n\t\t\tappendClass(targetAsset, \"parent_to_\" + r.target.entity.name + \"_\" + r.target.name)\n\t\t\t\n\t\t\tvar sourceAsset = document.getElementById('asset_' + r.source.entity.name)\n\t\t\tappendClass(sourceAsset, \"child_to_\" + r.source.entity.name + \"_\" + r.source.name)\n\t\t\tappendClass(sourceAsset, \"parent_to_\" + r.target.entity.name + \"_\" + r.target.name)\n\t\t})\n\t}\n\tif(relations2) {\n\t\trelations2.forEach(function(r) {\n\t\t\tif(r.associations) {\n\t\t\t\tr.associations.forEach(function(a, i) {\n\t\t\t\t\tassociationElem = document.getElementById(getAssociationId(a))\n\t\t\t\t\tappendClass(associationElem, \"child_to_\" + r.source.entity.name + \"_\" + r.source.name)\n\t\t\t\t\tappendClass(associationElem, \"parent_to_\" + r.target.entity.name + \"_\" + r.target.name)\n\t\t\t\t\tlinkElem = document.getElementById(\n\t\t\t\t\t\t\"link_\" + getAssociationId(a) + \n\t\t\t\t\t\t\"_\" + getPathId({source: r.source, target: r.target})\n\t\t\t\t\t)\n\t\t\t\t\tappendClass(linkElem, \"child_to_\" + r.source.entity.name + \"_\" + r.source.name)\n\t\t\t\t\tappendClass(linkElem, \"parent_to_\" + r.target.entity.name + \"_\" + r.target.name)\n\t\t\t\t\t\n\t\t\t\t\tvar a1 = document.getElementById('asset_' + a.source.name)\n\t\t\t\t\tappendClass(a1, \"child_to_\" + r.source.entity.name + \"_\" + r.source.name)\n\t\t\t\t\tappendClass(a1, \"parent_to_\" + r.target.entity.name + \"_\" + r.target.name)\n\n\t\t\t\t\tvar a2 = document.getElementById('asset_' + a.target.name)\n\t\t\t\t\tappendClass(a2, \"child_to_\" + r.source.entity.name + \"_\" + r.source.name)\n\t\t\t\t\tappendClass(a2, \"parent_to_\" + r.target.entity.name + \"_\" + r.target.name)\n\t\t\t\t})\n\t\t\t} else if(r.link) {\n\t\t\t\tr.link.forEach(function(l, i) {\n if(i+1 < r.link.length) {\n\t\t\t\t\t\tisaElem = document.getElementById(\"inheritance_\" + \n\t\t\t\t\t\t\tr.link[i] + \"_\" +\n\t\t\t\t\t\t\tr.link[i+1]\n\t\t\t\t\t\t)\n\t\t\t\t\t\tappendClass(isaElem, \"child_to_\" + r.source.entity.name + \"_\" + r.source.name)\n\t\t\t\t\t\tappendClass(isaElem, \"parent_to_\" + r.target.entity.name + \"_\" + r.target.name)\n\n\t\t\t\t\t\tlinkElem = document.getElementById(\n\t\t\t\t\t\t\t\"link_\" + getInheritanceId({subAsset: {name: r.link[i]}, superAsset: {name: r.link[i+1]}}) + \n\t\t\t\t\t\t\t\"_\" + getPathId({source: r.source, target: r.target})\n\t\t\t\t\t\t)\n\t\t\t\t\t\tappendClass(linkElem, \"child_to_\" + r.source.entity.name + \"_\" + r.source.name)\n\t\t\t\t\t\tappendClass(linkElem, \"parent_to_\" + r.target.entity.name + \"_\" + r.target.name)\n\t\t\t\t\t}\n\t\t\t\t\tvar a1 = document.getElementById('asset_' + l)\n\t\t\t\t\tappendClass(a1, \"child_to_\" + r.source.entity.name + \"_\" + r.source.name)\n\t\t\t\t\tappendClass(a1, \"parent_to_\" + r.target.entity.name + \"_\" + r.target.name)\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t}\n\n\tif(root.children) {\n\t\troot.children.forEach(function(asset) {\n\t\t\tif(asset.children) {\n\t\t\t\tasset.children.forEach(function(attackStep) {\n\t\t\t\t\tvar traversed = {}\n\t\t\t\t\ttraversed[attackStep.entity.name + \"_\" + attackStep.name] = true\n\t\t\t\t\tchildrenRecurse(attackStep, attackStep, traversed)\n\t\n\t\t\t\t\ttraversed = {}\n\t\t\t\t\ttraversed[attackStep.entity.name + \"_\" + attackStep.name] = true\n\t\t\t\t\tparentRecurse(attackStep, attackStep, traversed)\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t}\n}", "function SplayTree() { }", "function createHierarchies(rootID, node, index) {\n if (isCanceled)return;\n if (index >= node.nodes.length) return;\n let object = specif.getSpecIFObjectForID(node.nodes[index].object);\n if (object) {\n let page = createPageFromObject(object, rootID);\n page.title = pageNumber(node.object, index, object) + \" \" + page.title;\n data.createPage(page, function (response) {\n let createdPage = JSON.parse(response);\n let log = \"<p>/\";\n let notFirst = false;\n createdPage.ancestors.forEach(function (entry) {\n if (notFirst)\n log += entry.title + \"/\";\n else\n notFirst = true;\n });\n log += page.title;\n reorderCreatedPage(rootID, node, index, createdPage, specif.isChapter(object));\n }, function (err) {\n console.log(page);\n console.log(err);\n error(err)\n })\n } else {\n createHierarchies(rootID, node, index + 1)\n }\n }", "function createPath(parent, path)\n {\n if (!path.length) // never do \"path == []\"\n {\n return parent;\n }\n else\n {\n var head = path[0];\n var pathrest = path.slice(1, path.length);\n var target = null;\n var nextRoot = null;\n\n // check children\n var children = parent.getChildren();\n\n for (var i=0; i<children.length; i++)\n {\n if (children[i].label == head)\n {\n nextRoot = children[i];\n break;\n }\n }\n\n // else create new\n if (nextRoot == null)\n {\n nextRoot = new demobrowser.Tree(head);\n parent.add(nextRoot);\n }\n\n // and recurse with the new root and the rest of path\n target = createPath(nextRoot, pathrest);\n return target;\n }\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}", "getReflectionCategories(reflections) {\n const categories = new Map();\n for (const child of reflections) {\n const childCategories = this.getCategories(child);\n if (childCategories.size === 0) {\n childCategories.add(CategoryPlugin_1.defaultCategory);\n }\n for (const childCat of childCategories) {\n const category = categories.get(childCat);\n if (category) {\n category.children.push(child);\n }\n else {\n const cat = new models_2.ReflectionCategory(childCat);\n cat.children.push(child);\n categories.set(childCat, cat);\n }\n }\n }\n for (const cat of categories.values()) {\n this.sortFunction(cat.children);\n }\n return Array.from(categories.values());\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replays a fight result. Accepts the result and opens a Combat screen.
async replayFightResult(metaResult) { this.setState({ loading: true, }); let result; try { result = await this.state.contractFacade.replay( metaResult.seed, metaResult.selection_lhs, metaResult.selection_rhs, metaResult.variants_lhs, metaResult.variants_rhs, metaResult.commander_lhs, metaResult.commander_rhs); } catch (error) { console.log(error); return this.setState({ ...this.defaultLoadedState, toastOpen: true, toastContent: 'Transaction failed (Replay Fight).', }); } this.setState({ mode: Modes.Combat, trainingSelfSelection: result.selection_lhs, trainingSelfCommander: result.commander_lhs, trainingOpponentSelection: result.selection_rhs, trainingOpponentCommander: result.commander_rhs, trainingResult: result, loading: false, }); }
[ "function replayGame() {\n resetGame();\n togglePopup();\n }", "function showReplay() {\n document.getElementById('guessing-div').style.display = 'none';\n document.getElementById('replay-div').style.display = 'block';\n}", "function DisplayFight() {\r\n var DivDisplay = document.getElementById(\"DivDisplayFight\");\r\n\r\n if (DisplayLine < ResposeLines.length) {\r\n DivDisplay.innerHTML += \"<h2>\" + ResposeLines[DisplayLine] + \"</h2>\";\r\n DisplayLine++;\r\n DivDisplay.scrollBy(0, 100);\r\n }\r\n if (DisplayLine == ResposeLines.length) {\r\n clearInterval(IDDisplayFight);\r\n $(\"#lblStopButtonMSG\").text('');\r\n $(\"#btnStopFight\").prop('disabled', false);\r\n $(\"#btnStopFight\").fadeTo(0, 1);\r\n RoundNumber++;\r\n if (!Paused && ResponseObj.Player.Alive && ResponseObj.Enemy.Alive) {\r\n NextRound();\r\n }\r\n }\r\n}", "function playGame() {\n\tcomputerSelect();\n\tif (humanSelect == \"paper\" || humanSelect == \"scissors\" || humanSelect == \"rock\") {\n\t\tplay(humanSelect,computerSelection);\n\t\t$('#bot').attr('src','images/' + computerSelection + '.png');\n\t\t// the bot selection image doesn't show tried use delay so you would see it for a bit\n\t\t// before showing the score\n\t\t$('#outcome').text(result);\n\t\t$('#score').text(\"Score is: \" + humanScore + \" to \" + computerScore);\n\t\t}\n\t}", "function replay() {\n\tlocation.reload();\n}", "function showResult(isCorrect) {\r\n if (isCorrect) \r\n {\r\n correctAnswerScreen();\r\n currentScore(); \r\n }\r\n else \r\n {\r\n inCorrectAnswerScreen();\r\n \r\n } \r\n}", "gameOver(result) {\n document.getElementById('overlay').style.display = '';\n if (result === 'win') {\n document.getElementById('game-over-message').className = 'win';\n document.getElementById('game-over-message').innerHTML = `<br><i>Wow, you reached 88 miles per hour!</i> 🏎️💨 <p>Nailed it! The phrase was \"${this.activePhrase.phrase.toUpperCase()}\"!</p>`;\n document.getElementById('btn__reset').textContent = 'Go back to the future & try again?';\n } else {\n document.getElementById('game-over-message').className = 'lose';\n document.getElementById('game-over-message').innerHTML = `<br><i>Think, McFly, think!</i> 😖💭 <p>Better luck next time! The phrase was \"${this.activePhrase.phrase.toUpperCase()}\".</p>`;\n document.getElementById('btn__reset').textContent = 'Go back in time & try again?';\n }\n this.resetGame();\n }", "function playFight(p1, p2) {\n\tvar manaSpent = 0;\n\tvar turnCounter = 0;\n\twhile (true) {\n\t\t// player turn\n\t\t// run effects TODO\n\t\trunEffects(currentEffects, p1, p2);\n\t\t// age/expire effects TODO\n\t\tturnCounter++;\n\t\t// get decision\n\t\tconsole.log(p1, p2);\n\t\tvar decision = makePlayerDecision(p1, p2);\n\t\tconsole.log(decision);\n\t\tif (decision.mana > p1.mana)\n\t\t\treturn -manaSpent;\n\t\tmanaSpent += decision.mana;\n\t\tp1.mana -= decision.mana;\n\t\tif (decision.type === 'immediate') {\n\t\t\t// perform damage/heal/etc TODO\n\t\t\tif (decision.damage) { p2.hit -= decision.damage; }\n\t\t\tif (decision.heal) { p1.hit += decision.damage; }\n\t\t} else if (decision.type === 'effect') {\n\t\t\t// OR add effect TODO\n\t\t}\n\t\t// check for death TODO\n\t\tif (p1.hit <= 0) return -manaSpent;\n\n\t\t// boss turn\n\t\t// run effects TODO\n\t\t// age/expire effects TODO\n\t\tturnCounter++;\n\t\t// attack \n\t\tp1.hit -= calcDamage(p2, p1);\n\n\t\t// check for death\n\t\tif (p2.hit <= 0) return manaSpent;\n\t}\n\tif (true) {\n\t\tconsole.log(manaSpent);\n\t}\n}", "function showResult(status) {\n if (status === \"correct\") {\n $(\"#result\").html(\"Correct!\");\n correctAnswers++;\n $(\"#result-image-win\").show();\n $(\"#result-image-lose\").hide();\n } else if (status === \"incorrect\") {\n $(\"#result\").html(\"Incorrect :c\");\n incorrectAnswers++;\n $(\"#result-image-win\").hide();\n $(\"#result-image-lose\").show();\n } else {\n $(\"#result\").html(\"Time's up!\");\n timeOutAnswers++;\n $(\"#result-image-win\").hide();\n $(\"#result-image-lose\").show();\n }\n\n // show the question area and hide the result area\n $(\"#question-area\").hide();\n $(\"#result-area\").show();\n $(\"#end-of-game\").hide();\n\n $(\"#result-text\").html(\n `The answer was ${result.results[arrIndex].correct_answer}!`\n );\n\n clearInterval(showCount);\n\n if (roundCounter < 10) {\n count = 30;\n $(\"#countdown-display\").text(\n `Time remaining: ${count} seconds`\n );\n setTimeout(startCount, 4000);\n } else {\n setTimeout(endOfGame, 4000);\n }\n }", "function submitRoundOneA(){\n\tcurrentCard = deck.pop();\n\tvar cardAsString = idCard(currentCard);\n\t//see if players guess is correct\n\tvar suit = currentCard % 4;\n\tif (suit === 1 || suit === 2){\n\t\t//TODO create equation to determine the amount of drinks to assign\n\t\t$(\".instructions\").text(\"Give Drinks!\");\n\t} else {\n\t\t$(\".instructions\").text(\"Take Drinks!\");\n\t}\n\t//put card in players hand\n\thands[turn].push(currentCard);\n\tupdateHands();\n\t//move to next players turn\n\tturn++;\n\tif (turn === 4){\n\t\t//TODO is it possible to but some sort of pause here?\n\t\t//hide current round and show next\n\t\t$(\"#round1\").hide();\n\t\t$(\"#round2\").show();\n\t\t//reset turns\n\t\tturn = 0;\n\t\tround++;\n\t}\n\tsetPlayer(players[turn]);\n}", "function fwd_OnClick()\n{\n\ntry {\n\tDVD.PlayForwards(DVDOpt.ForwardScanSpeed);\n}\n\ncatch(e) {\n e.description = L_ERRORUnexpectedError_TEXT;\n\tHandleError(e);\n\treturn;\n}\n\n}", "function renderResults() {\n let score = STORE.score;\n let num = STORE.questionNumber;\n\n $('.main_card').html(generateResults(score, num));\n $('#restart').click(function(event) {\n event.preventDefault();\n console.log('Restarting Quiz');\n\n STORE.questionNumber = 0;\n STORE.score = 0;\n $('.count')\n .removeClass('snackbar')\n .removeClass('red')\n .removeClass('green')\n .removeClass('show')\n .text('');\n renderStartQuiz();\n });\n}", "function commence(p1, p2) {\n\t// Check if both players are ready to fight, if\n\t// they aren't, then we return. If they are, then\n\t// we'll begin fighting\n\tif(p1 == false || p2 == false) {\n\t\treturn;\n\t}\n\telse {\n\t\t// Here we'll want to wait a few seconds before we begin. We \n\t\t// don't want the action to happen instantly after the last \n\t\t// player chooses their last action. The strikePause variable \n\t\t// sets the delay\n\t\tsetTimeout(function()\n\t\t{\n\t\t\tconsole.log(\"Starting Round 1\");\n\t\t\t// Grab the first action from both players and calculate\n\t\t\t// who wins\n\t\t\tvar p1Action = player1.actions[0].toString();\n\t\t\tvar p2Action = player2.actions[0].toString();\n\t\t\tcalculateAttack(p1Action, p2Action);\n\t\t\t\n\t\t\t// Check to see if there are two actions that\n\t\t\t// will happen. If so, then we'll proceed to\n\t\t\t// the next moves. We'll also check if a player\n\t\t\t// has been defeated. If they are, then we'll \n\t\t\t// skip to the finishing animations\n\t\t\tif(player1.dead == false && player2.dead == false)\n\t\t\t{\n\t\t\t\tif(actionCount >= 2)\n\t\t\t\t{\n\t\t\t\t\t// Use strikePause to set a slight attack delay\n\t\t\t\t\tsetTimeout(function()\n\t\t\t\t\t{\n\t\t\t\t\t\tconsole.log(\"Starting Round 2\");\n\t\t\t\t\t\tvar p1Action = player1.actions[1].toString();\n\t\t\t\t\t\tvar p2Action = player2.actions[1].toString();\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Check to see if either player is currently blocking. Since stamina\n\t\t\t\t\t\t// can be no less than 1 we can only be blocking in rounds 2 and 3\n\t\t\t\t\t\tcheckForBlocking(p1Action, p2Action);\n\t\t\t\t\t\t\n\t\t\t\t\t\t// Check to see if there is a third action that\n\t\t\t\t\t\t// will happen. If so, then we'll continue fighting\n\t\t\t\t\t\t// We'll also check if a player has been defeated. \n\t\t\t\t\t\t// If they are, then we'll skip to the finishing animations\n\t\t\t\t\t\tif(player1.dead == false && player2.dead == false)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(actionCount == 3)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tsetTimeout(function()\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tconsole.log(\"Starting Round 3\");\n\t\t\t\t\t\t\t\t\tvar p1Action = player1.actions[2].toString();\n\t\t\t\t\t\t\t\t\tvar p2Action = player2.actions[2].toString();\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tcheckForBlocking(p1Action, p2Action);\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tif(player1.dead == false && player2.dead == false)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tconsole.log(\"Resetting after round 3 for next fight\");\n\t\t\t\t\t\t\t\t\t\t// If neither player died then reset for the next round\n\t\t\t\t\t\t\t\t\t\tresetForNextRound();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t// Check to see who died and play their finishing animation\n\t\t\t\t\t\t\t\t\t\tplayer1.dead == true ? endGame(\"player1\") : endGame(\"player2\");\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}, strikePause);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t// If we're done fighting then we'll reset\n\t\t\t\t\t\t\t\t// our stats for the next round\n\t\t\t\t\t\t\t\tconsole.log(\"Resetting after round 2 for next fight\");\n\t\t\t\t\t\t\t\tresetForNextRound();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t// Check to see who died and play their finishing animation\n\t\t\t\t\t\t\tplayer1.dead == true ? endGame(\"player1\") : endGame(\"player2\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}, strikePause);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// If we're done fighting then we'll reset\n\t\t\t\t\t// our stats for the next round\n\t\t\t\t\tconsole.log(\"Resetting after round 1 for next fight\");\n\t\t\t\t\tresetForNextRound();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// Check to see who died and play their finishing animation\n\t\t\t\tplayer1.dead == true ? endGame(\"player1\") : endGame(\"player2\");\n\t\t\t}\n\t\t}, strikePause);\n\t}\n}", "function displayGameScreen()\n{\n\t\n\tdisplayResourceElement();\n\t\t\t\n\tdisplayInfoElement();\n\t\n\tdisplayMapElement();\n\t\n\tjoinGame();\n\t\n\tif(player.onTurn == true)\n\t{\n\t\tdisplayEndTurnElement(\"salmon\");\n\t\t\n\t\tdisplayTurnCounterElement(\"lightGreen\");\n\t}\n\telse\n\t{\n\t\tdisplayEndTurnElement(\"lightSlateGrey\");\n\t\n\t\tdisplayTurnCounterElement(\"salmon\");\n\t}\n\t\n\tgameStarted = true;\n\t\n\tstage.update();\n}", "function rew_OnClick()\n{\n\ntry {\n\tDVD.PlayBackwards(DVDOpt.BackwardScanSpeed);\n}\n\ncatch(e) {\n e.description = L_ERRORUnexpectedError_TEXT;\n\tHandleError(e);\n\treturn;\n}\n\n}", "function output_games(result){\n let i = 0;\n let short_description = \"\";\n let title_length = 0;\n let j = 0;\n let font_size = \"28px\";\n window.scrollTo(0, 0);\n \n document.querySelector(\"main\").innerHTML = \"\";\n while(i < 50){\n \tdisplay_game(result[i]);\n i += 1;\n }\n}", "function draw() \n{\n\tif (screenChanger == 0)\n\t{\n\t\tscreenDecision1();\n\t}\n \n\telse if (screenChanger == 1)\n\t{\n\t\tscreenWelcome();\n\t}\n \n\telse if (screenChanger == 4)\n\t{\n\t\tscreenFail();\n\t}\n \n\telse if (screenChanger == 5)\n\t{\n\t\tscreenCongrats();\n\t}\n\t\n else if (screenChanger == 6)\n {\n screenCircles();\n }\n\t \n else if (screenChanger == 7)\n {\n\t\tscreenRectangles();\n }\n\t \n else if (screenChanger == 8)\n {\n screenTriangles();\n }\n}", "pass() {\n // in progress: getting the canPass functionality to work.\n // send info to server --> fact that player did not play cards\n //if (this.canPass) {\n //}\n //;else (document.getElementById(\"error_message_game\").innerHTML = \"you cannot pass on the first turn\");\n\n\t document.getElementById(\"error_message_game\").innerHTML = \"\";\n play_cards();\n }", "function run() {\n \tplayerChoice = this.innerText;\n \tcomputerGamble();\n \tcompare();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i]. Return the number of students doing their homework at time queryTime.More formally, return the number of students where queryTime lays in the interval[startTime[i], endTime[i]] inclusive
function busyStudent(startTime, endTime, queryTime) { let counter = 0; for (let i = 0; i < startTime.length; i++) { if (startTime[i] <= queryTime && endTime[i] >= queryTime) { counter++; } } return counter; }
[ "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 }", "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 calculateIndex(time) {\n let data = time.split(\":\");\n let currentTime = parseInt(data[0], 10) * 60 + parseInt(data[1], 10);\n let rangeMinutes = parseInt(process.env.rangeMinutes, 10);\n let timeStart = parseInt(process.env.timeStart, 10);\n return Math.floor((currentTime - timeStart) / rangeMinutes);\n}", "function _split(startTime, endTime, durationPerMeasure) {\n const res = [];\n let currStartTime = startTime;\n while (true) {\n const cutoffTime = location.nextMeasureTime(currStartTime, durationPerMeasure);\n const currEndTime = cutoffTime.lessThan(endTime) ? cutoffTime : endTime;\n res.push({\n start: currStartTime,\n end: currEndTime\n });\n if (currEndTime.geq(endTime)) {\n break;\n }\n currStartTime = currEndTime;\n }\n return res;\n}", "getIntervalSteps (start, end, asIndex) {\n\t\tlet totalSteps = this.getTotalStepCount();\n\t\tlet ref = this.tzero;\n\t\tstart -= ref;\n\t\tstart /= (60 * 1000);\n\t\tstart = Math.ceil(start / this.getStepInterval());\n\t\tend -= ref;\n\t\tend /= (60 * 1000);\n\t\tend = Math.floor(end / this.getStepInterval());\n\t\tlet ret = [];\n\t\tfor (let i=start; i<=end; i++) {\n\t\t\tif (asIndex) {\n\t\t\t\tlet index = i;\n\t\t\t\twhile (index < 0)\n\t\t\t\t\tindex += totalSteps;\n\t\t\t\tret.push(index % totalSteps);\n\t\t\t}\n\t\t\telse\n\t\t\t\tret.push(i);\n\t\t}\n\t\treturn ret;\n\t}", "function rangeDivisor(start, end, divisor) {\n let numArray = new Array()\n for (let i = start; i <= end; i++) {\n numArray.push(i) \n }\n let divisibleNums = 0\n numArray.forEach(elem => {\n if (elem % divisor == 0) {\n divisibleNums++\n }\n });\n return divisibleNums\n}", "function find_job_in_period(start, end, task, jobs){\n for(var i=0;i<jobs.length;i++){\n var job = jobs[i];\n if(job.task === task && job.start >= start && job.start < end){\n return job;\n }\n }\n return null;\n}", "inRangeIdea (num, start, end) {\n let startRange\n let endRange\n if (!end) {\n startRange = 0\n endRange = start\n } else if (start > end) {\n startRange = end\n endRange = start\n } else {\n startRange = start\n endRange = end\n }\n return this.checkRangeIdea(num, startRange, endRange)\n }", "_search(time, param = \"time\") {\n if (this._timeline.length === 0) {\n return -1;\n }\n\n let beginning = 0;\n const len = this._timeline.length;\n let end = len;\n\n if (len > 0 && this._timeline[len - 1][param] <= time) {\n return len - 1;\n }\n\n while (beginning < end) {\n // calculate the midpoint for roughly equal partition\n let midPoint = Math.floor(beginning + (end - beginning) / 2);\n const event = this._timeline[midPoint];\n const nextEvent = this._timeline[midPoint + 1];\n\n if ((0, _Math.EQ)(event[param], time)) {\n // choose the last one that has the same time\n for (let i = midPoint; i < this._timeline.length; i++) {\n const testEvent = this._timeline[i];\n\n if ((0, _Math.EQ)(testEvent[param], time)) {\n midPoint = i;\n } else {\n break;\n }\n }\n\n return midPoint;\n } else if ((0, _Math.LT)(event[param], time) && (0, _Math.GT)(nextEvent[param], time)) {\n return midPoint;\n } else if ((0, _Math.GT)(event[param], time)) {\n // search lower\n end = midPoint;\n } else {\n // search upper\n beginning = midPoint + 1;\n }\n }\n\n return -1;\n }", "function itowDiff(itowStart, itowEnd) {\n if (itowEnd < itowStart) { // if overflow\n return itowEnd + weekSeconds * 1000 - itowStart;\n }\n return itowEnd - itowStart; // simple case\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}", "function getStationIndex(startObj, endObj) {\n\n // declaring the startStationindex and endStationIndex variables to save the index numbers of the station provided by the user. By default they are set to -1 which means no indexes found.\n var startStationIndex = -1,\n endStationIndex = -1;\n\n // saving line name Index from trainlines array of objects into lineIndexObj - for e.g the index for line \"T4\" will be 2\n var lineIndexObj = getLineIndex(startObj, endObj);\n\n // saving the stations list from trainLines by using the start line index\n var startLineStationsList = trainLines[lineIndexObj.startLineIndex].stations;\n\n // saving the stations list from trainLines by using the end line index\n var endLineStationsList = trainLines[lineIndexObj.endLineIndex].stations;\n\n // looping through the start station array to check if the start station exist in the array, if it exists save its index into the startStationIndex variable\n for (var i = 0; i < startLineStationsList.length; i += 1) {\n if (startLineStationsList[i].toLowerCase() === startObj.station.toLowerCase()) {\n startStationIndex = i;\n break;\n }\n }\n\n // looping through the end station array to check if the end station exist in the array, if it exists save its index into the endStationIndex variable\n for (var i = 0; i < endLineStationsList.length; i += 1) {\n if (endLineStationsList[i].toLowerCase() === endObj.station.toLowerCase()) {\n endStationIndex = i;\n break;\n }\n }\n\n // save startStationIndex and endStationIndex into the variable\n var stationIndexObj = {\n startStationIndex: startStationIndex,\n endStationIndex: endStationIndex\n }\n\n // return the stationIndexObj with the station index numbers\n return stationIndexObj;\n}", "function intersectSchedules(schedule1, schedule2) {\n var res = [];\n \n schedule1.forEach(r1 => {\n schedule2.forEach(r2 => {\n var intersection = findIntersection(r1, r2);\n \n if (intersection) {\n res.push(intersection);\n }\n });\n });\n \n return res;\n }", "function PossibleSchedule(aCourses, nAverageStartTime, nAverageEndTime) {\n this.aCourses = aCourses;\n this.nAverageStartTime = nAverageStartTime;\n this.nAverageEndTime = nAverageEndTime;\n }", "function getTaskCompletionData(task_submissions, task_count) {\n //get number of days between start date and last task date\n let startDate = new Date(SPRINTS[currentSprint].sprintDate);\n let last_date = getLastSubmissionDate(task_submissions);\n\n let date_difference = calculateDateDifference(startDate, last_date);\n \n // console.log(date_difference);\n let tasks_remaining = [];\n\n //foreach day\n for(let i = 0; i <= date_difference; i++) \n {\n let task_date = new Date(startDate.getFullYear(),\n startDate.getMonth(),\n startDate.getDate() + i);\n\n //format the date into the standard date format for scrum tool\n task_date = FormatDate(task_date);\n\n if(task_submissions[task_date] != undefined) {\n task_count -= task_submissions[task_date];\n }\n tasks_remaining.push(task_count);\n }\n // console.log('tasks remaining', tasks_remaining);\n return tasks_remaining;\n}", "getLocationTimes(availability) {\n // NOTE: Location availability is stored in the Firestore database as:\n // availability: {\n // Friday: [\n // { open: '10:00 AM', close: '3:00 PM' },\n // { open: '10:00 AM', close: '3:00 PM' },\n // ],\n // }\n // ...\n // };\n var result = [];\n Object.entries(availability).forEach((time) => {\n var timeArray = time[1];\n var day = time[0];\n timeArray.forEach((time) => {\n result.push(Utils.combineMaps(time, {\n day: day\n }));\n });\n });\n\n // Now, we have an array of time maps (i.e. { open: '10:00 AM', close: \n // '3:00 PM' })\n var times = [];\n result.forEach((timeMap) => {\n times = times.concat(\n this.getTimesBetween(timeMap.open, timeMap.close, timeMap.day));\n });\n return times;\n }", "function waitingTime(array, p) {\n let tickectsAmout = array[p];\n let result = 0;\n let personLocation = p;\n while(tickectsAmout > 0) {\n let reducedValue = array.shift();\n\t\treducedValue--;\n result = result + 1;\n if(personLocation === 0) {\n personLocation = array.length;\n tickectsAmout -= 1;\n }else {\n personLocation--;\n }\n if(reducedValue > 0){\n array.push(reducedValue)\n }\n }\n return result;\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 avgTimePerQuestion (sessionsArray) {\n\t\treturn sessionsArray.reduce( function(a, b){\n\t\t\treturn a.concat(b.questions);\n\t\t}, []).reduce(function(prev, curr, i, arr){\n\t\t\treturn prev + (curr.totalTime / arr.length);\n\t\t},0);\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function begins the intro. Input: runIntro requires frame input from within the Leapmotion controller loop Output: runIntro returns true until it has completed cycling through each introText. It then returns false
function runIntro(frame){ if (paused) {return;} console.log(introCount); //Display the cards document.getElementById('expression').innerHTML = '<span class="intro">' + introTexts[introCount] + '</span>'; stop = Date.now(); checkHands(frame); // If we are on the last page of the slide if (introCount == (introTexts.length - 1)){ if ((confidence > .8) && (extendedFingers < 6) && (extendedFingers > 0) && ((stop-start) > 2000)){ difficulty = extendedFingers; console.log('woooo!!!!'); inIntro = false; return; } inIntro = true; } else // If the user wants to skip to the end; if ((confidence > .6) && (extendedFingers == 10)){ introCount = (introTexts.length - 1); expression = introTexts[introCount]; cardChange(expression, 0, true); inIntro = true; } else // If the user wants to move to the next page if ((confidence > .6) && (extendedFingers == (introCount+1))){ introCount++; expression = introTexts[introCount]; cardChange(expression, 0, true); if (introCount == 3){ start = Date.now(); } inIntro = true; } else { inIntro = true; } }
[ "function startIntro(){\n var intro = introJs();\n intro.setOptions({\n steps: [\n { \n intro: \"Hello world!\"\n },\n {\n element: document.querySelector('.cont'),\n intro: \"This is a tooltip.\"\n },\n // {\n // element: document.querySelectorAll('#step2')[0],\n // intro: \"Ok, wasn't that fun?\",\n // position: 'right'\n // },\n {\n element: '.cont2',\n intro: 'More features, more fun.',\n position: 'left'\n },\n // {\n // element: '#step4',\n // intro: \"Another step.\",\n // position: 'bottom'\n // }\n ]\n });\n intro.start();\n }", "function intro5()\n{\n let intro = introJs();\n intro.setOptions({overlayOpacity: 0.2, showStepNumbers: false, showBullets: false, hideNext: true, hidePrev: true});\n intro.onexit(function () {chrome.tabs.getSelected(null, function(tab) {chrome.tabs.reload(tab.id);});});\n window.setTimeout(function () {\n\n intro.addSteps([\n {\n intro: \"Before you make your first search, let's go over a few final things.\"\n },\n {\n intro: \"If you need to access Search Queue at any time, click the black plus icon on the right corner of the toolbar.\"\n },\n {\n element: document.getElementById('clear'),\n intro: \"To clear all the queued searches, click the clear button. This is disabled for now!\",\n disableInteraction: true\n },\n {\n element: document.getElementById('start'),\n intro: \"You're all set! Click the circular start button to make your first search.\"\n }\n ]);\n\n intro.start();\n\n }, 200);\n chrome.storage.local.set({'intro-step': -1});\n}", "function startIntro(){\n\tvar intro = introJs();\n\t\tintro.setOptions({\n\t\t\tsteps: [\n\t\t\t\t{\n\t\t\t\t\tintro: \"Welcome! This webpage will help you explore unemployment data in different areas of Münster.\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#settingsBox',\n\t\t\t\t\tintro: \"Use this sidebar to customize the data that is displayed on the map.\",\n\t\t\t\t\tposition: 'right'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#yearSection',\n\t\t\t\t\tintro: \"You can move this slider to get data from 2010 to 2014.\",\n\t\t\t\t\tposition: 'right'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#criteriaSection',\n\t\t\t\t\tintro: \"Choose a criterion to select a specific group of unemployed.\",\n\t\t\t\t\tposition: 'right'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#boundarySection',\n\t\t\t\t\tintro: \"You can also switch to districts to get finer granularity.\",\n\t\t\t\t\tposition: 'right'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#legendBox',\n\t\t\t\t\tintro: \"This legend will tell how many unemployed are represented by each color.\",\n\t\t\t\t\tposition: 'right'\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\telement: '#map',\n\t\t\t\t\tintro: \"Check the map to view your selected data! You can also click on all boundaries. A popup will show you a timeline to compare data of recent years and links to additional information.\",\n\t\t\t\t\tposition: 'left'\n\t\t\t\t}\n\t\t\t]\n\t\t});\n\n\t\tintro.start();\n}", "function intro3()\n{\n let intro = introJs();\n intro.setOptions({overlayOpacity: 0.2, showStepNumbers: false, showBullets: false, hideNext: true, hidePrev: true});\n intro.onexit(function () {chrome.tabs.getSelected(null, function(tab) {chrome.tabs.reload(tab.id);});});\n window.setTimeout(function () {\n\n intro.addSteps([\n {\n element: document.getElementById('search-container'),\n intro: \"Your searches have been added to the queue. Drag and drop the searches to reorder them!\"\n },\n {\n intro: \"Next, let's adjust some settings.\"\n },\n {\n element: document.getElementById('settings-open'),\n intro: \"Click the circular settings button.\"\n }\n ]);\n\n intro.start();\n\n }, 200);\n chrome.storage.local.set({'intro-step': 4});\n}", "function startTutorial() {\n\t// May or may not be necessary\n\tgameType = 'tutorial';\n\tstartGame();\n\ttutorialInstructionIndex = -1;\n\tcallbackAfterMessage = nextTutorialMessage;\n\tnextTutorialMessage();\n}", "function playIntro(intro){\n return intro\n}", "function introResponse() {\n var commands = {\n \"What is it like being an AI\": function() {\n beingAnAI();\n },\n \"Are you a human\": function() {\n humanQuestion();\n },\n \"I don't want to be here\": function() {\n doNotWant();\n }\n };\n\n // can only say the phrases as they appear on screen and can only say one phrase\n annyang.start({\n autoRestart: false,\n continuous: false\n });\n // show the commands and let player say one when function is triggered\n annyang.addCommands(commands);\n $('#intro').show();\n}", "function introMessage() {\n introDiv.classList.add('container', 'col-12', 'col-sm-4');\n introDiv.style.opacity = '1';\n \n introContainer.append(introDiv);\n introDiv.append(introText);\n introText.innerText = `Click the START Button`;\n}", "function intro() {\n background(0,0,50);\n\n textFont('Helvetica');\n textSize(18);\n textAlign(CENTER, CENTER);\n fill(255);\n noStroke();\n text('[ click anywhere to start animation ]', width/2,height/2);\n}", "function displayIntro() {\n image(introImages[introIndex], 0, 0, windowWidth, windowHeight);\n}", "build_intro_frames() {\n // only one intro frame so far, but we'll likely add more\n let intro_frame = {};\n intro_frame.title = INTRO_TITLE;\n intro_frame.instruction = INTRO_INSTRUCTION;\n intro_frame.text = INTRO_TEXT(this.variant);\n intro_frame.template = INTRO_FRAME_TEMPLATE;\n intro_frame.is_app = true;\n return [new IntroFrame(intro_frame, this.logger)];\n }", "function drawIntro(){\n\t\n}", "function handleIntroIntersect(entries) {\n\tentries.forEach(function (entry) {\n\t\tconst innerEl = entry.target.querySelector(\".intro__text\");\n\t\tif (entry.isIntersecting) {\n\t\t\tshowElement(entry.target, innerEl);\n\t\t} else {\n\t\t\thideElement(entry.target, innerEl);\n\t\t}\n\t});\n}", "function tourButtonClick() {\n\tstartButtonClick();\n\tstartIntro();\n}", "function introAnimation() {\n introMenu.animate({\n opacity: 0\n }, 1000, function() {\n introMenu.hide();\n info.show();\n info.animate({\n opacity: 1\n }, 1000);\n });\n}", "function displayStart() {\n introSFX.play();\n push();\n createCanvas(500, 500);\n background(0);\n textAlign(CENTER);\n textSize(20);\n textFont(myFont);\n fill(250);\n text(\"to infinity and beyond!\", width / 2, 80);\n text(\"press X to start your adventure\", width / 2, 450);\n imageMode(CENTER);\n translate(width / 2, height / 2);\n translate(p5.Vector.fromAngle(millis() / 1000, 40));\n image(playerImage, 5, 5);\n pop();\n\n // information for the stars in the background\n push();\n translate(width / 2, height / 2);\n for (var i = 0; i < stars.length; i++) {\n stars[i].update();\n stars[i].display();\n }\n pop();\n\n // To start the game, we only have to press the space bar to access the level one of the game\n if (keyIsPressed && key === 'x') {\n state = \"INSTRUCTION\";\n }\n}", "function nextTutorialMessage() {\n\ttutorialInstructionIndex ++;\n\tif(tutorialInstructions[tutorialInstructionIndex+1]) {\n\t\tdisplayMessage( \"Flip-a-Blox Tutorial\", tutorialInstructions[tutorialInstructionIndex].message );\n\t}\n\telse {\n\t\tcallbackAfterMessage = function() {};\n\t\thideMessage();\n\t\tplaying_state = true;\n\t}\n}", "function happycol_presentation_play(args){\n\thappycol_assignments(args, function(){\n\t\thappycol_presentation_beginShow(args);\n\t});\n\t\n}", "function initializeLesson() {\r\n lesson11.init();\r\n animate();\r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Injects all the dependencies in the base classes's constructor. The character's HTML Template, its CSS Template and Font Awesome will be added to the DOM. Every version of the character needs these dependencies to operate properly.
injectDependencies() { this.injectHtmlTemplate(); this.injectCssTemplate(this.widgetType); this.injectFontAwesome(); }
[ "init() {\n this._createShadowRoot()\n this._attachStyles()\n this._createElements()\n }", "init () {\n this._initSelectors()\n this._initElements()\n this._initProperties()\n this._initAttributes()\n\n Component.bindMethodToDOMElement(this, 'activateTab', this.activateTab)\n Component.bindMethodToDOMElement(this, 'addTab', this.addTab)\n Component.bindMethodToDOMElement(this, 'removeTab', this.removeTab)\n }", "function initComposer(){\n initToolbar();\n initEditor();\n initTextarea();\n}", "function Deps() {\n // Tracks all loaded scopes, so that they are not loaded twice.\n this.loadedList = {};\n\n // Flag to make sure nothing is loaded after the container objects are created.\n this.loaded = false;\n\n // Constructors contain a list of functions for each scope type\n // that are invoked when a scope is initialized.\n this.constructors = {};\n\n // List of new created instances that were not processed for dependencies.\n this.instanceQueue = [];\n\n // List of inceptions that were started but not finished.\n this.unfinishedInceptions = {};\n\n // Breaks recursion when creating new instance while creating new instance.\n this.creatingDependencies = false;\n\n // Load arguments as Scopes.\n this.load(arguments);\n }", "function setupClasses(){\n // Gather Variables to Pass to Classes\n doodleNames = [\"krill\",\"worm\",\"sunshine\",\"smiles\"];\n drawZone = document.querySelector(\".draw-zone\");\n\n // Declare Classes\n svgLoader = new SVGLOADER(document.querySelectorAll(\"svg[data-type='svg']\"),svgData);\n svgStage = new SVGSTAGE(doodleNames,drawZone,document.body);\n touchSwipe = new TOUCHSWIPE(drawZone,drawZone.querySelector(\".doodle\"),svgStage.eventCallback.bind(svgStage));\n}", "budgieSetup() {\n this.budgieContainer = BudgieDom.setupBudgieContainer(this);\n BudgieDom.setupBudgieCSS(this);\n BudgieDom.insertBudgieElements(this);\n BudgieDom.setupBudgieMouseDrag(this);\n // Only append extra items, and bind the scroll event if this is infinite scroll.\n if(this.options.infiniteScroll){\n this.appendEndingItems();\n this.prependStartingItems();\n BudgieDom.setupBudgieScrollProperties(this);\n }\n }", "function createElements() {\r\n _dom = {};\r\n createElementsForSelf();\r\n if (_opts.placement.popup) {\r\n createElementsForPopup();\r\n }\r\n createElementsForColorWheel();\r\n createElementsForNumbersMode();\r\n createElementsForSamples();\r\n createElementsForControls();\r\n }", "initAndPosition() {\n // Append the info panel to the body.\n $(\"body\").append(this.$el);\n }", "function _hydrateAndRenderExternalTemplates() {\n const header = new Header(\n './../../../templates/includes/header.jsr'\n );\n const footer = new Footer(\n './../../../templates/includes/footer.jsr'\n );\n const breadcrumb = new BreadCrumb(\n ['Hub', 'Mathématiques', 'PGCD'], \n ['../../../index.html', '', 'gcd.html'],\n ['before-icon-hub', 'before-icon-mathematics', ''],\n './../../../templates/includes/breadcrumb.jsr',\n );\n\n const headerTemplate = new Template(\n header.templateName,\n header.parentBlock,\n header.data\n );\n\n const footerTemplate = new Template(\n footer.templateName,\n footer.parentBlock,\n footer.data\n );\n\n const breadcrumbTemplate = new Template(\n breadcrumb.templateName,\n breadcrumb.parentBlock,\n breadcrumb.data\n );\n\n const render = new RenderExternalTemplate();\n render.render(headerTemplate);\n render.render(footerTemplate);\n render.render(breadcrumbTemplate);\n}", "injectElement() {\n document.body.innerHTML = `\n <${this.tagName}></${this.tagName}>\n `;\n mount(this.tagName);\n }", "function init() {\n\t\tid = utilities.UUID('toastify');\n\t\tvar root = document.querySelector(settings.root);\n\t\tvar toastifyEl = document.createElement('div');\n\t\t// Sets attributes and classes of toastify element.\n\t\ttoastifyEl.setAttribute('id', id);\n\t\ttoastifyEl.classList.add('toastify');\n\t\ttoastifyEl.classList.add('toastify--' + settings.position.horizontal);\n\t\ttoastifyEl.classList.add('toastify--' + settings.position.vertical);\n\t\troot.appendChild(toastifyEl);\n\t}", "function init(){\n buildToolbar();\n initEditor();\n }", "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 setup() {\n container.register({\n ChatAPIController: awilix.asClass(_controllers_ChatAPIController__WEBPACK_IMPORTED_MODULE_1__[\"ChatAPIController\"]),\n // services\n chatBotService: awilix.asClass(_use_cases_chatBotService__WEBPACK_IMPORTED_MODULE_2__[\"chatBotService\"]),\n // DAO\n mongoDao: awilix.asValue(mongoDao)\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 }", "constructor() { \n \n Body18.initialize(this);\n }", "initializing() {\n\n\n\n\n\n\n this._showInitMessage();\n this.log(yosay(\n chalk.yellow(\"Hi...!\\n\") +\n chalk.yellow(\"Share your ideas with me\\n\") +\n chalk.red(\"twitter:@dchatnu\")));\n\n //Initialize the project dependencies\n this.dependencies = [\n 'gitignore',\n 'babelrc',\n 'editorconfig',\n 'eslintrc',\n '_README.md',\n '_webpack.config.dev.js',\n '_webpack.config.prod.js'\n ];\n\n }", "init() {\n console.log('from init')\n\n this._placeCards(this.cards, this.element.cards);\n this._setStats();\n this._updateGameState(gameState.GAME);\n }", "function BaseController() {\n this.errors = [];\n this.messages = [];\n this.warnings = [];\n var self = this\n if (typeof this.onLoad == 'function') {\n jQuery(document).ready(function() {\n self.onLoad();\n })\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw the playground. Loop through all the added components
draw() { this.components.forEach( component => component.draw() ); }
[ "function renderPallet(){\n\tfor(let i = 0; i < numColor; i++){\n\t\tswatches[i].display();\n\t}\n\tfillIcon.display();\n}", "display() {\n this.draw(this.points.length);\n }", "draw(){\n\n for(let i=0; i<this.belt.length;i++){\n this.belt[i].draw();\n }\n }", "display() {\n //set the color\n stroke(this.element*255) ;\n //draw the point\n point(this.identity.x,this.identity.y)\n }", "draw() {\n push();\n translate(GSIZE / 2, GSIZE / 2);\n // Ordered drawing allows for the disks to appear to fall behind the grid borders\n this.el_list.forEach(cell => cell.drawDisk());\n this.el_list.forEach(cell => cell.drawBorder());\n this.el_list.filter(cell => cell.highlight)\n .forEach(cell => cell.drawHighlight());\n pop();\n }", "function drawShapes() {\n\tfor (var i = 0; i < shapes.length; i++) {\n\t\tvar points = shapes[i];\n\t\tdrawFinishedShape(points);\n\t}\n}", "function drawLEDs() {\n\t//create LED rows\n\tfor (x=0; x<=4; x++) {\n \t//create LED columns\n \tfor (y=0; y<=4; y++) {\n \t//create LED id\n \tvar divId = '('+x+','+y+')';\n //create LED div\n \tdocument.write('<div id=\"led'+divId+'\" class=\"ledz\" onclick=\"ledOnOff'+divId+'\"></div>');\n }\n document.write('<br />');\n\t}\n}", "function draw() {\n background(\"black\");\n scenery();\n\n //Loop over length of menagerie and call appropriate methods\n for (let i = 0; i < menagerie.length; i++) {\n menagerie[i].display();\n menagerie[i].update();\n menagerie[i].move();\n\n if (mouseIsPressed) {\n fill(\"white\");\n triangle(mouseX, mouseY, mouseX + 5, mouseY - 30, mouseX + 10, mouseY);\n arc(mouseX, mouseY, 30, 10, 0, 90);\n }\n }\n\n}", "function drawGrid() {\n for(let i = 0; i < HEIGHT; i++) {\n // create a new raw\n let raw = $('<div class=\"raw\"></div>');\n // fill the raw with squares\n for(let j = 0; j < WIDTH; j++) {\n raw.append('<div class=\"block\"></div>');\n }\n // append the raw to the grid container to create the grid\n $('#grid-container').append(raw);\n } \n console.log('[GRID] drawn');\n addGridListeners();\n }", "function drawEditionElements() {\n if (editionCheckbox.checked) {\n // Draw points\n for (var ptIndex = 0; ptIndex < customPoints.length; ptIndex++) {\n ctx.fillStyle = \"#f00\";\n ctx.fillRect(customPoints[ptIndex].x - (pointWidth / 2), customPoints[ptIndex].y - (pointHeight / 2), pointWidth, pointHeight);\n }\n // Draw lines\n if (polygonInConstruction.length > 0) {\n for (var i = 0; i < polygonInConstruction.length; i++) {\n point1 = findPointForId(polygonInConstruction[i][0]);\n point2 = findPointForId(polygonInConstruction[i][1]);\n ctx.strokeStyle = \"#0f0\";\n ctx.beginPath();\n ctx.moveTo(point1.x,point1.y);\n ctx.lineTo(point2.x, point2.y);\n ctx.stroke();\n }\n }\n // Draw polygons\n if (customPolygons.length > 0) {\n for (var i = 0; i < customPolygons.length; i++) {\n thePoly = []\n for (var j = 0; j < customPolygons[i].length; j++) {\n thePoint = findPointForId(customPolygons[i][j]);\n thePoly.push({x: thePoint.x, y: thePoint.y})\n }\n drawPolygon(thePoly);\n }\n }\n }\n}", "display() {\n this.scene.pushMatrix();\n this.spritesheet.activateShader();\n\n this.scene.translate(this.center_shift, 0, 0)\n\n for (let i = 0; i < this.text.length; i++) {\n this.spritesheet.activateCellp(this.getCharacterPosition(this.text.charAt(i)));\n this.rectangle.display();\n this.scene.translate(1, 0, 0);\n }\n\n this.scene.setActiveShaderSimple(this.scene.defaultShader);\n this.scene.popMatrix();\n }", "draw(gameObjects) {\r\n this.ctx.clearRect(0, 0, Helper.FieldSize.WIDTH, Helper.FieldSize.HEIGHT);\r\n for (let i = 0; i < gameObjects.length; i++) {\r\n gameObjects[i].draw(this.ctx);\r\n }\r\n }", "draw() {\n this.ghosts.forEach((ghost) => ghost.draw());\n }", "paintFrame() {\n for (let rowIterator = 0; rowIterator < this.gridState.length; rowIterator++) {\n for (let columnIterator = 0; columnIterator < this.columns; columnIterator++) {\n const cellState = Math.pow(2, columnIterator) & this.gridState[rowIterator]\n this.paintBrick(rowIterator, this.columns - columnIterator - 1, cellState !== 0)\n }\n }\n }", "fields() {\n // sets \"this.current\" to fields\n this.current = \"fields\";\n // draws the grass\n background(104, 227, 64);\n \n // draws a path\n this.path(width/2, 0);\n \n // draws a pile of rocks or a well\n if (this.well) {\n this.makeWell();\n } else {\n this.rocks();\n }\n\n // this draws a flower patch\n for (let i = 0; i < 200; i += 25) {\n for (let j = 0; j < 100; j += 20) {\n this.flower(i + 100, j + 450);\n }\n }\n }", "drawHTMLBoard() {\r\n\t\tfor (let column of this.spaces) {\r\n\t\t\tfor (let space of column) {\r\n\t\t\t\tspace.drawSVGSpace();\r\n\t\t\t}\t\r\n\t\t}\r\n\t}", "function updateShapeList(){\r\n\tvar list = document.getElementById(\"shapeList\");\r\n\tlist.innerHTML = \"\";\r\n\tvar i =0;\r\n\tfor(i=0;i<sciMonk.currentModel.shapes.length;i++){ /* <--- construction*/\r\n\t\tvar item = document.createElement(\"div\");\r\n\t\titem.setAttribute(\"onClick\",\"inflateEditShapeView(\"+i+\")\");\r\n\t\titem.setAttribute(\"onMouseOver\",\"showMarker(\"+i+\")\");\r\n\t\titem.setAttribute(\"onMouseOut\",\"hideMarker(\"+i+\")\");\r\n\t\tvar c = sciMonk.currentModel.shapes[i].colour;\r\n\t\titem.style.background = rgbToHex(c[0],c[1],c[2]);\r\n\t\titem.id = \"shapeItem\";\r\n\t\titem.innerHTML = \"<p>&lt;\"+sciMonk.currentModel.shapes[i].shapeType+\"&gt;</p>\";\r\n\t\tlist.appendChild(item);\r\n\t}\r\n}", "function createPallet(){\n\tfor(let i = 0; i < numColor; i++){\n\t\tswatches.push(new ColorSwatch(\t((i*colorSwatchRadius)+colorSwatchRadius/2), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcolorSwatchRadius/2, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcolorSwatchRadius/2, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t colorArray[i]));\n\t}\n\tfillIcon = new FillIcon(canvasWidth-frameThickness*.75, canvasWidth/40, canvasWidth/20);\n}", "function drawAllPigs(context) {\r\n for (var i = 0; i < pigs.length; i = i + 1) {\r\n var pig = pigs[i];\r\n drawOnePig(context, pig);\r\n } \r\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
then this function is used to display the appropriate category. if the "all" radio button is checked that means user wants to see all events and so all events are shown. if the "work" radio button is checked that means the user wants to see events related to work and so only work events are shown and so on.
function ischecked(){ if(all.checked){ displayEvent(); displayEvent(); }else if(work.checked){ displayCategory(work.value); displayCategory(work.value); }else if(school.checked){ displayCategory(school.value); displayCategory(school.value); }else if(social.checked){ displayCategory(social.value); displayCategory(social.value); } }
[ "function allDayState(all_day_box) {\n\tif($(all_day_box).is(':checked')) {\n\t\t$('#id_start_time_1').hide();\n\t\t$('#id_end_time_1').hide();\n\t\t$(\"label[for='id_start_time_0']\").text('Day'); \n\t\tif($(\"#id_repeats\").is(':checked')) {\n\t\t\t$('#start-row').hide();\n\t\t\t$('#end-row').hide();\n\t\t} else {\n\t\t\t$('#end-row').hide();\n\t\t}\n\t} else {\n\t\t$('#id_start_time_1').show();\n\t\t$('#id_end_time_1').show();\n\t\t$('#start-row').show();\n\t\t$('#end-row').show();\n\t\t$(\"label[for='id_start_time_0']\").text('Start'); \n\t\tif($(\"#id_repeats\").is(':checked')) {\n\t\t\t$('#id_start_time_0').hide();\n\t\t\t$('#id_end_time_0').hide();\n\t\t} else {\n\t\t\t$('#id_start_time_0').show();\n\t\t\t$('#id_end_time_0').show();\n\t\t}\n\t}\n\n}", "function buildRadioButtons(categories){\n\n // get the holder for radio buttons \"category-listing\"\n var radios = $('.category-listing');\n \n // an extra category for \"all\"\n radios.append('<input type=\"radio\" checked name=\"cat\" value=\"all\">Alla');\n \n // loop through and add the categories we got from ajax\n for(var i = 0; i < categories.length; i++){\n radios.append('<input type=\"radio\" name=\"cat\" value=\"' +\n categories[i].id +'\">' + categories[i].name);\n }\n \n // add a click handler for each radio button including the all one\n radios.find('input').click(function(){\n filterCat = $(this).val();\n getAllProducts();\n });\n\n }", "function showDepEmployeeViews() {\r\n if(this.checked) {\r\n $(\"#specific-view-rights\").css(\"display\", \"none\");\r\n } else {\r\n $(\"#specific-view-rights\").css(\"display\", \"block\");\r\n }\r\n }", "function showHideAccTimeSheet(type)\r\n {\r\n\r\n\r\n \tif(type==\"NewJob\")\r\n \t{\r\n \t\t \r\n document.getElementById(\"assistJob\").style.display=\"none\";\r\n document.getElementById(\"others\").style.display=\"none\";\r\n document.getElementById(\"newJob\").style.display=\"\";\r\n document.getElementById(\"StartStop\").style.display=\"\";\r\n document.getElementById(\"leaveForm\").style.display=\"none\"; \r\n $(\"#selectedradiovalue\").val(\"NewJob\");\r\n \t}\r\n else if(type==\"AssistJob\")\r\n {\r\n \t \r\n \t document.getElementById(\"newJob\").style.display=\"none\";\r\n \t document.getElementById(\"others\").style.display=\"none\";\r\n \t document.getElementById(\"assistJob\").style.display=\"\";\r\n document.getElementById(\"StartStop\").style.display=\"\";\r\n document.getElementById(\"leaveForm\").style.display=\"none\"; \r\n $(\"#selectedradiovalue\").val(\"AssistJob\");\r\n }\r\n else if(type==\"Others\")\r\n {\r\n \t \r\n \t document.getElementById(\"newJob\").style.display=\"none\";\r\n \t document.getElementById(\"assistJob\").style.display=\"none\";\r\n \t document.getElementById(\"others\").style.display=\"\";\r\n document.getElementById(\"StartStop\").style.display=\"\";\r\n document.getElementById(\"leaveForm\").style.display=\"none\"; \r\n $(\"#selectedradiovalue\").val(\"Others\");\r\n } \t\r\n \t\r\n }", "function showSetDepEmployeeViews() {\r\n if(this.checked) {\r\n $(\"#set-specific-view-rights\").css(\"display\", \"none\");\r\n } else {\r\n $(\"#set-specific-view-rights\").css(\"display\", \"block\");\r\n }\r\n }", "function pegaCategoria(e) {\n if (e.target.value === 'Alcóolico') {\n setCategoria(['Alcoholic', 'Non Alcoholic']);\n } else if (e.target.value === 'Categoria') {\n setCategoria([\n 'Ordinary Drink',\n 'Cocktail',\n 'Cocoa',\n 'Shot',\n 'Milk / Float / Shake',\n 'Other / Unknown',\n 'Coffee / Tea',\n 'Homemade Liqueur',\n 'Punch / Party Drink',\n 'Beer',\n 'Soft Drink / Soda',\n ]);\n } else if (e.target.value === 'Copo') {\n setCategoria([\n 'Highball glass',\n 'Cocktail glass',\n 'Old-fashioned glass',\n 'Collins glass',\n ]);\n }\n }", "function selectCategory(event)\n{\n var category = jQuery(this).attr('ref');\n if (null != categoryTreeCash[category])\n {\n _updateSubCategoryPad(category, categoryTreeCash[category]);\n }\n else\n {\n jQuery.ajax({\n url: '/cash-register/index/get-categories/category/' + category,\n type: \"GET\",\n dataType: \"html\",\n success: function(response) {\n updateSubCategoryPad(response, category);\n },\n error: function(xhr, status) {\n alert('ERROR ' + status);\n }\n });\n }\n}", "getCategory() {\n switch (this.foodType) {\n case 'solid': {\n if (this.catPercent <= 1.0) {\n this.catNum = 1;\n\n }\n else if (this.catPercent > 1.0 && this.catPercent <= 2.4) {\n this.catNum = 2;\n\n }\n else {\n this.catNum = 3;\n\n }\n break;\n }\n case 'liquid': {\n if (this.catPercent <= 0.4) {\n this.catNum = 1;\n\n }\n else if (this.catPercent > 0.4 && this.catPercent <= 0.5) {\n this.catNum = 2;\n\n }\n else {\n this.catNum = 3;\n\n }\n break;\n\n }\n case 'soup': {\n if (this.catPercent <= 0.5) {\n this.catNum = 1;\n\n }\n else if (this.catPercent > 0.5 && this.catPercent <= 1.0) {\n this.catNum = 2;\n\n }\n else {\n this.catNum = 3;\n\n }\n break;\n\n }\n default:\n alert('Please choose a category');\n }\n }", "categorizeAdventures() {\n const categorizedAdventures = [];\n this.props.adventures.forEach((adventure) => {\n if (adventure.catagory === this.props.category) { //sic\n categorizedAdventures.push(adventure);\n }\n })\n this.setState({adventures: categorizedAdventures})\n }", "function handleEventTypes() {\n var _this = this;\n\n this.allEventTypes = d3\n .set(\n this.initial_data.map(function(d) {\n return d[_this.config.event_col];\n })\n )\n .values()\n .sort();\n this.currentEventTypes = this.config.event_types || this.allEventTypes.slice();\n this.controls.config.inputs.find(function(input) {\n return input.description === 'Event Type';\n }).start = this.currentEventTypes;\n this.config.color_dom = this.currentEventTypes.concat(\n this.allEventTypes\n .filter(function(eventType) {\n return _this.currentEventTypes.indexOf(eventType) === -1;\n })\n .sort()\n );\n this.config.legend.order = this.config.color_dom.slice();\n }", "function catAndQuest() {\r\n\tdocument.getElementById('points').innerHTML= 'Points ' + (points);\r\n\tdocument.getElementById('count').innerHTML= 'Question ' + (++count);\r\n\tcategory = category[Math.floor(Math.random() * (category.length - 1))];\r\n\tvar questionList;\r\n\tswitch(category) {\r\n\t\tcase category[0]: {\r\n\t\t\tquestionList = historyQuestions;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcase category[1]: {\r\n\t\t\tquestionList = languageQuestions;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcase category[2]: {\r\n\t\t\tquestionList = natureQuestions;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tdefault: {\r\n\t\t\tquestionList = technologyQuestions;\r\n\t\t}\r\n\t}\r\n\tquestion = questionList[Math.floor(Math.random() * (questionList.length - 1))];\r\n\tdocument.getElementById('quest').innerHTML= question.question; // DRY\r\n}", "function showFilteredOrAllChatrooms(state,chatroomElement,categoryElement){\n getDataChatroom(state)\n .then(resQ=>{\n let chatroomArr;\n if(!categoryElement){\n state.chatroomList = resQ;\n chatroomArr = state.chatroomList;\n }else{\n chatroomArr = filterChatroom(state, categoryElement.text(),resQ);\n }\n renderChatroomList(state,chatroomElement,chatroomArr);\n });\n}", "function loadSubCategory() {\n\tvar categorySelect = document.getElementById('categorySelect');\n\tselectedCategory = categorySelect.options[categorySelect.selectedIndex].value;\n\tselectedCategoryText = categorySelect.options[categorySelect.selectedIndex].text;\n\tif (selectedCategory != 0) {\n\t\tdocument.getElementById('subCategory' + selectedCategory).style.display = 'block';\n\t}\n\tfor ( var i = 1; i < 9; i++) {\n\t\tvar id = 'subCategory' + i;\n\t\tif (i == selectedCategory) {\n\t\t\tcontinue;\n\t\t}\n\t\tdocument.getElementById(id).style.display = 'none';\n\t}\n}", "function displayData(date, month, year) {\n\tvar category = {};\n\tvar fistDay = new Date(today.getFullYear(), today.getMonth(), 1);\n\tvar lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0); \n\n\tvar groupby = \"startDate\";\n\n\tfor (var i = 0; i < schedule.length; i++) {\n\t\tif (!category[schedule[i][groupby]])\n\t\t\tcategory[schedule[i][groupby]] = [];\n\t\tif (selectedResourceId == schedule[i][\"resourceId\"]\n\t\t\t\t|| (selectedResourceId == undefined \n\t\t\t\t|| selectedResourceId.trim().length == 0))\n\t\tcategory[schedule[i][groupby]].push(schedule[i]);\n\t}\n\n\tfor (key in category) {\n\t\tif (category.hasOwnProperty(key)) {\n\t\t\tvar dateKey = new Date(key);\n\t\t\tif (category[key].length + \"\\n\") {\n\t\t\t\tfor (var i = 0; i < category[key].length; i++) {\n\t\t\t\t\tif (dateKey.getMonth() == month && dateKey.getFullYear() == year) {\n\t\t\t\t\t\t\n\t\t\t\t\t\tvar startTime = new Date(category[key][i].startDate).getDate();\n\t\t\t\t\t\tvar endTime = new Date(category[key][i].endDate).getDate();\n\t\t\t\t\t\tvar reservationId = date+'0'+category[key][i].reservationId ;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (date >= startTime && date <= endTime) {\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tvar dataDisplay = '<span id ='+reservationId +'>'\n\t\t\t\t\t\t\t\t\t+ category[key][i].startTime + \": \"\n\t\t\t\t\t\t\t\t\t+ category[key][i].resourceName + \"; \"\n\t\t\t\t\t\t\t\t\t+ category[key][i].userName;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tvar dataExisting = document.getElementById(date).innerHTML;\n\t\t\t\t\t\t\tdataExisting = dataExisting + dataDisplay;\n\t\t\t\t\t\t\tvar count = 0;\n\t\t\t\t\t\t\tif (userId == category[key][i].userId || isAdmin) {\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tdocument.getElementById(date).innerHTML = dataExisting + \n\t\t\t\t\t\t\t\t\"<img id='editico' src='/ResourceScheduler/js/delete.png'\" +\n\t\t\t\t\t\t\t\t\" onclick='getIdForDelete(\"+category[key][i].reservationId+\")'>\"+\n\t\t\t\t\t\t\t\t\"<img id='editico' src='/ResourceScheduler/js/icon.png'\" +\n\t\t\t\t\t\t\t\t\"onclick='getData(\"+category[key][i].reservationId+\")'>\" +\n\t\t\t\t\t\t\t\t\"<img id='editico' src='/ResourceScheduler/js/information.png'\" +\n\t\t\t\t\t\t\t\t\"onclick='show(tooltip\"+reservationId+\")'>\" +\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\"<div id='tooltip\"+reservationId+\"' class='tooltip'>Start: \"+category[key][i].startDate+\n\t\t\t\t\t\t\t\t\" \"+category[key][i].startTime+\n\t\t\t\t\t\t\t\t\"<br/>End: \"+category[key][i].endDate+\" \"+category[key][i].endTime+\n\t\t\t\t\t\t\t\t\"<br/>User Name: \"+category[key][i].userName+\n\t\t\t\t\t\t\t\t\"<br/>Resource Name: \"+category[key][i].resourceName+\n\t\t\t\t\t\t\t\t\"</div>\" +\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\"</span><br/>\";\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tdocument.getElementById(reservationId).style.background = '#8DD6C2';\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tdocument.getElementById(date).innerHTML = dataExisting +\n\t\t\t\t\t\t\t\t\t\t\"<img id='editico' src='/ResourceScheduler/js/information.png'\" +\n\t\t\t\t\t\t\t\t\t\t\"onclick='show(tooltip\"+reservationId+\")'>\"+\n\t\t\t\t\t\t\t\t\t\t\"<div id='tooltip\"+reservationId+\"' class='tooltip'>Start: \"+category[key][i].startDate+\n\t\t\t\t\t\t\t\t\t\t\" \"+category[key][i].startTime+\n\t\t\t\t\t\t\t\t\t\t\"<br/>End Time: \"+category[key][i].endDate+\" \"+category[key][i].endTime+\n\t\t\t\t\t\t\t\t\t\t\"<br/>User Name: \"+category[key][i].userName+\n\t\t\t\t\t\t\t\t\t\t\"<br/>Resource Name: \"+category[key][i].resourceName+\n\t\t\t\t\t\t\t\t\t\t\"</div></span><br/>\";\n\t\t\t\t\t\t\t\tdocument.getElementById(reservationId).style.background = '#95C6E8';\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "function getCategory(type){\n if (type == 'jeans' || type == 'pants' || type == 'leggings') return 'pants';\n if (type == 'longsleeve' || type == 'tshirt' || type == 'sweatshirt' || type == 'sweater' || type == 'dress') return 'shirts';\n if (type == 'tennisShoes' || type == 'heels') return 'shoes'; \n if (type == 'baseballHat' || type == 'winterHat' || type == 'gloves') return 'accessories'; \n if (type == 'winterCoat') return 'other';\n else return 'empty';\n}", "function renderFilterChoices() {\n filteredParks = allParks.filter( d => {\n if(filters[0].legend) {\n return d['Overall court grouping'] == filters[0].legend\n }\n else {\n return d\n }\n }).filter( d => {\n if(filters[1].borough) {\n return d['Borough'] == filters[1].borough\n } else {\n return d\n }\n }).filter( d => {\n if(filters[2].park) {\n return d['parkId'] == filters[2].park\n }\n else {\n return d\n }\n })\n\n renderParks(filteredParks) \n }", "function shouldShowEvent(event) {\n\n // Hack to remove canceled Office 365 events.\n if (event.title.startsWith(\"Canceled:\")) {\n return false\n }\n\n // If it's an all-day event, only show if the setting is active.\n if (event.isAllDay) {\n return showAllDay\n }\n\n // Otherwise, return the event if it's in the future.\n return (event.startDate.getTime() > date.getTime())\n}", "function setCategoryCheckboxesEventListener() {\n let categoryForm = document.getElementById('category-form');\n categoryForm.addEventListener('change', filterByCategory);\n}", "static findByCategory(searchCategory) {\r\n let results = []\r\n\r\n for (let event in all) {\r\n if (event.category.has(searchCategory)) {\r\n results.add(event);\r\n }\r\n }\r\n return results;\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Variables: share_display, share_usergen_default, action_share_description, action_page_title, action_page_description, action_links, properties, images, audio, video
function janrain_popup_share(url, options, variables) { // RPXNOW is not loaded in offline (demo) mode if (typeof RPXNOW === 'undefined') return; RPXNOW.loadAndRun(['Social'], function () { if (typeof options != 'object') options = {}; var activity = new RPXNOW.Social.Activity(variables.share_display, variables.action_share_description, url ); activity.setTitle (variables.action_page_title); activity.setDescription (variables.action_page_description); activity.setUserGeneratedContent(variables.share_usergen_default); if (typeof variables.action_links == 'object') { for (i=0; i<variables.action_links.length; i++) { activity.addActionLink(variables.action_links[i].text, variables.action_links[i].href); } } /* if (typeof variables.properties == 'object') { for (i=0; i<variables.properties.length; i++) { activity.addTextProperty(variables.properties[i].text, variables.properties[i].value); } } */ if (typeof variables.media == 'object') { var rpx_images; for (i=0; i<variables.media.length; i++) { var media = variables.media[i]; if (media.type=='image') { if (typeof rpx_images == 'undefined') rpx_images = new RPXNOW.Social.ImageMediaCollection(); rpx_images.addImage(media.src, media.href); } else if (media.type=='audio') { activity.setMediaItem(new RPXNOW.Social.Mp3MediaItem(media.src)); } else if (media.type=='video') { var rpx_video = new RPXNOW.Social.VideoMediaItem( media.original_url, media.thumbnail_url ); rpx_video.setVideoTitle(variables.video[i].caption); activity.setMediaItem(rpx_video); } } if (typeof rpx_images != 'undefined') activity.setMediaItem(rpx_images); } var finished = function(results) { // Process results of publishing. } options.finishCallback = finished; options.urlShortening = true; RPXNOW.Social.publishActivity(activity, options); }); }
[ "function weixinshare(){\n //wx.config({\n // debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。\n // appId: data.appId, // 必填,公众号的唯一标识\n // timestamp: data.timestamp, // 必填,生成签名的时间戳\n // nonceStr: data.nonceStr, // 必填,生成签名的随机串\n // signature: data.signature,// 必填,签名,见附录1\n // jsApiList: ['onMenuShareAppMessage','onMenuShareTimeline'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2\n //});\n wx.ready(function(){\n\n // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。\n // “基本类”按钮详见附录3\n wx.hideAllNonBaseMenuItem();\n });\n}", "function handleShareClick() {\n setShareUrl(window.location.origin + '/?' + simplifiedSharedParamsString);\n }", "function PopupShare(idx) {\r\n \r\n // SEE SAMPLES: https://gist.github.com/chrisjlee/5196139\r\n // https://github.com/Julienh/Sharrre\r\n \r\n var item=G.I[idx];\r\n\r\n var currentURL=document.location.protocol +'//'+document.location.hostname + document.location.pathname;\r\n var newLocationHash='#nanogallery/'+G.baseEltID+'/';\r\n if( item.kind == 'image' ) {\r\n newLocationHash+=item.albumID + '/' + item.GetID();\r\n }\r\n else {\r\n newLocationHash+=item.GetID();\r\n }\r\n \r\n var content ='';\r\n content+='<div class=\"nGY2PopupOneItem\" style=\"text-align:center;\" data-share=\"facebook\">' + G.O.icons.shareFacebook + '</div>';\r\n content+='<div class=\"nGY2PopupOneItem\" style=\"text-align:center;\" data-share=\"pinterest\">' + G.O.icons.sharePinterest + '</div>';\r\n content+='<div class=\"nGY2PopupOneItem\" style=\"text-align:center;\" data-share=\"tumblr\">' + G.O.icons.shareTumblr + '</div>';\r\n content+='<div class=\"nGY2PopupOneItem\" style=\"text-align:center;\" data-share=\"twitter\">' + G.O.icons.shareTwitter + '</div>';\r\n content+='<div class=\"nGY2PopupOneItem\" style=\"text-align:center;\" data-share=\"googleplus\">' + G.O.icons.shareGooglePlus + '</div>';\r\n content+='<div class=\"nGY2PopupOneItem\" style=\"text-align:center;\" data-share=\"vk\">' + G.O.icons.shareVK + '</div>';\r\n content+='<div class=\"nGY2PopupOneItem\" style=\"text-align:center;\" data-share=\"mail\">' + G.O.icons.shareMail + '</div>';\r\n content+='<div class=\"nGY2PopupOneItem\" style=\"text-align:center;\"></div>';\r\n content+='<input class=\"nGY2PopupOneItemText\" readonly type=\"text\" value=\"' + currentURL+newLocationHash + '\" style=\"width:100%;text-align:center;\">';\r\n content+='<br>';\r\n\r\n currentURL=encodeURIComponent(document.location.protocol +'//'+document.location.hostname + document.location.pathname + newLocationHash);\r\n\r\n var currentTitle=item.title;\r\n var currentTn=item.thumbImg().src;\r\n \r\n \r\n Popup('Share to:', content, 'Center');\r\n \r\n G.popup.$elt.find('.nGY2PopupOneItem').on('click', function(e) {\r\n e.stopPropagation();\r\n \r\n var shareURL='';\r\n var found=true;\r\n switch(jQuery(this).attr('data-share').toUpperCase()) {\r\n case 'FACEBOOK':\r\n // <a name=\"fb_share\" type=\"button\" href=\"http://www.facebook.com/sharer.php?u={$url}&media={$imgPath}&description={$desc}\" class=\"joinFB\">Share Your Advertise</a>\r\n //window.open(\"https://www.facebook.com/sharer.php?u=\"+currentURL,\"\",\"height=368,width=600,left=100,top=100,menubar=0\");\r\n shareURL='https://www.facebook.com/sharer.php?u='+currentURL;\r\n break;\r\n case 'VK':\r\n shareURL='http://vk.com/share.php?url='+currentURL;\r\n break;\r\n case 'GOOGLEPLUS':\r\n shareURL=\"https://plus.google.com/share?url=\"+currentURL;\r\n break;\r\n case 'TWITTER':\r\n // shareURL=\"https://twitter.com/share?url=\"+currentURL+\"&text=\"+currentTitle;\r\n shareURL='https://twitter.com/intent/tweet?text='+currentTitle+'url='+ currentURL;\r\n break;\r\n case 'PINTEREST':\r\n // shareURL='https://pinterest.com/pin/create/bookmarklet/?media='+currentTn+'&url='+currentURL+'&description='+currentTitle;\r\n shareURL='https://pinterest.com/pin/create/button/?media='+currentTn+'&url='+currentURL+'&description='+currentTitle;\r\n break;\r\n case 'TUMBLR':\r\n //shareURL='https://www.tumblr.com/widgets/share/tool/preview?caption=<strong>'+currentTitle+'</strong>&tags=nanogallery2&url='+currentURL+'&shareSource=legacy&posttype=photo&content='+currentTn+'&clickthroughUrl='+currentURL;\r\n shareURL='http://www.tumblr.com/share/link?url='+currentURL+'&name='+currentTitle;\r\n break;\r\n case 'MAIL':\r\n shareURL='mailto:?subject='+currentTitle;+'&body='+ currentURL;\r\n break;\r\n default:\r\n found=false;\r\n break;\r\n }\r\n \r\n if( found ) {\r\n window.open(shareURL, \"\" , \"height=550,width=500,left=100,top=100,menubar=0\" );\r\n G.popup.close();\r\n // $popup.remove();\r\n }\r\n \r\n });\r\n }", "function iglooActions () {\n\t//we should have things like pageTitle, user and revid\n\t//here- and the current page\n}", "function shareMedia( _type, _blob, _blob2 )\n{\n\tvar title = $('#input-title').val()\n\tvar description = $('#input-description').val()\n\tvar author = $('#input-author').val()\n\tvar website = $('#input-website').val()\n\tvar timestamp = new Date().getTime()\n\tvar extension = ''\n\tvar xhr = new XMLHttpRequest()\n\tvar fd = new FormData(document.forms[0])\n\tif( _type == 'screenshot' )\n\t{\n\t\txhr.open('POST', '/sharescreenshot', true)\n\t\textension = '.png'\t\t\n\t}\n\tif( _type == 'composition' )\n\t{\n\t\txhr.open('POST', '/sharecomposition', true)\n\t\tfd.append(\"thumbnail\", _blob2, 'thumbnail_' + timestamp + '.png')\n\t\textension = '.json'\n\t}\n\tvar filename = (title.replace(/ /g,'') || _type) + '_' + timestamp + extension\n\tfd.append(\"file\", _blob, filename)\n\tfd.append(\"author\", author || 'anonymous')\n\tfd.append(\"description\", description || 'no description')\n\tfd.append(\"title\", title || 'no title')\n\tfd.append(\"website\", website || '#')\n\txhr.send(fd)\n}", "genShareUrl(mediaId) {\n return `${clientConfig.staticUrl}/embed/@${mediaId}`;\n }", "function set_share (value)\n {\n share = value;\n modify();\n }", "function shareScreen() {\n console.log(\"SHARING SCREEN \" + isSharingScreen);\n document.getElementById(\"share\").disabled = true;\n document.getElementById(\"unshare\").disabled = false;\n document.getElementById(\"share\").style.display = \"none\";\n document.getElementById(\"unshare\").style.display = \"block\";\n leaveChannel();\n setTimeout(function() { \n joinChannel(channel_name, true); \n }, 1000);\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}", "shareFacebookPanophoto(params) {\n this.props.dispatch(shareFacebookPanophoto(params));\n }", "function handleMediaShare(entry) {\n\t\t\t// need to click the entry before entry_method.media is defined\n\t\t\tentry.enterLinkClick(entry.entry_method);\n\t\t\tmarkEntryLoading(entry);\n\n\t\t\t// and then wait\n\t\t\tvar temp_interval = setInterval(function() {\n\t\t\t\tif(entry.entry_method.media) {\n\t\t\t\t\tvar choices = entry.entry_method.media,\n\t\t\t\t\t\trand_choice = choices[Math.floor(Math.random() * choices.length)];\n\n\t\t\t\t\tclearInterval(temp_interval);\n\t\t\t\t\tentry.entry_method.selected = rand_choice;\n\t\t\t\t\tentry.mediaChoiceContinue(entry.entry_method);\n\t\t\t\t\tmarkEntryCompleted(entry);\n\t\t\t\t}\n\t\t\t}, 500);\n\t\t}", "function doMetaData() {\n\t\t\t// Metadata!!\n\n\t\t\t// Featured star!\n\t\t\t// These don't have anything unique, so we can construct whole hearted.\n\n\t\t\tif (($('#featured-star').length) \n\t\t\t\t|| ($('#protected-icon').length)\n\t\t\t\t|| ($('#good-star').length)\n\t\t\t\t|| ($('#spoken-icon').length) ) {\n\t\t\t\t// constuct the metadata box\n\t\t\t\tvar mdBox = $('<div />').addClass('rr_box').addClass('rr_mdcontainer');\n\n\t\t\t\t// Featured\n\t\t\t\tif ($('#featured-star').length) {\n\t\t\t\t\t// Remove the extant featured-star\n\t\t\t\t\t$('#featured-star').remove();\n\t\t\t\t\tvar tBox = $('<div />').addClass('rr_mdbox')\n\t\t\t\t\t\t\t\t\t.addClass('rr_fs')\n\t\t\t\t\t\t\t\t\t.text('Featured')\n\t\t\t\t\t\t\t\t\t.click(function() {\n\t\t\t\t\t\t\t\t\t\twindow.location = \"index.html?page=Wikipedia:Featured_articles\";\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\tmdBox.append(tBox);\n\t\t\t\t} else if ($('#good-star').length) {\n\t\t\t\t\t$('#good-star').remove();\n\t\t\t\t\tvar tBox = $('<div />').addClass('rr_mdbox')\n\t\t\t\t\t\t\t\t\t.addClass('rr_fs')\n\t\t\t\t\t\t\t\t\t.text('Good')\n\t\t\t\t\t\t\t\t\t.click(function() {\n\t\t\t\t\t\t\t\t\t\twindow.location = \"index.html?page=Wikipedia:Good_articles\";\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\tmdBox.append(tBox);\n\t\t\t\t}\n\n\t\t\t\t// Protected\n\t\t\t\tif ($('#protected-icon').length) {\n\t\t\t\t\t// Remove the extant featured-star\n\t\t\t\t\t$('#protected-icon').remove();\n\t\t\t\t\tvar tBox = $('<div />').addClass('rr_mdbox')\n\t\t\t\t\t\t\t\t\t.addClass('rr_prot')\n\t\t\t\t\t\t\t\t\t.text('Protected')\n\t\t\t\t\t\t\t\t\t.click(function() {\n\t\t\t\t\t\t\t\t\t\twindow.location = \"index.html?page=Wikipedia:Protection_policy\";\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\tmdBox.append(tBox);\n\t\t\t\t}\n\t\t\t\t// Spoken icon. Specialized.\n\t\t\t\tif ($('#spoken-icon').length) {\n\t\t\t\t\t//<a href=\"index.html?page=File:4chan.ogg\" title=\"File:4chan.ogg\"><img alt=\"Sound-icon.svg\" src=\"http://upload.wikimedia.org/wikipedia/commons/thumb/4/47/Sound-icon.svg/15px-Sound-icon.svg.png\" width=\"15\" height=\"11\" srcset=\"//upload.wikimedia.org/wikipedia/commons/thumb/4/47/Sound-icon.svg/23px-Sound-icon.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/4/47/Sound-icon.svg/30px-Sound-icon.svg.png 2x\" data-file-width=\"128\" data-file-height=\"96\"></a>\n\t\t\t\t\t// Remove the extant featured-star\n\t\t\t\t\t$('#spoken-icon').remove();\n\t\t\t\t\tvar tBox = $('<div />').addClass('rr_mdbox')\n\t\t\t\t\t\t\t\t.addClass('rr_spoken').text('Listen');\n\t\t\t\t\tmdBox.append(tBox);\n\t\t\t\t}\n\t\t\t\t$('#wsidebar').append(mdBox);\n\t\t\t}\n\t\t}", "function onShareClick() {\n $('.js-email-button').click(function(e) {\n const id = $(this).closest('article').attr('data-id')\n const petObj = getPetFromStore(id)\n window.location.href = `mailto:?&subject=Pet available for adoption from ${petObj.organization.name}&body=Pet Name: ${petObj.attributes.name} // Agency URL: ${petObj.organization.url}`\n })\n}", "function share_product_link() {\n share_icon = document.querySelectorAll('.listing-actions-con a.share');\n for (count = 0; count < 4; count++) {\n click_product(share_icon[count], count + 1).then();\n time_out(share_link = document.querySelector('.internal-share-con .internal-shares a'), count + 1);\n }\n }", "function initShareButton() {\n // share button clicked. copy the link to the clipboard\n $('#share-copy').click(() => {\n var aux = document.createElement(\"input\"); \n aux.setAttribute(\"value\", window.location.href); \n document.body.appendChild(aux); \n aux.select();\n document.execCommand(\"copy\"); \n document.body.removeChild(aux);\n\n alert(\"The share link has been copied to your clipboard.\");\n });\n}", "function createShareButton(memeId) {\n //Create an img element for the picture for the button\n var shareButton = document.createElement(\"img\");\n\n //Add the share button image to the img element\n shareButton.src = \"link.png\";\n\n //Give a class name to the all the share buttons to style all the share buttons\n shareButton.className = \"share_button\";\n\n //Set the onclick function for the share button\n shareButton.onclick = function () {\n //Get the URL of the meme\n var text = document.getElementById(memeId.toString()).childNodes[0].src;\n\n //Try copying the URL to the clipboard\n navigator.clipboard.writeText(text).then(function () {\n //Let the user know the URL was successfully added to the clipboard\n alert(\"Link saved to clipboard!\");\n }, function () {\n //Let the user know the copy failed\n alert(\"Error occurred!\");\n });\n }\n\n //Add the share button to the li element\n document.getElementById(memeId).appendChild(shareButton);\n}", "function configureSharing() {\n\tfor (var objectType in metaData) {\n\t\t\n\t\t//It not iterable or shareable, skip\n\t\tif (!Array.isArray(metaData[objectType])) continue;\n\t\tif (!shareable(objectType)) continue;\n\n\t\t//For each object of objectType\n\t\tfor (var obj of metaData[objectType]) {\n\t\t\n\t\t\t//Set sharing\n\t\t\tsetSharing(objectType, obj);\n\t\t}\n\t}\n}", "function privateDisplaySongMetadata(){\n\t\t/*\n\t\t\tSets all elements that will contain the active song's name metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"name\"]') ){\n\t\t\tvar metaNames = document.querySelectorAll('[amplitude-song-info=\"name\"]');\n\t\t\tfor( i = 0; i < metaNames.length; i++ ){\n\t\t\t\tmetaNames[i].innerHTML = config.active_metadata.name;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tSets all elements that will contain the active song's artist metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"artist\"]') ){\n\t\t\tvar metaArtist = document.querySelectorAll('[amplitude-song-info=\"artist\"]');\n\t\t\tfor( i = 0; i < metaArtist.length; i++ ){\n\t\t\t\tmetaArtist[i].innerHTML = config.active_metadata.artist;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tSets all elements that will contain the active song's album metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"album\"]') ){\n\t\t\tvar metaAlbum = document.querySelectorAll('[amplitude-song-info=\"album\"]');\n\t\t\tfor( i = 0; i < metaAlbum.length; i++ ){\n\t\t\t\tmetaAlbum[i].innerHTML = config.active_metadata.album;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tSets all elements that will contain the active song's cover art metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"cover\"]') ){\n\t\t\tvar coverImages = document.querySelectorAll('[amplitude-song-info=\"cover\"]');\n\t\t\tfor( i = 0; i < coverImages.length; i++ ){\n\t\t\t\t/*\n\t\t\t\t\tChecks to see if first, the song has a defined cover art and uses\n\t\t\t\t\tthat. If it does NOT have defined cover art, checks to see if there\n\t\t\t\t\tis a default. Otherwise it just sets the src to '';\n\t\t\t\t*/\n\t\t\t\tif( config.active_metadata.cover_art_url != undefined){\n\t\t\t\t\tcoverImages[i].setAttribute('src', config.active_metadata.cover_art_url);\n\t\t\t\t}else if( config.default_album_art != '' ){\n\t\t\t\t\tcoverImages[i].setAttribute('src', config.default_album_art);\n\t\t\t\t}else{\n\t\t\t\t\tcoverImages[i].setAttribute('src', '');\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\t/*\n\t\t\tStation information for live streams\n\t\t*/\n\n\t\t/*\n\t\t\tSets all of the elements that will contain the live stream's call sign metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"call-sign\"]') ){\n\t\t\tvar metaCallSign = document.querySelectorAll('[amplitude-song-info=\"call-sign\"]');\n\t\t\tfor( i = 0; i < metaCallSign.length; i++ ){\n\t\t\t\tmetaCallSign[i].innerHTML = config.active_metadata.call_sign;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tSets all of the elements that will contain the live stream's station name metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"station-name\"]') ){\n\t\t\tvar metaStationName = document.querySelectorAll('[amplitude-song-info=\"station-name\"]');\n\t\t\tfor( i = 0; i < metaStationName.length; i++ ){\n\t\t\t\tmetaStationName[i].innerHTML = config.active_metadata.station_name;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tSets all of the elements that will contain the live stream's location metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"location\"]') ){\n\t\t\tvar metaStationLocation = document.querySelectorAll('[amplitude-song-info=\"location\"]');\n\t\t\tfor( i = 0; i < metaStationLocation.length; i++ ){\n\t\t\t\tmetaStationLocation[i].innerHTML = config.active_metadata.location; \n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tSets all of the elements that will contain the live stream's frequency metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"frequency\"]') ){\n\t\t\tvar metaStationFrequency = document.querySelectorAll('[amplitude-song-info=\"frequency\"]');\n\t\t\tfor( i = 0; i < metaStationFrequency.length; i++ ){\n\t\t\t\tmetaStationFrequency[i].innerHTML = config.active_metadata.frequency;\n\t\t\t}\t\n\t\t}\n\n\t\t/*\n\t\t\tSets all of the elements that will contain the live stream's station art metadata\n\t\t\tTODO: Rename coverImages to stationArtImages\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"station-art\"]') ){\n\t\t\tvar coverImages = document.querySelectorAll('[amplitude-song-info=\"station-art\"]');\n\t\t\t/*\n\t\t\t\t\tChecks to see if first, the song has a defined station art and uses\n\t\t\t\t\tthat. If it does NOT have defined station art, checks to see if there\n\t\t\t\t\tis a default. Otherwise it just sets the src to '';\n\t\t\t\t*/\n\t\t\tfor( i = 0; i < coverImages.length; i++ ){\n\t\t\t\tif( config.active_metadata.cover_art_url != undefined){\n\t\t\t\t\tcoverImages[i].setAttribute('src', config.active_metadata.station_art_url);\n\t\t\t\t}else if( config.default_album_art != '' ){\n\t\t\t\t\tcoverImages[i].setAttribute('src', config.default_album_art);\n\t\t\t\t}else{\n\t\t\t\t\tcoverImages[i].setAttribute('src', '');\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\t}", "function outSideForumTreat(){\n var whereAmId=function(){\n var _src, ret=false;\n getUploaderSetting();\n for(var host in gvar.uploader){\n _src = gvar.uploader[host]['src'] || null;\n if( _src && self.location.href.indexOf( _src )!=-1 ){\n ret= String(host); break;\n }\n }\n return ret;\n };\n\n var el,els,par,lb,m=20,loc = whereAmId(),CSS=\"\",i=\"!important\";\n /*\n # do pre-check hostname on location\n */\n if( window == window.top ) return;\n \n \n switch(loc){\n case \"imageshack\":\n CSS=''\n +'h1,#top,.reducetop,#panel,#fbcomments,#langForm,.menu-bottom,#done-popup-lightbox,.ad-col,ins,div>iframe{display:none'+i+'}'\n +'.main-title{border-bottom:1px dotted rgb(204, 204, 204);padding:5px 0 2px 0;margin:5px 0 2px 0}'\n +'.right-col input{padding:0;width:99%;font-family:\"Courier New\";font-size:8pt}'\n ;break;\n case \"imgur\":\n CSS=''\n +'.panel.left #imagelist,#colorbox .top-tr, #upload-global-dragdrop,#upload-global-clipboard,#upload-global-form h1,#upload-global-queue-description{display:none'+i+'}'\n +'#gallery-upload-buttons{width:50%}'\n +'#upload-global-file-list{margin-top:-20px'+i+'}'\n +'#colorbox{position:absolute'+i+';top:0'+i+'}'\n +'.textbox.list{overflow-y:auto'+i+';max-height:100px}'\n ;break; \n case \"imagevenue\":\n CSS=''\n +'table td > table:first-child{display:none'+i+'}'\n ;break;\n case \"imgzzz\":\n CSS=''\n +'#toper,#mem-info,#bottom, .mainbox, .imargin h4{display:none'+i+'}'\n +'body > div{position:absolute;}'\n +'#mid-part{width:30px; background:#ddd; color:transparent;}'\n ;break;\n case \"cubeupload\":\n CSS=''\n +'.bsap{display:none'+i+'}'\n ;break;\n case \"photoserver\":\n CSS=''\n +'body,.content{margin:0'+i+';margin-top:35px'+i+'}'\n +'body>img,#topbar{top:0'+i+'}'\n +'body{background-color:#fff}'\n +'#loginbar{top:38px'+i+';display:block}'\n +'#footer{padding:0}'\n +'#overlay .content{top:3px'+i+'}'\n +'#overlay{position:absolute'+i+'}'\n ;break;\n case \"imagetoo\":\n CSS=''\n +'#topbar, div#top{display:none'+i+'}'\n ;break;\n case \"uploadimage_uk\":\n CSS=''\n +'ins{display:none'+i+'}'\n +'input[type=\"text\"].location{width:80%}'\n ;break;\n case \"uploadimage_in\":\n CSS=''\n +'#logo, p.teaser{display:none'+i+'}'\n +'#header{padding:0; height:25px'+i+';}'\n ;break;\n };\n // end switch loc\n if( CSS!=\"\" ) \n GM_addGlobalStyle(CSS,'inject_host_css', true);\n\n // treat on imageshack\n el = $D('//input[@wrap=\"off\"]',null,true);\n if(loc=='imageshack' && el){\n gvar.sITryKill = window.setInterval(function() {\n if( $D('.ui-dialog') ){\n clearInterval( gvar.sITryKill );\n var lL, ealb;\n\n // make sure, kill absolute div layer\n lb = $D('//div[contains(@style,\"z-index\")]',null);\n if( lL = lb.snapshotLength ){\n for(var i=0; i<lL; i++)\n Dom.remove( lb.snapshotItem(i) )\n }\n if( $D('#ad') ) Dom.remove( $D('#ad') );\n \n window.setTimeout(function(){\n el.removeAttribute('disabled'); \n var par=el.parentNode.parentNode;\n lb = $D('.tooltip',par);\n if(lb){\n lb[0].innerHTML=lb[1].innerHTML='';\n Dom.add(el,par);\n }\n // right-col manipulator\n var ei,et,rTitle=function(t){\n var e = createEl('div',{'class':'main-title'},t);\n return e;\n }, BBCodeImg=function(A){\n return '[IMG]'+A+'[/IMG]';\n }, BBCodeTh=function(A){\n var b=A.lastIndexOf('.'),c=A.substring(0,b)+'.th'+A.substring(b);\n return '[URL='+A+']'+BBCodeImg(c)+'[/URL]';\n };\n if( lb = $D('.right-col',null) ){\n lb[0].innerHTML='';\n et=rTitle('Direct Link'); Dom.add(et, lb[0]);\n ei = createEl('input',{type:'text', value:el.value, readonly:'readonly', 'class':'readonly'});\n _o('focus',ei, function(de){selectAll(de)}); Dom.add(ei, lb[0]);\n try{ei.focus();selectAll(ei)}catch(e){}\n \n et=rTitle('BBCode IMG'); Dom.add(et, lb[0]);\n ei = createEl('input',{type:'text', value:BBCodeImg(el.value), readonly:'readonly', 'class':'readonly'});\n _o('focus',ei, function(de){selectAll(de)}); Dom.add(ei, lb[0]);\n et=rTitle('BBCode Thumbnail'); Dom.add(et, lb[0]);\n ei = createEl('input',{type:'text', value:BBCodeTh(el.value), readonly:'readonly', 'class':'readonly'});\n _o('focus',ei, function(de){selectAll(de)}); Dom.add(ei, lb[0]);\n }\n }, 500);\n }else{\n if(max>0)\n m=m-1;\n else\n clearInterval(gvar.sITryKill);\n }\n }, 50);\n }\n else if(loc == 'imgur'){\n window.setTimeout(function(){\n par = $D('#content');\n par.insertBefore($D('#gallery-upload-buttons'), par.firstChild);\n try{\n Dom.remove($D('//div[contains(@class,\"panel\") and contains(@class,\"left\")]//div[@id=\"imagelist\"]',null,true))\n }catch(e){};\n }, 300);\n gallery = imgur = null;\n }\n return false;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function restart width of every story instead of showing story
function widthStoryRestart() { data.forEach(val => { if (val.id !== accountGlobal.id) { for (let i = 0; i < val.news.length; i++) { val.news[i].width = 0; } } else { for (let i = 0; i < val.news.length; i++) { if (val.news[i].id !== storyGlobal.id) val.news[i].width = 0; } } }) }
[ "function reassignWidth() {\n return data[accountGlobal.id].news[storyGlobal.id - 1].width;\n}", "function setAnimation() {\n const element = document.getElementById(\"mainStory-content\");\n element.classList.remove(\"animationMainStory\");\n void element.offsetWidth;\n element.classList.add(\"animationMainStory\");\n}", "function widenProgram() {\n let s = document.getElementsByClassName('wrap_xyqcvi')[0];\n s.style.setProperty(\"max-width\", \"none\", \"important\");\n\n clearInterval(widenprogram);\n}", "function SlideHorizontallyTransition() {}", "function textWiggle() {\n var timelineWiggle = new TimelineMax({repeat:-1, yoyo:true}); \n for(var j=0; j < 10; j++) {\n timelineWiggle.staggerTo(chars, 0.1, {\n cycle: {\n x: function() { return Math.random()*4 - 2; },\n y: function() { return Math.random()*4 - 2; },\n rotation: function() { return Math.random()*10 - 5; }\n },\n ease: Linear.easeNone\n }, 0);\n }\n }", "[resetRowWidth]() {\n\t\tconst self = this;\n\t\tself.width(self[CURRENT_AVAILABLE_WIDTH] - self[INDENT_WIDTH]);\n\t}", "function changeChannel(channelNum, prevNum) {\n for (let i = 0; i < jackbobStory.children.length; i++) {\n jackbobStory.children[i].classList.add(\"empty\");\n }\n playButton.classList.add(\"empty\");\n jackbobChannel.classList.remove(\"empty\");\n jackbobStory.children[counter].classList.remove(\"empty\");\n\n //this is to play the switch channel animation\n setTimeout(() => {\n jackbobChannel.classList.add(\"empty\");\n // jackbobStory.children[counter].classList.remove(\"empty\");\n if (counter != 0 && counter != maxNum - 1) {\n if (counter > 1) {\n playButton.classList.add(\"airingSoon\");\n } else {\n playButton.classList.remove(\"airingSoon\");\n }\n playButton.classList.remove(\"empty\");\n }\n }, 300);\n // jackbobStory.children[counter].classList.remove(\"empty\");\n}", "onWidthChange(width) {\n // Set new breakpoint\n var newState = {width: width};\n newState.breakpoint = this.getBreakpointFromWidth(newState.width);\n newState.cols = this.getColsFromBreakpoint(newState.breakpoint);\n \n if (newState.cols !== this.state.cols) {\n // Store the current layout\n newState.layouts = this.state.layouts;\n newState.layouts[this.state.breakpoint] = JSON.parse(JSON.stringify(this.state.layout));\n\n // Find or generate the next layout\n newState.layout = this.state.layouts[newState.breakpoint];\n if (!newState.layout) {\n newState.layout = utils.compact(utils.correctBounds(this.state.layout, {cols: newState.cols}));\n }\n }\n this.setState(newState);\n }", "function kata21(smplArr){\n let newElement = document.createElement(\"section\");\n newElement.setAttribute(\"id\", \"section3\");\n let headingElement= document.createElement(\"h1\");\n headingElement.className = \"subHeadingClass\";\n headingElement.appendChild(document.createTextNode(\"21--Display 20 solid gray rectangles, each 20px high, with widths in pixels given by the 20 elements of sampleArray.\"));\n \n var destination = document.getElementById(\"mainSection\");\n destination.appendChild(headingElement);\n destination.appendChild(newElement);\n \n destination = document.getElementById(\"section3\");\n let widthDiv;\n for (i=0;i<20;i++){\n let newElement1 = document.createElement(\"div\");\n let newElement2 = document.createElement(\"div\");\n widthDiv=smplArr[i];\n newElement1.style.width = widthDiv+'px';\n newElement1.className = \"drawRect1\";\n newElement2.className=\"spaceClass\";\n destination.appendChild(newElement1);\n destination.appendChild(newElement2);\n }\n \n}", "function reset(){\n\t\t\t\n\t\t\ttitle.text = _title;\n\t\t\ttitle.updateCache();\n\t\t\ttitle.x = -title.getMeasuredWidth() / 2;\n\t\t\ttitle.y = titleYPOS;\n\t\t\ttitle.alpha = 1;\n\t\t\t\n\t\t\tTweenMax.to([circleOver, smallCircleOver], 0, {scaleX:0, scaleY:0});\n\t\t\tTweenMax.to(title, 0, {y:titleYPOS, x:titleXPOS, alpha:1});\n\t\t}", "restart() {\n this.snake = new Snake();\n this.arcadeStepIncrease = 0.001;\n this.nExplorationWalls = 0;\n this.play();\n }", "function kata20(){\n let newElement = document.createElement(\"section\");\n newElement.setAttribute(\"id\", \"section2\");\n let headingElement= document.createElement(\"h1\");\n headingElement.className = \"subHeadingClass\";\n headingElement.appendChild(document.createTextNode(\"20--Display 20 solid gray rectangles, each 20px high, with widths ranging evenly from 105px to 200px (remember #4, above).\"));\n \n var destination = document.getElementById(\"mainSection\");\n destination.appendChild(headingElement);\n destination.appendChild(newElement);\n \n destination = document.getElementById(\"section2\");\n let widthDiv=105;\n for (i=0;i<20;i++){\n let newElement1 = document.createElement(\"div\");\n let newElement2 = document.createElement(\"div\");\n newElement1.style.width = widthDiv+'px';\n widthDiv+=5;\n newElement1.className = \"drawRect1\";\n newElement2.className=\"spaceClass\";\n destination.appendChild(newElement1);\n destination.appendChild(newElement2);\n }\n \n}", "function displayPlayingPiecesOne() {\n document.querySelectorAll('.pieces1').forEach(function(el) {\n el.style.display = 'grid';\n });\n\n }", "function wideToTall(num) {\n // Replace default classes with tall classes\n if (num == 0) {\n $('#overlay .entry-container').removeClass('entry-container').addClass('tall-entry-container');\n $('#overlay .img-container').removeClass('img-container').addClass('tall-img-container');\n $('#overlay .desc-container').removeClass('desc-container').addClass('tall-desc-container');\n $('#overlay img').addClass('tall-img');\n $('#overlay video').addClass('tall-video');\n }\n // Revert back to default classes\n else {\n $('#overlay .tall-entry-container').removeClass('tall-entry-container').addClass('entry-container');\n $('#overlay .tall-img-container').removeClass('tall-img-container').addClass('img-container');\n $('#overlay .tall-desc-container').removeClass('tall-desc-container').addClass('desc-container');\n // Reset img css\n $('#overlay img').removeClass('tall-img');\n $('#overlay video').removeClass('tall-video');\n }\n return;\n}", "function storyChange() {\n // The \"Finger Family\" is shown\n if (subscriberNumber === 10000) {\n image(storyImages[1], 0, 0, width, height);\n }\n // The \"Skull Family\" is shown\n else if (subscriberNumber === 5000) {\n image(badEndImages[0], 0, 0, width, height);\n }\n // The \"3AM Scene\" is shown\n else if (subscriberNumber === 24000) {\n image(storyImages[2], 0, 0, width, height);\n }\n // The \"Dark 3AM Scene\" is shown\n else if (subscriberNumber === 12000) {\n image(badEndImages[1], 0, 0, width, height);\n }\n // The \"Wholesome ElsaGate Scenario\" is shown\n else if (subscriberNumber === 40000) {\n image(storyImages[3], 0, 0, width, height);\n }\n // The \"Apology Video\" is shown\n else if (subscriberNumber === 20000) {\n image(badEndImages[2], 0, 0, width, height);\n }\n // The first ending image is shown\n else if (subscriberNumber === 50000) {\n image(goodEndImages[0], 0, 0, width, height);\n }\n // The second ending image is shown\n else if (subscriberNumber === 55000) {\n image(goodEndImages[1], 0, 0, width, height);\n }\n // The player's room is shown otherwise\n else {\n image(storyImages[0], 0, 0, width, height);\n }\n\n}", "set requestedWidth(value) {}", "function restart() {\n number = 60;\n start();\n }", "function set_skill_percent(){\n $('.skill-percent-line').each(function() {\n var width = $(this).data( \"width\" );\n $( this ).animate({width: width+'%'}, 1000 );\n\n });\n}", "updateWidth() {\n if (!this.isMounted() || !controller.$contentColumn.length) return;\n\n const left = controller.$contentColumn.offset().left - $(window).scrollLeft();\n const padding = 18;\n let width = $(document.body).hasClass('ltr') ?\n left - padding :\n $(window).width() - (left + controller.$contentColumn.outerWidth()) - padding;\n if (cd.g.skin === 'minerva') {\n width -= controller.getContentColumnOffsets().startMargin;\n }\n\n // Some skins when the viewport is narrowed\n if (width <= 100) {\n this.$topElement.hide();\n this.$bottomElement.hide();\n } else {\n this.$topElement.show();\n this.$bottomElement.show();\n }\n\n this.$topElement.css('width', width + 'px');\n this.$bottomElement.css('width', width + 'px');\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start the Recorder. Returns a promise which resolves when the recorder has started.
start() { return (0, _tslib.__awaiter)(this, void 0, void 0, function* () { (0, _Debug.assert)(this.state !== "started", "Recorder is already started"); const startPromise = new Promise(done => { const handleStart = () => { this._recorder.removeEventListener("start", handleStart, false); done(); }; this._recorder.addEventListener("start", handleStart, false); }); this._recorder.start(); return yield startPromise; }); }
[ "async function initRecorder() {\n let blob = {};\n if (!recorder) {\n try {\n recorder = new MediaRecorder(await initStream());\n } catch (e) {\n throw e;\n }\n //Recorder Events\n recorder.ondataavailable = (e) => {\n blob = e.data;\n };\n recorder.onstop = () => {\n let file = new AudioFile(\"hello\", blob, Date.now());\n addFile(file);\n selectPlaybackFile(file.getTemplate());\n };\n }\n}", "start(){\n this.recording = true ;\n }", "function start() {\n return documentLoaded()\n .then(initServiceWorker)\n .then(dataStore.init)\n .then(notificationsInit)\n .catch(console.log);\n }", "function startCapture() {\n\tinitSize();\n\tinitStyle();\n\t//capturing = true;\n\tstartTime = new Date().getTime();\n\tnextFrame();\n}", "start() {\n return P.resolve()\n .then(() => {\n if (!this._started) {\n this._started = true;\n return this.reload()\n .then(() => {\n dbg.log0('Started hosted_agents');\n this._monitor_stats();\n });\n }\n dbg.log1(`What is started may never start`);\n })\n .catch(err => {\n this._started = false;\n dbg.error(`failed starting hosted_agents: ${err.stack}`);\n throw err;\n })\n .then(() => {\n // do nothing. \n });\n }", "function start() {\n\tgetCurrentPatch()\n\t.then(getChampionIDs)\n\t.then(startScraping)\n\t.then(() => console.log(\"Done scraping.\"))\n\t.catch(function(err) {\n\t\tconsole.log(\"Error on promise chain: \" + err);\n\t\tconsole.log(\"Restarting...\");\n\t\tsleep(30000)\n\t\t.then(start);\n\t});\n}", "function startRecording(evt) {\n //console.log(\"Started recording\");\n\n // Resets the userdata to store new kinect data captures from scratch\n resetUserdata();\n\n // Detach the start/replay buttons, append the stop button, keep listeners\n $startButton.detach();\n $startReplayButton.detach();\n $buttonContainer.append($stopButton);\n\n // Reset frame counter\n frameCounter = 0;\n // Increment session counter\n sessionCounter += 1;\n // Allow recording\n isRecording = true;\n}", "function MediaRecorderWrapper(mediaStream) {\n // if user chosen only audio option; and he tried to pass MediaStream with\n // both audio and video tracks;\n // using a dirty workaround to generate audio-only stream so that we can get audio/ogg output.\n if (this.type == 'audio' && mediaStream.getVideoTracks && mediaStream.getVideoTracks().length && !navigator.mozGetUserMedia) {\n var context = new AudioContext();\n var mediaStreamSource = context.createMediaStreamSource(mediaStream);\n\n var destination = context.createMediaStreamDestination();\n mediaStreamSource.connect(destination);\n\n mediaStream = destination.stream;\n }\n\n // void start(optional long timeSlice)\n // timestamp to fire \"ondataavailable\"\n\n // starting a recording session; which will initiate \"Reading Thread\"\n // \"Reading Thread\" are used to prevent main-thread blocking scenarios\n this.start = function(mTimeSlice) {\n mTimeSlice = mTimeSlice || 1000;\n isStopRecording = false;\n\n function startRecording() {\n if (isStopRecording) return;\n\n mediaRecorder = new MediaRecorder(mediaStream);\n\n mediaRecorder.ondataavailable = function(e) {\n console.log('ondataavailable', e.data.type, e.data.size, e.data);\n // mediaRecorder.state == 'recording' means that media recorder is associated with \"session\"\n // mediaRecorder.state == 'stopped' means that media recorder is detached from the \"session\" ... in this case; \"session\" will also be deleted.\n\n if (!e.data.size) {\n console.warn('Recording of', e.data.type, 'failed.');\n return;\n }\n\n // at this stage, Firefox MediaRecorder API doesn't allow to choose the output mimeType format!\n var blob = new window.Blob([e.data], {\n type: e.data.type || self.mimeType || 'audio/ogg' // It specifies the container format as well as the audio and video capture formats.\n });\n\n // Dispatching OnDataAvailable Handler\n self.ondataavailable(blob);\n };\n\n mediaRecorder.onstop = function(error) {\n // for video recording on Firefox, it will be fired quickly.\n // because work on VideoFrameContainer is still in progress\n // https://wiki.mozilla.org/Gecko:MediaRecorder\n\n // self.onstop(error);\n };\n\n // http://www.w3.org/TR/2012/WD-dom-20121206/#error-names-table\n // showBrowserSpecificIndicator: got neither video nor audio access\n // \"VideoFrameContainer\" can't be accessed directly; unable to find any wrapper using it.\n // that's why there is no video recording support on firefox\n\n // video recording fails because there is no encoder available there\n // http://dxr.mozilla.org/mozilla-central/source/content/media/MediaRecorder.cpp#317\n\n // Maybe \"Read Thread\" doesn't fire video-track read notification;\n // that's why shutdown notification is received; and \"Read Thread\" is stopped.\n\n // https://dvcs.w3.org/hg/dap/raw-file/default/media-stream-capture/MediaRecorder.html#error-handling\n mediaRecorder.onerror = function(error) {\n console.error(error);\n self.start(mTimeSlice);\n };\n\n mediaRecorder.onwarning = function(warning) {\n console.warn(warning);\n };\n\n // void start(optional long mTimeSlice)\n // The interval of passing encoded data from EncodedBufferCache to onDataAvailable\n // handler. \"mTimeSlice < 0\" means Session object does not push encoded data to\n // onDataAvailable, instead, it passive wait the client side pull encoded data\n // by calling requestData API.\n mediaRecorder.start(0);\n\n // Start recording. If timeSlice has been provided, mediaRecorder will\n // raise a dataavailable event containing the Blob of collected data on every timeSlice milliseconds.\n // If timeSlice isn't provided, UA should call the RequestData to obtain the Blob data, also set the mTimeSlice to zero.\n\n setTimeout(function() {\n mediaRecorder.stop();\n startRecording();\n }, mTimeSlice);\n }\n\n // dirty workaround to fix Firefox 2nd+ intervals\n startRecording();\n };\n\n var isStopRecording = false;\n\n this.stop = function() {\n isStopRecording = true;\n\n if (self.onstop) {\n self.onstop({});\n }\n };\n\n this.ondataavailable = this.onstop = function() {};\n\n // Reference to itself\n var self = this;\n\n if (!self.mimeType && !!mediaStream.getAudioTracks) {\n self.mimeType = mediaStream.getAudioTracks().length && mediaStream.getVideoTracks().length ? 'video/webm' : 'audio/ogg';\n }\n\n // Reference to \"MediaRecorderWrapper\" object\n var mediaRecorder;\n}", "function startServer(serverPromise) {\n var self = this,\n startTime = Date.now(),\n browsersStarting,\n serverTimeout,\n serverProcess = fork(__dirname + '/KarmaWorker.js', { silent: true });\n\n // Limit the time it can take for a server to start to config.waitForServerTime seconds\n serverTimeout = setTimeout(function() {\n self._setStatus(KarmaServerStatus.DEFUNCT);\n serverPromise.reject(\n 'Could not connect to a Karma server on port ' + self._config.port + ' within ' +\n self._config.waitForServerTime + ' seconds'\n );\n }, self._config.waitForServerTime * 1000);\n\n serverProcess.send({ command: 'start', config: self._config });\n\n serverProcess.stdout.on('data', function(data) {\n var message = data.toString('utf-8'),\n messageParts = message.split(/\\s/g);\n\n logger.debug(message);\n\n //this is a hack: because Karma exposes no method of determining when the server is started up we'll dissect the log messages\n if(message.indexOf('Starting browser') > -1) {\n browsersStarting = browsersStarting ? browsersStarting.concat([messageParts[4]]) : [messageParts[4]];\n }\n if(message.indexOf('Connected on socket') > -1) {\n browsersStarting.pop();\n if(browsersStarting && browsersStarting.length === 0) {\n clearTimeout(serverTimeout);\n self._setStatus(KarmaServerStatus.READY);\n\n logger.info(\n 'Karma server started after %dms and is listening on port %d',\n (Date.now() - startTime), self._config.port\n );\n\n serverPromise.resolve(self);\n }\n }\n });\n\n return serverProcess;\n}", "startAnalysis() {\n return __awaiter(this, void 0, void 0, function* () {\n yield this._doBuild()\n .then(() => {\n this.update(AnalysisEvent.AnalysisBuildDone);\n })\n .catch((reason) => {\n this.update(AnalysisEvent.AnalysisBuildDone);\n });\n });\n }", "start() {\n var _this = this;\n\n return _asyncToGenerator(function* () {\n let startTask = _this.getTask(_this.workflow.startTaskId);\n\n if (!startTask) {\n throw new Error('Invalid workflow - missing start task');\n }\n\n yield _this.runTask(startTask);\n return _this.finish();\n })();\n }", "stop() {\n return (0, _tslib.__awaiter)(this, void 0, void 0, function* () {\n (0, _Debug.assert)(this.state !== \"stopped\", \"Recorder is not started\");\n const dataPromise = new Promise(done => {\n const handleData = e => {\n this._recorder.removeEventListener(\"dataavailable\", handleData, false);\n\n done(e.data);\n };\n\n this._recorder.addEventListener(\"dataavailable\", handleData, false);\n });\n\n this._recorder.stop();\n\n return yield dataPromise;\n });\n }", "start() {\n if (!this.stop) return\n this.stop = false\n this.__poll()\n }", "function startPreview() {\n //reset isCancelled\n barcodeDecoder.scanning = false;\n barcodeDecoder.isCancelled = false;\n\n // Prevent the device from sleeping while the preview is running\n oDisplayRequest.requestActive();\n\n // Set the preview source in the UI\n previewVidTag = document.createElement(\"video\");\n previewVidTag.id = \"cameraPreview\";\n previewVidTag.style.position = 'absolute';\n previewVidTag.style.top = '0';\n previewVidTag.style.left = '0';\n previewVidTag.style.height = '100%';\n previewVidTag.style.width = '100%';\n previewVidTag.style.zIndex = '900';\n document.body.appendChild(previewVidTag);\n\n var previewUrl = URL.createObjectURL(oMediaCapture);\n previewVidTag.src = previewUrl;\n previewVidTag.play();\n\n previewVidTag.addEventListener(\"playing\", function () {\n isPreviewing = true;\n setPreviewRotationAsync();\n });\n}", "_preload () {\n const preloader = new Preloader();\n\n preloader.run().then(() => { this._start() });\n }", "function startRenderingAudio(context) {\n\t\tconst renderTryMaxCount = 3\n\t\tconst renderRetryDelay = 500\n\t\tconst runningMaxAwaitTime = 500\n\t\tconst runningSufficientTime = 5000\n\t\tlet finalize = () => undefined\n\t\tconst resultPromise = new Promise((resolve, reject) => {\n\t\t\tlet isFinalized = false\n\t\t\tlet renderTryCount = 0\n\t\t\tlet startedRunningAt = 0\n\t\t\tcontext.oncomplete = (event) => resolve(event.renderedBuffer)\n\t\t\tconst startRunningTimeout = () => {\n\t\t\t\tsetTimeout(\n\t\t\t\t\t() => reject(makeInnerError('timeout' /* Timeout */)),\n\t\t\t\t\tMath.min(\n\t\t\t\t\t\trunningMaxAwaitTime,\n\t\t\t\t\t\tstartedRunningAt + runningSufficientTime - Date.now(),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst tryRender = () => {\n\t\t\t\ttry {\n\t\t\t\t\tcontext.startRendering()\n\t\t\t\t\tswitch (context.state) {\n\t\t\t\t\t\tcase 'running':\n\t\t\t\t\t\t\tstartedRunningAt = Date.now()\n\t\t\t\t\t\t\tif (isFinalized) {\n\t\t\t\t\t\t\t\tstartRunningTimeout()\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t// Sometimes the audio context doesn't start after calling `startRendering` (in addition to the cases where\n\t\t\t\t\t\t// audio context doesn't start at all). A known case is starting an audio context when the browser tab is in\n\t\t\t\t\t\t// background on iPhone. Retries usually help in this case.\n\t\t\t\t\t\tcase 'suspended':\n\t\t\t\t\t\t\t// The audio context can reject starting until the tab is in foreground. Long fingerprint duration\n\t\t\t\t\t\t\t// in background isn't a problem, therefore the retry attempts don't count in background. It can lead to\n\t\t\t\t\t\t\t// a situation when a fingerprint takes very long time and finishes successfully. FYI, the audio context\n\t\t\t\t\t\t\t// can be suspended when `document.hidden === false` and start running after a retry.\n\t\t\t\t\t\t\tif (!document.hidden) {\n\t\t\t\t\t\t\t\trenderTryCount++\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tisFinalized &&\n\t\t\t\t\t\t\t\trenderTryCount >= renderTryMaxCount\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\treject(\n\t\t\t\t\t\t\t\t\tmakeInnerError('suspended' /* Suspended */),\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\tsetTimeout(tryRender, renderRetryDelay)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error)\n\t\t\t\t}\n\t\t\t}\n\t\t\ttryRender()\n\t\t\tfinalize = () => {\n\t\t\t\tif (!isFinalized) {\n\t\t\t\t\tisFinalized = true\n\t\t\t\t\tif (startedRunningAt > 0) {\n\t\t\t\t\t\tstartRunningTimeout()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\treturn [resultPromise, finalize]\n\t}", "start() {\n if (!this.eb) {\n this.eb = new EventBus(this.busUrl);\n this.eb.onopen = function() {\n simulatorVerticle.eb.registerHandler(CALLSIGN_FLASH,simulatorVerticle.heartBeatHandler);\n simulatorVerticle.eb.registerHandler(CALLSIGN_BO,simulatorVerticle.carMessageHandler)\n };\n };\n this.enabled=true;\n }", "autoStart() {\r\n return __awaiter(this, void 0, void 0, function* () {\r\n return this.config.autoStartRls && this.start().then(() => true);\r\n });\r\n }", "start() {\n\n this.isPlaying = true; // set the 'playing' boolean to true\n\n this.playing = 0; // reset to the beginning\n this.playCurrent(); // start playing the current track\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process nums, return false if it times out, true otherwise
function processNumsTiming(n, backVals, timeout) { startTime = Date.now(); // Create the numSorter const numSorter = new NumSorter(); // Add even numbers 0 through n to allowed list for (let i = 0; i <= n; i++) { if (i % 2 === 0) numSorter.addAllowedNum(i); if (!checkTimeout(startTime, timeout)) return false // Break if timing out } // Build num list 0 through n numSorter.buildNumList(n); if (!checkTimeout(startTime, timeout)) return false // Break if timing out numCount = Math.floor(n / 2) + 1; expect(numSorter.numCount()).to.equal(numCount); // Add many -2 values to the back for (let i = 0; i < backVals; i++) { // not allowed yet numSorter.addNumToBack(-2); if (!checkTimeout(startTime, timeout)) return false // Break if timing out } // No nums should be added expect(numSorter.numCount()).to.equal(numCount); // Now they are allowed numSorter.addAllowedNum(-2); for (let i = 0; i < backVals; i++) { numSorter.addNumToBack(-2); if (!checkTimeout(startTime, timeout)) return false // Break if timing out } // Check that nums have been added and back let totalCount = numCount + backVals; expect(numSorter.numCount()).to.equal(totalCount) // Check that values are correct for (let i = 0; i < totalCount; i++) { num = numSorter.getFirstNum(); if (!checkTimeout(startTime, timeout)) return false // Break if timing out if (i < numCount) { // Middle nums should be even nums from 0 through n expect(num).to.equal(i * 2); } else { // Back nums should all equal -2 expect(num).to.equal(-2); } } return true; }
[ "function areNumbersInRange(puzzle) {\n for (var i = 0; i < puzzle.length; i++) {\n if (puzzle[i] < 0 || puzzle[i] > 9) {\n return false;\n }\n }\n return true;\n }", "function greaterThanSum(nums) {\n\tlet a = 0;\n\tfor (let i = 0; i < nums.length; i++) {\n\t\tif (a >= nums[i]) return false;\n\t\ta += nums[i];\n\t}\n\treturn true;\n}", "function passOrFail(array) {\n // let pass = false;\n // if (array >= 75) {\n // pass = true;\n // }\n let pass = array.map((x) => x >= 75);\n return pass;\n}", "inInfiniteLoop() {\n return this.round > 1 && arrayEqual(this.keepFactor[this.round - 1], this.keepFactor[this.round - 2]);\n }", "function checkRunOf3(arr) {\n\tfor (var i = 0; i < arr.length; i++) {\n\t\tvar v = arr[i];\n\t\tif (i == 0 || v != lastVal)\n\t\t{\n\t\t\tvar run = 1;\n\t\t\tvar lastVal = v;\n\t\t}\n\t\telse\n\t\t{\n\t\t\trun++;\n\t\t\tif (run>=3) return true;\n\t\t}\n\t}\n\treturn false;\n}", "function hops(arr) {\nvar current = 0;\nvar flag = false;\n\twhile (current !== arr.length - 1) {\n\t\tcurrent += arr[current];\n\t\tif (current === arr.length - 1) {\n\t\t\treturn true;\n\t\t} else if (current === current + arr[current]) {\n\t\t\treturn false;\n\t\t}\n\t}\n}", "function featured(number) {\n if (number > 9876543200) return false;\n let count = number + 1;\n\n\n while(true) {\n if (isOdd(count) && isMultipleOfSeven(count) && isUnique(count)) {\n return count;\n }\n count += 1;\n }\n}", "function checkLoops() {\n\t\tfor (var i = 0, il = this.loops.length; i < il; ++i) {\n\t\t\tvar loop = this.loops[i];\n\t\t\t\n\t\t\tif (loop._current !== loop.iterations && this._currentTime >= loop.stopTime) {\n\t\t\t\tthis._currentTime = loop.startTime;\n\t\t\t\tloop._current++;\n\t\t\t}\n\t\t}\n\t}", "function test (regex, numbers) {\n const append = '8888'\n const res = true\n const rex = new RegExp('^' + regex + '(.*)$')\n\n numbers.forEach(function (n) {\n n = n.replace(/x/g, '0')\n const n1 = n + append\n let res = n1.match(rex)\n\n if (res[1] !== n || res[2] !== append) {\n console.error(n, res)\n res = false\n }\n })\n\n return res\n}", "function isContiguous(nums, target) {\r\n // find all combinations of the list\r\n // https://stackoverflow.com/questions/5752002/find-all-possible-subset-combos-in-an-array\r\n // https://codereview.stackexchange.com/questions/7001/generating-all-combinations-of-an-array\r\n \r\n const combos = new Array(1 << nums.length)\r\n .fill()\r\n .map((e1, i) => {\r\n const combo = nums.filter((e2, j) => i & 1 << j);\r\n return combo;\r\n });\r\n\r\n // check each combo if they sum to target\r\n for (const l of combos) {\r\n let sum = l.reduce((a, b) => a + b, 0);\r\n if (sum === target) {\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n}", "function evenNumbers(numbers) {\n return numbers % 2 == 0;\n\n}", "function primeTime (num){\n\tvar SqrRtNum = Math.sqrt(num);\n\tvar primeNum = true;\n\tfor(var i=2 ; i<SqrRtNum ; i++){\n\t\tif(num%i === 0){\n\t\t\tprimeNum = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn primeNum;\n\n}", "function missingNumber(nums, maxNum) {\n\n let numsObj = new Object();\n\n for ( i = 1; i <= maxNum; i++){\n numsObj[i] = false;\n }\n \n for ( i = 0; i < nums.length; i++){\n let index = nums[i];\n numsObj[index] = true;\n }\n\n for (key in numsObj) {\n if (numsObj[key] === false) {\n return Number(key);\n }\n }\n}", "function OneShotLimitReached()\n{\n\treturn (crashesStarted + gearShiftsStarted) > oneShotLimit;\n}", "function divisible(arr) {\n\tlet sum = 0;\n\tlet prod = 1;\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tsum += arr[i];\n\t\tprod *= arr[i];\n\t}\n\n\tif (prod % sum === 0) {\n\t\treturn true;\t\t\t\n\t} else return false;\n}", "function check_each_task_executes_in_period(schedule){\n var results = {};\n\n var tasks = schedule.workload.tasks;\n\n var result = true;\n\n for(var i=0;i<tasks.length;i++){\n var task = tasks[i];\n\n var periods = schedule.hyperperiod_size / task.period;\n\n var missed_deadlines = [];\n\n var counter = 0;\n for(var j=0;j<periods;j++){\n var period_start = j*task.period;\n var period_end = period_start + task.period;\n\n // find a job in the period and make sure it starts >= its offset\n // and ends <= its deadline. If not, add it to the 'missed deadlines' list to report back\n var job = find_job_in_period(period_start, period_end, task.name, schedule.schedule);\n if(job){\n if((job.start >= (period_start + task.offset))\n &&\n (job.end <= (period_start + task.deadline))){\n counter++;\n } else {\n missed_deadlines.push(job);\n }\n }\n }\n if(counter === periods && missed_deadlines.length == 0){\n results[task.name] = {ok: true, missed_deadlines: []};\n } else {\n result = false;\n results[task.name] = {ok: true, missed_deadlines: missed_deadlines};\n }\n }\n\n return {total_result: result, task_results: results};\n}", "function every(array, callback){\n for (let i = 0; i < arr.length; i++){\n if (!callback(arr[i], i, arr)) return false;\n }\n return true;\n}", "function hasOddNumber(arr){\n return arr.some(function(el){\n return el % 2 !== 0;\n })\n}", "function checkEvery(arr) {\n return arr.every(v => v % 3 == 0 )\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read `Response.body` stream as ArrayBuffer. This function provide progress information by callback.
function readArrayBufferProgressively(res, callback) { if (!callback || !res.body) return res.arrayBuffer(); let contentLength = res.headers.get('Content-Length'); if (!contentLength) return res.arrayBuffer(); const total = parseInt(contentLength); let buffer = new Uint8Array(total); let loaded = 0; let reader = res.body.getReader(); let callbackScheduler = new dispatch_scheduler_1.default(); function accumulateLoadedSize(chunk) { buffer.set(chunk.value, loaded); loaded += chunk.value.length; if (callback) { callbackScheduler.request(() => callback(loaded, total)); } if (loaded == total) { callbackScheduler.forceDispatch(); return buffer.buffer; } else { return reader.read().then(accumulateLoadedSize); } } return reader.read().then(accumulateLoadedSize); }
[ "async *_bodyStream() {\n let buf = yield 0; // dummy yield to retrieve user provided buf.\n if (this.headers.has(\"content-length\")) {\n const len = this.contentLength;\n if (len === null) {\n return;\n }\n let rr = await this.r.read(buf);\n let nread = rr === Deno.EOF ? 0 : rr;\n let nreadTotal = nread;\n while (rr !== Deno.EOF && nreadTotal < len) {\n buf = yield nread;\n rr = await this.r.read(buf);\n nread = rr === Deno.EOF ? 0 : rr;\n nreadTotal += nread;\n }\n yield nread;\n }\n else {\n if (this.headers.has(\"transfer-encoding\")) {\n const transferEncodings = this.headers\n .get(\"transfer-encoding\")\n .split(\",\")\n .map((e) => e.trim().toLowerCase());\n if (transferEncodings.includes(\"chunked\")) {\n // Based on https://tools.ietf.org/html/rfc2616#section-19.4.6\n const tp = new mod_ts_3.TextProtoReader(this.r);\n let line = await tp.readLine();\n if (line === Deno.EOF)\n throw new bufio_ts_2.UnexpectedEOFError();\n // TODO: handle chunk extension\n const [chunkSizeString] = line.split(\";\");\n let chunkSize = parseInt(chunkSizeString, 16);\n if (Number.isNaN(chunkSize) || chunkSize < 0) {\n throw new Error(\"Invalid chunk size\");\n }\n while (chunkSize > 0) {\n let currChunkOffset = 0;\n // Since given readBuffer might be smaller, loop.\n while (currChunkOffset < chunkSize) {\n // Try to be as large as chunkSize. Might be smaller though.\n const bufferToFill = buf.subarray(0, chunkSize);\n if ((await this.r.readFull(bufferToFill)) === Deno.EOF) {\n throw new bufio_ts_2.UnexpectedEOFError();\n }\n currChunkOffset += bufferToFill.length;\n buf = yield bufferToFill.length;\n }\n await this.r.readLine(); // Consume \\r\\n\n line = await tp.readLine();\n if (line === Deno.EOF)\n throw new bufio_ts_2.UnexpectedEOFError();\n chunkSize = parseInt(line, 16);\n }\n const entityHeaders = await tp.readMIMEHeader();\n if (entityHeaders !== Deno.EOF) {\n for (const [k, v] of entityHeaders) {\n this.headers.set(k, v);\n }\n }\n /* Pseudo code from https://tools.ietf.org/html/rfc2616#section-19.4.6\n length := 0\n read chunk-size, chunk-extension (if any) and CRLF\n while (chunk-size > 0) {\n read chunk-data and CRLF\n append chunk-data to entity-body\n length := length + chunk-size\n read chunk-size and CRLF\n }\n read entity-header\n while (entity-header not empty) {\n append entity-header to existing header fields\n read entity-header\n }\n Content-Length := length\n Remove \"chunked\" from Transfer-Encoding\n */\n return; // Must return here to avoid fall through\n }\n // TODO: handle other transfer-encoding types\n }\n // Otherwise... Do nothing\n }\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 }", "_read() {\n if (this.index <= this.array.length) {\n //getting a chunk of data\n const chunk = {\n data: this.array[this.index],\n index: this.index\n };\n //we want to push chunks of data into the stream\n this.push(chunk);\n this.index += 1;\n } else {\n //pushing null wil signal to stream its done\n this.push(null);\n }\n }", "async peekBuffer(uint8Array, options) {\r\n const normOptions = this.normalizeOptions(uint8Array, options);\r\n const res = await fs.read(this.fd, uint8Array, normOptions.offset, normOptions.length, normOptions.position);\r\n if ((!normOptions.mayBeLess) && res.bytesRead < normOptions.length) {\r\n throw new peek_readable_1.EndOfStreamError();\r\n }\r\n return res.bytesRead;\r\n }", "function callback(response) {\r\n var result = '';\t\t// string to hold the response\r\n\r\n // as each chunk comes in, add it to the result string:\r\n response.on('data', function (data) {\r\n result += data;\r\n });\r\n\r\n // when the final chunk comes in, print it out:\r\n response.on('end', function () {\r\n console.log('result: ' + result);\r\n });\r\n}", "function BufferReadStream ( source ) {\n\n if ( ! buffer.isBuffer( source ) ) {\n throw( new Error( \"BufferReadStream source must be a buffer.\" ) );\n }\n\n //Call super constructor.\n stream.Readable.call(this);\n\n this._source = source;\n this._index = 0;\n this._length = this._source.length;\n}", "async function read_stream(readable_stream) {\n const reader = readable_stream.getReader();\n\n let chunks = [];\n while (true) {\n const {value: chunk, done} = await reader.read();\n if (done) {\n break;\n }\n chunks.push(chunk);\n }\n reader.releaseLock();\n\n return chunks;\n}", "async function getBufferFromUrl(url) {\n let arrayBuffer;\n if (globalThis.fetch) {\n const response = await fetch(url);\n arrayBuffer = await response.arrayBuffer();\n } else {\n const fs = await import('fs');\n const uint8Array = await fs.promises.readFile(url);\n arrayBuffer = uint8Array.buffer;\n }\n return arrayBuffer;\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 }", "checkPendingReads() {\n this.fillBuffer();\n\n let reads = this.pendingReads;\n while (reads.length && this.dataAvailable &&\n reads[0].length <= this.dataAvailable) {\n let pending = this.pendingReads.shift();\n\n let length = pending.length || this.dataAvailable;\n\n let result;\n let byteLength = this.buffers[0].byteLength;\n if (byteLength == length) {\n result = this.buffers.shift();\n }\n else if (byteLength > length) {\n let buffer = this.buffers[0];\n\n this.buffers[0] = buffer.slice(length);\n result = ArrayBuffer.transfer(buffer, length);\n }\n else {\n result = ArrayBuffer.transfer(this.buffers.shift(), length);\n let u8result = new Uint8Array(result);\n\n while (byteLength < length) {\n let buffer = this.buffers[0];\n let u8buffer = new Uint8Array(buffer);\n\n let remaining = length - byteLength;\n\n if (buffer.byteLength <= remaining) {\n this.buffers.shift();\n\n u8result.set(u8buffer, byteLength);\n }\n else {\n this.buffers[0] = buffer.slice(remaining);\n\n u8result.set(u8buffer.subarray(0, remaining), byteLength);\n }\n\n byteLength += Math.min(buffer.byteLength, remaining);\n }\n }\n\n this.dataAvailable -= result.byteLength;\n pending.resolve(result);\n }\n }", "async function readStreamFromAsyncIterator() {\n const stream = Readable.from(generate());\n let chunk;\n for await (chunk of stream) {\n console.log(chunk);\n }\n}", "async read(p) {\n let rr = p.byteLength;\n if (p.byteLength === 0)\n return rr;\n if (this.r === this.w) {\n if (p.byteLength >= this.buf.byteLength) {\n // Large read, empty buffer.\n // Read directly into p to avoid copy.\n const rr = await this.rd.read(p);\n const nread = rr === Deno.EOF ? 0 : rr;\n asserts_ts_1.assert(nread >= 0, \"negative read\");\n // if (rr.nread > 0) {\n // this.lastByte = p[rr.nread - 1];\n // this.lastCharSize = -1;\n // }\n return rr;\n }\n // One read.\n // Do not use this.fill, which will loop.\n this.r = 0;\n this.w = 0;\n rr = await this.rd.read(this.buf);\n if (rr === 0 || rr === Deno.EOF)\n return rr;\n asserts_ts_1.assert(rr >= 0, \"negative read\");\n this.w += rr;\n }\n // copy as much as we can\n const copied = util_ts_1.copyBytes(p, this.buf.subarray(this.r, this.w), 0);\n this.r += copied;\n // this.lastByte = this.buf[this.r - 1];\n // this.lastCharSize = -1;\n return copied;\n }", "async function pollQueue(){ //mit axios\n const response = await axios.get('http://localhost:3000/queue/pop')\n if (response.status === 200){ //=== überprüft auch varablentyp, ansonsten \"200\" == 200 !!, webstorm warnt dann vor automat. konvertierung\n const bytes = response.data.bytes //nicht response.body: axios macht daraus response.data\n bytecount += bytes\n }\n}", "fillBuffer() {\n let dataWanted = this.bufferSize - this.dataAvailable;\n\n if (!this._pendingBufferRead && dataWanted > 0) {\n this._pendingBufferRead = this._read(dataWanted);\n\n this._pendingBufferRead.then((result) => {\n this._pendingBufferRead = null;\n\n if (result) {\n this.onInput(result.buffer);\n\n this.fillBuffer();\n }\n });\n }\n }", "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}", "get bytesRead() {\r\n return this.transport ? this.transport.bytesRead : 0;\r\n }", "size() {\n return this.buf.byteLength;\n }", "function loadSample(audioContext, url){\n console.log('done');\n return new Promise(function(resolve, reject){\n fetch(url)\n .then((response) => {\n return response.arrayBuffer();\n })\n .then((buffer) =>{\n audioContext.decodeAudioData(buffer, (decodedAudioData) =>{\n resolve(decodedAudioData);\n });\n });\n });\n}", "static getArrayBuffer(obj) {\r\n let bytesCount = this.countBytes(obj);\r\n let arrayBuffer = new ArrayBuffer(bytesCount);\r\n let view = new DataView(arrayBuffer);\r\n this.serialize(obj, view);\r\n return arrayBuffer;\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle an event where a piece changes without moving or attack
function onPieceChange(data){ //The image is being changed if(data.image) pieces[tiles[(MAX_TILES-1)-data.x][(MAX_TILES-1)-data.y].occupant].image.src = data.image; //The job is being changed if(data.job) pieces[tiles[(MAX_TILES-1)-data.x][(MAX_TILES-1)-data.y].occupant].job = data.job; //Motion is being changed if(data.motion) eval("pieces[tiles[(MAX_TILES-1)-data.x][(MAX_TILES-1)-data.y].occupant].motion = " + data.motion); //Minion was murdered in cold blood, please may we all take a moment of silence if(data.alive == false){ pieces[tiles[(MAX_TILES-1)-data.x][(MAX_TILES-1)-data.y].occupant].alive = false; pieces[tiles[(MAX_TILES-1)-data.x][(MAX_TILES-1)-data.y].occupant].xTile = -1; pieces[tiles[(MAX_TILES-1)-data.x][(MAX_TILES-1)-data.y].occupant].yTile = -1; tiles[(MAX_TILES-1)-data.x][(MAX_TILES-1)-data.y].occupant = -1; } }
[ "function managePiece() {\n this.piece.place(); //we place the piece exactly in a correct position on the grid\n this.grid.mergePiece(this.piece); //we join the piece to the grid\n if (this.isGameOver()) { //if is game over ...\n this.conexionDOM.$soundGameOver[0].src = \"./assets/sound/events/game-over.m4a\"; //we change to \"gameOver\" music\n this.stop(); //we stopped the game\n } else { //if isn't game over ...\n this.grid.handleMatches(this.piece); //we call the function that handles possible matches\n this.piece.reset(this.nextPiece, this.x, this.y); //we take the next piece to play with\n this.nextPiece.isSpecial = false;\n }\n }", "function OnBeamTileConnectionThroughAnchoredSteelCablesUnderTheLegs_Change( e )\r\n{\r\n try\r\n {\r\n var newMeasuresOfEmergencyValue = Alloy.Globals.replaceCharAt( current_structural_elements_id * 13 + 9 , Alloy.Globals.ShedModeDamages[\"MEASURES_OF_EMERGENCY\"] , $.widgetAppCheckBoxShedModeFormsDamagesMeasuresOfEmergencyBeamTileConnectionThroughAnchoredSteelCablesUnderTheLegs.get_value() ) ;\r\n Alloy.Globals.ShedModeDamages[\"MEASURES_OF_EMERGENCY\"] = newMeasuresOfEmergencyValue ;\r\n }\r\n catch( exception )\r\n {\r\n Alloy.Globals.AlertUserAndLogAsync( L( 'generic_exception_msg' ) + exception.message ) ;\r\n }\r\n}", "function OnBeamTileConnectionThroughAnchoredSteelCablesOnTheSidesOfTheLegs_Change( e )\r\n{\r\n try\r\n {\r\n var newMeasuresOfEmergencyValue = Alloy.Globals.replaceCharAt( current_structural_elements_id * 13 + 8 , Alloy.Globals.ShedModeDamages[\"MEASURES_OF_EMERGENCY\"] , $.widgetAppCheckBoxShedModeFormsDamagesMeasuresOfEmergencyBeamTileConnectionThroughAnchoredSteelCablesOnTheSidesOfTheLegs.get_value() ) ;\r\n Alloy.Globals.ShedModeDamages[\"MEASURES_OF_EMERGENCY\"] = newMeasuresOfEmergencyValue ;\r\n }\r\n catch( exception )\r\n {\r\n Alloy.Globals.AlertUserAndLogAsync( L( 'generic_exception_msg' ) + exception.message ) ;\r\n }\r\n}", "function dropPiece(evt, availableTiles, startx, starty)\n{\n var correct = 0; //variable that decides if the piece was placed in the correct spot\n for(var i = 0; i < availableTiles.length;i++)\n {\n if(intersect(availableTiles[i]))\n {\n correct = 1;\n evt.currentTarget.x = availableTiles[i].x;\n evt.currentTarget.y = availableTiles[i].y;\n var x = evt.currentTarget.gridx;\n var y = evt.currentTarget.gridy;\n var tilex = availableTiles[i].gridx;\n var tiley = availableTiles[i].gridy;\n grid[x][y].placedPiece = \"\"; //since the piece has been moved the starting square is free now\n if(grid[tilex][tiley].placedPiece != \"\")\n {\n stage.removeChild(grid[tilex][tiley].placedPiece); //removes the piece that was on that square from the board\n }\n grid[tilex][tiley].placedPiece = evt.currentTarget; //updates the grid to show that there's a piece on the board at that location\n evt.currentTarget.gridx = tilex;\n evt.currentTarget.gridy = tiley;\n\n break;\n }\n }\n cleanBoard(availableTiles); // cleans the board of all pieces\n\n if(correct == 0) // if the piece was not placed in the correct place, then return it to it's original square.\n {\n evt.currentTarget.x = grid[startx][starty].x;\n evt.currentTarget.y = grid[startx][starty].y;\n }\n else { //if the piece was moved then a turn was made and swap turns and update info\n var startSquare = starty*8+x;\n var endSquare = evt.currentTarget.gridy*8+evt.currentTarget.gridx;\n\n moveMade(startSquare, endSquare); //updates the internal logic of the game\n }\n\n parseFen(fenstr); //refreshes the board\n stage.update();\n}", "function moveSomething(e) {\n\t\t\tfunction moveLeftRight(xVal){\n\t\t\t\tvar newX = xVal;\n\t\t\t\tboard.player.xPrev = board.player.x;\n\t\t\t\tboard.player.yPrev = board.player.y;\n\t\t\t\tboard.player.x = newX;\n\t\t\t\tboard.player.y = board.player.y;\n\t\t\t\tboard.position[newX][board.player.y] = 4;\n\t\t\t\tboard.position[board.player.xPrev][board.player.yPrev] = 0;\n\t\t\t\tboard.player.erasePrevious();\n\t\t\t\tboard.player.render();\n\t\t\t}\n\t\t\tfunction moveUpDown(yVal){\n\t\t\t\tvar newY = yVal;\n\t\t\t\tboard.player.xPrev = board.player.x;\n\t\t\t\tboard.player.yPrev = board.player.y;\n\t\t\t\tboard.player.x = board.player.x;\n\t\t\t\tboard.player.y = newY;\n\t\t\t\tboard.position[board.player.x][newY] = 4;\n\t\t\t\tboard.position[board.player.xPrev][board.player.yPrev] = 0;\n\t\t\t\tboard.player.erasePrevious();\n\t\t\t\tboard.player.render();\n\t\t\t}\n\t\t\tfunction enemiesMove(){\n\t\t\t\tif (!board.enemy1.enemyDead)\n\t\t\t\t\tenemy1Move.makeMove();\n\t\t\t\tif (!board.enemy2.enemyDead)\n\t\t\t\t\tenemy2Move.makeMove();\n\t\t\t\tif (!board.enemy3.enemyDead)\n\t\t\t\t\tenemy3Move.makeMove();\n\t\t\t}\n\t\t\tfunction checkForWin(){\n\t\t\t\tif (board.enemy1.enemyDead && board.enemy2.enemyDead && board.enemy3.enemyDead){\n\t\t\t\t\tconsole.log(\"You Win!!!!! *airhorn*\" )\n\t\t\t\t\tboard.player.eraseThis();\n\t\t\t\t\t//board.potion1.eraseThis();\n\t\t\t\t\t//board.potion2.eraseThis();\n\t\t\t\t\tctx.beginPath();\n\t\t\t\t\tctx.font = \"128px Georgia\";\n\t\t\t\t\tctx.fillStyle = \"#00F\";\n\t\t\t\t\tctx.fillText(\"You Win!!\", 40, 320);\n\t\t\t}\n\t\t\t}\n\t\t\tfunction restoreHealth(xVal,yVal){\n\t\t\t\tvar x = xVal;\n\t\t\t\tvar y = yVal;\n\t\t\t\tif (board.position[x][y] == 5){\n\t\t\t\t\tboard.player.restoreHealth();\n\t\t\t\t\tif(board.potion1.x == x && board.potion1.y == y)\n\t\t\t\t\t\tboard.potion1.eraseThis()\n\t\t\t\t\telse \n\t\t\t\t\t\tboard.potion2.eraseThis();\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(!board.player.playerDead || board.enemy1.enemyDead && board.enemy2.enemyDead && board.enemy3.enemyDead){\n\t\t\tswitch(e.keyCode) {\n\t\t\t\tcase 37:\n\t\t\t\t\t// left key pressed\n\t\t\t\t\tvar newX = board.player.x - 1;\n\t\t\t\t\tif(board.player.x == 0)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tif(board.position[newX][board.player.y] == 0 || board.position[newX][board.player.y] == 5)\n\t\t\t\t\t{\n\t\t\t\t\t\tconsole.log(\"Left was pressed...\\n\");\n\t\t\t\t\t\trestoreHealth(newX,board.player.y);\n\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\telse if(board.position[newX][board.player.y] == 3){\n\t\t\t\t\t\tconsole.log(\"Enemy is taking damage...\");\n\t\t\t\t\t\tif(board.enemy1.x == newX && board.enemy1.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy1.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy1.enemyDead)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy2.x == newX && board.enemy2.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy2.takeDamage();\n\t\t\t\t\t\t\t\tif(board.enemy2.enemyDead)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy3.x == newX && board.enemy3.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy3.takeDamage();\n\t\t\t\t\t\t\t\tif(board.enemy3.enemyDead)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t\tcase 38:\n\t\t\t\t\t// up key \n\t\t\t\t\tvar newY = board.player.y - 1;\n\t\t\t\t\tif(board.player.y == 0)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tif(board.position[board.player.x][newY] == 0 || board.position[board.player.x][newY] == 5)\n\t\t\t\t\t{\n\t\t\t\t\t console.log(\"Up was pressed...\\n\");\n\t\t\t\t\t\trestoreHealth(board.player.x,newY);\n\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\telse if(board.position[board.player.x][newY] == 3){\n\t\t\t\t\t\tconsole.log(\"Enemy is taking damage...\");\n\t\t\t\t\t\tif(board.enemy1.x == board.player.x && board.enemy1.y == newY){\n\t\t\t\t\t\t\tboard.enemy1.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy1.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy2.x == board.player.x && board.enemy2.y == newY){\n\t\t\t\t\t\t\tboard.enemy2.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy2.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy3.x == board.player.x && board.enemy3.y == newY){\n\t\t\t\t\t\t\tboard.enemy3.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy3.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 39:\n\t\t\t\t\t// right key pressed\n\t\t\t\t\tvar newX = board.player.x + 1;\n\t\t\t\t\tif(board.player.x == 9)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tif(board.position[newX][board.player.y] == 0 || board.position[newX][board.player.y] == 5)\n\t\t\t\t\t{\n\t\t\t\t\t\tconsole.log(\"Right was pressed...\\n\");\n\t\t\t\t\t\trestoreHealth(newX,board.player.y);\n\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse if(board.position[newX][board.player.y] == 3){\n\t\t\t\t\t\tconsole.log(\"Enemy is taking damage...\");\n\t\t\t\t\t\t\tif(board.enemy1.x == newX && board.enemy1.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy1.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy1.enemyDead){\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy2.x == newX && board.enemy2.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy2.takeDamage();\n\t\t\t\t\t\t\t\tif(board.enemy2.enemyDead){\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy3.x == newX && board.enemy3.y == board.player.y){\n\t\t\t\t\t\t\tboard.enemy3.takeDamage();\n\t\t\t\t\t\t\t\tif(board.enemy3.enemyDead){\n\t\t\t\t\t\t\t\tmoveLeftRight(newX);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 40:\n\t\t\t\t\t// down key pressed\n\t\t\t\t\tvar newY = board.player.y + 1;\n\t\t\t\t\tif(board.player.y == 9)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tif(board.position[board.player.x][newY] == 0 || board.position[board.player.x][newY] == 5)\n\t\t\t\t\t{\n\t\t\t\t\t\tconsole.log(\"Down was pressed...\\n\");\n\t\t\t\t\t\trestoreHealth(board.player.x,newY);\n\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse if(board.position[board.player.x][newY] == 3){\n\t\t\t\t\t\tconsole.log(\"Enemy is taking damage...\");\n\t\t\t\t\t\t\tif(board.enemy1.x == board.player.x && board.enemy1.y == newY){\n\t\t\t\t\t\t\tboard.enemy1.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy1.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy2.x == board.player.x && board.enemy2.y == newY){\n\t\t\t\t\t\t\tboard.enemy2.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy2.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if(board.enemy3.x == board.player.x && board.enemy3.y == newY){\n\t\t\t\t\t\t\tboard.enemy3.takeDamage();\n\t\t\t\t\t\t\tif(board.enemy3.enemyDead){\n\t\t\t\t\t\t\t\tmoveUpDown(newY);\n\t\t\t\t\t\t\t\tcheckForWin();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenemiesMove();\n\t\t\t\t\t}\n\t\t\t\t\tbreak; \n\t\t\t}\n\t\t\t//console.log(\"heres our current player position in moveSomething \"+board.player.x + board.player.y);\n\t\t\t}\t//console.log(\"heres our previous player position in moveSomething \"+board.player.xPrev + board.player.yPrev);\t\t\n\t\t}", "function OnInclusionOfConnectorsMadeOfElementsInABoltedSteelBeamAndTile_Change( e )\r\n{\r\n try\r\n {\r\n var newMeasuresOfEmergencyValue = Alloy.Globals.replaceCharAt( current_structural_elements_id * 13 + 10 , Alloy.Globals.ShedModeDamages[\"MEASURES_OF_EMERGENCY\"] , $.widgetAppCheckBoxShedModeFormsDamagesMeasuresOfEmergencyInclusionOfConnectorsMadeOfElementsInABoltedSteelBeamAndTile.get_value() ) ;\r\n Alloy.Globals.ShedModeDamages[\"MEASURES_OF_EMERGENCY\"] = newMeasuresOfEmergencyValue ;\r\n }\r\n catch( exception )\r\n {\r\n Alloy.Globals.AlertUserAndLogAsync( L( 'generic_exception_msg' ) + exception.message ) ;\r\n }\r\n}", "function performEnPassant(piece, target) {\n if(piece.getId()[0] != 'P')\n return false;\n var currentSpace = piece.getLocation(),\n y1 = currentSpace[1],\n y2 = target.id[1],\n x1 = currentSpace[0].charCodeAt(),\n x2 = target.id[0].charCodeAt(),\n spaceInFrontOfTarget;\n //good en passant\n if(y1 === '5' && y2 === '6' && Math.abs(x2-x1) === 1) {\n spaceInFrontOfTarget = String.fromCharCode(x2) + '5';\n spaceInFrontOfTarget = document.getElementById(spaceInFrontOfTarget).firstChild;\n if(spaceInFrontOfTarget && containsClass(spaceInFrontOfTarget.className, \"chessMan2\") && spaceInFrontOfTarget.id[0] === 'P') {\n spaceInFrontOfTarget.remove();\n //put the piece being captured in discard container.\n document.getElementsByClassName('bucketOfChess2')[0].appendChild(spaceInFrontOfTarget);\n return true;\n }\n } \n //evil en passant\n if(y1 === '4' && y2 === '3' && Math.abs(x2-x1) === 1) {\n spaceInFrontOfTarget = String.fromCharCode(x2) + '4';\n spaceInFrontOfTarget = document.getElementById(spaceInFrontOfTarget).firstChild;\n if(spaceInFrontOfTarget && containsClass(spaceInFrontOfTarget.className, \"chessMan1\") && spaceInFrontOfTarget.id[0] === 'P') {\n spaceInFrontOfTarget.remove();\n //put the piece being captured in discard container.\n document.getElementsByClassName('bucketOfChess1')[0].appendChild(spaceInFrontOfTarget);\n return true;\n }\n } \n}", "handleEvent(event) {\n const info = privates.get(this);\n\n // clear any waiting timer\n if (info.timer) {\n clearTimeout(info.timer);\n info.timer = 0;\n }\n\n // then analyze the action\n switch (event.type) {\n case 'press':\n this.onButtonPress(event);\n break;\n case 'changed':\n if (event.currentTarget === info.doors) {\n this.onDoorsChanged(event);\n } else {\n this.onElevatorChanged(event);\n }\n break;\n }\n }", "handleEatingClue(clue) {\n // Calculate distance from this predator to the prey\n let d = dist(this.x, this.y, clue.x, clue.y);\n // Check if the distance is less than their two radii (an overlap)\n if (d < (this.radius + clue.radius) && clue.isAlive === true) {\n timeToGrowPower = 0;\n // Increase predator health and constrain it to its possible range\n this.health += this.healthGainPerEat;\n this.health = constrain(this.health, 0, this.maxHealth);\n //update the clues caught score if its not alive anymore\n this.cluesCaught += 1;\n itemCaughtSound.play(); //plays the catch sound when someone gets caught by spies\n clue.isAlive = false; //the clue is not alive anymore\n }\n }", "function handleMove(event) {\n console.log('Handling player move.');\n game.recordMove(event);\n game.checkForWinner();\n game.switchPlayer();\n}", "function OnPillarPillarConnectionThroughMetalDishesAtTheEndOfThePier_Change( e )\r\n{\r\n try\r\n {\r\n var newMeasuresOfEmergencyValue = Alloy.Globals.replaceCharAt( current_structural_elements_id * 13 + 6 , Alloy.Globals.ShedModeDamages[\"MEASURES_OF_EMERGENCY\"] , $.widgetAppCheckBoxShedModeFormsDamagesMeasuresOfEmergencyPillarPillarConnectionThroughMetalDishesAtTheEndOfThePier.get_value() ) ;\r\n Alloy.Globals.ShedModeDamages[\"MEASURES_OF_EMERGENCY\"] = newMeasuresOfEmergencyValue ;\r\n }\r\n catch( exception )\r\n {\r\n Alloy.Globals.AlertUserAndLogAsync( L( 'generic_exception_msg' ) + exception.message ) ;\r\n }\r\n}", "function on_piece_select()\n{\n\tupdate_editor();\n}", "function mouseAction(event) { \nif((isWhite && whitePly) || (isBlack && !whitePly)) { //check player\n\n if(gameOver) { return; }\n var mouseX = event.clientX / aspectRatio;\n var mouseY = event.clientY / aspectRatio;\n var x = Math.floor(mouseX / squareSize);\n\n var y = Math.floor(mouseY / squareSize);\n if (isBlack) {\n y = 7 - y; //black's board is inverted to have black pieces at the bottom.\n x = 7 - x; // and mirrored\n\n }\n if(event.button === 0) {\n\tif(selectedSquare[0] == -1 || !isPieceSelected || boardArray[y][x] != \" \") {\n\t\tvar piece = boardArray[y][x]\n\t if(piece != \" \" && isTurn(piece)) {\n\t \t\tisPieceSelected = true;\n\t \t\tconsole.log(x);\n\t\t\tconsole.log(y);\n\t\t\tselectedSquare = [y, x];\n\t\t\tdrawPosition();\n\t\t\tlegalMoves = [];\n\t\t\tlegalMoves = findLegalMoves(y, x, true);\n\t\t\t\n\t\t\tdrawPosition();\n\t\t\t\n\t } else {\n \tmoveHandler(x,y);\n \t\n \tisPieceSelected = false;\n \tdrawPosition();\n\t }\n\t\t \n\t \n\t} else {\n\t\tmoveHandler(x, y);\n\t\t\n\t\tisPieceSelected = false;\n\t\tdrawPosition();\n\t\t\n\t}\t\t\t\t\t\t\t \n }\n} else { drawPosition(); }\n}", "function manageSpecialPiece() {\n if ((this.timeSpecialPiece % SPECIAL_FRECUENCY) === 0) {\n this.specialPieces.push(new Piece(this.ctx, this.x + POS_X_SPECIAL_PIECE +POS_X_GRID, POS_Y_SPECIAL_PIECE + POS_Y_GRID, true));\n this.conexionDOM.$soundEvents[0].src = \"./assets/sound/events/xtra-special.m4a\";\n this.timeSpecialPiece = 0;\n }\n }", "getNewPiece_() {\r\n if (this.isGameOver) {\r\n return\r\n }\r\n\r\n if (!this.isNewPieceNeeded_) {\r\n this.pieceTracker_();\r\n\r\n return;\r\n }\r\n\r\n let newPieceCoord = [];\r\n\r\n this.isNewPieceNeeded_ = false;\r\n this.piece_ = new Piece(this.gameConfig_);\r\n this.pieceController_.wrapNewPiece(this.piece_);\r\n newPieceCoord = this.piece_.getRandomPieceCoord();\r\n this.board_.updateMatrix(newPieceCoord);\r\n this.isGameOver = this.board_.isBoardFilledOnYAxis;\r\n\r\n requestAnimationUtil(this.getNewPiece_, this.gameSpeed_);\r\n }", "function OnPillarPillarConnectionThroughStrandSteel_Change( e )\r\n{\r\n try\r\n {\r\n var newMeasuresOfEmergencyValue = Alloy.Globals.replaceCharAt( current_structural_elements_id * 13 + 7 , Alloy.Globals.ShedModeDamages[\"MEASURES_OF_EMERGENCY\"] , $.widgetAppCheckBoxShedModeFormsDamagesMeasuresOfEmergencyPillarPillarConnectionThroughStrandSteel.get_value() ) ;\r\n Alloy.Globals.ShedModeDamages[\"MEASURES_OF_EMERGENCY\"] = newMeasuresOfEmergencyValue ;\r\n }\r\n catch( exception )\r\n {\r\n Alloy.Globals.AlertUserAndLogAsync( L( 'generic_exception_msg' ) + exception.message ) ;\r\n }\r\n}", "movePiece(p_index, t_index) {\n // Pull variables out of loop to expand scope\n let piece = null;\n let o_tile = null;\n let t_tile = null;\n\n // Look for old and new tiles by index\n for (let line of this.board) {\n for (let tile of line) {\n if (tile.index === p_index) {\n // Grap piece and old tile\n piece = tile.piece;\n o_tile = tile;\n }\n if (tile.index === t_index) {\n // Grab target tile\n t_tile = tile;\n }\n }\n }\n\n // Only move piece if old tile has one to move and move id valid\n // Make sure you can't take out your own pieces\n if (o_tile.piece && t_tile.valid) {\n if (o_tile.piece.color === this.turn) {\n if (t_tile.piece) {\n if (o_tile.piece.color !== t_tile.piece.color) {\n o_tile.piece = null;\n t_tile.piece = piece;\n this.turn = this.turn === 'black' ? 'white' : 'black'; \n }\n } else { \n o_tile.piece = null;\n t_tile.piece = piece;\n this.turn = this.turn === 'black' ? 'white' : 'black'; \n }\n }\n }\n\n // Reset all valid tags\n for (let line of this.board) {\n for (let tile of line) {\n tile.valid = false;\n }\n }\n }", "function mouseGrab(e) {\n console.log(\"mouseGrab\");\n var evt = e|| window.event;\n mousePiece = evt.target || evt.srcElement;\n maxZ ++;\n\n //Remove piece from array and stop animation\n $(mousePiece).stop(true);\n var index = movingPieces.indexOf(mousePiece);\n movingPieces.splice(index, 1);\n console.log(movingPieces);\n\n //Loop through an array with all removed pieces and assign a stop() to them\n // I think the updating of the animate array is a bit slow so it doesn't always apply when you click the piece\n stoppedPieces.push(mousePiece);\n\n mousePiece.style.zIndex = maxZ; // Place the piece above other objects\n\n mousePiece.style.cursor = \"move\";\n\n var mouseX = evt.clientX; // x-coordinate of pointer\n var mouseY = evt.clientY; // y-coordinate of pointer\n\n /* Calculate the distance from the pointer to the piece */\n diffX = parseInt(mousePiece.style.left) - mouseX;\n diffY = parseInt(mousePiece.style.top) - mouseY;\n\n /* Add event handlers for mousemove and mouseup events */\n addEvent(document, \"mousemove\", mouseMove, false);\n addEvent(document, \"mouseup\", mouseDrop, false);\n }", "move(tile) {\r\n if (this.player === this.map.cp) {\r\n if (!this.player.moved) {\r\n this.tile.unit = null\r\n this.tile = tile;\r\n tile.unit = this;\r\n this.mapX = tile.mapX;\r\n this.mapY = tile.mapY;\r\n this.hasFocus = false;\r\n this.pos = tile.pos;\r\n this.player.moved = true;\r\n if (tile.village) {\r\n if (tile.village.owner !== this.player) {\r\n tile.village.enemyStartTurn = this.map.turnCount;\r\n tile.village.attackedBy = this.player;\r\n } else {\r\n tile.village.enemyStartTurn = null;\r\n tile.village.attackedBy = null;\r\n }\r\n }\r\n }\r\n }\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CLUSTER MEAN get means of point in first and in 2nd half of arrays
clusterMean(data) { let half = data.slice(0, Math.floor(data.length / 2)); // first half of distances array const halfMeanX = half.map(p => p.x).reduce((a, b) => a + b) / half.length; const halfMeanY = half.map(p => p.y).reduce((a, b) => a + b) / half.length; let end = data.slice(Math.floor(data.length / 2), data.length); // second half of distances array const endMeanX = end.map(p => p.x).reduce((a, b) => a + b) / end.length; const endMeanY = end.map(p => p.y).reduce((a, b) => a + b) / end.length; const halfMean = { x: halfMeanX, y: halfMeanY } const endMean = { x: endMeanX, y: endMeanY } return { half: halfMean, end: endMean } }
[ "assignedPointsMean(arr, len) {\n \n const meanX = arr.map(p => p.x).reduce((a, b) => a + b) / len;\n const meanY = arr.map(p => p.y).reduce((a, b) => a + b) / len;\n return {\n x: meanX,\n y: meanY\n }\n }", "function calculateMean() {\n var mean = 0;\n for (var j = 0; j < $scope.data2.length; j++) {\n mean = mean + $scope.data2[j].y;\n }\n return mean = ((mean / 24).toFixed(2));\n }", "initMeans(k = 2) {\n this.means.length = k;\n this.means.fill(0)\n this.k = k;\n\n this.means.forEach((el, i) => {\n let cand = new P(400 * Math.random(), 400 * Math.random()); // this.el.width\n this.means.push(cand);\n });\n\n this.means = this.means.slice(k); // [0, 0, Point, Point] remove 2 zeros\n return this.means;\n }", "static seed(cluster) {\n let centroid = this.centroid(cluster)\n let mean = undefined\n let closestDistance = undefined\n for (let s = 0; s < cluster.stops.length; ++s) { \n let distance = this.distance(centroid.latitude, centroid.longitude, cluster.stops[s].latitude, cluster.stops[s].longitude)\n if (!closestDistance || distance < closestDistance) {\n mean = cluster.stops[s]\n closestDistance = distance\n }\n }\n if (!mean) console.log(\"Could not find centroid of cluster with id: \" + cluster.id)\n return mean\n }", "average(marks) {}", "average(stats) {\n return this.add(stats).scale(0.5);\n }", "function calculateAverage(){\n var average = new THREE.Vector2();\n for (let i = 0; i < allVectors.length; i++) {\n average.x += allVectors[i].x;\n average.y += allVectors[i].y;\n }\n average.x = average.x/allVectors.length;\n average.y = average.y/allVectors.length;\n return average;\n}", "function mean_with_reduce(array,callback) {\n if (callback) {\n array.map( callback );\n } \n const total = array.reduce((a, b) => a + b);\n return total/array.length;\n}", "function mean(values) {\n var average = []\n for (var i = 0; i < values.length; i++) {\n var sum = 0;\n for (var j = 0; j < values[i].length; j++) {\n sum = sum + values[i][j]\n }\n average.push(sum/values[i].length)\n }\n return average;\n }", "static centroid(cluster) {\n // NOTE: latitude [-90, 90] (South-North)\n // longitude [-180, 180] (West-East)\n let x = 0, y = 0, z = 0 // Cartesian coordinates\n for (let i = 0; i < cluster.stops.length; ++i) {\n let lat = cluster.stops[i].latitude / 180 * Math.PI\n let lon = cluster.stops[i].longitude / 180 * Math.PI\n // Convert lat/lon to Cartesian and calculate (rolling) average\n x = x * (i)/(i+1) + Math.cos(lat) * Math.cos(lon) / (i+1)\n y = y * (i)/(i+1) + Math.cos(lat) * Math.sin(lon) / (i+1)\n z = z * (i)/(i+1) + Math.sin(lat) / (i+1)\n }\n // Convert back to lat/lon\n return {latitude: Math.atan2(z, Math.sqrt(x*x + y*y)) * 180 / Math.PI, longitude: Math.atan2(y, x) * 180 / Math.PI}\n }", "assign(centrs) {\n\n let APoints = [],\n BPoints = [];\n\nlet points = this.points;\n points.forEach((val, i) => {\n\n let zerox = points[i].x - centrs[0].x; // distance to 1st centroid\n let zeroy = points[i].y - centrs[0].y;\n let onex = points[i].x - centrs[1].x; // distance to 2nd centroid\n let oney = points[i].y - centrs[1].y;\n\n\n // get posititive of each point from each centroid\n let sqzerox = Math.sqrt(zerox * zerox);\n let sqzeroy = Math.sqrt(zeroy * zeroy);\n let sqonex = Math.sqrt(onex * onex);\n let sqoney = Math.sqrt(oney * oney);\n\n // if the point is within the range (all points have less distance than 110 px to all points) push it to according array\n let ranges = this.getRanges();\n (sqzerox || sqzeroy) < ranges.xrange / 3 ? APoints.push(points[i]) : 0;\n (sqonex || sqoney) < ranges.xrange / 3 ? BPoints.push(points[i]) : 0;\n });\n\n return {\n AP: APoints,\n BP: BPoints\n };\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 cluster(xSpread, ySpread, fullness, compactness) {\n clusterArray = [];\n var maxDistance = Math.pow(Math.pow(ySpread, 2) + Math.pow(xSpread, 2), 0.5);\n for (var row = 0; row < 2 * ySpread; row++) {\n for (var col = 0; col < 2 * xSpread; col++) {\n var currentDistance = Math.pow(Math.pow(row - ySpread, 2) + Math.pow(col - xSpread, 2), 0.5);\n if (Math.random() < fullness * Math.pow(1 - currentDistance / maxDistance, compactness)) {\n clusterArray.push([col, row]);\n }\n }\n }\n console.log(clusterArray);\n return array1DTo2D(clusterArray);\n}", "function oneSampleMeans(sampleData, hypothetical_mean) {\n const sampleMean = sampleData.mean;\n const sd = Math.sqrt(sampleData.variance);\n const rootN = Math.sqrt(sampleData.number_of_units);\n // Returning the t value\n return (sampleMean - hypothetical_mean) / (sd / rootN);\n}", "function TempMeanValues()\r\n{\r\n\tCountryValues.call(this);\r\n}", "#rms(array) {\n const squares = array.map((value) => value * value);\n const sum = squares.reduce((accumulator, value) => accumulator + value);\n const mean = sum / array.length;\n return Math.sqrt(mean);\n }", "function fn_appendRegionalMeans(svg, geogroup_name, this_dim, data, x, y) {\n //data to plot\n var regionalVar = [];\n regionalVar[0] = this_dim === \"per capita\" ? \n regionalAvgs[geogroup_name] : regionalAvgs_GDP[geogroup_name];\n\n //city at x-axis endpts of horizontal line\n var x1_city = data[0].city;\n var x2_city = data[data.length - 1].city;\n\n //Tooltip for lines \n var tool_tip = d3.tip()\n .attr(\"class\", \"d3-tip-line\")\n .offset([-10, 0])\n .html(function (d, i) {\n console.log(\"this_dim: \", this_dim)\n console.log(\"this_dim u: \", dimUnits[this_dim])\n return (this_dim === \"per capita\" ? regionalVar : formatDecimalk(regionalVar[0]) )\n + \" \" + dimUnits[this_dim];\n });\n svg.call(tool_tip);\n\n //append line for regional mean\n svg.append(\"g\").selectAll(\"line\")\n .data(regionalVar)\n .enter().append(\"line\")\n .attr(\"class\", \"line\")\n .style(\"stroke\", \"#555\")\n .style(\"stroke-width\", \"2px\")\n .attr(\"x1\", function (d, i) { return x(x1_city); })\n .attr(\"y1\", function (d, i) { return y(d); })\n .attr(\"x2\", function (d, i) { return x(x2_city); })\n .attr(\"y2\", function (d, i) { return y(d); });\n\n //make an invisible fat line and use for tooltip so that\n //user does not have to position mouse over thin regional line\n //with surgical precision\n svg.append(\"g\").selectAll(\"line\")\n .data(regionalVar)\n .enter().append(\"line\")\n .attr(\"class\", \"line\")\n .style(\"stroke\", \"#555\")\n .style(\"stroke-width\", \"6px\")\n .style(\"opacity\", 0)\n .attr(\"x1\", function (d, i) { return x(x1_city); })\n .attr(\"y1\", function (d, i) { return y(d); })\n .attr(\"x2\", function (d, i) { return x(x2_city); })\n .attr(\"y2\", function (d, i) { return y(d); })\n .on('mouseover', tool_tip.show)\n .on('mouseout', tool_tip.hide); \n}", "function avgAge(persons) \n{\n var out;\nout=persons.reduce()\n\n return out\n}", "function findMinMax(centroid1, centroid2, data){\n\n\t\t//Kolla om någon av arrayerna är tom\n\t\t//Vad händer om all data tillhör cent 1 eller cent 2\n\n\t\tvar maxmin = [];\n\n\t\tif (centroid1.length != 0)\n\t\t{\n\t\t\tvar minAcen1 = data[centroid1[0]].A; \n\t\t\tvar minBcen1 = data[centroid1[0]].B; \n\t\t\tvar minCcen1 = data[centroid1[0]].C;\n\t\t\tvar maxAcen1 = 0;\n\t\t\tvar maxBcen1 = 0;\n\t\t\tvar maxCcen1 = 0;\n\n\t\t\tfor(i = 0; i < centroid1.length; i++)\n\t\t\t{\n\t\t\t\tif(data[centroid1[i]].A < minAcen1)\n\t\t\t\t{\n\t\t\t\t\tmaxAcen1 = minAcen1;\n\t\t\t\t\tminAcen1 = data[centroid1[i]].A;\n\n\t\t\t\t}\n\t\t\t\tif(data[centroid1[i]].B < minBcen1)\n\t\t\t\t{\n\t\t\t\t\tmaxAcen1 = minAcen1;\n\t\t\t\t\tminBcen1 = data[centroid1[i]].B;\n\t\t\t\t}\n\t\t\t\tif(data[centroid1[i]].C < minCcen1)\n\t\t\t\t{\n\t\t\t\t\tmaxAcen1 = minAcen1;\n\t\t\t\t\tminCcen1 = data[centroid1[i]].C;\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tif( centroid2.length != 0)\n\t\t{\n\t\t\tvar minAcen2 = data[centroid2[0]].A; \n\t\t\tvar minBcen2 = data[centroid2[0]].B; \n\t\t\tvar minCcen2 = data[centroid2[0]].C; \n\t\t\tvar maxAcen2 = 0;\n\t\t\tvar maxBcen2 = 0;\n\t\t\tvar maxCcen2 = 0;\n\n\t\t\tfor(i = 0; i < centroid2.length; i++)\n\t\t\t{\n\t\t\t\tif(data[centroid2[i]].A < minAcen2)\n\t\t\t\t{\n\t\t\t\t\tmaxAcen2 = minAcen2;\n\t\t\t\t\tminAcen2 = data[centroid2[i]].A;\n\n\t\t\t\t}\n\t\t\t\tif(data[centroid2[i]].B < minBcen2)\n\t\t\t\t{\n\t\t\t\t\tmaxAcen2 = minAcen2;\n\t\t\t\t\tminBcen2 = data[centroid2[i]].B;\n\t\t\t\t}\n\t\t\t\tif(data[centroid2[i]].C < minCcen2)\n\t\t\t\t{\n\t\t\t\t\tmaxAcen2 = minAcen2;\n\t\t\t\t\tminCcen2 = data[centroid2[i]].C;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\t\n\t\t\tconsole.log(\"Cen1, Min A: \" + minAcen1);\n\t\t\tconsole.log(\"Cen1, Min B: \" + minBcen1);\n\t\t\tconsole.log(\"Cen1, Min C: \" + minCcen1);\n\n\t\t\tconsole.log(\"Cen1, Max A: \" + maxAcen1);\n\t\t\tconsole.log(\"Cen1, Max B: \" + maxBcen1);\n\t\t\tconsole.log(\"Cen1, Max C: \" + maxCcen1);\n\n\t\t\tconsole.log(\"------------------------\");\n\n\t\t\tconsole.log(\"Cen2, Min A: \" + minAcen2);\n\t\t\tconsole.log(\"Cen2, Min B: \" + minBcen2);\n\t\t\tconsole.log(\"Cen2, Min C: \" + minCcen2);\n\n\t\t\tconsole.log(\"Cen2, Max A: \" + maxAcen2);\n\t\t\tconsole.log(\"Cen2, Max B: \" + maxBcen2);\n\t\t\tconsole.log(\"Cen2, Max C: \" + maxCcen2);\n\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set access to a Resource for a specific Agent. This function adds the relevant Access Control Policies and Rules to a Resource's Access Control Resource to define the given access for the given Agent specifically. In other words, it can, for example, add Policies that give a particular Agent Read access to the Resource. However, if other Policies specify that that Agent is denied Read access except if they're in a particular Group, then that will be left intact. This means that, unless only this function is used to manipulate access to this Resource, the set access might not be equal to the effective access for the given Agent. There are a number of preconditions that have to be fulfilled for this function to work: Access to the Resource is determined via an Access Control Resource. The Resource's Access Control Resource does not refer to (Policies or Rules in) other Resources. The current user has access to the Resource's Access Control Resource. If those conditions do not hold, this function will return `null`. Additionally, take note that the given access will only be applied to the given Resource; if that Resource is a Container, access will have to be set for its contained Resources independently.
function internal_setAgentAccess(resource, webId, access) { return internal_setActorAccess(resource, acp.agent, webId, access); }
[ "async function setAgentResourceAccess(resource, agent, access, options = internal_defaultFetchOptions) {\n return await setActorAccess(resource, agent, access, getAgentAccess$2, setAgentResourceAccess$1, options);\n}", "async function setGroupResourceAccess(resource, group, access, options = internal_defaultFetchOptions) {\n return await setActorAccess(resource, group, access, getGroupAccess$2, setGroupResourceAccess$1, options);\n}", "async function setPublicResourceAccess(resource, access, options = internal_defaultFetchOptions) {\n return await setActorClassAccess(resource, access, getPublicAccess$2, setPublicResourceAccess$1, options);\n}", "function internal_initialiseAclRule(access) {\n let newRule = createThing();\n newRule = setIri(newRule, rdf.type, acl.Authorization);\n if (access.read) {\n newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.read);\n }\n if (access.append && !access.write) {\n newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.append);\n }\n if (access.write) {\n newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.write);\n }\n if (access.control) {\n newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.control);\n }\n return newRule;\n}", "function updateAccess(req, res) {\n\n db.get(\"SELECT * FROM tool WHERE user = ? AND id =?\", req.signedCookies.user_id, req.body.toolId,\n function(err, row) {\n if (err) {\n res.status(500).send({ error: \"Error when updating access authority for tool: \" + req.body.toolId });\n } else {\n if(row) {\n db.run(\"UPDATE access SET authority=? WHERE userId=? AND toolId=?\", //auth_token is saltseed for the user\n [ req.body.authority, req.body.userId, req.body.toolId ], function(err){\n if(err) {\n res.status(500).send({ error: \"update access failed for tool:\"+ req.body.toolId });\n } else {\n res.json({ success: \"access authority is successfully updated.\" }); \n }\n }); \n } else {\n res.status(500).send({ error: \"Havn't enough authority to update access authority for tool: \" + req.body.toolId });\n }\n }\n });\n }", "addPermissionToRole (roleId, action, isAllowed = true) {\n assert.equal(typeof roleId, 'string', 'roleId must be string')\n assert.equal(typeof action, 'string', 'action must be string')\n assert.equal(typeof isAllowed, 'boolean', 'isAllowed must be boolean')\n return this._apiRequest(`/role/${roleId}/permission`, 'POST', {\n action: action,\n // TODO: dear api \"programmer\", what's a bool? hint: it's not something you smoke\n allowed: isAllowed ? 'yes' : 'no'\n })\n }", "function addPerm(cb) { \n patchRsc('ictrlREST.json', ictrlA, function () {\n console.log('ACCESS to iControl REST API: ictrlUser');\n cb(); \n });\n}", "_mayGrantOrRevoke(functionName, newPermission, granteePermissions = []) {\n const newPerms = _.flatten(this._unwindParameters(newPermission));\n const ourPerms = this.permissions();\n return _.every(newPerms, (newPerm) => {\n return _.some(ourPerms, (ourPerm) => ourPerm[functionName](newPerm, granteePermissions));\n });\n }", "static getAccess(entryId, flavorIds, referrer){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\tkparams.flavorIds = flavorIds;\n\t\tkparams.referrer = referrer;\n\t\treturn new kaltura.RequestBuilder('drm_drmlicenseaccess', 'getAccess', kparams);\n\t}", "function getGroupAccess$1(resource, group, options = internal_defaultFetchOptions) {\n return getActorAccess(resource, group, getGroupAccess$2, options);\n}", "function assignRoleTo(correctStudyRole) {\n try {\n if (DEBUG) {\n wom.log(DEBUG_PREFIX + \"executing assignRoleTo function\")\n }\n var assignedOwner = validateCurrentOwner(correctStudyRole, owner);\n if (assignedOwner) {\n this.setQualifiedAttribute(\"owner\", assignedOwner);\n if (DEBUG) {\n wom.log(DEBUG_PREFIX + \"Assigned owner is \" + assignedOwner.lastName);\n }\n }\n } catch (e) {\n wom.log(DEBUG_PREFIX + \"ERROR: \" + e.description);\n throw e;\n }\n }", "addPermission(permission, region = 'default') {\n if (!permission.id) {\n return;\n }\n this.authorizedMap[permission.id] = this.authorizedMap[permission.id] || {};\n // set default values\n permission.geographies = permission.geographies || [];\n permission.organizations = permission.organizations || [];\n permission.isAuthorized = permission.organizations.length > 0;\n this.authorizedMap[permission.id][region] = permission;\n }", "function authorize(access) {\n return function (req, res, next) {\n // first authorize read access against the patient\n auth.authorize(access)(req, res, function (err) {\n if (err) return next(err);\n\n // find journal entry from ID\n // TODO: we're making duplicate find calls for every dose endpoint\n req.patient.findJournalEntryById(req.params.journalentry, function (err, entry) {\n if (err) return next(err);\n\n if (entry.role === \"clinician\" && req.user.role !== \"clinician\") return next(errors.UNAUTHORIZED);\n\n // authorize against all medication given by medicationid\n // this isn't as slow as it looks: findMedicationById is asynchronous but could\n // just as easily by synchronous\n async.each(entry.medicationIds, function (medId, callback) {\n req.patient.findMedicationById(medId, function (err, medication) {\n if (err) return callback(err);\n callback(medication.authorize(access, req.user, req.patient));\n });\n }, next);\n });\n });\n };\n}", "grantWriteAccess () {\n\n\t\t\tlet clientId = appConfig.auth[process.env.NODE_ENV === 'production' ? 'prod' : 'dev'],\n\t\t\t\turl = 'https://api.github.com/authorizations';\n\n\t\t\treturn transport.request(url)//, null, this.buildAuthHeader())\n\t\t\t.then(\n\t\t\t\tresponse => {\n\t\t\t\t\tlet openRedistApp = response.find(authedApp => authedApp.app.client_id === clientId);\n\n\t\t\t\t\tif (!openRedistApp) throw new Error('User is not currently authed.');\n\n\t\t\t\t\tif (openRedistApp.scopes.includes('public_repo')) {\n\t\t\t\t\t\treturn { userHasWriteAccess: true };\n\t\t\t\t\t} else {\n\t\t\t\t\t\turl = `https://api.github.com/authorizations/${ openRedistApp.id }`;\n\t\t\t\t\t\treturn transport.request(url, null, {\n\t\t\t\t\t\t\t...this.buildAuthHeader(),\n\t\t\t\t\t\t\tmethod: 'PATCH',\n\t\t\t\t\t\t\tbody: {\n\t\t\t\t\t\t\t\tadd_scopes: [ 'public_repo' ]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\t\t\t.then(\n\t\t\t\tresponse => {\n\t\t\t\t\treturn { userHasWriteAccess: true };\n\t\t\t\t}\n\t\t\t)\n\t\t\t.catch(error => {\n\t\t\t\t// fail loudly if the application errors further down the promise chain.\n\t\t\t\tthis.handleError(error);\n\t\t\t\tthrow error;\n\t\t\t});\n\n\t\t}", "function ProxyControl(pram , ip) {\n\tchrome.proxy.settings.get({incognito: false}, function(config){\n\t\t//console.log(config.levelOfControl);\n\t\t//console.log(config);\n\t\t//console.log(pac);\n\t\tswitch(config.levelOfControl) {\n\t\t\tcase \"controllable_by_this_extension\":\n\t\t\t// 可获得proxy控制权限,显示信息\n\t\t\tconsole.log(\"Have Proxy Permission\");\n//\t\t\tproxyflag = 1;\n\t\t\tif(pram == \"set\"){\n\t\t\t\tconsole.log(\"Setup Proxy\");\n\t\t\t\tchrome.proxy.settings.set({value: pac, scope: \"regular\"}, function(details) {});\n\t\t\t}\n\t\t\tbreak;\n\t\t\tcase \"controlled_by_this_extension\":\n\t\t\t// 已控制proxy,显示信息\n\t\t\tconsole.log(\"Already controlled\");\n//\t\t\tproxyflag = 2;\n\t\t\tif(pram == \"unset\"){\n\t\t\t\tconsole.log(\"Release Proxy\");\n\t\t\t\tchrome.proxy.settings.clear({scope: \"regular\"});\n\t\t\t\tif(typeof(ip) == 'undefined') ip = \"none\";\n\t\t\t\tFlushCache(ip);\n\t\t\t}\n\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t// 未获得proxy控制权限,显示信息\n\t\t\tconsole.log(\"No Proxy Permission\");\n\t\t\tconsole.log(\"Skip Proxy Control\");\n//\t\t\tproxyflag = 0;\n\t\t\tbreak;\n\t\t}\n\t});\n}", "function insertAccess(req, res) {\n db.get(\"SELECT * FROM tool WHERE user = ? AND id =?\", req.signedCookies.user_id, req.body.toolId,\n function(err, row) {\n if (err) {\n res.status(500).send({ error: \"Error when adding access authority for tool: \" + req.body.toolId });\n } else {\n if(row){\n db.run(\"INSERT INTO access(toolId, userId, authority) VALUES (?, ?, ?)\",\n [ req.body.toolId, req.body.userId, req.body.authority ], function(err){\n if(err) {\n res.status(500).send({ error: \"Faild to add access authority for tool: \" + req.body.toolId });\n } else {\n res.json({ success: \"User is successfully added.\" });\n }\n });\n } else {\n res.status(500).send({ error: \"Can't insert access authority for tool created by others.\"});\n }\n }\n });\n }", "addToPrincipalPolicy(statement) {\n return this.role.addToPrincipalPolicy(statement);\n }", "async function permissions(req, res, next) {\n\ttry {\n\t\tconst request = await Request.findById(req.params.requestId);\n\t\tif (!request) throw new ApiError(\"REQUEST_NOT_FOUND\");\n\t\tconst user = await User.findById(req.decoded._id).populate();\n\t\tif (!user) throw new ApiError(\"USER_NOT_FOUND\");\n\t\tconst billing = await Billing.findOne({\n\t\t\trequests: { $in: [req.params.requestId] }\n\t\t});\n\t\treq.billing = billing;\n\t\t// bypass if admin:\n\t\tconst isAdmin = user.roles.find(role => role === \"admin\");\n\t\tif (isAdmin) {\n\t\t\treq.permissions = { read: true, write: true };\n\t\t\treturn next();\n\t\t}\n\t\tif (!billing) throw new ApiError(\"BILLING_NOT_FOUND\");\n\t\tif (isRequestFromUser(billing, user)) {\n\t\t\tif (isAdmin) return next();\n\t\t\telse {\n\t\t\t\treq.permissions = userPermissions(req.decoded._id, request);\n\t\t\t\treturn next();\n\t\t\t}\n\t\t} else if (await isRequestFromJournal(req, billing)) {\n\t\t\tif (isAdmin) return next();\n\t\t\telse {\n\t\t\t\treq.permissions = await journalPermissions(\n\t\t\t\t\treq.journal._id.toString(),\n\t\t\t\t\treq.decoded._id\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treq.permissions = { read: false, write: false };\n\t\treturn next();\n\t} catch (error) {\n\t\treturn next(error);\n\t}\n}", "function editorStoryAccessibleChange(element) {\n loadedStory.accessible = element.checked;\n editorDirty = true;\n}", "function hasAccessibleAcl(dataset) {\n return typeof dataset.internal_resourceInfo.aclUrl === \"string\";\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a demo for FineCoarseSpinner
function demoFineCoarseSpinner( layoutBounds, options ) { const numberProperty = new NumberProperty( 0, { range: new Range( 0, 100 ), tandem: options.tandem.createTandem( 'numberProperty' ) } ); const enabledProperty = new BooleanProperty( true, { tandem: options.tandem.createTandem( 'enabledProperty' ) } ); const spinner = new FineCoarseSpinner( numberProperty, { enabledProperty: enabledProperty, tandem: options.tandem.createTandem( 'spinner' ) } ); const checkbox = new Checkbox( new Text( 'enabled', { font: new PhetFont( 20 ), tandem: options.tandem.createTandem( 'checkbox' ) } ), enabledProperty ); return new VBox( { spacing: 60, children: [ spinner, checkbox ], center: layoutBounds.center } ); }
[ "function triggerSpinner() {\n\n //Object for spinner settings\n var optsb = {\n lines: 11 // The number of lines to draw\n , length: 40 // The length of each line\n , width: 13 // The line thickness\n , radius: 25 // The radius of the inner circle\n , scale: 0.5 // Scales overall size of the spinner\n , corners: 1 // Corner roundness (0..1)\n , color: '#d63837' // #rgb or #rrggbb or array of colors\n , opacity: 0.25 // Opacity of the lines\n , rotate: 0 // The rotation offset\n , direction: 1 // 1: clockwise, -1: counterclockwise\n , speed: 1 // Rounds per second\n , trail: 60 // Afterglow percentage\n , fps: 20 // Frames per second when using setTimeout() as a fallback for CSS\n , zIndex: 2e9 // The z-index (defaults to 2000000000)\n , className: 'spinner' // The CSS class to assign to the spinner\n , top: '42%' // Top position relative to parent\n , left: '50%' // Left position relative to parent\n , shadow: false // Whether to render a shadow\n , hwaccel: false // Whether to use hardware acceleration\n , position: 'absolute' // Element positioning\n }\n\n //Full Modal Spinner Get Dom Element and Create Spinner Object\n var targetB = document.getElementById('modal-loader');\n var spinnerb = new Spinner(optsb);\n var spinIt = spinnerb.spin(targetB);\n\n //Attach spinner to full screen modal\n $('#modal-loader').modal('show');\n $('#modal-loader').on('shown.bs.modal', function (e) {\n spinnerb;\n $('.modal-content').append(spinIt);\n })\n\n return spinnerb;\n}", "function showSpinner() {\n $(options.selectors.placesContent).addClass('hidden');\n $(options.selectors.spinner).removeClass('hidden');\n }", "function initializeSpinnerControlForQuantity() {\n\n\tvar jQueryFloat = parseFloat(jQuery.fn.jquery); // 1.1\n\tif (jQueryFloat >= 3) {\n\n\t\t// Extend spinner.\n\t\tif (typeof $.fn.spinner === \"function\" && $.widget(\"ui.spinner\", $.ui.spinner, {\n\t\t\t\t\t\t\t\t_buttonHtml: function() {\n\n\t\t\t\t\t\treturn `\\n\\t\\t\\t\\t\\t<a class=\"ui-spinner-button ui-corner-br ui-button ui-widget ui-state-default ui-button-text-only ui-spinner-down\" tabindex=\"-1\" role=\"button\">\\n\\t\\t\\t\\t\\t\\t<span class=\"ui-icon\"><i class=\\'fas fa-plus\\'></i></span>\\n\\t\\t\\t\\t\\t</a>\\n\\t\\t\\t\\t\\t<a class=\"ui-spinner-button ui-corner-tr ui-button ui-widget ui-state-default ui-button-text-only\" tabindex=\"-1\" role=\"button\">\\n\\t\\t\\t\\t\\t\\t<span class=\"ui-icon\"><i class=\\'fas fa-minus\\'></i></span>\\n\\t\\t\\t\\t\\t</a>\n\t\t`;\n\t\t\t\t\t}\n\t\t\t\t} ));\n\n\t}\n\n\n\tif (jQueryFloat < 3) {\n\n\t\tif ( $.isFunction( $.fn.spinner ) ) {\n\t\t$.widget( \"ui.spinner\", $.ui.spinner, {\n\t\t\t_buttonHtml: function() {\n\t\t\t\treturn `\n\t\t\t\t\t<a class=\"ui-spinner-button ui-spinner-down ui-corner-br ui-button ui-widget ui-state-default ui-button-text-only\" tabindex=\"-1\" role=\"button\">\n\t\t\t\t\t\t<span class=\"ui-icon\"><i class='fas fa-minus'></i></span>\n\t\t\t\t\t</a>\n\t\t\t\t\t<a class=\"ui-spinner-button ui-spinner-up ui-corner-tr ui-button ui-widget ui-state-default ui-button-text-only\" tabindex=\"-1\" role=\"button\">\n\t\t\t\t\t\t<span class=\"ui-icon\"><i class='fas fa-plus'></i></span>\n\t\t\t\t\t</a>`;\n\t\t\t},\n\t\t} );\n\t}\n\n\n\n\t}\n\n\n\n\n\n// WP5.6\n//\tif (typeof $.fn.spinner === \"function\" && $.widget(\"ui.spinner\", $.ui.spinner, {\n\t// _buttonHtml: function() {\n//\t\t\t\t\t\t\t\treturn '\\n\\t\\t\\t\\t\\t<a class=\"ui-spinner-button ui-corner-br ui-button ui-widget ui-state-default ui-button-text-only ui-spinner-down\" tabindex=\"-1\" role=\"button\">\\n\\t\\t\\t\\t\\t\\t<span class=\"ui-icon\"><i class=\\'fas fa-plus\\'></i></span>\\n\\t\\t\\t\\t\\t</a>\\n\\t\\t\\t\\t\\t<a class=\"ui-spinner-button ui-corner-tr ui-button ui-widget ui-state-default ui-button-text-only\" tabindex=\"-1\" role=\"button\">\\n\\t\\t\\t\\t\\t\\t<span class=\"ui-icon\"><i class=\\'fas fa-minus\\'></i></span>\\n\\t\\t\\t\\t\\t</a>'\n//\t\t\t\t\t\t}\n// }));\n\n\n\t// Initialze the spinner on load.\n\tinitSpinner();\n\n\t// Re-initialze the spinner on WooCommerce cart refresh.\n\t$( document.body ).on( 'updated_cart_totals', function() {\n\t\tinitSpinner();\n\t} );\n\n\t// Trigger quantity input when plus/minus buttons are clicked.\n\t(0,$)(document).on( 'click', '.ui-spinner-button', () => {\n\t\t$( '.ui-spinner-input' ).trigger( 'change' );\n\n\t} );\n}", "startSpinner() {\n if (this.viewports && this.viewports.length > 0) {\n this.viewports[0].startSpinner()\n }\n }", "loadSpinner(display){\n document.querySelector(\".contenido-spinner\").style.display = display;\n document.querySelector(\"#resultado\").style.display = \"none\";\n }", "function spinner() {\n var list = $id('List');\n if (list) {\n list.style.display = \"none\";\n\n //get other items associated with it and set them to none display\n $id('Main-listing-header').style.display = \"none\";\n $id('Tools-menu').style.display = \"none\";\n var footer = document.getElementsByClassName('Main-Footer')[0];\n if (footer) {\n footer.style.display = \"none\";\n }\n var h1 = document.createElement('h1');\n h1.className = 'spinny';\n h1.innerHTML = '<span class=\"spinny-vinny\">\\xAF_\\u30C4_/\\xAF</span>';\n $id('Main-container').appendChild(h1);\n } else {\n $id('main').innerHTML = '<h1 class=\"spinny><span class=\"spinny-vinny\">\\xAF_\\u30C4_/\\xAF</span></h1>\"';\n }\n}", "idleSpin() {\n this._sectors.rotation = 0;\n this.idleSpinTween = gsap.to(this._sectors, { \n rotation: Math.PI * 2, \n repeat: -1, \n duration: 12, \n ease: 'linear', \n onUpdate: this._onRotation.bind(this)\n });\n }", "function segmenterInit (elem, optParm) {\n function segments(opt) {\n var conf = {\n home: {\n pieces: 4,\n \t\tanimation: {\n \t\t\tduration: 1500,\n \t\t\teasing: 'easeInOutExpo',\n \t\t\tdelay: 100,\n \t\t\ttranslateZ: 100\n \t\t},\n \t\tparallax: true,\n \t\tpositions: [\n \t\t\t{top: 0, left: 0, width: 45, height: 45},\n \t\t\t{top: 55, left: 0, width: 45, height: 45},\n \t\t\t{top: 0, left: 55, width: 45, height: 45},\n \t\t\t{top: 55, left: 55, width: 45, height: 45}\n \t\t],\n onReady: function () {\n setTimeout(function () {\n segter.animate();\n opt['headline'].classList.remove('trigger-headline--hidden');\n }, 500);\n }\n },\n default: {\n onReady: function () {\n setTimeout(function () {\n segter.animate();\n }, 600);\n }\n }\n };\n return conf[opt['ctrl']] || conf.default;\n }\n if (elem) {\n var segter = new Segmenter(document.querySelector(elem), segments(optParm));\n }\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 }", "drawSlider() {\n let c = color(255, 255, 255);\n fill(c);\n noStroke();\n rect(this.x, this.y + this.topPadding + this.lateralPadding, this.width, this.height, 1, 1, 1, 1);\n }", "function confettiAnimation() {\n\nvar confettiSettings = {\n target: 'confetti-canvas'\n};\nvar confetti = new ConfettiGenerator(confettiSettings);\nconfetti.render();\n}", "componentDidMount(){\r\n\t\tlet t1 = gsap.timeline({repeat: 0, delay: 0, repeatDelay: 1});\r\n\t\tt1.from('#photoSlider', {\r\n\t\t\tduration: 1,\r\n\t\t\ty: -500,\r\n\t\t\tease: 'power1'\r\n\t\t});\r\n\t}", "load(callback) {\n\t\t\t\tlet element = timeline._activePart.element;\n\t\t\t\tlet points = timeline._activePart.points;\n\t\t\t\tfor(let q = 0; q < points.length; q++){\n\t\t\t\t\telement.append(points[q].element);\n\t\t\t\t}\n\t\t\t\telement.children().fadeIn('fast').promise().done(callback);\n\t\t\t\ttimeline.proceeding = false;\n\t\t\t}", "function MapLayers_Time_CreateSlider() {\n\nMapLayers.Time.\nToolbar = new MapLayers.Time._TimeBar();\n\n}", "onOpenSpinningWheel() {\n Actions.SpinningWheel();\n }", "function onSpinnerChange() {\n\tvar $spinner = $(this);\n\tvar value = $spinner.spinner('value');\n\n\t// If the value is null and the real value in the textbox is string we empty the textbox\n\tif (value === null && typeof $spinner.val() === 'string') {\n\t\t$spinner.val('');\n\t\treturn;\n\t}\n\n\t// Now check that the number is in the min/max range.\n\tvar min = $spinner.spinner('option', 'min');\n\tvar max = $spinner.spinner('option', 'max');\n\tif (typeof min === 'number' && this.value < min) {\n\t\tthis.value = min;\n\t\treturn;\n\t}\n\n\tif (typeof max === 'number' && this.value > max) {\n\t\tthis.value = max;\n\t}\n}", "function initCircleProgress (duration) {\n\n // On nettoie le circle progress\n $('#progress').empty()\n\n // On met à jour les paramètres à exécuter\n const circleParameters = {\n color: '#28a745',\n duration: duration, // en milliseconds\n easing: 'linear', // avance de façon linéaire\n trailWidth: 2, // largeur du trait du cercle en fond\n strokeWidth: 4, // largeur du trait de l'avancement\n from: { color: '#28a745', width: 2 },\n to: { color: duration === 0 ? '#28a745' : '#dc3545', width: 4 }, // Cas particulier du démarrage où la durée est à zéro, on laisse la couleur du début\n step: function (state, circle) {\n stepCircleProgress(state, circle, duration)\n }\n }\n\n // On recrée un circle progress à partir d'un ProgressBar\n const circle = new ProgressBar.Circle('#progress', circleParameters)\n\n // On anime le cercle une fois\n try {\n circle.animate(1)\n }\n catch (e) {\n // On ne fait rien, c'est juste pour occulter le message \"Uncaught (in promise)\" du circle progress qui gère mal le stop/rafraichissement\n }\n}", "function createPlanCircle() {\r\n planCircle = loadCircle(\"#total-plan-completion\");\r\n}", "hideSpinner() {\n this.spinnerVisible = false;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build the contents of the tableDiv element, filtered according to the specified type.
function buildFilteredTable (type) { // Generate "add column" cell. clearElement(addColumnDiv) addColumnDiv.appendChild(generateColumnAddDropdown(type)) const query = generateQuery(type) updateTable(query, type) }
[ "function renderTableForQuery (query, type) {\n // infer columns from query, to allow generic queries\n let columns\n if (!givenQuery) {\n columns = type.getColumns()\n } else {\n columns = inferColumns(query)\n }\n\n // Start with an empty list of rows; this will be populated\n // by the query.\n\n const rows = []\n\n // Create table element and header.\n\n const table = doc.createElement('table')\n\n table.appendChild(renderTableHeader(columns, type))\n table.appendChild(renderTableSelectors(rows, columns))\n\n // Run query. Note that this is perform asynchronously; the\n // query runs in the background and this call does not block.\n\n table.logicalRows = rows // Save for refresh\n table.columns = columns\n table.query = query\n\n runQuery(query, rows, columns, table)\n\n return table\n }", "function renderTable() {\n $tbody.innerHTML = \"\";\n for (var i = 0; i < filteredUFO.length; i++) {\n // Get get the current UFO object and its fields\n var ufo = filteredUFO[i];\n var observations = Object.keys(ufo);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < observations.length; j++) {\n // For every observations in the ufo object, create a new cell at set its inner text to be the current value at the current ufo'sobservation\n var observation = observations[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = ufo[observation];\n }\n }\n}", "static renderTableBody() {\n\n // Reset options list of each filter\n filterRegistry.forEach(obj => obj.options = ['']);\n\n // This is how table body is created. D3 does its magic.\n var tableBody = d3.select('tbody');\n tableBody.selectAll('tr')\n .data(data.filter(encounter => SelectFilter.filter(encounter)))\n .join('tr')\n .selectAll('td')\n .data(encounter => Object.values(encounter))\n .join('td')\n .text(value => value);\n\n // Based on filtered data update option lists for UNSET filters\n // (their options were already populated via SelectFilter.filter() calls above)\n filterRegistry.forEach(obj => obj.selectedOpt ? null : obj.makeOptions());\n\n // Update option lists for ACTIVE filters (at this moment they have only one option in the list - the one selected)\n // For each active filter we have to recreate a dataset WITHOUT that filter\n var activeFilters = [];\n filterRegistry.forEach(obj => obj.selectedOpt ? activeFilters.push(obj) : null);\n\n activeFilters.forEach(obj => {\n // temporary remove the filter from the registry\n let idx = filterRegistry.indexOf(obj);\n filterRegistry.splice(idx, 1);\n\n // Now apply remaining filters to the dataset, but only for the purpose of populating options of the removed filter\n // calling SelectFilter.filter() with obj as the second argument - only that obj options will be populated\n data.forEach(encounter => SelectFilter.filter(encounter, obj));\n\n // At this point the filter options should be repopulated and have to be transferred to the 'option' elements\n obj.makeOptions();\n\n // Put the filter back to the registry\n filterRegistry.splice(idx, 0, obj);\n });\n }", "function updateResultsTable(object, type) {\r\n\t\r\n\t/* First delete the old results table contents */\r\n\t\r\n\tif (document.getElementById(\"results\").rows.length > 1) {\r\n\t\t//Delete the table rows in reverse order to avoid missing rows\r\n\t\tfor (i = (document.getElementById(\"results\").rows.length) - 1; i >= 0; i--) {\r\n\t\t\tdocument.getElementById(\"results\").deleteRow(i);\r\n\t\t}\r\n\t}\r\n\t\r\n\t/* Then add the new table contents depending on the search query that was selected */\r\n\t\r\n\tfor (i = 0; i <= object.length; i++) {\r\n\t\tif (type == \"kit_by_drummer\") {\r\n\t\t\tif (i == 0) {\r\n\t\t\t\t//Add table headers \r\n\t\t\t\tvar row = document.getElementById(\"results\").insertRow(i);\r\n\t\t\t\t\r\n\t\t\t\tvar name = row.insertCell(0);\r\n\t\t\t\tvar pieces = row.insertCell(1);\r\n\t\t\t\tvar cymbals = row.insertCell(2);\r\n\t\t\t\t\r\n\t\t\t\tname.innerHTML = \"<center><b>Kit Brand Name</b></center>\";\r\n\t\t\t\tpieces.innerHTML = \"<center><b># of Pieces</b></center>\";\r\n\t\t\t\tcymbals.innerHTML = \"<center><b>Type of Cymbals</b></center>\";\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\t//Then add table contents\r\n\t\t\t\tvar row = document.getElementById(\"results\").insertRow(i);\r\n\t\t\t\t\r\n\t\t\t\tvar name = row.insertCell(0);\r\n\t\t\t\tvar pieces = row.insertCell(1);\r\n\t\t\t\tvar cymbals = row.insertCell(2);\r\n\t\t\t\t\r\n\t\t\t\tname.innerHTML = \"<center>\" + object[i-1].name + \"</center>\";\r\n\t\t\t\tpieces.innerHTML = \"<center>\" + object[i-1].pieces + \"</center>\";\r\n\t\t\t\tcymbals.innerHTML = \"<center>\" + object[i-1].cymbal_type + \"</center>\";\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (type == \"drummer_by_kit\") {\r\n\t\t\tif (object.length == 0) {\r\n\t\t\t\talert(\"There are no drummers in the database who use that drum kit\");\r\n\t\t\t}\r\n\t\t\telse if (i == 0) {\r\n\t\t\t\t//Add table headers \r\n\t\t\t\tvar row = document.getElementById(\"results\").insertRow(i);\r\n\t\t\t\t\r\n\t\t\t\tvar name = row.insertCell(0);\r\n\t\t\t\tvar band = row.insertCell(1);\r\n\t\t\t\tvar hometown = row.insertCell(2);\r\n\t\t\t\t\r\n\t\t\t\tname.innerHTML = \"<center><b>Drummer Name</b></center>\";\r\n\t\t\t\tband.innerHTML = \"<center><b>Band</b></center>\";\r\n\t\t\t\thometown.innerHTML = \"<center><b>Hometown</b></center>\";\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\t//Then add table contents\r\n\t\t\t\tvar row = document.getElementById(\"results\").insertRow(i);\r\n\t\t\t\t\r\n\t\t\t\tvar name = row.insertCell(0);\r\n\t\t\t\tvar band = row.insertCell(1);\r\n\t\t\t\tvar hometown = row.insertCell(2);\r\n\t\t\t\t\r\n\t\t\t\tname.innerHTML = \"<center>\" + object[i-1].name + \"</center>\";\r\n\t\t\t\tband.innerHTML = \"<center>\" + object[i-1].band + \"</center>\";\r\n\t\t\t\thometown.innerHTML = \"<center>\" + object[i-1].hometown + \"</center>\";\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (type == \"brand_by_drummer\") {\r\n\t\t\tif (i == 0) {\r\n\t\t\t\t//Add table headers \r\n\t\t\t\tvar row = document.getElementById(\"results\").insertRow(i);\r\n\t\t\t\t\r\n\t\t\t\tvar name = row.insertCell(0);\r\n\t\t\t\tvar founder = row.insertCell(1);\r\n\t\t\t\tvar country = row.insertCell(2);\r\n\t\t\t\tvar year = row.insertCell(3);\r\n\t\t\t\t\r\n\t\t\t\tname.innerHTML = \"<center><b>Brand Name</b></center>\";\r\n\t\t\t\tfounder.innerHTML = \"<center><b>Founder</b></center>\";\r\n\t\t\t\tcountry.innerHTML = \"<center><b>Country of Origin</b></center>\";\r\n\t\t\t\tyear.innerHTML = \"<center><b>Year Established</b></center>\";\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\t//Then add table contents\r\n\t\t\t\tvar row = document.getElementById(\"results\").insertRow(i);\r\n\t\t\t\t\r\n\t\t\t\tvar name = row.insertCell(0);\r\n\t\t\t\tvar founder = row.insertCell(1);\r\n\t\t\t\tvar country = row.insertCell(2);\r\n\t\t\t\tvar year = row.insertCell(3);\r\n\t\t\t\t\r\n\t\t\t\tname.innerHTML = \"<center>\" + object[i-1].name + \"</center>\";\r\n\t\t\t\tfounder.innerHTML = \"<center>\" + object[i-1].founder + \"</center>\";\r\n\t\t\t\tcountry.innerHTML = \"<center>\" + object[i-1].country_of_origin + \"</center>\";\r\n\t\t\t\tyear.innerHTML = \"<center>\" + object[i-1].year_established + \"</center>\";\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (type == \"drummer_by_brand\") {\r\n\t\t\tif (object.length == 0) {\r\n\t\t\t\talert(\"There are no drummers in the database who use that brand\");\r\n\t\t\t}\r\n\t\t\telse if (i == 0) {\r\n\t\t\t\t//Add table headers \r\n\t\t\t\tvar row = document.getElementById(\"results\").insertRow(i);\r\n\t\t\t\t\r\n\t\t\t\tvar name = row.insertCell(0);\r\n\t\t\t\tvar band = row.insertCell(1);\r\n\t\t\t\tvar hometown = row.insertCell(2);\r\n\t\t\t\t\r\n\t\t\t\tname.innerHTML = \"<center><b>Drummer Name</b></center>\";\r\n\t\t\t\tband.innerHTML = \"<center><b>Band</b></center>\";\r\n\t\t\t\thometown.innerHTML = \"<center><b>Hometown</b></center>\";\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\t//Then add table contents\r\n\t\t\t\tvar row = document.getElementById(\"results\").insertRow(i);\r\n\t\t\t\t\r\n\t\t\t\tvar name = row.insertCell(0);\r\n\t\t\t\tvar band = row.insertCell(1);\r\n\t\t\t\tvar hometown = row.insertCell(2);\r\n\t\t\t\t\r\n\t\t\t\tname.innerHTML = \"<center>\" + object[i-1].name + \"</center>\";\r\n\t\t\t\tband.innerHTML = \"<center>\" + object[i-1].band + \"</center>\";\r\n\t\t\t\thometown.innerHTML = \"<center>\" + object[i-1].hometown + \"</center>\";\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (type == \"stick_by_drummer\") {\r\n\t\t\tif (i == 0) {\r\n\t\t\t\t//Add table headers \r\n\t\t\t\tvar row = document.getElementById(\"results\").insertRow(i);\r\n\t\t\t\t\r\n\t\t\t\tvar brand = row.insertCell(0);\r\n\t\t\t\tvar stickType = row.insertCell(1);\r\n\t\t\t\t\r\n\t\t\t\tbrand.innerHTML = \"<center><b>Stick Brand</b></center>\";\r\n\t\t\t\tstickType.innerHTML = \"<center><b>Type</b></center>\";\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\t//Then add table contents\t\r\n\t\t\t\tvar row = document.getElementById(\"results\").insertRow(i);\r\n\t\t\t\t\r\n\t\t\t\tvar brand = row.insertCell(0);\r\n\t\t\t\tvar stickType = row.insertCell(1);\r\n\t\t\t\t\r\n\t\t\t\tbrand.innerHTML = \"<center>\" + object[i-1].name + \"</center>\";\r\n\t\t\t\tstickType.innerHTML = \"<center>\" + object[i-1].type + \"</center>\";\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (type == \"drummer_by_stick\") {\r\n\t\t\tif (object.length == 0) {\r\n\t\t\t\talert(\"There are no drummers in the database who use that stick type\");\r\n\t\t\t}\r\n\t\t\telse if (i == 0) {\r\n\t\t\t\t//Add table headers \r\n\t\t\t\tvar row = document.getElementById(\"results\").insertRow(i);\r\n\t\t\t\t\r\n\t\t\t\tvar name = row.insertCell(0);\r\n\t\t\t\tvar band = row.insertCell(1);\r\n\t\t\t\tvar hometown = row.insertCell(2);\r\n\t\t\t\t\r\n\t\t\t\tname.innerHTML = \"<center><b>Drummer Name</b></center>\";\r\n\t\t\t\tband.innerHTML = \"<center><b>Band</b></center>\";\r\n\t\t\t\thometown.innerHTML = \"<center><b>Hometown</b></center>\";\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\t//Then add table contents\r\n\t\t\t\tvar row = document.getElementById(\"results\").insertRow(i);\r\n\t\t\t\t\r\n\t\t\t\tvar name = row.insertCell(0);\r\n\t\t\t\tvar band = row.insertCell(1);\r\n\t\t\t\tvar hometown = row.insertCell(2);\r\n\t\t\t\t\r\n\t\t\t\tname.innerHTML = \"<center>\" + object[i-1].name + \"</center>\";\r\n\t\t\t\tband.innerHTML = \"<center>\" + object[i-1].band + \"</center>\";\r\n\t\t\t\thometown.innerHTML = \"<center>\" + object[i-1].hometown + \"</center>\";\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "function buildPromotionTable(filter_promotion) {\n\n $(\"#promotion_container\").empty();\n \n //greater than 480px viewport- Background Gradient \n $(\"#promotion_container\").addClass(\"details\");\n $(\"body\").addClass(\"bg\");\n\n //Index URL Promotion \n var promotion = promotion_data.promotion_objects.filter(function (promo) { return promo.promo_id == filter_promotion; })[0]\n console.log(promotion);\n //Index page \n var the_promohtml = $(\"<div>\").addClass(\"landing-page-promo-container\").addClass(\"holder\");\n\t//Back Button\n\tthe_promohtml.append($(\"<a/>\").addClass(\"return_state\").addClass(\"back\").attr(\"href\", \"./index.html\").attr(\"id\", \"home\").html(\"< Back\"));\n //Entry Deadline Date \n the_promohtml.append($(\"<div/>\").addClass(\"next-entry-deadline\").addClass(\"promotion-less\").html(\"The Next Entry Deadline is \" + new Date(promotion.drawings[0].entry_deadline).toLocaleString(\"en-us\", datetime_format) + \"!\"));\n //Banner Images calling \n the_promohtml.append($(\"<figure/>\").append($(\"<img/>\").attr(\"src\", promotion.promo_image_url).addClass(\"millionaire-madness\").attr(\"alt\", \"Millionaire-Madness\")));\n //define greater than 480px viewport and 480px or less viewport\n var promo_content_area = $(\"<div/>\").attr(\"id\", \"drawingdate-above480\");\n var promo_content_area_less = $(\"<div/>\").attr(\"id\", \"drawingdate-less480\").addClass(\"promotion-less\");\n \n //Add body-promotion content \n buildPromoInnerTable(promo_content_area, promotion,false)\n buildPromoInnerTable(promo_content_area_less, promotion,true)\n the_promohtml.append(promo_content_area);\n the_promohtml.append(promo_content_area_less);\n $(\"#promotion_container\").append(the_promohtml);\n\n}", "renderResultTable(content, element) {\n // th\"s and empty table elems\n let tableHeadings = [\"Flight number\", \"From\", \"To\", \"Departure\", \"Arrival\", \"Airline\", \"Plane\", \"Price\"];\n let table = $(\"<table></table>\").addClass(\"table table-striped\");\n let tableHead = $(\"<thead></thead>\");\n let tableBody= $(\"<tbody></tbody>\");\n let row = $(\"<tr></tr>\");\n // filling thead row here\n for(let i = 0, len = tableHeadings.length; i < len; i++) {\n row.append($(\"<th></th>\").text(tableHeadings[i]));\n }\n tableHead.append(row);\n table.append(tableHead);\n let sortedContent = content.sort(this.sortByPrices);\n // appending tbody content\n for(let i= 0, len = sortedContent.length; i < len; i++) {\n let row = $(\"<tr></tr>\");\n for (let prop in sortedContent[i]) {\n row.append($(\"<td></td>\").text(sortedContent[i][prop]));\n }\n tableBody.append(row);\n }\n table.append(tableBody);\n $(element).append(table);\n }", "function connTypeFilter(){\n\tvar val = $('#portTypeTT').val();\n\t$('tr').show();\n\n\t$('tr td.conntype').each(function() {\n\t\tif ($(this).text() != val)\n\t\t{\n\t\t\t$(this).parent().hide();\n\t\t}\n\t});\n}", "function typeofrptinfo()\n\t{\n\t\tvar type = $(\"#rptwebusage_type option:selected\").attr('value');\n\t\tvar iscustom = $(\"#rptsearch_time option:selected\").attr('value');\n\t\t\n\t\tif (type == 'topusersbyhost')\n\t\t{\n\t\t\t$(\"#rptwebusage_user_row\").hide();\n\t\t\t$(\"#rptwebusage_host_row\").show();\n\t\t\t$(\"#rptwebusage_userbymime_row\").hide();\n\t\t\t$(\"#rptwebusage_mimebyuser_row\").hide();\n\t\t}\n\t\t\n\t\telse if(type == 'tophostbyuser')\n\t\t{\n\t\t\t$(\"#rptwebusage_user_row\").show();\n\t\t\t$(\"#rptwebusage_host_row\").hide();\n\t\t\t$(\"#rptwebusage_userbymime_row\").hide();\n\t\t\t$(\"#rptwebusage_mimebyuser_row\").hide();\n\t\t\t$(\"#rptwebusage_destinationbymime_row\").hide();\n\t\t}\n\t\t\n\t\telse if (type == 'topuserbymime')\n\t\t{\n\t\t\t$(\"#rptwebusage_user_row\").hide();\n\t\t\t$(\"#rptwebusage_host_row\").hide();\n\t\t\t$(\"#rptwebusage_mimebyuser_row\").hide();\n\t\t\t$(\"#rptwebusage_userbymime_row\").show();\n\t\t\t$(\"#rptwebusage_destinationbymime_row\").hide();\n\t\t\t\n\t\t}\n\t\t\n\t\telse if (type == 'topmimebyuser')\n\t\t{\n\t\t\t$(\"#rptwebusage_user_row\").hide();\n\t\t\t$(\"#rptwebusage_host_row\").hide();\n\t\t\t$(\"#rptwebusage_userbymime_row\").hide();\n\t\t\t$(\"#rptwebusage_mimebyuser_row\").show();\n\t\t\t$(\"#rptwebusage_destinationbymime_row\").hide();\n\t\t}\n\t\t\n\t\telse if (type == 'topdestinationbymime')\n\t\t{\n\t\t\t$(\"#rptwebusage_user_row\").hide();\n\t\t\t$(\"#rptwebusage_host_row\").hide();\n\t\t\t$(\"#rptwebusage_userbymime_row\").hide();\n\t\t\t$(\"#rptwebusage_mimebyuser_row\").hide();\n\t\t\t$(\"#rptwebusage_destinationbymime_row\").show();\n\t\t}\n\t\t\n\t\telse \n\t\t{\n\t\t\t$(\"#rptwebusage_user_row\").hide();\n\t\t\t$(\"#rptwebusage_host_row\").hide();\n\t\t\t$(\"#rptwebusage_userbymime_row\").hide();\n\t\t\t$(\"#rptwebusage_mimebyuser_row\").hide();\n\t\t\t$(\"#rptwebusage_destinationbymime_row\").hide();\n\t\t}\n\t\t\n\t\tif (iscustom == \"custom\")\n\t\t\t$(\"#rptsearch_time_custom\").show();\n\t\telse\n\t\t\t$(\"#rptsearch_time_custom\").hide();\n\t}", "function createTable() {\n if (config.data.length === 0) {\n console.log(`No data for table at ${tableSelector}`);\n // Remove any order directive to avoid Datatables errors\n delete config['order'];\n return this;\n }\n htTable.DataTable(config);\n dtapi = htTable.DataTable();\n const customFilterIds = Object.keys(filterFields);\n if (customFilterIds.length > 0) {\n const fields = customFilterIds.map(key => filterFields[key].html).join('');\n $(tableSelector + '_wrapper .right-filters').append(`<span class=\"form-group ml-4 pull-right\">${fields}</span>`);\n customFilterIds.forEach(key => {\n if (filterFields[key].hdlr) { $(`#${key}`).change(filterFields[key].hdlr); }\n if (filterFields[key].defaultChoice) { $(`#${key}`).trigger('change'); }\n });\n }\n // configureSearchReset();\n if (rowBtns.length > 0) {\n rowBtns.forEach(btn => { activateButton(btn); });\n htTable.on('draw.dt', function () {\n rowBtns.forEach(btn => { activateButton(btn); });\n });\n htTable.on('page.dt', function () {\n rowBtns.forEach(btn => { activateButton(btn); });\n });\n }\n return this;\n }", "function renderTable() {\n // Set the value of ending index\n var endingIndex = startingIndex + resultsPerPage;\n\n $tbody.innerHTML = \"\";\n // Set the value of ending index\n for (var i = 0; i < filteredAliens.length; i++) {\n // Get the current address object and its fields\n var alien = filteredAliens[i];\n var fields = Object.keys(alien);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n // For every field in the address object, create a new cell and set its inner text to be the current value at the current address's field\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = alien[field];\n };\n };\n}", "function filterUFO() {\n // assign variable using querySelector() method to return the first element that matches a specified CSS selector in the document\n // these are used to select html elements based on their id, classes, types, attributes, values of attributes, etc.\n var table = document.querySelector(\"table\");\n // assign filter variable of date type to the criteria value entered on the html form\n var dateFilter = new Date(document.getElementById(\"datetime\").value);\n // call function to remove the html table currently on display\n clearRows();\n // call function to append a new table to html page and adds new rows of data for each UFO sighting per date criteria\n createUFO(table, tableData, dateFilter, true);\n}", "function filterFinalDataByType() {\n\n filterString = \"\";\n filteredFinalData = [];\n for(i = 0; i < localFinalData.length; i++) {\n\n let t = localFinalData[i];\n\n if (filterType == \"users\" && t.is_user == false)\n continue;\n\n if (filterType == \"groups\" && t.is_user == true)\n continue;\n\n filteredFinalData.push(t);\n\n }\n\n }", "function createFilterArea() {\n div.className = \"filterArea\";\n filterLabel.textContent = htmlTxt['filterLabelText'];\n filterCheckbox.type = 'checkbox';\n filterLabel.appendChild(filterCheckbox);\n div.appendChild(filterLabel);\n const listInfo = document.querySelector('#listInfo');\n listInfo.parentNode.insertBefore(div, listInfo.nextSibling);\n}", "function createTables() {\n $.each(tableIds, function(index, value) {\n\n // Get number of rows in this table\n var rowCount = $('#'+value+' tr').length;\n \n\n var bPaginate;\n var bLengthChange;\n var bInfo;\n var bFilter;\n\n if(rowCount<6) {\n bFilter = false;\n } else {\n bFilter = true;\n }\n\n if(rowCount<12) {\n bPaginate = false;\n bLengthChange = false;\n bInfo = false;\n } else { \n bPaginate = true;\n bLengthChange = true;\n bInfo = true;\n }\n\n // Create the table:\n $('#'+value).DataTable({'bPaginate': bPaginate,\n 'bLengthChange': bLengthChange,\n 'bInfo': bInfo,\n 'bFilter': bFilter});\n });\n}", "function constructPasscodeTable(sortedCards) {\n $(\"#passcode-table\").remove();\n var $list = '<table id=\"passcode-table\" class=\"mdl-data-table mdl-shadow--2dp\">\\\n <thead><tr>\\\n <th class=\"checkbox-col\"></th>\\\n <th class=\"mdl-data-table__cell--non-numeric type-col\">Type</th>\\\n <th>Quantity</th>\\\n </tr></thead>\\\n <tbody>';\n\n for (var i = 0; i !== sortedCards.length; ++i) {\n var type = sortedCards[i].type;\n var idName = \"passcode\" + type.replace(/ /g, \"-\");\n\n $list +=\n '<tr>\\\n <td>\\\n <label class=\"mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect mdl-data-table__select\" for=\"' + idName + '\">\\\n <input type=\"checkbox\" id=\"' + idName + '\" class=\"mdl-checkbox__input\" />\\\n </label>\\\n </td>\\\n <td class=\"mdl-data-table__cell--non-numeric\">' + type + '</td>\\\n <td>' + sortedCards[i].data.length + '</td></tr>';\n }\n\n $list += '</tbody></table>';\n\n $list = $($list);\n $list.prependTo(\"#passcode-table-panel\");\n }", "function buildHtmlTable(myList, selector) {\n let columns = addAllColumnHeaders(myList, selector);\n for (let i = 0; i < myList.length; i++) {\n let row$ = $('<tr/>');\n for (let colIndex = 0; colIndex < columns.length; colIndex++) {\n let cellValue = myList[i][columns[colIndex]];\n if (JSONValueIsArray(cellValue)) {\n for (let j = 0; j < cellValue.length; j++) {\n if (cellValue == null) cellValue = \"\";\n row$.append($('<td/>').html(cellValue[j]));\n if (colIndex < columns.length - 2)\n colIndex++;\n }\n } else {\n\n if (cellValue == null) cellValue = \"\";\n row$.append($('<td/>').html(cellValue));\n }\n }\n $(selector).append(row$);\n }\n}", "function new_html( ticArr, datastrArr ){\n // var list is the final result containing table content to display.\n var list, col_num, header_arr = [];\n if (ticArr.length == 1) {\n list = split_csv_by_row(datastrArr[0]);\n col_num = 2;\n header_arr = ['Date', ticArr[0]];\n } else if (ticArr.length == 2) {\n var list1 = split_csv_by_col(datastrArr[0]);\n var list2 = split_csv_by_col(datastrArr[1]);\n list = outerjoin(list1, list2); // outerjoin two tables.\n col_num = 3;\n header_arr = ['Date', ticArr[0], ticArr[1]];\n } else {\n console.log('Abnormal ticker array size.')\n }\n\n // use 2 arrays and tickers to generate new HTML page with table.\n var newHTMLDocument = document.implementation.createHTMLDocument(\"Raw Data Display\");\n\n // source online-hosted css code to control the newly-generated HTML.\n var stylelink = newHTMLDocument.createElement(\"link\");\n stylelink.rel = \"stylesheet\";\n stylelink.type = \"text/css\";\n stylelink.href = \"https://cdn.rawgit.com/liuwenbindo/jstest/master/stylesheet.css\";\n newHTMLDocument.head.appendChild(stylelink);\n\n // source online-hosted js code to control the newly-generated HTML.\n var js_ctrl = newHTMLDocument.createElement(\"script\");\n js_ctrl.src = \"https://cdn.rawgit.com/liuwenbindo/jstest/master/src_ctrl.js\"\n newHTMLDocument.head.appendChild(js_ctrl);\n\n // source jQuery in the newly-generated page.\n var jq_ctrl = newHTMLDocument.createElement(\"script\");\n jq_ctrl.src = \"https://cdn.rawgit.com/liuwenbindo/jstest/master/js/jquery-3.3.1.min.js\"\n newHTMLDocument.head.appendChild(jq_ctrl);\n\n // generate header.\n var tbl = newHTMLDocument.createElement(\"table\");\n tbl.id = \"price_table\";\n var tbl_body = newHTMLDocument.createElement(\"tbody\");\n var tr = newHTMLDocument.createElement(\"tr\");\n var th = []\n for (var i = 0; i < col_num; i++) {\n th.push(newHTMLDocument.createElement(\"th\"));\n th[i].innerHTML = header_arr[i];\n tr.appendChild(th[i]);\n }\n tbl_body.appendChild(tr);\n\n var leng = list.length;\n // generate table cells.\n for (var i = 1; i < leng-1; i++){\n var row = document.createElement(\"tr\"); //current row\n for (var j = 0; j < col_num; j++){\n var cell = document.createElement(\"td\");\n cell.innerHTML = list[i][j];\n row.appendChild(cell);\n }\n tbl_body.appendChild(row);\n }\n\n try {\n var h1 = newHTMLDocument.createElement(\"h1\");\n h1.innerHTML = \"Raw Data Display\";\n h1.id = \"raw_header\";\n newHTMLDocument.body.appendChild(h1);\n newHTMLDocument.body.appendChild(tbl);\n tbl.appendChild(tbl_body);\n } catch(e) {\n console.log(e);\n }\n\n // add the multiple selection box for more tickers.\n add_select(newHTMLDocument, tickerlist);\n // concatenate HTML strings to add onclick function of the submit button.\n newHTMLDocument.getElementById(\"select_div\").innerHTML += \"<br><input type = 'button' value ='Submit' onclick ='click_func(); return false;'>\"\n\n // display the HTML document in the new window.\n var htmlstr = \"<html>\" + newHTMLDocument.documentElement.innerHTML + \"</html>\";\n var x = window.open();\n x.document.open();\n x.document.write(htmlstr);\n x.document.close();\n}", "function buildCheckdivs(field_options) {\n //console.log(field_options,\"DYLAN\")\n var container = jQuery('<div/>', {\n class: 'colFilters_container'\n });\n container.append(\"<h4>Other Information</h4>\")\n // Build a checkdiv from attr.s of each <th>:\n console.log(\"field options: \" + field_options.length);\n var proto_checkdiv = $('#prototype_container .checkdiv');\n for (var i=0; i<field_options.length; i++) {\n console.log(\"field options positon \" + i + \": \" + field_options[i]);\n var field = $(field_options[i]);\n if (field.hasClass('logUrl2')) {\n continue; //don't build checkbox!\n }\n var checkdiv = proto_checkdiv.clone(true); //'true' keeps event binding\n var checkdiv_checkbox = checkdiv.find(\".checkdiv-checkbox\").first();\n checkdiv_checkbox.attr('value',field.data('fieldname'));\n console.log(field.data('fieldname')); //debug\n checkdiv_checkbox.attr('name',field.data('fieldtype'));\n checkdiv.find('.checkdiv-label').text(field.text());\n checkdiv.attr(\"data-state\", \"false\");\n checkdiv_checkbox.css(\"background-color\", \"#F1F1F1\");\n container.append(checkdiv);\n }\n // Add to DOM and bind event handlers:\n $('#display_panel_body').append(container);\n container.find('.checkdiv').on('click',function() {\n var isVisible = $(this).find('.checkdiv-checkbox').data('state');\n var fieldname = $(this).find('.checkdiv-checkbox').attr('value');\n words_table.column(fieldname + \":name\").visible(isVisible);\n //debugger;\n });\n}", "function create_table(name, head, data, need_textbox) {\n\t\n\tif (head[2] == \"aliases\") { //if this is present we know it's about genes not about organisms. \n\t\thead.push(\"Orthologs\");\n\t\tvar link = \"https://www.ncbi.nlm.nih.gov/homologene/?term=\" + name;\n\t\tvar hyperlink = \"<a href=\" + link + \"> orthologs </a>\";\n\t\tdata.push(hyperlink);\n\t}\n\n\n var i=0, rowEl=null,\n\t tableEl = document.createElement(\"table\");\n\t for (i=0; i < head.length; i++) {\n\t\trowEl = tableEl.insertRow(); // DOM method for creating table rows\n\t\trowEl.insertCell().innerHTML = \"<b>\" + head[i] + \"</b>\";\n\t\trowE2 = tableEl.insertRow();\n\t\tif (need_textbox.includes(head[i])) {\n\t\t\trowE2.insertCell().innerHTML= \"<textarea class='output' rows = '4' readonly = 'readonly'>\" + data[i] + \"</textarea>\";\n\t\t}\n\t\telse {\n\t\t\tif (head[i] == \"Orthologs\") {\n\t\t\t\trowE2.insertCell().innerHTML=data[i];\n\t\t\t}\n\t\t\telse{\n\t\t\t\trowE2.insertCell().innerHTML= \"<input class ='output' type='text' name='fname' readonly='readonly' value=\" + data[i] + \">\";\n\t\t\t}\n\t\t}\n\t }\n\tparent.document.getElementById('table_result').innerHTML = \"\";\n\tvar div = parent.document.getElementById('table_result')\n\tdiv.appendChild(tableEl)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get logs from all sources in list in chronological order
function getAllEntries(){ for(const [sourceId, logSource] of logSources.entries()){ getEntries(sourceId, logSource); } }
[ "function getLogsFromServer() {\n if (!$scope.logs) return;\n\n var logs = $scope.logs;\n var len = logs.length;\n for (var i = 0; i < len; i++) {\n getLog(logs[i]);\n }\n }", "function sink (log, sources, ms, cnt) {\n var lastKeys = null\n var stream = kefir.merge(sources)\n function saveToLog (values) {\n return kefir.fromNodeCallback(cb => {\n var docs = values.map(v => {\n return {\n links: lastKeys,\n value: v,\n }\n })\n log.batch(docs, cb)\n })\n }\n var saved = stream\n .bufferWithTimeOrCount(ms,cnt)\n .filter(buff => buff.length>0)\n .flatMap(saveToLog)\n saved.onValue(ns => {\n lastKeys = ns.map(n => n.key)\n })\n return saved\n}", "getLogs() {\n this.logs.map((log)=>{\n console[log.type].call(null, log.msg);\n })\n }", "function getEntries(sourceId, logSource){\n try{\n logSource.popAsync().then(\n function (entry){\n if(entry){\n //add sourceid to elem so it can be traced to source when popped from heap\n entry.sourceId=sourceId;\n heap.push(entry);\n logsFull.add(sourceId);\n //once all sources have one elem in heap, start the heap handling process\n if(logsFull.size==logSources.length)\n accessHeap();\n }\n }\n );\n }catch{\n console.log(\"getEntries function failed for source\" + sourceId)\n }\n }", "function fetchLogs(count) {\n function Skipped(message) {\n this.message = message;\n }\n return gcs.conversationLogs.conversationLog.get().then(function (logs) {\n return repeatAndExit(function (exit) {\n var log = logs[nextTranscript.logIndex];\n var recipients = log.conversationLogRecipient;\n var subject = log.subject;\n return Task.waitAll([subject.get(), recipients.get()]).then(function () {\n if (recipients().length != 1)\n throw new Skipped('conference');\n return recipients(0).sipUri.get();\n }).then(function (sip) {\n if (sip != participants(0).uri())\n throw new Skipped('different participant');\n return log.conversationLogTranscripts.conversationLogTranscript.get();\n }).then(function (transcripts) {\n return repeat(function () {\n var transcript = transcripts[nextTranscript.transcriptIndex++];\n if (!transcript)\n throw new Skipped('no more transcripts');\n var messageTranscript = transcript.messageTranscript;\n var html = messageTranscript.htmlMessage.href;\n var text = messageTranscript.plainMessage.href;\n var time = transcript.timeStamp;\n var href = transcript.contact.href;\n var dir = log.direction;\n var message = new Internal.Message({\n ucwa: ucwa,\n href: dir() == 'Incoming' ? '' : null,\n sender: { person: contactManager.get(href) },\n time: time(),\n text: text(),\n html: html(),\n direction: dir()\n });\n addMessageActivityItem(message);\n count--;\n if (count < 1)\n exit();\n });\n }).catch(function (err) {\n if (err instanceof Skipped) {\n nextTranscript.logIndex++;\n nextTranscript.transcriptIndex = 0;\n }\n else {\n throw err;\n }\n });\n });\n });\n }", "function getLog(index) {\r\n\t//$.get('status_'+ index +'.log', function(datados) {\r\n $.get(cs_folder+'/status_'+index+'.log', function(datados) {\r\n\t\t$(\"#layout_logger_console_content_\"+index).html('');\r\n\t\tvar lines = datados.split(\"\\n\");\r\n\t\tfor (nm in lines)\t{\r\n\t\t\t//console.log('lineas' + nm);\r\n\t\t\t$(\"#layout_logger_console_content_\"+index).append('<p>'+lines[nm]+'</p>');\r\n\t\t}\r\n\t});\r\n}", "eth_getLogs(filter) {\n return this.request(\"eth_getLogs\", Array.from(arguments));\n }", "get logPaths() {\n return this.getListAttribute('log_paths');\n }", "function getEventLogs(callback, n) {\n EventLog\n .find()\n .sort({\"timestamp\": -1})\n .limit(n || 10)\n .exec(callback);\n}", "function retrieveLogs(simulation){\n\t//calls function from localSimulationManager\n\tvar device_list=getAllDeviceObjects(simulation);\n\t\n\tfor (var i =0;i<device_list.length;i++){\n\t\tsimulationLogs+=device_list[i].activity+'\\n';\n\t}\n\tvar simulationLogs= simulation.activity_logs;\n\treturn simulationLogs;\n}", "processEntries() {\n let previousMinute = new Date();\n // One minute ago.\n previousMinute = previousMinute.setMinutes(previousMinute.getMinutes() - 1);\n\n // Keep only \"new\" log entries (less than 1 minute)\n this.logEntries = reduce(this.logEntries, (list, entry) => {\n if (entry >= previousMinute) {\n list.push(entry);\n }\n return list;\n }\n , {});\n }", "function filter_key_master(ulogs) {\n var flogs = [];\n for (var i = 0; i < ulogs.length; i++) {\n var d = ulogs[i];\n var pc = d.data;\n var ks = pc.ks;\n var cnode = ZPart.GetKeyNode(ks);\n if (cnode && cnode.device_uuid === ZH.MyUUID) flogs.push(d);\n }\n return flogs;\n}", "function autoMoveLogs(){\n logsLeft.forEach(logLeft => moveLogLeft(logLeft));\n logsRight.forEach(logRight => moveLogRight(logRight));\n }", "function batchGetLogs(filter, finalBlock, logs = []) {\n return __awaiter(this, void 0, void 0, function* () {\n if (filter.toBlock < finalBlock) {\n try {\n // toBlock is less than the finalBlock, Get logs with the incoming filter\n const normalizedLogs = yield getDecodedNormalizedLogs(filter);\n const accLogs = logs.concat(normalizedLogs);\n // Set new filter\n const newFilter = Object.assign({}, filter, { fromBlock: filter.toBlock + 1, toBlock: filter.toBlock + blockRangeThreshold });\n console.log(`Found ${normalizedLogs.length} logs`);\n console.log('Subtotal logs:', accLogs.length);\n console.log('Remaining blocks:', finalBlock - newFilter.fromBlock);\n console.log();\n // Recurse: new filter, new accumulation of logs\n return batchGetLogs(newFilter, finalBlock, accLogs);\n }\n catch (error) {\n console.log('Error while getting batched logs:', error);\n return batchGetLogs(filter, finalBlock, logs);\n }\n }\n // ----------------------------------------\n // toBlock is > finalBlock\n // Get final logs from the remaining blocks\n // ----------------------------------------\n try {\n const lastFilter = Object.assign({}, filter, { toBlock: finalBlock });\n const lastNormalizedLogs = yield getDecodedNormalizedLogs(lastFilter);\n console.log(`Found ${lastNormalizedLogs.length} logs`);\n // Return final array of decoded normalized logs\n const finalLogs = logs.concat(lastNormalizedLogs);\n console.log(`\n Total logs: ${finalLogs.length}\n `);\n return finalLogs;\n }\n catch (error) {\n console.log('Error while getting final logs:', error);\n return batchGetLogs(filter, finalBlock, logs);\n }\n });\n }", "getLogs() {\n if (this.auth()) {\n if (this.currentUser.type === \"admin\") {\n console.log(\"Saved logs: \");\n for (let i = 0; i < this.logs.length; i++) {\n console.log(this.logs[i]);\n }\n } else console.log('Access is denied')\n } else console.log('authorization required');\n }", "getLogs$() {\n return this.logs$.asObservable();\n }", "function get_history(filename, callback)\n{\n simpleGit.log([ filename ], function(err, data) {\n if(err) {\n console.error(err);\n callback();\n }\n\n var filter_data = data.all.map(function(elem) {\n return {\n date : elem.date,\n message : elem.message,\n author_email : elem.author_email\n }\n });\n\n callback(filter_data);\n });\n}", "function sortSources() {\n let screenSources = [];\n let applicationSources = [];\n // Difference with Mac selects:\n // 1 screen = \"Enitre Screen\", more than one like PC \"Screen 1, Screen 2...\"\n screenshareSourceArray.forEach((source) => {\n if (source.name.match(/(entire )?screen( )?([0-9]?)/i)) {\n screenSources.push(source);\n } else {\n applicationSources.push(source)\n }\n });\n screenSources.sort((a, b) => {\n let aNumber = a.name.replace(/[^\\d]/, \"\");\n let bNumber = b.name.replace(/[^\\d]/, \"\");\n return aNumber - bNumber;\n });\n let finalSources = [...screenSources, ...applicationSources];\n return finalSources;\n}", "function groupSourcesByDomain(sources) {\n return sources.valueSeq()\n .filter(source => !!source.get(\"url\"))\n .groupBy(source => (new URL(source.get(\"url\"))).hostname);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
$Id: CSSAnalyzer.js,v 1.5 2005/03/31 15:18:20 malex Exp $ ============================================================================ The CSSAnalyzer class ============================================================================ Constructor
function CSSAnalyzer(fileAttr, session) { this._doc = fileAttr; this._session = session; this._initialized = false; this._blocks = null; }
[ "parse(cssText) {\n return this.parseStylesheet(new tokenizer_1.Tokenizer(cssText));\n }", "function CSSCache()\n{\n this._blocks = new Object(); // hash table url -> CSSBlock\n this._dates = new Object(); // hash table url -> modification date \n}", "function CSSRule(raw_sel, raw_prop)\n{\n this._selectors = new Array();\n var list = raw_sel.split(',');\n for (var i=0; i<list.length; i++) {\n\t// take only element (not its parent, ancestor or sibling)\n\tsel = stripString(list[i]);\n\tvar last_sel = sel.split(/(\\s|>|\\+)+/);\n\tif (last_sel.length > 0)\n\t this._selectors.push(last_sel[last_sel.length-1]);\n }\n this._properties = new Array();\n var prop_list = raw_prop.split(';');\n for (var j=0; j<prop_list.length; j++) {\n\tvar res = prop_list[j].split(':');\n\tif (res.length == 2) {\n\t this._properties.push(stripString(res[0]));\n\t this._properties.push(res[1]);\n\t} \n }\n}", "function Stylesheet(ss) {\n if (typeof ss == \"number\") ss = document.styleSheets[ss];\n this.ss = ss;\n}", "parseStylesheet(tokenizer) {\n return this.nodeFactory.stylesheet(this.parseRules(tokenizer), { start: 0, end: tokenizer.cssText.length });\n }", "constructor(source, offset, length) {\n this.source = source\n this.offset = offset\n this.length = length\n this.cachedContent = null\n this.cachedLineCount = null\n }", "function WordParser () {}", "function retextCount() {\n this.Compiler = countWords;\n}", "tokenizeWhitespace(offset) {\n const start = offset;\n common_1.matcher.whitespaceGreedy.lastIndex = offset;\n const match = common_1.matcher.whitespaceGreedy.exec(this.cssText);\n if (match != null && match.index === offset) {\n offset = common_1.matcher.whitespaceGreedy.lastIndex;\n }\n return new token_1.Token(token_1.Token.type.whitespace, start, offset);\n }", "visitConstructor_declaration(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function ensureCSSAdded() {\n\t if (!cssNode) {\n\t cssNode = document.createElement(\"style\");\n\t cssNode.textContent = \"/* ProseMirror CSS */\\n\" + accumulatedCSS;\n\t document.head.insertBefore(cssNode, document.head.firstChild);\n\t }\n\t}", "static toStyleClass(str) {\n return str.replace(/(\\w)([A-Z])/g, (_m, m1, m2) => m1 + \"-\" + m2).toLowerCase();\n }", "enterConstructorDeclarator(ctx) {\n\t}", "get css() {\n return __webpack_require__(/*! ./parser-postcss */ \"./node_modules/prettier/parser-postcss.js\").parsers.css;\n }", "function createStyleManager() {\n\t var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},\n\t jss = _ref.jss,\n\t _ref$theme = _ref.theme,\n\t theme = _ref$theme === undefined ? {} : _ref$theme;\n\t\n\t if (!jss) {\n\t throw new Error('No JSS instance provided');\n\t }\n\t\n\t var sheetMap = [];\n\t var sheetOrder = void 0;\n\t\n\t // Register custom jss generateClassName function\n\t jss.options.generateClassName = generateClassName;\n\t\n\t function generateClassName(str, rule) {\n\t var hash = (0, _murmurhash3_gc2.default)(str);\n\t str = rule.name ? rule.name + '-' + hash : hash;\n\t\n\t // Simplify after next release with new method signature\n\t if (rule.options.sheet && rule.options.sheet.options.name) {\n\t return rule.options.sheet.options.name + '-' + str;\n\t }\n\t return str;\n\t }\n\t\n\t /**\n\t * styleManager\n\t */\n\t var styleManager = {\n\t get sheetMap() {\n\t return sheetMap;\n\t },\n\t get sheetOrder() {\n\t return sheetOrder;\n\t },\n\t setSheetOrder: setSheetOrder,\n\t jss: jss,\n\t theme: theme,\n\t render: render,\n\t reset: reset,\n\t rerender: rerender,\n\t getClasses: getClasses,\n\t updateTheme: updateTheme,\n\t prepareInline: prepareInline,\n\t sheetsToString: sheetsToString\n\t };\n\t\n\t updateTheme(theme, false);\n\t\n\t function render(styleSheet) {\n\t var index = getMappingIndex(styleSheet.name);\n\t\n\t if (index === -1) {\n\t return renderNew(styleSheet);\n\t }\n\t\n\t var mapping = sheetMap[index];\n\t\n\t if (mapping.styleSheet !== styleSheet) {\n\t jss.removeStyleSheet(sheetMap[index].jssStyleSheet);\n\t sheetMap.splice(index, 1);\n\t\n\t return renderNew(styleSheet);\n\t }\n\t\n\t return mapping.classes;\n\t }\n\t\n\t /**\n\t * Get classes for a given styleSheet object\n\t */\n\t function getClasses(styleSheet) {\n\t var mapping = (0, _utils.find)(sheetMap, { styleSheet: styleSheet });\n\t return mapping ? mapping.classes : null;\n\t }\n\t\n\t /**\n\t * @private\n\t */\n\t function renderNew(styleSheet) {\n\t var name = styleSheet.name,\n\t createRules = styleSheet.createRules,\n\t options = styleSheet.options;\n\t\n\t var sheetMeta = name + '-' + styleManager.theme.id;\n\t\n\t if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && (typeof document === 'undefined' ? 'undefined' : _typeof(document)) === 'object') {\n\t var element = document.querySelector('style[data-jss][data-meta=\"' + sheetMeta + '\"]');\n\t if (element) {\n\t options.element = element;\n\t }\n\t }\n\t\n\t var rules = createRules(styleManager.theme);\n\t var jssOptions = _extends({\n\t name: name,\n\t meta: sheetMeta\n\t }, options);\n\t\n\t if (sheetOrder && !jssOptions.hasOwnProperty('index')) {\n\t var index = sheetOrder.indexOf(name);\n\t if (index === -1) {\n\t jssOptions.index = sheetOrder.length;\n\t } else {\n\t jssOptions.index = index;\n\t }\n\t }\n\t\n\t var jssStyleSheet = jss.createStyleSheet(rules, jssOptions);\n\t\n\t var _jssStyleSheet$attach = jssStyleSheet.attach(),\n\t classes = _jssStyleSheet$attach.classes;\n\t\n\t sheetMap.push({ name: name, classes: classes, styleSheet: styleSheet, jssStyleSheet: jssStyleSheet });\n\t\n\t return classes;\n\t }\n\t\n\t /**\n\t * @private\n\t */\n\t function getMappingIndex(name) {\n\t var index = (0, _utils.findIndex)(sheetMap, function (obj) {\n\t if (!obj.hasOwnProperty('name') || obj.name !== name) {\n\t return false;\n\t }\n\t\n\t return true;\n\t });\n\t\n\t return index;\n\t }\n\t\n\t /**\n\t * Set DOM rendering order by sheet names.\n\t */\n\t function setSheetOrder(sheetNames) {\n\t sheetOrder = sheetNames;\n\t }\n\t\n\t /**\n\t * Replace the current theme with a new theme\n\t */\n\t function updateTheme(newTheme) {\n\t var shouldUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n\t\n\t styleManager.theme = newTheme;\n\t if (!styleManager.theme.id) {\n\t styleManager.theme.id = (0, _murmurhash3_gc2.default)(JSON.stringify(styleManager.theme));\n\t }\n\t if (shouldUpdate) {\n\t rerender();\n\t }\n\t }\n\t\n\t /**\n\t * Reset JSS registry, remove sheets and empty the styleManager.\n\t */\n\t function reset() {\n\t sheetMap.forEach(function (_ref2) {\n\t var jssStyleSheet = _ref2.jssStyleSheet;\n\t jssStyleSheet.detach();\n\t });\n\t sheetMap = [];\n\t }\n\t\n\t /**\n\t * Reset and update all existing stylesheets\n\t *\n\t * @memberOf module:styleManager~styleManager\n\t */\n\t function rerender() {\n\t var sheets = [].concat(_toConsumableArray(sheetMap));\n\t reset();\n\t sheets.forEach(function (n) {\n\t render(n.styleSheet);\n\t });\n\t }\n\t\n\t /**\n\t * Prepare inline styles using Theme Reactor\n\t */\n\t function prepareInline(declaration) {\n\t if (typeof declaration === 'function') {\n\t declaration = declaration(theme);\n\t }\n\t\n\t var rule = {\n\t type: 'regular',\n\t style: declaration\n\t };\n\t\n\t prefixRule(rule);\n\t\n\t return rule.style;\n\t }\n\t\n\t /**\n\t * Render sheets to an HTML string\n\t */\n\t function sheetsToString() {\n\t return sheetMap.sort(function (a, b) {\n\t if (a.jssStyleSheet.options.index < b.jssStyleSheet.options.index) {\n\t return -1;\n\t }\n\t if (a.jssStyleSheet.options.index > b.jssStyleSheet.options.index) {\n\t return 1;\n\t }\n\t return 0;\n\t }).map(function (sheet) {\n\t return sheet.jssStyleSheet.toString();\n\t }).join('\\n');\n\t }\n\t\n\t return styleManager;\n\t}", "function analyze_js(input, start, argPos) {\r\n\t\t\r\n\t// Set up starting variables\r\n\tvar currentArg\t\t= 1;\t\t\t\t // Only used if extracting argument position\r\n\tvar i\t\t\t\t\t= start;\t\t\t // Current character position\r\n\tvar length\t\t\t= input.length; // Length of document\r\n\tvar end\t\t\t\t= false;\t\t\t // Have we found the end?\r\n\tvar openObjects\t= 0;\t\t\t\t // Number of objects currently open\r\n\tvar openBrackets\t= 0;\t\t\t\t // Number of brackets currently open\r\n\tvar openArrays\t\t= 0;\t\t\t\t // Number of arrays currently open\r\n\t\r\n\t// Loop through input char by char\r\n\twhile ( end === false && i < length ) {\r\n\t\r\n\t\t// Extract current char\r\n\t\tvar currentChar = input.charAt(i);\r\n\t\r\n\t\t// Examine current char\r\n\t\tswitch ( currentChar ) {\r\n\t\t\r\n\t\t\t// String syntax\r\n\t\t\tcase '\"':\r\n\t\t\tcase \"'\":\r\n\t\t\t\r\n\t\t\t\t// Move up to the corresponding end of string position, taking\r\n\t\t\t\t// into account and escaping backslashes\r\n\t\t\t\twhile ( ( i = strpos(input, currentChar, i+1) ) && input.charAt(i-1) == '\\\\' );\r\n\t\t\t\r\n\t\t\t\t// False? Closing string delimiter not found... assume end of document \r\n\t\t\t\t// although technically we've screwed up (or the syntax is invalid)\r\n\t\t\t\tif ( i === false ) {\r\n\t\t\t\t\tend = length;\r\n\t\t\t\t}\r\n\t\t\t\r\n\t\t\t\tbreak;\r\n\t\t\r\n\t\t\r\n\t\t\t// End of operation\r\n\t\t\tcase ';':\r\n\t\t\t\tend = i;\r\n\t\t\t\tbreak;\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t// Newlines\r\n\t\t\tcase \"\\n\":\r\n\t\t\tcase \"\\r\":\r\n\t\t\t\t\r\n\t\t\t\t// Newlines are ignored if we have an open bracket or array or object\r\n\t\t\t\tif ( openObjects || openBrackets || openArrays || argPos ) {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\r\n\t\t\t\t// Newlines are also OK if followed by an opening function OR concatenation\r\n\t\t\t\t// e.g. someFunc\\n(params) or someVar \\n + anotherVar\r\n\t\t\t\t// Find next non-whitespace char position\r\n\t\t\t\tvar nextCharPos = i + strspn(input, \" \\t\\r\\n\", i+1) + 1;\r\n\t\t\t\t\r\n\t\t\t\t// And the char that refers to\r\n\t\t\t\tvar nextChar = input.charAt(nextCharPos);\r\n\t\t\t\t\r\n\t\t\t\t// Ensure not end of document and if not, char is allowed\r\n\t\t\t\tif ( nextCharPos <= length && ( nextChar == '(' || nextChar == '+' ) ) {\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Move up offset to our nextChar position and ignore this newline\r\n\t\t\t\t\ti = nextCharPos;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t// Still here? Newline not OK, set end to this position\r\n\t\t\t\tend = i;\r\n\t\t\t\tbreak;\r\n\r\n\r\n\t\t\t// Concatenation\r\n\t\t\tcase '+':\r\n\t\t\t\t// Our interest in the + operator is it's use in allowing an expression\r\n\t\t\t\t// to span multiple lines. If we come across a +, move past all whitespace,\r\n\t\t\t\t// including newlines (which would otherwise indicate end of expression).\r\n\t\t\t\ti += strspn(input, \" \\t\\r\\n\", i+1);\r\n\t\t\t\tbreak;\r\n\r\n\r\n\t\t\t// Opening chars (objects, parenthesis and arrays)\r\n\t\t\tcase '{':\r\n\t\t\t\t++openObjects;\r\n\t\t\t\tbreak;\r\n\t\t\tcase '(':\r\n\t\t\t\t++openBrackets;\r\n\t\t\t\tbreak;\r\n\t\t\tcase '[':\r\n\t\t\t\t++openArrays;\r\n\t\t\t\tbreak;\r\n\t\t\t\t\r\n\t\t\t// Closing chars - is there a corresponding open char? \r\n\t\t\t// Yes = reduce stored count. No = end of statement.\r\n\t\t\tcase '}':\r\n\t\t\t\topenObjects\t ? --openObjects\t : end = i;\r\n\t\t\t\tbreak;\r\n\t\t\tcase ')':\r\n\t\t\t\topenBrackets ? --openBrackets : end = i;\r\n\t\t\t\tbreak;\r\n\t\t\tcase ']':\r\n\t\t\t\topenArrays\t ? --openArrays\t : end = i;\r\n\t\t\t\tbreak;\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t// Comma\r\n\t\t\tcase ',':\r\n\t\t\t\r\n\t\t\t\t// No interest here if not looking for argPos\r\n\t\t\t\tif ( ! argPos ) {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t// Ignore commas inside other functions or whatnot\r\n\t\t\t\tif ( openObjects || openBrackets || openArrays ) {\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t// End now\r\n\t\t\t\tif ( currentArg == argPos ) {\r\n\t\t\t\t\tend = i;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t// Increase the current argument number\r\n\t\t\t\t++currentArg;\r\n\t\t\t\t\r\n\t\t\t\t// If we're not after the first arg, start now?\r\n\t\t\t\tif ( currentArg == argPos ) {\r\n\t\t\t\t\tvar start = i+1;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tbreak;\r\n\t\t\t\r\n\t\t\t// Any other characters\r\n\t\t\tdefault:\r\n\t\t\t\t// Do nothing\r\n\t\t}\r\n\t\t\r\n\t\t// Increase offset\r\n\t\t++i;\r\n\t\r\n\t}\r\n\t\r\n\t// End not found? Use end of document\r\n\tif ( end === false ) {\r\n\t\tend = length;\r\n\t}\r\n\r\n\t// Return array of start/end if looking for argPos\r\n\tif ( argPos ) {\r\n\t\treturn [start, end];\r\n\t}\r\n\t\r\n\t// Return end\r\n\treturn end;\r\n\t\r\n}", "function Selector() {\n\t\tthis.rules = {};\n\t}", "function compareFiles() {\n var css = new Hashset.string();\n var dups = new Hashset.string();\n\n var rules = getRules(program.args[0]);\n\n for (var i = 0; i < rules.length; i++) {\n for (var j=0; j < rules[i].selectors.length; j++) {\n css.add(rules[i].selectors[j]);\n }\n }\n\n rules = getRules(program.args[1]);\n\n for (var i = 0; i < rules.length; i++) {\n for (var j=0; j < rules.length; j++) {\n var sel = rules[i].selectors[j];\n if (css.contains(sel)) {\n dups.add(sel);\n }\n }\n }\n\n var iter = dups.iterator();\n while (iter.hasNext()) {\n console.log(iter.next());\n }\n\n}", "function compress(sin, bs, ic,bsort){\nvar sout= '';\nvar comp = 0;\nvar re;\n sout = sin;\n\n bs=(typeof(bs)=='undefined')?false:bs;\n ic=(typeof(ic)=='undefined')?false:ic; \n bsort=(typeof(bsort)=='undefined')?false:bsort;\n \n // I've not a lot of experience with Regular Expressions,\n // Any for additional add-ons.. please notify me!\t\n \n //remove all multiple white-spaces\n sout = sout.replace(/\\s+/g, ' ');\n \n //remove all -*/..-\n sout = sout.replace(/\\*\\/\\s+/g, '*\\/');\n \n //replace all occurences of - spaces + [ an { or an } ] + white-spaces - with \"the character\"\n sout = sout.replace(/\\s{0,}({|})\\s{0,}/g, '$1');\n\n //whipe out all spaces between css-names:.. and last value ; ..\n sout = sout.replace(/\\s{0,}(:|;|,)\\s{0,}/g, '$1');\n\n //remove all -;- before -}-\n sout=sout.replace(/(;})/g, '}');\n\n // shorthand notations\n sout = shorthand_notations(sout); \n\n //remove all comments\n if(!ic) sout = sout.replace(/(\\/\\*).*?(\\*\\/)\\s{0,}/g, '');\n \n //trim leading and trailing spaces (if any left)\n sout = sout.replace(/^\\s+/g, '').replace(/\\s+$/g, '');\n\n // sort css definitions (only if no comments included)\n if(!ic && bsort) sout = sortcss(sout);\n\n //and for the reading-ness of all.. replace -} or */- with - } and a line break -\n \n if(!bs){\n sout = sout.replace(/}/g, '}\\n'); \n sout=sout.replace(/\\*\\//g, '*\\/\\n'); \n }\n \n\n\n return sout;\n\n}//--------------------------------------------------------------" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Buff check: "Well fed"
function τSST_detect_buff_well_fed() { buffs_table.buff_msgs_summary = localStorage[storage_key_prefix + 'buffs_table_buff_messages']; var page_buffs_node = $(".buff-messages").find(".timer-message"); if (page_buffs_node.length) { var buffs_list = buffs_table.buff_messages; var buffs_list_new = page_buffs_node.find("td:first").map(function() { return $(this).text(); }).get(); var list_temp = []; var buff; while (buffs_list && buffs_list.length > 0) { buff = buffs_list.shift(); if (buffs_list_new.includes(buff)) { list_temp.push(buff); } } buffs_list = list_temp; while (buffs_list_new.length > 0) { buff = buffs_list_new.shift(); if (! buffs_list.includes(buff)) { buffs_list.push(buff); } } buffs_table.buff_messages = buffs_list; } // If this buff has changed, note the fact for our callers. buffs_table.buff_msgs_summary = buffs_table.buff_messages.join(','); if (localStorage[storage_key_prefix + 'buffs_table_buff_messages'] != buffs_table.buff_msgs_summary) { buffs_changed = true; } // Buff updates are stored only when actually updating a stat log. }
[ "function checkEntityForBuff(entity, buff) {\n let s = false;\n if (entity.s) s = Object.keys(entity.s).includes(buff);\n let overall = Object.keys(entity).includes(buff);\n return s || overall;\n}", "function τSST_detect_static_buffs() {\n // Available only in Player Details page (http://alpha.taustation.space/ - root page).\n τSST_detect_buff_genotype();\n τSST_detect_buff_vip(); // TODO: Does this show the GCT time when VIP will end? If so, add to \"...dynamic...()\" below.\n τSST_detect_buff_skills();\n\n // Available on most (any?) page.\n τSST_detect_buff_hotel_room();\n }", "function busted(hand) {\n if (getTotal(hand) > MAX_VALUE) {\n return true;\n } else {\n return false;\n }\n}", "function τSST_detect_buff_hotel_room() {\n buffs_table.location = undefined;\n\n if ($(\".zone-notice\").text().includes(\"now in a safe zone\") ||\n $('a[href=\"/area/hotel-rooms/enter-room\"]').text().includes(\"Return to hotel room view\"))\n {\n buffs_table.location = \"Hotel\";\n }\n\n // If this buff has changed, note the fact for our callers.\n if (localStorage[storage_key_prefix + 'buffs_table_location'] != buffs_table.location) {\n buffs_changed = true;\n }\n\n // Buff updates are stored only when actually updating a stat log.\n }", "function diffuseBomb(input){\n let params = {\n white: ['purple', 'green', 'red', 'orange'],\n red: ['green'],\n black: ['red','black','purple'],\n orange: ['red','black'],\n green: ['orange', 'white'],\n purple: ['black','red']\n };\n function lookAtWire(cut){\n let [current, next] = cut;\n return !next || params[current].includes(next) && diffuseBomb(cut.slice(1));\n }\n return lookAtWire(input.split('\\n')) ? \"Diffused\" : \"Boom\";\n}", "_checkSendBuffer() {\n\n this._d(`${this.insertIndex} / ${this.deleteIndex}.`);\n\n if ( this.insertIndex === this.deleteIndex ) {\n\n // end buffer is 'empty' => nothing to do then wait till's flled again.\n this.isLoopRunning = false ;\n this._d(\"Send loop temp stopped - empty send buffer.\");\n } else {\n if ( this.sendAr[ this.deleteIndex ] === \"\" ) {\n\n // If the command to be send if empty consider it as\n // empty buffer and exit the data send loop.\n this.isLoopRunning = false ;\n this._d(\"Sendbuffer entry empty (stopping send loop)!.\");\n } else {\n let data = this.sendAr[ this.deleteIndex ];\n this.sendAr[ this.deleteIndex ] = \"\"; // clear used buffer.\n this.deleteIndex++;\n\n if ( this.deleteIndex >= this.MAXINDEX ) {\n this.deleteIndex = 0;\n }\n this._d(`Setting deleteIndex to ${this.deleteIndex}.`);\n\n this._sendToAvr( data );\n }\n }\n }", "function check(smuggler,sheriff,players,decks){\n\tvar smugglerStats = players[smuggler].game;\n\tvar declared = smugglerStats.declared;\n\tvar sheriffStats = players[sheriff].game;\n\tvar lying=false;\n\tvar penalty=0;\n\t//forfeit any bribes\n\tfor(var bribe in player.bribe){\n\t\taddGood(sheriff,bribe);\n\t}\n\tfor(var good in smugglerStats.bag){\n\t\tif(good.name!=declared){\n\t\t\t//reset penalty to start being incurred to smuggler\n\t\t\tif(!lying){\n\t\t\t\tpenalty=0;\n\t\t\t}\n\t\t\tlying=true;\n\t\t\t//discard the good\n\t\t\tif(decks.leftHeap>decks.rightHeap){\n\t\t\t\tdecks.rightHeap.push(good);\n\t\t\t}else{\n\t\t\t\tdecks.leftHeap.push(good);\n\t\t\t}\n\t\t\tpenalty+=good.penalty;\n\t\t}else{\n\t\t\t//if player has been consistently truthful add more penalty\n\t\t\tif(!lying){\n\t\t\t\tpenalty+=good.penalty;\n\t\t\t}\n\t\t}\n\t\tpassThrough(smuggler);\n\t\tvar result;\n\t\tif(!lying){\n\t\t\tsheriffStats.money-=penalty;\n\t\t\tsmugglerStats.money+=penalty;\n\t\t\tresult = 'Tricked again! You lost {penalty} coins for incorrect inspection';\n\t\t}else{\n\t\t\tsheriffStats.money+=penalty;\n\t\t\tsmugglerStats.money-=penalty;\n\t\t\tresult = 'Gotcha! You caught them red handed. Nothing like a good profit';\n\t\t}\n\t\treturn{\"result\":result};\n\t}\n}", "writeReady() {\n return !this.highWater;\n }", "isWeakerThan(hand) {\n // ˅\n return this.judgeGame(hand) === -1;\n // ˄\n }", "function isRealRoom(data) {\n const [ encName, , checksum ] = data;\n\n return getChecksum(encName) === checksum;\n}", "function chkBabyCry() {\n if (player.sprite === player.withMb) {\n if((babyBoy.sprites.main === babyBoy.sprites.hungry) && (collide(player,babyBoy,60))) {\n giveMb(player,babyBoy);\n setTimeout(function () {babyGirl.cry();}, 2000);\n } else if((babyGirl.sprites.main === babyGirl.sprites.hungry) && (collide(player,babyGirl,60))) {\n giveMb(player,babyGirl);\n setTimeout(function () {babyBoy.cry();}, 3000);\n }\n }\n }", "function isDamagedFrame(frame) {\n // In real life, re-generate CRC and compare against the sender's CRC\n\n // Adding below code for simulation purpose only\n if (frame.attr(\"class\").indexOf(\"damagedFrame\") != -1) {\n return true;\n }\n\n return false;\n\n}", "function OneShotLimitReached()\n{\n\treturn (crashesStarted + gearShiftsStarted) > oneShotLimit;\n}", "function check() {\n\tif (userHp <= 0) {\n\t\tline();\n\t\tconsole.log('You LOST to a racoon! How sad for you. :(');\n\t\tline();\n\t\trematch();\n\t} else if (racHp <= 0) {\n\t\tline();\n\t\tconsole.log('You WON! You live to fight another day!');\n\t\tline();\n\t\trematch();\n\t} else {\n\t\tline();\n\t\tconsole.log(`You have ${userHp}Hp left. The raccoon has ${racHp}Hp left`);\n\t\tline();\n\t\tround();\n\t}\n}", "function isPlayerWin(player, casted, boss, state) {\n var playerHp = state.playerHp || player.hp;\n var playerMana = state.playerMana || player.mana;\n var playerArmor = state.playerArmor || 0;\n var bossHp = state.bossHp || boss.hp;\n var bossDamage = state.bossDamage || boss.damage;\n var shieldCountDown = state.shieldCountDown || 0;\n var poisonCountDown = state.poisonCountDown || 0;\n var rechargeCountDown = state.rechargeCountDown || 0;\n var turn = state.turn || 0;\n var finished = false;\n while (!finished && playerHp > 0 && bossHp > 0) {\n if (turn % 2 == 0 && turn / 2 >= casted.length) { // player did not have enough spells queued up\n finished = true;\n break;\n }\n if (turn % 2 == 0 && --playerHp <= 0) { // hard mode, player loses 1 hp each turn\n break;\n }\n //console.log(\"---\");\n //console.log(\"Player: HP: \" + playerHp + \" Mana: \" + playerMana + \" Armor: \" + playerArmor);\n //console.log(\"Boss: HP: \" + bossHp);\n if (shieldCountDown > 0) {\n playerArmor = 7;\n shieldCountDown--;\n if (shieldCountDown == 0) {\n playerArmor = 0;\n }\n }\n if (poisonCountDown > 0) {\n bossHp -= 3;\n poisonCountDown--;\n }\n if (rechargeCountDown > 0) {\n playerMana += 101;\n rechargeCountDown--;\n }\n\n if (turn % 2 == 0) {\n var spell = casted[turn / 2];\n //console.log(\"Player casts: \" + spell);\n if (spell == \"missile\") {\n playerMana -= 53;\n bossHp -= 4;\n }\n else if (spell == \"drain\") {\n playerMana -= 73;\n bossHp -= 2;\n playerHp += 2;\n }\n else if (spell == \"shield\") {\n playerMana -= 113;\n if (shieldCountDown > 0) {\n throw new Error(\"Cannot cast shield while shield is still active!\");\n }\n shieldCountDown = 6;\n }\n else if (spell == \"poison\") {\n playerMana -= 173;\n if (poisonCountDown > 0) {\n throw new Error(\"Cannot cast poison while poison is still active!\");\n }\n poisonCountDown = 6;\n }\n else if (spell == \"recharge\") {\n playerMana -= 229;\n if (rechargeCountDown > 0) {\n throw new Error(\"Cannot cast recharge while recharge is still active!\");\n }\n rechargeCountDown = 5;\n }\n else {\n console.log(\"Unknown spell: \" + spell);\n }\n if (playerMana < 53) {\n playerHp = 0; // player dies if they run out of mana\n //throw new Error(\"Player ran out of mana!\");\n }\n }\n else {\n playerHp -= Math.max(1, bossDamage - playerArmor);\n // console.log(\"Boss hits: \" + Math.max(1, bossDamage - playerArmor));\n }\n\n turn++;\n }\n if (finished) {\n return [undefined, {\n \"playerHp\": playerHp,\n \"playerMana\": playerMana,\n \"playerArmor\": playerArmor,\n \"bossHp\": bossHp,\n \"bossDamage\": bossDamage,\n \"shieldCountDown\": shieldCountDown,\n \"poisonCountDown\": poisonCountDown,\n \"rechargeCountDown\": rechargeCountDown,\n \"turn\": turn\n }]\n }\n else {\n if (playerHp <= 0) {\n //console.log(\"---\");\n //console.log(\"Player died. Boss HP: \" + bossHp);\n return [bossHp <= 0, {}]; // we have to check that if boss kills player, that it didn't die first\n }\n else {\n //console.log(\"---\");\n //console.log(\"Boss dies. Player: HP: \" + playerHp + \" Mana: \" + playerMana + \" Armor: \" + playerArmor);\n return [true, {}];\n }\n }\n}", "function realRoom(room){\r\n return roomChecksum(room.name) == room.checksum;\r\n}", "function τSST_detect_buff_skills() {\n buffs_table.skills_summary = localStorage[storage_key_prefix + 'buffs_table_skills'];\n\n var skills_node = $(\"#character_skills\");\n if (skills_node.length) {\n var player_skills = {};\n skills_node.find(\"tbody\").find(\"tr\")\n .map(function() {\n player_skills[$(this).find(\"td:first\").text()] =\n $(this).find(\"td:nth-of-type(2)\").text();\n return this;\n });\n\n for (var skill in skills_granting_regen_buffs) {\n if (player_skills.hasOwnProperty(skill)) {\n buffs_table.skills.push(skill + \" \" + player_skills[skill]);\n }\n }\n\n buffs_table.skills_summary = '';\n if (buffs_table.skills.length > 0) {\n buffs_table.skills_summary = buffs_table.skills.join(' + ');\n }\n }\n\n // If the Skills were just discovered for the first time, update our logs accordingly.\n // If they has actually changed, note the fact for our callers.\n if (buffs_table.skills_summary != localStorage[storage_key_prefix + 'buffs_table_skills']) {\n var first_discovery = false;\n for (var stat in all_stats) {\n\n var this_log = localStorage[storage_key_prefix + 'stat_logs_' + stat];\n if (! this_log) {\n first_discovery = true;\n } else if (this_log.includes(skills_placeholder) ||\n ! localStorage.hasOwnProperty(storage_key_prefix + 'buffs_table_skills')) {\n if (! buffs_table.skills_summary || ! buffs_table.skills_summary.length) {\n this_log = this_log.replace(' + ' + skills_placeholder, '');\n } else if (! this_log.includes(skills_placeholder)) {\n this_log = this_log.replace(/(vip\\?\\]|VIP)/, '$1 + ' + buffs_table.skills_summary);\n } else {\n this_log = this_log.replace(skills_placeholder, buffs_table.skills_summary);\n }\n first_discovery = true;\n }\n localStorage.setItem(storage_key_prefix + 'stat_logs_' + stat, this_log);\n }\n\n if (first_discovery) {\n // Technically, this didn't change; this is just the first time we could detect it.\n localStorage.setItem(storage_key_prefix + 'buffs_table_skills', buffs_table.skills_summary);\n } else {\n // We already had a real value, so this has actually changed.\n buffs_changed = true;\n }\n }\n\n // Buff updates are stored only when actually updating a stat log.\n }", "checkWin() {\nif all bgWLand|| or wgBLand\n}", "verifyContents(blindHash, blindingFactor, originalDoc) {\n if (!originalDoc.match(/^The bearer of this signed document, .*, has full diplomatic immunity.$/)) {\n return false;\n }\n let h = blindSignatures.messageToHash(originalDoc);\n if (!this.consistent(blindHash, blindingFactor, h)) {\n return false;\n }\n return true;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
MD5 OOP implementation. Use this class to perform an incremental md5, otherwise use the static methods instead.
function MD5() { // call reset to init the instance this.reset(); }
[ "digesting() {}", "function binl_md5(x, len) {/* append padding */x[len >> 5] |= 0x80 << ((len) % 32);x[(((len + 64) >>> 9) << 4) + 14] = len;var i, olda, oldb, oldc, oldd,a = 1732584193,b = -271733879,c = -1732584194,d = 271733878;for (i = 0; i < x.length; i += 16) {olda = a;oldb = b;oldc = c;oldd = d;a = md5_ff(a, b, c, d, x[i], 7, -680876936);d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);b = md5_gg(b, c, d, a, x[i], 20, -373897302);a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);d = md5_hh(d, a, b, c, x[i], 11, -358537222);c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);a = md5_ii(a, b, c, d, x[i], 6, -198630844);d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);a = safe_add(a, olda);b = safe_add(b, oldb);c = safe_add(c, oldc);d = safe_add(d, oldd);}return [a, b, c, d];}", "function isMD5Encrypted(inputString) {\r\n return /[a-fA-F0-9]{32}/.test(inputString);\r\n }", "function hash(text) {\n return crypto.createHash('md5').update(text).digest('hex')\n}", "function md5uri64(strings) {\n\tvar sum = crypto.createHash('md5');\n\tstrings.forEach(function(str) {\n\t\tsum.update(str, 'utf8');\n\t});\n\treturn sum.digest('base64').replace(/[\\+\\/=]/g, function(ch) {\n\t\treturn { '+': 'a', '/': 'b', '=': '' }[ch];\n\t});\n}", "function generateTrip(str)\n{\n var MD5 = crypto.createHash(\"MD5\");\n MD5.update(str);\n var trip = MD5.digest(\"base64\").slice(0, 6);\n console.log(\"Generated trip \" + trip);\n return trip;\n}", "function digestFiles(files) {\n\treturn Promise.all(files.map(function(file) {\n\t\treturn file.getMD5().then(function(md5) {\n\t\t\treturn { path: file.path, md5: md5 };\n\t\t});\n\t})).then(function(inputs) {\n\t\treturn md5uri64(inputs.map(function(input) {\n\t\t\treturn input.path + input.md5;\n\t\t}));\n\t});\n}", "function validateGatewayMD5(data) {\n if (!data || !data.x_MD5_Hash) return false;\n var s = MD5HASH + LOGINID + data.x_trans_id + data.x_amount;\n return (data.x_MD5_Hash === crypto.createHash('md5').update(s).digest('hex').toUpperCase());\n }", "function calcDigest() {\n\n\t\tvar digestM = hex_sha1(document.SHAForm.SourceMessage.value);\n\n\t\tdocument.SHAForm.MessageDigest.value = digestM;\n\n\t}", "static bytes5(v) { return b(v, 5); }", "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}", "static addChecksum(data) {\n let checksum = (data[0] + data[1] + data[2] + data[3] + data[4]) & 0xFF;\n data[5] = checksum;\n return checksum;\n }", "function decorateVanillaSparkMD5_md51_array(md51_array) {\n\treturn a => new Uint8Array((new Uint32Array(md51_array(a))).buffer)\n}", "_digest () {\n if (this.running) {\n this.emit('startDigest');\n\n Promise.all([this._processSessions(), this._processSections()])\n .then(() => {\n // this._init is used to tell if this is the first time running the digest function. On the first time, event listeners are not called as the bot is gathering the initial data\n this._init = false;\n\n // Write all the data to cache\n this._writeCache()\n .then(() => logger.info('Cache written to file.'))\n .catch(err => logger.error(err));\n\n // Emit the final event\n this.emit('endDigest');\n\n // Schedule the next digest\n if (this.running) {\n this._intervalObj = setTimeout(this._digest.bind(this), this.config.refreshDuration * 60000);\n }\n })\n .catch(err => logger.error(err));\n }\n }", "function calcFileSha1(file) {\n // New checksum calculator instance\n rusha = new Rusha();\n // File reader to get data\n reader = new FileReader();\n // Register reader onload event\n reader.onload = function(e) {\n // Calculate the checksum from the reader result\n var digest = rusha.digest(reader.result);\n // Set the label when finished\n $(\"#digest\").val(digest);\n // Enable the submit button\n $('button').prop('disabled', false);\n }\n // Signal checkcum calculation and load reader\n $(\"#digest\").val(\"Calcluating package checksum...\");\n reader.readAsBinaryString(file);\n}", "function cacheFileChecksum(p, checksum) {\n return tslib_1.__awaiter(this, void 0, void 0, function* () {\n const md5 = yield getFileChecksum(p);\n yield exports.writeFile(`${p}.md5`, md5, { encoding: 'utf8' });\n });\n}", "function core_sha1(x, len) {\n /* append padding */\n x[len >> 5] |= 0x80 << (24 - len % 32);\n x[((len + 64 >> 9) << 4) + 15] = len;\n\n var w = Array(80);\n var a = 1732584193;\n var b = -271733879;\n var c = -1732584194;\n var d = 271733878;\n var e = -1009589776;\n\n for (var i = 0; i < x.length; i += 16) {\n var olda = a;\n var oldb = b;\n var oldc = c;\n var oldd = d;\n var olde = e;\n\n for (var j = 0; j < 80; j++) {\n if (j < 16) w[j] = x[i + j];\n else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);\n var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));\n e = d;\n d = c;\n c = rol(b, 30);\n b = a;\n a = t;\n }\n\n a = safe_add(a, olda);\n b = safe_add(b, oldb);\n c = safe_add(c, oldc);\n d = safe_add(d, oldd);\n e = safe_add(e, olde);\n }\n return Array(a, b, c, d, e);\n\n }", "function hashName(mediaFile) {\n return mediaFile.md5 + path.extname(mediaFile.name);\n}", "function core_sha1(x, len) {\n\t/* append padding */\n\tx[len >> 5] |= 0x80 << (24 - len % 32);\n\tx[((len + 64 >> 9) << 4) + 15] = len;\n\n\tvar w = Array(80);\n\tvar a =\t1732584193;\n\tvar b = -271733879;\n\tvar c = -1732584194;\n\tvar d =\t271733878;\n\tvar e = -1009589776;\n\n\tfor(var i = 0; i < x.length; i += 16) {\n\t\tvar olda = a;\n\t\tvar oldb = b;\n\t\tvar oldc = c;\n\t\tvar oldd = d;\n\t\tvar olde = e;\n\n\t\tfor(var j = 0; j < 80; j++) {\n\t\t\tif(j < 16) w[j] = x[i + j];\n\t\t\telse w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);\n\t\t\tvar t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),\n\t\t\t\t\t\t\t\t\t\t\t safe_add(safe_add(e, w[j]), sha1_kt(j)));\n\t\t\te = d;\n\t\t\td = c;\n\t\t\tc = rol(b, 30);\n\t\t\tb = a;\n\t\t\ta = t;\n\t\t}\n\n\t\ta = safe_add(a, olda);\n\t\tb = safe_add(b, oldb);\n\t\tc = safe_add(c, oldc);\n\t\td = safe_add(d, oldd);\n\t\te = safe_add(e, olde);\n\t}\n\treturn Array(a, b, c, d, e);\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process up to one thing. Generally: If we are processing a literal, we make sure we have the data for the whole literal, then we process it. If we are not in a literal, we buffer until we have one newline.
function processData(data) { if (data.length === 0) return; var idxCRLF = null, literalInfo, curReq; // - Accumulate data until newlines when not in a literal if (self._state.curExpected === null) { // no newline, append and bail if ((idxCRLF = bufferIndexOfCRLF(data, 0)) === -1) { if (self._state.curData) self._state.curData = bufferAppend(self._state.curData, data); else self._state.curData = data; return; } // yes newline, use the buffered up data and new data // (note: data may now contain more than one line's worth of data!) if (self._state.curData && self._state.curData.length) { data = bufferAppend(self._state.curData, data); self._state.curData = null; } } // -- Literal // Don't mess with incoming data if it's part of a literal if (self._state.curExpected !== null) { curReq = curReq || self._state.requests[0]; if (!curReq._done) { var chunk = data; self._state.curXferred += data.length; if (self._state.curXferred > self._state.curExpected) { var pos = data.length - (self._state.curXferred - self._state.curExpected), extra = data.slice(pos); if (pos > 0) chunk = data.slice(0, pos); else chunk = undefined; data = extra; curReq._done = 1; } if (chunk && chunk.length) { if (self._LOG) self._LOG.data(chunk.length, chunk); if (curReq._msgtype === 'headers') { chunk.copy(self._state.curData, curReq.curPos, 0); curReq.curPos += chunk.length; } else curReq._msg.emit('data', chunk); } } if (curReq._done) { var restDesc; if (curReq._done === 1) { if (curReq._msgtype === 'headers') curReq._headers = self._state.curData.toString('ascii'); self._state.curData = null; curReq._done = true; } if (self._state.curData) self._state.curData = bufferAppend(self._state.curData, data); else self._state.curData = data; idxCRLF = bufferIndexOfCRLF(self._state.curData); if (idxCRLF && self._state.curData[idxCRLF - 1] === CHARCODE_RPAREN) { if (idxCRLF > 1) { // eat up to, but not including, the right paren restDesc = self._state.curData.toString('ascii', 0, idxCRLF - 1) .trim(); if (restDesc.length) curReq._desc += ' ' + restDesc; } parseFetch(curReq._desc, curReq._headers, curReq._msg); data = self._state.curData.slice(idxCRLF + 2); curReq._done = false; self._state.curXferred = 0; self._state.curExpected = null; self._state.curData = null; curReq._msg.emit('end', curReq._msg); // XXX we could just change the next else to not be an else, and then // this conditional is not required and we can just fall out. (The // expected check === 0 may need to be reinstated, however.) if (data.length && data[0] === CHARCODE_ASTERISK) { self._unprocessed.unshift(data); return; } } else // ??? no right-paren, keep accumulating data? this seems wrong. return; } else // not done, keep accumulating data return; } // -- Fetch w/literal // (More specifically, we were not in a literal, let's see if this line is // a fetch result line that starts a literal. We want to minimize // conversion to a string, as there used to be a naive conversion here that // chewed up a lot of processor by converting all of data rather than // just the current line.) else if (data[0] === CHARCODE_ASTERISK) { var strdata; idxCRLF = bufferIndexOfCRLF(data, 0); if (data[idxCRLF - 1] === CHARCODE_RBRACE && (literalInfo = (strdata = data.toString('ascii', 0, idxCRLF)).match(reFetch))) { self._state.curExpected = parseInt(literalInfo[2], 10); var desc = strdata.substring(strdata.indexOf('(')+1).trim(); var type = /BODY\[(.*)\](?:\<\d+\>)?/.exec(strdata)[1]; var uid = reUid.exec(desc)[1]; // figure out which request this belongs to. If its not assigned to a // specific uid then send it to the first pending request... curReq = self._findFetchRequest(uid, type) || self._state.requests[0]; var msg = new ImapMessage(); // because we push data onto the unprocessed queue for any literals and // processData lacks any context, we need to reorder the request to be // first if it is not already first. (Storing the request along-side // the data in insufficient because if the literal data is fragmented // at all, the context will be lost.) if (self._state.requests[0] !== curReq) { self._state.requests.splice(self._state.requests.indexOf(curReq), 1); self._state.requests.unshift(curReq); } msg.seqno = parseInt(literalInfo[1], 10); curReq._desc = desc; curReq._msg = msg; msg.size = self._state.curExpected; curReq._fetcher.emit('message', msg); curReq._msgtype = (type.indexOf('HEADER') === 0 ? 'headers' : 'body'); // This library buffers headers, so allocate a buffer to hold the literal. if (curReq._msgtype === 'headers') { self._state.curData = new Buffer(self._state.curExpected); curReq.curPos = 0; } if (self._LOG) self._LOG.data(strdata.length, strdata); // (If it's not headers, then it's body, and we generate 'data' events.) self._unprocessed.unshift(data.slice(idxCRLF + 2)); return; } } if (data.length === 0) return; data = customBufferSplitCRLF(data); var response = data.shift().toString('ascii'); // queue the remaining buffer chunks up for processing at the head of the queue self._unprocessed = data.concat(self._unprocessed); if (self._LOG) self._LOG.data(response.length, response); processResponse(stringExplode(response, ' ', 3)); }
[ "_completeLiteral(token) {\n // Create a simple string literal by default\n let literal = this._literal(this._literalValue);\n\n switch (token.type) {\n // Create a datatyped literal\n case 'type':\n case 'typeIRI':\n const datatype = this._readEntity(token);\n\n if (datatype === undefined) return; // No datatype means an error occurred\n\n literal = this._literal(this._literalValue, datatype);\n token = null;\n break;\n // Create a language-tagged string\n\n case 'langcode':\n literal = this._literal(this._literalValue, token.value);\n token = null;\n break;\n }\n\n return {\n token,\n literal\n };\n }", "exitMultiLineStringLiteral(ctx) {\n\t}", "_feed(chars) {\n\n var delimiter_pos;\n this._buffer = Buffer.concat([this._buffer, chars]);\n\n while((delimiter_pos = this._buffer.indexOf(DELIMITER)) != -1) {\n // Read until delimiter\n var buff = this._buffer.slice(0, delimiter_pos);\n this._buffer = this._buffer.slice(delimiter_pos + 1);\n\n // Check data are json\n var data = null;\n try {\n data = JSON.parse(buff.toString());\n } catch(e) {\n log.info(\"Bad data, not json\", buff, \"<raw>\", buff.toString(), \"</raw>\");\n continue;\n }\n\n // Send to client\n if(data)\n this.emit(\"transport_message\", data).catch(log.error);\n }\n }", "enterMultiLineStringLiteral(ctx) {\n\t}", "_isLiteral(tokenType) {\n return (\n tokenType === \"NUMBER\" ||\n tokenType === \"STRING\" ||\n tokenType === \"true\" ||\n tokenType === \"false\" ||\n tokenType === \"null\"\n );\n }", "_encodeLiteral(literal) {\n // Escape special characters\n let value = literal.value;\n if (escape.test(value)) value = value.replace(escapeAll, characterReplacer); // Write a language-tagged literal\n\n if (literal.language) return `\"${value}\"@${literal.language}`; // Write dedicated literals per data type\n\n if (this._lineMode) {\n // Only abbreviate strings in N-Triples or N-Quads\n if (literal.datatype.value === xsd.string) return `\"${value}\"`;\n } else {\n // Use common datatype abbreviations in Turtle or TriG\n switch (literal.datatype.value) {\n case xsd.string:\n return `\"${value}\"`;\n\n case xsd.boolean:\n if (value === 'true' || value === 'false') return value;\n break;\n\n case xsd.integer:\n if (/^[+-]?\\d+$/.test(value)) return value;\n break;\n\n case xsd.decimal:\n if (/^[+-]?\\d*\\.\\d+$/.test(value)) return value;\n break;\n\n case xsd.double:\n if (/^[+-]?(?:\\d+\\.\\d*|\\.?\\d+)[eE][+-]?\\d+$/.test(value)) return value;\n break;\n }\n } // Write a regular datatyped literal\n\n\n return `\"${value}\"^^${this._encodeIriOrBlank(literal.datatype)}`;\n }", "function mapLines(input, processLine, noProblem) {\r\n var remaining = '';\r\n var problem = false;\r\n\r\n input.on('data', function(data) {\r\n remaining += data;\r\n var index = remaining.indexOf('\\n');\r\n while (index > -1) {\r\n var line = remaining.substring(0, index);\r\n remaining = remaining.substring(index + 1);\r\n problem = problem || processLine(line);\r\n index = remaining.indexOf('\\n');\r\n }\r\n });\r\n\r\n input.on('end', function() {\r\n if (remaining.length > 0) {\r\n console.log(\"remaining...\");\r\n problem = problem || processLine(remaining);\r\n }\r\n if(!problem)\r\n noProblem();\r\n });\r\n \r\n input.on('error', function() {\r\n console.log(\"An error occured with the DB\");\r\n });\r\n}", "function searchLiterals(literalInputPipes, text, sep) {\n const literalMap = buildLiteralMap(text, sep)\n const literalInputArray = literalInputPipes.split('|')\n\n let outputTotal = {\n \"total\": literalInputArray.length,\n \"result\": []\n }\n Object.freeze(outputTotal)\n\n for (const literal of literalInputArray) {\n if (literalMap.has(literal)) {\n const output = {\n \"literal\": literal,\n \"count\" : literalMap.get(literal)\n }\n Object.freeze(output)\n\n outputTotal[\"result\"].push(output)\n }\n }\n console.log(outputTotal)\n}", "_encodeLiteral(literal) {\n // Escape special characters\n let value = literal.value;\n if (escape.test(value))\n value = value.replace(escapeAll, characterReplacer);\n\n // Write a language-tagged literal\n if (literal.language)\n return `\"${value}\"@${literal.language}`;\n\n // Write dedicated literals per data type\n if (this._lineMode) {\n // Only abbreviate strings in N-Triples or N-Quads\n if (literal.datatype.value === xsd.string)\n return `\"${value}\"`;\n }\n else {\n // Use common datatype abbreviations in Turtle or TriG\n switch (literal.datatype.value) {\n case xsd.string:\n return `\"${value}\"`;\n case xsd.boolean:\n if (value === 'true' || value === 'false')\n return value;\n break;\n case xsd.integer:\n if (/^[+-]?\\d+$/.test(value))\n return value;\n break;\n case xsd.decimal:\n if (/^[+-]?\\d*\\.\\d+$/.test(value))\n return value;\n break;\n case xsd.double:\n if (/^[+-]?(?:\\d+\\.\\d*|\\.?\\d+)[eE][+-]?\\d+$/.test(value))\n return value;\n break;\n }\n }\n\n // Write a regular datatyped literal\n return `\"${value}\"^^${this._encodeIriOrBlank(literal.datatype)}`;\n }", "_readObject(token) {\n switch (token.type) {\n case 'literal':\n // Regular literal, can still get a datatype or language\n if (token.prefix.length === 0) {\n this._literalValue = token.value;\n return this._readDataTypeOrLang;\n } // Pre-datatyped string literal (prefix stores the datatype)\n else this._object = this._literal(token.value, this._namedNode(token.prefix));\n\n break;\n\n case '[':\n // Start a new quad with a new blank node as subject\n this._saveContext('blank', this._graph, this._subject, this._predicate, this._subject = this._blankNode());\n\n return this._readBlankNodeHead;\n\n case '(':\n // Start a new list\n this._saveContext('list', this._graph, this._subject, this._predicate, this.RDF_NIL);\n\n this._subject = null;\n return this._readListItem;\n\n case '{':\n // Start a new formula\n if (!this._n3Mode) return this._error('Unexpected graph', token);\n\n this._saveContext('formula', this._graph, this._subject, this._predicate, this._graph = this._blankNode());\n\n return this._readSubject;\n\n case '<<':\n if (!this._supportsRDFStar) return this._error('Unexpected RDF* syntax', token);\n\n this._saveContext('<<', this._graph, this._subject, this._predicate, null);\n\n this._graph = null;\n return this._readSubject;\n\n default:\n // Read the object entity\n if ((this._object = this._readEntity(token)) === undefined) return; // In N3 mode, the object might be a path\n\n if (this._n3Mode) return this._getPathReader(this._getContextEndReader());\n }\n\n return this._getContextEndReader();\n }", "function processAndHighlightText( sValue, sOT, sTag, sCT, bInBox )\n{\n\tvar sRegExp, regExp;\n\t// <pre lang=\"cpp\">using</pre>\n\t\n\t// setting global variables\n\tsGlobOT = sOT;\n\tsGlobCT = sCT;\n\tsGlobTag = sTag;\n\tbGlobCodeInBox=bInBox;\n\t\t\n\t// building regular expression\n\tsRegExp = sGlobOT \n\t\t+\"\\\\s*\"\n\t\t+ sGlobTag\n\t\t+\".*?\"\n\t\t+sGlobCT\n\t\t+\"((.|\\\\n)*?)\"\n\t\t+sGlobOT\n\t\t+\"\\\\s*/\\\\s*\"\n\t\t+sGlobTag\n\t\t+\"\\\\s*\"\n\t\t+sGlobCT;\n\n\tregExp=new RegExp(sRegExp, \"gim\");\n\n\t// render pre\n\treturn sValue.replace( regExp, function( $0, $1 ){ return replaceByCode( $0, $1 );} );\n}", "function validLiteral(node) {\n if (node && node.type === 'Literal' && typeof node.value === 'string') {\n return true;\n }\n return false;\n}", "function isLiteral(node) {\n return node && node.type === typescript_estree_1.AST_NODE_TYPES.TSTypeLiteral;\n }", "function processText(tmp){\n line = line + (tmp.length)/tailleMax\n if (line >= nbLineMax){\n erase_text()\n line = 0;\n }\n}", "_readRDFStarTail(token) {\n if (token.type !== '>>') return this._error(`Expected >> but got ${token.type}`, token); // Read the quad and restore the previous context\n\n const quad = this._quad(this._subject, this._predicate, this._object, this._graph || this.DEFAULTGRAPH);\n\n this._restoreContext(); // If the triple was the subject, continue by reading the predicate.\n\n\n if (this._subject === null) {\n this._subject = quad;\n return this._readPredicate;\n } // If the triple was the object, read context end.\n else {\n this._object = quad;\n return this._getContextEndReader();\n }\n }", "function handleLine (line_) {\n\tconsole.assert (typeof (line_) === 'string');\n\n\tif (line_.length === 0)\n\t\treturn;\n\n\tif (! startsWith ('$', line_))\n\t\tugly.queuedCommands.push (line_);\n\telse if (startsWith ('$END_', line_)) {\n\t\trequestAnimationFrame (processQueuedCommands);\n\t}\n}", "handleNewLine(editorState, event) {\n // https://github.com/jpuri/draftjs-utils/blob/e81c0ae19c3b0fdef7e0c1b70d924398956be126/js/keyPress.js#L64\n if (isSoftNewlineEvent(event)) {\n return this.addLineBreak(editorState);\n }\n\n const content = editorState.getCurrentContent();\n const selection = editorState.getSelection();\n const key = selection.getStartKey();\n const offset = selection.getStartOffset();\n const block = content.getBlockForKey(key);\n\n const isDeferredBreakoutBlock = [BLOCK_TYPE.CODE].includes(\n block.getType(),\n );\n\n if (isDeferredBreakoutBlock) {\n const isEmpty =\n selection.isCollapsed() &&\n offset === 0 &&\n block.getLength() === 0;\n\n if (isEmpty) {\n return EditorState.push(\n editorState,\n Modifier.setBlockType(\n content,\n selection,\n BLOCK_TYPE.UNSTYLED,\n ),\n 'change-block-type',\n );\n }\n\n return false;\n }\n\n return this.handleHardNewline(editorState);\n }", "exitMultiLineStringExpression(ctx) {\n\t}", "function InputTextMultiline(label, buf, buf_size = buf instanceof ImStringBuffer ? buf.size : ImGuiInputTextDefaultSize, size = ImVec2.ZERO, flags = 0, callback = null, user_data = null) {\r\n const _callback = callback && ((data) => callback(new ImGuiInputTextCallbackData(data, user_data))) || null;\r\n if (Array.isArray(buf)) {\r\n return bind.InputTextMultiline(label, buf, buf_size, size, flags, _callback, null);\r\n }\r\n else if (buf instanceof ImStringBuffer) {\r\n const ref_buf = [buf.buffer];\r\n const _buf_size = Math.min(buf_size, buf.size);\r\n const ret = bind.InputTextMultiline(label, ref_buf, _buf_size, size, flags, _callback, null);\r\n buf.buffer = ref_buf[0];\r\n return ret;\r\n }\r\n else {\r\n const ref_buf = [buf()];\r\n const ret = bind.InputTextMultiline(label, ref_buf, buf_size, size, flags, _callback, null);\r\n buf(ref_buf[0]);\r\n return ret;\r\n }\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getValuesForFieldInPolicyAllTypes gets all values for a field for all rules in a policy of all ptypes, duplicated values are removed.
getValuesForFieldInPolicyAllTypes(sec, fieldIndex) { const values = []; const ast = this.model.get(sec); if (!ast) { return values; } for (const ptype of ast.keys()) { values.push(...this.getValuesForFieldInPolicy(sec, ptype, fieldIndex)); } return util.arrayRemoveDuplicates(values); }
[ "getValues() {\n return this.getValuesFromElement(this.element);\n }", "resolveValues(item, field, index_as, cf) {\n if( index_as !== field ) {\n this.logger.debug(`resolveValues for ${item[\"@id\"]} ${field} ${index_as}`);\n }\n const resolved = this.resolveAndFlatten(item, field, index_as, cf);\n\n if( cf['multi'] ) {\n return resolved;\n } else {\n if( Array.isArray(resolved) ) {\n if( resolved.length > 1 ) {\n this.logger.warn(`${field} resolves to multiple values, but isn't configured as multi`);\n this.logger.warn(`config = ${JSON.stringify(cf)}`);\n }\n return resolved[0];\n }\n }\n }", "pluginField(field) {\n // FIXME make this error when called during plugin updating\n let result = [];\n for (let plugin of this.plugins)\n plugin.takeField(field, result);\n return result;\n }", "get fieldValuesAsText() {\n return SPInstance(this, \"FieldValuesAsText\");\n }", "values (obj) {\n\t\tlet values = [];\n\t\tfor (let key in obj) {\n\t\t\tvalues.push(obj[key]);\n\t\t}\n\t\treturn values;\n\t}", "function fields_to_array(events,field){\n legend =[];\n i=events.length;\n\n while (i--) {\n if (events[i].fields[field]){\n legend.push(events[i].fields[field]);\n }\n }\n unique_fields = legend.filter( onlyUnique );\n}", "function getValues()\n{\n X = parseFloat($(\"#XValor\").val());\n fieldData.splice(0);\n let tempArray = [];\n $(body_wrapper).find(\"input\").each( function(a,b,c) {\n tempArray.push($(this).val());\n });\n\n for(let i=0; i < tempArray.length; i++)\n {\n if(tempArray[i].startsWith(\"[log10]\"))\n {\n let valor = Math.log10(parseFloat(tempArray[i].split(\" \").join(\"\").substr(tempArray[i].indexOf(\"]\")+1)));\n fieldData.push( [parseFloat(valor), parseFloat(tempArray[++i])] );\n }else\n {\n fieldData.push( [parseFloat(tempArray[i]), parseFloat(tempArray[++i])] );\n }\n\n } \n}", "function getInputEleVals(eles) {\n var valArr = [];\n for(var i = 0; i< eles.length; i++) {\n valArr.push(eles[i].value);\n }\n return valArr;\n}", "function mergedTypeValuesOf(entities) {\n const { typeName } = entities[entities.length - 1]\n\n const mergedAttributes = []\n for (const { attributes } of entities) {\n for (const attribute of attributes) {\n if (\n !mergedAttributes.some((a) =>\n a.equalsTo(attribute.pred, attribute.obj)\n )\n ) {\n mergedAttributes.push(attribute)\n }\n }\n }\n\n return new TypeValues(typeName, mergedAttributes)\n } // CONCATENATED MODULE: ./src/lib/component/EditPropertiesDialog/index.js", "get fieldValuesForEdit() {\n return SPInstance(this, \"FieldValuesForEdit\");\n }", "static findByValues(fieldName, values) {\n\t\t\tconst self = this;\n\t\t\treturn this._db(self.tableName).select('*').whereIn(fieldName, values)\n\t\t\t\t.map((row) => new self(row))\n\t\t\t\t.then((instances) => instances);\n\t\t}", "function formToFieldList(formID) {\n let form = document.getElementById(formID).elements;\n let formValues = [];\n\n for (let i = 0; i < form.length; i++) {\n if (form[i].type === 'text') {\n formValues.push(form[i].value)\n }\n if (form[i].type === 'checkbox') {\n formValues.push(form[i].checked)\n }\n }\n return formValues;\n}", "visitList_values_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "getTableauData () {\n if (!Array.isArray(this.data) || this.data.length === 0) {\n throw new Error('Data is not an array or is an empty!!')\n }\n\n return this.data.map((row) => {\n return {\n 'values': row.insights.data.map((value) => {\n return {\n 'post_id': parseInt(row.id.split('_')[1]),\n 'page_id': parseInt(row.id.split('_')[0]),\n 'page_post_id': row.id,\n [value.name]: value.values[0].value\n }\n })\n }\n }).reduce((a, b) => {\n let values = b.values.reduce((aF, bF) => {\n let keys = Object.keys(bF)\n\n keys.map((key) => {\n aF[key] = bF[key]\n })\n return aF\n }, {})\n\n return a.concat(values)\n }, [])\n }", "function getFilterValues (filter) {\n let filterValues = '';\n filterValues += filter.\n filterValues += filter.worksheetName + ' - ';\n filterValues += filter.fieldName + ' - ';\n switch (filter.filterType) {\n case 'categorical':\n filter.appliedValues.forEach(function (value) {\n filterValues += value.formattedValue + ', ';\n });\n break;\n case 'range':\n // A range filter can have a min and/or a max.\n if (filter.minValue) {\n filterValues += 'min: ' + filter.minValue.formattedValue + ', ';\n }\n\n if (filter.maxValue) {\n filterValues += 'min: ' + filter.maxValue.formattedValue + ', ';\n }\n break;\n case 'relative-date':\n filterValues += 'Period: ' + filter.periodType + ', ';\n filterValues += 'RangeN: ' + filter.rangeN + ', ';\n filterValues += 'Range Type: ' + filter.rangeType + ', ';\n break;\n default:\n }\n\n // Cut off the trailing \", \"\n return filterValues.slice(0, -2);\n }", "toArray() {\n const keys = this[ _schema ].keys,\n data = this[ _data ],\n changes = this[ _changeset ],\n arr = []\n\n for (let i = keys.length; i--;) {\n const key = keys[ i ],\n val = changes[ key ] || data[ key ]\n\n if (val != null)\n arr.push(key, val)\n }\n\n return arr\n }", "persistentValues() {\n var self = this._self || this;\n var names = self.persistentProperties();\n var values = [];\n names.forEach(function(name) { \n values.push(self[name]);\n });\n return (values);\n }", "function getValues(hm){\n\t//initialize resulting array\n\tvar res = [];\n\t//loop thru keys of associative array\n\tfor( var tmpKey in hm ){\n\t\t//get value\n\t\tvar tmpVal = hm[tmpKey];\n\t\t//make sure that acquired value is not a function\n\t\tif( typeof tmpVal != \"function\" ){\n\t\t\t//add value to resulting array of hashmap values\n\t\t\tres.push(tmpVal);\n\t\t}\t//end if value is not a function\n\t}\t//end loop thru keys of associative array\n\treturn res;\n}", "function mockTypeFields(type) {\n const fieldsData = {};\n\n return type.fieldsArray.reduce((data, field) => {\n field.resolve();\n\n if (field.parent !== field.resolvedType) {\n if (field.repeated) {\n data[field.name] = [mockField(field)];\n } else {\n data[field.name] = mockField(field);\n }\n }\n\n return data;\n }, fieldsData);\n}", "function loopEls(elements){\n //An empty array to push the values into\n var valuesNew = [];\n // loops through the form elements and gets their values\n for (var i = 0; i < elements.length; i++) {\n valuesNew.push(elements[i].value);\n };\n \n values = valuesNew;\n return valuesNew; \n \n \t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test Nominal attribute similarity function
function test_nominal_attribute(){ console.log("test_nominal_attribute....") var myMap = new Map(); myMap.set("Nominal", new Nominal(["0","1","2", "3", "4"])); //initialize var similarityDist = new SimilarityDistanceClass(myMap); var data = [ {"Nominal": "1"}, {"Nominal": "0"}, {"Nominal": "1"}, {"Nominal": "2"}, {"Nominal": "3"}, {"Nominal": "4"}, {"Nominal": -1} ]; var similarity_0_1 = similarityDist.compute(data[0], data[1]); var similarity_0_2 = similarityDist.compute(data[0], data[2]); var similarity_0_3 = similarityDist.compute(data[0], data[3]); var similarity_0_4 = similarityDist.compute(data[0], data[4]); var similarity_0_5 = similarityDist.compute(data[0], data[5]); var similarity_0_6 = similarityDist.compute(data[0], data[6]); //with missing value var similarity_6_0 = similarityDist.compute(data[6], data[0]); //with missing value var similarity_6_6 = similarityDist.compute(data[6], data[6]); //with missing value //check that 1 is identical to 1 assert(similarity_0_2 == 1.0); //check that 0 is same similar to 1 with 2 assert(similarity_0_1 == similarity_0_3); //check that 0 is more similar to 1 than 3 assert(similarity_0_1 == similarity_0_4); //check that 3 is more similar to 1 than 4 assert(similarity_0_4 == similarity_0_5); //two missing values are identical assert(similarity_6_6 == 1.0); //distance with missing value is symmetric assert(similarity_0_6 == similarity_6_0); //check that 2 is more similar than missing value assert(similarity_0_1 == similarity_0_6); console.log("PASS") }
[ "function test_mixed_attributes(){\r\n\t\r\n\tconsole.log(\"test_mixed_attributes....\")\r\n\r\n\tvar myMap = new Map();\r\n\tmyMap.set(\"Nominal\", new Nominal([\"0\",\"1\",\"2\", \"3\", \"4\"]));\r\n\tmyMap.set(\"Ordinal\", new Ordinal([\"0\",\"1\",\"2\",\"3\",\"4\"], 4, 0));\r\n\tmyMap.set(\"Numeric\", new Numeric(20.0, 0.0));\r\n\r\n\t//initialize\r\n\tvar similarityDist = new SimilarityDistanceClass(myMap);\r\n\r\n\tvar data = [ {\"Nominal\": \"1\", \"Ordinal\": \"1\", \"Numeric\": 5},\r\n\t\t\t\t {\"Nominal\": \"0\", \"Ordinal\": \"0\", \"Numeric\": 2},\r\n\t\t\t\t {\"Nominal\": \"1\", \"Ordinal\": \"1\", \"Numeric\": 5},\r\n\t\t\t\t {\"Nominal\": \"2\", \"Ordinal\": \"2\", \"Numeric\": 8},\r\n\t\t\t\t {\"Nominal\": \"3\", \"Ordinal\": \"3\", \"Numeric\": 9},\r\n\t\t\t\t {\"Nominal\": \"4\", \"Ordinal\": \"4\", \"Numeric\": 20}\r\n\t\t\t\t ];\r\n\t\r\n\tvar similarity_0_1 = similarityDist.compute(data[0], data[1]);\r\n\tvar similarity_0_2 = similarityDist.compute(data[0], data[2]);\r\n\tvar similarity_0_3 = similarityDist.compute(data[0], data[3]);\r\n\tvar similarity_0_4 = similarityDist.compute(data[0], data[4]);\r\n\tvar similarity_0_5 = similarityDist.compute(data[0], data[5]);\r\n\r\n\t//check that the first element is identical to second\r\n\tassert(similarity_0_2 == 1.0);\r\n\t\r\n\t//check that the first element and third one have the same similarity distance\r\n\tassert(similarity_0_1 == similarity_0_3);\r\n\t\r\n\t//check that the first element is more similar than the fourth one\r\n\tassert(similarity_0_1 > similarity_0_4);\r\n\r\n\t//check that the fourth element is more similar than the fifth\r\n\tassert(similarity_0_4 > similarity_0_5);\r\n\t\r\n\tconsole.log(\"PASS\")\r\n}", "function test_numeric_attribute(){\r\n\t\r\n\tconsole.log(\"test_numeric_attribute....\")\r\n\t\t\r\n\tvar myMap = new Map();\r\n\tmyMap.set(\"Numeric\", new Numeric(20.0, 0.0));\r\n\r\n\t//initialize\r\n\tvar numericSimilarityDistance = new SimilarityDistanceClass(myMap);\r\n\r\n\tvar data = [ {\"Numeric\": 5},\r\n\t\t\t\t {\"Numeric\": 2},\r\n\t\t\t\t {\"Numeric\": 5},\r\n\t\t\t\t {\"Numeric\": 8},\r\n\t\t\t\t {\"Numeric\": 9},\r\n\t\t\t\t {\"Numeric\": 20},\r\n\t\t\t\t {\"Numeric\": -1}\r\n\t\t\t\t ];\r\n\t\r\n\tvar similarity_0_1 = numericSimilarityDistance.compute(data[0], data[1]);\r\n\tvar similarity_0_2 = numericSimilarityDistance.compute(data[0], data[2]);\r\n\tvar similarity_0_3 = numericSimilarityDistance.compute(data[0], data[3]);\r\n\tvar similarity_0_4 = numericSimilarityDistance.compute(data[0], data[4]);\r\n\tvar similarity_0_5 = numericSimilarityDistance.compute(data[0], data[5]);\r\n\tvar similarity_0_6 = numericSimilarityDistance.compute(data[0], data[6]); //with missing value\r\n\tvar similarity_6_0 = numericSimilarityDistance.compute(data[6], data[0]); //with missing value\r\n\tvar similarity_6_6 = numericSimilarityDistance.compute(data[6], data[6]); //with missing value\r\n\t\r\n\r\n\t//check that 5 is identical to 5\r\n\tassert(similarity_0_2 == 1.0);\r\n\t\r\n\t//check that 2 is same similar to 5 with 8\r\n\tassert(similarity_0_1 == similarity_0_3);\r\n\t\r\n\t//check that 2 is more similar to 5 than 9\r\n\tassert(similarity_0_1 > similarity_0_4);\r\n\r\n\t//check that 9 is more similar to 5 than 20\r\n\tassert(similarity_0_4 > similarity_0_5);\r\n\t\r\n\t\r\n\t//two missing values are identical\r\n\tassert(similarity_6_6 == 1.0);\r\n\t\r\n\t//distance with missing value is symmetric\r\n\tassert(similarity_0_6 == similarity_6_0);\r\n\t\r\n\t//check that 2 is more similar than missing value\r\n\tassert(similarity_0_1 > similarity_0_6);\r\n\t\r\n\t//check that 9 is more similar than missing value\r\n\tassert(similarity_0_4 > similarity_0_6);\r\n\t\r\n\t//check that missing value is more similar than 20\r\n\tassert(similarity_0_6 > similarity_0_5);\r\n\t\r\n\tconsole.log(\"PASS\")\r\n}", "function test_ordinal_attribute(){\r\n\t\r\n\tconsole.log(\"test_ordinal_attribute....\")\r\n\r\n\t\r\n\tvar myMap = new Map();\r\n\tmyMap.set(\"Ordinal\", new Ordinal([\"0\",\"1\",\"2\",\"3\",\"4\"], 4, 0));\r\n\r\n\t//initialize\r\n\tvar similarityDist = new SimilarityDistanceClass(myMap);\r\n\r\n\tvar data = [ {\"Ordinal\": \"1\"},\r\n\t\t\t\t {\"Ordinal\": \"0\"},\r\n\t\t\t\t {\"Ordinal\": \"1\"},\r\n\t\t\t\t {\"Ordinal\": \"2\"},\r\n\t\t\t\t {\"Ordinal\": \"3\"},\r\n\t\t\t\t {\"Ordinal\": \"4\"},\r\n\t\t\t\t {\"Ordinal\": -1}\r\n\t\t\t\t ];\r\n\t\r\n\tvar similarity_0_1 = similarityDist.compute(data[0], data[1]);\r\n\tvar similarity_0_2 = similarityDist.compute(data[0], data[2]);\r\n\tvar similarity_0_3 = similarityDist.compute(data[0], data[3]);\r\n\tvar similarity_0_4 = similarityDist.compute(data[0], data[4]);\r\n\tvar similarity_0_5 = similarityDist.compute(data[0], data[5]);\r\n\tvar similarity_0_6 = similarityDist.compute(data[0], data[6]); //with missing value\r\n\tvar similarity_6_0 = similarityDist.compute(data[6], data[0]); //with missing value\r\n\tvar similarity_6_6 = similarityDist.compute(data[6], data[6]); //with missing value\r\n\r\n\t//check that 1 is identical to 1\r\n\tassert(similarity_0_2 == 1.0);\r\n\t\r\n\t//check that 0 is same similar to 1 with 2\r\n\tassert(similarity_0_1 == similarity_0_3);\r\n\t\r\n\t//check that 0 is more similar to 1 than 3\r\n\tassert(similarity_0_1 > similarity_0_4);\r\n\r\n\t//check that 3 is more similar to 1 than 4\r\n\tassert(similarity_0_4 > similarity_0_5);\r\n\t\r\n\t//two missing values are identical\r\n\tassert(similarity_6_6 == 1.0);\r\n\t\r\n\t//distance with missing value is symmetric\r\n\tassert(similarity_0_6 == similarity_6_0);\r\n\t\r\n\t//check that 0 is more similar than missing value\r\n\tassert(similarity_0_1 > similarity_0_6);\r\n\t\r\n\t//check that 3 is more similar than missing value\r\n\tassert(similarity_0_4 == similarity_0_6);\r\n\t\r\n\t//check that missing value is more similar than 20\r\n\tassert(similarity_0_6 > similarity_0_5);\r\n\t\r\n\tconsole.log(\"PASS\")\r\n}", "function similarityScore(patientID, subjectID, knnAttributes) {\r\n let score = 0;\r\n let outOf = 1;\r\n\r\n // console.log(knnAttributes)\r\n \r\n //giving error \r\n // if(self.patients[patientID].AgeAtTx && self.patients[subjectID].AgeAtTx){\r\n // let tieBreaker = -(Math.abs(self.patients[patientID].AgeAtTx - self.patients[subjectID].AgeAtTx)) / 150; // max age diff - 150\r\n\r\n // score += tieBreaker;\r\n\r\n // }\r\n\r\n let tieBreaker = -(Math.abs(self.patients[patientID].AgeAtTx - self.patients[subjectID].AgeAtTx)) / 150; // max age diff - 150\r\n\r\n score += tieBreaker;\r\n \r\n\r\n for (let attribute of knnAttributes) {\r\n // console.log(patientID, self.patients[patientID][axes[attribute].name] === self.patients[subjectID][axes[attribute].name]);\r\n if (self.patients[patientID][self.axes[attribute].name] === self.patients[subjectID][self.axes[attribute].name]) {\r\n score += 1;\r\n }\r\n if (self.patients[patientID][self.axes[attribute].name] != \"N/A\" && self.patients[subjectID][self.axes[attribute].name]!= \"N/A\" ) {\r\n outOf += 1;\r\n }\r\n }\r\n // let twoDecimalScore = score.toFixed(2)\r\n let percentage = (score / outOf) * 100;\r\n // let twoFix = percentage.toFixed(2);\r\n // let result = percentage.toFixed(2) + \" %\"\r\n\r\n // result = score + \" / \" + outOf\r\n return percentage;\r\n }", "function calcSimilarity(node1, node2) {\r\n\t\t\t\tvar calcedSimilarty = 0, weight = 0;\r\n\t\t\t\tfor (var calcF in calcFunctions)\r\n\t\t\t\t{\r\n\t\t\t\t\tvar cf = calcFunctions[calcF];\r\n\t\t\t\t\tif (cf.weight > 0)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcalcedSimilarty += cf.func(node1,node2);\r\n\t\t\t\t\t\tweight += cf.weight;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\treturn calcedSimilarty/weight;\r\n\t\t\t}", "function normalizedSimilarity(img, target) {\n\tvar sim = similarity(img, target.image);\n\treturn (sim - target.baseline) / (1 - target.baseline);\n}", "function baselineSimilarity(targetImg) {\n\tvar w = targetImg.width;\n\tvar h = targetImg.height;\n\tvar img = new ImageData2D().fillWhite(w, h);\n\treturn similarity(img, targetImg);\n}", "function binarySimilarity(img, targetImg) {\n\treturn img.percentSameBinary(targetImg);\n}", "function calculateSimilarityScore(dict1, dict2) {\n // Calculate vector norms\n var ss1 = 0.0;\n for (var i in dict1) {\n ss1 += dict1[i] * dict1[i];\n }\n ss1 = Math.sqrt(ss1);\n var ss2 = 0.0;\n for (var i in dict2) {\n ss2 += dict2[i] * dict2[i];\n }\n ss2 = Math.sqrt(ss2);\n // calculate dot product\n var dp = 0.0;\n for (var i in dict1) {\n if (i in dict2) {\n dp += (dict1[i] / ss1) * (dict2[i] / ss2);\n }\n }\n return 100 - Math.acos(dp) * 100 / Math.PI;\n}", "function Similarity(){\n var u = 1;\n for (u = 1; u < TweetCount+1; u ++){\n// check if there is previous text\nconsole.log(\"last text is: \" + TweetLastText[u]);\nif (TweetLastText[u] !== \"\"){\nTweetSimilar[u] = natural.JaroWinklerDistance(TweetLastText[u],TweetText[u]);\nconsole.log(\"the words similarity is: \" + TweetSimilar[u]);\n }\n// check tweet against all others\nvar o = 1;\n for (o = 1; o < TweetCount+1; o ++){\nif (TweetText[o] !== TweetText[u]){\n console.log(natural.JaroWinklerDistance(TweetText[u],TweetText[o]));\n}\n }\n\n\n\n }\n}", "async familiarityDistance(l, r) {\n let distanceSum = 0;\n let lCategories = await l.getCategories();\n let rCategories = await r.getCategories();\n for (let lc of lCategories) {\n for (let rc of rCategories) {\n distanceSum += this.levenshteinDistance(lc, rc);\n }\n }\n let titleDistance = this.levenshteinDistance(l.getTitle(), r.getTitle()); //distance between titles\n distanceSum += titleDistance;\n return distanceSum / (lCategories.length * rCategories.length + 1); //Total sum divided by number of distaces\n }", "relevance(that){cov_25grm4ggn6.f[9]++;let total=(cov_25grm4ggn6.s[47]++,0);let words=(cov_25grm4ggn6.s[48]++,Object.keys(this.count));cov_25grm4ggn6.s[49]++;words.forEach(w=>{cov_25grm4ggn6.f[10]++;cov_25grm4ggn6.s[50]++;total+=this.rank(w)*that.rank(w);});//return the average rank of my words in the other vocabulary\ncov_25grm4ggn6.s[51]++;return total/words.length;}", "function calculate_class_score_commonality(sentence, className){\r\n\tvar score = 0;\r\n\tvar mySentence = sw.removeStopwords(token.tokenize(sentence));\r\n\tvar word;\r\n\tfor (word in mySentence){\r\n\t\tvar stemmed_word = stemmer(mySentence[word])\r\n\t\tif (class_words[className].contains(stemmed_word)){\r\n\t\t\t score += (1 / corpus_words[stemmed_word])\r\n\t\t}\r\n\t}\r\n\treturn score;\r\n}", "function cosineSimilarity(query, doc){\n let sim_idx = 0;\n\n query instanceof Array ? query: query.split(\" \");\n let q_vec = createVSM(query, query);\n let doc_vec = createVSM(query, doc);\n\n for (let i in query){\n isNaN(q_vec[i] * doc_vec[i])? sim_idx += 0: sim_idx += q_vec[i] * doc_vec[i];\n }\n let product = findMag(q_vec) * findMag(doc_vec);\n\n if(isNaN(1.0 * sim_idx / (product))){\n return 0;\n } else {\n return 1.0 * sim_idx / (product);\n }\n }", "function mobEvaluate(mobius, x) {\n let [[a, b], [c, d]] = mobius;\n return (a * x + b) / (c * x + d);\n}", "function similaridadeDoCosseno() {\n var vetorL2 = [];\n var vetorProdutoEscalar = [];\n\n var vetorCosseno = [];\n\n for (var linha = 0; linha < matriz.length; linha++) {\n vetorL2[linha] = calculaL2(linha);\n vetorProdutoEscalar[linha] = produtoEscalar(linha);\n }\n console.log(\"vetor produto \", vetorProdutoEscalar);\n\n var normaDaChave = vetorL2[vetorL2.length - 1];\n\n for (var i = 0; i < vetorL2.length - 1; i++) {\n vetorCosseno[i] = [i, vetorProdutoEscalar[i] / (normaDaChave * vetorL2[i])];\n }\n\n vetorCosseno.sort(compare);\n\n return vetorCosseno;\n}", "function scoresSpecial(a, b) {\n let c = findSpecial(a);\n let d = findSpecial(b);\n let e = a[c];\n let f = b[d];\n if (a[c] === undefined) e = 0 ;\n if (b[d] === undefined) f = 0 ;\n return e + f;\n}", "function modis_ndviCalc(image){\n return image.normalizedDifference(['sur_refl_b02', 'sur_refl_b01']).rename('ndvi')\n}", "function saliency() {\n\n\tvar conceptCount = countConcepts(); // go through each predication and add the subject/object to an array returned with total and unique counts\n\tvar avgActivationWeight = computeAvgActivationWeight(conceptCount); // use the counts from above to calc the average count for all\n\n\tsetSC1(conceptCount, avgActivationWeight); \t\t\t\t\t\t// map counts >= average to true and rest to false\n\n\t// Calculate SC3 - repeat SC1 using the unique predications count\n\tsetAvgSumOther(conceptCount); \t// calc average of all other concepts for each concept\n\tsetSC3(conceptCount); \t// SC3 is SC2 of concepts from unique predications\n\tsetSalient(conceptCount); // set summaryLinks[i].predicate[j].salient = true if subj AND obj both true by SC1 or SC3.\n\n/* not in production version\n\tvar predicationCount = countPredications();\n\tbalancePredications(predicationCount);\n\tcomputeSRC1(predicationCount);\n\treturn join of conceptCount.SC1==true, uniqueConceptCount.SC3==true, relationCount??? and predicationCount.SRC1==true;\n*/\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Repeatedly issues requests to a server until we have all fragments of all images, then fires a `done` callback.
function getAllFragments(done) { var endpoint = 0; var queue = []; function _getAllFragments() { if (gotAllFragments()) { done(); } else { if (queue.length < 5) { queue.push(endpoint); getFragment(endpoint + 1, function (fragment) { if (fragment !== null && gotAllImageFragments(fragment.image_id)) { writeImage(fragment.image_id); } queue.pop(); }); endpoint = (endpoint + 1) % 5; _getAllFragments(); } else { setTimeout(function(){ _getAllFragments(); }, 5); } } } // Start the polling cycle. _getAllFragments(); }
[ "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 }", "async loadImages() {\n const resources = Array.from(this._resources.entries());\n\n console.info(`[ImageManager] Loading ${resources.length} image assets.`);\n\n await Promise.all(resources.map(([iKey, iValue]) => {\n console.info(`[ImageManager] Loading image ${iValue}.`);\n\n const img = new Image();\n img.src = iValue;\n\n return new Promise((resolve) => img.addEventListener('load', () => {\n this._images.set(iKey, img);\n resolve();\n }))\n }));\n\n this._loaded = true;\n\n console.info('[ImageManager] Images loaded.');\n }", "function onImageLoaded() {\r\n\t\t++numImagesLoaded;\r\n\t\t\r\n\t\tif (numImagesLoaded == numImagesRequested) {\r\n\t\t\tnumImagesLoaded = 0;\r\n\t\t\tnumImagesRequested = 0;\r\n\t\t\timagesToLoad = [];\r\n\r\n\t\t\tif (onAllImagesLoadedCallback !== null && onAllImagesLoadedCallback !== undefined) {\r\n\t\t\t\tonAllImagesLoadedCallback();\r\n\t\t\t\tonAllImagesLoadedCallback = null;\r\n\t\t\t}\r\n\t\t}\r\n\t}", "function lazyLoadImages(){\n\t\tvar wrappers = document.querySelector('#image_container');\n\t\tvar imgLoad = imagesLoaded( wrappers );\n\t\tfunction onAlways( instance ) {\n\t\t\t//This should only happen once all of the images have finished being loaded\n\t\t\tconsole.log(\"All images loaded\");\n\t\t\tcollage();\n\t\t\t$('.Collage').collageCaption();\n\t\t}\n\t\timgLoad.on( 'always', onAlways );\n\t}", "function imageLoaded() {\n imagesLoaded++\n if (imagesLoaded == totalImages) {\n allImagesLoaded()\n }\n }", "function imageLoaded() {\n noOfImageLoaded++;\n if (noOfImageLoaded == 10) {\n onLoadFinish();\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}", "async function getImages(breeds) {\n const promises = breeds.map((breed) =>\n fetch(`https://dog.ceo/api/breed/${breed[0]}/images/random`).then((response) => response.json())\n );\n const images = await Promise.all(promises);\n return images;\n}", "async WaitImageCachePromise() {\n await Promise.all(this.imageCachePromise_);\n }", "function preload_images() {\n for (var i = 0; i < c_PreloadChunkSize && imageIndex < images.length; i++, imageIndex++) {\n outstandingPreloadCount++;\n var image = images[imageIndex];\n (function(image) {\n $('<img />')\n .attr('alt', image.title)\n .attr('src', image.img + '_n.jpg')\n .one('load', function() {\n var link = $('<a />')\n .attr('href', image.img + '_b.jpg')\n .attr('title', image.title)\n .append($(this));\n gallery.append(link);\n outstandingPreloadCount--;\n })\n .error(function() {\n console.log('Error downloading image: ' + image.img);\n outstandingPreloadCount--;\n });\n })(image);\n }\n }", "function fetchDogImages() {\n fetch(imgUrl)\n .then(function(resp) {\n return resp.json()\n })\n .then(function(json) {\n renderDogImages(json)\n })\n}", "function updateCurImg(){\n console.log('attempting to update current image');\n\n\n //get the peek peekInsert\n var peekInsert = document.getElementById('peekOutsideDiv');\n if(peekInsert.currentId) var result = results[peekInsert.currentId];\n\n if(peekInsert.currentId && !result.hasImg){\n console.log('requesting image for id: ' + peekInsert.currentId);\n //if the image has not been downloaded yet then send another request to the server\n requestSingleImg(peekInsert.currentId, function(){});\n }\n\n setTimeout(function(){updateCurImg()}, 1000);\n}", "function getMoreImages() {\n\t\t// Return 0 if fetched all images, 1 if enough to fill screen and >1 otherwise\n\t\tvar uncovered_px = $box.height()+$box.offset().top - ($(document).scrollTop()+window.innerHeight),\n\t\t\tuncovered_rows = uncovered_px / settings.row_height;\n\n\t\tif (unloaded) {\n\t\t\t// Don't load more than if not all have loaded (think: slow connections!)\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (!fetched_all) {\n\t\t\tif (uncovered_rows < 2) {\n\t\t\t\tif (!loading_images && settings.getImages) {\n\t\t\t\t\tloading_images = true;\n\t\t\t\t\tsettings.getImages(addNew);\n\t\t\t\t}\n\t\t\t\treturn 2;\n\t\t\t}\n\t\t\treturn 1;\n\t\t}\n\t\treturn 0;\n\t}", "autoFetch() {\n while (this.processes.length > 0) {\n\n // Remove url from 'process' array\n const xmUrl = this.processes.pop();\n log.log(`Queuing ${xmUrl}`);\n \n this.counter = this.counter + 1;\n\n // Push the url to 'processCompleted'\n this.processesCompleted.push(xmUrl);\n\n // Feed the base Url and fetch HTML\n webService.getWeb(xmUrl).then((data) => {\n\n log.log(`Data received for ${xmUrl}`);\n const newUrls = rulesService.checkRules(data);\n this.allUrls = _.union(this.allUrls, newUrls);\n\n log.log(`Data Queued ${this.counter} - Completed - ${this.dataFetched}`);\n this.dataFetched = this.dataFetched + 1;\n \n if ((this.counter === this.dataFetched) && this.counter !== 1) {\n filesService.createXml(rulesService.sortLinks(this.allUrls));\n } else {\n this.queueUrls(newUrls);\n }\n });\n }\n }", "function findAsyncImages(){\n var asyncImageHolders = document.getElementsByClassName(asyncImgClasses.asyncImgHolder);\n for(var q = 0; q < asyncImageHolders.length; q++){\n var asyncWrap = asyncImageHolders[q];\n // Get img data\n var fullResSrc = asyncWrap.getAttribute(asyncImgDataKeys.dFullRes);\n var lowResSrc = asyncWrap.getAttribute(asyncImgDataKeys.dLowRes);\n var gradient = asyncWrap.getAttribute(asyncImgDataKeys.dGradient);\n var gradientTo = asyncWrap.getAttribute(asyncImgDataKeys.dGradientTo);\n var imgClass = asyncWrap.getAttribute(asyncImgDataKeys.dImgClass);\n var imgAlt = asyncWrap.getAttribute(asyncImgDataKeys.dImgAlt);\n\n // Remove current background image from wrap\n if(lowResSrc || fullResSrc) asyncWrap.style.backgroundImage = 'none';\n\n // Low res\n if(lowResSrc)\n asyncWrap.appendChild(\n loadAsyncImage(lowResSrc, true, imgClass, gradient, gradientTo, imgAlt)\n );\n // Full res\n if(fullResSrc)\n asyncWrap.appendChild(\n loadAsyncImage(fullResSrc, false, imgClass, gradient, gradientTo, imgAlt)\n );\n }\n}", "function setupLoadingAsynchronousImages()\n{\n // for each object with class \"asyncImgLoad\"\n $('.asyncImgLoad').each(\n function()\n { \n // save handle to loader - caintainer which we gona insert loaded image \n var loader = $(this);\n // get image path from loader title attribute\n var imagePath = loader.attr('title');\n // create new image object\n var img = new Image();\n // set opacity for image to maximum\n // value 0.0 means completly transparent\n $(img).css(\"opacity\", \"0.0\")\n // next we set function wich gona be caled then\n // image load is finished \n .load(\n function() \n {\n // insert loaded image to loader object \n // and remove unnecessary title attribute\n loader.append(this).removeAttr('title');\n // for inserted image we set margin to zero\n // opacity to max and fire up 500ms opacity animation \n $(this)\n .css(\"margin\", \"0px\")\n .css(\"opacity\", \"0.0\")\n .animate({opacity: 1.0}, 500,\n function()\n {\n // after animation we remove loader background image \n loader.css(\"background-image\", \"none\");\n }\n );\n }\n // set new value for attribute src - this means: load image from imagePath \n ).attr('src', imagePath); \n }\n );\n}", "function infiniScroll(pageNumber) {\n \n $.ajax({\n url: \"rest/getMoreImages/\"+pageNumber+\"/\"+uploadCount,\n type:'GET',\n success: function(imageJSON){\n \n var imageResults = $.parseJSON(imageJSON);\n for(var i=0;i<6;i++) { \n if(imageResults.images[i].userID !== \"\") {\n \n getGPlusName(imageResults.images[i].userID);\n \n $(\"#contentList\").append(\n '<li class=\"polaroid\">'+\n '<a href=\"javascript:void(0)\" title=\"'+plusName+'\">'+\n '<img src=\"uploads/'+imageResults.images[i].filename+'\" alt=\"'+plusName+'\" />'+\n '</a>'+\n '</li>');\n } else {\n streamOK = false;\n }\n }\n \n }\n });\n}", "function doLazyLoadImages() {\n DomUtil.doLoadLazyImages( self.$scroller, self.$pugs.find( \"pug\" ) );\n }", "function imsanity_resize_images() {\n\t// start the recursion\n\timsanity_resize_next(0);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTION: ShowAlert shows email alert or saved search popup a anchor mode savesearch or newalert
function ShowAlert() { var a = document.createElement('a'); a.href='/enUS/search-editor/default.html?mode=newalert&' + $j('#search_state').val(); a.setAttribute('rel','popup 700 750'); showpopup(a); }
[ "function alertMessageAdd() {\n\t\t\talert.css('display', 'block');\n\t\t}", "function showAlert(type, message, callback) {\n // Set alert colors\n setAlertStyle(type);\n // Determine type of alert to show\n var hitboxElement;\n if ($('#welcome-blue-hitbox').length) {\n // Check to see if we are on the welcome page\n hitboxElement = $('#welcome-blue-hitbox');\n } else {\n hitboxElement = $('#blue-hitbox-add-pane');\n }\n if (isElementInViewport(hitboxElement)) {\n // Hitbox is in view, show alert there\n return showHitboxAlert(hitboxElement, message, callback);\n } else {\n // Hitbox is not in view, show a fixed alert\n return showFixedAlert(hitboxElement, message, callback);\n }\n}", "function savepopup()\n{\n alert(\"You are about to leave (or refresh) this page. Would you like to save the currently stored information? You will then be taken back to home.\");\n\n}", "function alertpopupUitgelogd() {\n alert(\"U moet eerst registreren om te kunnen matchen!\");\n loadController(CONTROLLER_REGISTREER);\n }", "function showMessageOk() {\n var alert = $mdDialog.alert()\n .title('Alerta guardada')\n .htmlContent('La alerta ha sido guardada de forma correcta.')\n .ariaLabel('save alert')\n .ok('OK');\n\n $mdDialog.show(alert);\n $state.reload();\n }", "function showBookmarkPopup()\n{\n\t// if LMSFinish signal is sent then do not check bookmark\n\tif( afterLmsFinish )\n\t\treturn;\n\t\t\n\tvar screenBookmark = doLMSGetValue('cmi.core.lesson_location');\n\t\n\tif( screenBookmark.length == 0 )\n\t\treturn;\n\t\n\tvar screenBookmarkParts = getLocalTracker( currentLessonNo-1 );\n\t\n\tif( screenBookmarkParts.length < 3 && ! screenBookmarkParts.indexOf(':') )\n\t return;\n\t\n\tvar bookmarkedScreen = screenBookmarkParts.split(':')[1];\n \n\tif( bookmarkedScreen.length == 0 )\n\t return;\n\t\n\tbookmarkedScreen = parseInt(bookmarkedScreen);\n\t\n if( bookmarkedScreen > 1 && bookmarkedScreen <= noOfScreens && confirm( loadBookmarkText ) )\n goToBookmark( bookmarkedScreen, 1 );\n\t\n}", "alert( message )\n {\n this.$root.alert( message );\n }", "function showQuestion(){\n var lstrMessage = '';\n lstrMessageID = showQuestion.arguments[0];\n lobjField = showQuestion.arguments[1];\n lstrCaleeFunction = funcname(arguments.caller.callee);\n //Array to store Place Holder Replacement\n var larrMessage = new Array() ;\n var insertPosition ;\n var counter = 0 ;\n\n larrMessage = showQuestion.arguments[2];\n \n lstrMessage = getErrorMsg(lstrMessageID);\n \n if(larrMessage != null &&\n larrMessage.length > 0 ){\n\n while((insertPosition = lstrMessage.indexOf('#')) > -1){\n\n if(larrMessage[counter] == null ){\n larrMessage[counter] = \"\";\n }\n lstrMessage = lstrMessage.substring(0,insertPosition) +\n larrMessage[counter] +\n lstrMessage.substring(insertPosition+1,lstrMessage.length);\n counter++;\n }\n }\n\n //lstrFinalMsg = lstrMessageID + ' : ' + lstrMessage;\n lstrFinalMsg = lstrMessage;\n\n if(lobjField!=null){\n lobjField.focus();\n }\n var cnfUser = confirm(lstrFinalMsg);\n if( !cnfUser ) {\n isErrFlg = true;\n }\n if(cnfUser && lstrCaleeFunction == 'onLoad'){\n \tdisableButtons('2');\n }\n //End ADD BY SACHIN\n return cnfUser;\n}", "function fancyAlert(title, message, buttonName, width) {\n\n\tfancyConfirmCallback(null, title, message, buttonName, width);\n return false;\n}", "function renderAlertResult(alert) {\n $(`.alert-results[data-name=\"${queryPark}\"]`)\n .prop('hidden', false)\n .html(alert);\n}", "function createAlert_return(alert, textAlert) {\n var result = \"<div class=\\\"col-md-12\\\"><div class=\\\"alert alert-\" + alert + \"\\\">\"\n + \"<button aria-hidden=\\\"true\\\" data-dismiss=\\\"alert\\\" class=\\\"close\\\" type=\\\"buttonn\\\">&times;</button><p>\" + textAlert + \"</p></div></div>\";\n return result;\n}", "function showReportBrokenLink (\tobj, form_name, reportingIntro, reportingEmail, labelEmail, labelNote, report, Close, errorEmailAddress, errorNoteNoEmailAddress, lang, instance) {\n\t \tvar reportWindow = document.getElementById('ReportWindow');\n\t \tset_element_display_by_id_safe(form_name + '-reportlink-loading', 'inline');\n\t\tif (reportWindow == null) { \n\t\t\tvar txt = \t'<div id=\"ReportWindow\" ';\n\t\t\t\t\t\tif ( lang == 'heb' ) { txt += ' class=\"ExlRightBrokenLinkPopUp\"> '; } else { txt += ' class=\"ExlBrokenLinkPopUp\"> '; }\n\t\t\t\ttxt += \t'<div class=\"ExlRightDivBL\">' +\n\t\t\t\t\t\t'<a href=\"javascript:closeReportWindow();\" class=\"ExlCloseBL\" > ' +\n\t\t\t\t\t\t'<img src=\"/'+instance+'/img/express/darken_v-ico_close.gif\" width=\"16\" height=\"16\" border=\"0\" alt=' +Close+ ' title=' +Close+ '></a>' +\n\t\t\t\t\t\t'</div>' +\n\t\t\t\t\t\t'<div id=\"ReportingIntro\" tabIndex=\"0\" >'+ reportingIntro + '<br /><br />' + reportingEmail + '<br /><br /></div>' +\n\t\t\t\t\t\t'<div class=\"ExlInputDivBL\" >' +\n\t\t\t\t\t\t'<label for=\"id_e-mail\" ';\n\t\t\t\t\t\tif ( lang == 'heb' ) { txt += ' class=\"ExlRightLabelBL\"> '; } else { txt += ' class=\"ExlLeftLabelBL\"> '; }\n\t\t\t\ttxt += \tlabelEmail+ ' </label>' +\n\t\t\t\t\t\t'<input name=\"e-mail_value\" id=\"id_e-mail\" class=\"ExlInputBL\" ></input>' +\n\t\t\t\t\t\t'</div>' +\n\t\t\t\t\t\t'<div class=\"ExlInputDivBL\">' +\n\t\t\t\t\t\t'<label for=\"id_client_note\" ';\n\t\t\t\t\t\tif ( lang == 'heb' ) { txt += ' class=\"ExlRightLabelBL\"> '; } else { txt += ' class=\"ExlLeftLabelBL\"> '; }\n\t\t\t\ttxt += \tlabelNote+ ' </label>' + \n\t\t\t\t\t\t'<input name=\"note_value\" id=\"id_client_note\" class=\"ExlInputBL\" ></input>' +\n\t\t\t\t\t\t'</div>' +\n\t\t\t\t\t\t'<div id=\"error_div\" tabIndex=\"0\" class=\"ExlErrorDivBL\" >' + \n\t\t\t\t\t\t'<label id=\"report_error1\" class=\"ExlErrorLabelBL\" >' +errorEmailAddress+ '</label>' +\n\t\t\t\t\t\t'<label id=\"report_error2\" class=\"ExlErrorLabelBL\" >' +errorNoteNoEmailAddress+ '</label>' +\n\t\t\t\t\t\t'</div><br />' +\n\t\t\t\t\t\t'<div ';\n\t\t\t\t\t\tif ( lang == 'heb' ) { txt += 'class=\"ExlLeftReportDiv\"> '; } else { txt += 'class=\"ExlRightReportDiv\"> '; }\n\t\t\t\ttxt += \t'<label id=\"report_label\" title=' +report+ '>' +\n\t\t\t\t\t\t'<a href=\"#\" id=\"reportLink\" onclick=\"clickReportBrokenLink (this, \\''+form_name+'\\');\" class=\"ExlReportBL\" >[' +report+ ']</a>' +\n\t\t\t\t\t\t'</label>' +\n\t\t\t\t\t\t'</div>' +\n\t\t\t\t\t\t'</div>';\n\t\t var body = document.getElementsByTagName('body');\n\t\t document.body.innerHTML += txt;\n\t\t}else {\n\t\t\tdocument.getElementById('reportLink').setAttribute(\"onclick\",\"clickReportBrokenLink (this, '\"+form_name+\"')\");\n\t\t\tdocument.getElementById('id_e-mail').value = '';\n\t\t\tdocument.getElementById('id_client_note').value = '';\n\t\t\tset_element_display_by_id_safe('error_div', 'none');\n\t\t}\t\t\n\t\tset_element_display_by_id_safe(form_name + '-reportlink-loading', 'none');\t\n\t\tset_element_display_by_id_safe('ReportWindow', 'inline');\n\t \tdocument.getElementById(\"ReportingIntro\").focus();\t\t\n}", "function appAlert(msg, state, title) {\n var alertPopup = $ionicPopup.alert({\n title: (title == null || title == undefined) ? \"Error\" : title,\n template: msg\n });\n alertPopup.then(function(res) {\n if (state != undefined || state != null) {\n $state.go(state);\n }\n });\n }", "function filterPopUp(){\n\t$(\"#divAlert\").dialog({\n\t\tmodal: true,\n\t\tautoResize:true,\n\t\twidth: width - 200,\n\t\tmaxHeight: 700\n\t});\n\tif(enDisFilter == true){\n\t\t$(\"#divAlert\").load(\"pages/ConfigEditor/Filter.html\",function(){\n\t\t\tinitDynamicFilterValue();\n\t\t});\n\t}\n}", "function registerSuccessAlert(data) {\n swal({\n title: data.parameter.username +\n ' Your SuyaBay account has been successfully created',\n text: 'Send Email Confirmation',\n type: 'success',\n showCancelButton: true,\n closeOnConfirm: false,\n showLoaderOnConfirm: true,\n },\n function() {\n setTimeout(function() {\n swal('Email Confirmation sent to ' + data.parameter.email);\n }, 2000);\n clearField();\n window.location = '/';\n });\n}", "function messageWithHelpLink(alertObject,message){\n\t\treturn \"<a href='\"+ help_url + \"alerts.html\" + alertObject.info +\"' target='_ANDIhelp'>\"\n\t\t\t\t+message\n\t\t\t\t+\" <span class='ANDI508-screenReaderOnly'>, Open Alerts Help</span></a> \";\n\t}", "function showError() {\n alert(\"Cannot display search results\");\n }", "function showAssessmentsPopup( aLength) {\n \n\t\t\tself.selectedAnotations([]);\n\t\t\t//$('.popup').ojPopup('close');\n\t\t\t// Popup1 or popup2 if there are any assessments\n\t\t\t\n \n\t\t\t\t\tdocument.getElementById('popup1').style.display = 'flex';\n document.getElementById('selection-context').style.display = 'block';\n\t\t\t\t\n \n\t\t\t}", "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 }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
(13) Write a function that divides by 2 using binary manipulation only
function divBy2(value) { return value >> 1; }
[ "function divideByTwo(int) {\n return int >> 1\n}", "function divisibleByB(a, b) {\n\treturn a - a % b + b;\n}", "function two (num) {\n if (num>=2) {\n return \tparseInt(num/2)+two(parseInt(num/2));\n }\n else {\n return 0;\n }\n }", "function halveCount(a, b) {\n\tlet x = -1;\n\tfor (let i = 0; a > b; i++) {\n\t\ta /= 2;\n\t\tx++;\n\t}\n\treturn x;\n}", "function divInt_(x,n) {\r\n var i,r=0,s;\r\n for (i=x.length-1;i>=0;i--) {\r\n s=r*radix+x[i];\r\n x[i]=Math.floor(s/n);\r\n r=s%n;\r\n }\r\n return r;\r\n }", "function oddsSmallerThan(n) {\n // Your code here\n\n return parseInt(n /2)\n\n}", "division(a,b) {\n if( b === 0) {\n return 0;\n } else {\n return a/b;\n }\n }", "function dividieren(a,b) { \r\n if (b != 0) \r\n {\r\n return a / b;\r\n }\r\n \r\n return \"Teilen durch 0 nicht möglich!\";\r\n \r\n}", "function divBy4(num){\n return num/4\n\n}", "function expmod2(base, exp, m) {\n const toHalf = expmod2(base, exp / 2, m); //the constant declaration appears outside the conditional expression, it is executed even when the base case exp === 0 is reached\n return exp === 0\n ? 1\n : isEven(exp)\n ? (toHalf * toHalf) % m\n : (base * expmod2(base, exp - 1, m)) % m;\n}", "function division(a, b) {\n //tu codigo debajo\n let resultado = a / b;\n return resultado;\n​\n}", "function dividesEvenly(a, b) {\n\tif (a%b === 0) {\n\t\treturn true;\n\t} else return false;\n}", "function evensAndOdds(num){\n return num % 2 === 0 ? num.toString(2) : num.toString(16);\n}", "function isDivisible(argument1, argument2) {\n if ((argument1/argument2) % 2 === 0){\n return true;\n }\n else {\n return false;\n }\n}", "function ifevenorzero(n){\n if (n == 0){\n return 1\n }\n\n else{\n if(n % 2 == 0 ){\n return 1;\n }\n else{\n return 0;\n }\n }\n}", "function divid(a,b){\n var z = 10;\n return a/b;\n}", "function trickyDoubles(n){\n let strNum = n.toString();\n console.log(typeof strNum);\n \n if(strNum.length%2 === 0){\n let sliceLength = strNum.length/2;\n let firstPart = strNum.substr(0, sliceLength);\n let secondPart = strNum.substr(sliceLength, sliceLength);\n \n if(firstPart === secondPart){\n return Number(strNum);\n }\n }\n return strNum * 2;\n}", "function mod(x, n) {\n return (x % n + n) % n;\n}", "function halfNumber(num) {\n console.log(`Half of ${num} is ${num / 2}.`)\n return num / 2\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called when department is changed
function updateSelectedDepartment() { }
[ "function updateDeptsFunc(dept, sales) {\n\tvar queryDBquantity = \"SELECT total_sales FROM departments WHERE ?\";\n\t// using mySQL connection to run queryDBquantity\n\tconnection.query(queryDBquantity, {\n\t department_name: dept\n\t}, function(err, res) {\n\t\tif (err) throw err;\n\t\tvar deptSalesDB = res[0].total_sales;\n\t\tvar deptSalesDB = deptSalesDB + sales; // based on current deptSales\n\t\tvar queryUpdateQuantity = \"UPDATE departments SET ? WHERE ?\";\n\t\t// using mySQL connection to run queryUpdateQuantity\n\t\tconnection.query(queryUpdateQuantity, [{\n\t\t\ttotal_sales: deptSalesDB // fills in the SET clause\n\t\t}, {\n\t\t\tdepartment_name: dept // fills in the WHERE clause\n\t\t}], function(err, res) {});\n\t});\n}", "function updateDepTable(department, newSales) {\n connection.query(\n 'UPDATE departments SET ? WHERE ?',\n [\n {\n product_sales: newSales\n },\n {\n department_name: department\n }\n ],\n function(err, res) {\n if(err) throw err;\n\n // console.log(res.affectedRows + \" departments got updated!\");\n }\n )\n}", "function addDepartment() {\n\tinquirer.prompt(prompt.insertDepartment).then(function (answer) {\n\t\tvar query = \"INSERT INTO department (name) VALUES ( ? )\";\n\t\tconnection.query(query, answer.department, function (err, res) {\n\t\t\tif (err) throw err;\n\t\t\tconsole.log(\n\t\t\t\t`You have added this department: ${answer.department.toUpperCase()}.`,\n\t\t\t);\n\t\t});\n\t\tconsole.log(\"\\n<<<<<<<<<<<<<<<<<<<< ⛔ >>>>>>>>>>>>>>>>>>>>\\n\");\n\t\tviewAllDepartments();\n\t});\n}", "function addDepartment() {\n\tinquirer.prompt(prompt.insertDepartment).then(function (answer) {\n\t\tvar query = \"INSERT INTO department (name) VALUES ( ? )\";\n\t\tconnection.query(query, answer.department, function (err, res) {\n\t\t\tif (err) throw err;\n\t\t\tconsole.log(\n\t\t\t\t`You have added this department: ${answer.department.toUpperCase()}.`,\n\t\t\t);\n\t\t});\n\t\tconsole.log(\"\\n<<<<<<<<<<<<<<<<<<<< ⛔ >>>>>>>>>>>>>>>>>>>>\\n\");\n\t\tviewDepartments();\n\t});\n}", "function bindAfterDepDrpDwnReady()\n{\n\t$('#depDropDwnList').find(\"li input[type=checkbox]\").change(function() {\n\t\tif($(this).attr('id') != \"allDeptChkBox\"){\n\t\t\tonChangeDeptDropDown();\t\n\t\t\tif($(this).is(':checked')){\n\t\t\t\t$('#deptlst :input[value=\"'+$(this).attr('id')+'\"]').prop('checked', true);\n\t\t\t}else{\n\t\t\t\t$('#deptlst :input[value=\"'+$(this).attr('id')+'\"]').prop('checked', false);\n\t\t\t}\n\t\t}\t\t\n\t});\t\n\t\t\n}", "function fieldChanged(type, name, linenum) {\r\n\t\r\n\tsetStatusSetDate(name);\r\n\t\r\n}", "function departmentOpenDialogHandler(isNew, id) {\n\tif(isNew == null && typeof(isNew) == \"undefined\") {\n\t\tisNew = false;\n\t}\n\n\tif (!isNew) {\n\t\t// Loading an existing type\n\t\tvar array_key = -1;\n\t\tfor(department in jsDataObjects.departmentsArray) {\n\t\t\tif(jsDataObjects.departmentsArray[department].id == id) {\n\t\t\t\tarray_key = department;\n\t\t\t}\n\t\t}\n\t\tif(array_key == -1) {\n\t\t\treturn;\n\t\t}\n\t\t// get our college data from JS cache\n\t\tvar department = jsDataObjects.departmentsArray[array_key];\n\t\tjQuery(\"#department-id\").val(id);\n\t\tjQuery(\"#department-name\").val(department.name);\n\t\tvar emails_string = \"\";\n\t\tvar emails = department.emails;\n\t\t$.each(emails, function(key, val) {\n\t\t\tif (val.email != \"\") {\n\t\t\t\temails_string += val.email + \", \";\n\t\t\t}\n\t\t});\n\n\t\tjQuery(\"#department-emails\").val(emails_string.substring(0, emails_string.length-2));\n\t\t\n\t\tjQuery(\"#department-modal .modal-header h3\").text(\"Edit Department\");\n\t\tjQuery(\"#department-modal .modal-footer #department-save\").val(\"Save Department\");\n\t\tjQuery(\"#department-remove\").show();\n\t} else {\n\t\t// Adding a new department\n\t\tjQuery(\"#department-id\").val(\"\");\n\t\tjQuery(\"#department-name\").val(\"\");\n\t\tjQuery(\"#department-emails\").val(\"\");\n\t\t\n\t\tjQuery(\"#department-modal .modal-header h3\").text(\"Add Department\");\n\t\tjQuery(\"#department-modal .modal-footer #department-save\").val(\"Add Department\");\n\t\tjQuery(\"#department-remove\").hide();\n\n\t}\n\n\t// out any previous errors\n\tjQuery(\"#department-errors\").html(\"\");\n\tjQuery(\"#department-modal .control-group\").each(function () {\n\t\tjQuery(this).removeClass(\"error\"); \n\t});\n\n\tjQuery('#department-modal').modal('show');\n}", "function updateDepartmentCallData(user, department, departmentAnalyticsMap, departmentObjectsMap, departmentsParentMap){\n if(department && department.get(\"call_data_type\") && user.get(\"call_data\")){ // check if user has a department and user has call data\n var departmentId = department.id,\n callData = user.get(\"call_data\"),\n personalityList = userConstants.PERSONALITY_LIST;\n if(departmentAnalyticsMap[departmentId] && !departmentAnalyticsMap[departmentId].callData){ // check if department has no call center data\n departmentAnalyticsMap[departmentId].callData = {}; // create initial call center data map for the department\n for(var personalityIndex in personalityList){\n departmentAnalyticsMap[departmentId].callData[personalityList[personalityIndex].toLowerCase()] = {\n score: 0,\n count: 0,\n userCount: 0\n }\n }\n }\n // update call data of user department for each personality\n for(var personalityIndex in personalityList){\n var personalityCallDataObject = callData.get(personalityList[personalityIndex].toLowerCase() + \"Metric\");\n if(personalityCallDataObject && personalityCallDataObject.count >= userConstants.CALL_COUNT_THRESHOLD) {\n departmentAnalyticsMap[departmentId].callData[personalityList[personalityIndex].toLowerCase()].score += (typeof parseInt(personalityCallDataObject.score) == \"number\") ? parseInt(personalityCallDataObject.score) : 0;\n departmentAnalyticsMap[departmentId].callData[personalityList[personalityIndex].toLowerCase()].count += (parseInt(personalityCallDataObject.count));\n departmentAnalyticsMap[departmentId].callData[personalityList[personalityIndex].toLowerCase()].userCount++;\n }\n }\n }\n\n // if this department is a child department of any department then update it's parent department also\n if(department && departmentsParentMap[department.id]){\n updateDepartmentCallData(user, departmentObjectsMap[departmentsParentMap[department.id]], departmentAnalyticsMap, departmentObjectsMap, departmentsParentMap);\n }\n }", "function SelectedProcessChanged(){\n \n GetCurrentProcessFromCombo();\n \n LoadTaskArray();\n \n _curSelectedTask = null;\n \n LoadSLDiagram();\n \n ShowTaskPanel(false);\n \n ShowProcessProperties();\n}", "function prepareListener() {\n var droppy;\n droppy = document.getElementById(\"datecheck\");\n droppy.addEventListener(\"change\",getDoctors);\n}", "function departureDateHandler() {\n\thandlePastDate();\t\t\t\t\t\t// Ensures that a past date is handled.\n\tdateInverter();\t\t\t\t\t\t\t// Inverts dates if necessary.\n}", "async update(req,res){\n try {\n\n let params = req.allParams();\n let attr = {};\n if(params.name){\n attr.name = params.name;\n }\n if(params.description){\n attr.description = params.description;\n }\n \n const departmentById = await Department.update({\n id: req.params.department_id\n }, attr);\n return res.ok(departmentById);\n\n } catch (error) {\n return res.serverError(error);\n }\n }", "showAdditionalDepartments(el) {\n if (el.parents('.drop').find('.reception-add-review').is(':visible')) {\n el.parents('.drop').find('.reception-add-review').hide();\n } else {\n el.parents('.drop').find('.reception-add-review').find('.department-select-row').show();\n el.parents('.drop').find('.reception-add-review').show();\n }\n }", "departmentUnvalidity() {\n if ($scope.view.establishments.department.length >= 2) {\n // If the department isn't equal to one of the department that are in fact strings in STRING_DEPARTMENTS\n if (STRING_DEPARTMENTS.indexOf($scope.view.establishments.department) !== -1) {\n return false;\n }\n\n // If the department is in the list of french departments\n if (Number.isInteger(Number($scope.view.establishments.department))) {\n const integerDepartment = Number($scope.view.establishments.department);\n if ((integerDepartment > 0 && integerDepartment < 96) || (integerDepartment > 970 && integerDepartment < 977)) {\n return false;\n }\n }\n }\n\n $scope.view.errorMsg = 'Veuillez rentrer un departement français valide';\n return true;\n }", "changeContact(newContactId,domElement){\n let selectedContact = this.getContactById(Number(newContactId));\n this.currentChatPartner = selectedContact;\n super.notifyObservers(\"contactChanged\",{contact:selectedContact,elem:domElement,userId:this.personnelId});\n }", "function onSelectedChanged(val) {\n scope.$emit('selectedchange', val);\n }", "function viewEmployeeByDepartment() {\n\tconsole.log(\"View employees by department\\n\");\n\n\tvar query = `SELECT d.id, d.name\n\tFROM employee e\n\tLEFT JOIN role r\n\tON e.role_id = r.id\n\tLEFT JOIN department d\n\tON d.id = r.department_id\n\tGROUP BY d.id, d.name`;\n\n\tconnection.query(query, function (err, res) {\n\t\tif (err) throw err;\n\n\t\t// Select department\n\t\tconst departmentChoices = res.map((data) => ({\n\t\t\tvalue: data.id,\n\t\t\tname: data.name,\n\t\t}));\n\n\t\tinquirer\n\t\t\t.prompt(prompt.departmentPrompt(departmentChoices))\n\t\t\t.then(function (answer) {\n\t\t\t\tvar query = `SELECT e.id, e.first_name, e.last_name, r.title, d.name AS department \n\t\t\tFROM employee e\n\t\t\tJOIN role r\n\t\t\t\tON e.role_id = r.id\n\t\t\tJOIN department d\n\t\t\tON d.id = r.department_id\n\t\t\tWHERE d.id = ?`;\n\n\t\t\t\tconnection.query(query, answer.departmentId, function (err, res) {\n\t\t\t\t\tif (err) throw err;\n\n\t\t\t\t\tconsole.table(\"\\nDepartment Rota: \", res);\n\t\t\t\t\tconsole.log(\"\\n<<<<<<<<<<<<<<<<<<<< ⛔ >>>>>>>>>>>>>>>>>>>>\\n\");\n\n\t\t\t\t\tfirstPrompt();\n\t\t\t\t});\n\t\t\t});\n\t});\n}", "onDepChanged() {\n\t\tif (atom.packages.isPackageActive(this.dependentPkgs)) {\n\t\t\tthis.el.classList.remove('unsupportted')\n\t\t\tthis.el.onclick = '';\n\t\t} else {\n\t\t\tthis.el.classList.add('unsupportted')\n\t\t\tthis.el.onclick = async ()=>{\n\t\t\t\ttry { await atom.packages.installPackage(this.dependentPkgs, {\n\t\t\t\t\textraButtons: [\n\t\t\t\t\t\t{\ttext:'remove the Font Size Group',\n\t\t\t\t\t\t\tonDidClick:()=>{atom.config.set('bg-tree-view-toolbar.buttons.fontGroup',false);}}\n\t\t\t\t\t]}\n\t\t\t\t)} catch(e) {\n\t\t\t\t\tconsole.log(e)\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}", "function closeDepartment() {\n\tconsole.log(chalk.underline.red(\"\\nClose Department function under development\\n\"));\n\toverview();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
' Name : handle_bp_get_corp_account ' Return type : None ' Input Parameter(s) : req, startTime, apiName ' Purpose : Creating a class to handle the BP_GET_CORP_ACCOUNT API error with following members ' History Header : Version Date Developer Name ' Added By : 1.0 28th Apr,2012 Ravi Raj '
function handle_bp_get_corp_account(req, startTime, apiName) { this.req = req; this.startTime = startTime; this.apiName = apiName; }
[ "function handle_bp_account_lite(req, startTime, apiName) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\n}", "function handle_bp_remove_biller_corp_account(req, startTime, apiName) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\n}", "function handleGetBPAccount(billerCorpId, programId, isMsg) {\n /* To show the progress bar */\n showProgressBar();\n\n /* Hold request parameters and values for request parameters */ \n var request = new Object();\n request.userId = eval(getCookie(\"userId\"));\n request.billerCorpAccountId = billerCorpId;\n request.applicationId = applicationId;\n request.locale = getCookie(\"locale\");\n\n var call_bp_get_corp_account = new bp_get_corp_account(request, programId, isMsg);\n call_bp_get_corp_account.call();\n}", "function handle_bp_save_biller_corp_acct_creds(req, startTime, apiName) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\n}", "function handleBpGetCorpAccountOnSuccess(programId, isMsg) {\n\tvar acctCreds = bp_get_corp_account_obj.accountCredentials;\n\tfor (var j = 0; j < acctCreds.length; j++) {\n\t bpGetCorpAccountMap[acctCreds[j].elementId] = acctCreds[j].value;\n\t}\n\tuserNickName = bp_get_corp_account_obj.nickname;\n\thandleGetBillerCreds(bp_get_corp_account_obj.billerCorpId, programId, isMsg);\n}", "function handle_cm_get_payment_card(req, startTime, apiName, fromSubmittPay) {\n this.req = req;\n this.startTime = startTime;\n this.apiName = apiName;\n this.fromSubmittPay = fromSubmittPay;\n}", "function handle_bp_biller_corp_search(req, startTime, apiName) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\n}", "function handleGetBillerCreds(billerCorpId, programId, isMsg) {\n /* To show the progress bar */\n showProgressBar();\n\n /* Hold request parameters and values for request parameters */\n\tvar request = {};\n request.billerCorpId = billerCorpId;\n if (programId && programId != \"null\") {\n \trequest.programId = programId;\n\t}\n request.applicationId = applicationId;\n request.locale = getCookie(\"locale\");\n if (parseBoolean(localStorage.getItem(\"registerUser\"))) {\n $('#guestUserMyAccountBox').remove();\n $(\"#accBoxMainDivId\").removeClass(\"myAccountSection\");\n $('#myAccountBox').show();\n $('#userName').text(getCookie(\"userName\"));\n }\n \n var call_bp_biller_corp_creds = new bp_biller_corp_creds(request, isMsg);\n call_bp_biller_corp_creds.call();\n}", "returnableAccount(account){}", "function GetMainAccountTaskPerformData(req, callback) {\n\tcontractInfo.getContractInfo(req.params.contractAddress,(err,doc)=>{\n\t\tvar json = [];\n\t\tif(err){\n\t\t\tcallback(null, json);\n\t\t} else if (doc !== null) {\n var obj = {};\n var status = [];\n var abiJson = JSON.parse(doc.abi);\n var Multiply7 = web3.eth.contract(abiJson);\n var multi = Multiply7.at(req.params.contractAddress);\n var updateCount = multi.getstatusupdateCount();\n for (var j = 0; j < updateCount.toString(); j++) {\n var updateInfo = multi.getstatusupdate(j);\n var splitArr = [];\n var arr = updateInfo.toString().split(\",\");\n for (var k = 0; k < arr.length; k++) {\n splitArr.push(arr[k]);\n }\n if (splitArr[1] == req.session.address) {\n status.push(splitArr[3]);\n }\n }\n if (status.length > 0) {\n\t\t\t\tobj.status = common.getstatustext(status[status.length - 1]);\n }\n if (multi.owner() == req.session.address) {\n obj.contractNumber = multi.contractNumber();\n obj.contractAddress = doc.contractAddress;\n obj.ContractDescription = multi.contractDescription();\n obj.ContractOwnedby = multi.contractOwnedby();\n obj.data = \"Rejected Data\";\n obj.isrejected = false;\n json.push(obj);\n }\n var assigneeCount = multi.getassigneeCount();\n for (var i = 0; i < assigneeCount.toString(); i++) {\n var assignee = multi.getassignee(i);\n var assigneeSplitArr = [];\n var assigneeArr = assignee.toString().split(\",\");\n for (var m = 0; m < assigneeArr.length; m++) {\n assigneeSplitArr.push(assigneeArr[m]);\n }\n if (i == 1 && assigneeSplitArr[3] == props.status_rejected) {\n obj.isrejected = true;\n }\n }\n } else {\n callback(null, json);\n }\n\t});\n}", "function handle_bp_cancel_scheduled_payment(req, startTime, apiName, callFrom) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\tthis.callFrom = callFrom;\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}", "function AccountObj()\n{\n\tthis.Countries = new Array() // list of country codes used by all direct deposit accounts on record\n\tthis.Hash = new Array()\t // list of accounts indexed by country code; each is an AccountsHash object\n\tthis.sysAvailable = 0\t // total accounts available to add for the system, independent of country\n\tthis.totalOpen = 0\t // total number of active accounts for the system, across all countries\n\tthis.totalClose = 0\t // total number of inactive accounts for the system, across all countries\n\tthis.sysLimit = MAXACCOUNTS // the maximum allowable number of accounts the system will hold\n}", "function retrieveOrgData(resultRecord, fields, orgId, prefix, BPServiceURLBase, readyCallback){\n\tvar fieldsForURL = getFieldsOnPrefixFromList(fields, prefix);\n\tif ((fieldsForURL.length > 0) && (! isNullOrEmpty(orgId))) {\n\t\tvar urlStr = BPServiceURLBase.urlTmpForOrgSearch.replace('{cond}','(hrOrganizationCode='+orgId+')').replace('{fields}',fieldsForURL);\n\t\tconsole.log('retrieveOrgData.urlStr= '+urlStr);\n\t\trequest(urlStr, function (error, response, body) {\n\t\t\tvar errStr = getErrStrFromResponse(error, response, body); // empty if no error\n\t\t\tif (errStr.length > 0) { // error\n\t\t\t\tresultRecord.record[2] += ' / ' + errStr;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tvar bodyData = JSON.parse(body);\n\t\t\t\tvar db = bodyData.search['return'].count;\n\t\t\t\tif (db == 0) {\t\t// -- no record found\n\t\t\t\t\tresultRecord.record[2] += ' / Found 0 Organizations for hrOrganizationCode=' + orgId;\n\t\t\t\t}\n\t\t\t\telse { // found\n\t\t\t\t\tvar bodyDataRecord = bodyData.search.entry[0];\n\t\t\t\t\tfillResultRecord(resultRecord.record, fields, prefix, bodyDataRecord);\t\t\t\t\t\n\t\t\t\t}\t\t\t\n\t\t\t} // else\n\t\t\treadyCallback();\n\t\t}); // request\n\t} // if \n\telse {\n\t\treadyCallback(); // do nothing, because no field requested\n\t}\n}", "function getAbi(account){\n try {\n return eos.getAbi(account).then(function(abi) {\n return abi;\n });\n } catch (err) {\n let errorMessage = `Get Abi Controller Error: ${err.message}`;\n return errorMessage;\n } \n}", "function handle_user_get_profile(req, startTime, apiName) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\n}", "getSocialAccounts (context) {\n return new Promise(resolve => {\n ApiService.get('/api/social_accounts')\n .then(({data}) => {\n context.commit('setSocialAccounts', data)\n resolve(data)\n })\n .catch( err => {\n context.commit('setErrors', err)\n })\n })\n }", "function handle_bp_verify_funding_sources(req, startTime, apiName) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\n}", "function getServiceAPIVersionByReqObj (req, appData, type, callback, reqBy)\n{\n var redirectToLogout = true;\n var dataObjArr = [];\n var endPtList = [];\n var config = configUtils.getConfig();\n\n var endPtFromConfig = authApi.isOrchEndptFromConfig();\n if (null == endPtFromConfig) {\n endPtFromConfig = true;\n }\n if (true == endPtFromConfig) {\n var apiType = getApiTypeByServiceType(type);\n ip = httpsOp.getHttpsOptionsByAPIType(apiType, 'ip');\n port = httpsOp.getHttpsOptionsByAPIType(apiType, 'port');\n version = getOStackModuleApiVersion(apiType);\n protocol = httpsOp.getHttpsOptionsByAPIType(apiType, 'authProtocol');\n if ((null == ip) || (null == port) || (null == version) ||\n (null == protocol)) {\n logutils.logger.error(\"ip/port/apiVersion/authProtocol not found in\" +\n \" config file for:\" + apiType);\n callback(null);\n return;\n }\n var verLen = version.length;\n for (var i = 0; i < verLen; i++) {\n dataObjArr.push({'version': version[i], 'protocol': protocol, 'ip': ip,\n 'port': port});\n }\n if (!dataObjArr.length) {\n logutils.logger.error('apiVersion for ' + type + ' is NULL');\n callback(null);\n } else {\n dataObjArr.sort(function(a, b) {\n if (b['version'] > a['version']) {\n return 1;\n } else if (b['version'] < a['version']) {\n return -1;\n } else {\n return 0;\n }\n });\n callback(dataObjArr);\n }\n return;\n }\n var regionCookie =\n commonUtils.getValueByJsonPath(req, 'cookies;region', null, false);\n if (null == regionCookie) {\n callback(null, null, redirectToLogout);\n return;\n }\n var regionName = authApi.getCurrentRegion(req);\n var reqRegion = commonUtils.getValueByJsonPath(appData, \"authObj;reqRegion\",\n null);\n if (null != reqRegion) {\n regionName = reqRegion;\n }\n if ((null != regionName) && ('undefined' != regionName)) {\n serviceCatalog =\n commonUtils.getValueByJsonPath(req, 'session;serviceCatalog;' +\n regionName, null, false);\n } else {\n serviceCatalog = commonUtils.getValueByJsonPath(req,\n 'session;serviceCatalog',\n null, false);\n if (null != serviceCatalog) {\n for (var key in serviceCatalog) {\n regionName = key;\n req.session.regionname = regionName;\n serviceCatalog = serviceCatalog[key];\n break;\n }\n }\n }\n if (null != serviceCatalog) {\n mappedObj = null;\n try {\n mappedObjs = serviceCatalog[type].maps;\n } catch(e) {\n mappedObjs = null;\n }\n if ((null != mappedObjs) && (null != mappedObjs[0])) {\n callback(mappedObjs, regionName);\n return;\n }\n }\n authApi.getServiceCatalog(req, function(accessData) {\n if ((null == accessData) || (null == accessData.serviceCatalog)) {\n callback(null, null, redirectToLogout);\n return;\n }\n var keySt = require('./keystone.api');\n var svcCatalog =\n keySt.getServiceCatalogByRegion(req, regionName, accessData);\n var firstRegion = null;\n var config = configUtils.getConfig();\n if (null != svcCatalog) {\n for (var key in svcCatalog) {\n if (null == firstRegion) {\n firstRegion = key;\n }\n req.session.serviceCatalog[key] = svcCatalog[key];\n }\n }\n var mappedObjs = null;\n if (-1 != global.keystoneServiceListByProject.indexOf(type)) {\n var domProject = req.cookies[global.COOKIE_DOMAIN_DISPLAY_NAME] + ':' +\n req.cookies[global.COOKIE_PROJECT_DISPLAY_NAME];\n mappedObjs =\n commonUtils.getValueByJsonPath(svcCatalog, regionName + ';' +\n domProject + ';' + type +\n ';maps', null);\n } else {\n mappedObjs =\n commonUtils.getValueByJsonPath(svcCatalog, regionName + ';' + type +\n ';maps', null);\n }\n if ((null == mappedObjs) && (global.service.MAINSEREVR == reqBy)) {\n /* We did not find this region in the service catalog */\n if (global.REGION_ALL != regionCookie) {\n req.res.cookie(\"region\", firstRegion, {\n secure: !config.insecure_access\n });\n }\n callback(null, null, redirectToLogout);\n return;\n }\n callback(mappedObjs, regionName);\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to check up right left down Alaways have to check whether the node is a wall If is a wall then it wont be added to the the surr_node_coor if node alrd in close node need to do checking
function get_surr_coor(x){ const coor_current_node = x[0]; const surrounding_node_coor = []; // up const row_up = coor_current_node[0] - 1 ; const column_up = coor_current_node[1] ; if(check_wall(row_up,column_up) === 'unvisited _wall' || check_wall(row_up,column_up) === 'Starting-Node' || check_wall(row_up,column_up) === 'visited'){ }else{ surrounding_node_coor.push([row_up, column_up]); }; // down const row_down = coor_current_node[0] + 1 ; const column_down = coor_current_node[1] ; if(check_wall(row_down,column_down) === 'unvisited _wall' || check_wall(row_down,column_down) === 'Starting-Node' || check_wall(row_down,column_down) === 'visited'){ }else{ surrounding_node_coor.push([row_down, column_down]); }; // right const row_right = coor_current_node[0] ; const column_right = coor_current_node[1] + 1 ; if(check_wall(row_right,column_right) === 'unvisited _wall' || check_wall(row_right,column_right) === 'Starting-Node' || check_wall(row_right,column_right) === 'visited'){ }else{ surrounding_node_coor.push([row_right, column_right]); }; // left const row_left = coor_current_node[0] ; const column_left = coor_current_node[1] - 1 ; if(check_wall(row_left,column_left) === 'unvisited _wall' || check_wall(row_left,column_left) === 'Starting-Node' || check_wall(row_left,column_left) === 'visited'){ }else{ surrounding_node_coor.push([row_left, column_left]); }; return surrounding_node_coor ; }
[ "checkRI() {\n const leftChildHeight = this.left === null ? -1 : this.left.height;\n const rightChildHeight = this.right === null ? -1 : this.right.height;\n if (Math.abs(leftChildHeight - rightChildHeight) >= 2) {\n console.log(`RI INVALID! ${this.key}`);\n }\n if (Math.max(leftChildHeight, rightChildHeight) + 1 !== this.height) {\n console.log(`HEIGHT INVALID! ${this.key}`);\n }\n if (this.left) {\n this.left.checkRI();\n }\n if (this.right) {\n this.right.checkRI();\n }\n }", "function collisionRightBorder(circle){\n /*******************\n * PARTIE A ECRIRE */\n return circle.x+circle.radius>main_window.width;\n //return false;\n /*******************/\n}", "find_direction() {\n this.direction = (this.direction + 1) % 4; // CCW 90\n if (!this.is_facing_wall())\n return true;\n this.direction = (this.direction + 3) % 4; // CCW 270\n if (!this.is_facing_wall())\n return true;\n this.direction = (this.direction + 3) % 4; // CCW 270\n if (!this.is_facing_wall())\n return true;\n this.direction = (this.direction + 3) % 4; // CCW 270\n if (!this.is_facing_wall())\n return true;\n // If all four sides have walls\n console.log(\"Oops, an error occurred and the bot thinks it's trapped!\");\n return false;\n }", "function checkGrid(rover) {\r\n\tif ( \trover.position[0] < 0 || rover.position[0] > 9 ) {\r\n if (rover.position[0] < 0) {\r\n myRover.position[0]++;\r\n }\r\n if (rover.position[0] > 9) {\r\n myRover.position[0]--;\r\n }\r\n\t\treturn true;\r\n\t}\r\n\telse if (rover.position[1] < 0 || rover.position[1] > 9) {\r\n if (rover.position[1] < 0) {\r\n myRover.position[1]++;\r\n }\r\n if (rover.position[1] > 9) {\r\n myRover.position[1]--;\r\n }\r\n\t\treturn true;\r\n\t}\r\n\telse {\r\n\t\treturn false;\r\n\t}\r\n}", "function HittingTheWall(){\r\n for(let i = 0; i < curTetromino.length; i++){\r\n let newX = curTetromino[i][0] + startX;\r\n if(newX <= 0 && direction === DIRECTION.LEFT){\r\n return true;\r\n } else if(newX >= 11 && direction === DIRECTION.RIGHT){\r\n return true;\r\n } \r\n }\r\n return false;\r\n}", "function processRightEdge() {\n processEdge(\n [currentLevelMaxIndex, currentLevelMaxIndex - 1], // lowest value is always one up from bottom right corner\n c => {\n return c[1] > currentLevelMinIndex\n }, // right edge ends when y meets top edge\n c => {\n c[1]--\n return c\n }\n ) // traverse towards top edge\n}", "function nodeIsInsideCanvas(nodeX, nodeY)\r\n {\r\n if (nodeX > 0 && nodeX < settings.canvasWidth &&\r\n nodeY > 0 && nodeY < settings.canvasHeight) {\r\n return true;\r\n }\r\n \r\n return false;\r\n }", "hasWallInDirection (x, y, direction) {\n return !(this.getBlockValue(x, y) & direction);\n }", "function checkHitLeftRight(ball) {\n\t\tif (ball.offsetLeft <= 0 || ball.offsetLeft >= 975) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}", "function checkBoundries() {\n if (x > 560) { // if ship is more than the right of the screen\n rightMove = false; // stop it moving\n } else if (x < 40) { // if ship is more than the left of the screen\n moveLeft = false; // stop it moving\n }\n if (y > 560) { // if ship is more than the bottom of the screen\n downmove = false; // stop it moving\n } else if (y < 30) { // if ship is more than the top of the screen\n upmove = false; // stop it moving\n }\n}", "function removeLeftWall(currentCell, nextCell) {\n\tindex = points.indexOf(currentCell.p32);\n\tpoints.splice(index, 1);\n\tindex = points.indexOf(currentCell.p12);\n\tpoints.splice(index, 1);\n\tcurrentCell.hasAllWallsUp = false;\n\tindex = points.indexOf(nextCell.p22);\n\tpoints.splice(index, 1);\n\tindex = points.indexOf(nextCell.p41);\n\tpoints.splice(index, 1);\n\tnextCell.hasAllWallsUp = false;\n}", "function castleRook(king, mx, my) {\n\n let rook = null;\n\n if (king.player == 'human') {\n\n if (mx - king.x > 0) {\n rook = board[7][7];\n } else {\n rook = board[7][0];\n }\n\n } else {\n\n if (mx - king.x > 0) {\n rook = board[0][7];\n } else {\n rook = board[0][0];\n }\n\n }\n\n //Checks to see if the king is trying to move over pieces\n if (rook != null) {\n\n //King moving to the right\n if (mx - king.x > 0) {\n\n for (let x = king.x + 1; x < rook.x; x++) {\n\n //Piece found, return null\n if (board[king.y][x] != null) return null;\n\n //Check if king is attempting to move through check\n let king_x = king.x;\n let cell_content = board[king.y][x];\n\n board[king.y][king.x] = null;\n board[king.y][x] = king;\n king.x = x;\n\n let chk = isInCheck(king);\n\n //Revert\n king.x = king_x;\n board[king.y][x] = cell_content;\n board[king.y][king.x] = king;\n\n if (chk) return null;\n }\n\n }\n //King is moving to the left\n else {\n\n for (let x = king.x - 1; x > rook.x; x--) {\n\n //Piece found, return null\n if (board[king.y][x] != null) return null;\n\n //Check if king is attempting to move through check\n let king_x = king.x;\n let cell_content = board[king.y][x];\n\n board[king.y][king.x] = null;\n board[king.y][x] = king;\n king.x = x;\n\n let chk = isInCheck(king);\n\n //Revert\n king.x = king_x;\n board[king.y][x] = cell_content;\n board[king.y][king.x] = king;\n\n if (chk) return null;\n }\n\n }\n\n }\n\n return rook;\n\n}", "is_facing_wall_or_portal() {\n switch(this.direction){ \n case KeyboardCodeKeys.left:\n return this.maze.has_left_wall(this.row, this.col)\n || (this.col == 0);\n case KeyboardCodeKeys.right:\n return this.maze.has_right_wall(this.row, this.col)\n || (this.col == this.maze.col_count-1);\n case KeyboardCodeKeys.up:\n return this.maze.has_top_wall(this.row, this.col)\n || (this.row == 0);\n case KeyboardCodeKeys.down:\n return this.maze.has_bot_wall(this.row, this.col)\n || (this.row == this.maze.row_count-1);\n }\n }", "function removeLowerWall(currentCell, nextCell) {\n\tindex = points.indexOf(currentCell.p11);\n\tpoints.splice(index, 1);\n\tindex = points.indexOf(currentCell.p21);\n\tpoints.splice(index, 1);\n\tcurrentCell.hasAllWallsUp = false;\n\tindex = points.indexOf(nextCell.p42);\n\tpoints.splice(index, 1);\n\tindex = points.indexOf(nextCell.p31);\n\tpoints.splice(index, 1);\n\tnextCell.hasAllWallsUp = false;\n}", "function testWinCondition(row, col) {\n let t = boardState[row][col]; //last played token\n let bs = boardState;\n\n //DOWN\n if (row<=2 && t==bs[row+1][col] && t==bs[row+2][col] && t==bs[row+3][col])\n return (true);\n \n //DIAGONAL FORWARD - POSITION 1\n else if (row>=3 && col<=3 && t==bs[row-1][col+1] && t==bs[row-2][col+2] && t==bs[row-3][col+3])\n return (true);\n //DIAGONAL FORWARD - POSITION 2\n else if (row>=2 && row<=4 && col>=1 && col<=4 && t==bs[row+1][col-1] && t==bs[row-1][col+1] && t==bs[row-2][col+2])\n return (true);\n //DIAGONAL FORWARD - POSITION 3\n else if (row>=1 && row<=3 && col>=2 && col<=5 && t==bs[row+2][col-2] && t==bs[row+1][col-1] && t==bs[row-1][col+1])\n return (true);\n //DIAGONAL FORWARD - POSITION 4\n else if (row<=2 && col>=3 && t==bs[row+3][col-3] && t==bs[row+2][col-2] && t==bs[row+1][col-1])\n return (true);\n\n //DIAGONAL BACKWARD - POSITION 1\n else if (row<=2 && col<=3 && t==bs[row+1][col+1] && t==bs[row+2][col+2] && t==bs[row+3][col+3])\n return (true);\n //DIAGONAL BACKWARD - POSITION 2\n else if (row>=1 && row<=3 && col>=1 && col<=4 && t==bs[row-1][col-1] && t==bs[row+1][col+1] && t==bs[row+2][col+2])\n return (true);\n //DIAGONAL BACKWARD - POSITION 3\n else if (row>=2 && row<=4 && col>=2 && col<=5 && t==bs[row-2][col-2] && t==bs[row-1][col-1] && t==bs[row+1][col+1])\n return (true);\n //DIAGONAL BACKWARD - POSITION 4\n else if (row>=3 && col>=3 && t==bs[row-3][col-3] && t==bs[row-2][col-2] && t==bs[row-1][col-1])\n return (true);\n \n //HORIZONTAL - POSITION 1\n else if (col<=3 && t==bs[row][col+1] && t==bs[row][col+2] && t==bs[row][col+3])\n return (true);\n //HORIZONTAL - POSITION 2\n else if (col>=1 && col<=4 && t==bs[row][col-1] && t==bs[row][col+1] && t==bs[row][col+2])\n return (true);\n //HORIZONTAL - POSITION 3\n else if (col>=2 && col<=5 && t==bs[row][col-2] && t==bs[row][col-1] && t==bs[row][col+1])\n return (true);\n //HORIZONTAL - POSITION 4\n else if (col>=3 && t==bs[row][col-3] && t==bs[row][col-2] && t==bs[row][col-1])\n return (true);\n else \n return (false);\n}", "function is_to_the_left_of_blank(tile) {\n var isLeft = false;\n if (tile.row === blank.row - 1)\n {\n isLeft = true;\n }\n return isLeft;\n}", "function moveRight(){\r\n unDraw();\r\n const isAtRightEdge = current.some(index => (currentPosition + index) % width === (width-1));\r\n if (!isAtRightEdge){\r\n currentPosition +=1;\r\n }\r\n\r\n if(current.some(index => squares[currentPosition + index].classList.contains('taken'))){\r\n currentPosition -=1;\r\n }\r\n draw();\r\n }", "function is_next_to_blank(tile) {\n var isAdjacent = false;\n if (is_below_blank(tile) || is_above_blank(tile) || is_to_the_left_of_blank(tile) || is_to_the_right_of_blank(tile))\n {\n isAdjacent = true;\n }\n return isAdjacent;\n}", "function isInside(rw, rh, rx, ry, x, y)\n{\n return x <= rx+rw && x >= rx && y <= ry+rh && y >= ry // Get Click Inside a Bush\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Name: getClickedWord Called by: delegateMethod Parameters: selRange The clicked location in the DOM. node DOM node that was clicked. Returns: word (word that was clicked on, without punctuation, etc.) Explanation: Retrieves DOM node information for a mouse click. Given the node that was clicked, it gets the string contained therein, and finds the location in string that was clicked. This information is used by isolateWord to find the word that Annotext will look up.
function getClickedWord(selRange, node) { var nodeText = document.createRange(); nodeText.selectNode(node); var str = nodeText.toString(); var loc = selRange.focusOffset; return isolateWord(str,loc); }
[ "function click_word(word,dimension,mouse_event){\n console.log('word ');\n console.log(word);\n console.log('Dimension: ');\n console.log(dimension);\n /*alert('word: '+ item + ' with coordinates: '+ JSON.stringify(dimension));*/\n }", "function getWordOnPosition(pos) {\n\tvar editableDiv = document.getElementById(\"inputTextarea\");\n\tvar curPos = getCaretPositionInDiv(editableDiv);\n\tsetCaretPositionInDiv(editableDiv, pos);\n\tvar word = getCurrentWord();\n\tsetCaretPositionInDiv(editableDiv, curPos);\n\treturn word;\n}", "function acHighlightedText() {\n return Selector(\".autocomplete-item.highlighted\").textContent;\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 }", "wordAt(pos) {\n let { text, from, length } = this.doc.lineAt(pos)\n let cat = this.charCategorizer(pos)\n let start = pos - from,\n end = pos - from\n while (start > 0) {\n let prev = findClusterBreak(text, start, false)\n if (cat(text.slice(prev, start)) != dist_CharCategory.Word) break\n start = prev\n }\n while (end < length) {\n let next = findClusterBreak(text, end)\n if (cat(text.slice(end, next)) != dist_CharCategory.Word) break\n end = next\n }\n return start == end\n ? null\n : EditorSelection.range(start + from, end + from)\n }", "function printWord() {\n $(\"#word\").text(current_word.displayed_word);\n}", "function findWordIndex(word) {\n\t\tfor (var i = 1; i <= 3; i++) {\n\t\t\tfor (var j = 0; j < 16; j++) {\n\t\t\t\tvar menu_item = \"#\" + i + \"_\" + j + \"\";\n\t\t\t\t// might be item.target.text\n\t\t\t\tif($(menu_item).text() === word) {\n\t\t\t\t\t// return menu_item;\n\t\t\t\t\treturn j;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// return \"#none\";\n\t\treturn -1;\n\t}", "receiveWord(playerId, word) {\n console.log(\"receiveWord\");\n switch (this.state) {\n case GameStates.Picking: {\n console.log(\"OK\t\", this.currentDrawer);\n if (this.currentDrawer.id === playerId) {\n console.log(\"receive selection\");\n this.currentWord = word;\n } else {\n //error non drawer can't select word\n }\n }\n break\n }\n }", "function getWord(node, offset, include_end)\n{\n\tif(node.lastWord && \n\t offset >= node.lastWord.node_offset && offset < node.lastWord.node_offset + node.lastWord.word.length + (include_end ? 1 : 0))\n\t{\n\t\treturn node.lastWord;\n\t}\n\telse\n\t{\n\t\tvar word = node.firstWord;\n\t\t\n\t\twhile(word && word != node.lastWord)\n\t\t{\n\t\t\tif(offset >= word.node_offset && offset < word.node_offset + word.word.length + (include_end ? 1 : 0))\n\t\t\t{\n\t\t\t\treturn word;\n\t\t\t}\n\t\t\t\n\t\t\tword = word.nextWord;\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n}", "function getWordFromURL(url) {\n // get query param\n var a = url.split(\"q=\");\n if (a.length != 2) {\n return \"\"\n } \n\n // sanitize search query string:\n // remove trailing parameters\n // un URL encode\n // replace \"+\" with spaces\n var searchQueryStringRaw = a[1].split(\"&\")[0];\n var searchQueryString = decodeURIComponent(searchQueryStringRaw).replace(\"+\", \" \");\n\n console.log(searchQueryStringRaw);\n\n // if search query was of format \"define: [word]\", return word\n var terms = searchQueryString.split(\":\");\n if (terms.length == 2 && terms[0] == \"define\") {\n var definitionTarget = terms[1];\n \n // trim starting space, if necessary\n if (definitionTarget[0] == \" \" && definitionTarget.length > 1) {\n definitionTarget = definitionTarget.substring(1, definitionTarget.length);\n }\n return definitionTarget;\n }\n return \"\";\n}", "function mousePressed() {\n size = 10;\n word = lexicon.randomWord('nn', 3);\n voice.speak(word);\n}", "function handleWordClick(event) {\n // get letter associated with image\n let image = document.getElementById(\"image\").src.substring(57,58)\n console.log(\"image name\", image)\n let word = event.target.value\n console.log(\"word selected\", word)\n for (let i=0; i<8; i++) {\n wordList[word][i]+=images[image][i] \n } \n console.log(wordList[word])\n document.getElementById(\"image\").src = randImage()\n}", "function OneWordHelper_highlight(word, mainID) {\n this.p_currentWord = word\n\n this.locs = chlonnik.mainIndex.getNumbers(this.p_currentWord)\n for(var i = 0; i < this.locs.length; i++) {\n utl.id( 'w-'+this.locs[i] ).className = 'highlight'\n } // for i in this.locs\n\n this.showBar(mainID)\n} // _highlight function", "function newWord(txt) {\n\treturn txt.slice(1);\n}", "function spellcheck(originalString, suggestedWords)\r\n{\r\n\t// this function goes through all the words in the originalString,\r\n\t// looks to see if there is a suggestion for that word, and if so,\r\n\t// replaces it with some html\r\n\t\r\n\tg_suggestedWords = suggestedWords;\r\n\t\r\n\t// check for [[ ]], but not [[[ ]]]\r\n\t\t// it's not perfect, but should catch most stuff\r\n//\tvar tokenizer = /(\\{.*?\\})|(\\&lt;.*?\\&gt;)|(\\[\\[.*?\\]\\])|(\\[.*?\\])|(\\b.+?\\b)/;\r\n\r\n\t// I decided that we did want to spellcheck stuff in between <> and () etc\r\n\t\t// so we use this simple tokenizer instead\r\n\tvar tokenizer = /\\b(.+?)\\b/;\r\n\t// 1 is {}\r\n\t// 2 is <>\r\n\t// 3 is [[ ]]\r\n\t// 4 is [ ]\r\n\t// 5 is a word\r\n\tvar the_str = originalString;\r\n\tvar arr = tokenizer.exec(the_str, \"i\");\r\n\tvar rightContext = RegExp.rightContext;\r\n\t\r\n\tvar i = 0;\r\n\twhile (arr != null) {\r\n\t\ti++;\r\n\t\t\r\n\t\tvar word = arr[1];\r\n//\t\talert(\"next word is \" + word);\r\n\t\t// readies for next time\r\n\t\tarr = tokenizer.exec(rightContext);\r\n\t\t// we only need to search to the right of the word\r\n\t\t// that we just found\r\n\t\t// originally the string was searched from the beginning each time\r\n\t\trightContext = RegExp.rightContext;\r\n\t\t\r\n\t\tif (suggestedWords[word])\r\n\t\t{\r\n\t\t\toriginalString = makeWordClickable(word, i, originalString)\r\n\t\t}\r\n\t}\r\n\t// reset for next time someone does a spell check\r\n\tg_lengthAlreadySearched = 0;\r\n\treturn \"<div style='bgcolor:#0000FF' onmousedown='hideSuggestions()'>\" + originalString + \"</div>\";\r\n}", "function getDef(word) {\n var request = \"http://api.wordnik.com:80/v4/word.json/\"+word+\"/definitions?limit=1&sourceDictionaries=ahd&api_key=a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5\";\n return queryDict(request)[0].text;\n}", "function changeWord(x) {\r\n //get id from history value\r\n var id = history.getQueue()[(history.getLength() - 1) - x];\r\n\r\n addFocus(id);\r\n}", "function findHighlightTarget(start) {\n let target = start;\n\n while (target.nodeName === 'tspan') target = target.parentNode;\n\n if (target.nodeName === 'text') target = target.parentNode;\n\n if (target.nodeName === 'g' || target.nodeName === 'a') {\n let children = target.getElementsByTagName('rect');\n if (children.length === 0) {\n children = target.getElementsByTagName('path');\n }\n\n if (children.length === 0) return undefined;\n\n target = children.item(0);\n }\n\n return (\n target.nodeName === 'rect' ||\n target.nodeName === 'path' ||\n target.nodeName === 'circle' ||\n target.nodeName === 'ellipse') ? target : undefined;\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}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load userpromocode and append to req.
async function load(req, res, next) { req.userpromocode = await UserPromocode.get(req.params.userpromocodeId); return next(); }
[ "function load(req, res, next, userId) {\n _models.Professional.get(userId).then(function (professional) {\n req.professional = professional;\n return next();\n }).catch(function (e) {\n return next(e);\n });\n}", "willSendRequest (req) {\n req.params.set('apikey', this.context.tm_key)\n }", "function load(req, res, next, username) {\n User.getByUsername(username).then((user) => {\n if (!user) {\n const error = new APIError('no such user exists', 400, true);\n return next(error);\n }\n req.user = user;\t\t// eslint-disable-line no-param-reassign\n return next();\n }).error((e) => next(e));\n}", "function middleware1(request, response, next){\n user.findOne({username : request.params.username} , {_id : 0 , __v : 0})\n .then(function(user){\n if(user) {\n request.userData = user;\n next();\n }\n else response.sendStatus(404);\n })\n .catch(function(err){\n response.send(err);\n })\n}", "function handle_user_init_reg(req, startTime, apiName) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\n}", "function retrieveUAFromRequest() {\n\n \tvar currentUASet = environment.get(\"User-Agent\");\n if (currentUASet == null || currentUASet.isEmpty()) {\n logMessage(\"No User-Agent specified in the evaluation request environment parameters.\");\n return false;\n }\n currentUA = currentUASet.iterator().next();\n logMessage(\"User-Agent found with this resource request: \" + currentUA);\n \n\n}", "function passLoggedInUser(req, res, next){\n //Whatever is put in res.locals, is available in all the routes\n res.locals.loggedInUser = req.user;\n //Move on to next Middleware\n next();\n}", "function handle_user_get_profile(req, startTime, apiName) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\n}", "function handle_user_auth(req, startTime, apiName) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\n}", "function load(req, res, next, userId) {\n Client.get(userId)\n .then((client) => {\n req.client = client;\n return next();\n })\n .catch(e => next(e));\n}", "function handle_user_upd_profile(req, startTime, apiName) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\n}", "function load(req, res, next, id) {\n Enquiry.get(id)\n .then((enquiry) => {\n req.enquiry = enquiry; // eslint-disable-line no-param-reassign\n return next();\n })\n .catch(e => next(e));\n}", "function handle_user_terms(req, startTime, apiName) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\n}", "function middleware1(request, response, next){\n fs.readFile('./user.json', function(err, data){\n if(err) response.end(err);\n else {\n data = JSON.parse(data);\n data.forEach(function(value , index){\n if(request.params.username == data[index].username)\n {\n response.json(data[index]);\n return next();\n }\n })\n }\n })\n}", "function fillAdditionalInfoFromPromoRegister() {\n\t$('#emailIdAddInfoChkOut').val($(\"#emailIdPromoCode\").val());\n\t$('#mobileNoAddInfoChkOut').val($(\"#mobileNoPromoCode\").val());\n\t$('#zipCodeAddInfoChkOut').val($(\"#zipCodePromoCode\").val());\n\tif ($('#chkOptInEnhCreatProfPromo').is(\":checked\")) {\n\t\t$(\"#chkOptInEnhAddInfo\").prop('checked', true);\n\t} else {\n\t\t$(\"#chkOptInEnhAddInfo\").prop('checked', false);\n\t}\n\t$(\"#additional_info_box\").show();\n\tvalidateAdditionalInfo();\n}", "function addVoiceTaskRequest(req, res) {\n var timestamp = Number(new Date()); // current time as number\n var file = req.swagger.params.audiofile.value;\n var userId = req.swagger.params.userId.value;\n var splitFileName = file.originalname.split('.');\n var ext = splitFileName[splitFileName.length - 1].toLowerCase();\n var filename = userId + '_' + timestamp + '.' + ext;\n var audiopath = \"/usr/share/nginx/html/assets/audio-request/\" + filename;\n utility.fileUpload(path.resolve(audiopath), file.buffer).then(function () {\n var voiceTaskDetail = {\n userId: req.body.userId,\n audiopath: filename\n }\n new VoiceTask(voiceTaskDetail).save(function (err, voiceTaskData) {\n if (err) {\n return res.json(Response(500, \"failed\", utility.validationErrorHandler(err), err));\n } else {\n return res.json(Response(200, \"success\", constantsObj.messages.voiceTaskAdded, voiceTaskData));\n }\n });\n }).catch(function (err) {\n res.jsonp(Error(constant.statusCode.error, constant.messages.requestNotProcessed, err));\n });\n}", "function acceptStore(req, res, next) {\n approveStore(req, res).then((result) => {\n return res.status(200).json(result);\n }).catch((err) => {\n next(err);\n });\n}", "function getUserShoppingBag(req, res, next){\n var projectObject = {shopping_bag : 1};\n const uniquFieldValue = req.body[`${uniquField}`];\n userHandler.findUserByUniqueField(uniquField, uniquFieldValue, projectObject, function(err, userShoppingBagDoc){\n if(err){\n next(err);\n } else{\n const userShoppingBag = userToJson(userShoppingBagDoc);\n //if we want only the size of the shopping bag\n if(getBoolean(req.query.quantity) === true){\n var sizeOfShoppingBag = {\n size : userShoppingBag.shopping_bag.length\n }\n res.send(sizeOfShoppingBag);\n } else {\n //adding the total price to the shopping bag\n const totalPrice = userHandler.sumShoppingBag(userShoppingBag.shopping_bag);\n userShoppingBag['total_price'] = totalPrice;\n //if we want to add order\n if(getBoolean(req.query.order) === true){\n res.locals['order'] = userShoppingBag;\n next();\n } else{\n res.send(userShoppingBag);\n }\n \n } \n }\n });\n}", "function load(req, res, next, key) {\n Cache.get(key)\n .then((cache) => {\n req.cache = cache;\n return next();\n })\n .catch(e => next(e));\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a status and updates all checked videos with that status
function updateAllVideoStatuses(newStatus, currentStatus) { /* var id = null; $('.fab-main-videos').find('input:checkbox').each(function(){ id = $(this).attr('value'); if($(this).is(':checked')) { updateVideoStatus(newStatus, currentStatus, id); } var clickedElement = null; switch(newStatus) { case 'accepted': clickedElement = $("#videoAcceptAll"); break; case 'denied': clickedElement = $("#videoDenyAll"); break; } // uncheck the ALL checkboxes $('#fab-check_box').prop('checked', false); // remove greyed out button class clickedElement.removeClass("fab-grey"); }); */ alert('This feature has been temporarily disabled.'); }
[ "function updatevideostatus(){\n \n \n if(video.paused)\n {\n \n video.play();\n }\n else{\n video.pause();\n }\n\n \n }", "function update(){\n\tvlc.status().then(function(status) {\n\t\tvar newPlaying={\n\t\t state: escapeHtml(status.artist+\" - \"+status.album),\n\t\t details: escapeHtml(status.title),\n\t\t largeImageKey: \"vlc\",\n\t\t smallImageKey: status.state,\n\t\t instance: true,\n\t\t}\n\t\tif(newPlaying.state!==nowPlaying.state || newPlaying.details!==nowPlaying.details || newPlaying.smallImageKey!==nowPlaying.smallImageKey){\n\t\t\tconsole.log(\"Changes detected; sending to Discord\")\n\t\t\tif(status.state===\"playing\"){\n\t\t\t\tnewPlaying.startTimestamp=Date.now()/1000\n\t\t\t\tnewPlaying.endTimestamp=parseInt(parseInt(Date.now()/1000)+(parseInt(status.duration)-parseInt(status.time)))\n\t\t\t\tclient.updatePresence(newPlaying);\n\t\t\t}else{\n\t\t\t\tclient.updatePresence(newPlaying);\n\t\t\t}\n\t\t\tdelete newPlaying.startTimestamp\n\t\t\tdelete newPlaying.endTimestamp\n\t\t\tnowPlaying=newPlaying\n\t\t}\n\t});\n}", "async updateVideoStatus(ctx, next) {\n console.log('Controller HIT: VideoController::updateVideoStatus');\n return new Promise((resolve, reject) => {\n const vd = ctx.request.body\n ctx.params = {\"video\":vd.title};\n chpConnection.query({\n sql:`UPDATE Video \n SET isFree = NOT isFree\n WHERE title = ?;`,\n values: [vd.title]\n }, (err, res) => {\n if(err) {\n reject(err);\n }\n resolve();\n });\n })\n .then(await next)\n .catch(err => {\n ctx.status = 500;\n ctx.body = {\n error: `Internal Server Error: ${err}`,\n status: 500\n };\n });\n }", "function updatePlaybackStatus() {\n\tclient.sendCommand('status', (err, msg) => {\n\t\tvar status = mpd.parseKeyValueMessage(msg);\n\t\tif (status.state !== 'play') {\n\t\t\tsongData.value.playing = false;\n\t\t\tsongData.value.title = 'No Track Playing';\n\t\t}\n\t\telse\n\t\t\tsongData.value.playing = true;\n\t});\n}", "function videoToggle() {\n // set video state.\n setVideoState(!videoState);\n\n // toggle the video track.\n toggleTracks(userStream.getVideoTracks());\n\n // send update to all user, to update the status.\n sendUpdate(!videoState, audioState);\n }", "function updateStatus() {\r\n\t\tif (swfReady) {\r\n\t\t\tvar currentStatus = getSWF(\"app\").getStatus();\r\n\t\t\tdocument.forms[\"imForm\"].status.value = currentStatus;\r\n\t\t}\r\n\t}", "function updateStatus() {\n\tchrome.extension.sendRequest(\n\t\t\t{type: \"status?\"}\n\t\t, function(response) {\n\t\t\t$(\"ws_status\").textContent=response.ws_status;\n\t\t\t$(\"pn_status\").textContent=response.pn_status;\n\t\t\t});\t\t\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 _pauseCurrentPlayingVideo(){\n\t\t\tcontext.videoListControl.filter(function (videoItem) {\n\t\t\t\t// i need to get all the videos that are playing, which means its currentState is equals to 'play'\n\t\t\t\treturn videoItem.API.currentState === 'play';\n\t\t\t}).map(function (filteredVideo) {\n\t\t\t\t// pause the filtered video\n\t\t\t\tfilteredVideo.API.pause();\n\t\t\t});\n\t\t}", "static updateStatus(id, status){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.status = status;\n\t\treturn new kaltura.RequestBuilder('responseprofile', 'updateStatus', kparams);\n\t}", "static updateStatus(id, status){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.status = status;\n\t\treturn new kaltura.RequestBuilder('cuepoint_cuepoint', 'updateStatus', kparams);\n\t}", "function updateStatus(devices, new_status)\n{\n\tfor (var i in new_status )\t\t\t//for each status\n\t{\n\t\tfor(var j in devices)\t\t\t//look for the match ID\n\t\t{\n\t\t\tif( devices[j].deviceID == new_status[i].deviceID )\n\t\t\t{\n\t\t\t\tvar status = devices[j].status;\t\t//access the status array\t\t\t\n\t\t\t\t//running status\n\t\t\t\tstatus.running = typeof(new_status[i].running) ? new_status[i].running : status.running;\n\t\t\t\t//auto on mode settings\n\t\t\t\tif( typeof(new_status[i].autoOn) != 'undefined' )\n\t\t\t\t{\n\t\t\t\t\tstatus.autoOn.enable = typeof(new_status[i].autoOn.enable) ? new_status[i].autoOn.enable : status.autoOn.enable;\n\t\t\t\t\tstatus.autoOn.time = typeof(new_status[i].autoOn.time) ? new_status[i].autoOn.time : status.autoOn.time;\n\t\t\t\t}\n\t\t\t\t//auto off mode settings\n\t\t\t\tif( typeof(new_status[i].autoOff) != 'undefined' )\n\t\t\t\t{\n\t\t\t\t\tstatus.autoOff.enable = typeof(new_status[i].autoOff.enable) ? new_status[i].autoOff.enable : status.autoOff.enable;\n\t\t\t\t\tstatus.autoOff.time = typeof(new_status[i].autoOff.time) ? new_status[i].autoOff.time : status.autoOff.time;\n\t\t\t\t}\n\t\t\t\t//parameter of the device\n\t\t\t\tif(typeof(new_status[i].parameter)!='undefined')\n\t\t\t\t{\n\t\t\t\t\tvar para = new Array();\n\t\t\t\t\tpara = para.concat(new_status[i].parameter);\n\t\t\t\t\t//console.log(para.length);\n\t\t\t\t\tfor( var k=0; k < para.length; k++ )\n\t\t\t\t\t{\n\t\t\t\t\t\tpara[k] = (para[k] != null) ? para[k] : status.parameter[k] ;\n\t\t\t\t\t}\n\t\t\t\t\tstatus.parameter = para;\n\t\t\t\t\t//console.log(status.parameter);\n\t\t\t\t}\n\t\t\t\tbreak;\t\t//get out of the inner loop\n\t\t\t}\n\t\t}\n\t}\n}", "function checkWatchedVideos(title_content, image_url, video_url) {\n recently_watched_videos = JSON.parse(localStorage.getItem('watchedVideosArray'));\n\n if (recently_watched_videos.length == 0) {\n // ADD FIRST VIDEO TO JSON\n pushVideosToWatchedList(title_content, image_url, video_url);\n } else {\n // ADD MORE VIDEO TO JSON\n var isExistInWatched = false;\n var watchedVideoIndex = 0;\n $.each(recently_watched_videos, function(ind, obj_val) {\n watchedVideoIndex = ind + 1;\n if (obj_val.title === title_content && obj_val.image === image_url && obj_val.video === video_url) {\n isExistInWatched = true;\n console.log(\"Index number = \" + ind);\n recently_watched_videos.splice(ind, 1);\n }\n if (recently_watched_videos.length === watchedVideoIndex) {\n pushVideosToWatchedList(title_content, image_url, video_url);\n }\n });\n }\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 changeBackgroundVideoFileProgress(message) {\r\n changeBackgroundVideoContentProgress(message, liveBackgroundType);\r\n}", "function downloadSelectedVideos() {\n setCandidateVideos(previousVideos =>\n previousVideos.map(video => (video.isSelected && video.downloadState === 'none') ?\n { ...video, downloadState: 'requested', isSelected: false } :\n video\n )\n )\n\n const selectedVideos = candidateVideos\n .filter(video => video.isSelected)\n .map(video => ({ ...video, downloadState: 'requested', isSelected: false }))\n\n setRequestedVideos(previous => [...selectedVideos, ...previous])\n }", "static updateStatus(id, status){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.status = status;\n\t\treturn new kaltura.RequestBuilder('reach_vendorcatalogitem', 'updateStatus', kparams);\n\t}", "updateVideoTrack(state, track) {\n\t\tVue.set(state.self.tracks, 'audio', track)\n\t}", "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}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setter sur la variable this._imageUrl de l'attribut imageUrl
set imageUrl(monImageUrl) { this._imageUrl = monImageUrl }
[ "set imageURL(aValue) {\n this._logger.debug(\"imageURL[set]\");\n this._imageURL = aValue;\n }", "set imageURL(aValue) {\n this._logService.debug(\"gsDiggEvent.imageURL[set]\");\n this._imageURL = aValue;\n }", "get imageUrl() {\n return this._imageUrl\n }", "async updateImageSource() {\n const source = await this.getThumbnailURL();\n this.getImage().setAttribute('src', source);\n }", "set src(aValue) {\n this._logService.debug(\"gsDiggThumbnailDTO.src[set]\");\n this._src = aValue;\n }", "updateconvertedurl() {\n // src is only actually required property\n if (this.src) {\n const params = {\n height: this.height,\n width: this.width,\n quality: this.quality,\n src: this.src,\n rotate: this.rotate,\n fit: this.fit,\n watermark: this.watermark,\n wmspot: this.wmspot,\n format: this.format,\n };\n this.srcconverted = MicroFrontendRegistry.url(\n \"@core/imgManipulate\",\n params\n );\n }\n }", "get imageURL() {\n this._logger.debug(\"imageURL[get]\");\n return this._imageURL;\n }", "function setImageSrc(image, location) {\n image.src = location + '-640_medium.webp';\n}", "set fileURL(a) { throw \"readonly property\"; }", "addImage(url) {\n \n }", "async setBannerImageFromExternalUrl(url, props) {\n // validate and parse our input url\n const fileUrl = new URL(url);\n // get our page name without extension, used as a folder name when creating the file\n const pageName = this.json.FileName.replace(/\\.[^/.]+$/, \"\");\n // get the filename we will use\n const filename = fileUrl.pathname.split(/[\\\\/]/i).pop();\n const request = ClientsidePage(this, \"_api/sitepages/AddImageFromExternalUrl\");\n request.query.set(\"imageFileName\", `'${filename}'`);\n request.query.set(\"pageName\", `'${pageName}'`);\n request.query.set(\"externalUrl\", `'${url}'`);\n request.select(\"ServerRelativeUrl\");\n const result = await spPost(request);\n // set with the newly created relative url\n this.setBannerImage(result.ServerRelativeUrl, props);\n }", "function setImage(id, src) {\n\t// logMessage(\"id.src:\"+id+\"->\"+src);\n\tdocument.getElementById(id).src = src;\n}", "function setSrc(element,attribute){element.setAttribute(attribute,element.getAttribute('data-'+attribute));element.removeAttribute('data-'+attribute);}", "function setCameraImageUrl(baseurl) {\n\tvar url = baseurl + '?time=' + new Date().getTime();\n\tdocument.getElementById(\"cameraImage\").src = url;\n\tcameraImageUrlBox.value = url;\n}", "loadSrcSet() {\n if(this.fredCropper.el.attributes.srcset.value === \"null\") {\n console.log('correctly null');\n return false;\n }\n let srcset = this.fredCropper.el.attributes.srcset.value.split(',');\n\n srcset.forEach(function(t){\n let width = t.substr(t.lastIndexOf(\" \") + 1);\n let url = t.substr(0, t.lastIndexOf(\" \"));\n\n if(this.srcValues.length > 0) {\n this.srcValues.forEach((src) => {\n if (parseInt(src.width) === parseInt(width)) {\n src.url = url;\n }\n });\n }\n }.bind(this));\n\n let count = 0;\n this.srcValues.forEach(function(src) {\n if(src.url.length > 0) {\n count++;\n }\n });\n this.srcCount = count;\n //console.log(this.srcValues);\n }", "static imageSrcSetUrlForRestaurant(restaurant) {\r\n return (`/img2/${restaurant.id}` + `-300_small.webp 300w, ` + `/img/${restaurant.id}` + `.webp 600w`);\r\n }", "function objSetImage(obj, imgPath) {\n if (imgPath != obj.imgPath) {\n obj.imgPath = imgPath;\n obj.div.style.backgroundImage = \"url('\" + imgPath + \"')\";\n obj.div.style.width = imgProp[imgPath].width + \"px\";\n obj.div.style.height = imgProp[imgPath].height + \"px\";\n }\n}", "overrideUrl(iUrl) {\n return iUrl;\n }", "function setPicture(){\n\n\t\t\t\tvar sizes = new Object();\n\n\t\t\t\telement.find('source').each(function(){\n\n\t\t\t\t\tvar media, path, num;\n\t\t\t\t\tmedia = $(this).attr('media');\n\t\t\t\t\tpath = $(this).attr('src');\n\n\t\t\t\t\tif(media)\n\t\t\t\t\t\tnum = media.replace(/[^\\d.]/g, '');\n\t\t\t\t\telse\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] + '\" style=\"' + element.attr('style') + '\" alt=\"' + element.attr('alt') + '\">';\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\t\t\t\t\t\n\t\t\t\t\telement.find('img').attr('src', sizes[currentMedia]);\n\n\t\t\t\t}\n\n\t\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
u2 attribute_name_index; u4 attribute_length; u1 info[attribute_length]; }
function AttributeInfo(bytesArray, index) { this.bytes = bytesArray; var startByteIndex = index; var nameIndex = getTwoBytes(bytesArray, index); var attributeLength = getFourBytes(bytesArray, index + 2); var info = null; // todo:Add this this.length = function() { return 6 + attributeLength; } this.getCssClass = function() { return "attribute-info-section"; } this.getBytecode = function (indexUnused, constants) { var attributeName = getDirectString(nameIndex, constants); var code = ""; if(attributeName == "Code") { var codeAttribute = new CodeAttribute(bytesArray, index) code = codeAttribute.getBytecode(index, constants); } return "<table><tr><td class='method-byte-address'>" + formatAsFourByteHexString(index) + "</td><td class='method-byte-address'>" + formatAsHexString(nameIndex) + "</td><td>@" + attributeName + "</td></tr></table>" + code; } this.getReferenceIndex = function() { return nameIndex; } }
[ "getAttribLocation(name) {\n\t\treturn this.attributes[name] ? this.attributes[name].location : -1;\n\t}", "_updateAttributes() {\n const attributeManager = this.getAttributeManager();\n\n if (!attributeManager) {\n return;\n }\n\n const props = this.props; // Figure out data length\n\n const numInstances = this.getNumInstances();\n const startIndices = this.getStartIndices();\n attributeManager.update({\n data: props.data,\n numInstances,\n startIndices,\n props,\n transitions: props.transitions,\n // @ts-ignore (TS2339) property attribute is not present on some acceptable data types\n buffers: props.data.attributes,\n context: this\n });\n const changedAttributes = attributeManager.getChangedAttributes({\n clearChangedFlags: true\n });\n this.updateAttributes(changedAttributes);\n }", "defineAttribute(inName, inSize, inTypeStr) {\n\t\tthis.attributes[inName] = new ShaderAttribute(this, inName, inSize, inTypeStr);\n\t}", "get index_attrs(){\n\t\treturn [...module.iter(this)] }", "getAttributeList() {\n this.ensureParsed();\n return this.attributes_;\n }", "visitAttribute_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function extract_attr( jsonml ) {\n return jsonml.length > 1\n && typeof jsonml[ 1 ] === \"object\"\n && !( jsonml[ 1 ] instanceof Array )\n ? jsonml[ 1 ]\n : undefined;\n }", "visitIndex_attributes(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "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", "getIndex(attributeName) {\n const arg = this.args[attributeName];\n return arg ? arg.idx : null;\n }", "getSize(attributeName) {\n const arg = this.args[attributeName];\n return arg ? arg.values.length : null;\n }", "static createAttrDataObj(el){\n var res = {};\n DATA_MAP.forEach(function(value, key, map) {\n if(el.hasAttribute(key)){\n \n if(key == \"value\"){\n res[value] = el.value; \n } else if (key == \"data-cell_label\"){\n var refNames = value.split('-');\n var refVals = el.getAttribute(key).split('-');\n res[\"cell.\"+ refNames[0]] = refVals[0];\n res[\"cell.\"+ refNames[1]] = refVals[1];\n } else {\n res[value] = el.getAttribute(key); \n }\n \n }\n });\n return res;\n }", "visitAttribute_definition(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function getIndex(vertex, uv) {\n const attributeIndex = floor(frame / 2);\n const vertexIndex = vertex;\n const frameIndex = frame % 2;\n const uvIndex = uv;\n return attributeIndex * FRAME_UV_ATTRIBUTE_SIZE_PER_FRAME + vertexIndex * FRAME_UVS_PER_ATTRIBUTE * 2 + frameIndex * FRAME_UVS_PER_ATTRIBUTE + uvIndex;\n }", "function ElemListView_setInfo(theInfo) {\n var currInfo, currName = '';\n with (this) {\n for (var i=0; i < theInfo.length; i++) {\n if (i % (imagesPerName+1) == 0) {\n currName = theInfo[i];\n currInfo = '';\n for (var j=0; j < imgInfo.length; j++)\n if (currName == imgInfo[j].name) {\n currInfo = imgInfo[j];\n break;\n }\n } else {\n if (currInfo) {\n if (!currInfo.images) currInfo.images = new Array();\n currInfo.images.push(theInfo[i]);\n } } } }\n}", "function htmlNameOfDataAttribute (attribute) {\n attribute.replace(/([a-z][A-Z])/g, function (match) { \n return match[0] + '-' + match[1].toLowerCase();\n });\n return 'data-' + attribute;\n}", "function substrWithAttrCodes(pStr, pStartIdx, pLen)\n{\n\tif (typeof(pStr) != \"string\")\n\t\treturn \"\";\n\tif (typeof(pStartIdx) != \"number\")\n\t\treturn \"\";\n\tif (typeof(pLen) != \"number\")\n\t\treturn \"\";\n\tif ((pStartIdx <= 0) && (pLen >= console.strlen(pStr)))\n\t\treturn pStr;\n\n\t// Find the real start index. If there are Synchronet attribute \n\tvar startIdx = printedToRealIdxInStr(pStr, pStartIdx);\n\tif (startIdx < 0)\n\t\treturn \"\";\n\t// Find the actual length of the string to get\n\tvar len = pLen;\n\tvar printableCharCount = 0;\n\tvar syncAttrCount = 0;\n\tvar syncAttrRegexWholeWord = /^\\1[krgybmcw01234567hinpq,;\\.dtl<>\\[\\]asz]$/i;\n\tvar i = startIdx;\n\twhile ((printableCharCount < pLen) && (i < pStr.length))\n\t{\n\t\tif (syncAttrRegexWholeWord.test(pStr.substr(i, 2)))\n\t\t{\n\t\t\t++syncAttrCount;\n\t\t\ti += 2;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t++printableCharCount;\n\t\t\t++i;\n\t\t}\n\t}\n\tlen += (syncAttrCount * 2);\n\tvar shortenedStr = pStr.substr(startIdx, len);\n\t// Include any attribute codes that might appear before the start index\n\t// in the string\n\tvar attrIdx = pStr.lastIndexOf(\"\\1\", startIdx);\n\tif (attrIdx >= 0)\n\t{\n\t\tvar attrStartIdx = -1;\n\t\t// Generate a string of all Synchronet attributes at the found location\n\t\tfor (var i = attrIdx; i >= 0; i -= 2)\n\t\t{\n\t\t\tif (syncAttrRegexWholeWord.test(pStr.substr(i, 2)))\n\t\t\t\tattrStartIdx = i;\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\t\tif (attrStartIdx > -1)\n\t\t{\n\t\t\tvar attrStr = pStr.substring(attrStartIdx, attrIdx+2);\n\t\t\tshortenedStr = attrStr + shortenedStr;\n\t\t}\n\t}\n\treturn shortenedStr;\n}", "function genAttrQueries(a, h, t, rxs) {\r\n\t\tvar ra = {\r\n\t\t\titems : [],\r\n\t\t\tsel : '',\r\n\t\t\tmethod : h,\r\n\t\t\ttype : t\r\n\t\t};\r\n\t\tvar y = '';\r\n\t\tvar x = $.isArray(a) ? a : a && typeof a === 'string' ? a.split(',')\r\n\t\t\t\t: [];\r\n\t\tfor (var i = 0; i < x.length; i++) {\r\n\t\t\ty = '[' + x[i] + ']';\r\n\t\t\tra.items.push({\r\n\t\t\t\tname : x[i],\r\n\t\t\t\tsel : y,\r\n\t\t\t\tregExp : new RegExp('\\\\s' + x[i] + rxs, 'ig')\r\n\t\t\t});\r\n\t\t\tra.sel += ra.sel.length > 0 ? ',' + y : y;\r\n\t\t}\r\n\t\treturn ra;\r\n\t}", "_getBasisFileAttributes(basisFile) {\r\n const width = basisFile.getImageWidth(0, 0);\r\n const height = basisFile.getImageHeight(0, 0);\r\n const images = basisFile.getNumImages();\r\n const levels = basisFile.getNumLevels(0);\r\n const has_alpha = basisFile.getHasAlpha();\r\n return { width, height, images, levels, has_alpha };\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
scan wifi networks and display them in the list
function scan() { if (scanning) return; // stop auto-scanning if wifi disabled or the app is hidden if (!gWifiManager.enabled || document.mozHidden) { scanning = false; return; } scanning = true; var req = gWifiManager.getNetworks(); req.onsuccess = function onScanSuccess() { var allNetworks = req.result; var networks = {}; for (var i = 0; i < allNetworks.length; ++i) { var network = allNetworks[i]; // use ssid + capabilities as a composited key var key = network.ssid + '+' + network.capabilities.join('+'); // keep connected network first, or select the highest strength if (!networks[key] || network.connected) { networks[key] = network; } else { if (!networks[key].connected && network.relSignalStrength > networks[key].relSignalStrength) networks[key] = network; } } var networkKeys = Object.getOwnPropertyNames(networks); clear(false); // display network list if (networkKeys.length) { // sort networks by signal strength networkKeys.sort(function(a, b) { return networks[b].relSignalStrength - networks[a].relSignalStrength; }); // add detected networks for (var i = 0; i < networkKeys.length; i++) { var network = networks[networkKeys[i]]; if(countAverage){ if(test[networkKeys[i]]) { test[networkKeys[i]].signalStrength = parseInt(test[networkKeys[i]].signalStrength) + parseInt(network.signalStrength) ; test[networkKeys[i]].count += 1; } else{ var tempnetwork={}; tempnetwork.ssid=network.ssid; tempnetwork.capabilities=network.capabilities; tempnetwork.bssid=network.bssid; tempnetwork.signalStrength=network.signalStrength; tempnetwork.relSignalStrength=network.relSignalStrength; tempnetwork.count=1; test[networkKeys[i]] = tempnetwork; // add composited key to test //console.log("yangliang::"+networkKeys[i]); //console.log("yangliang::"+test[networkKeys[i]].toString()); //console.log("yangliang::"+test[networkKeys[i]].ssid); //console.log("yangliang::"+test[networkKeys[i]].capabilities); //console.log("yangliang::"+test[networkKeys[i]].bssid); //console.log("yangliang::"+test[networkKeys[i]].signalStrength); } console.log("yangliang::"+test[networkKeys[i]].signalStrength); console.log("yangliang::"+test[networkKeys[i]].count); console.log("yangliang::"+Math.round(test[networkKeys[i]].signalStrength/test[networkKeys[i]].count)); } if(!countAverage&&!autoscan) var listItem = newListItem(network, Math.round(test[networkKeys[i]].signalStrength/test[networkKeys[i]].count)); else var listItem = newListItem(network, null); // signal is between 0 and 100, level should be between 0 and 4 var level = Math.min(Math.floor(network.relSignalStrength / 20), 4); //listItem.className = 'wifi-signal' + level; // put connected network on top of list if (isConnected(network)) { listItem.classList.add('active'); listItem.querySelector('small').textContent = _('shortStatus-connected'); list.insertBefore(listItem, infoItem.nextSibling); } else { list.insertBefore(listItem, infoItem); } index[networkKeys[i]] = listItem; // add composited key to index } } else { // display a "no networks found" message if necessary list.insertBefore(newExplanationItem('noNetworksFound'), infoItem); } // display the "Search Again" button list.dataset.state = 'ready'; // auto-rescan if requested if (autoscan) { scanId = window.setTimeout(scan, scanRate); } scanning = false; }; req.onerror = function onScanError(error) { // always try again. scanning = false; window.setTimeout(scan, scanRate); }; }
[ "listNetworks() {\n return this.sendCmd(WPA_CMD.listNetwork);\n }", "function scan(config){\n cli.info(\"NETWORK FULL SCAN STARTED\\n\");\n _.each(_.keys(SPTree) , function(fromLan){\n _.each(_.keys(SPTree[fromLan]) , function(toLan){\n if (fromLan != toLan){\n doPathMeasures(fromLan , toLan);\n }\n })\n });\n}", "function wlansChannel(){\n var pushstream = new PushStream({\n host: window.location.hostname,\n port: window.location.port,\n modes: GUI.mode\n });\n pushstream.onmessage = listWLANs;\n pushstream.addChannel('wlans');\n pushstream.connect();\n $.ajax({\n url: '/command/?cmd=wifiscan',\n cache: false\n });\n}", "scanResults() {\n return this.sendCmd(WPA_CMD.scanResult);\n }", "function getAllSelectedManageConnectivity(){\n\t$('#deviceLeft').children('li').each(function () {\n\t\tvar selected_index = $(this).index();\n\t\tvar type = $('#deviceLeft li').eq(selected_index).attr('portType');\n\t\tvar pLeftObjPath = $('#deviceLeft li').eq(selected_index).attr('data-name');\n\t\tvar pRightObjPath = $('#deviceRight li').eq(selected_index).attr('data-name');\n\t\t/* to get the sourceDEvice */\n\t\tif (pRightObjPath == undefined || pRightObjPath == null || pRightObjPath == \"\"){\n\t\t\treturn;\n\t\t}\n\t\tvar rObj = pRightObjPath.split(\".\");\n\t\tvar destinationDevice = rObj[0];\n\t\t/* to get the destinationDEvice */\n\t\tvar lObj = pLeftObjPath.split(\".\");\n\t\tvar sourceDevice = lObj[0];\n\t\tvar condition = checkPortTypeMatch(selected_index, type, pLeftObjPath)\n\t\tif (condition == true && $('#deviceLeft li a').eq(selected_index).hasClass('highlight'))\n\t\t\tpushToLineConnect(selected_index,type,pLeftObjPath,destinationDevice,sourceDevice);\n\t});\t\n\n}", "scan(){\n // TODO : scan for new devices\n let ret=\"\", dev=[], device=null,re=null,id=null;\n\n this.count = 0;\n if(this.Bridges.ADB.isReady()){\n dev = this.Bridges.ADB.listDevices();\n this.count += dev.length;\n\n for(let i in dev){\n this.devices[dev[i].id] = dev[i];\n }\n ut.msgBox(\"Android devices\", Object.keys(this.devices));\n }\n\n // TODO : add SDB and others type of bridge\n \n if(this.count==1){\n this.setDefault(dev[0].id);\n }\n }", "scanForAllDevices() {\n if (this.btDevicesToPing.length <= 0) {\n // console.log(`[${new Date()}] no BT devices to ping`);\n } else {\n // console.log(`[${new Date()}] scanning for presence of any of ${this.btDevicesToPing.length} BT devices`);\n\n // scan for each device\n _.forEach(this.btDevicesToPing, (macAddress) => {\n this.pingBluetoothDevice(macAddress, this.onPingResult.bind(this));\n });\n }\n\n // sleep for interval and then repeat the scan\n this.nextScanTimer = setTimeout(this.scanForAllDevices.bind(this), this.scanIntervalSecs * 1000);\n }", "checkNetwork(network){}", "function nicsDetails(text) {\n var i = 0, content = '', nics = text[0];\n // console.log(nics);\n $.each(nics, function(i) {\n if (i === $('#nic-details').data('name')) {\n content += '<tr><th>Name:</th><td><strong>' + i + '<strong></td></tr>';\n content += '<tr><th>Type:</th><td>wireless</td></tr>';\n if (nics[i].currentssid === null) {\n content += '<tr><th>Status:</th><td><i class=\"fa fa-times red sx\"></i>no network connected</td></tr>';\n } else {\n content += '<tr><th>Status:</th><td><i class=\"fa fa-check green sx\"></i>connected</td></tr>';\n content += '<tr><th>Associated SSID:</th><td><strong>' + nics[i].currentssid + '</strong></td></tr>';\n }\n \n content += '<tr><th>Assigned IP:</th><td>' + ((nics[i].ip !== null) ? ('<strong>' + nics[i].ip + '</strong>') : 'none') + '</td></tr>';\n content += '<tr><th>Speed:</th><td>' + ((nics[i].speed !== null) ? nics[i].speed : 'unknown') + '</td></tr>';\n if (nics[i].currentssid !== null) {\n content += '<tr><th>Netmask:</th><td>' + nics[i].netmask + '</td></tr>';\n content += '<tr><th>Gateway:</th><td>' + nics[i].gw + '</td></tr>';\n content += '<tr><th>DNS1:</th><td>' + nics[i].dns1 + '</td></tr>';\n content += '<tr><th>DNS2:</th><td>' + nics[i].dns2 + '</td></tr>';\n }\n }\n });\n $('#nic-details tbody').html(content);\n}", "function getWifiInfo(callback){\r\n\tjQuery.getJSON( 'APIS/returnWifiJSON.txt', \r\n\t\t\tfunction(returnData, status){\r\n\t\t\t\tif(returnData.RETURN.success){\r\n\t\t\t\t\tcallback(returnData.RETURN.success,returnData);\r\n\t\t\t\t}else{\r\n\t\t\t\t\tcallback(returnData.RETURN.success,returnData.RETURN.errorDescription);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t);\r\n}", "function scan() {\n clear();\n var storages = navigator.getDeviceStorages('sdcard');\n var cursor = enumerateAll(storages, '');\n\n cursor.onsuccess = function() {\n var file = cursor.result;\n if (file) {\n var extension = _parseExtension(file.name);\n var cerExtension = ['cer', 'crt', 'pem', 'der'];\n if (cerExtension.indexOf(extension) > -1) {\n certificateFiles.push(file);\n\n var a = document.createElement('a');\n a.textContent = _parseFilename(file.name);\n var inputNickname =\n document.getElementById('certificate-file-nickname');\n a.onclick = function settingsNicknameForImportCertificateFile() {\n // given a default nickname from filename\n inputNickname.value = a.textContent;\n openDialog('wifi-enterCertificateNickname', function submit() {\n var certRequest = gWifiManager.importCert(file,\n '',\n inputNickname.value);\n // Gray out all item of certificate files\n // since we are importing other file.\n var items = list.querySelectorAll('li');\n for (var i = 0; i < items.length; i++) {\n items[i].classList.add('disabled');\n }\n\n certRequest.onsuccess = function() {\n // direct dialog to \"wifi-manageCertificates\"\n Settings.currentPanel = '#wifi-manageCertificates';\n // scan certificate list again\n // while the panel is ready #wifi-manageCertificates\n // dispatch event for gCertificateList.scan();\n dispatchEvent(new CustomEvent('certificate-imported'));\n };\n certRequest.onerror = function() {\n // Pop out alert message for certificate import failed\n var dialog =\n document.getElementById('certificate-import-failed');\n dialog.hidden = false;\n dialog.onsubmit = function confirm() {\n dialog.hidden = true;\n };\n // Re-enable all items of certificate files\n // since import file process is completed.\n var items = list.querySelectorAll('li');\n for (var i = 0; i < items.length; i++) {\n if (items[i].classList.contains('disabled'))\n items[i].classList.remove('disabled');\n }\n };\n });\n };\n var li = document.createElement('li');\n li.appendChild(a);\n list.appendChild(li);\n }\n\n cursor.continue();\n }\n };\n cursor.onerror = function() {\n var msg = 'failed to get file:' +\n cursor.error.name;\n console.warn(msg);\n };\n }", "function Network_networkOverview() {\n UCapManager.startScheduler({func:'Network_Overview_householdUsage', scope:\"element\", freq:1000});\n var dataArray = [];\n for (var i in UCapCore.devices)\n { for(var j = 0, k = UCapCore.devices[i].length; j < k; j++){\n var devicename = UCapCore.devices[i][j][1];\n var deviceusage = (UCapCore.devices[i][j][6]/1048576);\n dataArray.push([devicename,deviceusage]);\n }\n }\n UCapViz.drawChart({tar:'chartarea',data:dataArray});\n}", "function updateNetworkState() {\n var networkStatus = gWifiManager.connection.status;\n\n // networkStatus has one of the following values:\n // connecting, associated, connected, connectingfailed, disconnected.\n\n if (networkStatus === 'connectingfailed' && gCurrentNetwork) {\n settings.createLock().set({'wifi.connect_via_settings': false});\n // connection has failed, probably an authentication issue...\n delete(gCurrentNetwork.password);\n gWifiManager.forget(gCurrentNetwork); // force a new authentication dialog\n gNetworkList.display(gCurrentNetwork,\n _('shortStatus-connectingfailed'));\n gCurrentNetwork = null;\n }\n\n }", "async scan() {\n try {\n let that = this\n await waitUntil(() => {\n return (that.state === 'poweredOn')\n }, 20000)\n console.log('Starting to scan...')\n return await waitUntil(() => {\n noble.stopScanning()\n if(that.peripherals.length <= 0) {\n console.log('Scanning...')\n noble.startScanning()\n } else {\n console.log('Found ' + that.peripherals.length + ' devices.')\n return that.peripherals\n }\n }, 20000, 4000)\n } catch (err) {\n throw new Error(err)\n }\n }", "function findAndDisplay(event) {\r\n searchBluetoothDevices();\r\n displayDevices();\r\n}", "function getTips() {\n tipsComm = [];\n var temp = coffeeShops[klik].tips;\n for (var i = 0; i < temp.length; i++) {\n var lowerCase = temp[i].text.toLowerCase();\n console.log()\n if (lowerCase.indexOf('WiFi') > -1) {\n tipsComm.push(temp[i].text)\n }\n\n }\n}", "async function readCurrentNetworks(dockerAPI) {\n const currentNetworks = await waitFor(dockerAPI.getCurrentNetworks(), 'getCurrentNetworks');\n console.log('currentNetworks: ', currentNetworks);\n return currentNetworks;\n}", "start() {\n if (this.isL2PingAvailable){\n this.scanForAllDevices().bind(this);\n } else {\n this.checkForL2Ping(this.scanForAllDevices.bind(this));\n }\n }", "search_robots() {\n // if we need to search the network for robots\n if (robots_disp[0] == \"\") {\n // This is where robots and beacons are filtered\n // var patt = /^((?!B).)\\d{1,2}(?!_)/;\n // var handled_names = [];\n\n // for (let i = 0; i < topicsList.length; i++) {\n // console.log(\"Looking for robots on the network\");\n // let name = topicsList[i].split('/')[1];\n\n // if (handled_names.indexOf(name) == -1) {\n // if (patt.test(name) && (name != 'S01')) {\n // console.log('adding ', name, ' from the network');\n // if (_this.robot_name.indexOf(name) == -1) {\n // _this.robot_name.push(name);\n // _this.tabs_robot_name.push(name);\n // _this.x++;\n \n // }\n // }\n // handled_names.push(name);\n // }\n // }\n\n // Make decision of what to do with this improved system\n let topics = topicsList.filter(x => !handled_topics.includes(x));\n\n for (let i = 0; i < topics.length; i++) {\n // console.log(\"Looking for robots on the network\");\n if(topics[i].includes(ma_prefix) && topics[i].includes('odometry')){\n \n // reg ex patern for good robot names\n var patt = /\\b[A, C-R, T-Z]\\d{1,2}(?!_)\\b/i;\n let results = topics[i].match(patt);\n if(results){\n name = results[0];\n console.log('adding ', name, ' from the network');\n if (global_tabManager.robot_name.indexOf(name) == -1) {\n global_tabManager.robot_name.push(name);\n global_tabManager.tabs_robot_name.push(name);\n global_tabManager.x++;\n \n }\n }\n }\n handled_topics.push(topics[i]);\n }\n\n // If we can get robots from launch file\n } else {\n for (let i = 0; i < robots_disp.length; i++) {\n name = robots_disp[i];\n if (global_tabManager.robot_name.indexOf(name) == -1) {\n global_tabManager.robot_name.push(name);\n global_tabManager.tabs_robot_name.push(name);\n global_tabManager.x++;\n }\n }\n }\n\n let curr_robot_length = global_tabManager.robot_name.length; // Length of entire robots seen over all time after function\n\n // report robot as \"disconnect\" if it was previously discovered but we are no longer\n // receiving messages from it.\n let now = new Date();\n for (let i = 0; i < curr_robot_length; i++) {\n var battery_disp = $('#battery_' + global_tabManager.robot_name[i]);\n var battery_dom = $('#battery_status_' + global_tabManager.robot_name[i]);\n var color = 'grey';\n if (global_tabManager.battery[i] < 23.1) {\n color = 'red';\n } else if (global_tabManager.battery[i] < 24.5) {\n color = 'orange';\n }\n battery_disp.html('<font color=\"' + color + '\">' + global_tabManager.battery[i] + '</font>');\n battery_dom.html('<font color=\"' + color + '\">' + global_tabManager.robot_name[i] + '</font>');\n\n var status_dom = $('#connection_status_' + global_tabManager.robot_name[i]);\n if (global_tabManager.incomm[i]) {\n status_dom.html('<font color=\"green\">Connected</font>');\n }\n else {\n status_dom.html('<font color=\"red\">Disconnected</font>');\n }\n\n var task = '';\n var task_dom = $('#task_status_' + global_tabManager.robot_name[i]);\n var full_task = global_tabManager.tasks[i];\n if (full_task) {\n var tasks = full_task.split('+++');\n task = tasks[0];\n pubTask(task_dom, tasks, 1);\n }\n if (task == \"Home\") {\n task_dom.html('<font color=\"yellow\">Going Home</font>');\n } else if (task == \"Report\") {\n task_dom.html('<font color=\"yellow\">Reporting</font>');\n } else if (task == \"Deploy\") {\n task_dom.html('<font color=\"yellow\">Deploying Beacon</font>');\n } else if (task == \"Stop\") {\n task_dom.html('<font color=\"red\">Stopped</font>');\n } else if (task == \"Explore\") {\n task_dom.html('<font color=\"green\">Exploring</font>');\n } else if (task == \"guiCommand\") {\n task_dom.html('<font color=\"green\">GUI Goal</font>');\n } else {\n if (task == undefined) task = '';\n task_dom.html('<font color=\"red\">' + task + '</font>');\n }\n }\n\n for (global_tabManager.i; global_tabManager.i < curr_robot_length; global_tabManager.i++) {\n global_tabManager.add_tab();\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Disable all custom editors
function wrs_int_disableCustomEditors(){ Object.keys(_wrs_int_customEditors).forEach(function(key) { _wrs_int_customEditors[key].enabled = false; }); }
[ "SetExcludeEditorFromAnyPlatform() {}", "GetExcludeEditorFromAnyPlatform() {}", "function disableEditing() {\n disableForm(true);\n}", "disablePlugin() {\n this.settings = {};\n this.hiddenColumns = [];\n this.lastSelectedColumn = -1;\n\n this.hot.render();\n super.disablePlugin();\n this.resetCellsMeta();\n }", "function check_block_editor(doc, elem) {\n if (doc.editor != phila.editor.editor_id) {\n elem.find('input').prop('disabled', true);\n elem.find('textarea').prop('disabled', true);\n elem.find(':not(.block-edit)').fadeTo(0, 0.75);\n elem.find(':not(.block-edit)').addClass('disabled');\n }\n else {\n elem.find('input').removeProp('disabled');\n elem.find('textarea').removeProp('disabled');\n elem.find('*').removeClass('disabled');\n elem.find('*').fadeTo(0, 1);\n }\n}", "function disableme() {\n\tvar itms = getDisabledItems();\n\tfor(i=0; i< itms.length; i++) \n\t{\n\t\titms[i].readOnly = true;\n }\n}", "function disableAllButtons() {\n disableOrEnableButtons(false);\n }", "function revokeCustomTinyMceTextEditorPopup() {\n\thideModel('editorPopUp');\n}", "onHideEditorPanel()\n\t{\n\t\tthis.#postInternalCommand('onHideEditorPanel');\n\t}", "SetCompatibleWithEditor() {}", "function generateEditors() {\n for (var i=0; i<editorInstances.length; i++) {\n var editInst = editorInstances[i];\n editInst.ReplaceTextarea();\n }\n}", "hideEditor() {\n if (this._editor.active) {\n this._editor.active = false;\n\n $('#monaco').hide();\n\n $('#file-tabs-placeholder').show();\n $('#editor-placeholder').show();\n }\n }", "function revokeCustomtextEditorPopup() {\n\thideModel('editorPopUp');\n\t// Richfaces.hideModalPanel('customtextEditorPanel');\n}", "function disableMainPageButtons() {\n\t\t\tevents.forEach( ev => { \n\t\t\t\tev.button.mouseEnabled = false;\n\t\t\t\tev.button.cursor = \"default\";\n\t\t\t});\n\t\t\n\t\t\tcultures.forEach( cu => { \n\t\t\t\tcu.button.mouseEnabled = false;\n\t\t\t\tcu.button.cursor = \"default\";\n\t\t\t});\n\t\t\n\t\t\tself.aboutUsBtn.mouseEnabled = false;\n\t\t\tself.aboutUsBtn.cursor = \"default\";\n\t\t\n\t\t\tself.returnBtn.mouseEnabled = false;\n\t\t\tself.returnBtn.cursor = \"default\";\n\t\t}", "disable() {\n this.clearSelection();\n this._removeMouseDownListeners();\n this._enabled = false;\n }", "function changeCodeblockButtons(enabled) {\r\n if (enabled) {\r\n jQuery(\"#codeblock_add\").button(\"enable\");\r\n jQuery(\"#codeblock_save\").button(\"enable\");\r\n jQuery(\"#codeblock_remove\").button(\"enable\");\r\n jQuery(\"#codeblock_reset\").button(\"enable\");\r\n } else {\r\n jQuery(\"#codeblock_add\").button(\"disable\");\r\n jQuery(\"#codeblock_save\").button(\"disable\");\r\n jQuery(\"#codeblock_remove\").button(\"disable\");\r\n jQuery(\"#codeblock_reset\").button(\"disable\");\r\n }\r\n}", "function disable_button() {\n allow_add = false;\n}", "function makeReadOnlyContentCopyable() {\n try {\n if (typeof g_glideEditorArray != 'undefined' && g_glideEditorArray instanceof Array) {\n for (var i = 0; i < g_glideEditorArray.length; i++) {\n if (g_glideEditorArray[i].editor.getOption('readOnly') == 'nocursor')\n g_glideEditorArray[i].editor.setOption('readOnly', true);\n }\n }\n } catch (error) {\n console.error(error)\n }\n}", "_updateEditorConfig() {\n for (let i = 0; i < this.widgets.length; i++) {\n const cell = this.widgets[i];\n let config;\n switch (cell.model.type) {\n case 'code':\n config = this._editorConfig.code;\n break;\n case 'markdown':\n config = this._editorConfig.markdown;\n break;\n default:\n config = this._editorConfig.raw;\n break;\n }\n let editorOptions = {};\n Object.keys(config).forEach((key) => {\n var _a;\n editorOptions[key] = (_a = config[key]) !== null && _a !== void 0 ? _a : null;\n });\n cell.editor.setOptions(editorOptions);\n cell.editor.refresh();\n }\n }", "function exportEditor(editor) {\n if (!window.codeEditors) window.codeEditors = [];\n if (!window.codeEditors.includes(editor)) window.codeEditors.push(editor);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a control to this group. This method also updates the value and validity of the control.
addControl(name, control) { this.registerControl(name, control); this.updateValueAndValidity(); this._onCollectionChange(); }
[ "function addControl(ctrl, cType, options) {\n for (var i = 0; i < p.controls.length; ++i) {\n if (p.controls[i].control == ctrl) {\n console.warn(\"Already added control: %o\", ctrl);\n return;\n }\n }\n\n options = options || {};\n\n var ctrlData = { control: ctrl, elements: [], controlType: cType }\n p.controls.push(ctrlData);\n\n var addControlTo = function (cntr) {\n if (cntr == 'container') {\n cntr = options.container || dom.find('container');\n if (typeof cntr == 'string') { cntr = document.getElementById(cntr); }\n if (!cntr.dom) { dom.claim(cntr, 'controlContainer'); }\n } else if (cntr == 'overlay') {\n cntr = dom.find('overlay');\n }\n if (typeof ctrl.createControlElements != 'function') { return; }\n var ctrlElem = ctrl.createControlElements(cntr);\n if (!ctrlElem) { return; }\n cntr.appendChild(ctrlElem);\n ctrlData.elements.push(ctrlElem);\n Monocle.Styles.applyRules(ctrlElem, Monocle.Styles.control);\n return ctrlElem;\n }\n\n if (!cType || cType == 'standard' || cType == 'invisible') {\n addControlTo('container');\n } else if (cType == 'page') {\n forEachPage(addControlTo);\n } else if (cType == 'modal' || cType == 'popover' || cType == 'hud') {\n addControlTo('overlay');\n ctrlData.usesOverlay = true;\n } else if (cType == 'invisible') {\n addControlTo('container');\n } else {\n console.warn('Unknown control type: ' + cType);\n }\n\n if (options.hidden) {\n hideControl(ctrl);\n } else {\n showControl(ctrl);\n }\n\n if (typeof ctrl.assignToReader == 'function') {\n ctrl.assignToReader(API);\n }\n\n return ctrl;\n }", "addEmptyControl() {\n let control = FdEditformControl.create({\n caption: `${this.get('i18n').t('forms.fd-editform-constructor.new-control-caption').toString()} #${this.incrementProperty('_newControlIndex')}`,\n type: 'string',\n propertyDefinition: FdViewAttributesProperty.create({\n name: '',\n visible: true,\n }),\n });\n\n this._insertItem(control, this.get('selectedItem') || this.get('controlsTree'));\n this.send('selectItem', control, true);\n scheduleOnce('afterRender', this, this._scrollToSelected);\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 }", "addControls () {\n /**\n * @type {ControlsConfig}\n */\n this.controlsConfig = this.map_.get('mapConfig').controls\n if (checkFor(this.controlsConfig, 'onMap')) {\n this.addControlMultipleInternal_(this.map_, this.controlsConfig.onMap)\n }\n }", "add(from, to, value) {\n if (!this.addInner(from, to, value))\n (this.nextLayer || (this.nextLayer = new RangeSetBuilder())).add(\n from,\n to,\n value\n )\n }", "function insertControlRowToTable() {\r\n\t// find the TBODY pointer\r\n\tvar tbodyPointer = findTBodyPointer();\r\n\tif (tbodyPointer == null){ return false; }\r\n\r\n\t// add control Row as first in tbody\r\n\tvar newRow = tbodyPointer.insertRow(0);\r\n\tnewRow.setAttribute(\"class\", \"dynTable_ControlRow\");\r\n\t\r\n\t// insert new row for all columns\r\n\tfor (var i=0; i <dynTable_numOfColumns; i++) {\r\n\t\tvar newCell = newRow.insertCell(i);\r\n\t\tnewCell.setAttribute(\"class\", \"dynTable_ControlCells\");\r\n\t\tcreateCellOfControlRow(newCell, i);\r\n\t\t//newCell.appendChild(cellNode);\r\n\t}\r\n\r\n\r\n\treturn true;\r\n}", "function addInput(_, optionalValue) {\n const node = createInput(optionalValue);\n byId('options').appendChild(node);\n}", "function validateAddLine(collectionGroupId, addViaLightbox) {\n var collectionGroup = jQuery(\"#\" + collectionGroupId);\n var addControls = collectionGroup.data(kradVariables.ADD_CONTROLS);\n\n if (addViaLightbox) {\n collectionGroup = jQuery(\"#kualiLightboxForm\");\n }\n\n var controlsToValidate = jQuery(addControls, collectionGroup);\n\n var valid = validateLineFields(controlsToValidate);\n if (!valid) {\n if (!addViaLightbox) {\n showClientSideErrorNotification();\n }\n\n return false;\n }\n\n return true;\n}", "showControl(control) {\n // construct replacements\n let textReplacements = new Map([\n ['controlsText', control.txt],\n ]);\n // show GUI and bookkeep\n this.guiEnts.push(...this.ecs.getSystem(System.GUIManager)\n .runSequence('controls', textReplacements));\n }", "function LightControl(controlDiv, map) {\n controlDiv.style.padding = '30px';\n\n // Set CSS for the control border\n var controlUI = document.createElement('div');\n controlUI.style.backgroundColor = 'white';\n controlUI.style.borderStyle = 'solid';\n controlUI.style.borderWidth = '2px';\n controlUI.style.cursor = 'pointer';\n controlUI.style.textAlign = 'center';\n controlUI.title = 'Click to create a new light at the cursor position';\n controlDiv.appendChild(controlUI);\n\n // Set CSS for the control interior\n var controlText = document.createElement('div');\n controlText.style.fontFamily = 'Arial,sans-serif';\n controlText.style.fontSize = '14px';\n controlText.style.paddingLeft = '8px';\n controlText.style.paddingRight = '8px';\n controlText.innerHTML = '<b>Add Light</b>';\n controlUI.appendChild(controlText);\n\n google.maps.event.addDomListener(controlUI, 'click', function() {\n createLight();\n });\n }", "_addSlot() {\n if (this[_value]) {\n this[_fillElement].appendChild(this[_slotElement]);\n } else {\n this[_trackElement].appendChild(this[_slotElement]);\n }\n }", "_addControlToLinkedDisplays(ctrlItem) {\n const displays = this._findLinkedDisplays(true);\n for (const display of displays) {\n display.addControlFromResource(ctrlItem.resource());\n }\n }", "function TKR_addMultiFieldValueWidget(\n el, field_id, field_type, opt_validate_1, opt_validate_2) {\n var widget = document.createElement('INPUT');\n widget.name = 'custom_' + field_id;\n if (field_type == 'str') {\n widget.size = 90;\n }\n if (field_type == 'user') {\n widget.style = 'width:12em';\n widget.classList.add('userautocomplete');\n widget.classList.add('customfield');\n widget.classList.add('multivalued');\n widget.addEventListener('focus', function(event) {\n _acrob(null);\n _acof(event);\n });\n }\n if (field_type == 'int' || field_type == 'date') {\n widget.style.textAlign = 'right';\n widget.style.width = '12em';\n widget.min = opt_validate_1;\n widget.max = opt_validate_2;\n }\n if (field_type == 'int') {\n widget.type = 'number';\n } else if (field_type == 'date') {\n widget.type = 'date';\n }\n\n el.parentNode.insertBefore(widget, el);\n\n var del_button = document.createElement('U');\n del_button.onclick = function(event) {\n _removeMultiFieldValueWidget(event.target);\n };\n del_button.textContent = 'X';\n el.parentNode.insertBefore(del_button, el);\n}", "function AddItem(Text, Value, control) {\n // Create an Option object \n var opt = document.createElement(\"option\");\n var obj = document.getElementById(control); // Drop Down control object\n\n // Assign text and value to Option object\n opt.text = Text;\n opt.value = Value;\n \n // Add an Option object to Drop Down/List Box\n obj.options.add(opt);\n \n\n obj.selectedIndex = obj.options.length - 1; // focusing again to new value added in drop down control\n obj.options[obj.options.length - 1].selected=true;\n obj.value=Value;\n \n //$(obj).addClass(\"focus\");\n \n}", "function XFormRepeatControl(element, bind, innerControls, number) {\r\n assert(bind != null, \"repeat: bind is null\");\r\n assert(innerControls != null, \"repeat: innerControls is null\");\r\n \r\n XFormControl.call(this, element, bind, innerControls);\r\n \r\n this.number = number;\r\n this.index = 0;\r\n}", "function attachDataToControls() {\n this.controls.data = this.initial_data;\n this.controls.ready = true;\n }", "function addControls() {\n // Add home button\n L.easyButton(\n \"fa-home\",\n function (btn, map) {\n map.setView([home.lat, home.lng], home.zoom);\n },\n \"Zoom To Home\",\n { position: \"topright\" }\n ).addTo(myMap);\n\n // Reposition the zoom control\n myMap.zoomControl.setPosition(\"topright\");\n\n // Add a fullscreen toggle\n myMap.addControl(new L.Control.Fullscreen({ position: \"topright\" }));\n\n // Add scale bar\n L.control.betterscale().addTo(myMap);\n}", "function insertAtContainedControlsOnForm(container, index, control) {\n var controls;\n\n controls = container.containedControlsOnForm.slice(0);\n controls.splice(index, 0, control);\n container.containedControlsOnForm = controls;\n }", "function pressAdd() {\n\thandleAddSub(PLUS);\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}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Chapter 6 Yuki Check to Stop
function C006_Isolation_Yuki_CheckToStop() { // Yuki doesn't allow the player to stop if she has the egg if (C006_Isolation_Yuki_EggInside) { OverridenIntroText = GetText("NoPullEgg"); C006_Isolation_Yuki_CurrentStage = 200; C006_Isolation_Yuki_AllowPullBack = false; } // Yuki doesn't allow the player to stop if she's dominant if (ActorGetValue(ActorSubmission) <= -3) { OverridenIntroText = GetText("NoPullSub"); C006_Isolation_Yuki_CurrentStage = 200; C006_Isolation_Yuki_AllowPullBack = false; } }
[ "stop() {\n this.target = undefined;\n // @ts-expect-error\n const pathfinder = this.bot.pathfinder;\n pathfinder.setGoal(null);\n // @ts-expect-error\n this.bot.emit('stoppedAttacking');\n }", "function stopGame(){\n\tresetGame();\n\tgoPage('result');\n}", "function stopSnippet(){\n return playSong.pause();\n }", "function runPauseResumeStopTests() {\n //run all tests without an instance running\n try {\n ap.stopAllSounds();\n assert.ok(true, \"stopAllSounds(): no instance running\");\n }\n catch (e) {\n assert.ok(false, \"stopAllSounds(): no instance running\");\n }\n\n try {\n ap.stopSound(\"instanceId\");\n assert.ok(true, \"stopSound(): no instance running\");\n }\n catch (e) {\n assert.ok(false, \"stopSound(): no instance running\");\n }\n\n try {\n ap.pauseAllSounds();\n assert.ok(true, \"pauseAllSounds(): no instance running\");\n }\n catch (e) {\n assert.ok(false, \"pauseAllSounds(): no instance running\");\n }\n\n try {\n ap.resumeAllSounds();\n assert.ok(true, \"resumeAllSounds(): no instance running\");\n }\n catch (e) {\n assert.ok(false, \"resumeAllSounds(): no instance running\");\n }\n\n runPauseTest();\n }", "function stopHeartbeat() {\n\tGAME_OVER = true;\n\taddMessage(\"Game over! Score: &e0\", \"error\");\n\tdelete_cookie(\"chocolateChipCookie\");\n\tclearInterval(nIntervId);\n}", "function stopSeries(err) {\n if(err instanceof Error || (typeof err === 'object' && (err.code || err.error))) {\n stopErr = err;\n }\n isStopped = true;\n }", "function endPhaseConditions(){\r\n\r\n if (killerCountSetup == 0 || userKilled || totalFuel == userScore + computerScore || fuel == 0){\r\n return false;\r\n }\r\n else{\r\n return true;\r\n }\r\n}", "function maybeHalt() {\n taskEnding();\n maybeExit();\n return null;\n}", "exitDoWhileExpression(ctx) {\n\t}", "exitStatementNoShortIf(ctx) {\n\t}", "async stop() {\n var _a;\n if (this.pollingRunning) {\n debug('Stopping bot, saving update offset');\n this.pollingRunning = false;\n (_a = this.pollingAbortController) === null || _a === void 0 ? void 0 : _a.abort();\n await this.api.getUpdates({ offset: this.lastTriedUpdateId + 1 });\n this.pollingAbortController = undefined;\n }\n else {\n debug('Bot is not running!');\n }\n }", "_terminate() {\n console.log(\"terminate\");\n /*if (this.state !== or === ? GameStates.Terminating) {\n return; //error\n }*/\n\n this.state = GameStates.Terminating;\n clearTimeout(this.tick);\n this._clearTurn();\n this.destroy();\n }", "function stopLoop() {\n clearInterval (Defaults.game.handle);\n }", "stop() {\n if (!this.stopped) {\n for (let timeout of this.timeouts) {\n clearTimeout(timeout);\n }\n clearTimeout(this.mainLoopTimeout);\n this.stopped = true;\n }\n }", "exitLoopExpression(ctx) {\n\t}", "exitWhileExpression(ctx) {\n\t}", "function stopCountdown() {\n clearInterval(nIntervId);\n}", "function C006_Isolation_Yuki_CheckToEat() {\n\t\n\t// Yuki forces the player if she has the egg\n\tif (C006_Isolation_Yuki_EggInside) {\n\t\tOverridenIntroText = GetText(\"LickEgg\");\n\t\tGameLogAdd(\"Pleasure\");\n\t\tC006_Isolation_Yuki_CurrentStage = 200;\n\t}\n\n\t// Yuki forces the player if she's dominant\n\tif (ActorGetValue(ActorSubmission) <= -3) {\n\t\tOverridenIntroText = GetText(\"LickSub\");\n\t\tGameLogAdd(\"Pleasure\");\n\t\tC006_Isolation_Yuki_CurrentStage = 200;\n\t}\n\n}", "function stop_tcpdump(){\n\tobject.AGNetworkTookitTcpdump(stop_succeed_back, stop_error_back, 1, null);\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines the number of bits required to encode the number represented in the given buffer as an unsigned value. The buffer is taken to represent an unsigned number in littleendian form. The number of bits to encode is the (zerobased) bit number of the highestorder 1 bit, plus one. For example: 00011000 01010011 high low The highestorder 1 bit here is bit 12 (where the lowestorder bit is bit 0). So, we have to encode at least 13 bits total. As a special degenerate case, the number 0 requires 1 bit.
function unsignedBitCount(buffer) { var result = bits.highOrder(1, buffer) + 1; return result ? result : 1; }
[ "function encodeIntoByteBuffer(buffer) {\n var self = this;\n var initialPosition = buffer.position;\n buffer.putInt32(encodingCookie);\n buffer.putInt32(0); // Placeholder for payload length in bytes.\n buffer.putInt32(1);\n buffer.putInt32(self.numberOfSignificantValueDigits);\n buffer.putInt64(self.lowestDiscernibleValue);\n buffer.putInt64(self.highestTrackableValue);\n buffer.putInt64(1);\n var payloadStartPosition = buffer.position;\n fillBufferFromCountsArray(self, buffer);\n var backupIndex = buffer.position;\n buffer.position = initialPosition + 4;\n buffer.putInt32(backupIndex - payloadStartPosition); // Record the payload length\n buffer.position = backupIndex;\n return backupIndex - initialPosition;\n}", "function bufferToBigInt(buf) {\n return BigInt('0x' + bufferToHex(buf))\n}", "function $fb1c7bd82eb4c0c48c74268ddc57b$var$NextTableBitSize(count, len, root_bits) {\n var left = 1 << len - root_bits;\n\n while (len < $fb1c7bd82eb4c0c48c74268ddc57b$var$MAX_LENGTH) {\n left -= count[len];\n if (left <= 0) break;\n ++len;\n left <<= 1;\n }\n\n return len - root_bits;\n }", "function countTheBits(num) {\n\tlet numString;\n\tnumString = num.toString(2)\n\tlet result = 0;\n\tfor (let i = 0; i < numString.length; i++) {\n // console.log(numString[i])\n if(numString[i] == 1){\n result += 1\n }\n \n }\n\n\treturn result;\n}", "function limitBitsNumber(value) {\r\n\r\n if (value > 32) {\r\n\r\n return Math.floor(value / 10);\r\n } else {\r\n return value;\r\n }\r\n}", "static checkBitmask(bitLength, buffer) {\n const bits = new Uint1Array(buffer.buffer)\n const checkBits = bits.slice(0, bitLength)\n\n return checkBits[0] == 0 && (checkBits.indexOf(1) >= bitLength - 1 || checkBits.indexOf(1) == -1)\n }", "function bitCount(msg, encoding) {\n\tif (defs.encodings[encoding] === undefined) {\n\t\tencoding = defs.encodings.detect(msg);\n\t}\n\n\tif (encoding === 'ASCII') {\n\t\treturn defs.encodings.ASCII.encode(msg).length * 7; // * 7 since each character takes up 7 bits\n\t} else {\n\t\treturn defs.encodings.UCS2.encode(msg).length * 8; // * 8 since its encoded as 16-bits.\n\t}\n}", "static fromBuffer(buffer: Buffer): u64 {\n assert(buffer.length === 8, `Invalid buffer length: ${buffer.length}`);\n return new BN(\n [...buffer]\n .reverse()\n .map(i => `00${i.toString(16)}`.slice(-2))\n .join(''),\n 16,\n );\n }", "static uint88(v) { return n(v, 88); }", "function maskLength(mask, count) {\n if (mask) {\n /*jshint bitwise:false*/\n mask >>>= count;\n /*jshint bitwise:true*/\n return (Math.log(mask + 1) / Math.log(2));\n }\n return 0;\n}", "function calcVariableByteIntLength(length) {\n if (length >= 0 && length < 128) return 1;else if (length >= 128 && length < 16384) return 2;else if (length >= 16384 && length < 2097152) return 3;else if (length >= 2097152 && length < 268435456) return 4;else return 0;\n}", "static bytes31(v) { return b(v, 31); }", "bitCount() {\n let result = 0;\n for(let i = 0; i < this.array.length; i++){\n result += BitSet.countBits(this.array[i]) // Assumes we never have bits set beyond the end\n ;\n }\n return result;\n }", "add(key) {\n const indices = this.calculateBitIndices(key);\n let numAlreadySet = 0;\n\n for (let i = 0; i < indices.length; i += 1) {\n const counterValue = this.bitArray[indices[i]];\n if (counterValue > 0) {\n numAlreadySet += 1;\n }\n\n // Only increment the counter if we aren't going to overflow the integer.\n if (!(counterValue >= this.maxValue)) {\n this.bitArray[indices[i]] += 1;\n }\n }\n\n if (numAlreadySet < indices.length) {\n this.count += 1;\n }\n }", "function toBigendianUint64BytesUnsigned(i, bufferResponse = false) {\n let input = i\n if (!Number.isInteger(input)) {\n input = parseInt(input, 10)\n }\n\n const byteArray = [0, 0, 0, 0, 0, 0, 0, 0]\n\n for (let index = 0; index < byteArray.length; index += 1) {\n const byte = input & 0xFF // eslint-disable-line no-bitwise\n byteArray[index] = byte\n input = (input - byte) / 256\n }\n\n byteArray.reverse()\n\n if (bufferResponse === true) {\n const result = Buffer.from(byteArray)\n return result\n }\n const result = new Uint8Array(byteArray)\n return result\n}", "function getIPCount(bitCount) {\r\n\r\n valor = 32 - bitCount;\r\n return Math.pow(2, valor);\r\n\r\n}", "function size (buffer) {\r\n validate(buffer);\r\n\r\n return buffer.numberOfChannels * buffer.getChannelData(0).byteLength;\r\n}", "static uint112(v) { return n(v, 112); }", "function _getMessage(buffer /*: Buffer*/) /*: Array<BigInt>*/ {\n const words = [];\n let word = 0n;\n let byteLen = 0n;\n for (const c of buffer) {\n const b = byteLen++ & 0x7n;\n word |= BigInt(c) << (b << 3n);\n if (byteLen % 8n == 0n) {\n words.push(word);\n word = 0n;\n }\n }\n // Store original size (in bits)\n const bitSize = (byteLen << 3n) & U64;\n\n // Pad our message with a byte of 0x1 ala MD4 (Tiger1) padding\n const b = byteLen & 0x7n;\n if (b) {\n word |= 0x1n << (b << 3n);\n words.push(word);\n byteLen += 8n - b;\n } else {\n words.push(0x1n);\n byteLen += 8n;\n }\n\n for (byteLen %= 64n; byteLen < 56n; byteLen += 8n) {\n words.push(0n);\n }\n words.push(bitSize);\n return words;\n}", "static bytes28(v) { return b(v, 28); }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Requests a product. Use this to get the information you have set up in iTunesConnect, like the localized name and price for the current user.
function requestProduct(identifier, success) { showLoading(); Storekit.requestProducts([identifier], function (evt) { hideLoading(); if (!evt.success) { alert(L("ERROR_We_failed_to_talk_to_Apple_")); } else if (evt.invalid) { alert(L("ERROR_We_requested_an_invalid_product_")); } else { success(evt.products[0]); } }); }
[ "function askProduct() {\n inquirer.prompt([\n {\n type: \"list\",\n name: \"productPrompt\",\n message: \"What is the ID of the product you want to buy?\",\n choices: productIDs\n }\n ]).then(({ productPrompt }) => {\n connection.query(\"SELECT * FROM products WHERE item_id = ?\", [productPrompt], function (err, res) {\n if (err) throw err;\n console.log(chalk.blue(\"You have chosen: \") + chalk.magenta(res[0].product_name));\n //temporarily storing all the following information so that we can later pass it into the object constructor function\n currentItemName = res[0].product_name;\n currentItemID = res[0].item_id;\n currentItemPrice = res[0].price;\n availbleUnits = res[0].stock_quantity;\n //calls checkProduct function to ensure selection is correct\n checkProduct();\n });\n });\n}", "static async fetchProductById(productId) {\n const product = storage\n .get(\"products\")\n .find({ id: Number(productId) })\n .value()\n return product\n }", "async details (product) {\n debug('Getting details for', product)\n const fullDetails = await client.product.fetch(product)\n if (fullDetails) {\n debug(`fullDetails(${product})`, product)\n } else {\n console.error(`Product ${product} doesn't exist in this storefront!`)\n }\n return fullDetails\n }", "function purchaseProduct(product) {\n showInfo('Product purchased.')\n\n\n requester.get('user', sessionStorage.getItem('userId'), 'Kinvey')\n .then((userInfo) => {\n\n userInfo.cart = userInfo.cart || {};\n\n if (userInfo.cart.hasOwnProperty(product._id)) {\n userInfo.cart[product._id].quantity = Number(userInfo.cart[product._id].quantity) + 1;\n } else {\n userInfo.cart[product._id] = {\n quantity: 1,\n product: {\n name: product.name,\n description: product.description,\n price: product.price\n }\n }\n }\n requester.update('user', sessionStorage.getItem('userId'), 'kinvey', userInfo)\n .then(() => {\n showInfo('Product Purchased');\n showViewCart()\n })\n })\n }", "async showOneProduct (req, res) {\n\t\tlet {sku} = req.params;\n\t\ttry {\n\t\t\tconst oneProduct = await products.findOne({SKU:sku});\n\t\t\tres.send(oneProduct);\n\t\t}\n\t\tcatch(e){\n\t\t\tres.send({e});\n\t\t}\n\t}", "async show({ params }) {\n return Product.findProduct(params);\n }", "retreiveProductName() {\n this.waitUtil.waitForElementToBeClickable(\n this.lblProductName,\n 15000,\n \"Product Name\"\n );\n return this.lblProductName.getText();\n }", "function getProductDetails(thisProduct){\n\t\n\tvar product = \"\";\n\t\n\tproduct = {\n\t\t\t\n\t\t\tid : $(thisProduct).parent().parent().find(\"#product_id\").val(),\n\t\t\timagePath : $(thisProduct).parent().parent().find(\".image img\").attr(\"src\"),\n\t\t\tcategory : $(thisProduct).parent().parent().find(\"#category\").val(),\n\t\t\tprice : $(thisProduct).parent().parent().find(\"#price\").text(),\n\t\t\tname : $(thisProduct).parent().parent().find(\".name\").text(),\n\t\t\tmanufacturer : $(thisProduct).parent().parent().find(\".manufacturer\").text(),\n\t\t\tunits : $(thisProduct).parent().parent().find(\"#available\").text(),\n\t\t\tstatus : $(thisProduct).parent().parent().find(\".status\").text(),\n\t\t\tdescription : $(thisProduct).parent().parent().find(\"#description\").val()\n\t}\n\t\n\treturn product;\n}", "function buyProduct() {\n // query the database for all products on sale. \n /* Documentation: The simplest form of .query() is .query(sqlString, callback), \n where a SQL string is the first argument and the second is a callback: */\n connection.query(\"SELECT * FROM `products`\", function(err, results) {\n if(err) throw err;\n // once all items are displayed, prompt user with two messages: id? / units?\n inquirer\n .prompt([\n // pass in array of objects\n { \n //Requests product ID of item user would like to buy.\n name: \"chooseID\",\n type: \"list\",\n message: \"Please select product ID to place your order:\",\n filter: Number, \n choices: [\"100\", new inquirer.Separator(), \n \"101\", new inquirer.Separator(), \n \"102\", new inquirer.Separator(), \n \"103\", new inquirer.Separator(), \n \"104\", new inquirer.Separator(), \n \"105\", new inquirer.Separator(), \n \"106\", new inquirer.Separator(), \n \"107\", new inquirer.Separator(), \n \"108\", new inquirer.Separator(), \n \"109\", new inquirer.Separator()\n ] \n },\n {\n // Request number of units. \n name: \"numUnits\",\n type: \"list\",\n message: \"How many units would you like to buy?\",\n filter: Number,\n // Documentation: A separator can be added to any choices array: new inquirer.Separator() cool!\n choices: [\"1\", new inquirer.Separator(),\n \"2\", new inquirer.Separator(), \n \"4\", new inquirer.Separator(), \n \"8\", new inquirer.Separator(), \n \"16\", new inquirer.Separator()\n ]\n }\n ]) //prompt({}) ends\n .then(function(answers) { //.then(answers => {...}) [ES6 syntax]\n /* 7. Once the customer has placed the order, your application should check if your store has enough of the product to meet the customer's request.\n If not, the app should log a phrase like Insufficient quantity!, and then prevent the order from going through. */\n console.log(answers); //answers are the USER's FEEDBACK\n for(var i = 0; i < results.length; i++) { //results refer to the data we get from MySQL database\n if(results[i].id === answers.chooseID && results[i].stock_quantity >= answers.numUnits) { //works as expected\n // chooseID refers to the name property value of the promp question constructed in lines 105 to 114\n //return results[i].product_name; //this line cuts through the loop once it finds the selected id\n //create a function to update stock quantity available \n //multiply itme's price * number of units to purchase (USER's INPUT)\n var subtotal = results[i].price * answers.numUnits;\n // add sales tax rate of 8.25% (multiply subtotal * tax rate)\n var salesTax = subtotal * 0.0825;\n // calculate total amount\n var total = subtotal + salesTax;\n // console.log receipt\n console.log(`\n 〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️\n You purchased: ${answers.numUnits + \" \" + results[i].product_name + \"s!\"}\n ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ \n Subtotal: $ ${subtotal}\n Sales Tax: $ ${salesTax.toFixed(2)}\n TOTAL: $ ${total.toFixed(2)}\n ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ ★ ☆ \n WE APPRECIATE YOUR BUSINESS!\n 〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️〰️\n `) \n // The toFixed() method converts a number into a string, keeping a specified number of decimals.\n /* 8. However, if your store does have enough of the product, you should fulfill the customer's order.\n This means updating the SQL database to reflect the remaining quantity.\n Once the update goes through, show the customer the total cost of their purchase. */\n var balance = results[i].stock_quantity - answers.numUnits; \n console.log(\"Remaining number of \" + results[i].product_name + \"s in stock : \" + balance);\n // HERE WE NEED TO CONNECT TO MYSQL TO UPDATE THE DATA IN MYSQL DATABASE\n connection.query(\n \"UPDATE `products` SET stock_quantity = ? WHERE id = ?\", [balance, results[i].id],\n function(error) {\n if (error) throw error;\n console.log(\"Stock quantity has been UPDATED!\");\n //delete row with zero stock quantity\n // DELETE statement\n connection.query(\"DELETE FROM `products` WHERE `stock_quantity` = ?\", 0);\n connection.end();\n } \n ); // connection. query ends \n }\n // AS I CONTINUE LOOPING THROUGH MYSQL DATA & I DO NOT HAVE ENOUGH ITEMS IN MY INVENTORY:\n else if(results[i].id === answers.chooseID && results[i].stock_quantity < answers.numUnits) {\n console.log(\"Not enough items in stock! We apologize for the inconvenience.\");\n inquirer\n .prompt({\n type: \"confirm\", \n name: \"buyAgain\",\n message: \"Would you like to decrease the quantity of items?\"\n })\n .then(function(answers) {\n if(answers.buyAgain) {\n //call buyAgain() function\n buyAgain(); \n }\n else {\n connection.end();\n }\n }) //.then ends\n } //else if closes\n } //for loop closes\n }) //.then(){} ends\n }); //connection.query({}) ends\n}", "function getProduct(e) {\n const href = this.getAttribute(\"href\");\n const ele = document.querySelector(\"a[href='\" + href + \"']\");\n const image = ele.querySelector('figure img').src;\n const eledata = ele.querySelector('.results__data');\n const title = eledata.querySelector('h4').textContent;\n const date = eledata.querySelector('p.results__date').textContent;\n const author = eledata.querySelector('p.results__author').textContent;\n const description = eledata.querySelector('p.results__description').textContent;\n renderSearchResult(image, title, date, author, description);\n}", "function continueShopping() {\n getProducts();\n }", "getItem(product) {\n let itemOut = null\n this.operationOnItemByProduct({\n product, operation: (item) => {\n itemOut = item\n }\n });\n return itemOut;\n }", "function getProductPrices()\n {\n $.getJSON(productPricesEndpoint, function (data) {\n prices = data;\n\n updateProductPrices();\n });\n }", "static async get(req, res) {\n if (!req.params.variation_id) {\n return res.error('Invalid id supplied');\n }\n\n const variation = _.find(\n req.product.variations,\n {\n _id: mongoose.Types.ObjectId(req.params.variation_id),\n deleted: false,\n },\n );\n if (!variation) {\n return res.error('Item with id not found', 404);\n }\n\n return res.products_with_additional_prices(variation);\n }", "function requestProducts(req, res){\n Product.find({}, function(err, response){\n res.send(JSON.stringify(response));\n });\n}", "function createProduct(name, price) {\n // this.setState({ loading: true });\n const web3 = window.web3;\n // const networkId = web3.eth.net.getId();\n // const networkData = Marketplace.networks[networkId];\n\n\n const { account } = formData;\n console.log(\"account\", account);\n\n\n formData.marketplace.methods\n .createProduct(name, price)\n .send({ from: localStorage.getItem(\"account\") })\n .once(\"receipt\", (receipt) => {\n });\n\n }", "function promptUserPurchase() {\n\t\n\n\t// Prompt the user to select the product\n\tinquirer.prompt([\n\t\t{\n\t\t\ttype: 'input',\n\t\t\tname: 'item_id',\n\t\t\tmessage: 'Please enter an ID of the product you would like to purchase.',\n\t\t\t//validate: validateInput,\n\t\t\tfilter: Number\n\t\t},\n\t\t{\n\t\t\ttype: 'input',\n\t\t\tname: 'quantity',\n\t\t\tmessage: 'How many units of the product you would like to purchase?',\n\t\t\t\n\t\t\tfilter: Number\n\t\t}\n\t]).then(function(input) {\n\t\tvar item = input.item_id;\n\t\tvar quantity = input.quantity;\n\n\t\t// Check existing databass to confirm that selected item id exists in the quantity selected\n\t\tvar queryStr = 'SELECT * FROM products WHERE ?';\n\n\t\tconnection.query(queryStr, {item_id: item}, function(err, data) {\n\t\t\tif (err) throw err;\n\n\t\t\t// Dipslay an empty data array, if the user's input is invalid\n\t\t\tif (data.length === 0) {\n\t\t\t\tconsole.log('ERROR: Invalid Product ID. Please select a valid Product ID.');\n\t\t\t\tdisplayInventory();\n\n\t\t\t} else {\n\t\t\t\tvar productData = data[0];\n\n\t\t\t// Display if the quantity requested is in stock\n\t\t\t\tif (quantity <= productData.stock_quantity) {\n\t\t\t\t\tconsole.log('Congratulations, the product you have requested is in stock! Placing an order!');\n\n\t\t\t\t\t// Update query string\n\t\t\t\t\tvar updateQueryStr = 'UPDATE products SET stock_quantity = ' + (productData.stock_quantity - quantity) + ' WHERE item_id = ' + item;\n\t\t\t\t\t\n // Update the current inventory\n\t\t\t\t\tconnection.query(updateQueryStr, function(err, data) {\n\t\t\t\t\t\tif (err) throw err;\n\n\t\t\t\t\t\tconsole.log('Your oder has been placed! Your total is $' + productData.price * quantity);\n\t\t\t\t\t\tconsole.log('Thank you for shopping with us!');\n\t\t\t\t\t\tconsole.log(\"\\n---------------------------------------------------------------------\\n\");\n\n\t\t\t\t\t\t// Ends database connection\n\t\t\t\t\t\tconnection.end();\n\t\t\t\t\t})\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log('We are sorry, but there is not enough product in stock to complete your order. Your order can not be placed at this time.');\n\t\t\t\t\tconsole.log('Please modify your order, or make another selection.');\n\t\t\t\t\tconsole.log(\"\\n---------------------------------------------------------------------\\n\");\n\n\t\t\t\t\tdisplayInventory();\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t})\n}", "async function getQItem() {\n const bearer = await helpers.getBearerToken();\n const item = await helpers.getItem(itemUrl, bearer);\n return item;\n}", "function functionToBuy() {\n buySpecificItem(someItemFromShop);\n }", "static async getStoreInventory() {\n const storeInventory = storage.get(\"products\").value()\n return storeInventory\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
given a hex string return a base64 string
function hex2base64(s){ return Crypto.util.bytesToBase64(hex2bytes(s)) }
[ "function base64(data) {\n\tif (typeof data === 'object') data = JSON.stringify(data);\n\treturn Buffer.from(data).toString('base64');\n}", "toBase64() {\n return this._byteString.toBase64();\n }", "function hexReturnFull(hex) {\n\tvar shorthandRegex = /^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i;\n\treturn hex.replace(shorthandRegex, function(m, r, g, b) {\n\t\treturn \"#\" + r + r + g + g + b + b;\n\t});\n}", "function hex2hexKey(s){ return bigInt2hex(hex2bigIntKey(removeWhiteSpace(s))); }", "function hex2base58(s){ return Bitcoin.Base58.encode(hex2bytes(s))}", "function base582hex(s){\r\n var res, bytes\r\n try { res = parseBase58Check(s); bytes = res[1]; }\r\n catch (err) { bytes = Bitcoin.Base58.decode(s); }\r\n return bytes2hex(bytes)\r\n}", "base64() {\n\t\tif (typeof btoa === 'function') return btoa(String.fromCharCode.apply(null, this.buildFile()));\n\t\treturn new Buffer(this.buildFile()).toString('base64');\n\t}", "function completeBinary(str) {\n\tlet a = str;\n\twhile (a.length % 8 !== 0) {\n\t\ta = \"0\" + a;\n\t}\n\treturn a;\n}", "function rstr_sha1(s)\n\t\t{\n\t\t return binb2rstr(binb_sha1(rstr2binb(s), s.length * 8));\n\t\t}", "function hexToBinary( hex )\n{\n\tlet result = \"\";\n\n\t// Split by each hex character\n\thex.split( \"\" ).forEach( str =>\n\t{\n\t\t// Parse the character into an integer.\n\t\t// Convert the integer into a binary string representation.\n\t\t// Pad with leading zeros for four bits (each hex character is a nibble).\n\t\tresult += ( parseInt( str, 16 ).toString( 2 ) ).padStart( 4, '0' );\n\t} );\n\n\treturn result;\n}", "function generateTrip(str)\n{\n var MD5 = crypto.createHash(\"MD5\");\n MD5.update(str);\n var trip = MD5.digest(\"base64\").slice(0, 6);\n console.log(\"Generated trip \" + trip);\n return trip;\n}", "function base64URLToBytes(base64URL) {\n return atob(decodeURIComponent(base64URL)\n .replace(/[_-]/g, c => toB64[c]));\n}", "function md5uri64(strings) {\n\tvar sum = crypto.createHash('md5');\n\tstrings.forEach(function(str) {\n\t\tsum.update(str, 'utf8');\n\t});\n\treturn sum.digest('base64').replace(/[\\+\\/=]/g, function(ch) {\n\t\treturn { '+': 'a', '/': 'b', '=': '' }[ch];\n\t});\n}", "function generateHash(string) {\n\treturn crypto.createHash('sha256').update(string + configuration.encryption.salt).digest('hex');\n}", "function rgbString(hex) {\n\tcol = hexToRgb(hex);\n\treturn \"rgb(\"+col.r+\",\"+col.g+\",\"+col.b+\")\"\n}", "function isValidHexCode(str) {\n\treturn /^#[a-f0-9]{6}$/i.test(str);\n}", "function data_enc( string ) {\n\n //ZIH - works, seems to be the fastest, and doesn't bloat too bad\n return 'utf8,' + string\n .replace( /%/g, '%25' )\n .replace( /&/g, '%26' )\n .replace( /#/g, '%23' )\n //.replace( /\"/g, '%22' )\n .replace( /'/g, '%27' );\n\n //ZIH - works, but it's bloaty\n //return 'utf8,' + encodeURIComponent( string );\n\n //ZIH - works, but it's laggy\n //return 'base64,' + window.btoa( string );\n}", "function parseHexToASCII(buffer, start, end) {\n let sub_array = buffer.slice(start, end);\n let result = '';\n for (let i = 0; i < sub_array.length; i++)\n result += String.fromCharCode(sub_array[i]);\n return result;\n}", "function hex4(state) {\n return re(state, /^[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]/,\n function (s) {\n return parseInt(s, 16);\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hammer.Manager mock for use in environments without `document` / `window`.
function HammerManagerMock(m) { var instance = {}; var chainedNoop = function chainedNoop() { return instance; }; instance.get = function () { return null; }; instance.set = chainedNoop; instance.on = chainedNoop; instance.off = chainedNoop; instance.destroy = chainedNoop; instance.emit = chainedNoop; return instance; }
[ "function addHammerRecognizer(theElement) {\n // We create a manager object, which is the same as Hammer(), but without \t //the presetted recognizers.\n //alert(\"dfadfad\");\n var mc = new Hammer.Manager(theElement);\n \n \n // Tap recognizer with minimal 2 taps\n mc.add(new Hammer.Tap({\n event: 'doubletap',\n taps: 2,\n threshold:5,\n posThreshold:30\n }));\n // Single tap recognizer\n mc.add(new Hammer.Tap({\n event: 'singletap',\n taps:1,\n threshold:5\n }));\n \n \n // we want to recognize this simulatenous, so a quadrupletap will be detected even while a tap has been recognized.\n mc.get('doubletap').recognizeWith('singletap');\n // we only want to trigger a tap, when we don't have detected a doubletap\n mc.get('singletap').requireFailure('doubletap');\n \n \n mc.on(\"singletap\", function (ev) {\n //alert(\"sfdsfad\");\n //console.log(\"ev\"+ev);\n showDetails(ev);\n \n });\n mc.on(\"doubletap\", function (ev) {\n //showDynamicMap(ev);\n loadPage(\"mapPage\");\n showDynamicMap(ev);\n });\n \n}", "function MonsterManager() {\n Manager.call(this);\n}", "function WindowManager() {\n if (window_manager_ == null) {\n window_manager_ = new WindowManagerImpl(document.getElementById(\"data_windows\"),\n document.getElementById(\"window_menu\"));\n }\n return window_manager_;\n}", "function AppManager(){\n}", "constructor() {\r\n ObjectManager.instance = this;\r\n\r\n }", "function MockVolumeManager() {\n this.volumeInfoList = new cr.ui.ArrayDataModel([]);\n\n this.volumeInfoList.push(MockVolumeManager.createMockVolumeInfo(\n util.VolumeType.DRIVE, 'drive'));\n this.volumeInfoList.push(MockVolumeManager.createMockVolumeInfo(\n util.VolumeType.DOWNLOADS, 'downloads'));\n}", "function makeEventManager() {\n\n var manager = {};\n var list = {};\n\n /**\n * \teventManager.get(name) -> eventList\n * \t- name (String): Name of the event list.\n *\n * \tGets an [[eventList]] for the given `name`. If there is no\n * \t[[eventList]] for that `name`, one is created.\n *\n *\t\tvar manager = makeEventManager();\n *\t\tmanager.get(\"one\"); // -> eventList \"one\"\n *\t\tmanager.get(\"one\"); // -> eventList \"one\" again\n *\t\tmanager.get(\"two\"); // -> eventList \"two\"\n *\n **/\n function get(name) {\n\n if (!list[name]) {\n list[name] = makeEventList();\n }\n\n return list[name];\n\n }\n\n util.Object.assign(manager, {\n get: get\n });\n\n return Object.freeze(manager);\n\n }", "getManager(type) {\n return self.managers[self.normalizeType(type)];\n }", "function _kWidgetMock() {\n root.kWidget = {\n api: class {\n /**\n * mock constructor for the kWidget api class\n */\n constructor() {\n this.doRequest = (obj, cb) => {\n cb(response);\n };\n }\n },\n };\n}", "replaceSingleton() {\n AppManagementStore.setInstanceForTesting(this);\n }", "function setupMediaManager() {\n window.mediaElement = document.getElementById('tmp_video');\n window.mediaManager = new cast.receiver.MediaManager(window.mediaElement);\n\n window.mediaManager.onGetStatus = onGetStatus.bind(this);\n window.mediaManager.onLoad = onLoad.bind(this);\n window.mediaManager.onPauseOrig = window.mediaManager.onPause;\n window.mediaManager.onPause = onPause.bind(this);\n window.mediaManager.onPlayOrig = window.mediaManager.onPlay;\n window.mediaManager.onPlay = onPlay.bind(this);\n window.mediaManager.onSeekOrig = window.mediaManager.onSeek;\n window.mediaManager.onSeek = onSeek.bind(this);\n window.mediaManager.onSetVolumeOrig = window.mediaManager.onSetVolume;\n window.mediaManager.onSetVolume = onSetVolume.bind(this);\n window.mediaManager.onEndedOrig = window.mediaManager.onEnded;\n window.mediaManager.onEnded = onEnded.bind(this);\n window.mediaManager.onStopOrig = window.mediaManager.onStop;\n window.mediaManager.onStop = onStop.bind(this);\n window.mediaManager.onErrorOrig = window.mediaManager.onError;\n window.mediaManager.onError = onError.bind(this);\n window.mediaManager.customizedStatusCallback = customizedStatusCallback.bind(this);\n}", "function mock({ request = {}, response = {} }) {\n return nock(/\\.authy\\.com/)\n .get('/protected/json/app/stats')\n .query(request.query ? request.query : true)\n .reply(response.code, response.body);\n}", "function addEventListeners() {\n // pan watch point event\n var hammerPointer = new Hammer(document.querySelector('#pointer'));\n hammerPointer.on('pan', onPanPointer);\n}", "async function createManager() {\n const newManager = await new Manager();\n await newManager.getOfficeNumber();\n await manager.push(newManager);\n await generatorQs();\n}", "async enable (app, statsdiv = null) {\n this.app = app\n this.config = this.app.config\n\n this.detector = await getPitchDetector(this.comparePitch)\n\n if (statsdiv) {\n this.stats = new AudioStatsDisplay(statsdiv)\n this.stats.setup() // reveal stats page\n }\n\n // Get the audio context or resume if it already exists\n if (this.context === null) {\n let input = await getAudioInput()\n this.context = input.audioContext\n this.mic = input.mic\n this.media = input.media\n\n this.scriptNode = setupAudioProcess(this.context, this.mic, this.detector)\n\n } else if (this.context.state === 'suspended') {\n await this.context.resume()\n }\n\n this.isActive = true\n console.log('Audio Detection Enabled')\n\n }", "function DockManager(element)\n{\n if (element === undefined)\n throw new Error('Invalid Dock Manager element provided');\n\n this.element = element;\n this.context = this.dockWheel = this.layoutEngine = this.mouseMoveHandler = undefined;\n this.layoutEventListeners = [];\n\n this.defaultDialogPosition = new Point(0, 0);\n}", "function doSetup() {\n if (!QUnit.events) {\n var defaultManager = new QUnitEventPluginManager();\n QUnit.extend(QUnit, {\n EventsPluginManager: QUnitEventPluginManager,\n EventsPlugin: QUnitEventPlugin,\n events: defaultManager\n });\n }\n }", "setManager(type, manager) {\n self.managers[type] = manager;\n }", "function gameManager() {\n switch (game.gameMode) {\n case \"Classic\":\n {\n classic();\n break;\n }\n case \"Survival\":\n {\n survival();\n break;\n }\n case \"TimeAttack\":\n {\n ui.showUI(\"TimeAttackUI\");\n timeAttack();\n break;\n }\n }\n}", "function BannerManager(options) {\n this.banners = [];\n this.bannersIndex = [];\n this.server = null;\n this.displayBanner = false;\n this.rotationPeriod = 5000;\n this.carouselInitialised = false;\n \n this.bannerDialog = new BannerDialog();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursively loops through the initial comment's replies and their replies to mark them all as logically deleted.
function markDeleted(initialComment) { initialComment.deleted = true; if (initialComment.replies) { initialComment.replies.forEach(function(reply) { markDeleted(reply); }); } }
[ "function removecommentsubtree( pid ) {\n\tvar myctrclass = \".descendent-of-\" + pid;\n\n\t$( myctrclass ).each( function () { removecommentsubtree( $(this).attr( \"id\" ) ); } )\n\t\t.remove();\n}", "function onclickBtnReply(e) {\n e.preventDefault();\n /**\n * handle action on clicking reply button\n * take the input reply and insert it in\n * replies area\n */\n\n /**\n * get the identifier of the comment\n * @type {*|string}\n */\n\n var id = e.currentTarget.id.split(\"-\")[1];\n\n /**\n * Get id of the reply input area\n * @type {string}\n */\n var replyInputId = \"#comment-\" + id + \"-reply-input\";\n\n /**\n * get the input reply area\n * and store it in the reply\n * @type {*|void|jQuery}\n */\n var reply = $(replyInputId).val();\n\n /**\n * Clear the input reply area\n */\n $(replyInputId).val();\n\n\n /**\n * get the number of replies of this comment\n * to give beside prefix\n */\n\n var repliesAreaId = \"#comment-\" + id + \"-repliesArea\";\n /**\n * Get number of childern to determine the number of replies\n * @type {jQuery}\n */\n var count = $(repliesAreaId).children().length;\n\n /**\n * add 1 to the number of replies\n */\n\n let numOfRepliesId = \"#comment-\" + id + \"-numOfReplies\";\n let numOfReplies = parseInt($(numOfRepliesId).text()) + 1;\n $(numOfRepliesId).text(\"\" + numOfReplies);\n\n /**\n *Create replies using the Reply of prototype\n * @type {Reply}\n */\n\n var date = new Date().toJSON().slice(0, 10);\n var obj = new Reply(id, count);\n obj.date = date;\n obj.text = reply;\n obj.creation();\n\n\n /**\n * Make the reply button disabled\n */\n\n\n $(\"#\" + e.currentTarget.id).attr('disabled', 'disabled');\n\n\n}", "function disableReplying()\n{\n $('#comments-container').find('.commenting-field.main').hide();\n $('#comments-container').find('.action.reply').hide();\n}", "function CheckUnCheckAllComments(postid) {\r\n\r\n // loop on all comments row and check (or uncheck) each one\r\n var firstIsChecked = false;\r\n $('.cbxComment_' + postid).each(function (index, value) {\r\n if (index === 0 && $(this).is(':checked'))\r\n firstIsChecked = true;\r\n\r\n if (firstIsChecked === true)\r\n $(this).prop('checked', false);\r\n else\r\n $(this).prop('checked', true);\r\n });\r\n}", "function cleanupComments(doc) {\n\n\tvar result = [],\n\t\t\tlast = null,\n\t\t\ti, el;\n\n\tfor (i = 0; i < doc.length; i++) {\n\t\tel = doc[i];\n\n\t\tif (last == null) {\n\t\t\tlast = el\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (el.code.length === 0 && el.comment === \"\")\n\t\t\tcontinue;\n\n\t\tif (last.code.length == 0 || el.code.length == 0) {\n\t\t\tlast.code = last.code.concat(el.code)\n\t\t\tlast.markup += el.markup\n\t\t\tlast.comment += el.comment\n\t\t} else {\n\t\t\tresult.push(last);\n\t\t\tlast = el;\n\t\t}\n\n\t}\n\n\tresult.push(last);\n\treturn result;\n}", "prune(callback) {\n if (_.isArray(this.contents)) {\n const length = this.contents.length;\n\n if ((this.type === \"REPEAT\" && length > 0) || (this.type === \"REPEAT1\" && length > 1)) {\n // Any subtree may be removed\n for (let i = 0; i < length; i++) {\n const tree = _.cloneDeep(this);\n tree.contents.splice(i, 1);\n if (!callback(tree)) {\n return;\n }\n }\n }\n\n for (let i = 0; i < length; i++) {\n let callbackResult = true;\n\n this.contents[i].prune(t => {\n const tree = _.cloneDeep(this);\n tree.contents[i] = t;\n callbackResult = callback(tree);\n return callbackResult;\n });\n\n if (!callbackResult) {\n return;\n }\n }\n }\n }", "markSeenAll () { // mark this comment and all replies 'seen'\n if (!this.seenByMe) {\n this.seenByMe = true\n const token = localStorage.getItem(\"nb.user\");\n const headers = { headers: { Authorization: 'Bearer ' + token }}\n axios.post(`/api/annotations/seen/${this.id}`,{} ,headers)\n }\n for (let child of this.children) {\n child.markSeenAll()\n }\n }", "function unfoldComment (comment, scrollTarget) {\n //If we've already loaded\n if (comment.comments) {\n comment.element.parentElement.insertBefore(createCommentTextbox(comment.id), comment.element.nextSibling)\n for (var i = comment.comments.length-1; i >= 0; i--) {\n comment.element.parentElement.insertBefore(displayComment(comment.comments[i]), comment.element.nextSibling);\n }\n comment.unfolded = true;\n var el = comment.element.getElementsByClassName(\"show-hide-comments\")[0];\n el.innerText = el.innerText.replace(/^Show/, \"Hide\");\n }else {\n var req = new XMLHttpRequest();\n req.open(\"GET\", \"/api/program/\" + programData.id + \"/comment/\" + comment.id + \"/comments\");\n req.addEventListener(\"load\", function () {\n var data = JSON.parse(this.response);\n if (data && data.success) {\n comment.comments = data.comments;\n comment.replyCount = data.comments.length; //Reset local value to the correct number\n var el = comment.element.getElementsByClassName(\"show-hide-comments\")[0];\n el.innerText = el.innerText.replace(/\\(\\d+\\)/, \"(\" + comment.replyCount + \")\")\n\n unfoldComment(comment);\n\n if (scrollTarget) {\n var scrollComment = document.getElementById(scrollTarget);\n jumpToComment(scrollComment);\n }\n }\n });\n req.send();\n }\n}", "async function addReply(req) {\n const parentComment = await getCommentByID(req.body.commentID);\n const user = await getById(req.body.userID);\n const comment = new commentSchema();\n comment.text = req.body.comment;\n comment.username = user.username;\n comment.base = false;\n\n const newComment = new commentSchema(comment);\n await newComment.save();\n\n // add comment to the base comment's replies list\n user.comments.push(comment._id);\n parentComment.replyIDs.push(comment._id);\n\n parentComment.replies = await updateReplies(parentComment);\n\n await parentComment.save();\n await user.save();\n return newComment;\n}", "function deleteNote() {\r\n let thisNote = this.parentNode.parentNode;\r\n\r\n let notes = document.getElementsByClassName('note');\r\n let oldRects = new Map(); // Initialize an array for the old note positions\r\n\r\n // Collect all the current note positions\r\n for (let i = 0; i < notes.length; i++) {\r\n let rect = notes[i].getBoundingClientRect();\r\n oldRects.set(notes[i].id, rect);\r\n }\r\n\r\n thisNote.remove();\r\n\r\n animateReorder(oldRects, 300); // Using the old positions, animate the reording of the notes over the specified time\r\n}", "function cleanupReplies(message, userId) {\n bot.channels.get(curryBotChannel).fetchMessages().then(function(messages) {\n messages.forEach(function (msg) {\n if (msg.author.bot && msg.id !== message.id && msg.mentions.users.first()) {\n if (msg.mentions.users.first().id === userId) {\n msg.delete().then(function() {\n console.log(msg.id + \" deleted.\");\n }).catch(err => console.log(err));\n }\n }\n })\n }).catch(err => console.log(err));\n}", "_cancelComment() {\n this._comment = '';\n this._displayFormActions = false;\n }", "function validateCommentReplyForm(){\n\tvar field = document.getElementById(\"crField\");\n\tvar photoField = document.getElementById(\"crPhotoField\");\n\n\tif(field.value.trim().length >= 65500){\n\t\t// 65500\n\t\tfield.focus();\n\t\t$(\"#errorForContent\").show();\n\t\t$(\"#errorForContent\").text(\"Too Long Text\");\n\t\tfield.style.border = \"1px solid red\";\n\t\tfield.placeholder = \"Too long text\";\n\t\tevent.preventDefault();\n\t}else{\n\t\t$(\"#errorForContent\").hide();\n\t\tfield.style.border = \"none\";\n\t\tfield.placeholder = \"Add Comment...\"\n\t}\n\n\t// This if means if both the photo filed and comment field is empty then throw an error\n\tif(field.value.trim().length < 1 && photoField.files.length < 1){\n\t\t// for editing\n\t\tif($(\"#fileRemovedStatus\").is(\":disabled\")){\n\t\t\t// it means if someone just want to clear the text while editing and stick with old photo then do not show them error while submititng\n\t\t}else{\n\t\t\tfield.focus();\n\t\t\tfield.style.border = \"1px solid red\";\n\t\t\tfield.placeholder = \"can not add empty comment\";\n\t\t\t$(\"#errorForContent\").show();\n\t\t\t$(\"#errorForContent\").text(\"can not add empty comment\");\n\t\t\tevent.preventDefault();\n\t\t}\n\t}else{\n\t\tfield.placeholder = \"Add Comment...\";\n\t\t$(\"#errorForContent\").hide();\n\t\t$(\"#errorForContent\").text(\"\");\n\t\tfield.style.border = \"none\";\n\t}\t\n}", "function ServerBehavior_deleteIfAlreadyReferenced(allSBs)\n{\n var bAlreadyClaimed = false;\n var thisSBParts = this.getParticipants();\n if (thisSBParts && thisSBParts.length > 0)\n {\n var thisMainPartNode = this.getSelectedNode();\n if (thisMainPartNode == null)\n {\n thisMainPartNode = thisSBParts[0].getNode();\n }\n \n var thisSBName = this.getName();\n \n // Search through all server behavior objects. If any of them have already\n // claimed this node as their own, set the deleted flag for this server\n // behavior.\n for (var i = 0; !bAlreadyClaimed && i < allSBs.length; ++i)\n {\n if (allSBs[i].getParticipants)\n {\n var sbParts = allSBs[i].getParticipants();\n // Make sure we aren't looking at the same sbObj.\n if (allSBs[i].getName() != thisSBName && sbParts)\n {\n for (var j = 0; !bAlreadyClaimed && j < sbParts.length; ++j)\n {\n var sbPartNode = sbParts[j].getNode();\n // Check for the same node, and that the priority of the\n // other item is less than or equal to ours\n if (sbPartNode && sbPartNode == thisMainPartNode &&\n allSBs[i].getPriority() <= this.getPriority())\n {\n bAlreadyClaimed = true;\n this.deleted = true;\n }\n }\n }\n }\n else\n { // Handle UD1 and UD4 Server Behavior objects\n var sbParts = allSBs[i].participants;\n if (allSBs[i].type != thisSBName && sbParts)\n {\n for (var j = 0; !bAlreadyClaimed && j < sbParts.length; ++j)\n {\n var sbPartNode = sbParts[j];\n // Check for the same node, and that the priority of the\n // other item is less than or equal to ours\n if (sbPartNode && sbPartNode == thisMainPartNode)\n {\n bAlreadyClaimed = true;\n this.deleted = true;\n }\n }\n }\n }\n }\n }\n \n return bAlreadyClaimed;\n}", "function fixRelatedContentURIs(document) {\n function fixBlock(block) {\n if (block.content) {\n block.content.forEach(item => {\n if (item.mdn_url) {\n item.uri = mapToURI(item);\n delete item.mdn_url;\n }\n fixBlock(item);\n });\n }\n }\n document.related_content.forEach(block => {\n fixBlock(block);\n });\n}", "function removeAllSubscriptionsToComments(settings) {\n\t\t\n\t\tif(!settings.post_id) { return false; }\n\t\t \n\t\t$.xmlrpc({\n\t\t\turl: settings.xmlrpcurl + '/xmlrpc.php',\n\t\t\tmethodName: 'hri.removeAllSubscriptionsToComments',\n\t\t\tparams: [settings.wordpress_username, settings.wordpress_password, settings.email],\n\t\t\tsuccess: function(response, status, jqXHR) { \n\t\t\t\t\n\t\t\t\t(settings.commentnotification)(settings.phrases.subscribe_remall, \"#090\");\n\t\t\t},\n\t\t\terror: function(jqXHR, status, error) {\n\t\t\t\t\n\t\t\t\t(settings.errornotification)(error);\n\t\t\t}\n\t\t});\n\t}", "function unMarkAsHelpful(container, question) {\n\n var helpfulCount = question.numHelpful;\n var maxHelpfulCount = question.totalNumHelpful;\n var helpfulCountRemaining = maxHelpfulCount-helpfulCount;\n\n // if only one helpful answer remaining, we transitioned from having no helpful answers available,\n // update all rendering since a lot will likely need to be modified.\n if (helpfulCountRemaining == 1) {\n // cycle through messages, update buttons\n renderResponses(question);\n }\n // otherwise no need to traverse all page.\n else {\n var replyDiv = $j(container.closest('.js-thread-post-wrapper'));\n renderReply(replyDiv, question);\n }\n\n // inject correct / helpful answer\n renderInlineAnswers(question);\n\n return false;\n }", "function initComments() {\n const $comments = $('.comment-item');\n $comments.each((ind, comment) => {\n const $comment = $(comment);\n initComment($comment);\n });\n }", "function fixCommentsCounters( oldPostId, newPostId, mod ){\n //Fix old post \n var $cc = $( \"#post-\" + oldPostId ).find( \".comment-count\" );\n var currentNoc = parseInt( $cc.text() );\n $cc.text( currentNoc - mod );\n\n //Fix new post\n $cc = $( \"#post-\" + newPostId ).find( \".comment-count\" );\n currentNoc = parseInt( $cc.text() );\n $cc.text( currentNoc + mod );\n\n //Fix comment counter for every comment \n $( \"#the-comment-list tr:not(.wptc-special-drop)\" ).each( function(){\n var thisPostComCount = $( this ).find( \".post-com-count\" );\n if( thisPostComCount.length ){\n var thisPostId = $( this ).wptc().getData( \"postId\" );\n if( thisPostId == oldPostId ){\n var $cc = thisPostComCount.find( \".comment-count\" );\n var currentNoc = parseInt( $cc.text() );\n $cc.text( currentNoc - mod );\n } else if( thisPostId == newPostId ){\n var $cc = thisPostComCount.find( \".comment-count\" );\n var currentNoc = parseInt( $cc.text() );\n $cc.text( currentNoc + mod );\n }\n }\n });\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Name : validateDepartureDate() Parameters : none Processes : Reports errors if departure date is in the past. Return Value: none
function validateDepartureDate() { var departureDate = document.getElementById("departureDate").value; // Gets and stores value of departureDate. var departureDateError = document.getElementById("departureDateError"); // Gets and stores departureDateError element. var departureDateObject = new Date(departureDate); // Creates a departureDateObject from departureDate. var returnDate = document.getElementById("returnDate").value; // Gets and stores value of returnDate. var summaryDepartureDate = document.getElementById("summaryDepartureDate");// Gets and stores departureDate in summary. try { // Attempt logic. if (currentDate > departureDateObject) { // If departure date previous to current date. throw "The current departure date is not valid. Please select a new departure date"; } else { departureDateError.style.display = "none"; // Hide errors. ++formCompletion; // Increment form completion. (errors <= 1) ? errors = 0 : --errors; // Decrease erros within positives. bookable(); // Verify bookability. } } catch (msg) { departureDateError.style.display = "block"; // Show errors. departureDateError.innerHTML = "<p>" + msg + "</p>"; // Write errors. ++errors; // Increment errors. (formCompletion <= 1) ? formCompletion = 0 : --formCompletion; // Decrease form completion within positives. bookable(); // Verify bookability. } }
[ "function departureDateHandler() {\n\thandlePastDate();\t\t\t\t\t\t// Ensures that a past date is handled.\n\tdateInverter();\t\t\t\t\t\t\t// Inverts dates if necessary.\n}", "function handlePastDate() {\n\tvar departureDate = document.getElementById(\"departureDate\");\t\t\t\t\t// Gets and stores departureDate input.\n\tvar returnDate = document.getElementById(\"returnDate\");\t\t\t\t\t\t\t// Gets and stores returnDate input.\n\tvar summaryDepartureDate = document.getElementById(\"summaryDepartureDate\");\t\t// Gets and stores departureDate in summary.\n\tvar summaryReturnDate = document.getElementById(\"summaryReturnDate\");\t\t\t// Gets and stores returnDate in summary.\n\tvar departureDateObject = new Date(departureDate.value);\t\t\t\t\t\t// Creates a date object from the departure date value.\n\tvar returnDateObject = new Date(returnDate.value);\t\t\t\t\t\t\t\t// Creates a date object from the return date value.\n\n\tif (departureDateObject < currentDate) {\t\t\t\t\t\t\t\t\t\t// If selected departure date is less than currentDate.\n\t\tvar stringDeparturDate = currentDate.getFullYear() + \"-\" + (currentDate.getMonth() + 1) + \"-\" + (currentDate.getDate() < 10 ? \"0\" : \"\") + currentDate.getDate(); // Converts current date to usable format by adding a zero for single digit date: i.e. yyyy-mm-d -> yyyy-mm-\"0\"d.\n\t}\n}", "function validateStandardDate(due){\n var mess = \"\";\n if (due == \"\") {\n return mess;\n }\n var patt = /^20[0-9]{2}\\/[01][0-9]\\/[0-3][0-9]$/;\n var tmp = patt.exec(due);\n if (tmp == \"\") {\n return \"Date must take form YYYY/MM/DD.\";\n }\n return tmp;\n\n var DDcap = new Array();\n DDcap[0] = 31;\n DDcap[1] = 28;\n DDcap[2] = 31;\n DDcap[3] = 30;\n DDcap[4] = 31;\n DDcap[5] = 30;\n DDcap[6] = 31;\n DDcap[7] = 31;\n DDcap[8] = 30;\n DDcap[9] = 31;\n DDcap[10] = 30;\n DDcap[11] = 31;\n var PYY = /^[0-9]{1,4}/;\n var YY = parseInt(PYY.exec(due), 10);\n var PTMM = /\\/[0-9]{1,2}\\//;\n var TMM = PTMM.exec(due);\n var PMM = /[0-9]{1,2}/;\n var MM = parseInt(PMM.exec(TMM), 10);\n var PDD = /[0-9]{1,2}$/;\n var DD = parseInt(PDD.exec(due), 10);\n var t = new Date();\n //var et = (t.getTime() - t.getMilliseconds())/1000 - 1293840000; // time since 0:00:00 on Jan 1, 2011\n var bau = true;\n if(YY < 2013){\n mess = \"Date must take form YYYY/MM/DD. \";\n }\n if(MM > 12 || MM < 1){\n mess = \"Date must take form YYYY/MM/DD. \";\n }\n if(DD > DDcap[MM-1] && !(DD==29 && MM==2 && YY % 4 == 0) || DD == 0){\n mess += \"The date you entered is invalid for the month selected\";\n }\n return mess;\n}", "function ValidateAppointment()\n{\n AptDate = document.getElementById(\"IdDate\").value;\n today = new Date().toISOString().slice(0, 10);\n \n // reject past date\n if (AptDate < today) {\n document.getElementById(\"error\").innerHTML = \"Cannot create past appointments!\";\n document.getElementById(\"IdDate\").focus();\n return false; \n }\n \n return true;\n}", "function checkDate(time) {\r\n let today = new Date();\r\n today = today.getTime() - (today.getTime() % oneDayInMilliseconds); // Convert 'today' in multiple of a entire date\r\n let errors = []\r\n\r\n if (isNaN(time)) errors.push(\"Must provide a date.\");\r\n\r\n if (time < today) errors.push(\"Date must be in the future.\");\r\n\r\n // Search for a date conflict\r\n for (let i = 0; i < travelDates.length; i++) {\r\n if (travelDates[i].date == time) {\r\n errors.push(\"Date conflict.\");\r\n break;\r\n }\r\n }\r\n\r\n return errors;\r\n}", "departmentUnvalidity() {\n if ($scope.view.establishments.department.length >= 2) {\n // If the department isn't equal to one of the department that are in fact strings in STRING_DEPARTMENTS\n if (STRING_DEPARTMENTS.indexOf($scope.view.establishments.department) !== -1) {\n return false;\n }\n\n // If the department is in the list of french departments\n if (Number.isInteger(Number($scope.view.establishments.department))) {\n const integerDepartment = Number($scope.view.establishments.department);\n if ((integerDepartment > 0 && integerDepartment < 96) || (integerDepartment > 970 && integerDepartment < 977)) {\n return false;\n }\n }\n }\n\n $scope.view.errorMsg = 'Veuillez rentrer un departement français valide';\n return true;\n }", "function validateDateFilter() {\n var startEra = getEra(\"start\");\n var endEra = getEra(\"end\");\n var startDate = getDate(\"start\");\n var endDate = getDate(\"end\");\n\n if ((!startEra && startDate) || (startEra && !startDate)) {\n return false;\n }\n if ((!endEra && endDate) || (endEra && !endDate)) {\n return false; \n }\n if ((startEra && startDate) && !(endEra && endDate)) {\n return true;\n }\n if (!(startEra && startDate) && (endEra && endDate)) {\n return true;\n }\n return (compareDates(startDate, startEra, endDate, endEra) <= 0);\n}", "function validateDateForGapScan(date){\t\n\tvar valid = true;\n\tvar oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds\n\tvar todayDateArray = getTodayDate().split(\"/\");\n\tvar selDateArray = date.split(\"/\");\n\tvar selDate = new Date(selDateArray[2],selDateArray[1]-1,selDateArray[0]);\n\tvar todayDate = new Date(todayDateArray[2],todayDateArray[1]-1,todayDateArray[0]);\n\n\tvar diffDays = Math.round(Math.abs((todayDate.getTime() - selDate.getTime())/(oneDay)));\n\t\n\tif(selDate > todayDate){\n\t\tvalid = false;\n\t\t$.fn.showCustomMsg(['Entered date is greater than today\\'s date.'],error,'GapScan Report');\n\t}else if(diffDays > 6){\n\t\tvalid = false;\n\t\t$.fn.showCustomMsg(['This report is limited to last 7 days. Please choose a valid date.'],error,'GapScan Report');\n\t}\n\treturn valid;\n\t\n}", "function stOrderPlanRecptStartDateQuery(dp){\r\n\t$(\"#planRecptDateEnd\").attr('title','');\r\n\t$(\"#planRecptDateEnd\").removeClass('errorInput');\r\n\tvar planRecptEndDate=$(\"#planRecptDateEnd\").val();\r\n\tvar planRecptBeginDate= dp.cal.getNewDateStr();\r\n\tif(planRecptEndDate){\t\t\r\n\t\tvar subDays=getSubDays(planRecptBeginDate,planRecptEndDate);\r\n\t\tif(subDays<0){\r\n\t\t\t$(\"#planRecptDateEnd\").attr('title','结束日期小于开始日期');\r\n\t\t\t$(\"#planRecptDateEnd\").addClass('errorInput');\r\n\t\t\treturn false;\r\n\t\t}\r\n\t} \r\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}", "function validDates() {\n if (checkIn.val() != '' && checkOut.val() != '') {\n inDate = new Date(checkIn.val())\n outDate = new Date(checkOut.val())\n if (inDate < outDate) {\n return true\n }\n }\n return false\n }", "function addVacationDay(){\n\t\n\t//GET THE EXISTING VACATION DAYS, IF ANY\n\tvar vacationDaysArray = [];\n\tvacationDaysArray = U.profiles[Profile].vacationDays;\n\tvar l = vacationDaysArray.length;\n\tvar startPosition = null; //Used later to help remove any duplicate dates\n\t\n\t//GET THE INPUT VALUE\n\tvar theValue = $(\"#vacationDaysInput\")[0].value;\n\t\n\t//HIDE ANY ERROR MESSAGE THAT MAY BE PRESENT\n\thideErrorMessage(\"errorDiv-vacationDays\");\n\t\n\t///////////CHECK FOR ERRORS\n\t\n\t//Be sure it is not blank\n\tif(($.trim( theValue ) == '') || ($.trim( theValue ) == 'MM/DD/YYYY')){\n\t\tshowErrorMessage(\"errorDiv-vacationDays\",\"Your entry is blank. Please type in a date.\");\n\t\treturn false;\n\t}\n\t\n\t//Be sure the input date is formatted correctly\n\tvar date_regex = /^(\\d{1}|\\d{2})\\/(\\d{1}|\\d{2})\\/(\\d{2}|\\d{4})$/;\n\tvar dateRange_regex = /^(\\d{1}|\\d{2})\\/(\\d{1}|\\d{2})\\/(\\d{2}|\\d{4})-(\\d{1}|\\d{2})\\/(\\d{1}|\\d{2})\\/(\\d{2}|\\d{4})$/;\n\t\n\tif(!theValue.match(date_regex)){\n\t\t\n\t\t//If it does not match the format mm/dd/yyyy, see if they are trying to enter a date range\n\t\tif(theValue.match(dateRange_regex)){\n\t\t\t/////////WE HAVE A DATE RANGE, LADIES AND GENTLEMEN!\n\t\t\t\n\t\t\t//Isolate the start and end dates\n\t\t\tvar firstDate = theValue.split(\"-\")[0];\n\t\t\tvar lastDate = theValue.split(\"-\")[1];\n\t\t\t\n\t\t\tvar firstDateMilliseconds = new Date(firstDate).getTime();\n\t\t\tvar lastDateMilliseconds = new Date(lastDate).getTime();\n\t\t\tvar numberOfDaysInRange = ((lastDateMilliseconds - firstDateMilliseconds) / 86400000) + 1;\n\t\t\t\n\t\t\t//Be sure both first and last dates are valid\n\t\t\tvar validDate = new Date(firstDate);\n\t\t\tvar validDate2 = new Date(lastDate);\n\t\t\tif((validDate == \"Invalid Date\") || (validDate2 == \"Invalid Date\")){\n\t\t\t\tshowErrorMessage(\"errorDiv-vacationDays\",\"Your date range includes an invalid date. Use the format <b>month/day/year</b>, and make sure the month number is '12' or less, and the day is '31' or less.\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\t//Check that the first date is before the last date\n\t\t\tif(firstDateMilliseconds > lastDateMilliseconds){\n\t\t\t\tshowErrorMessage(\"errorDiv-vacationDays\",\"The first date in your range is later than the last date in your range. Enter the earlier date first.\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\t//Check that the first date and last date are not the same\n\t\t\tif(firstDateMilliseconds == lastDateMilliseconds){\n\t\t\t\tshowErrorMessage(\"errorDiv-vacationDays\",\"The first and last dates in your range are the same.\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\t//Check that the first date is not in the past\n\t\t\tvar todaysDateMilliseconds = new Date(today.toDateString()).getTime();\n\t\t\tif(firstDateMilliseconds < todaysDateMilliseconds){\n\t\t\t\tshowErrorMessage(\"errorDiv-vacationDays\",\"That date range includes dates in the past. <br>We don't care about dates in the past.\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\t//IF the date range input passes all those error checks, go ahead and add the new vacation days\n\t\t\t\n\t\t\t//////////////////////////////////////////////\n\t\t\t//////////////////ADD A RANGE OF VACATION DAYS\n\t\t\t\n\t\t\t//If there are already some vacationDays saved, loop through and put the new vacation days in their place\n\t\t\tif(l > 0){\n\t\t\t\tfor(i=0;i<l;i++){\n\n\t\t\t\t\t//Find the place in the array to insert the date range by comparing the first date in the range to the existing dates\n\t\t\t\t\tvar existingDateMillisecondsToCheck = new Date(U.profiles[Profile].vacationDays[i]).getTime();\n\t\t\t\n\t\t\t\t\tif(firstDateMilliseconds == existingDateMillisecondsToCheck){\n\t\t\t\t\t\t\n\t\t\t\t\t\t//If the matched date is the last of the existing vacation days, just add the new dates on the end without adding the first date, by starting x at 1 instead of 0\n\t\t\t\t\t\tif ((i+1) == l){\n\t\t\t\t\t\t\t//CODE TO ADD EACH DATE IN THE RANGE\n\t\t\t\t\t\t\tfor(x=1;x<numberOfDaysInRange;x++){\n\t\t\t\t\t\t\t\tvar theNewDate = new Date(firstDateMilliseconds + (86400000 * x)).toLocaleDateString();\n\t\t\t\t\t\t\t\tU.profiles[Profile].vacationDays.splice((i+1+x),0,theNewDate);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t//Update userData and reflow the projects\n\t\t\t\t\t\t\tupdateUserData(1);\n\t\t\t\t\t\t\t$(\"#vacationDaysInput\")[0].value = \"\";\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t//If the matched date is not the last of the existing vacation days, insert all of the dates and remove duplicates after\n\t\t\t\t\t\t\n\t\t\t\t\t\t//ADD EACH DATE IN THE RANGE\n\t\t\t\t\t\tfor(x=0;x<numberOfDaysInRange;x++){\n\t\t\t\t\t\t\tvar theNewDate = new Date(firstDateMilliseconds + (86400000 * x)).toLocaleDateString();\n\t\t\t\t\t\t\tU.profiles[Profile].vacationDays.splice((i+x),0,theNewDate);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t//CONTINUE LOOKING THROUGH THE ARRAY AND REMOVE ANY DUPLICATES\n\t\t\t\t\t\tstartPosition = i + numberOfDaysInRange;\n\t\t\t\t\t\tvar newNumberOfVacationDays = U.profiles[Profile].vacationDays.length;\n\t\t\t\t\t\tvar remainingDaysToCheck = newNumberOfVacationDays - startPosition;\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor(x=0;x<remainingDaysToCheck;x++){\n\t\t\t\t\t\t\tvar existingDateMillisecondsToCheck = new Date(U.profiles[Profile].vacationDays[startPosition]).getTime();\n\t\t\t\t\t\t\tif(existingDateMillisecondsToCheck <= lastDateMilliseconds){\n\t\t\t\t\t\t\t\t//If the date being checked is less than or equal to the lastDate in our range, remove it\n\t\t\t\t\t\t\t\tU.profiles[Profile].vacationDays.splice((startPosition),1);\n\t\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//Update userData and reflow the projects\n\t\t\t\t\t\tupdateUserData(1);\n\t\t\t\t\t\t$(\"#vacationDaysInput\")[0].value = \"\";\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif(firstDateMilliseconds > existingDateMillisecondsToCheck){\n\t\t\t\t\t\t//If we are at the end of our loop, add the proposed date range at the end of the array and be done\n\t\t\t\t\t\tif(i+1 == l){\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//ADD EACH DATE IN THE RANGE\n\t\t\t\t\t\t\tfor(x=0;x<numberOfDaysInRange;x++){\n\t\t\t\t\t\t\t\tvar theNewDate = new Date(firstDateMilliseconds + (86400000 * x)).toLocaleDateString();\n\t\t\t\t\t\t\t\tU.profiles[Profile].vacationDays.splice((i+1+x),0,theNewDate);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t//Update userData and reflow the projects\n\t\t\t\t\t\t\tupdateUserData(1);\n\t\t\t\t\t\t\t$(\"#vacationDaysInput\")[0].value = \"\";\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//Otherwise, continue looking through the loop\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}else{\n\t\t\t\t\t\t//If we have come to a place where the existingDateToCheck is bigger than theFirstDate, insert the range there\n\t\t\t\t\t\t//ADD EACH DATE IN THE RANGE\n\t\t\t\t\t\tfor(x=0;x<numberOfDaysInRange;x++){\n\t\t\t\t\t\t\tvar theNewDate = new Date(firstDateMilliseconds + (86400000 * x)).toLocaleDateString();\n\t\t\t\t\t\t\tU.profiles[Profile].vacationDays.splice((i+x),0,theNewDate);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t//CONTINUE LOOKING THROUGH THE ARRAY AND REMOVE ANY DUPLICATES\n\t\t\t\t\t\tstartPosition = i + numberOfDaysInRange;\n\t\t\t\t\t\tvar newNumberOfVacationDays = U.profiles[Profile].vacationDays.length;\n\t\t\t\t\t\tvar remainingDaysToCheck = newNumberOfVacationDays - startPosition;\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor(x=0;x<remainingDaysToCheck;x++){\n\t\t\t\t\t\t\tvar existingDateMillisecondsToCheck = new Date(U.profiles[Profile].vacationDays[startPosition]).getTime();\n\t\t\t\t\t\t\tif(existingDateMillisecondsToCheck <= lastDateMilliseconds){\n\t\t\t\t\t\t\t\t//If the date being checked is less than or equal to the lastDate in our range, remove it\n\t\t\t\t\t\t\t\tU.profiles[Profile].vacationDays.splice((startPosition),1);\n\t\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//Update userData and reflow the projects\n\t\t\t\t\t\tupdateUserData(1);\n\t\t\t\t\t\t$(\"#vacationDaysInput\")[0].value = \"\";\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}//If no vacationDays have been saved already, simply add the dates\n\t\t\t\n\t\t\t//ADD EACH DATE IN THE RANGE\n\t\t\tfor(x=0;x<numberOfDaysInRange;x++){\n\t\t\t\tvar theNewDate = new Date(firstDateMilliseconds + (86400000 * x)).toLocaleDateString();\n\t\t\t\tU.profiles[Profile].vacationDays.push(theNewDate);\n\t\t\t}\n\t\t\t//Update userData and reflow the projects\n\t\t\tupdateUserData(1);\n\t\t\t$(\"#vacationDaysInput\")[0].value = \"\";\n\t\t\treturn true;\n\t\t\t\n\t\t}else{\n\t\t\t/////////WE DO NOT HAVE A DATE RANGE -- the date it is just poorly formatted.\n\t\t\tshowErrorMessage(\"errorDiv-vacationDays\",\"Please format your entry like this: <b>mm/dd/yyyy</b>. For a date range, use a hyphen between dates, like this: <b>mm/dd/yyyy-mm/dd/yyyy.</b> Do not use any spaces. ...And you should be golden.\");\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\t//Be sure it is a valid date\n\tvar validDate = new Date(theValue);\n\tif(validDate == \"Invalid Date\"){\n\t\tshowErrorMessage(\"errorDiv-vacationDays\",\"That is an invalid date. Use the format <b>month/day/year</b>, and make sure the month number is '12' or less, and the day is '31' or less.\");\n\t\treturn false;\n\t}\n\t\n\t//Be sure it is not a date in the past\n\tvar theProposedDateMilliseconds = new Date(theValue).getTime();\n\tvar todaysDateMilliseconds = new Date(today.toDateString()).getTime();\n\tif(theProposedDateMilliseconds < todaysDateMilliseconds){\n\t\tshowErrorMessage(\"errorDiv-vacationDays\",\"That date is in the past, dude.\");\n\t\treturn false;\n\t}\n\t\n\t//If there are already some vacationDays saved, loop through and check that the new vacationDay is not a duplicate\n\tif(l > 0){\n\t\tfor(i=0;i<l;i++){\n\t\t\tvar theProposedDate = new Date(theValue).toDateString();\n\t\t\tvar existingDateToCheck = new Date(U.profiles[Profile].vacationDays[i]).toDateString();\n\t\t\tif(theProposedDate == existingDateToCheck){\n\t\t\t\tshowErrorMessage(\"errorDiv-vacationDays\",\"That Vacation Day has already been saved. You're all set!\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\t\n\t//IF YOU HAVE PASSED THE GAUNTLET OF ERROR-CHECKING, LET'S ADD THE NEW VACATION DAY\n\t\n\t////////////////////////////////////////////\n\t//////////////////ADD A SINGLE VACATION DAY\n\tif(l > 0){\n\t\tfor(i=0;i<l;i++){\n\t\t\t//Loop through and put the new vacationDay in the right place according to chronological order\n\t\t\tvar existingDateMilliseconds = new Date(U.profiles[Profile].vacationDays[i]).getTime();\n\t\t\tif(theProposedDateMilliseconds > existingDateMilliseconds){\n\t\t\t\t//If we are at the end of our loop, add the proposed date at the end of the array and be done\n\t\t\t\tif(i+1 == l){\n\t\t\t\t\tU.profiles[Profile].vacationDays.splice((i+1),0,new Date(theValue).toLocaleDateString());\n\t\t\t\t\t//Update user data and reflow projects\n\t\t\t\t\tupdateUserData(1);\n\t\t\t\t\t$(\"#vacationDaysInput\")[0].value = \"\";\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\t//Otherwise, continue looking through the loop\n\t\t\t\tcontinue;\n\t\t\t}else{\n\t\t\t\tU.profiles[Profile].vacationDays.splice(i,0,new Date(theValue).toLocaleDateString());\n\t\t\t\t//Update user data and reflow projects\n\t\t\t\tupdateUserData(1);\n\t\t\t\t$(\"#vacationDaysInput\")[0].value = \"\";\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}else{\n\t\t//If there are no vacationDays saved, just simply add it\n\t\tU.profiles[Profile].vacationDays.push(new Date(theValue).toLocaleDateString());\n\t\t//Update user data and reflow projects\n\t\tupdateUserData(1);\n\t\t$(\"#vacationDaysInput\")[0].value = \"\";\n\t\treturn true;\n\t}\n}", "function isDateACHSafe(dateFieldIdName)\n{\n\tvar dateOne = Date.parse(nextSafeACHDueDate);\n\t\n\tvar dateValue = document.getElementById(dateFieldIdName);\n\n\tif(!dateOne || !dateValue) return false;\n\t\n\tvar dateTwo = Date.parse(dateValue.value);\n\t\n\tvar diff = dateTwo - dateOne;\n\tvar days = Math.floor(diff / ( 1000 * 60 * 60 * 24));\n\n\tif(days >= 0)\n\t{\n\t\treturn true\n\t}\n\n\treturn false;\n}", "check_date(date){\n \n if(typeof(date) == 'undefined' || date == null)\n return false;\n \n return moment(date, 'YYYY-MM-DD').isValid();\n }", "function validateCreated(cb_err) {\n if (typeof this.created !== 'undefined') {\n if (!validator.isDate(this.created)) {\n cb_err();\n }\n }\n }", "function validateClassDates(classDesc, classValue, effFromDateDesc, effFromDateValue,\r\n effToDateDesc, effToDateValue) {\r\n if (classValue == null || classValue == '') {\r\n return '';\r\n }\r\n var date1OnOrAfterDate2 = isDate2OnOrAfterDate1(effFromDateValue, effToDateValue);\r\n if (date1OnOrAfterDate2 == 'N') {\r\n return getMessage(\"ci.common.error.classDescription.after\", new Array(classDesc, effToDateDesc, formatDateForDisplay(effToDateValue), effFromDateDesc, formatDateForDisplay(effFromDateValue))) + \"\\n\";\r\n }\r\n else {\r\n return '';\r\n }\r\n}", "function checkDateOnBlur(field,dataBaseField)\n{\t\n\t\n\t/*if (wrongDate)\t\n \t{\t\n \t\twrongDate=false;\n \t\treturn;\n \t}\n \t\t\n \tif (field.value!=\"\")\n \t{\n \t\t//se il campo comincia con il carattere . oppure - seguito da un numero\n \t\t//si aggiungere/sottrae alla dataBase il numero di giorni specificato\n \t\tif((field.value.substr(0,1)==\".\" || field.value.substr(0,1)==\"-\") \n \t\t\t && dataBaseField && isDateField(dataBaseField))\n \t\t{\n \t\t\tvar offset=parseInt(field.value.substr(1));\n \t\t\tif(!isNaN(offset))\t//se l'offset � un numero\n \t\t\t{\n \t\t\t\tif(offset>9999)\n \t\t\t\t\toffset=9999;\n \t\t\t\tif(offset!=0)\n \t\t\t\t\toffset--;\t//in modo che la differenza fra data di partenza e quella finale coincide con l'offset\n \t\t\t\tif(field.value.substr(0,1)==\"-\")\n \t\t\t\t\toffset=-offset;\n\t \t\t\tvar d = getDateFromText(dataBaseField.value);\n\t \t\td.setDate(d.getDate()+offset);\n\t\t\t\tvar curr_date = d.getDate();\n\t\t\t\tvar curr_month = d.getMonth();\n\t\t\t\tcurr_month++;\n\t\t\t\tvar curr_year = d.getFullYear();\n\t \t\t\tfield.value=curr_date + \"/\" + curr_month + \"/\" + curr_year;\n \t\t\t}\n \t\t}\t\n \t\t\n\t \tif (!isDateField(field))\n\t \t{\n\t \t\talert(\"Data non valida\");\n\t \t\tfield.focus();\n\t \t\twrongDate=true;\n\t \t}\n\t \telse\n\t \t\twrongDate=false;\n }\n else\n wrongDate=false;\n if (wrongDate)\t\n \t{\t\n \t\twrongDate=false;\n \t\treturn;\n \t}*/\n \t\n \tif (field.getValue()!=\"\")\n \t{\n \t\t//se il campo comincia con il carattere . oppure - seguito da un numero\n \t\t//si aggiungere/sottrae alla dataBase il numero di giorni specificato\n \t\t\n \t\tif((field.getValue().substr(0,1)==\".\" || field.getValue().substr(0,1)==\"-\") \n \t\t\t && dataBaseField && isDateField(dataBaseField))\n \t\t{\n \t\t\tvar offset=parseInt(field.getValue().substr(1));\n \t\t\tif(!isNaN(offset))\t//se l'offset � un numero\n \t\t\t{\n \t\t\t\tif(offset>9999)\n \t\t\t\t\toffset=9999;\n \t\t\t\tif(offset!=0)\n \t\t\t\t\toffset--;\t//in modo che la differenza fra data di partenza e quella finale coincide con l'offset\n \t\t\t\tif(field.getValue().substr(0,1)==\"-\")\n \t\t\t\t\toffset=-offset;\n\t \t\t\tvar d = getDateFromText(dataBaseField.getValue());\n\t \t\td.setDate(d.getDate()+offset);\n\t\t\t\tvar curr_date = d.getDate();\n\t\t\t\tvar curr_month = d.getMonth();\n\t\t\t\tcurr_month++;\n\t\t\t\tvar curr_year = d.getFullYear();\n\t \t\t\tfield.setValue(curr_date + \"/\" + curr_month + \"/\" + curr_year);\n \t\t\t}\n \t\t}\t\n \t\t\n\t \tif (!isDateField(field))\n\t \t{\n\t \t\talert(\"Data non valida\");\n\t \t\tfield.focus();\n\t \t\twrongDate=true;\n\t \t}\n\t \telse\n\t \t\twrongDate=false;\n }\n else\n wrongDate=false;\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 parseInputs(e) {\r\n e.preventDefault();\r\n let startDate = document.querySelector(\"#startDate\");\r\n let endDate = document.querySelector(\"#endDate\");\r\n startDate = new Date(startDate.value).getTime();\r\n endDate = new Date(endDate.value).getTime();\r\n\r\n if (!startDate || ! endDate || endDate - startDate <= 0) {\r\n alert(\"start date must be > end date\");\r\n return;\r\n } else {\r\n onSubmit(startDate, endDate)\r\n }\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scope a src/dest tuple to the app path
function createSrcDestPre (getScope, getIpfs, rootPath) { return async (...args) => { const appPath = await getAppPath(getScope, getIpfs, rootPath) args[0][0] = Path.join(appPath, safePath(args[0][0])) args[0][1] = Path.join(appPath, safePath(args[0][1])) return args } }
[ "function createSrcPre (getScope, getIpfs, rootPath) {\n return async (...args) => {\n const appPath = await getAppPath(getScope, getIpfs, rootPath)\n args[0] = Path.join(appPath, safePath(args[0]))\n return args\n }\n}", "_applyCustomConfig() {\n\n this._backupSPFXConfig();\n\n // Copy custom gulp file to\n this.fs.copy(\n this.templatePath('gulpfile.js'),\n this.destinationPath('gulpfile.js')\n );\n\n // Add configuration for static assets.\n this.fs.copy(\n this.templatePath('config/copy-static-assets.json'),\n this.destinationPath('config/copy-static-assets.json')\n );\n\n }", "function assetsTask() { return src('assets/**/*') .pipe(dest('dist/assets')) }", "function processDestState() {\n //Error if arg value missing for -dest. Error if folder path resolves\n //to root or is invalid. Otherwise, store value and move on to next\n //argument.\n if ('-dest' !== sword) {\n if (CDIVUTILS.validateFolderPath(sword)) {\n oresult.sdest = sword;\n bok = true;\n sstate = '';\n } else {\n throw 'Invalid value for command -repo. Invalid statement: ' +\n sword;\n }\n }\n }", "function copy_src(){\n return gulp.src(['components/**/*.ts'])\n .pipe(gulp.dest('generated'));\n}", "function copyPathFn( fq_src_path_str, fq_dest_path_str, do_dir_copy ) {\n if ( do_dir_copy ) {\n return new Promise( function ( resolve_fn, reject_fn ) {\n ncpFn( fq_src_path_str, fq_dest_path_str,\n function ( error_data ) {\n if ( error_data ) { return reject_fn(); }\n resolve_fn();\n }\n );\n });\n }\n\n return new Promise( function ( resolve_fn, reject_fn ) {\n var\n read_obj = fsObj.createReadStream( fq_src_path_str ),\n write_obj = fsObj.createWriteStream( fq_dest_path_str ),\n full_reject_fn = makeRejectFuncFn( reject_fn ),\n full_resolve_fn = makeResolveFuncFn( resolve_fn )\n ;\n\n read_obj.on( 'error', full_reject_fn );\n write_obj.on( 'error', full_reject_fn );\n write_obj.on( 'close', full_resolve_fn );\n read_obj.pipe( write_obj );\n });\n }", "_backupSPFXConfig() {\n\n // backup default gulp file;\n // Fallback to NodeJS FS Object because otherwise in Yeoman context not possible\n fs.renameSync(\n this.destinationPath('gulpfile.js'),\n this.destinationPath('gulpfile.spfx.js')\n );\n\n }", "_writingSampleCode() {\n\n this.fs.copy(\n this.templatePath('sample/src/templates/HelloWorld.hbs'),\n this.destinationPath('src/webparts/templates/HelloWorld.hbs')\n )\n\n }", "function copyAssets () {\n return gulp.src(ASSET_SOURCE_PATH + '/**/*')\n .pipe(gulp.dest(BUILD_PATH + '/assets'));\n}", "function copyAssetToContext(src, dest, context) {\n var sourceAsset = path.join(testDir, src);\n var targetAsset = path.join(context.dir, dest);\n\n if (!fs.existsSync(sourceAsset)) {\n // The source asset requested is missing\n throw new Error(\"The test asset is missing\");\n }\n\n // Attempt to copy the asset\n fs.copySync(sourceAsset, targetAsset);\n\n if (!fs.existsSync(targetAsset)) {\n // The target asset was not copied successfully\n throw new Error(\"The test asset could not be copied\");\n }\n}", "function destPath() {\n // Remove preceding slash '/'.\n return window.location.pathname.slice(1) + window.location.search;\n }", "extend(config) {\n\t\t\t// Add '~/shared' as an alias.\n\t\t\tconfig.resolve.alias.shared = resolve(__dirname, '../shared');\n\t\t\tconfig.resolve.alias['~shared'] = resolve(__dirname, '../shared');\n\t\t}", "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 }", "function FileSystemProvider(opts) {\r\n\tthis.directory = directory.resolver(opts || \"./views\");\t\r\n}", "function sourceFiles2ProjAsync(files) { // Last object of \"files\" will be name of the project where files will be added to NEEDSTOBECHANGED\n logger.debug(\"sourceFiles2ProjAsync\");\n var proj_name = files[files.length - 1];\n var docpath = remote.app.getPath('documents');\n\n var f2p_options = {\n name: proj_name,\n cwd: path.join(docpath, 'SLIPPS DECSV\\\\Projects\\\\' + proj_name + '\\\\')\n }\n const f2p_store = new Store(f2p_options);//\n var pre_dirfiles = f2p_store.get('source-files', []);\n logger.debug(pre_dirfiles);\n\n ipcRenderer.on('async-import-files-reply', (event, arg) => {\n logger.debug(\"BACK FROM APP - import files into project\");\n var dirfiles = fs.readdirSync(path.join(docpath, 'SLIPPS DECSV\\\\Projects\\\\' + proj_name + '\\\\source\\\\'));\n logger.debug(docpath);\n logger.debug(dirfiles);\n //console.log(\"RETURNED FROM APP: \");\n //console.log(arg);\n if (arg[0]) {\n // do something if importing was successful\n logger.debug(\"DONE IMPORTING SOURCE FILES!\");\n }\n else {\n logger.debug(\"ERROR WHILE IMPORTING!\");\n var reason1 = arg[1];\n // SHOW REASON TO USER! \n }\n logger.debug(\"STORE SOURCE: \" + f2p_store.get(\"source-files\", \"NONE!!!!\"));\n f2p_store.set(\"source-files\", dirfiles);\n ipcRenderer.removeAllListeners('async-import-files-reply');\n\n ipcRenderer.on('async-transform-files-reply', (event, arg) => {\n logger.debug(\"BACK FROM APP - returned from transforming src files to temp\");\n if (arg[0]) {\n logger.info(\"SRC to TEMP conversion success!\");\n // successfully ended the temp conversion\n logger.debug(\"SUCCESS AND FAIL ARRAYS\");\n logger.debug(arg[1]);//success array\n logger.debug(arg[2]);//fail array\n // filearr 0 = fileoriginal, 1 = filetemp, 2 = filedonestatus\n\n // fileS,\"temp#\"+fileS+\".json\",false\n for (var a = 0; a < arg[1].length; a++) {\n var fileArr = [];\n fileArr.push(arg[1][a][0], arg[1][a][1], arg[1][a][2]); // NEEDS UPDATE!!!!!! CUSTOM INPUT\n addProjFile(fileArr);\n }\n }\n else {\n logger.error(\"SRC to TEMP conversion failed!\");\n var reason2 = arg[1];\n // SHOW REASON TO USER!\n\n //folders missing\n }\n //var testing_opt = {\n // name: \"temp#\"+arg[1][0],\n // cwd: path.join(docpath, 'SLIPPS DECSV\\\\Projects\\\\' + proj_name + '\\\\temp\\\\')\n //}\n /*\n const testing_store = new Store(testing_opt);\n var teststring = testing_store.get(\"c\",\"AHAHAHAHAHAHAHAH\");\n //THIS IS FOR TESTING\n $(\"#edita-div\").addClass(\"is-shown\");\n $(\"#edit-A-edit-text\").html(teststring);\n */\n\n //updateFileList(proj_name);\n ipcRenderer.removeAllListeners('async-transform-files-reply');\n });\n ipcRenderer.send('async-transform-files', proj_name);\n });\n logger.debug(\"SENDING ASYNC TO MAIN APP!\");\n var send_arg = [];\n send_arg.push(files);\n send_arg.push(pre_dirfiles);\n logger.debug(\"########### LISTING FILELIST GOING TO BE SENT\");\n logger.debug(files);\n logger.debug(pre_dirfiles);\n ipcRenderer.send('async-import-files', send_arg);\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 setPortForDragandDrop(device,action){\n\tsetSlotForDragandDrop(device);\n\tvar cnt = 0;\n\tvar prtArr = [];\n\tif(globalInfoType == \"JSON\"){\n\t\tprtArr = getDeviceChildPort(device,prtArr);\n }else{\n prtArr = device.PortArr;\n }\n\tvar flag = false;\n\tfor(var t=0 ; t<prtArr.length; t++){\n\t\tif(prtArr[t].PORTMAP != undefined && prtArr[t].PORTMAP != null && prtArr[t].PORTMAP.length == 0){\n\t\t\tif(action == \"source\"){\n\t\t sourcePath = prtArr[t].ObjectPath;\n\t\t }else{\n \t\tdstPath = prtArr[t].ObjectPath;\n \t\t}\n\t\t\tflag = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(flag == false){\n\t\tvar slotcnt = 0;\n\t\tslotcnt = getSlotCount(device,slotcnt);\t\n\t\tcnt = getPortNumber(prtArr,cnt);\n\t\tvar portpath = device.ObjectPath+ \".Slot_\"+slotcnt+ \".Port_\"+cnt;\n\t\tif(action == \"source\"){\n\t\t\tsourcePath = portpath;\n\t\t}else{\n\t\t\tdstPath = portpath;\n\t\t}\n\t\tvar portname = \"Port_\" + cnt;\n\t\tstorePortInformation(\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",portname,\"new\",\"true\",portpath,\"\",\"\",\"\",\"\",\"\",lineSpeed,enablePort,\"Exclusive\",\"\",\"\",lineType,\"false\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",device.ObjectPath+\".Slot_\"+cnt);\n\t}\n}", "s(root, path) {\n let sourcemap = this.v(root,\n `${path ? path + '.' : ''}attributes.sourceMap[0]`, null);\n\n if (sourcemap) {\n sourcemap = this.convertSourcemap(sourcemap);\n }\n\n return sourcemap;\n }", "function setupDistBuild(cb) {\n context.dev = false;\n context.destPath = j('dist', context.assetPath);\n del.sync('dist');\n cb();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates hidden divs to store the letters
function storeLetters(letters) { let letterContainer = document.getElementById("letterContainer"); for (const char of letters) { let underlined = document.createElement("div"); underlined.setAttribute("class", "underlined"); letterContainer.appendChild(underlined); var charContainer = document.createElement("div"); charContainer.setAttribute("hidden", ""); charContainer.setAttribute("class", "hiddenChar"); charContainer.innerHTML = char; underlined.appendChild(charContainer); } }
[ "function genBoxes() {\n for (var i = 0; i < answer_length; i++) {\n\n if (answer[i] != \" \") {\n var letter = answer[i].toUpperCase();\n // var $newBoxDiv = $(\"<div class='letterBox'></div> \").text(answer[i].toUpperCase());\n // var $newBoxDiv = $(\"<div class ='flip-container'> <div class='card'> <div class='front'></div> <div class='letterBox back'></div></div></div> \");\n var $newBoxDiv = \"<div class ='flip-container'>\" +\n \"<div class='card'>\" +\n \"<div class='letterBox front'>\" + letter + \"</div>\" + //need letterbox class because the front is visible when click, front font size =0 to hide the char\n \"<div class='letterBox back'>\" + letter + \"</div>\" +\n \"</div></div>\";\n answer_length_nospace++;\n }\n else {\n // if asnwer character is space, then generate blank box\n var $newBoxDiv = $(\"<div class='letterBoxSpace'></div>\");\n }\n //append to DIV\n $letterBoxesHolder.append($newBoxDiv);\n\n }\n\n}", "function start(){\n\tvar div = \"\";\n\tfor ( i = 0; i < 25; i++) {\n\t\tvar element = \"let\" + i;\n\t\tdiv = div + '<div class = \"letter\" onclick = \"check('+i+')\" id=\"'+element+'\">'+letters[i]+'</div>';\n\t\tif ((i + 1) % 7 == 0) div = div + '<div style = \"clear:both;\"></div>';\n\t}\n\tdocument.getElementById(\"alphabet\").innerHTML = div;\n\tgenerateWord();\n}", "function showCurrentWord() { \n var wordChoiceDiv = document.getElementById(\"wordChoices\");\n wordChoiceDiv.innerHTML = \"<div id=\\\"wordChoices\\\"></div>\"; // Clears the Div tag for each word\n console.log(currentWord); \n for (var i = 0; i < currentWord.length; i++) { // for every letter in the currentWord, type an underscore\n var newSpan = document.createElement(\"span\");\n newSpan.innerHTML= \"_ \";\n newSpan.setAttribute(\"id\",\"letter-\"+i);\n wordChoiceDiv.appendChild(newSpan); \n } \n }", "function hideLetters() {\n\t\t\thide = '';\n\t\t\tfor(i = 0; i < word.length; i++) {\n\t\t\t\thide += \"-\";\n\t\t\t}\n\t\t\tconsole.log(hide);\n\t\t\tvar targetA = document.getElementById(\"word\");\n\t\t\ttargetA.innerHTML = hide;\n\t\t}", "function displayWord(word) {\n splitWord = word.split(\"\");\n firstLetter = splitWord[0];\n $.each(splitWord, function (index) {\n $(\".word\").append(\n `<div class=\"letter-box b-neon-blue\" id=\"${index}\"></div>`\n );\n });\n }", "function start()\r\n{\r\n \r\n let div_content =\"\";\r\n \r\n for (i=0; i<=11; i++)\r\n {\r\n let element = \"number\" + i;\r\n div_content = div_content + '<div class=\"letter\" onclick=\"run('+i+')\" id=\"'+element+'\">'+numbers[i]+'<br>'+letter[i]+'</div>';\r\n if ((i+1) % 3 ==0) div_content = div_content + '<div style=\"clear:both;\"></div>';\r\n }\r\n \r\n document.getElementById(\"key_cont\").innerHTML = div_content;\r\n \r\n\r\n}", "function displayWord(){\n // 1) create the container to append each letter\n var container = $(\"<p>\")\n // 2) loop through the userArray and append their word to the container\n userCountryArray.forEach(function(element){\n if (element == \" \"){\n container.append( $(\"<span>\").html(\"__ \") );\n } else if(element == \"//\") {\n container.append( $(\"<span>\").html(\"&nbsp;\") );\n } else{\n container.append( $(\"<span>\").html(element) );\n }\n })\n //3) empty the user word container\n $(\"#word_target\").empty();\n //4) update the user word with the container\n $(\"#word_target\").append(container);\n}", "renderMainForm() {\n this.cryptoArray = this.cryptogram.split(\" \")\n this.mainCryptoDiv = document.createElement('div')\n this.mainCryptoDiv.id = \"main-crypto-div\"\n\n this.cryptoArray.forEach(word => {\n this.wordSpan = document.createElement('span')\n this.wordSpan.className = \"word-span\"\n\n this.fieldDiv = document.createElement('div')\n this.labelDiv = document.createElement('div')\n\n this.charArray = word.split('')\n this.charArray.forEach(char => {\n if (/[A-Z]/.test(char)) {\n this.charInput = this.createCharInput(char)\n this.charInput.className = 'char-input'\n\n this.charInput.addEventListener('input', this.handleInputToAll)\n \n this.charLabel = this.createCharLabel(char)\n\n this.charLabelSpan = document.createElement('span')\n this.charLabelSpan.className = 'char-label'\n this.charLabelSpan.append(this.charLabel)\n \n this.fieldDiv.append(this.charInput)\n this.labelDiv.append(this.charLabelSpan)\n } else {\n this.charSpan = document.createElement('span')\n this.charSpan.innerText = char\n this.charSpan.className = 'punctuation'\n this.fieldDiv.append(this.charSpan)\n }\n })\n this.wordSpan.append(this.fieldDiv, this.labelDiv)\n this.mainCryptoDiv.append(this.wordSpan)\n })\n return this.mainCryptoDiv\n }", "function updateHiddenCharacters(){\n var hiddenCharacters = [];\n var shownCharacters = [];\n $('.character_circle').each(function(i, obj) {\n shownCharacters.push(obj);\n for(var j =0; j< hiddenInputs.length; j++){\n var numInputs = $(obj).attr(hiddenInputs[j]);\n\n if(numInputs > 0){\n shownCharacters.splice(shownCharacters.indexOf(obj), 1);\n hiddenCharacters.push(obj);\n break;\n }\n }\n });\n for(var k = 0; k < shownCharacters.length; k++){\n $(shownCharacters[k]).show(400);\n }\n for(var k = 0; k < hiddenCharacters.length; k++){\n $(hiddenCharacters[k]).hide(400);\n }\n}", "showMatchedLetter(letter) {\n\t\tlet currentLetter = letter.textContent;\n\t\tlet letterBoxes = document.querySelectorAll('.letter');\n\t\tfor (let i = 0; i < letterBoxes.length; i++) {\n\t\t\tif (letterBoxes[i].classList.contains(currentLetter)) {\n\t\t\t\tletterBoxes[i].classList.remove('hide');\n\t\t\t\tletterBoxes[i].classList.add('show');\n\t\t\t\tletterBoxes[i].textContent = currentLetter;\n\t\t\t\tif (shownLetters <= letterBoxes.length) {\n\t\t\t\t\tshownLetters += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "showMatchedLetter(input) {\r\n const letters = Array.from(document.getElementsByClassName(\"letter\"));\r\n letters\r\n .filter(letter => letter.classList.contains(input))\r\n .forEach(li => li.classList.replace('hide', 'show'));\r\n }", "function hideLevels(lower, upper){\n\tfor( let i = lower; i <= upper; i++){\n\t\tfor(let j = 2; j < 8; j++){\n\t\t\tdocument.getElementById(\"r\"+j+\"c\"+i+\"_text\").style.visibility = \"hidden\";\n\t\t\tdocument.getElementById(\"r\"+j+\"c\"+i+\"_button\").style.visibility = \"hidden\";\n\t\t\tif(j%2 !== 0){\n\t\t\t\tdocument.getElementById(\"r\"+j+\"c\"+i+\"_text2\").style.visibility = \"hidden\";\n\t\t\t\tdocument.getElementById(\"r\"+j+\"c\"+i+\"_text3\").style.visibility = \"hidden\";\n\t\t\t}\n\t\t\t\n\t\t}\n\tdocument.getElementById(\"r\"+1+\"c\"+i+\"_text\").style.visibility = \"hidden\";\n\t}\n}", "function revealLetter() {\n\t\t\tuserGuessIndex = word.indexOf(userGuess);\n\t\t\tfor (i=0; i < word.length; i++) {\n\t\t\t\tif (word[i] === userGuess) {\n\t\t\t\t\thide = hide.split(\"\");\n\t\t\t\t\thide[i] = userGuess;\n\t\t\t\t\thide = hide.join(\"\");\n\t\t\t\t\ttargetA.innerHTML = hide;\n\n\t\t\t\t}\n\t\t\t}\t\n\t\t}", "function hidePopups(){\n\tvar keys = document.getElementById(\"keysDiv\");\n\tkeys.style.visibility = \"visible\";\n\tvar len=popupList.length;\n\tfor(var i=0;i<len;i++){\n\t\tdocument.getElementById(popupList[i]).style.visibility = \"hidden\";\n\t}\n}", "function chooseCharSubset(s) {\n\tvar l = document.getElementById('editpage-specialchars').getElementsByTagName('p');\n\tfor (var i = 0; i < l.length ; i++) {\n\t\tl[i].style.display = i == s ? 'inline' : 'none';\n\t\tl[i].style.visibility = i == s ? 'visible' : 'hidden';\n\t}\n}", "function makeCards() {\n //clear previous search results\n cardWrapperDiv.innerHTML = ``;\n for (let i = 0; i < recipeList.length; i++) {\n let newCard = document.createElement(`div`);\n newCard.classList.add(`card`);\n newCard.setAttribute(`data-id`, [i]);\n newCard.setAttribute(`style`, `background-image: url(${recipeList[i].image}); background-position: center;`);\n\n newCard.innerHTML = `\n <div >\n <span class=\"card-title\">${recipeList[i].label}</span>\n </div> \n `;\n cardWrapperDiv.append(newCard);\n\n }\n\n }", "createElements() {\n //Create div containers\n var divEl = document.createElement(\"div\");\n var innerDivEl = document.createElement(\"div\");\n\n //Create h3 element for title, set its text to the question, append to div.\n var questionEl = document.createElement(\"h3\");\n questionEl.textContent = this.question;\n divEl.appendChild(questionEl);\n\n //create a shuffled indexer for our answers\n var answerIndex = shuffleIndex(this.answers.length);\n\n //loop through and create answer button elements, append them to the bottom of the question element.\n for (var i = 0; i < this.answers.length; i++) {\n var buttonEl = document.createElement(\"button\");\n buttonEl.textContent = this.answers[answerIndex[i]];\n\n innerDivEl.append(buttonEl);\n }\n\n divEl.appendChild(innerDivEl);\n\n return divEl;\n }", "function displaySentence(letterArray) {\n let formHTML = `<form id=\"sentenceForm\">`;\n letterArray.forEach(letter => {\n formHTML += `<div class=\"word\"><input type=\"text\" id=\"${letter}\" name=\"${letter}\" placeholder=\"${letter}\"></input></div>`;\n })\n formHTML += `</form>`;\n sentenceForm.innerHTML = formHTML;\n}", "buildKeyboard() {\n\t\tconst keybed = this.keyboard.getElementsByClassName('keybed');\n\t\tconst octaves = window.innerWidth / (window.innerWidth < 800 ? 600 : 500);\n\t\tkeybed[0].innerHTML = this.generateKeys(octaves, window.innerWidth < 800 ? 3 : 2);\n\t\tthis.keyboard.style.display = '';\n\t\tthis.initKeyListeners();\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
data should be an array of objects, each with two keys options should be an object of arrays, each with two elements (first one for the left column, second for the right column) options should specify the headers, fields, and alignment (right or left)
function printTable(options, data) { // Calculate widths for each column let fieldMax = [] options.fields.forEach((field, i) => { fieldMax[i] = Math.max.apply(Math,data.map(function(item) { return item[field].toString().length })) }) const leftLength = Math.max(fieldMax[0], options.headers[0].length) + 2 const rightLength = Math.max(fieldMax[1], options.headers[1].length) + 2 // The lines on top/bottom/between header and data const rowSeparator = '| ' + Array(leftLength).join('-') + '+' + Array(rightLength).join('-') + ' |' // Console log the table console.log(rowSeparator) printDataRow(options.headers[0], options.headers[1]) console.log(rowSeparator) data.forEach((row) => { printDataRow(row[options.fields[0]], row[options.fields[1]]) }) console.log(rowSeparator) // Function to create the header and data rows function printDataRow (leftData, rightData) { let leftDataRow = '' let rightDataRow = '' if (options.alignment[0] === 'left') { leftDataRow = '| ' + leftData + Array(leftLength - leftData.toString().length - 1).join(' ') + ' | ' } else { leftDataRow = '| ' + Array(leftLength - leftData.toString().length - 1).join(' ') + leftData + ' | ' } if (options.alignment[1] === 'left') { rightDataRow = rightData + Array(rightLength - rightData.toString().length - 1).join(' ') + ' |' } else { rightDataRow = Array(rightLength - rightData.toString().length - 1).join(' ') + rightData + ' |' } const dataRow = leftDataRow + rightDataRow console.log(dataRow) } }
[ "tabulate(\n headers,\n rows,\n options) {\n if (!_.isArray(headers))\n TypeException(\"headers\", \"array\")\n if (!rows)\n TypeException(\"rows\", \"array\")\n if (_.any(rows, x => { return !_.isArray(x); }))\n TypeException(\"rows child\", \"array\")\n var o = _.extend({}, KingTableTextBuilder.options, options || {});\n var headersAlignment = o.headersAlignment,\n rowsAlignment = o.rowsAlignment,\n padding = o.padding,\n cornerChar = o.cornerChar,\n headerLineSeparator = o.headerLineSeparator,\n cellVerticalLine = o.cellVerticalLine,\n cellHorizontalLine = o.cellHorizontalLine,\n minCellWidth = o.minCellWidth,\n headerCornerChar = o.headerCornerChar;\n if (padding < 0)\n OutOfRangeException(\"padding\", 0)\n var self = this;\n // validate the length of headers and of each row: it must be the same\n var headersLength = headers.length;\n if (!headersLength)\n ArgumentException(\"headers must contain at least one item\")\n if (_.any(rows, x => { x.length != headersLength; }))\n ArgumentException(\"each row must contain the same number of items\")\n\n var s = \"\"\n\n // sanitize all values\n _.reach(headers, x => {\n return this.checkValue(x);\n })\n _.reach(rows, x => {\n return this.checkValue(x);\n })\n\n var valueLeftPadding = S.ofLength(SPACE, padding)\n padding = padding * 2;\n // for each column, get the cell width\n var cols = _.cols([headers].concat(rows)),\n colsLength = _.map(cols, x => {\n return Math.max(_.max(x, y => { return y.length; }), minCellWidth) + padding;\n });\n // does the table contains a caption?\n var totalRowLength;\n var caption = o.caption, checkLength = 0;\n if (caption) {\n checkLength = padding + caption.length + 2;\n }\n\n // does option contains information about the pagination?\n var paginationInfo = self.paginationInfo(o);\n if (paginationInfo) {\n // is the pagination info bigger than whole row length?\n var pageInfoLength = padding + paginationInfo.length + 2;\n checkLength = Math.max(checkLength, pageInfoLength);\n }\n\n // check if the last column length should be adapted to the header length\n if (checkLength > 0) {\n totalRowLength = _.sum(colsLength) + (colsLength.length) + 1;\n if (checkLength > totalRowLength) {\n var fix = checkLength - totalRowLength;\n colsLength[colsLength.length - 1] += fix;\n totalRowLength = checkLength;\n }\n }\n\n if (caption) {\n s += cellVerticalLine + valueLeftPadding + caption + S.ofLength(SPACE, totalRowLength - caption.length - 3) + cellVerticalLine + RN;\n }\n if (paginationInfo) {\n s += cellVerticalLine + valueLeftPadding + paginationInfo + S.ofLength(SPACE, totalRowLength - paginationInfo.length - 3) + cellVerticalLine + RN;\n }\n\n var headCellsSeps = _.map(colsLength, l => {\n return S.ofLength(headerLineSeparator, l);\n }),\n cellsSeps = _.map(colsLength, l => {\n return S.ofLength(cellHorizontalLine, l);\n });\n\n var headerLineSep = \"\";\n // add the first line\n _.each(headers, (x, i) => {\n headerLineSep += headerCornerChar + headCellsSeps[i];\n });\n // add last vertical separator\n headerLineSep += headerCornerChar + RN;\n\n if (paginationInfo || caption) {\n s = headerLineSep + s;\n }\n s += headerLineSep;\n\n // add headers\n _.each(headers, (x, i) => {\n s += cellVerticalLine + self.align(valueLeftPadding + x, colsLength[i], headersAlignment);\n });\n\n // add last vertical singleLineSeparator\n s += cellVerticalLine + RN;\n\n // add header separator\n s += headerLineSep;\n\n // build line separator\n var lineSep = \"\", i;\n for (i = 0; i < headersLength; i++)\n lineSep += cornerChar + cellsSeps[i];\n lineSep += cornerChar;\n\n // build rows\n var rowsLength = rows.length, j, row, value;\n for (i = 0; i < rowsLength; i++) {\n row = rows[i];\n for (j = 0; j < headersLength; j++) {\n value = row[j];\n s += cellVerticalLine + self.align(valueLeftPadding + value, colsLength[j], rowsAlignment);\n }\n s += cellVerticalLine + RN;\n s += lineSep + RN;\n }\n return s;\n }", "parseFetchedResult(data) {\n const {bodyDataKey, footerDataKey} = this.props\n if (check.object(data)) {\n if (data[bodyDataKey]) this.setState({tableBodyData: data[bodyDataKey]})\n if (data[footerDataKey]) this.setState({tableFooterData: data[footerDataKey]})\n } else if (check.array(data)) {\n this.setState({tableBodyData: data})\n } else {\n throw new Error('Invalid data format')\n }\n }", "function detailColumns(options) {\n options = object.extend({width: '110px', columns: 2}, options || {})\n var cols = []\n for (var i = 0; i < options.columns; i++) {\n cols.push(template.COL({width: options.width}))\n cols.push(template.COL())\n }\n return template.COLGROUP(cols)\n}", "function adjustDataFieldNames(data) {\n var adjustedData = [];\n _.each(data, function(rowItem) {\n var adjustedRowItem = adjustFieldNames(rowItem);\n adjustedData.push(adjustedRowItem);\n });\n return adjustedData;\n }", "function data_table_simple(array, div_id) {\n key_names = Object.keys(array[0])\n columns_list = []\n key_names.forEach(function(i) {\n columns_list.push({\n data: i,\n title: i,\n name: i\n })\n })\n div_id = div_id || \"#table\"\n array.forEach(function(D) {\n key_check_func_dictionary(key_names, D)\n })\n return $(div_id).DataTable({\n paging: false,\n dom: '<\"html5buttons\"B>lTfgitp',\n data: array,\n columns: columns_list,\n select: true,\n colReorder: true,\n buttons: [{\n extend: \"excel\",\n title: document.title\n }, {\n extend: \"colvis\",\n title: document.title\n }],\n order: [3, \"desc\"]\n });\n}", "function generateOptionTable(options) {\n let text = dedent`\\n\n | Name | Type | Description |\n | ---- | ---- | ----------- |\n `;\n\n Object.entries(options).forEach(([option, value]) => {\n if (option.includes('-')) {\n return;\n }\n\n text += `\\n| ${option} | ${makeType(value)} | ${value.description} |`;\n });\n\n return text;\n}", "format(options) {\n this._withTable(options, ({ range, lines, table, focus }) => {\n let newFocus = focus;\n // complete\n const completed = formatter.completeTable(table, options);\n if (completed.delimiterInserted && newFocus.row > 0) {\n newFocus = newFocus.setRow(newFocus.row + 1);\n }\n // format\n const formatted = formatter.formatTable(completed.table, options);\n newFocus = newFocus.setOffset(exports._computeNewOffset(newFocus, completed.table, formatted, false));\n // apply\n this._textEditor.transact(() => {\n this._updateLines(range.start.row, range.end.row + 1, formatted.table.toLines(), lines);\n this._moveToFocus(range.start.row, formatted.table, newFocus);\n });\n });\n }", "alignColumn(alignment, options) {\n this._withTable(options, ({ range, lines, table, focus }) => {\n let newFocus = focus;\n // complete\n const completed = formatter.completeTable(table, options);\n if (completed.delimiterInserted && newFocus.row > 0) {\n newFocus = newFocus.setRow(newFocus.row + 1);\n }\n // alter alignment\n let altered = completed.table;\n if (0 <= newFocus.column &&\n newFocus.column <= altered.getHeaderWidth() - 1) {\n altered = formatter.alterAlignment(completed.table, newFocus.column, alignment, options);\n }\n // format\n const formatted = formatter.formatTable(altered, options);\n newFocus = newFocus.setOffset(exports._computeNewOffset(newFocus, completed.table, formatted, false));\n // apply\n this._textEditor.transact(() => {\n this._updateLines(range.start.row, range.end.row + 1, formatted.table.toLines(), lines);\n this._moveToFocus(range.start.row, formatted.table, newFocus);\n });\n });\n }", "setColumnValues(index, options) {\n const column = this.children[index];\n\n if (column && JSON.stringify(column.data.options) !== JSON.stringify(options)) {\n column.set({\n options\n }, () => {\n column.setIndex(0);\n });\n }\n }", "function formatData(data){\n //var severityNames = [\"unknown\", \"negligible\", \"low\", \"medium\", \"high\", \"critical\"]\n var severityNames = [\"Critical\", \"High\", \"Medium\", \"Low\"];\n var packageNames = [];\n var blockData = [];\n data = data.sort(function(a, b) { \n return (a.Critical + a.High + a.Medium + a.Low) < (b.Critical + b.High + b.Medium + b.Low);\n //return (b.critical * 3 + b.high * 2 + b.medium * 1 ) - (a.critical * 3 + a.high * 2 + a.medium * 1 );\n });\n\n for(var i = 0; i < data.length; i++){\n var y = 0;\n packageNames.push(data[i].package);\n for(var j = 0; j < severityNames.length; j++){\n var height = parseFloat(data[i][severityNames[j]]);\n var block = {'y0': parseFloat(y),\n 'y1': parseFloat(y) + parseFloat(height),\n 'height': height,\n 'x': data[i].package,\n 'cluster': severityNames[j]};\n y += parseFloat(data[i][severityNames[j]]);\n blockData.push(block);\n }\n }\n\n return {\n blockData: blockData,\n packageNames: packageNames,\n severityNames: severityNames\n };\n\n}", "function fetchData(data, callback, settings) {\n var normQuery = {};\n var orderCol = parseInt(data.order.column, 10);\n\n normQuery['columns'] = data.columns;\n\n angular.forEach(data.columns, function(value, index) {\n \n })\n\n if (!isNaN(orderCol)) {\n normQuery['order'] = {\n column: data.columns[orderCol].data,\n dir: data.order.dir\n }\n }\n\n normQuery['search'] = {};\n\n angular.forEach(scope.filters, function(value, index) {\n if (value.model && value.model !== '__all') {\n normQuery.search[value.name] = value.model;\n } \n });\n\n scope.conf.dataSource(normQuery, callback);\n }", "function drawDataInTable( data, prop, value ) {\r\n var response = \"<div class='tableHeader'>\" + prop + \": \" + value + \"</div>\";\r\n response += \"<table style='width:100%;text-align:left;border:1px solid black;'><tr><th>Date</th><th>App Version</th><th>Test Case ID</th><th>OBS ID</th></tr>\";\r\n for( var index = 0; index < data.length; index++ ) {\r\n response += \"<tr>\";\r\n response += \"<td>\" + data[index].Date + \"</td>\";\r\n response += \"<td>\" + data[index].App_Version + \"</td>\";\r\n response += \"<td>\" + data[index].Test_Case_Id + \"</td>\";\r\n response += \"<td>\" + data[index].OBS_ID + \"</td>\";\r\n response += \"</tr>\";\r\n }\r\n response += \"</table>\";\r\n return response;\r\n }", "function CallBack_ShowColumSubType(data) {\r\n grid_columnsubtypes.SetDatasource(data);\r\n}", "function makeAreaData(data){\n return data.map(function(d){\n return {\n \"Date\" : d[\"Date\"],\n \"DateP\" : d[\"DateP\"],\n \"Other\" : d[\"otherPercent\"],\n \"Dormant\" : d[\"dormantPercent\"],\n \"Other Shifts\" : d[\"otherShiftsPercent\"],\n \"Leave\" : d[\"leavePercent\"],\n \"CNIC Mismatch\" : d[\"CNICPercent\"]\n }\n })\n }", "function applyMultiselectOptions(data, fields, gridApi, exclusionaryMode) {\n // Create a column accessor function\n var colAccessor = getColAccessor(gridApi)\n\n // Apply options data to column options\n _.each(fields, function(d) {\n var opts = _.chain(data)\n .pluck(d)\n .unique()\n .sortBy()\n .value()\n\n // Adds items prefixed with !\n if (exclusionaryMode) {\n opts = opts.concat(_.map(opts, function(d) { return '!' + d }))\n }\n\n colAccessor(d).filter.options = opts\n })\n }", "function dataObjsToDataTables(dataObjs,dataTables){\n // sanity check the data\n if(dataObjs.length<1){\n console.log('dataObjsToDataTables: error, dataObjs.length < 1');\n return;\n }\n // get the first valid dataObj\n var firstValidIndex = getFirstValidIndex();\n if(dataObjs[firstValidIndex].data.length<=0){\n console.log('dataObjsToDataTables: error, data.length < 1')\n return;\n }\n if(dataObjs[firstValidIndex].headings.length<=0){\n console.log('dataObjsToDataTables: error, headings.length < 1')\n return;\n }\n if(dataObjs[firstValidIndex].data[0].length<=0){\n console.log('dataObjsToDataTables: error, data[0].length < 1')\n return;\n } \n var numHeadings = dataObjs[firstValidIndex].headings.length;\n var numCols = dataObjs[firstValidIndex].data[0].length;\n var numRows = dataObjs[firstValidIndex].data.length;\n var headings = dataObjs[firstValidIndex].headings;\n var numDataTables = numHeadings;\n var numObjs = dataObjs.length;\n console.log('numHeadings ' + numHeadings + ' nuCols ' + numCols + ' numRows ' + numRows + ' headings ' + headings);\n if(numCols!=numHeadings){\n console.log('dataObjsToDataTables: error, numCols!=numHeadings');\n return;\n }\n // set up the mapping from a dataObj's index in the vector to the dataTable column index\n var dataObjColIndex = [];\n for(obj=0;obj<numObjs;++obj){\n var suffixAndExt = dataObjs[obj].fileName.split(\"_\").pop();\n var suffix = suffixAndExt.substr(0, suffixAndExt.indexOf('.'));\n dataObjColIndex.push(Number(suffix));\n }\n // first check that the dataObjs are compatible\n for(i=0;i<dataObjs.length;++i){\n if(!dataObjs[i].initialized) continue;\n var fileName = dataObjs[i].filename\n if(dataObjs[i].headings.length!=numHeadings){\n console.log('dataObjsToDataTables: error, ' + fileName + ' has an invalid number of headings');\n return;\n }\n if(dataObjs[i].data[0].length!=numCols){\n console.log('dataObjsToDataTables: error, ' + fileName + ' has an invalid number of columns');\n return;\n }\n // get the column number from the filename \n for(j=0;j<numHeadings;++j){\n if(dataObjs[i].headings[j]!=headings[j]){\n console.log('dataObjsToDataTables: error, ' + fileName + ' headings do not match');\n return;\n }\n }\n }\n // collate the data objects data into a data table for each column\n // one dataTable for every heading with a column for every dataObj\n\n for(dt=0;dt<numDataTables;++dt){\n if(dataTables.length<dt+1){\n dataTables.push(new google.visualization.DataTable());\n dataTables[dt].addColumn('number', 'step');\n for(obj=0;obj<numObjs;++obj){\n // strip the filename to everything between the last underscore and the file extension\n //var suffixAndExt = dataObjs[obj].fileName.split(\"_\").pop();\n //var suffix = suffixAndExt.substr(0, suffixAndExt.indexOf('.')); \n dataTables[dt].addColumn('number', \"pt_\" + obj);//dataObjColIndex[obj]);\n }\n }\n var dataTable = dataTables[dt];\n dataTable.removeRows(0,dataTable.getNumberOfRows());\n dataTable.addRows(numRows);\n //console.log('DATA TABLE SIZE ' + numRows + ' x ' + dataTables[dt].getNumberOfColumns());\n // set the x labels\n for(row=0;row<numRows;++row){\n dataTable.setCell(row,0,row);\n }\n // copy all the dataObjs data into this dataTable\n for(row=0;row<numRows;++row){\n for(obj=0;obj<numObjs;++obj){\n if(dataObjs[obj].initialized)\n dataTable.setCell(row,dataObjColIndex[obj]+1,dataObjs[obj].data[row][dt]);\n //dataTable.setCell(row,obj+1,dataObjs[obj].data[row][dt]);\n }\n }\n // remove the columns for points that failed:\n //for(obj=0;obj<numObjs;++obj){\n // if(!dataObjs[obj].initialized)\n // dataTable.hideColumns(dataObjColIndex[obj]+1);\n //}\n }\n}", "function populateDataArrays(rows, category, zipsArray, dataArray) {\r\n\t//Depending on category, parse that field from data and add to arrays\r\n\tswitch (category)\r\n\t{\r\n\t\tcase \"Inquiry\": \r\n\t rows.forEach(function(r){\r\n\t r.Inquiry = parseInt(r.Inquiry);\r\n\t r.Zipcodes = parseInt(r.Zipcodes);\r\n\t \r\n\t //If zipcode data is not 0, add it to be drawn\r\n\t if (r.Inquiry != 0) {\r\n\t zipsArray.push(r.Zipcodes);\r\n\t dataArray.push(r.Inquiry);\r\n\t }\r\n\t });\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase \"Applied\":\r\n\t rows.forEach(function(r){\r\n\t r.Applied = parseInt(r.Applied);\r\n\t r.Zipcodes = parseInt(r.Zipcodes);\r\n\t \r\n\t //If zipcode data is not 0, add it to be drawn\r\n\t if (r.Applied != 0) {\r\n\t zipsArray.push(r.Zipcodes);\r\n\t dataArray.push(r.Applied);\r\n\t }\r\n\t });\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"Accepted\":\r\n\t rows.forEach(function(r){\r\n\t r.Accepted = parseInt(r.Accepted);\r\n\t r.Zipcodes = parseInt(r.Zipcodes);\r\n\t \r\n\t //If zipcode data is not 0, add it to be drawn\r\n\t if (r.Accepted != 0) {\r\n\t zipsArray.push(r.Zipcodes);\r\n\t dataArray.push(r.Accepted);\r\n\t }\r\n\t });\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase \"Enrolled\":\r\n\t rows.forEach(function(r){\r\n\t r.Enrolled = parseInt(r.Enrolled);\r\n\t r.Zipcodes = parseInt(r.Zipcodes);\r\n\t \r\n\t //If zipcode data is not 0, add it to be drawn\r\n\t if (r.Enrolled != 0) {\r\n\t zipsArray.push(r.Zipcodes);\r\n\t dataArray.push(r.Enrolled);\r\n\t }\r\n\t });\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tdefault:\r\n\t}\r\n}", "formatAll(options) {\n this._textEditor.transact(() => {\n const re = exports._createIsTableRowRegex(options.leftMarginChars);\n let pos = this._textEditor.getCursorPosition();\n let lines = [];\n let startRow = undefined;\n let lastRow = this._textEditor.getLastRow();\n // find tables\n for (let row = 0; row <= lastRow; row++) {\n const line = this._textEditor.getLine(row);\n if (this._textEditor.acceptsTableEdit(row) && re.test(line)) {\n lines.push(line);\n if (startRow === undefined) {\n startRow = row;\n }\n }\n else if (startRow !== undefined) {\n // get table info\n const endRow = row - 1;\n const range$1 = new range.Range(new point.Point(startRow, 0), new point.Point(endRow, lines[lines.length - 1].length));\n const table = parser.readTable(lines, options);\n const focus = table.focusOfPosition(pos, startRow);\n let diff;\n if (focus !== undefined) {\n // format\n let newFocus = focus;\n const completed = formatter.completeTable(table, options);\n if (completed.delimiterInserted && newFocus.row > 0) {\n newFocus = newFocus.setRow(newFocus.row + 1);\n }\n const formatted = formatter.formatTable(completed.table, options);\n newFocus = newFocus.setOffset(exports._computeNewOffset(newFocus, completed.table, formatted, false));\n // apply\n const newLines = formatted.table.toLines();\n this._updateLines(range$1.start.row, range$1.end.row + 1, newLines, lines);\n // update cursor position\n diff = newLines.length - lines.length;\n pos = formatted.table.positionOfFocus(newFocus, startRow);\n }\n else {\n // format\n const completed = formatter.completeTable(table, options);\n const formatted = formatter.formatTable(completed.table, options);\n // apply\n const newLines = formatted.table.toLines();\n this._updateLines(range$1.start.row, range$1.end.row + 1, newLines, lines);\n // update cursor position\n diff = newLines.length - lines.length;\n if (pos.row > endRow) {\n pos = new point.Point(pos.row + diff, pos.column);\n }\n }\n // reset\n lines = [];\n startRow = undefined;\n // update\n lastRow += diff;\n row += diff;\n }\n }\n if (startRow !== undefined) {\n // get table info\n const endRow = lastRow;\n const range$1 = new range.Range(new point.Point(startRow, 0), new point.Point(endRow, lines[lines.length - 1].length));\n const table = parser.readTable(lines, options);\n const focus = table.focusOfPosition(pos, startRow);\n // format\n let newFocus = focus;\n const completed = formatter.completeTable(table, options);\n // @ts-expect-error TODO\n if (completed.delimiterInserted && newFocus.row > 0) {\n // @ts-expect-error TODO\n newFocus = newFocus.setRow(newFocus.row + 1);\n }\n const formatted = formatter.formatTable(completed.table, options);\n // @ts-expect-error TODO\n newFocus = newFocus.setOffset(\n // @ts-expect-error TODO\n exports._computeNewOffset(newFocus, completed.table, formatted, false));\n // apply\n const newLines = formatted.table.toLines();\n this._updateLines(range$1.start.row, range$1.end.row + 1, newLines, lines);\n // @ts-expect-error TODO\n pos = formatted.table.positionOfFocus(newFocus, startRow);\n }\n this._textEditor.setCursorPosition(pos);\n });\n }", "_arrangeTracksLinear(data, allow_overlap = true) {\n if (allow_overlap) {\n // If overlap is allowed, then all the data can live on a single row\n return [data];\n }\n\n // ASSUMPTION: Data is given to us already sorted by start position to facilitate grouping.\n // We do not sort here because JS \"sort\" is not stable- if there are many intervals that overlap, then we\n // can get different layouts (number/order of rows) on each call to \"render\".\n //\n // At present, we decide how to update the y-axis based on whether current and former number of rows are\n // the same. An unstable sort leads to layout thrashing/too many re-renders. FIXME: don't rely on counts\n const {start_field, end_field} = this.layout;\n\n const grouped_data = [[]]; // Prevent two items from colliding by rendering them to different rows, like genes\n data.forEach((item, index) => {\n for (let i = 0; i < grouped_data.length; i++) {\n // Iterate over all rows of the\n const row_to_test = grouped_data[i];\n const last_item = row_to_test[row_to_test.length - 1];\n // Some programs report open intervals, eg 0-1,1-2,2-3; these points are not considered to overlap (hence the test isn't \"<=\")\n const has_overlap = last_item && (item[start_field] < last_item[end_field]) && (last_item[start_field] < item[end_field]);\n if (!has_overlap) {\n // If there is no overlap, add item to current row, and move on to the next item\n row_to_test.push(item);\n return;\n }\n }\n // If this item would collide on all existing rows, create a new row\n grouped_data.push([item]);\n });\n return grouped_data;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
State State is the parent object of Health, Stamina, Happiness. States holds Health, Stamina, Happiness common properties and behaviours.
function State(){ this.max=100; this.value = this.max; this.stateFlag; /* This increases the value property of an object of type State * @param o object inheriting from State * @param inc int the increment to be added */ this.increaseState = function(o, inc) { if(o.value<o.max) o.value+=inc; } /* This decreases the value property of an object of type State * @param o object inheriting from State * @param dec int the decrement to be subtracted */ this.decreaseState = function(o, dec) { if(o.value>0) o.value-=dec; } this.checkState=function(o,threshold) { if(o.value<threshold) { o.stateFlag=true; }else{ if(o.value>=o.max) { o.stateFlag=false; } } return o.stateFlag; } }
[ "function State() {\n\n this.update = function () {\n console.log(\"Warning: Current state must implement 'update' method\");\n }\n\n this.handleInput = function () {\n console.log(\"Warning: Current state must implement 'handleInput' method\");\n }\n\n this.enter = function () {\n console.log(\"Warning: Current state must implement 'enter' method\");\n }\n\n this.exit = function () {\n console.log(\"Warning: Current state must implement 'exit' method\");\n }\n\n}", "fullState() {\n return Object.assign({}, this.state, this.internals);\n }", "getStatus(){ \n // return a clone of the current state garantees it can be \n // stored by the user without being altered when new input events happen\n return {...VIRTUAL_BUTTONS_STATE}; \n // ...eventually deep clone ... unnecessary rignt now ( no nested objects )\n // return JSON.parse( JSON.serialize( VIRTUAL_BUTTONS_STATE ) ); \n }", "static newStateList() {\n return State.AVAILABLE_STATES.map((item) => new State(item.name, item.message));\n }", "apply_state(state, {merge = true}) {\n\t\tlet new_state = {};\n\t\tif (!merge) {\n\t\t\tnew_state = fromPairs(SYNCHRONIZED.map((name) => [name, INITIAL_STATE[name]]));\n\t\t}\n\t\tnew_state = Object.assign(\n\t\t\tnew_state,\n\t\t\tstate\n\t\t);\n\t\tthis.setState(new_state);\n\t}", "static bindState () {\n for (const j in this.state) {\n if (this.state.hasOwnProperty(j)) {\n observe.watch(this.state, j, (newValue, oldValue) => {\n if (!this.__isSetState__) {\n this.state[j] = oldValue;\n this.__isSetState__ = true;\n console.error('Must use setState to update!');\n } else {\n this.__isSetState__ = false;\n }\n }, {\n deep: true\n });\n }\n }\n\t}", "get state() {\n if (!this._state)\n this.startState.applyTransaction(this);\n return this._state;\n }", "async updateState(state) {\n let key = this.ctx.stub.createCompositeKey(state.getClass(), state.getSplitKey());\n let data = State.serialize(state);\n await this.ctx.stub.putState(key, data);\n }", "getHassState() {\n\t\tlet hass_state = super.getHassState();\n\t\tlet gate_state = this.status;\n\t\thass_state[ 'Uptime' ] = this.secondsToDTHHMMSS( this.getUpTime() );\n\t\thass_state[ 'Last Connected' ] = gate_state.lastOpened;\n\t\thass_state[ 'Last Message' ] = gate_state.lastMessage;\n\t\thass_state[ 'Last Error' ] = gate_state.lastError;\n\t\thass_state[ 'Connections' ] = gate_state.sessionCount || 0;\n\t\thass_state[ 'Total Messages' ] = gate_state.messageCount || 0;\n\t\thass_state[ 'Dispatched Messages' ] = this.dl.dispatchCount;\n\t\thass_state[ 'Commands' ] = gate_state.commandCount || 0;\n\t\thass_state[ 'Confirmations' ] = gate_state.confirmCount || 0;\n\t\thass_state[ 'Errors' ] = gate_state.errorCount || 0;\n\t\treturn hass_state;\n\t}", "function StateMachine(props) {\n return __assign({ Type: 'AWS::StepFunctions::StateMachine' }, props);\n }", "function HippoBee(creature){\n\n //------- Properties Definition ---------\n //this.hasLanded = false;\n this.health = new Health();\n this.stamina = new Stamina();\n this.happiness = new Happiness(); \n this.hippoImg = new Image();\n this.path = \"creatures/hippoBee/media/\";\n this.loadedImgSet = new Array();\n this.pos = {x:100,y:100};\n this.up = this.left = -1;\n this.down = this.right = 1;\n this.dirX = 1;\n this.dirY = -1;\n this.count=0;\n this.frameSpeed=4;\n this.angle = 45;\n \n //-------- Methods Definition ------------\n \n this.health.prototype=new State();\n this.stamina.prototype=new State();\n this.happiness.prototype=new State();\n \n //----------- Getters ---------------\n this.getHealth = function(){\n return this.health.getValue();\n }\n this.getStamina = function(){\n return this.stamina.getValue();\n }\n this.getHappiness = function(){\n return this.happiness.getValue();\n }\n \n //------------- Setters --------------\n this.setHealth = function(value){\n return this.health.setValue(value);\n }\n this.setStamina = function(value){\n return this.stamina.setValue(value);\n }\n this.setHappiness = function(value){\n return this.happiness.setValue(value);\n }\n \n //------------- Other Methods ----------------\n this.checkState = function(stateType,thereshold){\n return stateType.prototype.checkState(stateType.prototype,thereshold);\n }\n /* This decreases the value of one of the types of states. \n * @param dec int the decrement\n * @param stateType object an object inheriting from State\n */\n this.decreaseState = function(stateType,dec){\n stateType.prototype.decreaseState(stateType.prototype,dec);\n }\n /* This increases the value of one of the types of states. \n * @param inc int the increment\n * @param stateType object an object inheriting from State\n */\n this.increaseState = function(stateType,inc){\n stateType.prototype.increaseState(stateType.prototype,inc);\n }\n /* This draws a new image on the canvas \n * @param img Image the image to be drawn\n * TODO: Move the code that draws the glow around the image\n */\n this.drawImg = function(img){\n context.clearRect(0, 0, canvas.width, canvas.height);\n context.drawImage(img, 0, 0, canvas.width, canvas.height);\n context.shadowBlur = 40;\n context.shadowColor = \"rgb(250, 250, 250)\";\n }\n /* This loads the next sequence of images used to animate the bee.\n * @param nextImgSequence an Array of strings, i.e. the names of the images to load\n */\n this.loadImgSequence = function(nextImgSequence){\n \n this.loadedImgSet = nextImgSequence;\n \n }\n /* \n * This loads the first image to be drawn on the canvas.\n */\n this.initImg = function(){\n this.hippoImg.src = this.path + this.loadedImgSet[0];\n }\n /* \n * This will change the image to be drawn on the canvas\n * \n */\n this.animate = function(){\n //constrain values of i between 1 and maxFrm value\n i = (i+1)%this.loadedImgSet.length;\n this.hippoImg.width = canvas.width/2;\n this.hippoImg.height = canvas.height/2;\n this.hippoImg.src = this.path + this.loadedImgSet[i]; \n }\n /* \n * Utility fucntion: converts degrees to radiants.\n * @param angle int an angle in degree\n * @return angle in radiants\n * \n */\n this.toRadiants = function(angle){\n return (angle * Math.PI / 180);\n }\n \n this.boundariesCheck=function(angle)\n {\n var reflectionAngle = angle;\n if(this.pos.x<=0)\n {\n if(angle>90&&angle<180)\n {\n reflectionAngle=angle-90;\n }\n else if(angle<270&&angle>180)\n {\n reflectionAngle=angle+90;\n }\n else if(angle==180)\n {\n reflectionAngle=0;\n }\n }\n else if(this.pos.x >= world.width - width )\n {\n if(angle<90&&angle>0)\n {\n reflectionAngle=angle+90;\n }\n else if(angle<360&&angle>270)\n {\n reflectionAngle=angle-90;\n }\n else if(angle==0||angle==360)\n {\n reflectionAngle=180;\n }\n }\n if(this.pos.y<=0)\n {\n if(angle>270&&angle<360)\n {\n reflectionAngle=angle-270;\n }\n else if(angle<270&&angle>180)\n {\n reflectionAngle=angle-90;\n }\n else if(angle==270)\n {\n reflectionAngle=90;\n }\n }\n else if(this.pos.y >= world.height - height+5 )\n {\n \n if(angle>0&&angle<90)\n {\n reflectionAngle=angle+270;\n }\n else if(angle<180&&angle>90)\n {\n reflectionAngle=angle+90;\n }\n else if(angle==90)\n {\n reflectionAngle=270;\n }\n }\n return reflectionAngle;\n }\n \n /* \n * This is responsible for moving the creature.\n * @param angle int the angle in radiants between the moving direction and the x axis.\n * @param speed int the movement speed \n * \n */\n this.move = function(angle, speed){\n this.angle=this.boundariesCheck(angle);\n var radiants = this.toRadiants(this.angle);\n this.pos.x = this.pos.x + (Math.cos(radiants)*speed);\n this.pos.y = this.pos.y + (Math.sin(radiants)*speed); \n this.updatePosition();\n \n }\n \n /* This performs the creature landing.\n * @param xPos int the current hippoBee horizontal position\n * @param yPos int the current hippoBee vertical position\n * @param xInc int the value to be added or subracted\n * @param yInc int the value to be added or subracted\n * @return object pos the X and Y position object\n */\n this.land = function(){\n if(this.pos.y>=world.height-canvas.height+5){\n creature.trigger(\"landed\");\n }else\n {\n this.move(90, 5);\n }\n }\n \n /* This is responsible for the flying process. Invoked at every tick.\n * @param xPos int the current hippoBee horizontal position\n * @param yPos int the current hippoBee vertical position\n * @param xInc int the value to be added/subracted to/from xPos\n * @param yInc int the value to be added/subracted to/from yPos\n * @return object pos the X and Y position object\n */\n this.fly = function(){\n \n if(!(this.count%100)){\n this.angle = Math.random()*360; \n }\n this.move(this.angle, 5);\n if(!(this.count%this.frameSpeed))\n {\n this.decreaseState(this.health, 1);\n this.decreaseState(this.stamina, 1);\n }\n this.count++;\n }\n /* This is responsible for the eating process.\n * @param xPos int the current hippoBee horizontal position\n * @param yPos int the current hippoBee vertical position\n * @param xInc int the value to be added/subracted to/from xPos\n * @param yInc int the value to be added/subracted to/from yPos\n * @return object pos the X and Y position object\n */\n this.eat = function(){\n var theGrass = jj.get(\"grass\");\n theGrass.eat();\n \n \n this.increaseState(this.health, 2);\n }\n \n this.sleep = function(){\n this.increaseState(this.stamina,2);\n }\n \n /* \n * This is responsible for passing the upddated poisition to the creature object.\n */\n this.updatePosition = function()\n {\n creature.position({\n top:this.pos.y, \n left:this.pos.x\n });\n }\n \n \n }", "function PseudoState(name, parent, kind) {\n if (kind === void 0) { kind = PseudoStateKind_1.PseudoStateKind.Initial; }\n var _this = this;\n this.name = name;\n this.kind = kind;\n /**\n * The outgoing transitions available from this vertex.\n * @internal\n */\n this.outgoing = [];\n this.parent = parent instanceof State_1.State ? parent.getDefaultRegion() : parent;\n this.qualifiedName = this.parent + \".\" + this.name;\n // if this is a starting state (initial, deep or shallow history), record it against the parent region\n if (this.kind === PseudoStateKind_1.PseudoStateKind.Initial || this.isHistory()) {\n util_1.assert.ok(!this.parent.starting, function () { return \"Only one initial pseudo state is allowed in region \" + _this.parent; });\n this.parent.starting = this;\n }\n this.parent.children.unshift(this);\n util_1.log.info(function () { return \"Created \" + _this.kind + \" pseudo state \" + _this; }, util_1.log.Create);\n }", "function StateMachine(defaultState) {\n\n var currentState;\n var previousState;\n var defaultState = defaultState; //can also be used as a \"reset\" state\n\n\n // our machine acts as the head, and delegates most of the handling to the current state\n // we return the next state directly from the state object logic itself and change if needed\n this.update = function () {\n if (!currentState) {\n this.resetToDefault(); // if for some reason there is no state, just reset (on the first frame of every State Machine created)\n }\n var nextState = currentState.update(); //get next state from update\n if (nextState) {\n this.handleReceivedState(nextState);\n return; // no need to handle inputs, as we've changed states anyway\n }\n\n this.handleInput(); //once we're done updating, we take the input. We might need to switch this order at some point(?)\n }\n\n this.updateAnimation = function () {\n if (!currentState) {\n this.resetToDefault();\n }\n if (currentState.animation) { currentState.animation.update(); }\n }\n\n // Input detection is defined in the actual state object\n this.handleInput = function () {\n\n var nextState = currentState.handleInput();\n if (nextState) {\n this.handleReceivedState(nextState);\n return;\n }\n }\n\n this.draw = function () {\n if (currentState.draw) {\n currentState.draw();\n } else {\n console.log(\"Tried to call inexistent draw function on state machine:\", this);\n }\n }\n\n // Left commented to reuse after the game releases\n // Use only for crude, exceptional cases\n // If you can, return a new state in the state update functions instead!\n /*\n this.changeState = function (state) {\n\n if (typeof state.enter === \"undefined\") {\n console.log(\"Error: state provided is not valid. Could not change.\");\n return;\n }\n\n if (typeof currentState !== \"undefined\") {\n currentState.exit();\n }\n\n previousState = currentState;\n currentState = state;\n\n state.enter(); //states handle their own initialization\n }*/\n\n this.changeToPrevious = function () {\n\n if (typeof previousState === \"undefined\") {\n console.log(\"Error: state machine has no previous state. Returning...\");\n return;\n }\n\n currentState.exit();\n\n currentState = previousState;\n previousState = undefined; //might not work. Eventually, we could have a stack of states, which might be useful for complex animations (?)\n\n currentState.enter();\n }\n\n //Changes to the next state that was received through one of the update functions of the current state\n this.handleReceivedState = function (nextState) {\n\n //Weakly typed languages ftw\n if (nextState === \"previous\") {\n nextState = previousState;\n if (typeof previousState === \"undefined\") {\n console.log(\"Error: state machine has no previous state. Returning...\");\n return;\n }\n }\n\n if (currentState){\n currentState.exit(); //could have been undefined if received from another source than updates (like at init)\n }\n if (nextState.animation && nextState!=currentState) {\n nextState.animation.loop();\n }\n //make the switch and save previous\n previousState = currentState;\n currentState = nextState;\n currentState.enter();\n\n }\n\n this.resetToDefault = function () {\n this.handleReceivedState(defaultState); //handleReceivedState is used as a crude way to change states here; only when necessary! Instead, return states in update and/or handleInputs! :)\n }\n\n this.getAnimation = function () {\n if (currentState && currentState.animation) {\n return currentState.animation;\n } else {\n //console.log(\"No animation to access for state machine:\", this);\n }\n }\n\n this.getCurrentState = function () {\n return currentState;\n }\n}", "function Sandbox() {\n this[STATE_KEY] = {};\n }", "async addState(state) {\n console.log(state.getClass())\n let key = this.ctx.stub.createCompositeKey(state.getClass(), state.getSplitKey())\n let data = State.serialize(state)\n await this.ctx.stub.putState(key, data)\n }", "getActiveState() {\r\n return this.activeState.name;\r\n }", "function GameState (state) {\n // Storage class that is passed to all players at end of turn\n this.Players = [] ;//Ordered array of players in game\n this.Name = \"\" ;// Game name\n this.id = \"\";\n this.Started = false\n this.GameOwner = 0; //Index into players array of player that owns game\n this.CurrentPlayer = 0; //Index into players array of current player\n // History is array of TurnStates keeping a detailed history of each turn.\n // Note first TurnState is only interesting in terms of initial bag state and each\n //player's tray state\n this.History = [];\n if (state) {\n this.Players = state.Players\n this.Name = state.Name\n this.id = state.id\n this.Started = state.Started \n if (state.GameOwner) this.GameOwner = state.GameOwner;\n if (state.CurrentPlayer) this.CurrentPlayer = state.CurrentPlayer;\n if (state.History ){\n var history = []\n for(var i=0;i<state.History.length;i++){\n var bag = new Bag(true, state.History[i].Bag.letters)\n var boardState = new BoardState(state.History[i].BoardState.letters)\n var turn = null;\n if (state.History[i].Turn) {\n turn = new Turn(state.History[i].Turn.Type, state.History[i].Turn.LettersIn, state.History[i].Turn.LettersOut, \n state.History[i].Turn.TurnNumber, state.History[i].Turn.Player, state.History[i].Turn.NextPlayer)\n }\n var trayStates = [];\n for(var j=0;j<state.History[i].TrayStates.length;j++){ \n trayStates.push( new TrayState(state.History[i].TrayStates[j].player, state.History[i].TrayStates[j].letters, state.History[i].TrayStates[j].score));\n }\n history.push( new TurnState(bag, boardState, trayStates, state.History[i].End, turn))\n }\n this.History = history ;\n }\n }\n this.GetNextPlayer = function() {\n var next = this.CurrentPlayer +1;\n if (next >= this.Players.length){\n next =0;\n }\n return next;\n }\n this.GetPlayers = function(){\n return this.Players;\n }\n this.GetCurrentPlayerIndex = function(){\n return this.CurrentPlayer\n }\n this.GetNumberOfPlayers = function(){\n return this.Players.length;\n }\n this.IsPlayer = function(playerName){\n for (var i=0;i<Players.length;i++){\n if (playerName == Players[i]) return true;\n }\n return false;\n }\n this.GetBoardState = function(){\n var boardState = null;\n var lastTurn = this.GetLastTurn();\n if (lastTurn){\n boardState = lastTurn.GetBoardState();\n }\n return boardState;\n }\n this.CloneLastTurnState =function(){\n var last = this.GetLastTurnState();\n return last.Clone();\n }\n this.GetLastTurnState = function(){\n var lastTurnState = null;\n if (this.History.length >0 ) {\n lastTurnState = this.History[this.History.length-1]\n }\n return lastTurnState;\n }\n this.HasGameEnded = function(){\n var ended = false;\n var lastTurnState = this.GetLastTurnState();\n if (lastTurnState){\n ended = lastTurnState.End;\n }\n return ended;\n }\n \n this.GetLastTurn = function(){\n //Actually only gets last proper turn because there is no turn object in first turnState\n var lastTurn = null;\n if (this.History.length >=1 ) {\n lastTurn = this.History[this.History.length-1].Turn;\n }\n return lastTurn;\n }\n this.GetMyTrayState =function (playerName) {\n var trayState = null;\n if (this.History.length >=1 ) {\n var trays = this.History[this.History.length-1].GetTrayStates();\n if (trays) {\n for (var i=0;i<trays.length;i++){\n if (trays[i].GetPlayer() == playerName){\n trayState = trays[i]\n break;\n }\n }\n }\n }\n return trayState;\n }\n this.AddTurnState = function(turnState){\n this.History.push(turnState);\n }\n this.HasScores = function(){\n return (this.History.length > 0);\n }\n this.GetBagSize = function(){\n var count = 0;\n if (this.History.length >=1 )\n {\n count = this.History[this.History.length-1].GetBagSize();\n }\n return count;\n }\n this.GetPlayerScore = function (playerName){\n var lastTurnState = this.History[this.History.length-1];\n return lastTurnState.GetPlayerScore(playerName);\n }\n this.GetGameOwner = function(){\n return this.Players[ this.GameOwner];\n }\n this.RemoveLastState = function(){\n var lastTurnState = this.History.pop();\n var newLastTurn = this.GetLastTurn();\n if (newLastTurn){\n this.CurrentPlayer = newLastTurn.NextPlayer;\n }else{\n //This is same code at start game first player is first tray state\n this.SetCurrentPlayerByName(lastTurnState.GetTrayState(0).GetPlayer());\n }\n }\n this.SetCurrentPlayerByName = function(playerName){\n this.CurrentPlayer = 0\n for (var i=0;i<this.Players.length;i++){\n if (this.Players[i] == playerName){\n this.CurrentPlayer = i;\n break;\n }\n }\n }\n this.SetCurrentPlayer = function(index){\n this.CurrentPlayer = index; \n }\n this.GetCurrentPlayer = function(){\n var player = \"\";\n if (this.CurrentPlayer <= (this.Players.length -1) ){\n player = this.Players[this.CurrentPlayer];\n }\n return player\n }\n}", "switchState(state){\n\t\tthis.currentState = state;\n\t\tswitch(state){\n\t\tcase configNamespace.STATE_MACHINE.START:\n\t\t\tthis.drawStartPage();\n\t\t\tthis.longInfoText = infoTextsNamespace.longPageDescription.startPage;\n\t\t\tthis.drawShortInfoText(infoTextsNamespace.shortPageDescription.startPage);\n\t\t\tthis.changeButtonPointerEvents(this.startButton);\n\t\t\tbreak;\n\t\tcase configNamespace.STATE_MACHINE.MAP:\n\t\t\tthis.drawMapPage();\n\t\t\tthis.longInfoText = infoTextsNamespace.longPageDescription.mapPage;\n\t\t\tthis.drawShortInfoText(infoTextsNamespace.shortPageDescription.mapInfo);\n\t\t\tthis.changeButtonPointerEvents(this.mapButton);\n\t\t\tbreak;\n\t\tcase configNamespace.STATE_MACHINE.LINE_CHART:\n\t\t\tthis.drawLineChartPage();\n\t\t\tthis.longInfoText = infoTextsNamespace.longPageDescription.lineChartPage;\n\t\t\tthis.drawShortInfoText(infoTextsNamespace.shortPageDescription.lineChartInfo);\n\t\t\tthis.changeButtonPointerEvents(this.timeLineButton);\n\t\t\tbreak;\n\t\tcase configNamespace.STATE_MACHINE.CRIME_CORRELATION:\n\t\t\tthis.drawCrimeCorrelationPage();\n\t\t\tthis.longInfoText = infoTextsNamespace.longPageDescription.correlationPage;\n\t\t\tthis.drawShortInfoText(infoTextsNamespace.shortPageDescription.correlationInfo);\n\t\t\tthis.changeButtonPointerEvents(this.correlationButton);\n\t\t\tbreak;\n\t\tcase configNamespace.STATE_MACHINE.UNIVERSE:\n\t\t\tthis.drawUniversePage();\n\t\t\tthis.longInfoText = infoTextsNamespace.longPageDescription.universePage;\n\t\t\tthis.drawShortInfoText(infoTextsNamespace.shortPageDescription.universeInfo);\n\t\t\tthis.changeButtonPointerEvents(this.universeButton);\n\t\t\tbreak;\n\t\tcase configNamespace.STATE_MACHINE.IMPRESSUM:\n\t\t\tthis.drawImpressumPage();\n\t\t\tthis.longInfoText = infoTextsNamespace.longPageDescription.impressumPage;\n\t\t\tthis.drawShortInfoText(\"\");\n\t\t\tthis.enableButton(this.activeButton);\n\t\t\tbreak;\n\t\tcase configNamespace.STATE_MACHINE.DATA_REGULATION:\n\t\t\tthis.drawDataRegulationPage();\n\t\t\tthis.longInfoText = infoTextsNamespace.longPageDescription.dataRegulationPage;\n\t\t\tthis.drawShortInfoText(\"\");\n\t\t\tthis.enableButton(this.activeButton);\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}", "function GlobalStateManager() {\n\n\t// Holds the currently-selected project\n\tthis.currentProject = null;\n\n\t// Holds the currently-selected file\n\tthis.currentFile = null;\n\n\t// Length of time to display for realtime graphs, in seconds\n\tthis.realtimeTimeWindow = 600;\n\n\t// Holds incrementing graph identifier\n\tthis.nextGraphIdentifier = 0\n\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The method will get an event and a game_id and will update the game with the given event. The game should be a past game. The validtion is implemented in the client side. If the event exist it will be updated with the new value
async function addEventToGame(game_id,event){ let events_ids = await DButils.execQuery(`SELECT GamesEvents.gameid, Events.eventid FROM Events JOIN GamesEvents ON Events.eventid = GamesEvents.eventid WHERE GamesEvents.gameid = ${game_id} AND Events.EventDate = '${event.event_date}' AND Events.EventTime = '${event.event_time}' AND Events.EventGameTime = ${event.event_game_time}`) /* Check if the event already exist. Event is represented by Eventid. If Yes -> Update it Else -> Create a new event */ if (events_ids.length > 0) await DButils.execQuery(`Update Events SET EventDesc = '${event.event}' WHERE eventid = ${events_ids[0].eventid}`); else{ await DButils.execQuery(`INSERT INTO Events ([EventDate], [EventTime], [EventGameTime], [EventDesc]) Values ('${event.event_date}', '${event.event_time}', ${event.event_game_time},'${event.event}')`) // Update the new event in the GamesEvents relationship table. // The following command return the last isnerted item to a table const last_event = await DButils.execQuery(`SELECT eventid FROM Events WHERE EventDate = '${event.event_date}' AND EventTime = '${event.event_time}' AND EventGameTime = ${event.event_game_time}`) DButils.execQuery(`INSERT INTO GamesEvents ([gameid], [eventid]) VALUES (${game_id}, ${last_event[0].eventid})`) } }
[ "function handleEditGamePage() {\n document.addEventListener(\"DOMContentLoaded\", function (event) {\n \"use strict\";\n\n firebase.database().ref('/Globals').once('value').then(function (snapshot) {\n teamName = snapshot.child('TeamName');\n });\n\n var datetime = localStorage.getItem(\"datetime\");\n\n if (datetime != null) {\n firebase.database().ref('/Games/' + datetime).once('value').then(function (snapshot) {\n if (!snapshot.exists()) {\n alert('Not a recorded game');\n window.location = \"/view-game-schedule.html\";\n }\n\n var datetime = snapshot.child('datetime'),\n location = snapshot.child('location'),\n them = snapshot.child('them'),\n inputs = document.querySelectorAll('.form-control');\n\n inputs[0].value = them.val();\n inputs[1].value = location.val();\n inputs[2].value = datetime.val();\n });\n } else {\n alert('Not a valid game');\n window.location = \"/view-game-schedule.html\";\n }\n });\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}", "@action addNewEvent(playerId) {\n const playerIndex = this.trackingList.findIndex(player => player.id === playerId);\n if (playerIndex === -1) return;\n const player = this.trackingList[playerIndex];\n let newEvent = {};\n newEvent.timestamp = new Date();\n newEvent.isUpdated = false;\n newEvent.gameId = this.gameId;\n newEvent.teamId = this.teamId;\n newEvent.sequence = this.eventsList.length === 0 ? 1 : (parseInt(this.eventsList[this.eventsList.length - 1].sequence, 10) + 1)\n newEvent.eventType = \"\";\n newEvent.player = player;\n this.eventsList.push(newEvent);\n }", "function updateGame(game, action) {\n if (typeof game === 'undefined') return makeGame();\n\n if (action.type === 'FRAME_READY') {\n if (game.get(\"mode\") === 'GAME_ON') {\n var player = updatePlayer(game.get(\"player\"), { 'type': 'STEP' });\n\n var boulders = game.get(\"boulders\").map(function(boulder) {\n return updateBoulder(boulder, { 'type': 'STEP' });\n });\n\n var missiles = game.get(\"missiles\").reduce(function(accum, missile) {\n var missile2 = updateMissile(missile, { 'type': 'STEP' });\n if (missile2.get(\"mode\") == 'GONE') {\n return accum;\n } else {\n return accum.push(missile2);\n }\n }, Immutable.List());\n\n var collisionResult = detectCollisions(player, missiles, boulders);\n var player2 = collisionResult[0];\n var missiles2 = collisionResult[1];\n var boulders2 = collisionResult[2];\n\n /* Assemble new game state from all that */\n var game2;\n if (player2.get(\"mode\") === 'GONE') {\n game2 = game.set(\"mode\", 'GAME_OVER')\n .set(\"timer\", 100)\n .set(\"highScore\", player2.get(\"score\") > game.get(\"highScore\") ? player2.get(\"score\") : game.get(\"highScore\"));\n } else {\n game2 = game;\n }\n return game2.set(\"player\", player2)\n .set(\"boulders\", boulders2.size === 0 ? makeBoulders() : boulders2)\n .set(\"missiles\", missiles2);\n } else if (game.get(\"mode\") === 'GAME_OVER') {\n var game2 = game.update(\"timer\", decr);\n if (game2.get(\"timer\") <= 0) {\n return resetGame(game2);\n } else {\n return game2;\n }\n } else if (game.get(\"mode\") === 'ATTRACT_TITLE') {\n if (game.get(\"credits\") > 0) {\n return game;\n } else {\n return countDown(game, function(game) {\n return game.set(\"mode\", 'ATTRACT_HISCORES').set(\"timer\", 400);\n });\n }\n } else if (game.get(\"mode\") === 'ATTRACT_HISCORES') {\n return countDown(game, function(game) {\n return game.set(\"mode\", 'ATTRACT_TITLE').set(\"timer\", 400);\n });\n }\n throw new Error(\"Unhandled mode: \" + game.get(\"mode\"));\n } else if (action.type === 'CONTROLS_CHANGED') {\n if (game.get(\"mode\") === 'ATTRACT_TITLE' || game.get(\"mode\") === 'ATTRACT_HISCORES') {\n if (action.prev.startPressed && (!action.startPressed)) {\n if (game.get(\"credits\") > 0) {\n var player = resetPlayer(game.get(\"player\"));\n return game.set(\"player\", player).update(\"credits\", decr).set(\"mode\", 'GAME_ON');\n } else {\n return game;\n }\n } else {\n return game;\n }\n } else if (game.get(\"mode\") === 'GAME_ON') {\n var player = game.get(\"player\");\n if (fireWentDown(action) && player.get(\"mode\") === 'PLAYING') {\n var mx = player.get(\"x\");\n var my = player.get(\"y\");\n var h = player.get(\"h\");\n var mv = 2.0;\n var mvx = Math.cos(degreesToRadians(h)) * mv;\n var mvy = Math.sin(degreesToRadians(h)) * mv;\n return game.update(\"missiles\", function(m) {\n return m.push(makeMissile(mx, my, mvx, mvy));\n });\n } else {\n return game.set(\"player\", updatePlayer(game.get(\"player\"), action));\n }\n } else if (game.get(\"mode\") === 'GAME_OVER') {\n return game;\n }\n throw new Error(\"Unhandled mode: \" + game.get(\"mode\"));\n } else if (action.type === 'COIN_INSERTED') {\n var game2 = game.update(\"credits\", incr);\n if (game2.get(\"mode\") === 'ATTRACT_HISCORES') {\n return game2.set(\"mode\", 'ATTRACT_TITLE');\n } else {\n return game2;\n }\n }\n throw new Error(\"Unhandled action: \" + action.type);\n}", "function updateActiveGame() {\n // Return if we're not logged in\n if(!Dworek.state.loggedIn)\n return;\n\n // Request new game info if the same game is still active\n if(Dworek.state.activeGame != null && (Dworek.state.activeGame == Dworek.utils.getGameId() || !Dworek.utils.isGamePage()))\n requestGameInfo();\n\n // Return if we're not on a game page\n if(!Dworek.utils.isGamePage()) {\n Dworek.utils.lastViewedGame = null;\n return;\n }\n\n // Get the ID of the game page\n const gameId = Dworek.utils.getGameId();\n\n // Return if the last viewed game is this game\n if(Dworek.state.lastViewedGame == gameId)\n return;\n\n // Check whether this game is different than the active game\n if(Dworek.state.activeGame != gameId) {\n // Automatically select this as active game if we don't have an active game now\n if(Dworek.state.activeGame === null) {\n // Set the active game\n setActiveGame(gameId);\n\n } else {\n // Ask the user whether to select this as active game\n showDialog({\n title: 'Change active game',\n message: 'You may only have one active game to play at a time.<br /><br />Would you like to change your active game to this game now?',\n actions: [\n {\n text: 'Activate this game',\n value: true,\n state: 'primary',\n icon: 'zmdi zmdi-swap',\n action: function() {\n // Set the active game\n setActiveGame(gameId);\n }\n },\n {\n text: 'View current game',\n value: true,\n icon: 'zmdi zmdi-long-arrow-return',\n action: function() {\n // Navigate to the game page\n Dworek.utils.navigateToPath('/game/' + Dworek.state.activeGame);\n }\n },\n {\n text: 'Ignore'\n }\n ]\n\n }, function(value) {\n // Return if the action is already handled\n if(!!true)\n return;\n\n // Show a notification to switch to the active game\n showNotification('Switch to your active game', {\n action: {\n text: 'Switch',\n action: function() {\n $.mobile.navigate('/game/' + Dworek.state.activeGame, {\n transition: 'flow'\n });\n }\n }\n });\n });\n }\n }\n\n // Update the status labels\n updateStatusLabels();\n\n // Update the last viewed game\n Dworek.state.lastViewedGame = gameId;\n}", "function updateGame(id) {\n location.href = 'UpdateGame.html?gameid=' + id;\n}", "function joinGame(gameId) {\n\n if(!gameId) {\n console.log('error, game id is null'); //todo handle error\n return;\n }\n\n firebaseGame = new Firebase(FIREBASE_URL + '/games/' + gameId);\n firebaseGame.once('value', function(dataSnapshot) {\n\n var game = dataSnapshot.val();\n if(game) {\n\n //transaction is a safe way of setting value, ensures only one person can write a value\n firebaseGame.child('info').transaction(function(currentData) {\n if(currentData && currentData.state == 'waiting') {\n return {state: 'playing'};\n } else {\n return null; //don't allow setting data\n }\n }, function(error, committed, snapshot) {\n if(error) {\n console.log('abnormal error'); //todo handle error\n }\n else if(!committed) {\n console.log('somebody plays already'); //todo handle case\n } else {\n console.log('i joined the game');\n playerId = 2;\n firebaseGame.child('player/2').set({name: 'hansi'});\n watchGameAbort();\n firebaseGame.onDisconnect().remove();\n onGameStart();\n }\n });\n\n } else {\n console.log('game doesnt exist'); //todo handle error\n }\n });\n }", "function createGame() {\n if(document.getElementById('opponent').value && document.getElementById('location').value &&\n document.getElementById('start-date').value && document.getElementById('start-time').value) {\n var email;\n firebase.auth().onAuthStateChanged(function(user) {\n if(user) {\n email = user.email.replace('.', '').replace('@', '');\n console.log(email);\n db.collection(\"users\").where(\"email\", \"==\", email).get().then(function(querySnapshot) {\n querySnapshot.forEach(function(doc) {\n var team = doc.data().team;\n console.log(doc.id);\n db.collection(\"teams\").doc(team).collection(\"schedule\").doc(document.getElementById('start-date').value +\n \" \" + document.getElementById('opponent').value).set({\n title: document.getElementById('opponent').value,\n location: document.getElementById('location').value,\n startDate: document.getElementById('start-date').value,\n startTime: document.getElementById('start-time').value,\n eventType: 'game'\n }).then(function(result) {\n window.location = \"schedule-admin.html\";\n return false;\n });\n });\n });\n }\n });\n }\n else {\n document.getElementById(\"warning\").innerHTML = \"Please fill out all event information!\";\n return false;\n }\n}", "function addGame() {\n console.log(\"in addGame...\");\n\n //only make new game if current game is empty\n // if ((vm.currentGame === null) || (vm.currentGame.gameInProgress || vm.currentGame.postGame)) {\n \n vm.games.$add(blankBoard)\n .then(function(ref) {\n setCurrentGame(ref.key());\n // vm.currentGame.time = Firebase.ServerValue.TIMESTAMP;\n vm.currentGame.time = new Date().getTime();\n saveCurrentGame();\n }, catchError);\n }", "addGameToOffer(event) {\n const {gameOffer} = this.state;\n const gamesToAdd = Array.from(gameOffer);\n\n // for only one game offer per trade\n this.props.userGames.games.map((game) => {\n if (game.id.toString() === event.target.value) {\n gamesToAdd[0] = game;\n }\n });\n\n this.setState({\n gameOffer: gamesToAdd,\n requestErrorMessage: '',\n });\n }", "function updateGameDatabaseforPlayer1() {\n console.log(\"im in updateGameDatabaseeforPlayer1\");\n gameRef.update({\n player1ChoiceMade: player1ChoiceMade,\n player1Choice: player1Choice\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 }", "#setGameLost() {\n this.#gameState = 4\n document.dispatchEvent(this.#gameStateEvent)\n }", "function newgameOK(response) {\n if (response.indexOf(\"<!doctype html>\") !== -1) { // User has timed out.\n window.location = \"access-denied.html\";\n } else if (response === \"nobox\") {\n $(\"#bi_error\").text('Invalid Game Box ID.').show(); \n $(\"#boxid\") .trigger('focus');\n } else if (response === \"dupname\") {\n $(\"#sn_error\").text('Duplicate Game Name is not allowed.').show(); \n $(\"#sessionname\") .trigger('focus');\n } else if (response.indexOf(\"noplayer\") !== -1) { \n // Response contains \"noplayer\".\n var plerr = 'Player #' + response.substr(9) + ' does not exist';\n $(\"#pc_error\").text(plerr).show(); \n $(\"#player1\") .trigger('focus');\n } else if (response === \"success\") {\n $('#newgame .error').hide();\n $('#newgame :text').val('');\n // Send an email notification to each player in the game.\n var cString;\n BD18.mailError = false;\n for (var i = 0; i < BD18.playerCount; i++) {\n cString = 'game=' + BD18.name + '&login=' + BD18.player[i];\n $.post(\"php/emailPlayerAdd.php\", cString, emailPlayerResult);\n }\n delayGoToMain();\n } else if (response === \"fail\") {\n var ferrmsg ='New game was not created due to an error.\\n';\n ferrmsg += 'Please contact the BOARD18 webmaster.';\n alert(ferrmsg);\n } else { // Something is definitly wrong in the code.\n var nerrmsg ='Invalid return code from createGame.php.\\n';\n nerrmsg += response + '\\nPlease contact the BOARD18 webmaster.';\n alert(nerrmsg);\n }\n}", "function save_event() {\n\tvar new_event_name = $(\"#event_name\").val()+\"\";\n\n\tif (new_event_name == \"\") {\n $('#error-display').css('display', 'table');\n\t\t$('#bad-boy').html(\"Please enter an event name\");\n\t}\n\telse{\n\t\tedit_event_name(event_selected, new_event_name);\n\t\tadd($(\"#bind\").val(),$(\"#event_name\").val());\n\t\tclose_window();\n\t}\n}", "async function updateGamePlayer(req, gid, target) {\n\n return new Promise(function(resolve, reject) {\n const connection = getConnection()\n\n const queryString = \"UPDATE game SET \" + target + \"='\" + req.user.uid + \"' WHERE gid=\" + gid + \";\";\n\n connection.query(queryString, (err, rows, fields) => { \n if (err) {\n console.log(\"Failed to update game user: \" + err + \"\\n\");\n connection.end();\n reject();\n } else {\n console.log(\"Successfully updated game!\");\n connection.end();\n resolve();\n }\n });\n \n console.log(\"Finishing updating game data...\")\n });\n}", "function getGameNotification(){\n\tvar json = {\n\t\t'session': localStorage.sessionId,\n\t\t'gameNumber': localStorage.currentGameNum,\n\t\t'gameOpponent': localStorage.gameOpponent,\n\t\t'userGameFlag': localStorage.gameFlag\n\t};\n\tperformPostRequest(\"get-game-notification.php\", json, function(data){\n\t\tswitch(data.status) {\n\t\t\tcase 202:\n\t\t\t\tsetElementInGameMap(data.row, data.col, getGameOpponentFlag());\n\t\t\t\tlocalStorage.gameAreaClickCounter = 1;\n\t\t\t\tlocalStorage.gameTurn = 1;\n\t\t\t\tsetUserTurnInCounter();\n\t\t\t\tuserTurnChecker();\n\t\t\t\tbreak;\n\t\t\tcase 200:\n\t\t\t\tdeclareWinner(data);\n\t\t\t\tbreak;\n\t\t\tcase 204:\n\t\t\t\tshowErrorMessage(\"Вашият опонент напусна играта!\");\n\t\t\t\tbreak;\n\t\t\tcase 470:\n\t\t\t\tlogOut();\n\t\t\t\tbreak;\n\t\t}\n\t});\n}", "proposePlace(req, res, next) {\n // employee proposes a place\n req.assert('place', 'Place is missing').notEmpty();\n req.getValidationResult().then(result => {\n if (result.isEmpty()) {\n const eventId = req.query.eventId;\n const place = req.body.place;\n // Validate req data\n if (!eventId || !Utils.isValidObjectId(eventId) || !place) {\n return Callbacks.ValidationError('Invalid id or place' || 'Validation error', res);\n } else {\n // check for exisiting and update\n EventModel.findOne({\n _id: new ObjectID(eventId)\n }, (err, existinEvent) => {\n if (err) {\n return Callbacks.SuccessWithError(err, res);\n }\n if (existinEvent) {\n // if event is already finalized return err message\n if (existinEvent.isFinalized) {\n return Callbacks.SuccessWithError('Event already finalized', res);\n }\n // update proposed places array\n existinEvent.proposedPlaces.push(req.body.place);\n const eventUpdate = {\n $set: {\n eventName: existinEvent.eventName,\n proposedPlaces: existinEvent.proposedPlaces,\n isFinalized: existinEvent.isFinalized\n }\n };\n\n // update the event\n EventModel.update({ _id: new ObjectID(eventId) }, eventUpdate, function (err, result) {\n console.log('err', err);\n if (err) {\n return Callbacks.InternalServerError(err, res);\n }\n // mail template \n const emailtemplate = `<h1>Hi ${Constants.MANAGER_EMAIL}, a new place , \n ${place.locationName} has been added to the Event, ${existinEvent.eventName}.\n </h1><a href='${Constants.APP_REDIRECT_URL}'>Click Here to Goto App</a>`;\n // sending mail via emailer utility function\n Emailer.sendEmail(\n Constants.MANAGER_EMAIL, Constants.FROM_MAIL, Constants.EVENT_PLACE_ADDITION_SUBJECT,\n '', emailtemplate\n ).then(resp => {\n console.log('Emailer reponse', resp)\n const response = 'Event : propose place updated successfully!';\n return Callbacks.Success(response, res);\n })\n .catch(err => {\n return Callbacks.Failed(404, 'Couldnt Send mail', res)\n })\n\n });\n } else {\n return Callbacks.SuccessWithError('Event does not exist.', res);\n }\n });\n }\n } else {\n const errors = result.array();\n return Callbacks.ValidationError(errors[0].msg || 'Validation error', res);\n }\n });\n }", "function endGame(villagersWin) {\n console.log(\"Endgame called\");\n\n var cycleNumber = GameVariables.findOne(\"cycleNumber\").value - 1;\n var winnerText = \"\";\n\n if (villagersWin) {\n console.log(\"Villagers win\");\n winnerText = \"The Villagers have won!\";\n } else {\n console.log(\"Werewolves win\");\n winnerText = \"The Werewolves have won!\";\n }\n\n EventList.insert({type: \"info\", cycleNumber: cycleNumber, text: winnerText, timeAdded: new Date()});\n\n GameVariables.update(\"lastGameResult\", {$set: {value: villagersWin, enabled: true}});\n\n var players = Players.find({joined: true});\n var werewolfId = Roles.findOne({name: \"Werewolf\"})._id;\n\n // Let's set the variables for all the players that were in the game\n players.forEach(function(player) {\n Players.update(player._id, {$set: {seenEndgame: false, ready: false}});\n\n if (villagersWin) {\n if (player.role == werewolfId) {\n Players.update(player._id, {$set: {alive: false}});\n }\n } else {\n if (player.role != werewolfId) {\n Players.update(player._id, {$set: {alive: false}});\n }\n }\n });\n\n // Re-enable the lobby\n GameVariables.update(\"gameMode\", {$set: {value: \"lobby\"}});\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Autoselect text on focus
function focusText() { window.setTimeout(function () { const range = document.createRange(); range.selectNodeContents(document.activeElement); const sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); }, 1); }
[ "onFocusAutosuggest(event) {\n event.target.select();\n }", "_focusActiveOption() {\n var _a;\n if (!this.useActiveDescendant) {\n (_a = this.listKeyManager.activeItem) === null || _a === void 0 ? void 0 : _a.focus();\n }\n this.changeDetectorRef.markForCheck();\n }", "function firstInputOnFocus() {\r\n\t name.setAttribute(\"autofocus\",true);\r\n}", "function blockTextSelection(){_document2['default'].body.focus();_document2['default'].onselectstart=function(){return false;};}", "function selectPhrase(editArea)\r\n{\r\n var startPos = editArea.selectionStart;\r\n var endPos = editArea.selectionEnd;\r\n var selPhrase = editArea.value.substring(startPos, endPos);\r\n var _phrase = document.getElementById('phrase');\r\n if (_phrase)\r\n {\r\n _phrase.value = selPhrase;\r\n } \r\n}", "setFocusToFirstItem() {\n if (this.interactiveChildElements.length) {\n this.interactiveChildElements[0].focus();\n }\n }", "didFocus () {\n\n }", "startSelection(label) {\n this.selector = label;\n }", "function setSelectedText(objectUrl) {\r\n var text_iframe = document.getElementById('text-input'); \r\n text_iframe.contentWindow.setSelectedText(objectUrl);\r\n }", "function selectKnCell(e){\n\tvar knCell = keynapse.currentKnCell;\n\tstopKeynapse();\n\n\tif(knCell.type == 'text'){\n\t\t$(knCell).focus();\t\t\n\t} else {\n\t\t$(knCell).focus();\n\t\t$(knCell).trigger(\"click\");\n\t}\n}", "activate () {\n this.focus();\n }", "function returnFocus() {\n if( focused )\n focused.focus();\n }", "function storeCaret (txtarea) { \r\n if (txtarea.createTextRange) { \r\n txtarea.caretPos = document.selection.createRange().duplicate();\r\n } \r\n }", "inputTextAndSelectFromResult(element, text){\n driver.findElement(element).sendKeys(text);\n //TODO find less fragile locator/way of seleting this element\n driver.findElement(By.className(\"hierarchy-picker-node\")).click();\n \n }", "updateCaret() {\n\t\tthis.caret = this.textarea.selectionStart;\n\t}", "function select_first_input(){\n $(\"input[type='text']:not(.exclude_select):first\", document.forms[0]).focus().select();$(\".force_select:first\", document.forms[0]).focus().select();\n}", "function selectUser(userItem){\n inputText = textArea.html();\n // alert('input text is ' + inputText);\n // alert('caretStartPosition is ' + caretStartPosition + ', to is ' + (caretStartPosition + fullCachedName.length) + ', addedString is is ' + \"@\" + userItem.find(\"span.the_name\").html() );\n \n replacedText = replaceString(caretStartPosition, caretStartPosition +\n fullCachedName.length, inputText, \n userItem.find(\"div.occluded\").html());\n textArea.focus();\n textArea.html(replacedText);\n hideUserFrame();\n setEndOfContenteditable(textArea[0]);\n }", "add_focus() {\n this.element.focus();\n }", "function selectLine(ta, line) {\n if (!ta.setSelectionRange) return;\n \n var count = 0;\n var start = 0;\n var text = ta.value;\n for (var i = 0; i<text.length; i++) {\n if (text[i] == \"\\n\" || (start!=0 && i==text.length-1)) {\n count++; // [i] is the end of line count\n if (count == line - 1) start = i + 1;\n else if (count == line ) {\n ta.focus();\n ta.setSelectionRange(start, i);\n return;\n }\n }\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Dispatches `projectschange` event, requests update, and notifies any resize.
async [notifyProject]() { this.dispatchEvent(new CustomEvent('projectschange')); await this.requestUpdate(); // @ts-ignore if (this.notifyResize) { // @ts-ignore this.notifyResize(); } }
[ "update(projects) {\n $(this.projectList).empty();\n for (let proj in projects) {\n if (projects[proj].name == undefined) continue;\n let p = document.createElement('div');\n $(p).addClass('proj-value');\n $(this.projectList).append(p);\n\n let input = CreateElement('input', p, 'proj-input');\n $(input).attr('type', 'text');\n $(input).val(projects[proj].name);\n\n new Button(this.top, p, 'times proj-icon', Button.ACTION, () => this.updateValue('delete', proj), {});\n\n new Button(this.top, p, 'file-download proj-icon', Button.ACTION, () => IO.DownloadJSON(projects[proj], projects[proj].name), {});\n\n $(p).on('click', function () {\n this.updateValue('open', proj);\n $(this.element).slideUp(SLIDE_SPEED);\n }.bind(this));\n\n $(input).on('click', function (e) { e.stopPropagation(); }.bind(this));\n $(input).on('change', function () { this.updateValue('rename', proj, $(input).val()); }.bind(this));\n }\n this.toggleDarkMode(this.top.darkMode.val);\n }", "projectChanged() {\n const oldSI = this.getSimulationInterface();\n this.checkForDepositLibrary();\n this.treeController.reloadTree();\n this.workspaceController.resetEditors();\n const newSI = this.getSimulationInterface();\n oldSI.transferCallbacks(newSI);\n }", "function onProjectSelect() {\n\t\tself.tableData = (self.resourceMap && self.resourceMap[self.project.id]) || [];\n\t\tself.gridOptions.data = self.tableData;\n\t\tself.gridApi.grid.clearAllFilters();\n\t\tself.gridApi.pagination.seek(1);\n\t\tvar rowCount = Math.min(10, self.tableData.length);\n\t\tangular.element(document.getElementsByClassName('grid')[0]).css('height', ((rowCount + 6) * 30) + 'px');\n\t}", "async function getChangesForProjects(projects, osd, log) {\n log.verbose('getting changed files');\n const {\n stdout\n } = await (0, _execa.default)('git', ['ls-files', '-dmto', '--exclude-standard', '--', ...Array.from(projects.values()).filter(p => osd.isPartOfRepo(p)).map(p => p.path)], {\n cwd: osd.getAbsolute()\n });\n const output = stdout.trim();\n const unassignedChanges = new Map();\n\n if (output) {\n for (const line of output.split('\\n')) {\n const [tag, ...pathParts] = line.trim().split(' ');\n const path = pathParts.join(' ');\n\n switch (tag) {\n case 'M':\n case 'C':\n // for some reason ls-files returns deleted files as both deleted\n // and modified, so make sure not to overwrite changes already\n // tracked as \"deleted\"\n if (unassignedChanges.get(path) !== 'deleted') {\n unassignedChanges.set(path, 'modified');\n }\n\n break;\n\n case 'R':\n unassignedChanges.set(path, 'deleted');\n break;\n\n case '?':\n unassignedChanges.set(path, 'untracked');\n break;\n\n case 'H':\n case 'S':\n case 'K':\n default:\n log.warning(`unexpected modification status \"${tag}\" for ${path}, please report this!`);\n unassignedChanges.set(path, 'invalid');\n break;\n }\n }\n }\n\n const sortedRelevantProjects = Array.from(projects.values()).sort(projectBySpecificitySorter);\n const changesByProject = new Map();\n\n for (const project of sortedRelevantProjects) {\n if (osd.isOutsideRepo(project)) {\n changesByProject.set(project, undefined);\n continue;\n }\n\n const ownChanges = new Map();\n const prefix = osd.getRelative(project.path);\n\n for (const [path, type] of unassignedChanges) {\n if (path.startsWith(prefix)) {\n ownChanges.set(path, type);\n unassignedChanges.delete(path);\n }\n }\n\n log.verbose(`[${project.name}] found ${ownChanges.size} changes`);\n changesByProject.set(project, ownChanges);\n }\n\n if (unassignedChanges.size) {\n throw new Error(`unable to assign all change paths to a project: ${JSON.stringify(Array.from(unassignedChanges.entries()))}`);\n }\n\n return changesByProject;\n}", "_onProjectItemClicked(projectName) {\n // TODO: give full information on the project and whether the user is a member of it\n let event = new CustomEvent(\"project-selected\", {\n detail: {\n message: \"Selected project in project list.\",\n project: this.getProjectByName(projectName)\n },\n bubbles: true\n });\n this.dispatchEvent(event);\n }", "updateProjectListView(projectData) {\n this.clearInnerHTML(this.projects);\n this.projectData.forEach(project => this.render(project));\n }", "function editProject(key){\n\tvar name = $(\"#newProjectTitle\").val().trim();\n\tvar email = $(\"#newProjectEmail\").val().trim();\n\tvar description = $(\"#newProjectInfo\").val().trim();\n\tvar genre = $(\"#newProjectGenre\").val().trim();\n\tvar needs = [\"\"];\n\tvar wants = [\"\"];\n\t$(\".inputNewNeed\").each(function(index) {\n\t\tneeds.push($(this).text());\n\t});\n\t$(\".inputNewWant\").each(function(index) {\n\t\twants.push($(this).text());\n\t});\n\tvar index;\n\t//get project\n\tfor(var i = 0; i< myProjects.length; i++){\n\t\tif(myProjects[i].key === key){\n\t\t\tindex = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t//validate\n\tif (name != \"\"){\n\t\tmyProjects[index].name = name;\n\t}\n\tif (email != \"\"){\n\t\tmyProjects[index].email = email;\n\t}\n\tif (description != \"\"){\n\t\tmyProjects[index].description = description;\n\t}\n\tif (genre != \"\"){\n\t\tmyProjects[index].genre = genre;\n\t}\n\tif(needs[1] !== undefined){\n\t\tmyProjects[index].needs = needs;\n\t}\n\tif(wants[1] !== undefined){\n\t\tmyProjects[index].wants = wants;\n\t}\n\t//update\n\tprojectsEndPoint.child(key).update(myProjects[index]);\n}", "openProject(event) {\n const controller = event.data.controller;\n ListDialog.type = 'openProject';\n const warning = new WarningDialog(() => {\n const dialog = new ListDialog(() => {\n if (dialog.selectedItems.length != 0) {\n dialog.selectedItems\n .forEach((value) => {\n controller.loadProject(value);\n });\n if (controller.persistenceController.getCurrentProject().version > BeastController.BEAST_VERSION) {\n InfoDialog.showDialog('This BEAST-version is older than the version this project was created with!<br>Some of of the components may be incompatible with this version.');\n }\n }\n }, controller.listProjects());\n dialog.show();\n }, () => {\n MenubarController.openAfterWarning = true;\n $('#saveProject')\n .click();\n }, () => {\n MenubarController.openAfterWarning = true;\n $('#exportProject')\n .click();\n }, null);\n if (controller.isDirty()) {\n warning.show();\n }\n else {\n warning.callbackContinue();\n }\n MenubarController.openAfterWarning = false;\n }", "function update() {\n console.log(\"UPDATE\");\n // Update ractive components\n updateRactives();\n\n // Upgrade all added MDL elements\n upgradeMDL();\n // Reset listeners on all dynamic content\n resetListeners();\n\n // Initiate save to localStorage on every data change\n saveLocal();\n\n // Log updated data object\n console.log(projectManager.getProject());\n\n // Check data entry buttons and enable/disable where necessary\n checkButtons();\n\n // Update interface - check group totals and alter table colours warning of problems\n updateInterface();\n}", "function editProject(userProject) {\r\n return new Promise((resolve, reject) => {\r\n dashboardModel.editProject(userProject).then((data) => {\r\n resolve({ code: code.OK, message: '', data: data })\r\n }).catch((err) => {\r\n if (err.message === message.INTERNAL_SERVER_ERROR)\r\n reject({ code: code.INTERNAL_SERVER_ERROR, message: err.message, data: {} })\r\n else\r\n reject({ code: code.BAD_REQUEST, message: err.message, data: {} })\r\n })\r\n })\r\n}", "function displayProjectsList() {\n\t\t\t\t\t$(\"#d-percent_complete\").css('width', '0%');\t// Shrink the bar down to 0% so it grows when opening a new project.\n\t\t\t\t\t$projectListEles.addClass(\"show\");\n\t\t\t\t\t$projectDetailsEles.removeClass(\"show\");\t\n\t\t\t\t\tclearHash();\n\t\t\t\t}", "function onUpdatedGridData() {\n // Publish model changed\n Control.publishModelChanged(component.address, {values: component.model.values});\n // Store event\n component.storeEvent('change');\n // Show/hide save button\n component.repositionSaveButton();\n // Resize the grid (to show or not scrollbars)\n component.resize();\n }", "function loadProjects() {\n API.getProjects()\n .then((res) => setProjects(res.data))\n .catch((err) => console.log(err));\n }", "function updateRelatedProjects(skill) {\n \n //Hide/reset existing projects\n $('.project-item').hide();\n\n //Check if the related projects section is showing. If not, show it.\n if (!$('#related-projects-p').is(\":visible\")) {\n $('#related-projects-p').toggle();\n }\n\n //Loop through all projects. If project uses skill, add project to list\n var projects = getAllProjects();\n var matches = 0;\n\n // for (let project of projects) {\n for (var i = 0; i < projects.length; i++) {\n var project = projects[i];\n if (project.skills.includes(skill)) {\n\n $('#project-btn-' + (matches + 1)).show();\n $('#project-btn-' + (matches + 1)).text(project.project);\n\n matches++;\n\n }\n\n };\n\n //If skill not used in any projects, prompt to pick another\n if (matches == 0) {\n $('#related-projects-p').hide();\n $('#no-projects-p').show();\n $('#no-projects-p').text(\"Oops, looks like I haven't used \" + skill + \" in any public projects. Try another!\");\n }\n\n\n }", "function refresh_all_action_items() {\n\tconsole.log(\"now refreshing\");\n\t$(\"div#projects div.project\").each( function() {\n\t\trefresh_action_items(this);\n\t});\n}", "handleModifySelPGTobj($change){\n\t const rIndex = this.props.UI.selectedRowIndex;\n\t this.props.onPGTobjArrayChange(\"update\", {index: rIndex, $Updater: $change});\n\t}", "updateListedProject(project){\n\t\tlet projects = this.state.projects\n\t\tlet index = _.indexOf(projects, _.find(projects, {id: project.id}));\n\n\t\tif(index >= 0){\n\t\t\tprojects.splice(index, 1, project);\t\n\t\t} else {\n\t\t\tprojects.unshift(project)\n\t\t}\t\t\n\n\t\tthis.setState({\n\t\t\tprojects: projects,\n\t\t\teditProject: undefined\n\t\t})\n\t}", "createProject(event) {\n const controller = event.data.controller;\n const warning = new WarningDialog(() => {\n controller.createNewProject();\n }, () => {\n MenubarController.createAfterWarning = true;\n $('#saveProject')\n .click();\n }, () => {\n MenubarController.createAfterWarning = true;\n $('#exportProject')\n .click();\n }, null);\n if (controller.isDirty()) {\n warning.show();\n }\n else {\n warning.callbackContinue();\n }\n MenubarController.createAfterWarning = false;\n }", "function xcodeproj() {\n\tconst pbxprojChanged = danger.git.modified_files.find(filepath =>\n\t\tfilepath.endsWith('project.pbxproj'),\n\t)\n\n\tif (!pbxprojChanged) {\n\t\treturn\n\t}\n\n\tmarkdown(\n\t\t'The Xcode project file changed. Maintainers, double-check the changes!',\n\t)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reference to a type parameter.
function TTypeParam(name) { this.name = name; }
[ "function tcbCtxParam(node) {\n var typeArguments = undefined;\n // Check if the component is generic, and pass generic type parameters if so.\n if (node.typeParameters !== undefined) {\n typeArguments =\n node.typeParameters.map(function (param) { return ts.createTypeReferenceNode(param.name, undefined); });\n }\n var type = ts.createTypeReferenceNode(node.name, typeArguments);\n return ts.createParameter(\n /* decorators */ undefined, \n /* modifiers */ undefined, \n /* dotDotDotToken */ undefined, \n /* name */ 'ctx', \n /* questionToken */ undefined, \n /* type */ type, \n /* initializer */ undefined);\n }", "function parseTypeReference() {\n var ref;\n\n if (token.type === _tokenizer.tokens.identifier) {\n ref = identifierFromToken(token);\n eatToken();\n } else if (token.type === _tokenizer.tokens.number) {\n ref = t.numberLiteralFromRaw(token.value);\n eatToken();\n }\n\n return ref;\n }", "set type(aValue) {\n this._logger.debug(\"type[set]\");\n this._type = aValue;\n }", "visitType_elements_parameter(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "enterTypeParameterModifier(ctx) {\n\t}", "function Reference() {}", "function TQualifiedReference(qname) {\n this.qname = qname; // string\n}", "static from(type, value) {\n return new Typed(_gaurd, type, value);\n }", "function isParameter(node) {\n\t return node.kind() == \"Parameter\" && node.RAMLVersion() == \"RAML08\";\n\t}", "enterTypeVariable(ctx) {\n\t}", "function TTypeParameterScope(parent) {\n this.env = new Map\n this.parent = parent;\n}", "createOrReplaceType(name) {\n\t\treturn this.declareType(name);\n\t}", "function resolveType(aResource,RDF,BMDS)\n{\n\tvar type = getProperty(aResource,\"http://www.w3.org/1999/02/22-rdf-syntax-ns#type\",RDF,BMDS);\n\tif (type != \"\")\n\t\ttype = type.split(\"#\")[1];\n\n\tif (type==\"\")\n\t\ttype=\"Immutable\";\n\treturn type;\n}", "function getTypeIdentifier(Repr) {\n\t return Repr[$$type] || Repr.name || 'Anonymous';\n\t }", "enterTypeReference(ctx) {\n\t}", "get rdfaDatatype() {\n if (this.args.datatype) {\n return this.args.datatype;\n }\n\n return this.normalizedRdfaBindings[this.args.prop]?.datatype;\n }", "lookupDescriptor(any) {\n return this.root.lookupType(AnySupport.stripHostName(any.type_url));\n }", "typeSpec() {\n const token = this.currentToken;\n if (this.currentToken.type === tokens.INTEGER) {\n this.eat(tokens.INTEGER);\n } else if (this.currentToken.type === tokens.REAL) {\n this.eat(tokens.REAL);\n }\n return new Type(token);\n }", "static registerType(type) { ShareDB.types.register(type); }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if the new site announcement has been shown 3 times already if not, show it and increment the cookie value
function displayNewSiteAnnouncement() { const NewSiteCookie = 'newSiteAnnouncementShown'; const NewSiteAnnouncement = 'New Site Announcement'; const MaxDisplays = 3; try { // check if the lightbox has been shown once already this _session_ (ie visit to the website) if (!session.getItem(NewSiteCookie)) { session.setItem(NewSiteCookie, 'yes'); // set the session flag so it won't be shown again // check how many times the lightbox has been shown altogether (localSettings this time) let count = parseInt(local.getItem(NewSiteCookie), 10) || 0; if (count < MaxDisplays) { wixWindow.openLightbox(NewSiteAnnouncement); // asynchronous count++; local.setItem(NewSiteCookie, count); } } } catch (err) { // do nothing } }
[ "function wpbingo_ShowNLPopup() {\n\t\tif($('.newsletterpopup').length){\n\t\t\tvar cookieValue = $.cookie(\"digic_lpopup\");\n\t\t\tif(cookieValue == 1) {\n\t\t\t\t$('.newsletterpopup').hide();\n\t\t\t\t$('.popupshadow').hide();\n\t\t\t}else{\n\t\t\t\t$('.newsletterpopup').show();\n\t\t\t\t$('.popupshadow').show();\n\t\t\t}\t\t\t\t\n\t\t}\n\t}", "function MM_FlashRememberIfDetectedSelf(count, units)\r\n{\r\n // the sniffer appends an empty search string to the URL\r\n // to indicate that it is the referrer\r\n\r\n if (document.location.search.indexOf(\"?\") != -1)\r\n {\r\n\tif (!count) count = 60;\r\n\tif (!units) units = \"days\";\r\n\r\n\tvar msecs = new Object();\r\n\r\n\tmsecs.minute = msecs.minutes = 60000;\r\n\tmsecs.hour = msecs.hours = 60 * msecs.minute;\r\n\tmsecs.day = msecs.days = 24 * msecs.hour;\r\n\r\n\tvar expires = new Date();\r\n\r\n\texpires.setTime(expires.getTime() + count * msecs[units]);\r\n\r\n\tdocument.cookie =\r\n\t 'MM_FlashDetectedSelf=true ; expires=' + expires.toGMTString();\r\n }\r\n}", "function MM_FlashDemur(count, units)\r\n{\r\n if (!count) count = 60;\r\n if (!units) units = \"days\";\r\n\r\n var msecs = new Object();\r\n\r\n msecs.minute = msecs.minutes = 60000;\r\n msecs.hour = msecs.hours = 60 * msecs.minute;\r\n msecs.day = msecs.days = 24 * msecs.hour;\r\n\r\n var expires = new Date();\r\n\r\n expires.setTime(expires.getTime() + count * msecs[units]);\r\n\r\n document.cookie =\r\n\t'MM_FlashUserDemurred=true ; expires=' + expires.toGMTString();\r\n\r\n\r\n if (!MM_FlashUserDemurred())\r\n {\r\n\talert(\"Your browser must accept cookies in order to \" +\r\n\t \"save this information. Try changing your preferences.\");\r\n\r\n\treturn false;\r\n }\r\n else\r\n\treturn true;\r\n}", "function hide(div){\n div.css('display','none')\n document.cookie='closed_announce=1'\n}", "function eatCookie() {\n cookiesEaten++;\n cookieInventory--;\n}", "function setCookie(){\r\nvar xxcookie = document.cookie;\r\n\tif (xxcookie.indexOf(\"DesafioLeoLearning\") >= 0){ //verifica se o cookie existe\r\n\t}else{//caso não exista cria o cookie e exibe o banner na tela\t\t\r\n\t\tdocument.cookie = \"username=DesafioLeoLearning; expires=Thu, 18 Dec 2093 12:00:00 UTC\";\r\n\t\tdocument.getElementById('banner').style.marginTop = '0px';\r\n\t}\t\r\n}", "function initializeCookieBanner() {\n let isCookieAccepted = localStorage.getItem(\"cc_isCookieAccepted\");\n if (isCookieAccepted === null) {\n localStorage.clear();\n localStorage.setItem(\"cc_isCookieAccepted\", \"false\");\n showCookieBanner();\n }\n if (isCookieAccepted === \"false\") {\n showCookieBanner();\n }\n}", "function GetAllCookies() {\n \n if (document.cookie === \"\") {\n document.getElementById(\"cookies\").innerHTML = (\"<p style='color: #ff0000;padding-bottom: 15px;'>\" + \"There are no cookies on this page!\" + \"</p>\");\n \n } else {\n document.getElementById(\"cookies\").innerHTML = (\"<p style='color: #000;'>\" + \"These are the cookies on this page:\" + \"</p>\" + \"<p class='utm-values'>\" + document.cookie + \"</p>\");\n }\n }", "function updateGold(){\n //update gold counter\n $(\".cashCounter\").html('');\n $(\".cashCounter\").html(\"$\"+totalGold);\n //update goldcounting cookie to save your progress \n document.cookie = \"gold=\"+totalGold+\"; expires=Thu, 18 Dec 2019 12:00:00 UTC; path=/\";\n }", "static showCookieWarning() {\n return !getLocal('cookie-warning', false);\n }", "function fnCookieWarning(){\r\n if(fnGetConfig(\"Footer_Cookie_Policy\")){\r\n\r\n function createCookie(name, value, days){\r\n if(days){\r\n var date=new Date();\r\n date.setTime(date.getTime()+(days*24*60*60*1000));\r\n var expires=\"; expires=\"+ date.toGMTString();\r\n }else var expires=\"\";\r\n document.cookie=name +\"=\"+ value + expires +\"; path=/\";\r\n }\r\n\r\n function readCookie(name){\r\n var nameEQ=name +\"=\",\r\n ca=document.cookie.split(';');\r\n for(var i=0;i<ca.length;i++){\r\n var c=ca[i];\r\n while(c.charAt(0)==' ')c=c.substring(1,c.length);\r\n if(c.indexOf(nameEQ)==0)return c.substring(nameEQ.length,c.length);\r\n }\r\n return null;\r\n }\r\n\r\n function eraseCookie(name){createCookie(name,\"\",-1);}\r\n\r\n var cookieBody=document.getElementsByTagName(\"BODY\")[0],\r\n cookieLaw=document.getElementById(\"cookie-law\"),\r\n cookieURL=document.getElementById(\"cookie-url\"),\r\n cookieName=\"cookiewarning\",\r\n cookieWarning=document.createElement(\"div.\"+ cookieName);\r\n \r\n function setCookieWarning(active){(!!active)?cookieBody.classList.add(cookieName):cookieBody.classList.remove(cookieName);}\r\n\r\n cookieURL.href=\"/page,arq,cookie-policy-\"+ (\"0\"+FC$.Language).slice(-2) +\".htm,cookie\";\r\n cookieLaw.addEventListener(\"click\", function(){\r\n createCookie(cookieName,1,365)\r\n setCookieWarning(false);\r\n });\r\n\r\n if(readCookie(cookieName)!=1)setCookieWarning(true);\r\n\r\n function removeMe(){\r\n\teraseCookie(cookieName);\r\n\tsetCookieWarning(false);\r\n }\r\n }\r\n }", "function cookieAdvices(numberAdvices, indexAdvice) {\n\tvar oldValue = getCookie(\"advice\"); //get the old value of the cookie\n\tvar newValues = \"\"; //create a new empty cookie value\n\t\n\t//check if the old cookie was empty \n\tif (oldValue == \"\") {\n\t\tvar newValues = \"\";\n\t\tfor (i in Array.from(Array(numberAdvices).keys())) { //fill it with zeroes\n\t\t\tnewValues += 0;\n\t\t\tnewValues += \"%\";\n\t\t}\n\t}\n\t\n\telse {\n\t\tvar newValuesList = oldValue.split(\"%\"); //new value is a list of the values in the old value string\n\t\t\n\t\t//replace the value for the checkboxs of the selected index \n\t\tif (newValuesList[indexAdvice] == 1) {\n\t\t\tnewValuesList[indexAdvice] = 0; \n\t\t} else {\n\t\t\tnewValuesList[indexAdvice] = 1;\n\t\t}\n\t\t\n\t\t//make a string of all values\n\t\tfor (i in Array.from(Array(numberAdvices).keys())) { \n\t\t\tnewValues += newValuesList[i];\n\t\t\tnewValues += \"%\";\n\t\t}\n\t}\n\t\n\tsetCookie(\"advice\", newValues);\n\tconsole.log(\"testing if cookie exists\");\n\tconsole.log(document.cookie);\n}", "function setVisits() {\n var firstVisit = getCookie('FirstVisit');\n var lastVisit = getCookie('LastVisit');\n var visits = getCookie('Visits');\n var date = new Date();\n var newDate = date.getTime();\n // date.toUTCString();\n\n if (firstVisit == '') {\n setCookie('FirstVisit', newDate, 365);\n setCookie('Visits', 1, 365);\n }\n\n var hours = ((newDate - lastVisit) / (1000 * 60 * 60)).toFixed(1);\n\n if (hours > 12) {\n visits = visits + 1;\n setCookie('Visits', visits, 365);\n }\n\n setCookie('LastVisit', newDate, 365);\n}", "function installNotice() {\n\n\t// check if not already set ...\n\tchrome.storage.sync.get(CONSTANTS.INSTALL_KEY, function(result) {\n\n\t\t// and .. ?\n\t\tif(!result.install) {\n\n\t\t\t// get current timestamp\n\t\t var now = new Date().getTime();\n\n\t\t // params to save\n\t\t params = {};\n\n\t\t // set our initial items\n\t\t params[CONSTANTS.INSTALL_KEY] = JSON.stringify({\n\n\t\t \ttimestamp: now\n\n\t\t });\n\n\t\t // set as a note\n\t\t chrome.storage.sync.set(params, function() {\n\n\t\t \t// -- ENABLE TO VIEW THE CONTENT OF THE SYNC DATA STORAGE OBJECT\n\t\t\t\t// chrome.storage.sync.get(null, function (data) { console.info(data) });\n\n\t\t \t// open our welcome page with meta data\n\t\t\t chrome.tabs.create({\n\n\t\t\t \turl: CONSTANTS.URL.WEB + '/welcome?' + [\n\n\t\t\t \t\t'client=chrome',\n\t\t\t \t\t'timestamp=' + now\n\n\t\t\t \t].join('&')\n\n\t\t\t });\n\n\t\t });\n\n\t\t}\n\n\t});\n\n}", "function MM_FlashUserDemurred()\r\n{\r\n return (document.cookie.indexOf(\"MM_FlashUserDemurred\") != -1);\r\n}", "isNewUserCheck() {\n let userCookie = this.helper.getCookieInfo('userName');\n\n // If cookie exists, it means that user visited site earlier.\n if (userCookie.cookieExists) {\n this.userCookie = userCookie.value;\n }\n\n return !userCookie.cookieExists;\n }", "function updateTillPlayed()\n{\n setCookie('timePlayed', song.currentTime);\n}", "function createNoCookiesNoticeBox(message) {\n $('<div/>', { 'class': 'alert is--warning no--cookies' }).append($('<div/>', { 'class': 'alert--icon' }).append($('<i/>', { 'class': 'icon--element icon--warning' }))).append($('<div/>', {\n 'class': 'alert--content',\n 'html': message\n }).append($('<a/>', {\n 'class': 'close--alert',\n 'html': '✕'\n }).on('click', function () {\n $(this).closest('.no--cookies').hide();\n }))).appendTo('.page-wrap');\n }", "function setCookie(c_name, value) {\n var exdate = new Date();\n exdate.setDate(exdate.getDate() + 365);\n var c_value = escape(value) + \"; expires=\" + exdate.toUTCString();\n document.cookie = c_name + \"=\" + c_value;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
build an object from key/value pairs: var obj = h$buildObject(key1, val1, key2, val2, ...); note: magic name: invocations of this function are replaced by object literals wherever possible
function h$buildObject() { var r = {}, l = arguments.length; for(var i = 0; i < l; i += 2) { var k = arguments[i], v = arguments[i+1]; r[k] = v; } return r; }
[ "function createMyObject() {\n return{\n foo:'bar',\n answerToUniverse: 42,\n \"olly olly\": 'oxen free',\n sayHello: function(){\n \treturn 'hello';\n }\n };\n}", "object(...keyValues) {\n const code = ['{']\n for (const [key, value] of keyValues) {\n if (code.length > 1) code.push(',')\n code.push(key)\n if (key !== value || this.opts.es5) {\n code.push(':')\n ;(0, code_1.addCodeArg)(code, value)\n }\n }\n code.push('}')\n return new code_1._Code(code)\n }", "function buildObjectFromObjectData(objectData, roomID, type) {\n\n if (!objectData) {\n Modules.Log.error('No object data!');\n }\n\n var type = type || objectData.type;\n\n // get the object's prototype\n var proto = ObjectManager.getPrototypeFor(type);\n\n // build a new object\n\n var obj = Object.create(proto);\n obj.init(objectData.id);\n\n // set the object's attributes and rights\n // as well as the object type and its room\n // attributes\n obj.setAll(objectData.attributes);\n obj.rights = objectData.rights;\n obj.id = objectData.id;\n obj.attributeManager.set(objectData.id, 'id', objectData.id);\n obj.inRoom = roomID;\n obj.attributeManager.set(objectData.id, 'inRoom', roomID);\n\n obj.set('type', type);\n\n // runtimeData is an array that containts variables\n // an object gets in server side programs which should be\n // available on every instance of the object\n // but are not persisted, so here the runtime data is restored\n // for the new object\n \n if (!runtimeData[obj.id])\n runtimeData[obj.id] = {}; //create runtime data for this object if there is none\n\n obj.runtimeData = runtimeData[obj.id];\n\n // if the object has an afterCreation function, it is called here\n\n if (typeof obj.afterCreation == \"function\") {\n obj.afterCreation();\n }\n\n return obj;\n}", "function object(state) {\n var object = {}, key;\n if (charp(state, '{')) {\n white(state);\n if (charp(state, '}')) {\n return object;\n }\n\n while (!end(state)) {\n key = string(state, '\"') || string(state, \"'\") || identistring(state);\n white(state);\n if (charp(state, ':')) {\n if (Object.hasOwnProperty.call(object, key)) {\n error('Duplicate key \"' + key + '\"', state);\n }\n resetcol(state);\n object[key] = term(state);\n white(state);\n if (charp(state, '}')) {\n return object;\n } else if (charp(state, ',')) {\n white(state);\n } else {\n error('Expecting } or ,', state);\n }\n } else {\n error('Expecting :', state);\n }\n }\n error('Bad object', state);\n } else {\n return '';\n }\n }", "function objectFun(first, last, age, email, color) {\n var person = {\n \tfirst_name: first,\n \tlast_name: last,\n \tage: age,\n \temail: email,\n \tfav_color: color\n };\n return person;\n}", "function make_req_entry(obj_name, obj_value, obj_inst)\r\n{\r\n\tvar r = obj_name;\r\n\tvar s = new String(obj_inst);\r\n\r\n\t// instance already contains 'dot'\r\n\tif (s.indexOf('.') != -1) {\r\n\t\tr += obj_inst+'='+obj_value;\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tfor (var i=0; i<obj_inst.length-1; i++) {\r\n\t\tr += (s.substr(i, 1) + '.');\r\n\t}\r\n\t\r\n\tr += s.substr(obj_inst.length-1, 1);\r\n\tr += '='+obj_value;\r\n\t\r\n\treturn r;\r\n}", "function newObject() {\r\n let journalObject = {\r\n // dateObjectProperty: creationDate,\r\n date: creationDate,\r\n // confidenceObjectProperty: confidenceLevel,\r\n confidence: confidenceLevel,\r\n // journalObjectProperty: journalEnt\r\n journal: journalEnt,\r\n // makeObject() {\r\n // return journalObjectArray.push(journalObject);\r\n // }\r\n }\r\n // return journalObjectArray.push(journalObject);\r\n return journalEntries.push(journalObject);\r\n}", "function ValueObject(ConstructorFn) {\n return function (initialValues) {\n var obj = new ConstructorFn();\n var hasOwnProp = Object.prototype.hasOwnProperty;\n\n // Use initial values where possible.\n if (initialValues) {\n for (var key in obj) {\n if (hasOwnProp.call(obj, key) && hasOwnProp.call(initialValues, key)) {\n obj[key] = initialValues[key];\n }\n }\n }\n\n // Object.seal prevents any other properties from being added to the object.\n // Every property an object needs should be set by the original constructor.\n return _Object$seal(obj);\n };\n}", "function asObjectFactory(groups) {\n return () => {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const obj = {};\n for (const group of groups) {\n if (isObjectAssignable(group.key)) {\n obj[group.key] = group.items;\n }\n }\n return obj;\n };\n}", "function make_function_value(parameters, locals, body, env) {\n return { tag: \"function_value\",\n parameters: parameters,\n locals: locals,\n body: body,\n environment: env,\n // we include a prototype property, initially\n // the empty object. This means, user programs\n // can do: my_function.prototype.m = ...\n prototype: {},\n // another way of calling a function is by\n // invoking it via my_function.call(x,y,z)\n // This is actually an object method application,\n // and thus it becomes\n // (my_function[\"call\"])(my_function,x,y,z)\n // Therefore, we add an argument (let's call it\n // __function__) in front of the parameter list.\n call: { tag: \"function_value\",\n parameters: pair(\"__function__\",\n parameters),\n locals: locals,\n body: body,\n environment: env\n },\n // the property Inherits is available for all functions f\n // in the given program. This means that we can call\n // f.Inherits(...), using object method application\n Inherits: inherits_function_value\n };\n}", "function ObjectMap(stringify){\n\n\tif(typeof stringify == 'function')\n /**\n \t* Method to find unique string keys for objects.\n \t*/\n \tthis.__stringify__ = stringify;\n else throw new Error(\"Please specify a valid function to find string representation of the objects\");\n\n \n /**\n * A plain old javascript object, to hold key-value pairs\n */\n this.__map__ = {};\n\n /**\n * A varibale to keep track of the number of key-value pairs\n * in the map\n */\n this.__size__=0;\n}", "function createObj(id, textValue, dateValue, timeValue) {\n let noteObjTemp = Object.create(noteObjTemplate);\n noteObjTemp.id = id;\n noteObjTemp.text = textValue;\n noteObjTemp.date = dateValue;\n noteObjTemp.time = timeValue;\n return noteObjTemp;\n }", "function buildEmployee(employee) {\n let name = employee.name;\n let id = employee.id;\n let email = employee.email;\n let role = employee.role; \n\n // checking to see the correct keys and values \n // console.log('inside the build employee function',employee);\n\n switch (role) {\n case 'Manager': return new Manager(name, id, email, employee.officeNumber);\n case 'Intern': return new Intern(name, id, email, employee.school);\n case 'Engineer': return new Engineer(name, id, email, employee.gitHub);\n default: return 'something went really wrong in building an employee';\n }\n}", "kvProps(key: string, name: ?string = null) {\n let finalName = name;\n if (!finalName) {\n if (/^[a-zA-Z_][a-zA-Z_0-9]*$/.test(key)) {\n finalName = key;\n } else {\n throw new Error(`HrQuery::kvProps expected either the second argument to be provided, or for the first argument to be a valid identifier.`);\n }\n }\n const desc = this.kvDesc(key);\n\n if (!desc) return {};\n\n const props = {\n [finalName]: desc.value,\n [`${finalName}Error`]: desc.error,\n [`${finalName}HasError`]: desc.hasError,\n [`${finalName}Loading`]: desc.loading,\n [`${finalName}Etc`]: desc.etc || {},\n };\n\n return props;\n }", "function makeUser(usernameInput) {\n const username = usernameInput.value;\n const UserObject = {\n name: username,\n wallet: 75,\n };\n\n return UserObject;\n\n}", "function makePerson (name, birthday, ssn) {\n var newPerson = {name, birthday, ssn}\n return newPerson\n }", "function makeTestChemProperties(symbol, name, creator,\n colorSolid, colorLiquid, colorGas,\n id, molarMass, meltingPoint, boilingPoint, density, waterSoluble){\n\n let p = {};\n p[CHEMICAL_PROPERTY_ID] = id;\n p[CHEMICAL_PROPERTY_SYMBOL] = symbol;\n p[CHEMICAL_PROPERTY_NAME] = name;\n p[CHEMICAL_PROPERTY_CREATOR] = creator;\n p[CHEMICAL_PROPERTY_COLOR_SOLID] = colorSolid;\n p[CHEMICAL_PROPERTY_COLOR_LIQUID] = colorLiquid;\n p[CHEMICAL_PROPERTY_COLOR_GAS] = colorGas;\n p[CHEMICAL_PROPERTY_MOLAR_MASS] = molarMass;\n p[CHEMICAL_PROPERTY_MELTING_POINT] = meltingPoint;\n p[CHEMICAL_PROPERTY_BOILING_POINT] = boilingPoint;\n p[CHEMICAL_PROPERTY_DENSITY] = density;\n p[CHEMICAL_PROPERTY_WATER_SOLUBLE] = waterSoluble;\n return p;\n}", "static uniqueIdentityToHashObject(uniqueIdentity) {\n var terms = uniqueIdentity.split(':');\n if (terms.length != 2) {\n throw \"unique-identity has invalid format\";\n }\n let hashType = terms[0];\n let hashValue = terms[1];\n if (SUPPORTED_COMMON_NAME_HASH_TYPES.indexOf(hashType) < 0) {\n throw \"hash function '\" + hashType + \"' is not supported for certificate Common Name unique identity\";\n }\n return {\n 'hashType': hashType,\n 'hashValue': hashValue\n };\n }", "function createObject(vertices) {\n return { vertices: vertices };\n}", "function makeTestChemicalJSON(id, mass, concentration){\n let c = {};\n c[EXP_JSON_CHEM_ID] = id;\n c[EXP_JSON_CHEM_MASS] = mass;\n c[EXP_JSON_CHEM_CONCENTRATION] = concentration;\n return c;\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new target data instance with an updated sequence number.
withSequenceNumber(t) { return new si(this.target, this.targetId, this.purpose, t, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken); }
[ "function newRequest(data){\n var request = createNewRequestContainer(data.requestId);\n createNewRequestInfo(request, data);\n }", "setNew(val) {\n return this._new !== val\n ? Object.assign(new this.constructor(this._data), {\n _new: val\n })\n : this\n }", "function newReference(source, target) {\n var oldMem = copyObject(currentMemoryModel);\n if (toggleEditingMode === true) {\n relations.push({source: source, target: target});\n var indexList = lookForFrameOrVar(source);\n\n if(indexList.location === \"stack\") {\n currentMemoryModel.memoryModel.stacks[indexList.stackIndex][indexList.frameIndex].vars[indexList.elementIndex].value = target;\n currentMemoryModel.memoryModel.stacks[indexList.stackIndex][indexList.frameIndex].vars[indexList.elementIndex].type = \"reference\";\n }\n else{\n currentMemoryModel.memoryModel.heaps[indexList.heapIndex][indexList.frameIndex].vars[indexList.elementIndex].value = target;\n currentMemoryModel.memoryModel.heaps[indexList.heapIndex][indexList.frameIndex].vars[indexList.elementIndex].type = \"reference\";\n }\n percolatorSend({\n msgType: 'updateMemoryModel',\n data: {newMemoryModel: currentMemoryModel, oldMemoryModel: oldMem}\n });\n }\n}", "newRecord() {}", "function setTargetDefinition (symbol, index) {\n $scope.targetDefinition.symbol = symbol;\n $scope.targetDefinition.index = index;\n }", "function TplBuilder(template, data, domTarget) {\n this.template = template;\n this.data = data;\n this.domTarget = domTarget;\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}", "function newTrain(t, d, ft, fr) {\n\n // Whatever will be in this variable will be \"pushed\" to a new reference,\n // instead of replacing an old reference.\n var train = database.ref().push();\n\n // sets the following parameters.\n // The parameter names is the name on the left of the colon.\n // The parameter value is the name on the right of the colon.\n train.set({\n trainName: t,\n destination: d,\n firstTrainTime: ft,\n frequency: fr\n });\n}", "function add_tar(new_target, dbs, target, searchmode) {\n if (new_target) {\n\t new_target.$save(function(){\n //new record in bacster_bac:\n var new_bac = new Bac({bacset: dbs, target: new_target.pk});\n new_bac.$save(function(){\n //new record in bacster_bacsession:\n var new_bacsession = new Bacsession({bac: new_bac.pk, session: session.data().user.id});\n new_bacsession.$save(function(){\n //add target to the grid:\n\t\t $scope.myData.push({ 'target' : target, 'search type' : searchmode});\n });\n });\n\t });\n }\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 }", "prependData(target, data){\n var node = new DLLNode(data);\n var runner = this.head;\n while(runner){\n if(runner === target){\n node.next = runner;\n node.prev = runner.prev;\n runner.prev.next = node;\n runner.prev = node;\n this.length++;\n if(runner === this.head){\n this.head = node;\n }\n }else{\n runner = runner.next;\n }\n }\n }", "createTargetArray() {\r\n const dim = this.board === 5 ? 3 : 4;\r\n let targetArray = new Array(dim);\r\n for (let i = 0; i < targetArray.length; i++) {\r\n targetArray[i] = new Array(dim);\r\n for (let j = 0; j < targetArray[i].length; j++) {\r\n targetArray[i][j] = Math.floor(Math.random() * 6 + 1);\r\n }\r\n }\r\n this.targetArray = targetArray;\r\n }", "function start() {\n targetNumber = Math.floor(Math.random() * 102) + 19;\n console.log(targetNumber);\n applyValues();\n console.log(toppings);\n updateHtml();\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 }", "createScheduleProcess(timestamp) {\n /*\n In a real world application, we will get associated timezoneCode according\n to the language.\n For simplicity, here we just random isoCode and timezoneCode.\n */\n const randomISOCode = textUtils.getRandomItem(this.database.languages)\n .isoCode.toLowerCase();\n const { id } = this.database.emailBodies.find((eb) => eb.isoCode === randomISOCode);\n const { code } = textUtils.getRandomItem(this.database.timezones);\n\n const scheduleProcess = new ScheduleProcessModel({\n emailBodyId: id,\n /*\n For now, random recipients list. In the real world - You will probably want\n to fetch them according to theire culture (similar to the email body),\n timezone, isSubscribed=true, and by the product demands.\n */\n recipientsList: this.createRecipients(),\n timezoneCode: code,\n /*\n For now, random recurrence days and specific time. In the real world it's depend\n on the recipients culture, timezone, and product needs.\n */\n recurrenceDaysInWeek: textUtils.getRandomNumbersList(),\n recurrenceTime: timeUtils.getRandomHour(),\n treatmentScheduleAt: timestamp\n });\n this.database.scheduleProcesses.push(scheduleProcess);\n return scheduleProcess;\n }", "function generateTarget() {\n targetScore = Math.floor(Math.random() * (121 - 19) + 19);\n $(\"#targetScore\").text(targetScore);\n}", "cloneAttributes(target, source) {\n [...source.attributes].forEach( attr => { target.setAttribute(attr.nodeName === \"id\" ? 'data-id' : attr.nodeName ,attr.nodeValue) })\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}", "function generateNewAddress(){\n \n server.accounts()\n .accountId(source.publicKey())\n .call()\n .then(({ sequence }) => {\n const account = new StellarSdk.Account(source.publicKey(), sequence)\n const transaction = new StellarSdk.TransactionBuilder(account, {\n fee: StellarSdk.BASE_FEE\n })\n .addOperation(StellarSdk.Operation.createAccount({\n destination: destination.publicKey(),\n startingBalance: '2'\n }))\n .setTimeout(30)\n .build()\n transaction.sign(StellarSdk.Keypair.fromSecret(source.secret()))\n return server.submitTransaction(transaction)\n })\n .then(results => {\n console.log('Transaction', results._links.transaction.href)\n console.log('New Keypair', destination.publicKey(), destination.secret())\n })\n\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ajax call to retrieve all guilds
function retrieveGuilds(){ $('#create_guild').show(); $.ajax({ type: "GET", url: "/WebArenaGoupSI1-04-BE/Upgrade/retrieveAllGuilds", contentType: "application/json", dataType: "json", success: function (data) { $("#guildTable").empty(); //populate HTML ul with list of guilds $.each(data, function(key,value) { //$("#listAllGuilds").children().remove(); $("#guildTable").append('<tr><td>' + value.Guild.name + '</td><td><button onclick="join_guil('+value.Guild.id+');">' + "Join Guild" + '</button></td></tr>'); }); }, error: function (error){ } }); }
[ "function retrievePlayerGuild(){\n $('#create_guild').hide();\n $.ajax({\n\t type: \"GET\",\n\t url: \"/WebArenaGoupSI1-04-BE/Upgrade/retrievePlayersGuild\",\n contentType: \"application/json\",\n dataType: \"json\",\n success: function (data) { \n \n //populate HTML ul with list of guilds\n $(\"#guildTable\").empty();\n //$(\"#listAllGuilds\").children().remove();\n $(\"#guildTable\").append('<tr><td>' + data.Guild.name + '</td><td><button onclick=\"leave_guil();\">' + \"Leave Guild\" + '</button></td></tr>'); \n },\n\t error: function (error){\n\t }\n }); \n}", "function _GET_AllThreads() {\n\n $.ajax({\n dataType: \"json\",\n // headers: { \"Authorization\": \"Basic \" + btoa(state.user + \":\" + state.password) },\n url: \"/threads\",\n success: function success(data) {\n state.movieThreads = data.movieThreads;\n saveToStorage(state); // persist\n renderMovieThreads(state);\n },\n type: \"GET\"\n });\n}", "function getGists(){\n\tvar url = API_URL + '/gists/public';\n\t$(\"#gists_result\").text('');\n\t\n\t$.ajax({\n\t\turl : url,\n\t\ttype : 'GET',\n\t\tcrossDomain : true,\n\t\tdataType : 'json',\n\t}).done(function(data,status,jqxhr){\n\t\t\t\tvar gists = data;\n\t\t\t\t\n\t\t\t\t//$.each(gists, function(i,v){\n\t\t\t\tfor (var i=0; i<5; i++){\n\t\t\t\t\tvar gist = gists[i];\n\t\t\t\t\t\n\t\t\t\t\t$('<h4> Datos Gist </h4>').appendTo($('#gists_result'));\n\t\t\t\t\t$('<p>').appendTo($('#gists_result'));\n\t\t\t\t\t$('<strong> ID: </strong>' + gist.id + '<br>').appendTo($('#gists_result'));\n\t\t\t\t\t$('<strong> URL: </strong>' + gist.url + '<br>').appendTo($('#gists_result'));\n\t\t\t\t\t$('<strong> Descripcion: </strong>' + gist.description + '<br>').appendTo($('#gists_result'));\n\t\t\t\t\t$('<strong> Propietario: </strong>' + gist.owner.login + '<br>').appendTo($('#gists_result'));\n\t\t\t\t\t$('</p>').appendTo($('#gists_result'));\n\t\t\t\t\tconsole.log(gist);\n\t\t\t\t};\n\t}).fail(function(){\n\t\t$('#gists_result').text('No hay gists publicos');\n\t});\n}", "async delete() {\n\t\tawait this.reload();\n\t\treturn this.datahandler.removeGuild(this.guild);\n\t}", "function userLoadPrivileges(){\n $.ajax({\n url : endpoint+'?action=users&subaction=getAllPrivileges',\n method: 'GET'\n }).done(function(response){\n if(response != undefined){\n response = JSON.parse(response);\n if(response.success == true){\n for(var i=0; i< response.items.length; i++){\n var item = response.items[i];\n //console.log(item);\n $('.field-user-privilege').append('<option value=\"'+item+'\">'+item+'</option>');\n }\n }\n }\n });\n}", "listAllGroups () {\n return this._apiRequest('/groups/all')\n }", "function unselectGuild() {\n if (scheduledCmds[selectedGuild]) {\n for (let i = 0; i < scheduledCmds[selectedGuild].length; i++) {\n clearTimeout(scheduledCmds[selectedGuild][i].timeout);\n }\n }\n selectedGuild = null;\n mainBody.children[0].classList.remove('hidden');\n if (mainBody.children.length > 2) {\n mainBody.children[2].classList.add('hidden');\n }\n for (let i in guildList.children) {\n if (typeof guildList.children[i].style === 'undefined') continue;\n guildList.children[i].classList.remove('hidden');\n guildList.children[i].classList.remove('selected');\n guildList.children[i].onclick = function() {\n selectGuild(this.id);\n };\n }\n }", "getGuild() {\n this.logger.debug(GuildService.name, this.getGuild.name, \"Executing\");\n this.logger.debug(GuildService.name, this.getGuild.name, \"Exiting with guild.\");\n return this.guild;\n }", "function getWords() {\n\tif (player != \"\" && room != -1) {\n//\t\tdebug(\"-\");\n\t\tvar geturl = \"/sanaruudukko/rest/sr/process?func=getwords&player=\" + player + \"&passcode=\" + passcode;\n\t\t$.ajax({\n//\t\t\tcache: false,\n\t\t\tdataType : 'xml',\n\t\t\ttype : 'GET',\n\t\t\turl : geturl,\n\t\t\tsuccess : function(data) {\n\t\t\t\tupdatewords(data);\n\t\t\t}\n\t\t});\n\t}\n}", "function getMenus(){\n $.ajax({\n url:root_url+'/site_page/getMenus',\n type:'post',\n dataType:'json',\n success:function(data){\n var isStorable = false;\n /*remove existing menus*/\n if($(\"#megamenu\").length > 0) {\n $(\"#megamenu\").html(\"\");\n }\n /*check whether storage is supported to browser*/\n if(typeof(Storage) !== \"undefined\") {\n isStorable = true;\n localStorage.setItem(\"megamenu.expire\",new Date().getTime());\n }\n $.each(data, function(key, value){\n /*insert the submenu to it's location */\n $(\".menu_wrapper ul li a\").each(function(){\n var menu_name = $(this).html();\n var first_part_name = menu_name.split(\" \");\n var name_to_match = first_part_name[0].toLowerCase();\n if(key == name_to_match) {\n if(isStorable) {\n localStorage.setItem(\"megamenu.\"+key,value);\n }\n $(\"#megamenu\").append(value);\n return false;\n }\n });\n });\n },\n error:function(){\n }\n });\n }", "function showGroupName(){\n\tvar url = \"https://\"+CURRENT_IP+\"/cgi-bin/NFast_3-0/CGI/RESERVATIONMANAGER/FastConsoleCgi.py?action=getgroupnamelist&query={'QUERY':[{'username':'\"+globalUserName+\"'}]}\";\n\t\t$.ajax({\n\t\turl: url,\n\t\tdataType: 'html',\n\t\tmethod: 'POST',\n\t\tproccessData : false,\n\t\tasync:false,\n\t\tsuccess: function(data) {\n\t\t\tdata = $.trim(data);\n\t\t\tdata = data.replace(/'/g,'\"');\n\t\t\tvar json = jQuery.parseJSON(data);\n\t\t\t\tconsole.log(\"getGROUP\",data)\n\t\t\t\tfor (var i = 0; i< json.data[0].row.length; i++ ){\n\t\t\t\t\tvar groupname = json.data[0].row[i].GroupName;\n\t\t\t\t\tvar hostname =\tjson.data[0].row[i].HostName;\n\t\t\t\t\tvar usermember = json.data[0].row[i].UserMember;\n\t\t\t\tstr += \"<li style='font-size:10px;list-style:none;cursor:pointer;text-align:left;margin-left:4px;' class='createdGroup'>\"+groupname+\"</li>\"\t\t\t\t\n\t\t\t\t}\n\t\t\t\t$('#grouplist').html(str);\n\t\t\t}\n\t});\n}", "function getNodes() {\n \n $.ajax({\n url : window.helper.getAPIUrl(\"servers\"),\n method: \"GET\",\n crossDomain: true,\n success : function(list) {\n window.nodes = createMarkers(list, \"Node\");\n showMarkers(window.nodes);\n getClients(list);\n },\n error : function(request, error) {\n window.alert(\"Could not retrieve the data, see console for details.\");\n window.console.dir(error);\n }\n });\n \n// createMarkers(loadTestData());\n// createClients(loadTestData());\n}", "function loadAllLessons(){\n\tconsole.log(\"========Loading All Lessons==========\");\n\n\t// Query the database for all the lessons \n\tAjax(\"../Lux/Assets/query.php\", {query:{type:\"lesson\"}}, \n\tfunction(data){\n\t\tvar obj = data[1];\n\t\t// loop all the lessons\n\t\tif(obj.length != 0){\n\t\t\tfor(var key in obj){\n\t\t\t\tappendLesson(obj[key], key, true);\n\t\t\t}\n\t\t}\n\t\taddNewLesson();\n\t});\n}", "function getItems() {\n fetch('http://genshinnews.com/api')\n .then(response => response.text())\n .then(data => {\n discordHooks = JSON.parse(`[${data}]`)\n webhookLoop(discordHooks)\n });\n }", "function populateSqdDropdown(){\n var xhttp = new XMLHttpRequest();\n xhttp.onreadystatechange = function() {\n if (this.readyState == 4 && this.status == 200) {\n let outputArray = JSON.parse(xhttp.responseText);\n let loopCounter = outputArray.length;\n for(i = 0; i<loopCounter; ++i){\n let squadronName = outputArray[i];\n let html = '<option>'+squadronName+'</option>';\n $(\"#squadronSelect\").append(html);\n }\n }\n };\n xhttp.open(\"GET\", \"scripts/squadronquery.php\", true);\n xhttp.send();\n}", "function getGroupInfo(){\n // Snorlax OP\n var groupInfoArray = []; // (Name, ID, Requests)\n // AJAX HERE\n $.ajax({\n url: \"https://hackforums.net/usercp.php?action=usergroups\",\n cache: false,\n success: function(response) {\n if (!$(response).find(\"Groups You Lead\")){\n window.alert(\"Group Management Links 2.0 FAILED!\\nGroup privledges not found!\");\n }\n else{\n $(response).find(\"a:contains('View Members')\").each(function() {\n groupInfoArray.push($(this).parent().prev().text()); // Group Name\n if(debug){console.log(groupInfoArray[0]);}\n groupInfoArray.push($(this).attr(\"href\").substr(20)); // Group ID\n if(debug){console.log(groupInfoArray[1]);}\n groupInfoArray.push($(this).parent().next().text().replace(/[^0-9]/g, '')); // Pending Requests\n if(debug){console.log(groupInfoArray[2]);}\n });\n GM_setValue(\"groupInfo\", groupInfoArray.join().toString());\n }\n prevInfo = GM_getValue(\"groupInfo\", false);\n setGroupInfo();\n }\n });\n}", "getGamesFromServer(){\n\n const user = this.getUser();\n\n this.showLoader();\n\n Ajax.get('/games', {user}, true).then(function(data){\n\n Ajax.validateAjaxResponseRedirect(data);\n\n if(data.length) {\n\n data.forEach(function (element) {\n\n this.addItemToGamesList(element, user);\n }.bind(this));\n }else{\n\n this.showMessage('You have no ongoing games.')\n }\n\n return Ajax.get('/games_to_join', {user}, true);\n }.bind(this)).then(function(data){\n\n if(data.length){\n\n data.forEach(function(item){\n\n this.addItemToSliderMenu(item);\n }.bind(this));\n }else{\n\n this.addItemToSliderMenu();\n }\n\n this.hideLoader();\n this.validateGamesQuantity();\n }.bind(this));\n }", "get guildID() {\n return this._player.guildID;\n }", "function downloadWorldData() {\n // Load continent JSON async.\n $.getJSON(\"https://api.guildwars2.com/v2/continents?ids=all\", function(data) {\n // Load first available continent\n continentList = data;\n renderContinent(continentList[0]);\n });\n\n // Load map data async\n jQuery.getJSON(\"https://api.guildwars2.com/v1/maps\", function(data) {\n mapData = new Object();\n\n for (var object in data.maps) {\n // We need to check if we're dealing with a map or some other undefined junk within the maps object\n // Typical javascript rubbish.\n if (!data.maps.hasOwnProperty(object)) continue;\n var m = data.maps[object];\n\n if (mapData[m.continent_id] == undefined)\n mapData[m.continent_id] = []\n\n mapData[m.continent_id].push(m)\n }\n\n populateContinent(continentList[0]);\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to tally up the positive an negative from the SVM prediction
function calculateSentiment(svmPredictionValues){ var positive = 0; var negative = 0; var i; for(i = 0; i < svmPredictionValues.length; i++){ if(svmPredictionValues[i] == 1){ positive++; } else{ negative++; } if((i+1) >= svmPredictionValues.length){ console.log(" "); console.log(" "); console.log("==========================================="); console.log(" "); console.log("**************SVM Data Report**************") console.log(" "); console.log("Positives: " + positive); console.log("Negatives: " + negative); console.log(" "); console.log(svmReport); console.log(" "); console.log("==========================================="); if(positive > negative){ console.log("Positive sentiment."); console.log(" "); positive = 0; negative = 0; } if(positive < negative){ console.log("Negative sentiment."); console.log(" "); positive = 0; negative = 0; } if(positive = negative){ console.log("Neutral sentiment."); console.log(" "); positive = 0; negative = 0; } } } twitterFeed(); predictionValues.length = 0; }
[ "through(threshold) {\n\n\t\tlet d = this.value - threshold\n\t\tlet d_old = this.value_old - threshold\n\n\t\treturn d >= 0 && d_old < 0 ? 1 : d <= 0 && d_old > 0 ? -1 : 0\n\n\t}", "function countKdressKwiMinus() {\n\t\t\tif(instantObj.noOfKdressKWI > 0) {\n\t\t\t\tinstantObj.noOfKdressKWI = instantObj.noOfKdressKWI - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function countKdressKwfMinus() {\n\t\t\tif(instantObj.noOfKdressKWF > 0) {\n\t\t\t\tinstantObj.noOfKdressKWF = instantObj.noOfKdressKWF - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function calculatePredictedFinish() {}", "speedUp() {\n if(this.score > 30) {\n return 1.8;\n }\n if(this.score > 20) {\n return 1.7;\n }\n if(this.score > 15) {\n return 1.5;\n }\n else if(this.score > 12) {\n return 1.4;\n }\n else if(this.score > 10) {\n return 1.3;\n }\n else if(this.score > 8) {\n return 1.2;\n }\n else if(this.score > 5) {\n return 1.1;\n }\n return 1;\n }", "function countPositives(arr) {\n var count = 0;\n for (var x=0; x<arr.length; x++) {\n if (arr[x] > 0) {\n count++\n }\n }\n arr[arr.length - 1] = count\n return arr\n}", "function total_sub_instruction_count_aux(id_of_top_ins, aic_array){\n let result = 0 //this.added_items_count[id_of_top_ins]\n let tally = 1 //this.added_items_count[id_of_top_ins]\n for(let i = id_of_top_ins; true ; i++){\n let aic_for_i = aic_array[i] //this.added_items_count[i]\n if (aic_for_i === undefined) {\n shouldnt(\"total_sub_instruction_count_aux got undefined from aic_array: \" + aic_array)\n }\n result += aic_for_i //often this is adding 0\n tally += aic_for_i - 1\n if (tally == 0) { break; }\n else if (tally < 0) { shouldnt(\"in total_sub_instruction_count got a negative tally\") }\n }\n return result\n}", "function countSuitsBlazerWwiMinus() {\n\t\t\tif(instantObj.noOfSuitsBlazerWWI > 0) {\n\t\t\t\tinstantObj.noOfSuitsBlazerWWI = instantObj.noOfSuitsBlazerWWI - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "calcIgnorance() {\n var _this = this;\n var data = this.data;\n\n // Loop through all CATEGORIES\n $.each(data.categories, function(index, category) {\n if (_this.debug) console.log(\"\\nCALC Ignorance - Category: \" + category.name + \" >>>>>>>>>>>>>>>>>>>>>>>>>>>>\");\n var ignorance_result = category.MdashH / (1 - category.MlH);\n category.Ignorance = ignorance_result;\n if (_this.debug) console.log(\"category.Ignorance: \" + category.Ignorance);\n });\n\n }", "function countSuitsBlazerMwiMinus() {\n\t\t\tif(instantObj.noOfSuitsBlazerMWI > 0) {\n\t\t\t\tinstantObj.noOfSuitsBlazerMWI = instantObj.noOfSuitsBlazerMWI - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function countKurtaMwiMinus() {\n\t\t\tif(instantObj.noOfKurtaMWI > 0) {\n\t\t\t\tinstantObj.noOfKurtaMWI = instantObj.noOfKurtaMWI - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function countSuitsBlazerWwfMinus() {\n\t\t\tif(instantObj.noOfSuitsBlazerWWF > 0) {\n\t\t\t\tinstantObj.noOfSuitsBlazerWWF = instantObj.noOfSuitsBlazerWWF - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function getPV(current_cashflow, growth_rate_1, growth_rate_2, discount_rate){\n var pv = 0\n var temp = current_cashflow\n var sum = 0\n for(var i = 0; i < 10; i++){\n var discountFactor = 1 / (1 + discount_rate) ** (i + 1)\n //Before Discount\n if(i < 3)\n temp = temp * growth_rate_1 \n else\n temp = temp * growth_rate_2 \n // console.log(\"temp\", i+1, \": \", temp);\n //After discount\n sum += temp * discountFactor\n // console.log(\"discount\", i+1, \": \", discountFactor);\n // console.log(\"sum \",i+1, \": \",sum)\n }\n pv = sum\n return pv\n}", "function countKurtaMwfMinus() {\n\t\t\tif(instantObj.noOfKurtaMWF > 0) {\n\t\t\t\tinstantObj.noOfKurtaMWF = instantObj.noOfKurtaMWF - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function countCarpetHwfMinus() {\n\t\t\tif(instantObj.noOfCarpetHWF > 0) {\n\t\t\t\tinstantObj.noOfCarpetHWF = instantObj.noOfCarpetHWF - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function countTshirtWwiMinus() {\n\t\t\tif(instantObj.noOfTshirtWWI > 0) {\n\t\t\t\tinstantObj.noOfTshirtWWI = instantObj.noOfTshirtWWI - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function countTshirtMwiMinus() {\n\t\t\tif(instantObj.noOfTshirtMWI > 0) {\n\t\t\t\tinstantObj.noOfTshirtMWI = instantObj.noOfTshirtMWI - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function countTowelHwfMinus() {\n\t\t\tif(instantObj.noOfTowelHWF > 0) {\n\t\t\t\tinstantObj.noOfTowelHWF = instantObj.noOfTowelHWF - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}", "function countLungiDhotiMwfMinus() {\n\t\t\tif(instantObj.noOfLungiDhotiMWF > 0) {\n\t\t\t\tinstantObj.noOfLungiDhotiMWF = instantObj.noOfLungiDhotiMWF - 1;\n\t\t\t\tcountTotalBill();\n\t\t\t}\n\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ping at mouse position
function ping(x, y) { mousePos = { x: x, y: y }; if (mousePos.y < toolbox.height) { return; } toolComponent = Qt.createComponent("ping.qml"); if (toolComponent.status == Component.Loading) { toolComponent.statusChanged.connect(finishCreation); } else { finishCreation(); } }
[ "function ping() {\n primus.clearTimeout('ping').write('primus::ping::'+ (+new Date));\n primus.emit('outgoing::ping');\n primus.timers.pong = setTimeout(pong, primus.options.pong);\n }", "function ping() {\n rpc.tunnel.ping(function (err, _ts) {\n if (err) return console.error(err)\n clearTimeout(timer)\n timer = setTimeout(ping, 10e3)\n })\n }", "function updateMouse(e) {\n mouseX = e.pageX;\n mouseY = e.pageY;\n}", "function showMousePosition(x, y){\n if(!(x > canvasWidth || x < 0 || y > canvasHeight || y < 0)){\n mouseParagraph.html(\"x: \"+ Number.parseFloat(x).toFixed(0) + \" y: \" + Number.parseFloat(y).toFixed(0)); \n } else{\n mouseParagraph.html(\"\"); \n\n }\n}", "startTrackingMouse() {\n if (!this._pointerWatch) {\n let interval = 1000 / Clutter.get_default_frame_rate();\n this._pointerWatch = PointerWatcher.getPointerWatcher().addWatch(interval, this.scrollToMousePos.bind(this));\n }\n }", "function drawPointerPos() {\n circle(context,pointer.x,pointer.y,pointer.radius/step*50);\n}", "function mouseApasat(ev) {\n x1 = my_canvasX(ev);\n y1 = my_canvasY(ev);\n m_apasat = true;\n \n}", "function mousePressed() {\n covid20.x = mouseX;\n covid20.y = mouseY;\n}", "function clickOnPoint() {\n var x = 58,\n y = 275;\n _DygraphOps[\"default\"].dispatchMouseDown_Point(g, x, y);\n _DygraphOps[\"default\"].dispatchMouseMove_Point(g, x, y);\n _DygraphOps[\"default\"].dispatchMouseUp_Point(g, x, y);\n }", "function sketchpad_mouseDown() {\n mouseDown=1;\n drawDot(ctx,mouseX,mouseY,pencilThickness, currentColor);\n}", "function mouseclicks()\n{\n //mouse makes yellow dot\n fill(255,255,0);\n circle(mousex, mousey, d);\n \n}", "function mousePressed() {\n shocked = true;\n}", "function mousePressed() {\n // Check if the mouse is in the x range of the target\n if (mouseX > targetX - targetImage.width/2 && mouseX < targetX + targetImage.width/2) {\n // Check if the mouse is also in the y range of the target\n if (mouseY > targetY - targetImage.height/2 && mouseY < targetY + targetImage.height/2) {\n //add in victory music\n winningSound.play();\n gameOver = true;\n }\n }\n}", "function mousePressed(){\r\n count-=1;\r\n if(gameState===\"PLAY\" && count>0){\r\n particle=new Particle(mouseX,10,10);\r\n }\r\n}", "isTrackingMouse() {\n return !!this._mouseTrackingId;\n }", "function pingFromPlant(){\n\n}", "function paddleInCanvas(){\nif(mouseY+paddle1Height > height){\nmouseY=height-paddle1Height;\n}\nif(mouseY < 0){\nmouseY =0;\n}\n\n\n}", "static _get_mousepos_percent(event) {\n var x = event.clientX + window.scrollX;\n var y = event.clientY + window.scrollY;\n var width = window.innerWidth;\n var height = window.innerHeight;\n return {x: (100.0*x)/width, y: (100.0*y)/height};\n }", "function mousemove(e) {\n var ifrPos = eventXY(e) // mouse from iframe origin\n var xyOI = iframeXY(iframe) // iframe from window origin\n var xySW = scrollXY(window) // window scroll\n var xySI = scrollXY(iwin) // iframe scroll\n // mouse in iframe viewport\n var xyMouse = xy.subtract(ifrPos, xySI)\n // mouse in window viewport\n var winPos = xy.subtract(xy.add(xyMouse, xyOI), xySW)\n lastMousePos = xyMouse\n coords.show(xy.str(ifrPos), xy.add(winPos, deltaXY))\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Visit a parse tree produced by PlSqlParserconstructor_declaration.
visitConstructor_declaration(ctx) { return this.visitChildren(ctx); }
[ "enterConstructorDeclarator(ctx) {\n\t}", "visitConstructor_spec(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "visitDeclare_spec(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "exitConstructorDeclarator(ctx) {\n\t}", "visitType_declaration(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function ensureConstructor (path: NodePath) {\n let lastProperty;\n const [existing] = path.get('body.body').filter(\n item => {\n if (item.isClassProperty()) {\n lastProperty = item;\n return false;\n }\n return item.node.kind === 'constructor';\n }\n );\n if (existing) {\n return existing;\n }\n let constructorNode;\n if (path.has('superClass')) {\n const args = t.identifier('args');\n constructorNode = t.classMethod(\n 'constructor',\n t.identifier('constructor'),\n [t.restElement(args)],\n t.blockStatement([\n t.expressionStatement(\n t.callExpression(\n t.super(),\n [t.spreadElement(args)]\n )\n )\n ])\n );\n\n }\n else {\n constructorNode = t.classMethod(\n 'constructor',\n t.identifier('constructor'),\n [],\n t.blockStatement([])\n );\n }\n\n if (lastProperty) {\n lastProperty.insertAfter(constructorNode);\n }\n else {\n path.get('body').unshiftContainer('body', constructorNode);\n }\n}", "enterClassMemberDeclaration(ctx) {\n\t}", "enterNormalClassDeclaration(ctx) {\n\t}", "enterConstructorBody(ctx) {\n\t}", "function ProgramParser() {\n \t\t\n \t\t this.parse = function(kind) {\n \t\t \tswitch (kind) { \t\n \t\t \t\tcase \"declaration\": return Declaration();\n \t\t \t\tbreak;\n\t \t\t\tdefault: return Program();\n\t \t\t}\n\t \t}\n \t\t\n \t\t// Import Methods from the expression Parser\n \t\tfunction Assignment() {return expressionParser.Assignment();}\n \t\tfunction Expr() {return expressionParser.Expr();}\n \t\tfunction IdentSequence() {return expressionParser.IdentSequence();}\n \t\tfunction Ident(forced) {return expressionParser.Ident(forced);}\t\t\n \t\tfunction EPStatement() {return expressionParser.Statement();}\n\n\n\t\tfunction whatNext() {\n \t\t\tswitch (lexer.current.content) {\n \t\t\t\tcase \"class\"\t\t: \n \t\t\t\tcase \"function\"\t \t: \n \t\t\t\tcase \"structure\"\t:\n \t\t\t\tcase \"constant\" \t:\n \t\t\t\tcase \"variable\" \t:\n \t\t\t\tcase \"array\"\t\t: \treturn lexer.current.content;\t\n \t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\tdefault\t\t\t\t:\treturn lexer.lookAhead().content;\n \t\t\t}\n\t\t}\n\n// \t\tDeclaration\t:= {Class | Function | VarDecl | Statement} \n\t\tfunction Declaration() {\n\t\t\tswitch (whatNext()) {\n \t\t\t\t\t\n \t\t\t\t\tcase \"class\"\t: return Class();\n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"function\" : return Function();\n \t\t\t\t\tbreak;\n \t\t\t\t\n \t\t\t\t\tcase \"structure\" : return StructDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"array\"\t: return ArrayDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\n \t\t\t\t\tcase \"constant\" :\n \t\t\t\t\tcase \"variable\" : return VarDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault\t\t\t: return false;\n \t\t\t }\n\t\t}\n\n// \t\tProgram\t:= {Class | Function | VarDecl | Structure | Array | Statement} \n//\t\tAST: \"program\": l: {\"function\" | \"variable\" ... | Statement} indexed from 0...x\n\t\tthis.Program=function() {return Program()};\n \t\tfunction Program() {\n \t\t\tdebugMsg(\"ProgramParser : Program\");\n \t\t\tvar current;\n \t\t\tvar ast=new ASTListNode(\"program\");\n \t\t\t\n \t\t\tfor (;!eof();) {\n \t\t\t\t\n \t\t\t\tif (!(current=Declaration())) current=Statement();\n \t\t\t\t\n \t\t\t\tif (!current) break;\n \t\t\t\t\n \t\t\t\tast.add(current);\t\n \t\t\t} \t\t\t\n \t\t\treturn ast;\n \t\t}\n \t\t\n //\t\tClass:= \"class\" Ident [\"extends\" Ident] \"{\" [\"constructor\" \"(\" Ident Ident \")\"] CodeBlock {VarDecl | Function}\"}\"\n//\t\tAST: \"class\" : l: name:Identifier,extends: ( undefined | Identifier),fields:VarDecl[0..i], methods:Function[0...i]\n\t\tfunction Class() {\n\t\t\tdebugMsg(\"ProgramParser : Class\");\n\t\t\tlexer.next();\n\n\t\t\tvar name=Ident(true);\t\t\t\n\t\t\t\n\t\t\tvar extend={\"content\":undefined};\n\t\t\tif(test(\"extends\")) {\n\t\t\t\tlexer.next();\n\t\t\t\textend=Ident(true);\n\t\t\t}\n\t\t\t\n\t\t\tcheck (\"{\");\n\t\t\tvar scope=symbolTable.openScope();\n\t\t\t\n\t\t\tvar methods=[];\n\t\t\tvar fields=[];\n\t\t\t\n\t\t\tif (test(\"constructor\")) {\n\t\t\t\tlexer.next();\n\t\t \t\t//var retType={\"type\":\"ident\",\"content\":\"_$any\",\"line\":lexer.current.line,\"column\":lexer.current.column};\n\t\t\t\tvar constructName={\"type\":\"ident\",\"content\":\"construct\",\"line\":lexer.current.line,\"column\":lexer.current.column};\n\t\t\t\tmethods.push(FunctionBody(name,constructName));\n\t\t\t}\n\t\t\t\n\t\t\tvar current=true;\n\t\t\twhile(!test(\"}\") && current && !eof()) {\n\t\t\t\t \t\n\t\t \tswitch (whatNext()) {\n \t\t\t\t\t\n \t\t\t\t\tcase \"function\"\t: methods.push(Function()); \n \t\t\t\t\tbreak;\n \t\t\t\t\t\n \t\t\t\t\tcase \"constant\":\n \t\t\t\t\tcase \"variable\" : fields.push(VarDecl(true));\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault\t\t\t: current=false;\n \t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tcheck(\"}\");\n\t\t\t\n\t\t\tmode.terminatorOff();\n\n\t\t\tsymbolTable.closeScope();\n\t\t\tsymbolTable.addClass(name.content,extend.content,scope);\n\t\t\t\n\t\t\treturn new ASTUnaryNode(\"class\",{\"name\":name,\"extends\":extend,\"scope\":scope,\"methods\":methods,\"fields\":fields});\n\t\t}\n\t\t\n //\t\tStructDecl := \"structure\" Ident \"{\" VarDecl {VarDecl} \"}\"\n //\t\tAST: \"structure\" : l: \"name\":Ident, \"decl\":[VarDecl], \"scope\":symbolTable\n \t\tfunction StructDecl() {\n \t\t\tdebugMsg(\"ProgramParser : StructDecl\");\n \t\t\t\n \t\t\tlexer.next(); \n \t\t\t\n \t\t\tvar name=Ident(true); \n \t\t\t\n \t\t\tcheck(\"{\");\n \t\t\tmode.terminatorOn();\n \t\t\t\n \t\t\tvar decl=[];\n \t\t\t\n \t\t\tvar scope=symbolTable.openScope();\t\n \t\t\tdo {\t\t\t\t\n \t\t\t\tdecl.push(VarDecl(true));\n \t\t\t} while(!test(\"}\") && !eof());\n \t\t\t\n \t\t\tmode.terminatorOff();\n \t\t\tcheck (\"}\");\n \t\t\t\n \t\t\tsymbolTable.closeScope();\n \t\t\tsymbolTable.addStruct(name.content,scope);\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"structure\",{\"name\":name,\"decl\":decl,\"scope\":scope});\n \t\t} \n \t\t\n //\tarrayDecl := \"array\" Ident \"[\"Ident\"]\" \"contains\" Ident\n //\t\tAST: \"array\" : l: \"name\":Ident, \"elemType\":Ident, \"indexTypes\":[Ident]\n \t\tfunction ArrayDecl() {\n \t\t\tdebugMsg(\"ProgramParser : ArrayDecl\");\n \t\t\t\n \t\t\tlexer.next(); \n \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\t\n \t\t\tcheck(\"[\");\n \t\t\t\t\n \t\t\tvar ident=Ident(!mode.any);\n \t\t\tif (!ident) ident=lexer.anyLiteral();\n \t\t\t\t\n \t\t\tvar indexType=ident;\n \t\t\t\t\n \t\t\tvar bound=ident.content;\n \t\t\t\t\n \t\t\tcheck(\"]\");\n \t\t\t\t\n \t\t\tvar elemType; \t\n \t\t\tif (mode.any) {\n \t\t\t\tif (test(\"contains\")) {\n \t\t\t\t\tlexer.next();\n \t\t\t\t\telemType=Ident(true);\n \t\t\t\t}\n \t\t\t\telse elemType=lexer.anyLiteral();\n \t\t\t} else {\n \t\t\t\tcheck(\"contains\");\n \t\t\t\telemType=Ident(true);\n \t\t\t}\n \t\t\t\n \t\t\tcheck (\";\");\n \t\t\tsymbolTable.addArray(name.content,elemType.content,bound);\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"array\",{\"name\":name,\"elemType\":elemType,\"indexType\":indexType});\n \t\t} \n \t\t\n//\t\tFunction := Ident \"function\" Ident \"(\" [Ident Ident {\"[\"\"]\"} {\",\" Ident Ident {\"[\"\"]\"}) } \")\" CodeBlock\n//\t\tAST: \"function\":\tl: returnType: (Ident | \"_$\"), name:name, scope:SymbolTable, param:{name:Ident,type:Ident}0..x, code:CodeBlock \n\t\tthis.Function=function() {return Function();}\n \t\tfunction Function() {\n \t\t\tdebugMsg(\"ProgramParser : Function\");\n \t\t\n \t\t\tvar retType;\n \t\t\tif (mode.decl) retType=Ident(!(mode.any));\n \t\t\tif (!retType) retType=lexer.anyLiteral();\n \t\t\t\n \t\t\tcheck(\"function\");\n \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\t\n \t\t\treturn FunctionBody(retType,name);\n \t\t}\n \t\t\n \n \t\t// The Body of a function, so it is consistent with constructor\n \t\tfunction FunctionBody(retType,name)\t{\n \t\t\tvar scope=symbolTable.openScope();\n \t\t\t\n \t\t\tif (!test(\"(\")) error.expected(\"(\");\n \t\t\n var paramList=[];\n var paramType=[];\n var paramExpected=false; //Indicates wether a parameter is expected (false in the first loop, then true)\n do {\n \t\t\tlexer.next();\n \t\t\t\n \t\t\t/* Parameter */\n \t\t\tvar pName,type;\n \t\t\tvar ident=Ident(paramExpected);\t// Get an Identifier\n \t\t\tparamExpected= true;\n \t\t\t\n \t\t\t// An Identifier is found\n \t\t\tif (ident) {\n \t\t\t\t\n \t\t\t\t// When declaration is possible\n \t\t\t\tif (mode.decl) {\n \t\t\t\t\t\n \t\t\t\t\t// One Identifier found ==> No Type specified ==> indent specifies Param Name\n \t\t\t\t\tif (!(pName=Ident(!(mode.any)))) {\n \t\t\t\t\t\ttype=lexer.anyLiteral();\n \t\t\t\t\t\tpName=ident;\n \t\t\t\t\t} else type=ident; // 2 Identifier found\n \t\t\t\t} else {\t// Declaration not possible\n \t\t\t\t\ttype=lexer.anyLiteral();\n \t\t\t\t\tpName=ident;\n \t\t\t\t}\t\n\n\t\t\t\t\t// Store Parameter\n\t\t\t\t\tparamType.push(type); \n \t\tparamList.push({\"name\":pName,\"type\":type});\n \t\t \n \t\t \tsymbolTable.addVar(pName.content,type.content);\n \t\t} \n \t\t} while (test(\",\") && !eof());\n\n \tcheck(\")\");\n \t\t\t \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tsymbolTable.closeScope();\n \t\t\t\n \t\t\tsymbolTable.addFunction(name.content,retType.content,paramType);\n \t\t\treturn new ASTUnaryNode(\"function\",{\"name\":name,\"scope\":scope,\"param\":paramList,\"returnType\":retType,\"code\":code});\n \t\t}\n \t\t\t\n\t\t\n //\t\tVarDecl := Ident (\"variable\" | \"constant\") Ident [\"=\" Expr] \";\" \n //\t\tAST: \"variable\"|\"constant\": l : type:type, name:name, expr:[expr]\n \t\tthis.VarDecl = function() {return VarDecl();}\n \t\tfunction VarDecl(noInit) {\n \t\t\tdebugMsg(\"ProgramParser : VariableDeclaration\");\n \t\t\tvar line=lexer.current.line;\n \t\t\tvar type=Ident(!mode.any);\n \t\t\tif (!type) type=lexer.anyLiteral();\n \t\t\t\n \t\t\tvar constant=false;\n \t\t\tvar nodeName=\"variable\";\n \t\t\tif (test(\"constant\")) {\n \t\t\t\tconstant=true; \n \t\t\t\tnodeName=\"constant\";\n \t\t\t\tlexer.next();\n \t\t\t}\n \t\t\telse check(\"variable\"); \n \t\t\t \t\t\t\n \t\t\tvar name=Ident(true);\n \t\t\tsymbolTable.addVar(name.content,type.content,constant);\n\n\t\t\tvar expr=null;\n\t\t\tif(noInit==undefined){\n\t\t\t\tif (test(\"=\")) {\n\t\t\t\t\tlexer.next();\n\t\t\t\t\texpr=Expr();\n\t\t\t\t\tif (!expr) expr=null;\n\t\t\t\t}\n\t\t\t} \n\t\n\t\t\tcheck(\";\");\n\t\t\tvar ast=new ASTUnaryNode(nodeName,{\"type\":type,\"name\":name,\"expr\":expr});\n\t\t\tast.line=line;\n\t\t\treturn ast;\n \t\t}\n \t\t\t\t\n//\t\tCodeBlock := \"{\" {VarDecl | Statement} \"}\" \n//\t\tCodeblock can take a newSymbolTable as argument, this is needed for functions that they can create an scope\n//\t\tcontaining the parameters.\n//\t\tIf newSymbolTable is not specified it will be generated automatical\n// At the End of Codeblock the scope newSymbolTable will be closed again\t\t\n//\t\tAST: \"codeBlock\" : l: \"scope\":symbolTable,\"code\": code:[0..x] {code}\n \t\tfunction CodeBlock() {\n \t\t\tdebugMsg(\"ProgramParser : CodeBlock\");\n\t\t\t\n\t\t\tvar scope=symbolTable.openScope();\n\t\t\tvar begin=lexer.current.line;\n\t\t\tcheck(\"{\");\n \t\t\t\n \t\t\tvar code=[];\n \t\t\tvar current;\n\n \t\t\twhile(!test(\"}\") && !eof()) {\n \t\t\t\tswitch (whatNext()) {\n \t\t\t\t\tcase \"constant\":\n \t\t\t\t\tcase \"variable\": current=VarDecl();\n \t\t\t\t\tbreak;\n \t\t\t\t\tdefault: current=Statement();\t\t\t\t\t\n \t\t\t\t}\n\n \t\t\t\tif(current) {\n \t\t\t\t\tcode.push(current);\n \t\t\t\t} else {\n \t\t\t\t\terror.expected(\"VarDecl or Statement\"); break;\n \t\t\t\t}\n \t\t\t}\t\n \t\t\t\n \t\t\tvar end=lexer.current.line;\n \t\t\tcheck(\"}\");\n \t\t\tsymbolTable.closeScope();\n \t\t\treturn new ASTUnaryNode(\"codeBlock\",{\"scope\":scope,\"code\":code,\"begin\":begin,\"end\":end});\n \t\t}\n \t\t\n//\t\tStatement\t:= If | For | Do | While | Switch | JavaScript | (Return | Expr | Assignment) \";\"\n \t\tfunction Statement() {\n \t\t\tdebugMsg(\"ProgramParser : Statement\");\n \t\t\tvar ast;\n \t\t\tvar line=lexer.current.line;\n \t\t\t\n \t\t\tswitch (lexer.current.content) {\n \t\t\t\tcase \"if\"\t \t\t: ast=If(); \n\t \t\t\tbreak;\n \t\t\t\tcase \"do\"\t \t\t: ast=Do(); \n \t\t\t\tbreak;\n \t\t\t\tcase \"while\" \t\t: ast=While(); \t\t\n \t\t\t\tbreak;\n \t\t\t\tcase \"for\"\t\t\t: ast=For();\n \t\t\t\tbreak;\n \t\t\t\tcase \"switch\"\t\t: ast=Switch(); \t\n \t\t\t\tbreak;\n \t\t\t\tcase \"javascript\"\t: ast=JavaScript(); \n \t\t\t\tbreak;\n \t\t\t\tcase \"return\"\t\t: ast=Return(); \n \t\t\t\t\t\t\t\t\t\t check(\";\");\n \t\t\t\tbreak;\n \t\t\t\tdefault\t\t\t\t: ast=EPStatement(); \n \t\t\t\t\t check(\";\");\n \t\t\t}\n \t\t\tast.line=line;\n \t\t\tast.comment=lexer.getComment();\n \t\t\tlexer.clearComment(); \t\t\t\n \t\t\treturn ast;\t\n \t\t}\n \t\t\n//\t\tIf := \"if\" \"(\" Expr \")\" CodeBlock [\"else\" CodeBlock]\n//\t\tAST : \"if\": l: cond:Expr, code:codeBlock, elseBlock:(null | codeBlock)\n \t\tfunction If() {\n \t\t\tdebugMsg(\"ProgramParser : If\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tvar elseCode;\n \t\t\tif (test(\"else\")) {\n \t\t\t\tlexer.next();\n \t\t\t\telseCode=CodeBlock();\n \t\t\t}\n \t\t\treturn new ASTUnaryNode(\"if\",{\"cond\":expr,\"code\":code,\"elseBlock\":elseCode});\n \t\t}\n \t\t\n// \t\tDo := \"do\" CodeBlock \"while\" \"(\" Expr \")\" \n//\t\tAST: \"do\": l:Expr, r:CodeBlock \n \t\tfunction Do() {\t\n \t\t\tdebugMsg(\"ProgramParser : Do\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\tcheck(\"while\");\n \t\t\t\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\t\n \t\t\tcheck(\";\");\n\n \t\t\treturn new ASTBinaryNode(\"do\",expr,code);\n \t\t}\n \t\t\n// \t\tWhile := \"while\" \"(\" Expr \")\" \"{\" {Statement} \"}\" \n//\t\tAST: \"while\": l:Expr, r:codeBlock\n \t\tfunction While(){ \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : While\");\n \t\t\t\n \t\t\t//if do is allowed, but while isn't allowed gotta check keyword in parser\n \t\t\tif (preventWhile) error.reservedWord(\"while\",lexer.current.line);\n \t\t\t\n \t\t\tlexer.next();\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tvar code = CodeBlock();\n \t\t\t\t \t\t\t\n \t\t\treturn new ASTBinaryNode(\"while\",expr,code);\n \t\t}\n \t\t\n//\t\tFor := \"for\" \"(\"(\"each\" Ident \"in\" Ident | Ident Assignment \";\" Expr \";\" Assignment )\")\"CodeBlock\n//\t\tAST: \"foreach\": l: elem:Ident, array:Ident, code:CodeBlock \n//\t\tAST: \"for\": l: init:Assignment, cond:Expr,inc:Assignment, code:CodeBlock\n \t\tfunction For() { \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : For\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tcheck(\"(\");\n \t\t\t\n \t\t\tif (test(\"each\")) {\n \t\t\t\tlexer.next();\n \t\t\t\tvar elem=IdentSequence();\n \t\t\t\tcheck(\"in\");\n \t\t\t\tvar arr=IdentSequence();\n \t\t\t\t\n \t\t\t\tcheck(\")\");\n \t\t\t\t\n \t\t\t\tvar code=CodeBlock();\n \t\t\t\t\n \t\t\t\treturn new ASTUnaryNode(\"foreach\",{\"elem\":elem,\"array\":arr,\"code\":code});\n \t\t\t\t\n \t\t\t} else {\n \t\t\t\tvar init=Assignment();\n \t\t\t\tif (!init) error.assignmentExpected();\n \t\t\t\t\n \t\t\t\tcheck(\";\");\n \t\t\t\t\n \t\t\t\tvar cond=Expr();\n \t\t\t\n \t\t\t\n \t\t\t\tcheck(\";\");\n \t\t\t\n \t\t\t\tvar increment=Assignment();\n \t\t\t\tif (!increment) error.assignmentExpected();\n \t\t\t \n \t\t\t\tcheck(\")\");\n \t\t\t\tvar code=CodeBlock();\t\n \t\t\t\n \t\t\t\treturn new ASTUnaryNode(\"for\",{\"init\":init,\"cond\":cond,\"inc\":increment,\"code\":code});\n \t\t\t}\t\n \t\t}\n \t\t\n//\t\tSwitch := \"switch\" \"(\" Ident \")\" \"{\" {Option} [\"default\" \":\" CodeBlock] \"}\"\t\n// AST: \"switch\" : l \"ident\":IdentSequence,option:[0..x]{Option}, default:CodeBlock\n \t\tfunction Switch() {\t\t\t\n \t\t\tdebugMsg(\"ProgramParser : Switch\");\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tcheck(\"(\");\n\n \t\t\tvar ident=IdentSequence();\n \t\t\tif (!ident) error.identifierExpected();\n \t\t\t\n \t\t\tcheck(\")\");\n \t\t\t\n \t\t\tcheck(\"{\");\n \t\t\t\n \t\t\tvar option=[];\n \t\t\tvar current=true;\n \t\t\tfor (var i=0;current && !eof();i++) {\n \t\t\t\tcurrent=Option();\n \t\t\t\tif (current) {\n \t\t\t\t\toption[i]=current;\n \t\t\t\t}\n \t\t\t}\n \t\t\tcheck(\"default\");\n \t\t\t\n \t\t\tcheck(\":\");\n \t\t\t\n \t\t\tvar defBlock=CodeBlock();\n \t\t \t\t\t\n \t\t\tcheck(\"}\");\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"switch\", {\"ident\":ident,\"option\":option,\"defBlock\":defBlock});\n \t\t}\n \t\t\n//\t\tOption := \"case\" Expr {\",\" Expr} \":\" CodeBlock\n// AST: \"case\" : l: [0..x]{Expr}, r:CodeBlock\n \t\tfunction Option() {\n \t\t\tif (!test(\"case\")) return false;\n \t\t\t\n \t\t\tdebugMsg(\"ProgramParser : Option\");\n \t\t\t\n \t\t\tvar exprList=[];\n \t\t\tvar i=0;\n \t\t\tdo {\n \t\t\t\tlexer.next();\n \t\t\t\t\n \t\t\t\texprList[i]=Expr();\n \t\t\t\ti++; \n \t\t\t\t\n \t\t\t} while (test(\",\") && !eof());\n \t\t\t\n \t\t\tcheck(\":\");\n \t\t\t\n \t\t\tvar code=CodeBlock();\n \t\t\t\n \t\t\treturn new ASTBinaryNode(\"case\",exprList,code);\n \t\t}\n \t\t\n// JavaScript := \"javascript\" {Letter | Digit | Symbol} \"javascript\"\n//\t\tAST: \"javascript\": l: String(JavascriptCode)\n \t\tfunction JavaScript() {\n \t\t\tdebugMsg(\"ProgramParser : JavaScript\");\n\t\t\tcheck(\"javascript\");\n\t\t\tcheck(\"(\")\n\t\t\tvar param=[];\n\t\t\tvar p=Ident(false);\n\t\t\tif (p) {\n\t\t\t\tparam.push(p)\n\t\t\t\twhile (test(\",\") && !eof()) {\n\t\t\t\t\tlexer.next();\n\t\t\t\t\tparam.push(Ident(true));\n\t\t\t\t}\t\n\t\t\t}\n \t\t\tcheck(\")\");\n \t\t\t\t\t\n \t\t\tvar js=lexer.current.content;\n \t\t\tcheckType(\"javascript\");\n \t\t\t\t\t\t\n \t\t\treturn new ASTUnaryNode(\"javascript\",{\"param\":param,\"js\":js});\n \t\t}\n \t\t\n// \t\tReturn := \"return\" [Expr] \n//\t\tAST: \"return\" : [\"expr\": Expr] \n \t\tfunction Return() {\n \t\t\tdebugMsg(\"ProgramParser : Return\");\n \t\t\tvar line=lexer.current.line;\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\tvar ast=new ASTUnaryNode(\"return\",expr);\n \t\t\tast.line=line;\n \t\t\treturn ast;\n \t\t}\n\t}", "enterExplicitConstructorInvocation(ctx) {\n\t}", "function createStatement1( machine )\n {\n machine.checkToken(\")\");\n columns = machine.popToken();\n machine.checkToken(\"(\");\n alias = machine.popToken().identifier;\n machine.checkToken(\"table\");\n machine.checkToken(\"create\");\n machine.pushToken( new createStatement( constructor_table, alias, columns ) );\n }", "enterConstructorInvocation(ctx) {\n\t}", "visitCursor_declaration(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "function parse_StatementList(){\n\t\n\n\t\n\n\tvar tempDesc = tokenstreamCOPY[parseCounter][0]; //check desc of token\n\tvar tempType = tokenstreamCOPY[parseCounter][1]; //check type of token\n\n\tif (tempDesc == ' print' || tempType == 'identifier' || tempType == 'type' || tempDesc == ' while' || tempDesc == ' if' || tempDesc == '{' ){ //if next token is a statment\n\t\tdocument.getElementById(\"tree\").value += \"PARSER: parse_StatementList()\" + '\\n';\n\t\tCSTREE.addNode('StatementList', 'branch');\n\t\t\n\t\t\n\t\tparse_Statement(); \n\t\n\t\tparse_StatementList();\n\t\t\n\t\tCSTREE.endChildren();\n\t\n\t\t\n\t\t\n\t}\n\telse{\n\t\t\n\t\t\n\t\t//e production\n\t}\n\n\n\n\n\t\n\t\n}", "function STLangVisitor() {\n STLangParserVisitor.call(this);\n this.result = {\n \"valid\": true,\n \"error\": null,\n \"tree\": {\n \"text\": \"\",\n \"children\": null\n }\n };\n\treturn this;\n}", "visitPragma_declaration(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "constructor(declarationScope) {\n this.declarationScope = declarationScope;\n }", "declarations() {\n let declarationList = [];\n // starts with a var followed by bunch of var declarations\n if (this.currentToken.type === tokens.VAR) {\n this.eat(tokens.VAR);\n while (this.currentToken.type === tokens.ID) {\n declarationList = [...declarationList, ...this.variableDeclaration()];\n this.eat(tokens.semi);\n }\n }\n\n while (this.currentToken.type === \"PROCEDURE\") {\n this.eat(tokens.PROCEDURE);\n const procName = this.currentToken.name;\n this.eat(tokens.ID);\n this.eat(tokens.semi);\n const blockNode = this.block();\n const procDecl = new ProcedureDecl(procName, blockNode);\n declarationList.push(procDecl);\n this.eat(tokens.semi);\n }\n return declarationList;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes the current shape from the grid. same deal but reverse
function removeShape() { for (var row = 0; row < currentShape.shape.length; row++) { for (var col = 0; col < currentShape.shape[row].length; col++) { if (currentShape.shape[row][col] !== 0) { grid[currentShape.y + row][currentShape.x + col] = 0; } } } }
[ "clearGrid() {\n for (let row = 0; row < this.N; row++) {\n for (let column = 0; column < this.N; column++) {\n this.grid[row][column].element.remove();\n }\n }\n this.grid = null;\n\n this.width = 0;\n this.height = 0;\n this.N = 0;\n\n this.startTile = null;\n this.endTile = null;\n }", "delete() {\n this.deltaX = 0;\n this.deltaY = +5;\n // if bubble currently on the board, remove it\n if (this.row !== undefined && this.col !== undefined) {\n let row = this.board.pieces[this.row];\n let col = this.col;\n row[col] = null;\n }\n this.falling = true;\n this.collided = false;\n this.canvas.objects.push(this);\n }", "function removeGrid() {\n const container = document.querySelector('#sketch-container');\n while (container.firstChild) {\n container.removeChild(container.lastChild);\n }\n\n }", "deleteGrid() {\n this.gridArray.length = 0; // deleting the grid array\n let child = this.gridDOM.lastElementChild;\n\n // deleting all the squares from the grid\n while(child) {\n this.gridDOM.removeChild(child);\n child = this.gridDOM.lastElementChild;\n }\n }", "function lineClear() {\n\tlet countClearLines = 0;\n\tlet line = 0;\n\tlet lineCount = grid[0].length - 2;\n\tfor (let i = 0; i < grid.length; i++) {\n\t\tfor (let j = 0; j < grid.length; j++) {\n\t\t\tif (grid[j][lineCount] === true) line++;\n\t\t}\n\t\tif (line === grid.length) {\n\t\t\tcountClearLines++;\n\t\t\tctx.clearRect(\n\t\t\t\t0,\n\t\t\t\t(bottom - 1 - i) * squareDimensions,\n\t\t\t\tsquareDimensions * 20,\n\t\t\t\tsquareDimensions\n\t\t\t);\n\t\t\tclearPlacement(lineCount);\n\t\t\tmoveDown((lineCount - 1) * squareDimensions);\n\t\t\tlineCount++;\n\t\t}\n\t\tlineCount--;\n\t\tline = 0;\n\t}\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 clearGrid() {\n initializeColorGrid();\n draw();\n }", "function removeDim() {\r\n\r\n var gO = NewGridObj; // currently configured grid\r\n\r\n gO.numDims--;\r\n if (gO.numDims == 1) gO.multiCol = 0; //MPI: bug fix\r\n gO.dimTitles.pop();\r\n gO.dimComments.pop();\r\n gO.dimIsExtended.pop(); //MPI:\r\n\r\n // Note. Not updating other variables because they are not visible\r\n //\r\n reDrawConfig(); // redraw with updates\r\n}", "function clearAndRedraw() {\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n\n for (let i = 0; i < shapes.length; i++) {\n shape = shapes[i];\n\n if (shape.r) {\n ctx.beginPath();\n ctx.strokeStyle = \"black\";\n ctx.lineWidth = 2;\n ctx.fillStyle = shape.color;\n ctx.arc(shape.x, shape.y, Math.abs(shape.r), 0, 2 * Math.PI);\n ctx.fill();\n ctx.stroke();\n } else if (shape.w) {\n drawRectangleBorder(shape.x, shape.y, shape.w, shape.h);\n\n ctx.fillStyle = shape.color;\n ctx.beginPath();\n ctx.rect(shape.x, shape.y, shape.w, shape.h);\n ctx.fill()\n } else {\n ctx.beginPath();\n ctx.lineWidth = 3;\n ctx.strokeStyle = shape.color;\n ctx.moveTo(shape.x, shape.y);\n ctx.lineTo(shape.lx, shape.ly);\n ctx.stroke();\n }\n }\n }", "function clearCanvas() {\n elements.gridCanvas.innerHTML = '';\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 }", "eraseRectangularSelection() {\n // infer 4 corners of the rectangle based on the two points that have been drawn\n this.clearHighlights();\n d3.selectAll('#grid .point-path').remove();\n\n const payload = {\n points: [\n this.points[0],\n { x: this.points[1].x, y: this.points[0].y },\n this.points[1],\n { x: this.points[0].x, y: this.points[1].y },\n ],\n };\n\n this.$store.dispatch('geometry/eraseSelection', payload);\n\n // clear points from the grid\n this.points = [];\n }", "removeFigure(figure){\n\t\tthis.boardMatrix[figure.positionY][figure.positionX].sprite.destroy();\n\t\tthis.boardMatrix[figure.positionY][figure.positionX].figure = null;\n\t\tfigure.isAlive = false;\n\t}", "function removeExprAndGridHighlight() {\r\n\r\n var sO = CurStepObj;\r\n\r\n // get active child expression\r\n //\r\n var expr = getActiveExprObj(sO);\r\n\r\n if (expr) {\r\n\r\n var gO = expr.gO;\r\n\r\n // if the grid is highlighted\r\n //\r\n var need_grid_refresh = (expr.isGridCell() &&\r\n (gO.hasSelection || (gO.selIndDim >= 0)));\r\n\r\n if (need_grid_refresh || expr.isRange()) {\r\n\r\n\t gO.hasSelection = false; // no highlihged cell in grid\r\n\t gO.selIndDim = INVID; // no higlighted indices in any dim\r\n\r\n var iO = getIndObjOfHtmlId(gO.htmlId);\r\n\r\n\t drawGrid(gO, iO, gO.htmlId, false);\t\r\n\t //\r\n\t sO.activeParentExpr = null; // remove expression\r\n\t sO.activeParentPath = \"\"; // no active expression/space\r\n\t sO.activeChildPos = INVID; // remove sub expression Id\r\n\t}\r\n\r\n\r\n }\r\n\r\n // Remove any number that is actively being entered\r\n //\r\n resetOnInput();\r\n}", "function clearParticle(particle) {\n var locationToRemove = particle.locations.shift();\n ctx.fillStyle = \"#FFFFFF\";\n ctx.fillRect(locationToRemove.x * (width / rows), locationToRemove.y * (height / rows), width / rows, height / rows);\n}", "function clearGrid() {\n const mainDiv = document.getElementById('canvas');\n mainDiv.innerHTML = '';\n}", "function reset() {\n svg_g.selectAll(\".brush\").call(brush.move, null);\n svg_g.selectAll(\".brushMain\").call(brush.move, null);\n }", "function disable_draw() {\n drawing_tools.setShape(null);\n}", "remove () {\r\n // unclip all targets\r\n this.targets().forEach(function (el) {\r\n el.unclip();\r\n });\r\n\r\n // remove clipPath from parent\r\n return super.remove()\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Higherlevel mouse helper function to specifically map mouse coordinates into the coordinates on a canvas that appear under it. This depends on the details of how a canvas gets scaled by CSS.
function canvas_mouse_coords(event, element) { var rcoords = relative_mouse_coords(event, element); // Assume that the CSS object-fit property is "fill" (the default). var xscale = element.width / element.offsetWidth; var yscale = element.height / element.offsetHeight; return {x: rcoords.x * xscale, y: rcoords.y * yscale} }
[ "function adjustMouseCoords() {\n\t// adjust for zoom\n\txMouse /= zoomFactor;\n\tyMouse /= zoomFactor;\n\t// adjust for pan\n\t// first get viewBox info\n\tvar vBox = canvas.getAttribute(\"viewBox\").split(\" \");\n\tvar vBoxX = parseFloat(vBox[0]);\n\tvar vBoxY = parseFloat(vBox[1]);\n\tvar vBoxW = parseFloat(vBox[2]);\n\tvar vBoxH = parseFloat(vBox[3]);\n\t// then add the resulting offset\n\txMouse += vBoxX;\n\tyMouse += vBoxY;\n}", "function calcMouseCoords() {\n var xMid = canvasW / 2;\n var yMid = canvasH / 2;\n\n //var game0x = (xMid - camx * camzoom); (diff from 0x, then just scale mouse diff)\n gameMouseX = (rawMouseX - (xMid - camx * camzoom)) / camzoom; // + (rawMouseX)\n gameMouseY = (rawMouseY - (yMid - camy * camzoom)) / camzoom; //(rawMouseY) / camzoom;\n}", "function getRawCoords(e){\n \tvar mousePos = canvas.getBoundingClientRect();\n \tvar coords = {\n \t\tx : e.clientX - mousePos.left,\n \t\ty : e.clientY - mousePos.top\n \t}\n\n \treturn coords;\n }", "function get_relative_mouse_coordinates(event)\n{\n\tvar mouse_x, mouse_y;\n\n\tif(event.offsetX)\n\t{\n\t\tmouse_x = event.offsetX;\n\t\tmouse_y = event.offsetY;\n\t}\n\telse if(event.layerX)\n\t{\n\t\tmouse_x = event.layerX;\n\t\tmouse_y = event.layerY;\n\t}\n\n\treturn { x: mouse_x, y: mouse_y };\n}", "getPointerXY(e) {\n const boundingBox = this.getBoundingBox();\n let clientX = 0;\n let clientY = 0;\n if (e.clientX && e.clientY) {\n clientX = e.clientX;\n clientY = e.clientY;\n } else if (e.touches && e.touches.length > 0 && e.touches[0].clientX &&\n e.touches[0].clientY) {\n clientX = e.touches[0].clientX;\n clientY = e.touches[0].clientY;\n }\n\n //SVG scaling: usually not an issue.\n const sizeRatioX = 1;\n const sizeRatioY = 1;\n\n const inputX = (clientX - boundingBox.left) * sizeRatioX;\n const inputY = (clientY - boundingBox.top) * sizeRatioY;\n\n return { x: inputX, y: inputY };\n }", "function getPhysicsCoord(mouseEvent){\n var rect = canvas.getBoundingClientRect();\n var x = mouseEvent.clientX - rect.left;\n var y = mouseEvent.clientY - rect.top;\n\n x = (x - w / 2) / scaleX;\n y = (y - h / 2) / scaleY;\n\n return [x, y];\n}", "function mouseoverhandler(event) {\n mouseIn = event.target.id;\n //console.log(\"the mouse is over canvas:: \" + mouseIn);\n }", "function get_canvas_coords(event){\n var rect = $('#canvas')[0].getBoundingClientRect();\n var coords = event;\n if (event.originalEvent.touches && event.originalEvent.touches.length > 0) {\n // is a touch event: coords are elsewhere\n coords = event.originalEvent.touches[0];\n }\n return [coords.clientX - rect.left, coords.clientY - rect.top];\n}", "function updateMouse(e) {\n mouseX = e.pageX;\n mouseY = e.pageY;\n}", "function handleMouseDown(e) {\r\n // ctx.restore();\r\n e.preventDefault();\r\n mouseX = parseInt(e.clientX - offsetX);\r\n console.log(mouseX);\r\n mouseY = parseInt(e.clientY - offsetY);\r\n console.log(mouseY);\r\n\r\n // save drag-startXY, \r\n // move temp canvas over main canvas,\r\n // set dragging flag\r\n startX = mouseX;\r\n startY = mouseY;\r\n\r\n // ctxTemp.clearRect(0, 0, canvasTemp.width, canvasTemp.height);\r\n // $(\"#canvasTemp\").css({\r\n // left: 0,\r\n // top: 0\r\n // });\r\n isDown = true;\r\n}", "function mousePressed() {\n covid20.x = mouseX;\n covid20.y = mouseY;\n}", "function findXY(event) {\n x = event.clientX;\n y = event.clientY;\n}", "function mouseApasat(ev) {\n x1 = my_canvasX(ev);\n y1 = my_canvasY(ev);\n m_apasat = true;\n \n}", "function setupCanvasMousing(c)\n{\n //add these vars to document\n document.mouseDiffX = 0;\n document.mouseDiffY = 0;\n document.oldMouseX = 0;\n document.oldMouseY = 0;\n document.down_object = null;\n document.hover_object = c;\n\n // Tell object c what to do when it hears a mouse down event\n c.mouseDownHandler = function(event)\n {\n var pos = document.getAbsolutePosition(this);\n // Not sure if this will work on Opera\n document.mouseDiffX = event.screenX - (event.pageX - pos.x); //pageX gives scroll\n document.mouseDiffY = event.screenY - (event.pageY - pos.y);\n document.oldMouseX = event.pageX - pos.x;\n document.oldMouseY = event.pageY - pos.y;\n this.shift_down = event.shiftKey;\n var mouse_pos = find_true_mouse(event, c);\n\n // Call object c's mouseDown(x,y) function\n if (this.mouseDown(mouse_pos.x, mouse_pos.y))\n {\n // If object c accepted the mouse then tell the document to:\n // disallow selection\n document.disableMouseSelection();\n // any mouse moves are now drags\n document.removeEventListener(\"mousemove\", document.mouseMoveHandler, false);\n document.addEventListener(\"mousemove\", document.mouseDragHandler, false);\n // any mouse ups should be handled specially\n document.addEventListener(\"mouseup\", document.mouseUpHandler, false);\n // tell the document who was clicked\n document.down_object = c;\n this.prev_mouse_pos = mouse_pos;\n }\n };\n\n // Tell the document how to handle drags\n document.mouseDragHandler = function(event)\n {\n //var realx = event.screenX - this.mouseDiffX;\n //var realy = event.screenY - this.mouseDiffY;\n if (this.down_object)\n {\n var mouse_pos = find_true_mouse(event, this.down_object);\n // tell the object that recieved the original click to drag\n this.down_object.mouseDrag(\n mouse_pos.x,\n mouse_pos.y,\n mouse_pos.x - this.down_object.prev_mouse_pos.x,\n mouse_pos.y - this.down_object.prev_mouse_pos.y);\n this.down_object.prev_mouse_pos = mouse_pos;\n }\n //this.oldMouseX = realx;\n //this.oldMouseY = realy;\n };\n\n document.mouseMoveHandler = function(event)\n {\n if (this.hover_object)\n {\n //var pos = document.getAbsolutePosition(this.hover_object);\n var mouse_pos = find_true_mouse(event, this.hover_object);\n\n this.shift_down = event.shiftKey;\n\n this.hover_object.mouseMove(\n mouse_pos.x,\n mouse_pos.y,\n 0, 0);\n }\n }\n\n // Tell the document how to handle the up event\n document.mouseUpHandler = function(event)\n {\n this.removeEventListener(\"mousemove\", this.mouseDragHandler, false);\n this.addEventListener(\"mousemove\", this.mouseMoveHandler, false);\n this.removeEventListener(\"mouseup\", this.mouseUpHandler, false);\n if (this.down_object)\n {\n this.down_object.mouseUp(\n event.screenX - this.mouseDiffX,\n event.screenY - this.mouseDiffY);\n }\n // reset down_object to null, so that any time this.down_object\n // contains null unless something's being dragged\n this.down_object = null;\n this.enableMouseSelection();\n };\n\n // Get the absolute position of a screen element\n // Input:\n // element screen element in question\n // Return:\n // (x,y) coordinates of top left corner of element\n document.getAbsolutePosition = function(element)\n {\n var r = {x: element.offsetLeft, y: element.offsetTop};\n if (element.offsetParent) {\n var tmp = this.getAbsolutePosition(element.offsetParent);\n r.x += tmp.x;\n r.y += tmp.y;\n }\n return r;\n };\n\n // Turn off selection\n document.disableMouseSelection = function()\n {\n this.onselectstart = function() {\n return false;\n };\n };\n\n // Turn on selection\n document.enableMouseSelection = function()\n {\n this.onselectstart = function() {\n return true;\n };\n };\n\n // Hook up c's mousedown event to the mouseDownHandler we just\n // defined\n c.addEventListener(\"mousedown\", c.mouseDownHandler, false);\n document.addEventListener(\"mousemove\", document.mouseMoveHandler, false);\n}", "function getWebGLCoordinates(event, target){\n\tconst pos = getNoPaddingNoBorderCanvasRelativeMousePosition(event, target);\n\n\t// pos is in pixel coordinates for the canvas.\n\t// so convert to WebGL clip space coordinates\n\treturn {\n\t\tx: pos.x / gl.canvas.width * 2 - 1,\n\t\ty: pos.y / gl.canvas.height * -2 + 1\n\t}\n}", "function handleCanvasEventProxy(evt) {\n\n\tif (evt.layerX || evt.layerY == 0) { // Firefox\n\t\tevt._x = evt.layerX - painterCanvas_.offsetLeft;\n\t\t// evt._y = evt.layerY - painterCanvas_.offsetTop;\n\t\tevt._y = evt.layerY;\n\t}\n\telse if (evt.offsetX || evt.offsetY == 0) { //Opera\n\t\tevt._x = evt.offsetX - painterCanvas_.offsetLeft;\n\t\tevt._y = evt.offsetY - painterCanvas_.offsetTop;\n\t}\n\n\t// dispatch to the current drawing method\n\tvar methodFunc = method[evt.type];\n\tif (methodFunc) {\n\t\tmethodFunc(evt);\n\t}\n\telse {\n\t\tconsole.log(\"No drawing method: \" + currentMethodType);\n\t}\n}", "function initMouse() {\r\n\tGame.mouse = Crafty.e(\"2D, Mouse\").attr({\r\n\t\tw : Game.width(),\r\n\t\th : Game.height(),\r\n\t\tx : 0,\r\n\t\ty : 0\r\n\t});\r\n\t//Everytime somewhere is clicked, this method is executed\r\n\tGame.mouse.bind('Click', function(e) {\r\n\t\t//Calculates the board field that is clicked, e.g Floor(157.231 / 70) = 2 \r\n\t\tGame.mousePos.x = Math.floor(Crafty.mousePos.x / Game.map_grid.tile.width);\r\n\t\tGame.mousePos.y = Math.floor(Crafty.mousePos.y / Game.map_grid.tile.width);\r\n\t\tconsole.log(Game.mousePos.x, Game.mousePos.y);\r\n\t\tconsole.log(\"x: \" + Crafty.mousePos.x + \" - y: \" + Crafty.mousePos.y);\r\n\r\n\t\t// CLick on a figure\r\n\t\tif ((Game.board[Game.mousePos.x][Game.mousePos.y].player == Game.playerTurn) && Game.turn\t//if the figure has the same color as the player who is next\r\n\t\t\t\t&& Game.board[Game.mousePos.x][Game.mousePos.y].type != 'Chip') { //and wether it is no \r\n\t\t\tif (Game.mousePos.x != Game.clicked.x || Game.mousePos.y != Game.clicked.y) { \r\n\t\t\t\tGame.setColor(Game.clicked.x, Game.clicked.y, false);\r\n\t\t\t}\r\n\t\t\t//Save the selected figure\r\n\t\t\tGame.clicked.x = Game.mousePos.x;\r\n\t\t\tGame.clicked.y = Game.mousePos.y\r\n\t\t\tGame.clicked.active = 'true';\r\n\r\n\t\t\tconsole.log(\"DEBUG> Clicked!!\");\r\n\t\t\tGame.setColor(Game.clicked.x, Game.clicked.y, true); //Highlight the figure in green\r\n\t\t} else if (Game.clicked.active == 'true' && Game.clicked.x == Game.mousePos.x \r\n\t\t\t\t&& Game.clicked.y == Game.mousePos.y) { //Click on the selceted figure again\r\n\t\t\tGame.setColor(Game.clicked.x, Game.clicked.y, false);\r\n\t\t\tGame.clicked.x = -1;\r\n\t\t\tGame.clicked.y = -1;\r\n\t\t\tGame.clicked.active = 'false';\r\n\r\n\t\t\t// Click on a field, make a turn\r\n\t\t} else if (Game.clicked.active == 'true' && Game.turn) {\r\n\t\t\tsend('{\"type\" : \"turn\", \"x\" : \"' + Game.mousePos.x + '\", \"y\" : \"' + Game.mousePos.y + '\", \"oldX\" : \"' + Game.clicked.x\r\n\t\t\t\t\t+ '\", \"oldY\" : \"' + Game.clicked.y + '\"}'); //send turn request to server\r\n\t\t} else {\r\n\t\t\ttoastr.warning('Du bist nicht dran!');\r\n\t\t}\r\n\t});\r\n\t\r\n\t//bind mouse to Crafty stage\r\n\t//Crafty.addEvent(Game.mouse, Crafty.stage.elem, \"mousedown\", Game.mouse.onMouseDown);\r\n}", "function save_mouse_position() {\n mouse_position_x = mouseX\n mouse_position_y = mouseY\n}", "offsetByCanvas(canvasTarget) {\n const offset = { x: 0, y: 0 };\n let i;\n for (i = 0; i < this.indexOfTarget(canvasTarget); i += 1) {\n offset.x += this.canvases[i].getWidth();\n }\n return offset;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Base your assertions from an existing CloudFormation template formatted as an inmemory JSON object.
static fromJSON(template, templateParsingOptions) { try { jsiiDeprecationWarnings.aws_cdk_lib_assertions_TemplateParsingOptions(templateParsingOptions); } catch (error) { if (process.env.JSII_DEBUG !== "1" && error.name === "DeprecationError") { Error.captureStackTrace(error, this.fromJSON); } throw error; } return new Template(template, templateParsingOptions); }
[ "ensureTestStructure(transaction) {\n transaction.test.request = transaction.request;\n transaction.test.expected = transaction.expected;\n transaction.test.actual = transaction.real;\n transaction.test.errors = transaction.errors;\n transaction.test.results = transaction.results;\n }", "templateMatches(expected) {\n const matcher = matcher_1.Matcher.isMatcher(expected) ? expected : match_1.Match.objectLike(expected);\n const result = matcher.test(this.template);\n if (result.hasFailed()) {\n throw new Error([\n 'Template did not match as expected. The following mismatches were found:',\n ...result.toHumanStrings().map(s => `\\t${s}`),\n ].join('\\n'));\n }\n }", "function fillTemplate(contractName, contractArgs) {\n return `'use strict'\nObject.defineProperty(exports, '__esModule', { value: true })\nconst contract = require('@truffle/contract')\nconst ${contractName} = contract(${JSON.stringify(contractArgs, null, 1)})\n\nif (process.env.NODE_ENV === 'test') {\n try {\n eval('${contractName}.setProvider(web3.currentProvider)')\n } catch (e) {}\n}\n\nexports.${contractName} = ${contractName}\n`;\n}", "function AssessmentTemplate(props) {\n return __assign({ Type: 'AWS::Inspector::AssessmentTemplate' }, props);\n }", "function run(json, template, testingMode) {\n if (!template) {\n console.log(\"Please provide a template EJS file for the Generator to use. \" + \"Load it via fs.readFileSync in Node or XHR in the browser.\");\n return null;\n }\n\n // `now` is actually now, unless we're running this for a test,\n // in which case it's always Jan 1, 2000 at 12PM UTC\n var now = testingMode ? new Date('2000-01-01T12:00:00Z') : new Date();\n\n var ccda = _.template(template, {\n filename: 'ccda.xml',\n bb: json,\n now: now,\n tagHelpers: ejs.helpers,\n codes: Core.Codes\n });\n return ccda;\n}", "function validateTemplate(template, schema){\n console.log(\"Validating template \" + templateFileName + \" against schema \" + schemaFileName + \" . . .\");\n //var validation = validate(templateFile, schema);\n var validator = new validate.Validator(schema);\n var check = validator.check(template);\n console.log(\"Validation: \" + check);\n}", "function Template(props) {\n return __assign({ Type: 'AWS::SES::Template' }, props);\n }", "function createVendorTemplate(bundle) {\n const sender_password = bundle.authData.sender_password;\n const sender_id = bundle.authData.sender_id;\n const temp_session_ID = bundle.authData.temp_session_ID;\n const timestamp = Date.now();\n\n const name = bundle.inputData.name;\n const printAs = bundle.inputData.printAs;\n const companyName = bundle.inputData.companyName;\n\n var jsonObj = {\n request: {\n control: {\n senderid: sender_id,\n password: sender_password,\n controlid: timestamp,\n uniqueid: false,\n dtdversion: '3.0',\n includewhitespace: false,\n },\n operation: {\n authentication: {\n sessionid: temp_session_ID,\n },\n content: {\n function: { $: {controlid: \"220c4620-ed4b-4213-bfbb-10353bb73b62\" },\n create: {\n vendor: {\n name: name\n },\n displayContact: {\n printAs: printAs,\n companyName: companyName,\n \n // Enter more fields for Vendor Information here\n }\n }\n }\n }\n }\n }\n };\n\n return jsonObj;\n}", "function template(dom, object) {\n\treturn dom.replace(/{(\\w+)}/g, function(_, k) {\n\t\treturn object[k];\n\t});\n}", "function _XjsonsProcessor() {\n\n\tthis.error = _.obj.extend(function(func) {\n\t\tthis.errorHandlers.add(func);\n\t},\n\t{\n\t\tobj: function(val) {return val + ' should be an object';},\n\t\tarr: function(val) {return val + ' should be an array';},\n\t\temb: function(val) {return val + ' should be an ' + (type || 'embedded');},\n\t\twtf: function() {return 'WTF error occured';}\n\t});\n\n\tthis.emitError = function(ptype, val, type) {\n\t\tthis.errorHandlers.exec([this.error[ptype](val, type)]);\n\t};\n\n\tthis.process = function() {\n\n\t\tvar _this = this;\n\n\t\t// shema - value rules\n\t\t// obj - obj with property which is shema for\n\n\t\tfunction process(shema, obj) {\n\n\t\t\tvar\tpropName = shema.inputProp || shema.outputProp,\n\t\t\t\tobjC = obj[propName],\n\t\t\t\totype = _.type(objC);\n\n\t\t\tif(shema.type === 'object') {\n\t\t\t\tif(otype.is('object')) {\n\t\t\t\t\tfor(var prop in shema.value) {\n\t\t\t\t\t\tif(shema.value.hasOwnProperty(prop)) {\n\t\t\t\t\t\t\tif(!process(shema.value[prop], objC)) {\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}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t_this.emitError('obj', obj);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(shema.type === 'obj-template') {\n\t\t\t\tif(!otype.is('object')) {\n\t\t\t\t\t_this.emitError('obj', obj);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tfor(var prop in obj) {\n\t\t\t\t\tif(obj.hasOwnProperty(prop)) {\n\t\t\t\t\t\tif(!process(shema.value[0], obj[prop])) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(shema.type === 'array') {\n\t\t\t\tif(!otype.is('array')) {\n\t\t\t\t\t_this.emitError('arr', obj);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tfor(var prop in shema.value) {\n\t\t\t\t\tif(shema.value.hasOwnProperty(prop)) {\n\t\t\t\t\t\tif(!process(shema.value[prop], obj[prop])) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(shema.type === 'arr-template') {\n\t\t\t\tif(!otype.is('array')) {\n\t\t\t\t\t_this.emitError('arr', obj);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tfor(var prop in obj) {\n\t\t\t\t\tif(obj.hasOwnProperty(prop)) {\n\t\t\t\t\t\tif(!process(shema.value[0], obj[prop])) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(shema.type === 'embedded') {\n\n\t\t\t\tvar toleranceFlag = true;\n\n\t\t\t\tif(shema.value === 'I') {\n\t\t\t\t\tobj = parseInt(obj);\n\t\t\t\t\tshema.value = i;\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 'F') {\n\t\t\t\t\tobj = parseFloat(obj);\n\t\t\t\t\tshema.value = f;\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 'D') {\n\t\t\t\t\tobj = +obj;\n\t\t\t\t\tshema.value = d;\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 'B') {\n\t\t\t\t\tobj = !!obj;\n\t\t\t\t\tshema.value = b;\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 'U') {\n\t\t\t\t\tobj = undefined;\n\t\t\t\t\tshema.value = u;\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 'S') {\n\t\t\t\t\tobj += '';\n\t\t\t\t\tshema.value = s;\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 'N') {\n\t\t\t\t\tobj = null;\n\t\t\t\t\tshema.value = n;\n\t\t\t\t}\n\n\t\t\t\tif(shema.value === 'i') {\n\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 'f') {\n\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 'd') {\n\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 'b') {\n\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 'u') {\n\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 's') {\n\n\t\t\t\t}\n\t\t\t\telse if(shema.value === 'n') {\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t\telse {\n\t\t\t\t_this.error.wtf();\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\treturn process(this.xjsons, this.target, true);\n\t};\n\n}", "static fromStack(stack, templateParsingOptions) {\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_Stack(stack);\n jsiiDeprecationWarnings.aws_cdk_lib_assertions_TemplateParsingOptions(templateParsingOptions);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, this.fromStack);\n }\n throw error;\n }\n return new Template(toTemplate(stack), templateParsingOptions);\n }", "function cfnVirtualGatewayJsonFormatRefPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_JsonFormatRefPropertyValidator(properties).assertSuccess();\n return {\n Key: cdk.stringToCloudFormation(properties.key),\n Value: cdk.stringToCloudFormation(properties.value),\n };\n}", "_getPatchBody(value) {\n let body = {};\n const patch = this.config.patch;\n value = typeof value !== 'undefined' ? value : this.config.control.value;\n if (IsObject(value)) {\n const val = value;\n body = Object.assign(Object.assign({}, body), val);\n }\n else if (IsArray(value)) {\n body[this.config.patch.field] = value;\n }\n else {\n body[this.config.patch.field] = value;\n if (this.config.empty && !body[this.config.patch.field]) {\n body[this.config.patch.field] = PopTransform(String(value), this.config.empty);\n }\n }\n if (this.config.patch.json)\n body[this.config.patch.field] = JSON.stringify(body[this.config.patch.field]);\n if (patch && patch.metadata) {\n for (const i in patch.metadata) {\n if (!patch.metadata.hasOwnProperty(i))\n continue;\n body[i] = patch.metadata[i];\n }\n }\n return body;\n }", "async function getResourceStackAssociation() {\n templates = {};\n\n await sdkcall(\"CloudFormation\", \"listStacks\", {\n StackStatusFilter: [\"CREATE_COMPLETE\", \"ROLLBACK_IN_PROGRESS\", \"ROLLBACK_FAILED\", \"ROLLBACK_COMPLETE\", \"DELETE_FAILED\", \"UPDATE_IN_PROGRESS\", \"UPDATE_COMPLETE_CLEANUP_IN_PROGRESS\", \"UPDATE_COMPLETE\", \"UPDATE_ROLLBACK_IN_PROGRESS\", \"UPDATE_ROLLBACK_FAILED\", \"UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS\", \"UPDATE_ROLLBACK_COMPLETE\"]\n }, true).then(async (data) => {\n await Promise.all(data.StackSummaries.map(async (stack) => {\n await sdkcall(\"CloudFormation\", \"getTemplate\", {\n StackName: stack.StackId,\n TemplateStage: \"Processed\"\n }, true).then((data) => {\n template = null;\n try {\n template = JSON.parse(data.TemplateBody);\n templates[stack.StackName] = template;\n } catch(err) {\n console.log(\"Couldn't parse\"); // TODO: yaml 2 json\n }\n });\n }));\n });\n\n console.log(templates);\n}", "function setTemplate() {\n return {\n species: \"\",\n nickname: \"\",\n gender: \"\",\n ability: \"\",\n evs: statTemplate(0),\n ivs: statTemplate(31),\n nature: \"\",\n item: \"\",\n moves: [],\n other: {},\n };\n}", "function makeTestEquipmentJSON(id, amount){\n let eq = {};\n eq[EXP_JSON_EQUIP_OBJ_ID] = id;\n eq[EXP_JSON_EQUIP_AMOUNT] = amount;\n return eq;\n}", "function cfnAnomalyDetectorJsonFormatDescriptorPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnAnomalyDetector_JsonFormatDescriptorPropertyValidator(properties).assertSuccess();\n return {\n Charset: cdk.stringToCloudFormation(properties.charset),\n FileCompression: cdk.stringToCloudFormation(properties.fileCompression),\n };\n}", "async function createTemplate(obj, args, context, info) {\n\n\n // 1. user login\n let userId = store.getUserId()\n if (!userId) {\n return {\n err_code: 4000,\n err_msg: 'User token is not valid or empty'\n }\n }\n\n // 2. get my company\n let myCompany = await Company.findUserCompany(userId)\n if (!myCompany) {\n return {\n err_code: 4001,\n err_msg: 'Can not find user company'\n }\n }\n\n // 2. create\n let inputData = args.input\n console.log('args', args)\n if (!inputData.name ) {\n return {\n err_code: 4002,\n err_msg: 'Missing template name' \n }\n }\n\n if (!inputData.html ) {\n return {\n err_code: 4003,\n err_msg: 'Missing html' \n }\n }\n if (!inputData.css ) {\n return {\n err_code: 4003,\n err_msg: 'Missing css' \n }\n }\n let filteredData = {\n name: inputData.name,\n html: inputData.html,\n css: inputData.css,\n js: inputData.js,\n isDefault: inputData.isDefault,\n active: inputData.active\n }\n\n // note: Template.create return a promise object, not a query, \n // so create().lean() will be error\n let newTemplate = await Template.create(filteredData)\n\n // 3. attach to company\n await Company.findOneAndUpdate({_id: myCompany._id}, {$push: {templates: newTemplate._id}}, {upsert: false, new: true})\n\n // 3. return\n return newTemplate\n\n}", "function cfnVirtualGatewayVirtualGatewayTlsValidationContextPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualGateway_VirtualGatewayTlsValidationContextPropertyValidator(properties).assertSuccess();\n return {\n SubjectAlternativeNames: cfnVirtualGatewaySubjectAlternativeNamesPropertyToCloudFormation(properties.subjectAlternativeNames),\n Trust: cfnVirtualGatewayVirtualGatewayTlsValidationContextTrustPropertyToCloudFormation(properties.trust),\n };\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUnctiont o wrap the event_data for dividing partitions, removing a network from a partition
function wrapPartitionDivider( network, partition, simulation){ var event_data = {}; event_data.split_networks_list = [ network]; event_data.partition_id = partition._id; event_data.simulation_id = simulation._id; return event_data; }
[ "function wrapPartitionMerge(partitiona, partitionb, simulation){\n\tvar event_data = {};\n\tevent_data.partition_a_id = partitiona._id;\n\tevent_data.partition_b_id = partitionb._id;\n\tevent_data.simulation_id = simulation._id;\n\treturn event_data;\n}", "_removeServiceStreamDataListener ( ) {\n\n this.serviceStream.removeListener(\n 'data'\n , this.boundStreamListener\n );\n }", "eraseEvent(state, num) {\n state.events.splice(num, 1);\n\n }", "function trashDrop(ev) {\n // this only does something if dragging from a particular meal\n let dayID = ev.dataTransfer.getData('dayID');\n let mealID = ev.dataTransfer.getData('mealID');\n if (dayID != '' && mealID != '') {\n let dishID = ev.dataTransfer.getData('dishID');\n let meal = DragNDropGlobals.weekData[dayID][mealID];\n let idx = meal.indexOf(dishID);\n if (idx > -1) {\n meal.splice(idx, 1);\n }\n serialize(DragNDropGlobals.weekData, DragNDropGlobals.weekFN, () => { location.reload(); });\n }\n}", "sendUpdateTripSectionsEvent(event, self) {\n\n if (event != null && event.data != null && event.data.sections != null) {\n self.log.info(JSON.stringify(event.data, null, 4));\n\n let msg = self.broker.createMessage();\n self.log.info(\"Message was created.\");\n msg.setName(\"updateTripSections\");\n msg.appendToBody(\"tripSections\", event.data);\n\n self.broker.publish(msg);\n self.log.info(\"Message was sent.\")\n } else {\n self.log.info(\"Event received from Vue seems to be null or the wrong one.\");\n }\n }", "function removerEventos() {\n for (let i = 3; i < 8; i++) {\n div[i].removeEventListener('click', eventoClickDiv)\n }\n }", "function _removeImageFromBlock(e) {\n e.preventDefault();\n\n var\n $this = $(this),\n container = $this.closest('.morris-uploader'),\n fileInput = container.find('input[type=\"file\"]'),\n removeDetector = container.find('input.detached-logo'),\n imageId = container.data('image-id'),\n onchangeDetector = container.parent().find('input.onchange'),\n attachDetector = container.find('input.attached-logo');\n\n if (container.hasClass('uploaded') || container.hasClass('editing')) {\n container.css('backgroundImage', 'none').removeClass('uploaded').removeClass('editing');\n //reset file input\n fileInput.val('');\n $('.select').find('.select-placeholder').attr('selected', 'selected');\n }\n if (!container.hasClass('choosed-by-select')) {\n if (container.data('type') == 'unselectable') {\n removeDetector.val(1);\n } else {\n removeDetector.val(imageId);\n }\n } else {\n console.log('hasnt');\n container.removeClass('choosed-by-select');\n onchangeDetector.val(false);\n }\n\n container.removeAttr('data-image-id');\n //for some reason after deleting data removes only from html\n container.data('image-id', null);\n attachDetector.val('');\n _ajaxList();\n }", "remove(eventName) {\n if (this.eventStorage[eventName]) {\n delete this.eventStorage[eventName];\n }\n }", "visitDrop_index_partition(ctx) {\n\t return this.visitChildren(ctx);\n\t}", "delete() {\n\t\t// Remove all edge relate to vertex\n\t\tthis.vertexMgmt.edgeMgmt.removeAllEdgeConnectToVertex(this)\n\n\t\t// Remove from DOM\n\t\td3.select(`#${this.id}`).remove()\n\t\t// Remove from data container\n\t\t_.remove(this.dataContainer.vertex, (e) => {\n\t\t\treturn e.id === this.id\n\t\t})\n\t}", "delete(event) {\n event.preventDefault()\n if (this.onDelete == \"reload\") {\n this.reload(event)\n } else {\n const item = event.target.closest(\"[data-target*='pshr-uploads.item']\")\n item.parentNode.removeChild(item)\n }\n }", "handleCutVideo() {\n let self = this;\n\n // send event to parent that our task is starting\n self.props.onTaskStart( { taskName : 'Cut Video' } );\n\n let msg = { edl : this.edl.rawData() };\n\n cutVideo( msg,function(progress) {\n // send event to parent that our progress has updated\n self.props.onTaskProgress(progress);\n });\n }", "'mountPurge' ({ commit, state, rootState }, { eid }) {\n var cmode = _.get(state.items, `[${eid}].connection_mode`, '')\n\n if (cmode == CONNECTION_MODE_FUNCTION) {\n var pipes = _.filter(rootState.pipes.items, pipe => _.get(pipe, 'parent.eid') == eid)\n _.each(pipes, pipe => {\n commit('pipes/DELETED_PIPE', pipe.eid, { root: true })\n })\n }\n }", "delPerson( name ) {\n let delId = this.findPersonId( name );\n if (delId != null) {\n let idToDelete = this.edges.getIds( {\n filter : function(item) {\n return (item.from == delId || item.to == delId);\n }\n });\n console.log( \"Removing \", idToDelete );\n this.edges.remove( idToDelete );\n this.nodes.remove( delId );\n }\n }", "function partitioningMethod(x)\n{\n\tvar err;\n\t//post(\"Partitioning\", x, \"\\n\");\n\terr = parsePartitioningMethod(x);\n\tif (myPartitioningMethod == CLASSICALPARTITIONING)\n\t{\n\t\tinduceBoundariesFromData();\n\t\tpartitioningComputing();\n\t}\n\t//displaysGlobalVariables();\n}", "function setDataToBeDeleted(destination,source){\n var devices = getDevicesNodeJSON();\n\tvar allline =[];\n\tvar dstArr2 = destination.split(\".\");\n\tvar srcArr2 = source.split(\".\");\n\tfor(var i = 0; i < devices.length; i++){\n\t\tif(dstArr2[0] == devices[i].ObjectPath || srcArr2[0] == devices[i].ObjectPath){\n\t\t\tallline = gettargetmap(devices[i].ObjectPath,allline);\n\t\t}\n\t}\n\tvar linkData = \"\";\n\tfor(var t=0; t<allline.length; t++){\n\t\tvar source = allline[t].Source;\t\n\t\tvar destination = allline[t].Destination;\t\n\t\tvar srcArr = source.split(\".\");\n\t\tvar dstArr = destination.split(\".\");\n\t\tvar portobject;\n\t\tvar portobject2;\n\t\tvar srcName = \"\";\n\t\tvar dstName = \"\";\n\t\tvar srcPortName = \"\";\n\t\tvar dstPortName = \"\";\n\t\tif((srcArr[0] == srcArr2[0] && dstArr[0] == dstArr2[0]) || (dstArr[0] == srcArr2[0] && srcArr[0] == dstArr2[0])){\n\t\t\tportobject = getPortObject2(source);\n\t\t\tportobject2 = getPortObject2(destination);\n\t\t\tif(portobject.PortName != \"\"){\n\t\t\t\tsrcPortName = portobject.PortName;\n\t\t\t}else{\n\t\t\t\tvar pathArr = source.split(\"_\");\n\t\t\t\tvar portPath = pathArr[pathArr.length-1].split(\"_\");\n\t\t\t\tsrcPortName = pathArr[pathArr.length-1];\n\t\t\t\tif(portPath[0] != \"Port\"){\n\t\t\t\t\tsrcPortName = \"Port_\"+portPath[1];\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(portobject2.PortName != \"\"){\n\t\t\t\tdstPortName = portobject2.PortName;\n\t\t\t}else{\n\t\t\t\tvar pathArr = destination.split(\"_\");\n\t\t\t\tvar portPath = pathArr[pathArr.length-1].split(\"_\");\n\t\t\t\tdstPortName = pathArr[pathArr.length-1];\n\t\t\t\tif(portPath[0] != \"Port\"){\n\t\t\t\t\tdstPortName = \"Port_\"+portPath[1];\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar srcDevice = getDeviceObject2(srcArr[0]);\n\t\t\tvar dstDevice = getDeviceObject2(dstArr[0]);\n\t\t\tif(srcDevice.DeviceName != \"\"){\n\t\t\t\tsrcName = srcDevice.DeviceName;\n\t\t\t}else{\n\t\t\t\tsrcName = srcDevice.ObjectPath;\n\t\t\t}\n\t\t\tif(dstDevice.DeviceName != \"\"){\n\t\t\t\tdstName = dstDevice.DeviceName;\n\t\t\t}else{\n\t\t\t\tdstName = dstDevice.ObjectPath;\n\t\t\t}\n\t\t\tvar path = source + \"::\" + destination;\n\t\t\tvar linkName = srcName + \"->\" + srcPortName + \"<-->\" + dstName + \"->\" + dstPortName;\n\t\t\tlinkData += \"<tr><td><input type='checkbox' class='linkiddelete' did='\"+path+\"' onclick='selectAllConnectivivty(this)'/></td>\";\n\t\t\tlinkData += \"<td><span>\"+linkName+\"</span></td></tr>\";\n\t\t}\n\t}\n\t$('#deleteLinkTable > tbody').empty().append(linkData)\n}", "function deletePowerSource(powerplant)\n{\n var pp = powerplant;\n shifting.powerPlants[powerplant].color = \"white\";\n sharedElectricData.variables[powerplant].color = \"white\";\n shifting.powerPlants[powerplant].name = \"\";\n sharedElectricData.variables[powerplant].name = \"\";\n\n for (i=0, n=shifting.powerPlants[powerplant].min.length; i < n; i++) {\n shifting.powerPlants[powerplant].min[i]=0;\n sharedElectricData.variables[powerplant].min[i]=0;\n \n }\n for (i=0, n=shifting.powerPlants[powerplant].max.length; i < n; i++) {\n shifting.powerPlants[powerplant].max[i]=0;\n sharedElectricData.variables[powerplant].max[i]=0;\n }\n $(\"#ps-list-item-\"+pp.slice(-1)).remove();\n $(\"#dragsimulate\").trigger(\"customDragEvent\");\n $(\"#color-legend tbody tr.data\").remove();\n updatePowerPlantLegend();\n resetLegendInitialValues();\n}", "function updateModelOnConnectionDetach() {\n self.jsPlumbInstance.bind('connectionDetached', function (connection) {\n\n // set the isDesignViewContentChanged to true\n self.configurationData.setIsDesignViewContentChanged(true);\n\n var target = connection.targetId;\n var targetId = target.substr(0, target.indexOf('-'));\n /*\n * There is no 'in' or 'out' clause(for other connection they will have like 'view74_element_6-out')\n * section in partition connection point. So once we substr with '-' we don't get any value. So we\n * explicitly set the targetId. Simply if targetId is '' that means this connection is related to a\n * partition.\n * */\n if (targetId === '') {\n targetId = target;\n } else if (!self.configurationData.getSiddhiAppConfig()\n .getDefinitionElementById(targetId, true, true)) {\n console.log(\"Target element not found!\");\n }\n var targetElement = $('#' + targetId);\n\n var source = connection.sourceId;\n var sourceId = source.substr(0, source.indexOf('-'));\n /*\n * There is no 'in' or 'out' clause(for other connection they will have like 'view74_element_6-out')\n * section in partition connection point. So once we substr with '-' we don't get any value. So we\n * explicitly set the sourceId. Simply if sourceId is '' that means this connection is related to a\n * partition.\n * */\n if (sourceId === '') {\n sourceId = source;\n } else if (!self.configurationData.getSiddhiAppConfig()\n .getDefinitionElementById(sourceId, true, true)) {\n console.log(\"Source element not found!\");\n }\n var sourceElement = $('#' + sourceId);\n\n // removing edge from the edgeList\n var edgeId = '' + sourceId + '_' + targetId + '';\n self.configurationData.removeEdge(edgeId);\n\n var model;\n\n if (sourceElement.hasClass(constants.SOURCE) && targetElement.hasClass(constants.STREAM)) {\n self.configurationData.getSiddhiAppConfig().getSource(sourceId)\n .setConnectedElementName(undefined);\n\n } else if (targetElement.hasClass(constants.SINK) && sourceElement.hasClass(constants.STREAM)) {\n self.configurationData.getSiddhiAppConfig().getSink(targetId)\n .setConnectedElementName(undefined);\n\n } else if (targetElement.hasClass(constants.AGGREGATION)\n && (sourceElement.hasClass(constants.STREAM) || sourceElement.hasClass(constants.TRIGGER))) {\n model = self.configurationData.getSiddhiAppConfig().getAggregation(targetId)\n model.setConnectedSource(undefined);\n if(sourceElement.hasClass(constants.STREAM)) {\n model.resetModel(model);\n }\n } else if (sourceElement.hasClass(constants.STREAM) || sourceElement.hasClass(constants.TABLE)\n || sourceElement.hasClass(constants.AGGREGATION) || sourceElement.hasClass(constants.WINDOW)\n || sourceElement.hasClass(constants.TRIGGER)\n || sourceElement.hasClass(constants.PARTITION_CONNECTION_POINT)) {\n\n // if the sourceElement has the class constants.PARTITION_CONNECTION_POINT then that is\n // basically a stream because a connection point holds a connection to a stream.\n // So we replace that sourceElement with the actual stream element.\n if (sourceElement.hasClass(constants.PARTITION_CONNECTION_POINT)) {\n var sourceConnection = self.jsPlumbInstance.getConnections({target: sourceId});\n var sourceConnectionId = sourceConnection[0].sourceId;\n var connectedStreamId = sourceConnectionId.substr(0, sourceConnectionId.indexOf('-'));\n sourceElement = $('#' + connectedStreamId);\n sourceId = connectedStreamId;\n }\n\n if ((sourceElement.hasClass(constants.STREAM) || sourceElement.hasClass(constants.WINDOW)\n || sourceElement.hasClass(constants.TRIGGER))\n && (targetElement.hasClass(constants.PROJECTION) || targetElement.hasClass(constants.FILTER)\n || targetElement.hasClass(constants.WINDOW_QUERY)\n || targetElement.hasClass(constants.FUNCTION_QUERY))) {\n model = self.configurationData.getSiddhiAppConfig()\n .getWindowFilterProjectionQuery(targetId);\n model.resetInputModel(model);\n\n } else if (targetElement.hasClass(constants.JOIN)) {\n model = self.configurationData.getSiddhiAppConfig().getJoinQuery(targetId);\n var queryInput = model.getQueryInput();\n var sourceElementObject =\n self.configurationData.getSiddhiAppConfig().getDefinitionElementById(sourceId);\n if (sourceElementObject !== undefined) {\n var disconnectedElementSourceName = (sourceElementObject.element).getName();\n if (!queryInput) {\n console.log(\"Join query output is undefined!\");\n return;\n }\n var firstConnectedElement = queryInput.getFirstConnectedElement();\n var secondConnectedElement = queryInput.getSecondConnectedElement();\n if (!firstConnectedElement && !secondConnectedElement) {\n console.log(\"firstConnectedElement and secondConnectedElement are undefined!\");\n } else if (firstConnectedElement &&\n (firstConnectedElement.name === disconnectedElementSourceName ||\n !firstConnectedElement.name)) {\n queryInput.setFirstConnectedElement(undefined);\n } else if (secondConnectedElement\n && (secondConnectedElement.name === disconnectedElementSourceName ||\n !secondConnectedElement.name)) {\n queryInput.setSecondConnectedElement(undefined);\n } else {\n console.log(\"Error: Disconnected source name not found in join query!\");\n return;\n }\n\n // if left or sources are created then remove data from those sources\n if (queryInput.getLeft() !== undefined\n && queryInput.getLeft().getConnectedSource() === disconnectedElementSourceName) {\n queryInput.setLeft(undefined);\n } else if (queryInput.getRight() !== undefined\n && queryInput.getRight().getConnectedSource() === disconnectedElementSourceName) {\n queryInput.setRight(undefined);\n }\n model.resetInputModel(model);\n }\n\n } else if (sourceElement.hasClass(constants.STREAM)\n || sourceElement.hasClass(constants.TRIGGER)) {\n\n var disconnectedElementName;\n if (sourceElement.hasClass(constants.STREAM)) {\n disconnectedElementName =\n self.configurationData.getSiddhiAppConfig().getStream(sourceId).getName();\n } else {\n disconnectedElementName =\n self.configurationData.getSiddhiAppConfig().getTrigger(sourceId).getName();\n }\n\n if (targetElement.hasClass(constants.PATTERN)) {\n model = self.configurationData.getSiddhiAppConfig().getPatternQuery(targetId);\n model.resetInputModel(model, disconnectedElementName);\n } else if (targetElement.hasClass(constants.SEQUENCE)) {\n model = self.configurationData.getSiddhiAppConfig().getSequenceQuery(targetId);\n model.resetInputModel(model, disconnectedElementName);\n }\n }\n\n } else if (targetElement.hasClass(constants.STREAM) || targetElement.hasClass(constants.TABLE)\n || targetElement.hasClass(constants.WINDOW)) {\n if (sourceElement.hasClass(constants.PROJECTION) || sourceElement.hasClass(constants.FILTER)\n || sourceElement.hasClass(constants.WINDOW_QUERY)\n || sourceElement.hasClass(constants.FUNCTION_QUERY)\n || sourceElement.hasClass(constants.JOIN)\n || sourceElement.hasClass(constants.PATTERN)\n || sourceElement.hasClass(constants.SEQUENCE)) {\n\n if (sourceElement.hasClass(constants.PROJECTION) || sourceElement.hasClass(constants.FILTER)\n || sourceElement.hasClass(constants.WINDOW_QUERY)\n || sourceElement.hasClass(constants.FUNCTION_QUERY)) {\n model = self.configurationData.getSiddhiAppConfig()\n .getWindowFilterProjectionQuery(sourceId);\n } else if (sourceElement.hasClass(constants.JOIN)) {\n model = self.configurationData.getSiddhiAppConfig().getJoinQuery(sourceId);\n } else if (sourceElement.hasClass(constants.PATTERN)) {\n model = self.configurationData.getSiddhiAppConfig().getPatternQuery(sourceId);\n } else if (sourceElement.hasClass(constants.SEQUENCE)) {\n model = self.configurationData.getSiddhiAppConfig().getSequenceQuery(sourceId);\n }\n model.resetOutputModel(model);\n }\n }\n\n // validate source and target elements\n checkJSONValidityOfElement(self, sourceId, true);\n checkJSONValidityOfElement(self, targetId, true);\n });\n }", "setPresenceData (callback) {\n\t\t// set the presence data, but then delete the parameter in question\n\t\tsuper.setPresenceData(() => {\n\t\t\tdelete this.presenceData[this.parameter];\n\t\t\tcallback();\n\t\t});\n\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
given an array of [x,y] points, return the average
function average_point(list) { var sum_x = 0; var sum_y = 0; var num_points = 0; for(var i=0; i<list.length; i++) { sum_x += list[i][0]; sum_y += list[i][1]; num_points += 1; } return [sum_x / num_points, sum_y / num_points]; }
[ "assignedPointsMean(arr, len) {\n \n const meanX = arr.map(p => p.x).reduce((a, b) => a + b) / len;\n const meanY = arr.map(p => p.y).reduce((a, b) => a + b) / len;\n return {\n x: meanX,\n y: meanY\n }\n }", "function avgValue(array)\n{\n\tvar sum = 0;\n\tfor(var i = 0; i <= array.length - 1; i++)\n\t{\n\t\tsum += array[i];\n\t}\n\tvar arrayLength = array.length;\n\treturn sum/arrayLength;\n}", "function absAvg(arr){\n // arr is a typed array! \n var abs_avg = arr.reduce((a,b) => (a+Math.abs(b))) / arr.length;\n return abs_avg; \n}", "function averageNumbers(array){\n let sum = 0;\n let avg;\n for ( let i = 0 ; i < array.length ; i++ ){\n sum = sum + array[i];\n avg = sum / array.length\n }\n return avg\n}", "function calculateAverage(){\n var average = new THREE.Vector2();\n for (let i = 0; i < allVectors.length; i++) {\n average.x += allVectors[i].x;\n average.y += allVectors[i].y;\n }\n average.x = average.x/allVectors.length;\n average.y = average.y/allVectors.length;\n return average;\n}", "function mean(values) {\n var average = []\n for (var i = 0; i < values.length; i++) {\n var sum = 0;\n for (var j = 0; j < values[i].length; j++) {\n sum = sum + values[i][j]\n }\n average.push(sum/values[i].length)\n }\n return average;\n }", "function avg(v){\n s = 0.0;\n for(var i=0; i<v.length; i++)\n s += v[i];\n return s/v.length;\n}", "function calcAverage (tips) {\n var sum = 0;\n for (var i = 0; i < tips.length; i++) {\n sum += tips[i];\n }\n return sum / tips.length;\n}", "function mean_with_reduce(array,callback) {\n if (callback) {\n array.map( callback );\n } \n const total = array.reduce((a, b) => a + b);\n return total/array.length;\n}", "function averagePoint(a, b) {\n\tvar ax = a.RA;\n\tvar bx = b.RA;\n\tif(ax - bx > FULL_CIRCLE / 2) {\n\t\t//bx is too far at the left\n\t\tbx += 360;\n\t} else if (bx - ax > 360 / 2) {\n\t\t//ax is too far at the left\n\t\tax += 360;\n\t}\n\n\treturn new Point((ax+bx)/2, (a.Dec + b.Dec)/2);\n}", "function maxMinAvg(arr){\n var max = arr[0];\n var min = arr[0];\n var avg = null;\n for(i=0;i<arr.length;i++){\n if(arr[i]<min){\n min = arr[i];\n }\n if(arr[i]>max){\n max = arr[i];\n }\n avg+=arr[i];\n }\n var newArr = [max, min, avg/arr.length]\n return newArr;\n}", "function calcAverage(tips){\n var sum = 0\n for(var i = 0; i < tips.length; i++){\n sum = sum + tips[i]\n }\n return sum / tips.length\n }", "average(marks) {}", "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 averageAge(people){\n\tvar average = 0;\n\tfor(var i = 0; i < people.length; i++){\n\t\taverage += people[i].age;\n\t}\n\treturn average / people.length;\n}", "function computeEachPoint(min, max, fx)\n{\n let xData = [];\n let yData = [];\n const step = 0.1;\n\n for(let i = min;i <= max; i += step)\n {\n xData.push(i);\n let y = fx(i);\n yData.push(y);\n }\n\n return [xData, yData];\n}", "function avgAge(persons) \n{\n var out;\nout=persons.reduce()\n\n return out\n}", "function calculateMean() {\n var mean = 0;\n for (var j = 0; j < $scope.data2.length; j++) {\n mean = mean + $scope.data2[j].y;\n }\n return mean = ((mean / 24).toFixed(2));\n }", "function average(a, b, fn) {\n return fn(a, b) / 2;\n}", "function average(x1, x2, x3, x4, x5) {\n var sum = x1 + x2 + x3 + x4 + x5;\n var avg = sum / 5;\n return console.log(avg)\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets X position for the cluster or label of a given weight class weightClass class being queried weightClassList ordered list of weight classes being considered. for label X's this should be all of them, but when the network is filtered by weight class only consider the list of filtered classes
function getXForWeightClass(weightClass, weightClassList) { if(weightClassList == null) { weightClassList = weightClasses; } var i = weightClassList.indexOf(weightClass); if(i === -1) return -1; var margin = 50; return margin + (width - 2 * margin) / weightClassList.length * (i + .5); }
[ "function getIndicesWithClass(ar, class_name)\n{\n\tvar ind = [];\n\tfor (var i = 0; i < ar.size(); i++)\n\t{\n\t\tif (ar.hasClass(i, class_name))\n\t\t{\n\t\t\tind.push(i);\n\t\t}\n\t}\n\treturn ind;\n}", "function getCheckBoxValue(checkBoxClass){\r\n\tvar checkboxList = document.getElementsByClassName(checkBoxClass);\r\n\tconsole.log(checkboxList);\r\n\tvar index = -1;\r\n\tif(checkboxList !== null) {\r\n\t\tfor(var i = 0; i < checkboxList.length; i++) {\r\n\t\t\tif(checkboxList[i].checked === true){\r\n\t\t\t\tindex = i;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t} return index;\r\n}", "function getPosition(event) {\n var toParse = event.target.className;\n var row = toParse.substring((toParse.indexOf('row_'))+4,(toParse.indexOf('col')));\n var col = toParse.substring((toParse.indexOf('col'))+4,(toParse.length));\n return [parseInt(row), parseInt(col)];\n }", "__getClassStartingWith(node, prefix) {\n return _.filter(\n $(node)\n .attr('class')\n .split(' '),\n className => _.startsWith(className, prefix)\n )[0];\n }", "findNodePos(number) {\n for (let layer = 0; layer < this.nodes.length; layer++) {\n for (let node = 0; node < this.nodes[layer].length; node++) {\n if (this.nodes[layer][node].number === number) return [layer, node];\n }\n }\n return false;\n }", "function findUnconnectedPreds(label) {\n\t\n\tfor (var j = 0; j < selection.summarization.unconnectedPreds.length; j++) {\n\t\t\t\n\t\tif (selection.summarization.unconnectedPreds[j] == label) {\n\t\t\t\t\t\n\t\t\treturn j;\n\t\t}\n\t}\n\n\treturn -1;\n}", "pos_x() {\n return(this.pos.x);\n }", "function classify(Template, candidate) {\n let Results = [];\n let Classes = [];\n for (let k = 0; k < 3; k++) {\n let bestGestureClass = null;\n let bestScore = -Infinity;\n // compute the similarity score of the candidate against each gesture class\n for (let c = 0; c < _this.gestureClasses.length; c += 1) {\n let score = Template[k][_this.gestureClasses[c]].initialWeight;\n let weightsVector = Template[k][_this.gestureClasses[c]].weightsVectorCl;\n for (let i = 0; i < weightsVector.length; i += 1)\n score += weightsVector[i] * candidate[k].featureVector[i];\n if (score > bestScore) {\n bestScore = score;\n bestGestureClass = _this.gestureClasses[c];\n }\n }\n Results.push({ bestGestureClass, bestScore });\n }\n //The Heuristic\n if (Results[0].bestGestureClass == Results[1].bestGestureClass && Results[1].bestGestureClass == Results[2].bestGestureClass) {\n return [Results[0].bestGestureClass, Results[0].bestScore];\n }\n else {\n bestScore = -Infinity;\n Classes.push(Results[0].bestGestureClass);\n if (Results[0].bestGestureClass != Results[1].bestGestureClass) {\n Classes.push(Results[1].bestGestureClass);\n if (Results[2].bestGestureClass != Results[1].bestGestureClass && Results[2].bestGestureClass != Results[0].bestGestureClass) {\n Classes.push(Results[2].bestGestureClass);\n }\n } else if (Results[0].bestGestureClass != Results[2].bestGestureClass) {\n Classes.push(Results[2].bestGestureClass);\n }\n for (let c = 0; c < Classes.length; c += 1) {\n let WeightedScore = 0;\n for (let k = 0; k < 3; k++) {\n let score = Template[k][Classes[c]].initialWeight;\n let weightsVector = Template[k][Classes[c]].weightsVectorCl;\n for (let i = 0; i < weightsVector.length; i += 1)\n score += weightsVector[i] * candidate[k].featureVector[i];\n WeightedScore += score * DEFAULT_WEIGHTS[k];\n }\n if (WeightedScore > bestScore) {\n bestScore = WeightedScore;\n bestGestureClass = Classes[c];\n }\n }\n\n return [bestGestureClass, bestScore];\n }\n\n}", "function filterByClass(elements, className, include) {\n var results = [];\n for (var i = 0; i < elements.length; i++) {\n if (hasClass(elements[i], className) == include)\n results.push(elements[i]);\n }\n return results;\n }", "function getRow(element){\n var row_num = parseInt(element.classList[0][4]);\n return row_num;\n}", "labeled() {\n return getLabels(this.grid);\n }", "function getClassOfElement(partition, currState)\n{\n for(var i = 0; i < partition.length; i++)\n {\n if(partition[i].includes(currState))\n {\n return i;\n }\n }\n}", "function countIndWithClass(ar, class_name)\n{\n\tvar count = 0;\n\tfor (var i = 0; i < ar.size(); i++)\n\t{\n\t\tif (ar.hasClass(i, class_name))\n\t\t{\n\t\t\tcount++;\n\t\t}\n\t}\n\treturn count;\n}", "arrangeClassListView(classList_) {\n var classListLen = classList_.length;\n var subColumnList = new Array();\n subColumnList[0] = new Array();\n var subColumnCount = 1;\n var maxEndTimeClass = classList_[0];\n for (var i = 0; i < classListLen; i++) {\n var currentClass = classList_[i];\n if (timeToNumber(currentClass.classData.endTime) >= timeToNumber(maxEndTimeClass.classData.endTime)) {\n maxEndTimeClass = currentClass;\n }\n var done = false;\n for (var j = 0; j < subColumnCount; j++) {\n var currentSubColumn = subColumnList[j];\n if (currentSubColumn.length == 0 ||\n !isClassOverlapping(currentClass, currentSubColumn[currentSubColumn.length - 1])) {\n currentSubColumn.push(currentClass);\n done = true;\n break;\n }\n }\n if (!done) {\n subColumnList[subColumnCount] = new Array();\n subColumnList[subColumnCount].push(currentClass);\n subColumnCount += 1;\n }\n var nextClass;\n if (i < classListLen - 1) {\n nextClass = classList_[i+1];\n } else {\n nextClass = undefined; \n }\n if (!isClassOverlapping(maxEndTimeClass, nextClass)) {\n for (var k = 0; k < subColumnCount; k++) {\n for (var l = 0; l < subColumnList[k].length; l++) {\n subColumnList[k][l].zOrder = (k + 1) + \"/\" + subColumnCount;\n subColumnList[k][l].updateView();\n }\n }\n subColumnList = new Array();\n subColumnList[0] = new Array();\n subColumnCount = 1;\n }\n }\n }", "function getPositions(which) {\n var sv = (which == 2) ? svg2 : svg;\n var positions = [];\n sv.selectAll(\".shapecontainer\").each(function(d) {\n translate = d3.select(this).attr(\"transform\");\n pos = translate.substring(translate.indexOf(\"(\")+1, translate.indexOf(\")\")).split(\",\");\n pos[0] = +pos[0];\n pos[1] = +pos[1];\n positions.push(pos);\n });\n return positions;\n}", "function get_the_class(ip){\n \tif (0 <= ip && ip <= 2147483647) { return 'Class A'; }\n \telse if (2147483648 <= ip && ip <= 3221225471) { return 'Class B'; }\n \telse if (3221225472 <= ip && ip <= 3758096383) { return 'Class C'; }\n \telse if (3758096384 <= ip && ip <= 4026531839) { return 'Class D'; }\n \telse if (4026531840 <= ip && ip <= 4294967295) { return 'Class E'; }\t\n \telse { return ''; }\n }", "function getStartAndTargetNode(allNodes){\n\n\t// check that exist\n\tvar startNodeElement = $('.element.startNode'); \n\tvar targetNodeElement = $('.element.targetNode');\n\tif(startNodeElement.length==0 || targetNodeElement.length==0){ return [null, null, false];}\n\n\t// get elements with start and target classes\n\tvar startNodeID = startNodeElement[0].id; \n\tvar targetNodeID = targetNodeElement[0].id;\n\n\t// get the coordinates information from the ID\n\t[startNodeRow, startNodeCol] = getNodePositionFromID(startNodeID);\n\t[targetNodeRow, targetNodeCol] = getNodePositionFromID(targetNodeID);\n\n\t// get the node at those coordinates \n\t[startNode, ignore]= getNodeAtPosition(startNodeRow, startNodeCol, allNodes);\n\t[targetNode, ignore] = getNodeAtPosition(targetNodeRow, targetNodeCol, allNodes);\n\n\treturn [startNode.value, targetNode.value, true];\n}", "function getTrainingSet(dtm, label){\n\tvar i;\n\tvar tuple;\n\tvar result = [];\n\n\tfor(i = 0; i < dtm.length; i++){\n\t\ttuple = [dtm[i], label[i]];\n\t\tresult.push(tuple);\n\t}\n\n\teventEmitter.emit('trainingSet', result);\n}", "TreeAdvanceToLabelPos()\n {\n let g = this.guictx;\n g.CurrentWindow.DC.CursorPos.x += this.GetTreeNodeToLabelSpacing();\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the opposite of a given position
function oppositePosition(p) { if (p === 'top') { return 'bottom'; } else if (p === 'bottom') { return 'top'; } else if (p === 'left') { return 'right'; } else if (p === 'right') { return 'left'; } return p; }
[ "negate() {\n return new Vector2(-this.x, -this.y);\n }", "negate() {\n return new Vector3(-this.x, -this.y, -this.z);\n }", "function opposite (degrees) {\n return constrain(degrees - 180)\n}", "negate() {\n return new Vector4(-this.x, -this.y, -this.z, -this.w);\n }", "function opposite(dir1, dir2) {\n dir1 = dir1.toLowerCase()\n dir2 = dir2.toLowerCase()\n \n if (dir1 === 'north' && dir2 === 'south') { \n return true\n } else if (dir1 === 'south' && dir2 === 'north') {\n return true \n } else if (dir1 === 'east' && dir2 === 'west') { \n return true \n } else if (dir1 === 'west' && dir2 === 'east') { \n return true\n } else { \n return false \n }\n }", "moveAwayFromCurrentTile() {\n const { col } = this;\n const { row } = this;\n const { grid } = this.board;\n\n // If above isn't blocked, move there.\n /** @type {BoardTile} */\n if (grid[row - 1][col].isLowBlocked() === false) {\n super.move(-1, 0);\n return;\n }\n // Below.\n if (grid[row + 1][col].isLowBlocked() === false) {\n super.move(+1, 0);\n return;\n }\n // Left.\n if (grid[row][col - 1].isLowBlocked() === false) {\n super.move(0, -1);\n return;\n }\n // Right.\n if (grid[row][col + 1].isLowBlocked() === false) {\n super.move(0, +1);\n }\n }", "function negate(func) {\n return function() {\n return !(func.apply(this, arguments))\n }\n}", "not(selection) {\n if (selection === 'R') {\n return 'L';\n } else if (selection === 'L') {\n return 'R';\n } else if (selection === 'home') {\n return 'away';\n } else if (selection === 'away') {\n return 'home';\n }\n }", "function invertNum(num)\n{\n\treturn num *= -1;\n}", "function invert_negatives(input) {\n if(input > 0) {\n return -input;\n }\n if(input < 0) {\n return input;\n }\n if(isNaN(input)) {\n return false;\n }\n}", "function posNeg(x,y, z) {\n\t(((x < 0)&&(y > 0)) || ((x > 0) && (y < 0)) || ((x < 0)&&(y<0) && (z === true))) ? console.log(\"true\") : console.log(\"false\");\n}", "invert() {\n for (let i = 0; i < this._data.length; i++) {\n this._data[i] = ~this._data[i];\n }\n }", "function reverseAndNot(i) {\n return parseInt(i.toString().split(\"\").reverse().join(\"\") + i);\n}", "function inv ( subject ) {\n return subject * -1;\n }", "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}}", "invert() {\n quat.invert(this, this);\n return this.check();\n }", "getExistingAdjacentPosns(posn) {\n\t\tvar theWorld = this;\n\t\treturn posn.getAdjacentPosnsWithWraparound(theWorld).filter(function(p) {\n\t\t\treturn !!theWorld.get(p);\n\t\t})\n\t}", "function inverseGravity() \n{ \n if (player.inverted === false) \n { \n player.angle = -180; \n player.body.gravity.y = -2000; \n player.inverted = true; \n } \n else if (player.inverted ===true)\n { \n player.angle = 0; \n player.body.gravity.y = 2000; \n player.inverted = false; \n }\n}", "function getXmovement(fromIndex,toIndex){if(fromIndex==toIndex){return'none';}if(fromIndex>toIndex){return'left';}return'right';}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear moving and idle timeouts
clearTimeouts() { clearTimeout(this.movingTimeout); clearTimeout(this.idleTimeout); }
[ "function clearAllTimeouts() {\n \n /* Getting new max timeout timer ID */\n var id = window.setTimeout(function() {}, 0);\n \n /* Going down through the timeout timers and clearing them */\n while (id--) {\n window.clearTimeout(id);\n } \n}", "function clearMonitorTimeout() {\n serlog('Clear disp. off');\n consolelog('Clear display off');\n if (monitorTimeoutId != null) {\n clearTimeout(monitorTimeoutId);\n\tmonitorTimeoutId = null;\n }\n}", "function clearMoves(){\n player1Move = null;\n player2Move = null;\n}", "function resetTimeout() {\n\t\tclearTimeout(timeOut);\n\t\ttimeOut = setTimeout(function() {publicNext();}, timeAutoSlice);\n\t}", "function clearMove(){\n for(var y; y < 8; y++){\n for(var x; x < 8; x++){\n if(state.board[y][x] === 'move'){\n state.board[y][x] = null;\n }\n }\n }\n}", "function resetMoves() {\n moveCount = 0;\n updateMoves();\n updateStars();\n}", "function clearTimeOutHint() {\n clearTimeout(tHint);\n }", "reset(){\n this.setSpeed();\n this.setStartPosition();\n }", "clearAndResetUpdate(){\n\t\tclearTimeout(timer);\n\t\tthis.getChats();\t\n\t}", "function resetBoard() {\n clearInterval(interval);\n timer.innerHTML = '0 mins 0 secs';\n countMoves.innerHTML = '';\n newBoard();\n}", "function clearGrid() {\n score = 0\n mode = null\n firstMove = false\n moves = 10\n timer = 60\n interval = null\n grid.innerHTML = ''\n }", "resetPenTimer() {\n this.penTimer = 0;\n this.incDotCounter();\n }", "function resetHover() {\n hovering = false;\n startTimeout();\n }", "function clearSaveTimer()\r\n\t{\r\n\t\tif (UpdateTimeOut)\r\n\t\t{\r\n\t\t\twindow.clearTimeout(UpdateTimeOut);\r\n\t\t\tUpdateTimeOut = null;\r\n\t\t}\r\n\t}", "reset() {\n\t\tclearInterval(this.timer);\n\t\tthis.setState(this.initialState);\n\t}", "function resetTiles() {\n\t\tvar positions = createPositionArray(xCount, yCount, diameter);\n\t\t\n\t\tfor(var i = 0; i < tiles.length; i++){\n\t\t\ttiles[i].setPosition(positions.pop());\n\t\t}\n\t\trotateTiles();\n\t\tgroupTiles();\n\t}", "function reset() {\n\n // Remove alert division\n alertDiv.parentNode.removeChild(alertDiv);\n\n // Clear the logout timer\n clearTimeout(logoutTimer);\n\n // Restart the alert timer\n document.onmousemove = resetAlertTimer;\n document.onkeypress = resetAlertTimer;\n }", "function resetVars(state) {\n keepBallAttached = false;\n ballIsUp = false;\n fired = false;\n }", "function resetAllEvents(){\n\t\t\tevents.forEach( ev => { \n\t\t\t\tev.button.gotoAndStop(0);\n\t\t\t\tev.button.cursor = \"pointer\";\n\t\t\t\tev.choosen = false; \n\t\t\t});\n\t\t\t// update instructions\n\t\t\tself.instructions.gotoAndStop(0);\n\t\t\t// update side box\n\t\t\tself.sideBox.gotoAndStop(0);\n\t\t}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Displays 4 paragraphs at a delay interval using promises
function runPromises(text, delay){ // code goes here console.log('runPromises is called', text, delay); return new Promise(function(resolve, reject){ setTimeout(resolve(addParagraph(text)), delay) }) .then(Promise.resolve()) .then(Promise.resolve()) .then(Promise.resolve()) }
[ "function runForLoop(text, delay) {\n // code goes here\n console.log('runForLoop is called', text, delay);\n for (let i = 0; i < 4; i++) {\n setTimeout(addParagraph, delay * i, text);\n };\n}", "function displayWaitingText() {\n var index = 0;\n var waitingMessages = [ 'Creating Your Station...',\n 'This Could Take Up To 30 secs...',\n 'So... uh....',\n 'Nice weather, huh?...',\n \" (fingers tapping...) \"];\n\n showNextMessage();\n \n function showNextMessage() {\n $scope.submitButtonInfo.text = waitingMessages[index];\n \n // iterate\n index++;\n if (index >= waitingMessages.length) {\n index = 0;\n }\n \n // set next message change\n submitButtonTextChangeTimeout = $timeout(function () {\n showNextMessage();\n }, 5000);\n }\n }", "function generateParagraph() {\n // Clear the current text\n $('#content').text('');\n // Generate ten sentences for our paragraph\n // (Output is an array)\n let sentenceArray = markov.generateSentences(20);\n // Turn the array into a single string by joining with spaces\n let sentenceText = sentenceArray.join(' ');\n // Put the new text onto the page\n $('#content').append(sentenceText);\n}", "function startTimeout() {\n timeout = setTimeout(function () {\n hideParagraph();\n }, 2000);\n }", "function gamePatterReplay() {\n for (var i = 0; i < gamePattern.length; i++) {\n (function(i) {\n setTimeout(function() {\n $('#' + gamePattern[i]).fadeOut(100).fadeIn(100);\n console.log(gamePattern[i]);\n }, 500 * i);\n })(i);\n }\n setTimeout(nextSequence, 500 * i);\n}", "function delay() {\n const t = calculateDelay(selection.q.length) * 1000;\n setTimeout(function() {\n timerStart();\n }, t);\n}", "_sayHello () {\n const printHello = async () => {\n await animate.pauseBetween();\n await animate.printText(this.DOM.sayHelloHello, locale[this.lang]['main']['hello'], this.timePrintText);\n await animate.printText(this.DOM.sayHelloIndie, locale[this.lang]['main']['indie'], this.timePrintText);\n await animate.printText(this.DOM.sayHelloDev, locale[this.lang]['main']['dev'], this.timePrintText);\n await animate.pauseBetween();\n }\n\n printHello().then(() => {\n this.DOM.body.classList.add('load');\n this.isLoaded = true;\n }).catch((err) => { console.log(err.message) });\n }", "function readParagraphs() \n{\n if ((xhrContent.readyState === 4) && (xhrContent.status === 200)) \n {\n let MyContent = JSON.parse(xhrContent.responseText);\n let paragraphs = MyContent.paragraphs;\n paragraphs.forEach(function (paragraph) \n {\n let paragraphElements = document.getElementById(paragraph.id);\n //Searches element ids and aligns them with suitable paragraphs in the html\n if(paragraphElements) \n {\n paragraphElements.innerHTML = paragraph.content;\n } \n }, this);\n }\n}", "function printQuote() {\n clearInterval(timerId);\n const newQuote = getRandomQuote();\n const newColor = getRandomColor();\n let htmlStr = `<p class=\"quote\"> ${newQuote.quote} </p><p class=\"source\">${newQuote.source}`;\n if(newQuote.citation){\n htmlStr += `<span class=\"citation\"> ${newQuote.citation} </span>`;\n }\n if(newQuote.year){\n htmlStr += `<span class=\"year\"> ${newQuote.year} </span>`;\n }\n if(newQuote.tags){\n htmlStr += `<span class=\"tags\"> ${newQuote.tags} </span>`;\n }\n htmlStr += '</p>';\n document.getElementById('quote-box').innerHTML = htmlStr;\n document.body.style.backgroundColor = newColor;\n timerId = setInterval(printQuote, 15000);\n}", "function displayPostGameSentence(winnerSentence) {\n gameWrapper.classList.remove('game-fade-in'); // Fade-out the game UI\n finalSentence.classList.remove('final-fade-in'); // Fade-out final sentence\n\n setTimeout(() => {\n winnerSentence.classList.add('display-sentence');\n displayRestarButton(); // Display restart button\n }, 2000);\n}", "function fillTitles() {\n setTimeout(() => catOneTitle_button.innerText = getRandomCategory(), 1000);\n setTimeout(() => catTwoTitle_button.innerText = getRandomCategory(), 2000);\n setTimeout(() => catThreeTitle_button.innerText = getRandomCategory(), 3000);\n setTimeout(() => catFourTitle_button.innerText = getRandomCategory(), 4000);\n setTimeout(() => catFiveTitle_button.innerText = getRandomCategory(), 5000);\n setTimeout(() => catSixTitle_button.innerText = getRandomCategory(), 6000);\n }", "function printTimeout(str, n) {\r\n const timeInMs = n * 1000;\r\n setTimeout(function() { console.log(str); }, timeInMs);\r\n}", "function displayFinalSentence() {\n enableMainButtons(100);\n setTimeout(() => {\n finalSentence.classList.add('final-fade-in'); // Fade-in final sentence\n gameWrapper.classList.add('game-fade-in'); // Fade-in the game UI\n btnRules.classList.add('display-btn-rules');\n }, FINAL_SENTENCE_APPARITION_DELAY);\n}", "function generateLoremIpsum() {\n var number = parseInt(numOfParagraphs.value);\n var text = lorem.generateParagraphs(number);\n loremIpsumText.innerText = text;\n}", "function printQuote() {\n var randomQuote;\n do { randomQuote = getRandomQuote(); } while (randomQuote === currentQuote);\n currentQuote = randomQuote;\n randomBackgroundColor();\n var htmlString = `<p class=\"quote\">${randomQuote.quote}</p> <p class=\"source\">${randomQuote.source}`;\n if (randomQuote.hasOwnProperty('citation')) htmlString += `<span class=\"citation\">${randomQuote.citation}</span>`;\n if (randomQuote.hasOwnProperty('year')) htmlString += `<span class=\"year\">${randomQuote.year}</span>`;\n if (randomQuote.hasOwnProperty('tags')) htmlString += `<br><span>tags: ${randomQuote.tags}</span>`;\n htmlString += `</p>`;\n document.getElementById('quote-box').innerHTML = htmlString;\n window.clearInterval(timer);\n timer = window.setInterval(printQuote, 20000);\n}", "function output_games(result){\n let i = 0;\n let short_description = \"\";\n let title_length = 0;\n let j = 0;\n let font_size = \"28px\";\n window.scrollTo(0, 0);\n \n document.querySelector(\"main\").innerHTML = \"\";\n while(i < 50){\n \tdisplay_game(result[i]);\n i += 1;\n }\n}", "function displaySleep(sleep)\n{\n document.getElementById(\"mood-sleep-main\").text = \" \" + sleep + \" HR \"; \n}", "function wordLoader() {\n\tif (splitWord.length === 0) {\n\t\tsetTimeout(function() {\n\t\t\tsplashTextInsert()\n\t\t}, 1000);\n\t} else if (x <= splitWord.length && x>=0) {\n\t\tsetTimeout(function() {\n\t\t\t$(\"#splashLoader\").append(splitWord[x]); \n\t\t\tx++;\n\t\t\twordLoader();\n\t\t}, Math.floor(Math.random() * 400) + 100);\n\t} else if (x > splitWord.length && x>=0) {\n\n\t\tsetTimeout(function() {\n\t\t\t$(\"#splashLoader\").empty();\n\t\t\tsplitWord.pop();\n\t\t\t$(\"#splashLoader\").text(splitWord.join(\"\"));\n\t\t\t--x;\n\t\t\twordLoader();\n\t\t}, 200);\n\t}\n}", "function runAfterDelay(delay,callback){\n console.log('(Exercise 7).Wait for '+delay+' secs....'); \n callback(delay);\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Custom type guard for CustomSecurityScheme. Returns true if node is instance of CustomSecurityScheme. Returns false otherwise. Also returns false for super interfaces of CustomSecurityScheme.
function isCustomSecurityScheme(node) { return node.kind() == "CustomSecurityScheme" && node.RAMLVersion() == "RAML10"; }
[ "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === SigningProfilePermission.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === ServiceLinkedRole.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === ContainerPolicy.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === RelationshipLink.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === UserGroup.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === PrivateLinkService.__pulumiType;\n }", "function _check_acl_role(_acl_role) {\n if (_acl_role === undefined)\n return;\n /* now, _acl_role is(should be) ArgAclRoleValueTypeWhenCheck */\n if (extend === undefined)\n return _check_acl_act(_acl_role);\n /* now, _acl_role is(should be) ACLRoleVarHostType */\n var exts = _acl_role.extends;\n if (exts !== undefined) {\n /*\n check whether AClPermissionDescriptorKey `extend` exists in parent-AClPermissionDescriptor's 'extends' hash.\n {\n '1234': {\n 'extends': {\n 'ext': {}\n }\n }\n }\n */\n if (_check_acl_act(exts[extend]))\n return true;\n /*\n check whether AClPermissionDescriptorKey `*` exists in parent-AClPermissionDescriptor's 'extends' hash.\n {\n '1234': {\n 'extends': {\n '*': {}\n }\n }\n }\n */\n return _check_acl_act(exts['*']);\n }\n }", "hasInheritance(node) {\n let inherits = false;\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n if (match_1.default(child, 'extends', 'implements')) {\n inherits = true;\n }\n }\n return inherits;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Resolver.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === CustomerGateway.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Host.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === EncryptionConfig.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === KeySigningKey.__pulumiType;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === JavaAppLayer.__pulumiType;\n }", "function checkSecurity(){\t\t\t\n\t\t// Check the security tokens\n\t\tif (messageIn.type!=INIT && (messageIn.tokenParent!=securityTokenParent || messageIn.tokenChild!=securityTokenChild)){\n\t\t\tlog( \"Security token error: Invalid security token received. The message will be discarded.\" );\n\t\t\thandleSecurityError(smash.SecurityErrors.INVALID_TOKEN);\n\t\t\treturn false;\n\t\t}\t\t\n\t\t// Attacks should never pass the security check. Code below is to debug the implementation.\n//\t\tif(oah_ifr_debug){\n//\t\t\tif (messageIn.type!=INIT && messageIn.type!=ACK && messageIn.type!=PART && messageIn.type!=END){\n//\t\t\t\tif(oah_ifr_debug)debug(\"Syntax error: Message Type. The message will be discarded.\");\n//\t\t\t\treturn false;\n//\t\t\t}\n//\t\t\tif (!(messageIn.msn>=0 && messageIn.msn<=99)){\n//\t\t\t\tif(oah_ifr_debug)debug(\"Syntax error: Message Sequence Number. The message will be discarded.\");\n//\t\t\t\treturn false;\n//\t\t\t}\n//\t\t\tif (!(messageIn.ack==0 || messageIn.ack==1)){\n//\t\t\t\tif(oah_ifr_debug)debug(\"Syntax error: ACK. The message will be discarded.\");\n//\t\t\t\treturn false;\n//\t\t\t}\n//\t\t\tif (!(messageIn.ackMsn>=0 && messageIn.ackMsn<=99)){\n//\t\t\t\tif(oah_ifr_debug)debug(\"Syntax error: ACK Message Sequence Number. The message will be discarded.\");\n//\t\t\t\treturn false;\n//\t\t\t}\n//\t\t}\n\t\treturn true;\n\t}", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === AppServicePlan.__pulumiType;\n }", "function check(...types) {\n for (const type of types) {\n if (type === currentToken().type) {\n return true;\n }\n }\n return false;\n }", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === DisasterRecoveryConfig.__pulumiType;\n }", "function isSecureServerRole(configuration) {\n if (configuration.serverRole.SecurityZone === 'Secure') return true;\n return false;\n}", "static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Key.__pulumiType;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find Location Id from Shared Key
function find_location_from_shared_key(shared_key){ var return_result="-1"; var locationSearchObj = search.create({ type: "location", filters: [ //["internalid","anyof",code], ["custrecord_tsa_iu_shared_key_loc", "is", shared_key], "AND", ["custrecord_tsa_loc_type", "is", 1] ], columns: [ search.createColumn({ name: "internalid", label: "Internal ID" }) ] }); log.debug("location_lookup::find_location_id_from_shared_key", "Looked up shared_key:"+shared_key); locationSearchObj.run().each(function (result) { log.debug("location_lookup::find_location_id_from_shared_key", "location internalid: " + result.getValue({ name: "internalid" })); return_result = result.getValue({ name: "internalid" }); return false; }); return return_result; }
[ "function getUrlEntry(key)\r\n{\r\n\tvar search=location.search.slice(1);\r\n\t//alert(search);\r\n\tvar my_id=search.split(\"&\");\r\n\t//alert(my_id);\r\n\ttry {\r\n\t\tfor(var i=0;i<my_id.length;i++)\r\n\t\t{\r\n\t\t\tvar ar=my_id[i].split(\"=\");\r\n\t\t\tif(ar[0]==key)\r\n\t\t\t{\r\n\t\t\t\treturn ar[1];\r\n\t\t\t}\r\n\t\t}\r\n\t} catch (e) {\r\n\t}\r\n\t\r\n\treturn null;\r\n}", "ComputeKeyIdentifier() {\n\n }", "findUniqueIdentifier() {\n const metadataId = this.attributes[\"unique-identifier\"];\n if (metadataId) {\n const uidMetadata = this.metadata.findItemWithId(\n \"dc:identifier\",\n metadataId\n );\n if (uidMetadata) {\n return uidMetadata.value;\n }\n }\n }", "function getPointId(uniqueId) {\n var markersCount = markers.length - 1;\n for (var j = markersCount; j > -1; j--) {\n if (markers[j].listId == uniqueId) {\n return j;\n }\n }\n}", "function getPairId(token0, token1){\r\n try {\r\n const jsonString = fs.readFileSync('./Output.json')\r\n const pairsJson = JSON.parse(jsonString)\r\n return pairsJson[\"pairs\"][token0][token1];\r\n } catch(err) {\r\n console.log('Error in getting the pair id', err)\r\n return\r\n }\r\n}", "function getClientKey() {\n\n }", "function hyperDbKeyToId (key) {\n var components = key.split('/')\n return components[components.length - 1]\n}", "get(key) {\n let index = this._hash(key);\n if (this.keyMap[index]) {\n for (let i = 0; i < this.keyMap[index].length; i++) {\n if (this.keyMap[index][i][0] === key) {\n return this.keyMap[index][i][1];\n }\n }\n }\n return undefined;\n }", "function remoteLookup (callback) {\n bo.runtime.sendMessage({\n type: \"remoteLookup\",\n payload: {\n // window.location.pathname.split('/')\n // Array(4) [ \"\", \"d\", \"1886119869\", \"Soccer\" ]\n // window.location.pathname.split('/')[2]\n // \"1886119869\"\n testId: window.location.pathname.split('/')[2]\n }\n }, callback);\n}", "function getStationId(stationName, bound) {\n\tvar stationIdCursor = Stops.find({\n\t\t\"stop_name\": stationName,\n\t\t\"platform_code\": bound\n\t},{\n\t\tfields: {\n\t\t\t\"stop_id\": 1\n\t\t}\n\t});\n\n\tvar stationIdFetched = stationIdCursor.fetch()\n\n\tif (stationIdFetched.length !== 0) {\n\t\tvar stationId = stationIdCursor.fetch()[0][\"stop_id\"];\n\t}\n\n\treturn stationId;\n}", "function getBasemapId(itemId) {\r\n var bmArray = basemapGallery.basemaps;\r\n for (var i = 0; i < bmArray.length; i++) {\r\n if (bmArray[i].itemId === itemId) {\r\n return bmArray[i].id;\r\n }\r\n }\r\n return false;\r\n}", "function getCodeFromKey(key) {\r\n //Constants for key\r\n if (key == STUDENT_INBOX_KEY) return 1;\r\n if (key == ADMIN_INBOX_KEY) return 2;\r\n if (key == STUDENT_SENT_ITEMS_KEY) return 3;\r\n if (key == ADMIN_SENT_ITEMS_KEY) return 4;\r\n}", "function getId(index) {\n\treturn cachedPinInfo[index].id;\n}", "function getPlatformId(){\n return getURLParameter('platform');\n}", "function getLocation (id, callback) {\n\tconsole.log(id);\n locationModel.findOne({ '_id': id }, function (err, location) {\n if (err) {\n callback(err);\n }\n callback(null, location);\n });\n}", "getLongId(orgId, shortId) {\n return __awaiter(this, void 0, void 0, function* () {\n //TODO: update the lastUsed\n try {\n const result = yield this.firestore.collection('org').doc(orgId).collection(ShortId_1.default.docName).doc(shortId).get();\n // tslint:disable-next-line\n if (util_1.isNullOrUndefined(result.data())) {\n return {\n type: AppProviderTypes_1.ResultType.ERROR,\n message: `No id mapping found for orgId: ${orgId}, shortId: ${shortId}.`\n };\n }\n //@ts-ignore\n const shortIdObj = ShortId_1.default.deserialize(result.data());\n return {\n type: AppProviderTypes_1.ResultType.SUCCESS,\n result: shortIdObj.longId,\n };\n }\n catch (err) {\n return {\n type: AppProviderTypes_1.ResultType.ERROR,\n message: err.message,\n };\n }\n });\n }", "function getStorageKey(listKey) {\n return AppInfoService.getLocalStoragePrefix() + Constants.STORAGE_KEY_MRU + '_' + listKey.toUpperCase();\n }", "function keyLookup(key) {\n if (key == 'i') {\n return 73\n } else if (key == 'o') {\n return 79\n } else if (key == 'p') {\n return 80\n } else {\n return 'Error(keyLookup): No key match!'\n }\n}", "peerKey(peer) {\n return peer.address + ':' + peer.port;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update plot limit indicator color
function update_plot_limit_indicator () { limit_indicator_color = "green"; // check if any selections are over plotting limit for (var k = 0; k < max_num_sel; k++) { if (selections.len_filtered_sel(k+1) > max_num_plots) { limit_indicator_color = "orange"; break; } } }
[ "_colorUpdate() {\n if(this.value){\n this.updateStyles({\n '--l2t-paper-color-indicator-icon': this.value,\n '--l2t-paper-color-indicator-icon-display': 'block',\n });\n } else {\n this.updateStyles({\n '--l2t-paper-color-indicator-icon': 'transparent',\n '--l2t-paper-color-indicator-icon-display': 'none',\n });\n }\n }", "function update_color_choosen_indicator(){\n r = red_slider.value;\n g = green_slider.value;\n b = blue_slider.value;\n choosen_color_indicator.style.backgroundColor = toRGB(r,g,b); \n}", "function setDrawingColor(event) {\n sketchController.color = this.value;\n}", "function refreshSwatch() {\nvar coloredSlider = $( \"#coloredSlider\" ).slider( \"value\" ),\ncurrentColor = getTheColor( coloredSlider );\nstrokeStyle = currentColor;\n\n$( \"#coloredSlider .ui-state-default, .ui-widget-content .ui-state-default\" ).css( \"background-color\", currentColor );\n}", "function update_indicators(i)\r\n{\r\n\r\n // how many plots are being displayed?\r\n var num_plots_displayed = plots_displayed[0] + plots_displayed[1] + plots_displayed[2];\r\n\r\n // if the user has rapidly clicked the difference button\r\n // we may get behind the actual display -- check if we need up date\r\n if (i >= num_plots_displayed) {\r\n return;\r\n }\r\n\r\n\t// update resolution indicator\r\n\ttoggle_resolution (i, plots_selected_resolution[i]);\r\n\r\n\t// update selection max indicator\r\n\tif (plots_selected_displayed[i] == 0)\r\n\t{\r\n\r\n\t\t// do not show display indicator\r\n\t\t$(\"#dac-plots-displayed-\" + (i+1)).hide();\r\n\t\t$(\"#dac-plots-not-displayed-\" + (i+1)).hide();\r\n\r\n\t}\r\n\telse if (limit_indicator_color == \"green\") {\r\n\r\n\t\t// all plots displayed\r\n\t\t$(\"#dac-plots-not-displayed-\" + (i+1)).hide();\r\n\t\t$(\"#dac-plots-displayed-\" + (i+1)).show();\r\n\r\n\t} else {\r\n\r\n\t\t// some plot not displayed\r\n\t\t$(\"#dac-plots-displayed-\" + (i+1)).hide();\r\n\t\t$(\"#dac-plots-not-displayed-\" + (i+1)).css(\"color\", limit_indicator_color);\r\n\t\t$(\"#dac-plots-not-displayed-\" + (i+1)).show();\r\n\r\n\t}\r\n}", "function update_brush_size_indicator(){\n choosen_brush_size_indicator.innerHTML = brush_size_slider.value + \"px\";\n}", "function drawMarkers(plot, ctx) {\n \"use strict\"\n var tmp, maxIndex;\n var xMin = plot.getOptions().xaxis.min;\n var xMax = plot.getOptions().xaxis.max;\n var px = plot.getAxes().xaxis;\n var py = plot.getAxes().yaxis;\n var canvas = $(plot.getCanvas());\n var ctx = canvas[0].getContext('2d'); \n var offset = plot.getPlotOffset();\n var radius = 10;\n var dx, dy; //coordinates of highest point\n var sx, sy; // coordinates of indicator shape\n var max; //maximum value of series at set timeframe\n //indicator dimensions\n var IND_HEIGHT = 24; \n var IND_WIDTH = 30;\n var textOffset_x = 0; //indicator text horizontal offset\n\n //draw indicator for each series \n $.each(plot.getData(), function (i, val) {\n tmp = splitArray(val.datapoints.points, val.datapoints.pointsize, xMax, xMin);\n //acquire the index of the highest value for each series\n maxIndex = tmp.y.indexOf(Math.max.apply(Math, tmp.y)); \n max = tmp.y[maxIndex];\n //transform data point x & y values to canvas coordinates\n dx = px.p2c(tmp.x[maxIndex]) + offset.left;\n dy = py.p2c(tmp.y[maxIndex]) + offset.top - 12;\n sx = dx + 2;\n sy = dy - 22;\n\n //draw indicator\n ctx.beginPath(); \n ctx.moveTo(sx, sy + IND_HEIGHT);\n ctx.lineTo(sx, sy + 30);\n ctx.lineTo(sx + 5, sy + IND_HEIGHT);\n ctx.closePath();\n ctx.fillStyle = val.color; \n\n //set horizontal text offset based on value. \n /*\n TODO:\n Make this more robust - base length adjustment on number of chars instead\n */\n if (max < 10) {\n textOffset_x = 12;\n }\n else if (max >= 10 && max < 100) {\n textOffset_x = 8;\n }\n else if (max >= 100 && max <= 1000) {\n textOffset_x = 4;\n }\n\n ctx.rect(sx,sy, IND_WIDTH, IND_HEIGHT);\n ctx.fillStyle = val.color; \n ctx.fill(); \n\n ctx.fillStyle = '#fff' \n ctx.font = '11pt Calibri';\n ctx.fillText(max, sx + textOffset_x ,sy + 16 ); \n });\n }", "function cycleDrawColour() {\n Data.Edit.Node.style.stroke = cycleColour(Data.Edit.Node.style.stroke);\n hasEdits(true);\n}", "function colourChange(){\n currentColour++;\n if(currentColour==colours.length)currentColour = 0;\n circle(context,halfWidth,halfHeight,step/2,true);\n}", "function plotlyDefaultColor(index){\n index = index%10;\n return plotlyColors[index];\n}", "function color_toggle() {\n console.log(counter);\n svg.selectAll(\"g\").remove();\n if (counter%2 == 0) {\n /* Color scheme from light blue to dark blue */\n color.range(d3.schemePuBu[9]);\n tract_counter -= 1;\n tract_toggle();\n } else {\n /* Color scheme from light yellow to dark red */\n color.range(d3.schemeOrRd[9]);\n tract_counter -= 1;\n tract_toggle();\n }\n counter += 1;\n return color;\n}", "refreshColorBarInfo() {\n if (this.colorBarRef.current) { // Only resets upon legend change given the app has been loaded and the colorBar is loaded up\n this.setColorBarColor(this.colorBarRef.current.state.color);\n }\n }", "function colorChanged(){\n\tsetGradientColor(lastDirection , rgbString(color1.value) , rgbString(color2.value) , true);\n}", "function resetAfterSuddenIntervalStop(){\n for(i = 0; i < barAmount; i++){\n intsToSortArray[i].changeColor(\"#8083c9\");\n }\n updateCanvas();\n}", "function controlChangeHandler () {\n setColours(this.value);\n }", "function setColorPickerListener() {\n document.getElementById(\"picker\").addEventListener(\"change\", function(){\n setCurrentColor(document.getElementById(\"picker\").value);\n changePoint (currentColor, document.getElementById(\"currentColor_r0c0\"), \"black\");\n });\n }", "function changeToRed(red){\n if (red >= 20000){\n $('#monthlyBudget').addClass('makeRed');\n }\n }", "addColorScaleMember() {\n const state = this.state;\n state.configuration.charts[0].colorScale.push('');\n this.setState(state);\n this.props.onConfigurationChange(state.configuration);\n }", "drawCountryColorChart(count, max) {\n\n info(\"worldmap : masking (colorChart)\")\n const [enterSel, updateSel, mergeSel, exitSel] = this.D3.mkSelections(\n this.g.selectAll(\"path\"), this.outlineData.features, \"path\")\n exitSel.remove()\n\n function cname(countryFeature) {\n return matchCountryNames(countryFeature[\"properties\"][\"sovereignt\"].toLowerCase())\n }\n\n mergeSel\n .attr(\"d\", this.path)\n .attr(\"fill\", (features) => {\n const frac = count.getOrElse(cname(features), 0) / max;\n return this.countriesColorPalette(frac)\n })\n .on('mouseover', (features) => eventOnMouseOver(features, this.tooltip, cname(features) + \":\\n\" + count.getOrElse(cname(features), 0) + \" events reported\"))\n .on('mouseout', (d) => eventOnMouseOut(d, this.tooltip))\n\n this.colorchartShown = true;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a given robot is sending you radio.
isRadioing(robot) { return robot.signal >= 0; }
[ "sendForm() {\n\t\tlet rand = Math.floor(Math.random() * 101);\n\t\tif(rand <= 70) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}", "function subcommable(action, send) {\n if (structEquiv(action.chan, send.chan)) {\n return patternMatch(action.pattern, send.message);\n }\n\n return false;\n}", "function isOnPatrolRoute(robot) {\n for (let i = 0; i < ROUTE_PATROL.length; ++i) {\n if (robot.r === ROUTE_PATROL[i].r && robot.c === ROUTE_PATROL[i].c) {\n return true;\n }\n }\n return false;\n}", "function anyRadioButtonsUnchecked()\n{\n\tvar traceChecked = radChecked(\"#traceYes\") || radChecked(\"#traceNo\");\n\tvar handChecked = radChecked(\"#chooseLeft\") || radChecked(\"#chooseRight\");\n\t\n\treturn traceChecked == false || handChecked == false;\n}", "static check_connected(data) {\n if (data == \"False\") {\n // Send notification error\n bulmaToast.toast({\n message: \"Could not connect to printer... <a onclick=\\\"COM.reconnect_printer()\\\">Retry?</a>\",\n type: \"is-danger\",\n position: \"bottom-right\",\n dismissible: true,\n closeOnClick: false,\n duration: 99999999,\n animate: { in: \"fadeInRight\", out: \"fadeOutRight\" }\n });\n return\n } else if (data == \"True\") {\n // Send notification success\n bulmaToast.toast({\n message: \"Printer connected successfully!\",\n type: \"is-success\",\n position: \"bottom-right\",\n dismissible: true,\n closeOnClick: false,\n duration: 4000,\n animate: { in: \"fadeInRight\", out: \"fadeOutRight\" }\n });\n return\n }\n\n // If no data, ask backend if grbl is connected\n console.log(\"Checking printer connection...\")\n WS.ws.send(COM.payloader(\"RQV\", \"grbl\"))\n }", "isLocalOnHold() {\n if (this.state !== CallState.Connected) return false;\n if (this.unholdingRemote) return false;\n let callOnHold = true; // We consider a call to be on hold only if *all* the tracks are on hold\n // (is this the right thing to do?)\n\n for (const tranceiver of this.peerConn.getTransceivers()) {\n const trackOnHold = ['inactive', 'recvonly'].includes(tranceiver.currentDirection);\n if (!trackOnHold) callOnHold = false;\n }\n\n return callOnHold;\n }", "function isSensor(raddec) {\n let foundSensorPacket = false;\n let hasPackets = (raddec.hasOwnProperty('packets') &&\n (raddec.packets.length > 0));\n\n if(hasPackets) {\n raddec.packets.forEach(function(packet) {\n if(isSensorPacket(packet)) {\n foundSensorPacket = true;\n }\n });\n }\n\n return foundSensorPacket;\n}", "checkWin() {\nif all bgWLand|| or wgBLand\n}", "function checkBabyBot(words){\n return words.includes(\"@\" + configs.bot.username)\n || words.includes(\"@pete_bot_\")\n || words.includes(\"@pete_bot\")\n || words.includes(\"pete_bot\")\n || words.includes(\"pete_bot_\")\n || words.includes(\"pete_bot__\")\n || words.includes(\"@pete_bot_\")\n || words.includes(\"@Pete_Bot_\")\n || words.includes(\"@Pete_bot_\")\n || words.includes(\"Pete_Bot_\")\n || words.includes(\"Pete_bot_\")\n}", "function callsHarlan(message) {\n try {\n return message.text.toLowerCase().indexOf('check your tone') > -1\n}\ncatch(e) {\n return console.log(e)//throw error in console for verification\n }\n}", "function isMessageFromOpponent(data)\n{\n // Is it from our opponent and is it intended for us?\n return (data.payload.sender == g_remote_uuid && data.payload.target == g_local_uuid);\n}", "function check_potentiometer(reading) {\n\t\tpotentiometer_check = Math.floor(reading.value * 100);\n\t\tif (potentiometer_reading != potentiometer_check\n\t\t\t\t\t\t\t\t && !isNaN(potentiometer_check)){\n\t\t\tpotentiometer_reading = potentiometer_check;\n\t\t\tsocket.emit(\"potentiometer\", potentiometer_check);\n\t\t}\n\t}", "function isSensorPacket(packet) {\n let isMinew = (packet.substr(26,4) === 'e1ff');\n let isCodeBlue = (packet.substr(24,6) === 'ff8305');\n if(isMinew) {\n let isTemperatureHumidity = (packet.substr(38,4) === 'a101');\n let isVisibleLight = (packet.substr(38,4) === 'a102');\n let isAcceleration = (packet.substr(38,4) === 'a103');\n if(isTemperatureHumidity || isVisibleLight || isAcceleration) {\n return true;\n }\n }\n if(isCodeBlue) {\n let isPuckyActive = (packet.substr(30,2) === '02');\n return isPuckyActive;\n }\n\n return false;\n}", "inChannel() {\n return this.current_voice_channel_id != null;\n }", "function check_is_bot(message) {\n // Step 1: remove all the weird characters\n const char_replace = { '1': 'l', '2': 'z', '3': 'e', '4': 'a', '5': 's', '6': 'b', '7': 't', '9': 'g', '0': 'o' };\n const noramlized = message\n // we decompose the message, so 'w̸̢͛' becomes [ \"w\", \"̸\", \"̢\", \"͛\" ]\n .normalize(\"NFD\").split('')\n // this is in case the bot uses substitution, e.g. 13375p34k => leetspeak\n .map(c => { if (c in char_replace) { return char_replace[c]; } else { return c; } })\n // we only care about the alphabetic characters, remove everything else\n .filter(c => c.match(/[a-zA-Z]/))\n // turn the message back into a string\n .join('').toLowerCase();\n\n // Step 2: check if the message is from the bot\n // we check if the message has these substrings:\n // - big follows com\n // - Buy followers, primes and viewers\n // we use substring_distance and a threshold, so we can also detect it if the bot makes \"typos\"\n // e.g. we also detect \"big follow com\", or \"bgi folows com\"\n var similarity = substring_distance('bigfollowscom', noramlized);\n similarity += substring_distance('buyfollowersprimesandviewers', noramlized);\n const similarity_threshold = 3;\n return (similarity <= similarity_threshold);\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 }", "attemptLike() {\n this.log('waiting for buttons...');\n\n this.waitForButtons(() => {\n /*\n If the video is already liked/disliked\n or the user isn't subscribed to this channel,\n then we don't need to do anything.\n */\n if (this.isVideoRated()) {\n this.log('video already rated');\n return this.stop();\n }\n if (this.options.like_what === 'subscribed' && !this.isUserSubscribed()) {\n this.log('user not subscribed');\n return this.stop();\n }\n\n this.cache.likeButton.click();\n this.log('like button clicked');\n this.stop();\n });\n }", "_getAVRMuteStatus() {\n this._MuteCommand( \"mute_request\" ) ;\n }", "function isResponsible(person) {\n\t\treturn ((person.status === \"single\" || \n\t\t\t\t person.name === \"Eko\") ? false : true);\n\t}", "function checkIfMyTurn() {\n console.log(\"in checkIfMyTurn...\");\n if (vm.currentGame.gameInProgress) {\n if ((vm.playerTeam === \"x\") && (vm.currentGame.turn) && (vm.playerName === vm.currentGame.player1) ||\n (vm.playerTeam === \"o\") && (!vm.currentGame.turn) && (vm.playerName === vm.currentGame.player2)){\n return true;\n }\n }\n return false;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new account item in Monday
async function createMondayAccount(account) { console.log('Creting new Monday account:', account.Name) await monday.createItem(boardId, account.Id, { Name: () => account.Name, Phone: () => account.Phone, }) }
[ "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 }", "function add_saturday()\n{\n\tvar name = validate_name( 'saturday_name', 'Saturday Night Social' );\n\tif( ! name )\n\t{\n\t\treturn;\n\t}\n\n\tvar socializer = {};\n\tsocializer.amount = 95;\n\tsocializer.item_name = saturday_id;\n\tsocializer.on0 = saturday_name_code;\n\tsocializer.os0 = name;\n\tsocializer.tax_rate = 13;\n\n\tcart_contents.push( socializer );\n\trebuild_cart();\n}", "@action\n newEntryAction() {\n this.set('newEntry', this.store.createRecord('timesheet-missing', {\n person_id: this.person.id,\n position_id: this.positions.firstObject.id\n }));\n }", "function createAccount (account) {\r\n accounts.push(account);\r\n return account;\r\n}", "function createAlarm() {\n\n // default delay of 60 seconds\n var userDelay = 60;\n\n if (userInput() != '') {\n userDelay = parseInt(userInput());\n }\n\n var alarmInfo = {\n delayInMinutes: userDelay,\n periodInMinutes: userDelay\n }\n\n chrome.alarms.create(alarmName, alarmInfo);\n chrome.notifications.create('reminder', {\n type: 'basic',\n iconUrl: 'img/icon_128.png',\n title: 'Info:',\n message: 'Die Erinnerungen sind jetzt aktiviert!'\n }, function(notificationId) {});\n }", "function createAccount(account, masterPassword){\r\nvar accounts = getAccounts(masterPassword);\r\naccounts.push(account);\r\n\r\n}", "async function createDefaultWallets (account: EdgeAccount, fiatCurrencyCode: string, dispatch: Dispatch) {\n // TODO: Run these in parallel once the Core has safer locking:\n await safeCreateWallet(account, 'wallet:bitcoin', s.strings.string_first_bitcoin_wallet_name, fiatCurrencyCode, dispatch)\n await safeCreateWallet(account, 'wallet:bitcoincash', s.strings.string_first_bitcoincash_wallet_name, fiatCurrencyCode, dispatch)\n await safeCreateWallet(account, 'wallet:ethereum', s.strings.string_first_ethereum_wallet_name, fiatCurrencyCode, dispatch)\n\n dispatch(trackAccountEvent('SignupWalletsCreated'))\n}", "function workOrderCreate() {\n // Define the data object and include the needed parameters.\n // Make the Create API call and assign a callback function.\n}", "function submitForm(){\n let form = document.querySelector(Form.id);\n let appointment = Object.create(Appointment);\n appointment.who = form.querySelector(\"[name=who]\").value;\n appointment.about = form.querySelector(\"[name=about]\").value;\n appointment.agenda = form.querySelector(\"[name=agenda]\").value;\n let day = form.querySelector(\"[name=day]\").value;\n appointment.day = day;\n // Create a random id if it is a new appointment\n appointment.id = form.querySelector(\"[name=id]\").value || \n 'appointment-'+\n form.querySelector(\"[name=day]\").value+'-'+\n (1+Math.random()).toString(36).substring(7)\n ;\n Calendar.appointments[day] = appointment;\n closeForm();\n showNewAppointment(appointment);\n showMessage(\"Success\", \"Your appointment has been sucessfully saved.\");\n}", "function createDayEntry() {\n return connect().then(({ collection, client}) => {\n return new Promise((resolve, reject) => {\n let date = new Date();\n let datum = ('0' + date.getDate()).slice(-2) + '.' + ('0' + (date.getMonth() + 1)).slice(-2) + '.' + date.getFullYear();\n collection.findOne({\"dateWithoutTime\": datum}, async (err, res) => {\n if(err) {\n reject(err);\n } else if(res === null) {\n let day = new Day(date);\n await collection.insertOne(day, { safe: true }, (error, result) => {\n if(error) {\n reject(error);\n } else {\n resolve(result);\n }\n });\n } else {\n reject();\n }\n client.close();\n });\n });\n });\n}", "function createDay(week, date) { //TODO: remove week from parameters\n\tvar daySchedule = Parser.getSchedule(date);\n\t\n\t//TODO repeated code from Parser.getSchedule()\n\tvar dateString = date.getMonth().valueOf()+1 + \"/\" + date.getDate().valueOf() + \"/\" + date.getFullYear().toString().substr(-2);\n\t\n\tvar col = week.insertCell(-1);\n\tcol.date = date.valueOf(); //store date in cell element\n\t\n\tif(date.getMonth()==9 && date.getDate()==31) //check Halloween\n\t\tcol.classList.add(\"halloween\");\n\t\n\tvar head = document.createElement(\"div\");\n\thead.classList.add(\"head\");\n\tvar headWrapper = document.createElement(\"div\");\n\theadWrapper.classList.add(\"headWrapper\");\n\theadWrapper.innerHTML = DAYS_OF_WEEK[date.getDay()] + \"<div class=\\\"headDate\\\">\" + dateString + \"</div>\";\n\thead.appendChild(headWrapper);\n\tcol.appendChild(head);\n\t\n\tvar prevEnd = \"8:00\"; //set start of day to 8:00AM\n\t\n\tfor(var i=0;i<daySchedule.length;i++) {\n\t\tvar periodObj = daySchedule[i];\n\t\tvar passing = $(\"<div>\").addClass(\"period\");\n\n\t\tvar period = $(\"<div>\", { class: \"period\" });\n\t\t\n\t\tif(opts.showPassingPeriods) {\n\t\t\tpassing.append(Period.createPeriod(\"\",prevEnd,periodObj.start,date));\n \t\t col.appendChild(passing.get(0));\n\t\t\tprevEnd = periodObj.end;\n\t\t}\n\t\t\n\t\tperiod.append(periodObj.getHTML(date));\n\t\t\t\n\t\tcol.appendChild(period.get(0));\n\t}\n}", "async function createOrUpdateScheduledActionByScope() {\n const scope = \"subscriptions/00000000-0000-0000-0000-000000000000\";\n const name = \"monthlyCostByResource\";\n const ifMatch = \"\";\n const scheduledAction = {\n displayName: \"Monthly Cost By Resource\",\n fileDestination: { fileFormats: [\"Csv\"] },\n kind: \"Email\",\n notification: {\n subject: \"Cost by resource this month\",\n to: [\"user@gmail.com\", \"team@gmail.com\"],\n },\n schedule: {\n daysOfWeek: [\"Monday\"],\n endDate: new Date(\"2021-06-19T22:21:51.1287144Z\"),\n frequency: \"Monthly\",\n hourOfDay: 10,\n startDate: new Date(\"2020-06-19T22:21:51.1287144Z\"),\n weeksOfMonth: [\"First\", \"Third\"],\n },\n status: \"Enabled\",\n viewId: \"/providers/Microsoft.CostManagement/views/swaggerExample\",\n };\n const options = {\n ifMatch,\n };\n const credential = new DefaultAzureCredential();\n const client = new CostManagementClient(credential);\n const result = await client.scheduledActions.createOrUpdateByScope(\n scope,\n name,\n scheduledAction,\n options\n );\n console.log(result);\n}", "function createTask(){\n\n let title = document.getElementById(\"new-task-title\").value;\n let description = document.getElementById(\"new-task-description\").value;\n let due = document.getElementById(\"new-task-due\").value;\n\n if(!emptyValues(title, description, due)){\n let task = {\n title,\n description,\n due,\n created : new Date()\n }\n tasks++;\n\n //success, insert created task into DOM\n insertTask(task);\n displayPopupMessage(\"Gjøremål opprettet\");\n displayListSection();\n\n }else{\n\n //error, user input not valid\n displayPopupMessage(\"Alle felter må fylles ut.\", false);\n }\n}", "async function addSchedule(ctx) {\n const { usernamect, availdate} = ctx.params;\n try {\n const sqlQuery = `INSERT INTO parttime_schedules VALUES ('${usernamect}', '${availdate}')`;\n await pool.query(sqlQuery);\n ctx.body = {\n 'username_caretaker': usernamect,\n 'availdate': availdate\n };\n } catch (e) {\n console.log(e);\n ctx.status = 403;\n }\n}", "function createAccount()\n{\n let nameRef = document.getElementById(\"name\");\n let emailIdRef = document.getElementById(\"emailId1\");\n let password1Ref = document.getElementById(\"password1\");\n let password2Ref = document.getElementById(\"password2\");\n if(password1Ref.value == password2Ref.value)\n {\n accounts.addAccount(emailIdRef.value);\n let user = accounts.getAccount(accounts.count - 1); //to get the last account\n user.name = nameRef.value;\n user.password = password1Ref.value;\n if (getDataLocalStorageTrip() != undefined)\n {\n let trip = getDataLocalStorageTrip();\n user.addTrip(trip._tripId);\n //subtracting -1 to access the last trip\n user.getTripIndex(user._trips.length -1)._country = trip._country;\n user.getTripIndex(user._trips.length -1)._date = trip._date;\n user.getTripIndex(user._trips.length -1)._start = trip._start;\n user.getTripIndex(user._trips.length -1)._end = trip._end;\n user.getTripIndex(user._trips.length -1)._stops = trip._stops;\n trip = \"\"; //to clear the trip local data\n updateLocalStorageTrip(trip);\n }\n updateLocalStorageUser(user)\n updateLocalStorageAccount(accounts); //updating the new accounts array into the local storage\n alert(\"Account created successfully\");\n window.location = \"index.html\"; \n }\n else\n {\n alert(\"ERROR! Password does not match\");\n }\n}", "async function okCreateShift() {\n if (userRole === \"Admin\") {\n try {\n let thisShift = undefined;\n let newStart = startTimeInput.value;\n let newEnd = endTimeInput.value;\n let startDate = new Date(SelectedDate + \"T\" + newStart + \"Z\");\n let endDate = new Date(SelectedDate + \"T\" + newEnd + \"Z\");\n let newEmployee = undefined;\n let update = createUpdate(thisShift, startDate, endDate, newEmployee);\n updates.push(update);\n ShiftModalCloseAction();\n saveButtonEnable();\n alert(\"Vagten er nu oprettet! Tryk gem for at tilføje vagten\");\n } catch (e) {\n console.log(e.name + \": \" + e.message);\n }\n }\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}", "function cronJobCreateForm() {\n log(COL_TIMESTAMP, new Date())\n // Check for scheduled lessons from Wed to Wed\n var from = new Date();\n from.setDate(from.getDate() - from.getDay() + 3); // Get Wednesday of current week\n Logger.log('from %s', from.toString())\n var until = new Date(from);\n until.setDate(from.getDate() + 7); // Get a week from 'from' date\n Logger.log('until %s', until.toString());\n var dates = getScheduledDates(from, until);\n if (dates.length == 0) {\n log(COL_DATESTRING, '(not scheduled)');\n return;\n } else {\n log(COL_DATESTRING, dates2Str(dates, DATES_DELIMITER));\n }\n // Create form\n createForm(dates);\n}", "function subtest_can_switch_to_existing_email_account_wizard(w) {\n plan_for_window_close(w);\n plan_for_new_window(\"mail:autoconfig\");\n\n // Click on the \"Skip this and use my existing email\" button\n mc.click(new elib.Elem(w.window.document.querySelector(\".existing\")));\n\n // Ensure that the Account Provisioner window closed\n wait_for_window_close();\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For each key, find its consecutive file name of the sound
function findFilePath (key) { let filePath = "sounds/" switch (key) { case "w": filePath += "tom-1.mp3" break; case "a": filePath += "tom-2.mp3" break; case "s": filePath += "tom-3.mp3" break case "d": filePath += "tom-4.mp3" break; case "j": filePath += "snare.mp3" break; case "k": filePath += "crash.mp3" break; case "l": filePath += "kick-bass.mp3" break; default: filePath = null; } return filePath; }
[ "function getAudioFileName(key) {\n\n var fileName = \"sounds/\";\n\n switch(key) {\n case 'w': fileName += \"tom-1\"; break;\n case 'a': fileName += \"tom-2\"; break;\n case 's': fileName += \"tom-3\"; break;\n case 'd': fileName += \"tom-4\"; break;\n case 'j': fileName += \"snare\"; break;\n case 'k': fileName += \"crash\"; break;\n case 'l': fileName += \"kick-bass\"; break;\n }\n\n return fileName + \".mp3\";\n}", "function get_sounds(message){\r\n var files = fs.readdirSync('./sounds/');\r\n var names = \"```fix\\n\";\r\n files.forEach(file => {\r\n names = names.concat(file).concat('\\n');\r\n });\r\n names = names.concat(\"```\");\r\n message.channel.send(names);\r\n}", "async getFile(key) {\n const self = this;\n await U.waitUntil(() => self.made);\n return Path.join(self.directory, Value.encodeValue(key).toString('hex'));\n }", "function getShipMapKeyFromFileName(filename)\r\n{\r\n return \"_\" + filename.match(/-(.*)Shipyard/)[1]\r\n}", "function makeSound(key){\n //this switch statement takes in a single key character as input\n //then assigns the specific listener function to the diff event keys\n switch (key) {\n case 'w':\n var tom1 = new Audio(\"sounds/tom-1.mp3\");\n tom1.play();\n break;\n\n case 'a':\n var tom2 = new Audio(\"sounds/tom-2.mp3\");\n tom2.play();\n break;\n\n case 's':\n var tom3 = new Audio(\"sounds/tom-3.mp3\");\n tom3.play();\n break;\n\n case 'd':\n var tom4 = new Audio(\"sounds/tom-4.mp3\");\n tom4.play();\n break;\n\n case 'j':\n var snare = new Audio(\"sounds/snare.mp3\");\n snare.play();\n break;\n\n case 'k':\n var crash = new Audio(\"sounds/crash.mp3\");\n crash.play();\n break;\n\n case 'l':\n var kick = new Audio(\"sounds/kick-bass.mp3\");\n kick.play();\n break;\n\n default: console.log(buttonInnerHTML); //just showing which button triggered default case\n\n }\n}", "getByKey(key) {\n key = this.normalizePath(key);\n var result = this.loadedScreensavers.find((obj) => {\n return obj.key === key;\n });\n return result;\n }", "fileName(playlist) {\n\t\treturn playlist.name.replace(/[^a-z0-9\\- ]/gi, '').replace(/[ ]/gi, '_').toLowerCase();\n\t}", "function findSoundAndPlay(message, channelID, userID){\n\tvar group_found = false,\n\tfound = false,\n\tsound_found = false,\n\tsound_path = sound_root, \n\tbase_group = sound_list, \n\tsounds_group, sounds_final,\n\tcur, names;\n\n\tvar requestMessage = message;\n\trequestMessage = requestMessage.split(\" \");\n\trequestMessage.shift();\n\n\t//request a group folder\n\tif(requestMessage.length > 0){\n\t\t//if the request is invalid\n\t\tif(isKeyPresent(base_group, requestMessage[0])){\n\t\t\t//requested key is present, go go\n\t\t\tgroup_found = true;\n\t\t\tsounds_group = base_group[requestMessage[0]];\n\n\t\t\t//check if the second param is here\n\t\t\t//if not we skip down and pick at random\n\t\t\tif(requestMessage.length > 1){\n\t\t\t//console.log(\"Trying \" + requestMessage[1]);\n\t\t\tvar keys = Object.keys(sounds_group);\n\t\t\tvar i, j;\n\t\t\t//loop through keys\n\t\t\tfor(i=0; i<keys.length && (!found); i+=1){\n\t\t\t\tcur = sounds_group[keys[i]];\n\t\t\t\tnames = cur.aliases;\n\t\t\t\t//loop through aliases\n\t\t\t\tfor(j=0; j<names.length && (!found); j+=1){\n\t\t\t\t\tif(requestMessage[1] === names[j]){\n\t\t\t\t\t\tsound_path = cur.path;\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tsound_found = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n\n\t//If the lookup failed at the group level, or sound level, we catch and remediate here\n\n\t//if we failed to match the group get one at random\n\t//this will be fed to establishing the sound clip\n\tif(group_found == false){\n\t\t\t//pick a random group and random folder\n\t\t\t//get a random group from sounds\n\t\t\tsounds_group = base_group[pickRandomKey(base_group)];\n\t\t\tgroup_found = true;\n\t}\n\n\t//if we failed to match the sound we get one here at random...\n\t//sounds_group is guaranteed to be established by now either at random or by choice.\n\tif(sound_found == false){\n\t\t\t//get a random sounds from group\n\t\t\tsounds_final = sounds_group[pickRandomKey(sounds_group)];\n\t\t\t//append to the static sound_root\n\t\t\tsound_path = sounds_final.path;\n\t\t\tsound_found = true;\n\t}\n\n\tconsole.log(sound_path);\n\tplayAudioFromUserID(channelID, userID, sound_path);\n}", "function createGuitarSoundArray() {\n var sound_srcs = [\n [ // String 1\n \"sound_files/guitar/1_0_E3.mp3\", // String 1, Fret 0\n \"sound_files/guitar/1_1_F3.mp3\", // String 1, Fret 1\n \"sound_files/guitar/1_2_Fs3.mp3\", // ...\n \"sound_files/guitar/1_3_G3.mp3\",\n \"sound_files/guitar/1_4_Gs3.mp3\"\n ],\n [ // String 2\n \"sound_files/guitar/2_0_A3.mp3\",\n \"sound_files/guitar/2_1_As3.mp3\",\n \"sound_files/guitar/2_2_B3.mp3\",\n \"sound_files/guitar/2_3_C4.mp3\",\n \"sound_files/guitar/2_4_Cs4.mp3\"\n ],\n [ // String 3\n \"sound_files/guitar/3_0_D4.mp3\",\n \"sound_files/guitar/3_1_Ds4.mp3\",\n \"sound_files/guitar/3_2_E4.mp3\",\n \"sound_files/guitar/3_3_F4.mp3\",\n \"sound_files/guitar/3_4_Fs4.mp3\"\n ],\n [ // String 4\n \"sound_files/guitar/4_0_G4.mp3\",\n \"sound_files/guitar/4_1_Gs4.mp3\",\n \"sound_files/guitar/4_2_A4.mp3\",\n \"sound_files/guitar/4_3_As4.mp3\",\n \"sound_files/guitar/4_4_B4.mp3\"\n ],\n [ // String 5\n \"sound_files/guitar/5_0_B4.mp3\",\n \"sound_files/guitar/5_1_C5.mp3\",\n \"sound_files/guitar/5_2_Cs5.mp3\",\n \"sound_files/guitar/5_3_D5.mp3\",\n \"sound_files/guitar/5_4_Ds5.mp3\"\n ],\n [ // String 6\n \"sound_files/guitar/6_0_E5.mp3\",\n \"sound_files/guitar/6_1_F5.mp3\",\n \"sound_files/guitar/6_2_Fs5.mp3\", // ...\n \"sound_files/guitar/6_3_G5.mp3\", // String 6, Fret 3\n \"sound_files/guitar/6_4_Gs5.mp3\" // String 6, Fret 4\n ]\n ];\n\n return sound_srcs;\n}", "function CreateSoundFileURL(){\n\n //******************************\n //START DEFINE SOUNDS FILE URLS FOR S3\n //******************************\n\n//Patterns to construct sound file URL\n//Use enharmonics to reduce number of files needed\n\n//Contains sound file URLs for files stored on Amazon S3\n const pitchS3EndUrl = {\n C: {\n doubleflat: '/Bflat.mp3',\n flat: '/B.mp3',\n natural: '/C.mp3',\n sharp: '/Csharp.mp3',\n doublesharp: '/D.mp3'\n },\n \n D: {\n doubleflat: '/C.mp3',\n flat: '/Csharp.mp3',\n natural: '/D.mp3',\n sharp: '/Eflat.mp3',\n doublesharp: '/E.mp3'\n },\n E: {\n doubleflat: '/D.mp3',\n flat: '/Eflat.mp3',\n natural: '/E.mp3',\n sharp: '/F.mp3',\n doublesharp: '/Fsharp.mp3'\n },\n F: {\n doubleflat: '/Eflat.mp3',\n flat: '/E.mp3',\n natural: '/F.mp3',\n sharp: '/Fsharp.mp3',\n doublesharp: '/G.mp3'\n },\n G: {\n doubleflat: '/F.mp3',\n flat: '/Fsharp.mp3',\n natural: '/G.mp3',\n sharp: '/Aflat.mp3',\n doublesharp: '/A.mp3'\n },\n A: {\n doubleflat: '/G.mp3',\n flat: '/Aflat.mp3',\n natural: '/A.mp3',\n sharp: '/Bflat.mp3',\n doublesharp: '/B.mp3'\n },\n B: {\n doubleflat: '/A.mp3',\n flat: '/Bflat.mp3',\n natural: 'B',\n sharp: '/C.mp3',\n doublesharp: '/Csharp.mp3'\n }\n};\n //******************************\n //END DEFINE SOUNDS FILE URLS FOR S3 AND SOUNDCLOUD\n //******************************\n\n\n //Construct audio file URL.\n //If vibrato requested add 'v' to end of URL\n if (objNotePackage.Vibrato=='vibrato') {\n //Check for A440 special case\n if (['4', '40'].indexOf(objNotePackage.accidental) === -1){\n objNotePackage.audioUrl = S3_BASE_URL + 'audio/' + pitchS3EndUrl[objNotePackage.pitch][objNotePackage.multiplier + objNotePackage.accidental] +'v.mp3';\n }\n else {\n objNotePackage.audioUrl = S3_BASE_URL + 'audio/A440v.mp3';\n }\n\n }\n else {\n //Check for A440 special case\n if (['4', '40'].indexOf(objNotePackage.accidental) === -1){\n objNotePackage.audioUrl = S3_BASE_URL + 'audio/' + pitchS3EndUrl[objNotePackage.pitch][objNotePackage.multiplier + objNotePackage.accidental] +'.mp3';\n }\n else {\n objNotePackage.audioUrl = S3_BASE_URL + 'audio/A440.mp3';\n }\n }\n \n\n return; //No data is returned\n}", "function getFileName(index, name) {\n return index.file[index.namemap.indexOf(name)];\n}", "function influxKey(key, type) {\n var k = key.split(',');\n\n var name = k.shift();\n var tags = k;\n\n return name + '.' + type + (tags.length > 0 ? ',' + tags.join(',') : '')\n}", "static findCharactersWithSingleSound(characters) {\n return _.select(characters, char => { \n return Canigma.findSoundsByCharacter(char).length == 1;\n });\n }", "static findCharactersBySound(sound) {\n return SoundToCharacters[sound];\n }", "static async getFirstAssetFromKeyPrefix(ctx, assetType, assetKeyPrefix) {\n\t\t//Get iterator of assets based on asset type partial composite key provided\n\t\tlet assetIterator = await PharmanetHelper.getAssetIterator(ctx,pharmaNamespaces[assetType],assetKeyPrefix);\n\t\tlet asset = await assetIterator.next();\n\n\t\t//If there are no assets for given key then iterator will have no results\n\t\t//Thus accessing next() result from iterator will give only done status\n\t\t//If next() returns value then at least one asset is existing with given partial key prefix\n\t\tlet assetValue = asset.value;\n\t\t\n\t\t//Close the iterator if matching assets are existing, if not then iterator is already closed by this point\n\t\tif(assetValue){\n\t\t\tawait assetIterator.close();\n\t\t}\n\n\t\treturn assetValue;\n\t}", "function probeFileName(dir, marker) {\n return path.join(dir, marker + \".scythe_probe\");\n}", "function getFilePath(journey_id, saveDate){\n\treturn journey_id + '_' + saveDate + '.wav';\n}", "function randomKeyboardSound(){\n let i=Math.floor(Math.random()*5)+1;\n let audiokeyboard=new Audio('assets/audio/sounds/keyb' + i + '.mp3');\n audiokeyboard.play();\n}", "static findSoundsByCharacter(character) {\n return CharacterToSounds[character];\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks to see if a target is one of the cells in the puzzle matrix
function isCell(target) { return target.tagName === "INPUT" && target.classList.length && target.classList[0] === 'sudoku-input'; }
[ "isValidMoveNew(row, column) {\n if (!isInBoundaries(row, column)) {\n return false;\n }\n if (!this.tileSet.hasTileAt(row, column)) {\n return false;\n }\n var dx = [1, 0, -1, 0];\n var dy = [0, 1, 0, -1];\n let thisTile = this.tileSet.getTileAt(row, column);\n for (var i = 0; i < 4; ++i) {\n // if the given cell's i'th neighbour has the same color as this\n // cell, then this move is valid\n var neighbourTile = this.tileSet.getTileAt(row + dx[i], column + dy[i]);\n if (thisTile.equalTo(neighbourTile)) {\n return true;\n }\n }\n // if we have not found any neighbours with the same color, then the\n // move is not valid\n return false;\n }", "function colCheck(puzzle) {\n for (var c = 0; c < puzzle.length; c++) {\n if(checkColumn(puzzle,c) == false) return false;\n }\n return true;\n}", "function checkSolution() {\r\n if (tileMap.empty.position !== 3) {\r\n return false;\r\n }\r\n\r\n for (var key in tileMap) {\r\n if (key == 1 || key == 9) {\r\n continue;\r\n }\r\n\r\n var prevKey = key == 4 ? 'empty' : key == 'empty' ? 2 : key - 1;\r\n if (tileMap[key].position < tileMap[prevKey].position) {\r\n return false;\r\n }\r\n }\r\n\r\n // Clear history if solved\r\n history = [];\r\n return true;\r\n }", "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}", "isPossible(row, col) {\n\n // ROW CHECK\n for (let i = 0; i < col; i++)\n if (this.board[row][i])\n return false\n\n // DIAGONAL DOWN\n for (let i = row, j = col; i >= 0 && j >= 0; i--, j--)\n if (this.board[i][j])\n return false\n\n // DIAGONAL UP\n for (let i = row, j = col; j >= 0 && i < this.size; i++, j--)\n if (this.board[i][j])\n return false\n\n return true;\n }", "hasDuplicatedTargets () {\n return this.targets.some((target, position) => {\n return this.targets.indexOf(target) !== position;\n })\n }", "function checkAdjacentTiles(x1, y1) {\n if((x1>=0)&&(y1>=0)&&(x1<columns)&&(y1<rows)) //Verify if coordinates do not fall outside of the gridMatrix.\n return gridMatrix[x1+y1*columns];\n}", "function isAt(x, y){\n for(var i = 0; i < tileArray.length; i++){\n if(tileArray[i]._x == x && tileArray[i]._y == y){\n return true;\n }\n }\n return false;\n }", "isSingleCell() {\n return this.fromRow == this.toRow && this.fromCell == this.toCell;\n }", "function checkGrid(board, y, x, num) {\n\tconst baseX = 3 * Math.floor(x / 3);\n\tconst baseY = 3 * Math.floor(y / 3);\n\n\tfor (let i = 0; i < 3; i++) {\n\t\tfor (let j = 0; j < 3; j++) {\n\t\t\tif (!(j + baseY == y && i + baseX == x) && board[j + baseY][i + baseX] == num) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true;\n}", "hasSumInARow(x,y,targetCount){\r\n return (this.north(x, y, 1,targetCount) || this.northEast(x, y, 1,targetCount) || this.east(x, y, 1,targetCount) || this.southEast(x, y, 1,targetCount) || this.south(x, y, 1,targetCount) || this.southWest(x, y, 1,targetCount) || this.west(x, y, 1,targetCount) || this.northWest(x, y, 1,targetCount));\r\n }", "function checkWin(board) {\n var firstColor = board[0][0];\n var count = board.length;\n for(var i = 0 ; i < count ; i++) {\n for(var j = 0 ; j < count ; j++) {\n if (board[i][j] !== firstColor) {\n return false\n }\n }\n }\n return true\n}", "isBoardClear() {\n for (let x = 0; x < this.width; ++x) {\n for (let y = 0; y < this.height; ++y) {\n var square = this.grid[x][y];\n \n if (square !== null && square.hasOwnProperty('visible') && square.visible !== true) {\n return false;\n }\n }\n }\n \n return true;\n }", "function solve(board) {\n\tconst empty = findUnassigned(board);\n \n\t//if no cell is empty the board is solved\n\tif (!empty) {\n\t\treturn true;\n\t}\n\n\tconst row = empty[0];\n\tconst col = empty[1];\n\n\tfor (let i = 1; i < 10; i++) {\n\n\t\t//if i is valid at empty cell, set cell to i\n\t\tif (checkRow(board, row, col, i) && checkColumn(board, row, col, i) && checkGrid(board, row, col, i)) { \n\t\t\tboard[row][col] = i;\n\n\t\t\tif (solve(board)) { \n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t// unset cell\n\t\t\tboard[row][col] = 0;\n\t\t}\n\t}\n\n\treturn false;\n}", "function isColOk(grid, col, num) {\n for (var row = 0; row < 9; row++)\n if (grid[row][col].value == num)\n return false;\n\n return true;\n }", "function isSolvable (puzzleArray, rows, cols) {\n let product = 1\n for (let i = 1, l = rows * cols - 1; i <= l; i++) {\n for (let j = i + 1, m = l + 1; j <= m; j++) {\n product *= (puzzleArray[i - 1] - puzzleArray[j - 1]) / (i - j)\n }\n }\n return Math.round(product) === 1\n}", "function checkWin(currentClass) {\n return winningCombos.some((combination) => {\n return combination.every((index) => {\n return allCells[index].classList.contains(currentClass);\n });\n });\n}", "function isNeighbors(tile1, tile2) {\r\n\t\tvar left1 = parseInt(window.getComputedStyle(tile1).left);\r\n\t\tvar top1 = parseInt(window.getComputedStyle(tile1).top);\r\n\t\tvar left2 = parseInt(window.getComputedStyle(tile2).left);\r\n\t\tvar top2 = parseInt(window.getComputedStyle(tile2).top);\r\n\t\tif (Math.abs(left1 + top1 - left2 - top2) == 100) {\r\n\t\t\treturn true;\r\n\t\t} else {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}", "equals(grid) {\n if (this.height !== grid.height) { return false; }\n if (this.width !== grid.width) { return false; }\n\n let ans = true;\n for (let r = 0; r < this.height; r++) {\n for (let c = 0; c < this.width; c++) {\n if (this.get(r,c) !== grid.get(r,c)) { ans = false; }\n }\n }\n return ans;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a SupplyRequestWhen resource
static get __resourceType() { return 'SupplyRequestWhen'; }
[ "when(item) {\n return new Promise((resolve, reject) => {\n const listener = this.on('add', () => {\n if(this[ITEMS].has(item)) {\n resolve();\n this.off('add', listener);\n }\n });\n listener();\n });\n }", "function handleContextREQ (request) {\n\n\n\tsendResponse.call(this, \"ContextRESP\", request, 1, []);\n}", "function AcceptRequest(requestID) {\n try {\n var bRequest = GetBorrowingRequest(requestID);\n var lRequest = GetLentingRequest(requestID);\n\n // Them vao lich su\n bookshelf.ThemSachVaoLichSuMuon(lRequest.id_user_muon, bRequest.id_user_cho_muon, bRequest.id_sach, bRequest.ngay_muon, bRequest.ngay_tra);\n bookshelf.ThemSachVaoLichSuChoMuon(bRequest.id_user_cho_muon, lRequest.id_user_muon, bRequest.id_sach, bRequest.ngay_muon, bRequest.ngay_tra);\n\n // Xoa yeu cau\n bookshelf.XoaYeuCau(requestID);\n return true;\n } catch (ee) {\n console.log(ee)\n return false;\n }\n}", "trigger() {\n\n if (this._requestDataObject) {\n this.triggerWithBody(this._requestDataObject);\n } else {\n this.triggerEmpty();\n }\n }", "function handleRequest() {\r\n var dateForm = getDateForm();\r\n var paramForm = getParamForm();\r\n if (dateForm !== null && paramForm !== null) {\r\n requestItemInfoAndWait(dateForm, paramForm);\r\n }\r\n}", "get needsFulfilled()\n {\n return this.fulfillment[this.stage];\n }", "function jsonWhen(request) {\n var deferred = when.defer(),\n promise = deferred.promise;\n\n d3.json(request, received);\n\n function received(err, json) {\n if (err && err.status != 200) {\n deferred.reject(err);\n } else {\n deferred.resolve(json);\n }\n }\n\n return promise;\n}", "function getRequest(event) {\n //code\n return request = {\n headers: event.headers,\n body: JSON.parse(event.body)\n };\n}", "requested(userId) {\n return this.getList(userId, STATE_KEY.requested);\n }", "insideReq(floorReq) {\n for(let i=0 ; this.floors.length <= 10 ; i++){\n if(this.currentfloor === floorReq){\n this.manager.completePickup(floorReq)\n } else {\n this.manager.requestPickup(floorReq)\n }\n }\n }", "function anotherRequestPending() {\n if (requestPending) {\n $scope.lastActionOutcome = $scope.lastActionOutcome + 'Please wait. ';\n return true;\n }\n requestPending = true;\n return false;\n }", "$registerRequestResponse() {\n this.$container.bind('Adonis/Core/Request', () => Request_1.Request);\n this.$container.bind('Adonis/Core/Response', () => Response_1.Response);\n }", "function modelify(key) {\n return function () {\n var args = Array.prototype.slice.call(arguments),\n result = providers[key].apply(context || providers[key], args),\n sequence = Futures.sequence();\n if ('function' !== typeof(result.when)) {\n throw new Futures.exception('\"chainify\" provider \"' + key + '\" isn\\'t promisable');\n }\n sequence(function (fulfill) {\n result.when(fulfill);\n });\n return methodify(providers[key], sequence);\n };\n }", "function GenericRequest() {}", "function IsAvailablePonintForRequest(childId, points) {\n return $resource(_URLS.BASE_API + 'giftcard/isAvailablePonintForRequest/' + childId + '/' + points + _URLS.TOKEN_API + $localStorage.token).get().$promise;\n }", "_handlePrivacyRequest () {\n const privacyMode = this.preferencesController.getFeatureFlags().privacyMode\n if (!privacyMode) {\n this.platform && this.platform.sendMessage({\n action: 'approve-legacy-provider-request',\n selectedAddress: this.publicConfigStore.getState().selectedAddress,\n }, { active: true })\n this.publicConfigStore.emit('update', this.publicConfigStore.getState())\n }\n }", "function handle_bp_verify_funding_sources(req, startTime, apiName) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\n}", "[CREATE_APPROVE_PURCHASEORDER](context, formData) {\n console.log(formData, \"test\");\n return new Promise((resolve, reject) => {\n ApiService.setHeader();\n ApiService.post(\"/api/purchaseorder/ApprovePurchaseOrder\", formData)\n .then(result => {\n context.commit(\"CLEAR_ERROR\");\n context.commit(\"ADD_PURCHASEORDER\", result.data);\n resolve(result);\n })\n .catch(err => {\n context.commit(\"SET_ERROR\", { result: err.message });\n reject(err);\n });\n });\n }", "static isV1Request(request, type) {\n switch(type) {\n case DaxMethodIds.getItem:\n return !DynamoDBV1Converter._isArrayEmpty(request.AttributesToGet);\n case DaxMethodIds.batchGetItem:\n if(!DynamoDBV1Converter._isMapEmpty(request.RequestItems)) {\n for(const tableName of Object.getOwnPropertyNames(request.RequestItems)) {\n if(!DynamoDBV1Converter._isArrayEmpty(request.RequestItems[tableName].AttributesToGet)) {\n return true;\n }\n }\n }\n return false;\n case DaxMethodIds.putItem:\n case DaxMethodIds.deleteItem:\n return !DynamoDBV1Converter._isMapEmpty(request.Expected);\n case DaxMethodIds.updateItem:\n return !DynamoDBV1Converter._isMapEmpty(request.Expected) ||\n !DynamoDBV1Converter._isMapEmpty(request.AttributeUpdates);\n case DaxMethodIds.query:\n return (!DynamoDBV1Converter._isArrayEmpty(request.AttributesToGet) ||\n !DynamoDBV1Converter._isMapEmpty(request.QueryFilter) ||\n !DynamoDBV1Converter._isMapEmpty(request.KeyConditions));\n case DaxMethodIds.scan:\n return (!DynamoDBV1Converter._isArrayEmpty(request.AttributesToGet) ||\n !DynamoDBV1Converter._isMapEmpty(request.ScanFilter));\n case DaxMethodIds.batchWriteItem:\n return false;\n default:\n throw new DaxClientError('Invalid request type', DaxErrorCode.Validation, false);\n }\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the first account listed, unless a default account has been set explicitly
async currentAccount() { const accounts = await this.web3.eth.getAccounts() const defaultAccount = this.web3.eth.defaultAccount return defaultAccount || accounts[0] }
[ "function getAccount(username){\n var matchedAccount;\n\n accounts.forEach(function(account){\n if (account.username === username){\n matchedAccount = account;\n }\n\n });\n\n return matchedAccount;\n\n\n}", "async getAccount(accountNo) {\n try {\n const accounts = await this.getAccounts();\n return accounts.find(account => account.accountNo == accountNo);\n } catch (err) {\n throw err;\n }\n }", "get effectiveAccount() {\n return this.action.actionProperties.role?.env.account\n ?? this.action.actionProperties?.resource?.env.account\n ?? this.action.actionProperties.account;\n }", "getAccount(actor) {\n const getAccount = new queries.GetAccount(actor);\n return getAccount.execute(this.publicKey);\n }", "function getAccount(name) {\n var acc = read(name);\n if (acc === \"undefined\"){\n\t\t// storage not supported by browser\n } else if (acc == null) {\n\t // nothing stored at that key\n return new Account(name, [], []);\n } else {\n // result successfully found\n return JSON.parse(acc);\n }\n}", "function findAccountById(accounts, id) {\n for(let i = 0; i < accounts.length; i++) {\n if(accounts[i].id === id) {\n return accounts[i];\n }\n }\n}", "getAccount(pin){\n for (let i = 0; i < this.accounts.length; i++) {\n if (this.accounts[i].pin === pin) {\n //return the bank account that matches our pin\n console.log (\"GetAccount\");\n this.currentAccount = this.accounts[i]; \n updateATM(); \n return this.accounts[i];\n }\n }\n return null; \n }", "returnableAccount(account){}", "loadCoinbaseAccount(currency, force) {\n return this.loadCoinbaseAccounts(force).then((accounts) => {\n for (const account of accounts) {\n if (account.currency === currency) {\n return Promise.resolve(account);\n }\n }\n return Promise.reject(new errors_1.GTTError(`No Coinbase account for ${currency} exists`));\n });\n }", "getAccountByName(name, commit=true) {\n for (let i = 0; i < this.accounts.length; i++) {\n let account = this.accounts[i];\n if (account.name === name) {\n return account;\n }\n }\n if (commit) {\n let newAccount = new Account(name);\n this.accounts.push(newAccount);\n return newAccount;\n } else {\n return undefined;\n }\n }", "getOtherAccountName(account) {\n return __awaiter(this, void 0, void 0, function* () {\n var otherAccount = yield this.getOtherAccount(account);\n if (otherAccount != null) {\n return otherAccount.getName();\n }\n else {\n return \"\";\n }\n });\n }", "function getCurrentUser() {\n let storage = LocalStorageManager.getStorage();\n\n if (storage.currentLoggedInUserEmail !== null) {\n // the email was not null, so there is a logged in user\n for (let i in storage.users) {\n // loop through all users and find the one with the currentLoggedInUserEmail\n let user = storage.users[i];\n if (user.email == storage.currentLoggedInUserEmail) {\n return user;\n }\n }\n }\n\n // user was not found in users list\n return null;\n }", "static async getAccountId() {\n var sts = new AWS.STS();\n var resp = await sts.getCallerIdentity({}).promise();\n return resp.Account;\n }", "ListOfAuthorizedDeferredPaymentAccountForThisCustomer() {\n let url = `/me/paymentMean/deferredPaymentAccount`;\n return this.client.request('GET', url);\n }", "function subtest_get_an_account_part_2(w) {\n // An account should have been added.\n Assert.equal(nAccounts(), gNumAccounts + 1);\n\n // We want this provider to be our default search engine.\n wait_for_element_invisible(w, \"window\");\n wait_for_element_visible(w, \"successful_account\");\n\n // Make sure the search engine is checked\n Assert.ok(w.e(\"search_engine_check\").checked);\n\n // Then click \"Finish\"\n mc.click(w.eid(\"closeWindow\"));\n}", "getUserByUsername(username) {\n for (var id in this.users) {\n if (username === this.users[id].username)\n return this.users[id];\n }\n return null;\n }", "ListOfOVHAccountsTheLoggedAccountHas() {\n let url = `/me/ovhAccount`;\n return this.client.request('GET', url);\n }", "async getAccountUuid(usn) {\n let accountUuidCache = this.accountUuidCache;\n let uuid = accountUuidCache[usn];\n\n if (uuid != null) {\n return Promise.resolve(uuid);\n }\n\n return this\n .query(\"query($usn: String) { account(usn: $usn) { accountUuid } }\", {usn: usn})\n .then((result) => {\n const uuid = result.data.account.accountUuid;\n accountUuidCache[usn] = uuid;\n return uuid;\n });\n }", "async updateAccount() {\r\n const accounts = await web3.eth.getAccounts();\r\n const account = accounts[0];\r\n this.currentAccount = account;\r\n console.log(\"ACCOUNT: \"+account)\r\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use `__generateActionName` function to generate action names. E.g. If you create an action with name `hello` it will be `action:hello` for the Flux.
function __generateActionName(name) { return 'action:' + name; }
[ "function actionCreator(action){\n return action\n}", "generateActionMessages() {\n this.generateActionGoalMessage();\n this.generateActionResultMessage();\n this.generateActionFeedbackMessage();\n this.generateActionMessage();\n }", "playAction(name) {\n this.action(actions[name])\n }", "function createAction(type) {\n function actionCreator(payload) {\n return {\n type: type,\n payload: payload\n };\n }\n\n actionCreator.toString = function () {\n return \"\".concat(type);\n };\n\n actionCreator.type = type;\n return actionCreator;\n}", "function getAction() {\r\n\r\n return( action );\r\n\r\n }", "function formatAction(req) {\n\t\tconst iam_action = getFirstAction(req);\t\t\t\t\t\t\t// get the iam action on the request\n\n\t\tif (req._client_event === true) {\n\t\t\tconst resource = (req.params && req.params.resource) ? simpleStr(req.params.resource) : '-';\n\t\t\tconst verb = (req.body && req.body.action_verb) ? req.body.action_verb : pickVerb(req);\n\t\t\tconst str = ev.STR.SERVICE_NAME + '.' + resource + '.' + verb;\n\t\t\treturn str.toLowerCase();\n\t\t} else {\n\t\t\tlet str = '';\t\t\t\t\t\t\t\t\t\t\t\t// populated below\n\t\t\tif (!iam_action) {\t\t\t\t\t\t\t\t\t\t\t// no action b/c its public\n\t\t\t\tstr = get_last_word_in_path(req) + '.' + pickVerb(req);\n\t\t\t} else if (iam_action === ev.STR.CREATE_ACTION) {\n\t\t\t\tstr = 'components.create';\n\t\t\t} else if (iam_action === ev.STR.DELETE_ACTION) {\n\t\t\t\tstr = 'components.delete';\n\t\t\t} else if (iam_action === ev.STR.REMOVE_ACTION) {\n\t\t\t\tstr = 'components.remove';\n\t\t\t} else if (iam_action === ev.STR.IMPORT_ACTION) {\n\t\t\t\tstr = 'components.import';\n\t\t\t} else if (iam_action === ev.STR.EXPORT_ACTION) {\n\t\t\t\tstr = 'components.export';\n\t\t\t} else if (iam_action === ev.STR.RESTART_ACTION) {\n\t\t\t\tif (req && req.path.includes('/sessions')) {\n\t\t\t\t\tstr = 'sessions.delete';\n\t\t\t\t} else if (req && req.path.includes('/cache')) {\n\t\t\t\t\tstr = 'cache.delete';\n\t\t\t\t} else {\n\t\t\t\t\tstr = 'ibp_console.start';\n\t\t\t\t}\n\t\t\t} else if (iam_action === ev.STR.LOGS_ACTION) {\n\t\t\t\tstr = 'logs.read';\n\t\t\t} else if (iam_action === ev.STR.VIEW_ACTION) {\n\t\t\t\tif (req && req.path.includes('/notifications')) {\n\t\t\t\t\tstr = 'notifications.read';\n\t\t\t\t} else if (req && req.path.includes('/signature_collections')) {\n\t\t\t\t\tstr = 'signature_collections.read';\n\t\t\t\t} else if (req && req.path.includes('/components')) {\n\t\t\t\t\tstr = 'components.read';\n\t\t\t\t} else {\n\t\t\t\t\tstr = 'ibp_console.read';\n\t\t\t\t}\n\t\t\t} else if (iam_action === ev.STR.SETTINGS_ACTION) {\n\t\t\t\tstr = 'ibp_console.' + pickVerb(req);\n\t\t\t} else if (iam_action === ev.STR.USERS_ACTION) {\n\t\t\t\tstr = 'users.' + pickVerb(req);\n\t\t\t} else if (iam_action === ev.STR.API_KEY_ACTION) {\n\t\t\t\tstr = 'api_keys.' + pickVerb(req);\n\t\t\t} else if (iam_action === ev.STR.NOTIFICATIONS_ACTION) {\n\t\t\t\tif (req && req.path.includes('/bulk')) {\n\t\t\t\t\tstr = 'notifications.delete';\n\t\t\t\t} else {\n\t\t\t\t\tstr = 'notifications.' + pickVerb(req);\n\t\t\t\t}\n\t\t\t} else if (iam_action === ev.STR.SIG_COLLECTION_ACTION) {\n\t\t\t\tstr = 'signature_collections.' + pickVerb(req);\n\t\t\t} else if (iam_action === ev.STR.C_MANAGE_ACTION) {\n\t\t\t\tif (req && req.path.includes('/actions')) {\n\t\t\t\t\tstr = 'components.configure';\n\t\t\t\t} else {\n\t\t\t\t\tstr = 'components.' + pickVerb(req);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlogger.warn('[act track] unknown iam action, please add it to activity_tracker_lib:', iam_action, req.actions);\n\t\t\t\tstr = 'unknown.' + pickVerb(req);\n\t\t\t}\n\n\t\t\t// end format is <service name>.<object descriptor>.<action verb>\n\t\t\treturn (ev.STR.SERVICE_NAME + '.' + str).toLowerCase();\t\t\t// pre-append the service name and we are done\n\t\t}\n\n\t\t// pick a action verb from the request method for this crud call\n\t\tfunction pickVerb(req) {\n\t\t\tconst methodMap = {\n\t\t\t\tGET: 'read',\n\t\t\t\tDELETE: 'delete',\n\t\t\t\tPOST: 'create',\n\t\t\t\tPUT: 'update',\n\t\t\t\tPATCH: 'configure',\n\t\t\t\tHEAD: 'connect',\n\t\t\t\tOPTIONS: 'allow',\n\t\t\t\tVIEW: 'monitor',\n\t\t\t};\n\n\t\t\tif (req.method && methodMap[req.method]) {\n\t\t\t\treturn methodMap[req.method];\n\t\t\t} else {\n\t\t\t\treturn 'monitor';\n\t\t\t}\n\t\t}\n\t}", "stateActionDispatch (action) {\n this.send('state.action.dispatch', { action })\n }", "registerActions() {\n this.registerAction(\"read\", new read_action_1.default());\n this.registerAction(\"write\", new write_action_1.default());\n }", "function generateMangledName(name, o)\n{\n\tif (o.isDebugMode)\n\t{\n\t\treturn \"_$\" + name + \"$\" + o.debugSuffix + \"_\";\n\t}\n\telse\n\t{\n\t\treturn generateIdentifierFromSeed(o.nameCache.seed++);\n\t}\n}", "getActionIdentifier() {\n return this._actionIdentifier;\n }", "_buildSemanticAction(semanticAction) {\n if (!semanticAction) {\n return null;\n }\n\n // Builds a string of args: '$1, $2, $3...'\n let parameters = [...Array(this.getRHS().length)]\n .map((_, i) => `$${i + 1}`)\n .join(',');\n\n const handler = CodeUnit.createHandler(parameters, semanticAction);\n\n return (...args) => {\n // Executing a handler mutates $$ variable, return it.\n handler(...args);\n return CodeUnit.getSandbox().$$;\n };\n }", "_resolveControllerAction (action) {\n let [controllerName, actionName] = action.split ('@');\n\n if (!controllerName)\n throw new Error (`The action must include a controller name [${action}]`);\n\n if (!actionName)\n actionName = SINGLE_ACTION_CONTROLLER_METHOD;\n\n // Locate the controller object in our loaded controllers. If the controller\n // does not exist, then throw an exception.\n let controller = get (this.controllers, controllerName);\n\n if (!controller)\n throw new Error (`${controllerName} not found`);\n\n // Locate the action method on the loaded controller. If the method does\n // not exist, then throw an exception.\n let method = controller[actionName];\n\n if (!method)\n throw new Error (`${controllerName} does not define method ${actionName}`);\n\n return new MethodCall ({ obj: controller, method });\n }", "sampleAction(array) {\n this.action(sample(array.map(e => actions[e])))\n }", "action(type, payload) {\n var action;\n if (payload) {\n action = _.extend({}, payload, {actionType: type});\n } else {\n action = {actionType: type};\n }\n debug('Action: ' + type, action);\n this.dispatch(action);\n }", "getActions() {\n return Object.keys(this.actions)\n .map(a => this.actions[a]);\n }", "function greet(action){\n action();\n}", "remove(actionToRemove) {\n\t\tthis.actions = this.actions.filter( action => action.name !== actionToRemove.name);\n\t}", "function youGetTaco(action) {\n if (action === \"eat\") {\n return \"EAT TACOS\";\n \n \n } \n }", "function compileAction(lexer, ruleName, action) {\n if (!action) {\n return { token: '' };\n }\n else if (typeof (action) === 'string') {\n return action; // { token: action };\n }\n else if (action.token || action.token === '') {\n if (typeof (action.token) !== 'string') {\n __WEBPACK_IMPORTED_MODULE_1__monarchCommon_js__[\"k\" /* throwError */](lexer, 'a \\'token\\' attribute must be of type string, in rule: ' + ruleName);\n return { token: '' };\n }\n else {\n // only copy specific typed fields (only happens once during compile Lexer)\n var newAction = { token: action.token };\n if (action.token.indexOf('$') >= 0) {\n newAction.tokenSubst = true;\n }\n if (typeof (action.bracket) === 'string') {\n if (action.bracket === '@open') {\n newAction.bracket = 1 /* Open */;\n }\n else if (action.bracket === '@close') {\n newAction.bracket = -1 /* Close */;\n }\n else {\n __WEBPACK_IMPORTED_MODULE_1__monarchCommon_js__[\"k\" /* throwError */](lexer, 'a \\'bracket\\' attribute must be either \\'@open\\' or \\'@close\\', in rule: ' + ruleName);\n }\n }\n if (action.next) {\n if (typeof (action.next) !== 'string') {\n __WEBPACK_IMPORTED_MODULE_1__monarchCommon_js__[\"k\" /* throwError */](lexer, 'the next state must be a string value in rule: ' + ruleName);\n }\n else {\n var next = action.next;\n if (!/^(@pop|@push|@popall)$/.test(next)) {\n if (next[0] === '@') {\n next = next.substr(1); // peel off starting @ sign\n }\n if (next.indexOf('$') < 0) { // no dollar substitution, we can check if the state exists\n if (!__WEBPACK_IMPORTED_MODULE_1__monarchCommon_js__[\"i\" /* stateExists */](lexer, __WEBPACK_IMPORTED_MODULE_1__monarchCommon_js__[\"j\" /* substituteMatches */](lexer, next, '', [], ''))) {\n __WEBPACK_IMPORTED_MODULE_1__monarchCommon_js__[\"k\" /* throwError */](lexer, 'the next state \\'' + action.next + '\\' is not defined in rule: ' + ruleName);\n }\n }\n }\n newAction.next = next;\n }\n }\n if (typeof (action.goBack) === 'number') {\n newAction.goBack = action.goBack;\n }\n if (typeof (action.switchTo) === 'string') {\n newAction.switchTo = action.switchTo;\n }\n if (typeof (action.log) === 'string') {\n newAction.log = action.log;\n }\n if (typeof (action.nextEmbedded) === 'string') {\n newAction.nextEmbedded = action.nextEmbedded;\n lexer.usesEmbedded = true;\n }\n return newAction;\n }\n }\n else if (Array.isArray(action)) {\n var results = [];\n var idx;\n for (idx in action) {\n if (action.hasOwnProperty(idx)) {\n results[idx] = compileAction(lexer, ruleName, action[idx]);\n }\n }\n return { group: results };\n }\n else if (action.cases) {\n // build an array of test cases\n var cases = [];\n // for each case, push a test function and result value\n var tkey;\n for (tkey in action.cases) {\n if (action.cases.hasOwnProperty(tkey)) {\n var val = compileAction(lexer, ruleName, action.cases[tkey]);\n // what kind of case\n if (tkey === '@default' || tkey === '@' || tkey === '') {\n cases.push({ test: null, value: val, name: tkey });\n }\n else if (tkey === '@eos') {\n cases.push({ test: function (id, matches, state, eos) { return eos; }, value: val, name: tkey });\n }\n else {\n cases.push(createGuard(lexer, ruleName, tkey, val)); // call separate function to avoid local variable capture\n }\n }\n }\n // create a matching function\n var def = lexer.defaultToken;\n return {\n test: function (id, matches, state, eos) {\n var idx;\n for (idx in cases) {\n if (cases.hasOwnProperty(idx)) {\n var didmatch = (!cases[idx].test || cases[idx].test(id, matches, state, eos));\n if (didmatch) {\n return cases[idx].value;\n }\n }\n }\n return def;\n }\n };\n }\n else {\n __WEBPACK_IMPORTED_MODULE_1__monarchCommon_js__[\"k\" /* throwError */](lexer, 'an action must be a string, an object with a \\'token\\' or \\'cases\\' attribute, or an array of actions; in rule: ' + ruleName);\n return '';\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
padding blankHTML if node is empty (for cursor position)
function paddingBlankHTML(node){if(!isVoid(node)&&!nodeLength(node)){node.innerHTML=blankHTML;}}
[ "preprocessNodes(node) {\n let cleanedNode = node.cloneNode();\n if (node.nodeType === Node.ELEMENT_NODE) {\n const tag = tagName(node);\n // If we have to replace the tagname we create another node with the new\n // tagname and copy all the attribute of the original node\n if (this.tagMap[tag]) {\n cleanedNode = document.createElement(this.tagMap[tag]);\n this.copyAllAttrs(node, cleanedNode);\n }\n // Clean all node childs\n cleanedNode.textContent = '';\n if (this.lumpTags.includes(tag)) {\n cleanedNode.setAttribute(\"property\", \"http://lblod.data.gift/vocabularies/editor/isLumpNode\");\n }\n if (node.hasChildNodes()) {\n let children = node.childNodes;\n for (let i = 0; i < children.length; i++) {\n const cleanedChild = this.preprocessNodes(children[i]);\n if (cleanedChild) {\n if (this.lumpTags.includes(tag)) {\n // make sure we can place the cursor before the non editable element\n cleanedNode.appendChild(document.createTextNode(\"\"));\n }\n cleanedNode.appendChild(cleanedChild);\n if (this.lumpTags.includes(tag)) {\n // make sure we can place the cursor after the non editable element\n cleanedNode.appendChild(document.createTextNode(\"\"));\n }\n }\n }\n }\n }\n else if (node.nodeType === Node.TEXT_NODE) {\n // remove invisible whitespace (so keeping non breaking space)\n // \\s as per JS [ \\f\\n\\r\\t\\v\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff].\n cleanedNode.textContent = node.textContent.replace(invisibleSpace,'')\n .replace(/[ \\f\\n\\r\\t\\v\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+/g,' ');\n if (cleanedNode.length == 0)\n return null;\n }\n return cleanedNode;\n }", "function is_node_empty(node, regardBrAsEmpty) {\n if (regardBrAsEmpty === void 0) { regardBrAsEmpty = true; }\n if (!node)\n return false;\n return (node.nodeType == Node.TEXT_NODE && /^[\\s\\r\\n]*$/.test(node.nodeValue)) ||\n (node.nodeType == Node.COMMENT_NODE) ||\n (regardBrAsEmpty && node.nodeName == \"BR\");\n }", "balanceHtml() {\n\t\tif (!this.left && this.right) {\n\t\t\tthis.htmlRight = this.right.html;\n\t\t\tthis.setChildToNull(true);\n\t\t} else if (!this.right && this.left) {\n\t\t\tthis.htmlLeft = this.left.html;\n\t\t\tthis.setChildToNull(false);\n\t\t} else if (this.right && this.left) {\n\t\t\tthis.htmlLeft = this.left.html;\n\t\t\tthis.htmlRight = this.right.html;\n\t\t\tthis.setHtml();\n\t\t\tthis.updateRootHtml();\n\t\t} else {\n\t\t\tthis.htmlLeft = (\n\t\t\t\t<li className='null'>\n\t\t\t\t\t<div>null</div>\n\t\t\t\t</li>\n\t\t\t);\n\n\t\t\tthis.htmlRight = (\n\t\t\t\t<li className='null'>\n\t\t\t\t\t<div className='null'>null</div>\n\t\t\t\t</li>\n\t\t\t);\n\t\t\tthis.setHtml();\n\t\t\tthis.updateRootHtml();\n\t\t}\n\t}", "function blank() {\n putstr(padding_left(seperator, seperator, sndWidth));\n putstr(\"\\n\");\n }", "function isEmptyNode(node) {\n if (node && node.textContent) {\n return false;\n }\n if (!node ||\n !node.childCount ||\n (node.childCount === 1 && isEmptyParagraph(node.firstChild))) {\n return true;\n }\n var block = [];\n var nonBlock = [];\n node.forEach(function (child) {\n child.isInline ? nonBlock.push(child) : block.push(child);\n });\n return (!nonBlock.length &&\n !block.filter(function (childNode) {\n return (!!childNode.childCount &&\n !(childNode.childCount === 1 && isEmptyParagraph(childNode.firstChild))) ||\n childNode.isAtom;\n }).length);\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 }", "function isEmptyHtml( el ){\n\treturn !$.trim(el.html())\n}", "function getEmptyCell() {\n return game.querySelector(\".empty\");\n }", "function isEmptyDocument(node) {\n var nodeChild = node.content.firstChild;\n if (node.childCount !== 1 || !nodeChild) {\n return false;\n }\n return (nodeChild.type.name === 'paragraph' &&\n !nodeChild.childCount &&\n nodeChild.nodeSize === 2);\n}", "function isEmptyParagraph(node) {\n return (!node ||\n (node.type.name === 'paragraph' && !node.textContent && !node.childCount));\n}", "function removeNbsp () {\n\t\tif (screenDown.innerHTML == \"&nbsp;\") screenDown.innerHTML = \"\";\n\t}", "createBlankNode(suggestedName) {\n let name, index;\n // Generate a name based on the suggested name\n if (suggestedName) {\n name = suggestedName = `_:${suggestedName}`, index = 1;\n while (this._ids[name])\n name = suggestedName + index++;\n }\n // Generate a generic blank node name\n else {\n do { name = `_:b${this._blankNodeIndex++}`; }\n while (this._ids[name]);\n }\n // Add the blank node to the entities, avoiding the generation of duplicates\n this._ids[name] = ++this._id;\n this._entities[this._id] = name;\n return this._factory.blankNode(name.substr(2));\n }", "function NilNode() {\n}", "function editorEmptyRender() {\n $( \".preview\" ).html( `<div class=\"empty\"><span class=\"icon\"></span><span>当前未选择任何适配站点</span></div>` );\n}", "function placeEmptyPlaceholder() {\n $('.details-table td').each(function () {\n if ($(this).text() == '' || $(this).text() == null || $(this).text() == 'None' || $(this).text() == 'none') {\n $(this).text('-');\n }\n });\n}", "function docClear (node)\n{\n\twhile (node.firstChild)\n\t\tnode.removeChild(node.firstChild);\n\tnode.innerHTML = \"\";\n}", "toNode() {\n if (this.character) {\n return document.createTextNode(this.character);\n } else {\n const node = document.createElementNS(\"http://www.w3.org/1998/Math/MathML\", \"mspace\");\n node.setAttribute(\"width\", this.width + \"em\");\n return node;\n }\n }", "firstChild() {\n return this.enterChild(1, 0, 4 /* Side.DontCare */)\n }", "function emptyError() {\n console.log(document.getElementById(\"error\").innerHTML);\n if (document.getElementById(\"error\").innerHTML === \"\") {\n return true;\n }\n return false;\n }" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTIONS Loads i articles, i = articlesPerLoad
function loadArticles() { // Count Down let i = articlesPerLoad; while (i > 0) { if(articlesLoaded <= maxArticles) { // "articlesLoaded" is also the key of the array getArticleData(storyIDs[articlesLoaded]); articlesLoaded++; } i--; } }
[ "function loadArticles() {\n // clear article list\n clearArticleListChildren();\n\n // Create the query to load the last 12 articles and listen for new ones.\n var articlesRef = firebase.firestore().collection('articles');\n\n if (isUserSignedIn()) {\n // Get public articles\n var query_public = articlesRef.where('permission', '==', \"public\").orderBy('createdAt', 'desc').limit(10);\n loadArticlesWithQuery(query_public);\n\n // Get protected articles\n var query_protected = articlesRef.where('permission', '==', \"protected\").orderBy('createdAt', 'desc').limit(10);\n loadArticlesWithQuery(query_protected);\n\n // Get private articles owned by current user\n var query_own_private = articlesRef.where('permission', '==', \"private\").where('authorId', '==', getUserId()).orderBy('createdAt', 'desc').limit(10);\n loadArticlesWithQuery(query_own_private);\n } else {\n // Get public articles\n var query_public = articlesRef.where('permission', '==', \"public\").orderBy('createdAt', 'desc').limit(10);\n loadArticlesWithQuery(query_public);\n }\n}", "function load() {\n numOfPages();\n loadList();\n}", "function fetchArticles() {\n\treturn (dispatch) => {\n\t\tresource(\"GET\", \"articles\")\n\t\t.then(r => dispatch({type: 'articles', \n\t\t\tarticles: sortArticles(r.articles)}))\n\t}\n}", "function loadRecent() {\n \n if (paginationOptions.pageFirst > 0) {\n paginationOptions.pageFirst = 0;\n }\n viewsOptions.page = paginationOptions.pageFirst;\n\n return retreiveArticles(viewsOptions);\n }", "async prepareStories (recArticles, pageInitialSize, isHardLimit = false) {\n\n\t\tconst stories = [];\n\n\t\tfor (let index = 0; index < recArticles.length; index++) {\n\t\t\tconst recArticle = recArticles[index];\n\t\t\tconst story = { itemId: recArticle._id.toString() };\n\n\t\t\t// Full-fat stories contain all properties.\n\t\t\tif (!pageInitialSize || index < pageInitialSize) {\n\t\t\t\tstory.isFullFat = true;\n\t\t\t\tstory.title = recArticle.title;\n\t\t\t\tstory.articleUrl = recArticle.articleUrl;\n\t\t\t\tstory.articleDate = recArticle.articleDate;\n\t\t\t\tstory.priority = (typeof recArticle.isPriority !== `undefined` ? recArticle.isPriority : false);\n\t\t\t\tstory.published = (typeof recArticle.isPublished !== `undefined` ? recArticle.isPublished : true);\n\t\t\t}\n\n\t\t\t// Don't add any low-fat stories if we have a hard limit.\n\t\t\telse if (isHardLimit) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Low-fat stories only contain the item ID.\n\t\t\telse {\n\t\t\t\tstory.isFullFat = false;\n\t\t\t}\n\n\t\t\tstories.push(story);\n\t\t}\n\n\t\treturn mapListToDictionary(stories, `itemId`);\n\n\t}", "function init ( ) {\r\n articleContainer = document.querySelector('#article-container');\r\n \r\n for (var i = 0; i < articleSRC.length; i++){\r\n var art = document.createElement(\"div\");\r\n art.setAttribute(\"id\", \"article-\"+i);\r\n art.setAttribute(\"class\", \"article\");\r\n articleContainer.appendChild(art);\r\n art.style.display = 'none';\r\n articleContainers[i] = art;\r\n \r\n }\r\n var next = document.querySelectorAll('#next-article');\r\n var prev = document.querySelectorAll('#prev-article');\r\n for(var b = 0; b < next.length; b++){\r\n next[b].addEventListener('click', nextArticle);\r\n prev[b].addEventListener('click', prevArticle);\r\n }\r\n \r\n //Load the first Article by default\r\n loadJSON( currentArticle );\r\n articleContainers[currentArticle].style.display = 'block'\r\n //Shows the current article number\r\n document.querySelector('#current-article-1').textContent = (currentArticle+1)+\"/\"+articleSRC.length;\r\n document.querySelector('#current-article-2').textContent = (currentArticle+1)+\"/\"+articleSRC.length;\r\n document.querySelector('#rating').style.display = 'none';\r\n \r\n \r\n}", "getAllNews() {\n\n this.dataBase.findByIndex(\"/news\", [\"_id\", \"title\", \"attachment\"],\"categoryId\", mvc.routeParams.id).then( data => {\n if (data) {\n let length = data.docs.length;\n this.liftNewsInCategory = data.docs.slice(0, length / 2);\n this.rightNewsInCategory = data.docs.slice(length / 2, length);\n mvc.apply();\n } else {\n this.getAllNews()\n }\n }, () => {\n this.getAllNews();\n });\n\n }", "loadItems(url) {\n this.indexUrl = url;\n this.getFromServer(url, this.serverParams).then(response => {\n this.totalRecords = response.meta.total;\n this.rows = response.data;\n });\n }", "function loadList() {\n var begin = ((currentPage - 1) * numberPerPage);\n var end = begin + numberPerPage;\n\n pageList = hotelsArr.slice(begin, end);\n getDetails();\n check();\n}", "function initializeLoadMore() {\n\n zeusLoadMore.updateScroll = true;\n window.curPage = 0; // initialize counter for load more\n window.nextSlotId = 1; // initialize nextSlot ID for ads\n window.showLoadMore = true; // begin the load more unless content retrieved is exhausted\n var zeusLoadMoreSettings = zeusLoadMore.drupalSettings();\n var type = zeusLoadMoreSettings['type'];\n var channel = zeusLoadMoreSettings['curChannel'];\n var disqusOnDemand = zeusLoadMoreSettings['disqusOnDemand'];\n // flag for infinite scroll or load more on click\n var loadMoreOnScroll = zeusLoadMoreSettings['loadMoreOnScroll'];\n var initialNid = zeusLoadMoreSettings['initialNid'];\n var initialUrl = zeusLoadMoreSettings['initialUrl'];\n var initialTitle = zeusLoadMoreSettings['initialTitle'];\n var initialHTitle = zeusLoadMoreSettings['initialHTitle'];\n zeusLoadMore.dtm = {};\n zeusLoadMore.pageTitle = {};\n zeusLoadMore.headTitle = {};\n zeusLoadMore.url = {};\n zeusLoadMore.sponsored = {}; //used on content pages\n\n //zeusLoadMore.currPage = 0; //initialize counter for zeus smartqueue load more\n zeusLoadMore.dfp = {}; //used for zeus_smartqueue\n zeusLoadMore.extraData = {}; // used for slideshows\n zeusLoadMore.itemCount = 1;\n zeusLoadMore.itemsContainer = jQuery('#itemsContainer');\n\n // If infinite scroll is enabled\n if (typeof loadMoreOnScroll !== 'undefined' && loadMoreOnScroll === 1) {\n\n window.flagtoload = true;\n window.lastScrollTop = 0;\n /*** based on http://ejohn.org/blog/learning-from-twitter/ **/\n jQuery(window).scroll(function() {\n window.didScroll = true;\n });\n\n setInterval(function() {\n if ( window.didScroll ) {\n window.didScroll = false;\n zeusLoadMore.iScrollHandler();\n }\n }, 500);\n\n if (type === 'zeus_content') {\n if (typeof dataLayer !== 'undefined') {\n zeusLoadMore.dtm[initialNid] = dataLayer;\n }\n zeusLoadMore.url[initialNid] = initialUrl;\n zeusLoadMore.pageTitle[initialNid] = initialTitle;\n zeusLoadMore.headTitle[initialNid] = initialHTitle;\n zeusLoadMore.navPage = 1; // Used when adding more to scroll navigation list\n zeusLoadMore.noMoreData = 0; // Flag to check if there is any more data\n // ajax call to load the settings\n // need it before any load more call\n jQuery.getJSON('/load-more-settings-content/ajax/'+initialNid, function(json, status) {\n if(status === \"success\") {\n zeusLoadMore.dfp[initialNid] = json.dfp;\n }\n });\n\n // Set up the comment count links for iscroll\n // jQuery('.comment-count-wrap a.show-comments').addClass('show-comments-section');\n jQuery('.content-wrapper a.show-comments').addClass('show-comments-section');\n\n if (zeusLoadMoreSettings['comments'] === 'facebook') {\n // facebook\n zeusLoadMore.initializeFbComments();\n\n } else if (disqusOnDemand === 1) {\n // disqus\n zeusLoadMore.initializeDisqus();\n }\n // Outbrain\n zeusLoadMore.initializeOutbrainWidgetIds();\n // Sponsored\n if (jQuery('body').hasClass('sponsored')) {\n zeusLoadMore.sponsored[initialNid] = 1;\n } else {\n zeusLoadMore.sponsored[initialNid] = 0;\n }\n\n } else if (type === 'zeus_smartqueue') {\n window.flagtoload = false;\n // ajax call to load the settings\n // need it before any load more call\n // @todo: right now separator ad does not work without iscroll\n jQuery.getJSON('/load-more-settings/ajax/'+channel, function(json, status) {\n if(status === \"success\") {\n zeusLoadMore.dfp = json.dfp;\n window.flagtoload = true;\n }\n });\n }\n jQuery('.pager-load-more li.pager-next').hide(); // Hide load more button if infinite scroll enabled\n } else {\n // default is load more click\n if (type === 'zeus_smartqueue') {\n jQuery(\".pager-load-more.page_\"+curPage).click(function(event) {\n event.preventDefault();\n zeusLoadMore.loadMoreHandlerZeusSmartqueue();\n });\n }\n }\n}", "function nextArticle(){\r\n //hide all\r\n for(var index = 0; index < articleContainers.length; index++){\r\n if(articleContainers[index] != null){\r\n articleContainers[index].style.display = \"none\";\r\n }\r\n }\r\n if(currentArticle < articleSRC.length-1){\r\n // increment current\r\n currentArticle++;\r\n //show current\r\n articleContainers[currentArticle].style.display = 'block';\r\n //set current article\r\n document.querySelector('#current-article-1').textContent = (currentArticle+1)+\"/\"+articleSRC.length;\r\n document.querySelector('#current-article-2').textContent = (currentArticle+1)+\"/\"+articleSRC.length;\r\n // if not loaded create next\r\n if(currentArticle < articleSRC.length-1 && articles[currentArticle+1] == null){\r\n loadJSON(currentArticle+1)\r\n }\r\n }else if(currentArticle < articleSRC.length){\r\n \r\n // Show the rating page\r\n document.querySelector('#rating').style.display = 'block';\r\n currentArticle++;\r\n document.querySelector('#current-article-1').textContent = 'Rating Page';\r\n document.querySelector('#current-article-2').textContent = 'Rating Page';\r\n }\r\n}", "function GetRecentArticles(n) {\n return $http.get('/api/public/articles/recent/'+n).then(handleSuccess, handleError('Error getting recent articles'));\n }", "function fetchPosts() { // jshint ignore:line\n // Exit if postURLs haven't been loaded\n if (!postURLs) return;\n\n isFetchingPosts = true;\n $('.infinite-spinner').css('display', 'block');\n // Load as many posts as there were present on the page when it loaded\n // After successfully loading a post, load the next one\n var loadedPosts = 0;\n\n postCount = $('body').find('.js-postcount').length,\n callback = function() {\n loadedPosts++;\n var postIndex = postCount + loadedPosts;\n\n if (postIndex > postURLs.length-1) {\n disableFetching();\n $('.infinite-spinner').css('display', 'none');\n return;\n }\n\n if (loadedPosts < postsToLoad) {\n fetchPostWithIndex(postIndex, callback);\n } else {\n isFetchingPosts = false;\n $('.infinite-spinner').css('display', 'none');\n }\n };\n\n fetchPostWithIndex(postCount + loadedPosts, callback);\n }", "async function load() {\n for (var page = 0; page < 10; page++) {\n let url = `https://www.newegg.com/p/pl?N=100006740%204814&Page=${page}&PageSize=96&order=BESTSELLING`\n makeRequest(url)\n await timer(500)\n\n }\n}", "function initializeArticleFeed() {\n\tvar feeds = document.querySelectorAll('[data-content-type=\\'cdp-article-feed\\']');\n\tforEach(feeds, function (index, feed) {\n\t\trenderArticleFeed(feed);\n\t});\n}", "function loadMoreRecords(){\n if(count == 0){\n count++;\n }else{\n getAllVideos(self.videos.length,10);\n }\n }", "function get_loads(req){\r\n var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;\r\n //Limit to three boat results per page\r\n var q = datastore.createQuery(LOAD).limit(5);\r\n\r\n var results = {};\r\n\r\n if(Object.keys(req.query).includes(\"cursor\")){\r\n q = q.start(req.query.cursor);\r\n }\r\n\r\n return datastore.runQuery(q).then( (entities) => {\r\n results.loads = entities[0].map(ds.fromDatastore);\r\n for (var object in results.loads)\r\n {\r\n if(results.loads[object].carrier.length === 1)\r\n {\r\n var bid = results.loads[object].carrier[0];\r\n var boatUrl = req.protocol + '://' + req.get('host') + '/boats/' + bid;\r\n results.loads[object].carrier = [];\r\n results.loads[object].carrier = {\"id\": bid, \"self\": boatUrl};\r\n }\r\n \r\n // Make sure self link does not have cursor in it\r\n if(Object.keys(req.query).includes(\"cursor\"))\r\n {\r\n results.loads[object].self = req.protocol + '://' + req.get('host') + results.loads[object].id;\r\n }\r\n else\r\n {\r\n results.loads[object].self = fullUrl +'/' + results.loads[object].id;\r\n }\r\n }\r\n if(entities[1].moreResults !== ds.Datastore.NO_MORE_RESULTS){\r\n results.next = req.protocol + \"://\" + req.get(\"host\") + req.baseUrl + \"?cursor=\" + encodeURIComponent(entities[1].endCursor);\r\n }\r\n }).then(() =>{\r\n return count_loads().then((number) => {\r\n results.total_count = number;\r\n return results; \r\n });\r\n });\r\n}", "getFailedArticles(timeout = 10000) {\n Articles.getAllArticlesFromJson(Properties.basePath, timeout).then(\n results => {\n let articles = results[0],\n staticCollections = results[1];\n\n // merge the previous successful Articles with our new results.\n let mergedArticles = [..._articles, ...articles];\n // merge the previous successful static collections with our new results.\n let mergedStaticArticles = [\n ..._staticCollections,\n ...staticCollections\n ];\n Properties.articles = mergedArticles;\n _articles = mergedArticles;\n\n let sCollections = mergedStaticArticles.length\n ? this.sortStaticArticles(mergedStaticArticles)\n : [];\n\n // render the merged articles merged static collections.\n this.renderArticles(mergedArticles, sCollections);\n }\n );\n }", "function newsRequest(tickerSearch) {\n\n var apiKey = \"44ec6ee2a9c74c3dbe590b43546a857c\";\n var queryURL = \"https://newsapi.org/v2/everything?q=\" + tickerSearch + \"&apiKey=\" + apiKey;\n\n $.ajax({\n url: queryURL,\n method: \"GET\"\n }).then(function (response) {\n\n var articlesArray = [];\n // creating a loop to pull the top 3 articles\n for (var i = 0; i < 3; i++) {\n articlesArray.push(response.articles[i]);\n }\n\n displayArticles(articlesArray);\n\n });\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reset JSS registry, remove sheets and empty the styleManager.
function reset() { sheetMap.forEach(function (_ref2) { var jssStyleSheet = _ref2.jssStyleSheet; jssStyleSheet.detach(); }); sheetMap = []; }
[ "_destroyStyles() {\n if (!this.styleSheet) {return}\n this.styleSheet.destroy();\n this.styleSheet = null;\n }", "reStyle() {\n console.log('restyle')\n this._destroyStyles();\n this._initStyles();\n }", "function reset() {\n defaultRenderers_ = {};\n decoratorFunctions_ = {};\n}", "function removePageStyles(sheetIndex, restorePlace) {\n return changingStylesheet(function () {\n p.stylesheets[sheetIndex] = null;\n var i = 0, cmpt = null;\n while (cmpt = p.reader.dom.find('component', i++)) {\n var doc = cmpt.contentDocument;\n var styleTag = doc.getElementById('monStylesheet'+sheetIndex);\n styleTag.parentNode.removeChild(styleTag);\n }\n }, restorePlace);\n }", "reset() {\n this._registry = new Map();\n }", "function clearAddOns() {\r\n}", "resetEverything() {\n this.resetLoader();\n this.remove(0, Infinity);\n }", "function createStyleManager() {\n\t var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},\n\t jss = _ref.jss,\n\t _ref$theme = _ref.theme,\n\t theme = _ref$theme === undefined ? {} : _ref$theme;\n\t\n\t if (!jss) {\n\t throw new Error('No JSS instance provided');\n\t }\n\t\n\t var sheetMap = [];\n\t var sheetOrder = void 0;\n\t\n\t // Register custom jss generateClassName function\n\t jss.options.generateClassName = generateClassName;\n\t\n\t function generateClassName(str, rule) {\n\t var hash = (0, _murmurhash3_gc2.default)(str);\n\t str = rule.name ? rule.name + '-' + hash : hash;\n\t\n\t // Simplify after next release with new method signature\n\t if (rule.options.sheet && rule.options.sheet.options.name) {\n\t return rule.options.sheet.options.name + '-' + str;\n\t }\n\t return str;\n\t }\n\t\n\t /**\n\t * styleManager\n\t */\n\t var styleManager = {\n\t get sheetMap() {\n\t return sheetMap;\n\t },\n\t get sheetOrder() {\n\t return sheetOrder;\n\t },\n\t setSheetOrder: setSheetOrder,\n\t jss: jss,\n\t theme: theme,\n\t render: render,\n\t reset: reset,\n\t rerender: rerender,\n\t getClasses: getClasses,\n\t updateTheme: updateTheme,\n\t prepareInline: prepareInline,\n\t sheetsToString: sheetsToString\n\t };\n\t\n\t updateTheme(theme, false);\n\t\n\t function render(styleSheet) {\n\t var index = getMappingIndex(styleSheet.name);\n\t\n\t if (index === -1) {\n\t return renderNew(styleSheet);\n\t }\n\t\n\t var mapping = sheetMap[index];\n\t\n\t if (mapping.styleSheet !== styleSheet) {\n\t jss.removeStyleSheet(sheetMap[index].jssStyleSheet);\n\t sheetMap.splice(index, 1);\n\t\n\t return renderNew(styleSheet);\n\t }\n\t\n\t return mapping.classes;\n\t }\n\t\n\t /**\n\t * Get classes for a given styleSheet object\n\t */\n\t function getClasses(styleSheet) {\n\t var mapping = (0, _utils.find)(sheetMap, { styleSheet: styleSheet });\n\t return mapping ? mapping.classes : null;\n\t }\n\t\n\t /**\n\t * @private\n\t */\n\t function renderNew(styleSheet) {\n\t var name = styleSheet.name,\n\t createRules = styleSheet.createRules,\n\t options = styleSheet.options;\n\t\n\t var sheetMeta = name + '-' + styleManager.theme.id;\n\t\n\t if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && (typeof document === 'undefined' ? 'undefined' : _typeof(document)) === 'object') {\n\t var element = document.querySelector('style[data-jss][data-meta=\"' + sheetMeta + '\"]');\n\t if (element) {\n\t options.element = element;\n\t }\n\t }\n\t\n\t var rules = createRules(styleManager.theme);\n\t var jssOptions = _extends({\n\t name: name,\n\t meta: sheetMeta\n\t }, options);\n\t\n\t if (sheetOrder && !jssOptions.hasOwnProperty('index')) {\n\t var index = sheetOrder.indexOf(name);\n\t if (index === -1) {\n\t jssOptions.index = sheetOrder.length;\n\t } else {\n\t jssOptions.index = index;\n\t }\n\t }\n\t\n\t var jssStyleSheet = jss.createStyleSheet(rules, jssOptions);\n\t\n\t var _jssStyleSheet$attach = jssStyleSheet.attach(),\n\t classes = _jssStyleSheet$attach.classes;\n\t\n\t sheetMap.push({ name: name, classes: classes, styleSheet: styleSheet, jssStyleSheet: jssStyleSheet });\n\t\n\t return classes;\n\t }\n\t\n\t /**\n\t * @private\n\t */\n\t function getMappingIndex(name) {\n\t var index = (0, _utils.findIndex)(sheetMap, function (obj) {\n\t if (!obj.hasOwnProperty('name') || obj.name !== name) {\n\t return false;\n\t }\n\t\n\t return true;\n\t });\n\t\n\t return index;\n\t }\n\t\n\t /**\n\t * Set DOM rendering order by sheet names.\n\t */\n\t function setSheetOrder(sheetNames) {\n\t sheetOrder = sheetNames;\n\t }\n\t\n\t /**\n\t * Replace the current theme with a new theme\n\t */\n\t function updateTheme(newTheme) {\n\t var shouldUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n\t\n\t styleManager.theme = newTheme;\n\t if (!styleManager.theme.id) {\n\t styleManager.theme.id = (0, _murmurhash3_gc2.default)(JSON.stringify(styleManager.theme));\n\t }\n\t if (shouldUpdate) {\n\t rerender();\n\t }\n\t }\n\t\n\t /**\n\t * Reset JSS registry, remove sheets and empty the styleManager.\n\t */\n\t function reset() {\n\t sheetMap.forEach(function (_ref2) {\n\t var jssStyleSheet = _ref2.jssStyleSheet;\n\t jssStyleSheet.detach();\n\t });\n\t sheetMap = [];\n\t }\n\t\n\t /**\n\t * Reset and update all existing stylesheets\n\t *\n\t * @memberOf module:styleManager~styleManager\n\t */\n\t function rerender() {\n\t var sheets = [].concat(_toConsumableArray(sheetMap));\n\t reset();\n\t sheets.forEach(function (n) {\n\t render(n.styleSheet);\n\t });\n\t }\n\t\n\t /**\n\t * Prepare inline styles using Theme Reactor\n\t */\n\t function prepareInline(declaration) {\n\t if (typeof declaration === 'function') {\n\t declaration = declaration(theme);\n\t }\n\t\n\t var rule = {\n\t type: 'regular',\n\t style: declaration\n\t };\n\t\n\t prefixRule(rule);\n\t\n\t return rule.style;\n\t }\n\t\n\t /**\n\t * Render sheets to an HTML string\n\t */\n\t function sheetsToString() {\n\t return sheetMap.sort(function (a, b) {\n\t if (a.jssStyleSheet.options.index < b.jssStyleSheet.options.index) {\n\t return -1;\n\t }\n\t if (a.jssStyleSheet.options.index > b.jssStyleSheet.options.index) {\n\t return 1;\n\t }\n\t return 0;\n\t }).map(function (sheet) {\n\t return sheet.jssStyleSheet.toString();\n\t }).join('\\n');\n\t }\n\t\n\t return styleManager;\n\t}", "function svgClearAll() {\n\t\n\t// clear out undo and redo information\n\tclearUndoRedoLists();\n\t\n\t// clear out drawn objects\n\tvar myObject;\n\tfor (var i = 1; i < currentObject; i += 1) {\n\t\tmyObject = document.getElementById(objectStr + i.toString());\n\t\tif (myObject != null) {\n\t\t\tdrawingGroup.removeChild(myObject);\n\t\t}\n\t}\n\tcurrentObject = 1;\n\n\t// clear out platform objects\n\tvar myParent;\n\tfor (var j = 1; j < currentPlatform; j += 1) {\n\t\tmyObject = document.getElementById(platformStr + j.toString());\n\t\tif (myObject != null) {\n\t\t\tmyParent = myObject.parentNode;\n\t\t\tmyParent.removeChild(myObject);\n\t\t}\n\t}\n\tcurrentPlatform = 1;\n\t\n\t// clear out platform actions list\n\tfor (var i = platformActionsList.length - 1; i >= 0; i -= 1) {\n\t\tmyID = platformActionsList.pop();\n\t}\n}", "function remeasureFonts() {\n configuration_js_2.clearAllFontInfos();\n }", "function reinjectStyles() {\n if (!styleElements) {\n orphanCheck();\n return;\n }\n ROOT = document.documentElement;\n docRootObserver.stop();\n const imported = [];\n for (const [id, el] of styleElements.entries()) {\n const copy = document.importNode(el, true);\n el.textContent += \" \"; // invalidate CSSOM cache\n imported.push([id, copy]);\n addStyleElement(copy);\n }\n docRootObserver.start();\n styleElements = new Map(imported);\n }", "function cleanupStyles() {\n // Remove style tag with debug styles:\n var styleTags = document.querySelectorAll(\"#debug-styles\");\n styleTags.forEach((element) => element.parentNode.removeChild(element));\n\n // Remove all debug elements:\n var debugMessages = document.querySelectorAll(\".debug-message\");\n debugMessages.forEach((element) => element.parentNode.removeChild(element));\n}", "function clearRegisterClientPage(){\r\n $('#contentSection').empty();\r\n removeCSS('register_client');\r\n}", "function resetAll() {\n exports.results.forEach((cache) => cache.reset());\n}", "_initStyles() {\n const styles = this.constructor.styles !== undefined ? this.constructor.styles : this.styles();\n if (!styles) { return }\n this.styleSheet = new ScreenStyle(styles, this.id);\n }", "async resetAddonSet() {\n logger.info(\"Removing all system add-on upgrades.\");\n\n // remove everything from the pref first, if uninstall\n // fails then at least they will not be re-activated on\n // next restart.\n this._addonSet = { schema: 1, addons: {} };\n SystemAddonInstaller._saveAddonSet(this._addonSet);\n\n // If this is running at app startup, the pref being cleared\n // will cause later stages of startup to notice that the\n // old updates are now gone.\n //\n // Updates will only be explicitly uninstalled if they are\n // removed restartlessly, for instance if they are no longer\n // part of the latest update set.\n if (this._addonSet) {\n let ids = Object.keys(this._addonSet.addons);\n for (let addon of await AddonManager.getAddonsByIDs(ids)) {\n if (addon) {\n addon.uninstall();\n }\n }\n }\n }", "dispose() {\n const settingsfile = this.workspaceRoot + '/.vscode/settings.json';\n const vscodeSettingsDir = this.workspaceRoot + '/.vscode';\n const settingsFileJson = JSON.parse((fs.readFileSync(settingsfile, \"utf8\")));\n const cc = JSON.parse(JSON.stringify(vscode_1.workspace.getConfiguration('workbench').get('colorCustomizations')));\n const deleteSettingsFileUponExit = JSON.parse(JSON.stringify(vscode_1.workspace.getConfiguration('windowColors').get('🌈 DeleteSettingsFileUponExit')));\n if (deleteSettingsFileUponExit) {\n fs.unlinkSync(settingsfile);\n fs.rmdirSync(vscodeSettingsDir); //only deletes empty folders\n }\n else if (Object.keys(settingsFileJson).length === 1 && Object.keys(cc).length === 3) {\n const aColorWasModified = (cc['activityBar.background'] !== this.colors.sideBarColor_dark.hex() && cc['activityBar.background'] !== this.colors.sideBarColor_light.hex()) ||\n (cc['titleBar.activeBackground'] !== this.colors.titleBarColor_dark.hex() && cc['titleBar.activeBackground'] !== this.colors.titleBarColor_light.hex()) ||\n (cc['titleBar.activeForeground'] !== this.colors.titleBarTextColor_dark.hex() && cc['titleBar.activeForeground'] !== this.colors.titleBarTextColor_light.hex());\n if (!aColorWasModified) {\n fs.unlinkSync(settingsfile);\n fs.rmdirSync(vscodeSettingsDir); //only deletes empty folders\n }\n }\n }", "clear() {\n // Wipe out the DOM content.\n for (let [, containerElem] of this._containerHtmlElems) {\n $(containerElem).empty();\n }\n // Clear the data structures.\n this._containerHtmlElems.clear();\n this._svgDisplays.clear();\n }", "function clearAllSheetData(){\n var sheets = ['lists', 'bounced', 'paid', 'expired', 'log', 'otherdata'],\n sheet,\n rows,\n x, y,\n i, j;\n getScriptLock();\n try{\n for(x = 0, y = sheets.length; x < y; x++){\n sheet = constants.ss.getSheetByName(constants.sheets[sheets[x]].name);\n rows = sheet.getDataRange();\n i = constants.sheets[sheets[x]].headerRows + 1;\n j = rows.getNumRows() - constants.sheets[sheets[x]].headerRows;\n\n if (j < 1) continue;\n sheet.deleteRows(i, j);\n }\n }\n finally{\n constants.lock.releaseLock();\n }\n}" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }