query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Handles the user clicking the image controls menu save button. | function imageControlsSaveClick() {
Settings.Filters.Brightness = Data.Controls.Brightness.value;
Settings.Filters.Contrast = Data.Controls.Contrast.value;
Settings.Filters.Hue = Data.Controls.Hue.value;
Settings.Filters.Saturation = Data.Controls.Saturation.value;
saveSettings();
Data.Controls.Open = false;
setControlsPosition();
} | [
"function menuSaveClick() {\n requestSave();\n}",
"function menuImageClick() {\n Data.Edit.Mode = EditModes.Image;\n updateMenu();\n}",
"function save() {\n dialogOut.dialog( \"close\" );\n }",
"function check_set_save_inspirations(current_img_id,save_img_btn) {\n $.post(RELATIVE_PATH + '/config/processing.php',{form : 'Inspiration Sidebar Saved Arr'}, function(data) {\n // alert(current_img_id);\n if ($.inArray(current_img_id, data) !== -1)\n {\n $(save_img_btn).text('Saved');\n }else{\n $(save_img_btn).text('Save');\n }\n },'json');\n }",
"handleSave() {\n const can = document.getElementById('paint');\n const img = new Image();\n\n /**\n * If the state of the default canvas is the same that\n * the canvas after click on save we show an error instead\n * send the image in png to the father component\n */\n if (can.toDataURL() === this.state.defaultCanvas) {\n alert('Canvas is blank');\n } else {\n img.src = can.toDataURL('image/png');\n this.props.onReciveSign(img.src);\n }\n }",
"function imagebisButtonClick(e, data) {\n\t\t// Wire up the submit button click event handler\n\t\t$(data.popup).find(\"input[type=file]\")\n\t\t\t.unbind(\"change\")\n\t\t\t.bind(\"change\", function(e) {\n\t\t\t\tvar $_this = $(this);\n\n\t\t\t\t// Get the editor\n\t\t\t\tvar editor = data.editor; \n\t\t\t\t$_this.upload(URL_SITE+'ajax:photo/upload/align:'+ $(data.popup).find(\"input:radio[name=align]:checked\").val() +'/', function(res) {\n\t\t\t\t\tvar html = res.image;\n\n\t\t\t\t\t// Insert the html\n\t\t\t\t\tif (res.image) {\n\t\t\t\t\t\teditor.execCommand(data.command, html, null, data.button);\n\t\t\t\t\t\teditor.find( 'img[src=\"'+html+'\"]' ).attr( 'align', $(data.popup).find(\"input:radio[name=align]:checked\").val() );\n\t\t\t\t\t}\n\t\t\t\t}, 'json');\n\n\t\t\t\t// reset popup\n\t\t\t\t$(this).val('');\n\t\t\t\teditor.hidePopups();\n\t\t\t\teditor.focus();\n\t\t\t}\n\t\t);\n\t}",
"function save() {\n\n var image = canvas.toDataURL(\"image/png\");\n //grab the title the user entered\n var title = document.getElementById('nameForm').value;\n //save into collection called sketches, this is found in items.js\n Meteor.call('sketches.insert', title , image);\n console.log(title+\" has been saved!\");\n //console.log(image);\n // save this image (along with other attributes) in a Drawings array/list as custom data under the user ID\n}",
"function onSaveButtonClicked(event) {\n\t// console.log('clicked');\n\tif ('caches' in window) {\n\t\tcaches.open('user-requested')\n\t\t .then(function (cache) {\n\t\t\t cache.add('https://httpbin.org/get');\n\t\t\t cache.add('/src/images/sf-boat.jpg');\n\t\t });\n\t}\n}",
"function onClickVocabularyImg() {\n\t// Set flag\n\t$('#scenario_vocabulary').val('vocabulary');\n\n\tonOffAreaScenarioVocabulary(CLIENT.ONVOCABULARY);\n}",
"function saveDiagram(){\n\tvar x=\"\";\n\tvar y=confirm(\"Save diagram as JPEG?\");\n\tvar canvas=$(\"canvas\");\n\n\tif(y==true){\n\t\t$(\"#configPopUp\").dialog({\n\t\t\tmodal: true,\n\t\t\twidth: \"auto\",\t\n\t\t\tautoResize: true,\n\t\t\tmaxHeight: 500,\n\t\t\topen: function(event, ui) { $(\".ui-dialog-titlebar-close\").show(); }\n\t\t});\n\t\t$(\"#configPopUp\").empty().load(\"pages/ConfigEditor/diagramFilename.html\");\n\t\t$('span.ui-dialog-title').text('SAVE DIAGRAM');\t\n\t\t$(\".ui-dialog\").position({\n \t my: \"center\",\n \tat: \"center\",\n\t of: window\n\t \t});\t\n\t}\n\treturn;\n}",
"save() {\n if (this.properties.saveCallback) {\n this.properties.saveCallback();\n } else if (this.properties.localStorageReportKey) {\n if ('localStorage' in window && window['localStorage'] !== null) {\n try {\n let report = this.getReport();\n // console.log(JSON.stringify(report));\n window.localStorage.setItem(this.properties.localStorageReportKey, JSON.stringify(report));\n this.modified = false;\n } catch (e) {}\n }\n }\n this.updateMenuButtons();\n }",
"function evSaveScreen (event) {\n\talert('saving screen definitions');\n}",
"function saveImage() {\n var data = canvas.toDataURL();\n $(\"#url\").val(data);\n }",
"addExportCanvasListener(){\n uiElements.BTN_EXPORT.addEventListener(\"click\", () => {\n uiElements.CANAVS.toBlob(function(blob){\n saveAs(blob, \"image.png\");\n });\n });\n }",
"function keyPressed() {\n if (keyCode === DELETE) {\n background(0);\n }\n\n// If the return key is pressed this will give the user an option to save\n// their canvas\n if (keyCode === RETURN) {\n save();\n save('myCanvas.jpg');\n }\n }",
"function keyPressed() {\r\n if (key == 'x') {\r\n save(\"screenshotART_151_\" + saveCount + \".png\");\r\n saveCount++;\r\n }\r\n}",
"function exportPngClick() {\n const filename = Data.IsSavedDiagram ?\n Data.SavedDiagramTitle :\n decodeURIComponent(Data.Filename);\n\n const svgXml = getSvgXml();\n const background = window.getComputedStyle(document.body).backgroundColor;\n exportPng(filename + '.png', svgXml, background);\n}",
"function saveGallery()\n{\n\tif (recogInitialized)\n\t{\n\t\tm_Recog.saveGallery(galleryFileName, function(name, status)\n\t\t{ \n\t\t if(status)\n\t\t {\t\n\t\t\t\tself.postMessage({aTopic: 'gallery saved'});\t\n\t\t }\n\t\t});\n\t}\n}",
"function BtnTaskApplyClick(){\n SaveTask(); \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Basic validation of the actions's structure: It should have an intent, an array of dependencies and notions | validate () {
if (typeof this.intent !== 'string') {
return false
}
if (!Array.isArray(this.dependencies) || !Array.isArray(this.notions)) {
return false
}
const dependenciesValidity = this.dependencies.every(dep => {
if (typeof dep.isMissing !== 'object') {
return false
}
if (!Array.isArray(dep.actions)) {
return false
}
return dep.actions.every(a => typeof a === 'string')
})
if (!dependenciesValidity) {
return false
}
const notionsValidity = this.notions.every(n => {
if (typeof n.isMissing !== 'object') {
return false
}
if (!Array.isArray(n.entities)) {
return false
}
return n.entities.every(e => typeof e === 'object' && typeof e.entity === 'string' && typeof e.alias === 'string')
})
if (!notionsValidity) {
return false
}
const requiresItself = this.dependencies.some(dependency => dependency.actions.some(a => a === this.name()))
if (this.dependencies.length > 0 && requiresItself) {
return false
}
return true
} | [
"dependenciesAreComplete (actions, conversation) {\n return this.dependencies.every(dependency => dependency.actions.some(a => {\n const requiredAction = actions[a]\n if (!requiredAction) {\n throw new Error(`Action ${a} not found`)\n }\n return requiredAction.isDone(conversation)\n }))\n }",
"isActionable (actions, conversation) {\n return this.dependenciesAreComplete(actions, conversation)\n }",
"function validateAction(action){\r\n\tvar actionArray = ['save', 'updateProfile', 'updateRSVP', 'delete', 'signout'];\r\n\tif(actionArray.includes(action)){\r\n\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}",
"function addRequiredAction(action) {\n setActions([...actions,action]);\n }",
"_validateAndParseCommandArguments() {\n const validationErrors = this._validateCommandArguments();\n\n if (validationErrors.length > 0) {\n _forEach(validationErrors, (error) => {\n throw error;\n });\n }\n }",
"static itemAction(item) {\n\t\t// If requirement doesn't exist or if requirement exists and is true\n\t\tif (item.hasOwnProperty(\"requirement\") ? Parser.parseJS(item.requirement) : true)\n\t\t{\n\t\t\tvar itemById = InventoryHandler.getItemById(item.name);\n\t\t\tswitch(item.action) {\n\t\t\t\tcase \"add\":\n\t\t\t\t\titemById.owned = true; // You own the object\n\t\t\t\t\tdelete itemById.scene; // It's not in any scene\n\t\t\t\t\t// DEBUG: show placed items\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`%cYou now own ${itemById.hidden ? \"hidden item\" : \"item\"} \"${itemById.name}\"`,\n\t\t\t\t\t\tconsoleStyles.debug\n\t\t\t\t\t);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"remove\":\n\t\t\t\t\tdelete itemById.scene; // The object is in no scene\n\t\t\t\t\titemById.owned = false; // You no longer own it\n\t\t\t\t\t// DEBUG: show placed items\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`%c${itemById.hidden ? \"Hidden item\" : \"Item\"} \"${itemById.name}\" was just removed\"`,\n\t\t\t\t\t\tconsoleStyles.debug\n\t\t\t\t\t);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"place\":\n\t\t\t\t\titemById.scene = item.scene; // The object is in the given scene\n\t\t\t\t\titemById.owned = false; // You no longer own it\n\t\t\t\t\t// DEBUG: show placed items\n\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t`%c${itemById.hidden ? \"Hidden item\" : \"Item\"} \"${itemById.name}\" was just placed into scene \"${itemById.scene}\"`,\n\t\t\t\t\t\tconsoleStyles.debug\n\t\t\t\t\t);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}",
"function validateArgs() {\n //No arguments or any argument set including the help argument are both\n //automatically valid.\n //If -pre, -dest, -ign, -ext, -enc, or -cst were provided, -repo\n //must also have been provided.\n //The presence of -sets and -args is always optional.\n\n //Allow no arguments or any set with a -help argument.\n if (0 === aargsGiven.length || -1 !== aargsGiven.indexOf('-help')) {\n return;\n }\n\n //Otherwise, require the -repo command if -pre, -dest, -ign, -ext,\n //-enc, or -cst were provided.\n if ((-1 !== aargsGiven.indexOf('-pre') ||\n -1 !== aargsGiven.indexOf('-dest') ||\n -1 !== aargsGiven.indexOf('-ign') ||\n -1 !== aargsGiven.indexOf('-ext') ||\n -1 !== aargsGiven.indexOf('-enc') ||\n -1 !== aargsGiven.indexOf('-cst')) &&\n -1 === aargsGiven.indexOf('-repo')) {\n throw 'Invalid argument set. Must use -repo if using any other ' +\n 'command except -help, -sets, or -args.';\n }\n }",
"getMissingDependencies (actions, conversation) {\n return this.dependencies\n .filter(d => d.actions.map(a => actions[a]).every(a => !a.isDone(conversation)))\n }",
"function handleRequest(req, res, urn){\n if(!isRequestValid(req)){\n return res.status(500).json({\n status: 'error',\n message: \"Fields required: \" + activityFields + \" and incorrect type required: Create, Update or Delete\"\n });\n }else return forwardRequest(req, res, urn);\n}",
"function validateItem (data, command) {\n var invalidMsg = 'Invalid Command - (' + command.member.displayName() + ' ITEM): ';\n var item = new Item(command.name, data);\n var ability;\n\n if (!command.name) {\n throw new Error(invalidMsg + 'command must include an item name.');\n } else if (!item.is_set) {\n throw new Error(invalidMsg + 'item ' + command.name + ' not found.');\n } else if (!item.hasItem(command.member)) {\n throw new Error(invalidMsg + 'inventory or equipment does not contain item ' + command.name);\n } else if (!command.target.name && item.target !== 'none') {\n throw new Error(invalidMsg + 'command must include a target');\n }\n\n ability = item.ability;\n if (ability) {\n switch (ability.type) {\n case 'SKILL':\n var skill = new Skill();\n if (!skill.findSkill(ability.name, data)) {\n throw new Error(invalidMsg + 'skill name ' + ability.name + ' not found.');\n }\n break;\n case 'SPELL':\n var spell = new Spell();\n if (!spell.findSpell(ability.name, data)) {\n throw new Error(invalidMsg + 'spell name ' + ability.name + ' not found.');\n }\n break;\n default:\n throw new Error(invalidMsg + 'unknown item ability type ' + ability.type);\n break;\n }\n }\n\n return true;\n }",
"function parseActionDescriptor(descriptor) {\n const descriptors = [];\n while (descriptor.trim()) {\n const matches = descriptor.match(actionDescriptorPattern);\n if (!matches) {\n console.error(`Descriptor '${descriptor}' is invalid.`);\n return [];\n }\n descriptors.push({\n event: matches[1] ? matches[1].slice(0, -2).trim() : undefined,\n identifier: matches[4],\n method: matches[5],\n options: matches[6] ? parseOptions(matches[6]) : []\n });\n descriptor = matches[7] || '';\n }\n return descriptors;\n}",
"function testActivityChoiceParsing() { \n Logger.log('Testing activity choice parsing...');\n \n if (!checkActivityChoiceParsing('Throwing',\n '5 pts./15 min.',\n 'Throwing [5 pts./15 min.] Throwing in pairs (at most 3 players/disc)')) {\n return false;\n }\n \n if (!checkActivityChoiceParsing('Playing video games',\n '1 pts./3 hr.',\n 'Playing video games [1 pts./3 hr.] Mindlessly gazing into your phone forever')) {\n return false;\n }\n \n if (!checkActivityChoiceParsing('Sharing media',\n '3 pts.',\n 'Sharing media [3 pts.] Blah blah blah')) {\n return false;\n }\n \n if (!checkActivityChoiceParsing('Daily team check-in',\n '1 pts.',\n 'Daily team check-in [1 pts.] Blah blah blah')) {\n return false;\n }\n \n Logger.log('Test passed.');\n return true;\n}",
"function isIngressValid(o) {\n annotations = o.metadata.annotations;\n Object.keys(definitions).forEach(function(key) {\n if (annotations[key]) {\n filter = definitions[key];\n if (!filter.exec(annotations[key])) {\n deny(\"metadata.annotations[\"+key+\"]\", \"invalid user input, should match: \"+ filter.toString(), annotations[key]);\n }\n }\n });\n}",
"hasAccountActions(){}",
"function validateParameters(args) {\n\tif (!args.camera) {\n\t\tsumerian.SystemBus.emit(\"sumerian.warning\", { title: \"Please specify the camera entity on Initialization.js\", message: \"Please specify the camera entity on the inspector panel of 'Initialization.js' on the 'Main Script' entity to configure your scene. By default, this entity is called 'Closeup Camera', and you can drag and drop the entity onto the inspector panel of the script file.\"});\n\t}\n\n\tif (!args.host) {\n\t\tsumerian.SystemBus.emit(\"sumerian.warning\", { title: \"Please specify the Host entity on Initialization.js\", message: \"Please specify the Host entity on the inspector panel of 'Initialization.js' on the 'Main Script' entity to configure the scene for your target screen size. By default, this entity is called 'Host', and you can drag and drop the entity onto the inspector panel of the script file.\"});\n\t}\n\n\tif (!args.poiTarget) {\n\t\tsumerian.SystemBus.emit(\"sumerian.warning\", { title: \"Please specify the Host POI entity on Initialization.js\", message: \"Please specify the Host's point of interest (POI) target entity on the inspector panel of 'Initialization.js' on the 'Main Script' entity to configure the scene for your target screen size. By default, this entity is called 'Host POI Target', and you can drag and drop the entity onto the inspector panel of the script file.\"});\n\t}\n}",
"legalArguments(args, params) {\n doCheck(\n args.length === params.length,\n `Expected ${params.length} args in call, got ${args.length}`\n );\n args.forEach((arg, i) => this.isAssignableTo(arg, params[i].type));\n }",
"generateActionMessages() {\n this.generateActionGoalMessage();\n this.generateActionResultMessage();\n this.generateActionFeedbackMessage();\n this.generateActionMessage();\n }",
"_validateCommandArguments() {\n const validatedCommandList = _map(this.commandList, (command) => {\n if (typeof command === 'undefined') {\n return null;\n }\n\n const errorMessage = command.validateArgs();\n\n if (errorMessage) {\n // we only return here so all the errors can be thrown at once\n // from within the calling method\n return errorMessage;\n }\n\n command.parseArgs();\n });\n\n return _compact(validatedCommandList);\n }",
"function validateActivities() {\n let checked = 0;\n for (let i = 0; i < checkboxes.length; i++) {\n const checkbox = checkboxes[i];\n if (checkbox.checked) {\n checked += 1;\n }\n }\n if (checked == 0) {\n return false;\n } else {\n return true;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a number to the list of allowed numbers Should not have any duplicates in allowedNums | addAllowedNum(num) {
if (!this.allowedNums.has(num)) {
this.allowedNums.add(num);
return `${num} added to allowedNums`;
} else {
return `${num} already in allowedNums`;
}
} | [
"function addGuess(num) {\n guesses.push(num);\n }",
"function roboNumbers(number) {\n const numbersArray = [];\n for(let i = 0; i <= number; i++){\n if (checkIfContains3(i)){\n numbersArray.push(\"Won't you be my neighbor?\");\n } else if(checkIfContains2(i)) {\n numbersArray.push(\"Boop!\");\n } else if(checkIfContains1(i)) {\n numbersArray.push(\"Beep!\");\n } else {\n numbersArray.push(i);\n }\n }\n return fixFormatting(numbersArray);\n}",
"function validateRandomNo(n){\n\t//check if no is aleady generated once\n\tif(!random_no.includes(n)){//if not generated push to random_no\n\t\trandom_no.push(n);\n\t\t//return true as no is not generated yet.\n\t\treturn true;\n\t}\n\telse{//is generated once\n\t\t//access it's index\n\t\tlet index = random_no.indexOf(n);//gives index of fist occurrence.\n\t\t//check if is generated twice\n\t\tif(random_no.indexOf(n,index+1) === -1){//n does not exist after index.\n\t\t\trandom_no.push(n);\n\t\t\treturn true;\n\t\t}\n\t\telse {//already generated twice\n\t\t\treturn\tfalse;\n\t\t}\n\t}\n}",
"function replaceN() {\n numbers[numbers.indexOf(12)] = 1221;\n numbers[numbers.indexOf(18)] = 1881;\n}",
"function addNumbers() {\n questionNumber++;\n}",
"_addPages (startNumber, upToNumbers) {\n var upTo = Math.min(...upToNumbers)\n\n for (var i = startNumber; i <= upTo; i++) {\n if (!this._pageNumberIncluded(i)) {\n this._addPageNumber(i)\n }\n }\n }",
"function add(rangeList, range) {\n // Noop if range collection already covers all\n if (rangeList === FULL) {\n return rangeList;\n } // Validate the input range\n\n\n if (range[0] < 0) {\n range[0] = 0;\n }\n\n if (range[0] >= range[1]) {\n return rangeList;\n } // TODO - split off to tree-shakable Range class\n\n\n const newRangeList = [];\n const len = rangeList.length;\n let insertPosition = 0;\n\n for (let i = 0; i < len; i++) {\n const range0 = rangeList[i];\n\n if (range0[1] < range[0]) {\n // the current range is to the left of the new range\n newRangeList.push(range0);\n insertPosition = i + 1;\n } else if (range0[0] > range[1]) {\n // the current range is to the right of the new range\n newRangeList.push(range0);\n } else {\n range = [Math.min(range0[0], range[0]), Math.max(range0[1], range[1])];\n }\n }\n\n newRangeList.splice(insertPosition, 0, range);\n return newRangeList;\n}",
"addNumToBack(num) {\n if (this.isNumAllowed(num)) this.numList.enqueue(num);\n // return this.numList[this.numList.length - 1];\n return this.numList.tail.value;\n }",
"function appendNumber(number) {\n appendNumberOrOperator(number);\n}",
"function specialNumbers(X) {\n let specialNums = [];\n let num = 2;\n while (true) {\n if (isPrime(num)) {\n let special1 = num * (num - 16);\n let special2 = num * (num + 16);\n if (special1 <= X) {\n specialNums.push(special1);\n }\n if (special2 <= X) {\n specialNums.push(special2);\n }\n if (special1 > 0 && special2 > 0 && special1 >= X && special2 >= X) {\n break;\n }\n }\n num++;\n }\n specialNums = [...new Set(specialNums)];\n specialNums.sort((a, b) => a - b);\n let isSpecialX = specialNums[specialNums.length - 1] === X;\n console.log(`${X} is ${isSpecialX ? '' : 'not '}special number!`);\n console.log(`special numbers under ${X}: `, specialNums.join(', '));\n\n function isPrime(num) {\n for (let i = 2; i < num; i++) {\n if (num % i === 0) return false;\n }\n return num > 1;\n }\n}",
"function plusOne(digits) {\n // loop backwards\n\n for(let i = digits.length - 1; i >= 0; i--) {\n if( digits[i] >= 9) {\n digits[i] = 0\n } else {\n digits[i]++;\n return digits;\n }\n }\n\n // now if we had increased a 9 to a 10 then\n // we add one a the beginning of the array\n return [1, ...digits];\n}",
"function findUniques(nums) {\n var newNums = [];\n\n for (var i = 0; i < nums.length; i++) {\n if (newNums.indexOf(nums[i]) < 0 )\n newNums.push(nums[i])\n }\n return newNums \n}",
"function addAllCurrencies(){\r\n\tfor(k = 0; k < denominations.length; k += 1){\r\n\t\tif(usedCurrencies.includes(\"\"+k)){continue;}\r\n\t\taddCurrency(\"\"+k);\r\n\t}\r\n}",
"function generateNumbers(){\n var set=new Array();\n for(i=0;i<9;i++){\n var number=Math.floor(Math.random()*9+1);\n while(set.indexOf(number)>-1){\n number=Math.floor(Math.random()*9+1);\n }\n set[i]=number;\n }\n return set;\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}",
"checkIfNumberAlreadyUsed(number) {\n return localStorage.getItem(\"chosen_nr\").includes(number.toString());\n }",
"function addOdds(evensOnlyArray) {\n var newArr = []\n for(var i = 0; i < evensOnlyArray.length; i++) {\n newArr.push(evensOnlyArray[i] + 1)\n }\n evensOnlyArray.unshift(1)\n return allNums = evensOnlyArray.concat(newArr)\n}",
"function addMSUtoMSU(){\n\t\n\tvar oldMSUTemp = document.getElementById('redExistMSUValue').value;\n\tvar newMSUTemp = document.getElementById('redMSUValue').value;\n\tif(!isNumber(oldMSUTemp) || !isNumber(newMSUTemp) ){\n\t\talert(\"Enter a valid Number!\");\n\t} else {\n\t\tif(checkExhibit() && oldMSUTemp != '' && newMSUTemp != '' ){\n\t\t\tvar oldMSU=0,newMSU=0;\n\t\t\toldMSU=parseInt(document.getElementById('redExistMSUValue').value);\n\t\t\tnewMSU=parseInt(document.getElementById('redMSUValue').value);\n\t\t\tvar total = (newMSU + oldMSU);\n\t\t\tvar totalVUTemp = convertMSUtoVU(total);\n\t\t\tconvertVUtoMSU(totalVUTemp,'redtotalUtilizationVal');\t\t\t\t\t\n\t\t\t\n\t\t\tvar oldVUforOldMSU = convertMSUtoVU(oldMSU);\n\t\t\tdocument.getElementById('redrequiredVUValue').innerHTML = totalVUTemp-oldVUforOldMSU;\t\t\n\t\t}\n\t}\t\n}",
"function checkNumbers(a, b) {\n if (a === 50 || b === 50 || a + b === 50) return true;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the headless horseman property for an object, creating it first, if necessary. | function getHH(obj) {
if (!obj.hasOwnProperty(_HH_PROPERTY)) {
obj[_HH_PROPERTY] = {};
}
return obj[_HH_PROPERTY];
} | [
"_firstHeading() {\n const headings = this._allHeadings();\n return headings[0];\n }",
"function objOrCreate(obj, prop) {\n\tif (!obj.hasOwnProperty(prop)) {\n\t\tobj[prop] = {};\n\t}\n\treturn obj[prop];\n}",
"function randomProperty (obj, random) {\n\t\t\tvar keys = Object.keys(obj);\n\t\t\treturn obj[keys[ random ]];\n\t\t}",
"ensureProperty(obj, prop, value) {\n if (!(prop in obj)) {\n obj[prop] = value;\n }\n }",
"createProperty(obj, name, value, post = null, priority = 0, transform = null, isPoly = false) {\n obj['__' + name] = {\n value,\n isProperty: true,\n sequencers: [],\n tidals: [],\n mods: [],\n name,\n type: obj.type,\n __owner: obj,\n\n fade(from = 0, to = 1, time = 4, delay = 0) {\n Gibber[obj.type].createFade(from, to, time, obj, name, delay);\n return obj;\n }\n\n };\n Gibber.addSequencing(obj, name, priority, value, '__');\n Object.defineProperty(obj, name, {\n configurable: true,\n get: Gibber[obj.type].createGetter(obj, name),\n set: Gibber[obj.type].createSetter(obj, name, post, transform, isPoly)\n });\n }",
"function Horn(horn) {\n this.image_url = horn.image_url; \n this.title = horn.title;\n this.description = horn.description;\n this.keyword = horn.keyword;\n this.horns = horn.horns;\n\n allHorns.push(this);\n}",
"function getHeroExample() {\n const EXAMPLES = getReactComponent('EXAMPLES');\n const exampleNames = Object.keys(EXAMPLES);\n let DefaultHeroExample = exampleNames.length && EXAMPLES[0];\n // HACK/ib - Check if this is a dummy example injected to keep graphgl happy\n // Set to null if undefined\n if (!DefaultHeroExample || DefaultHeroExample.title === 'none') {\n DefaultHeroExample = null;\n }\n\n let HeroExample = getReactComponent('HERO_EXAMPLE', DefaultHeroExample);\n if (!HeroExample) {\n console.warn('ocular: No hero example found', EXAMPLES);\n }\n return HeroExample;\n}",
"get heads () {\n const heads = {}\n this.miners.forEach(m => {\n const head = this.minersHeads[m]\n if (!heads[head]) {\n heads[head] = 0\n }\n heads[head]++\n })\n return heads\n }",
"getHoveredObject() {\n return this._hoveredOver;\n }",
"function determineHeading(){\n let player = determineTitle();\n\n // these conditions will never be true at the same time\n let checkMate = (props.checkMate ? \": CHECKMATE\" : \"\");\n let staleMate = (props.staleMate ? \": STALEMATE\" : \"\");\n\n // will not display \"CHECK\" if state is checkmate or stalemate\n let check = \"\";\n if ( !props.checkMate && !props.staleMate ){\n if ( props.inCheck )\n check = \": CHECK\";\n }\n else{\n check = \"\";\n }\n\n return player + checkMate + staleMate + check\n }",
"function getBlankMonster()\r\n{\r\n\treturn bestiary[3];\r\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}",
"function fetchPlayedHeroName(matchObj)\n{\n const HERO_ID = matchObj.hero_id;\n\n for (let id = 0; id < heroesObj.heroes.length; ++id)\n {\n const JSON_HERO_ID = heroesObj.heroes[id].id;\n if (JSON_HERO_ID == HERO_ID)\n {\n return heroesObj.heroes[id].localized_name + \" hero_id: \" + HERO_ID;\n }\n }\n return \"unmapped hero\" + \" hero_id: \" + HERO_ID;\n}",
"function findFirstProp(objs, p) {\n for (let obj of objs) {\n if (obj && obj.hasOwnProperty(p)) { return valueize(obj[p]); }\n }\n}",
"function getFrontGear() {\n return bicycle.frontGear;\n}",
"function shortenIfExists(obj, property) {\n if (obj[property]) {\n obj[property] = shorten(obj[property]);\n }\n}",
"function prop(name){\n return function(obj){\n return obj[name];\n };\n}",
"function SheHe(Obj) {\n if (Obj.gender == \"male\" || Obj.gender == \"Male\") {\n return \"He\";\n }\n else {\n if (Obj.gender == \"female\" || Obj.gender == \"Female\") {\n return \"She\";\n }\n }\n}",
"get metallic() {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to load grid when exiting from attack room | function loadGrid()
{
attRoom = -1;
document.removeEventListener('keyup',moveAttPlayer);
$.post("ajax/setAttackPlayer.php",
{
id: teamId,
room: '-1',
row: '0',
col: '0'
},
function(data,status){}
);
$('#attackTitle').text('Attack player: Grid');
$('#attackBox').load('grid.php');
$('#attackStoreButton').html("Go to Store");
} | [
"function loadGrid(roster, seed, classType) {\n\tvar sessionRoster = JSON.parse(sessionStorage.getItem('roster'));\n\tvar sessionClass = JSON.parse(sessionStorage.getItem('classroom'));\n\tvar sessionSeat = JSON.parse(sessionStorage.getItem('seats'))\n\tgrid = JSON.parse(sessionStorage.getItem('finalGridContainer'));\n\tgridCol = parseInt(sessionClass.width,10)\n\tgridRow = parseInt(sessionClass.height,10)\n\tnumPerStation = parseInt(sessionClass.numPerStation,10)\n\tfinalSeatMap = sessionSeat\n\tfinalSeed = seed\n\tstudents = roster.students\n students.sort(sortByName);\n\trosterSize = roster.students.length\n\t\n\t//console.log(finalSeatMap)\n\t//console.log(students)\n\t$('.finalGridContainer').append(grid);\n\t//$('.seat_item').attr(\"onclick\",\"swap($(this).attr('id'))\");\n\t//$('.station_item').attr(\"onclick\",\"displaySeatInfo($(this).attr('id'))\");\n\t//$('.seat_item').attr(\"onclick\",\"displaySeatInfo($(this).attr('id'))\");\n\t$('.station_item').attr(\"onclick\",\"\");\n\t$('.seat_item').attr(\"onclick\",\"\");\n\t$('.seat_item').attr(\"onmousedown\",\"mouseDown($(this).attr('id'))\");\n\t$('.seat_item').attr(\"onmouseup\", \"mouseUp($(this).attr('id'))\");\n\t$('.seat_item').each(function (value, index) {\n\t\t$(this).css('left', 0);\n\t});\n\n\tif (classType == \"lab\") {\n\t\tlab = true\n\t\tassignStationsByRow(seed);\n\t\tattachStationInfo()\n\t\tcreateSeatTable();\n\t}\n\telse {\n\t\tassignSeatsByRow(seed);\n\t\tattachInfo();\n\t\tcreateSeatTable();\n\t}\n}",
"function loadLevel(){\n\n\t\t//saveChar(n, r, ge, go, l, t, a);\n\t\tnewLevel++;\n // Next we get to change the background\n //var BG = PIXI.Texture.fromImage(\"res/\" + currentArea.name + \".png\");\n\t\tvar BG = PIXI.Texture.fromImage(currentArea.name + \".png\");\n\t doorOut.tint = 0x999966;\n\n\t\tconsole.log(\"\t\" + newLevel + \" \" + currentArea.name);\n\n\t\t// Gotta reset those chests, jsut gonna make new ones for now, will 'reset' them later.\n \t for(var i = 0; i < 5; i++){\n\n \t chests[i] = new chest(INDEX, i);\n\t chests[i].sprite.position.x = 650; //20 + (90 * i);\n \t chests[i].sprite.position.y = 42 + (80 * i); //50;\n \t stage.addChild(chests[i].sprite);\n \t }\n\t\t\n\t\t// Next we get to change the background\n \t//var BG = PIXI.Texture.fromImage(\"res/\" + currentArea.name + \".png\");\n\t\t//areaBackground.setTexture(BG);\n\t\tareaBackground.texture = BG;\n //stage.addChild(areaBackground);\n\t}",
"function resetGameOfLife()\n{\n // RESET ALL THE DATA STRUCTURES TOO\n gridWidth = canvasWidth/cellLength;\n gridHeight = canvasHeight/cellLength;\n updateGrid = new Array();\n renderGrid = new Array();\n \n // INIT THE CELLS IN THE GRID\n boardReset();\n \n // RENDER THE CLEARED SCREEN\n renderGame();\n}",
"load() {\n log.debug('Entities - load()', this.game.renderer);\n this.game.app.sendStatus('Lots of monsters ahead...');\n\n if (!this.sprites) {\n log.debug('Entities - load() - no sprites loaded yet', this.game.renderer);\n this.sprites = new Sprites(this.game.renderer);\n\n this.sprites.onLoadedSprites(() => {\n log.debug('Entities - load() - sprites done loading, loading cursors');\n this.game.input.loadCursors();\n this.game.postLoad();\n this.game.start();\n });\n }\n\n this.game.app.sendStatus('Yes, you are also a monster...');\n\n if (!this.grids) {\n log.debug('Entities - load() - no grids loaded yet');\n this.grids = new Grids(this.game.map);\n }\n }",
"function reloadDungeonPanel(contextPath) {\r\n\tif(dungeonId > 0 && $(\"[id^=equipmentdungeonsFrame]\").length < 1) {\r\n\t\tloadSpan('dungeonsFrame',contextPath+'/play/dungeon/'+dungeonId);\r\n\t}\r\n}",
"function resetGrid(){\n for (var col = 0; col < width; col++){\n var drop = document.getElementById('drop-'+col);\n drop.setAttribute('style','');\n drop.setAttribute('fill-opacity','0');\n }\n document.getElementById('game_end').style.display = 'none';\n playerTurn = 1;\n moveNumber = 1;\n document.getElementById('player_turn').innerHTML = \"Player 1's Move\";\n gameOver = false;\n for (var row = 0; row < height; row++){\n for (var col = 0; col < width; col++){\n grid[row][col] = 0;\n }\n }\n drawGrid();\n makeBotMove();\n}",
"function onScreenLoad(){\n\tstate = parent.newGameState(JSON.parse(localStorage[\"save\"]));\n\tstate.bugs = 9;\n\tscreen1.bugCount = $(\"#bugCount\");\n\tgenerateBreederList(state.breeders);\n\tdisplayTotal();\n\tparent.removeCover();\n}",
"function fnReloadGrid() {\n $boxGrid.paragonGridReload();\n }",
"function C101_KinbakuClub_RopeGroup_LoadJenna() {\n\tActorLoad(\"Jenna\", \"ClubRoom1\");\n\tLeaveIcon = \"\";\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 }",
"function clearGrid() {\n initializeColorGrid();\n draw();\n }",
"function loadGridMenu(){\n\t$.ajax({\n\t\turl: \"pages/ConfigEditor/gridPopup.html\",\n\t\tdataType: 'html',\n\t\tsuccess: function(data) {\n\t\t\t$(\"#gridPanel\").append(data);\n//\t\t\t$( \"#configEditorPage\" ).trigger('create');\n\t\t\tloadBarsMenu();\n\t\t}\n\t});\n}",
"function death (player, killFloor) {\n this.registry.destroy();\n this.events.off();\n this.scene.restart();\n}",
"loadLevelSALO() {\n g_references.clear();\n g_history.loadLevelFromClipboard().then(function () {\n this.deleteItemsEventsEtc();\n let that = this;\n this._room_canvas.clear();\n that.renderScene();\n }).catch(() => {\n alert(\"Something went wrong while loading your Level Code. Please check your Level Code and try again!\");\n });\n }",
"function refreshView() {\n let DOMcellCollection = document.getElementsByClassName('cell');\n for (let i = 0; i < DOMcellCollection.length; i++) {\n let DOMcell = DOMcellCollection[i];\n let DOMcellX = DOMcell.getAttribute('x');\n let DOMcellY = DOMcell.getAttribute('y');\n if (currentGame.grid[DOMcellX][DOMcellY].revealed) {\n DOMcell.classList.add('revealed');\n DOMcell.classList.remove('unrevealed');\n DOMcell.firstChild.classList.remove('hidden')\n }\n if (!currentGame.playing && currentGame.grid[DOMcellX][DOMcellY].isMine) {\n DOMcell.classList.add('exploded');\n DOMcell.classList.remove('unrevealed');\n DOMcell.firstChild.classList.remove('hidden')\n }\n }\n}",
"resetGrid() {\n this.createGridArray();\n\n // reinitializing the saved start and goal squares\n startSquareIndex = 0;\n goalSquareIndex = this.gridArray.length - 1;\n this.startSquare = this.getSquareByIndex(startSquareIndex);\n this.startSquare.state = start;\n this.goalSquare = this.getSquareByIndex(goalSquareIndex);\n this.goalSquare.state = goal;\n\n this.colorGrid(); // recolor the grid\n this.updateSquareCosts(); // update the costs for HTML\n this.isShowingCost = false;\n this.toggleCosts();\n }",
"function renderGameLost(ctx) {\n resultHeader.innerText = \"You Lost!\";\n gameBtn.innerText = SMILEY_FROWN;\n clearInterval(timer);\n revealEntireGrid(ctx);\n canvas.removeEventListener(\"click\", gridClickListener);\n}",
"function infectedGrid(currentBoard, row, column, currentPlayer) {\n\tvar opponent;\n\tif(currentPlayer == 1) {\n\t\topponent = 2;\n\t} \n\telse {\n\t\topponent = 1;\n\t}\n\n\tvar infectedGridList = [];\n\tif(row > 0 && row < length - 1 && column > 0 && column < length - 1) {\n\t\tif(currentBoard[row+1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row+1][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row+1][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t}\n\tif(row > 0 && row < length - 1 && column == 0) {\n\t\tif(currentBoard[row+1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row+1][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t}\n\tif(row > 0 && row < length - 1 && column == length - 1) {\n\t\tif(currentBoard[row-1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row+1][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row+1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t}\n\tif(row == 0 && column > 0 && column < length - 1) {\n\t\tif(currentBoard[row+1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row+1][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row+1][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\n\t}\n\tif(row == length - 1 && column > 0 && column < length - 1) {\n\t\tif(currentBoard[row][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t}\n\treturn infectedGridList;\n\n}",
"function useGame({\n initialGrid,\n generateGrid,\n rows,\n columns,\n mines,\n}) {\n const [playGrid, setPlayGrid] = useState(\n Array(rows)\n .fill(null)\n .map(() => Array(columns).fill(null)),\n );\n\n const [gameState, setGameState] = useState('playing');\n\n /**\n * Function to call when left click on cell\n * @param {int} rowIndex\n * @param {int} columnIndex\n * @returns {void}\n */\n const toggleFlag = (isFlagged, rowIndex, columnIndex) => {\n const newPlayGrid = [...playGrid];\n newPlayGrid[rowIndex][columnIndex] = isFlagged ? null : 'F';\n setPlayGrid(newPlayGrid);\n };\n\n /**\n * Function to call when right click on cell\n * @param {event} event need event to prevent default behaviour\n * @param {int} rowIndex\n * @param {int} columnIndex\n * @returns {void}\n */\n const handleRightClickOnCell = (event, rowIndex, columnIndex) => {\n event.preventDefault();\n const content = playGrid[rowIndex][columnIndex];\n const isFlagged = content === 'F';\n if (gameState === 'playing' && (isFlagged || content === null)) {\n toggleFlag(isFlagged, rowIndex, columnIndex);\n }\n };\n\n /**\n * Update gameState (victory/defeat/playing)\n * @returns {void}\n */\n const checkResult = () => {\n let newState = 'playing';\n let remainingCellCount = 0;\n for (let rowIndex = 0; rowIndex < rows; rowIndex += 1) {\n for (let columnIndex = 0; columnIndex < columns; columnIndex += 1) {\n const content = playGrid[rowIndex][columnIndex];\n if (content === 'F' || content === null) {\n // Count cells that weren't tested\n remainingCellCount += 1;\n } else if (content === 'X') {\n newState = 'defeat';\n setGameState(newState);\n return;\n }\n }\n }\n if (remainingCellCount === mines) {\n newState = 'victory';\n }\n setGameState(newState);\n };\n\n const revealGrid = () => {\n const newPlayGrid = [...playGrid];\n playGrid.forEach(((row, rowIndex) => {\n row.forEach((cell, columnIndex) => {\n if (cell === 'X') {\n newPlayGrid[rowIndex][columnIndex] = 'B';\n } else {\n newPlayGrid[rowIndex][columnIndex] = initialGrid[rowIndex][columnIndex];\n }\n });\n }));\n setPlayGrid(newPlayGrid);\n };\n\n /**\n * Reveal safe zone around safe cell located at rowIndex, columnIndex\n * @param {int} rowIndex\n * @param {int} columnIndex\n * @returns {void}\n */\n const revealZone = (rowIndex, columnIndex) => {\n const newPlayGrid = [...playGrid];\n\n let cellsToReveal = [[rowIndex, columnIndex]];\n let newCellsToReveal = [];\n let row;\n let column;\n\n const hasBeenChecked = Array(rows)\n .fill(null)\n .map(() => Array(columns).fill(false));\n\n do {\n newCellsToReveal = [];\n for (let i = 0; i < cellsToReveal.length; i += 1) {\n [row, column] = cellsToReveal[i];\n // reveal current cell\n newPlayGrid[row][column] = initialGrid[row][column];\n hasBeenChecked[row][column] = true;\n\n // search for adjacent cells to reveal\n if (row - 1 >= 0) {\n if (!hasBeenChecked[row - 1][column]) {\n if (initialGrid[row - 1][column] === 0) {\n // add top cell\n newCellsToReveal.push([row - 1, column]);\n } else {\n // limit number cell has been found\n newPlayGrid[row - 1][column] = initialGrid[row - 1][column];\n }\n hasBeenChecked[row - 1][column] = true;\n }\n if (column - 1 >= 0 && !hasBeenChecked[row - 1][column - 1]) {\n if (initialGrid[row - 1][column - 1] === 0) {\n // add top left hand corner cell\n newCellsToReveal.push([row - 1, column - 1]);\n } else {\n // limit number cell has been found\n newPlayGrid[row - 1][column - 1] = initialGrid[row - 1][column - 1];\n }\n hasBeenChecked[row - 1][column - 1] = true;\n }\n\n if (column + 1 < columns && !hasBeenChecked[row - 1][column + 1]) {\n if (initialGrid[row - 1][column + 1] === 0) {\n // add top right hand corner cell\n newCellsToReveal.push([row - 1, column + 1]);\n } else {\n // limit number cell has been found\n newPlayGrid[row - 1][column + 1] = initialGrid[row - 1][column + 1];\n }\n hasBeenChecked[row - 1][column + 1] = true;\n }\n }\n\n if (column - 1 >= 0 && !hasBeenChecked[row][column - 1]) {\n if (initialGrid[row][column - 1] === 0) {\n // add left cell\n newCellsToReveal.push([row, column - 1]);\n } else {\n // limit number cell has been found\n newPlayGrid[row][column - 1] = initialGrid[row][column - 1];\n }\n hasBeenChecked[row][column - 1] = true;\n }\n\n if (column + 1 < columns && !hasBeenChecked[row][column + 1]) {\n if (initialGrid[row][column + 1] === 0) {\n // add right cell\n newCellsToReveal.push([row, column + 1]);\n } else {\n // limit number cell has been found\n newPlayGrid[row][column + 1] = initialGrid[row][column + 1];\n }\n hasBeenChecked[row][column + 1] = true;\n }\n\n if (row + 1 < rows) {\n if (!hasBeenChecked[row + 1][column]) {\n if (initialGrid[row + 1][column] === 0) {\n // add bottom cell\n newCellsToReveal.push([row + 1, column]);\n } else {\n // limit number cell has been found\n newPlayGrid[row + 1][column] = initialGrid[row + 1][column];\n }\n hasBeenChecked[row + 1][column] = true;\n }\n\n if (column - 1 >= 0 && !hasBeenChecked[row + 1][column - 1]) {\n if (initialGrid[row + 1][column - 1] === 0) {\n // add bottom left hand cell\n newCellsToReveal.push([row + 1, column - 1]);\n } else {\n // limit number cell has been found\n newPlayGrid[row + 1][column - 1] = initialGrid[row + 1][column - 1];\n }\n hasBeenChecked[row + 1][column - 1] = true;\n }\n\n if (column + 1 < columns && !hasBeenChecked[row + 1][column + 1]) {\n if (initialGrid[row + 1][column + 1] === 0) {\n // add bottom right hand cell\n newCellsToReveal.push([row + 1, column + 1]);\n } else {\n // limit number cell has been found\n newPlayGrid[row + 1][column + 1] = initialGrid[row + 1][column + 1];\n }\n hasBeenChecked[row + 1][column + 1] = true;\n }\n }\n }\n // update cellsToReveal\n cellsToReveal = [...newCellsToReveal];\n // keep searching unless there are no more cells to reveal\n } while (cellsToReveal.length > 0);\n // update playGrid\n setPlayGrid(newPlayGrid);\n };\n\n /**\n * Reveal cell content located at rowIndex, columnIndex\n * @param {int} rowIndex\n * @param {int} columnIndex\n * @returns {void}\n */\n const revealCell = (rowIndex, columnIndex) => {\n const newPlayGrid = [...playGrid];\n const content = initialGrid[rowIndex][columnIndex];\n newPlayGrid[rowIndex][columnIndex] = content;\n setPlayGrid(newPlayGrid);\n };\n\n /**\n * Check content of cell at (rowIndex, columnIndex) in initGrid and change state of playGrid\n * @param {int} rowIndex\n * @param {int} columnIndex\n * @returns {int}\n */\n const tryCell = (rowIndex, columnIndex) => {\n const content = initialGrid[rowIndex][columnIndex];\n\n if (content === 0) {\n // reveal zone\n revealZone(rowIndex, columnIndex);\n } else {\n // revealCell\n revealCell(rowIndex, columnIndex);\n }\n };\n\n /**\n * Function to call when left click on cell\n * @param {int} rowIndex\n * @param {int} columnIndex\n * @returns {void}\n */\n const handleLeftClickOnCell = (rowIndex, columnIndex) => {\n if (gameState !== 'playing' || playGrid[rowIndex][columnIndex] !== null) {\n return;\n }\n tryCell(rowIndex, columnIndex);\n };\n\n const reset = () => {\n generateGrid(rows, columns, mines);\n setPlayGrid(Array(rows)\n .fill(null)\n .map(() => Array(columns).fill(null)));\n setGameState('playing');\n };\n\n useEffect(() => {\n reset();\n }, [rows, columns]);\n\n useEffect(() => {\n if (gameState === 'playing') {\n checkResult();\n }\n }, [playGrid]);\n\n useEffect(() => {\n if (gameState !== 'playing') {\n revealGrid();\n }\n }, [gameState]);\n\n return {\n playGrid,\n setPlayGrid,\n gameState,\n handleLeftClickOnCell,\n handleRightClickOnCell,\n tryCell,\n toggleFlag,\n checkResult,\n reset,\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use potions as neccesary | function UsePotion() {
if (currentTime<parent.next_pot) return false;
// default health potions heal 200
if (character.hp < 100) {
parent.use('hp');
Sleep(UsePotion, 500);
} else if (character.mp < 100) {
parent.use('mp');
Sleep(UsePotion, 500);
} else if (character.max_hp - character.hp > 200) {
parent.use('hp');
Sleep(UsePotion, 500);
} else if (character.max_mp - character.mp > 300) {
parent.use('mp');
Sleep(UsePotion, 500);
}
return true;
} | [
"function buy_potions()\n{\n\tvar potionTypes = [\"hpot0\", \"mpot0\"];\n\tvar purchaseAmount = 50;\n\n\tif(empty_slots() > 0)\n\t{\n\t\tfor(typeID in potionTypes)\n\t\t{\n\t\t\tvar type = potionTypes[typeID];\n\t\t\t\n\t\t\tvar item_def = parent.G.items[type];\n\t\t\t\n\t\t\tif(item_def != null)\n\t\t\t{\n\t\t\t\tvar cost = item_def.g * purchaseAmount;\n\n\t\t\t\tif(character.gold >= cost)\n\t\t\t\t{\n\t\t\t\t\tvar num_potions = num_items(type);\n\n\t\t\t\t\tif(num_potions < mininumPotionsToHaveOnHand)\n\t\t\t\t\t{\n\t\t\t\t\t\tbuy(type, purchaseAmount);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tgame_log(\"Not Enough Gold!\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tgame_log(\"Inventory Full!\");\n\t}\n}",
"function healingPotionMacro() {\n const speaker = ChatMessage.getSpeaker();\n let actor;\n if (speaker.token) actor = game.actors.tokens[speaker.token];\n if (!actor) actor = game.actors.get(speaker.actor);\n\n if (actor) {\n const currentDamage = parseInt(actor.data.data.characteristics.health.value);\n const healingRate = parseInt(actor.data.data.characteristics.health.healingrate);\n\n let newdamage = currentDamage - healingRate;\n if (newdamage < 0)\n newdamage = 0;\n\n actor.update({\n \"data.characteristics.health.value\": newdamage\n });\n\n\n var templateData = {\n actor: this.actor,\n token: canvas.tokens.controlled[0]?.data,\n data: {\n itemname: {\n value: game.i18n.localize('DL.DialogUseItemHealingPotion')\n },\n description: {\n value: game.i18n.localize('DL.DialogUseItemHealingPotionText').replace(\"#\", healingRate)\n }\n }\n };\n\n let chatData = {\n user: game.user._id,\n speaker: {\n actor: actor._id,\n token: actor.token,\n alias: actor.name\n }\n };\n\n let template = 'systems/demonlord/templates/chat/useitem.html';\n renderTemplate(template, templateData).then(content => {\n chatData.content = content;\n ChatMessage.create(chatData);\n });\n }\n}",
"function UseBots()\r\n{\r\n if (!config.calculateBotUsage)\r\n return;\r\n\r\n var currentArmor = GetCurrentArmorValue();\r\n var botInput = SearchForTagByValue('input', 'resid', '8');\r\n \r\n if (!botInput)\r\n return;\r\n \r\n\r\n var botBox = botInput.parentNode.childNodes[1];\r\n var botAmount = calculateBotRequirement(currentArmor);\r\n var currentBots = parseInt(botBox.parentNode.parentNode.childNodes[1].textContent, 10);\r\n \r\n if (currentBots < botAmount)\r\n botAmount = currentBots;\r\n\r\n /* Notify User */\r\n if (botAmount > 0)\r\n {\r\n botBox.value = botAmount;\r\n\r\n PAL.Toast('PRESS \"' + config.key_use_bots + '\" TO USE ' + botAmount + ' BOTS.', PAL.e_toastStyle.NOTIFY);\r\n }\r\n}",
"function selectPokemon(){\n var choosePokemon = prompt(\"Choose a Pokemon: BULBASAUR, CHARMANDER, SQUIRTLE, PIKACHU, DRATINI, EEVEE, MEOWTH, or RATTATA?\").toLowerCase();\n if (choosePokemon === \"bulbasaur\") {myPokemon = new Bulbasaur();}\n else if (choosePokemon === \"charmander\") {myPokemon = new Charmander();}\n else if (choosePokemon === \"squirtle\") {myPokemon = new Squirtle();}\n else if (choosePokemon === \"dratini\") {myPokemon = new Dratini();}\n else if (choosePokemon === \"eevee\") {myPokemon = new Eevee();}\n else if (choosePokemon === \"meowth\") {myPokemon = new Meowth();}\n else if (choosePokemon === \"rattata\") {myPokemon = new Rattata();}\n else {myPokemon = new Pikachu();} //default option if you fail to make a proper choice. (you can also choose it)\n myPokemon.inventory += 1; //will allow the user to heal twice\n //give user the option to choose a nickname\n var chooseNickname = confirm(\"Do you want to give your \" + choosePokemon + \" a nickname? Click 'OK' for yes, and 'CANCEL' for no\");\n if (chooseNickname === true) {var pokeNickname = prompt(\"What will you name your \" + choosePokemon + \"?\"); myPokemon.name = pokeNickname;}\n console.log(\"I choose you, \" + myPokemon.name + \"!!!\");\n\n //select the computer's pokemon:\n var botChoose = Math.floor(Math.random() * (8 - 1 + 1)) + 1; //random number from 1-8 represents number of pokemon\n if (botChoose === 1) {botPokemon = new Bulbasaur();}\n else if (botChoose === 2) {botPokemon = new Charmander();}\n else if (botChoose === 3) {botPokemon = new Squirtle();}\n else if (botChoose === 4) {botPokemon = new Dratini();}\n else if (botChoose === 5) {botPokemon = new Eevee();}\n else if (botChoose === 6) {botPokemon = new Meowth();}\n else if (botChoose === 7) {botPokemon = new Rattata();}\n else {botPokemon = new Pikachu();}\n console.log(\"The computer chose \" + botPokemon.name);\n //if the computer & user choose the same pokemon, prefix computer pokemon's name with \"enemy\" to differentiate it:\n if (myPokemon.name === botPokemon.name) {botPokemon.name = \"Enemy \" + botPokemon.name;}\n\nbattle(myPokemon, botPokemon);\n} //end selectPokemon function",
"function practice(ninja, weapon, technique) {}",
"function drawPropeller(){\n // your code here\n angle += angleSpeed;\n Body.setAngle(propeller.body, angle);\n Body.setAngularVelocity(propeller.body, angleSpeed);\n\n propeller.draw();\n}",
"_trapSpotter(character, trap, effect) {\n // Trap spotter only works with supported character sheets.\n let sheet = getOption('sheet');\n if(!sheet)\n return;\n\n // Use an implementation appropriate for the current character sheet.\n let hasTrapSpotter = getOption('fnHasTrapSpotter');\n\n // Check if the character has the Trap Spotter ability.\n if(hasTrapSpotter) {\n hasTrapSpotter(character)\n .then(hasIt => {\n\n // If they have it, make a secret Perception check.\n // Quit early if this character has already attempted to trap-spot\n // this trap.\n if(hasIt) {\n let trapId = trap.get('_id');\n let charId = trap.get('_id');\n\n // Check for a previous attempt.\n let attempts = state.itsatrapthemepathfinder.trapSpotterAttempts;\n if(!attempts[trapId])\n attempts[trapId] = {};\n if(attempts[trapId][charId])\n return;\n else\n attempts[trapId][charId] = true;\n\n // Make the secret Perception check.\n return this.getPerceptionModifier(character)\n .then(perception => {\n if(_.isNumber(perception))\n return TrapTheme.rollAsync(`1d20 + ${perception}`);\n else\n throw new Error('Trap Spotter: Could not get Perception value for Character ' + charToken.get('_id') + '.');\n })\n .then(searchResult => {\n return searchResult.total;\n })\n .then(total => {\n // Inform the GM about the Trap Spotter attempt.\n sendChat('Trap theme: ' + this.name, `/w gm ${character.get('name')} attempted to notice trap \"${trap.get('name')}\" with Trap Spotter ability. Perception ${total} vs DC ${effect.spotDC}`);\n\n // Resolve whether the trap was spotted or not.\n if(total >= effect.spotDC) {\n let html = TrapTheme.htmlNoticeTrap(character, trap);\n ItsATrap.noticeTrap(trap, html.toString(TrapTheme.css));\n }\n });\n }\n })\n .catch(err => {\n sendChat('Trap theme: ' + this.name, '/w gm ' + err.message);\n log(err.stack);\n });\n }\n }",
"function PropellingNozzles(power, afterBurnerCondition) {\n this.power = power,\n this.afterBurnerCondition = afterBurnerCondition\n}",
"function poids()\n{\n message.channel.send({ embed: {\n color:0x00AE86,\n title:'Création du personnage',\n description: 'Quel est votre poids (en kg)?',\n } });\n}",
"function partidaGuanyada(){\n //si estatParaula equival a la paraula, vol dir que tots els caràcters estàn descoverts. \n if( estatParaula===paraula){\n //substituim el teclat de pantalla per un missatge:\n document.getElementById('botonsPantalla').innerHTML = 'Has guanyat. Enhorabona. Ets un màquina.';\n }\n}",
"function mix() {\n const characterNum = randomNum(10);\n const characterNum2 = randomNum(10);\n const character = characters[characterNum];\n const quotedCharacter = characters[characterNum2];\n const quoteListLength = content[quotedCharacter].quotes.length;\n const quoteNum = randomNum(quoteListLength);\n const quotation = content[quotedCharacter].quotes[quoteNum];\n const image = content[character].image;\n monoImage.src = image;\n monoImage.alt = \"image of \" + character;\n monoQuote.innerHTML = quotation;\n\n}",
"function PrisonCatchKneelingEscape() {\n\tCharacterSetActivePose(Player, null, true);\n\tInventoryWear(Player, \"Chains\", \"ItemArms\", \"Default\", 3);\n\tInventoryGet(Player, \"ItemArms\").Property = { Type: \"Hogtied\", SetPose: [\"Hogtied\"], Difficulty: 0, Block: [\"ItemHands\", \"ItemLegs\", \"ItemFeet\", \"ItemBoots\"], Effect: [\"Block\", \"Freeze\", \"Prone\"] };\n\tCharacterRefresh(Player);\n\tPrisonPolice.Stage = \"CatchAggressive5\";\n\tPrisonPolice.CurrentDialog = DialogFind(PrisonPolice, \"CatchAggressiveFailedEscape\");\n}",
"function Phrase(options) {\r\n\r\n\tthis.lire = function () {\r\n\t\treturn this.corps;\r\n\t};\r\n\r\n\tthis.__assembler = function (texte) {\r\n\t\tvar resultat = texte.join(\" \");\r\n\t\tvar point = probaSwitch(Grimoire.recupererListe(\"PF\"), this.PROBA_POINT_FINAL);\r\n\t\tresultat = resultat.replace(/ \\,/g, \",\");\r\n\t\tresultat = resultat.replace(/' /g, \"'\");\r\n\t\tresultat = resultat.replace(/à les /g, \"aux \");\r\n\t\tresultat = resultat.replace(/à le /g, \"au \");\r\n\t\tresultat = resultat.replace(/ de ([aeiouhéèêàùäëïöü])/gi, \" d'$1\");\r\n\t\tresultat = resultat.replace(/ de les /g, \" des \");\r\n\t\tresultat = resultat.replace(/ de de(s)? ([aeiouéèêàîïùyh])/gi, \" d'$2\");\r\n\t\tresultat = resultat.replace(/ de de(s)? ([^aeiouéèêàîïùyh])/gi, \" de $2\");\r\n\t\tresultat = resultat.replace(/ de d'/g, \" d'\");\r\n\t\tresultat = resultat.replace(/ de (le|du) /g, \" du \");\r\n\t\tresultat = resultat.replace(/^(.*)je ([aeiouéèêàîïùyh])/i, \"$1j'$2\");\r\n\t\tresultat = resultat.replace(/£/g, \"h\").replace(/µ/g, \"Y\");\r\n\t\tresultat = resultat.substr(0, 1).toUpperCase() + resultat.substr(1) + point;\r\n\t\treturn resultat;\r\n\t};\r\n\r\n\toptions || (options = {});\r\n\tthis.PROBA_POINT_FINAL = [8, 1, 1];\r\n\r\n\tthis.structure = options.memeStr || Grimoire.genererStructure();\r\n\tthis.mots = [];\r\n\r\n\tvar posVerbe = -1, posVerbe2 = -1, posModal = -1, posDe = -1, posQue = -1, posPR = -1;\r\n\tvar personne = 0, temps = -1;\r\n\tvar premierGN = false, advPost = false, flagNoNeg = false;\r\n\r\n\t/* --- BOUCLE SUR LES BLOCS DE LA STRUCTURE --- */\r\n\tfor (var i = 0, iMax = this.structure.length; i < iMax; ++i) {\r\n\t\tif (this.structure[i].substr(0, 1) == \"§\") {\r\n\t\t\tvar litteral = this.structure[i].substr(1);\r\n\t\t\tif (litteral.indexOf(\"/\") > -1) {\r\n\t\t\t\tlitteral = litteral.split(\"/\")[(de(2) - 1)];\r\n\t\t\t}\r\n\t\t\tthis.mots.push(litteral);\r\n\t\t\tif (litteral == \"sans\") {\r\n\t\t\t\tflagNoNeg = true;\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tvar mot;\r\n\t\t\tif (this.structure[i] == \"GN\") {\r\n\t\t\t\tif (options.sujetChoisi && !premierGN) {\r\n\t\t\t\t\tmot = options.sujetChoisi;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif (de(11) > 1) {\r\n\t\t\t\t\t\tmot = Generateur.groupeNominal(premierGN);\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tmot = Grimoire.recupererMot(this.structure[i]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tpremierGN = true;\r\n\t\t\t} else if (this.structure[i] == \"CO\") {\r\n\t\t\t\tif (de(11) > 1) {\r\n\t\t\t\t\tmot = Generateur.complementObjet(personne);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tmot = Grimoire.recupererMot(this.structure[i]);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tmot = Grimoire.recupererMot(this.structure[i]);\r\n\t\t\t}\r\n\t\t\tvar posPersonne = mot.indexOf(\"@\");\r\n\t\t\tif (posPersonne > -1) {\r\n\t\t\t\tpersonne = (personne > 0) ? personne : parseInt(mot.substr(posPersonne + 1), 10);\r\n\t\t\t\tmot = mot.substr(0, posPersonne);\r\n\t\t\t}\r\n\t\t\tthis.mots.push(mot);\r\n\t\t}\r\n\t\tvar verbesNonMod = [\"VT\", \"VN\", \"VOA\", \"VOD\", \"VOI\", \"VTL\", \"VAV\", \"VET\", \"VOS\"];\r\n\t\tvar verbesMod = [\"VM\", \"VD\", \"VA\"];\r\n\t\tif (verbesNonMod.indexOf(this.structure[i]) > -1) {\r\n\t\t\tif (posVerbe > -1) {\r\n\t\t\t\tif (posModal > -1) {\r\n\t\t\t\t\tposVerbe2 = i;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tposModal = posVerbe;\r\n\t\t\t\t\tposVerbe = i;\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tposVerbe = i;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (verbesMod.indexOf(this.structure[i]) > -1) {\r\n\t\t\tposModal = i;\r\n\t\t}\r\n\t\tif (this.structure[i] == \"§que\") {\r\n\t\t\tposQue = i;\r\n\t\t}\r\n\t\tif (this.structure[i] == \"CT\") {\r\n\t\t\tvar posTemps = this.mots[i].indexOf(\"€\");\r\n\t\t\tif (posTemps > -1) {\r\n\t\t\t\ttemps = parseInt(this.mots[i].substr(posTemps + 1), 10);\r\n\t\t\t\tthis.mots[i] = this.mots[i].substr(0, posTemps);\r\n\t\t\t}\r\n\t\t\twhile (this.mots[i].indexOf(\"$\") > -1) {\r\n\t\t\t\tvar nom;\r\n\t\t\t\tdo {\r\n\t\t\t\t\tnom = Generateur.GN.nomsPropres.puiser().replace(/_F/, \"\");\r\n\t\t\t\t} while (this.mots[i].indexOf(nom) > -1);\r\n\t\t\t\tthis.mots[i] = this.mots[i].replace(/\\$/, nom);\r\n\t\t\t}\r\n\t\t\tthis.mots[i] = this.mots[i].replace(/ de ([aeiouyhéèâ])/gi, \" d'$1\");\r\n\r\n\t\t}\r\n\t\tif ((this.structure[i] == \"CL\") || (this.structure[i] == \"AF\")) {\r\n\t\t\twhile (this.mots[i].indexOf(\"$\") > -1) {\r\n\t\t\t\tvar nom;\r\n\t\t\t\tdo {\r\n\t\t\t\t\tnom = Generateur.GN.nomsPropres.puiser().replace(/_F/, \"\");\r\n\t\t\t\t} while (this.mots[i].indexOf(nom) > -1);\r\n\t\t\t\tthis.mots[i] = this.mots[i].replace(/\\$/, nom);\r\n\t\t\t}\r\n\t\t\tthis.mots[i] = this.mots[i].replace(/ de ([aeiouyhéèâ])/gi, \" d'$1\");\r\n\r\n\t\t\twhile (this.mots[i].indexOf(\"+\") > -1) {\r\n\t\t\t\tvar posPlus = this.mots[i].indexOf(\"+\");\r\n\t\t\t\tvar fem = this.mots[i].charAt(posPlus + 1) == \"F\";\r\n\r\n\t\t\t\tvar nom, ok;\r\n\t\t\t\tdo {\r\n\t\t\t\t\tok = true;\r\n\t\t\t\t\tnom = Generateur.GN.nomsCommuns.puiser();\r\n\t\t\t\t\tif (nom.indexOf(\"_\") > -1) {\r\n\t\t\t\t\t\tvar pos = nom.indexOf(\"_\");\r\n\t\t\t\t\t\tvar genre = nom.charAt(pos + 1);\r\n\t\t\t\t\t\tif (!fem && (genre == \"F\") || (fem && genre == \"H\")) {\r\n\t\t\t\t\t\t\tok = false;\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tnom = nom.split(\"_\")[0];\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tvar pos = nom.indexOf(\"%\");\r\n\t\t\t\t\t\tif (nom.substr(pos + 1).length == 1) {\r\n\t\t\t\t\t\t\tnom = nom.replace(/(.*)%e/, \"$1%$1e\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tnom = nom.split(\"%\")[((fem) ? 1 : 0)];\r\n\t\t\t\t\t}\r\n\t\t\t\t} while ((!ok) || (nom === undefined));\r\n\t\t\t\tnom = Generateur.accordPluriel(nom, false);\r\n\t\t\t\tthis.mots[i] = this.mots[i].replace(/\\+[FH]/, nom);\r\n\t\t\t}\r\n\r\n\t\t\tthis.mots[i] = this.mots[i].replace(/ de ([aeiouyhéèâ])/gi, \" d'$1\");\r\n\t\t}\r\n\t\tif ((this.structure[i] == \"CL\") || (this.structure[i] == \"CT\") || (this.structure[i] == \"AF\")) {\r\n\t\t\tvar nombre;\r\n\t\t\twhile (this.mots[i].indexOf(\"&\") > -1) {\r\n\t\t\t\tnombre = de(10) + 1;\r\n\t\t\t\tif (this.mots[i].indexOf(\"&0\") > -1) {\r\n\t\t\t\t\tnombre = (nombre * 10) - 10;\r\n\t\t\t\t}\r\n\t\t\t\tif (this.mots[i].indexOf(\"&00\") > -1) {\r\n\t\t\t\t\tnombre *= 10;\r\n\t\t\t\t}\r\n\t\t\t\tnombre = nombre.enLettres();\r\n\t\t\t\tthis.mots[i] = this.mots[i].replace(/&(0){0,2}/, nombre);\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (this.structure[i].split(\"_\")[0] == \"PR\") {\r\n\t\t\tposPR = i;\r\n\t\t}\r\n\t}\r\n\t/* --- FIN DE LA BOUCLE SUR LES BLOCS DE LA STRUCTURE --- */\r\n\tif (temps == -1)\r\n\t\ttemps = (de(2) > 1) ? 2 : de(3);\r\n\r\n\tif (posQue > -1) {\r\n\t\tthis.mots[posQue] = (this.mots[posQue + 1].voyelle()) ? \"qu'\" : \"que\";\r\n\t}\r\n\tif (posPR > -1) {\r\n\t\tvar tPers = 2;\r\n\t\tif ((/^s(\\'|e )/).test(this.mots[posPR])) {\r\n\t\t\ttPers = [2, personne];\r\n\t\t}\r\n\t\tvar neg1 = \"\", neg2 = \"\";\r\n\t\tif ((!flagNoNeg) && (de(9) > 8)) {\r\n\t\t\tneg1 = (this.mots[posPR].voyelle()) ? \"n'\" : \"ne \";\r\n\t\t\tneg2 = \" \" + probaSwitch(Grimoire.recupererListe(\"NG\"), Grimoire.PROBA_NEGATIONS);\r\n\t\t}\r\n\t\tthis.mots[posPR] = \"en \" + neg1 + Grimoire.conjuguer(this.mots[posPR], 4, tPers) + neg2;\r\n\t}\r\n\r\n\tif (posModal > -1) {\r\n\t\tvar baseVerbe = Grimoire.conjuguer(this.mots[posModal], temps, personne);\r\n\t\tif (!flagNoNeg && !advPost && (de(11) > 10)) {\r\n\t\t\tvar voyelle = baseVerbe.voyelle();\r\n\t\t\tvar neg = probaSwitch(Grimoire.recupererListe(\"NG\"), Grimoire.PROBA_NEGATIONS);\r\n\t\t\tbaseVerbe = ((voyelle) ? \"n'\" : \"ne \") + baseVerbe + \" \" + neg;\r\n\t\t}\r\n\t\tthis.mots[posModal] = baseVerbe;\r\n\r\n\t\tif (this.mots[posVerbe].indexOf(\"#\") > -1) {\r\n\t\t\tthis.mots[posVerbe] = this.mots[posVerbe].split(\"#\")[0];\r\n\t\t}\r\n\t\tif (((personne % 3) != 0) && (/^s(\\'|e )/).test(this.mots[posVerbe])) {\r\n\t\t\tvar pr = Grimoire.pronomsReflexifs[personne - 1] + \" \";\r\n\t\t\tif ((this.mots[posVerbe].indexOf(\"'\") > -1) && (personne < 3)) {\r\n\t\t\t\tpr = pr.replace(/e /, \"'\");\r\n\t\t\t}\r\n\t\t\tthis.mots[posVerbe] = this.mots[posVerbe].replace(/s(\\'|e )/, pr);\r\n\t\t}\r\n\t\tif (!flagNoNeg && (de(11) > 10)) {\r\n\t\t\tvar neg2 = probaSwitch(Grimoire.recupererListe(\"NG\"), Grimoire.PROBA_NEGATIONS);\r\n\t\t\tthis.mots[posVerbe] = \"ne \" + neg2 + \" \" + this.mots[posVerbe];\r\n\t\t}\r\n\t\tif (posVerbe2 > -1) {\r\n\t\t\tif (this.mots[posVerbe2].indexOf(\"#\") > -1) {\r\n\t\t\t\tthis.mots[posVerbe2] = this.mots[posVerbe2].split(\"#\")[0];\r\n\t\t\t}\r\n\t\t\tif (((personne % 3) != 0) && (/^s(\\'|e )/).test(this.mots[posVerbe2])) {\r\n\t\t\t\tvar pr = Grimoire.pronomsReflexifs[personne - 1] + \" \";\r\n\t\t\t\tif ((this.mots[posVerbe2].indexOf(\"'\") > -1) && (personne < 3)) {\r\n\t\t\t\t\tpr = pr.replace(/e /, \"'\");\r\n\t\t\t\t}\r\n\t\t\t\tthis.mots[posVerbe2] = this.mots[posVerbe2].replace(/s(\\'|e )/, pr);\r\n\t\t\t}\r\n\t\t\tif (!flagNoNeg && (de(11) > 10)) {\r\n\t\t\t\tvar neg2 = probaSwitch(Grimoire.recupererListe(\"NG\"), Grimoire.PROBA_NEGATIONS);\r\n\t\t\t\tthis.mots[posVerbe2] = \"ne \" + neg2 + \" \" + this.mots[posVerbe2];\r\n\t\t\t}\r\n\t\t}\r\n\t} else if (posVerbe > -1) {\r\n\t\tvar baseVerbe = Grimoire.conjuguer(this.mots[posVerbe], temps, personne);\r\n\t\tif (baseVerbe === undefined)\r\n\t\t\treturn new Phrase(options);// et sa copine\r\n\t\tif (!flagNoNeg && !advPost && (de(11) > 10)) {\r\n\t\t\tvar voyelle = baseVerbe.voyelle();\r\n\t\t\tvar neg = probaSwitch(Grimoire.recupererListe(\"NG\"), Grimoire.PROBA_NEGATIONS);\r\n\t\t\tbaseVerbe = ((voyelle) ? \"n'\" : \"ne \") + baseVerbe + \" \" + neg;\r\n\t\t}\r\n\t\tthis.mots[posVerbe] = baseVerbe;\r\n\t}\r\n\r\n\tthis.corps = this.__assembler(this.mots);\r\n\treturn this;\r\n}",
"function useSkill(skillNumber, mainCharacter, enemy){\n\n if(skillNumber>=1 && skillNumber<=4){\n var skill = mainCharacter.getSkill(skillNumber-1);\n var dmg = getSkillDamage(mainCharacter, enemy, skillNumber); // Skill kullandık.\n\n if (dmg == \"cooldown\"){ // Cooldown Control\n cout(skill.name+\" cooldown \"+skill.current_cooldown+\" turn\",\"yellow\");\n return;\n } else if (dmg == \"no_mana\"){ // Mana Control\n cout(\"Not Enough Mana for \"+skill.name,\"purple\");\n return;\n } else if (dmg != 0){\n enemy.healthDown(dmg);\n }\n if(enemy.getHealth() <= 0){\n endFight(1, enemy); // Kazandı ise 1, 2. parametre exp\n return;\n }\n }\n if(skillNumber==5){\n if(mainCharacter.getHealth() == mainCharacter.getMaxHealth()){\n cout(\"Your HP is Full\", \"yellow\");\n return;\n }\n if(!getItemById(1)){\n cout(\"You don't have Health Potion!\",\"red\");\n return;\n }\n else\n useHpPotion(mainCharacter);\n }\n if(skillNumber==6){\n if(mainCharacter.getMana() == mainCharacter.getMaxMana()){\n cout(\"Your Mana is Full\", \"yellow\");\n return;\n }\n if(!getItemById(5)){\n cout(\"You don't have Mana Potion!\",\"red\");\n return;\n }\n else\n useManaPotion(mainCharacter);\n }\n\n // Enenmy(AI) Damage\n var random_skill, dmg2;\n do{\n if(enemy.getMana() < enemy.getSkill(3).mana_cost && enemy.getHealth() * 5/4 < mainCharacter.getHealth()){ // Manası ultiye yetmiyor ve canı bizden az ise:\n dmg2 == \"ulti_degil\";\n dmg2 = getSkillDamage(enemy, mainCharacter, 1); // AI Basic Attack yaptı.\n } else { // Manası ultiye yetiyor ise:\n dmg2 = getSkillDamage(enemy, mainCharacter, 4); // AI ulti attı.\n if(dmg2 == \"no_mana\" || dmg2 == \"cooldown\"){\n random_skill = getRandomInt(1,4);\n dmg2 = getSkillDamage(enemy, mainCharacter, random_skill); // AI skill kullandı.\n }\n }\n\n } while (dmg2 == \"no_mana\" || dmg2 == \"cooldown\" || dmg2 == \"ulti_degil\");\n if (dmg2 != 0){\n mainCharacter.healthDown(dmg2);\n }\n if(mainCharacter.getHealth() <= 0){\n endFight(0); // Kazanamadı ise 0\n }\n cout(\"-----\");\n}",
"function collectMilkBottle() {\n if (collide(player, milkBottle, 60)) {\n player.sprite = player.withMb;\n milkBottle.hide();\n }\n }",
"firePhazer() {\n if (this.chargeEmpty === false) {\n let newPhazer = new Phazers();\n player.updateCharge();\n phazers.push(newPhazer);\n laserBlast.play();\n }\n //if the player tries to fire the phaser while charge is empty, play the empty battery sound\n else {\n lowCharge.playMode('untilDone');\n lowCharge.play();\n }\n }",
"function PrisonMaidLightTorture() {\n\tPrisonMaidIsAngry = true;\n\tPrisonMaid.Stage = \"PrisonerTortured\";\n\tvar torture = Math.random() * 4;\n\tif (torture < 1) {\n\t\tPrisonMaid.CurrentDialog = DialogFind(PrisonMaid, \"PrisonMaidTortureFondleButt\");\n\t} else if (torture < 2) {\n\t\tPrisonMaid.CurrentDialog = DialogFind(PrisonMaid, \"PrisonMaidTortureFondleBreast\");\n\t} else if (torture < 3) {\n\t\tPrisonMaid.CurrentDialog = DialogFind(PrisonMaid, \"PrisonMaidTortureMassage\");\n\t} else if (torture < 4) {\n\t\tPrisonMaid.CurrentDialog = DialogFind(PrisonMaid, \"PrisonMaidTortureTickle\");\n\t}\n}",
"particleBurst(killer){\n\t\tfor(var i = 35; i > 0; i--){\n\t\t\tvar p = new seekerParticle(this.pos.x, this.pos.y, \"#55d\", killer);\n\t\t\tp.setRandVel(Math.random() * 35);\n\t\t\tparticles.push(p);\n\t\t}\n\t}",
"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}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function calculates the sum of the chip counts and counts the number of splitting players then calculates the split percentage each player gets. | function setSplits(pay_3, pay_2, pay_1) {
var check_box = document.getElementsByName('splits[]');
var chip_count = document.getElementsByName('chipcounts[]');
var original_splits = document.getElementsByName('original_splits[]');
var split_count = 0;
var chip_count_value = 0;
var preceeding_chip_count = 0;
var chip_count_sum = 0;
var players_chip_count = 0;
// Loop through all the check boxes.
for (i = 0; i < check_box.length; i++) {
// Hide all the chipcount text boxes
chip_count[i].style.visibility = "hidden";
// If the third place player is not checked to split, change their split_diff
// back to it's default according to the settings
if (check_box[i].checked === false && i === check_box.length - 3) {
chip_count[i].value = pay_3;
}
// If the second place player is not checked to split, change their split_diff
// back to it's default according to the settings
if (check_box[i].checked === false && i === check_box.length - 2) {
chip_count[i].value = pay_2;
}
// If the first place player is not checked to split, change their split_diff
// back to it's default according to the settings
if (check_box[i].checked === false && i === check_box.length - 1) {
chip_count[i].value = pay_1;
}
// If a check box is checked count it as a splitting player.
if (check_box[i].checked) {
split_count = split_count + 1;
}
// If the associated chip count with the splitting player
// has no value, set the chip count to 0. Otherwise, get
// the integer value of the given chip count value.
if (chip_count[i].value === "") {
chip_count_value = 0;
} else {
chip_count_value = parseInt(chip_count[i].value);
// Make sure that a lower winner, preceeding chip count, does not have a larger
// chip count than a higher winner.
if (preceeding_chip_count > chip_count_value) {
alert("Check you chip counts! You can not have a larger chip count for a lower winner.");
return false;
}
preceeding_chip_count = chip_count_value;
}
// Sum all the chip_count values to get the total chip count sum.
chip_count_sum = chip_count_sum + chip_count_value;
}
// If there is only one split_count, notify the user that a split must have at least
// two players and exit the function.
if (split_count === 1) {
alert("You must have at least two players to split!");
return false;
}
// If the chip count sum = 0, the the split is done evenly and set the
// chip count sum to 1.
if (chip_count_sum === 0) {
chip_count_sum = 1;
// For every check box that is checked, divide the chip count sum by
// the split count to find the even percetage each splitting player gets.
for (i = 0; i < check_box.length; i++) {
if (check_box[i].checked) {
chip_count[i].value = chip_count_sum / split_count;
}
}
// If the chip count sum > 0, then the split is done by percentage.
} else {
// For every check box that is checked, divide the corresponding
// chip count value by the total chip count sum to get the
// percentage of each splitting player.
for (i = 0; i < check_box.length; i++) {
if (check_box[i].checked) {
players_chip_count = parseInt(chip_count[i].value);
// If the chip_count_sum is > 0 then the split is by percentage and no splitting players
// can have a chip count of 0
if (players_chip_count <= 0 || isNaN(players_chip_count)) {
alert("All splitting players must have a chip count!");
return false;
}
if (split_count === 2) {
// If only 2 players are splitting, subtract 3rd place's percetage from
// each of the chip counts to account for the percentage they get.
chip_count[i].value = (players_chip_count - (players_chip_count * pay_3)) / chip_count_sum;
// Save the original split percentage to the hidden field to use when splitting points.
original_splits[i].value = players_chip_count / chip_count_sum;
} else {
chip_count[i].value = players_chip_count / chip_count_sum;
// Save the original split percentage to the hidden field to use when splitting points.
original_splits[i].value = players_chip_count / chip_count_sum;
}
}
}
}
return true;
} | [
"calculatePercentage(player) {\n\t\t\tplayer.percentage = (parseFloat(player.wins) / parseFloat(player.games)).toFixed(3);\n\t\t}",
"function getTotalScore() {\n\n let ai = 0;\n let human = 0;\n\n //Calculate pawn penalties\n //Number of pawns in each file\n let human_pawns = [];\n let ai_pawns = [];\n\n for (let x = 0; x < 8; x++) {\n\n let h_cnt = 0;\n let a_cnt = 0;\n\n for (let y = 0; y < 8; y++) {\n\n let chk_piece = board[y][x];\n\n if (chk_piece != null && chk_piece instanceof Pawn) {\n\n if (chk_piece.player == 'human') h_cnt++;\n else a_cnt++;\n\n //Pawn rank bonuses\n if (x > 1 && x < 6) {\n\n //Normalize y to chess rank 1 - 8\n let rank = (chk_piece.player == 'human') ? Math.abs(y - 7) + 1 : y + 1;\n\n switch (x) {\n\n case 2:\n if (chk_piece == 'human' && chk_piece.color == 'white') human += 3.9 * (rank - 2);\n else if (chk_piece == 'human' && chk_piece.color == 'black') human += 2.3 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'white') ai -= 2.3 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'black') ai -= 3.9 * (rank - 2);\n break;\n\n case 3:\n if (chk_piece == 'human' && chk_piece.color == 'white') human += 5.4 * (rank - 2);\n else if (chk_piece == 'human' && chk_piece.color == 'black') human += 7.0 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'white') ai -= 7.0 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'black') ai -= 5.4 * (rank - 2);\n break;\n\n case 4:\n if (chk_piece == 'human' && chk_piece.color == 'white') human += 7.0 * (rank - 2);\n else if (chk_piece == 'human' && chk_piece.color == 'black') human += 5.4 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'white') ai -= 5.4 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'black') ai -= 7.0 * (rank - 2);\n break;\n\n case 5:\n if (chk_piece == 'human' && chk_piece.color == 'white') human += 2.3 * (rank - 2);\n else if (chk_piece == 'human' && chk_piece.color == 'black') human += 3.9 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'white') ai -= 3.9 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'black') ai -= 2.3 * (rank - 2);\n break;\n\n }\n\n }\n\n }\n\n }\n\n human_pawns.push(h_cnt);\n ai_pawns.push(a_cnt);\n\n }\n\n for (let i = 0; i < 8; i++) {\n\n //Doubled pawn penalty\n if (human_pawns[i] > 1) human -= (8 * human_pawns[i]);\n if (ai_pawns[i] > 1) ai += (8 * ai_pawns[i]);\n\n //Isolated pawn penalties\n if (i == 0) {\n if (human_pawns[i] > 0 && human_pawns[i + 1] == 0) human -= (10 * human_pawns[i]);\n if (ai_pawns[i] > 0 && ai_pawns[i + 1] == 0) ai += (10 * ai_pawns[i]);\n }\n else if (i == 7) {\n if (human_pawns[i] > 0 && human_pawns[i - 1] == 0) human -= (10 * human_pawns[i]);\n if (ai_pawns[i] > 0 && ai_pawns[i - 1] == 0) ai += (10 * ai_pawns[i]);\n }\n else {\n if (human_pawns[i] > 0 && human_pawns[i - 1] == 0 && human_pawns[i + 1] == 0) human -= (10 * human_pawns[i]);\n if (ai_pawns[i] > 0 && ai_pawns[i - 1] == 0 && ai_pawns[i + 1] == 0) ai += (10 * ai_pawns[i]);\n }\n\n }\n\n //Get material score\n for (let y = 0; y < 8; y++) {\n\n for (let x = 0; x < 8; x++) {\n\n if (board[y][x] != null) {\n\n let piece = board[y][x];\n\n //Material\n if (piece.player == 'human') human += piece.score;\n else ai += piece.score; \n\n //Knight bonuses/penalties \n if (piece instanceof Knight) {\n\n //Center tropism\n let c_dx = Math.abs(3.5 - x);\n let c_dy = Math.abs(3.5 - y);\n\n let c_sum = 1.6 * (6 - 2 * (c_dx + c_dy));\n\n if (piece.player == 'human') human += c_sum;\n else ai -= c_sum;\n\n //King tropism\n if (piece.player == 'human') {\n\n let k_dx = Math.abs(_cking.x - x);\n let k_dy = Math.abs(_cking.y - y);\n\n let k_sum = 1.2 * (5 - (k_dx + k_dy));\n\n human += k_sum;\n\n\n } else {\n\n let k_dx = Math.abs(_pking.x - x);\n let k_dy = Math.abs(_pking.y - y);\n\n let k_sum = 1.2 * (5 - (k_dx + k_dy));\n\n ai -= k_sum;\n\n }\n\n }\n\n //Rook bonuses/penalties\n else if (piece instanceof Rook) {\n\n //Seventh rank bonus\n if (piece.player == 'human' && y == 1) human += 22;\n else if (piece.player == 'ai' && y == 6) ai -= 22;\n\n //King tropism\n if (piece.player == 'human') {\n\n let k_dx = Math.abs(_cking.x - x);\n let k_dy = Math.abs(_cking.y - y);\n\n let k_sum = -1.6 * Math.min(k_dx, k_dy);\n\n human += k_sum;\n\n } else {\n\n let k_dx = Math.abs(_pking.x - x);\n let k_dy = Math.abs(_pking.y - y);\n\n let k_sum = -1.6 * Math.min(k_dx, k_dy);\n\n ai -= k_sum;\n\n }\n\n //Doubled rook bonus\n //Check rank\n let left_chk = true;\n let right_chk = true;\n let up_chk = true;\n let down_chk = true;\n for (let i = 1; i < 8; i++) {\n\n if (!left_chk && !right_chk && !down_chk && !up_chk) break;\n\n //Check left side\n if (x - i >= 0 && left_chk) {\n\n let chk_piece = board[y][x - i];\n if (chk_piece != null) {\n if (chk_piece instanceof Rook && chk_piece.player == piece.player) break;\n else left_chk = false;\n }\n\n } else left_chk = false;\n\n //Check right side\n if (x + i < 8 && right_chk) {\n\n let chk_piece = board[y][x + i];\n if (chk_piece != null) {\n if (chk_piece instanceof Rook && chk_piece.player == piece.player) break;\n else right_chk = false;\n }\n\n } else right_chk = false;\n\n //Check up side\n if (y - i >= 0 && up_chk) {\n\n let chk_piece = board[y - i][x];\n if (chk_piece != null) {\n if (chk_piece instanceof Rook && chk_piece.player == piece.player) break;\n else up_chk = false;\n }\n\n } else up_chk = false;\n\n //Check down side\n if (y + i < 8 && down_chk) {\n\n let chk_piece = board[y + i][x];\n if (chk_piece != null) {\n if (chk_piece instanceof Rook && chk_piece.player == piece.player) break;\n else down_chk = false;\n }\n\n } else down_chk = false;\n\n }\n\n //Doubled rook found\n if (left_chk || right_chk || down_chk || up_chk) {\n\n if (piece.player == 'human') human += 8;\n else ai -= 8;\n\n }\n\n //Open file bonus\n let open_file = true;\n\n for (let i = 1; i < 8; i++) {\n\n //Check up\n if (y - i >= 0) {\n\n let chk_piece = board[y - i][x];\n if (chk_piece != null) {\n if (chk_piece instanceof Pawn) {\n open_file = false;\n break;\n }\n }\n\n }\n\n //Check down\n if (y + i < 8) {\n\n let chk_piece = board[y + i][x];\n if (chk_piece != null) {\n if (chk_piece instanceof Pawn) {\n open_file = false;\n break;\n }\n }\n\n }\n\n }\n\n if (open_file) {\n\n if (piece.player == 'human') human += 8;\n else ai -= 8;\n\n }\n\n\n }\n\n //Queen bonuses/penalties\n else if (piece instanceof Queen) {\n\n //King tropism\n if (piece.player == 'human') {\n\n let k_dx = Math.abs(_cking.x - x);\n let k_dy = Math.abs(_cking.y - y);\n\n let k_sum = -0.8 * Math.min(k_dx, k_dy);\n\n human += k_sum;\n\n\n } else {\n\n let k_dx = Math.abs(_pking.x - x);\n let k_dy = Math.abs(_pking.y - y);\n\n let k_sum = -0.8 * Math.min(k_dx, k_dy);\n\n ai -= k_sum;\n\n }\n\n }\n\n //King bonuses/penalties\n else if (piece instanceof King) {\n\n //Cant castle penalty\n if (!piece.hasCastled) {\n\n //Castling no longer possible as king has moved at least once\n if (!piece.firstMove) {\n\n if (piece.player == 'human') human -= 15;\n else ai += 15;\n\n } else {\n\n //Rooks\n let q_rook;\n let k_rook;\n\n //Check flags, true if castling is available\n let q_rook_chk = false;\n let k_rook_chk = false;\n\n if (piece.player == 'human') {\n\n if (piece.color == 'white') {\n\n q_rook = castleRook(piece, x - 2, y);\n k_rook = castleRook(piece, x + 2, y);\n\n } else {\n\n q_rook = castleRook(piece, x + 2, y);\n k_rook = castleRook(piece, x - 2, y);\n\n }\n\n } else {\n\n if (piece.color == 'white') {\n\n q_rook = castleRook(piece, x + 2, y);\n k_rook = castleRook(piece, x - 2, y);\n\n } else {\n\n q_rook = castleRook(piece, x - 2, y);\n k_rook = castleRook(piece, x + 2, y);\n\n }\n\n }\n\n q_rook_chk = q_rook != null && q_rook.firstMove;\n k_rook_chk = k_rook != null && k_rook.firstMove;\n\n //Castling no longer available\n if (!q_rook_chk && !k_rook_chk) {\n\n if (piece.player == 'human') human -= 15;\n else ai += 15;\n \n }\n //Queen side castling not available\n else if (!q_rook_chk) {\n\n if (piece.player == 'human') human -= 8;\n else ai += 8;\n\n }\n //King side castling not available\n else if (!k_rook_chk) {\n\n if (piece.player == 'human') human -= 12;\n else ai += 12;\n\n }\n\n }\n\n //Check kings quadrant\n let enemy_pieces = 0;\n let friendly_pieces = 0;\n\n //Find quadrant\n //Top/Left\n if (y < 4 && x < 4) {\n\n for (let i = 0; i < 4; i++) {\n\n for (let j = 0; j < 4; j++) {\n\n let chk_piece = board[i][j];\n if (chk_piece != null) {\n\n //Skip this cell as this is the king\n if (i == y && x == j) continue;\n\n //Enemy piece found\n if (piece.player != chk_piece.player) {\n\n if (chk_piece instanceof Queen) enemy_pieces += 3;\n else enemy_pieces++;\n\n }\n //Friendly piece found\n else {\n\n if (chk_piece instanceof Queen) friendly_pieces += 3;\n else friendly_pieces++;\n\n }\n\n }\n\n }\n\n }\n\n }\n //Top/Right\n else if (y < 4 && x >= 4) {\n\n for (let i = 0; i < 4; i++) {\n\n for (let j = 4; j < 8; j++) {\n\n let chk_piece = board[i][j];\n if (chk_piece != null) {\n\n //Skip this cell as this is the king\n if (i == y && x == j) continue;\n\n //Enemy piece found\n if (piece.player != chk_piece.player) {\n\n if (chk_piece instanceof Queen) enemy_pieces += 3;\n else enemy_pieces++;\n\n }\n //Friendly piece found\n else {\n\n if (chk_piece instanceof Queen) friendly_pieces += 3;\n else friendly_pieces++;\n\n }\n\n }\n\n }\n\n }\n\n }\n //Bottom/Left\n else if (y >= 4 && x < 4) {\n\n for (let i = 4; i < 8; i++) {\n\n for (let j = 0; j < 4; j++) {\n\n let chk_piece = board[i][j];\n if (chk_piece != null) {\n\n //Skip this cell as this is the king\n if (i == y && x == j) continue;\n\n //Enemy piece found\n if (piece.player != chk_piece.player) {\n\n if (chk_piece instanceof Queen) enemy_pieces += 3;\n else enemy_pieces++;\n\n }\n //Friendly piece found\n else {\n\n if (chk_piece instanceof Queen) friendly_pieces += 3;\n else friendly_pieces++;\n\n }\n\n }\n\n }\n\n }\n\n }\n //Bottom/Right\n else {\n\n for (let i = 4; i < 8; i++) {\n\n for (let j = 4; j < 8; j++) {\n\n let chk_piece = board[i][j];\n if (chk_piece != null) {\n\n //Skip this cell as this is the king\n if (i == y && x == j) continue;\n\n //Enemy piece found\n if (piece.player != chk_piece.player) {\n\n if (chk_piece instanceof Queen) enemy_pieces += 3;\n else enemy_pieces++;\n\n }\n //Friendly piece found\n else {\n\n if (chk_piece instanceof Queen) friendly_pieces += 3;\n else friendly_pieces++;\n\n }\n\n }\n\n }\n\n }\n\n }\n\n if (enemy_pieces > friendly_pieces) {\n\n let diff = enemy_pieces - friendly_pieces;\n\n if (piece.player == 'human') human -= (5 * diff);\n else ai += (5 * diff);\n\n }\n\n }\n\n }\n\n //Bishop bonuses/penalties\n if (piece instanceof Bishop) {\n\n //Back rank penalty\n if (piece.player == 'human' && y == 7) human -= 11;\n else if (piece.player == 'ai' && y == 0) ai += 11;\n\n //Bishop pair bonus\n let pair = false;\n\n for (let i = 0; i < 8; i++) {\n\n for (let j = 0; j < 8; j++) {\n\n if (i == y && j == x) continue;\n\n let chk_piece = board[i][j];\n\n if (chk_piece != null && chk_piece.player == piece.player && chk_piece instanceof Bishop) {\n pair = true;\n break;\n }\n\n }\n\n }\n\n if (pair && piece.player == 'human') human += 50;\n else if (pair && piece.player == 'ai') ai -= 50;\n\n //Pawn penalties\n let p_cntr = 0;\n\n //Top left\n if (x - 1 >= 0 && y - 1 >= 0 && board[y - 1][x - 1] != null && board[y - 1][x - 1] instanceof Pawn) p_cntr++;\n\n //Top right\n if (x + 1 < 8 && y - 1 >= 0 && board[y - 1][x + 1] != null && board[y - 1][x + 1] instanceof Pawn) p_cntr++;\n\n //Bottom left\n if (x - 1 >= 0 && y + 1 < 8 && board[y + 1][x - 1] != null && board[y + 1][x - 1] instanceof Pawn) p_cntr++;\n\n //Bottom right\n if (x + 1 < 8 && y + 1 < 8 && board[y + 1][x + 1] != null && board[y + 1][x + 1] instanceof Pawn) p_cntr++;\n\n if (piece.player == 'human') human -= (p_cntr * 3);\n else ai += (p_cntr * 3);\n\n }\n\n\n \n }\n\n }\n\n }\n\n return ai + human;\n\n}",
"function setupPerPlayerCardCounts() {\n if (!getOption(\"show_card_counts\")) return true;\n if (turn_number < 2) return true;\n\n // Make sure things aren't already setup.\n if ($('#player1_copper').length != 0) return false;\n\n if ($('#chat ~ a[href^=\"/mode/\"]').text() == \"images\") {\n setupPerPlayerTextCardCounts();\n\n // Setup the counts again whenever the table is recreated.\n $(\"#supply\").bind(\"DOMNodeInserted\", function(e) {\n if (e.target.constructor == HTMLTableElement) {\n if ($('#player1_copper').length == 0) {\n setupPerPlayerTextCardCounts();\n }\n }\n });\n } else {\n setupPerPlayerImageCardCounts('kingdom');\n setupPerPlayerImageCardCounts('basic');\n\n // Setup the counts again whenever the table is recreated.\n $(\"#supply\").bind(\"DOMNodeInserted\", function(e) {\n if (e.target.constructor == HTMLTableElement) {\n if ($('#player1_copper').length == 0) {\n setupPerPlayerImageCardCounts('kingdom');\n setupPerPlayerImageCardCounts('basic');\n }\n }\n });\n }\n return true;\n}",
"function batspergame (player) {\n\treturn player.atbats / player.games;\n}",
"howManyPieces(player, intersections) { \n let count = 0;\n for (var c = 0; c < intersections.length; c++) { \n if (intersections[c] === player) { count++; }\n }\n return count;\n }",
"function memoryGetCardCountWidth(pairCount) {\n var cardCount = pairCount * 2;\n var temp = Math.round(Math.sqrt(cardCount));\n var found = ((cardCount % temp) == 0);\n \n var down = temp - 1;\n var up = temp + 1;\n \n while (!found) {\n if ((cardCount % up) == 0)\n temp = up;\n else if ((cardCount % down) == 0)\n temp = down;\n \n up--;\n down--;\n \n found = ((cardCount % temp) == 0);\n }\n\n return temp;\n}",
"function setCardCount() {\n playerCountHigh = checkCardCountHigh(playerCards);\n playerCountLow = checkCardCountLow(playerCards);\n\n dealerCountHigh = checkCardCountHigh(dealerCards);\n dealerCountLow = checkCardCountLow(dealerCards);\n\n console.log('Player High: ' + playerCountHigh);\n console.log('Player Low: ' + playerCountLow);\n console.log(playerCards);\n\n console.log('Dealer High: ' + dealerCountHigh);\n console.log('Dealer Low: ' + dealerCountLow);\n console.log(dealerCards);\n}",
"function homerunspergame (player) {\n\treturn player.homeruns / player.games;\n}",
"updateGoodTypeCounts() {\n getValidGoodTypes().forEach((goodType) => {\n // Reset all calculated values from previous iteration\n this.setRoyalty(goodType.name, 0);\n this.countSubtotals[goodType.name] = 0;\n // Each player has inputs that come in a specific type. Some goods score extra when it comes to\n // determining bonuses for first and second (King and Queen). Recaclulate the total for each goodType.\n goodType.goods.forEach((targetGood) => {\n // Multiplier is relevant for royal goods.\n this.countSubtotals[goodType.name] += this.getCount(targetGood.name) * targetGood.multiplier;\n });\n });\n }",
"__score(){\n this.p1Score = 0;\n this.p2Score = 0;\n\n //Will be Used to Track Which Spaces Have Been Checked\n var visited = new GameBoard(this.size);\n\n for(var row = 0; row < this.size; row++){\n for(var col = 0; col < this.size; col++){\n var hasBlackNeighbours = false;\n var hasWhiteNeighbours = false;\n\n //Only Check Empty Spaces Which Have Not Yet Been Visited\n if(visited.get(row, col) === 0 && this.board.get(row, col) === 0){\n visited.set(1, row, col);\n //An Array Containing The Coordinates of a Grouping of Empty Spaces\n var emptySpaces = this.board.__getArmyCoords(0, row, col);\n\n for(var i = 0; i < emptySpaces.length; i++){\n visited.set(1, emptySpaces[i].x, emptySpaces[i].y);\n if(this.__hasOccupiedNeighbours(2, emptySpaces[i].x, emptySpaces[i].y)){\n hasBlackNeighbours = true;\n }\n if(this.__hasOccupiedNeighbours(1, emptySpaces[i].x, emptySpaces[i].y)){\n hasWhiteNeighbours = true;\n }\n //If The Grouping of Spaces Has Black and White\n //Neighbours, the territory is not owned by either\n if(hasBlackNeighbours && hasWhiteNeighbours){\n break;\n }\n }\n if(!(hasBlackNeighbours && hasWhiteNeighbours)){\n if(hasBlackNeighbours){\n this.p2Score += emptySpaces.length;\n }else if(hasWhiteNeighbours){\n this.p1Score += emptySpaces.length;\n }\n }\n }\n }\n }\n //Score = Territory Owned + Stones Captured + Stones on Board + Komi\n this.p1Score += this.p1Captured + this.board.count(1);\n this.p2Score += this.p2Captured + this.board.count(2) + 6.5;\n }",
"function numberOfNewSoldiers(player) {\n return Math.floor(numberOfSquaresControlled(player) / costOfSoldier);\n}",
"getNumberOfCoins() {\n let numberOfCoins = 120000 + (this.numberOfBlocks) * 100;\n return numberOfCoins;\n }",
"function setupPerPlayerTextCardCounts() {\n if (disabled) return;\n\n // For each row in the supply table, add a column count cell for each player.\n $(\".txcardname\").each(function() {\n var $this = $(this);\n var cardName = $this.children(\"[cardname]\").first().attr('cardname');\n\n // Insert new cells after this one.\n var insertAfter = $this.next();\n for (var p in players) {\n var cell = createPlayerCardCountCell(players[p], cardName);\n insertAfter.after(cell);\n insertAfter = cell;\n }\n insertAfter.after($('<td class=\"availPadding\"></td>'));\n });\n growHeaderColumns();\n}",
"lootDivide(loot, players = this.members) {\n loot = roundDown(loot);\n\n let div = loot.map(x => Math.floor(+x / (players.length || players)));\n\n console.log(` ${div[div.length - 1]} copper pieces each (minimum)\n `);\n\n let lootEach = [Array.from(div), Array.from(div), Array.from(div)];\n let lootRemainder = loot[loot.length - 1] % (players.length || players);\n // console.log(lootRemainder);\n\n for (let i = 0; lootRemainder > 0; i++) {\n i > loot.length ? i = 0 : false;\n lootEach[i][loot.length - 1] += 1;\n lootRemainder--;\n }\n\n this.members.forEach(member => {\n // set random cut position for splice method\n let cut = Math.floor(Math.random() * lootEach.length);\n // randomly assign couch pouches to party members\n member.pPouch = roundUp(lootEach.splice(cut, 1).flat());\n\n });\n console.log(this.members);\n }",
"function calculate_starting_bonuses(stats) {\n\tvar weap_1_stat = weapon_stats[document.getElementById(\"starting_weapon_1\").value];\n\tstats[weap_1_stat] += 1;\n\t\n\tvar weap_2_stat = weapon_stats[document.getElementById(\"starting_weapon_2\").value];\n\tstats[weap_2_stat] += 1;\n\n\tvar spirit_stat = spirit_stats[document.getElementById(\"starting_guardian_spirit\").value];\n\tstats[spirit_stat] += 1;\n}",
"totalScore() {\n let total = 0;\n\n for (let i = 0; i < this.plays.length; i++) {\n //NOTE why why why do we need to call it Scrabble.score instead of just this.score?\n total += Scrabble.score(this.plays[i]);\n }\n\n return total;\n }",
"sumFinalResultsScore(finalResults) {\n let confettiQuantity = 0;\n finalResults.finalScoreboard.forEach((result) => {\n confettiQuantity += result.score;\n });\n return Math.floor(confettiQuantity / 2);\n }",
"function numberOfSquaresControlled(player) {\n var counter = 0;\n\n for (var row = 0; row < ySize; row++) {\n for (var col = 0; col < xSize; col++) {\n var square = board[row][col];\n if (square.player == player && numberOfActiveSoldiers(square) > 0) {\n counter++;\n }\n }\n } \n return counter;\n}",
"function setupPerPlayerImageCardCounts(region) {\n if (disabled) return;\n\n var selector = '.' + region + '-column';\n\n // make \"hr\" rows span all columns\n var numPlayers = 1 + player_count;\n $(selector + ' .hr:empty').append('<td colspan=\"' + numPlayers + '\"></td>');\n\n $(selector + ' .supplycard').each(function() {\n var $this = $(this);\n var cardName = $this.attr('cardname');\n for (var p in players) {\n $this.append(createPlayerCardCountCell(players[p], cardName));\n }\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Close this handle. NOTE: After closing the handle, it must not be used anymore. Doing so will throw an error. Official libcurl documentation: [`curl_easy_cleanup()`]( | close() {
curlInstanceMap.delete(this.handle);
this.removeAllListeners();
if (this.handle.isInsideMultiHandle) {
multiHandle.removeHandle(this.handle);
}
this.handle.setOpt(Curl.option.WRITEFUNCTION, null);
this.handle.setOpt(Curl.option.HEADERFUNCTION, null);
this.handle.close();
} | [
"close() {\r\n // clear recorder cache\r\n return new Promise((resolve, reject) => {\r\n if (this.httpProxyServer) {\r\n // destroy conns & cltSockets when closing proxy server\r\n for (const connItem of this.requestHandler.conns) {\r\n const key = connItem[0];\r\n const conn = connItem[1];\r\n logUtil.printLog(`destorying https connection : ${key}`);\r\n conn.end();\r\n }\r\n\r\n for (const cltSocketItem of this.requestHandler.cltSockets) {\r\n const key = cltSocketItem[0];\r\n const cltSocket = cltSocketItem[1];\r\n logUtil.printLog(`closing https cltSocket : ${key}`);\r\n cltSocket.end();\r\n }\r\n\r\n if (this.socketPool) {\r\n for (const key in this.socketPool) {\r\n this.socketPool[key].destroy();\r\n }\r\n }\r\n\r\n this.httpProxyServer.close((error) => {\r\n if (error) {\r\n logUtil.printLog(`proxy server close FAILED : ${error.message}`, logUtil.T_ERR);\r\n } else {\r\n this.httpProxyServer = null;\r\n this.status = PROXY_STATUS_CLOSED;\r\n logUtil.printLog(`proxy server closed at ${this.proxyHostName}:${this.proxyPort}`);\r\n resolve(\"CLOSED\");\r\n }\r\n reject(error);\r\n });\r\n } else {\r\n resolve();\r\n }\r\n })\r\n }",
"close() {\n // _close will also be called later from the requester;\n this.requester.closeRequest(this);\n }",
"async close() {\n this.resolveClose(this.data);\n }",
"close() {\n this[_socket].close();\n\n if (this[_timeout] !== null) {\n clearTimeout(this[_timeout]);\n }\n }",
"function cb(err) {\n\t\t\t\tif (!fd) return real_cb(err)\n\t\t\t\tfs.close(fd, function() {\n\t\t\t\t\treal_cb(err)\n\t\t\t\t})\n\t\t\t}",
"function onPythonClose(err, script){\n if(err) logAndWrite((\"PYTHON: \" + err.toString()).red);\n script.end(function(err, code, signal){onPythonEnd(err, code, signal, script)}); // After pythonsycript closed, end this object and free ressources\n \n}",
"async close() {\n // close chokidar watchers\n if (this.watchers && this.watchers.length) {\n this.watchers.forEach(watcher => {\n watcher.close();\n });\n this.watchers = [];\n }\n // close devMiddleware\n if (this.devMiddleware) {\n await new Promise(resolve => {\n this.devMiddleware.close(() => resolve());\n });\n }\n // stop serverCompiler watching in ssr mode\n if (this.serverWatching) {\n await new Promise(resolve => {\n this.serverWatching.close(() => resolve());\n });\n this.serverWatching = null;\n }\n }",
"async _destroy(err, cb) {\n if (this._resultSet) {\n const rs = this._resultSet;\n this._resultSet = null;\n if (this._fetching) {\n await new Promise(resolve =>\n this.once('_doneFetching', resolve));\n }\n try {\n await rs._impl.close();\n } catch (closeErr) {\n cb(closeErr);\n return;\n }\n }\n cb(err);\n }",
"[kStreamClose](id, code) {\n const stream = this.#streams.get(id);\n if (stream === undefined)\n return;\n\n stream.destroy();\n }",
"release() {\n /* This is executed inside of a try-catch because if the connection was released, throws an error. */\n try {\n this.connection.release();\n } catch (err) {\n // logger.error('There was an attempt to release an connection already released.');\n }\n }",
"function onConnectionClose() {\n\tif (shutdownInProgress && 0 === (httpServer.connections + httpsServer.connections))\n\t\tshutdownNext()\n}",
"close(callback) {\r\n debugLog(\"ServerSecureChannelLayer#close\");\r\n // close socket\r\n this.transport.disconnect(() => {\r\n this._abort();\r\n if (_.isFunction(callback)) {\r\n callback();\r\n }\r\n });\r\n }",
"close () {\n if (this.closed) {\n // TODO: this should do something meaningful. May be throw an error or reject a Promise?\n return\n }\n if (!this.closed) {\n this.mediaRoom.close()\n }\n\n /**\n * Call close event\n *\n * @event Call#close\n *\n */\n this.emit('close', this._callId)\n }",
"close() {\n\t\t// Close all live sockets\n\t\tthis.sockets.forEach(socket => {\n\t\t\tif (!socket.destroyed) socket.end();\n\t\t});\n\n\t\tthis.sockets.clear();\n\t}",
"release() {\n if (Stack.onresolve) {\n Stack.onresolve(this.id)\n }\n\n delete stacks[this.id]\n ids.release(this.id)\n\n if (this.close) {\n this.close()\n }\n }",
"function HTTPDONE(self) {\n if (self._type !== 'http') {\n throw new Error('HTTP_NOT_INUSE');\n }\n if (self._state !== 'done') {\n throw new Error('HTTP_PENDING');\n }\n return self._http;\n }",
"function cleanup() {\n if (global.gc) {\n global.gc();\n }\n}",
"close() {\n const close = _.once((error) => {\n setTimeout( () => {\n if (error) console.error('Closing BitwigIO with error:', error);\n this.port.close();\n }, 100);\n });\n\n // If we already have an error, the 'empty' message may never come. To\n // prevent us from waiting indefinitely, just close now.\n if (this.error) close(this.error);\n else if (this.ready && this.queue.length === 0 && this.molasses.queue.length === 0) close();\n else {\n this.on('empty', close);\n this.on('error', close);\n }\n }",
"close() {\n return spPost(WebPartDefinition(this, \"CloseWebPart\"));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
total is equal to experience. To reach the next level your XP should be at least at threshold. If you kill the monster in front of you, you will gain more experience points in the amount of the reward. | function reachNextLevel(experience, threshold, reward) {
return experience + reward >= threshold;
} | [
"getTotalXpForLevel(player, level) {\n return this.xpTable[level]\n }",
"damage(damagePoints){\n this.hp -= damagePoints\n return damagePoints\n }",
"checkTotal(hand){\n if(hand.total >= 10){\n hand.total -= 10;\n }\n }",
"getTnl(player) {\n const requiredXp = this.getTotalXpForLevel( player, player.level + 1 )\n const tnl = requiredXp - player.experience\n return tnl\n }",
"function updateLevel(){\t\t//easy level\n \tif(game.score ==6){\n \t\tzombie.speed = 5;\n \t}else\n \tif(game.score <=11){\t\t//hard level\n \t\tzombie.spawnRate++;\n \t}else\n \tif(game.score >= 19){\t\t//insane Level\n \t\tzombie.spawnRate++;\n \t\tzombie.speed = 8;\n \t}\n}",
"function hitPoints (tengu, add1, add2) {\n\tvar hd = tengu.hd;\n\tvar level = tengu.level;\n\tvar hitPoints = 0;\n\tvar zeroLevelHitPoints = Math.floor((Math.random() * 4) + 1) + add1 + add2;\n\tvar hitPointsEachLevel = Math.floor((Math.random() * 6) + 1) + add1 + add2;\n\t\n\tif (level === 1) {\n\t\thitPoints = zeroLevelHitPoints + hitPointsEachLevel;\n\t\tif (hitPoints <= 3) {\n\t\t\thitPoints = 4;\n\t\t}\n\t}\t\n\telse if (level === 2) {\n\t\thitPoints = zeroLevelHitPoints + hitPointsEachLevel + hitPointsEachLevel;\n\t\tif (hitPoints <= 7) {\n\t\t\thitPoints = 8;\n\t\t}\n\t}\n\telse if (level === 3) {\n\t\thitPoints = zeroLevelHitPoints + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel;\n\t\tif (hitPoints <= 9) {\n\t\t\thitPoints = 10;\n\t\t}\n\t}\n\telse if (level === 4) {\n\t\thitPoints = zeroLevelHitPoints + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel;\n\t\tif (hitPoints <= 13) {\n\t\t\thitPoints = 14;\n\t\t}\n\t}\n\telse if (level === 5) {\n\t\thitPoints = zeroLevelHitPoints + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel\n\t\t + hitPointsEachLevel;\n\t\tif (hitPoints <= 15) {\n\t\t\thitPoints = 16;\n\t\t}\n\t}\n\telse if (level === 6) {\n\t\thitPoints = zeroLevelHitPoints + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel\n\t\t + hitPointsEachLevel + hitPointsEachLevel;\n\t\tif (hitPoints <= 19) {\n\t\t\thitPoints = 20;\n\t\t}\n\t}\n\telse if (level === 7) {\n\t\thitPoints = zeroLevelHitPoints + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel\n\t\t + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel;\n\t\tif (hitPoints <= 22) {\n\t\t\thitPoints = 23;\n\t\t}\n\t}\n\telse if (level === 8) {\n\t\thitPoints = zeroLevelHitPoints + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel\n\t\t + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel;\n\t\tif (hitPoints <= 25) {\n\t\t\thitPoints = 26;\n\t\t}\n\t}\n\telse if (level === 9) {\n\t\thitPoints = zeroLevelHitPoints + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel\n\t\t + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel;\n\t\tif (hitPoints <= 28) {\n\t\t\thitPoints = 29;\n\t\t}\n\t}\n\telse if (level === 10) {\n\t\thitPoints = zeroLevelHitPoints + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel\n\t\t + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel + hitPointsEachLevel;\n\t\tif (hitPoints <= 31) {\n\t\t\thitPoints = 32;\n\t\t}\n\t}\n\treturn hitPoints;\n}",
"function calculateDamageHitSuccess(defenderSkillAverage, attackerSkillAverage){\n \n var baseHitPottential = getRandomInt(0, 100);\n var deffenderSkillAdvantage = getPercentage(defenderSkillAverage, attackerSkillAverage)-100;\n \n var hitSuccess = baseHitPottential;\n\n \n \n if(deffenderSkillAdvantage > 0){\n if(deffenderSkillAdvantage > 100){\n deffenderSkillAdvantage = 100;\n }\n hitSuccess = hitSuccess - getRandomInt(0, deffenderSkillAdvantage);\n }\n \n return hitSuccess;\n \n}",
"function calculate_ninja_points(stats) {\n\tvar points = 0;\n\tif (stats.level >= 5) points += 2;\n\tpoints += levels(\"dexterity\") * 2;\n\tstats[\"ninja_skill_points\"] = points;\n}",
"function partyHPS() {\n let power = 10;\n if (!character.party) return power;\n //Add priest heals\n for (let key in parent.party_list) {\n let member = parent.party_list[key];\n let entity = getCharacterData()[member] || parent.entities[member];\n if (!entity || entity.ctype !== 'priest') continue;\n power += entity.attack * entity.frequency * damage_multiplier(-entity.rpiercing || 0) * 0.925;\n }\n return power * 0.9;\n}",
"function pointsChance(player) {\n\n var points = 0;\n for (var i = 0; i < 5; i++) {\n points = points + dices[player - 1][i].value;\n }\n \n return points;\n}",
"function addToScore(points){\r\n\t\tscore += points;\r\n\t\taddLifeRunningTotal += points;\r\n\t}",
"function highBet(){\n\t\tbet += 10\n\t\talert(\"You have now bet \"+bet)\n\t}",
"function doDamage() {\n let newGroup = {}\n let deadGuys = 0;\n\n if (props.secondGroup) \n newGroup = JSON.parse(JSON.stringify(props.secondGroup))\n else\n newGroup = JSON.parse(JSON.stringify(props.group))\n\n props.changePrevState(JSON.parse(JSON.stringify(newGroup)))\n\n \n //Make an array of keys with the values that are above 0\n let nonzeros = []\n if (props.selection) {\n newGroup.creatures.forEach((element, index) => {\n if (element > 0 && props.selectedCreatures.includes(index) ) \n nonzeros.push(index) \n })\n }\n else {\n newGroup.creatures.forEach((element, index) => {\n if( element > 0 ) \n nonzeros.push(index)\n })\n }\n\n switch(props.targetType) {\n case \"lowest\":\n nonzeros.sort(function(a, b){return newGroup.creatures[a]-newGroup.creatures[b]});\n break;\n case \"highest\":\n nonzeros.sort(function(a,b){return newGroup.creatures[b]-newGroup.creatures[a]})\n break;\n default: \n nonzeros = SmallFunctions.shuffle(nonzeros)\n break;\n }\n\n \n let targets = props.numTargets;\n let rollResults = []\n let finalResults = []\n let damage = null;\n \n\n if (!props.aoe && !props.secondGroup) { //If doing single target damage\n let remainder = props.damage;\n if (props.bleedthrough) targets += 1;\n\n while (nonzeros.length > 0 && targets > 0 && remainder > 0) {\n\n if(newGroup.creatures[nonzeros[0]] > remainder){\n newGroup.creatures[nonzeros[0]] -= remainder\n remainder = 0;\n }\n else if (newGroup.creatures[nonzeros[0]] === remainder) {\n remainder = 0;\n deadGuys += 1;\n newGroup.creatures[nonzeros[0]] = 0;\n }\n else{\n remainder -= newGroup.creatures[nonzeros[0]]\n newGroup.creatures[nonzeros[0]] = 0\n deadGuys += 1;\n }\n nonzeros.splice(0, 1)\n targets -= 1; \n console.log(\"loop\") \n } \n \n }\n else {\n if (props.saveRule === \"None\") \n rollResults = []\n else if (props.aoe)\n rollResults = SmallFunctions.rollDice(props.rolltype, props.numTargets )\n else //If it is an attack group action\n rollResults = SmallFunctions.rollDice(props.rolltype, props.numAttackers )\n\n \n\n if(props.aoe) { //if aoe effect\n while (targets > 0 && nonzeros.length > 0) {\n if (props.saveRule === \"None\" || rollResults[0] + newGroup.Saves[props.saveType]< props.saveDC ) \n damage = props.damage\n \n else if (props.saveRule === \"Half\")\n damage = Math.floor(props.damage / 2)\n \n else \n damage = 0;\n \n newGroup.creatures[nonzeros[0]] = Math.max( 0 , newGroup.creatures[nonzeros[0]] - (damage))\n if (newGroup.creatures[nonzeros[0]] === 0) deadGuys += 1;\n finalResults.push([rollResults[0], damage, false])\n rollResults.splice(0,1)\n nonzeros.splice(0,1)\n targets -= 1;\n }\n \n\n }\n else { //if group attack\n nonzeros = nonzeros.splice(0, targets)\n while (rollResults.length > 0 && nonzeros.length > 0) {\n let newDamage = props.selectedAttack.damBonus\n let victim = Math.floor(Math.random()*nonzeros.length)\n finalResults.push([rollResults[0]])\n for (let i = 0; i < props.selectedAttack.numDie; i++) {\n newDamage += Math.floor(Math.random() * props.selectedAttack.damDie) + 1\n }\n if(props.selectedAttack.saving) {\n if(rollResults[0] + newGroup.Saves[props.selectedAttack.savingType] < props.selectedAttack.DC ) {\n newGroup.creatures[nonzeros[victim]] = Math.max(0, newGroup.creatures[nonzeros[victim]] - newDamage)\n finalResults[finalResults.length-1].push(newDamage)\n finalResults[finalResults.length-1].push(false)\n }\n else {\n finalResults[finalResults.length-1].push(0)\n finalResults[finalResults.length-1].push(false) \n }\n }\n else {\n if( rollResults[0] + props.selectedAttack.bonus >= newGroup.armorClass ) {\n newGroup.creatures[nonzeros[victim]] = Math.max(0, newGroup.creatures[nonzeros[victim]] - newDamage)\n finalResults[finalResults.length-1].push(newDamage)\n finalResults[finalResults.length-1].push(true)\n }\n else {\n finalResults[finalResults.length-1].push(0)\n finalResults[finalResults.length-1].push(true)\n }\n }\n\n if(newGroup.creatures[nonzeros[victim]] === 0) {\n nonzeros.splice(victim, 1)\n deadGuys += 1\n }\n rollResults.splice(0,1) \n\n } \n }\n }\n\n \n if(props.saveRule === \"None\")\n props.changeRollResults([])\n else\n props.changeRollResults(finalResults)\n props.updateGroup(newGroup) \n props.changeDeadGuys(deadGuys) \n }",
"function attack() {\n\tplayer_attack += 5;\n\topponent_hp -= getRandNum();\n}",
"function givePoints1() {\n sumScore = sumScore + number1;\n console.log(\"Total score: \" + sumScore);\n $(\"#totalScore\").text(sumScore);\n if (sumScore == randomNum) {\n winGame();\n }\n else if (sumScore > randomNum) {\n looseGame();\n }\n }",
"calculateNewScore() {\n this.score = 0;\n let numberOfAces = 0;\n for (const card of this.hand) {\n if (card.value === 'A') {\n this.score += card.weight()[1];\n numberOfAces++;\n } else {\n this.score += card.weight();\n }\n }\n if (this.score > 21 && numberOfAces !== 0) {\n for (let i = 0; i < numberOfAces; i++) {\n this.score -= 10; // Count the ace as 1 instead, removing 10.\n if (this.score <= 21) {\n break;\n }\n }\n }\n }",
"attackOutcome (opponentDodge) {\n let successRoll = this.getRandomInt();\n if (successRoll >= opponentDodge){\n return true;\n } else {\n return false;\n }\n }",
"function levelUpLeech(){\n if(protein >= upgradeLeechCost)\n {\n protein -= upgradeLeechCost;\n levelLeech += 1;\n\n performCalculations();\n updateLabels();\n }\n}",
"damage(dmg) {\n \n var newHp = (this.hp - dmg);\n if (newHp < 0) {\n this.hp = 0;\n this.die();\n }\n else this.hp = newHp;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests removing a root. | function testRemoveRoot() {
delegate.addRoot(document.body);
delegate.registerHandlers({
'mousedown .foo': f1,
'mousemove .quix': f2
}, {});
delegate.removeRoot(document.body);
el1.dispatchEvent(createMouseEvent('mousedown'));
el2.dispatchEvent(createMouseEvent('mousemove'));
thermo.scheduler.runFrameDebugDebug();
assertEvents(f1, []);
assertEvents(f2, []);
} | [
"delete(val) {\n debugger\n let currentNode = this.root;\n let found = false;\n let nodeToRemove;\n let parent = null;\n\n // find the node we want to remove\n while (!found) {\n if (currentNode === null || currentNode.val === null) {\n return 'the node was not found'\n }\n if (val === currentNode.val) {\n nodeToRemove = currentNode;\n found = true;\n } else if (val < currentNode.val) {\n parent = currentNode;\n currentNode = currentNode.left;\n } else {\n parent = currentNode;\n currentNode = currentNode.right;\n }\n }\n\n console.log(\"We found the node\");\n console.log('parent node', parent);\n\n // helper variable which returns true if the node we've removing is the left\n // child and false if it's right\n const nodeToRemoveIsParentsLeftChild = parent.left === nodeToRemove;\n\n // if nodeToRemove is a leaf node, remove it\n if (nodeToRemove.left === null && nodeToRemove.right === null) {\n if (nodeToRemoveIsParentsLeftChild) parent.left = null;\n else parent.right = null\n } else if (nodeToRemove.left !== null && nodeToRemove.right === null) {\n // only has a left child\n if (nodeToRemoveIsParentsLeftChild) {\n parent.left = nodeToRemove.left;\n } else {\n parent.right = nodeToRemove.left;\n }\n } else if (nodeToRemove.left === null && nodeToRemove.right !== null) {\n // only has a right child\n if (nodeToRemoveIsParentsLeftChild) {\n parent.left = nodeToRemove.right;\n } else {\n parent.right = nodeToRemove.right;\n }\n } else {\n // has 2 children\n const rightSubTree = nodeToRemove.right;\n const leftSubTree = nodeToRemove.left;\n // sets parent nodes respective child to the right sub tree\n if (nodeToRemoveIsParentsLeftChild) {\n parent.left = rightSubTree;\n } else {\n parent.right = rightSubTree;\n }\n\n // find the lowest free space on the left side of the right sub tree\n // and add the leftSubtree\n let currentLeftNode = rightSubTree;\n let currentLeftParent;\n let foundSpace = false;\n while (!foundSpace) {\n if (currentLeftNode === null) foundSpace = true;\n else {\n currentLeftParent = currentLeftNode;\n currentLeftNode = currentLeftNode.left;\n }\n }\n currentLeftParent.left = leftSubTree;\n return 'the node was successfully deleted'\n }\n }",
"function deviceRootRemove(datastore_id, root_uuid, device_root, file_name, file_tombstone, device_id) {\n var now = new Date().getTime();\n var new_timestamp = device_root['timestamp'] + 1 > now ? device_root['timestamp'] + 1 : now;\n\n device_root['timestamp'] = new_timestamp;\n device_root['tombstones'][file_name] = file_tombstone;\n\n var new_root = deviceRootSerialize(device_id, datastore_id, root_uuid, device_root);\n return new_root;\n}",
"_removeNode(tree, path) {\n if(tree){\n if (path.length === 1) {\n delete tree[path[0]];\n return;\n }\n return this._removeNode(tree[path[0]], path.slice(1));\n }\n }",
"delete(leaf) {\n const root = this.root();\n\n if (!root) {\n return false;\n }\n\n if (leaf === root) {\n this._root = null;\n this._numLeafs = 0;\n return true;\n } // Iterate up from the leaf deleteing it from it's parent's branches.\n\n\n let node = leaf.parent;\n let branchKey = leaf.branchKey;\n\n while (node) {\n var _node4;\n\n node.branches.delete(branchKey); // Stop iterating if we hit the root.\n\n if (node === root) {\n if (node.branches.size === 0) {\n this._root = null;\n this._numLeafs = 0;\n } else {\n this._numLeafs--;\n }\n\n return true;\n } // Stop iterating if there are other branches since we don't need to\n // remove any more nodes.\n\n\n if (node.branches.size > 0) {\n break;\n } // Iterate up to our parent\n\n\n branchKey = (_node4 = node) === null || _node4 === void 0 ? void 0 : _node4.branchKey;\n node = node.parent;\n } // Confirm that the leaf we are deleting is actually attached to our tree\n\n\n for (; node !== root; node = node.parent) {\n if (node == null) {\n return false;\n }\n }\n\n this._numLeafs--;\n return true;\n }",
"function removeTestFileFromRootFolder() {\n var root = DriveApp.getRootFolder(),\n id = '1xIeidH1-Em-xDlm_84e70FrORfkttXFfVqYRzEv58ZA',\n file = DriveApp.getFileById(id);\n root.removeFile(file);\n}",
"function solution_1 (root, key) {\n if (!root) return null; // EDGE CASE: empty input\n \n // `find` UTILITY FUNCTION - recursively searches input tree for a node with value matching `key`.\n // if such a node exists, returns an array containing (1) the node, and (2) its parent node, or null if the matching node is the root.\n // if such a node does not exist, returns [null, null]\n function find (node, parent = null) {\n if (key < node.val) {\n return node.left ? find(node.left, node) : [null, null];\n } else if (key > node.val) {\n return node.right ? find(node.right, node) : [null, null];\n } else {\n return [node, parent];\n } \n }\n\n // INITIALIZATION\n const [node, parent] = find(root); // set `node` (the node to be removed) and `parent` (a reference to its parent)\n if (!node) return root; // if `node` is null, then there is no work to be done. we simply return `root`\n\n // REMOVE THE NODE BY RECONFIGURING ALL NECESSARY NODE CONNECTIONS\n if (!node.left && !node.right) { // CASE 1: the `node` to be removed has no children\n if (parent) { // if `parent` is not null...\n parent[parent.val < node.val ? 'right' : 'left'] = null; // ...disconnect `parent` in the direction of `node`\n return root; // ...return original root\n }\n return null; // `parent` may be null if the `node` to be removed was the `root`. since `node` has no children, return empty tree (null)\n } else if (!node.left) { // CASE 2: the `node` to be removed only has a right child\n if (parent) { // if `parent` is not null...\n parent[parent.val < node.val ? 'right' : 'left'] = node.right; // ...connect `parent` in the direction of `node` to `node.right`\n return root; // ...return original root\n }\n return node.right; // `parent` may be null if the `node` to be removed was the `root`. since `node` has no left child, return `node.right`\n } else if (!node.right) { // CASE 3: reverse the logic of case 2\n if (parent) {\n parent[parent.val < node.val ? 'right' : 'left'] = node.left;\n return root;\n }\n return node.left;\n } else { // CASE 4: the `node` to be removed has both children\n\n // find the `replacement` node and its parent (we could either go right, and then keep going as left as possible, or go left, and keep going as right as possible. here i choose the former)\n let replacement = node.right;\n let replacementParent = node;\n while (replacement.left) {\n replacementParent = replacement;\n replacement = replacement.left;\n }\n \n // we decided to go right and then left to find replacement. now we have to hook up `replacement.left` to the original `node.left`...\n replacement.left = node.left;\n \n // ...and then hook up `replacement.right` to the original `node.right` (UNLESS `node.right` IS the `replacement`, in which case we can skip this step)\n if (node.right !== replacement) {\n replacementParent[\n replacementParent.val < replacement.val ? 'right' : 'left'\n ] = replacement.right; // hook up `replacementParent` in the direction of `replacement` to `replacement.right`\n replacement.right = node.right // hook up `replacement.right` to original `node.right`\n } \n \n // finally, hook up `parent` to `replacement` and return\n if (parent) { \n parent[parent.val < node.val ? 'right' : 'left'] = replacement;\n return root; // if `parent`, then we simply return the original `root`\n } else {\n return replacement; // else, it must be the case that the node we removed was the original `root`, so return `replacement`\n }\n }\n}",
"function _remove(predicate, tree) {\n\tif (isEmpty(tree)) {\n\t\treturn tree;\n\t} else if (R.pipe(R.view(lenses.data), predicate)(tree)) {\n\t\tif (!isEmpty(tree.left) && !isEmpty(tree.right)) {\n\t\t\t// Get in-order successor to `tree`; \"delete\" it; replace values in `tree`.\n\t\t\tconst successorLens =\n\t\t\t\tlensForSuccessorElement(tree);\n\t\t\t// assert(successorLens != null);\n\n\t\t\tconst successor = \n\t\t\t\tR.view(successorLens, tree);\n\t\t\t/*\n\t\tassert.notEqual(\n\t\t\tsuccessor,\n\t\t\tnull,\n\t\t\t`Expected successor of ${JSON.stringify(tree)}`);\n\t\t\t*/\n\n\t\t\treturn R.pipe(\n\t\t\t\tR.set(successorLens, empty),\n\t\t\t\tR.set(lenses.data, R.view(lenses.data, successor))\n\t\t\t)(tree);\n\t\t} else if (!isEmpty(tree.left)) {\n\t\t\treturn tree.left;\n\t\t} else if (!isEmpty(tree.right)) {\n\t\t\treturn tree.right;\n\t\t} else {\n\t\t\treturn empty;\n\t\t}\n\t} else {\n\t\treturn R.pipe(\n\t\t\tR.over(lenses.leftChild, remove(predicate)),\n\t\t\tR.over(lenses.rightChild, remove(predicate))\n\t\t)(tree);\n\t}\n}",
"function removeChildren(node) {\n\t\tjQuery(node).empty();\n\t}",
"function removeElement(node) {\n\t\tjQuery(node).remove();\n\t}",
"function removeExpr() {\r\n\r\n var sO = CurStepObj;\r\n var pos;\r\n\r\n // If an expression is active, we remove that expression AND activate\r\n // the space just before that removed expression (i.e., the sapce\r\n // id same as that of removed expression)\r\n //\r\n if (!sO.isSpaceActive) { // expression highlighted\r\n\r\n // console.log(\"no space\");\r\n\r\n pos = sO.activeChildPos;\r\n\r\n if (pos != ROOTPOS) {\r\n\r\n //console.log(\"not root\");\r\n\r\n // If we are deleting an arg of a function call, update the\r\n // header\r\n // \r\n var removed = true;\r\n if (sO.activeParentExpr.isUserFuncCall()) {\r\n removed = removeFuncArg(sO.activeParentExpr, pos);\r\n }\r\n\t //\r\n if (removed) {\r\n sO.activeParentExpr.exprArr.splice(pos, 1);\r\n sO.isSpaceActive = true; // activate space before removed expr\r\n }\r\n\r\n } else { // can't remove root str (e.g., if/else)\r\n\r\n\r\n if (sO.activeParentExpr.exprArr.length ||\r\n sO.activeParentExpr.isCondition()) {\r\n\r\n // Cannot delete non-empty 'foreach' OR any mask box \r\n //\r\n showTip(TipId.RootEdit);\r\n\r\n } else {\r\n\r\n // if no children, mark as deleted (e.g., bare 'foreach')\r\n //\r\n sO.activeParentExpr.deleted = DeletedState.Deleted;\r\n }\r\n }\r\n\r\n } else { // if space highlighted\r\n\r\n // console.log(\"space @\" + sO.activeChildPos);\r\n\r\n //pos = -1; // remove at very end by default\r\n\r\n if (sO.activeChildPos > 0) {\r\n pos = --sO.activeChildPos; // -- to move to previous space\r\n\r\n /*\r\n\t if (pos < 0) { // if we moved to ROOTPS\r\n\t\tsO.isSpaceActive = false; // space no longer active\r\n\t }\r\n\t */\r\n\r\n sO.activeParentExpr.exprArr.splice(pos, 1);\r\n }\r\n\r\n\r\n\r\n // var expr = sO.activeParentExpr.exprArr[pos];\r\n // if (expr.isDefinition()) expr.str = 'DELETED';\r\n\r\n\r\n\r\n }\r\n\r\n}",
"function removeChildren() {\n plantBox.innerHTML = '';\n}",
"function deleteNodes(xPath,params) {\r\n\t\tparams=params||{};\r\n\t\tvar o=selectNodes(xPath,params); if (o){\r\n\t\t\tif(o.snapshotItem) for(var i=o.snapshotLength-1; (item=o.snapshotItem(i)); i--) item.parentNode.removeChild(item);\r\n\t\t\telse for(var i=o.length-1; i>=0; i--) if(o[i]) o[i].parentNode.removeChild(o[i]);\r\n\t\t}\r\n\t\to=null;\r\n\t}",
"remove () {\n if (this.wrap && this.parent) {\n return !!this.parent.removeChild(this.wrap)\n }\n\n return !!console.log('Has not found \"Keypad\" that needed to be removed.')\n }",
"function removeFromDB(r){\n var database = firebase.database();\n var booksRef = database.ref('books');\n\n var key = r.parentNode.parentNode.getAttribute(\"id\");\n booksRef.child(key).remove().then(function(){\n console.log(\"Remove success\");\n }).catch(function(error){\n console.log(\"Remove failed : \", error);\n });\n \n document.querySelector(\"tbody\").innerHTML = \"\";\n retrieveData();\n}",
"_prunePath(tree, path) {\n if (_.isEmpty(_.get(tree, path))) {\n this._removeNode(tree, path);\n return this._prunePath(tree, path.slice(0, -1));\n }\n }",
"function emptyScene(scene){\n\n while(scene.children.length > 0){\n var objectToRemove = scene.children[0];\n scene.remove(objectToRemove);\n }\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 }",
"function folderCleanUp() {\n DriveApp.getFoldersByName('test1').next().setTrashed(true);\n DriveApp.getFoldersByName('test2').next().setTrashed(true);\n}",
"function deleteMinimum(node, removeCallBack) {\n\n if (noChildren(node)) {\n removeCallBack(node);\n return null;\n }\n\n if (rightChildOnly(node)) {\n removeCallBack(node);\n return node.right;\n }\n\n if (node.left) {\n node.left = deleteMinimum(node.left, removeCallBack);\n return node;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a promise to get all inview features across all viewports. Used for group autoscaling. | async getInViewFeatures() {
if (!(this.browser && this.browser.referenceFrameList)) {
return []
}
let allFeatures = []
const visibleViewports = this.viewports.filter(viewport => viewport.isVisible())
for (let vp of visibleViewports) {
const referenceFrame = vp.referenceFrame
const {chr, start, bpPerPixel} = vp.referenceFrame
const end = start + referenceFrame.toBP(vp.getWidth())
const needsReload = !vp.featureCache || !vp.featureCache.containsRange(chr, start, end, bpPerPixel)
if (needsReload) {
await vp.loadFeatures()
}
if (vp.featureCache && vp.featureCache.features) {
if (typeof vp.featureCache.features.getMax === 'function') {
const max = vp.featureCache.features.getMax(start, end)
allFeatures.push({value: max})
} else {
const vpFeatures = typeof vp.featureCache.queryFeatures === 'function' ?
vp.featureCache.queryFeatures(chr, start, end) :
FeatureUtils.findOverlapping(vp.featureCache.features, start, end)
allFeatures = allFeatures.concat(vpFeatures)
}
}
}
return allFeatures
} | [
"function getFeatures() {\n // set up query\n var q = new Query();\n // only within extent\n q.geometry = map.extent;\n q.returnGeometry = true;\n q.outFields = [\"*\"];\n \n // give me all of them!\n q.where = \"1=1\";\n // make sure I get them back in my spatial reference\n q.outSpatialReference = map.spatialReference;\n // get em!\n featureLayer.queryFeatures(q, function (featureSet) {\n var data = [];\n // if we get results back\n if (featureSet && featureSet.features && featureSet.features.length) {\n // set data to features\n data = featureSet.features; // Graphic []\n }\n // set heatmap data\n heatLayer.setData(data);\n });\n }",
"function __getFeatures(ref) {\n return fromCache(ref, CACHE_KEY_FEATURES);\n}",
"async getIpv6AddrTable()\n {\n const addressInfo = await getAddressInfo();\n const byIpAddr = addressInfo.byIpAddr;\n\n return Promise.resolve()\n .then(\n () =>\n {\n let ipAddr;\n let promises = [];\n\n // Call `getIpv6AddrEntry` for each IPv6 address, binding the\n // just-retrieved addressInfo so that `getIpAddrEntry` need\n // not re-retrieve it.\n for (ipAddr in byIpAddr.IPv6)\n {\n promises.push(this.getIpv6AddrEntry.bind(addressInfo)(ipAddr));\n }\n\n return Promise.all(promises);\n });\n }",
"async getIpv6IfStatsTable()\n {\n return Promise.resolve()\n .then(() => addIfIndexes())\n .then((ifNames) =>\n {\n return Promise.all(\n ifNames.map((ifName) =>\n this.getIpv6IfStatsEntry(ifName, ifIndexMap[ifName])));\n });\n }",
"async getIpv6Interfaces()\n {\n return Promise.resolve()\n .then(() => addIfIndexes())\n .then((ifNames) => ifNames.length);\n }",
"buildFeatureVector() {\n // create empty feature vector\n let featureVector = [];\n // get all partial feature vectors and merge them together\n for (let i in this.nodes) {\n let dataAvailable = this.nodes[i].checkDataAvailability();\n if (dataAvailable == false) {\n console.log(\"Can not be generated!\");\n return [];\n }\n let partialFeatureVector = this.nodes[i].getPartialFeatureVector();\n featureVector = featureVector.concat(partialFeatureVector);\n }\n // return the feature vector\n return featureVector;\n }",
"async getIpAddrTable()\n {\n const addressInfo = await getAddressInfo();\n const byIpAddr = addressInfo.byIpAddr;\n\n return Promise.resolve()\n .then(\n () =>\n {\n let ipAddr;\n let promises = [];\n\n // Call `getIpAddrEntry` for each IPv4 address, binding the\n // just-retrieved addressInfo so that `getIpAddrEntry` need\n // not re-retrieve it.\n for (ipAddr in byIpAddr.IPv4)\n {\n promises.push(this.getIpAddrEntry.bind(addressInfo)(ipAddr));\n }\n\n return Promise.all(promises);\n });\n }",
"function getFeatureList() {\n var featList = [];\n self.features.forEach(function(feat, index, array) {\n featList.push(feat.name);\n });\n return featList;\n }",
"function getAllEvents() {\n if (dbPromise) {\n dbPromise.then(function (db) {\n var transaction = db.transaction('EVENT_OS', \"readonly\");\n var store = transaction.objectStore('EVENT_OS');\n var request = store.getAll();\n return request;\n }).then(function (request) {\n displayOnMap(request);\n });\n }\n}",
"lookupSelectedRegions() {\r\n const collection = Array();\r\n for (const region of this.regions) {\r\n if (region.isSelected) {\r\n collection.push(region);\r\n }\r\n }\r\n return collection;\r\n }",
"async function fetchOSMData(bounds) {\n let response = await axios.get('https://api.openstreetmap.org/api/0.6/map?bbox=' + bounds.bottomLeft.lon + ',' + bounds.bottomLeft.lat + ',' + bounds.topRight.lon + ',' + bounds.topRight.lat);\n let elements = response.data.elements;\n let filteredElements = [];\n\n if (elements) {\n elements.forEach(element => {\n if (element.type === 'node' && element.tags && (element.tags.tourism || element.tags.natural || element.tags.amenity || element.tags.sport)) {\n filteredElements.push({id: element.id, lat: element.lat, lon: element.lon, tags: element.tags});\n }\n });\n }\n\n return filteredElements;\n}",
"async getIpv6IfTable()\n {\n // If we don't yet have the PCI database parsed, do it now.\n if (! pciIds)\n {\n pciIds = await require(\"./parsePciIds\")(this.pciIdPath);\n }\n\n return Promise.resolve()\n .then(() => addIfIndexes())\n .then((ifNames) =>\n {\n return Promise.all(\n ifNames.map((ifName) =>\n this.getIpv6IfEntry(ifName, ifIndexMap[ifName])));\n });\n }",
"function getNavigators() {\n return new Promise(resolve => {\n xapi.Status.Peripherals.ConnectedDevice.get().then(async devices => {\n var data = devices.filter(device => device.Name.toLowerCase().includes(\"navigator\") && device.Type.toLowerCase().includes(\"touchpanel\"));\n resolve(data);\n });\n });\n}",
"async function getInvestableRegions() {\n const investable_regions = {\n regions: [\"camden\", \"kew\", \"rochdale\"],\n };\n\n await waitFor(Math.random() * 3000);\n\n return investable_regions;\n}",
"async function ListFunctions() {\n let functionService = new fx.FunctionService(process.env.MICRO_API_TOKEN);\n let rsp = await functionService.list({});\n console.log(rsp);\n}",
"async _listVirtualHostsForEnvironment(token, envName) {\n\t\treturn requestPromise({\n\t\t\t...this.requestSettings.hosts(envName, token),\n\t\t\t...this.proxySettings\n\t\t});\n\t}",
"async retrieveUserTopTracks() {\n let topTracks = await this.spotify.getMyTopTracks();\n const features = await this.getAudioFeatures(topTracks.body.items);\n return features;\n }",
"function getAllSensori(){\n\treturn new Promise(function(resolve,reject){\n\t\tvar keys = Array();\n\tdb.collection(\"sensors\").get().then(function(snapshot) {\n\t\tsnapshot.forEach(function(userSnapshot) {\n\t\t\tkeys.push(userSnapshot.id);\n\t\t});\n\t\tresolve(keys);\n\t}).catch((y) => reject(y));\n\t});\n}",
"getViewports(rect) {\n Object(_utils_assert__WEBPACK_IMPORTED_MODULE_16__[\"default\"])(this.viewManager);\n return this.viewManager.getViewports(rect);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sorts list of objects containing a numeric values, given a valuekey | function numericListSort(listitems, valuekey) {
listitems.sort(function(a, b) {
var compA = parseFloat(a[valuekey]);
var compB = parseFloat(b[valuekey]);
return (compA > compB) ? -1 : (compA <= compB) ? 1 : 0;
})
return listitems;
} | [
"function numericLengthSort(listitems, valuekey) {\n listitems.sort(function(a, b) {\n var compA = a[valuekey].length;\n var compB = b[valuekey].length;\n return (compA > compB) ? -1 : (compA <= compB) ? 1 : 0;\n })\n return listitems;\n}",
"function sortArrayOfObjects (arr, key) {\n for (item in arr){\n if (typeof arr[item][key] === \"string\"){ //check if values are strings so we can sort alphabetically\n arr.sort(function(a, b) {\n var nameA = a[key].toUpperCase();\n var nameB = b[key].toUpperCase();\n if (nameA < nameB) {\n return -1;\n }\n if (nameA > nameB) {\n return 1;\n }\n return 0;\n }\n );\n } else if (typeof arr[item][key]===\"number\") { //check if values are numbers so we can sort numerically\n arr.sort(function (a,b){\n return a[key] - b[key];\n });\n }\n }\n}",
"function sortMapValues(o) {\n return Object.values(o).sort((aa, bb) => {\n let a = typeof aa === 'string' ? parseInt(aa, 10) : aa\n let b = typeof bb === 'string' ? parseInt(bb, 10) : bb\n return a === b ? 0 : a < b ? -1 : 1\n })\n}",
"function valuesSortedByPosition(obj) {\n return $.map(obj, function(x){return x;})\n .sort(function(a,b) {return a.position - b.position;});\n}",
"function sortBy(costObject, key) {\n const sortedCostArray = [];\n const sortedCostObject = {};\n\n Object.entries(costObject).forEach(([k, v]) => {\n sortedCostArray.push([k, v]);\n });\n\n sortedCostArray.sort(function(a, b) {\n return b[1][key] - a[1][key];\n });\n\n sortedCostArray.forEach(([k, v]) => {\n sortedCostObject[k] = v;\n });\n return sortedCostObject;\n}",
"function valuesSortedById(obj) {\n return $.map(obj, function(x){return x;})\n .sort(function(a,b) {return a.id - b.id;});\n}",
"function sortDessertsByPopularity(dessertObject) {\n let dessertArray = Object.values(dessertObject)\n let countObject = {}\n\n dessertArray.forEach((dessert) =>{\n countObject[dessert] = 0\n })\n\n dessertArray.forEach((dessert) =>{\n countObject[dessert] = countObject[dessert] + 1\n })\n console.log('this is the count object', countObject)\n\n let keysArray = Object.keys(countObject);\n\n\n return keysArray.sort((a,b) =>{\n console.log('this is a',a) //a is a dessert\n console.log('this is b',b)\n let countA = countObject[a] //this is the number of the a variable dessert\n let countB = countObject[b]\n // console.log('this is countA', countA)\n // console.log('this is countB', countB)\n if (countA < countB){ //if the number of a desserts is inferior to b desserts, keep a and b in order, else switch them\n return 1\n } else {\n return -1\n }\n })\n}",
"function sortOpenList(){\n openList.sort(function(a,b){\n // Sort the list so that the item with the lowest F value goes to the end of the list\n return b.f - a.f;\n });\n}",
"function sortResults() {\n let perDesc = (a, b) => a[0] - b[0]\n let perAsc = (a, b) => b[0] - a[0]\n let indDesc = (a, b) => (a[1] + a[2]) - (b[1] + b[2])\n let indAsc = (a, b) => (b[1] + b[2]) - (a[1] + a[2])\n switch (sortBy.value) {\n case \"0\":\n result.sort(perDesc)\n break;\n case \"1\":\n result.sort(perAsc)\n break;\n case \"2\":\n result.sort(indDesc)\n break;\n case \"3\":\n result.sort(indAsc)\n break;\n }\n\n\n\n}",
"sortBaseHp(items) {\n\n items.sort(function(a, b){\n\n if(a.hp < b.hp){ \n \n return -1;\n }\n if(a.hp > b.hp) {\n \n return 1;\n }\n return 0;\n })\n \n return items;\n \n }",
"function sortByKeyDesc(array, key) {\n return array.sort(function(a, b) {\n let x = a[key];\n let y = b[key]; \n return ((x > y) ? -1 : ((x < y) ? 1 : 0));\n });\n}",
"function scoreSort(a, b){\n return b.score-a.score;\n}",
"function sortOn(arr) {\n var comparators = [];\n for (var i=1; i<arguments.length; i+=2) {\n comparators.push(getKeyComparator(arguments[i], arguments[i+1]));\n }\n arr.sort(function(a, b) {\n var cmp = 0,\n i = 0,\n n = comparators.length;\n while (i < n && cmp === 0) {\n cmp = comparators[i](a, b);\n i++;\n }\n return cmp;\n });\n return arr;\n}",
"function sort_by(sort_criterion){\r\n return function(x,y){\r\n return (x[sort_criterion] < y[sort_criterion]) ? -1 : (x[sort_criterion] > y[sort_criterion]) ? 1 : 0;\r\n }\r\n}",
"function sortArrayBy( array, key, opt ) {\n\topt = opt || {};\n\t// TODO: use code generation instead of multiple if statements?\n\tvar sep = unescape('%uFFFF');\n\t\n\tvar i = 0, n = array.length, sorted = new Array( n );\n\tif( opt.numeric ) {\n\t\tif( typeof key == 'function' ) {\n\t\t\tfor( ; i < n; ++i )\n\t\t\t\tsorted[i] = [ ( 1000000000000000 + key(array[i]) + '' ).slice(-15), i ].join(sep);\n\t\t}\n\t\telse {\n\t\t\tfor( ; i < n; ++i )\n\t\t\t\tsorted[i] = [ ( 1000000000000000 + array[i][key] + '' ).slice(-15), i ].join(sep);\n\t\t}\n\t}\n\telse {\n\t\tif( typeof key == 'function' ) {\n\t\t\tfor( ; i < n; ++i )\n\t\t\t\tsorted[i] = [ key(array[i]), i ].join(sep);\n\t\t}\n\t\telse if( opt.caseDependent ) {\n\t\t\tfor( ; i < n; ++i )\n\t\t\t\tsorted[i] = [ array[i][key], i ].join(sep);\n\t\t}\n\t\telse {\n\t\t\tfor( ; i < n; ++i )\n\t\t\t\tsorted[i] = [ array[i][key].toLowerCase(), i ].join(sep);\n\t\t}\n\t}\n\t\n\tsorted.sort();\n\t\n\tvar output = new Array( n );\n\tfor( i = 0; i < n; ++i )\n\t\toutput[i] = array[ sorted[i].split(sep)[1] ];\n\t\n\treturn output;\n}",
"function byAge(arr){\nreturn arr.sort((a, b) => a.age - b.age)\n}",
"function sortStock(a, b) {\n if (parseInt(a[0]) > parseInt(b[0])) return 1;\n else return -1;\n}",
"function sortDrinkByPrice(drinks) {\n\treturn drinks.sort((a, b) => a.price - b.price);\n}",
"function sortGroceries() {\n let categories = Array.from(new Set(groceryList.map((grocery) => grocery.category))).sort();\n let tempgroceryList = [];\n categories.forEach((category) => {\n let currentCategoryItems = groceryList.filter((grocery) => grocery.category == category);\n currentCategoryItems = currentCategoryItems.sort((a, b) => (a.qty > b.qty) ? 1 : ((b.qty > a.qty) ? -1 : 0));\n currentCategoryItems.forEach((item) => {\n tempgroceryList.push(item)\n })\n })\n groceryList = tempgroceryList;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the effective permissions for the current user | async function getCurrentUserEffectivePermissions() {
return SPQueryable(this, "EffectiveBasePermissions")();
} | [
"get effectiveBasePermissionsForUI() {\n return SPQueryable(this, \"EffectiveBasePermissionsForUI\");\n }",
"get effectiveBasePermissions() {\n return SPQueryable(this, \"EffectiveBasePermissions\");\n }",
"async function getPermissionsFor (acl, user, req) {\n const accesses = MODES.map(mode => acl.can(user, mode))\n const allowed = await Promise.all(accesses)\n return PERMISSIONS.filter((mode, i) => allowed[i]).join(' ')\n}",
"grantsAllowed() {\n return this.grantPrivileges().reduce((a, b) => (\n a | this._config.grantPrivileges[b]\n ), 0);\n }",
"updatePermissions() {\n this.permissions = this.codenvyAPI.getProject().getPermissions(this.workspaceId, this.projectName);\n }",
"async function permissionCheck(user, group, targetUser, action) {\n const userRole = await getRole(user, group);\n const targetRole = await getRole(targetUser, group);\n\n if (!canAffect(userRole, targetRole)) {\n throw new RequestError(`${userRole} cannot ${action} ${targetRole}`);\n }\n\n return [userRole, targetRole];\n}",
"function GetSecurityRolesOfCurrentUser(executionContext) {\n try {\n //Get the form context\n var formContext = executionContext.getFormContext();\n //Get the Current User Guid\n var userRoles = formContext.context.getUserRoles();\n Xrm.Utility.alertDialog(userRoles);\n }\n catch (e) {\n Xrm.Utility.alertDialog(e.message);\n }\n}",
"edit(permission) {\n this.currentEditingUserPermission = permission;\n this.mode = 'EDIT_PERMISSIONS';\n\n // transform current permissions\n this.currentEditingUserPermissionModel = {};\n this.currentEditingUserPermissionModel['read'] = false;\n this.currentEditingUserPermissionModel['write'] = false;\n this.currentEditingUserPermissionModel['build'] = false;\n this.currentEditingUserPermissionModel['run'] = false;\n this.currentEditingUserPermissionModel['update_acl'] = false;\n\n // report user permission to the model\n for (let role in this.currentEditingUserPermission.permissions) {\n this.currentEditingUserPermissionModel[this.currentEditingUserPermission.permissions[role]] = true;\n }\n\n }",
"userPermissionSet(\n { commit, dispatch, rootState, rootGetters },\n { id, userId, permission }\n ) {\n dispatch('sync/start', `layersUserPermissionSet`, { root: true })\n return rootState.api\n .setLayerPermissionsForUser(id, userId, permission)\n .then(p => {\n const permissions = p.data\n dispatch('sync/stop', `layersUserPermissionSet`, {\n root: true\n })\n commit('permissionsUpdate', {\n id,\n typeId: userId,\n permission: (permissions.users && permissions.users[userId]) || 0,\n type: 'users'\n })\n dispatch('messages/success', 'User permissions updated', {\n root: true\n })\n\n // If the current user was updated\n // And if the current user is not an admin\n // => the permissions for the current user have changed\n if (\n rootGetters['user/isCurrentUser'](userId) &&\n !rootGetters['user/isAdmin'](permissions)\n ) {\n // Re-list the layers in every corpuUids\n dispatch('listAll')\n commit('popup/close', null, { root: true })\n }\n\n return permissions\n })\n .catch(e => {\n dispatch('sync/stop', `layersUserPermissionSet`, {\n root: true\n })\n dispatch('messages/error', e.message, { root: true })\n\n throw e\n })\n }",
"grantPrivileges() {\n const result = [];\n Object.keys(this._config.grantPrivileges).forEach((privilege) => {\n if (this.hasPrivilege(privilege)) {\n result.push(privilege);\n }\n });\n return result;\n }",
"getEffectiveBasePermissions(webObjectIdentity, webUrl, formDigestValue) {\n const basePermissionsResult = new base_permissions_1.BasePermissions();\n const requestOptions = {\n url: `${webUrl}/_vti_bin/client.svc/ProcessQuery`,\n headers: {\n 'X-RequestDigest': formDigestValue\n },\n body: `<Request AddExpandoFieldTypeSuffix=\"true\" SchemaVersion=\"15.0.0.0\" LibraryVersion=\"16.0.0.0\" ApplicationName=\"${config_1.default.applicationName}\" xmlns=\"http://schemas.microsoft.com/sharepoint/clientquery/2009\"><Actions><Query Id=\"11\" ObjectPathId=\"5\"><Query SelectAllProperties=\"false\"><Properties><Property Name=\"EffectiveBasePermissions\" ScalarProperty=\"true\" /></Properties></Query></Query></Actions><ObjectPaths><Identity Id=\"5\" Name=\"${webObjectIdentity}\" /></ObjectPaths></Request>`\n };\n return new Promise((resolve, reject) => {\n request_1.default.post(requestOptions).then((res) => {\n if (this.debug) {\n this.cmd.log('Attempt to get the web EffectiveBasePermissions');\n }\n const json = JSON.parse(res);\n const contents = json.find(x => { return x.ErrorInfo; });\n if (contents && contents.ErrorInfo) {\n return reject(contents.ErrorInfo.ErrorMessage || 'ClientSvc unknown error');\n }\n const permissionsObj = json.find(x => { return x.EffectiveBasePermissions; });\n if (permissionsObj) {\n basePermissionsResult.high = permissionsObj.EffectiveBasePermissions.High;\n basePermissionsResult.low = permissionsObj.EffectiveBasePermissions.Low;\n return resolve(basePermissionsResult);\n }\n reject('Cannot proceed. EffectiveBasePermissions not found'); // this is not supposed to happen\n }, (err) => { reject(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 }",
"async function checkPermission(entType, resType, entID, resID) {\n var level = 0 //no permissions is assumed until proven otherwise\n var anyone = get_group.get(\"all\")\n var groupID = anyone ? anyone.GroupID : null\n var result = get_perms(\"GroupEnt\", groupID, resType, resID) //check if the all group has been granted access and what level\n if(result?.Permissions >= level) { level = result.Permissions }\n\n result = get_perms(entType, entID, resType, resID) //check if the user has been explicitly granted permissions and what level\n if (result?.Permissions >= level) { level = result.Permissions }\n if (entType == \"UserEnt\") {\n groups = get_groups?.get(entID)\n if (groups) {\n groups = Object?.values(groups) //get IDs of all groups that the user belongs to \n groups?.forEach((group) => {\n result = get_perms(\"GroupEnt\", group, resType, resID)\n if (result?.Permissions >= level) { level = result.Permissions } //check permissions of each group that the user belongs to and what level\n })\n }\n }\n return level //return highest level of permission that user has been granted whether explicitly or through some group\n}",
"function get_perms(entType, entID, resType, resID) {\n return db.prepare(`SELECT Permissions FROM Perms WHERE ${entType}=? AND ${resType}=?;`).get(entID, resID)\n}",
"function filterPermissionsByRestrictedAccessHandler(context, entityTypeId, entityId, permissions, operationMsg) {\n if (context.user.restrictedAccessHandler) {\n const originalOperations = permissions;\n if (context.user.restrictedAccessHandler.permissions) {\n const entityPerms = context.user.restrictedAccessHandler.permissions[entityTypeId];\n\n if (!entityPerms) {\n permissions = [];\n } else if (entityPerms === true) {\n // no change to operations\n } else if (entityPerms instanceof Set) {\n permissions = permissions.filter(perm => entityPerms.has(perm));\n } else {\n if (entityId) {\n const allowedPerms = entityPerms[entityId];\n if (allowedPerms) {\n permissions = permissions.filter(perm => allowedPerms.has(perm));\n } else {\n const allowedPerms = entityPerms['default'];\n if (allowedPerms) {\n permissions = permissions.filter(perm => allowedPerms.has(perm));\n } else {\n permissions = [];\n }\n }\n } else {\n const allowedPerms = entityPerms['default'];\n if (allowedPerms) {\n permissions = permissions.filter(perm => allowedPerms.has(perm));\n } else {\n permissions = [];\n }\n }\n }\n } else {\n permissions = [];\n }\n log.verbose(operationMsg + ' with restrictedAccessHandler -- entityTypeId: ' + entityTypeId + ' entityId: ' + entityId + ' operations: [' + originalOperations + '] -> [' + permissions + ']');\n }\n\n return permissions;\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 permissions (stat) {\n let owner = fsUid > 0 ? fsUid === stat.uid : true\n let group = fsGid > 0 ? fsGid === stat.gid : true\n let mode = stat.mode\n return (canRead(owner, group, mode) ? 4 : 0) |\n (canWrite(owner, group, mode) ? 2 : 0) |\n (canExec(owner, group, mode) ? 1 : 0)\n }",
"function fnsviewpermissiondetails() {\r\n\t\t$http.get('http://localhost:1337/viewpermissions').success(function (data) {\r\n\t\t\t$scope.userrelationcollection = data;\r\n\t\t});\r\n\t}",
"getAllAdmins() {\n return this.getUserSets('ADMIN');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fungsi untuk cloud mask dari band Fmask data Landsat 8 SR. | function maskL8sr(image) {
// Bit 3 dan 5 masing-masing adalah cloud shadow dan cloud.
var cloudShadowBitMask = ee.Number(2).pow(3).int();
var cloudsBitMask = ee.Number(2).pow(5).int();
// Dapatkan band pixel QA (Quality Assessment)
// Landsat 8 SR mempunyai sr_aerosol band, pixel_qa band, dan radsat_qa band
var qa = image.select('pixel_qa');
// Kedua 'flag' harus diatur ke 'nol', yang menunjukkan kondisi yang jelas (bebas awan dan bayangan awan).
var mask = qa.bitwiseAnd(cloudShadowBitMask).eq(0)
.and(qa.bitwiseAnd(cloudsBitMask).eq(0));
// Kembalikan nilai citra yang di-mask, diskalakan ke [0, 1].
return image.updateMask(mask).divide(10000);
} | [
"function fMask(img){\n var fmsk = img.select('cfmask');\n var cloudAndShadow = fmsk.eq(2).or(fmsk.eq(4)).eq(0);\n return img.updateMask(img.mask().and(cloudAndShadow));\n}",
"function computeSlopeMask(threshold) {\n var minWaterMask = mndwiMax.gt(ndwiMinWater) // maximum looks like water\n var maxLandMask = mndwiMin.lt(ndwiMaxLand) // minimum looks like land\n \n var mask = scale.unmask().abs().gt(threshold)\n .multiply(minWaterMask) \n .multiply(maxLandMask) \n\n if(ndviFilter > -1) {\n var ndviMask = ndviMin.lt(ndviFilter)\n mask = mask.multiply(ndviMask) // deforestation?\n }\n\n if(filterCount > 0) {\n var countMask = annualPercentile.select('count').min().gt(filterCount)\n mask = mask.multiply(countMask);\n }\n \n if(options.useSwbdMask) {\n mask = mask.multiply(swbdMask)\n }\n \n // add eroded original scale mask (small scale-friendly erosion, avoid kernel too large)\n var erodedScaleMask = scaleMask\n .focal_min(10000, 'square', 'meters').reproject('EPSG:4326', null, 1000)\n\n mask = mask.multiply(erodedScaleMask)\n\n if(options.debugMapLayers) {\n Map.addLayer(minWaterMask.not().mask(minWaterMask.not()), {}, 'min water mask', false)\n Map.addLayer(maxLandMask.not().mask(maxLandMask.not()), {}, 'max land mask', false)\n \n if(ndviFilter > -1) {\n Map.addLayer(ndviMask.not().mask(ndviMask.not()), {}, 'ndvi mask', false)\n }\n if(filterCount > 0) {\n Map.addLayer(countMask.not().mask(countMask.not()), {}, 'count mask', false)\n }\n \n if(options.useSwbdMask) {\n Map.addLayer(swbdMask.not().mask(swbdMask.not()), {}, 'swbd mask', false)\n }\n \n Map.addLayer(erodedScaleMask.not().mask(erodedScaleMask.not()), {}, 'scale original mask (eroded)', false)\n }\n\n return mask;\n }",
"function removeMasks() {\n $('form').submit(function () {\n $('.mask-cpf').mask(\"99999999999\");\n $('.mask-zipcode').mask(\"99999999\");\n });\n}",
"function getFmask(field, mask, customMask, placeholder) {\r\n if (mask=='')\r\n return\r\n jQuery(function($) {\r\n if (customMask!='') {\r\n $.mask.definitions['~']=customMask\r\n }\r\n $('#'+field).mask(mask,{placeholder:placeholder})\r\n } )\r\n}",
"function imageMask(img, f, maskValue) {\n function mask(img, x, y){\n if (f(img, x, y)) {return maskValue;}\n else {return img.getPixel(x, y);}\n }\n return imageMapXY(img, mask);\n}",
"function projectShadows(cloudMask,TDOMMask,image, meanAzimuth,meanZenith,cloudHeights,dilatePixels){\n //Find dark pixels\n var darkPixels = image.select(['nir','swir1','swir2']).reduce(ee.Reducer.sum()).lt(irSumThresh);//.gte(1);\n \n //Get scale of image\n var nominalScale = cloudMask.projection().nominalScale();\n\n //Find where cloud shadows should be based on solar geometry\n //Convert to radians\n var azR =ee.Number(meanAzimuth).multiply(Math.PI).divide(180.0).add(ee.Number(0.5).multiply(Math.PI ));\n var zenR =ee.Number(0.5).multiply(Math.PI ).subtract(ee.Number(meanZenith).multiply(Math.PI).divide(180.0));\n \n //Find the shadows\n var shadows = cloudHeights.map(function(cloudHeight){\n cloudHeight = ee.Number(cloudHeight);\n \n var shadowCastedDistance = zenR.tan().multiply(cloudHeight);//Distance shadow is cast\n var x = azR.cos().multiply(shadowCastedDistance).divide(nominalScale).round();//X distance of shadow\n var y = azR.sin().multiply(shadowCastedDistance).divide(nominalScale).round();//Y distance of shadow\n return cloudMask.changeProj(cloudMask.projection(), cloudMask.projection().translate(x, y));\n });\n\n var shadow = ee.ImageCollection.fromImages(shadows).max();\n \n //Create shadow mask\n shadow = shadow.updateMask(shadow.mask().and(cloudMask.mask().not()));\n shadow = shadow.focal_max(dilatePixels);\n shadow = shadow.updateMask(shadow.mask().and(darkPixels).and(TDOMMask));\n \n \n return shadow;\n}",
"draw_with_mask(mask)\n {\n for (let i = 0; i < 4; i++)\n for (let j = 0; j < 4; j++)\n if (mask[i][j] === 0 || this.numbers[i][j] === 0)\n {\n let grid = new FilletRectangle(width / 2 - height / 2 + j * (gap + grid_size) + gap, i * (gap + grid_size) + gap, grid_size, grid_size, 5, 'rgb(50, 50, 50)');\n grid.draw();\n }\n else\n {\n // draw grids' color\n let color = this.num2color.get(this.numbers[i][j]);\n if (color === undefined)\n color = this.num2color.get(2048);\n let rec = new FilletRectangle(width / 2 - height / 2 + j * (gap + grid_size) + gap, i * (gap + grid_size) + gap, grid_size, grid_size, 5, color);\n rec.draw();\n\n // draw numbers (white)\n this.draw_number([i, j]);\n }\n }",
"mask({ data, scope = 'public' }) {\n const modelMask = this.model.getMask({ scope });\n\n validate(modelMask, { minLength: 1, type: 'string' });\n\n return mask(data, modelMask);\n }",
"startMasks() {\n $.each(this.masks, (wrapperFieldSelector, mask) => {\n const $wrapperField = $(wrapperFieldSelector);\n if (! $wrapperField.length) {\n return;\n }\n const $input = $wrapperField.find('input');\n if (! $input.length) {\n return;\n }\n $input.mask(mask);\n });\n }",
"maskFilter (mask) {\n\t\treturn (el, index) => {\n\t\t\treturn mask[index % mask.length];\n\t\t};\n\t}",
"function filterColS1(startdate, enddate, bounds) {\n //Asign proper cloud and collection filter\n var Icol = 'COPERNICUS/S1_GRD_FLOAT';\n \n //Search Image Collection\n var IC = ee.ImageCollection(Icol)\n .filterBounds(bounds.geometry()) //reduce search to bounds\n .filterDate(startdate, enddate) //reduce search to date range\n .filterMetadata('instrumentMode', 'equals', 'IW')\n .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV'))\n .filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VH'));\n \n IC = IC.map(maskEdge); // remove black edges by buffering\n \n IC = IC\n .sort('system:time_start');\n \n //Number of Images in Collection\n var Icount = IC.size();\n // print(Icol, ' collection size: ', Icount)\n \n //return a collection\n return ee.ImageCollection(IC);\n }",
"function createFrictionLayer(filteredfrictionData) {\n circleGroup = [];\n map.removeLayer(frictionCanvas);\n frictionCanvas = L.canvas({ padding: 0.5, pane: \"circlemarkers\", });\n //frictionCanvas.clearLayers();\n\n for (var i = 0; i < filteredfrictionData.length; i += 1) { \n\n if(filteredfrictionData[i].MeasureValue >= 0.35 && filteredfrictionData[i].MeasureValue < 1.00){\n var frictionPointColor ='#007000';\n\n }else if(filteredfrictionData[i].MeasureValue >= 0.25 && filteredfrictionData[i].MeasureValue < 0.34){\n var frictionPointColor ='#FFBF00';\n\n }else{\n // 0.00-0.25 and Measurevalues that aren't valid.\n var frictionPointColor ='#CC0000';\n }\n \n let circle = L.circleMarker([filteredfrictionData[i].Latitude, filteredfrictionData[i].Longitude], {\n renderer: frictionCanvas,\n color: frictionPointColor\n \n });\n\n circle.bindPopup(popupfriction(filteredfrictionData[i], circle));\n circleGroup.push(circle);\n circle.addTo(map);\n \n }\n \n\n\n //Det är här för att det ska ladda snyggare. Motsvarande för att sätta igång är i maptilelayers.js i början av funktionen.\n geojson.eachLayer(function (layer) { \n layer.setStyle({fillOpacity :0 }) \n noColor = true;\n });\n\n info.remove(map);\n //temperatureScale.remove(map);\n $( \"#search-container\" ).hide();\n}",
"function createMask(m)\n{\n\tmask = \"\";\n\tword_length = m.length;\n \nfor (i = 0; i < word_length; i ++)\n{\n\tmask += \"#\";\n}\n\treturn mask;\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 mxRackF5BigIpi7000(bounds, fill, stroke, strokewidth)\n{\n\tmxShape.call(this);\n\tthis.bounds = bounds;\n\tthis.fill = fill;\n\tthis.stroke = stroke;\n\tthis.strokewidth = (strokewidth != null) ? strokewidth : 1;\n}",
"function MasklayerHide() {\r\n var bgObj = document.getElementById(\"MaskLayout\");\r\n bgObj.style.display = \"none\";\r\n//\tif($.browser.firefox){\r\n//\t\tvar bgObjfirefox=document.getElementById(\"MaskLayoutFirefox\");\r\n//\t\tbgObjfirefox.style.display = \"none\";\r\n//\t}\r\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 }",
"function modis_qaMask(image) {\n var qa = image.select('SummaryQA')\n var mask = qa.eq(0)\n return image.updateMask(mask)\n}",
"function mxRackF5BigIpi2000(bounds, fill, stroke, strokewidth)\n{\n\tmxShape.call(this);\n\tthis.bounds = bounds;\n\tthis.fill = fill;\n\tthis.stroke = stroke;\n\tthis.strokewidth = (strokewidth != null) ? strokewidth : 1;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET PENCIL SHADE, A RETANGLE PATH | function getPencilHolderShade(x,y,w,h){
var result="M"+x+" "+y+",";
result=result+"L"+(x+w)+" "+y+",";
result=result+"L"+(x+w)+" "+(y+h)+",";
result=result+"L"+x+" "+(y+h)+",";
result=result+"Z";
return result;
} | [
"function getPencilHead(x,y,s){\n\tvar result=\"M\"+(x+s)+\" \"+y+\",\";\n\tresult=result+\"L\"+(x+s/3)+\" \"+y+\",\";\n\tresult=result+\"L\"+(x+s/3)+\" \"+(y+s/6)+\",\";\n\tresult=result+\"S\"+(x-s/3)+\" \"+(y+s/2)+\" \"+(x+s/3)+\" \"+(y+s*5/6)+\",\";\n\tresult=result+\"L\"+(x+s/3)+\" \"+(y+s)+\",\";\n\tresult=result+\"L\"+(x+s)+\" \"+(y+s)+\",\";\n\tresult=result+\"Z\";\n\t\n\treturn result;\n}",
"function getPencilBody(x,y,s){\n\tvar result=\"M\"+x+\" \"+y+\",\";\n\tresult=result+\"L\"+(x+s*4)+\" \"+y+\",\";\n\tresult=result+\"S\"+(x+s*4.5)+\" \"+(y+s/2)+\" \"+(x+s*4)+\" \"+(y+s)+\",\";\n\tresult=result+\"L\"+x+\" \"+(y+s)+\",\";\n\tresult=result+\"Z\";\n\t\n\treturn result;\n}",
"function getGearDarkShade(x,y,s){\n\tvar result=\"M\"+(x+Math.cos(Math.PI*11/12)*s/2)+\" \"+(y-Math.sin(Math.PI*11/12)*s/2)+\",L\"+(x+Math.cos(Math.PI*11/12)*s/2)+\" \"+(y-Math.sin(Math.PI*11/12)*s/2+s/12)+\",L\"+(x+Math.cos(Math.PI*11/12)*s/3)+\" \"+(y-Math.sin(Math.PI*11/12)*s/3+s/12)+\",L\"+(x+Math.cos(Math.PI*11/12)*s/3)+\" \"+(y-Math.sin(Math.PI*11/12)*s/3)+\"Z,\";\n\t\n\tresult=result+\"M\"+(x+Math.cos(-Math.PI*3/4)*s/2)+\" \"+(y-Math.sin(-Math.PI*3/4)*s/2)+\",L\"+(x+Math.cos(-Math.PI*3/4)*s/2)+\" \"+(y-Math.sin(-Math.PI*3/4)*s/2+s/12)+\",L\"+(x+Math.cos(-Math.PI*11/12)*s/2)+\" \"+(y-Math.sin(-Math.PI*11/12)*s/2+s/12)+\",L\"+(x+Math.cos(-Math.PI*11/12)*s/2)+\" \"+(y-Math.sin(-Math.PI*11/12)*s/2)+\"Z,\";\n\t\n\tresult=result+\"M\"+(x+Math.cos(-Math.PI*7/12)*s/3)+\" \"+(y-Math.sin(-Math.PI*7/12)*s/3)+\",L\"+(x+Math.cos(-Math.PI*7/12)*s/3)+\" \"+(y-Math.sin(-Math.PI*7/12)*s/3+s/12)+\",S\"+(x+Math.cos(-Math.PI*2/3)*s/3)+\" \"+(y-Math.sin(-Math.PI*2/3)*s/3+s/12)+\" \"+(x+Math.cos(-Math.PI*3/4)*s/3)+\" \"+(y-Math.sin(-Math.PI*3/4)*s/3+s/12)+\",L\"+(x+Math.cos(-Math.PI*3/4)*s/3)+\" \"+(y-Math.sin(-Math.PI*3/4)*s/3)+\"Z,\";\n\t\n\tresult=result+\"M\"+(x+Math.cos(-Math.PI/4)*s/3)+\" \"+(y-Math.sin(-Math.PI/4)*s/3)+\",L\"+(x+Math.cos(-Math.PI/4)*s/2)+\" \"+(y-Math.sin(-Math.PI/4)*s/2)+\",L\"+(x+Math.cos(-Math.PI/4)*s/2)+\" \"+(y-Math.sin(-Math.PI/4)*s/2+s/12)+\",L\"+(x+Math.cos(-Math.PI/4)*s/3)+\" \"+(y-Math.sin(-Math.PI/4)*s/3+s/12)+\"Z\";\n\t\n\treturn result;\n}",
"path(x, y) {\n stroke(116, 122, 117);\n strokeWeight(4);\n fill(147, 153, 148);\n for (let i = 0; i < 2; i++) {\n for (let j = 0; j < 2; j++) {\n rect(x - this.pxl * i, y + this.pxl * j, this.pxl, this.pxl);\n }\n }\n }",
"get needleOutline() {\n return brushToString(this.i.hy);\n }",
"function getGearLightShade(x,y,s){\n\tvar result=\"M\"+(x+Math.cos(Math.PI/12)*s/2)+\" \"+(y-Math.sin(Math.PI/12)*s/2)+\",L\"+(x+Math.cos(Math.PI/12)*s/2)+\" \"+(y-Math.sin(Math.PI/12)*s/2+s/12)+\",L\"+(x+Math.cos(Math.PI/12)*s/3)+\" \"+(y-Math.sin(Math.PI/12)*s/3+s/12)+\",L\"+(x+Math.cos(Math.PI/12)*s/3)+\" \"+(y-Math.sin(Math.PI/12)*s/3)+\"Z,\";\n\t\n\tresult=result+\"M\"+(x+Math.cos(-Math.PI/12)*s/2)+\" \"+(y-Math.sin(-Math.PI/12)*s/2)+\",L\"+(x+Math.cos(-Math.PI/12)*s/2)+\" \"+(y-Math.sin(-Math.PI/12)*s/2+s/12)+\",L\"+(x+Math.cos(-Math.PI/4)*s/2)+\" \"+(y-Math.sin(-Math.PI/4)*s/2+s/12)+\",L\"+(x+Math.cos(-Math.PI/4)*s/2)+\" \"+(y-Math.sin(-Math.PI/4)*s/2)+\"Z,\";\n\t\n\tresult=result+\"M\"+(x+Math.cos(-Math.PI*5/12)*s/3)+\" \"+(y-Math.sin(-Math.PI*5/12)*s/3)+\",L\"+(x+Math.cos(-Math.PI*5/12)*s/3)+\" \"+(y-Math.sin(-Math.PI*5/12)*s/3+s/12)+\",S\"+(x+Math.cos(-Math.PI/3)*s/3)+\" \"+(y-Math.sin(-Math.PI/3)*s/3+s/12)+\" \"+(x+Math.cos(-Math.PI/4)*s/3)+\" \"+(y-Math.sin(-Math.PI/4)*s/3+s/12)+\",L\"+(x+Math.cos(-Math.PI/4)*s/3)+\" \"+(y-Math.sin(-Math.PI/4)*s/3)+\"Z,\";\n\t\n\tresult=result+\"M\"+(x+Math.cos(-Math.PI*5/12)*s/2)+\" \"+(y-Math.sin(-Math.PI*5/12)*s/2)+\",L\"+(x+Math.cos(-Math.PI*5/12)*s/2)+\" \"+(y-Math.sin(-Math.PI*5/12)*s/2+s/12)+\",L\"+(x+Math.cos(-Math.PI*7/12)*s/2)+\" \"+(y-Math.sin(-Math.PI*7/12)*s/2+s/12)+\",L\"+(x+Math.cos(-Math.PI*7/12)*s/2)+\" \"+(y-Math.sin(-Math.PI*7/12)*s/2)+\"Z,\";\n\t\n\tresult=result+\"M\"+(x+Math.cos(-Math.PI*3/4)*s/3)+\" \"+(y-Math.sin(-Math.PI*3/4)*s/3)+\",L\"+(x+Math.cos(-Math.PI*3/4)*s/2)+\" \"+(y-Math.sin(-Math.PI*3/4)*s/2)+\",L\"+(x+Math.cos(-Math.PI*3/4)*s/2)+\" \"+(y-Math.sin(-Math.PI*3/4)*s/2+s/12)+\",L\"+(x+Math.cos(-Math.PI*3/4)*s/3)+\" \"+(y-Math.sin(-Math.PI*3/4)*s/3+s/12)+\"Z,\";\n\t\n\tresult=result+\"M\"+(x+s/6)+\" \"+y+\",S\"+x+\" \"+(y-s/6)+\" \"+(x-s/6)+\" \"+y+\",A\"+(s/6)+\" \"+(s/6)+\" 1 1 1 \"+(x+s/6)+\" \"+y;\n\t\n\treturn result;\n}",
"function getEraserFrontSide(x,y,s){\n\tvar result=\"M\"+(x-s*2/3)+\" \"+(y+s/3)+\",\";\n\tresult=result+\"L\"+(x-s/3*8)+\" \"+(y+s/3)+\",\";\n\tresult=result+\"L\"+(x-s/3*8)+\" \"+(y+s*5/6)+\",\";\n\tresult=result+\"L\"+(x-s*2/3)+\" \"+(y+s*5/6)+\",\";\n\tresult=result+\"Z\";\n\t\n\treturn result;\n}",
"function createPathString(data) {\n\t\t\t\n\t\t\t var points = data.charts[data.current].points;\n\t\t\t\n\t\t\t \n\t\t\t\tvar path = 'M 25 291 L ' + data.xOffset + ' ' + (data.yOffset - points[0].value);\n\t\t\t\tvar prevY = data.yOffset - points[0].value;\n\t\t\t\n\t\t\t\tfor (var i = 1, length = points.length; i < length; i++) {\n\t\t\t\t\tpath += ' L ';\n\t\t\t\t\tpath += data.xOffset + (i * data.xDelta) + ' ';\n\t\t\t\t\tpath += (data.yOffset - points[i].value);\n\t\t\t\n\t\t\t\t\tprevY = data.yOffset - points[i].value;\n\t\t\t\t}\n\t\t\t\t//path += ' L 989 291 Z';\n\t\t\t\tpath += ' L 2200 291 Z';\n\t\t\t\treturn path;\n\t\t\t}",
"function renderPallet(){\n\tfor(let i = 0; i < numColor; i++){\n\t\tswatches[i].display();\n\t}\n\tfillIcon.display();\n}",
"makeWell() {\n stroke(116, 122, 117);\n strokeWeight(2);\n fill(147, 153, 148);\n ellipse(125, 75, this.pxl, this.pxl);\n fill(0, 0, 255);\n ellipse(125, 75, this.pxl - 10, this.pxl - 10);\n }",
"function getEraserRightSide(x,y,s){\n\tvar result=\"M\"+x+\" \"+y+\",\";\n\tresult=result+\"S\"+(x-s/3)+\" \"+y+\" \"+(x-s*2/3)+\" \"+(y+s/3)+\",\";\n\tresult=result+\"L\"+(x-s*2/3)+\" \"+(y+s*5/6)+\",\";\n\tresult=result+\"L\"+(x-s*7/9)+\" \"+(y+s)+\",\";\n\tresult=result+\"S\"+(x-s/2)+\" \"+(y+s)+\" \"+(x+s/6)+\" \"+(y+s/3)+\",\";\n\tresult=result+\"L\"+x+\" \"+(y+s/2)+\",\";\n\tresult=result+\"Z\";\n\t\t\n\treturn result;\n}",
"startPencil(event){\n this.art.push({\n tool: 'polyline',\n points: `${event.clientX},${event.clientY} `,\n width: this.strokeWidth != 0 ? this.strokeWidth : 1,\n stroke: this.stroke\n });\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 drawOutline(){\n fill(125);\n stroke(125);\n index = buttonArr.indexOf(buttonVal2);\n rect(windowWidth/2 - 394 + 1920/42 * (index+1), windowHeight - 104, 39, 39, 4, 4) \n}",
"getOutline(){\n if(!this.surfaces.length) return null;\n let pointsFromSurfaces = [];\n for(let surface of this.surfaces){\n pointsFromSurfaces = pointsFromSurfaces.concat(surface.points);\n }\n return grahamScan(pointsFromSurfaces);\n }",
"get MeshRenderer() {}",
"function getWireframeColor() {\r\n var hex = document.getElementById(\"foreground-color\").value;\r\n var red = parseInt(hex.substring(1, 3), 16);\r\n var green = parseInt(hex.substring(3, 5), 16);\r\n var blue = parseInt(hex.substring(5, 7), 16);\r\n return vec4(red / 255.0, green / 255.0, blue / 255.0);\r\n}",
"function _g_scr_color() { \n\tvar sc=\"\";\n\tif (self.screen) {\n\t\tsc=screen.colorDepth+\"-bit\";\n\t}\n\treturn sc;\n}",
"function DrawHelperStrokes(){\n context.strokeStyle = 'green'\n context.beginPath();\n context.arc(Dx, Dy, 5, 0, Math.PI*2, false);\n context.stroke();\n\n context.beginPath();\n context.moveTo(Ax, Ay);\n context.lineTo(Dx-(Ax-Dx)*0.6, Dy-(Ay-Dy)*0.6);\n context.stroke();\n\n context.beginPath();\n context.moveTo(Bx, By);\n context.lineTo(Dx-(Bx-Dx)*0.6, Dy-(By-Dy)*0.6);\n context.stroke();\n\n context.beginPath();\n context.moveTo(Cx, Cy);\n context.lineTo(Dx-(Cx-Dx)*0.6, Dy-(Cy-Dy)*0.6);\n context.stroke();\n context.strokeStyle = 'black'\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that we fail gracefully if we try to attach() a on a newwindow event after the opener has been destroyed. | function testNewWindowAttachAfterOpenerDestroyed() {
var testName = 'testNewWindowAttachAfterOpenerDestroyed';
var webview = embedder.setUpGuest_('foobar');
var onNewWindow = function(e) {
embedder.assertCorrectEvent_(e, '');
// Remove the opener.
webview.parentNode.removeChild(webview);
// Pass in a timeout so we ensure the newwindow disposal codepath
// works properly.
window.setTimeout(function() {
// At this point the opener <webview> is gone.
// Trying to discard() will fail silently.
e.window.attach(document.createElement('webview'));
window.setTimeout(function() { embedder.test.succeed(); }, 0);
}, 0);
e.preventDefault();
};
webview.addEventListener('newwindow', onNewWindow);
// Load a new window with the given name.
embedder.setUpNewWindowRequest_(webview, 'guest.html', '', testName);
} | [
"function testNewWindowDiscardAfterOpenerDestroyed() {\n var testName = 'testNewWindowDiscardAfterOpenerDestroyed';\n var webview = embedder.setUpGuest_('foobar');\n\n var onNewWindow = function(e) {\n embedder.assertCorrectEvent_(e, '');\n\n // Remove the opener.\n webview.parentNode.removeChild(webview);\n // Pass in a timeout so we ensure the newwindow disposal codepath\n // works properly.\n window.setTimeout(function() {\n // At this point the opener <webview> is gone.\n // Trying to discard() will fail silently.\n e.window.discard();\n window.setTimeout(function() { embedder.test.succeed(); }, 0);\n }, 0);\n\n e.preventDefault();\n };\n webview.addEventListener('newwindow', onNewWindow);\n\n // Load a new window with the given name.\n embedder.setUpNewWindowRequest_(webview, 'guest.html', '', testName);\n}",
"function testNewWindowDeferredAttachment() {\n var testName = 'testNewWindowDeferredAttachment';\n var webview = embedder.setUpGuest_('foobar');\n\n var onNewWindow = function(e) {\n chrome.test.log('Embedder notified on newwindow');\n embedder.assertCorrectEvent_(e, '');\n\n var newwebview = document.createElement('webview');\n\n newwebview.addEventListener('loadstop', function() {\n chrome.test.log('Guest in newwindow got loadstop.');\n embedder.test.succeed();\n });\n\n try {\n e.window.attach(newwebview);\n } catch (e) {\n embedder.test.fail();\n }\n\n // Append the <webview> in DOM later.\n window.setTimeout(function() {\n document.querySelector('#webview-tag-container').appendChild(newwebview);\n }, 0);\n };\n webview.addEventListener('newwindow', onNewWindow);\n\n // Load a new window with the given name.\n embedder.setUpNewWindowRequest_(webview, 'guest.html', '', testName);\n}",
"function testDestroyOpenerBeforeAttachment() {\n embedder.test.succeed();\n\n let webview = new WebView();\n webview.src = embedder.guestOpenOnLoadURL;\n document.body.appendChild(webview);\n\n // By spinning forever here, we prevent `webview` from completing the\n // attachment process. But since the guest is still created and it calls\n // window.open, we have a situation where two unattached webviews have an\n // opener relationship. The C++ side will test that we can shutdown safely in\n // this case.\n while (true) {}\n}",
"async function testNewWindowAttachInSubFrame() {\n let testName = 'testNewWindowAttachInSubFrame';\n let webview = embedder.setUpGuest_('foobar');\n\n let subframe = document.createElement('iframe');\n subframe.src = '/subframe_with_webview.html';\n await new Promise((resolve) => {\n subframe.onload = resolve;\n document.body.appendChild(subframe);\n });\n\n webview.addEventListener('newwindow', (e) => {\n embedder.assertCorrectEvent_(e, '');\n\n let newwebview = subframe.contentDocument.querySelector('webview');\n newwebview.addEventListener('loadstop', embedder.test.succeed);\n try {\n e.window.attach(newwebview);\n } catch (e) {\n embedder.test.fail();\n }\n });\n\n embedder.setUpNewWindowRequest_(webview, 'guest.html', '', testName);\n}",
"function popupPVAsWindow_onbeforeUnload(event)\n{\n\ttry\n\t{\n\t\t// explorer?\n\t\tif (window.event)\n\t\t{\n\t\t\te = window.event;\n\t\t}\n\t\t\n\t\tif (e.clientX <= 0 || e.clientY <= 0)\n\t\t{\n\t\t\tif (!window.close())\n\t\t\t{\n\t\t\t\tdt_pvClosePopUp(false);\n\t\t\t}\n\t\t}\n\t}\n\tcatch(e)\n\t{\n\t}\n}",
"function aePopupModalWindow(aParentWindow, aUri, aWinName, aWidth, aHeight, aResizable, aParams)\r\n{\r\n\treturn aePopupWindow(aParentWindow, aUri, aWinName, aWidth, aHeight, aResizable, true, aParams);\r\n}",
"adoptTab(aTab, aIndex, aSelectTab) {\n // Swap the dropped tab with a new one we create and then close\n // it in the other window (making it seem to have moved between\n // windows). We also ensure that the tab we create to swap into has\n // the same remote type and process as the one we're swapping in.\n // This makes sure we don't get a short-lived process for the new tab.\n let linkedBrowser = aTab.linkedBrowser;\n let params = {\n eventDetail: { adoptedTab: aTab },\n preferredRemoteType: linkedBrowser.remoteType,\n sameProcessAsFrameLoader: linkedBrowser.frameLoader,\n skipAnimation: true,\n index: aIndex,\n };\n\n let numPinned = this._numPinnedTabs;\n if (aIndex < numPinned || (aTab.pinned && aIndex == numPinned)) {\n params.pinned = true;\n }\n\n if (aTab.hasAttribute(\"usercontextid\")) {\n // new tab must have the same usercontextid as the old one\n params.userContextId = aTab.getAttribute(\"usercontextid\");\n }\n let newTab = this.addWebTab(\"about:blank\", params);\n let newBrowser = this.getBrowserForTab(newTab);\n\n // Stop the about:blank load.\n newBrowser.stop();\n // Make sure it has a docshell.\n newBrowser.docShell;\n\n // We need to select the tab before calling swapBrowsersAndCloseOther\n // so that window.content in chrome windows points to the right tab\n // when pagehide/show events are fired. This is no longer necessary\n // for any exiting browser code, but it may be necessary for add-on\n // compatibility.\n if (aSelectTab) {\n this.selectedTab = newTab;\n }\n\n aTab.parentNode._finishAnimateTabMove();\n this.swapBrowsersAndCloseOther(newTab, aTab);\n\n if (aSelectTab) {\n // Call updateCurrentBrowser to make sure the URL bar is up to date\n // for our new tab after we've done swapBrowsersAndCloseOther.\n this.updateCurrentBrowser(true);\n }\n\n return newTab;\n }",
"function popupPVAsWindow_onunload(event)\n{\n\ttry\n\t{\n\t\tif (!window.close())\n\t\t{\n\t\t\tdt_pvClosePopUp(false);\n\t\t}\n\t}\n\tcatch(e)\n\t{\n\t}\n}",
"launchNewWindow(p) {\n let appInfo = this.app.get_app_info();\n let actions = appInfo.list_actions();\n if (this.app.can_open_new_window()) {\n this.animateLaunch();\n // This is used as a workaround for a bug resulting in no new windows being opened\n // for certain running applications when calling open_new_window().\n //\n // https://bugzilla.gnome.org/show_bug.cgi?id=756844\n //\n // Similar to what done when generating the popupMenu entries, if the application provides\n // a \"New Window\" action, use it instead of directly requesting a new window with\n // open_new_window(), which fails for certain application, notably Nautilus.\n if (actions.indexOf('new-window') == -1) {\n this.app.open_new_window(-1);\n }\n else {\n let i = actions.indexOf('new-window');\n if (i !== -1)\n this.app.launch_action(actions[i], global.get_current_time(), -1);\n }\n }\n else {\n // Try to manually activate the first window. Otherwise, when the app is activated by\n // switching to a different workspace, a launch spinning icon is shown and disappers only\n // after a timeout.\n let windows = this.getWindows();\n if (windows.length > 0)\n Main.activateWindow(windows[0])\n else\n this.app.activate();\n }\n }",
"function _registerLeaveAlertListener() {\n window.addEventListener(\"beforeunload\", _leaveAlertEvent);\n }",
"function WindowsManager () {\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Flag to raise while the main window is open.\r\n\t\t\t * @field\r\n\t\t\t * @private\r\n\t\t\t */\r\n\t\t\tvar isMainWindowOpen = false;\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Returns the default display options for a newly created window.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @return { NativeWindowInitOptions }\r\n\t\t\t * \t\tAn object specifying display options for a new window. \r\n\t\t\t */\r\n\t\t\tfunction getDefWindowOptions () {\r\n\t\t\t\tvar options = new NativeWindowInitOptions();\r\n\t\t\t\toptions.type = NativeWindowType.UTILITY;\r\n\t\t\t\treturn options;\r\n\t\t\t}\r\n\r\n\t\t\t/**\r\n\t\t\t * Returns the default display boundaries for a newly created \r\n\t\t\t * window.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @return { Rectangle }\r\n\t\t\t * \t\tA rectangle defining the boundaries of this new window.\r\n\t\t\t */\t\t\t\r\n\t\t\tfunction getDefBoundaries () {\r\n\t\t\t\tvar bounds = new Rectangle();\r\n\t\t\t\tbounds.x = Math.max(0, (screen.width-800)/2);\r\n\t\t\t\tbounds.y = Math.max(0, (screen.height-600)/2);\r\n\t\t\t\tbounds.width = 800;\r\n\t\t\t\tbounds.height = 600;\r\n\t\t\t\treturn bounds;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Creates the main window of the application.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t */\r\n\t\t\tthis.makeMainWindow = function () {\r\n\t\t\t\tvar htmlLoader = HTMLLoader.createRootWindow (\r\n\t\t\t\t\ttrue,\r\n\t\t\t\t\tgetDefWindowOptions(), \r\n\t\t\t\t\tfalse,\r\n\t\t\t\t\tgetDefBoundaries()\r\n\t\t\t\t);\r\n\t\t\t\thtmlLoader.addEventListener('htmlDOMInitialize', function() {\r\n\t\t\t\t\tisMainWindowOpen = true;\r\n\t\t\t\t\tmakeWindowModal (htmlLoader.window, self);\r\n\t\t\t\t\thtmlLoader.window.nativeWindow.addEventListener (\r\n\t\t\t\t\t\t'close',\r\n\t\t\t\t\t\t function() {isMainWindowOpen = false}\r\n\t\t\t\t\t);\r\n\t\t\t\t\tvar event = eventManager.createEvent(\r\n\t\t\t\t\t\tWINDOW_CREATED_EVENT,\r\n\t\t\t\t\t\t{'window': htmlLoader.window}\r\n\t\t\t\t\t);\r\n\t\t\t\t\teventManager.fireEvent(event);\r\n\t\t\t\t});\r\n\t\t\t\thtmlLoader.loadString(' ');\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Makes a window modal to a certain parent window.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param oWindow { Object Window }\r\n\t\t\t * \t\tThe window to be made modal.\r\n\t\t\t * @param oParentWindow { Object Window }\r\n\t\t\t * \t\tThe parent of the modal window. Any attempt to access the \r\n\t\t\t * \t\tparent while the modal window is open will fail.\r\n\t\t\t */\r\n\t\t\tfunction makeWindowModal (oWindow, oParentWindow) {\r\n\t\t\t\t\r\n\t\t\t\toParentWindow.nativeWindow.addEventListener (\r\n\t\t\t\t\t'closing',\r\n\t\t\t\t\tfunction (event) {\r\n\t\t\t\t\t\t//if (isMainWindowOpen) { event.preventDefault() };\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\toParentWindow.nativeWindow.addEventListener (\r\n\t\t\t\t\t'displayStateChanging', \r\n\t\t\t\t\tfunction (event) {\r\n\t\t\t\t\t\t//if (isMainWindowOpen) { event.preventDefault() };\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\toParentWindow.nativeWindow.addEventListener (\r\n\t\t\t\t\t'moving',\r\n\t\t\t\t\tfunction (event) {\r\n\t\t\t\t\t\t//if (isMainWindowOpen) { event.preventDefault() };\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\toParentWindow.nativeWindow.addEventListener (\r\n\t\t\t\t\t'resizing', \r\n\t\t\t\t\tfunction(event) {\r\n\t\t\t\t\t\t//if(isMainWindowOpen) { event.preventDefault() };\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\toWindow.nativeWindow.addEventListener(\r\n\t\t\t\t\t'deactivate',\r\n\t\t\t\t\tfunction() {\r\n\t\t\t\t\t\t//oWindow.nativeWindow.activate();\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\toWindow.nativeWindow.addEventListener(\r\n\t\t\t\t\t'closing',\r\n\t\t\t\t\tfunction(){\r\n\t\t\t\t\t\tvar ev = eventManager.createEvent(BROWSER_UNLOAD_EVENT);\r\n\t\t\t\t\t\teventManager.fireEvent(ev);\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\t \r\n\t\t\t}\r\n\t\t}",
"function checkIfFramed()\n{\n var anchors, i;\n\n if (window.parent != window) { // Only if we're not the top document\n anchors = document.getElementsByTagName('a');\n for (i = 0; i < anchors.length; i++)\n if (!anchors[i].hasAttribute('target'))\n\tanchors[i].setAttribute('target', '_parent');\n document.body.classList.add('framed'); // Allow the style to do things\n }\n}",
"onBeforeUnload(callback) {\n return this.windowEventHandler.addUnloadCallback(callback);\n }",
"onAllWindowsClosed() {\r\n // Stub\r\n }",
"function test_close_message_a() {\n close_tab();\n // our current tab is now undefined for the purposes of this test.\n}",
"function exoduswindowclose(returnvalues) {\n\n //window.opener.gchildwin_returnvalue = returnvalues\n if (window.opener) {\n window.opener.focus()//for MSEDGE\n if (window.opener.exodus_setchildwin_returnvalue) {\n if (typeof returnvalues == 'undefined')\n returnvalues = ''\n returnvalues.exodusisarray = true\n window.opener.exodus_setchildwin_returnvalue(returnvalues)\n }\n }\n window.returnValue = returnvalues\n window.close()\n}",
"function installUnsafewindowPolyfill() {\n\tif (typeof unsafeWindow === 'undefined') {\n\t\tif (typeof XPCNativeWrapper === 'function' && typeof XPCNativeWrapper.unwrap === 'function')\n\t\t\tunsafeWindow = XPCNativeWrapper.unwrap(window);\n\t\telse if (window.wrappedJSObject)\n\t\t\tunsafeWindow = window.wrappedJSObject;\n\t}\n}",
"function onClosed() {\n\t// dereference the window\n\t// for multiple windows store them in an array\n\tmainWindow = null;\n}",
"function windowExists(name) {\n\n for (var i = 0; i < windows.length; i++) {\n\n // IE needs a try/catch here for to avoid an access violation on windows[i].name\n // in some cases.\n try {\n if (windows[i].name == name) {\n return true;\n }\n }\n catch (exception) {\n }\n }\n\n return false;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FUNCTION: onRead( error, actual ) Read event handler. Checks for errors and compares streamed data to expected data. | function onRead( error, actual ) {
expect( error ).to.not.exist;
assert.strictEqual( actual[ 0 ], 2 );
done();
} | [
"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 }",
"_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 }",
"function readFilePolling(filename) {\n const stream = createReadStream(filename);\n\n stream.on('readable', () => {\n let data;\n while ((data = stream.read()) !== null) {\n console.log(data);\n }\n });\n}",
"function matchDataRead(corrupted, keys_readed) {\n \n //If the file that we read does not exist, we must invert this interaction\n if(corrupted == null){\n return true;\n }\n \n //If the corrupted version is empty, the request has not readed corrupted data\n if(Object.keys(corrupted).length==0){\n return false;\n }\n \n else{\n var field= keys_readed.shift();\n //If the corrupted contains this key\n if(corrupted.hasOwnProperty(field))\n {\n // Return true if is the last key of the path\n if(keys_readed.length==0)\n {\n return true;\n }\n // If not, we continue to analyze\n else\n {\n return matchDataRead(corrupted[field],keys_readed);\n }\n }\n else \n {\n return false\n }\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 }",
"function read(){\n\n }",
"get bytesRead() {\r\n return this.transport ? this.transport.bytesRead : 0;\r\n }",
"readEvents(checkSemaphore) {\n let fromBlock = this.lastReadBlock;\n let toBlock = fromBlock + 10000;\n if (toBlock > this.highestBlock) {\n toBlock = this.highestBlock;\n }\n if (!checkSemaphore) {\n if (this.readingEvents === true) {\n return;\n }\n this.readingEvents = true;\n }\n logger.info(\n \"Reading block-range %d -> %d (%d remaining)\",\n fromBlock,\n toBlock,\n this.highestBlock - fromBlock\n );\n this.contract.getPastEvents(\n \"PeepethEvent\",\n {\n fromBlock: fromBlock,\n toBlock: toBlock\n },\n (error, events) => {\n events.map(this.parseEvent.bind(this));\n logger.info(\"done..\");\n this.lastReadBlock = toBlock;\n if (this.highestBlock > toBlock) {\n this.readEvents(true);\n } else {\n logger.info(\n \"fromBlock %d - lastReadBlock %d - highestBlock %d\",\n fromBlock,\n this.lastReadBlock,\n this.highestBlock\n );\n logger.info(\"event reader going to sleep\");\n this.dumpUsers();\n this.readingEvents = false;\n }\n }\n );\n }",
"consumeReadableCallback() {\n if (this.readableCallback_ === null) {\n return;\n }\n const callback = this.readableCallback_;\n this.readableCallback_ = null;\n callback();\n }",
"function testChunkStreamWithData(data, chunkSize) {\n\t\t//We have to wrap all this in a promise so that the test runner\n\t\t//will wait until the asynchronous code has had a chance to complete\n\t\treturn new Promise((resolve, reject) => {\n\t\t\t//Create a Node.js read stream with the test data\n\t\t\tconst readStream = streamify(data);\n\t\t\t\n\t\t\t//Handle any read stream errors\n\t\t\treadStream.on('error', error => reject(error));\n\t\t\t\n\t\t\t//Calculate the expected chunks\n\t\t\tconst expectedChunks = calculateChunks(data, chunkSize);\n\t\t\t\n\t\t\t//Create the integer chunk stream\n\t\t\tconst stream = fileIO.createAutoPauseIntegerChunkStream(readStream, chunkSize);\n\t\t\t\n\t\t\t//Handle any integer stream errors\n\t\t\tstream.onError(error => reject(error));\n\t\t\t\n\t\t\t//Read the chunks from the integer chunk stream\n\t\t\tconst actualChunks = [];\n\t\t\t\n\t\t\tstream.onValue(chunkData => {\n\t\t\t\tactualChunks.push(chunkData.chunk);\n\t\t\t\tchunkData.resume();\n\t\t\t});\n\t\t\t\n\t\t\t//When the stream ends, compare the actual chunks with the expected chunks\n\t\t\tstream.onEnd(() => {\n\t\t\t\t//Verify that we have the same number of chunks\n\t\t\t\texpect(actualChunks.length).toBe(expectedChunks.length);\n\t\t\t\t\n\t\t\t\t//Compare the chunks to verify that they are the same\n\t\t\t\t_.zip(expectedChunks, actualChunks)\n\t\t\t\t\t.forEach(chunkPair => {\n\t\t\t\t\t\tcompareChunks(chunkPair[0], chunkPair[1]);\n\t\t\t\t\t});\n\t\t\t\t\t\n\t\t\t\tresolve();\n\t\t\t});\t\t\t\n\t\t});\n\n\t}",
"async function validateMediaFlow(room) {\n const testTimeMS = 6000;\n // wait for some time.\n await new Promise(resolve => setTimeout(resolve, testTimeMS));\n\n // get StatsReports.\n const statsBefore = await room.getStats();\n const bytesReceivedBefore = getTotalBytesReceived(statsBefore);\n\n // wait for some more time.\n await new Promise(resolve => setTimeout(resolve, testTimeMS));\n\n const statsAfter = await room.getStats();\n const bytesReceivedAfter = getTotalBytesReceived(statsAfter);\n console.log(`Total bytes Received in ${room.localParticipant.identity}'s Room: ${bytesReceivedBefore} => ${bytesReceivedAfter}`);\n if (bytesReceivedAfter <= bytesReceivedBefore) {\n throw new Error('no media flow detected');\n }\n}",
"function testIntegerStreamWithData(data) {\n\t\t//We have to wrap all this in a promise so that the test runner\n\t\t//will wait until the asynchronous code has had a chance to complete\n\t\treturn new Promise((resolve, reject) => {\n\t\t\t//Create a Node.js read stream with the test data\n\t\t\tconst readStream = streamify(data);\n\t\t\t\n\t\t\t//Handle any read stream errors\n\t\t\treadStream.on('error', error => reject(error));\n\t\t\t\n\t\t\t//Create the integer stream\n\t\t\tconst stream = fileIO.createIntegerStream(readStream);\n\t\t\t\n\t\t\t//Handle any integer stream errors\n\t\t\tstream.onError(error => reject(error));\n\t\t\t\n\t\t\t//Read the integers from the integer stream\n\t\t\tconst expectedIntegers = data.map(integerString => parseInt(integerString));\n\t\t\tconst actualIntegers = [];\n\t\t\t\n\t\t\tstream.onValue(integer => actualIntegers.push(integer));\n\t\t\t\n\t\t\t//When the stream ends, compare the actual integers with the expected integers\n\t\t\tstream.onEnd(() => {\n\t\t\t\t//Verify that we have the same number of integers\n\t\t\t\texpect(actualIntegers.length).toBe(expectedIntegers.length);\n\t\t\t\t\n\t\t\t\t//Compare the integers to verify that they are the same\n\t\t\t\t_.zip(expectedIntegers, actualIntegers)\n\t\t\t\t\t.forEach(integerPair => expect(integerPair[0]).toBe(integerPair[1]));\n\t\t\t\t\t\n\t\t\t\tresolve();\n\t\t\t});\t\t\t\n\t\t});\n\n\t}",
"function createMockedReadStream(sign, length){\n return tester.createRandomStream(function () {\n return sign;\n }, length);\n}",
"static validateReadingExceedsLength(pageClientAPI, dict) {\n\n //Reading is not allowed, or reading is optional and empty\n if (libThis.evalIgnoreReading(dict)) {\n return Promise.resolve(true);\n }\n\n //New reading length must be <= global maximum\n let max = libCom.getAppParam(pageClientAPI, 'MEASURINGPOINT', 'ReadingLength');\n\n if (libThis.evalReadingLengthWithinLimit(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, 'ReadingSim'), message);\n dict.InlineErrorsExist = true;\n return Promise.reject(false);\n }\n }",
"function onStreamError(err) {\n console.error('Log error:', err);\n process.exit(1);\n }",
"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 }",
"function captureStdio(expected, fn, opts) {\n var buf = [];\n\n var _errwrite = process.stderr.write;\n var _outwrite = process.stdout.write;\n process.stdout.write = outwrite;\n process.stderr.write = errwrite;\n\n fn();\n\n process.stdout.write = _outwrite;\n process.stderr.write = _errwrite;\n\n if (opts && opts.raw) {\n return buf;\n }\n\n return buf.some(function (line) {\n return line.indexOf(expected) !== -1;\n });\n\n function outwrite(msg, cb) {\n buf.push(msg.toString());\n\n if (opts && opts.passthrough) {\n return _outwrite.apply(this, arguments);\n }\n\n if (cb) cb();\n return true;\n }\n\n function errwrite(msg, cb) {\n buf.push(msg.toString());\n\n if (opts && opts.passthrough) {\n return _errwrite.apply(this, arguments);\n }\n\n if (cb) cb();\n return true;\n }\n}",
"function containsData(byteoffset, data_offset, data_size, chunk_size, callback) {\n // if traj data falls in this buffer\n if (byteoffset <= data_offset && byteoffset + chunk_size > data_offset) {\n \n // if the buffer contains all the traj data\n if (byteoffset + chunk_size > data_offset + data_size) {\n // trajectory = {};\n\n var offset = data_offset - byteoffset;\n\n // var x = data.readFloatLE(offset);\n // var y = data.readFloatLE(offset + 4);\n // var z = data.readFloatLE(offset + 8);\n\n // trajectory.x = x;\n // trajectory.y = y;\n // trajectory.z = z;\n\n // callback(true, offset);\n return offset;\n\n // num_dev offset=41612 and size=4\n // file_name offset=41624 and size=7\n // time offset=41616 and size=8\n \n\n // console.log(trajectory);\n\n } else { // otherwise, the data gets cut off\n console.log(\"data cut off\");\n // callback(false, offset);\n return offset;\n }\n\n }\n // callback(false, null);\n return false;\n}",
"readStream(){\n redis.consumeFromQueue(config.EVENTS_STREAM_CONSUMER_GROUP_NAME, this.consumerId, 1, config.EVENTS_STREAM_NAME, false, (err, messages) => {\n if (err) {\n this.logger.warn(`Failed to read events. ${err.message}`);\n }\n\n if (messages){\n this.logger.log('Received message from event stream.');\n\n this.processMessages(messages);\n }\n\n setTimeout(()=>{\n this.readStream();\n }, 1000);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Only the keys data contains person > person relationships (supervisor > keyholder) | function findSupervisorEdges (
personCollection,
supervisorPersonEdges,
keysData
) {
return Promise.each(keysData, function (row, i) {
let keyholder = { name: row['FIRST'] + ' ' + row['LAST NAME'] }
if (row['SUPERVISOR'] && row['SUPERVISOR'].trim().length > 0) {
let supervisor = row['SUPERVISOR'].trim()
supervisor = {
name:
supervisor[0] +
supervisor.substring(1, supervisor.length).toLowerCase()
}
return personCollection
.byExample(keyholder)
.then(function (keyholderCursor) {
if (keyholderCursor.count === 0) {
console.log('KEYHOLDER NOT FOUND:', keyholder)
return null
} else if (keyholderCursor.count > 1) {
console.log(
'MULTIPLE PEOPLE FOUND FOR KEYHOLDER: ',
keyholderCursor._result
)
return null
} else {
return personCollection
.byExample(supervisor)
.then(function (supervisorCursor) {
if (supervisorCursor.count === 0) {
console.log('SUPERVISOR NOT FOUND:', supervisor)
return null
} else if (supervisorCursor.count > 1) {
console.log(
'MULTIPLE PEOPLE FOUND FOR SUPERVISOR: ',
supervisorCursor._result
)
return null
} else {
// console.log('LINKED SUPERVISOR', supervisor.name, ' TO PERSON ', keyholder.name);
let edge = {
_from: supervisorCursor._result[0]._id,
_to: keyholderCursor._result[0]._id
}
return supervisorPersonEdges.save(edge)
}
})
}
})
} else return null
})
} | [
"function findKeysDataRoomPersonEdges (\n roomCollection,\n personCollection,\n roomKeyholderEdges,\n keysData\n) {\n return Promise.each(keysData, function (row, i) {\n let room = { name: row['BUILDING'] + ' ' + row['ROOM NUMBER'] }\n let keyholder = { name: row['FIRST'] + ' ' + row['LAST NAME'] }\n return roomCollection.byExample(room).then(function (roomCursor) {\n if (roomCursor.count === 0) {\n // Not finding rooms in the keys dataset is likely okay. The ROOM column may contain\n // some values that aren't strictly room numbers (e.g., master or building keys). These should\n // be the only ones that are caught in this part of the logic.\n // console.log('ROOM NOT FOUND:', room.name);\n return null\n } else if (roomCursor.count > 1) {\n console.log('MULTIPLE ROOMS FOUND: ', roomCursor._result)\n return null\n } else {\n return personCollection\n .byExample(keyholder)\n .then(function (keyholderCursor) {\n if (keyholderCursor.count === 0) {\n console.log('KEYHOLDER NOT FOUND:', keyholder.name)\n return null\n } else if (keyholderCursor.count > 1) {\n console.log(\n 'MULTIPLE PEOPLE FOUND FOR KEYHOLDER: ',\n keyholderCursor._result\n )\n return null\n } else {\n // console.log('LINKED ROOM', room.name, ' TO PERSON ', keyholder.name);\n let edge = {\n _from: roomCursor._result[0]._id,\n _to: keyholderCursor._result[0]._id\n }\n return roomKeyholderEdges.save(edge)\n }\n })\n .then(function () {\n if (row['SUPERVISOR'] && row['SUPERVISOR'].trim().length > 0) {\n let supervisor = row['SUPERVISOR'].trim()\n supervisor = {\n name:\n supervisor[0] +\n supervisor.substring(1, supervisor.length).toLowerCase()\n }\n return personCollection\n .byExample(supervisor)\n .then(function (supervisorCursor) {\n if (supervisorCursor.count === 0) {\n console.log('SUPERVISOR NOT FOUND:', supervisor.name)\n return null\n } else if (supervisorCursor.count > 1) {\n console.log(\n 'MULTIPLE PEOPLE FOUND FOR SUPERVISOR: ',\n supervisorCursor._result\n )\n return null\n } else {\n // console.log('LINKED ROOM', room.name, ' TO PERSON ', supervisor.name);\n let edge = {\n _from: roomCursor._result[0]._id,\n _to: supervisorCursor._result[0]._id\n }\n return roomKeyholderEdges.save(edge)\n }\n })\n }\n })\n }\n })\n })\n}",
"function getKeysDataPeople (keysData) {\n let keysPeople = {}\n return Promise.each(keysData, function (row, i) {\n //Parse out the keyholder as a person\n let keyholder = (row['FIRST'].trim() + ' ' + row['LAST NAME'].trim()).trim()\n keysPeople[keyholder] = keysPeople[keyholder] || {\n name: keyholder,\n keys: [],\n puid: row['PUID'],\n status: row['STATUS'],\n department: row['DEPARTMENT'],\n _type: 'person'\n }\n keysPeople[keyholder].keys.push(row['KEY NUMBER'])\n keysPeople[keyholder].fulltext = createFullText(\n keysPeople[keyholder],\n searchablePeopleAttributes\n )\n\n //Parse out the supervisor as a person\n if (row['SUPERVISOR'] && row['SUPERVISOR'].trim().length > 0) {\n let supervisor = row['SUPERVISOR'].trim()\n let name =\n supervisor[0] + supervisor.substring(1, supervisor.length).toLowerCase()\n keysPeople[name] = {\n name: name,\n _type: 'person'\n }\n keysPeople[name].fulltext = createFullText(\n keysPeople[name],\n searchablePeopleAttributes\n )\n }\n return null\n }).then(() => {\n return keysPeople\n })\n}",
"function getKeys() {\n for (let data of Object.values(person)) {\n console.log(`${data}`);\n }\n}",
"function relationshipKeys(model, update) {\n if (!model) {\n return []\n }\n return Object.keys(model).filter(function(key) {\n return model[key].relationshipType;\n }).filter(function(key) {\n return key in update\n });\n}",
"isKeyField() {\n return 1 === this.length && \"__name__\" === this.get(0);\n }",
"visitSupplemental_id_key_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"getDataSubset(allowed) {\n \n const subsetData = Object.keys(this.data)\n .filter(name => allowed.includes(name))\n .reduce((obj, key) => {\n obj[key] = this.data[key];\n return obj;\n }, {});\n\n return subsetData\n }",
"getAllChildrenAndStaff() {\n var users = JSON.parse(this.getAllUsers()).data;\n var staff = [];\n var children = [];\n\n users.forEach(user => {\n if (['lowStaff', 'upStaff', 'sysOverseer'].includes(user['permission'])) {\n staff.push(user);\n } else {\n children.push(user)\n }\n })\n\n return {\n children: children,\n staff: staff\n };\n }",
"function whoHasKey(tableObj, key){\n for ( var name in tableObj){\n if (key in tableObj[name]){\n return name;\n }\n }\n}",
"function DDLightbarMenu_SelectItemKeysIncludes(pKey)\n{\n\treturn (this.additionalSelectItemKeys.indexOf(pKey) > -1);\n}",
"_add_one_required(keys, parent_keys) {\n this._one_required[parent_keys.join(':')] = keys;\n }",
"_add_required_key(key, parent_keys) {\n this._required.push([...parent_keys, key].join(':'));\n }",
"function customerInfos(data) {\n let infosTarget = [\"firstName\",\"lastName\",\"address\",\"city\",\"email\"];\n for ( let info of infosTarget) {\n for ( let key in data.contact) {\n if ( info == key) {\n createObject(info,\"span\",null,data.contact[key],0);\n }\n }\n }\n}",
"isSubset(dataObjectContainer,dataObject){\n if ( dataObject.children && dataObject.children.length > 0 ){\n if ( dataObjectContainer !== dataObject.children ){\n return Object.keys(dataObject.children).some( key=>{\n this.isSubset (dataObjectContainer,dataObject.children[key])\n })\n }\n }\n return dataObjectContainer === dataObject.children\n }",
"serializeBelongsTo (snapshot, json, relationship) {\n const { options: { serialize } } = relationship;\n\n if (serialize !== false) {\n let key = relationship.key;\n let belongsTo = snapshot.belongsTo (key);\n key = this.keyForRelationship ? this.keyForRelationship (key, \"belongsTo\", \"serialize\") : key;\n\n if (belongsTo === null) {\n json[key] = null;\n }\n else if (!isNone (belongsTo)) {\n json[key] = belongsTo.id;\n }\n }\n }",
"function checkDataExistence(dataObj, prede, obje) {\n var inObj = new Set()\n for (var y of dataObj) {\n if (y.p === prede && y.o === obje) { \n inObj.add(y) \n } \n };\n return inObj;\n }",
"function relationshipLogger(obj) {\n var relationships = obj.relationships\n if ((relationships && relationships.friends.length > 0) || (relationships && relationships.matches.length > 0)) {\n console.log(obj.relationships); \n }\n else{\n console.log(\"You have no relationships :(\");\n }\n\n}",
"denormalizePrimaryKey(data, primaryKey, prop) {\n const platform = this.driver.getPlatform();\n const pk = platform.getSerializedPrimaryKeyField(primaryKey);\n if (Utils_1.Utils.isDefined(data[pk], true) || Utils_1.Utils.isDefined(data[primaryKey], true)) {\n let id = data[pk] || data[primaryKey];\n if (prop.type.toLowerCase() === 'objectid') {\n id = platform.denormalizePrimaryKey(id);\n }\n delete data[pk];\n data[primaryKey] = id;\n }\n }",
"daughters(person) {\n var children = person.sons;\n const daughter = [];\n children.forEach(function (kid) {\n if (kid.gender === 'female') {\n daughter.push(kid);\n }\n }, this);\n\n return daughter;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
NEXT PROBLEM / As of this point you should have a makePerson and a makeCard function which returns you either a person or a credit card object. Now, create a bindCard function that takes in a person object as its first parameter and a creditcard object as its second parameter. Have bindCard merge the two parameters together into a new object which contains all the properties from the person as well as the creditcard. While Object.assign would give you the answer, specRunner requires an answer without using it. | function bindCard(person, creditcard) {
var both = {}
for(var key in person){
both[key] = person[key];
for (var key in creditcard){
both[key] = creditcard[key];
}
}
return both;
} | [
"function bindCard(personObj, creditcardObj) {\n let combinedObj = {};\n combinedObj = Object.assign(combinedObj, personObj, creditcardObj)\n return combinedObj;\n }",
"function makeCard(cardNumber, expirationDate, securityCode) {\n var card = {\n cardNumber: cardNumber,\n expirationDate: expirationDate,\n securityCode: securityCode\n }\n return card;\n }",
"function makePerson (name, birthday, ssn) {\n var newPerson = {name, birthday, ssn}\n return newPerson\n }",
"function createCard(cardnum, CVC, exp, type){\n if (type == \"Amex\"){\n \n card = new Amex(cardnum, CVC, exp);\n \n }\n \n if (type == \"Visa\"){\n card = new Visa(cardnum, CVC, exp);\n }\n \n if (type == \"MC\"){\n card = new MC(cardnum, CVC, exp);\n }\n \n return card;\n}",
"static prepCard(card) {\n card.name = card.name.split('-').join(' ');\n card.reverse = Math.random() > .8 ? true : false;\n }",
"function getCard() {\n\t\n\t// STUB: this code shows a minmal model for a Card object. You job is to build a better one!\n\tvar card = {\n\t\tisFaceUp : true,\n\t\ttoString : function() { \n\t\t\t\t\t\treturn \"2d\"; \n\t\t\t\t\t},\n\t};\n\t\n\treturn card;\t\n}",
"function makePerson(name, birthday, ssn) {\n var out = {\n name: name,\n birthday: birthday,\n ssn: ssn\n }\n return out;\n }",
"function createCard(){\n\t\tinquirer.prompt([\n\t\t\t{\n\t\t\t\ttype: \"list\",\n\t\t\t\tmessage: \"What kind of cards would you like to create?\",\n\t\t\t\tchoices: [\"basic\", \"cloze\"],\n\t\t\t\tname: \"cardChoice\"\n\t\t\t}\n\t\t])\n\t\t.then(function(card_menu){\n\t\t\tswitch(card_menu.cardChoice){\n\t\t\t\tcase \"basic\":\n\t\t\t\t\tconsole.log(\"OK, lets create a Basic card\");\n\t\t\t\t\tcreateBasic();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"cloze\":\n\t\t\t\t\tconsole.log(\"Ok, this will be a cloze call, ha ha ha ha!\")\n\t\t\t\t\tcreateCloze();\n\t\t\t\t\tbreak;\n\t\t\t};\n\n\t\t});\n\t}",
"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}",
"static fromObject(obj) {\n if (Card.isValid(obj)) {\n const caption = obj.caption && typeof obj.caption === 'string' ? obj.caption : '';\n const frontUrl = obj.frontUrl && typeof obj.frontUrl === 'string' ? obj.frontUrl : '';\n const backUrl = obj.backUrl && typeof obj.backUrl === 'string' ? obj.backUrl : '';\n return new Card(obj.name, obj.value, obj.color, caption, frontUrl, backUrl);\n }\n else{\n throw new Error('Invalid card object', obj);\n }\n }",
"function playerAcquireCard(oplayer, card) {\n let pay = {};\n const player = clone(oplayer);\n let short = 0;\n colors.forEach(color => {\n const cost = card[color] - player.bonus[color];\n if(cost > 0) {\n if(player.resources[color] >= cost) {\n player.resources[color] -= cost;\n pay[color] = cost;\n } else {\n short += (cost - player.resources[color]);\n pay[color] = player.resources[color];\n player.resources[color] = 0;\n }\n }\n });\n pay.gold = short;\n player.resources.gold -= short;\n player.score += card.points;\n player.bonus[card.provides] += 1;\n return [ pay, player ];\n}",
"bookFromAuthorData(book, author) {\n if (book.author_id == author.author_id) {\n book.gender = author.gender\n book.nationality = author.nationality\n }\n return book\n }",
"function Create(card) {\n var dfd = $q.defer();\n var token = OrderCloud.Auth.ReadToken();\n var cc = {\n \"buyerID\": OrderCloud.BuyerID.Get(),\n \"orderID\": null,\n \"transactionType\": \"createCreditCard\",\n \"amount\": null,\n \"cardDetails\": {\n \"paymentID\": null,\n \"creditCardID\": null,\n \"cardholderName\": card.CardholderName,\n \"cardType\": card.CardType,\n \"cardNumber\": card.CardNumber,\n \"expirationDate\": card.ExpMonth + card.ExpYear,\n \"cardCode\": card.CVV\n }\n };\n $resource(authorizeneturl, {}, {authorize: {method: 'POST', headers: {'Authorization': 'Bearer ' + token, 'Content-type': 'application/json'}}}).authorize(cc).$promise\n .then(function(response){\n if(response.messages && response.messages.resultCode && response.messages.resultCode == 'Error') {\n toastr.info('Sorry, something went wrong. Please check your card data and try again');\n } else if(response.Error) {\n toastr.info('Sorry, something went wrong. Please try again');\n } else {\n toastr.success('Your card has been created', 'Success');\n }\n dfd.resolve(response);\n })\n .catch(function(){\n toastr.info('Sorry, something went wrong. Please try again');\n dfd.resolve();\n });\n return dfd.promise;\n }",
"function personFromPersonStore(name, age) {\n // add code here\n this.name=name;\n this.age=age;\n this.greet=function () {\n showMsg(`hello`)\n}\n return Object.create(this) \n}",
"function AssignGiftCardToHouse(giftCard){\n return $resource(_URLS.BASE_API + 'homegiftcard' + _URLS.TOKEN_API + $localStorage.token, {\n card_id : giftCard.Id,\n house_id : giftCard.houseId,\n points : giftCard.value,\n child_id : JSON.stringify(giftCard.child_id),\n enable : 1\n }, {\n fetch: 'JSONP',\n 'query': {\n method: 'POST',\n isArray: false\n }\n }).query().$promise;\n }",
"function changePersonToBart(person) {\n //changes the property of firstName to be 'Bart'\n person.firstName = 'Bart'\n\n //changes the property of 'favorite color' to be orange\n person[\"favorite color\"] = \"orange\"\n \n //removes the last item in the hobbies array\n person.hobbies.pop()\n \n //adds a new item to the hobbies array\n person.hobbies.push('Skateboarding')\n \n //returns the object with the updated properties\n return person\n}",
"function fillArrayWithBusinessCards() {\n const card1 = new BusinessCard(\n 'Cedric', 'Coppens', \n 'Front-End\\nDevelopper', \n '09 252 54 84', '0476 68 44 00', \n 'cediric.coppens@codeempire.be', 'www.cedricco.be', \n 1, new Date(1995, 08, 16),\n {\n street: 'Werkhuizenstraat',\n number: 205,\n postalCode: 9050,\n city: 'Gentbrugge',\n geolocation: {\n lat: 51.023248,\n long: 3.764278,\n }\n },\n images[0]\n );\n\n const card2 = new BusinessCard(\n 'Bobina', 'De Bouwer', \n 'Front-End\\nDeveloper',\n '09 272 20 20', '0497 85 64 20', \n 'bobina.debouwer@codeempire.be', 'www.bobinadb.be', \n 2, new Date(1970, 12, 9),\n {\n street: 'Blekte',\n number: 15,\n postalCode: 9340,\n city: 'Oordegem',\n geolocation: {\n lat: 50.965622,\n long: 3.906555,\n }\n },\n images[1]\n );\n\n const card3 = new BusinessCard(\n 'Pat', 'Fenis', \n 'Full-Stack\\nDeveloper',\n '09 252 40 25', '0498 75 24 10', \n 'pat.fenis@codeempire.be', 'www.patfe.be', \n 0, new Date(1985, 2, 12),\n {\n street: 'Geraardsbergsesteenweg',\n number: 135,\n postalCode: 9090,\n city: 'Melle',\n geolocation: {\n lat: 50.984511,\n long: 3.797633,\n }\n },\n images[2]\n );\n\n const card4 = new BusinessCard(\n 'Alberto', 'De Kapper', \n 'Senior\\nDesigner',\n '09 232 42 21', '0455 23 44 31', \n 'alberto.dekapper@codeempire.be', 'www.albertodk.be', \n 9, new Date(1988, 11, 1),\n {\n street: 'Denderstraat',\n number: 22,\n postalCode: 9300,\n city: 'Aalst',\n geolocation: {\n lat: 50.943842,\n long: 4.036269,\n }\n },\n images[3]\n );\n\n const card5 = new BusinessCard(\n 'Didier', 'Vanacker', \n 'CEO\\nCode Empire',\n '09 220 18 58', '0485 45 43 11', \n 'didier.vanacker@codeempire.be', 'www.didierva.be', \n 1, new Date(1965, 4, 25),\n {\n street: 'Oude Brugsepoort',\n number: 25,\n postalCode: 9800,\n city: 'Deinze',\n geolocation: {\n lat: 50.988806,\n long: 3.521667,\n }\n },\n images[4]\n );\n\n const card6 = new BusinessCard(\n 'Karen', 'Klager', \n 'Junior\\nDesigner',\n '09 333 25 00', '0465 75 23 55', \n 'karen.klager@codeempire.be', 'www.karenkl.be', \n 2, new Date(1988, 10, 8),\n {\n street: 'Peperstraat',\n number: 10,\n postalCode: 9800,\n city: 'Deinze',\n geolocation: {\n lat: 50.996636,\n long: 3.547397,\n }\n },\n images[5]\n );\n\n const card7 = new BusinessCard(\n 'Anna', 'Van Kamp', \n 'Front-End\\nDeveloper',\n '09 230 55 11', '0487 82 00 20', \n 'anna.vankamp@codeempire.be', 'www.annavk.be', \n 2, new Date(1990, 10, 15),\n {\n street: 'Raketstraat',\n number: 5,\n postalCode: 9000,\n city: 'Gent',\n geolocation: {\n lat: 51.040376,\n long: 3.711820,\n }\n },\n images[6]\n );\n\n const card8 = new BusinessCard(\n 'Inge', 'De Praet', \n 'Full-Stack\\nDeveloper',\n '09 232 55 55', '0488 23 64 55', \n 'inge.depraet@codeempire.be', 'www.ingedp.be', \n 2, new Date(1965, 6, 12),\n {\n street: 'Muinklaan',\n number: 6,\n postalCode: 9000,\n city: 'Gent',\n geolocation: {\n lat: 51.042921,\n long: 3.729417,\n }\n },\n images[7]\n );\n\n const card9 = new BusinessCard(\n 'Mario', 'Van Achteren', \n 'Back-End\\nDeveloper',\n '09 260 15 75', '0478 85 25 14', \n 'mario.vanachteren@codeempire.be', 'www.mariova.be', \n 1, new Date(1970, 8, 8),\n {\n street: 'Kluizestraat',\n number: 8,\n postalCode: 9860,\n city: 'Oosterzele',\n geolocation: {\n lat: 50.940002,\n long: 3.791565,\n }\n },\n images[8]\n );\n\n businessCards.push(card1, card2, card3, card4, card5, card6, card7, card8, card9);\n}",
"function change(x) {\n var object2 = Object.assign({}, x);//copying the object to new object2\n // Object.freeze(x);\n //object2 = x;\n \n object2.name = \"Manu\"//Change value of new Object;\n \n console.log(object2, x);\n //{ name: 'Manu', age: 2 } { name: 'ananthu', age: 2 }the original object remains the same even though it is abstract data type\n}",
"function createCard() {\n inquirer.prompt(createprompt).then(function(response) {\n if(res.type === 'Cloze') {\n var fc = new flashcard(res.front.trim(), res.back.trim(), true);\n\n if(!fc.valudate()) {\n createCard();\n } else {\n return;\n }\n };\n } else {\n var fc = new flashcard(res.front.trim(), res.back.trim());\n reviewCard(fc);\n }\n});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to open and close the portfolio section slider | function portfolioSlider() {
$('#portfolio .section-title').click(function(e) {
e.preventDefault();
$('#portfolio-section-slider').slideToggle(300);
});
$('.portfolio-link').click(function(e) {
e.preventDefault();
$('#portfolio-section-slider').slideToggle(300);
});
} | [
"function hideSliders() {\r\n $('#about-section-slider, #portfolio-section-slider').hide();\r\n}",
"function exitSlider () {\nmainWrapper.style.display = 'none';\n}",
"function CloseSilder(){\n modelBG.style.display = \"none\";\n modelSlider.style.display = \"none\";\n }",
"function setupPortfolio()\r\n{\r\n setupSliderAndThumbs();\r\n}",
"function slider() {\n if (position) {\n buildSlidePositionHtml(numSlides);\n }\n\n if (navigation) {\n buildSlideNavHtml();\n }\n\n if (autoPlay) {\n play();\n }\n}",
"function footerToggle() {\r\n var slider = document.getElementById('slider');\r\n var fade = document.getElementById('fade-wrapper');\r\n var footerToggle = document.getElementById('footer-toggle');\r\n if (footerToggle.innerHTML === 'Read More (+)') {\r\n footerToggle.innerHTML = 'Read Less (-)';\r\n fade.classList.toggle('footer-toggle-hidden');\r\n } else {\r\n footerToggle.innerHTML = 'Read More (+)';\r\n fade.classList.toggle('footer-toggle-hidden');\r\n }\r\n //Close footer toggle if open on window resize\r\n window.onresize = function() {\r\n footerToggle.innerHTML = 'Read More (+)';\r\n fade.classList.add('footer-toggle-hidden');\r\n document.getElementById('slider').classList.remove('open');\r\n }\r\n slider.classList.toggle('open');\r\n fade.classList.toggle('footer-toggle');\r\n }",
"function hideSlider() {\r\n\tvar mydiv = document.getElementById('day-panel');\r\n\tmydiv.style.display = (mydiv.style.display = 'none');\r\n}",
"function addPortfolio() {\n const jsPortfolio = document.querySelector('.portfolio-add');\n const captionP = [\n 'This page is made using Bootstrap 4, CSS, JS and JQuery. Made illustrations using Adobe Illustrator.',\n 'Made using Foundation 6, CSS, JS and JQuery. Used Google Optize Experiment A/B test before publishing this page.',\n 'Made using Bootstrap, CSS, JS and JQuery. Used Google analytics, SEO best practices.', \n 'Fetch and show data in real time, Type ahead using JS',\n 'Live output of HTML,CSS and JS. Made using jQuery', \n 'Clock made by using JavaScript and Bootstrap', \n 'CSS variables varried using JavaScript', \n 'Local weather data fetched from API using jQuery', \n 'Drum kit plays sounds and CSS animation when keys pressed', \n 'Always looking for certain keys to be pressed in certain order, & then does certain task', \n 'Selecting all checkboxes between two points, using JavaScript', \n 'Random quotes are fetched from API and can be tweeted. Implemented in jQuery', \n 'JavaScript is used to handle click events and response accordingly', \n 'Used JavaScript to draw, change color & font-size in HTML5 Canvas', \n 'Search wikipedia articles from Wikipedia API using jQuery', \n 'Customize HTML5 Video player using JavaScript', \n 'Data Fetched from twitch API using twitch API, Bootstrap used for styling', \n 'Made using Google Maps API, implemented using Python,flask and SQLite etc', \n 'Reaction time game made using jQuery', 'Made follow along Navbar like stripe.com using JavaScript.', \n \"Free Code Camp's first project, an attribute page to Abdul Sattar Edhi\"];\n const html = [];\n for (let i = 0; i < captionH4.length; i++) {\n html.push(`<div class=\"col-md-4 portfolio-item\">\n <a id=\"${i}\" href=\"#modal\" class=portfolio-link data-toggle=modal>\n <div class=portfolio-hover>\n <div class=portfolio-hover-content>\n <i class=\"fa fa-3x fa-plus\"></i>\n </div>\n </div>\n <img class=\"img-responsive\" alt=\"${imgAlt[i]}\" src=\"${imgSrc[i]}\">\n </a>\n <div class=\"portfolio-caption scroll\">\n <h4>${captionH4[i]}</h4>\n <p class=\"text-muted\">${captionP[i]}</div>\n </div>`);\n }\n jsPortfolio.innerHTML = html.join('');\n const links = Array.from(document.querySelectorAll(\".portfolio-link\"));\n links.forEach((link) => link.addEventListener(\"click\", handleLink));\n}",
"handleClick (event) {\n minusSlides(1);\n }",
"async closeSlidingItems() {\r\n const item = this.el.querySelector('ion-item-sliding');\r\n if (item && item.closeOpened) {\r\n return item.closeOpened();\r\n }\r\n return false;\r\n }",
"function w3_close() {\n mySidebar.style.display = \"none\";\n }",
"function projectSliderOne() {\n $('.project-slider-one').slick({\n infinite: true,\n dots: false,\n arrows: false,\n speed: 500,\n slidesToShow: 5,\n slidesToScroll: 1,\n autoplay: true,\n autoplaySpeed: 5000,\n responsive: [\n {\n breakpoint: 1800,\n settings: {\n slidesToShow: 4,\n }\n },\n {\n breakpoint: 1200,\n settings: {\n slidesToShow: 3,\n }\n },\n {\n breakpoint: 992,\n settings: {\n slidesToShow: 2,\n }\n },\n {\n breakpoint: 650,\n settings: {\n slidesToShow: 1,\n }\n },\n ]\n });\n }",
"function projectDisplay() {\n// set variable outside of click function to hold previously clicked project\nvar lastClick;\n $('.project-tile').click(function(e){\n// set variables\n let $target = $(e.currentTarget);\n let $targetId = $target.attr('data-target');\n let $slick = $(`#${$targetId}-slick`);\n let $gifSlide = $target.attr('data-value') || 0;\n// change slide in gif orbit to project that was clicked on\n $('.project-container').slick('slickGoTo', $gifSlide )\n// closes project details if already open, else opens project details\n if (lastClick === $targetId && ($('.project-tile').hasClass('selectedItem'))) {\n $('.project-description').hide();\n $('.project-tile').removeClass('selectedItem');\n } else {\n lastClick = $targetId;\n $('.project-tile').removeClass('selectedItem');\n $target.addClass('selectedItem');\n $('.project-description').hide();\n $(`#${$targetId}-description`).removeClass('hidden').fadeToggle(1000);\n// initializes slick carousel for screenshots in project details\n $slick.slick({\n prevArrow: \"<img class='slick-prev' src='img/left-arrow-icon.png'>\",\n nextArrow: \"<img class='slick-next' src='img/right-arrow-icon.png'>\"\n });\n };\n });\n}",
"function choiceCoaProd() {\n var $coaSlider = $('#productSliderCoa');\n var $coaItem = $('#productSliderCoa .item');\n var $coaLink = $('#productSliderCoa .radioCoa');\n $coaLink.on('click', function (e) {\n e.preventDefault();\n $coaItem.removeClass('active');\n $(this).parent($coaItem).addClass('active');\n }); // hide arrows and :after if child elements <= 4\n\n $coaSlider.each(function (index) {\n var $slidesNum = $(this).find('.slick-slide').length;\n\n if ($slidesNum <= 4) {\n $(this).parent('.form-row-slider').addClass('hide');\n } else {\n $(this).parent('.form-row-slider').removeClass('hide');\n }\n }); // hide prev arrow and show if slider swipe\n\n $coaSlider.find('.slick-prev').hide();\n $coaSlider.on('afterChange', function () {\n $(this).find('.slick-prev').show();\n });\n }",
"function initializeSliders() {\n rowSlider.value = num_rows;\n colSlider.value = num_cols;\n rowOutput.innerText = num_rows;\n colOutput.innerText = num_cols;\n document.getElementById(\"settings-sliders\").style.display = \"none\";\n}",
"function sg_hide_series(){\n\t\t$('#startup-nav-series').hide('slide', {direction: 'left'}, 250).find('.active').removeClass('active'); // slide out of view then remove all active from nav bar\n\t\t$('#sg-series-container').fadeOut(250).removeClass('active').find('.active').removeClass('active'); // and fade out series view then remove all active\n\t}",
"function projectSliderTwo() {\n $('.project-slider-two').slick({\n infinite: true,\n dots: false,\n arrows: true,\n prevArrow: '<button type=\"button\" class=\"slick-arrow slick-prev\"><i class=\"far fa-angle-left\"></i></button>',\n nextArrow: '<button type=\"button\" class=\"slick-arrow slick-next\"><i class=\"far fa-angle-right\"></i></button>',\n speed: 500,\n slidesToShow: 2,\n slidesToScroll: 1,\n autoplay: true,\n autoplaySpeed: 5000,\n responsive: [\n {\n breakpoint: 992,\n settings: {\n slidesToShow: 1,\n }\n },\n {\n breakpoint: 576,\n settings: {\n slidesToShow: 1,\n arrows: false,\n }\n }\n ]\n });\n }",
"function switchSlides() {\n\n pit.cookies.set({\n name: 'cur_slide',\n value: 'presentation~' + window.location.pathname.split('/')[3] + curSlide,\n expires: 21600,\n path: '/'\n });\n\n for (var i = 0; i < slides.length; i++) {\n\n if (i < slidesOrder.indexOf(curSlide)) {\n\n slides[i].classList.remove('presentation__slide--active', 'presentation__slide--after');\n slides[i].classList.add('presentation__slide--before', 'presentation__slide--inactive');\n continue;\n\n }\n if (i > slidesOrder.indexOf(curSlide)) {\n\n slides[i].classList.remove('presentation__slide--active', 'presentation__slide--before');\n slides[i].classList.add('presentation__slide--after', 'presentation__slide--inactive');\n\n }\n\n }\n\n if (slidesOrder.indexOf(curSlide) !== -1) {\n\n slides[slidesOrder.indexOf(curSlide)].classList.remove('presentation__slide--after', 'presentation__slide--before', 'presentation__slide--inactive');\n slides[slidesOrder.indexOf(curSlide)].classList.add('presentation__slide--active');\n progressBar.style.width = parseInt(slidesOrder.indexOf(curSlide)/(slides.length-1) * 100) + '%';\n\n }\n\n if (slidesOrder.indexOf(curSlide) === 0) {\n\n prevSlideBtn.classList.add('hide');\n\n } else {\n\n prevSlideBtn.classList.remove('hide');\n\n }\n\n if (slidesOrder.indexOf(curSlide) === slides.length - 1) {\n\n nextSlideBtn.classList.add('hide');\n\n } else {\n\n nextSlideBtn.classList.remove('hide');\n\n }\n\n }",
"function SlideshowToggle(){\r\n if( G.VOM.playSlideshow ) {\r\n window.clearTimeout(G.VOM.playSlideshowTimerID);\r\n G.VOM.playSlideshow=false;\r\n G.VOM.$viewer.find('.playPauseButton').html(G.O.icons.viewerPlay);\r\n }\r\n else {\r\n G.VOM.playSlideshow=true;\r\n DisplayNextImage();\r\n G.VOM.$viewer.find('.playPauseButton').html(G.O.icons.viewerPause);\r\n }\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A function that displays the information on nodes | function display_nodes_info( node )
{
while( node != null )
{
console.log( "Data : ",node.data )
node = node.next
}
} | [
"printNodes() {\n for (let layer = 0; layer < this.nodes.length; layer++) {\n for (let node = 0; node < this.nodes[layer].length; node++) {\n document.writeln(this.nodes[layer][node].number + \" | \");\n }\n document.writeln(\"</br>\");\n }\n document.writeln(\n \"----------------------------------------------------------------</br>\"\n );\n }",
"function showNodeData(d) {\n var object ={};\n object.name = d.name.toString(); // transform to string or it will show and array\n object.type = d.type;\n object.solvers = d.solvers;\n object.status = d.status;\n\n var ppTable = prettyPrint(object);\n document.getElementById('d6_1').innerHTML = \"Node\".bold();\n var item = document.getElementById('d6_2');\n\n if(item.childNodes[0]){\n item.replaceChild(ppTable, item.childNodes[0]); //Replace existing table\n }\n else{\n item.appendChild(ppTable);\n }\n\n}",
"print() {\n for (let layer = 0; layer < this.nodes.length; layer++) {\n for (let node = 0; node < this.nodes[layer].length; node++)\n this.nodes[layer][node].print();\n }\n }",
"function ShowInfo() {\n\t\tconsole.log('article: ', article);\n\t\t// console.log(articleText);\n\t}",
"function showInfo(element) {\n elName.textContent = element.number + ' ' + element.name;\n elName.href = element.source;\n\n elSummary.textContent = element.summary;\n elDiscoveredBy.textContent = u(element.discovered_by);\n elNameGivenBy.textContent = u(element.named_by);\n elAtomicMass.textContent = u(element.atomic_mass) + ' u';\n elDensity.textContent = u(element.density) + ' g/L';\n\n // Replace null by \"Unknown\"\n function u(s) {\n return s ? s : 'Unknown';\n }\n}",
"function display_All()\n{\n\t\t\ti = 0;\n\t\t\twhile (i < trueNodeids.length) {\n\t\t\t\tconsole.log(trueNodeids[i].id);\n\t\t\t\ti++;\n\t\t\t}\n}",
"function printNode(ID) {\n var childArray = new Array(); // store all children of node with ID into childArray[]\n var thisNode; // \"this\"\n for (i=0; i< nodes.length;i++){ // finding all children whose parentID == ID\n if (nodes[i][5] == ID){\n childArray.push(nodes[i]);\n //console.log(ID);\n }\n else if (nodes[i][0] == ID){\n thisNode = nodes[i];\n }\n }\n var numChildren = childArray.length;\n console.log(\"Number of children: \" + numChildren);\n\n var url = \"/story/\" + ID; // this is the url that will link to the edit's unique webpage\n \n // printing the icon and associated up/down votes\n p.image(\"/static/img/icons/doc3.png\", x-(img/2), y-(img/2), img, img)\n .hover(\n function(){\n this.attr({src: \"/static/img/icons/doc3_hovered.png\"});\n },\n function(){\n this.attr({src: \"/static/img/icons/doc3.png\"});\n })\n .attr({cursor: \"pointer\", href: url});\n \n var upVote = thisNode[6];\n var downVote = thisNode[7];\n p.text(x-(img/2.5), y+(img/2.5), upVote).attr({\"font-size\": 30, \"font-weight\": \"bold\", fill: \"#02820B\"});\n p.text(x+(img/2.5), y+(img/2.5), downVote).attr({\"font-size\": 30, \"font-weight\": \"bold\", fill: \"#B71306\"});\n console.log(\"Printed icon\"); // finish printing icon\n \n // if thisNode only has one child, draw a straight line downward to the child node\n if (numChildren == 1){\n y += 100;\n console.log(\"X: \" + x);\n console.log(\"Y: \" + y);\n path += \" L \" + x + \" \" + y;\n //path += \" l 0 200\";\n \n printNode(childArray[0][0]);\n y -= 100;\n console.log(\"X: \" + x);\n console.log(\"Y: \" + y);\n path += \" M \" + x + \" \" + y;\n }\n\n // if thisNode has multiple children, draw lines at 45-degrees in both directions downward, and if numChildren > 2, spaced equally inward from these outer lines\n else if (numChildren > 1){\n for (i=0; i < numChildren;i++){\n var newI = i;\n var newNum = numChildren;\n var angle = (((newI / (newNum-1))*200)-100);\n x += angle;\n y += 100;\n path += \" L \" + x + \" \" + y;\n console.log(\"X: \" + x);\n console.log(\"Y: \" + y);\n console.log(childArray);\n \n printNode(childArray[i][0]);\n x -= angle;\n y -= 100;\n path += \" M \" + x + \" \" + y;\n console.log(\"X: \" + x);\n console.log(\"Y: \" + y);\n i = newI;\n }\n }\n \n else if (numChildren == 0){\n console.log(\"No children\");\n return;\n }\n console.log(\"Number of children: \" + numChildren);\n }",
"printGraph() {\r\n console.log(\"Graph: \");\r\n console.log('nodeList ', this.nodeList);\r\n console.log('edgeList ', this.edgeList);\r\n console.log('graph_algo ', this.graph_algo);\r\n console.log('Current startNode is ', this.currentStartNode);\r\n console.log('Current endNode is ', this.currentEndNode);\r\n }",
"function showGraph() {\n for(var i = 0; i < this.vertices; i++) {\n putstr(i + \" -> \");\n for( var j =0; j < this.vertices; j++) {\n if (this.adj[i][j] != undefined)\n putstr(this.adj[i][j] + ' ');\n }\n print();\n }\n}",
"showInfo() {\n let sp = 25; // Spacing\n push();\n // Vertical offset to center text with the image\n translate(this.x * 2, this.y - 50);\n textAlign(LEFT);\n textSize(20);\n textStyle(BOLD);\n text(movies[this.id].title, 0, 0);\n textStyle(NORMAL);\n text(\"Directed by \" + movies[this.id].director, 0, 0 + sp);\n text(\"Written by \" + movies[this.id].writer, 0, 0 + sp * 2);\n text(\"Year: \" + movies[this.id].year, 0, 0 + sp * 3);\n text(\"Running time: \" + movies[this.id].time + \" min\", 0, 0 + sp * 4);\n // Index of the movie / total movies in the dataset\n text(\"(\" + (this.id + 1) + \"/\" + nMovies + \")\", 0, 0 + sp * 5);\n pop();\n }",
"function nr_basicRenderNode(node,divid,titleid)\n{\n\tvar div = $('#'+divid);\n\tdiv.empty();\n\tvar title = $('#'+titleid);\n\tvar ttext = su_getNodeShortLabel(node);\n\ttitle.text(ttext);\n\tdocument.title=ttext;\n\n\t// loop over properties\n\tparr = su_getNodePropertyAndDisplayNames(node.type,node);\n\tvar len = parr.length;\n\tvar prop = null;\n\tvar disp = null;\n\tvar val = null;\n\tvar row = null;\n\tvar lc = null;\n\tvar rc = null;\n\tfor(var i=0; i<len; i++)\n\t{\n\t\tprop = parr[i][0];\n\t\tdisp = parr[i][1];\n\t\tval = node[prop];\n\t\tif(isEmpty(val)) val = node[prop.toLowerCase()];\n\t\tif(isEmpty(val)) continue;\n\t\t\n\t\trow = $('<div class=\"w3-row\"></div>');\n\t\tlc = $('<div class=\"w3-col s1 w3-theme-d3 w3-center\"><p>'+disp+'</p></div>');\n\t\trc = $('<div class=\"w3-col s5 w3-theme-l3\"><p> '+val+'</p></div>');\n\t\trow.append(lc);\n\t\trow.append(rc);\n\t\tdiv.append(row);\n\t}\n} // end nr_basicRenderNode",
"function showLevels() {\n nodes.forEach(node => {\n node.color = Colorlvl[node.lvl - 1];\n });\n recharge();\n}",
"printConsole() {\n for (let layer = 0; layer < this.nodes.length; layer++) {\n for (let node = 0; node < this.nodes[layer].length; node++)\n this.nodes[layer][node].printConsole();\n }\n }",
"function showAttrs(node, opt) {\n\t\tvar i;\n\t\tvar out = \"<table class='ms-vb' width='100%'>\";\n\t\tfor (i=0; i < node.attributes.length; i++) {\n\t\t\tout += \"<tr><td width='10px' style='font-weight:bold;'>\" + i + \"</td><td width='100px'>\" +\n\t\t\t\tnode.attributes.item(i).nodeName + \"</td><td>\" + checkLink(node.attributes.item(i).nodeValue) + \"</td></tr>\";\n\t\t}\n\t\tout += \"</table>\";\n\t\treturn out;\n\t} // End of function showAttrs",
"function displayInfoElement()\n{\n\t//info element\n\tvar IEsquare = new createjs.Shape();\n\tIEsquare.graphics.beginStroke(\"Black\").drawRect(0, 0, 350, 46);\n\tIEsquare.x = 325;\n\tIEsquare.y = 0;\n\tIEsquare.name = \"IEsquare\";\n\tstage.addChild(IEsquare);\n\tupdateInfoText();\n}",
"function showNode(node, color) {\r\n if (color) { \r\n setColor(node, color);\r\n }\r\n resetNode(node, 0);\r\n }",
"display() {\n console.log(`Title: ${this.title}\\nAuthor: ${this.author}\\nPrice: ${this.price}`);\n }",
"function nodeTextActive(){\r\n for (var i = 0;i<visTree.orderedNodes.length;i++) {\r\n if (mouseX > visTree.orderedNodes[i].boxLeft && mouseX < visTree.orderedNodes[i].boxRight) {\r\n if (mouseY > visTree.orderedNodes[i].boxTop && mouseY < visTree.orderedNodes[i].boxBottom) {\r\n //sets flag for expanded view\r\n nodeText(visTree.orderedNodes[i],1);\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n}",
"function showFamilyTree(familyTree) {\n if (familyTree) {\n var chartConfig = {\n container: '#familyTreeChart',\n scrollbar: 'fancy',\n connectors: {type: 'step'},\n animateOnInit: true,\n animation: {nodeAnimation: 'easeOutBounce', nodeSpeed: 700, connectorsAnimation: 'bounce', connectorSpeed: 700},\n node: {HTMLclass: 'chartNode'}\n };\n var chartData = [chartConfig];\n var nodes = {};\n familyTree.forEach(function(member, index, family) {\n var memberID = member.member_id;\n var parentID = (member.parent_id) ? member.parent_id : member.spouse_id;\n var parent = nodes[parentID];\n var location = (member.location) ? member.location : '';\n var orientation = (!member.parent_id && parent) ? 'EAST' : null; // Add horizontal orientation for the second node in a spouse relation\n var link = {id: memberID, href: '#'};\n var node = {\n text: {name: member.name, title: location},\n orientation: orientation,\n link: link\n };\n if (parent) {\n node['parent'] = parent;\n }\n if (member['fb_id']) {\n node['image'] = 'http://graph.facebook.com/' + member['fb_id'] + '/picture';\n }\n //console.log('node: ' + JSON.stringify(node));\n nodes[member.member_id] = node;\n chartData.push(node);\n });\n var tree = new Treant(chartData);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visit a parse tree produced by PlSqlParserautogenerated_sequence_definition. | visitAutogenerated_sequence_definition(ctx) {
return this.visitChildren(ctx);
} | [
"visitCreate_sequence(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitAlter_sequence(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitSeq_of_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"_generate(ast) {}",
"visitSequence_spec(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitDrop_sequence(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitSequence_start_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitSequence_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function ExprSeqSav(eO, exprBodyArr) {\r\n\r\n this.mySeq = (eO) ? eO.mySeq : -1;\r\n\r\n // STEP 1:\r\n //\r\n // Go thru sub expresssions of eO and add them\r\n // \r\n this.exprArrSeq = null;\r\n //\r\n if (eO && eO.exprArr) { // this node is not a leaf\r\n\r\n this.exprArrSeq = new Array();\r\n //\r\n for (var i = 0; i < eO.exprArr.length; i++) {\r\n\r\n assert((eO.exprArr[i].mySeq > 0), \"invalid expr seq for save\");\r\n\r\n this.exprArrSeq.push(new ExprSeqSav(eO.exprArr[i],\r\n exprBodyArr));\r\n }\r\n }\r\n\r\n\r\n // STEP 2:\r\n //\r\n // Enter the 'body' (everything except seq #s), into the global array\r\n // exprBodyArr (if it is not already entered) \r\n //\r\n if (eO && !exprBodyArr[eO.mySeq]) {\r\n exprBodyArr[eO.mySeq] = new ExprBodySav(eO, exprBodyArr);\r\n }\r\n}",
"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}",
"mergeSequences () {\n let lastListElement;\n this.sequence.forEach((e, i) => {\n if (lastListElement && e.locationID === lastListElement.locationID && e.firstStart > lastListElement.lastEnd) {\n e.pushEvent(lastListElement.sequence);\n delete this.sequence[this.sequence.indexOf(lastListElement)];\n } else if(lastListElement && e.locationID === lastListElement.locationID) {\n lastListElement.createAlternativeSequence(e.sequence);\n delete this.sequence[this.sequence.indexOf(e)];\n e = lastListElement;\n }\n lastListElement = e;\n });\n this.updateTravelTime();\n }",
"function Seq(/* exp1, exp2, ... */) {\n precondition_arg_list(arguments);\n return new OEN_Seq(arguments);\n}",
"visitData_manipulation_language_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitRegular_id(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 increaseSequence(root,bias){\n if(root.hasOwnProperty('children')) {\n increaseSequence(root.children[0],bias);\n increaseSequence(root.children[1],bias);\n }\n else{\n root.sequence+=bias;\n }\n }",
"visitSeq_of_declare_specs(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitId_expression(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function animateInsertNode(parentID) {\n\n\n\t//Animating root insertion\n\t//Insertion CASE 1\n\tvar inputValue = document.getElementById(\"inNum\").value;\n\tif (!parentID) {\n\t\ttempData = {\n\t\t\t\"id\": \"n1\",\n\t\t\t\"value\": inputValue,\n\t\t\t\"color\": \"black\",\n\t\t\t\"children\": []\n\t\t};\n\t\tglobj.root = tempData;\n\t\tupdate(globj.root);\n\t}\n\t//Animating a node insertion \n\telse {\n\n\t\t//Adding a new node in the data \n\t\td3.select(\"#\" + parentID)\n\t\t\t.property(\"children\", function(d) {\n\t\t\t\tvar child = null;\n\t\t\t\tif (!d.children) {\n\t\t\t\t\t//Time to do the rotations\n\t\t\t\t\tchild = {\n\t\t\t\t\t\t\"id\": \"n\" + String(++globj.id),\n\t\t\t\t\t\t\"value\": inputValue,\n\t\t\t\t\t\t\"color\": \"red\",\n\t\t\t\t\t\t\"children\": []\n\t\t\t\t\t}\n\t\t\t\t\td.children = [child];\n\n\t\t\t\t} else {\n\t\t\t\t\t//Time to do the rotation\n\t\t\t\t\tchild = {\n\t\t\t\t\t\t\"id\": \"n\" + String(++globj.id),\n\t\t\t\t\t\t\"value\": inputValue,\n\t\t\t\t\t\t\"color\": \"red\",\n\t\t\t\t\t\t\"children\": []\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\td.children.push(child);\n\t\t\t\t}\n\t\t\t\tconsole.log(\"Inserting child with id:\" + globj.id);\n\t\t\t\tupdate(globj.root);\n\t\t\t\tinsert_case1(d3.select(\"#\" + child.id).datum(), d);\n\t\t\t});\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Whether this content has any settings. | get hasSettings() {
return !!this.settings.findSetting(() => true);
} | [
"inDOM() {\n\t\t\treturn $(Utils.storyElement).find(this.dom).length > 0;\n\t\t}",
"any() {\n return Object.keys(this.datos).length > 0;\n }",
"hasLoadedAnyDataFiles() {\n return this.loadedDataFiles.length > 0;\n }",
"isEmpty() {\n return (this.queue.length == 0);\n }",
"get isSetup() {\n return this.system.hasInstance(this);\n }",
"function checkSettings() {\n\tconsole.log('--checking for db settings...');\n\tlet settings;\n\ttry {\n\t\tsettings = db.getData('/settings');\n\t} catch (err) {\n\t\tsettings = {\n\t\t\twhiteList: [],\n\t\t\tlandingBg: {\n\t\t\t\tenable: false,\n\t\t\t\turl: ''\n\t\t\t},\n\t\t\tautoCrop: true\n\t\t};\n\t\tdb.push('/settings', settings);\n\t}\n}",
"function isDisplayClear()\n{\n if ($siteDisplay.innerHTML === '')\n return true;\n\n else\n return false;\n}",
"function isEmpty () {\n return _navigationStack.length === 0;\n }",
"isEnabled() {\n //Override.\n return $gameMessage.currentWindow === this.SETTINGS.UNIQUE_ID;\n }",
"async exists() {\n return $(this.rootElement).isExisting();\n }",
"hasWatchers() {\n return this.watchers.length > 0;\n }",
"isSet() {\n return this._isSet === true;\n }",
"isEmpty() {\n // the heap has a mark in the top of heap\n return this.size === 1;\n }",
"function checkContents() {\n\n var content = document.getElementById(\"content\");\n\n if (typeof(content) !== 'undefined' && content !== null) {\n return checkContent = true;\n }\n else {\n return checkContent = false;\n }\n}",
"isInDOM() {\n return document.querySelector(\"#iovon-hybrid-modal\") !== null;\n }",
"needsAnyAttention() {\n if (this.json_.hasOwnProperty(\"attention_set\")) {\n return Object.keys(this.json_.attention_set).length > 0;\n }\n return false\n }",
"function isEnabled() {\n return tray != undefined;\n}",
"inSafeMode() {\n return this.getLoadSettings().safeMode;\n }",
"isEmpty() {\n return queue.length === 0;\n }",
"function ServerBehavior_getIsEmpty()\n{\n if ( (this.parameters && this.parameters.length > 0)\n || (this.applyParameters && this.applyParameters.length > 0)\n )\n {\n return false;\n }\n else\n {\n return true;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
post username and passwword to api to signin | function signin(){
var payload = {
"username": username.value,
"password": password.value
};
send_post_request(window.location.origin + '/api/rest-auth/login/', payload, function (data, status){
if (status == 200 || status == 201){
signin_message.innerHTML = "Welcome, " + username.value + "!";
// Store token in browser
sessionStorage.setItem("token", data["key"]);
sessionStorage.setItem("username", username.value);
// go home
location.href = window.location.origin
}else{
signin_message.innerHTML = "Sign in Failed!";
}
}, use_token=false)
} | [
"login(username, password) {\r\n return this._call(\"post\", \"login\", { username, password });\r\n }",
"login (email, password) {\n assert.equal(typeof email, 'string', 'email must be string')\n assert.equal(typeof password, 'string', 'password must be string')\n const ctx = this\n return this._apiRequest('/user/login', 'POST', { email, password })\n .then(res => {\n ctx.api_access_key = res.api_access_key\n return res\n })\n }",
"function addUser() {\n const username = document.getElementById('usernameUserSection').value;\n const password = document.getElementById('password').value;\n\n const dataToSend = JSON.stringify({username: username, password: password});\n const url = `${URL_BASE}/add/user`;\n const request = new XMLHttpRequest();\n request.open('POST', url);\n request.send(dataToSend);\n}",
"function requestSignup (username, name, email, password) {\n\tvar xhttp = new XMLHttpRequest();\n\txhttp.onreadystatechange = function() {\n\t\tif (xhttp.readyState == 4 && xhttp.status == 200){\n\t\t\talert(xhttp.responseText);\n\t\t\twindow.open(\"login.html\", \"_self\");\n\t\t}\n\t};\n\ttry{\n\t\txhttp.open(\"GET\", \"/signup/\" + username + \"/\" + name + \"/\" + email + \"/\" + password, true);\n\t\txhttp.send(null);\n\t}\n\tcatch(e){\n\t\talert(e);\n\t}\n}",
"auth({ username, password, refreshToken }) {\n let authBody = authData;\n if (typeof refreshToken !== 'undefined') {\n // 使用 refreshToken 刷新令牌\n authBody.grant_type = 'refresh_token';\n authBody.refresh_token = refreshToken;\n } else if (typeof username !== 'undefined' &&\n typeof password !== 'undefined') {\n // 使用账号密码刷新令牌\n authBody.grant_type = 'password';\n authBody.username = username;\n authBody.password = password;\n } else {\n // 无效输入\n return Promise.reject(new Error('wrong params input'));\n }\n\n return this._post({\n url: 'https://oauth.secure.pixiv.net/auth/token',\n body: authBody\n }).then(body => {\n this.accessToken = 'Bearer ' + body.response.access_token;\n this.refreshToken = body.response.refresh_token;\n this.isLogin = true;\n\n return body.response;\n });\n }",
"login(params, callback){\n request(genRequestOptions({\n 'url' : 'https://apps.mypurecloud.com/api/v2/login',\n 'method' : 'POST',\n 'token' : null,\n 'data' : params\n }), function(error, response, body){\n if(error || response.statusCode !== 200){\n if(response.statusCode === 401)\n callback({'status' : 403, 'error' : body});\n else\n callback({'status' : response.statusCode, 'error' : body});\n }\n else{\n callback(null, body);\n }\n });\n }",
"function createaccount(createaccount_token) {\n var params_1 = {\n action: \"createaccount\",\n username: \"your_username\",\n password: \"your_password\",\n retype: \"retype_your_password\",\n createreturnurl: wikiUrl,\n createtoken: createaccount_token,\n format: \"json\"\n };\n\n request.post({ url: endPoint, form: params_1 }, function (error, res, body) {\n if (error) {\n return;\n }\n console.log(body);\n });\n}",
"function doLogin(username, password){\n\thideOrShow(\"register\", false);\n\n\tif(!username || !password)\n\t{\n\t\tusername = document.getElementById(\"loginName\").value.toLowerCase(); //Assign from user field.\n\t\tpassword = document.getElementById(\"loginPassword\").value; //Assign from pass field.\n\t}\n\n\tUSERNAME = username;\n\t//Create JSON body.\n\tlet body = {\n\t\t\"username\": username,\n\t\t\"password\": password\n\t}\n\n\t$.post(urlBase + \"api/login\", body)\n\t\t.done(function(data) {\n\t\t\tif(data.success === false){\n\t\t\t\talert(\"Could not login: \\n\" + data.message );\n\t\t\t}\n\t\t\telse{\n\t\t\t\tconsole.log(data);\n\t\t\t\tif(data.token)\n\t\t\t\t\tdocument.cookie = \"USER=\" + data.token;\n\t\t\t\t\tdocument.cookie = \"USERNAME=\" + username;\n\t\t\t\t\tdocument.cookie = \"PASSWORD=\" + password;\n\t\t\t\thideOrShow(\"Front Page\", false);\n\t\t\t\thideOrShow(\"contactPage\", true);\n\t\t\t\tgetContacts();\n\t\t\t}\n\n\t\t})\n\t\t.fail(function(err) {\n\t\t\tconsole.log(err);\n\t\t\talert(\"Failed to login\");\n\t\t})\n}",
"register (credentials){\n return Api().post('register', credentials)\n }",
"function loginUser(username, password) {\n $.post('/api/login', {\n username: username,\n password: password,\n })\n .then(function () {\n // code to redirect to the index page\n window.location.replace('/');\n })\n .catch(function (err) {\n console.log(err);\n });\n }",
"static sign_in(callback = null) {\n // Hide the inputs\n window.UI.hide(\"authenticate-inputs\");\n // Change the output message\n this.output(\"Hold on - Signing you in...\");\n // Send the API call\n window.API.send(\"authenticate\", \"signin\", {\n name: window.UI.find(\"authenticate-name\").value,\n password: window.UI.find(\"authenticate-password\").value\n }, (success, result) => {\n if (success) {\n // Push the session cookie\n window.PathStorage.setItem(\"token\", result);\n // Call the authentication function\n this.authentication(callback);\n } else {\n // Show the inputs\n window.UI.show(\"authenticate-inputs\");\n // Change the output message\n this.output(result, true);\n }\n });\n }",
"async function login({ commit }, userData) {\n\t// one day ill implement snackbars with the auth state or use it in a component or footer\n\tcommit('auth_request')\n let response = await restApi\n\t\t.post('login', {\n\t\t\tusername: userData.username,\n\t\t\tpassword: userData.password,\n\t\t})\n\t\t.then((response) => {\n\t\t\t// we use the data we get back in the response object after the promise succeeds\n\t\t\t//you can change the data object props to match whatever your sever sends\n\t\t\tconst token = response.data.token\n\t\t\tconst user = response.data.username\n\t\t\t// storing jwt in localStorage. https cookie is safer place to store\n\t\t\tls.set('tokenKey', { token: token }) // using secure-ls to encrypt local storage\n\t\t\tls.set('userKey', { user: user })\n\t\t\taxios.defaults.headers.common['Authorization'] = 'Bearer ' + token\n\t\t\t// calling the mutation \"auth_success\" to change/update state.properties to the new values passed along in the second param\n\t\t\tcommit('auth_success', { token, user })\n\t\t})\n\t\t.catch((err) => {\n\t\t\tconsole.log('login error' + err)\n\t\t\tcommit('auth_error')\n\t\t\tls.remove('token')\n\t\t})\n return response\n}",
"static login() {\n const doc = navigationDocument.documents[navigationDocument.documents.length - 1]\n const e = doc.getElementsByTagName('textField').item(0)\n const user = encodeURIComponent(e.getAttribute('data-username'))\n const pass = encodeURIComponent(e.getFeature('Keyboard').text)\n\n const dataString = `username=${user}&password=${pass}&remember=CHECKED&action=login&submit=Log+in`\n\n $.post('https://archive.org/account/login.php', dataString, (xhr) => {\n // https://developer.apple.com/documentation/tvmljs/xmlhttprequest\n // TVA.alert(TVA.amp(dataString))\n // TVA.alert(xhr.getAllResponseHeaders())\n if (xhr.status !== 200) {\n TVA.user = {}\n TVA.alert(`server responded with non-success status: ${xhr.status}`)\n return\n }\n\n // if (xhr.responseText.indexOf('Your browser does not appear to support cookies'))\n // return TVA.alert('testcookie set/send problem')\n\n // debugger\n // return TVA.alert(TVA.amp(xhr.responseText).replace(/</g, '<').replace(/>/g, '>'))\n TVA.set_user(TVA.last_week)\n })\n }",
"signup(email, password, data) {\n return new Promise((resolve, reject) => {\n const url = `${this.apiBase}/auth/signup`;\n const payload = { email, password, data };\n\n const requestOpts = this._makeFetchOpts('POST', payload);\n fetch(url, requestOpts).then(response => {\n resolve();\n });\n })\n }",
"function signin (req, res, next) {\n\n passport.authenticate('local', function(err, user, info) {\n if (err || !user) {\n res.status(400).send(info);\n } else {\n // Remove sensitive data before login\n user.scrub();\n L.debug(\"\"+JSON.stringify(user));\n req.login(user, function(err) {\n if (err) {\n res.status(400).send(err);\n } else {\n res.status(200).json(user);\n }\n });\n }\n })(req, res, next);\n}",
"authenticateCustom(id, create, username, vars = {}, options = {}) {\n const request = {\n \"id\": id,\n \"vars\": vars\n };\n return this.apiClient.authenticateCustom(this.serverkey, \"\", request, create, username, options).then((apiSession) => {\n return new Session(apiSession.token || \"\", apiSession.refresh_token || \"\", apiSession.created || false);\n });\n }",
"function handle_user_auth(req, startTime, apiName) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\n}",
"static sign_up(callback = null) {\n // Hide the inputs\n window.UI.hide(\"authenticate-inputs\");\n // Change the output message\n this.output(\"Hold on - Signing you up...\");\n // Send the API call\n window.API.send(\"authenticate\", \"signup\", {\n name: window.UI.find(\"authenticate-name\").value,\n password: window.UI.find(\"authenticate-password\").value\n }, (success, result) => {\n if (success) {\n // Call the signin function\n this.sign_in(callback);\n } else {\n // Show the inputs\n window.UI.show(\"authenticate-inputs\");\n // Change the output message\n this.output(result, true);\n }\n });\n }",
"post(data, callback) {\n // Check fro required field(s)\n const phone =\n typeof data.payload.phone === 'string'\n && data.payload.phone.trim().length === 10\n ? data.payload.phone.trim()\n : false;\n\n const password =\n typeof data.payload.password === 'string'\n && data.payload.password.trim().length\n ? data.payload.password.trim()\n : false;\n\n if(phone && password) {\n // Lookup matching user\n _data.read('users', phone, (err, userData) => {\n if(!err && userData) {\n // Hash the sent password\n const hashedPassword = helpers.hash(password);\n if(hashedPassword === userData.hashedPassword) {\n // If valid create a new random token, set expiration 1 hour in the future\n const id = helpers.createRandomString(20);\n const expires = Date.now() + 1000 * 60 * 60;\n const tokenObject = {\n phone,\n id,\n expires\n };\n\n // Store the token\n _data.create('tokens', id, tokenObject, err => {\n if(!err) {\n callback(200, tokenObject);\n }\n else {\n callback(500, { Error: 'Couldn\\'t create new token' });\n }\n })\n }\n else {\n callback(400, { Error: 'Incorrect password' });\n }\n }\n else {\n callback(400, { Error: 'Couldn\\'t find user' });\n }\n })\n }\n else {\n callback(400, { Error: 'Missing required fields' });\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
using promises I first find a user and get their votes array and add the newst vote in after, I update the db entry with new array of votes | function usersUpdate(req, res) {
User.findOne({username: req.body.username}).exec()
.then( user => {
if (!user) return res.status(404).json({ message: 'User not found.'});
updateCandidate(req);
user.votes.push(req.body.votes);
return user;
})
.then(user => {
User.findOneAndUpdate({ username: user.username }, user, { new: true }, (err, user) => {
if (err) return res.status(500).json({ message: 'Something went wrong.'});
if (user.votes.length > 3) return res.status(403).json({ message: 'Number of allowed votes exceeded.'});
return res.status(201).json({ message: 'Thank you for your vote.', user});
});
});
} | [
"function vote() {\n for (party in total_votes_per_party) {\n if (total_votes_per_party[party] > 0) {\n // Calculate the increment for this party\n var increment = Math.round(multiplier * Math.random());\n // Vote and then remove those votes from the counters\n var votes_left = total_votes_per_party[party];\n var votes_to_cast = (votes_left > increment) ? increment : votes_left;\n var inc = {};\n inc['votes.' + party] = votes_to_cast;\n db.votetotals.update({\n constituency: \"uk\"\n }, {\n $inc: inc\n }, {\n upsert: true\n }, {});\n total_votes_per_party[party] = votes_left - votes_to_cast;\n }\n }\n}",
"function updateUserQuestionProgress(user,question,quiz,tags,ok_for_alexa,tallySuccess) {\n\t\t//\tconsole.log(['update progress',user,question,quiz,tags,ok_for_alexa,tallySuccess]);\n\t\t\treturn new Promise(function(resolve,reject) {\n\t\t\t\tinitdb().then(function(db) {\n\t\t\t\t\tdb.collection('userquestionprogress').findOne({$and:[{'user': {$eq:ObjectId(user)}},{question:ObjectId(question)} , {block:{ $not: { $gt: 0 } }}]}).then(function(progress) {\n\t\t\t\t\t\t//console.log(['UPDATE PROGRESS FOUND',progress])\n\t\t\t\t\t\tvar isNew = false;\n\t\t\t\t\t\tif (!progress) {\n\t\t\t\t\t\t\tisNew = true;\n\t\t\t\t\t\t\tprogress = {user:ObjectId(user),question:ObjectId(question)};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprogress.topic=quiz;\n\t\t\t\t\t\tprogress.tags=tags;\n\t\t\t\t\t\tprogress.ok_for_alexa=ok_for_alexa;\n\t\t\t\t\t\tprogress.seenTally = parseInt(progress.seenTally,10) > 0 ? parseInt(progress.seenTally,10) + 1 : 1;\n\t\t\t\t\t\t//console.log(['trySETSEEN',new Date().getTime()/1000])\n\t\t\t\t\t\tprogress.seen = parseInt(new Date().getTime()/1000,10);\n\t\t\t\t\t\t//console.log(['SETSEEN',progress.seen])\n\t\t\t\t\t\tif (tallySuccess) {\n\t\t\t\t\t\t\tprogress.successTally = parseInt(progress.successTally,10) > 0 ? parseInt(progress.successTally,10) + 1 : 1;\n\t\t\t\t\t\t\tprogress.success = progress.seen;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprogress.successRate = (parseInt(progress.successTally,10) > 0 && parseInt(progress.seenTally,10) > 0) ? progress.successTally/progress.seenTally : 0;\n\t\t\t\t\t\tprogress.block=0;\n\t\t\t\t\t // console.log(['update progress NOW',progress]);\n\t\t\t\t\t\tif (isNew) {\n\t\t\t\t\t\t\tdb.collection('userquestionprogress').insertOne(progress).then(function(res) {\n\t\t\t\t\t\t\t//\tconsole.log(['inserted progre00ss',res])\n\t\t\t\t\t\t\t\tupdateUserStats(user,question,tallySuccess).then(function() {\n\t\t\t\t\t\t\t\t\tresolve()\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t}).catch(function(e) {\n\t\t\t\t\t\t\t console.log(['err',e]);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdb.collection('userquestionprogress').updateOne({_id:ObjectId(progress._id)},{$set:progress}).then(function(res) {\n\t\t\t\t\t\t\t//\tconsole.log(['updated progre00ss',res])\n\t\t\t\t\t\t\t\tupdateUserStats(user,question,tallySuccess).then(function() {\n\t\t\t\t\t\t\t\t\tresolve()\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t}).catch(function(e) {\n\t\t\t\t\t\t\t console.log(['err',e]);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} \n\t\t\t\t }).catch(function(e) {\n\t\t\t\t\t console.log(['err',e]);\n\t\t\t\t });\n\t\t\t\t})\n\t\t\t})\n\t\t}",
"function edgeVote(voterId, voteableId, type, vote_points) {\n assert(isValidVoteType(type), \"vote type must be in \" + VOTE_TYPES);\n\n var voteableCollection = getCollectionNameFromId(voteableId);\n var tabulatedData;\n\n // While excecuting below transaction, both 'votes' and voteableCollection are locked to\n // ensure data isolation and consistency:\n // * No-one can modify those collections while transaction is being executed\n // * All database changes will be success or failure together\n db._executeTransaction({\n collections: {\n write: [ 'votes', voteableCollection ]\n },\n\n // If you need 100% durability, change waitForSync to true. The db will wait until transaction data\n // is written to disk before return the result\n waitForSync: false,\n\n action: function () {\n // UPSERT .. mean: If there is no vote _from voterId _to voteableId, create it with INSERT ...\n // Else update vote data with UPDATE ...\n var result = db._query(`\n UPSERT { _from: @voterId, _to: @voteableId }\n INSERT { _from: @voterId, _to: @voteableId, type: @type, count: 1, createdAt: DATE_NOW() }\n UPDATE { type: @type, count: OLD.count + 1, updatedAt: DATE_NOW() } IN votes\n RETURN { isNewVote: IS_NULL(OLD), isSameVote: !!OLD && (OLD.type == NEW.type) }\n `, {\n voterId: voterId,\n voteableId: voteableId,\n type: type\n }).toArray()[0];\n // console.log(result); /* DEBUG */\n\n if (result.isSameVote) {\n\n tabulatedData = db._query(`\n LET voteableObj = DOCUMENT(@voteableId)\n RETURN {\n id: voteableObj._id,\n upVotesCount: voteableObj.upVotesCount,\n downVotesCount: voteableObj.downVotesCount,\n totalVotePoint: voteableObj.totalVotePoint\n }\n `, { voteableId: voteableId }).toArray()[0];\n\n } else { // new-vote or re-vote\n\n var upVotesCountDelta = 0;\n var downVotesCountDelta = 0;\n\n if (result.isNewVote) {\n if (type === 'up') {\n upVotesCountDelta = 1;\n } else { // down vote\n downVotesCountDelta = 1;\n }\n } else { // re-vote\n if (type === 'up') {\n upVotesCountDelta = 1;\n downVotesCountDelta = -1;\n } else { // down vote\n upVotesCountDelta = -1;\n downVotesCountDelta = 1;\n }\n }\n\n // console.log(upVotesCountDelta); /* DEBUG */\n // console.log(downVotesCountDelta); /* DEBUG */\n\n tabulatedData = db._query(`\n LET voteableObj = DOCUMENT(@voteableId)\n\n LET upVotesCount = voteableObj.upVotesCount + @upVotesCountDelta\n LET downVotesCount = voteableObj.downVotesCount + @downVotesCountDelta\n\n UPDATE voteableObj WITH {\n upVotesCount: upVotesCount,\n downVotesCount: downVotesCount,\n totalVotePoint: ${vote_points[UP]}*upVotesCount + ${vote_points[DOWN]}*downVotesCount\n } IN @@voteableCollection\n\n RETURN {\n id: NEW._id,\n upVotesCount: NEW.upVotesCount,\n downVotesCount: NEW.downVotesCount,\n totalVotePoint: NEW.totalVotePoint\n }\n `, {\n voteableId: voteableId,\n upVotesCountDelta: upVotesCountDelta,\n downVotesCountDelta: downVotesCountDelta,\n '@voteableCollection': voteableCollection\n }).toArray()[0];\n }\n } // action\n }); // _executeTransaction\n return tabulatedData;\n}",
"function updateCandidate(req) {\n Candidate.findOne({ name: req.body.votes }, (err, candidate) => {\n candidate.votes++;\n Candidate.findOneAndUpdate({ name: req.body.votes }, candidate, { new: true }, (err, candidate) => {\n if (err) return res.status(500).json({ message: 'Something went wrong.' });\n });\n })\n}",
"async incrementDownvote(reviewId, authenticateduser) {\n const downvoteAdded = await addDownvoter(reviewId, authenticateduser)\n if (downvoteAdded !== null) {\n let upvotes = await getUpvoters(this.props.reviewId)\n let downvotes = await getDownvoters(this.props.reviewId)\n upvotes = upvotes.data.length\n downvotes = downvotes.data.length\n this.setState({upvotes: upvotes})\n this.setState({downvotes: downvotes})\n }\n }",
"function eligibleToVote(fromUserId) {\r\n return new Promise(function(resolve, reject) {\r\n var d = new Date();\r\n var yesterday = d.setDate(d.getDate()-1);\r\n UserVote.find({\r\n fromUser: fromUserId,\r\n voteDate: {$gt: yesterday}\r\n })\r\n .then((userVotes) => {\r\n if (userVotes.length >= MAX_VOTES) {\r\n return reject({msg: 'Sorry Capn\\' you only get ' + MAX_VOTES + ' per day!'});\r\n } else {\r\n return resolve(userVotes);\r\n }\r\n })\r\n .catch((err) => {\r\n return reject({msg: 'Error validating number of daily votes.'});\r\n });\r\n });\r\n}",
"static readByUserId(userId) {\n return new Promise((resolve, reject) => {\n (async () => {\n try {\n const pool = await sql.connect(con);\n const result = await pool.request()\n .input('userId', sql.Int(), userId)\n .query(`\n SELECT u.userId, p.pokName, p.pokAbilities, p.pokHeight, p.pokWeight, p.pokGender, p.pokPokemonId, t.pokTypeId, t.pokTypeName\n FROM pokUser u\n JOIN pokFavoritPokemon f\n ON u.userId = f.FK_userId\n JOIN pokPokemon p\n ON f.FK_pokPokemonId = p.pokPokemonId\n JOIN pokPokemonTypes pt\n ON pt.FK_pokPokemonId = p.pokPokemonId\n JOIN pokType t\n ON t.pokTypeId = pt.FK_pokPokemonId\n WHERE u.userId = @userId\n `)\n\n const pokemons = [];\n let lastPokemonIndex = -1;\n result.recordset.forEach(record => {\n if (pokemons[lastPokemonIndex] && record.pokPokemonId == pokemons[lastPokemonIndex].pokPokemonId) {\n console.log(`Pokemon with id ${record.pokPokemonId} already exists.`);\n const newType = {\n pokTypeId: record.pokTypeId,\n pokTypeName: record.pokTypeName,\n pokTypeDescription: record.pokTypeDescription\n }\n pokemons[lastPokemonIndex].pokTypes.push(newType);\n } else {\n console.log(`Pokemon with id ${record.pokPokemonId} is a new pokemon.`)\n const newPokemon = {\n pokPokemonId: record.pokPokemonId,\n pokName: record.pokName,\n pokHeight: record.pokHeight,\n pokWeight: record.pokWeight,\n pokAbilities: record.pokAbilities,\n pokGender: record.pokGender,\n pokFavorite: record.userId,\n pokTypes: [\n {\n pokTypeId: record.pokTypeId,\n pokTypeName: record.pokTypeName,\n pokTypeDescription: record.pokTypeDescription\n }\n ]\n }\n pokemons.push(newPokemon);\n lastPokemonIndex++;\n }\n });\n const validPokemons = [];\n pokemons.forEach(pokemon => {\n const { error } = Pokemon.validate(pokemon);\n if (error) throw { errorMessage: `Pokemon validation failed.` };\n\n validPokemons.push(new Pokemon(pokemon));\n });\n\n resolve(validPokemons);\n\n } catch (error) {\n reject(error);\n }\n\n sql.close();\n })();\n });\n }",
"addInterestedUser ({ commit, getters }, payload) {\n commit('setLoading', true)\n const user = getters.User\n const newInterestedPost = payload.id\n firebase\n .firestore()\n .collection('users')\n .doc(user.id)\n .update({\n interestedPosts: firebase.firestore.FieldValue.arrayUnion(newInterestedPost)\n })\n .then(() => {\n commit('updatePost', payload)\n commit('addInterestedUser', payload)\n })\n .catch(error => {\n alert(error)\n })\n firebase\n .firestore()\n .collection('posts')\n .doc(newInterestedPost)\n .update({\n interestedUsers: firebase\n .firestore\n .FieldValue\n .arrayUnion(user.id)\n })\n .then(() => {\n commit('setLoading', false)\n })\n .catch(error => {\n alert(error)\n })\n }",
"async updateUserSkills(user, newSkills) {\n try {\n //update or add new skills asynchronously \n await Promise.all(newSkills.map(async (newSkill) => {\n //get the old skill instance\n const skillInstance = user.skills.filter(skill => skill.name == newSkill.name);\n\n //if the user already has the skill, update its rating if necessary\n if (skillInstance.length > 0) {\n if (skillInstance[0].usersSkills.rating != newSkill.rating) {\n await skillInstance[0].usersSkills.update({ rating: newSkill.rating });\n }\n //if the user does not has the skill, associate the user with the new skill\n } else {\n //to-do: put the following code to SkillService: getSkillNameFromId\n //get the skillId from the skill name \n const skill = await this.skillModel.findOne({\n where: { 'name': newSkill.name },\n attributes: [\"id\"]\n });\n\n //throw an error if skill doesn't exist\n if (!skill) {\n let err = new Error(`The skill: ${newSkill.name} does not exist in our database.`);\n err.status = 500;\n throw err;\n };\n\n //associate user with the new skill\n await user.addSkill(skill, { through: { rating: newSkill.rating } });\n }\n }));\n } catch (err) {\n throw err;\n }\n }",
"async function updateVoteSum(params, isRemoval){\n try {\n let postObj = Question;\n\n if(params['post-type'] == 'answer'){\n postObj = Answer;\n }\n\n let vote = await Vote.findById(params['vote-id']);\n let valueToChange = vote.vote;\n if(isRemoval){\n valueToChange = -valueToChange;\n }\n // console.log(\"vote.vote\", vote.vote);\n // console.log(\"valueToChange\", valueToChange);\n\n let updateVoteSumQuery = postObj.findByIdAndUpdate(params['post-id'],\n { \"$inc\": { \"voteSum\": valueToChange } },\n { \"$pull\": { \"votes\": params['vote-id'] } }\n );\n\n let updateVoteSumQueryResult = await updateVoteSumQuery.exec();\n console.log(\"updateVoteSum query result\", updateVoteSumQueryResult);\n } catch (e) {\n console.error(\"Error while updateing vote sum\", e);\n }\n\n }",
"recalcVotes(pollID) {\n var dbPoll = Polls.findOne(pollID);\n\n if (dbPoll) {\n var allOptions = dbPoll.options;\n allOptions.forEach((option) => {\n var votesForOption = dbPoll.votes.filter((vote) => vote.optionID === option._id).length;\n option.numVotes = votesForOption;\n });\n\n Polls.update(dbPoll._id, {$set: {options: allOptions}});\n }\n }",
"function writeResultsToUser() {\n dbRefUsers.child(user).once('value', snap => {\n if (snap.hasChild('results')) {\n if(snap.child('results').hasChild(value)) {\n var totalAmount = snap.child('results').child(value).val().amount;\n var pointQuestion = snap.child('results').child(value).val().points;;\n totalAmount += answeredQuestions;\n pointQuestion += points;\n snap.child('results').child(value).ref.update({\n amount: totalAmount,\n points: pointQuestion\n });\n }\n else {\n createUserResult(user);\n }\n\n } else {\n createUserResult(user);\n }\n });\n}",
"async addGeofenceToChildArray(userId, geofencesName, childsPhoneNumber) {\n childCollection = await children()\n childFound = await childCollection.findOne({childPhoneNumber:childsPhoneNumber}, { projection: { _id: 1 } })\n let childId = childFound._id\n geofenceCollection = await geofences()\n geofenceFound = await geofenceCollection.findOne({geofenceName: geofencesName})\n let geofencesId = geofenceFound._id\n usersCollection = await users()\n \n let geofencingName = geofenceFound.geofenceName\n let geofenceAddress = geofenceFound.formattedAddress\n let foundLat = geofenceFound.lat\n let foundLng = geofenceFound.lng\n let foundRadius = geofenceFound.radius\n \n \n return this.get(userId).then(currentUser => {\n return usersCollection.updateOne(\n { 'children.id': childId },\n {\n $push: {\n 'children.$.registeredGeofences': {\n geofenceId: geofencesId,\n geofenceName: geofencingName,\n formattedAddress: geofenceAddress,\n lat: foundLat, \n lng: foundLng,\n radius: parseInt(foundRadius),\n CreatedAt: new Date()\n }\n }\n }\n );\n });\n }",
"function refundBets(IDArray) {\n\tif (typeof IDArray !== \"object\") {\n\t\tconsole.log(typeof IDArray);\n\t\tIDArray = [IDArray];\n\t}\n\treturn new Promise(resolve => {\n\t\tlet eachID = [];\n\t\tIDArray.forEach(id => {\n\t\t\teachID.push(\n\t\t\t\tnew Promise(resolve => {\n\t\t\t\t\tRace.findOne({ raceID: id }, (err, race) => {\n\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\tthrow Error(err);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlet eachRace = [];\n\t\t\t\t\t\trace.entrants.forEach(entrant => {\n\t\t\t\t\t\t\teachRace.push(\n\t\t\t\t\t\t\t\tnew Promise(resolve => {\n\t\t\t\t\t\t\t\t\tlet eachBet = [];\n\t\t\t\t\t\t\t\t\tentrant.bets.forEach(bet => {\n\t\t\t\t\t\t\t\t\t\teachBet.push(\n\t\t\t\t\t\t\t\t\t\t\tnew Promise((resolve, reject) => {\n\t\t\t\t\t\t\t\t\t\t\t\tUser.findOne(\n\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttwitchUsername:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbet.twitchUsername,\n\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t(err, doc) => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\terr.message =\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"Could not find user in bet payout\";\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tthrow Error(err);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tdoc.betHistory.forEach(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tuserBet => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tuserBet.raceID ===\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trace.raceID &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tuserBet.entrant ===\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tentrant.name\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tuserBet.result = `race cancelled`;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdoc.points +=\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tuserBet.amountBet;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tdoc.markModified(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"betHistory\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tdoc.save(err => {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (err) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tthrow Error(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\terr\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t//return the edited bet as an array for map conversion\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbet.isPaid = true;\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tresolve([\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbet.twitchUsername,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbet,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tresolve(\n\t\t\t\t\t\t\t\t\t\tPromise.all(eachBet).then(newBets => {\n\t\t\t\t\t\t\t\t\t\t\treturn newBets;\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t});\n\t\t\t\t\t\tresolve(\n\t\t\t\t\t\t\tPromise.all(eachRace).then(data => {\n\t\t\t\t\t\t\t\treturn data;\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t);\n\t\t\t\t\t});\n\t\t\t\t})\n\t\t\t);\n\t\t});\n\t\tresolve(\n\t\t\tPromise.all(eachID).then(data => {\n\t\t\t\treturn data;\n\t\t\t})\n\t\t);\n\t});\n}",
"createThought({ params, body }, res) {\n \n // create custom id to pass with thought\n const thoughtId = new Types.ObjectId();\n \n // find the user associated with the thought\n User.findOneAndUpdate(\n { _id: params.userId },\n { $push: { thoughts: thoughtId } },\n { new: true }\n )\n .then(dbUserData => {\n if (!dbUserData){\n res.status(404).json({ message: 'No User found with this id!' });\n return;\n }\n return Thought.create({...body, _id:thoughtId, username:dbUserData.username})\n })\n .then(newThought=> {\n res.json(newThought);\n })\n .catch(err => res.status(400).json(err));\n }",
"upvoteBook(bookId) {\n this.bookId = bookId;\n\n // Check if book is in books.json file\n let booksData = readData(booksFile);\n const bookIndex = findBook(bookId);\n if (bookIndex < 0) return { statusCode: '404', message: 'Book not found' };\n\n // Increment count\n if (booksData.books[bookIndex].upvotes) {\n booksData.books[bookIndex].upvotes += 1;\n } else {\n booksData.books[bookIndex].upvotes = 1;\n }\n booksData = updateData(booksFile, booksData);\n return { statusCode: '201', message: 'Successfully upvoted book' };\n }",
"function addVisitId(db, p_id, v_id, v_date) {\n return new Promise((resolve, reject) => {\n return db.get(p_id)\n .then(function(doc) {\n if (!doc.visit_ids){doc.visit_ids = []} //needed for old record compatability\n patient = new pmodel.Patient(doc)\n patient.visit_ids.push(v_id);\n patient.last_visit = v_date;\n return db.put(patient)\n .then(result => {\n resolve(result);\n })\n .catch(err => {\n console.log(\"error in addVisitID\", err);\n reject(err);\n });\n });\n });\n}",
"function databaseQuery() {\n\n userInitial = firebase.database().ref(\"users/\");\n userInvites = firebase.database().ref(\"users/\" + user.uid + \"/invites\");\n\n var fetchData = function (postRef) {\n postRef.on('child_added', function (data) {\n onlineInt = 1;\n\n var i = findUIDItemInArr(data.key, userArr);\n if(userArr[i] != data.val() && i != -1){\n checkGiftLists(data.val());\n\n //console.log(\"Adding \" + userArr[i].userName + \" to most updated version: \" + data.val().userName);\n userArr[i] = data.val();\n }\n\n if(data.key == user.uid){\n user = data.val();\n console.log(\"User Updated: 1\");\n }\n });\n\n postRef.on('child_changed', function (data) {\n var i = findUIDItemInArr(data.key, userArr);\n if(userArr[i] != data.val() && i != -1){\n checkGiftLists(data.val());\n\n console.log(\"Updating \" + userArr[i].userName + \" to most updated version: \" + data.val().userName);\n userArr[i] = data.val();\n }\n\n if(data.key == user.uid){\n user = data.val();\n console.log(\"User Updated: 2\");\n }\n });\n\n postRef.on('child_removed', function (data) {\n var i = findUIDItemInArr(data.key, userArr);\n if(userArr[i] != data.val() && i != -1){\n console.log(\"Removing \" + userArr[i].userName + \" / \" + data.val().userName);\n userArr.splice(i, 1);\n }\n });\n };\n\n var fetchInvites = function (postRef) {\n postRef.on('child_added', function (data) {\n inviteArr.push(data.val());\n\n inviteNote.style.background = \"#ff3923\";\n });\n\n postRef.on('child_changed', function (data) {\n console.log(inviteArr);\n inviteArr[data.key] = data.val();\n console.log(inviteArr);\n });\n\n postRef.on('child_removed', function (data) {\n console.log(inviteArr);\n inviteArr.splice(data.key, 1);\n console.log(inviteArr);\n\n if (inviteArr.length == 0) {\n console.log(\"Invite List Removed\");\n inviteNote.style.background = \"#008222\";\n }\n });\n };\n\n fetchData(userInitial);\n fetchInvites(userInvites);\n\n listeningFirebaseRefs.push(userInitial);\n listeningFirebaseRefs.push(userInvites);\n }",
"function handleUserVote(id, is_up, update_element) {\n var button_id = (is_up ? \"upvote\" : \"downvote\") + id;\n if ($(\"#\" + button_id).hasClass(\"disabled\")) {\n return;\n }\n var cur_vote = parseInt($(\"#\"+update_element).html());\n database_update(vote_table, \"id = \" + id, is_up ? {upvotes: \"upvotes + 1\"} : {downvotes: \"downvotes + 1\"});\n cur_vote += 1;\n $(\"#\" + update_element).html(String(cur_vote));\n if (is_up) {\n allVotes[id].up = cur_vote;\n } else {\n allVotes[id].down = cur_vote;\n }\n // Force them to reopen the dialog\n $(\"#\" + button_id).addClass(\"disabled\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a TG products array and extracts all the product IDs and returns them in an array | async function _extract_variant_ids (products){
if (products.length == 0 || typeof products === 'undefined' || products === null || !Array.isArray(products)){
throw new VError(`products parameter not usable`);
}
let ids = [];
for (let i = 0; i < products.length; i++){
ids = ids.concat(products[i].variant_ids);
}
return ids;
} | [
"async function _extract_related_product_variant_ids (products, line_item_variants){\n let all_product_variants = [];\n \n for (let i = 0; i < products.length; i++){\n for (let j = 0; j < line_item_variants.length; j++){\n if (products[i].variant_ids.includes(line_item_variants[j])){\n all_product_variants.push(products[i].variant_ids);\n }\n }\n }\n \n return all_product_variants;\n}",
"async function getHighlightedProducts() {\n\ttry {\n\t\tconst { rows } = await client.query(`\n SELECT id FROM products \n WHERE \"isHighlighted\" = true;\n `);\n\n\t\tconst prodIdArray = rows.map((product) => {\n\t\t\tconst [newProductId] = Object.values(product);\n\t\t\treturn newProductId;\n\t\t});\n\n\t\tconst productsArray = await Promise.map(\n\t\t\tprodIdArray,\n\t\t\tasync function (productId) {\n\t\t\t\treturn await getProductById(productId);\n\t\t\t},\n\t\t\t{ concurrency: 25 },\n\t\t);\n\n\t\treturn productsArray;\n\t} catch (error) {\n\t\tthrow error;\n\t}\n}",
"async function _extract_line_item_variant_ids (line_items){\n let line_item_variants = [];\n\n for (let i = 0; i < line_items.length; i++){\n for (let j = 0; j < line_items[i].length; j++){\n line_item_variants.push(line_items[i][j].variant_id);\n }\n }\n \n return line_item_variants;\n}",
"function getIds() {\n\tlet ids = []\n\tlet mdls = document.getElementsByClassName('modal')\n\tlet idPrefix = \"product-modal \"\n\tfor (i = 0; i < mdls.length; i++) {\n\t\tlet id = mdls[i].id\n\t\tid = id.slice(idPrefix.length, id.length)\n\t\tids.push(id)\n\t}\n\treturn ids\n}",
"function loadArray() {\n connection.query(\"SELECT * FROM products\", function (err, res) {\n if (err) throw err;\n res.forEach(element => {\n var newProduct = element.item_id + \" | \" + element.product_name + \" | $\" + element.customer_price;\n productArr.push(newProduct);\n });\n });\n}",
"async function _extract_image_ids (variants){\n if (variants.length == 0 || typeof variants === 'undefined' || variants === null || !Array.isArray(variants)){\n throw new VError(`variants parameter not usable`);\n }\n\n let ids = [];\n\n /*\n * Defaults to plucking the first image. This is fine now but in a future where\n * variants may have multiple images we'll need to do better\n */\n\n for (let i = 0; i < variants.length; i++){\n if (variants[i].image_ids.length > 0){\n ids.push(variants[i].image_ids[0]);\n }\n }\n\n return ids;\n}",
"function getBrandsFromProducts (products) {\n\treturn [...new Set(products.map(product => product.brand))];\n}",
"getObjectIDs() {\n let res = [];\n this.state.selectedCourses.map(function(info) {\n res.push(info._id);\n })\n return res;\n }",
"async function _extract_order_ids (orders){\n if (orders.length == 0 || typeof orders === 'undefined' || orders === null || !Array.isArray(orders)){\n throw new VError(`orders parameter not usable`);\n }\n\n let ids = [];\n\n for (let i = 0; i < orders.length; i++){\n for (let j = 0; j < orders[i].length; j++){\n ids.push({\"order_id\":orders[i][j].id});\n }\n }\n\n return ids;\n}",
"function getProductsSansIndex(array) {\n var finalAnswer = []; //gonna put each product in here\n var result = array.map(function (currentVal, currentIndex) { //map over the array\n var product = array.filter(function (filteredValue, filteredIndex) { //filter out the index\n return filteredIndex !== currentIndex; //get the values where the current place in the map are not equal to the current place in the filter\n })\n .reduce(function (total, currentValue) { //multiply the array values\n return total * currentValue;\n });\n finalAnswer.push(product); //push the final product to the final answer\n });\n return finalAnswer;\n}",
"function getBeerIdAndAmount(single_order_node) {\n var ret = []\n var products = single_order_node.getElementsByClassName(\"single_product\");\n for (var i = 0; i < products.length; i++) {\n const single_product = products[i];\n const beer_id = single_product.getElementsByClassName(\"beer_id\")[0].innerText;\n const amount = single_product.getElementsByClassName(\"c_num\")[0].innerText;\n const temp = {\"id\": beer_id, \"amount\": amount};\n ret.push(temp);\n }\n return ret;\n}",
"function getProducts(order, callback) {\n const date = moment(order.dataValues.createdAt).format('LLLL');\n order.date = date;\n\n const { items } = order.dataValues.cart;\n const productIds = Object.keys(items);\n\n models.Product.findAll({\n attributes: ['id', 'title'],\n where: { id: productIds }\n })\n .then(products => {\n let productsObject = {};\n products.forEach(product => {\n productsObject[product.id] = product.title;\n });\n order.items = generateArray(productsObject, items);\n callback();\n }) // END .then(products => {\n .catch(err => callback(err));\n} // END (order, callback) => {",
"function getArtistIDArray(artist_array) {\n\tvar artist_id_array = []\n\treturn new Promise((resolve, reject) => {\n\t\tfor (var index = 0; index < artist_array.length; ++index) {\n\t\t\tsearchForArtist(artist_array[index]).then(function (data) {\n\t\t\t\tartist_id_array.push(data)\n\t\t\t\tresolve(artist_id_array);\n\t\t\t})\n\t\t}\n\t});\n\treturn artist_id_array;\n}",
"function getAllProductsinCurrentOptiongroups(a, b, c){\n // return a list of bundle product Id's. based on flag provided.\n var res = [];\n _.each(a, function (group) {\n res.push(_.pluck(group[b], c));\n });\n\t\t\tres = _.flatten(res);// Flattens a nested array.\n res = _.filter(res, function(prodId){return !_.isUndefined(prodId)});\n\t\t\treturn res;\n }",
"function getGenre(ids){\n let genresArr = [];\n ids.forEach((e)=>{\n for (let i = 0; i<genresByID.length;i++){\n if (e === genresByID[i].id) {\n genresArr.push(genresByID[i].name)\n }\n }\n })\n return genresArr.join(' - ')\n}",
"function getProductByID(productArray, id) {\r\n return productArray.find(function(product){\r\n return product.id == id;\r\n });\r\n}",
"function getDocIds(items) {\n\t\tvar docIds = [];\n\t\tfor ( var i in items ) {\n\t\t\tdocIds.push(items[i].id);\n\t\t}\n\t\treturn docIds;\t\t\n\t}",
"function productosSeleccionados(){\n var arrayproductos = new Array();\n var cont=0;\n var table = document.getElementById('table_productos');\n checkboxes = document.getElementsByName('sld');\n \n \n for(var i=0 ,r=1, n=checkboxes.length;i<n;i++,r++) {\n if (checkboxes[i].checked) {\n cont = cont + 1;\n var id_prod= table.rows[r].cells[1].innerHTML;\n var item={};\n item.ID_PRO=id_prod;\n arrayproductos.push(item);\n \n }\n }\n // alert(arrayproductos);\n return arrayproductos;\n}",
"function _getUniqueTagids(bids) {\n\t\t\tvar key;\n\t\t\tvar map = {};\n\t\t\tvar Tagids = [];\n\t\t\tbids.forEach(function(bid) {\n\t\t\t\tmap[utils.getBidIdParamater('tagid', bid.params)] = bid;\n\t\t\t});\n\t\t\tfor (key in map) {\n\t\t\t\tif (map.hasOwnProperty(key)) {\n\t\t\t\t\tTagids.push(map[key]);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Tagids;\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
AdminFeedbacks Fetch all Feedbacks | getFeedbacks() {
return this.http.get('feedback');
} | [
"async function getFeedback(where, attributes) {\n const highlights = await FeedbackRepository.findAll({\n where,\n attributes,\n });\n\n return highlights;\n}",
"async getAllLessons() {\n const lessonCollection = await lessons();\n const lessonList = await lessonCollection.find({}).toArray();\n return lessonList;\n }",
"list(req, res) {\n return Chat.findAll({\n where: {\n incidentId: req.params.id\n },\n include: userAttributes\n })\n .then(chat => {\n return res\n .status(200)\n .send({ data: { chats: chat }, status: 'success' });\n })\n .catch(error => {\n errorLogs.catchErrors(error);\n res.status(400).send(error);\n });\n }",
"async getAllBugs() {\n const bugs = await dbContext.Bug.find({}).populate('creator')\n return bugs\n }",
"function getAll() {\n return messages.find();\n}",
"async findAll() {\n return await Tutorial.findAll({\n include: [\"comments\"],\n }).then((tutorials) => {\n return tutorials;\n });\n }",
"list(req, res) {\n return Group \n .findAll({\n include: [{\n model: GroupEvent,\n as: 'groupEvents',\n }],\n })\n .then(groups => res.status(200).send(groups))\n .catch(error => res.status(400).send(error));\n }",
"function fetchQuestions() {\n server.get('dailyQuestions')\n .then((response) => {\n setQuestions(response.data.questions);\n });\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 }",
"set_feedback(value) {\n this.feedback = value;\n return this;\n }",
"ListOfModerators(domain, name, email) {\n let url = `/email/domain/${domain}/mailingList/${name}/moderator?`;\n const queryParams = new query_params_1.default();\n if (email) {\n queryParams.set('email', email);\n }\n return this.client.request('GET', url + queryParams.toString());\n }",
"_updateAnomalyFeedback() {\n debounce(this, this._updateAnomalyFeedbackDebounce, ROOTCAUSE_SESSION_DEBOUNCE_INTERVAL);\n }",
"list(req, res) {\n const userId = req.param('userId');\n\n if(req.token.id !== userId) {\n return res.fail('You don\\'t have permission to do this.');\n }\n\n ApplianceService.fetchAllForUser(userId)\n .then(res.success)\n .catch(res.fail);\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}",
"async getComments() {\n try {\n if (!this.API || !this.issue || this.isLoadingComments)\n return;\n this.isLoadingComments = true;\n const comments = await this.API.getComments({\n accessToken: this.accessToken,\n issueId: this.issue.id,\n query: this.query,\n });\n this.comments = comments;\n if (this.query.page !== comments.page) {\n this.query.page = comments.page;\n }\n if (this.query.perPage !== comments.perPage) {\n this.query.perPage = comments.perPage;\n }\n return comments;\n }\n catch (e) {\n if (e.response && [401, 403].includes(e.response.status) && !this.isLogined) {\n this.isLoginRequired = true;\n }\n else {\n this.$emit('error', e);\n throw e;\n }\n }\n finally {\n this.isLoadingComments = false;\n }\n }",
"static listAllOfMyNews() {\n\t\treturn RestService.get('api/news');\n\t}",
"function allMessages(req, res) {\n Offer.findById(req.params.id) \n .populate('message.user')\n .then(offer => {\n if (!offer) return res.status(404).json({ message: 'Offer Not Found' })\n res.status(200).json(offer.message)\n })\n .catch(err => res.status(500).json(err))\n}",
"findAllEventCanals(req, res){\n Event.getAllEventCanals((err, data) => {\n if (err)\n res.status(500).send({\n message:\n err.message || \"Some error occurred while retrieving event canals.\"\n });\n else res.send(data);\n });\n }",
"function getBeerComments(req, res) {\n commentModel\n .findByBeerId(req.params.beerid)\n .then(function(commentData) {\n res.json(commentData);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Refreshes the channel members text element based on the states of connectionData[profileName].channels[channelName].members and activeWindow. Types: Result is void. | function redrawChannelMembers() {
utilsModule.clearChildren(memberListElem);
var profile = self.activeWindow[0];
var party = self.activeWindow[1];
var show = profile in connectionData && party in connectionData[profile].channels;
if (show) {
var members = connectionData[profile].channels[party].members;
members.sort(function(s, t) { // Safe mutation; case-insensitive ordering
return s.toLowerCase().localeCompare(t.toLowerCase());
});
members.forEach(function(name) {
var li = utilsModule.createElementWithText("li", name);
if (members.length < MAX_CHANNEL_MEMBERS_TO_COLORIZE)
li.style.color = nickColorModule.getNickColor(name);
li.oncontextmenu = menuModule.makeOpener([["Open PM window", function() { self.openPrivateMessagingWindow(name, null); }]]);
memberListElem.appendChild(li);
});
}
memberCountText.data = show ? members.length.toString() : "N/A";
utilsModule.setClasslistItem(memberListHeadingElem, "hide", !show);
} | [
"function updateMemberList() {\n people_list = RTMchannel.getMembers().toString(); // gets list of channel members\n document.getElementById(\"people_list\").innerHTML = \"<u>People</u>: \" + people_list.toString();\n}",
"onUpdatedChannels () {\n //OnX modules\n this._privMsg = new PrivMsg(this.bot)\n this._userNotice = new UserNotice(this.bot)\n this._clearChat = new ClearChat(this.bot)\n this._clearMsg = new ClearMsg(this.bot)\n this._userState = new UserState(this.bot)\n\n setInterval(this.updateBotChannels.bind(this), UPDATE_ALL_CHANNELS_INTERVAL)\n\n Logger.info(\"### Fully setup: \" + this.bot.userId + \" (\" + this.bot.userName + \")\")\n }",
"function update_connected_users() \n{\n $('#users_connected').html(\n hb_subscription.presence.length\n );\n}",
"function redrawWindowList() {\n\t\tutilsModule.clearChildren(windowListElem);\n\t\tself.windowNames.forEach(function(windowName) {\n\t\t\t// windowName has type str, and is of the form (profile+\"\\n\"+party)\n\t\t\tvar parts = windowName.split(\"\\n\");\n\t\t\tvar profile = parts[0];\n\t\t\tvar party = parts[1];\n\t\t\tvar window = windowData[windowName];\n\t\t\t\n\t\t\t// Create the anchor element\n\t\t\tvar a = utilsModule.createElementWithText(\"a\", party != \"\" ? party : profile);\n\t\t\tvar n = window.numNewMessages;\n\t\t\tif (n > 0) {\n\t\t\t\t[\" (\", n.toString(), \")\"].forEach(function(s) {\n\t\t\t\t\ta.appendChild(utilsModule.createElementWithText(\"span\", s));\n\t\t\t\t});\n\t\t\t}\n\t\t\tutilsModule.setClasslistItem(a, \"nickflag\", window.isNickflagged);\n\t\t\ta.onclick = function() {\n\t\t\t\tself.setActiveWindow(windowName);\n\t\t\t\treturn false;\n\t\t\t};\n\t\t\ta.oncontextmenu = function(ev) {\n\t\t\t\tvar menuItems = [];\n\t\t\t\tif (window.isMuted)\n\t\t\t\t\tmenuItems.push([\"Unmute window\", function() { window.isMuted = false; }]);\n\t\t\t\telse {\n\t\t\t\t\tmenuItems.push([\"Mute window\", function() {\n\t\t\t\t\t\tvar win = window;\n\t\t\t\t\t\twin.isMuted = true;\n\t\t\t\t\t\twin.numNewMessages = 0;\n\t\t\t\t\t\twin.isNickflagged = false;\n\t\t\t\t\t\tredrawWindowList();\n\t\t\t\t\t}]);\n\t\t\t\t}\n\t\t\t\tvar closable = !(profile in connectionData) || (party != \"\" && !(party in connectionData[profile].channels));\n\t\t\t\tvar func = function() { networkModule.sendAction([[\"close-window\", profile, party]], null); };\n\t\t\t\tmenuItems.push([\"Close window\", closable ? func : null]);\n\t\t\t\tif (utilsModule.isChannelName(party) && profile in connectionData) {\n\t\t\t\t\tvar mode = party in connectionData[profile].channels;\n\t\t\t\t\tvar func = function() {\n\t\t\t\t\t\tnetworkModule.sendAction([[\"send-line\", profile, (mode ? \"PART \" : \"JOIN \") + party]], null);\n\t\t\t\t\t};\n\t\t\t\t\tmenuItems.push([(mode ? \"Part\" : \"Join\") + \" channel\", func]);\n\t\t\t\t}\n\t\t\t\tmenuModule.openMenu(ev, menuItems);\n\t\t\t};\n\t\t\t\n\t\t\tvar li = document.createElement(\"li\");\n\t\t\tli.appendChild(a);\n\t\t\tif (party == \"\")\n\t\t\t\tutilsModule.setClasslistItem(li, \"profile\", true);\n\t\t\twindowListElem.appendChild(li);\n\t\t});\n\t\trefreshWindowSelection();\n\t\t\n\t\tvar totalNewMsg = 0;\n\t\tfor (var key in windowData)\n\t\t\ttotalNewMsg += windowData[key].numNewMessages;\n\t\tvar activeWin = self.activeWindow\n\t\tif (activeWin != null) {\n\t\t\tvar s = (activeWin[1] != \"\" ? activeWin[1] + \" - \" : \"\") + activeWin[0] + \" - MamIRC\";\n\t\t\tdocument.title = (totalNewMsg > 0 ? \"(\" + totalNewMsg + \") \" : \"\") + s;\n\t\t\tif (optimizeMobile)\n\t\t\t\tdocument.querySelector(\"#main-screen header h1\").firstChild.data = s;\n\t\t}\n\t}",
"function displayParticipants() {\n\t// get category of the theme\n\tcategory = $(\"#partUpdateMessage\").text();\n\t$(\"#partUpdateMessage\").hide();\n\n\tvar participantsHTML = document.getElementById(\"displayCount\");\n\tvar partNum = 0;\n\tvar participantsRef = firebaseRef.ref('challenges/' + data + '/count');\n\tparticipantsRef.on('value', function(snapshot) {\n\t\tpartNum = snapshot.val();\n\t\tif( partNum == null ) {\n\t\t\tparticipantsHTML.innerHTML = \"0\";\n\t\t}\n\t\telse {\n\t\t\tparticipantsHTML.innerHTML = partNum.toLocaleString();\n\t\t}\n\t});\n}",
"function populate(randomUsers){\n // Variable declaration\n const newMembersDiv = document.getElementById('new-members');\n const recentActivityDiv = document.getElementById('recent-activity');\n const membersActivity = [\"posted YourApp's SEO Tips\", \"commented on Facebook's Changes for 2018\", \"liked the post Facebook's Change for 2018\", \"commented on YourApp's SEO Tips\"];\n const activityTime = ['1 day ago', '5 hours ago', '5 hours ago', '4 hours ago'];\n\n // Loop through random users to populate member sections\n for (let i = 0; i < randomUsers.length; i++){\n const member = randomUsers[i];\n\n // Wrapper div for user info\n const memberDiv = document.createElement('div');\n memberDiv.className = 'member-info';\n\n // Image avatar\n const imageDiv = document.createElement('div');\n const img = document.createElement('img');\n img.src = member.picture.thumbnail;\n img.alt = firstUp(member.name.first) + ' ' + firstUp(member.name.last);\n img.className = 'avatar';\n imageDiv.appendChild(img);\n memberDiv.appendChild(imageDiv);\n\n // Use the 4 first users to populate \"New Members\" specific info\n if (i <= 3){\n // Wrapping div\n const detailsDiv = document.createElement('div');\n\n // Name\n const name = document.createElement('p');\n name.className = 'member-name';\n name.innerHTML = firstUp(member.name.first) + ' ' + firstUp(member.name.last);\n detailsDiv.appendChild(name);\n\n // Email\n const email = document.createElement('p');\n email.innerHTML = member.email;\n email.className = 'member-email';\n detailsDiv.appendChild(email);\n memberDiv.appendChild(detailsDiv);\n\n // Signup Date\n const dateDiv = document.createElement('div');\n dateDiv.className = 'flex-item-last';\n const signupDate = document.createElement('p');\n const dateOptions = {month: '2-digit', day: '2-digit', year: '2-digit'};\n signupDate.innerHTML = new Date(member.registered.date).toLocaleDateString('en-US', dateOptions);\n signupDate.className = 'member-signup';\n dateDiv.appendChild(signupDate);\n\n memberDiv.appendChild(dateDiv);\n\n // Line break between members\n newMembersDiv.appendChild(memberDiv);\n if (i < 3){\n const line = document.createElement('hr');\n line.className = \"max-length\";\n newMembersDiv.appendChild(line);\n }\n }\n // The 4 last users populates \"Recent Activity\" specific info\n else {\n // Wrapping div\n const activityDiv = document.createElement('div');\n memberDiv.appendChild(activityDiv);\n\n // Activity\n const activity = document.createElement('p');\n activity.innerHTML = firstUp(member.name.first) + ' ' + firstUp(member.name.last) + membersActivity[i -4];\n activityDiv.appendChild(activity);\n\n // Time\n const time = document.createElement('p');\n time.innerHTML = activityTime[i -4];\n time.className = 'activity-time';\n activityDiv.appendChild(time);\n\n // Signup Date\n const arrowDiv = document.createElement('div');\n arrowDiv.className = 'flex-item-last';\n const arrow = document.createElement('p');\n arrow.innerHTML = '›'\n arrow.className = 'activity-arrow';\n arrowDiv.appendChild(arrow);\n memberDiv.appendChild(arrowDiv);\n\n // Add linebreak if not the last one\n recentActivityDiv.appendChild(memberDiv);\n if (i < 7){\n const line = document.createElement('hr');\n recentActivityDiv.appendChild(line);\n }\n }\n }\n}",
"function subscriptionSucceeded(members) {\n console.log('Success!');\n // call addMember for each user already subscribed\n members.each(addMember);\n}",
"clearAndResetUpdate(){\n\t\tclearTimeout(timer);\n\t\tthis.getChats();\t\n\t}",
"function name_updater(){\n console.log(\"I entered her hihihi\");\n if(oldview_number != view_number){ //Condition used to prevente Discord API rate limit\n var final_name = channel_name[0].concat('-',channel_name[1],'-', view_number.toString());\n client.guilds.cache.get(serverId).channels.cache.get(textChannelId).edit({name: final_name}) //Changes Name of the channel specified with the id textChannelID\n .then(newChannel => console.log(`Channel's new name is ${newChannel.name}`));\n oldview_number = view_number;\n }\n}",
"function showPanelMembers() {\r\n xmlhttpPanel = createXMLHttpRequestHandler();\r\n xmlhttpPanel.onreadystatechange = function() {\r\n if (xmlhttpPanel.readyState == 4 && xmlhttpPanel.status == 200) {\r\n document.getElementById(\"panel_members\").innerHTML = \"\";\r\n $( \"#panel_members\" ).append(xmlhttpPanel.responseText);\r\n }\r\n };\r\n\r\n xmlhttpPanel.open(\"GET\",\"find_panel_members.php\", true);\r\n xmlhttpPanel.send();\r\n}",
"function initMemberDropdown() {\n var contributorsUrl = \"https://api.github.com/repos/\" + repoName + \"/stats/contributors\";\n\n var $memberDropdownList = $(\"#member-dropdown-list\");\n var $memberDropdownMenu = $(\"#member-dropdown-list .dropdown-menu\");\n\n populateMemberDropdown($memberDropdownMenu, contributorsUrl);\n\n // Click event for member dropdown to replace the display text with the selected text\n $memberDropdownMenu.on(\"click\", \"li a\", function() {\n var $memberDropdownDisplay = $(this).closest(\".dropdown\").find(\".display-text\");\n var selectedText = $(this).html();\n\n $memberDropdownDisplay.html(selectedText);\n });\n}",
"function uppdatMemberInAppData(e){\n\n const originalName =e.target.closest('.member-in-list').querySelector('.memebr-name').textContent;\n\n const newList = {\n name:e.target.closest('.member-in-list').querySelector('.new-member-name').value\n };\n\n appData.members.forEach((member)=>{\n if(member.name===originalName){\n member.name=newList.name;\n }\n })\n\n}",
"function refreshCurrentCampaign() {\n\t\tdebugger;\n\t\tresolverContract.methods.campaigns(currentCampaign).call()\n\t\t\t.then(camp =>{\n\t\t\t\tsetOption1Text(camp.option1Description)\n\t\t\t\tsetOption2Text(camp.option2Description)\n\t\t\t});\n\t\t\n\t\t//setOption1Text( \"Discover the Lock Ness Monster\")\n\t\t//setOption2Text( \"Discover the Sasquatch\")\n\t}",
"function setupChannel() {\n // Join the general channel\n generalChannel.join().then(function(channel) {\n print('Joined channel as <span class=\"me\">' + username + '</span>.', username, new Date());\n });\n\n // Listen for new messages sent to the channel\n generalChannel.on('messageAdded', function(message) {\n //printMessage(message.author, message.body);\n print(message.body,message.author,message.dateCreated);\n });\n // Listen for new messages sent to the channel\n generalChannel.on('memberLeft', function(data) {\n console(data);\n //print(message.body,message.author,message.dateCreated);\n });\n }",
"assignTeamMembersToState(opts = { refresh: false }) {\n if ((this.state && this._isMounted) && (!this.state.teamMembersList || opts.refresh)) {\n this.setState({\n teamMembersList: undefined,\n getTeamMembers: undefined\n });\n let teamMember = [];\n ApiCalls.getTeamMembers({\n teamId: this.params.uid\n }).then(apiResults => {\n apiResults.forEach(result => {\n result.modalVisible = false;\n result.key = result.uid.toString() + \"_\" + result.modalVisible.toString();\n teamMember.push(result.uid);\n });\n this.setState({\n teamMembersList: apiResults,\n teamMember: teamMember,\n });\n }, error => {\n this.setState({\n teamMember: teamMember,\n });\n HandleError.handleError(this, error);\n Alert.alert(\"Error!\",\n JSON.stringify(this.state.getTeamMembers || this.state.Error),\n (this.state.Error ?\n [{\n text: \"OK\", onPress: () => {\n this.assignTeamMembersToState({ refresh: true });\n }\n }] : null\n ), { cancelable: false }\n );\n });\n }\n }",
"refresh ()\n {\n // If someone has it open, don't refresh\n if (!this.is_open)\n {\n this.contents = loot.generator.GetLoot(this.type, this.position);\n this.active = true;\n this.opened = false;\n this.sync_nearby();\n this.respawn_time = 0;\n jcmp.events.Call('log', 'loot', \n `Lootbox ${this.id} type ${this.type} refreshed.`);\n }\n else // Try again in 15 seconds to refresh.\n {\n setTimeout(() =>\n {\n this.refresh();\n }, 15 * 1000);\n }\n }",
"function refreshCreditsRemaining() {\n $(\"#credits_remaining\").html(user.creditsRemaining());\n}",
"refreshMentions()\n {\n this.mentions = this.messageRaw.match(/<@(?:\\d){13}>/g) === null ? [] : new Array(...this.messageRaw.match(/<@(?:\\d){13}>/g));\n if (this.mentions.includes(`<@${thisUser.id}>`) && !this.msg.classList.contains('mention'))\n {\n $(this.msg).addClass('mention');\n if (document.visibilityState === 'hidden')\n {\n document.title = `${document.title.match(/\\d+/) === null ? 1 : parseInt(document.title.match(/\\d+/)[0]) + 1}🔴 🅱️iscord`;\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'visible')\n {\n document.title = '🅱️iscord';\n }\n }, { once: true });\n }\n }\n else if (!this.mentions.includes(`<@${thisUser.id}>`) && this.msg.classList.contains('mention'))\n {\n $(this.msg).removeClass('mention');\n document.title = `${document.title.match(/\\d+/) === null ? '' : parseInt(document.title.match(/\\d+/)[0]) - 1 <= 0 ? '' : `${parseInt(document.title.match(/\\d+/)[0]) - 1}🔴 `}🅱️iscord`;\n }\n }",
"function muut_update_online_users_widget() {\n if(show_anon_count) {\n update_anon_count();\n }\n if(show_num_logged_in) {\n update_num_logged_in();\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
MAIN FUNCTIONS We will build the current targets into a JSON structure. The reason: its the only way i found to pass them thru the message without altering its contents very much. This way I can add the targets to "roll" parameter (the only one that i could find) and it will be send. The "roll" parameter is a JSON dict, so i think as long I keep the targets in a separate key inside this dict I'll not mess with other modules | function attachTargetsToMessage(messageData) {
let settings = game.settings.get(MOD_ID, "targetsSendToChat");
if( settings === "none" ) { return; }
else if( settings === "explicit" && messageData.type != CONST.CHAT_MESSAGE_TYPES.ROLL ) { return; }
else if( settings === "implicit" && messageData.type != CONST.CHAT_MESSAGE_TYPES.ROLL && !messageData.content.includes("dice-roll") ) { return; }
// Create JSON structure
let JSONListOfTargets = targetsJSON();
if (JSONListOfTargets == null) return;
JSONListOfTargets = `"selectedTargets":` + JSONListOfTargets;
// Clear targets
if( game.settings.get(MOD_ID, "targetsClearOnRoll") && settings !== "all" ) clearTargets();
// Attach to message content
if(messageData.roll) messageData.roll = messageData.roll.substr(0,messageData.roll.length-1) + "," + JSONListOfTargets + "}";
else messageData.roll = "{" + JSONListOfTargets + "}";
} | [
"function renderToMessage_Targets(html, messageData) {\n // Return cases\n if( game.settings.get(MOD_ID, \"targetsSendToChat\") === \"none\" ) { return; }\n if( !messageData.message.roll ) { return; }\n \n var rollDict = JSON.parse(messageData.message.roll);\n let targetedTokens = getTokenObjsFromIds(rollDict.selectedTargets);\n if(!targetedTokens) { return; }\n \n // Build targets message\n let targetNodes = getTokensHTML(targetedTokens);\n if( !targetNodes || targetNodes.length == 0 ) { return; }\n \n // Create Base Info\n let targetsDiv = document.createElement(\"div\");\n targetsDiv.classList.add(\"targetList\");\n \n let targetsLabel = document.createElement(\"span\");\n targetsLabel.classList.add(\"targetListLabel\");\n targetsLabel.innerHTML = `<b>TARGETS:</b>`;\n targetsDiv.append(targetsLabel);\n \n // Add targets\n for(let i = 0; i < targetNodes.length; i++) {\n targetNode = targetNodes[i];\n targetsDiv.append(targetNode);\n }\n \n // append back to the message html\n html[0].append(targetsDiv);\n \n // Add target all hover function\n if( game.settings.get(MOD_ID, \"chatIntegrationClick\") ) {\n let targetsLabelList = html.find(\".targetListLabel\");\n if(targetsLabelList) targetsLabelList.click(_onChatNameClick_all);\n }\n}",
"function targetsJSON() {\n let targetTokens = getTargetedTokens();\n if(!targetTokens || targetTokens.length == 0) return null;\n \n // Create JSON structure\n let JSONtargets = `[`;\n\n let firstFlag = true;\n for(let i = 0; i < targetTokens.length; i++) {\n if (firstFlag) firstFlag = false;\n else JSONtargets += \",\";\n JSONtargets += `\"` + targetTokens[i].id + `\"`;\n }\n JSONtargets += \"]\";\n \n return JSONtargets\n}",
"roll(event, rollType = null, targetNumber = null) {\n /**Roll Type Possibilities\n * - fatigue\n * - attack\n * - powerActivation\n */\n const owner = this.actor;\n if (!owner) {return false;}\n let ablCode = (rollType === \"fatigue\") ? this.data.data.ablFatigue : this.data.data.useAbl;\n\n if (rollType === null) {\n switch (this.type) {\n case \"weapon\":\n rollType = \"attack\"\n break;\n case \"power\":\n rollType = \"powerActivation\"\n default:\n break;\n }\n }\n \n if (targetNumber === null) {\n switch (rollType) {\n case \"fatigue\":\n ablCode = this.data.data.ablFatigue;\n targetNumber = this.data.data.fatigueTN ? this.data.data.fatigueTN : null;\n break;\n \n case \"powerActivation\":\n targetNumber = this.data.data.targetNumber ? this.data.data.targetNumber : null;\n break;\n \n case \"attack\":\n const targets = game.user.targets;\n if (targets.size === 0) break;\n if (targets.size > 1) {\n // TODO - add case for multiple targets attacked\n let warning = game.i18n.localize(\"age-system.WARNING.selectOnlyOneTarget\");\n ui.notifications.warn(warning);\n return;\n } else {\n const targetId = targets.ids[0];\n const targetToken = canvas.tokens.placeables.find(t => t.data._id === targetId);\n targetNumber = targetToken.actor.data.data.defense.total;\n }\n break;\n \n default:\n break;\n }\n }\n\n const rollData = {\n event: event,\n actor: owner,\n abl: ablCode,\n itemRolled: this,\n rollTN: targetNumber,\n rollType\n }\n Dice.ageRollCheck(rollData);\n }",
"function buildTargetTypes() {\n let url = `https://pokeapi.co/api/v2/move-target/`;\n superagent.get(url)\n .then((results) => {\n results.body.results.forEach((result) => {\n let SQL = `INSERT INTO target_type(api_id, name) VALUES($1, $2);`;\n let values = [result.url.split('/')[6], result.name];\n\n client.query(SQL, values);\n })\n })\n}",
"addTarget({target, linkRole}) {\n this.#status[target] = {die:false, linkRole, target}\n }",
"function setupJoke() {\n randomKnockKnockJoke().forEach( stageOfJoke => {\n conversationBacklog.push(stageOfJoke)\n })\n \n}",
"buildMovement () {\n\t\tvar baseMovement = DigimonStages[this.stage].baseMovement + this.statMods['BaseMovement'];\n\t\tthis.qualityFlags['speedyMax'] = false;\n\t\tvar movement = this.handleRestriction(baseMovement, 'BaseMovement');\n\n\t\tthis.movementDetails = {\n\t\t\t'Movement': movement,\n\t\t\t'Jump Height': Math.floor(movement/2),\n\t\t\t'Jump Length': Math.floor(movement/2),\n\t\t\t'Swim Speed': Math.floor(movement/2)\n\t\t};\n\n\t\tfor (let i in this.extraMovementTypes) {\n\t\t\tvar statMod = this.statMods.hasOwnProperty(this.extraMovementTypes[i]) ? this.statMods[this.extraMovementTypes[i]] : 0;\n\n\t\t\tswitch (this.extraMovementTypes[i]) {\n\t\t\t\tcase 'Flight Speed':\n\t\t\t\t\tif (this.qualityFlags['Advanced Mobility - Flight']) {\n\t\t\t\t\t\tstatMod += this.specValues[this.qualityFlags['Advanced Mobility - Flight']];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Digging Speed':\n\t\t\t\t\tif (this.qualityFlags['Advanced Mobility - Digger']) {\n\t\t\t\t\t\tstatMod += this.specValues[this.qualityFlags['Advanced Mobility - Digger']];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Swim Speed':\n\t\t\t\t\tif (this.qualityFlags['Advanced Mobility - Swimmer']) {\n\t\t\t\t\t\tstatMod += this.specValues[this.qualityFlags['Advanced Mobility - Swimmer']];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Wallclimb Speed':\n\t\t\t\t\tif (this.qualityFlags['Advanced Mobility - Wallclimber']) {\n\t\t\t\t\t\tstatMod += this.specValues[this.qualityFlags['Advanced Mobility - Wallclimber']];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Jump Height':\n\t\t\t\t\tif (this.qualityFlags['Advanced Mobility - Jumper']) {\n\t\t\t\t\t\tstatMod += this.specValues[this.qualityFlags['Advanced Mobility - Jumper']] * 5;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Jump Length':\n\t\t\t\t\tif (this.qualityFlags['Advanced Mobility - Jumper']) {\n\t\t\t\t\t\tstatMod += this.specValues[this.qualityFlags['Advanced Mobility - Jumper']];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Teleport Distance':\n\t\t\t\t\tstatMod += baseMovement - movement;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t}\n\n\t\t\tthis.movementDetails[this.extraMovementTypes[i]] = movement + statMod;\n\t\t}\n\t}",
"set target(target) {\n _target = target;\n options.difficulty = target.stats.defence;\n diceRoller = new DiceRoller(options);\n }",
"function sendTurnData(){\n let emitKey = (phase === PHASES.GUESSING || phase === PHASES.START) ? 'nextGuess' : 'nextImage';\n for(let name in players){\n let player = players[name];\n let playerIdx = passOrder.indexOf(name);\n let targetIdx = (playerIdx + turnCount) % passOrder.length;\n let targetPlayer = players[passOrder[targetIdx]];\n let data = player.entryData[player.entryData.length - 1].data;\n targetPlayer.socket.emit(emitKey, data);\n targetPlayer.targetPlayer = player;\n }\n }",
"onTargetAssigned(target) {}",
"__build_topic(house_id, from_module, to_module, command, args) {\r\n if (args == \"\") args = \"null\"\r\n return [\"egeoffrey\", \"v\"+this.__module.gateway_version, house_id, from_module, to_module, command, args].join(\"/\")\r\n }",
"function postWinnerMessage(winnersInfo, channels, title, message) {\n let attachments = []\n \n winnersInfo.forEach(userInfo => {\n attachments.push({\n //pretext: message,\n color: '#36a64f',\n author_name: userInfo.real_name,\n author_icon: userInfo.profile.image_48,\n thumb_url: userInfo.profile.image_192,\n footer: title,\n ts: Date.now()\n })\n })\n \n let jsonPayload = {\n text: message,\n as_user: false,\n icon_emoji: \":tada\",\n attachments: attachments\n }\n postMessage(channels, jsonPayload)\n}",
"addViewingRole({initiator, target, day, role}) {\n const {viewingRole} = this.#status[initiator];\n viewingRole.push({target, day, role})\n this.#actions = [];\n }",
"function doDamage() {\n let newGroup = {}\n let deadGuys = 0;\n\n if (props.secondGroup) \n newGroup = JSON.parse(JSON.stringify(props.secondGroup))\n else\n newGroup = JSON.parse(JSON.stringify(props.group))\n\n props.changePrevState(JSON.parse(JSON.stringify(newGroup)))\n\n \n //Make an array of keys with the values that are above 0\n let nonzeros = []\n if (props.selection) {\n newGroup.creatures.forEach((element, index) => {\n if (element > 0 && props.selectedCreatures.includes(index) ) \n nonzeros.push(index) \n })\n }\n else {\n newGroup.creatures.forEach((element, index) => {\n if( element > 0 ) \n nonzeros.push(index)\n })\n }\n\n switch(props.targetType) {\n case \"lowest\":\n nonzeros.sort(function(a, b){return newGroup.creatures[a]-newGroup.creatures[b]});\n break;\n case \"highest\":\n nonzeros.sort(function(a,b){return newGroup.creatures[b]-newGroup.creatures[a]})\n break;\n default: \n nonzeros = SmallFunctions.shuffle(nonzeros)\n break;\n }\n\n \n let targets = props.numTargets;\n let rollResults = []\n let finalResults = []\n let damage = null;\n \n\n if (!props.aoe && !props.secondGroup) { //If doing single target damage\n let remainder = props.damage;\n if (props.bleedthrough) targets += 1;\n\n while (nonzeros.length > 0 && targets > 0 && remainder > 0) {\n\n if(newGroup.creatures[nonzeros[0]] > remainder){\n newGroup.creatures[nonzeros[0]] -= remainder\n remainder = 0;\n }\n else if (newGroup.creatures[nonzeros[0]] === remainder) {\n remainder = 0;\n deadGuys += 1;\n newGroup.creatures[nonzeros[0]] = 0;\n }\n else{\n remainder -= newGroup.creatures[nonzeros[0]]\n newGroup.creatures[nonzeros[0]] = 0\n deadGuys += 1;\n }\n nonzeros.splice(0, 1)\n targets -= 1; \n console.log(\"loop\") \n } \n \n }\n else {\n if (props.saveRule === \"None\") \n rollResults = []\n else if (props.aoe)\n rollResults = SmallFunctions.rollDice(props.rolltype, props.numTargets )\n else //If it is an attack group action\n rollResults = SmallFunctions.rollDice(props.rolltype, props.numAttackers )\n\n \n\n if(props.aoe) { //if aoe effect\n while (targets > 0 && nonzeros.length > 0) {\n if (props.saveRule === \"None\" || rollResults[0] + newGroup.Saves[props.saveType]< props.saveDC ) \n damage = props.damage\n \n else if (props.saveRule === \"Half\")\n damage = Math.floor(props.damage / 2)\n \n else \n damage = 0;\n \n newGroup.creatures[nonzeros[0]] = Math.max( 0 , newGroup.creatures[nonzeros[0]] - (damage))\n if (newGroup.creatures[nonzeros[0]] === 0) deadGuys += 1;\n finalResults.push([rollResults[0], damage, false])\n rollResults.splice(0,1)\n nonzeros.splice(0,1)\n targets -= 1;\n }\n \n\n }\n else { //if group attack\n nonzeros = nonzeros.splice(0, targets)\n while (rollResults.length > 0 && nonzeros.length > 0) {\n let newDamage = props.selectedAttack.damBonus\n let victim = Math.floor(Math.random()*nonzeros.length)\n finalResults.push([rollResults[0]])\n for (let i = 0; i < props.selectedAttack.numDie; i++) {\n newDamage += Math.floor(Math.random() * props.selectedAttack.damDie) + 1\n }\n if(props.selectedAttack.saving) {\n if(rollResults[0] + newGroup.Saves[props.selectedAttack.savingType] < props.selectedAttack.DC ) {\n newGroup.creatures[nonzeros[victim]] = Math.max(0, newGroup.creatures[nonzeros[victim]] - newDamage)\n finalResults[finalResults.length-1].push(newDamage)\n finalResults[finalResults.length-1].push(false)\n }\n else {\n finalResults[finalResults.length-1].push(0)\n finalResults[finalResults.length-1].push(false) \n }\n }\n else {\n if( rollResults[0] + props.selectedAttack.bonus >= newGroup.armorClass ) {\n newGroup.creatures[nonzeros[victim]] = Math.max(0, newGroup.creatures[nonzeros[victim]] - newDamage)\n finalResults[finalResults.length-1].push(newDamage)\n finalResults[finalResults.length-1].push(true)\n }\n else {\n finalResults[finalResults.length-1].push(0)\n finalResults[finalResults.length-1].push(true)\n }\n }\n\n if(newGroup.creatures[nonzeros[victim]] === 0) {\n nonzeros.splice(victim, 1)\n deadGuys += 1\n }\n rollResults.splice(0,1) \n\n } \n }\n }\n\n \n if(props.saveRule === \"None\")\n props.changeRollResults([])\n else\n props.changeRollResults(finalResults)\n props.updateGroup(newGroup) \n props.changeDeadGuys(deadGuys) \n }",
"function postAchievementsToSlack() {\n // Retrieve stored game information\n var gameJSONString = sessionStorage.getItem('currentGame');\n var gameJSON = JSON.parse(gameJSONString);\n\n var playerInFirst = JSON.parse(sessionStorage.getItem('playerInFirst'));\n var playerInLast = JSON.parse(sessionStorage.getItem('playerInLast'));\n\n var slackBody ='{\"text\": \"*Cheevos!*\", \"attachments\": [';\n for (i = 0; i < gameJSON.achievements.length; i++) {\n if (i == gameJSON.achievements.length - 1) {\n var cheevoAttachment = '{\"author_name\": \"Cheevo Bot\", \"author_icon\": \"http://a.slack-edge.com/7f18https://a.slack-edge.com/a8304/img/api/homepage_custom_integrations-2x.png\", \"image_url\": \"http://league-tracker-ui-2.mybluemix.net/images/' + gameJSON.achievements[i].name + '.png\" }, { \"title\": \"Eligible Players\", \"text\": \"' + playerInLast + '\"}';\n cheevoAttachment += ']}';\n } else {\n var cheevoAttachment = '{\"author_name\": \"Cheevo Bot\", \"author_icon\": \"http://a.slack-edge.com/7f18https://a.slack-edge.com/a8304/img/api/homepage_custom_integrations-2x.png\", \"image_url\": \"http://league-tracker-ui-2.mybluemix.net/images/' + gameJSON.achievements[i].name + '.png\" }, { \"title\": \"Eligible Players\", \"text\": \"NOT ' + playerInFirst + '\"}';\n cheevoAttachment += ',';\n }\n slackBody += cheevoAttachment;\n }\n console.log('Slack body = ' + slackBody);\n\n // Post the achievements to slack\n $.ajax({\n type: 'POST',\n// beforeSend: function(request) {\n// request.setRequestHeader(\"Content-type\", \"application/json\");\n// },\n url: 'https://hooks.slack.com/services/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',\n// data: '{ \"text\": \"Cheevos!\", \"attachments\": [{ \"title\": \"For NOT Elliot\", \"fields\": [{ \"title\": \"Volume\", \"value\": \"1\", \"short\": true }, { \"title\": \"Issue\", \"value\": \"3\", \"short\": true } ], \"author_name\": \"Stanford S. Strickland\", \"author_icon\": \"http://a.slack-edge.com/7f18https://a.slack-edge.com/a8304/img/api/homepage_custom_integrations-2x.png\", \"image_url\": \"http://league-tracker-ui-2.mybluemix.net/images/yaBasic.png\" }, { \"title\": \"Synopsis\", \"text\": \"After @episod pushed exciting changes to a devious new branch back in Issue 1, Slackbot notifies @don about an unexpected deploy...\" } ] }'\n data: slackBody,\n }).done(function(response) {\n console.log('Successfully POSTed results');\n// window.location.href=\"mainMenu.html?seasonId=\" + seasonId;\n }).fail(function(data) {\n console.log('Failed to POST results: ' + data);\n });\n}",
"function trialLoop(targets){\n /////////////////////////////// Accel, head, and eye tracking\n // Accel gesture detection\n condensed_arrays = accelArrayHandler(orient_short_history);\n\n leftrightgesture = classify_leftright(condensed_arrays[0]);\n bfgesture = classify_backfront(condensed_arrays[1]);\n pageturngesture = classify_pageturn(condensed_arrays[2])\n\n gyro_steady = (leftrightgesture == 0) && (bfgesture == 0) && (pageturngesture == 0);\n // head pose gesture detection\n let pushpullgesture = 0;\n if (gyro_steady && prediction.faceInViewConfidence > .85){\n let cur_head_size = faceGeom.getGeom()[3];\n\n head_size_history.push(Math.sqrt(cur_head_size))\n if (head_size_history.length > lastsecHistoryLen){\n head_size_history.shift();\n }\n\n pushpullgesture = headsizeToGesture(head_size_history, 1.15);\n }\n head_steady = (pushpullgesture == 0);\n // Update eye tracking only when stable -- there's a little steady delay though\n if (gyro_steady && head_steady){\n localPreds.push([...curPred]);\n if (localPreds.length > lastsecHistoryLen){\n localPreds.shift();\n setGridTextColorWhite(targets[1]);\n }\n }\n\n /////////////////////////////// Gesture detection\n all_gestures = [leftrightgesture, bfgesture, pushpullgesture, pageturngesture];\n hist = [localPreds, orient_short_history, head_size_history, angaccel_short_history];\n exposeArrays = JSON.stringify([condensed_arrays, all_gestures, targets, hist])\n\n// gestureHistories.push(JSON.stringify([condensed_arrays, all_gestures, targets, hist]));\n\n console.log(all_gestures);\n // If all gestures is not all 0 and has no 99s (unsteady), a gesture is detected. Log it\n if (!all_gestures.every(elem => elem == 0 || elem == 99) && (sum(all_gestures) < 120)){\n// if (!all_gestures.every(elem => elem == 0) && all_gestures.every(elem => elem != 99)){\n segmentPrediction = getMeanEyeSegment(localPreds.slice(3)) // Averaging predicted gaze XYs\n\n\n\n // Add to accel history\n // condensed is lr, bf, then page turn\n // detected [leftrightgesture, bfgesture, pushpullgesture, pageturngesture]\n // target [targetgest, targetgaze;\n gestureHistories.push(JSON.stringify([condensed_arrays, all_gestures, targets, hist]));\n\n trialEndHandler([all_gestures, segmentPrediction], targets, hist);\n } else{\n if ((Date.now() - trialStartTime) > trial_time*1000){ // Timeout\n // Failed to detect gesture, but save eye position anyway\n segmentPrediction = getMeanEyeSegment(localPreds.slice(3))\n\n trialEndHandler([-1, segmentPrediction], targets, hist);\n return;\n } else{ // Otherwise, run the loop again\n setTimeout(() => trialLoop(targets), trial_delay);\n }\n }\n}",
"function predictBotOrTrolls(msgs) {\n // console.debug('predictBotOrTrolls:', msgs.length, msgs)\n\n // Will keep predictions in order after async POST to web service\n let predictions = []\n msgs.forEach((msg, m) => {\n const data = {\n ups: msg.ups,\n score: msg.score,\n controversiality: msg.controversiality ? 1 : 0,\n author_verified: msg.author_verified ? 1 : 0,\n no_follow: msg.no_follow ? 1 : 0,\n over_18: msg.over_18 ? 1 : 0,\n author_comment_karma: msg.author_comment_karma,\n author_link_karma: msg.author_link_karma,\n is_submitter: msg.is_submitter ? 1 : 0\n }\n\n // Integrate ML web service\n unirest\n .post('https://botidentification-comments.herokuapp.com/')\n .type('json')\n .send(data)\n .end((res) => {\n // console.debug('data sent', JSON.stringify(data))\n // TODO: Handle errors?\n if (2 != res.statusType) {\n // 2 = Ok 5 = Server Error\n console.error('Response not OK, HTTP code', res.code)\n console.error('Data sent', JSON.stringify(data))\n console.error('Response body', res.body)\n }\n // console.debug('res.body', res.body)\n predictions[m] = 2 == res.statusType ? res.body : { prediction: null }\n predictions[m].username = msg.author\n predictions[m].comment_prev = `${msg.body.slice(0, 200)}...`\n predictions[m].datetime = moment\n .unix(msg.created_utc)\n .format('MMM Do HH:mm:ss z')\n predictions[m].link_hash = msg.link_id.slice(3)\n\n // Determine behavior\n switch (predictions[m].prediction) {\n case 'Is a normal user':\n predictions[m].behavior = 'normal'\n break\n case 'Is a Bot':\n predictions[m].behavior = 'bot'\n break\n case 'Is a Troll':\n predictions[m].behavior = 'troll'\n break\n default:\n predictions[m].behavior = 'unknown'\n }\n // console.debug('prediction', m, predictions[m])\n\n // Push to wss once all messages have been predicted.\n // Anon fn. below counts non-empty elements in `predictions`\n if (\n msgs.length == predictions.reduce((ac, cv) => (cv ? ac + 1 : ac), 0)\n ) {\n // console.debug(m, `Pushing ${msgs.length} predictions to wss`)\n wss.clients.forEach((client) =>\n client.send(JSON.stringify(predictions))\n )\n }\n })\n //unirest.post\n })\n}",
"function roll () {\n const player = document.getElementById('player').value;\n const action = document.getElementById('action').value;\n const dice_pile = document.getElementById('dice-pile').value;\n const dice = document.getElementById('dice').value;\n const mod = document.getElementById('mod').value;\n const date = new Date().toString();\n\n const data = {\"player\":player, \"action\":action, \"dice_pile\":dice_pile, \"dice\":dice,\"mod\":mod,\"date\":date}\n socket.emit('roll', data)\n}",
"function buildocrPayload (filesArr) {\n let labels = getLabels();\n var JSONBody = {\n \"template\":{\n \"labels\": labels\n },\n \"pdffiles\": {\n \"files\": filesArr\n }\n };\n console.log('payload: ' +JSON.stringify(JSONBody))\n return JSONBody;\n \n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a member to a subcollection in a room | async addMemberToRoomSubCollection(roomId, userId, playerType, userName, botType) {
let path = "room/" + roomId + "/members"
await this.db.collection(path).doc(userId).set({
inroomState: true,
memberId: userId,
name: userName,
type: playerType,
botType: botType,
cards: [],
deltCards: false,
swapedCards: false,
countCardsSwapped: 0,
totalSwapAmmount: 5,
balance: 100,
hasFolded: false,
excludeCards: [],
status: "",
lastBetAmount: 0,
});
} | [
"async addRoomListToUser(fieldCurrent, fieldOwner, collectionPath, docId, itemId) {\n if (fieldCurrent === \"currentRoom\" && fieldOwner === \"isRoomOwner\") {\n await this.db.collection(collectionPath).doc(docId).update({\n currentRoom: itemId,\n isRoomOwner: true,\n roomOwnerId: itemId\n });\n }\n if (fieldCurrent === \"currentRoom\") {\n await this.db.collection(collectionPath).doc(docId).update({\n currentRoom: itemId\n });\n }\n if (fieldCurrent === \"currentRoom\" && fieldOwner === \"removeOwner\") {\n await this.db.collection(collectionPath).doc(docId).update({\n currentRoom: itemId,\n roomOwnerId: \"\"\n });\n }\n if (fieldCurrent === \"membersList\") {\n await this.db.collection(collectionPath).doc(docId).update({\n membersList: firebase.firestore.FieldValue.arrayUnion(itemId)\n });\n }\n }",
"joinRoom(room) {\n this.room = room;\n\n this.room.addClient(this);\n }",
"function processAddMemberForm(data)\n{\n var member_index = memberIndex(data);\n insertMember(data, member_index);\n}",
"function addMemberToAppData(e){\n // console.info(e.target.closest('.modal-content ').querySelector('.new-member-input').getAttribute('data-id'));\n // const color = addLabelColors();\n const newList = {\n name: e.target.closest('.modal-content ').querySelector('.new-member-input').value,\n id:uuid(),\n labelColor: addColor()\n };\n appData.members.push(newList);\n}",
"function addEventMember(eventId, memberIndex) {\n // get details from members array\n var memberName = flashTeamsJSON[\"members\"][memberIndex].role;\n var memberUniq = flashTeamsJSON[\"members\"][memberIndex].uniq;\n var memberColor = flashTeamsJSON[\"members\"][memberIndex].color;\n\n // get event\n var indexOfEvent = getEventJSONIndex(eventId);\n\n // add member to event\n flashTeamsJSON[\"events\"][indexOfEvent].members.push({name: memberName, uniq: memberUniq, color: memberColor});\n\n // render on events\n renderAllMemberLines();\n}",
"function subscriptionSucceeded(members) {\n console.log('Success!');\n // call addMember for each user already subscribed\n members.each(addMember);\n}",
"joinRoom(room) {\n this.ajax.post(`/rooms/${room.id}/join`).then(() => {\n this.transitionToRoute('play.room', room);\n });\n }",
"function addSub(id, coin) {\n init();\n return new Promise(function (resolve, reject) {\n // Get a Database Object\n var db = admin.firestore();\n // Create a temporary object to store the future value\n var updateObj = {\n subs: {}\n };\n updateObj[\"subs\"][coin] = true;\n // Tell database to update the object\n db.collection('users').doc(id).set(updateObj, { merge: true }).then(function () {\n resolve();\n }).catch(function (error) {\n reject(error);\n });\n });\n}",
"addPart ({ id, owner, file, partNum }, portalOpts) {\n const args = this.addOptions({\n id,\n owner,\n file,\n partNum\n }, portalOpts);\n\n return addItemPart(args)\n .catch(handleError);\n }",
"function addBeerToCollection() {\n _store2.default.dispatch((0, _beerActions.addBeer)());\n return;\n}",
"function addRoomsToData(data) {\r\n // filter down to only rooms that can accept a new player\r\n var availableRooms = _.filter(rooms, function (room) {\r\n return room.playerIds.length < 4;\r\n });\r\n\r\n // if no rooms are available, create a new room\r\n if (availableRooms.length == 0) {\r\n var newRoom = generateRoom();\r\n rooms.push(newRoom);\r\n availableRooms.push(newRoom);\r\n }\r\n\r\n // convert available rooms to just room id and player count\r\n // and attach to data message\r\n data.rooms = _.map(availableRooms, function (room, index) {\r\n return {\r\n roomId: room.id,\r\n roomIndex: index + 1,\r\n playerCount: room.playerIds.length\r\n };\r\n });\r\n\r\n // attach total number of rooms to data message\r\n data.totalRooms = rooms.length;\r\n\r\n // map-reduce to get total number of players in game\r\n // and attach to message\r\n var roomCounts = _.map(rooms, function (room) {\r\n return room.playerIds.length;\r\n });\r\n data.playersInRooms = _.reduce(roomCounts, function (sum, count) {\r\n return sum + count;\r\n });\r\n }",
"add(info) {\n this.contacts.push(new Contact(info[0], info[1], info[2], info[3]));\n }",
"function AddMemberToGroup(event) {\n\t\t\t\n\t\tvar grp=event.target.name;\n\t\t\n\t\t//alert(\"This is Group id \" + event.target.name + \" : \" + event.target.id);\n\t\t\n\t\t$.ajax({\n\t\t\turl : 'http://localhost:8080/facebook_v01/webapi/groupdetails/addMemberToGroup/'\n\t\t\t\t\t+ event.target.name + '/' + event.target.id,\n\t\t\ttype : 'POST',\n\t\t\tasync:false,\n\t\t\tcomplete : function(request, textStatus, errorThrown){\n\t\t\t\tif(request.status===201){\n\t\t\t\t\t\n\t\t\t\t\t//location.reload();\n\t\t\t\t\n\t\t\t\t\t$('#AddMemberToGrouplist1').empty();\n\t\t\t\t\t$('#AddMemberToGrouplist2').empty();\n\t\t\t\t\taddComponentAddMembersToGroupList(grp);\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\twindow.location.href = 'errorpage.html';\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}",
"addInstructor(newInstructor){\n this.instructors.push(newInstructor);\n }",
"addSub(name) {\n let newSubredditList = this.props.subreddits;\n newSubredditList.push(name);\n this.props.callbackFromParent(newSubredditList);\n }",
"function roomsCtrl($scope, $firebaseArray){\n var roomsRef = new Firebase(\"https://bloc-chat-aa.firebaseio.com/\");\n \n // create a synchronized array\n $scope.rooms = $firebaseArray(roomsRef);\n \n // add new items to the array\n $scope.addRoom = function() {\n console.log('in here')\n $scope.rooms.$add({\n roomName: $scope.newRoomText,\n userName: $scope.newUsernameText \n });\n }; \n \n var chatrooms = $firebaseArray(roomsRef.child('roomsCtrl'));\n\n return {\n all: chatrooms\n };\n \n }",
"async addGeofenceToChildArray(userId, geofencesName, childsPhoneNumber) {\n childCollection = await children()\n childFound = await childCollection.findOne({childPhoneNumber:childsPhoneNumber}, { projection: { _id: 1 } })\n let childId = childFound._id\n geofenceCollection = await geofences()\n geofenceFound = await geofenceCollection.findOne({geofenceName: geofencesName})\n let geofencesId = geofenceFound._id\n usersCollection = await users()\n \n let geofencingName = geofenceFound.geofenceName\n let geofenceAddress = geofenceFound.formattedAddress\n let foundLat = geofenceFound.lat\n let foundLng = geofenceFound.lng\n let foundRadius = geofenceFound.radius\n \n \n return this.get(userId).then(currentUser => {\n return usersCollection.updateOne(\n { 'children.id': childId },\n {\n $push: {\n 'children.$.registeredGeofences': {\n geofenceId: geofencesId,\n geofenceName: geofencingName,\n formattedAddress: geofenceAddress,\n lat: foundLat, \n lng: foundLng,\n radius: parseInt(foundRadius),\n CreatedAt: new Date()\n }\n }\n }\n );\n });\n }",
"function addStudentToLectureViewers(){\n dbRef.child(\"lectures/\" + sessionStorage.currentSubject + \"/\" + sessionStorage.lectureDate + \"/viewers\").set({\n id: sessionStorage.bruker\n }).then(function(){\n incrementStudCountLecture(1)\n })\n}",
"addStaffNum(id,){\n this._staffNum.push(id);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to determine flow of regime | function regime(reynum)
{
var reg=document.getElementById("flow");
if(reynum<2000)
{
reg.innerHTML="Laminar Flow";
}
else if(reynum>2000 && reynum<4000)
{
reg.innerHTML="Transitional Flow";
}
else
{
reg.innerHTML="Turbulent Flow";
}
} | [
"function patientFlowP2(patient){\n\tvar state = patient.state\n\tvar hasArrived = (Math.abs(patient.target.row-patient.location.row)\n\t\t\t\t\t +Math.abs(patient.target.col-patient.location.col))==0;\n\tvar receptionistsAvail = receptionistAvailable()\n\tvar P2_bed = P2_in_bed();\n\tswitch(state){\n\t\tcase RECEPTION:\n\t\t\tif (hasArrived){\n\t\t\t\tif (receptionistsAvail.length){\n\t\t\t\t\treceptionistNumber = receptionistsAvail[0]\n\t\t\t\t\tchangeCaregiverState(patient, receptionistNumber, RECEPTIONIST, BUSY)\n\t\t\t\t\ttargetLocation = patient.caregiver.attr\n\t\t\t\t\tchangePatientState(patient, INRECEPTION, targetLocation, \"spot\")\n\t\t\t\t}\n\t\t\t}\n\t\tbreak;\n\t\tcase INRECEPTION:\n\t\t\tif (hasArrived){\n\t\t\t\tif (patient.timeDelay){\n\t\t\t\t\t// if leaving\n\t\t\t\t\tif ((patient.timeDelay - 1) == 0){\n\t\t\t\t\t\tpatient.timeDelay = NaN\n\t\t\t\t\t\tchangeCaregiverState(patient, patient.caregiver.number, RECEPTIONIST, IDLE)\n\t\t\t\t\t\tchangePatientState(patient, TRIAGE, triage, \"area\")\n\t\t\t\t\t}\n\t\t\t\t\t// minus one minute of time delay\n\t\t\t\t\telse {\n\t\t\t\t\t\tpatient.timeDelay = --patient.timeDelay\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// generate new time delay if just arrived\n\t\t\t\telse {\n\t\t\t\t\ttimeDelay = probabilityDelay(models.reception.name, models.reception.params)\n\t\t\t\t\tpatient.timeDelay = timeDelay\n\t\t\t\t}\n\t\t\t}\n\t\tbreak;\n\t\tcase TRIAGE:\n\t\t\tif (hasArrived){\n\t\t\t\tif (patient.timeDelay){\n\t\t\t\t\t// if leaving\n\t\t\t\t\tif ((patient.timeDelay - 1) == 0){\n\t\t\t\t\t\tif (P2_bed.length >= max_space.Bed_Space){\n\t\t\t\t\t\t\tpatientStatistics[1].rejected += 1;\n\t\t\t\t\t\t\tchangePatientState(patient,DISCHARGED,entrance,\"spot\")\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tpatient.timeDelay = NaN\n\t\t\t\t\t\t\tchangePatientState(patient, BED, bedSpace, \"area\")\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// minus one minute of time delay\n\t\t\t\t\telse {\n\t\t\t\t\t\tpatient.timeDelay = --patient.timeDelay\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// generate new time delay if just arrived\n\t\t\t\telse {\n\t\t\t\t\ttimeDelay = probabilityDelay(models.triage.name, models.triage.params)\n\t\t\t\t\tpatient.timeDelay = timeDelay\n\t\t\t\t}\n\t\t\t}\n\t\tbreak;\n\t\tcase BED:\n\t\t\tif (hasArrived){\n\t\t\t\tif (patient.delayState){\n\t\t\t\t\tif ((patient.timeDelay - 1) == 0){\n\t\t\t\t\t\tlogStatistics(patient, 1)\n\t\t\t\t\t\tpatient.timeDelay = NaN\n\t\t\t\t\t\tchangePatientState(patient, patient.delayState, patient.delaySpace, \"spot\")\n\t\t\t\t\t}\n\t\t\t\t\t// minus one minute of time delay\n\t\t\t\t\telse {\n\t\t\t\t\t\tpatient.timeDelay = --patient.timeDelay\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tvar randBedProb = Math.random()\n\t\t\t\t\t// If going home after checkup\n\t\t\t\t\tif (randBedProb< probabilities.bedHome){\n\t\t\t\t\t\tpatient.timeDelay = probabilityDelay(models.doctorP2.name, models.doctorP2.params)\n\t\t\t\t\t\tpatient.delayState = DISCHARGED\n\t\t\t\t\t\tpatient.delaySpace = exit\n\t\t\t\t\t}\n\t\t\t\t\t// If going to ward after checkup\n\t\t\t\t\telse if (randBedProb < probabilities.bedHome + probabilities.bedWard){\n\t\t\t\t\t\tpatient.timeDelay = probabilityDelay(models.P2toWard.name, models.P2toWard.params)\n\t\t\t\t\t\tpatient.delayState = WARDED\n\t\t\t\t\t\tpatient.delaySpace = wards\n\t\t\t\t\t}\n\t\t\t\t\t// If short stay in bed space\n\t\t\t\t\telse {\n\t\t\t\t\t\tpatient.timeDelay = probabilityDelay(models.P2toStay.name, models.P2toStay.params)\n\t\t\t\t\t\tpatient.delayState = DISCHARGED\n\t\t\t\t\t\tpatient.delaySpace = exit\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tbreak;\n\t\tcase WARDED:\n\t\t\tif (hasArrived){\n\t\t\t\tpatient.state = EXITED\n\t\t\t}\n\t\tbreak;\n\t\tcase DISCHARGED:\n\t\t\tif (hasArrived){\n\t\t\t\tpatient.state = EXITED\n\t\t\t}\n\t\tbreak;\n\t\tdefault:\n\t\tbreak;\n\t}\n}",
"function patientFlowP1(patient){\n\tvar state = patient.state\n\tvar hasArrived = (Math.abs(patient.target.row-patient.location.row)\n\t\t\t\t\t +Math.abs(patient.target.col-patient.location.col))==0;\n\tswitch(state){\n\t\tcase INEMERGENCY:\n\t\t\tif (hasArrived){\n\t\t\t\tif (patient.timeDelay){\n\t\t\t\t\t// if leaving\n\t\t\t\t\tif ((patient.timeDelay - 1) == 0){\n\t\t\t\t\t\tpatient.timeDelay = NaN\n\t\t\t\t\t\tchangePatientState(patient, WARDED, wards, \"spot\")\n\t\t\t\t\t\tlogStatistics(patient, 0)\n\t\t\t\t\t}\n\t\t\t\t\t// minus one minute of time delay\n\t\t\t\t\telse {\n\t\t\t\t\t\tpatient.timeDelay = --patient.timeDelay\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// generate new time delay if just arrived\n\t\t\t\telse {\n\t\t\t\t\ttimeDelay = probabilityDelay(models.doctorP1.name, models.doctorP1.params)\n\t\t\t\t\tpatient.timeDelay = timeDelay\n\t\t\t\t}\n\t\t\t}\n\t\tbreak;\n\t\tcase WARDED:\n\t\t\tif (hasArrived){\n\t\t\t\tpatient.state = EXITED\n\t\t\t}\n\t\tbreak;\n\t\tdefault:\n\t\tbreak;\n\t}\n}",
"function compute_LF_ferment(ibu) {\n var LF_ferment = 0.0;\n var LF_flocculation = 0.0;\n\n // The factors here come from Garetz, p. 140\n if (ibu.flocculation.value == \"high\") {\n LF_flocculation = 0.95;\n } else if (ibu.flocculation.value == \"medium\") {\n LF_flocculation = 1.00;\n } else if (ibu.flocculation.value == \"low\") {\n LF_flocculation = 1.05;\n } else {\n console.log(\"ERROR: unknown flocculation value: \" + ibu.flocculation.value);\n LF_flocculation = 1.00;\n }\n\n LF_ferment = SMPH.fermentationFactor * LF_flocculation;\n if (SMPH.verbose > 5) {\n console.log(\"LF ferment : \" + LF_ferment.toFixed(4));\n }\n return LF_ferment;\n}",
"step() {\n let byte = this.ram[this.cpu.pc];\n let instruction = opcodes.get(byte);\n this.penaltyCycles = 0; // reset cycle penalty\n\n let address = this[instruction.mode]();\n this[instruction.opcode](address);\n //this.runCycles += instruction.cycles + this.penaltyCycles;\n this.incrementPc();\n\n // we want the display to refresh in single-step mode.\n if (!this.isRunning) {\n this.refreshVideo();\n }\n return instruction.cycles + this.penaltyCycles;\n }",
"function powerOfTheFire (fliActive) {\n return fliActive / 129\n}",
"function calcShockRatios(gam,mach) {\n\tvar stemp = 0;\n\tvar sdens = 0;\n\tvar spress = 0;\n\tstemp = calcShockTemperature(gam,mach,1.0);\n\tsdens = calcShockDensity(gam,mach,1.0);\n\tspress = calcShockPressure(gam,mach,1.0);\n\treturn [stemp,sdens,spress];\n}",
"function patientFlowP3(patient){\n\tvar state = patient.state\n\tvar hasArrived = (Math.abs(patient.target.row-patient.location.row)\n\t\t\t\t\t +Math.abs(patient.target.col-patient.location.col))==0;\n\tvar receptionistsAvail = receptionistAvailable();\n\tvar doctorsAvail = doctorsAvailable();\n\tvar P3_wait = P3_waiting();\n\tswitch(state){\n\t\tcase RECEPTION:\n\t\t\tif (hasArrived){\n\t\t\t\tif (receptionistsAvail.length){\n\t\t\t\t\treceptionistNumber = receptionistsAvail[0]\n\t\t\t\t\tchangeCaregiverState(patient, receptionistNumber, RECEPTIONIST, BUSY)\n\t\t\t\t\ttargetLocation = patient.caregiver.attr\n\t\t\t\t\tchangePatientState(patient, INRECEPTION, targetLocation, \"spot\")\n\t\t\t\t}\n\t\t\t}\n\t\tbreak;\n\t\tcase INRECEPTION:\n\t\t\tif (hasArrived){\n\t\t\t\tif (patient.timeDelay){\n\t\t\t\t\t// if leaving\n\t\t\t\t\tif ((patient.timeDelay - 1) == 0){\n\t\t\t\t\t\tpatient.timeDelay = NaN\n\t\t\t\t\t\tchangeCaregiverState(patient, patient.caregiver.number, RECEPTIONIST, IDLE)\n\t\t\t\t\t\tchangePatientState(patient, TRIAGE, triage, \"area\")\n\t\t\t\t\t}\n\t\t\t\t\t// minus one minute of time delay\n\t\t\t\t\telse {\n\t\t\t\t\t\tpatient.timeDelay = --patient.timeDelay\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// generate new time delay if just arrived\n\t\t\t\telse {\n\t\t\t\t\ttimeDelay = probabilityDelay(models.reception.name, models.reception.params)\n\t\t\t\t\tpatient.timeDelay = timeDelay\n\t\t\t\t}\n\t\t\t}\n\t\tbreak;\n\t\tcase TRIAGE:\n\t\t\tif (hasArrived){\n\t\t\t\tif (patient.timeDelay){\n\t\t\t\t\t// if leaving\n\t\t\t\t\tif ((patient.timeDelay - 1) == 0){\n\t\t\t\t\t\tpatient.timeDelay = NaN\n\t\t\t\t\t\tif (P3_wait.length >= max_space.Waiting_Area){\n\t\t\t\t\t\t\tpatientStatistics[2].rejected += 1;\n\t\t\t\t\t\t\tchangePatientState(patient, DISCHARGED, entrance, \"spot\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tchangePatientState(patient, WAITING, waitingRoom, \"area\")\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\t// minus one minute of time delay\n\t\t\t\t\telse {\n\t\t\t\t\t\tpatient.timeDelay = --patient.timeDelay\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// generate new time delay if just arrived\n\t\t\t\telse {\n\t\t\t\t\ttimeDelay = probabilityDelay(models.triage.name, models.triage.params)\n\t\t\t\t\tpatient.timeDelay = timeDelay\n\t\t\t\t}\n\t\t\t}\n\t\tbreak;\n\t\tcase WAITING:\n\t\t\tif (hasArrived){\n\t\t\t\tif (doctorsAvail.length){\n\t\t\t\t\tdoctorNumber = doctorsAvail[0]\n\t\t\t\t\tchangeCaregiverState(patient, doctorNumber, DOCTOR, BUSY)\n\t\t\t\t\ttargetLocation = patient.caregiver.attr\n\t\t\t\t\tchangePatientState(patient, INTREATMENT, targetLocation, \"spot\")\n\t\t\t\t}\n\t\t\t}\n\t\tbreak;\n\t\tcase INTREATMENT:\n\t\t\tif (hasArrived){\n\t\t\t\tif (patient.timeDelay){\n\t\t\t\t\tif ((patient.timeDelay - 1) == 0){\n\t\t\t\t\t\tpatient.timeDelay = NaN\n\t\t\t\t\t\tchangeCaregiverState(patient, patient.caregiver.number, DOCTOR, IDLE)\n\t\t\t\t\t\tchangePatientState(patient, PHARMACY, pharmacy, \"area\")\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tpatient.timeDelay = --patient.timeDelay\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\ttimeDelay = probabilityDelay(models.doctorP3.name, models.doctorP3.params)\n\t\t\t\t\tpatient.timeDelay = timeDelay\n\t\t\t\t}\n\t\t\t}\n\t\tbreak;\n\t\tcase PHARMACY:\n\t\t\tif (hasArrived){\n\t\t\t\tif (patient.timeDelay){\n\t\t\t\t\t// if leaving\n\t\t\t\t\tif ((patient.timeDelay - 1) == 0){\n\t\t\t\t\t\tpatient.timeDelay = NaN\n\t\t\t\t\t\tchangePatientState(patient, DISCHARGED, exit, \"spot\")\n\t\t\t\t\t\tlogStatistics(patient, 2)\n\t\t\t\t\t}\n\t\t\t\t\t// minus one minute of time delay\n\t\t\t\t\telse {\n\t\t\t\t\t\tpatient.timeDelay = --patient.timeDelay\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// generate new time delay if just arrived\n\t\t\t\telse {\n\t\t\t\t\ttimeDelay = probabilityDelay(models.pharmacy.name, models.pharmacy.params)\n\t\t\t\t\tpatient.timeDelay = timeDelay\n\t\t\t\t}\n\t\t\t}\n\t\tbreak;\n\t\tcase DISCHARGED:\n\t\t\tif (hasArrived){\n\t\t\t\tpatient.state = EXITED;\n\t\t\t}\n\t\tbreak;\n\t\tdefault:\n\t\tbreak;\n\t}\n}",
"getPreviousStep (time, asIndex) {\n\t\tlet ref = this.tzero;\n\t\ttime -= ref;\n\t\ttime /= (60 * 1000);\n\t\tlet ret = Math.floor(time / this.getStepInterval());\n\t\tif (asIndex)\n\t\t\tret = ret % this.getTotalStepCount();\n\t\treturn ret;\n\t}",
"function timeTilNextShuttle(route, stop) {\n var t = getCurrTime();\n var day = t / 10000;\n var time = t % 10000;\n\n if (route == RouteA)\n {\n if (day < 1 || day > 5)\n return -1;\n else \n return timeDiff(routeAMF, time);\n }\n else if (route == RouteB)\n {\n if (day < 1 || day > 5)\n return -1;\n else\n return timeDiff(routeBMF, time);\n }\n else if (route == RouteAB)\n {\n if (day < 1 || day > 5) \n return timeDiff(routeABSSu, time);\n else\n return timeDiff(routeABMF, time);\n }\n else if (route == RouteC)\n {\n if (day > 4)\n return -1;\n else \n return timeDiff(routeCSuR, time);\n }\n else if (route == BakerySquareL)\n { \n if (stop == CICstop) \n {\n if (day < 1 || day > 5)\n return -1;\n else\n return timeDiff(BakerySquareLRCICMF, time);\n }\n else if (stop == BakerySquarestop)\n {\n if (day < 1 || day > 5)\n return -1;\n else \n return timeDiff(BakerySquareLRBSMF, time);\n }\n else \n return -1;\n }\n else if (route == BakerySquareS)\n {\n if (stop == CICstop) \n {\n if (day < 1 || day > 5)\n return -1;\n else\n return timeDiff(BakerySquareSRCICMF, time);\n }\n else if (stop == BakerySquarestop)\n {\n if (day < 1 || day > 5)\n return -1;\n else \n return timeDiff(BakerySquareSRBSMF, time);\n }\n else \n return -1;\n }\n else if (route == PTCroute)\n { \n if (stop == Morewoodstop) \n {\n if (day < 1 || day > 5)\n return timeDiff(PTCMorewoodSSu, time);\n else\n return timeDiff(PTCMorewoodMF, time);\n }\n else if (stop == PTCstop)\n {\n if (day < 1 || day > 5)\n return timeDiff(PTCPTCSSu, time);\n else\n return timeDiff(PTCPTCMF, time);\n }\n else\n return -1;\n }\n else \n return -1;\n}",
"getNextStep (time, asIndex) {\n\t\tlet ref = this.tzero;\n\t\ttime -= ref;\n\t\ttime /= (60 * 1000);\n\t\tlet ret = Math.ceil(time / this.getStepInterval());\n\t\tif (asIndex)\n\t\t\tret = ret % this.getTotalStepCount();\n\t\treturn ret;\n\t}",
"function calculateFrameTime(){\r\n\t\t\t\r\n\t\t\t//Sum the time for all frames\r\n\t\t\tvar sumFrameTimes = 0;\r\n\t\t\ttempFrameTime.forEach(time => sumFrameTimes += time);\r\n\t\t\t//Divide to get the average Frame time\r\n\t\t\tvar avgFrameTime = sumFrameTimes/tempFrameTime.length;\r\n\t\t\t//Push it into the array to be saved\r\n\t\t\tavgFrameTimeArray.push(avgFrameTime);\r\n\t\t\tconsole.log(\"avgFrameTime: \" + avgFrameTime);\r\n\t\t\t\r\n\t\t\t//Reset the array for the next trial\r\n\t\t\ttempFrameTime = []; \r\n\t\t}",
"function calculateDetectorFrequency(scope,operator) {\n\tvar _distance = circle_centre - detector_container.x - 50; /** Calculating the distance between source and detector */\n\tvar _distance_temp;\t\n\tif ( operator*_distance < 0 ) { /** When both source and detector moving towards */\n\t\t/** Calculating the detected frequency and interchanging the frequency if getting high value while source and detector moving away */\n\t\tdetected_frequency = source_frequency *(medium_velocity - detector_velocity)/ (medium_velocity - source_velocity)\t\n\t\t_distance_temp = source_frequency *(medium_velocity + detector_velocity)/ (medium_velocity + source_velocity)\t\n\t\tif ( _distance_temp > detected_frequency && detector_velocity > 0 && medium_velocity == air_velocity) { /** Interchanging the frequency if getting high value while source and detector moving away */\n\t\t\tdetected_frequency = _distance_temp;\n\t\t}\n\t} else {\n\t\t/** Calculating the detected frequency if both source and detector moves away from each other */\n\t\tdetected_frequency = source_frequency *( medium_velocity + detector_velocity )/ ( medium_velocity + source_velocity )\n\t\t_distance_temp = source_frequency *( medium_velocity - detector_velocity )/ ( medium_velocity - source_velocity )\t\t\t\t\t\t\n\t\tif ( detected_frequency > _distance_temp && detector_velocity > 0 && medium_velocity == air_velocity ) { /** Interchanging the frequency if getting high value while source and detector moving away */\n\t\t\tdetected_frequency = _distance_temp;\t\n\t\t} \t\n\t}\n}",
"async function timeTravelToTransition() {\n let startTimeOfNextPhaseTransition = await stakingHbbft.startTimeOfNextPhaseTransition.call();\n\n await validatorSetHbbft.setCurrentTimestamp(startTimeOfNextPhaseTransition);\n const currentTS = await validatorSetHbbft.getCurrentTimestamp.call();\n currentTS.should.be.bignumber.equal(startTimeOfNextPhaseTransition);\n await callReward(false);\n }",
"getPreviousTime (step, time) {\n\t\tlet ret = this.getStepTime(step);\n\t\tlet totalTime = this.getTotalInterval() * 60 * 1000;\n\t\twhile (ret > time)\n\t\t\tret -= totalTime;\n\t\treturn ret;\n\t}",
"function getContestTime(contest){\n\n // visited contest, so circular appears - return circular info\n if (contest.timeStart == -1) {\n return { circular: [contest.index] };\n }\n\n // time start already known - so return end\n if (contest.timeStart) {\n return parseInt(contest.timeStart) + parseInt(contest.timeLength);\n }\n\n // independent contest, so it can start at project start\n if (!(contest.dependsOn.length) && contest.follow <= 0) {\n contest.timeStart = 0;\n return contest.timeLength;\n }\n\n // mark current contest as visited\n contest.timeStart = -1;\n\n // calculate times for all contests on which depends this one\n var dependTimes = [];\n\n // check follow after contest, if set\n if (contest.follow > 0) {\n var followTime = getContestTime(contests[contest.follow - 1]);\n\n // circular was found\n if (followTime.circular) {\n // circular closed, when contest circuit return to itself\n if (followTime.circular[0] == contest.index) {\n followTime.circularClose = true;\n }\n if (!followTime.circularClose) followTime.circular.push(contest.index);\n return followTime;\n }\n dependTimes.push(followTime);\n }\n\n // check all depends on contests\n for (var i = 0; i < contest.dependsOn.length; i++) {\n var dependTime = getContestTime(contests[contest.dependsOn[i] - 1]);\n\n // circular was found\n if (dependTime.circular) {\n // circular closed, when contest circuit return to itself\n if (dependTime.circular[0] == contest.index) {\n dependTime.circularClose = true;\n }\n if (!dependTime.circularClose) dependTime.circular.push(contest.index);\n return dependTime;\n }\n dependTimes.push(dependTime);\n }\n\n // find the last contest on which depends this ends\n contest.timeStart = Math.max.apply(null, dependTimes) + contestInterval;\n\n return parseInt(contest.timeStart) + parseInt(contest.timeLength);\n }",
"function flow(input, funcArray) {\n \n if (funcArray.length === 0){\n return input;\n } else{\n let output = funcArray[0](input);\n return flow(output, funcArray.slice(1))\n }\n \n }",
"function part1() {\n let frequency = 0\n changes.map(change => {\n frequency += parseInt(change)\n })\n return frequency\n}",
"function draw_regret_graph(data) {\n var title = \"Expected Regret per step\"\n var y_title = \"Expected Regret\"\n var String_title = [title, y_title]\n var mean = data[\"regret_figure\"][0]\n var std = data[\"regret_figure\"][1]\n var input_data = {'String_title': String_title, 'mean': mean, 'std': std}\n draw_ROA(input_data)\n}",
"function getPwm(hour) {\t\n\tif (LOG) { console.log(\"Looking for TP (\" + hour + \") -----------------\"); }\n\tvar rampe_pwm = { blue: -1, white: -1};\n\tif ( !(TPS[0].hour < hour && hour < TPS[TPS.length-1].hour) ) {\t//hour is in implicit period (night)\n\t\ttp1 = TPS[TPS.length-1];\n\t\ttp2 = TPS[0];\n\t\tif (DEBUG) { console.log( 'night: ' + hour + \" (\" + TPS[TPS.length-1].hour + \"-\" + TPS[0].hour +\")\" ); }\n\t\tif (LOG) { console.log('TP1-TP2', tp1, tp2 ); }\n\t\tvar ratio = ratioPwm(tp1, tp2, hour);\n\t} else {\t//find hour in TPS\n\t\tfor( i = 0; i < TPS.length-1; i++ ) {\n\t\t\ttp1 = TPS[i];\n\t\t\ttp2 = TPS[i+1];\n\t\t\tif ( tp1.hour <= hour && hour <= tp2.hour) {\n\t\t\t\tif (DEBUG) { console.log( tp1.hour + \" <= \" + hour + \" < \" + tp2.hour); }\n\t\t\t\tif (LOG) { console.log( 'TP1-TP2', tp1, tp2 ); }\n\t\t\t\tvar ratio = ratioPwm(tp1, tp2, hour);\n\t\t\t}\n\t\t}\n\t}\n\treturn ratio;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
the exchange responseObjects of this event readonly attribute jsval responseObjects; / // part of my own items. | get responseObjects()
{
return this._responseObjects;
} | [
"get jsons() {\n\t\treturn this[root_json] ? this[root_json].$proxy() : null\n\t}",
"function getEvents(){\nreturn events;\n}",
"function getAllItemsCallback(response){\n\t\n}",
"function loadResponse(){\n var APODObject = JSON.parse(this.response)\n APODList.push(APODObject)\n}",
"get eventReceivers() {\n return SPCollection(this, \"EventReceivers\");\n }",
"$registerRequestResponse() {\n this.$container.bind('Adonis/Core/Request', () => Request_1.Request);\n this.$container.bind('Adonis/Core/Response', () => Response_1.Response);\n }",
"currentInfoResponses() {\n const { infoResponses } = this.props;\n\n return this.imageServiceIds().map(imageId => (\n infoResponses[imageId]\n )).filter(infoResponse => (infoResponse !== undefined\n && infoResponse.isFetching === false\n && infoResponse.error === undefined));\n }",
"events() {\n return new OpenFDADrugEvents(this.api);\n }",
"function _dispatchedExpectedEvents_(){this._dispatchedExpectedEvents$_LKQ=( new mx.collections.ArrayCollection());}",
"get raw() {\n return this.#raw_response;\n }",
"function reframeResponseForTodayTab(response){\t\n\tvar object = {};\n\tvar todayArray = [];\n\tvar daterangeArray = [];\n\t//var todayDate = getTodayDateForOOC(2);\n\t//var urgentDatesArray = getUrgentIndicatorDates();\n\tfor ( var i = 0; i < response.length; i++) {\n\t\tobject = {};\n\t\tobject.article_no = response[i].article_no;\n\t\tobject.article_desc = response[i].article_desc;\n\t\tif(response[i].soh != null){\n\t\t\tif(response[i].soh.split(\" \")[1].trim() == \"EA\"){\n\t\t\t\tobject.soh = Number(response[i].soh.split(\" \")[0].trim()).toFixed(0)+\" \"+response[i].soh.split(\" \")[1].trim();\n\t\t\t}\n\t\t\telse{\n\t\t\t\tobject.soh = Number(response[i].soh.split(\" \")[0].trim()).toFixed(3)+\" \"+response[i].soh.split(\" \")[1].trim();\t\n\t\t\t}\n\t\t}\n\t\t\n\t\tobject.base_uom = response[i].base_uom;\n\t\tobject.aisle_no = response[i].aisle_no;\t\n\t\tobject.expiry_date = response[i].expiry_date;\t\n\t\tif(response[i].tab_name == \"today\"){\n\t\t\t//if(determineUrgentIndicator(response[i],urgentDatesArray) == 'Χ'){\t\t\t\t\n\t\t\ttodayArray.push(object);\n\t\t\t//}\n\t\t}else if(response[i].tab_name == \"date_range\"){\n\t\t\tdaterangeArray.push(object);\n\t\t}\t\t\n\t}\n\tresponseTodayTab = todayArray;\t\n\tresponseDaterangeTab = daterangeArray;\n\tconsole.log(\"Reframed response for today tab\");\n\tconsole.log(responseTodayTab);\n}",
"extractValidObjects(responseJson) {\n let objectList = [];\n for (let i = 0; i < responseJson.value.length && objectList.length < maxSearchResults; i++) {\n if (\n this.isValidUrl(responseJson.value[i].PrimaryImageUrl) &&\n this.isValidUrl(responseJson.value[i].LinkResource)\n ) {\n // Extract all objects with a valid image and resource Urls\n objectList.push(responseJson.value[i]);\n }\n }\n return objectList;\n }",
"function handleResponse(data) {\r\n var parsedResponse = JSON.parse(data.currentTarget.response);\r\n console.log(parsedResponse.items);\r\n var parsedItems = Object.values(parsedResponse.items);\r\n var itemTimeslotArray = buildTimeslotArray(parsedItems);\r\n // pageConstructor(parsedItems, itemTimeslotArray);\r\n console.log(parsedItems);\r\n var currentDate = getDateForm();\r\n var paramForm = getParamForm();\r\n// console.log(currentDate);\r\n htmlConstructor(parsedItems, itemTimeslotArray, currentDate, paramForm);\r\n}",
"function convertResponse(events) {\n const items = [];\n\n // iterate through each issue and extract id, title, etc. into a new array\n for (let i = 0; i < events.length; i++) {\n const raw = events[i];\n const item = {\n id: raw.id,\n title: raw.summary,\n description: raw.description,\n date: raw.start.dateTime,\n link: raw.htmlLink,\n raw: raw\n };\n\n items.push(item);\n }\n\n return { items };\n}",
"function respondToAllTag(bidRequest) {\n var tags = bidRequest.tags;\n response_tags = [];\n if (tags && tags.length > 0) {\n tags.forEach(function(tag) {\n response_tags.push(generateBidResponse(tag));\n });\n }\n return response_tags;\n}",
"function ajaxHandleResponses(s,jqXHR,responses){var contents=s.contents,dataTypes=s.dataTypes,responseFields=s.responseFields,ct,type,finalDataType,firstDataType;// Fill responseXXX fields\nfor(type in responseFields){if(type in responses){jqXHR[responseFields[type]]=responses[type];}}// Remove auto dataType and get content-type in the process\nwhile(dataTypes[0]===\"*\"){dataTypes.shift();if(ct===undefined){ct=s.mimeType||jqXHR.getResponseHeader(\"content-type\");}}// Check if we're dealing with a known content-type\nif(ct){for(type in contents){if(contents[type]&&contents[type].test(ct)){dataTypes.unshift(type);break;}}}// Check to see if we have a response for the expected dataType\nif(dataTypes[0]in responses){finalDataType=dataTypes[0];}else{// Try convertible dataTypes\nfor(type in responses){if(!dataTypes[0]||s.converters[type+\" \"+dataTypes[0]]){finalDataType=type;break;}if(!firstDataType){firstDataType=type;}}// Or just use first one\nfinalDataType=finalDataType||firstDataType;}// If we found a dataType\n// We add the dataType to the list if needed\n// and return the corresponding response\nif(finalDataType){if(finalDataType!==dataTypes[0]){dataTypes.unshift(finalDataType);}return responses[finalDataType];}}// Chain conversions given the request and the original response",
"getAllEvents() {\r\n return Event.all;\r\n }",
"function handleResponse(event) {\n let elementClicked = event.target; // returns the list element \"<li>3</li>\" that was clicked on\n \n // Record user selection.\n let questionObject;\n\n // Find the questionObject that corresponds to the question the user responded to.\n for (i = 0; i < questionObjects.length; i++) {\n if (document.getElementsByTagName(\"p\")[0].innerText == questionObjects[i].question) {\n questionObjects[i].userResponse = Array.from(elementClicked.parentNode.children).indexOf(elementClicked);\n break;\n }\n }\n // Ask next question if questions are left to be asked. Otherwise, get results.\n if (questionsAlreadyAsked.length == questionObjects.length) {\n document.getElementsByTagName(\"ul\")[0].removeEventListener(\"click\", handleResponse);\n getResults();\n } else {\n askNextQuestion();\n }\n}",
"function getAllLocationsCallback(response){\n\t\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set the global flag on a RegExp (you have to create a new one) | function _globalize($regexp) {
return new RegExp(String($regexp).slice(1, -1), "g");
} | [
"function regexpFrom(string, flags) {\n return new RegExp(core.escapeRegExp(string), flags);\n }",
"function addFlags(regexp, flags) {\n\n var reg = core.interpretRegExp(regexp);\n var regFlags = core.arrayUnique(\n reg.flags.split(\"\"),\n flags.split(\"\")\n ).join(\"\");\n\n return new RegExp(reg, regFlags);\n\n }",
"function regenerateRegExp(){\r\n\t\tpseudoRE = new RegExp('::?(' + Object.keys(pseudos).join('|') + ')(\\\\\\\\[0-9]+)?');\r\n\t}",
"function patternCache() {\n pattern = new RegExp(settings.start + \"\\\\s*(\" + settings.path + \")\\\\s*\" + settings.end, \"gi\");\n }",
"function regExBuilder (find, regex, insensitive) {\n if (find) {\n var re = regex ? find : s.escapeRegExp(find)\n var reOptions = 'g' + (insensitive ? 'i' : '')\n return new RegExp(re, reOptions)\n }\n}",
"function regExBuilder(options){\n var re = options.regex ? options.find : w.escapeRegExp(options.find),\n reOptions = \"g\" + (options.insensitive ? \"i\" : \"\");\n return new RegExp(re, reOptions);\n}",
"function TestRE(v, re)\n{\n return new RegExp(re).test(v);\n}",
"function getRegExp(pattern, flags) {\n var safeFlags = angular.isString(flags) ? flags : \"\";\n return (angular.isString(pattern) && pattern.length > 0) ? new RegExp(pattern, safeFlags) : null;\n }",
"regexAll (text, array) {\n for (const i in array) {\n let regex = array[i][0]\n const flags = (typeof regex === 'string') ? 'g' : undefined\n regex = new RegExp (regex, flags)\n text = text.replace (regex, array[i][1])\n }\n return text\n }",
"function generateRegExp() {\n\n\tvar str = '';\n\tvar arr = [];\n\tvar tmp = \"@(types)\";\n\t\n\t// Get all the replaceable keywords from corpus, stick them into an array\n\tfor(type in corpus) {\n\t\tarr.push(type);\n\t}\n\t\n\t// Construct regular expression in the form of '@(keyword1,keyword2,keyword3,...)'\n\tvar exp = tmp.replace(\"types\", arr.join('|'));\n\t\n\treturn new RegExp(exp, \"ig\");\n}",
"function generateRegExp() {\n\n\tvar str = '';\n\tvar arr = [];\n\tvar tmp = \"@(types)\";\n\t\n\tfor (type in corpus) {\n\t\tarr.push(type);\n\t}\n\t\n\tvar exp = tmp.replace(\"types\", arr.join('|'));\n\t\n\treturn new RegExp(exp, \"ig\");\n}",
"function parseRegExp(node) {\n const evaluated = (0, util_1.getStaticValue)(node, globalScope);\n if (evaluated == null || !(evaluated.value instanceof RegExp)) {\n return null;\n }\n const { source, flags } = evaluated.value;\n const isStartsWith = source.startsWith('^');\n const isEndsWith = source.endsWith('$');\n if (isStartsWith === isEndsWith ||\n flags.includes('i') ||\n flags.includes('m')) {\n return null;\n }\n const text = parseRegExpText(source, flags.includes('u'));\n if (text == null) {\n return null;\n }\n return { isEndsWith, isStartsWith, text };\n }",
"highlightSearchSyntax() {\n console.log('highlightRegexSyntax');\n if (this._highlightSyntax) {\n this.regexField.setBgHtml(this.regexField.getTextarea().value.replace(XRegExp.cache('[<&>]', 'g'), '_'));\n this.regexField.setBgHtml(this.parseRegex(this.regexField.getTextarea().value));\n } else {\n this.regexField.setBgHtml(this.regexField.getTextarea().value.replace(XRegExp.cache('[<&>]', 'g'), '_'));\n }\n }",
"function Simplification() {\r\n var regEx = document.getElementsByClassName(\"simpli\")[0].value;\r\n var text = document.getElementsByClassName(\"simpli\")[1].value;\r\n\r\n var re = new RegExp(regEx);\r\n\r\n var reponse = re.exec(text);\r\n document.getElementById(\"testSimpli\").value = reponse;\r\n\r\n}",
"function PCREListener() {\n antlr4.tree.ParseTreeListener.call(this);\n return this;\n}",
"function getRegExpForCurrentEnv() {\n if (MY_DEBUG) {\n return MY_DEBUG_REGEXP;\n }\n\n let url = location.href;\n if (url.match(DEV_URL_REGEXP)) {\n return DEV_URL_REGEXP;\n } else if (url.match(STG_URL_REGEXP)) {\n return STG_URL_REGEXP;\n } else {\n return PRO_URL_REGEXP;\n }\n}",
"eatRegExpIdentifierName() {\n this._lastStrValue = \"\";\n if (this.eatRegExpIdentifierStart()) {\n this._lastStrValue += String.fromCodePoint(this._lastIntValue);\n while (this.eatRegExpIdentifierPart()) {\n this._lastStrValue += String.fromCodePoint(this._lastIntValue);\n }\n return true;\n }\n return false;\n }",
"function parseRegExpText(pattern, uFlag) {\n // Parse it.\n const ast = regexpp.parsePattern(pattern, undefined, undefined, uFlag);\n if (ast.alternatives.length !== 1) {\n return null;\n }\n // Drop `^`/`$` assertion.\n const chars = ast.alternatives[0].elements;\n const first = chars[0];\n if (first.type === 'Assertion' && first.kind === 'start') {\n chars.shift();\n }\n else {\n chars.pop();\n }\n // Check if it can determine a unique string.\n if (!chars.every(c => c.type === 'Character')) {\n return null;\n }\n // To string.\n return String.fromCodePoint(...chars.map(c => c.value));\n }",
"function replaceAll(str, term, replacement) {\n return str.replace(new RegExp(escapeRegExp(term), 'g'), replacement);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function builds a curve factory from a standard curves object | function buildCurve(curve) {
var base = d3['curve' + curve.name]; // The base curve without any arguments
var args = curve.args;
var built;
if (args !== false) {
var x;
built = base;
for (var i = 0; i < args.length; i++) {
x = args[i];
built = built[x.name](x.value) // Plug in the argument
}
} else {
built = base;
}
return d3.line().curve(built);
} | [
"get curve() {}",
"getCurve( startX, startY, endX, endY ) {\n let middleX = startX + (endX - startX) / 2;\n return `M ${startX} ${startY} C ${middleX},${startY} ${middleX},${endY} ${endX},${endY}`;\n }",
"static CreateCubicBezier(v0, v1, v2, v3, nbPoints) {\n // tslint:disable-next-line:no-parameter-reassignment\n nbPoints = nbPoints > 3 ? nbPoints : 4;\n const bez = new Array();\n const equation = (t, val0, val1, val2, val3) => {\n const res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 +\n 3.0 * t * (1.0 - t) * (1.0 - t) * val1 +\n 3.0 * t * t * (1.0 - t) * val2 +\n t * t * t * val3;\n return res;\n };\n for (let i = 0; i <= nbPoints; i++) {\n bez.push(new Vector3_1$2.Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));\n }\n return new Curve3(bez);\n }",
"function generate_curve_data (i)\r\n{\r\n\r\n // make data arrays for each selection\r\n var curve_data = [];\r\n var curr_sel_ind = 0;\r\n\r\n for (var k = 0; k < max_num_sel; k++) {\r\n\r\n // make array of indices into selection colors\r\n var curr_sel_color = [];\r\n for (var j = 0; j < plots_selected_time[i].length; j++) {\r\n\t\t curr_sel_color.push(k);\r\n\t }\r\n\r\n\t // get current selection\r\n\t var curr_sel = selections.filtered_sel(k+1);\r\n\r\n\t // make array of data for current selection\r\n\t for (var j = 0; j < Math.min(curr_sel.length, max_num_plots); j++) {\r\n\t\t curve_data.push(d3.transpose([plots_selected_time[i],\r\n\t\t\t\t plots_selected_data[i][j + curr_sel_ind],\r\n\t\t\t\t curr_sel_color]));\r\n\t };\r\n\r\n\t // update selection index\r\n\t curr_sel_ind = curr_sel_ind + Math.min(curr_sel.length, max_num_plots);\r\n }\r\n\r\n\treturn curve_data;\r\n}",
"function compile(obj) {\n obj = traverse(obj).map(function (value) {\n if (this.isLeaf && String(value)[0] === '$') {\n this.update(new Function('curves', 'return ' + String(value).substr(1)))\n }\n })\n\n return function render(curves) {\n return traverse(obj).map(function (value) {\n if (typeof value === 'function') {\n this.update(value(curves))\n }\n })\n }\n}",
"static createArray(curves) {\n const result = new Loop();\n for (const curve of curves) {\n result.children.push(curve);\n }\n return result;\n }",
"function buildsGridOverParametrizedCurve({\n studyFun, //studyFun: t|->z, z is in study domain,\n curveFun, //studyFun: t|->[x,y], x,y are in model space,\n tA, //tStart\n tB, //tEnd\n tN, //number of steps used to paint measurement arc,\n svgParent, //f.e., stdMod.svgScen,\n\n //conditionally optionals\n //svgel, //possibly existing svgel to avoid recreation\n rgCurveName,\n decorations, //see api in \"destructuring arguments\" below\n\n }){\n\n //-----------------------------\n // //\\\\ destructuring arguments\n //-----------------------------\n decorations = decorations || {};\n var {\n lettersShiftMedpos, //format = [ x, y ]\n decimalDigits,\n measurementStroke,\n measurementStrokeWidth,\n fontSize,\n } = decorations;\n fontSize = fontSize || 12;\n //-----------------------------\n // \\\\// destructuring arguments\n //-----------------------------\n\n\n var returnApi = {};\n\n\n //-----------------------------\n // //\\\\ gets features\n //-----------------------------\n var studyStart = studyFun( tA );\n var studyEnd = studyFun( tB );\n var studyRange = studyEnd - studyStart;\n //-----------------------------\n // \\\\// gets features\n //-----------------------------\n\n\n //--------------------------------------------------------\n // //\\\\ estimates grid thinness\n //--------------------------------------------------------\n //calculates grid's grades\n var decUnitlog = Math.log10( studyRange );\n decUnitlog = Math.floor( decUnitlog );\n\n var decUnit = Math.pow( 10, decUnitlog );\n //if decUnit is too big, decreases it 10 times for dense grid\n decUnit = decUnit > studyRange * 0.5 ? decUnit * 0.1 : decUnit;\n //starts the grid from \"rounded\" grade\n var linesStart = Math.ceil( studyStart / decUnit ) * decUnit;\n\n ///abandoned feature: implements variable scale, for fixed grades\n //var gradeCounter = 0;\n //slider.variableGrades = [];\n //--------------------------------------------------------\n // \\\\// estimates grid thinness\n //--------------------------------------------------------\n\n\n\n\n /*\n //================================================\n // //\\\\ buids thin subgrades\n //================================================\n (function() {\n if( studyRange / decUnit < 7 ) {\n var subGrade = decUnit / 10;\n for( var gline=linesStart-decUnit; gline<=slider.maxVal; gline+=subGrade ) {\n\n if( gline < slider.minVal ) continue; \n ///main level of the grade on vertical axis of the slider\n var mediaModelGradeY =\n //origin on the bottom of svg\n //sconf.pictureHeight + \n mod2inn_scale * (\n //\"-\" because of screen Y inversion:\n - ( gline - slider.minVal ) *\n slider.value2media\n ) + slider.SLIDERS_RULE_BOTTOM\n ;\n ///creates pivots for grid line\n var gridPivots = [\n [ rgBottomPoint.medpos[0], mediaModelGradeY ],\n [ rgTopPoint.medpos[0]+13, mediaModelGradeY ],\n ];\n var svgel = slider.subgrid = nssvg.polyline({\n pivots : gridPivots,\n parent : svgParent,\n style : {\n opacity : 1,\n 'stroke-width' : 1,\n },\n });\n }\n }\n //decSubUnit = decUnit > studyRange * 0.5 ? decUnit * 0.1 : decUnit;\n })();\n //================================================\n // \\\\// buids thin subgrades\n //================================================\n */\n\n\n for( var gline=linesStart; gline<=studyEnd; gline+=decUnit ) {\n\n var t = ( gline - studyStart ) / studyRange * ( tB - tA );\n var gridPos = curveFun( t );\n var gridMedpos = ssF.mod2inn( gridPos, stdMod );\n\n //----------------------------------\n // //\\\\ creates grade radial lines\n //----------------------------------\n var GRID_WIDTH = 0.015;\n var GRID_LETTER_WIDTH = 0.03;\n\n var norm = getsCurveNormal( t, tA, tB );\n var normMedpos = ssF.mod2inn( norm, stdMod );\n var medpos = ssF.mod2inn( [0,0], stdMod );\n var medNorm = [ (normMedpos[0]-medpos[0])*GRID_WIDTH,\n (normMedpos[1]-medpos[1])*GRID_WIDTH,\n ];\n var medLetterNorm = [ (normMedpos[0]-medpos[0])*GRID_LETTER_WIDTH,\n (normMedpos[1]-medpos[1])*GRID_LETTER_WIDTH,\n ];\n var gridPivots = [\n gridMedpos,\n [ gridMedpos[0]-medNorm[0], gridMedpos[1]-medNorm[1] ],\n ];\n var gridLetterPivots = [\n gridMedpos[0]-medLetterNorm[0],\n gridMedpos[1]-medLetterNorm[1]\n ];\n\n nssvg.polyline({\n pivots : gridPivots,\n parent : svgParent,\n style : {\n opacity : 1,\n //for thick grades, width is bigger than from thin grades:\n 'stroke-width' : 2,\n },\n });\n //----------------------------------\n // \\\\// creates grade radial lines\n //----------------------------------\n\n\n\n //---------------------------------------------------------- \n // //\\\\ prints grade digital lablel for math model magnitude\n // measured by the gauge\n //---------------------------------------------------------- \n decimalDigits = decimalDigits || 0;\n\n //implement this ? as a function\n //var variableGrade = slider.variableGrades[ gradeCounter++ ] = {};\n //variableGrade.gline = gline;\n //variableGrade.decimalDigits = decimalDigits;\n //variableGrade.svgel =\n\n var x = gridLetterPivots[0];\n var y = gridLetterPivots[1];\n if( lettersShiftMedpos ) {\n x += lettersShiftMedpos[0];\n y += lettersShiftMedpos[1];\n }\n nssvg.printText({\n text : gline.toFixed( decimalDigits ),\n x,\n y,\n parent : svgParent,\n style : {\n 'font-size' : fontSize,\n 'font-weight' : 'normal',\n 'stroke-width' : '1',\n 'stroke' : '1',\n 'fill' : 'black',\n 'opacity' : 0.5,\n },\n });\n //---------------------------------------------------------- \n // \\\\// prints grade digital lablel for math model magnitude\n //---------------------------------------------------------- \n }\n\n returnApi.measurement = {\n rgName : rgCurveName + '_measurement',\n };\n\n returnApi.drawsMeasurement = drawsMeasurement;\n return returnApi;\n\n\n\n\n function getsCurveNormal( t, tA, tB )\n {\n var step = (tB - tA)/1000;\n var f0 = curveFun( t );\n var f1 = curveFun( t+step );\n //finds \"derivative\", tang\n var tang = [ f1[0]-f0[0], f1[1]-f0[1], ];\n var abs2 = tang[0]*tang[0] + tang[1]*tang[1];\n //finds normal to curve's tangent\n var norm = mat.vector2normalOrts( tang );\n return norm.norm;\n }\n\n\n ///possibly draws the curve-\"pipe\" which is aka \"column\" in thermometer\n function drawsMeasurement( t )\n {\n var step = ( tB - tA ) / tN;\n returnApi.measurement.rgX = ssF.paintsCurve({\n mmedia : svgParent,\n fun : curveFun,\n rgName : returnApi.measurement.rgName,\n strokeWidth : measurementStrokeWidth || 30,\n start : tA, //222, //??? abs value seems irrelevant, just a flag\n step,\n stepsCount : Math.ceil( tN * ( t - tA )/( tB - tA ) ),\n addToStepCount : 1, //adds an extra closing point at the end,\n //addedCssClass : ns.haz( ssD.repoConf[0], 'addedCssClass' ),\n stroke : measurementStroke,\n //for color, otherwise taken\n // from sDomF.getFixedColor( rgName )\n });\n }\n }",
"function drawCornerCurve (xFrom, yFrom, xTo, yTo, bendDown, attr, doubleCurve, shiftx1, shifty1, shiftx2, shifty2 ) {\n var xDistance = xTo - xFrom;\n var yDistance = yFrom - yTo;\n\n var dist1x = xDistance/2;\n var dist2x = xDistance/10;\n var dist1y = yDistance/2;\n var dist2y = yDistance/10;\n\n var curve;\n\n if (bendDown) {\n var raphaelPath = 'M ' + (xFrom) + ' ' + (yFrom) +\n ' C ' + (xFrom + dist1x) + ' ' + (yFrom + dist2y) +\n ' ' + (xTo + dist2x) + ' ' + (yTo + dist1y) +\n ' ' + (xTo) + ' ' + (yTo);\n curve = editor.getPaper().path(raphaelPath).attr(attr).toBack();\n } else {\n var raphaelPath = 'M ' + (xFrom) + ' ' + (yFrom) +\n ' C ' + (xFrom - dist2x) + ' ' + (yFrom - dist1y) +\n ' ' + (xTo - dist1x) + ' ' + (yTo - dist2y) +\n ' ' + (xTo) + ' ' + (yTo);\n curve = editor.getPaper().path(raphaelPath).attr(attr).toBack();\n }\n\n if (doubleCurve) {\n var curve2 = curve.clone().toBack();\n curve .transform('t ' + shiftx1 + ',' + shifty1 + '...');\n curve2.transform('t ' + shiftx2 + ',' + shifty2 + '...');\n }\n}",
"static CreateHermiteSpline(p1, t1, p2, t2, nbPoints) {\n const hermite = new Array();\n const step = 1.0 / nbPoints;\n for (let i = 0; i <= nbPoints; i++) {\n hermite.push(Vector3_1$2.Vector3.Hermite(p1, t1, p2, t2, i * step));\n }\n return new Curve3(hermite);\n }",
"function generateECDSA(curve) {\n\t\tvar parts = [];\n\t\tvar key;\n\t\n\t\tif (CRYPTO_HAVE_ECDH) {\n\t\t\t/*\n\t\t\t * Node crypto doesn't expose key generation directly, but the\n\t\t\t * ECDH instances can generate keys. It turns out this just\n\t\t\t * calls into the OpenSSL generic key generator, and we can\n\t\t\t * read its output happily without doing an actual DH. So we\n\t\t\t * use that here.\n\t\t\t */\n\t\t\tvar osCurve = {\n\t\t\t\t'nistp256': 'prime256v1',\n\t\t\t\t'nistp384': 'secp384r1',\n\t\t\t\t'nistp521': 'secp521r1'\n\t\t\t}[curve];\n\t\n\t\t\tvar dh = crypto.createECDH(osCurve);\n\t\t\tdh.generateKeys();\n\t\n\t\t\tparts.push({name: 'curve',\n\t\t\t data: new Buffer(curve)});\n\t\t\tparts.push({name: 'Q', data: dh.getPublicKey()});\n\t\t\tparts.push({name: 'd', data: dh.getPrivateKey()});\n\t\n\t\t\tkey = new PrivateKey({\n\t\t\t\ttype: 'ecdsa',\n\t\t\t\tcurve: curve,\n\t\t\t\tparts: parts\n\t\t\t});\n\t\t\treturn (key);\n\t\t} else {\n\t\t\tif (ecdh === undefined)\n\t\t\t\tecdh = __webpack_require__(515);\n\t\t\tif (ec === undefined)\n\t\t\t\tec = __webpack_require__(172);\n\t\t\tif (jsbn === undefined)\n\t\t\t\tjsbn = __webpack_require__(105).BigInteger;\n\t\n\t\t\tvar ecParams = new X9ECParameters(curve);\n\t\n\t\t\t/* This algorithm taken from FIPS PUB 186-4 (section B.4.1) */\n\t\t\tvar n = ecParams.getN();\n\t\t\t/*\n\t\t\t * The crypto.randomBytes() function can only give us whole\n\t\t\t * bytes, so taking a nod from X9.62, we round up.\n\t\t\t */\n\t\t\tvar cByteLen = Math.ceil((n.bitLength() + 64) / 8);\n\t\t\tvar c = new jsbn(crypto.randomBytes(cByteLen));\n\t\n\t\t\tvar n1 = n.subtract(jsbn.ONE);\n\t\t\tvar priv = c.mod(n1).add(jsbn.ONE);\n\t\t\tvar pub = ecParams.getG().multiply(priv);\n\t\n\t\t\tpriv = new Buffer(priv.toByteArray());\n\t\t\tpub = new Buffer(ecParams.getCurve().\n\t\t\t encodePointHex(pub), 'hex');\n\t\n\t\t\tparts.push({name: 'curve', data: new Buffer(curve)});\n\t\t\tparts.push({name: 'Q', data: pub});\n\t\t\tparts.push({name: 'd', data: priv});\n\t\n\t\t\tkey = new PrivateKey({\n\t\t\t\ttype: 'ecdsa',\n\t\t\t\tcurve: curve,\n\t\t\t\tparts: parts\n\t\t\t});\n\t\t\treturn (key);\n\t\t}\n\t}",
"function drawBezierCurve(context, p1x, p1y, p2x, p2y, p3x, p3y, p4x, p4y, lines) {\r\n const bezierMatrix = [[-1, 3, -3, 1], [3, -6, 3, 0], [-3, 3, 0, 0], [1, 0, 0, 0]];\r\n const pointVectorX = [p1x, p2x, p3x, p4x];\r\n const pointVectorY = [p1y, p2y, p3y, p4y];\r\n\r\n const cx = multiplyMatrixByVector(bezierMatrix, pointVectorX);\r\n const cy = multiplyMatrixByVector(bezierMatrix, pointVectorY);\r\n\r\n step = 1/lines;\r\n for(let t = 0; Math.floor((t+step)*100)/100 <= 1; t+=step) {\r\n let startX = calculateCurvePoint(cx, 1-t);\r\n let startY = calculateCurvePoint(cy, 1-t);\r\n let endX = calculateCurvePoint(cx, 1-(t+step));\r\n let endY = calculateCurvePoint(cy, 1-(t+step));\r\n\r\n drawLine(context, startX, startY, endX, endY);\r\n if(Math.floor((t+step)*100)/100 === 1)\r\n break\r\n }\r\n}",
"function gras_chart_factory_make(registry, args)\n{\n //create containers\n var chart_box = $('<table />').attr({class:'chart_container'});\n var tr = $('<tr />');\n var td = $('<td />');\n tr.append(td);\n\n //call into the factory\n try\n {\n var chart = new registry.chart_factories[args.chart_type](args, td.get(0));\n }\n catch(err)\n {\n return;\n }\n\n //setup the title\n var tr_title = $('<tr />');\n var th_title = $('<th />');\n tr_title.append(th_title);\n th_title.text(chart.title);\n\n //register the chart\n var chart_info = {chart:chart,args:args,panel:chart_box};\n registry.active_charts.push(chart_info);\n $('#charts_panel').append(chart_box);\n\n //close button\n var close_div = $('<div/>').attr({class:'chart_designer_block_close'});\n var close_href = $('<a />').attr({href:'#', class:\"ui-dialog-titlebar-close ui-corner-all\", role:\"button\"});\n var close_span = $('<span />').attr({class:\"ui-icon ui-icon-closethick\"}).text('close');\n close_div.append(close_href);\n close_href.append(close_span);\n th_title.append(close_div);\n $(close_href).click(function()\n {\n var index = $.inArray(chart_info, registry.active_charts);\n registry.active_charts.splice(index, 1);\n chart_box.remove();\n gras_chart_save(registry);\n });\n gras_chart_save(registry);\n\n //finish gui building\n chart_box.append(tr_title);\n chart_box.append(tr);\n\n //implement draggable and resizable from jquery ui\n var handle_stop = function(event, ui)\n {\n args['width'] = chart_box.width();\n args['height'] = chart_box.height();\n args['position'] = chart_box.offset();\n chart.gc_resize = false;\n chart.update(registry.point);\n gras_chart_save(registry);\n };\n\n if ('default_width' in chart) chart_box.width(chart.default_width);\n chart_box.resizable({stop: handle_stop, create: function(event, ui)\n {\n if ('width' in args) chart_box.width(args.width);\n if ('height' in args) chart_box.height(args.height);\n },\n start: function(event, ui)\n {\n chart.gc_resize = true;\n chart.update(registry.point);\n }});\n\n chart_box.css('position', 'absolute');\n chart_box.draggable({stop: handle_stop, create: function(event, ui)\n {\n if ('position' in args) chart_box.offset(args.position);\n }, cursor: \"move\"});\n\n //set the cursor on the title bar so its obvious\n tr_title.hover(\n function(){$(this).css('cursor','move'); close_div.show();},\n function(){$(this).css('cursor','auto'); close_div.hide();}\n );\n close_div.hide();\n}",
"function bezier(p1x, p1y, p2x, p2y) {\n var bezier = new unitbezier(p1x, p1y, p2x, p2y);\n return function (t) {\n return bezier.solve(t);\n };\n }",
"function drawCurve() {\n\tfor(let i=0;i<curvePts.length-1;i++) {\n\t\tlet pt1 = curvePts[i];\n\t\tlet pt2 = curvePts[i+1];\n\t\tdrawLine(pt1.x, pt1.y, pt2.x, pt2.y, 'rgb(0,255,0)');\n\t}\n}",
"decompose() {\n let Q = this.decomposeU();\n // Using Q, create Bezier strip surfaces. These are individual BSurf objects\n // Their u curve will be bezier, but will still be expressed as BSpline\n // Their v curve will still be bspline\n let L = 2 * (this.u_degree + 1);\n let u_bez_knots = common_1.empty(L);\n for (let i = 0; i < this.u_degree + 1; i++) {\n u_bez_knots.set(i, 0);\n u_bez_knots.set(L - i - 1, 1);\n }\n let bezStrips = [];\n for (let numUBez = 0; numUBez < Q.length; numUBez++) {\n let cpoints = Q.getA(numUBez);\n bezStrips.push(new BSplineSurface(this.u_degree, this.v_degree, u_bez_knots, this.v_knots, cpoints));\n }\n let bezSurfs = [];\n // Decompose each bezier strip along v\n for (let bezStrip of bezStrips) {\n let Q = bezStrip.decomposeV();\n for (let numUBez = 0; numUBez < Q.length; numUBez++) {\n let cpoints = Q.getA(numUBez);\n bezSurfs.push(new BezierSurface(this.u_degree, this.v_degree, cpoints));\n }\n }\n return bezSurfs;\n }",
"function makeTestChemicalEquation(reacts, prods){\n let eq = {};\n eq[EQUATION_PROPERTY_REACTANTS] = reacts;\n eq[EQUATION_PROPERTY_PRODUCTS] = prods;\n return eq;\n}",
"function generateCubicPoints(offset, length, elevation, sx, sy, hdg, lateralOffset) {\n\n\tvar x, y, z;\n\tvar points = [];\n\tvar tOffset = [];\n\tvar sOffset = [];\t// each point's s distance from the begining of the cubic curve\n\n\tvar ds = 0;\n\n\tdo {\n\n\t\tif (ds > length || Math.abs(ds - length) < 1E-4) {\n\t\t\tds = length;\n\t\t}\n\n\t\tx = sx + (ds + offset) * Math.cos(hdg);\n\t\ty = sy + (ds + offset) * Math.sin(hdg);\n\t\tz = cubicPolynomial(ds + offset, elevation.a, elevation.b, elevation.c, elevation.d);\n\n\t\tpoints.push(new THREE.Vector3(x, y, z));\n\t\tsOffset.push(ds + offset);\n\t\tif (lateralOffset) tOffset.push(cubicPolynomial(ds + offset, lateralOffset.a, lateralOffset.b, lateralOffset.c, lateralOffset.d));\n\t\n\t\tds += step;\n\t\n\t} while(ds < length + step);\n\n\tif (lateralOffset) {\n\n\t\tfor (var i = 0; i < points.length; i++) {\n\t\t\n\t\t\tvar point = points[i];\n\t\t\tvar t = tOffset[i];\n\t\t\tvar ds = sOffset[i];\n\n\t\t\tsvector = new THREE.Vector3(1, 0, 0);\n\t\t\tsvector.applyAxisAngle(new THREE.Vector3(0, 0, 1), hdg);\n\t\t\ttvector = svector.clone();\n\t\t\ttvector.cross(new THREE.Vector3(0, 0, -1));\n\t\t\thvector = svector.clone();\n\t\t\thvector.cross(tvector);\n\n\t\t\ttvector.multiplyScalar(t);\n\t\t\thvector.multiplyScalar(0);\t// no height\n\n\t\t\tpoint.x += tvector.x + hvector.x;\n\t\t\tpoint.y += tvector.y + hvector.y;\n\t\t\tpoint.z += tvector.z + hvector.z;\n\t\t}\n\t}\n\n\treturn points;\n}",
"continue(curve) {\n const lastPoint = this._points[this._points.length - 1];\n const continuedPoints = this._points.slice();\n const curvePoints = curve.getPoints();\n for (let i = 1; i < curvePoints.length; i++) {\n continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));\n }\n const continuedCurve = new Curve3(continuedPoints);\n return continuedCurve;\n }",
"function bezierCurve(u, q){\n\tvar B = bern3;\n\tvar n = 4;\n\n\tvar p = vec3(0,0,0);\n\n\tfor(var i=0; i<n; i++){\n\t\tp = add(p, scale(B(i, u), q[i]));\n\n\t}\n\n\treturn p;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clear the user projection if set. Note that this method is not yet a part of the stable API. Support for user projections is not yet complete and should be considered experimental. | function clearUserProjection() {
userProjection = null;
} | [
"function unproject(coord) {\n return map.unproject(coord, map.getMaxZoom());\n}",
"unproject(xy) {\n Object(_utils_assert__WEBPACK_IMPORTED_MODULE_10__[\"default\"])(this.internalState);\n const viewport = this.internalState.viewport || this.context.viewport;\n return viewport.unproject(xy);\n }",
"toDefaultProjection(lat, long) {\n return ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857');\n }",
"clearSourceSelections() {\n this.mappingSelectionsService_.removeSourceProvider(\n this.selectedSourceProviderId);\n }",
"function clearLat() {\n lat = [];\n}",
"function resetSelectedRegion() {\n selectedRegion = undefined\n }",
"function preserveOriginalCRS(dataset, jsonObj) {\n var info = dataset.info || {};\n if (!info.crs && 'input_geojson_crs' in info) {\n // use input geojson crs if available and coords have not changed\n jsonObj.crs = info.input_geojson_crs;\n\n }\n\n // Removing the following (seems ineffectual at best)\n // else if (info.crs && !isLatLngCRS(info.crs)) {\n // // Setting output crs to null if coords have been projected\n // // \"If the value of CRS is null, no CRS can be assumed\"\n // // source: http://geojson.org/geojson-spec.html#coordinate-reference-system-objects\n // jsonObj.crs = null;\n // }\n}",
"function clearExistingProposalCoordinators() {\n\t$j('#' + propCoordId).empty();\n}",
"function clearUserForm() {\n setErrorMessages([])\n setUserData(emptyUserFormData)\n }",
"function resetData() {\n geoJSON = {\n type: \"FeatureCollection\",\n features: []\n };\n myMap.data.forEach(function(feature) {\n myMap.data.remove(feature);\n });\n }",
"function emptyUserForm(){\n\t\t$scope.user ={};\n\t\t$scope.useremailexist = false;\n\t\t$scope.usernamexist = false;\n\t}",
"function clearSelectedPoints () {\n\tselectedPoints = [];\n}",
"function reset() {\n var bottomLeft = project(bounds[0]),\n topRight = project(bounds[1]);\n\n svg.attr(\"width\", topRight[0] - bottomLeft[0])\n .attr(\"height\", bottomLeft[1] - topRight[1])\n .style(\"margin-left\", bottomLeft[0] + \"px\")\n .style(\"margin-top\", topRight[1] + \"px\");\n\n g.attr(\"transform\", \"translate(\" + -bottomLeft[0] + \",\" + -topRight[1] + \")\");\n feature.attr(\"d\", path);\n }",
"clear() {\n this.context.clearRect(\n this.frame.x / this.getZoomFactor(), \n this.frame.y / this.getZoomFactor(), \n this.frame.w / this.getZoomFactor(), \n this.frame.h / this.getZoomFactor()\n );\n }",
"function reset() {\n var browserWidth = $(window).width();\n if(browserWidth <= 1000) {\n map.setCenter(mapOptions.center);\n map.setZoom(11);\n } else if(browserWidth > 1000) {\n map.setCenter(mapOptions.center);\n map.setZoom(12);\n }\n }",
"function cleanMap() {\n\n\t// Disable position selection by mouse click.\n\tdisablePositionSelect();\n\n\t// Remove existing nearby stations layer.\n\tif (map.getLayersByName(\"Nearby Docking Stations\")[0] != null)\n\t\tmap.removeLayer(map.getLayersByName(\"Nearby Docking Stations\")[0]);\n\t\t\n\t// Reset select controls.\n\tif (selectControl !=null) {\n\t\tselectControl.unselectAll();\n\t\tselectControl.deactivate();\n\t}\n \tif (selIncControl !=null) {\n\t\tselIncControl.unselectAll();\n\t\tselIncControl.deactivate();\n\t}\n \tif (voteControl !=null) {\n\t\tvoteControl.unselectAll();\n\t\tvoteControl.deactivate();\n\t} \n\tif (selectDockControl != null) {\n\t\tselectDockControl.unselectAll();\n\t\tselectDockControl.deactivate();\n\t}\n\n\tif (distr_stats != null)\n\t\tmap.removeLayer(distr_stats);\n}",
"clearAllZoomRegions() {\n for (let i = 0; i < this._zoomRegions.length; i++)\n this._zoomRegions[i].setActive(false);\n\n this._zoomRegions.length = 0;\n this.stopTrackingMouse();\n this.showSystemCursor();\n }",
"function resetProject() {\n\tprojectManager.resetProject();\n // Reset ractive bindings\n setRactives();\n update();\n showProjectResetDialogue();\n}",
"function clearSelectedPointsCanvas() {\n\tvar selectedPointsCanvas = document.getElementById('select-points')\n\tvar selectedCtx = selectedPointsCanvas.getContext('2d')\n\tselectedCtx.clearRect(0, 0, selectedPointsCanvas.offsetWidth, selectedPointsCanvas.offsetHeight)\n}",
"function clearOrgunitAssignment() {\n\tfor (var i = 0; metaData.dataSets && i < metaData.dataSets.length; i++) {\n\t\tmetaData.dataSets[i].organisationUnits = [];\n\t}\n\n\tfor (var i = 0; metaData.programs && i < metaData.programs.length; i++) {\n\t\tmetaData.programs[i].organisationUnits = [];\n\t}\n\n\tfor (var i = 0; metaData.users && i < metaData.users.length; i++) {\n\t\tmetaData.users[i].organisationUnits = [];\n\t\tmetaData.users[i].dataViewOrganisationUnits = [];\n\t\tmetaData.users[i].teiSearchOrganisationUnits = [];\n\t}\n\n\n\tfor (var i = 0; metaData.hasOwnProperty(\"predictors\") && i < metaData.predictors.length; i++) {\n\t\tmetaData.predictors[i].organisationUnitLevels = [];\n\t}\n\t\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function compares the LEDs in pending to those in active and if there is a difference it will send them via MIDI message If there is more than 30 lights changed it sends the MIDI in a single message ("optimized mode") rather than individually | function flushLEDs()
{
// changedCount contains number of lights changed
var changedCount = 0;
// count the number of LEDs that are going to be changed by comparing pendingLEDs to activeLEDs array
for(var i=0; i<80; i++)
{
if (pendingLEDs[i] != activeLEDs[i]) changedCount++;
}
// exit function if there are none to be changed
if (changedCount == 0) return;
//uncommenting this displays a count of the number of LEDs to be changed
// //println("Repaint: " + changedCount + " LEDs");
for(var i = 0; i<80; i++)
{
if (pendingLEDs[i] != activeLEDs[i])
{
activeLEDs[i] = pendingLEDs[i];
var colour = activeLEDs[i];
if (i < 16) // Main Grid
{
var column = i & 0x7;
var row = i >> 3;
if (colour >=200 && colour < 328)//flashing colour numeration. need to substract 200 to get the appropriate final color
{
host.getMidiOutPort(1).sendMidi(0x92, 96 + row*16 + column, colour-200);
}
else
{
host.getMidiOutPort(1).sendMidi(0x9F, 96 + row*16 + column, colour);
}
}
else if (i>=64 && i < 66) // Right buttons
{
host.getMidiOutPort(1).sendMidi(0x9F, 96 + 8 + (i - 64) * 16, colour);
}
}
}
} | [
"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 updateLeds() {\n if (led_state.Red===\"blink\") {\n GPIO.blink(pin_Red, blink_On, blink_Off);\n }else {\n GPIO.blink(pin_Red,0,0); //Turn off blinking\n let redlight=(led_state.Red==='1') ? 1:0 ; \n GPIO.write(pin_Red,redlight);\n }\n if (led_state.Blue===\"blink\") {\n GPIO.blink(pin_Blue, blink_On, blink_Off);\n }else {\n GPIO.blink(pin_Blue,0,0); //Turn off blinking\n let bluelight=(led_state.Blue==='1') ? 1:0 ; \n GPIO.write(pin_Blue,bluelight);\n }\n}",
"compare() {\n let result1 = this.state.gameplayOne;\n let result2 = this.state.gameplayTwo;\n let win = [...this.state.win];\n\n // Setting arrays which will be filled by true or false since a winning combination is detected in the player's game.\n let tabTrueFalse1 = [];\n let tabTrueFalse2 = [];\n // winningLine may help to know which winning combination is on the set and then have an action on it. To think.\n let winningLine = [];\n\n if (this.state.gameplayOne.length >= 3) {\n tabTrueFalse1 = win.map(elt =>\n elt.every(element => result1.includes(element))\n );\n }\n if (this.state.gameplayTwo.length >= 3) {\n tabTrueFalse2 = win.map(elt =>\n elt.every(element => result2.includes(element))\n );\n }\n\n //Launching youWon()\n tabTrueFalse1.includes(true) ? this.youWon(1) : null;\n tabTrueFalse2.includes(true) ? this.youWon(2) : null;\n }",
"function checkstatus(t) {\n\tturnonlist = [];\n\tfor (f = 0; f < 10; f++) {\t\n\t\tfor (var key in buildingSnapshots[t][f]){\n\t\t\tvar obj = buildingSnapshots[t][f][key];\n\t\t\tfor (var prop in obj){\n\t\t\t\tif (obj[prop] === true) {\n\t\t\t\t\tturnonlist.push(key);\n\t\t\t\t} \n\t\t\t}\n\t\t}\n\t}\n\t//these are the rooms in the current time interval that need to be turned on\n\t//console.log(turnonlist);\n\tclearrooms();\n\tupdaterooms(turnonlist);\n}",
"async sendLocalState () {\n if (!this.device) throw new Error('Controller not initialized. You must call .init() first!')\n\n if (this.state.interface === 'usb') \n {\n const report = new Uint8Array(16);\n\n // Report ID\n report[0] = 0x05;\n\n // Enable Rumble (0x01), Lightbar (0x02)\n report[1] = 0xF0 | 0x01 | 0x02;\n\n // Light rumble motor\n report[4] = this.rumble.light;\n // Heavy rumble motor\n report[5] = this.rumble.heavy;\n \n // Lightbar Red\n report[6] = this.lightbar.r\n // Lightbar Green\n report[7] = this.lightbar.g\n // Lightbar Blue\n report[8] = this.lightbar.b\n\n this.lastSentReport = report.buffer\n\n return this.device.sendReport(report[0], report.slice(1))\n } \n else if (this.state.interface === 'bt') {\n const report = new Uint16Array(79)\n const crcBytes = new Uint8Array(4)\n const crcDv = new DataView(crcBytes.buffer)\n\n // Header\n report[0] = 0xA2\n // Report ID\n report[1] = 0x11\n\n // Poll Rate\n report[2] = 0x80\n // Enable rumble and lights\n report[4] = 0xFF\n\n // Light rumble motor\n report[7] = this.rumble.light\n // Heavy rumble motor\n report[8] = this.rumble.heavy\n\n // Lightbar Red\n report[9] = this.lightbar.r\n // Lightbar Green\n report[10] = this.lightbar.g\n // Lightbar Blue\n report[11] = this.lightbar.b\n\n crcDv.setUint32(0, this.crc32(new String(report.slice(0, 75))))\n report[75] = crcBytes[3]\n report[76] = crcBytes[2]\n report[77] = crcBytes[1]\n report[78] = crcBytes[0]\n \n this.lastSentReport = report.buffer\n\n return this.device.sendReport(report[1], report.slice(2))\n }\n }",
"function τSST_detect_buff_well_fed() {\n buffs_table.buff_msgs_summary = localStorage[storage_key_prefix + 'buffs_table_buff_messages'];\n \n var page_buffs_node = $(\".buff-messages\").find(\".timer-message\");\n if (page_buffs_node.length) {\n var buffs_list = buffs_table.buff_messages;\n var buffs_list_new = page_buffs_node.find(\"td:first\").map(function() {\n return $(this).text();\n }).get();\n\n var list_temp = [];\n var buff;\n\n while (buffs_list && buffs_list.length > 0) {\n buff = buffs_list.shift();\n if (buffs_list_new.includes(buff)) {\n list_temp.push(buff);\n }\n }\n buffs_list = list_temp;\n\n while (buffs_list_new.length > 0) {\n buff = buffs_list_new.shift();\n if (! buffs_list.includes(buff)) {\n buffs_list.push(buff);\n }\n }\n\n buffs_table.buff_messages = buffs_list;\n }\n\n // If this buff has changed, note the fact for our callers.\n buffs_table.buff_msgs_summary = buffs_table.buff_messages.join(',');\n if (localStorage[storage_key_prefix + 'buffs_table_buff_messages'] != buffs_table.buff_msgs_summary) {\n buffs_changed = true;\n }\n\n // Buff updates are stored only when actually updating a stat log.\n }",
"function compareRamp (activeObject) {\n if (activeObject.type == 'onRamp') {\n for (var i = 0; i < onRampArray.length; i++) {\n if (activeObject.member == onRampArray[i].id) {return onRampArray[i]; }\n }\n }\n else if (activeObject.type == 'offRamp') {\n for (var i = 0; i < offRampArray.length; i++) {\n if (activeObject.member == offRampArray[i].id) {return offRampArray[i]; }\n }\n }\n}",
"static find_status(action) {\n if (!Server.pending || file !== Server.pending.agenda) return null;\n let match = null;\n\n for (let status of Pending.status) {\n let found = true;\n\n for (let [name, value] of Object.entries(action)) {\n if (name !== \"status\" && value !== status[name]) found = false\n };\n\n if (found) match = status\n };\n\n return match\n }",
"function decode_light_control_status(data) {\n\tdata.command = 'bro';\n\tdata.value = 'light control status - ';\n\n\t// Examples\n\t//\n\t// D1 D2\n\t// 11 01 Intensity=1, Lights=on, Reason=Twilight\n\t// 21 02 Intensity=2, Lights=on, Reason=Darkness\n\t// 31 04 Intensity=3, Lights=on, Reason=Rain\n\t// 41 08 Intensity=4, Lights=on, Reason=Tunnel\n\t// 50 00 Intensity=5, Lights=off, Reason=N/A\n\t// 60 00 Intensity=6, Lights=off, Reason=N/A\n\t//\n\t// D1 - Lights on/off + intensity\n\t// 0x01 : Bit0 : Lights on\n\t// 0x10 : Bit4 : Intensity 1\n\t// 0x20 : Bit5 : Intensity 2\n\t// 0x30 : Bit4+Bit5 : Intensity 3\n\t// 0x40 : Bit6 : Intensity 4\n\t// 0x50 : Bit4+Bit6 : Intensity 5\n\t// 0x60 : Bit5+Bit6 : Intensity 6\n\t//\n\t// D2 - Reason\n\t// 0x01 : Bit0 : Twilight\n\t// 0x02 : Bit1 : Darkness\n\t// 0x04 : Bit2 : Rain\n\t// 0x08 : Bit3 : Tunnel\n\t// 0x10 : Bit4 : Garage\n\n\tconst mask1 = bitmask.check(data.msg[1]).mask;\n\tconst mask2 = bitmask.check(data.msg[2]).mask;\n\n\tconst parse = {\n\t\tintensity : null,\n\t\tintensity_str : null,\n\t\tintensities : {\n\t\t\tl1 : mask1.bit4 && !mask1.bit5 && !mask1.bit6 && !mask1.bit8,\n\t\t\tl2 : !mask1.bit4 && mask1.bit5 && !mask1.bit6 && !mask1.bit8,\n\t\t\tl3 : mask1.bit4 && mask1.bit5 && !mask1.bit6 && !mask1.bit8,\n\t\t\tl4 : !mask1.bit4 && !mask1.bit5 && mask1.bit6 && !mask1.bit8,\n\t\t\tl5 : mask1.bit4 && !mask1.bit5 && mask1.bit6 && !mask1.bit8,\n\t\t\tl6 : !mask1.bit4 && mask1.bit5 && mask1.bit6 && !mask1.bit8,\n\t\t\tl0 : !mask1.bit4 && !mask1.bit5 && !mask1.bit6 && mask1.bit8,\n\t\t},\n\n\t\tlights : mask1.bit0,\n\t\tlights_str : 'lights on: ' + mask1.bit0,\n\n\t\treason : null,\n\t\treason_str : null,\n\t\treasons : {\n\t\t\ttwilight : mask2.bit0 && !mask2.bit1 && !mask2.bit2 && !mask2.bit3 && !mask2.bit4 && !mask2.bit8,\n\t\t\tdarkness : !mask2.bit0 && mask2.bit1 && !mask2.bit2 && !mask2.bit3 && !mask2.bit4 && !mask2.bit8,\n\t\t\train : !mask2.bit0 && !mask2.bit1 && mask2.bit2 && !mask2.bit3 && !mask2.bit4 && !mask2.bit8,\n\t\t\ttunnel : !mask2.bit0 && !mask2.bit1 && !mask2.bit2 && mask2.bit3 && !mask2.bit4 && !mask2.bit8,\n\t\t\tgarage : !mask2.bit0 && !mask2.bit1 && !mask2.bit2 && !mask2.bit3 && mask2.bit4 && !mask2.bit8,\n\t\t\tnone : !mask2.bit0 && !mask2.bit1 && !mask2.bit2 && !mask2.bit3 && !mask2.bit4 && mask2.bit8,\n\t\t},\n\t};\n\n\t// Loop intensity object to obtain intensity level\n\tfor (const intensity in parse.intensities) {\n\t\tif (parse.intensities[intensity] === true) {\n\t\t\t// Convert hacky object key name back to integer\n\t\t\tparse.intensity = parseInt(intensity.replace(/\\D/g, ''));\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Loop reason object to obtain reason name\n\tfor (const reason in parse.reasons) {\n\t\tif (parse.reasons[reason] === true) {\n\t\t\tparse.reason = reason;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Append prefixes to log strings\n\tparse.intensity_str = 'intensity: ' + parse.intensity;\n\tparse.reason_str = 'reason: ' + parse.reason;\n\n\tupdate.status('rls.light.intensity', parse.intensity, false);\n\tupdate.status('rls.light.lights', parse.lights, false);\n\tupdate.status('rls.light.reason', parse.reason, false);\n\n\t// Assemble log string\n\tdata.value += parse.intensity_str + ', ' + parse.lights_str + ', ' + parse.reason_str;\n\n\treturn data;\n}",
"function drawStatusLED()\n {\n // Check faulted state\n var faultCount = Object.keys(fault_detector.getCurrentFaults()).length;\n if (faultCount > 0)\n {\n // Set LED to green\n image = document.getElementById('status_led');\n image.src = 'static/images/red_light.png';\n }\n else\n {\n image = document.getElementById('status_led');\n image.src = 'static/images/green_light.png';\n }\n }",
"function toggleCabinetLEDs() {\n\n\t if( cabinets === 0 ) {\n\t cabinet_leds.writeSync( 1 );\n\t cabinets = 1;\n\t } else {\n\t cabinet_leds.writeSync( 0 );\n\t cabinets = 0;\n\t }\n\n\t sendReturn();\n\n\t}",
"function switchStatus(lobby) {\n getGame(lobby).status = (getStatus(lobby) == 0)? 1: 0;\n}",
"changeLedsColor(binaryNumber) {\n\n let ledList = this.state.leds;\n let binaryString = binaryNumber.toString();\n\n let binaryDiff = 8 - binaryString.length;\n\n for (let i=0;i<binaryDiff;i++) {\n ledList[i].color = 'grey';\n }\n\n for (let i=0;i<binaryString.length;i++) {\n let ledIndex = i + binaryDiff;\n\n if (binaryString.charAt(i) === '1') {\n ledList[ledIndex].color = 'green';\n } else {\n ledList[ledIndex].color = 'grey';\n }\n }\n\n this.setState({leds: ledList});\n }",
"validateActivityStatus() {\r\n let res = this.state.selectedData.every((livestock) => {\r\n return !(livestock.ActivitySystemCode == livestockActivityStatusCodes.Deceased ||\r\n livestock.ActivitySystemCode == livestockActivityStatusCodes.Killed ||\r\n livestock.ActivitySystemCode == livestockActivityStatusCodes.Lost);\r\n });\r\n if (!res) this.notifyToaster(NOTIFY_WARNING, { message: this.strings.INVALID_RECORD_LOST_STATUS });\r\n return res;\r\n }",
"function lookupNewLed() {\n got(LED_URL)\n .then(response => {\n //console.log(\"API call finished with response: \"+response.body);\n if (response.body) {\n try {\n temp = new Number(response.body);\n //console.log(\"Temp: \"+temp);\n if (temp >= 0 && temp < strip.length) {\n setCurrentLed(temp);\n }\n } catch (e) {\n console.log(\"Invalid number returned from the API: \" + e.message);\n }\n }\n })\n .catch(err => {\n console.error(err);\n });\n}",
"function detect_changes(initial) {\n\tvar current = parse_model();\n\tvar changes = [];\n\t\n\tfor (var team_num = 0; team_num < current.teams.length; team_num++) {\n\t\tvar old_team = initial.teams[team_num];\n\t\tvar new_team = current.teams[team_num];\n\t\tif (!old_team) {\n\t\t\tchanges.push({\n\t\t\t\taction: 'create-team',\n\t\t\t\tteam_number: new_team.number,\n\t\t\t\tmodel: new_team\n\t\t\t});\n\t\t} else {\n\t\t\tif (old_team.name !== new_team.name) {\n\t\t\t\tchanges.push({\n\t\t\t\t\taction: 'change-team',\n\t\t\t\t\tteam_number: new_team.number,\n\t\t\t\t\tteam_name: new_team.name\n\t\t\t\t});\n\t\t\t}\n\t\t\tfor (var board_num = 0; board_num < current.board_count; board_num++) {\n\t\t\t\tvar old_player = old_team.boards[board_num];\n\t\t\t\tvar new_player = new_team.boards[board_num];\n\t\t\t\tif (old_player === null && new_player === null) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (old_player === null || new_player === null\n\t\t\t\t\t\t|| old_player.name != new_player.name\n\t\t\t\t\t\t|| old_player.is_captain != new_player.is_captain\n\t\t\t\t\t\t|| old_player.is_vice_captain != new_player.is_vice_captain) {\n\t\t\t\t\tchanges.push({\n\t\t\t\t\t\taction: 'change-member',\n\t\t\t\t\t\tteam_number: new_team.number,\n\t\t\t\t\t\tboard_number: board_num + 1,\n\t\t\t\t\t\tplayer: new_player\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfor (var board_num = 0; board_num < current.board_count; board_num++) {\n\t\tvar old_alt_list = initial.alternates[board_num];\n\t\tvar new_alt_list = current.alternates[board_num];\n\t\tvar old_names = {};\n\t\t$.each(old_alt_list, function() {\n\t\t\told_names[this.name] = this;\n\t\t});\n\t\t$.each(new_alt_list, function() {\n\t\t\tif (this.name in old_names) {\n\t\t\t\tdelete old_names[this.name];\n\t\t\t} else {\n\t\t\t\tchanges.push({\n\t\t\t\t\taction: 'create-alternate',\n\t\t\t\t\tboard_number: board_num + 1,\n\t\t\t\t\tplayer_name: this.name\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t\t$.each(old_names, function() {\n\t\t\tchanges.push({\n\t\t\t\taction: 'delete-alternate',\n\t\t\t\tboard_number: board_num + 1,\n\t\t\t\tplayer_name: this.name\n\t\t\t});\n\t\t});\n\t}\n\t\n\treturn changes;\n}",
"function initializeLEDs() {\r\n \r\n greenLed.writeSync(0)\r\n redLed.writeSync(0)\r\n\r\n}",
"setYellowLights() {\n\t\t// Get the array traffic lights from the config\n\t\tlet lights = this.config.getDirections()[this.getDirectionIndex()];\n\n\t\t// Set the traffic lights to green based on the direction of the traffic\n\t\tlights.map((direction) => {this.trafficLights[direction].color = TRAFFIC_LIGHT_YELLOW;});\n\n\t\t// Set the color of the traffic lights visually and print a log\n\t\tthis.draw.traffic(this.getTrafficLights());\n\t}",
"checkActionStatus() {\n if (this.state >= SolairesAction.STATUS.DONE)\n return;\n if (this.state == SolairesAction.STATUS.ACK)\n SolairesAction.updateGMAck(false);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
allow a user to delete a habit | async function deleteHabit(req, res) {
await Habit.findByIdAndDelete(req.params.id);
show(req, res);
} | [
"'click .delete'() {\n\t\tMeteor.call('tasks.remove', this._id, (error) => {\n\t\t\tif (error)\n\t\t\t\tBert.alert( 'An error occured: ' + error.reason + '! Only the creator of the task can delete it.', 'danger', 'growl-top-right' );\n\t\t\telse\n\t\t\t\tBert.alert( 'Task removed successfully!', 'success', 'growl-top-right' );\n\t\t});\n\t}",
"function deleteButtonPressed(entity) {\n db.remove(entity);\n }",
"function deleteExpense(id) {\n console.log(\"DELETE BUTTON WORKS\");\n }",
"function confirmDelete(row){\n console.log(\"row = \", row)\n setSelectedPetId(row.petId);\n setSelectedPetName(row.name);\n setGuestId(row.guestId);\n setConfirmDeleteVisible(true);\n console.log('deleting row:', row);\n }",
"function deleteView(superviseesData) {\n var deleteIcon = app.getElement(\".icon_delete\");\n\n for (var i = 0; i < deleteIcon.length; i++) {\n deleteIcon[i].addEventListener(\"click\", function() {\n empId = this.getAttribute(\"data-emp\");\n app.modalDisplayTrue(deleteModalView);\n deleteModalText.innerHTML = \"Confirm Delete?\";\n app.modalDisplayTrue(deleteYes);\n app.modalDisplayTrue(deleteNo);\n okDeleteBtn.classList.add(\"display_none\");\n registerDeleteEvent(superviseesData, empId);\n });\n }\n }",
"onDeleteHobby(indexNoHobby) {\n const { hobbyTrait } = this.state;\n const newHobbyTrait = { ...hobbyTrait };\n newHobbyTrait.traits.data.splice(indexNoHobby, 1);\n this.setState({\n hobbyTrait: newHobbyTrait,\n });\n\n const {\n handle,\n tokenV3,\n updateUserTrait,\n deleteUserTrait,\n } = this.props;\n\n if (newHobbyTrait.traits.data.length > 0) {\n updateUserTrait(handle, 'hobby', newHobbyTrait.traits.data, tokenV3);\n } else {\n deleteUserTrait(handle, 'hobby', tokenV3);\n }\n this.setState({\n showConfirmationHobby: false,\n isHobbyEdit: false,\n indexNoHobby: null,\n isSubmitHobby: false,\n });\n }",
"deleteTodo() {\n\t let todo = this.get('todo');\n\t this.sendAction('deleteTodo', todo);\n\t }",
"function deleteFunction() {\n inquirer.prompt([{\n type: \"list\",\n message: \"Make a Selection:\",\n name: \"choice\",\n choices: [\n \"Delete Employee\",\n \"Delete Role\",\n \"Delete Department\"\n ]\n }]).then(function (event) {\n switch (event.choice) {\n case \"Delete Department\":\n deleteDepartment();\n break;\n case \"Delete Role\":\n deleteRole();\n break;\n case \"Delete Employee\":\n deleteEmployee();\n break;\n\n }\n })\n}",
"function deleteTrain() {\n if (CurrentUser === undefined || CurrentUser === null) {\n $('#authModal').modal(); // Restrict access to logged in users only. \n return;\n }\n\n var uniqueKey = $(this).closest('tr').data('key');\n var childRef = dbRef.child(uniqueKey);\n\n childRef.remove().then(function () {\n console.log(\"Remove succeeded.\");\n\n }).catch(function (error) {\n console.log(\"Remove failed: \" + error.message);\n });\n\n $(this).closest('tr').remove();\n}",
"function viewTaskdeleteThisTask() {\r\n if (confirm(\"You are about to delete this task?\")) {\r\n // Get taskobject === clicked taskCard\r\n TempLocalStorageTaskArray = getLocalStorage(\"task\");\r\n tempIndex = TempLocalStorageTaskArray.findIndex(obj => obj.name === viewTaskTitleDiv.innerHTML);\r\n //delete from localstorage where thisTask === \"task\".name\r\n // finn index og splice fra array\r\n TempLocalStorageTaskArray.splice(tempIndex, 1);\r\n setLocalStorage(\"task\", TempLocalStorageTaskArray);\r\n } else {\r\n console.log('no task was deleted');\r\n }\r\n\r\n\r\n}",
"handleDeleteItems(e){\n\t\tconst id = e.target.attributes.keyset.value\n\t\tActions.deleteTodo(id)\n\t}",
"function deleteRole() {\n db.query(`SELECT * FROM role`, (err, data) => {\n if (err) throw err;\n\n const roles = data.map(({\n id,\n title\n }) => ({\n name: title,\n value: id\n }));\n //inquirer prompt that presents a list of roles to choose from\n inquirer.prompt([{\n type: 'list',\n name: 'name',\n message: \"Select a Role to remove\",\n choices: roles\n }])\n .then(event => {\n db.query(`DELETE FROM role WHERE role.id = ${event.name} `, (err, result) => {\n if (err) throw err;\n console.log(\"Role has been removed from the database.\");\n\n initPrompt();\n });\n });\n });\n}",
"function deleteVassalOnClick(e){\r\n // Remove the element\r\n g_vassals.splice(parseInt(e.currentTarget.parentNode.id.split('vassal_')[1]), 1);\r\n\r\n setVassals();\r\n setVassalTable();\r\n}",
"function deleteAgencyOrProgram() {\n\t\n\tvar r = confirm(\"Are you sure you want to permanently DELETE this program/agency?\");\n\tdocument.getElementById('editDBform').action = 'sql/remove/super_remover.php';\n\treturn r;\n}",
"function deleteToDo(position){\r\ntoDos.splice(position, 1);\r\ndisplayToDos();\r\n}",
"function handleDeleteIdea() {\n $('body').on(\"click\", \".js-delete-idea-btn\", (event) => {\n var result = confirm(\"Are you sure you want to delete this idea?\");\n if (result) {\n const ideaID = $(event.currentTarget).data('id');\n deleteIdea({ jwToken: user, ideaID, onSuccess: getAndDisplayIdeas, onError: \"\" });\n }\n });\n}",
"function handleDelete(event) {\n\tlet id = event.target.id;\n\n\tlet output = [];\n\n\toutput = db_appointments.filter(function (value) {\n\t\treturn value.idPengunjung !== id;\n\t});\n\n\tdb_appointments = output;\n\n\tevent.target.parentElement.remove();\n}",
"function erase(e) {\n database.database_call(`DELETE FROM subnote WHERE id=${id} `);\n alerted.note(\"The current note was deleted!\", 1);\n Alloy.Globals.RenderSubNotesAgain();\n $.view_subnotes.close();\n}",
"function del()\n{\n var r = confirm(\"¿Estas seguro de eliminar?\");\n\n if(r == true)\n {\n agenda.results.splice(index, 1);\n primer();\n }\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
chat equivalents : To = 2 Today = 2day Tomorrow = 2mrw Please = pls Because = b/c With = w/ Without = w/o Before = b4 Great = gr8 Ate = 8 Okay/Ok = k People = ppl For = 4 Be = b See = c Owe = o Are = r You = u Why = y About = abt Awesome = awsm Birthday = b/day Check = chk Could = cd Should = shd Would = wd Disconnect = dc Enough = enuf | function chatify( tweetSize , words ){
chatEq = {};
for( i =0; i < words.length; i++ ){
chatWord = getChatWord( words[i] );
if( chatWord != words[i] ){
chatEq[ words[i] ] = chatWord;
reducedWordSize = words[ i ].length - chatWord.length;
tweetSize = tweetSize - reducedWordSize;
}
if( tweetSize <= 140 )
break;
}
return chatEq;
} | [
"function processSentence(nama, age, address, hobby){\n \n return 'Nama saya ' + nama +', umur saya '+ age +' tahun, alamat saya di ' +address +', dan saya punya hobby yaitu '+ hobby\n \n}",
"function messageData(user, text){\n text = text.replace(':)', '\\uD83D\\uDE00')\n text = text.replace(':(', '\\uD83D\\uDE41')\n text = text.replace(':o', '\\uD83D\\uDE2E')\n return{\n user, \n text,\n time: moment().format('h:mm a')\n }\n}",
"function chatbotResponse() {\n talking = true;\n botMessage = \"I'm confused\"; //the default message\n\n if (lastUserMessage === 'hey' || lastUserMessage =='hello'||lastUserMessage =='hii'||lastUserMessage =='hi'||lastUserMessage =='howdy'||lastUserMessage =='hey bro'||lastUserMessage =='pranam'||lastUserMessage =='namaste') {\n const hi = ['hii dear','Pranam','hello']\n botMessage = hi[Math.floor(Math.random()*(hi.length))];;\n }\n if (lastUserMessage === 'Virtual Travellers' || lastUserMessage =='Arya'||lastUserMessage =='geetika'||lastUserMessage =='rohan'||lastUserMessage =='prateek'||lastUserMessage =='anonymous'||lastUserMessage =='meghana'||lastUserMessage =='nikhita'||lastUserMessage =='pateswar'||lastUserMessage =='gurpreet'||lastUserMessage =='adarsh'||lastUserMessage =='deven'||lastUserMessage =='aishwarya'||lastUserMessage =='ishiqa'||lastUserMessage =='vishnu'||lastUserMessage =='aman'||lastUserMessage =='sukhi') {\n const hi = ['hi','howdy','hello']\n botMessage = hi[Math.floor(Math.random()*(hi.length))];;\n }\n if (lastUserMessage === 'rajasthan' || lastUserMessage =='india') {\n const hi = ['Khama Ghani','Padharo mare desh','hello']\n botMessage = hi[Math.floor(Math.random()*(hi.length))];;\n }\n if (lastUserMessage === 'will you help me?' || lastUserMessage =='help?'||lastUserMessage =='can you help me?') {\n const hi = ['Yes, sure how may I help u?','okk, what kind of help?','Help of what kind?']\n botMessage = hi[Math.floor(Math.random()*(hi.length))];;\n }\n if (lastUserMessage =='how to learn more?'||lastUserMessage =='effective ways to study in exams?'||lastUserMessage =='how to study?'||lastUserMessage =='how to score more?') {\n const hi = ['by working hard','by putting your best efforts and working hard','Here are the results>>>Work Hard']\n botMessage = hi[Math.floor(Math.random()*(hi.length))];;\n //document.write(\"<p>Link: \" + txt.link(\"http://tourism.rajasthan.gov.in/\") + \"</p>\");\n \n \n }\n if (lastUserMessage === 'Are you ready to talk to me?' || lastUserMessage =='Ready?') {\n const hi = ['yupp, always','Ever ready,hahahha','yupp, ask me what you have got>>>']\n botMessage = hi[Math.floor(Math.random()*(hi.length))];;\n \n \n \n }\n if (lastUserMessage === 'I love you' || lastUserMessage =='Thank You') {\n const hi = ['Thats so sweet of you','So sweet','You are always welcome']\n botMessage = hi[Math.floor(Math.random()*(hi.length))];;\n \n \n \n }\n if (lastUserMessage === 'why have you been designed?' || lastUserMessage =='Aim of your designing?'||lastUserMessage =='why were you designed?'||lastUserMessage =='why are you designed?') {\n const hi = ['To help the people for their betterment and to uplift the society providing them a better future.','For helping the people and serving their cause.','In order to help the people to find the way for their betterment & to uplift the society serving the cause and thus, providing a better future to all of them.']\n botMessage = hi[Math.floor(Math.random()*(hi.length))];;\n \n \n \n }\n \n\n \n\n\n if (lastUserMessage === 'what is your name?'||lastUserMessage =='name?'||lastUserMessage =='whats your name?') {\n botMessage = 'My name is ' + botName;\n }\n}",
"function timeInWords(hour, minute) {\n var dict = {\n 00: \" o' clock \",\n 1: \"one minute past \",\n 59: \"one minute to \",\n 45: \"quarter to \",\n 30: \" minutes to \",\n 30: \" minutes past \"\n\n\n }\n let words = [\n \"zero\",\n \"one\",\n \"two\",\n \"three\",\n \"four\",\n \"five\",\n \"six\",\n \"seven\",\n \"eight\",\n \"nine\",\n \"ten\",\n \"eleven\",\n \"twelve\",\n \"thirteen\",\n \"fourteen\",\n \"fifteen\",\n \"sixteen\",\n \"seventeen\",\n \"eightteen\",\n \"nineteen\",\n \"twenty\",\n \"twenty one\",\n \"twenty two\",\n \"twenty three\",\n \"twenty four\",\n \"twenty five\",\n \"twenty six\",\n \"twenty seven\",\n \"twenty eight\",\n \"twenty nine\"\n ];\n if (m == 0) {\n return (words[h] + \" o' clock \");\n } else\n if ((m == 1)) {\n return (\"one minute past \" + words[h]);\n } else if (m == 59) {\n return (\"one minute to \" + words[(h % 12) + 1]);\n } else if (m == 45) {\n return (\"quarter to \" + words[(h % 12) + 1]);\n\n } else if (m <= 30) {\n return (words[m] + \" minutes past \" + words[h])\n } else if (m > 30) {\n return (words[60 - m] + \" minutes to \" + words[(h % 12) + 1])\n }\n console.log(words[h], words[m]);\n}",
"function scuberGreetingForFeet(feet){\nif ( feet <= 400 ) {\n return ('This one is on me!');\n}\nelse if ( feet <= 2499 ) {\n return ('I will gladly take your thirty bucks.');\n}\nelse if ( feet >= 2500 ) {\n return ('No can do.');\n}\n}",
"function parseConvertNumbersAndLetters(words, index) {\n var state = 0; //1=first number, 2=first word, 3=second number, 4=second word\n var i = index;\n var n1 = 0;\n var n2 = 0;\n var w1 = '';\n var w2 = '';\n while(i < words.length) {\n var word = words[i];\n for(var j = 0; j < word.length; j++) {\n if(word == 'to') {\n state = 3;\n continue;\n }\n var n = word.charCodeAt(j) - 48;\n if(n >= 0 && n <= 9) {\n // digit\n if(state == 0) {\n state = 1;\n n1 = n;\n }\n else if(state == 1) n1 = n1 * 10 + n;\n else if(state == 3) n2 = n2 * 10 + n;\n } else {\n // letter\n var c = word[j];\n if(state < 2) state = 2;\n if(state == 2) w1 += c;\n if(state == 3) state = 4;\n if(state == 4) w2 += c;\n }\n }\n if(state == 4) break; //don't continue parsing past the one word\n i++;\n }\n if(n1 == 0) n1 = 1;\n if(n2 == 0) n2 = 1;\n return [n1, w1, n2, w2, i];\n}",
"function numberToWords(value)\n {\n if (!value || isNaN(value)) return \"\";\n let numberInWordsStr=\"\";\n if (value && value.length)\n {\n let digitsGroupArr = [\n {arr:[],showStr:\"billion\"},\n {arr:[],showStr:\"million\"},\n {arr:[],showStr:\"thousand\"},\n {arr:[],showStr:\"\"},\n ];\n //we take the number and split it into parts of 3 digits, each in a group accordingly\n let numberAsString=value.split(\"\").reverse().join('');\n\n for (var i = 0; i < numberAsString.length; i++) {\n let digit = numberAsString[i];\n if (i<3){\n digitsGroupArr[3].arr.push(digit);\n } else\n if (i<6){\n digitsGroupArr[2].arr.push(digit);\n } else\n if (i<9){\n digitsGroupArr[1].arr.push(digit);\n } else\n if (i<12){\n digitsGroupArr[0].arr.push(digit);\n }\n }\n\n //loop through the groups and get the right sentence for each 3 digit group\n for (item of digitsGroupArr) {\n if (item.arr.length && parseInt(item.arr.join(''))>0)\n {\n let str=getSentenceFor(item.arr.reverse().join(''),item.showStr);\n if (str)\n {\n //if we get a sentence, add it to the full sentence string\n numberInWordsStr+=numberInWordsStr.length?\", \"+str:str;\n }\n }\n }\n }\n\n return numberInWordsStr;\n }",
"function chat(){\n // if (speechRec.resultValue){\n let input = speechRec.resultString;\n bot.reply(\"local-user\", input).then(function(reply) {\n console.log(\"Bot>\", reply);\n // output.html(reply);\n speech.speak(reply)\n });\n \n // }\n }",
"function tweetToHtml(t) {\n\tconsole.log(\"went to tweettohtml\");\n\tvar content='';\n\tvar a = t.msg.split(\" \");\n\tcontent += '<div class=\"tweet\" id = \"t'+t.tweetid+'\" ><b>'+t.name+'</b> <a href=\"/'+t.username+'/profile\"> @'+t.username+'</a>'\n\t\t +'<div class=\"tmsg\">'+msgToHtml(t.msg)+'</div>'\n\t\t + t.date +'<br>'\n\t\t +'<a href=\"/'+t.tweetid+'/detailedTweet\">Detail</a> | ' \n\t\t +'<a href=\"/'+t.tweetid+'/simpleReply\">Reply</a> | '\n\t\t +'<a href=\"/\">Retweet</a> | '\n\t\t + '<a class=\"delT\" id=\"'+t.tweetid+'\" href=>Delete</a> '\n\t\t +'</div>';\n return content;\n}",
"function askAlcohol(chat_id) {\n var message = \"How many drinks did you have today, \" + weekdayAndDate() + \"?\";\n \n var alcoholKeyboard = {inline_keyboard: [[{text: \"🚫\", callback_data: \"0\"}, \n {text: \"🍺\", callback_data: \"1\"},\n {text: \"🍺🍺\", callback_data: \"2\"},\n {text: \"🥴 3+\", callback_data: \"3+\"}\n ]]};\n \n return sendQuestion(chat_id, message, keyboard = alcoholKeyboard);\n}",
"toTokens(msg) {\n // remove the prefix\n let tokensString = msg.content.slice(1).trim();\n // parse the tokens into an array\n let tokens = parse(tokensString)['_'];\n return tokens;\n }",
"function cambiar_espacios(){\n aux = \"\";\n\n for(msn in mensaje){\n if(mensaje[msn] != \" \"){\n aux = aux + mensaje[msn];\n }else{\n aux = aux + \"_\";\n }\n }\n mensaje = aux;\n}",
"async sendMessages({ text, chat_id }) {\n // text, chat_id) {\n try {\n const url = `https://api.telegram.org/bot${this.key}/sendMessage`;\n let send = await Robo.request({\n url: url,\n method: \"POST\",\n data: {\n chat_id: chat_id,\n text: text,\n },\n });\n return send.result;\n } catch (e) {\n // console.log(e);\n }\n }",
"function telephoneWords (digitString) {\n\n var keypadObj = {\n \"0\" : \"0\",\n \"1\" : \"1\",\n \"2\" : \"ABC\",\n \"3\" : \"DEF\",\n \"4\" : \"GHI\",\n \"5\" : \"JKL\",\n \"6\" : \"MNO\",\n \"7\" : \"PQRS\",\n \"8\" : \"TUV\",\n \"9\" : \"WXYZ\",\n }\n var result = [];\n var temp = [];\n function findSolution(digitString, keypadObj, result, temp) {\n if (digitString.length === 0) {\n var resultArr = [];\n for (var i = 0; i < temp.length; i++) {\n resultArr[i] = temp[i];\n }\n result.push(resultArr.join(\"\"));\n return;\n }\n\n var currStr = keypadObj[digitString.substring(0,1)];\n for (var j = 0; j < currStr.length; j++) {\n temp.push(currStr.charAt(j));\n findSolution(digitString.substring(1), keypadObj, result, temp);\n temp.pop();\n }\n\n }\n\n findSolution(digitString, keypadObj, result, temp)\n return result;\n\n}",
"function constructNote(message, letters) {\n let frequencyCounter1 = {};\n\n for (let char of letters) {\n frequencyCounter1[char] = ++frequencyCounter1[char] || 1;\n }\n\n for (let char of message) {\n if (!frequencyCounter1[char]) return false;\n frequencyCounter1[char]--;\n }\n\n return true;\n}",
"function formatGroupMessage(user_idFrom, text) {\n\treturn {\n\t\tfrom: user_idFrom,\n\t\ttext: text,\n\t\tcreatedAt: moment()\n\t}\n}",
"function champIdToName(id) {\n switch (id) {\n case 1: return \"Annie\";\n case 2: return \"Olaf\";\n case 3: return \"Galio\";\n case 4: return \"Twisted Fate\";\n case 5: return \"Xin Zhao\";\n case 6: return \"Urgot\";\n case 7: return \"Leblanc\";\n case 8: return \"Vladimir\";\n case 9: return \"Fiddlesticks\";\n case 10: return \"Kayle\";\n case 11: return \"Master Yi\";\n case 12: return \"Alistar\";\n case 13: return \"Ryze\";\n case 14: return \"Sion\";\n case 15: return \"Sivir\";\n case 16: return \"Soraka\";\n case 17: return \"Teemo\";\n case 18: return \"Tristana\";\n case 19: return \"Warwick\";\n case 20: return \"Nunu\";\n case 21: return \"Miss Fortune\";\n case 22: return \"Ashe\";\n case 23: return \"Tryndamere\";\n case 24: return \"Jax\";\n case 25: return \"Morgana\";\n case 26: return \"Zilean\";\n case 27: return \"Singed\";\n case 28: return \"Evelynn\";\n case 29: return \"Twitch\";\n case 30: return \"Karthus\";\n case 31: return \"Cho'gath\";\n case 32: return \"Amumu\";\n case 33: return \"Rammus\";\n case 34: return \"Anivia\";\n case 35: return \"Shaco\";\n case 36: return \"Dr. Mundo\";\n case 37: return \"Sona\";\n case 38: return \"Kassadin\";\n case 39: return \"Irelia\";\n case 40: return \"Janna\";\n case 41: return \"Gangplank\";\n case 42: return \"Corki\";\n case 43: return \"Karma\";\n case 44: return \"Taric\";\n case 45: return \"Veigar\";\n case 48: return \"Trundle\";\n case 50: return \"Swain\";\n case 51: return \"Caitlyn\";\n case 53: return \"Blitzcrank\";\n case 54: return \"Malphite\";\n case 55: return \"Katarina\";\n case 56: return \"Nocturne\";\n case 57: return \"Maokai\";\n case 58: return \"Renekton\";\n case 59: return \"Jarvan IV\";\n case 60: return \"Elise\";\n case 61: return \"Orianna\";\n case 62: return \"Wukong\";\n case 63: return \"Brand\";\n case 64: return \"Lee Sin\";\n case 67: return \"Vayne\";\n case 68: return \"Rumble\";\n case 69: return \"Cassiopeia\";\n case 72: return \"Skarner\";\n case 74: return \"Heimerdinger\";\n case 75: return \"Nasus\";\n case 76: return \"Nidalee\";\n case 77: return \"Udyr\";\n case 78: return \"Poppy\";\n case 79: return \"Gragas\";\n case 80: return \"Pantheon\";\n case 81: return \"Ezreal\";\n case 82: return \"Mordekaiser\";\n case 83: return \"Yorick\";\n case 84: return \"Akali\";\n case 85: return \"Kennen\";\n case 86: return \"Garen\";\n case 89: return \"Leona\";\n case 90: return \"Malzahar\";\n case 91: return \"Talon\";\n case 92: return \"Riven\";\n case 96: return \"Kog'Maw\";\n case 98: return \"Shen\";\n case 99: return \"Lux\";\n case 101: return \"Xerath\";\n case 102: return \"Shyvana\";\n case 103: return \"Ahri\";\n case 104: return \"Graves\";\n case 105: return \"Fizz\";\n case 106: return \"Volibear\";\n case 107: return \"Rengar\";\n case 110: return \"Varus\";\n case 111: return \"Nautilus\";\n case 112: return \"Viktor\";\n case 113: return \"Sejuani\";\n case 114: return \"Fiora\";\n case 115: return \"Ziggs\";\n case 117: return \"Lulu\";\n case 119: return \"Draven\";\n case 120: return \"Hecarim\";\n case 121: return \"Kha'zix\";\n case 122: return \"Darius\";\n case 126: return \"Jayce\";\n case 127: return \"Lissandra\";\n case 131: return \"Diana\";\n case 133: return \"Quinn\";\n case 134: return \"Syndra\";\n case 143: return \"Zyra\";\n case 150: return \"Gnar\";\n case 154: return \"Zac\";\n case 157: return \"Yasuo\";\n case 161: return \"Vel'koz\";\n case 201: return \"Braum\";\n case 222: return \"Jinx\";\n case 223: return \"Tahm Kench\";\n case 236: return \"Lucian\";\n case 238: return \"Zed\";\n case 245: return \"Ekko\";\n case 254: return \"Vi\";\n case 266: return \"Aatrox\";\n case 267: return \"Nami\";\n case 268: return \"Azir\";\n case 412: return \"Thresh\";\n case 421: return \"Rek'Sai\";\n case 429: return \"Kalista\";\n case 432: return \"Bard\";\n case 999: return \"All Mages\";\n default: return \"Unknown\";\n }\n}",
"function transrateCommand(command){\n\tvar array_tmp = command.split(\"、\");\t\n\tvar str_tmp = \"\";\n\tswitch(array_tmp[0]){\n\t\t\tcase \"■背景\":\n\t\t\t\tstr_tmp = \"bg\";\n\t\t\tbreak;\n\t\t\n\t\t\tcase \"■タイトル\":\n\t\t\t\tstr_tmp = \"title\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■キャラ\":\n\t\t\t\tstr_tmp = \"char\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■キャラ消し\":\n\t\t\t\tstr_tmp = \"rm\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■音楽\":\n\t\t\t\tstr_tmp = \"music\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■音楽ストップ\":\n\t\t\t\tstr_tmp = \"musicstop\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■ジャンプ\":\n\t\t\t\tstr_tmp = \"goto\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■フラグセット\":\n\t\t\t\tstr_tmp = \"flagset\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■フラグ計算\":\n\t\t\t\tstr_tmp = \"flagcal\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■もし\":\n\t\t\t\tstr_tmp = \"if\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■選択肢\":\n\t\t\t\tstr_tmp = \"select\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■ウェイト\":\n\t\t\t\tstr_tmp = \"wait\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■SE\":\n\t\t\t\tstr_tmp = \"se\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■シェイク\":\n\t\t\t\tstr_tmp = \"shake\";\n\t\t\tbreak;\n\t\t\tcase \"■キャラシェイク\":\n\t\t\t\tstr_tmp = \"charshake\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"■#\":\n\t\t\t\tstr_tmp = \"#\";\n\t\t\tbreak;\n\t\t\t\n\t\t\tcase \"//\":\n\t\t\t\tstr_tmp = \"//\";\n\t\t\tbreak;\n\t\t}\n\n\t\t//もし置き換えが発生していたら変換\n\t\tif(str_tmp != \"\"){\n\t\t\tcommand = command.replace(/、/g, \" \");\n\t\t\tcommand = command.replace(array_tmp[0], str_tmp);\n\t\t}\n\t\treturn command;\n}",
"function generateTrashTalk(option) {\n //error notice\n if (!option.character) {\n return '請選擇一個幹話對象'\n }\n //define things user might want\n const task = {\n engineer: ['加個按鈕', '加新功能', '切個版', '改一點 code'],\n designer: ['畫一張圖', '改個 logo', '順便幫忙設計一下', '隨便換個設計'],\n entrepreneur: ['週末加班', '要能賺錢', '想個 business model', '找 VC 募錢']\n }\n\n const phrase = ['很簡單', '很容易', '很快', '很正常']\n\n //create a collection to store things user picked up\n let request = []\n\n if (option.character === 'engineer') {\n request = request.concat(task.engineer)\n return `身為一個工程師${sample(request)}${sample(phrase)}吧!`\n }\n\n if (option.character === 'designer') {\n request = request.concat(task.designer)\n return `身為一個設計師${sample(request)}${sample(phrase)}吧!`\n }\n\n if (option.character === 'entrepreneur') {\n request = request.concat(task.entrepreneur)\n return `身為一個創業家${sample(request)}${sample(phrase)}吧!`\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Append additional headers, e.g., xgooguserproject, shared across the classes inheriting AuthClient. This method should be used by any method that overrides getRequestMetadataAsync(), which is a shared helper for setting request information in both gRPC and HTTP API calls. | addSharedMetadataHeaders(headers) {
// quota_project_id, stored in application_default_credentials.json, is set in
// the x-goog-user-project header, to indicate an alternate account for
// billing and quota:
if (!headers['x-goog-user-project'] && // don't override a value the user sets.
this.quotaProjectId) {
headers['x-goog-user-project'] = this.quotaProjectId;
}
return headers;
} | [
"function TrackerSetHeader(\n Authorization = '',\n ppr = '',\n deltaId = '',\n deltamatic = '',\n channelId = '',\n appId = '',\n sessionId = ''\n ) {\n _HEADER = {\n Authorization: Authorization,\n UserAgent: `PPR|${ppr}, DL|${deltaId}, DLM|${deltamatic}`,\n channeId: channelId,\n appId: appId,\n sessId: sessionId\n }\n}",
"appendRobotHeaders()\n\t{\n\t\tconst xRobotsTag = this.currentResponse.headers[\"x-robots-tag\"];\n\n\t\t// @todo https://github.com/nodejs/node/issues/3591\n\t\tif (xRobotsTag != null)\n\t\t{\n\t\t\tthis.currentRobots.header(xRobotsTag);\n\t\t}\n\t}",
"function attachToken(request) {\r\n var token = getToken();\r\n if (token) {\r\n request.headers = request.headers || {};\r\n request.headers['x-access-token'] = token;\r\n }\r\n return request;\r\n }",
"function setCommonHeaders(req) {\n // Set (or clear) user agent\n if (userAgent) {\n req.set('User-Agent', userAgent);\n } else {\n req.unset('User-Agent');\n }\n // Prevent caching so response time will be accurate\n req\n .set('Cache-Control', 'no-cache')\n .set('Pragma', 'no-cache');\n }",
"procesarHeaders(){\n var headers = {\n \"Accept\": \"*/*\",\n \"User-Agent\": \"Cliente Node.js\"\n };\n if(this.basicAuth != undefined){\n headers.Authorization = \"Basi c\" + this.basicAuth;\n }\n return headers;\n }",
"static addPragmaHeaders(page) {\n page.setExtraHTTPHeaders({'Pragma': 'akamai-x-cache-on, akamai-x-cache-remote-on, akamai-x-check-cacheable, akamai-x-get-cache-key, akamai-x-get-ssl-client-session-id, akamai-x-get-true-cache-key, akamai-x-get-request-id, x-akamai-cpi-trace, akamai-x-tapioca-trace, akamai-x-get-extracted-values'});\n }",
"setAuthToken(requestObject) {\n if (this._token) {\n return requestObject.set(\n 'Authorization',\n `Token ${this._token}`\n );\n }\n return requestObject;\n }",
"extractTraceFromHeaders(projectId) {\n const rawReq = this.metadata.httpRequest;\n if (rawReq && 'headers' in rawReq) {\n return context_1.getOrInjectContext(rawReq, projectId, false);\n }\n return null;\n }",
"function setHeaderWithToken() {\n var cookie = $.cookie(\"accessToken\");\n\n $(document).ajaxSend(function (event, jqxhr, settings) {\n jqxhr.setRequestHeader('Authorization', 'bearer ' + cookie);\n });\n }",
"defaultHeaders(otherHeaders = {}) {\n\n let acceptHeaders = {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }\n\n return Object.assign({}, acceptHeaders, otherHeaders)\n }",
"function buildAuthOptions(authOptions) {\n return __assign({ clientCapabilities: [], azureCloudOptions: DEFAULT_AZURE_CLOUD_OPTIONS, skipAuthorityMetadataCache: false }, authOptions);\n }",
"static createFromGoogleCredential(googleCredentials) {\n return CallCredentials.createFromMetadataGenerator((options, callback) => {\n let getHeaders;\n if (isCurrentOauth2Client(googleCredentials)) {\n getHeaders = googleCredentials.getRequestHeaders(options.service_url);\n }\n else {\n getHeaders = new Promise((resolve, reject) => {\n googleCredentials.getRequestMetadata(options.service_url, (err, headers) => {\n if (err) {\n reject(err);\n return;\n }\n if (!headers) {\n reject(new Error('Headers not set by metadata plugin'));\n return;\n }\n resolve(headers);\n });\n });\n }\n getHeaders.then(headers => {\n const metadata = new metadata_1.Metadata();\n for (const key of Object.keys(headers)) {\n metadata.add(key, headers[key]);\n }\n callback(null, metadata);\n }, err => {\n callback(err);\n });\n });\n }",
"function fetchWithHeader() {\n fetch('https://api.github.com/users?since=135').then(function(response) {\n console.log(response.headers.get('Content-Type'));\n console.log(response.headers.get('Date'));\n\n console.log(response.status);\n console.log(response.statusText);\n console.log(response.type);\n console.log(response.url);\n });\n}",
"function setPaginationHeaders({ req, res, limit, offset, total }) {\n if (req == null || res == null || limit == null || offset == null || total == null) {\n return\n }\n function url(baseUrl, query, rel) {\n let url = baseUrl\n let index = 0\n _.forOwn(query, (value, key) => {\n url += `${(index == 0 ? \"?\" : \"&\")}${key}=${value}`\n index += 1\n })\n return `<${url}>; rel=\"${rel}\"`\n }\n // Set X-Total-Count header\n res.set(\"X-Total-Count\", total)\n let links = []\n let baseUrl = getBaseUrl(req, false) + req.path\n let query = _.cloneDeep(req.query)\n query.limit = limit\n // rel: first\n query.offset = 0\n links.push(url(baseUrl, query, \"first\"))\n // rel: prev\n if (offset > 0) {\n query.offset = Math.max(offset - limit, 0)\n links.push(url(baseUrl, query, \"prev\"))\n }\n // rel: next\n if (limit + offset < total) {\n query.offset = offset + limit\n links.push(url(baseUrl, query, \"next\"))\n }\n // rel: last\n let current = 0\n while (current + limit < total) {\n current += limit\n }\n query.offset = current\n links.push(url(baseUrl, query, \"last\"))\n // Set Link header\n res.set(\"Link\", links.join(\",\"))\n}",
"function constructResponseHeaders(request, response) {\n\n //header array we'll eventually print, plus our own\n let finalHeaders = response.getHeaders();\n\n if (!finalHeaders) {\n finalHeaders = {}\n }\n\n finalHeaders = getSafeResponseHeaders(finalHeaders);\n \n //We look at all the request headers, and for each, we prepend x-fwd- and add them to the response headers array\n for (const [headerName, valuesForHeaderName] of Object.entries(request.getHeaders())) {\n var newHeaderName = 'x-fwd-' + headerName;\n finalHeaders[newHeaderName] = [];\n valuesForHeaderName.forEach((headerVal) => {\n finalHeaders[newHeaderName].push(headerVal);\n });\n }\n\n return finalHeaders;\n}",
"function authorize(request, token) {\n return Object.assign(\n { headers: {'Authorization': `userToken=${token}` } },\n request)\n}",
"constructor(authString) {\n this.eloquaOptions = {\n headers: {\n authorization: authString\n }\n };\n }",
"static add(addResponseProfile){\n\t\tlet kparams = {};\n\t\tkparams.addResponseProfile = addResponseProfile;\n\t\treturn new kaltura.RequestBuilder('responseprofile', 'add', kparams);\n\t}",
"setHeader(key, value) {\n this._headers[key] = value\n }",
"static fromHttp2Headers(headers) {\n const result = new Metadata();\n for (const key of Object.keys(headers)) {\n // Reserved headers (beginning with `:`) are not valid keys.\n if (key.charAt(0) === ':') {\n continue;\n }\n const values = headers[key];\n try {\n if (isBinaryKey(key)) {\n if (Array.isArray(values)) {\n values.forEach(value => {\n result.add(key, Buffer.from(value, 'base64'));\n });\n }\n else if (values !== undefined) {\n if (isCustomMetadata(key)) {\n values.split(',').forEach(v => {\n result.add(key, Buffer.from(v.trim(), 'base64'));\n });\n }\n else {\n result.add(key, Buffer.from(values, 'base64'));\n }\n }\n }\n else {\n if (Array.isArray(values)) {\n values.forEach(value => {\n result.add(key, value);\n });\n }\n else if (values !== undefined) {\n result.add(key, values);\n }\n }\n }\n catch (error) {\n const message = `Failed to add metadata entry ${key}: ${values}. ${(0, error_1.getErrorMessage)(error)}. For more information see https://github.com/grpc/grpc-node/issues/1173`;\n (0, logging_1.log)(constants_1.LogVerbosity.ERROR, message);\n }\n }\n return result;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
HAND STATE RELATED isBettingDone checks if a round of betting has completed. | isBettingDone(lineup, dealer, state, bbAmount) {
if (this.isHandComplete(lineup, dealer, state)) {
return true;
}
const activePlayers = activeLineup(lineup, dealer, state, this.rc);
let maxBet;
if (state === 'waiting' || state === 'preflop') {
try {
maxBet = this.getMaxBet(activePlayers, state);
} catch (err) {
if (state === 'waiting') {
return false;
}
// try with all players, in case everyone all-in
maxBet = this.getMaxBet(lineup, state);
}
}
if (state === 'waiting') {
return maxBet.amount > 0;
}
if (state === 'dealing') {
const noRecCount = countNoReceipts(lineup, this.rc);
if (noRecCount === 0) {
return true;
}
}
const allInPlayerCount = this.countAllIn(lineup);
if (allInPlayerCount > 0 && activePlayers.length === 1) {
// see if last active player matched latest all-in
const maxAllInAmount = maxAllIn(lineup, this.rc);
if (!maxBet) {
maxBet = this.getMaxBet(activePlayers, state);
}
return (maxAllInAmount <= maxBet.amount);
}
const allEven = evenLineup(activePlayers, this.rc);
if (!allEven) {
return false;
}
const checker = findLatest({ sorted: true, lineup: activePlayers }, Type.CHECK_PRE, this.rc);
if (checker.last) {
// prefop betting done if check found
if (state === 'preflop') {
return true;
}
// on other streets wait until all active players have checked
const checkType = (state === 'preflop') ? // eslint-disable-line
Type.CHECK_PRE : (state === 'flop') ? // eslint-disable-line
Type.CHECK_FLOP : (state === 'turn') ?
Type.CHECK_TURN : Type.CHECK_RIVER;
const checkCount = countReceipts(lineup, checkType, this.rc);
if (checkCount === activePlayers.length) {
return true;
}
return false;
}
if (state === 'preflop') {
if (!bbAmount) throw new Error('BB amount cannot be undefined');
const bbPos = this.getBbPos(lineup, dealer, state);
const bbRec = this.rc.get(lineup[bbPos].last);
if (isActive(lineup[bbPos], state, this.rc) &&
bbRec.type !== Type.CHECK_PRE &&
maxBet.amount === parseInt(bbAmount, 10)) {
return false;
}
}
if (allInPlayerCount > 0 && activePlayers.length === 0) {
return true;
}
if (allEven) {
return true;
}
throw Error('could not determine betting state');
} | [
"function isTournamentCompleted(tournament){\n console.log(tournament.tournament.progressMeter);\n return tournament.tournament.progressMeter == 100\n}",
"isHandComplete(lineup, dealer, state) {\n const activePlayers = activeLineup(lineup, dealer, state, this.rc);\n const allInPlayerCount = this.countAllIn(lineup);\n if (state === 'showdown') {\n if (checkForReceipt(lineup, Type.SHOW, this.rc)) {\n return (activePlayers.length === 0 && allInPlayerCount === 0);\n }\n return (activePlayers.length <= 1 && allInPlayerCount === 0);\n }\n return (\n (activePlayers.length <= 1 && allInPlayerCount === 0) ||\n (activePlayers.length === 0 && allInPlayerCount === 1)\n );\n }",
"function endRound () {\n\t/* check to see how many players are still in the game */\n var inGame = 0;\n var lastPlayer = 0;\n for (var i = 0; i < players.length; i++) {\n if (players[i] && !players[i].out) {\n inGame++;\n lastPlayer = i;\n }\n }\n \n /* if there is only one player left, end the game */\n if (inGame == 1) {\n\t\tconsole.log(\"The game has ended!\");\n\t\t$gameBanner.html(\"Game Over! \"+players[lastPlayer].label+\" won Strip Poker Night at the Inventory!\");\n\t\tgameOver = true;\n \n for (var i = 0; i < players.length; i++) {\n if (HUMAN_PLAYER == i) {\n $gamePlayerCardArea.hide();\n } \n else {\n $gameOpponentAreas[i-1].hide();\n }\n }\n \n\t\thandleGameOver();\n\t} else {\n\t\t$mainButton.html(\"Deal\");\n if (players[HUMAN_PLAYER].out && AUTO_FORFEIT) {\n setTimeout(advanceGame,FORFEIT_DELAY);\n }\n\t}\n\t$mainButton.attr('disabled', false);\n actualMainButtonState = false;\n}",
"isFinished() {\n\t\treturn this.staircases.every(function(s) {return s.staircase.isComplete();});\n\t}",
"getPlayerRoundState(sessionID) {\n let player = this.getPlayer(sessionID)\n if (player == null) return null;\n let latestRound = this.getLatestRound()\n let roundRole = this.isRoundJudge(sessionID, latestRound) ? 'judge' : 'player'\n let playerChoice = _.find(latestRound.otherPlayerCards, card => card.owner.pID === player.pID) || null;\n let otherPlayerCards = latestRound.otherPlayerCards;\n let cards = player.cards;\n let QCard = latestRound.QCard;\n let roundNum = latestRound.roundNum;\n let roundJudge = latestRound.roundJudge.name;\n let winningCard = latestRound.winningCard;\n let winner = latestRound.winner;\n // timeRemaining in seconds\n let timeLeft = _.max([0, _.floor(this.roundLength - ((new Date() - latestRound.roundStartTime) / 1000))]);\n let roundState;\n\n if (latestRound.roundState === 'judge-selecting' || latestRound.roundState === 'viewing-winner') {\n timeLeft = 0\n roundState = latestRound.roundState\n }\n else if (roundRole == 'judge') {\n roundState = 'judge-waiting'\n }\n else if (playerChoice != null) {\n roundState = 'player-waiting'\n }\n else {\n roundState = 'player-selecting'\n }\n\n return {\n roundState,\n roundRole,\n roundJudge,\n roundNum,\n QCard,\n cards,\n otherPlayerCards,\n playerChoice,\n winningCard,\n winner,\n timeLeft\n }\n }",
"function continueDealPhase () {\n\t/* hide the dialogue bubbles */\n for (var i = 1; i < players.length; i++) {\n $gameDialogues[i-1].html(\"\");\n $gameAdvanceButtons[i-1].css({opacity : 0});\n $gameBubbles[i-1].hide();\n }\n\t\n\t/* set visual state */\n if (!players[HUMAN_PLAYER].out) {\n showHand(HUMAN_PLAYER);\n }\n for (var i = 1; i < players.length; i++) {\n hideHand(i);\n }\n \n /* enable player cards */\n for (var i = 0; i < $cardButtons.length; i++) {\n $cardButtons[i].attr('disabled', false);\n }\n\t\n\t/* suggest cards to swap, if enabled */\n\tif (CARD_SUGGEST && !players[HUMAN_PLAYER].out) {\n\t\tdetermineAIAction(HUMAN_PLAYER);\n\t\t\n\t\t/* dull the cards they are trading in */\n\t\tfor (var i = 0; i < hands[HUMAN_PLAYER].tradeIns.length; i++) {\n\t\t\tif (hands[HUMAN_PLAYER].tradeIns[i]) {\n\t\t\t\tdullCard(HUMAN_PLAYER, i);\n\t\t\t}\n\t\t}\n\t}\n \n /* allow each of the AIs to take their turns */\n currentTurn = 0;\n advanceTurn();\n}",
"isRoundJudge(sessionID, round) {\n let player = this.getPlayer(sessionID);\n return player && round.roundJudge.pID === player.pID;\n }",
"opponentSelectionDone(opponent) {\n const trainingOpponentSelection = opponent.selection;\n\n this.setState({\n mode: Modes.ShipSelection,\n settingAttack: true,\n trainingOpponent: opponent.address,\n trainingOpponentSelection,\n trainingOpponentCommander: opponent.commander,\n trainingCp: this._selectionToCp(trainingOpponentSelection),\n });\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}",
"endOfGame(){\n let winningCombination = this.findWinningCombination();\n if(winningCombination){\n return true;\n }\n else{\n return false\n }\n }",
"moveCompleted() {\n // Housekeeping\n this.from = null;\n // Check if the game is actually over!\n let moves = this.getMoves();\n if (moves.length === 0) {\n if (this.game.in_check()) {\n // CHECKMATE\n this.showResult(true, this.getTurn(false));\n }\n else {\n // STALEMATE\n this.showResult(false);\n }\n }\n else {\n if (this.gameOver) return;\n\n // If the game isn't over we want to show the results of the last move\n // in terms of updating the fog, so\n // Flip the turn back to the player who just played\n this.flipTurn();\n // Display the fog\n this.setupFog(false);\n // Flip the turn back to the correct player\n this.flipTurn();\n // Wait and then...\n setTimeout(() => {\n // Animate the fog to totally opaque so that nobody can see anything\n $.when($('.fog').animate({\n opacity: 1\n }, 1000))\n .then(() => {\n // And then show the instructions for the next turn\n this.showInstruction();\n });\n }, 2000);\n }\n\n }",
"checkGoalReached() {\n\t\tthis.afterDeadline();\n\t\tif (amountRaised >= fundingGoal){\n\t\t\tfundingGoalReached = true;\n\t\t\t// emit GoalReached(beneficiary, amountRaised);\n\t\t}\n\t\tcrowdsaleClosed = true;\n\t}",
"function CompleteQuest () {\n\tif(coins >= 5){\n\n\t\t//This tells us that the quest is complete and ready to be turned in.\n\t\t_questDone = true;\n\t\t//This changes what our NPC will say now that the quest is finished and ready to be turned in.\n\t\t_npcs.NPCList[0].npcStage = 2;\n\t\t//This changes our quest log's details.\n\t\t_quests.QuestList[0].questStage = 2;\n\t}\n\telse {\n\t\t_questDone = false;\n\t}\n}",
"function roundEnded() {\n\tif (roundCont == true) {\n\t\tclearInterval(interval);\n\t\ttargetDate = null;\n\t\troundCont = false;\n//\t\tdocument.myForm.round.disabled = false;\n\t\tupdateButtons();\n\t\tgetWords();\n\t}\n}",
"function checkPageDone(page) {\n var isDone = _.every(page.differences, function(d) { return d.state != \"in_use\"; });\n if (isDone) {\n console.log(\"Marking page as done:\", page._id);\n page.state = \"done\";\n page.saveAsync();\n }\n return isDone;\n}",
"function isRoundTrip() {\n\tvar roundTrip = document.getElementById(\"tripOne\");\t\t\t\t\t// Gets and assigns value to store tripOne.\n\tvar lRoundTrip = document.querySelector(\"[for='tripOne']\");\t\t\t// Gets and assigns value to store label for tripOne for roundTrip.\n\tvar oneWay = document.getElementById(\"tripTwo\");\t\t\t\t\t// Gets and assigns value to store tripTwo.\n\tvar lOneWay = document.querySelector(\"[for='tripTwo']\");\t\t\t// Gets and assigns value to store label for tripTwo for One-Way.\n\tif (roundTrip.checked == true) { \t\t\t\t\t\t\t\t\t// Checks if round trip is selected. \n\t\tlRoundTrip.classList.add(\"active\");\t\t\t\t\t\t\t\t// Adds class active to lRoundTrip selector.\n\t\toneWay.checked == false;\t\t\t\t\t\t\t\t\t\t// Sets oneWay as not checked.\n\t\tlOneWay.classList.remove(\"active\");\t\t\t\t\t\t\t\t// Removes active class to oneWay's label.\n\t\tplaceReturnDate();\t\t\t\t\t\t\t\t\t\t\t\t// Displays the return date label and input.\n\t\tresetTicketData();\t\t\t\t\t\t\t\t\t\t\t\t// Resets ticket departure date information.\n\t\tsummaryArray[1] = \"Round Trip\";\t\t\t\t\t\t\t\t\t// Sets Round trip string to populate cost summary.\n\t\tupdateSummaryHeader();\t\t\t\t\t\t\t\t\t\t\t// Updates the summary header.\n\t\tcalculateCost();\t\t\t\t\t\t\t\t\t\t\t\t// Re-calculates cost.\n\t\tbookable();\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Verify if trip is bookable.\n\t\treturn true;\n\t} else {\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// If roundTrip is not selected.\n\t\treturn false;\n\t}\n}",
"function isAnswer() {\r\n\tif (!answer.branches)\r\n\t\treturn false;\r\n\t\t\r\n\tvar i = 0;\r\n\tfor (i in answer.branches) {\r\n\t\tvar branch = answer.branches[i];\r\n\t\tbranch.any = true;\r\n\t\tif (branch.words) {\r\n\t\t\tvar nb = compareSet(branch,userInput.list);\r\n\t\t\t/* console.log(\"branch: \" + branch.words,\r\n\t\t\t\t\t\t\"input: \" + userInput.list,\r\n\t\t\t\t\t\t\"matched: \" + nb); */\r\n\t\t\tif(nb >= 0.5) {\r\n\t\t\t\tbotAction.next = getAction(branch.action);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tbotAction.next = getAction(branch.action);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tif(!answer.wait){\r\n\t\tanswer = {};\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\treturn true;\r\n}",
"isTakeoff() {\n return this.flightPhase === FLIGHT_PHASE.TAKEOFF;\n }",
"function completeRevealPhase () {\n /* reveal everyone's hand */\n for (var i = 0; i < players.length; i++) {\n if (players[i] && !players[i].out) {\n determineHand(i);\n showHand(i);\n }\n }\n \n /* figure out who has the lowest hand */\n recentLoser = determineLowestHand();\n console.log(\"Player \"+recentLoser+\" is the loser.\");\n \n /* look for the unlikely case of an absolute tie */\n if (recentLoser == -1) {\n console.log(\"Fuck... there was an absolute tie\");\n /* inform the player */\n \n /* hide the dialogue bubbles */\n for (var i = 1; i < players.length; i++) {\n $gameDialogues[i-1].html(\"\");\n $gameAdvanceButtons[i-1].css({opacity : 0});\n $gameBubbles[i-1].hide();\n }\n \n /* reset the round */\n $mainButton.html(\"Deal\");\n $mainButton.attr('disabled', false);\n if (players[HUMAN_PLAYER].out && AUTO_FORFEIT) {\n setTimeout(advanceGame, FORFEIT_DELAY);\n }\n return;\n }\n \n /* update behaviour */\n\tvar clothes = playerMustStrip (recentLoser);\n updateAllGameVisuals();\n \n /* highlight the loser */\n for (var i = 0; i < players.length; i++) {\n if (recentLoser == i) {\n $gameLabels[i].css({\"background-color\" : loserColour});\n } else {\n $gameLabels[i].css({\"background-color\" : clearColour});\n }\n }\n \n /* set up the main button */\n\tif (recentLoser != HUMAN_PLAYER && clothes > 0) {\n\t\t$mainButton.html(\"Continue\");\n\t} else {\n\t\t$mainButton.html(\"Strip\");\n\t}\n if (players[HUMAN_PLAYER].out && AUTO_FORFEIT) {\n setTimeout(advanceGame,FORFEIT_DELAY);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use this function to populate DB with orders from ../assets/orders.json | async function populateOrders() {
let orderNarrators = [];
let advertisers = [];
let customers = [];
let contacts = [];
let narrators = [];
try {
advertisers = await Advertiser.find();
customers = await Customer.find();
contacts = await Contact.find();
narrators = await Narrator.find();
} catch (error) {
console.log(error);
}
const orders = require('../assets/ORDERS.json');
orders.forEach(async (order) => {
order.customer = customers.find(c => c.id === order.customerId);
order.advertiser = advertisers.find(a => a.id === order.advertiserId);
order.contact = order.advertiser.contacts[Math.round(Math.random() * (order.advertiser.contacts.length - 1))];
order.price = {
detailes: false,
fullPrice: order.price,
discount: order.discount,
collection: []
};
order.narratorsId.forEach(narrId => {
const n = narrators.find(nar => nar.id === narrId);
if (n) {
orderNarrators = [...orderNarrators, n];
}
});
order.narrators = orderNarrators;
orderNarrators = [];
try {
const dbOrder = new Order(order);
await dbOrder.save();
} catch (error) {
return console.log(error);
}
});
} | [
"function update_orders() {\n\t$.ajax({\n\t\tcontentType: 'application/json; charset=UTF-8',\n\t\tdata: null,\n\t\tdataType: 'json',\n\t\terror: function (jqXHR, textStatus, errorThrown) {\n\t\t\tfailure('Failed to get order data', jqXHR.statusText);\n\t\t},\n\t\tsuccess: function (data, textStatus, jqXHR) {\n\t\t\tif(data.result == 'ok') {\n\t\t\t\tfor(var i in data.orders) {\n\t\t\t\t\tvar order = data.orders[i];\n\n\t\t\t\t\tvar $row = $('.orders table tr[orderid=' + order.orderid + ']');\n\t\t\t\t\tif(!$row.length) {\n\t\t\t\t\t\tvar tr = document.createElement('TR');\n\t\t\t\t\t\ttr.setAttribute('orderid', order.orderid);\n\t\t\t\t\t\ttr.className = 'order';\n\n\t\t\t\t\t\tvar columns = ['orderid', 'amount', 'created', 'account', 'pending', 'credit', 'cancel', 'debit'];\n\n\t\t\t\t\t\tfor(var i in columns) {\n\t\t\t\t\t\t\tvar td = document.createElement('TD');\n\t\t\t\t\t\t\ttd.className = columns[i];\n\t\t\t\t\t\t\ttr.appendChild(td);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$row = $(tr);\n\t\t\t\t\t\t$('.orders table').append($row);\n\t\t\t\t\t}\n\t\t\t\t\tvar $row_td = $row.find('td');\n\t\t\t\t\t$row_td.eq(0).text(order.orderid);\n\n\t\t\t\t\tvar amount = '-';\n\t\t\t\t\tif(typeof(order.amount) != 'undefined' && order.amount != null) {\n\t\t\t\t\t\tamount = order.amount;\n\t\t\t\t\t}\n\t\t\t\t\tif(typeof(order.currency) != 'undefined' && order.currency != null) {\n\t\t\t\t\t\tamount = amount + ' ' + order.currency;\n\t\t\t\t\t}\n\t\t\t\t\t$row_td.eq(1).text(amount);\n\t\t\t\t\t$row_td.eq(2).text(order.created)?order.created:'';\n\n\t\t\t\t\t_build_notification_td($row_td.eq(3), order.account);\n\t\t\t\t\t_build_notification_td($row_td.eq(4), order.pending);\n\t\t\t\t\t_build_notification_td($row_td.eq(5), order.cancel);\n\t\t\t\t\t_build_notification_td($row_td.eq(6), order.credit);\n\t\t\t\t\t_build_notification_td($row_td.eq(7), order.debit);\n\t\t\t\t}\n\t\t\t\tif(data.orders.length) {\n\t\t\t\t\t$('.orders').removeClass('hidden');\n\n\t\t\t\t\t$('.orders table tr.order').click(function() {\n\t\t\t\t\t\t$(this).toggleClass('show-extra');\n\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\ttype: 'GET',\n\t\turl: '/php/example.php/orders',\n\t});\n}",
"async loadFromJSON(JSONs) {\n if(JSONs) {\n let JSONObj = JSONs.JSONItems\n for (let i = 0; i < JSONObj.length; i++) {\n let product = new Product(JSONObj[i].id, JSONObj[i].name, JSONObj[i].price, JSONObj[i].image);\n for (let j = 0; j < JSONObj[i].count; j++) {\n await this.addItem(product);\n }\n }\n }\n }",
"function parseAndSetupFarmOrders(order) {\n var fOrderArr = [];\n var ordList = [];\n var farmId = \"\";\n var fOrder;\n\n var hInvList = order.get('homeInventories');\n\n // Setup the first Id\n farmId = hInvList[0].get('farmId');\n \n for (var i = 0 ; i < hInvList.length; i++) {\n var hInv = hInvList[i];\n //var fInv = hInv.get(\"farmInv\");\n\n var hInvFarmId = hInv.get('farmId');\n if (hInvFarmId !== farmId) {\n // Pack and save the previous order list!\n fOrder = createFarmOrder(farmId, order, ordList);\n fOrderArr.push(fOrder);\n\n /* Setup for the next Farm! */\n farmId = hInvFarmId;\n ordList = [];\n }\n ordList.push(hInv);\n }\n\n if (ordList.length > 0) {\n // Save the last batch!\n fOrder = createFarmOrder(farmId, order, ordList);\n fOrderArr.push(fOrder);\n }\n\n return fOrderArr;\n}",
"function loadData(data) {\n\tif (data !== undefined && data !== null) {\n\t\tvar storageSpace = JSON.parse(data);\n\t\torders = [];\n\t\tfor (var i = 0; i < storageSpace.orders.length; i++) {\n\t\t\tvar newOrder = orderFactory();\n\t\t\tnewOrder.load(storageSpace.orders[i]);\n\t\t\torders.push(newOrder);\n\t\t}\n\t\tbaseItems = itemGroupFactory();\n\t\tbaseItems.load(storageSpace.baseItems);\n\t\toptionalItems = itemGroupFactory();\n\t\toptionalItems.load(storageSpace.optionalItems);\n\t\tlastOrderId = storageSpace.lastOrderId;\n\t} else {\n\t\tconsole.log(\"Received undefined: generating clean system.\");\n\t\torders = [];\n\t\tbaseItems = itemGroupFactory();\n\t\toptionalItems = itemGroupFactory();\n\t\tlastOrderId = 0;\n\t\tsyncToStorage();\n\t}\n}",
"function getOrders(){\n return JSON.parse(localStorage.getItem(\"orders\"));\n}",
"async function loadDeals() {\n const res = await fetch('./deals.json')\n const deals = await res.json();\n deals.forEach((deal, index) => deal.index = index);\n return deals;\n}",
"async getAllOrders(parent,args,ctx,info){\n return await ctx.db.query.orders({},info);\n }",
"function sendOrderInfoToDb(order) {\n console.log(\"Enter sendOrderInfoToDb()\");\n\n \n // Implement request\n $.ajax({\n url: 'http://localhost:3000/commandes',\n type: 'POST',\n dataType: 'JSON',\n contentType: \"application/json\",\n data: order.serializeOrder(),\n })\n\n // Request success\n .done(function(data){\n console.log(data);\n console.log(\"Success ! Data: \" + JSON.stringify(data));\n })\n}",
"function insertPersOrderByATG(req, res) {\n var tempPersOrdersModel = new persOrdersModel();\n\n tempPersOrdersModel.orderId = req.body.orderId;\n tempPersOrdersModel.fluid = req.body.fluid;\n tempPersOrdersModel.ycc = req.body.ycc;\n tempPersOrdersModel.source = req.body.source;\n tempPersOrdersModel.sku = req.body.sku;\n tempPersOrdersModel.quantity = req.body.quantity;\n tempPersOrdersModel.price = req.body.price;\n tempPersOrdersModel.thumbnailImg = req.body.thumbnailImg;\n tempPersOrdersModel.labelImg = req.body.labelImg;\n tempPersOrdersModel.previewImg = req.body.previewImg;\n tempPersOrdersModel.printImg = req.body.printImg;\n tempPersOrdersModel.labelText1 = req.body.labelText1;\n tempPersOrdersModel.labelText2 = req.body.labelText2;\n tempPersOrdersModel.commodity = req.body.commodity;\n tempPersOrdersModel.destination = req.body.destination;\n tempPersOrdersModel.labelType = req.body.labelType;\n tempPersOrdersModel.$addToSet = {\n orchestrator: { print_ready_image: 't' },\n orderstatus: { status: 'under process' }\n };\n console.log(tempPersOrdersModel);\n tempPersOrdersModel.save()\n .then(function(insertedPersOrder) {\n res.json(insertedPersOrder);\n })\n .catch(function(err) {\n console.log('error:', err);\n res.send('Inserted failed due to ' + err);\n });\n}",
"function writeOrderAWS(){\n AWS.config.update(aws_dynamo_order_config);\n\n var docClient = new AWS.DynamoDB.DocumentClient();\n var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});\n // var index = Date.now()\n var cart_data = JSON.parse(localStorage.getItem(\"cart_data\"));\n var default_quantity = 1;\n\n for (i = 0; i < cart_data.dishes.length; i++){\n var dish = cart_data.dishes[i];\n var params = {\n TableName: 'CustomerOrderTable',\n Item: {\n 'orderID' : { N: Date.now().toString() },\n 'cost' : {N: dish.cost.toString() },\n 'customer' : { S: cart_data.user_name },\n 'deliveryLocation' : {S: cart_data.delivery_address},\n 'foodName' : {S: dish.name },\n 'paid' : {N: dish.cost.toString() },\n 'quantity' : {N: default_quantity.toString() },\n }\n };\n\n console.log(\"To be written\");\n console.log(params);\n\n // Call DynamoDB to add the item to the table\n ddb.putItem(params, function(err, data) {\n if (err) {\n console.log(\"Writing order to db - Error: \", err);\n return false;\n } \n else {\n console.log(\"Writing order to db - Success\", data);\n }\n });\n \n // Clear past order in localStorage, prepare for a new order\n clearUserOrder();\n return true;\n // index++;\n }\n}",
"function getProducts(order, callback) {\n const date = moment(order.dataValues.createdAt).format('LLLL');\n order.date = date;\n\n const { items } = order.dataValues.cart;\n const productIds = Object.keys(items);\n\n models.Product.findAll({\n attributes: ['id', 'title'],\n where: { id: productIds }\n })\n .then(products => {\n let productsObject = {};\n products.forEach(product => {\n productsObject[product.id] = product.title;\n });\n order.items = generateArray(productsObject, items);\n callback();\n }) // END .then(products => {\n .catch(err => callback(err));\n} // END (order, callback) => {",
"function InsertTablesContent(data) {\n\t//json mode\n\tvar orders = data.orders;\n\tvar items = data.inventory;\n\n\tinsertIntoDataTable(orders);\n\tinsertIntoItemTable(items);\n\t\n}",
"function getCartContents() {\n db.Cart\n .findAll({\n where: {\n UserId: authenticatedUser\n },\n include: [db.Product, db.User]\n })\n .then(function(cartItems) {\n \t//if there is something in the users shopping cart\n \tif (cartItems.length > 0) {\n //create order from cart items \t\n\t for (var i = 0; i < cartItems.length; i++) {\n\n\t db.Order\n\t .create({\n\t orderId: orderNum,\n\t quantity: cartItems[i].quantity,\n\t purchasePrice: cartItems[i].Product.price,\n\t ccLast4: ccLast4, \n\t BillingId: orderNum,\n\t ProductId: cartItems[i].Product.id,\n\t UserId: authenticatedUser, \n\t ShippingId: orderNum\n\t })\n\t .then(function(orders) {});\n\t }\n\t //place the order through Stripe\n\t placeOrder(cartItems);\n\n }\n })\n .catch(function(err) {\n console.log(err.message);\n // response.send(err);\n });\n }",
"fetchOrdersByCustomerId(customerId, kioskStationId) {\n AppDispatcher.handleCartAction({\n actionType: ActionConstants.ORDER_REQUEST_DATA,\n customerId: customerId,\n kioskStationId: kioskStationId\n });\n OrderApi.initOrdersDataByCustomerId(customerId, kioskStationId);\n }",
"function or_place_all_orders()\n{\n\t\n\t//loop for each supplier and place order for only those suppliers which are not placed yet \n\t$.each (supplier_orders_list, function (supplier_id, supplier_order_detail)\n\t{\n\t\tif(typeof(supplier_order_detail)!='undefined')\n\t\t{\n\t\t\tif (!supplier_order_detail.ordered)\n\t\t\t{\n\t\t\t\t//Place order for the supplier\n\t\t\t\t//alert(supplier_id);\n\t\t\t\t//alert(supplier_orders_list[supplier_id].products_list);\n\t\t\t\tor_place_order(supplier_id);\n\t\t\t}\n\t\t}\n\t});\n}",
"function getPedals() {\n $$.getJSON('Pedals.json', function (json) {\n myApp.template7Data.pedalslist = json ;\n });\n}",
"function setJSONAddressToOrderAddress(orderAddress, jsonObj) {\n orderAddress.setFirstName(jsonObj.firstName);\n orderAddress.setLastName(jsonObj.lastName);\n orderAddress.setPhone(jsonObj.phone);\n orderAddress.setAddress1(jsonObj.address1);\n orderAddress.setAddress2(jsonObj.address2);\n orderAddress.setCity(jsonObj.city);\n orderAddress.setStateCode(jsonObj.stateCode);\n orderAddress.setPostalCode(jsonObj.postalCode);\n orderAddress.setCountryCode(jsonObj.countryCode.value);\n}",
"function populateDepotObjectsReport(depot, owner, depotsId, depotObjectsId, callback){\n DepotObject.create({\n\n depot: depot,\n owner: owner,\n name: \"test depot object\",\n image: null,\n guarantee: \"\",\n dateOfExpiry: \"\",\n description: \"Depot Description\"\n\n }, function (err, result) {\n\n depotObjectsId.push(new ObjectId(result._id));\n\n DepotObject.create({\n\n depot: depot,\n owner: owner,\n name: \"test depot object\",\n image: null,\n guarantee: \"2016-06-17\",\n dateOfExpiry: \"2016-06-17\",\n uses: 21,\n description: \"Depot Description\"\n\n }, function (err, result) {\n\n depotObjectsId.push(new ObjectId(result._id));\n\n DepotObject.create({\n\n depot: depot,\n owner: owner,\n name: \"test depot object\",\n image: null,\n guarantee: \"2017-02-17\",\n dateOfExpiry: \"2017-02-17\",\n uses: 21,\n description: \"Depot Description\"\n\n }, function (err, result) {\n\n depotObjectsId.push(new ObjectId(result._id));\n\n DepotObject.create({\n\n depot: depot,\n owner: owner,\n name: \"test depot object\",\n image: null,\n guarantee: \"2017-07-01\",\n dateOfExpiry: \"2017-07-01\",\n uses: 21,\n description: \"Depot Description\"\n\n }, function (err, result) {\n\n depotObjectsId.push(new ObjectId(result._id));\n\n Depot.create({\n\n name: \"Depot name\",\n owner: owner,\n location: \"Depot Location\",\n type: \"Storage Room\",\n distance: \"[0-1km]\",\n description: \"Depot Description\"\n\n }, function (err, result) {\n\n depotsId.push(new ObjectId(result._id));\n\n callback();\n\n });\n\n });\n\n });\n\n });\n\n });\n}",
"function importList (obj) {\n let data = obj.dishes;\n let done = 0;\n $('#label_file_input').text(done + \" / \" + data.length);\n data.forEach(function (item) {\n let title = item.name + \" #\" + item.category.toLowerCase();\n let obj = {\n title: title,\n ingredients: item.ingredients.join('\\n'),\n description: \"\"\n };\n console.log(obj);\n // send to api\n $.post(\"/recipes/add\", obj, () => {\n done++;\n $('#label_file_input').text(done + \" / \" + data.length);\n if (done == data.length) {\n location.reload();\n }\n });\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies client authentication on the request's header if either basic authentication or bearer token authentication is selected. | injectAuthenticatedHeaders(opts, bearerToken) {
var _a;
// Bearer token prioritized higher than basic Auth.
if (bearerToken) {
opts.headers = opts.headers || {};
Object.assign(opts.headers, {
Authorization: `Bearer ${bearerToken}}`,
});
}
else if (((_a = this.clientAuthentication) === null || _a === void 0 ? void 0 : _a.confidentialClientType) === 'basic') {
opts.headers = opts.headers || {};
const clientId = this.clientAuthentication.clientId;
const clientSecret = this.clientAuthentication.clientSecret || '';
const base64EncodedCreds = this.crypto.encodeBase64StringUtf8(`${clientId}:${clientSecret}`);
Object.assign(opts.headers, {
Authorization: `Basic ${base64EncodedCreds}`,
});
}
} | [
"function setHeaderWithToken() {\n var cookie = $.cookie(\"accessToken\");\n\n $(document).ajaxSend(function (event, jqxhr, settings) {\n jqxhr.setRequestHeader('Authorization', 'bearer ' + cookie);\n });\n }",
"function authorize(request, token) {\n return Object.assign(\n { headers: {'Authorization': `userToken=${token}` } },\n request)\n}",
"procesarHeaders(){\n var headers = {\n \"Accept\": \"*/*\",\n \"User-Agent\": \"Cliente Node.js\"\n };\n if(this.basicAuth != undefined){\n headers.Authorization = \"Basi c\" + this.basicAuth;\n }\n return headers;\n }",
"function bearerAuth(req, res, next) {\r\n passport.authenticate('bearer', {\r\n session: false\r\n },\r\n function(err, user, info) {\r\n if (err) return res.send(500, err);\r\n if (!req.query.access_token) {\r\n return res.send(401, {\r\n message: \"An access token must be provided\"\r\n });\r\n }\r\n if (!user) {\r\n return res.send(401, {\r\n message: \"Access token has expired or is invalid\"\r\n });\r\n }\r\n req.user = user;\r\n next();\r\n })(req, res, next);\r\n }",
"setAuthToken(requestObject) {\n if (this._token) {\n return requestObject.set(\n 'Authorization',\n `Token ${this._token}`\n );\n }\n return requestObject;\n }",
"function authAware(req, res, next) {\n if (req.session.oauth2tokens) {\n req.oauth2client = getClient();\n req.oauth2client.setCredentials(req.session.oauth2tokens);\n }\n\n next();\n\n // Save credentials back to the session as they may have been\n // refreshed by the client.\n if (req.oauth2client) {\n req.session.oauth2tokens = req.oauth2client.credentials;\n }\n }",
"function attachToken(request) {\r\n var token = getToken();\r\n if (token) {\r\n request.headers = request.headers || {};\r\n request.headers['x-access-token'] = token;\r\n }\r\n return request;\r\n }",
"function setAxiosToken(token) {\n axios.defaults.headers[\"Authorization\"] = \"Bearer \" + token;\n}",
"static isAuthenticated(req, res, next) {\n const Authorization = req.get('Authorization');\n\n if (Authorization) {\n const token = Authorization.replace('Bearer ', '');\n try {\n // JWTSECRET=some long secret string\n const payload = jwt.verify(token, process.env.JWTSECRET);\n\n // Attach the signed payload of the token (decrypted of course) to the request.\n req.jwt = {\n payload\n };\n\n next();\n } catch {\n // The JSON Web Token would not verify.\n res.sendStatus(401);\n }\n } else {\n // There was no authorization.\n res.sendStatus(401);\n }\n }",
"authenticate() {\n this.set('hasResponseMessage', null);\n const {\n formatUsername,\n password,\n api,\n selectedEnvironemnt\n } = this.getProperties('formatUsername', 'password', 'api', 'selectedEnvironemnt');\n return this.get('session').authenticate('authenticator:application', formatUsername, password, api, selectedEnvironemnt)\n .catch(() => {\n this.set('hasResponseMessage', \"Invalid login. Please try again.\");\n });\n }",
"defaultHeaders(otherHeaders = {}) {\n\n let acceptHeaders = {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }\n\n return Object.assign({}, acceptHeaders, otherHeaders)\n }",
"function validateAndInitHeader(event) {\n vm.isAuth = TcAuthService.isAuthenticated()\n if (vm.isAuth) {\n initHeaderProps(event)\n } else {\n loadUser().then(function(token) {\n // update auth flag\n vm.isAuth = TcAuthService.isAuthenticated()\n initHeaderProps(event)\n }, function(error) {\n // do nothing, just show non logged in state of navigation bar\n })\n }\n }",
"function isAuthenticatedAs(req, username) {\n if (isAuthenticated(req)) {\n if (getUsername(req) === username) {\n return true;\n } else {\n return false;\n }\n }\n}",
"function setCommonHeaders(req) {\n // Set (or clear) user agent\n if (userAgent) {\n req.set('User-Agent', userAgent);\n } else {\n req.unset('User-Agent');\n }\n // Prevent caching so response time will be accurate\n req\n .set('Cache-Control', 'no-cache')\n .set('Pragma', 'no-cache');\n }",
"_checkAuthenticationStatus()\n {\n // First, check if we have the appropriate authentication data. If we do, check it.\n // If we don't, trigger an event to inform of login require.\n if (this._token.value === '')\n {\n Radio.channel('rodan').trigger(RODAN_EVENTS.EVENT__AUTHENTICATION_LOGINREQUIRED);\n }\n else\n {\n var authRoute = Radio.channel('rodan').request(RODAN_EVENTS.REQUEST__SERVER_GET_ROUTE, 'auth-me');\n var request = new XMLHttpRequest();\n request.onload = (event) => this._handleAuthenticationResponse(event);\n request.ontimeout = (event) => this._handleTimeout(event);\n request.open('GET', authRoute, true);\n request.setRequestHeader('Accept', 'application/json');\n this._setAuthenticationData(request);\n request.send();\n }\n }",
"static Authorize(req, res, role) {\n return __awaiter(this, void 0, void 0, function* () {\n // Checks if a token is provided\n const token = req.header('x-access-token');\n if (!token) {\n return false;\n }\n const verify = this.verify(token, process.env.TOKEN_SECRET, role);\n if (!verify) {\n return false;\n }\n else if (verify) {\n return true;\n }\n });\n }",
"authenticate({ method, ruri, body }, challenge, cnonce = null /* test interface */)\n {\n this._algorithm = challenge.algorithm;\n this._realm = challenge.realm;\n this._nonce = challenge.nonce;\n this._opaque = challenge.opaque;\n this._stale = challenge.stale;\n\n if (this._algorithm)\n {\n if (this._algorithm !== 'MD5')\n {\n logger.warn('authenticate() | challenge with Digest algorithm different than \"MD5\", authentication aborted');\n\n return false;\n }\n }\n else\n {\n this._algorithm = 'MD5';\n }\n\n if (!this._nonce)\n {\n logger.warn('authenticate() | challenge without Digest nonce, authentication aborted');\n\n return false;\n }\n\n if (!this._realm)\n {\n logger.warn('authenticate() | challenge without Digest realm, authentication aborted');\n\n return false;\n }\n\n // If no plain SIP password is provided.\n if (!this._credentials.password)\n {\n // If ha1 is not provided we cannot authenticate.\n if (!this._credentials.ha1)\n {\n logger.warn('authenticate() | no plain SIP password nor ha1 provided, authentication aborted');\n\n return false;\n }\n\n // If the realm does not match the stored realm we cannot authenticate.\n if (this._credentials.realm !== this._realm)\n {\n logger.warn('authenticate() | no plain SIP password, and stored `realm` does not match the given `realm`, cannot authenticate [stored:\"%s\", given:\"%s\"]', this._credentials.realm, this._realm);\n\n return false;\n }\n }\n\n // 'qop' can contain a list of values (Array). Let's choose just one.\n if (challenge.qop)\n {\n if (challenge.qop.indexOf('auth-int') > -1)\n {\n this._qop = 'auth-int';\n }\n else if (challenge.qop.indexOf('auth') > -1)\n {\n this._qop = 'auth';\n }\n else\n {\n // Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here.\n logger.warn('authenticate() | challenge without Digest qop different than \"auth\" or \"auth-int\", authentication aborted');\n\n return false;\n }\n }\n else\n {\n this._qop = null;\n }\n\n // Fill other attributes.\n\n this._method = method;\n this._uri = ruri;\n this._cnonce = cnonce || Utils.createRandomToken(12);\n this._nc += 1;\n const hex = Number(this._nc).toString(16);\n\n this._ncHex = '00000000'.substr(0, 8-hex.length) + hex;\n\n // Nc-value = 8LHEX. Max value = 'FFFFFFFF'.\n if (this._nc === 4294967296)\n {\n this._nc = 1;\n this._ncHex = '00000001';\n }\n\n // Calculate the Digest \"response\" value.\n\n // If we have plain SIP password then regenerate ha1.\n if (this._credentials.password)\n {\n // HA1 = MD5(A1) = MD5(username:realm:password).\n this._ha1 = Utils.calculateMD5(`${this._credentials.username}:${this._realm}:${this._credentials.password}`);\n }\n // Otherwise reuse the stored ha1.\n else\n {\n this._ha1 = this._credentials.ha1;\n }\n\n let a2;\n let ha2;\n\n if (this._qop === 'auth')\n {\n // HA2 = MD5(A2) = MD5(method:digestURI).\n a2 = `${this._method}:${this._uri}`;\n ha2 = Utils.calculateMD5(a2);\n\n logger.debug('authenticate() | using qop=auth [a2:\"%s\"]', a2);\n\n // Response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2).\n this._response = Utils.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth:${ha2}`);\n\n }\n else if (this._qop === 'auth-int')\n {\n // HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody)).\n a2 = `${this._method}:${this._uri}:${Utils.calculateMD5(body ? body : '')}`;\n ha2 = Utils.calculateMD5(a2);\n\n logger.debug('authenticate() | using qop=auth-int [a2:\"%s\"]', a2);\n\n // Response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2).\n this._response = Utils.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth-int:${ha2}`);\n\n }\n else if (this._qop === null)\n {\n // HA2 = MD5(A2) = MD5(method:digestURI).\n a2 = `${this._method}:${this._uri}`;\n ha2 = Utils.calculateMD5(a2);\n\n logger.debug('authenticate() | using qop=null [a2:\"%s\"]', a2);\n\n // Response = MD5(HA1:nonce:HA2).\n this._response = Utils.calculateMD5(`${this._ha1}:${this._nonce}:${ha2}`);\n }\n\n logger.debug('authenticate() | response generated');\n\n return true;\n }",
"_configureAuthentication() {\n this.authenticator = new Authenticator(this.appConfig.oauth);\n }",
"auth({ username, password, refreshToken }) {\n let authBody = authData;\n if (typeof refreshToken !== 'undefined') {\n // 使用 refreshToken 刷新令牌\n authBody.grant_type = 'refresh_token';\n authBody.refresh_token = refreshToken;\n } else if (typeof username !== 'undefined' &&\n typeof password !== 'undefined') {\n // 使用账号密码刷新令牌\n authBody.grant_type = 'password';\n authBody.username = username;\n authBody.password = password;\n } else {\n // 无效输入\n return Promise.reject(new Error('wrong params input'));\n }\n\n return this._post({\n url: 'https://oauth.secure.pixiv.net/auth/token',\n body: authBody\n }).then(body => {\n this.accessToken = 'Bearer ' + body.response.access_token;\n this.refreshToken = body.response.refresh_token;\n this.isLogin = true;\n\n return body.response;\n });\n }",
"constructor(authString) {\n this.eloquaOptions = {\n headers: {\n authorization: authString\n }\n };\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
consolidateHtml takes in a string of html gotten from curl on genius lyric page and splices out only the lyrics section defined by content between .lyrics_container and .song_footer | function consolidateHtml(str) {
var relevantHtml = str.substring(str.indexOf("<lyrics *>")+1);
relevantHtml = relevantHtml.substring(0,relevantHtml.indexOf("</lyrics>"));
return relevantHtml;
} | [
"function addLyricsToPage(lyrics, title) {\n var str = consolidateHtml(lyrics);\n //console.log(str);\n var links = addOnClicks(str);\n //console.log(links);\n var output = \"<div class='lyric-title-container'>\" + \n \"<h2 class='lyric-title'>\" + title + \"</h2>\" + \"</div>\";\n links[0].id = \"lyricsContainer\";\n for(i = 0; i < links.length; i++) {\n output += links[i].outerHTML;\n }\n output = output;\n document.getElementById(\"watch-discussion\").innerHTML = \"\";\n document.getElementById(\"watch-discussion\").innerHTML = output;\n setUpListeners();\n linkIds = [];\n}",
"function parse(lrc)\n{\n str=lrc.split(\"[\");\n //str[0]=\"\"\n //str[1]=\"xx:xx.xx]lyrics1\"\n //str[2]=\"yy:yy.yy]lyrics2\"\n //Skip str[0]\n for(var i=1;i<str.length;i++)\n {\n //str[i] format is 00:11.22]x\n //time format is 00:11.22\n var time=str[i].split(']')[0];\n //lyrics format is \"x\"\n var lyrics=str[i].split(']')[1];\n var minute=time.split(\":\")[0];\n var second=time.split(\":\")[1];\n //xx:xx.xx is converted into total seconds\n var sec=parseInt(minute)*60+parseInt(second);\n //save total seconds\n timeArray[i-1]=sec-sessionStorage.time;\n //save lyrics\n lyricsArray[i-1]=lyrics;\n }\n var allLyrics=document.getElementById(\"poemContent\");\n var counter = 0;\n for(var i=0;i<timeArray.length;i++) {\n allLyrics.innerHTML += '<p class=\"sentence\" id=\"' + i + '\">' + lyricsArray[i] + '</p>';\n\n }\n\n\n}",
"function getElements() {\n\n for(let i = 0; i < 6; i++) {\n var idxBeg = $(\"source\").value.indexOf(begSubstrings[i]);\n eoeElements[i] = $(\"source\").value.substring(idxBeg + begSubstrings[i].length - 1);\n var idxEnd = eoeElements[i].indexOf(\"</\");\n eoeElements[i] = eoeElements[i].substring(i,idxEnd);\n }\n\n //A little post-loop cleanup to catch irregularities in styling from page to page\n eoeElements[0] = eoeElements[0].substring(1,eoeElements[0].length)\n\n if(eoeElements[1].substring(0,7) == ` class=`) {\n eoeElements[1] = eoeElements[1].substring(19,eoeElements[1].length)\n }\n\n startOfLinkText = eoeElements[4].lastIndexOf(`>`) + 1\n eoeElements[4] = eoeElements[4].substring(startOfLinkText,eoeElements[4].length)\n\n endOfLink = eoeElements[3].indexOf('jcr:') -1\n eoeElements[3] = \"http://www.buffalo.edu/ubit/news/article.host.html/\" + eoeElements[3].substring(0, endOfLink) + \".detail.html\"\n\n endOfImageLink = eoeElements[5].indexOf(`\"`)\n eoeElements[5] = \"http://www.buffalo.edu/content/shared/www\" + eoeElements[5].substring(0,endOfImageLink)\n\n $(\"textArea\").innerHTML = \"<b>Title: </b>\" + eoeElements[0] +\n \"<br><b>Teaser: </b>\" + eoeElements[1] +\n \"<br><b>Link text: </b>\" + eoeElements[4] +\n \"<br><b>Link: </b>\" + eoeElements[3];\n\n $(\"image\").innerHTML = \"<img src='\" + eoeElements[5] + \"'></img>\"\n}",
"function addOnClicks(relevantHtml) {\n var relHTML = relevantHtml.replace(\"<p>\", \"\");\n relHTML = relHTML.replace(\"</p>\", \"\");\n \n var html = $.parseHTML(relHTML);\n //console.log(relevantHtml);\n var links = $(\".lyrics\", html);\n //iterate over links and add onclick and remove href to <a>\n for(i = 0; i < links[0].children.length; i++) {\n if(links[0].children[i].tagName == 'A') {\n links[0].children[i].removeAttribute(\"href\");\n links[0].children[i].id = links[0].children[i].getAttribute(\"data-id\");\n linkIds.push(links[0].children[i].id);\n links[0].children[i].onclick = function() {\n annotationOnClick(this.id);\n };\n }\n }\n return links;\n}",
"function parse(html, shouldSort) {\n var $ = cheerio.load(html);\n\n return $('page').map((idx, pageElem) => {\n var $page = $(pageElem);\n\n return new Page(\n $page.attr('width'), $page.attr('height'),\n $page.children('word').map((idx, wordElem) => {\n var $word = $(wordElem);\n\n return new Text(\n $word.attr('xmin'), $word.attr('xmax'),\n $word.attr('ymin'), $word.attr('ymax'), $word.text().trim()\n );\n }).get()\n );\n }).get();\n}",
"convertHtml(htmlText, lnMode) {\n const docDef = [];\n this.lineNumberingMode = lnMode || LineNumberingMode.None;\n // Cleanup of dirty html would happen here\n // Create a HTML DOM tree out of html string\n const parser = new DOMParser();\n const parsedHtml = parser.parseFromString(htmlText, 'text/html');\n // Since the spread operator did not work for HTMLCollection, use Array.from\n const htmlArray = Array.from(parsedHtml.body.childNodes);\n // Parse the children of the current HTML element\n for (const child of htmlArray) {\n const parsedElement = this.parseElement(child);\n docDef.push(parsedElement);\n }\n return docDef;\n }",
"function processMostUniqueWords(songs) {\n // we will need to process lyric sections in the same way as part II \n // next we will need to process lyric sections for unique words \n // we will need two additional fields in our store for this section: \n // we will need to store the lyric sections\n // we will also need to store the unique words count \n const artistAttributions = [];\n const artistLyrics = [];\n songs.map(song => {\n // go through the lyrics_text and break out into lyric sections \n const lyricText = song.lyrics_text.split('\\n\\n');\n // go through each item in the array of lyric sections and sanitize the data for more artist attributions \n lyricText.map(section => {\n // now we are at the lyric section level for each song\n // we want to properly attribute a section to the artist or artists who sing it\n // we need to sanitize the string and return an array of artist(s)\n const regex = /\\[(.*?)\\]/g;\n const sectionAttribution = section.match(/\\[(.*?)\\]/g);\n const sectionLyricsSeparated = section.replace(regex, '');\n // console.log({sectionLyricsSeparated});\n // console.log({sectionAttribution});\n \n const attributionsHeadersSeparated = sectionAttribution[0].split(':');\n if (attributionsHeadersSeparated.length == 1) {\n // if length equals 1 it means there is no additional attribution on this section and we can attribute it to the primary_artist \n artistAttributions.push(song.primary_artist);\n artistLyrics.push({\n artistName: song.primary_artist,\n artistLyrics: sectionLyricsSeparated\n });\n\n \n } else {\n // else continue to find artists in headers \n const artistStr = attributionsHeadersSeparated[1].replace(/]/i, '');\n const artistStr2 = artistStr.replace(/Both/i, '');\n // noticed there were occurrences of the word Both throughout some of the data \n\n const headersStripped = artistStr2\n .split(',').join('').split('+').join('').split('&')\n // TODO: super ugly ^ go back and fix this \n headersStripped.map(artist => {\n artistAttributions.push(artist.trim())\n const trimmedName = artist.trim();\n let obj = {\n artistName: trimmedName,\n artistLyrics: sectionLyricsSeparated\n }\n artistLyrics.push(obj);\n \n });\n\n\n }\n\n\n });\n });\n // console.log(artistAttributions);\n console.log(artistLyrics);\n\n // assignLyricSectionToArtist(artistAttributions);\n // assignLyricTextToArtist(artistLyrics);\n\n}",
"loadWrapper(headHtml, cardContainer, category) {\n if (headHtml != undefined && cardContainer != undefined) {\n let headCardWrapper = document.createElement(\"div\");\n let line = document.createElement(\"div\");\n headCardWrapper.classList.add(\"right-workflow-wrapper\");\n line.classList.add(\"horizontal-line\");\n line.classList.add(\"line\");\n headCardWrapper.id = category.categorySlug;\n headCardWrapper.innerHTML = headHtml;\n headCardWrapper.appendChild(cardContainer);\n headCardWrapper.appendChild(line);\n this.wrapper.appendChild(headCardWrapper);\n this.cardEvents();\n }\n else if (headHtml == undefined && cardContainer == undefined) {\n let headCardWrapper = document.querySelectorAll(\".right-workflow-wrapper\");\n headCardWrapper.forEach((wrp) => {\n if (wrp.id == category.categorySlug) {\n let Ele = document.getElementById(wrp.id);\n let parent = Ele.parentElement;\n parent.removeChild(wrp);\n }\n })\n }\n }",
"cleanupHTML(html) {\n const parser = new DOMParser();\n const document = parser.parseFromString(html, \"text/html\");\n const rootNode = document.body;\n const preprocessedNode = this.preprocessNodes(rootNode);\n const cleanedHtml = DomPurify.sanitize(preprocessedNode.innerHTML, {ALLOWED_TAGS: this.safeTags, ALLOWED_ATTR: this.safeAttributes, ADD_URI_SAFE_ATTR: this.uriSafeAttr});\n return cleanedHtml;\n }",
"collectHeadingsAndKeywords() {\n const $ = cheerio.load(fs.readFileSync(this.pageConfig.resultPath));\n this.collectHeadingsAndKeywordsInContent($(`#${CONTENT_WRAPPER_ID}`).html(), null, false, []);\n }",
"function displaySimpleLyric(data,songArtist,songName)\n{\n if(data.lyrics==undefined){\n alert(\"Sorry no lyric found\");\n document.getElementById('lyricSimple').innerHTML=\"<h1></h1>\";\n }\n else{\n const lyric = data.lyrics.replace(/(\\r\\n|\\r|\\n)/gi,'<br>');\n const string =`<h1 class='text-success mb-4'>${songArtist} - ${songName}</h1>\n <h5 id='fulll-lyric' class='lyric text-white'>\n ${lyric}\n \n </h5>`\n document.getElementById('lyricSimple').innerHTML=string;\n } \n \n}",
"function parseText( string, parsedText ) {\n var matches;\n parsedText = parsedText || [];\n\n if ( !string ) {\n return parsedText;\n }\n\n matches = descriptionRegex.exec( string );\n if ( matches ) {\n // Check if the first grouping needs more processing,\n // and if so, only keep the second (markup) and third (plaintext) groupings\n if ( matches[ 1 ].match( descriptionRegex ) ) {\n parsedText.unshift( matches[ 2 ], matches[ 3 ] );\n } else {\n parsedText.unshift( matches[ 1 ], matches[ 2 ], matches[ 3 ] );\n }\n\n return parseText( matches[ 1 ], parsedText );\n } else if ( !parsedText.length ) {\n // No links found\n parsedText.push( string );\n }\n\n return parsedText;\n }",
"function extractSections() {\n for (var i = 0; i < nytResponse.results.length; i++) {\n var s = nytResponse.results[i].section;\n append(sections, s);\n }\n\n}",
"function displayLyric(data,songArtist,songName){\n \n if(data.lyrics==undefined){\n document.getElementById('lyricFancy').innerHTML=\"<h1>SORRY! NOT FOUND</h1>\";\n alert(\"Sorry no lyric found\"); \n }\n\n else{\n const lyric = data.lyrics.replace(/(\\r\\n|\\r|\\n)/gi,'<br>');\n \n const string =`<h1 class='text-success mb-4'>${songArtist} - ${songName}</h1>\n <h5 id='fulll-lyric' class='lyric text-white'>\n ${lyric}\n \n </h5>`\n document.getElementById('lyricFancy').innerHTML=string;\n } \n}",
"function prepareHTML(source) {\n $(\"#progress\").removeClass('hide');\n var listContainer = $(\"#listContainer\");\n var configs = [\n {\n header : 'Knowledge Articles',\n pattern : /KB\\d{6,7}/g,\n url : origin + '/kb_view.do?sysparm_article=',\n tableName : 'kb_knowledge',\n fields : 'short_description',\n labelsMap : {\n 'short_description' : 'Short description'\n },\n limit : 1\n },\n {\n header : 'Problems',\n pattern : /PRB\\d{6,7}/g,\n url : origin + '/problem.do?sysparm_query=number=',\n tableName : 'problem',\n fields : 'problem_state,description,priority',\n labelsMap : {\n 'problem_state' : 'Problem state',\n 'description' : 'Description',\n 'priority' : 'Priority'\n },\n fieldsMap : {\n 'problem_state' : {\n '-40' : 'New',\n '-42' : 'Investigation',\n '1' : 'Confirmed',\n '2' : 'Work in Progress',\n '9' : 'Testing',\n '3' : 'Closed'\n },\n 'priority' : {\n '0' : 'Critical (Outage)',\n '2' : 'High',\n '3' : 'Moderate',\n '4' : 'Low',\n '5' : 'Planning'\n }\n },\n limit : 1\n },\n {\n header : 'Tasks',\n pattern : /INT\\d{6,7}/g,\n url : origin + '/incident.do?sysparm_query=number=',\n tableName : 'incident',\n fields : 'severity,description',\n labelsMap : {\n 'severity' : 'Severity',\n 'description' : 'Description'\n },\n limit : 1\n },\n {\n header : 'Fix Targets',\n pattern : /FIX\\d{6,7}/g,\n url : origin + '/u_fix_target.do?sysparm_query=number=',\n tableName : 'u_fix_target',\n fields : 'description,state',\n labelsMap : {\n 'state' : 'State',\n 'description' : 'Description'\n },\n fieldsMap : {\n 'state' : {\n '-50' : 'Draft',\n '-51' : 'Awaiting Fix',\n '2' : 'Work in Progress',\n '-7' : 'Ready for Testing',\n '-52' : 'Testing Failed',\n '3' : 'Closed'\n }\n },\n limit : 1\n },\n {\n header : 'Stories',\n pattern : /STRY\\d{6,7}/g,\n url : origin + '/rm_story.do?sysparm_query=number=',\n tableName : 'rm_story',\n fields : 'description,state',\n labelsMap : {\n 'state' : 'State',\n 'description' : 'Description'\n },\n fieldsMap : {\n 'state' : {\n '-6' : 'Draft',\n '1' : 'Ready',\n '2' : 'Work in progress',\n '-7' : 'Ready for testing',\n '-8' : 'Testing',\n '3' : 'Complete',\n '4' : 'Cancelled',\n '6' : 'Accepted',\n '5' : 'Ready for acceptance'\n }\n },\n limit : 1\n }\n ];\n\n for (var i = 0; i < configs.length; i++) {\n var config = configs[i];\n // preparing the list container.\n var itemListContainer = document.createElement('div');\n\n // preparing the unordered list.\n var itemUl = document.createElement('ul');\n itemUl.setAttribute('class', 'collection with-header text-primary');\n itemUl.appendChild(prepareListHeader(config.header));\n\n var items = source.match(config.pattern);\n\n if (items) {\n prepareResultsList(itemUl, items, config);\n itemListContainer.appendChild(itemUl);\n listContainer.append(itemListContainer);\n }\n }\n if (0 === listContainer.children().length) {\n showErrorNotification('No records found on the page', true);\n }\n $(\"#progress\").hide();\n}",
"_computeMeta() {\n let metaText = '';\n let matches = [];\n if (this.sutta && this.sutta.text) {\n matches = this.sutta.text.match(/<footer>((.|\\n)*)<\\/footer>/);\n }\n try {\n if (matches && matches.length > 0) {\n metaText = matches[1];\n }\n } catch (e) {\n console.error(e);\n }\n return metaText;\n }",
"function extractTextInfo(pageContent) {\n\n\ttext_block = pageContent;\n\ttext_info = [];\n\n\tfor (var i = 0; i < text_block.length; i++) {\n\t\t//getting the text coordinate information\n\t\tvar res = text_block[i].split(\";\");\n\t\t\n\t\tvar coordinate_split_left = res[3].split(\":\");\n\t\tvar coordinate_split_top = res[4].split(\":\");\n\t\tvar coordinate_split_width = res[5].split(\":\");\n\t\tvar coordinate_split_height = res[6].split(\":\");\n\n\t\tvar left = coordinate_split_left[1];\n\t\tvar top = coordinate_split_top[1];\n\t\tvar width = coordinate_split_width[1];\n\t\tvar height = coordinate_split_height[1];\n\n\t\tleft = parseInt(left);\n\t\ttop = parseInt(top);\n\t\twidth = parseInt(width);\n\t\theight = parseInt(height);\n\n\t\tvar single_coordinate = [left, top, width, height];\n\n\t\t// getting the text field string, remove the html tag and other redundant information.\n\t\tvar sample = text_block[i];\n\t\tvar mark = 'font-size';\n\t\tvar res = ''; \n\t\tvar index_start = sample.indexOf(mark);\n\n\t\tvar sub_sample = sample.substr(index_start);\n\n\t\tindices = getIndicesOf(sub_sample,'font-size');\n\t\tvar result = \"\";\n\t\tfor (var l = 0; l < indices.length; l++) {\n\t\t\tvar index_start = indices[l];\n\t\t\tvar curr_sample = sub_sample.substr(index_start+16);\n\t\t\tvar index_start = curr_sample.indexOf('</span>');\n\t\t\tif (index_start != -1) {\n\t\t\t\tcurr_sample = curr_sample.substring(0, index_start);\n\t\t\t}\n\t\t\tcurr_sample = curr_sample.split(\"<br>\").join(\"\");\n\t\t\tcurr_sample = curr_sample.split(\"\\n\").join(\"\");\n\n\t\t\tresult += curr_sample;\n\t\t}\n\t\ttext_info.push([single_coordinate, result]);\n\t}\n\treturn text_info;\n}",
"function requestKaAns(err,response,html){\n console.log(err);\n // console.log(res.statusCode);\n //console.log(html);//html code of URL will be printed by this\n //fs.writeFileSync(\"ipl.html\",html);//explaination in copy \n //html page -> selector -> input\n //load file\n //load html\n console.log(\"Received file\");\n let STool=ch.load(html);\n let outputObj = STool(\"div.summary\");\n //it give html of that matching element\n //console.log(outputObj.html());\n //it gives val\n //console.log(outputObj.text());\n //select => unique\n //html => output -> html\n //fs.writeFileSync(\"summary.html\",outputObj.text());\n let inningsArr=STool(\"div.card.content-block.match-scorecard-table\");//1 innings' table will be stored here \n let fullHtml=\"<table>\";//to present the output as a table\n for(let i = 0 ; i < inningsArr.length-1 ; i++){\n let tableBatsman = STool(inningsArr[i]).find(\"table.table.batsman\");//STool will wrap the data. find() will find the batsman table in that data\n //extract batsman from the table\n fullHtml+= STool(tableBatsman).html();\n fullHtml+= \"<table>\";\n }\n fs.writeFileSync(\"innings.html\", fullHtml);\n}",
"_set_htmls(self, htmls) {\n var childIDs = Object.keys(htmls);\n for (var i = 0; i < childIDs.length; i++) {\n self.set_html(htmls[childIDs[i]], childIDs[i]);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve Available Payment Options Retrieves all payment types available within the requested Infusionsoft account | async getAllPaymentOptions () {
return this._api.request('InvoiceService.getAllPaymentOptions')
} | [
"ListAvailablePaymentMethodsInThisNicCountry() {\n let url = `/me/availableAutomaticPaymentMeans`;\n return this.client.request('GET', url);\n }",
"RetrieveAvailablePaymentMethod() {\n let url = `/me/payment/availableMethods`;\n return this.client.request('GET', url);\n }",
"paymentMethodOptions() {\n const {settings, invoices, setProp} = this.props;\n const selectedPaymentMethod = invoices.get('paymentMethod');\n const achAvailable = settings.getIn(['achInfo', 'accountNumber']);\n const ccAvailable = settings.get(['ccInfo', 'number']);\n // Determine payment options\n const paymentOptions = [];\n if (achAvailable) {\n paymentOptions.push({value: 'bank-account', name: 'Bank account'});\n // ACH only, select it\n if (!ccAvailable && selectedPaymentMethod === 'credit-card') {\n setProp('bank-account', 'paymentMethod');\n }\n }\n if (settings.get('getCcInfoSuccess')) {\n paymentOptions.push({value: 'credit-card', name: 'Credit card'});\n // CC only, select it\n if (!ccAvailable && selectedPaymentMethod === 'bank-account') {\n setProp('credit-card', 'paymentMethod');\n }\n }\n return Immutable.fromJS(paymentOptions);\n }",
"function getLanguageTypes() {\n personLanguageProficiencyLogic.getLanguageTypes().then(function (response) {\n $scope.languageList = response;\n }, function (err) {\n appLogger.log(err);\n appLogger.error('ERR', err);\n\n });\n\n }",
"async getAllShippingOptions () {\n return this._api.request('InvoiceService.getAllShippingOptions')\n }",
"function createPaymentOptions() {\n\teditCashHistoryFundRowId = null;\n\tresetCashSection();\n\tshowTotalPaymentAndDue(); /* Disable the guest user more info and create account box */\n\tvar paymentOptionTypes = JSON.parse(localStorage.getItem(\"fundingSourceTypes\"));\n\tvar cashPaymentOptions = new Array();\n\tfor(var paymentOptionIndex in paymentOptionTypes) {\n\t\tvar paymentOptionType = paymentOptionTypes[paymentOptionIndex];\n\t\tvar paymentOptionSourcesJsonType = paymentOptionType.jsonType;\n\t\tvar paymentOptionTenderType = paymentOptionType.tenderType;\n\t\tif(paymentOptionSourcesJsonType === jsonTypeConstant.PROMOCREDIT){\n\t\t\tif(parseBoolean(localStorage.getItem(\"registerUser\"))) {\n\t\t\t\tvar visiblePromoCodeInputId = getVisiblePromoCodeBoxId();\n\t\t\t\t$(\"#\" + visiblePromoCodeInputId).val(\"\");\n\t\t\t\t$(\"#promoCodeSection\").show();\n\t\t\t} else {\n\t\t\t\t$(\"#discountAndPromoCodeReg\").show();\n\t\t\t\t$(\"#promoCodeBox\").show();\n\t\t\t}\n\t\t\t$(\"#errorPromoCodeRes\").hide();\n\t\t\t$(\"#summuryPromoCode\").hide();\n\t\t\t$('#checkoutPromoCodeAmount').hide();\n\t\t\tvar visiblePromoCodeInputId = getVisiblePromoCodeBoxId();\n\t\t\t$(\"#\" + visiblePromoCodeInputId).removeClass(\"error_red_border\");\n\t\t\tsubmitBtnEnableUI('checkoutApply');\n\t\t\tvalidationTracking = UNVALIDATED;\n\t\t\tlastPromoCode = \"\";\n\t\t\tregisterEventsForPromoCode();\n\t\t}\n\t\t/* if payment method is cash (create cash options) else create card option */\n\t\tif (paymentOptionTenderType && paymentOptionTenderType.toUpperCase() === tenderTypeConstant.CASH) {\n\t\t\tcashPaymentOptions.push(paymentOptionType);\n\t\t}\n\t}\n\tif (cashPaymentOptions.length > 0) {\n\t\t$(\"#checkoutCreditsCoverAllAmountDue\").hide();\n\t\t$(\"#cardPaymentOptionsContainer\").show();\n\t\t$(\"#cashDataMainContainer\").show(); /* Show CASH ribbon on screen */\n\t\tcreateCashPaymentOption(cashPaymentOptions.sort(sortByFundingSourceType));\n\t}\n\texpandSingleFundingSource();\n\t\n}",
"function hidePaymentOptions() {\n // loop through paymentOptions object and set display to none\n for (prop in paymentOptions)\n toggleView(paymentOptions[prop], false);\n }",
"function setupPaymentMethods17() {\n const queryParams = new URLSearchParams(window.location.search);\n if (queryParams.has('message')) {\n showRedirectErrorMessage(queryParams.get('message'));\n }\n\n $('input[name=\"payment-option\"]').on('change', function(event) {\n\n let selectedPaymentForm = $('#pay-with-' + event.target.id + '-form .adyen-payment');\n\n // Adyen payment method\n if (selectedPaymentForm.length > 0) {\n\n // not local payment method\n if (!('localPaymentMethod' in\n selectedPaymentForm.get(0).dataset)) {\n\n resetPrestaShopPlaceOrderButtonVisibility();\n return;\n }\n\n let selectedAdyenPaymentMethodCode = selectedPaymentForm.get(\n 0).dataset.localPaymentMethod;\n\n if (componentButtonPaymentMethods.includes(selectedAdyenPaymentMethodCode)) {\n prestaShopPlaceOrderButton.hide();\n } else {\n prestaShopPlaceOrderButton.show();\n }\n } else {\n // In 1.7 in case the pay button is hidden and the customer selects a non adyen method\n resetPrestaShopPlaceOrderButtonVisibility();\n }\n });\n }",
"ListOfPaypalAccountsUsableForPaymentsOnThisAccount() {\n let url = `/me/paymentMean/paypal`;\n return this.client.request('GET', url);\n }",
"function GetDropDownList() {\n var typeCodeList = [\"WMSYESNO\", \"WMSRelationShip\", \"INW_LINE_UQ\", \"PickMode\"];\n var dynamicFindAllInput = [];\n\n typeCodeList.map(function (value, key) {\n dynamicFindAllInput[key] = {\n \"FieldName\": \"TypeCode\",\n \"value\": value\n }\n });\n var _input = {\n \"searchInput\": dynamicFindAllInput,\n \"FilterID\": appConfig.Entities.CfxTypes.API.DynamicFindAll.FilterID\n };\n\n apiService.post(\"eAxisAPI\", appConfig.Entities.CfxTypes.API.DynamicFindAll.Url + authService.getUserInfo().AppPK, _input).then(function (response) {\n if (response.data.Response) {\n typeCodeList.map(function (value, key) {\n PickupanddeliverydetailCtrl.ePage.Masters.DropDownMasterList[value] = helperService.metaBase();\n PickupanddeliverydetailCtrl.ePage.Masters.DropDownMasterList[value].ListSource = response.data.Response[value];\n });\n }\n });\n }",
"function LoadDropDownValuesForPayment(id,str)\r\n{\r\n var dropDownList =document.getElementById(id);\r\n\tif(showACHItem('ccdpay'))\r\n\t{\r\n\t var optn=document.createElement(\"OPTION\");\r\n\t optn.text = \"CCD Payment (Corporate)\";\r\n\t optn.value = \"CCD\"+str;\r\n\t dropDownList.options.add(optn);\r\n\t}\r\n\tif(showACHItem('child'))\r\n\t{\r\n\t var optn=document.createElement(\"OPTION\");\r\n\t optn.text = \"Child Support Payment\";\r\n\t optn.value = \"CHILD\"+str;\r\n\t dropDownList.options.add(optn);\r\n\t}\r\n\tif(showACHItem('ctx'))\r\n\t{\r\n\t var optn=document.createElement(\"OPTION\");\r\n\t optn.text = \"CTX Payment (Corporate Trade Exchange)\";\r\n\t optn.value = \"CTX\"+str;\r\n\t dropDownList.options.add(optn);\r\n\t}\r\n\tif(showACHItem('federal'))\r\n\t{\r\n\t var optn=document.createElement(\"OPTION\");\r\n\t optn.text = \"Federal Tax\";\r\n\t optn.value = \"FED\"+str;\r\n\t dropDownList.options.add(optn);\r\n\t}\r\n\tif(showACHItem('iat'))\r\n\t{\r\n\t var optn=document.createElement(\"OPTION\");\r\n\t optn.text = \"IAT Payment (International)\";\r\n\t optn.value = \"IAT\"+str;\r\n\t dropDownList.options.add(optn);\r\n\t}\r\n\tif(showACHItem('payment'))\r\n\t{\r\n\t var optn=document.createElement(\"OPTION\");\r\n\t optn.text = \"PPD Payment (Personal)\";\r\n\t optn.value = \"PPD\"+str;\r\n\t dropDownList.options.add(optn);\r\n\t}\r\n\tif(showACHItem('state'))\r\n\t{\r\n\t var optn=document.createElement(\"OPTION\");\r\n\t optn.text = \"State Tax\";\r\n\t optn.value = \"STATE\"+str;\r\n\t dropDownList.options.add(optn);\r\n\t}\r\n\tif(showACHItem('stp820'))\r\n\t{\r\n\t var optn=document.createElement(\"OPTION\");\r\n\t optn.text = \"STP 820 Payment\";\r\n\t optn.value = \"STP820\"+str;\r\n\t dropDownList.options.add(optn);\r\n\t}\r\n}",
"getChoices() {\r\n const cardOptions = [\r\n {\r\n value: 'Gora',\r\n synonyms: ['gora']\r\n },\r\n {\r\n value: 'Pass',\r\n synonyms: ['pass']\r\n },\r\n {\r\n value: 'Pabili',\r\n synonyms: ['pabili']\r\n }\r\n ];\r\n\r\n return cardOptions;\r\n }",
"function getPricingSchemesList() {\n $.get(\"api/pricing\", function(pricingSchemes) {\n console.log(pricingSchemes);\n });\n\n }",
"function hideAllPaymentOptions() {\n creditCard.style.display = 'none';\n paypal.style.display = 'none';\n bitcoin.style.display = 'none';\n}",
"ListOfRegisteredPaymentMeanYouCanUseToPayThisOrder(orderId) {\n let url = `/me/order/${orderId}/availableRegisteredPaymentMean`;\n return this.client.request('GET', url);\n }",
"function show_payment_form() {\n var $payment_el = $(this); // Using `this` is gross.\n var $form = $payment_el.parents('form');\n var payment_type = $payment_el.val();\n var class_name = 'payment-info-' + payment_type;\n $form.find('.payment-info').each(function () {\n var $el = $(this);\n if ($el.hasClass(class_name))\n $el.show();\n else\n $el.hide();\n });\n show_element($form);\n if (payment_type == 'paypal') {\n var $email = $form.find('[name=\"paypal_email\"]');\n if ($email.val() === '')\n $email.val($form.find('[name=\"email\"]').val());\n }\n }",
"function paymentOptions(option) {\r\n const ccDIV = document.getElementById(\"credit-card\");\r\n const ppDIV = document.getElementById(\"paypal\");\r\n const bitcoinDIV =document.getElementById(\"bitcoin\");\r\n if(option == \"credit card\"){\r\n ccDIV.style.display = \"inherit\";\r\n ppDIV.style.display = \"none\";\r\n bitcoinDIV.style.display = \"none\";\r\n } else if (option == \"paypal\"){\r\n ccDIV.style.display = \"none\";\r\n ppDIV.style.display = \"inherit\";\r\n bitcoinDIV.style.display = \"none\";\r\n } else if (option == \"bitcoin\"){\r\n ccDIV.style.display = \"none\";\r\n ppDIV.style.display = \"none\";\r\n bitcoinDIV.style.display = \"inherit\";\r\n }\r\n}",
"ListOfAuthorizedDeferredPaymentAccountForThisCustomer() {\n let url = `/me/paymentMean/deferredPaymentAccount`;\n return this.client.request('GET', url);\n }",
"function getBP(){\n\t\t\tapi.GET('billing_periods',{sy:$scope.ActiveSy, limit:'less'}, function success(response){\n\t\t\t\t$scope.billing_periods = response.data;\n\t\t\t})\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send a request to refresh the captcha image. | function _refreshCaptcha() {
$.getJSON(config.captchaRefreshURL, {}, function(json) {
$captcha_image[0].src = json.image_url;
$captcha_image.next()[0].value= json.key;
});
return false;
} | [
"function vpb_refresh_aptcha()\r\n{\r\n\treturn $(\"#vpb_captcha_code\").val('').focus(),document.images['captchaimg'].src = document.images['captchaimg'].src.substring(0,document.images['captchaimg'].src.lastIndexOf(\"?\"))+\"?rand=\"+Math.random()*1000;\r\n}",
"function Refresh_Image(the_id)\n{\n var data = {\n action: 'x2_get_image',\n id: the_id\n };\n\t\t\n jQuery.get(ajaxurl, data, function(response)\n\t\t{\n\n if(response.success === true)\n\t\t\t{\n jQuery('#x2-preview-image').replaceWith( response.data.image );\n }\n });\n}",
"function gifRefresh() {\n window.location.reload();\n}",
"function recargar_captcha() {\n\tvar url = \"captcha.php\";\n\tvar src = \"\";\n\tvar pars = \"recargar=si\";\n\tvar ajax = new Ajax.Request(url, {\n\t\t//Cuando es sincrono _NO_ se ejecutan los callbacks\n\t\tasynchronous : false,\n\t\tparameters : pars,\n\t\tmethod : \"post\",\t\t\n\t\t//onComplete : procesaRespuesta\t\t\n\t});\n\tfunction procesaRespuesta(resp) {\n\t\tvar text = resp.responseText;\t\n\t\tsrc = text;\n\n\t}\n\tprocesaRespuesta(ajax.transport);\n\treturn src;\n}",
"function reloadImage(img) {\n const src = img.attr('src');\n img.removeAttr('src');\n setTimeout(() => {\n img.attr('src', src);\n }, 500);\n}",
"function sendImage(e) {\n \n var uri = '',\n data = {};\n\n if (!isAndroid && cv.toDataURL) {\n uri = cv.toDataURL();\n }\n else {\n uri = (Canvas2Image.saveAsBMP(cv, true, cWidth, cHeight)).src;\n }\n\n data.imageData = uri;\n \n $.ajax({\n url: '/post',\n type: 'post',\n data: data\n }).done(function (res) {\n\n //clear the image.\n ctx.fillRect(0, 0, cWidth, cHeight);\n });\n }",
"async function initiateCaptchaRequest(api_key) {\n const form_data = {\n method: \"userrecaptcha\",\n pageurl: config.uber_login_url,\n googlekey: config.uber_site_key,\n key: api_key,\n json: 1,\n };\n console.log(\n `Submitting soution request to 2Captcha for ${config.uber_login_url}`\n );\n const response = await request.post(config.captcha_submit_url, {\n form: form_data,\n });\n return JSON.parse(response).request;\n}",
"onApplyRecaptchaExpired() {\n this.store.dispatch( this.actions.expiredRecaptcha( 'Apply' ) );\n }",
"function sendImage(date, id) {\n let year = date.getFullYear()\n let month = date.getMonth() + 1\n let day = date.getDate()\n //load the page\n request({\n uri: \"http://www.gocomics.com/calvinandhobbes/\" + year + \"/\" + month + \"/\" + day,\n }, function(error, response, body) {\n let $ = cheerio.load(body)\n //get the picture\n let pictureUrl = $('.item-comic-image img').attr('src')\n console.log(pictureUrl)\n //send pic to user\n bot.sendPhoto(id, pictureUrl)\n })\n}",
"function updatePicture () {\n MeteorCameraUI.getPicture({ width: 400, height: 400 }, function (err, data) {\n // what is this sorcery...\n if (err && err.error == 'cancel') {\n return;\n }\n\n if (err) {\n return handleError(err);\n }\n\n $ionicLoading.show({\n template: 'Updating picture...'\n });\n // calling data from the server method, receiving data back from server\n Meteor.call('updatePicture', data, (err) => {\n $ionicLoading.hide();\n handleError(err);\n });\n });\n }",
"function requestGifFromServer( cmd , param ){\n debug.log( \"[getGifImage]:\", \"Requesting GIF for:\", param );\n\n loader.show(); //Show loading\n\n api( cmd, param, function( response ){\n renderGifResponse( response.data ); //Display final GIF\n debug.log(\"[requestGifFromServer]\", \"RESPONSE:\", response);\n } , function(){\n loader.hide();\n });\n}",
"function change_send_img_rate(rate){\n interval = rate;\n if(send_loop_id == null){\n return;\n }else{\n end_send_loop();\n send_img_loop();\n } \n}",
"function updateSlimemanImage() {\n document.getElementById(\"SlimemanImage\").src = \"assets/images/face\" + (maxTries - remainingGuesses) + \".png\";\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}",
"async function attemptReload() {\n await fetch(''); // Check the server really is back\n location.reload();\n }",
"function replay() {\n\tlocation.reload();\n}",
"function refresh() {\n\tsetInterval(function() {\n\t\tconsole.log(\"refresh\");\n\t\twindow.location.reload();\n\t}, 20000);\n}",
"function sendResetPasswordRequest() {\n if (validateInputFieldOfResetArea()) {\n /* To show the progress bar */\n showProgressBar();\n\n $('#new_pwd').removeClass(\"error_red_border\");\n $('#re_new_pwd').removeClass(\"error_red_border\");\n /* Used for Disable the button and coming from utility.js */\n disableButton(\"reset_pwd\");\n \n var request = {};\n request.userId = user_auth_obj.userId;\n request.applicationId = applicationId;\n request.locale = getCookie(\"locale\");\n request.newPassword = $('#re_new_pwd').val();\n \n var call_user_reset_pwd = new user_reset_pwd(request);\n call_user_reset_pwd.call();\n }\n}",
"function url_force_reload(url) { \n var date_now = new Date();\n return url + '?v=' + date_now.getTime(); \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
changes the price of a stock to a random new one, in a given range | CHANGE_PRICES(state) {
// use a forEach() because it's an array
// otherwise if it was an object you'd for(x in y)
state.stocks.forEach(stock => {
// doesn't make sense for the volatility to vary between a large range,
// so it should only be a growth or shrinkage of the original price
const min = 0.85
const max = 1.15
// the tried and true rand * (max - min) + min range calculation
stock.pps = Math.round(stock.pps * (Math.random() * (max - min) + min))
})
} | [
"changeStockPrices(state) {\n state.stocks.forEach(stock => {\n stock.price = Math.round(stock.price * (1 + Math.random() - 0.5));\n });\n }",
"function priceChange() {\n\tfor (var i = 0; i < fruits.length; i++) {\n\t\tvar randomPrice = randomNumber(-.50, .50);\n\t\tvar currentPrice = fruits[i][1];\n\t\tvar newPrice = randomPrice + currentPrice;\n\t\tif (newPrice < .50) {\n\t\t\tnewPrice = .50;\n\t\t} else if (newPrice > 9.99) {\n\t\t\tnewPrice = 9.99;\n\t\t}\n\t\tfruits[i][1] = newPrice;\n\t}\n}",
"function changeFruitPrice (fruit) {\n\tvar priceAdj = 0;\n\t//randomly chooses a value between -50 and 50\n\tpriceAdj = randomNumber(-50,50);\n\t//turns it in to cents\n\tpriceAdj /= 100;\n\tconsole.log(\"priceAdj\", priceAdj);\n\tfruit.price +=priceAdj;\n\t//prevents the fruit price from going above 9.99 and below .50\n\tif (fruit.price > 9.99) {\n\t\tfruit.price = 9.99;\n\t} else if (fruit.price < 0.50) {\n\t\tfruit.price = 0.50;\n\t}\n\tvar price = '#' + fruit.name + \"Price\";\n\t$(price).text(fruit.price.toFixed(2));\n}",
"function updatePrice(fruit) {\n\tconsole.log(\"updatePrice:\", 'running');\n\tdo {\n\t\tvar priceChange = randomNumber(-50, 50);\n\t\tconsole.log('priceChange', priceChange);\n\t\tfruit.price += priceChange;\n\t} while(fruit.price >= 999 || fruit.price <= 50);\n\n\tconsole.log(fruit.price);\n\treturn fruit.price;\n}",
"function getRandomStockMove( originalPrice, volatilityIndex, dir = null) {\n let magnitude;\n let direction;\n let volatility;\n\n // calculate direction if necessary\n if (dir === null) {\n direction = Math.floor(Math.random() * 2); // 0 or 1\n } else {\n direction = dir;\n }\n\n // a random magnitude\n magnitude = Math.random() * volatilityIndex;\n\n return !direction ? ( originalPrice - magnitude ) : ( originalPrice + magnitude );\n}",
"function getRandomMoney(){\n var num = Math.random();\n if (num < 0.6) {\n money = 10000;\n prestige = 10;\n } else if (num < 0.9) {\n money = 100000;\n prestige = 30;\n } else if (num < 0.99) {\n money = 1000000;\n prestige = 50;\n } else {\n money = 10000000;\n prestige = 70;\n };\n }",
"async price_update() {}",
"function updatePrice() {\n for (i=0;i<fruitList.length;i++){\n object = $('.fruits').eq(i).data();\n object.marketPrice = generateRandomPrice(object.marketPrice);\n $('.fruits').eq(i).data(object);\n $('.fruits').eq(i).find('.market-price').text(object.marketPrice);\n }\n }",
"function randomFromInterval(from,to){return Math.floor(Math.random()*(to-from+1)+from);}",
"generateCalBurnt()\r\n {\r\n var calories = Math.floor((Math.random() * 20) + 1)\r\n console.log(calories)\r\n }",
"function randomSalary(min, max) {\n return Math.random() * (max - min) + min;\n}",
"function getRandomFloat(min, max, fix) {\n\treturn ((Math.random() * (max - min)) + min).toFixedNumber(fix)\n}",
"function scheduleNextTrade(){\n setTimeout(makeRandomTrade, 1000);\n}",
"async function changePrice(srcToken, destToken, rate) {\n console.log(\"change price to \" + rate);\n\n const gasPrice = await C.web3.eth.getGasPrice();\n\n return new Promise(resolve => {\n C.contractPriceFeed.methods.setRates(srcToken, destToken, C.web3.utils.toWei(rate.toString(), 'Ether'))\n .send({ from: A.owner[0].adr, gas: 2500000, gasPrice: gasPrice })\n .then(async (tx) => {\n //console.log(\"change price Transaction: \", tx);\n resolve(tx.transactionHash);\n })\n .catch((err) => {\n console.error(\"Error on changing price\");\n console.error(err);\n });\n });\n}",
"function getRandomFloat(min, max)\n{\n return min + Math.random() * (max - min);\n}",
"function getRandomFloat(min, max) {\r\n return Math.random() * (max - min + 1) + min;\r\n}",
"function randomInt(low, high){\n\treturn Math.round(Math.random()*(high-low)+low);\n}",
"set price(value) {\n this._price = 80;\n }",
"function randomize() {\n $(\"#saturation\").slider('value', rand(0, 100));\n $(\"#lightness\").slider('value', rand(0, 100));\n\n var min = rand(0, 360);\n var max = rand(0, 360);\n\n if (min > max) {\n min = min + max;\n max = min - max;\n min = min - max;\n }\n\n $(\"#hue\").slider('values', 0, min);\n $(\"#hue\").slider('values', 1, max);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
the function is used to handle the event onkeyUpInput when user press any kay the method check if the length of the input is greater than 0 and the enable reply button if the input length is equal to 0 the reply button is disabled | function onKeyUpInputReply(e) {
/**
* the id of the replyButton
*
*/
var inputBtn = "#comment-" + e.currentTarget.id.split('-')[1] + "-reply-btn";
/**
* Get the reply input
*
*/
var reply = $("#" + e.currentTarget.id).val().trim();
/**
* check the reply length
*/
if (reply.length == 0) {
/**
* There is no input
*/
$(inputBtn).attr('disabled', 'disabled');
} else {
/**
* there is an input
*/
$(inputBtn).removeAttr('disabled');
}
} | [
"function checkCommentLength(textareaObj) {\n let key = event.keyCode || event.which;\n //check the number of character in textbox\n if (textareaObj.value.length > 0) {\n $(textareaObj).siblings('.comment-submit').removeAttr('disabled');\n /*I'm not sure if I should add the 'hit enter' feature. Comments are pretty\n detailed and the ability to use Enter might be useful.\n if (key === 13) {\n sendComment($(textareaObj).siblings('.comment-submit'));\n }*/\n }else {\n $(textareaObj).siblings('.comment-submit').attr('disabled', 'disabled');\n }\n\n}",
"function btnDisable() {\n // add disable attribute to the add button \n $(\"#add-topic-btn\").attr('disabled', true);\n $('input').keyup(function () {\n var disable = false;\n $('input:text').each(function () {\n if (userInput.val() == \"\") {\n disable = true;\n }\n });\n $('#add-topic-btn').prop('disabled', disable);\n });\n }",
"handleInteraction(input) {\n this.activePhrase.checkLetter(input);\n Array.from(document.getElementsByClassName('key')).forEach(key => { //Creating an array of the QWERTY keys to loop through.\n if (key.textContent === input && key.disabled !== true) {\n if (this.activePhrase.checkLetter(input) !== true) {\n key.disabled = true;\n key.classList.add('wrong');\n this.removeLife();\n } else {\n key.disabled = true;\n key.classList.add('chosen');\n this.activePhrase.showMatchedLetter(input);\n this.checkForWin();\n if (this.checkForWin()) {\n this.gameOver('win'); //If the checkForWin method returns true, the gameOver method is called and passed the 'win' parameter.\n }\n }\n }\n });\n }",
"onSendButtonClick() {\n const userInputValue = this.userInput.value;\n if (userInputValue != \"\" && userInputValue.replace(/\\s/g, \"\").length > 0) {\n window.character.send(userInputValue);\n }\n }",
"function input(event_type) {\r\n\tinput_keyboard_options_with_one_state(0, event_type, \"lowercase_alphabet\"); //virtual_keyboard option 0; alphabet\r\n\tinput_keyboard_options_with_two_states(1, event_type, \"lowercase_accent_characters_one\", 8, 9); //virtual_keyboard option 1; accent characters one\r\n\tinput_keyboard_options_with_two_states(2, event_type, \"lowercase_accent_characters_two\", 10, 11); //virtual_keyboard option 2; accent characters two\r\n\tinput_keyboard_options_with_one_state(3, event_type, \"lowercase_accent_characters_three\"); //virtual_keyboard option 3; accent characters three\r\n\tinput_keyboard_options_with_one_state(4, event_type, \"lowercase_accent_characters_four\"); //virtual_keyboard option 4; accent characters four\r\n\tinput_keyboard_options_with_two_states(5, event_type, \"punctuation_numbers_one\", 4, 5); //virtual_keyboard option 5; punctuation and numbers\r\n\tinput_keyboard_options_with_two_states(6, event_type, \"punctuation_numbers_two\", 6, 7); //virtual_keyboard option 6; punctuation\r\n\r\n\tinput_editing_keys(7, event_type, delete_function, \"Delete\"); //delete \r\n\tinput_character_keys(8, event_type, 0, \"KeyQ\") //q (113), Q (81), 1 (49)\r\n\tinput_character_keys(9, event_type, 1, \"KeyW\"); //w (119), W (87), 2 (50)\r\n\tinput_character_keys(10, event_type, 2, \"KeyE\"); //e (101), E (69), 3 (51)\r\n\tinput_character_keys(11, event_type, 3, \"KeyR\"); //r (114), R (82), 4 (52)\r\n\tinput_character_keys(12, event_type, 4, \"KeyT\"); //t (116), T (84), 5 (53)\r\n\tinput_character_keys(13, event_type, 5, \"KeyY\"); //y (121), Y (89), 6 (54)\r\n\tinput_character_keys(14, event_type, 6, \"KeyU\"); //u (117), U (85), 7 (55)\r\n\tinput_character_keys(15, event_type, 7, \"KeyI\"); //i (105), I (73), 8 (56)\r\n\tinput_character_keys(16, event_type, 8, \"KeyO\"); //o (111), O (79), 9 (57)\r\n\tinput_character_keys(17, event_type, 9, \"KeyP\"); //p (112), P (80), 0 (48)\r\n\tinput_editing_keys(18, event_type, backspace_function, \"Backspace\") //backspace\r\n\t\r\n\tinput_whitespace_keys(19, event_type, 9, \"Tab\"); //horizonal tab (9)\r\n\tinput_character_keys(20, event_type, 10, \"KeyA\"); //a (97), A (65), @ (64)\r\n\tinput_character_keys(21, event_type, 11, \"KeyS\"); //s (115), S (83), # (35)\r\n\tinput_character_keys(22, event_type, 12, \"KeyD\"); //d (100), D (68), $ (36)\r\n\tinput_character_keys(23, event_type, 13, \"KeyF\"); //f (102), F (70), & (38)\r\n\tinput_character_keys(24, event_type, 14, \"KeyG\"); //g (103), G (71), * (42)\r\n\tinput_character_keys(25, event_type, 15, \"KeyH\"); //h (104), H (72), ( (40)\r\n\tinput_character_keys(26, event_type, 16, \"KeyJ\"); //j (106), J (74), ) (41)\r\n\tinput_character_keys(27, event_type, 17, \"KeyK\"); //k (107), K (75),' (39)\r\n\tinput_character_keys(28, event_type, 18, \"KeyL\"); //l (108), L (76), \" (34)\r\n\tinput_whitespace_keys(29, event_type, 13, \"Enter\") //enter (13)\r\n\r\n\tinput_caps_lock(30, event_type, 0, 1, 2, 3, \"CapsLock\"); //left caps lock\r\n\tinput_character_keys(31, event_type, 19, \"KeyZ\"); //z (122), Z (90), % (37)\r\n\tinput_character_keys(32, event_type, 20, \"KeyX\"); //x (120), X (88), - (45)\r\n\tinput_character_keys(33, event_type, 21, \"KeyC\"); //c (99), C (67), + (43)\r\n\tinput_character_keys(34, event_type, 22, \"KeyV\"); //v (118), V (86), = (61)\r\n\tinput_character_keys(35, event_type, 23, \"KeyB\"); //b (98), B (66), / (47)\r\n\tinput_character_keys(36, event_type, 24, \"KeyN\"); //n (110), N (78), semicolon (59)\r\n\tinput_character_keys(37, event_type, 25, \"KeyM\"); //m (109), M (77), colon (59)\r\n\tinput_character_keys(38, event_type, 26, \"Comma\"); //comma (44), exclamtion mark (33)\r\n\tinput_character_keys(39, event_type, 27, \"Period\"); //full stop (46), question mark (63)\r\n\tinput_caps_lock(40, event_type, 0, 1, 2, 3, \"CapsLock\"); //right caps lock\r\n\r\n\tinput_keyboard_options_with_two_states(41, event_type, \"punctuation_numbers_one\", 4, 5); // punctuation numbers \r\n\tinput_keyboard_options_with_two_states(42, event_type, \"punctuation_numbers_two\", 6, 7);//punctuation 2\r\n\tinput_whitespace_keys(43, event_type, 32, \"Space\"); //space (32)\r\n\tinput_keyboard_options_with_two_states(44, event_type, \"lowercase_accent_characters_one\", 8, 9); //accent chars\r\n\tinput_keyboard_options_with_two_states(45, event_type, \"lowercase_accent_characters_two\", 10, 11); //accent chars 2\t\r\n}",
"function validateFormInput(inputText, button, buttonClassName, char) {\n if(inputText.length === 0) {\n button.disabled = true;\n button.style.opacity = .5;\n button.className = buttonClassName;\n } else if(inputText.length > 140) {\n button.disabled = true;\n button.style.opacity = .5;\n button.className = buttonClassName;\n char.style.color = 'red';\n } else {\n button.disabled = false;\n button.style.opacity = 1;\n button.classList.remove('no-hover');\n char.style.color = '';\n }\n}",
"function takeUserInput(value){\n if(value !== 'Submit' && value !== '<' && value !== 'C' && userInput.length < 4){\n userInput += value;\n print();\n }\n else{\n switch(value){\n case 'Submit': // if the submit button is pressed then call the isValid() function\n // to check whether the userInput is valid or not.\n tries--;\n isValid();\n break;\n case '<': // backspace statement.\n if(userInput.length > 0){\n userInput = userInput.substr(0, userInput.length -1); \n print();\n }\n break;\n case 'C': // delets all the userInput\n reset();\n }\n }\n\n function print(){ // prints the real time userInput value.\n userText.value = userInput;\n }\n\n } // end function registerInput();",
"function submitToBot(event) {\r\n\tif(event && event.keyCode != 13){\r\n\t\treturn false;\r\n\t}\r\n\tvar v = textInput.value.trim();\r\n\tif(v.length > 0) {\r\n\t\tnewInput(v);\r\n\t}\r\n}",
"function pressIt() {\n $('#typing').on('keydown', function(e) {\n if (e.which === 71){\n alert(\"you pressed G\");\n return;\n }\n })\n}",
"function processInput() {\r\n\t\r\n\tvar time = 500;\r\n\tif (isAnswer()) {\r\n\t\tconsole.log('isAnswer');\r\n\t\r\n\t} else if(isRepeat()){\r\n\t\tconsole.log('isRepeat');\r\n\t\t\r\n\t} else if (isTrigger()) {\r\n\t\tconsole.log('isTrigger');\r\n\t\t\r\n\t} else if (includeKey()) {\r\n\t\tconsole.log('includeKey');\r\n\t\t\r\n\t} else if (isShort()) {\r\n\t\t//return;\r\n\t\tconsole.log('isShort');\r\n\t} else if (noReaction()) {\r\n\t\treturn;\r\n\t} else {\r\n\t\tconsole.log('notUnderstood');\r\n\t\tnotUnderstood();\r\n\t}\r\n\t\r\n\tvar read = userInput.current.length*50;\r\n\t\r\n\t//setTimeout(showWriting,read);\r\n\t\r\n\ttime += Math.ceil((Math.random()*500)-250);\r\n\tif (botAction.repeat()){\r\n\t\tinputState(true);\r\n\t} else {\t\r\n\t\tsetTimeout(processAllActions,read+time);\r\n\t}\r\n\t\r\n\tuserInput.last = userInput.format;\r\n}",
"function privkeycheck() {\n \tvar privkeycheck = document.getElementById(\"privatekeyform\");\n\n \tif (privkeycheck.value.length == 64) {\n \t\tdocument.getElementById(\"privkeycheckbtn\").disabled = false;\n \t} else {\n \t\tdocument.getElementById(\"privkeycheckbtn\").disabled = true;\n \t}\n }",
"function input_character_keys(key_array_index, event_type, character_key_index, key_code) {\r\n\tkey_array[key_array_index].addEventListener(event_type, function(event) {\r\n\t\tif (event_type == \"keydown\" && document.getElementById(\"mirrored_textarea\") != document.activeElement) {\r\n\t\t\tif (event.key === \" \" || event.key === \"Enter\" || event.key === \"Spacebar\") {\r\n\t\t\t\ttoggle_button(event.target);\r\n\t\t\t\tevent.preventDefault();\r\n\t\t\t\tedit_textarea(character_key_index);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tevent.preventDefault();\r\n\t\t\tedit_textarea(character_key_index);\r\n\t\t}\r\n\t});\r\n\r\n\tdocument.addEventListener(\"keydown\", function(event) {\r\n\t\tif (event.defaultPrevented) {\r\n\t\t\treturn; // Do nothing if event already handled\r\n\t\t}\r\n\t\tif (event.code == key_code && modifier_key_pressed == false) {\r\n\t\t\ttoggle_button(event.target);\r\n\t\t\tkey_button_array[key_array_index].classList.add(\"focus\");\r\n\t\t\tsetTimeout(function () {key_button_array[key_array_index].classList.remove(\"focus\");}, 250);\r\n\t\t\tedit_textarea(character_key_index);\r\n\t\t\tevent.preventDefault();\r\n\t\t}\r\n\t});\r\n}",
"function keyDown() {\r\n checkOverflow(this);\r\n}",
"function MASE_InputVerifcode(el_input, event_key) {\n //console.log(\"=== MASE_InputVerifcode =====\") ;\n //console.log(\"event_key\", event_key) ;\n\n // enable save btn when el_input has value\n const disable_save_btn = !el_input.value;\n //console.log(\"disable_save_btn\", disable_save_btn) ;\n el_MASE_btn_save.disabled = disable_save_btn;\n\n if(!disable_save_btn && event_key && event_key === \"Enter\"){\n\n // hide info box\n el_MASE_info_container\n\n MASE_Save(\"save\")\n }\n }",
"function disableChatOnPressReturn(evt) {\n if (evt.which == 13 || evt.keyCode == 13) {\n VeAPI.Chat.manager.disable();\n //TODO: Change to delayChat\n return false;\n }\n return true;\n }",
"function updChatroomMsgEnter(state){\n $('.messages').on('keypress','#text', function (e) {\n var key = e.which;\n if(key === 13) // the enter key code\n {\n event.preventDefault();\n setUpdatedMessages(state,$('#text').val(),$('.conversation'));\n $('#text').val('');\n }\n });\n}",
"function validateUserInput(currentElement, evt, regEx) {\n /* Getting the char code for pressed key event */\n var charCode = evt.charCode;\n var regExpr = new RegExp(\"^\" + regEx + \"$\");\n // if browser version is IE-8\n if (navigator.appVersion.match(/MSIE [\\d.]+/) == \"MSIE 8.0\") {\n \tcharCode = evt.keyCode;\n }\n var txtBoxVal = $(currentElement).val().trim();\n /* To get the current cursor position with in the text */\n var inputIndex = $(currentElement).caret().start;\n /* To create the new amount string combining curent amount and new char pressed at cursor position */\n txtBoxVal = insertCharAt(txtBoxVal, inputIndex, String.fromCharCode(charCode));\n if (txtBoxVal) {\n if (isCtrlKeyPressed(evt, charCode)) { /* Validating for CTRL+C/X/V key event for firefox */\n return true;\n } else if (isSpecialKeyPressed(charCode)) { /* Validating for Left/Right arrow, Delete key event for firefox */\n return true;\n } else if (getSelectedArea() && regExpr.test(txtBoxVal)) { /* Checking if the complete or partial text is selected in input field */\n return true;\n } else {\n return regExpr.test(txtBoxVal);\n }\n }\n}",
"function user_is_typing(type, id)\n{\n\tvar token = $('#token').val();\n\tvar URL = $.base_url + 'ajax/chat_type_ajax.php';\n\tvar timer, timeout = 750;\n \n $(type).keyup(function()\n {\n if (typeof timer != undefined)\n clearTimeout(timer);\n\t\t\n $.post(URL, 'status=typing_'+id+'&token='+token, function(res) {});\n\t\t\n timer = setTimeout(function()\n {\n\t\t\t$.post(URL, 'status=stopped&token='+token, function(res) {});\n }, timeout);\n });\t\n}",
"function enableButtons() {\n\t//event listener for the guess button\n\t$(\"#guess\").click(function () { \n\t\t//calls the guesser function and passes the value of the input box to the function \n\t\tguesser($(\"#letterHolder\").val()); \n\t\t//and clears the letter input box after guess button is clicked\n\t\t$(\"#letterHolder\").val(\"\"); \n\t});\n\t\n\t$(\"#letterHolder\").removeAttr(\"disabled\");\n\t//initializes the letter holder for the first game\n\t//after the first game the code below is turned on and off\n\t//by removing or adding the the disabled css attribute\n\t//applied to the letterholder id \n\twindow.onload = () => {\n\t\t//does the same thing as as above but with the enter key while in the input box\n\t\t$(\"#letterHolder\").keypress(function (enterButton) { \n\t\t\tvar key = enterButton.which;\n\n\t\t\tif (key === 13) {\n\t\t\t\tguesser($(\"#letterHolder\").val());\n\t\t\t\t$(\"#letterHolder\").val(\"\");\n\t\t\t}\n\t\t});\n\t}\n\n\t$(\"#hintButton\").click(function () {\t\t\n\t\t$(\"#hint\").html(hintArray[hangManArray.indexOf(newWord)]);\n\t\thintUsed = true;\n\t})\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a function called odds that accepts an array as a parameter and returns an array of just the odd numbers. If you wrote it using each, great! If you used anything else, refactor it to use a for loop. | function odds(arr) {
oddArr = [];
each(arr, function(element) {
if (element % 2 !==0) {
oddArr.push(element);
};
});
return oddArr;
} | [
"function arrayodd() {\n var oddarray = [];\n for (var i = 1; i <= 50; i = i + 2) {\n oddarray.push(i);\n }\n return oddarray;\n}",
"function arrayOfOdds (arr){\n var arr = [];\n for(var i = 0; i <= 50; i++){\n if(i % 2 !== 0){\n arr.push(i);\n }\n }\n return arr;\n}",
"function evenIndexedOddNumbers(arr) {\n var output = [];\n each(arr, function(e, i) {\n if ((e % 2 !== 0) && (i % 2 === 0)) {\n output.push(e)\n }\n })\n return output;\n}",
"function oddities(array) {\n var oddElements = [];\n var i;\n\n for (i = 0; i < array.length; i += 2) {\n oddElements.push(array[i]);\n }\n\n return oddElements;\n}",
"function odds(arr) {\n return filter(arr, function(elem) {\n // remember to RETURN the filter function\n return elem % 2 !== 0;\n });\n}",
"function doubleOddNumbers(arr) {\n let oddNumsArr = arr.filter(function(num){\n return num%2 === 1\n })\n let oddNumsDoubledArr = oddNumsArr.map(function(num){\n return num * 2\n })\n return oddNumsDoubledArr\n}",
"function filterOddElements(arr) {\n\t// input/parameter --> array\n\t// EDGE CASE:\n\t//if the array has no odd elements\n\tif (arr.length === 0) {\n\t\t// return []\n\t\treturn [];\n\t}\n\t// create a result variable --> empty array\n\tconst oddArr = [];\n\t// iterate through the array\n\tfor (let i = 0; i < arr.length; i++) {\n\t\t// if element of array are not divisble by two --> odd\n\t\tif (arr[i] % 2 !== 0) {\n\t\t\t// push elements inside array\n\t\t\toddArr.push(arr[i]);\n\t\t}\n\t}\n\t//return the odd array\n\treturn oddArr;\n}",
"function evenOddPartition(arr) {\n\tconst evens = []\n\tconst odds = []\n\tarr.filter(int => int % 2 === 0 ? evens.push(int) : odds.push(int))\n\treturn [evens, odds]\n}",
"function pickIt(arr){\n var odd=[],even=[];\n \n for(let i = 0; i < arr.length; i++) {\n if(arr[i] % 2 === 0) even.push(arr[i])\n else odd.push(arr[i])\n }\n\n return [odd,even];\n}",
"function makeEven(array) {\n //tulislah code kalian disini!\n\n var result = [];\n if (array.length % 2 === 0) {\n for (i = 0; i < array.length; i++) {\n if (i === 1 || i === array.length-2) {\n continue;\n } else {\n result.push(array[i]);\n }\n }\n } else {\n for (i = 0; i < array.length; i++) {\n if (i === Math.round(array.length/2)-1) {\n continue;\n } else {\n result.push(array[i]);\n }\n }\n }\n return result;\n\n}",
"function processOddNums (arr) {\n // let finalIndex = arr.length -1;\n // let result = [];\n // for (let i = finalIndex; i > 0; i--) {\n // if (i % 2 !== 0) {\n // let num = 2 * arr[i];\n // result.push(num)\n // }\n // }\n // console.log(result.join(\" \"));\n\n console.log(\n (arr.filter((el, index) => index % 2 != 0))\n .map(e => e = 2 * e)\n .reverse()\n .join(\" \"))\n}",
"function countOdds(array) {\n var total = 0;\n for(var i = 0; i < array.length; i++) {\n if(array[i] % 2 != 0) {\n total++;\n }\n }\n return total;\n }",
"function evensAndOdds(arr) {\n var evens = 0;\n var odds = 0;\n\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] % 2 === 0) {\n odds = 0;\n evens++;\n if (evens === 3) {\n console.log(\"Even more so!\");\n evens = 0;\n }\n } else {\n evens = 0;\n odds ++;\n if (odds === 3) {\n console.log(\"That's odd!\")\n odds = 0;\n }\n }\n }\n}",
"function printOddNumbersOnly(arr) {\n arr.filter(num => num % 2 == 1).forEach(element => console.log(element));\n}",
"function evenOddTransform(arr, n) {\n\tfor (let i = 0; i < n; i++) {\n\t\tfor (let j = 0; j < arr.length; j++) {\n\t\t\tif (arr[j] % 2 !== 0) {\n\t\t\t\tarr[j] += 2;\n\t\t\t} else if (arr[j] % 2 === 0) {\n\t\t\t\tarr[j] -= 2;\n\t\t\t}\n\t\t}\n\t}\n\treturn arr;\n}",
"function addOdds(evensOnlyArray) {\n var newArr = []\n for(var i = 0; i < evensOnlyArray.length; i++) {\n newArr.push(evensOnlyArray[i] + 1)\n }\n evensOnlyArray.unshift(1)\n return allNums = evensOnlyArray.concat(newArr)\n}",
"function isPerfectlyOdd(arr){\n if(arr.length === 0){\n return false;\n } \nfor(let i =1; i<arr.length; i +=2){\n console.log(i);\n if(arr[i] % 2 === 0){\n // console.log(arr[i]);\n return false;\n }\n\n}\nreturn true;\n }",
"function segregateOddEven(arr,callback){\n let odd=[]\n let even=[] \n arr.map(function(x){\n (x%2==0?odd.push(x):even.push(x));\n })\n console.log(\"segregated array: \"+odd+\" \"+even);\n callback(odd,even,meanCalculator);\n}",
"function numberIndexEven(array){\r\n \r\n return map(array,function(value, index){\r\n if((typeof(value)==='number')&& (index%2===0)){\r\n return value*2;\r\n }else{ return value}\r\n })\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
END Purpose: This function handles ajax put request. It takes the id for the row that will be updated. Inputs: Id. Output: None. | function put() {
// Create a url for the ajax request.
$.each(editObject, function(index, value) {
if(index == 'id') {
url += index+"="+value;
} else {
url += "&"+index+"="+value;
}
});
$.ajax({
url: 'api/?'+url,
method: 'PUT',
data: editObject,
success: function() {
// Log a message apon success.
console.log("Item updated in inventory.");
// Reload the search from's select dropdowns and the table body.
reloadSelectDropdowns();
get();
// Clear the url string.
url = "";
},
error: function (xhr, ajaxOptions, thrownError) {
// Log any error messages.
console.log(xhr.status);
console.log(thrownError);
}
});
} | [
"updateById(id, data) {\n return this.post('/' + id + '/edit', data);\n }",
"function putToDos(id, data) {\n\n var defer = $q.defer();\n\n $http({\n method: 'PUT',\n url: 'http://localhost:50341/api/ToDoListEntries/' + id,\n data: data\n }).then(function(response) {\n if (typeof response.data === 'object') {\n defer.resolve(response);\n toastr.success('Updated ToDo List Item!');\n } else {\n defer.reject(response);\n //error if found but empty\n toastr.warning('Failure! </br>' + response.config.url);\n }\n },\n // failure\n function(error) {\n //error if the file isn't found\n defer.reject(error);\n $log.error(error);\n toastr.error('error: ' + error.data + '<br/>status: ' + error.statusText);\n });\n\n return defer.promise;\n }",
"update(req, res) {\n Origin.update(req.body, {\n where: {\n id: req.params.id\n }\n })\n .then(function (updatedRecords) {\n res.status(200).json(updatedRecords);\n })\n .catch(function (error){\n res.status(500).json(error);\n });\n }",
"function saveOrUpdateDetails() {\n // Collect Form Input Data into variable\n let bookname1 = $('#bookname').val();\n let studentid1 = parseInt($('#studentid').val());\n let issuedate1 = $('#issuedate').val();\n let issuestatus1 = $(\"#issuestatus\").val();\n\n // Collect Issue ID \n let issueid = $(\"#issueid\").val();\n let updateForm = false;\n\n if (issueid != \"\") {\n updateForm = true;\n issueid = parseInt(issueid)\n }\n\n // Save Details in Book Issue in JSON Form\n let issueData = {\n bookname: bookname1,\n studentid: studentid1,\n issuedate: issuedate1,\n issuestatus: issuestatus1\n };\n\n let requestType = \"POST\";\n let urlAddress = 'api/Issues'\n if (updateForm) {\n issueData['issueid'] = issueid;\n requestType = \"PUT\";\n urlAddress = 'api/Issues/' + issueid;\n }\n\n // Request the Web API for Insertion\n $.ajax({\n type: requestType,\n url: urlAddress,\n data: JSON.stringify(issueData),\n contentType: \"application/json; charset=utf-8\"\n }).done(function (response) {\n // Display Insert or Update Message\n let message = \"Book Issue Details are Saved in System\";\n if (updateForm) {\n message = \"Book Issue Details are Updated in System\";\n }\n alert(message);\n $(\"#details\").slideToggle();\n resetFormInput();\n\n loadTableData();\n }).fail(function (xhr, status) {\n // Error Message\n alert(\"Book Issue Details are not Saved in System\")\n\n $(\"#details\").slideToggle();\n resetFormInput();\n });\n}",
"function userUpdate(fname, lname, email, pswrd) {\n return $.ajax({\n method: \"PUT\",\n url: \"/api/user\",\n dataType: \"json\",\n contentType: \"application/json\",\n data: JSON.stringify({\n id: userInfo.id,\n fname: fname,\n lname: lname,\n email: email,\n password: pswrd\n })\n });\n}",
"Update(tablename, data, id, callback) {\n elasticClient.update({\n index: indexName,\n type: tablename,\n // version_type:version_type,\n id: id,\n // version: version,\n retry_on_conflict: 5,\n body: {\n doc: data,\n doc_as_upsert: true,\n }\n }, function (err, results) {\n callback(err, results)\n })\n }",
"function updateUser(user_id) {\n user = {\n Id: user_id,\n First_name: prevName.innerHTML,\n Last_name: prevLast.innerHTML,\n Password: prevPassword.innerHTML,\n IsAdmin: previsAdminCB.checked\n }\n ajaxCall(\"PUT\", \"../api/Users\", JSON.stringify(user), updateUser_success, updateUser_error);\n}",
"function saveOrUpdatePost(){\n\t\t\n\t\t//get the values from the input elements\n\t\tvar title=$('#edittitle').val();\n\t\tvar text=$('#edittext').val();\n\t\tvar id=$('#postid').val();\n\t\t\n\t\t//create the data object and fill it in\n\t\tvar dataObj = {};\n\t\tdataObj[\"id\"] = id;\n\t\tdataObj[\"title\"] = title;\n\t\tdataObj[\"text\"] = text;\n\t\t\n\t\t//make the call to saveorupdate REST Service\n\t\t$.ajax({ \n\t\t url: \"saveorupdatepost\", \n\t\t type: 'POST', \n\t\t dataType: 'json', \n\t\t data: JSON.stringify(dataObj), //convert to JSON String to pass to the service\n\t\t contentType: 'application/json',\n\t\t mimeType: 'application/json',\n\t\t success: function(data) { \n\t\t \tshowPost(data.id);\n\t\t },\n\t\t error:function(data,status,er) { \n\t\t alert(status+\",\"+er);\n\t\t }\n\t\t});\n\t\t\n\t}",
"function updateDog(id) {\n var x = document.forms[\"editdogform\"][\"name\"].value;\n var y = document.forms[\"editdogform\"][\"birthdate\"].value;\n var z = document.forms[\"editdogform\"][\"breed\"].value;\n\n if (x == \"\") {\n alert(\"Name must be filled out\");\n return false;\n }\n else if (y == \"\") {\n alert(\"Birthdate must be entered\");\n return false;\n }\n else if (z == \"\") {\n alert(\"Breed must be filled out\");\n return false;\n }\n else {\n $.ajax({\n url: '/dogs/' + id,\n type: 'PUT',\n data: $('#editdogform').serialize(),\n success: function (result) {\n window.location.replace(\"./\");\n }\n })\n }\n}",
"function editActivity(clicked_id) {\n\tvar baseUrl = \"http://localhost:8080/api/itinerary/event/update/\" + clicked_id;\n\tvar ddlDate = document.getElementById(\"ddlDate\" + clicked_id);\n\tvar startTime = document.getElementById(\"tbStartTime\" + clicked_id).value;\n\tvar endTime = document.getElementById(\"tbEndTime\" + clicked_id).value;\n\n\tvar checkValid = moment(startTime, \"hh:mm A\").isBefore(moment(endTime, \"hh:mm A\"));\n\n\t/* before allowing edit, check if time set is valid */\n\tif (checkValid == true) {\n\t\tdocument.getElementById(\"conflictAlert\" + clicked_id).style.display = \"none\";\n\n\t\t$.ajax({\n\t\t\turl: baseUrl,\n\t\t\ttype: \"PUT\",\n\t\t\tcontentType: \"application/json\",\n\t\t\tdata: JSON.stringify({\n\t\t\t\teventDate: ddlDate.options[ddlDate.selectedIndex].value,\n\t\t\t\tstartTime: moment(startTime, \"hh:mm A\").format(\"HH:mm\"),\n\t\t\t\tendTime: moment(endTime, \"hh:mm A\").format(\"HH:mm\"),\n\t\t\t}),\n\t\t}).done(function (responseText) {\n\t\t\tif (responseText[\"code\"] == 200) {\n\t\t\t\twindow.location.reload();\n\t\t\t}\n\t\t});\n\t} else {\n\t\tdocument.getElementById(\"conflictAlert\" + clicked_id).style.display = \"\";\n\t}\n}",
"function updateSupplier(req, res, next){ \n supplierService.update(req.params.id, req.body)\n .then((result)=> res.status(200).json(result))\n .catch((err)=>next(err));\n}",
"static updateCustomer (id, body) {\n return axios.put(`${url}/${id}`, body)\n }",
"function editTrain() {\n if (CurrentUser === undefined || CurrentUser === null) {\n $('#authModal').modal(); // Restrict access to logged in users only. \n return;\n }\n\n var uniqueKey = $(this).closest('tr').data('key');\n\n rowArray = [];\n $(this).closest('tr').children().each(function () {\n rowArray.push($(this).text());\n });\n\n for (var i = 0; i < rowArray.length; i++) {\n var inputID = \"#\" + scheduleTableFields[i];\n $(inputID).val(rowArray[i]);\n }\n\n $(\"#add-train-form\").data(\"key\", uniqueKey);\n $(\"#add-train-form\").data(\"action\", \"update\");\n var plusIcon = $(\"<i>\").addClass(\"fas fa-plus\");\n $(\"#add-train\").html(\"Update \").append(plusIcon);\n\n}",
"updateQuestion(id, q) {\n this._assertValidQuestion(q, false);\n const promise = this._ajaxUpdateQuestion(id, q);\n promise.then((response) => {\n const status = response.status;\n if (status >= 200 && status < 300) {\n q.id = id;\n this._localUpdateQuestion(q);\n } else {\n throw Error(`Unexpected PUT response: ${status}`);\n }\n });\n return promise;\n }",
"function editBusiness (editBusiness) {\n console.log('editBusiness function is run');\n $http({\n method: 'PUT',\n url: '/business/edit' + editBusiness.id,\n data: editBusiness\n }).then(function(response) {\n getBusiness();\n });\n console.log('editBusiness.id', editBusiness.id);\n } // NOTE: for: function editBusiness",
"function updateEmployee(employee,id,callback)\n{\n db.run(\"UPDATE Employees SET firstname=?,lastname=?,salary=?,role=? WHERE rowid=?\",\n [employee.firstname, employee.lastname, employee.salary, employee.role, id],\n function(err) { callback(); });\n}",
"function updateRemarks(id, data) {\n\tvar response = \"\";\n\t$.ajax({\n\t\tbeforeSend : function() {\n\t\t\t$('#spinner').show()\n\t\t},\n\t\tcomplete : function() {\n\t\t\t$('#spinner').hide();\n\t\t},\n\t\ttype : \"post\",\n\t\tasync : false,\n\t\tdata : JSON.stringify(data),\n\t\turl : myContextPath + \"/shipping/requestFromSales/remarks?id=\" + id,\n\t\tcontentType : \"application/json\",\n\t\tsuccess : function(data) {\n\t\t\tresponse = data;\n\t\t}\n\t});\n\treturn response;\n}",
"update(id, entity, config) {\n const url = this.resolveUrl(config, id);\n const method = (config && config.method) || this.getHttpMethod(HttpMethod.PUT);\n this.loader.dispatch({\n method,\n loading: true,\n entityId: id,\n storeName: this.store.storeName,\n });\n const configWithBody = Object.assign(Object.assign({}, config), { body: entity });\n return this.http.request(method, url, configWithBody).pipe(mapResponse(config), tap((responseEntity) => {\n if (!config || (config && !config.skipWrite)) {\n this.store.update(id, responseEntity);\n }\n this.dispatchSuccess({\n method,\n payload: responseEntity,\n successMsg: config && config.successMsg,\n });\n }), catchError((error) => this.handleError(method, error, config && config.errorMsg)), finalize(() => {\n this.loader.dispatch({\n method,\n loading: false,\n entityId: id,\n storeName: this.store.storeName,\n });\n }));\n }",
"function put() {\n let data = {\n name: userInfo.elements.name.value,\n firstname: userInfo.elements.firstname.value,\n lastname: userInfo.elements.lastname.value,\n email: userInfo.elements.email.value,\n password: userInfo.elements.password.value\n };\n\n let postData = JSON.stringify(data);\n\n fetch(`https://smackfly-2fd1.restdb.io/rest/users-fly-smacker/${id}`, {\n method: \"put\",\n headers: {\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"x-apikey\": \"5de40f274658275ac9dc2152\",\n \"cache-control\": \"no-cache\"\n },\n body: postData\n }\n)\n.then(d => d.json())\n.then( updatedUser => {\n userInfo.elements.name.value=updatedUser.name,\n userInfo.elements.firstname.value=updatedUser.firstname;\n userInfo.elements.lastname.value=updatedUser.lastname;\n userInfo.elements.email.value=updatedUser.email;\n userInfo.elements.password.value=updatedUser.password;\n\n updateUserBtn.textContent = \"Success!\";\n updateUserBtn.style.backgroundColor = \"#fca91f\";\n});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve the patient id from the reference | get patientId() {
// subject.reference = 'Patient/{patientId}'
return (
this._subject
&& this._subject.reference
&& this._subject.reference.split('/')[1]
);
} | [
"function getPatientByID(patientID) {\r\n return self.patients[patientID];\r\n }",
"id() {\n \n // implementation should be inside the child class, but below implementation\n // if for simplicity in many occasions\n if (typeof this.data.id != 'undefined') return this.data.id;\n\n // no ID\n return null;\n }",
"function extractCitationReferenceInfo(id) {\n var md = id.match(/^ref_([^_]+)_([0-9])+$/);\n return (md && {id: md[1], count: parseInt(md[2])}) || null;\n}",
"get recurrenceId()\n\t{\n\t\t//dump(\"get recurrenceId: title:\"+this.title+\", value:\"+this._calEvent.recurrenceId);\n\t\treturn this._calEvent.recurrenceId;\n\t}",
"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 getId(dbEntity){\n return dbEntity.entity.key.path[0].id ||\n dbEntity.entity.key.path[0].name;\n}",
"function GetGuidOfTheRecord(executionContext) {\n try {\n //Get the form context\n var formContext = executionContext.getFormContext();\n //Get the current Record Guid\n var recordGuid = formContext.data.entity.getId();\n Xrm.Utility.alertDialog(recordGuid);\n }\n catch (e) {\n Xrm.Utility.alertDialog(e.message);\n }\n}",
"get id() {\n this._id = getValue(`cmi.objectives.${this.index}.id`);\n return this._id;\n }",
"function findCurrentNote() {\n return $(\"#current-note-display\")[0].getAttribute(\"data-id\");\n}",
"function getPatientNumber() {\r\n return Object.keys(self.patients).length;\r\n }",
"@api get assetId(){\n return this.recordId;\n }",
"function getCDID(measure) {\n cdid = inflationIDMap[measure];\n return cdid;\n}",
"function getMemberId() {\n return $routeParams.memberId ? $routeParams.memberId : 'me';\n }",
"function getResID() {\n profile = JSON.parse(getCookie(\"spProfile\"));\n\n return Number(profile.RestaurantID);\n}",
"function getId(item) {\n // gets the id of an item\n return item.enchantment == 0 ? item.item_id : item.item_id + \"@\" + item.enchantment;\n}",
"function getReference(){\n\tif (typeof(Storage)!==\"undefined\"){\t\t\t\t\t\t\t\t\t// if the browser support web storage\n\t\tif (localStorage.getItem(\"referenceNumber\") !== null){\t\t\t// if there is reference number stored in the local storage\n\t\t\tdocument.getElementById(\"referenceNumber\").value = localStorage.getItem(\"referenceNumber\");\t\t//filled the reference number input\n\t\t}\n\t}\n}",
"function getClinicalObjectUid(writebackContext, pjdsClinicalObjectUid, callback) {\n if (pjdsClinicalObjectUid) {\n return callback(null, writebackContext, pjdsClinicalObjectUid);\n } else {\n var clinicalObject = {};\n clinicalObject.patientUid = writebackContext.model.patientUid;\n clinicalObject.authorUid = writebackContext.model.authorUid;\n clinicalObject.domain = 'ehmp-observation';\n clinicalObject.subDomain = 'labResult';\n clinicalObject.visit = writebackContext.model.visit;\n clinicalObject.ehmpState = 'active';\n clinicalObject.referenceId = writebackContext.model.referenceId;\n pjds.create(writebackContext.logger, writebackContext.appConfig, clinicalObject, function(err, response) {\n if (err) {\n return callback(err);\n }\n writebackContext.logger.debug({\n clinicalObject: response\n }, 'new clinical object');\n var location = response.headers.location;\n var clinicalObjectUid = location.substring(location.indexOf('urn:va'), location.length);\n return callback(null, writebackContext, clinicalObjectUid);\n });\n }\n}",
"function getRecord() {\n return recordName;\n }",
"getID() {\r\n return this.id.toString().padStart(3, '0');\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check the CanIUse database to see if targets are supported | function canIUseSupported(stats, _ref) {
var version = _ref.version,
target = _ref.target,
parsedVersion = _ref.parsedVersion;
var targetStats = stats[target];
return versionIsRange(version) ? (0, _keys2.default)(targetStats).some(function (statsVersion) {
return versionIsRange(statsVersion) && compareRanges(parsedVersion, statsVersion) ? !targetStats[statsVersion].includes('y') : false;
}) : targetStats[version] && !targetStats[version].includes('y');
} | [
"function getUnsupportedTargets(node, targets) {\n var stats = _data2.default.data[node.id].stats;\n\n return targets.filter(function (target) {\n return canIUseSupported(stats, target);\n }).map(formatTargetNames);\n}",
"function needTarget(effect,other_data){\n return (!other_data.isLS && !other_data.sp && (effect['passive target'] !== undefined && effect['passive target'] !== 'self'));\n }",
"function ensureAllDatasetsMapToCancer(){\n\t\t\tdatasets.forEach(function(db){\n\t\t\t\tif (!datasetToCancer[db]){\n\t\t\t\t\tconsole.log(\"Unknown cancer type: \" + db);\n\t\t\t\t\tprocess.exit(1);\n\t\t\t\t}\n\t\t\t});\n\t\t}",
"function cmdUse(useTarget)\n{\n\t// To begin, all items in the room are checked to see if they might be a potential target for the USE command.\n\tvar itemTarget = checkItemContext(useTarget);\n\t// If the item to USE is in the room, then call its USE function - if it has one. Otherwise, note that the item can't be used (at least on its own).\n\t// Pass time if successful.\n\tif (itemTarget >= 0) {\n\t\tif (roomArray[currentRoom].items[itemTarget].canUse) { roomArray[currentRoom].items[itemTarget].itemUse(); passTime(); }\n\t\telse { printError(\"You don't see any way to use \" + useTarget + \".\"); }\n\t\treturn;\n\t}\n\t// Next, all inventory objects are checked as well.\n\tvar invTarget = checkInvContext(useTarget);\n\t// If the item to USE is in the inventory, then call its USE function - if it has one. Otherwise, note that the item can't be used (at least on its own).\n\t// Pass time if successful.\n\tif (invTarget >= 0) {\n\t\tif (inventory[invTarget].canUse) { inventory[invTarget].itemUse(); passTime(); }\n\t\telse { printError(\"You don't see any way to use \" + useTarget + \".\"); }\n\t\treturn;\n\t}\n\t// Next, all entities are checked. (You can't USE an entity, but it's helpful to be able to give a different error message if the player tried to.)\n\tvar entTarget = checkEntityContext(useTarget);\n\tif (entTarget >= 0) {\n\t\tprintError(\"Ah. So you're one of those 'nihilists'. How quaint.\");\n\t// Otherwise, return an error.\t\n\t} else {\n\t\tprintError(\"You can't see \" + useTarget + \" here.\");\n\t}\n}",
"function scriptCanExecute(script) {\n if (script.requiresAll) {\n for (var i=0, files = Object.keys(fileModules), n=files.length; i<n; i++) {\n if (!fileModules[files[i]].isReady()) return false;\n }\n return true;\n } else {\n return modulesAreReady(script.requiring.items);\n }\n }",
"function supportsDisplay() {\n var hasDisplay =\n this.event.context &&\n this.event.context.System &&\n this.event.context.System.device &&\n this.event.context.System.device.supportedInterfaces &&\n this.event.context.System.device.supportedInterfaces.Display\n\n return hasDisplay;\n}",
"function syntaxCheckResult() {\n var result = false;\n var inputLinks = getLinks();\n var jointLinks = graph.getLinks();\n let destSourceMapper = initializeDestSourceMapper(jointLinks, inputLinks);\n for(var destId in destSourceMapper){\n var naryRelationships = getNaryRelationships(destSourceMapper, destId);\n result = syntaxErrorExists(naryRelationships) ? true : result;\n }\n return result;\n}",
"check(target) {\n const targetType = typeof target;\n assert('string' === targetType, 'Type error, target should be a string, ' +\n `${targetType} given`);\n }",
"function hasAccessibleAcl(dataset) {\n return typeof dataset.internal_resourceInfo.aclUrl === \"string\";\n}",
"_triggerCheck() {\n const triggers = document.body.querySelectorAll('[data-toggler]');\n Array.prototype.slice.call(triggers).forEach((trigger) => {\n let datatarget;\n if (trigger.dataset.togglerTarget !== undefined) {\n datatarget = trigger.dataset.togglerTarget;\n }\n else if (trigger.hasAttribute('href')) {\n datatarget = trigger.getAttribute('href');\n }\n\n if (datatarget) {\n const targets = document.body.querySelectorAll(datatarget);\n Array.prototype.slice.call(targets).forEach((target) => {\n if (target.isSameNode(this.element)) {\n if (Toggler.getPlugin(target).isVisible()) {\n trigger.classList.add(Toggler.Config.CLASS_TARGET_VISIBLE);\n }\n else {\n trigger.classList.remove(Toggler.Config.CLASS_TARGET_VISIBLE);\n }\n }\n });\n }\n });\n }",
"function usesDB(request)\n{\n var url = request.url.toLowerCase();\n if(isSearch(url)) return(true);\n else if(url.endsWith(\".svg\")) return(false);\n else if(url.endsWith(\".png\")) return(false);\n else if(url.endsWith(\".jpg\")) return(false);\n else if(url.indexOf(\"persona1b.html\") >= 0) return(false);\n else if(url.indexOf(\"kingdom\") >= 0) return(true);\n else if(url.indexOf(\"person\") >= 0) return(true);\n else if(url.indexOf(\"duchy\") >= 0) return(true);\n else if(url.indexOf(\"county\") >= 0) return(true);\n else if(url.indexOf(\"barony\") >= 0) return(true);\n else if(url.indexOf(\"manor\") >= 0) return(true);\n else if(url.indexOf(\"library\") >= 0) return(true);\n else if(url.indexOf(\"catalogue\") >= 0) return(true);\n else if(url.indexOf(\"cinema\") >= 0) return(true);\n else if(url.indexOf(\"television\") >= 0) return(true);\n else if(url.indexOf(\"theology\") >= 0) return(true);\n else if(url.indexOf(\"philosophy\") >= 0) return(true);\n return(false);\n}",
"static getShouldLogDbActions() {\n\t\treturn false;\n\t}",
"function isDistAvailable(logger) {\n let arch;\n const detectedArch = detectArch_1.detectArch(logger);\n switch (detectedArch) {\n case \"x64\":\n arch = \"x64\" /* x64 */;\n break;\n default:\n if (logger) {\n logger.error(`System arch \"${detectedArch}\" not supported. Must build from source.`);\n }\n return false;\n }\n let platform;\n switch (os.platform()) {\n case \"win32\":\n case \"cygwin\":\n platform = \"windows\" /* WINDOWS */;\n break;\n case \"darwin\":\n platform = \"macos\" /* MACOS */;\n break;\n case \"linux\":\n if (detectLibc_1.detectLibc().isNonGlibcLinux) {\n platform = \"linux-musl\" /* LINUX_MUSL */;\n }\n else {\n platform = \"linux\" /* LINUX */;\n }\n break;\n default:\n if (logger) {\n logger.error(`System platform \"${os.platform()}\" not supported. Must build from source.`);\n }\n return false;\n }\n return {\n platform,\n arch\n };\n}",
"isAssignedToManage(document) {\r\n if (typeof document === 'string') {\r\n if ([\r\n 'product',\r\n 'role',\r\n 'employee'\r\n ].indexOf(document) > -1) {\r\n // Doesn't belong to client\r\n return true\r\n }\r\n\r\n /**\r\n * We have countries assigned to us.\r\n */\r\n if (this.assignedCountries.length || this.assignAllCountries) {\r\n return true\r\n }\r\n\r\n /**\r\n * We have clients assigned to us.\r\n */\r\n if (this.assignedClients.length || this.assignAllClients) {\r\n return true\r\n }\r\n\r\n /**\r\n * We don't have anything assigned, that means we can't do shit.\r\n */\r\n return false\r\n } else {\r\n if (document instanceof Vendor) {\r\n if (!(document instanceof Vendor) && typeof document.vendor === 'undefined') {\r\n // Doesn't belong to vendor\r\n return true\r\n }\r\n\r\n if (this.assignAllCountries) {\r\n // Can manage vendors from any country\r\n return true\r\n }\r\n\r\n const countryId = document instanceof Vendor\r\n ? document.country\r\n ? document.country.id\r\n : null\r\n : document.vendor.country\r\n ? document.vendor.country.id\r\n : null\r\n\r\n if (!countryId) {\r\n // Vendor has no country set, it can be accessed by anyone\r\n return true\r\n }\r\n\r\n if (this.assignedCountries.indexOf(countryId) < 0) {\r\n // Cant manage country of this vendor\r\n return false\r\n }\r\n\r\n // All good\r\n return true\r\n } else {\r\n if (!(document instanceof Client) && typeof document.client === 'undefined') {\r\n // Doesn't belong to client\r\n return true\r\n }\r\n\r\n const clientUuid = document instanceof Client ? document.uuid : document.client.uuid\r\n\r\n if (this.assignAllClients) {\r\n // Can manage all clients\r\n return true\r\n } else if (this.assignedClients.indexOf(clientUuid) < 0) {\r\n // Can't manage client of this document, forfeit\r\n return false\r\n }\r\n\r\n // Countries doesn't matter for direct document management\r\n return true\r\n }\r\n }\r\n }",
"get supportedUsagesClasses() {\n return this.getListAttribute('supported_usages_classes');\n }",
"hasAnnotationSupport() {\n\t\tif(this.props.annotationSupport != null) {\n\t\t\tif(this.props.annotationSupport.currentQuery || this.props.annotationSupport.singleItem) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"function isTransformSupported() {\n return isCssSupported(['transformProperty', 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform']);\n }",
"function moduleCanExecute(module) {\n return modulesAreReady(module.requiring.items);\n }",
"async selectDeviceForTextureFormatOrSkipTestCase(formats) {\n if (!Array.isArray(formats)) {\n formats = [formats];\n }\n const features = new Set();\n for (const format of formats) {\n if (format !== undefined) {\n features.add(kTextureFormatInfo[format].feature);\n }\n }\n\n await this.selectDeviceOrSkipTestCase(Array.from(features));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads an XML document a processes it with a processor function | function ProcessableXML() {
} | [
"function loadXMLDoc(url, element_id)\r\n{\r\nif (url !=\"\")\r\n{\r\nvar xhttp;\r\nif (window.XMLHttpRequest)\r\n {\r\n xhttp=new XMLHttpRequest();\r\n }\r\nelse\r\n {\r\n xhttp=new ActiveXObject(\"Microsoft.XMLHTTP\");\r\n }\r\nxhttp.open(\"GET\",url,false);\r\nxhttp.send();\r\ndocument.getElementById(element_id).innerHTML=xhttp.responseText;\r\n} else {\r\ndocument.getElementById(element_id).innerHTML=\"\";\r\n}\r\n}",
"function ajaxLoad(path, callback, stylesheetPath, args) { \n\tvar request, xmlDoc ;\n\trequest = new XMLHttpRequest();\n\trequest.onreadystatechange = function() {\n\t\tif (request.readyState == 4 && request.status == 200) {\n\t\t\txmlDoc = request.responseXML;\n\t\t\targs.unshift(xmlDoc); // the xml document will be the first argument, unless it is unshifted by an xsl stylesheet\n\t\t\tif (stylesheetPath) {\n\t\t\t\t// this passes the execution to getStylesheet, \n\t\t\t\t// which re-calls ajaxLoad, unshifts the stylesheet,\n\t\t\t\t// \tand executes the callback (by hitting the else below)\n\t\t\t\tgetStylesheet(stylesheetPath, callback, args); \n\t\t\t}\n\t\t\telse {\n\t\t\t\t// called if no stylesheet is defined (or if the stylesheet is already unshifted)\n\t\t\t\tcallback.apply(null,args); // using apply to pass an array of arguments to the callback function\n\t\t\t}\n\t\t}\n\t}\n\trequest.open(\"GET\", path, true); \n\trequest.send();\n}",
"function invokeByXMLPost(url, doc, onLoad) {\n\tvar xhr = createXHR();\n\t\n\txhr.onreadystatechange = function() {\n\t\tif (xhr.readyState == 4) {\n\t\t\tif(xhr.status == 200) {\n\t\t\t\tonLoad(xhr);\n\t\t\t}\n\t\t\txhr = null; //Prevent memory leak in IE\n\t\t}\n\t};\n\tvar xml = DOMToString(doc);\n\txhr.open(\"POST\", url, true);\n\txhr.setRequestHeader(\"Content-Type\",\n\t\t\"application/xml; charset=UTF-8\");\n\txhr.setRequestHeader(\"Accept\", \"application/xml\");\n\txhr.send(xml);\n}",
"function loadXML(url)\n {\n\n if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari\n xmlhttp = new XMLHttpRequest();\n }\n else {// code for IE6, IE5\n xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n try\n {\n xmlhttp.open(\"GET\", url, false); //GET method,URL described and synchronous..hence false\n xmlhttp.send(); //call XML\n var xmlDoc = xmlhttp.responseXML;\n alert(xmlDoc); \n if (xmlDoc==null) \n {\n printMessage(\"XML file does not exist.\");\n }\n else if(xmlhttp.status==404)\n {\n printMessage(\"File not found\");\n }\n //Firefox specific code\n else if (xmlDoc.documentElement.nodeName == \"parsererror\")\n {\n printMessage(\"Error in XML file\");\n }\n else\n {\n processxmlDoc(xmlDoc);\n }\n }\n catch(exception)\n {\n if(exception.message.indexOf('restricted')!=-1)\n {\n printMessage(\"Error in XML file\");\n }\n else\n {\n printMessage(exception.message);\n }\n }\n\n }",
"parseXML(rawText) {\n // TODO: different code paths for XLIFF 1.2 vs. 2.0 (this is the only way to support both)\n // Document.init();\n // Working - just return the Document object from this function\n const deferred = $q.defer();\n const self = this;\n\n // <xliff xmlns=\"urn:oasis:names:tc:xliff:document:2.0\" version=\"2.0\"\n\n const xml = parser.parseFromString(rawText, 'text/xml');\n\n // Parsing error?\n const parserError = xml.querySelector('parsererror');\n // if (parserError !== null) {\n if (xml.documentElement.nodeName == 'parsererror') {\n console.log('Error while parsing XLIFF file');\n $log.error('Error while parsing');\n const errorString = new XMLSerializer().serializeToString(parserError);\n $log.error(errorString);\n\n $log.error(new XMLSerializer().serializeToString(xml));\n self.parsingError = true;\n return;\n } else {\n self.parsingError = false;\n }\n\n const Document = {};\n // Set Document DOM to the parsed result\n Document.DOM = xml;\n // Working - the XLIFF parser returns a Document representation of the XLIFF\n Document.segments = [];\n Document.sourceLang = sourceLang;\n Document.targetLang = targetLang;\n\n Document.segmentStates = [];\n\n const file = xml.querySelector('file');\n const xliffTag = xml.querySelector('xliff');\n\n $log.log('xliff version: ');\n $log.log(xliffTag.getAttribute('version'));\n\n // TODO: fork here, depending on xliff version -- we want to support both 2.0 and 1.2 for the time being\n\n // Read the source and target language - set defaults to English and German\n var sourceLang = file.getAttribute('source-language');\n if (!sourceLang) sourceLang = 'en';\n Document.sourceLang = sourceLang;\n\n var targetLang = file.getAttribute('target-language');\n if (!targetLang) targetLang = 'de';\n Document.targetLang = targetLang;\n\n // Working -- segmentation with <seg-source> and <mrk> tags is Optional\n // add support for pure <source> and <target>\n const sourceSegments = this.getTranslatableSegments(xml);\n\n // for every segment, get its matching target mrk, if it exists - note: it may not exist\n const targetSegments = _.map(sourceSegments,\n (seg) => {\n if (seg.nodeName === 'mrk') {\n return self.getMrkTarget(xml, seg);\n }\n // there's no mrks inside <target>, just a <target> -- TODO: do we require target nodes to exist?\n return seg.parentNode.querySelector('target');\n },\n );\n\n // we can assume that translators will want to translate every segment, so there should be at least an\n // empty target node corresponding to each source node\n const sourceWithTarget = _.zip(sourceSegments, targetSegments);\n _.each(sourceWithTarget,\n (seg) => {\n const sourceText = seg[0].textContent;\n const targetText = seg[1] ? seg[1].textContent : '';\n if (!seg[1]) {\n const mid = seg[0].getAttribute('mid');\n $log.info('Target segment missing: ' + mid);\n seg[1] = self.createNewMrkTarget(Document.DOM, seg[0], '', targetLang);\n }\n\n const segPair = {\n source: seg[0].textContent,\n target: seg[1].textContent,\n sourceDOM: seg[0],\n targetDOM: seg[1],\n // TODO: the segment state should be taken from the XLIFF see XliffTwoParser\n state: 'initial',\n };\n\n // Add the pairs so we can access both sides from a single ngRepeat\n Document.segments.push(segPair);\n\n // TODO: make this useful\n // Document.translatableNodes.push(seg);\n });\n\n // TODO: remove the document-loaded event, and use the result of the resolved promise directly\n // tell the world that the document loaded\n $log.log('Xliff parser returning');\n // $log.log(Document);\n deferred.resolve(Document);\n\n // return Document;\n return deferred.promise;\n }",
"function getXMLDocument(){\n var xDoc=null;\n\n if( document.implementation && document.implementation.createDocument ){\n xDoc=document.implementation.createDocument(\"\",\"\",null);//Mozilla/Safari \n }else if (typeof ActiveXObject != \"undefined\"){\n var msXmlAx=null;\n try{\n msXmlAx=new ActiveXObject(\"Msxml2.DOMDocument\");//New IE\n }catch (e){\n msXmlAx=new ActiveXObject(\"Msxml.DOMDocument\"); //Older Internet Explorer \n }\n xDoc=msXmlAx;\n }\n if (xDoc==null || typeof xDoc.load==\"undefined\"){\n xDoc=null;\n }\n return xDoc;\n}",
"function cXparse(src) {\n var frag = new _frag();\n\n // remove bad \\r characters and the prolog\n frag.str = _prolog(src);\n\n // create a root element to contain the document\n var root = new _element();\n root.name = \"ROOT\";\n\n // main recursive function to process the xml\n frag = _compile(frag);\n\n // all done, lets return the root element + index + document\n root.contents = frag.ary;\n root.index = _Xparse_index;\n _Xparse_index = new Array();\n return root;\n}",
"function getNextXML() {\n currentTestIndex = 0;\n\n // already loaded this section.\n if(testGroups[testGroupIndex].status == 'loaded') {\n testGroups[testGroupIndex].onLoaded = function(){};\n loader.getNextTest();\n return;\n }\n // not loaded, so we attach a callback to come back here when the file loads.\n else {\n presenter.updateStatus(\"Loading file: \" + testGroups[testGroupIndex].path);\n testGroups[testGroupIndex].onLoaded = getNextXML;\n \n }\n }",
"function loadAndBuildSyntax( xmlDoc )\n{\n\tvar xmlModDoc, languageNode, languageNodeList;\n\tvar needBuildNode, bNeedBuild;\n\n\t// check if build needed...\n\tbNeedBuild = true;\n\tneedBuildNode = xmlDoc.documentElement.selectSingleNode(\"/highlight\").attributes.getNamedItem(\"needs-build\");\n\tif (needBuildNode == null || needBuildNode.nodeTypedValue==\"yes\")\n\t{\n\t\t// iterate languages and prebuild\n\t\tlanguageNodeList = xmlDoc.documentElement.selectNodes(\"/highlight/languages/language\");\n\t\tlanguageNodeList.reset();\n\t\tfor(languageNode = languageNodeList.nextNode(); languageNode != null; languageNode = languageNodeList.nextNode())\n\t\t{\n\t\t\t/////////////////////////////////////////////////////////////////////////\t\t\n\t\t\t// build regular expressions\n\t\t\tbuildRules( languageNode );\t\n\t\t}\n\n\t\t// updating...\n\t\txmlDoc.documentElement.selectSingleNode(\"/highlight\").setAttribute(\"needs-build\",\"no\");\n\t}\n\t\n\t// save file if asked\n\tsaveBuildNode = xmlDoc.documentElement.selectSingleNode(\"/highlight\").attributes.getNamedItem(\"save-build\");\n\tif (saveBuildNode != null && saveBuildNode.nodeTypedValue == \"yes\")\n\t\txmlDoc.save( sXMLSyntax );\n\t\t\n\t// closing file\n\treturn xmlDoc;\n}",
"static loadDocument(urn) {\n\n return new Promise((resolve, reject) => {\n\n const paramUrn = !urn.startsWith('urn:')\n ? 'urn:' + urn\n : urn\n\n Autodesk.Viewing.Document.load(paramUrn, (doc) => {\n\n resolve(doc)\n\n }, (error) => {\n\n reject(error)\n })\n })\n }",
"function loadContent()\n {\n xhrContent = new XMLHttpRequest();\n xhrContent.open(\"GET\",\"Scripts/paragraphs.json\",true);\n xhrContent.send(null);\n xhrContent.addEventListener(\"readystatechange\",readParagraphs);\n }",
"function XML_(){\n let url = `https://${domain}/API/Account/${rad_id}/${APIendpoint}.json?offset=${pagenr}`;\n if (relation.length > 0) {\n url += `&load_relations=[${relation}]`;\n }\n if (query.length > 0) {\n url += query;\n }\n console.log(url);\n let uri = encodeURI(url);\n let e = new XMLHttpRequest();\n e.open(\"GET\", uri, document.getElementById('fasthands').checked),\n e.onload = function(){\n if ( e.status >= 200 && e.status < 400 ){\n t = JSON.parse(e.responseText);\n if (report === 'OrderNumbers') {\n unparse_();\n } else {\n parse_Data_();\n }\n }\n },\n e.send();\n }",
"function findXML(){\n\tdescribe(\"Find XML\", function(){\n\t\tit(\"Game XML titled 'gummibar.xml' should be found in './xml/math'\", function(done){\n\n\t\t\tfs.readFile(xmlFileName, function(err, data){\n\n\t\t\t\tif (err) throw err;\n\n\t\t\t\txmlString = data; \n\n\t\t\t\tdone();\n\t\t\t});\n\t\t});\n\t});\n}",
"function _onFinishedLoadingDOM() {\n var request = new XMLHttpRequest();\n request.open(\"GET\", exports.url);\n request.onload = function onLoad() {\n if ((request.status >= 200 && request.status < 300) ||\n request.status === 304 || request.status === 0) {\n _mapDocumentToSource(request.response);\n _load.resolve();\n } else {\n var msg = \"Received status \" + request.status + \" from XMLHttpRequest while attempting to load source file at \" + exports.url;\n _load.reject(msg, { message: msg });\n }\n };\n request.onerror = function onError() {\n var msg = \"Could not load source file at \" + exports.url;\n _load.reject(msg, { message: msg });\n };\n request.send(null);\n }",
"function _processOutputXMLFile() {\n\n // Check if output.xml file exists\n if (fs.existsSync(outputXMLPath)) {\n // Process contents\n RF_DEBUG && console.log('[rsbatech:robotframework] Starting to parse output.xml file located at:'+outputXMLPath);\n\n var stream = fs.createReadStream(outputXMLPath),\n xml = new XmlStream(stream),\n suites = {};\n\n xml.on('startElement: suite', Meteor.bindEnvironment( function processSuite(suiteNode) {\n if (suiteNode.$.id) { // Exclude <suite> node in <statistics> sections\n suites[suiteNode.$.id] = suiteNode.$.name;\n }\n }));\n\n xml.collect('kw'); // Store individual keywords in an array\n xml.collect('arg'); // Store individual keyword arguments in an array\n xml.on('updateElement: test', Meteor.bindEnvironment( function processTestElement(testNode) {\n\n var report = {\n id: testNode.$.id,\n name: testNode.$.name,\n framework: FRAMEWORK_NAME,\n result: (testNode.status && testNode.status.$.status === 'PASS') ? 'passed' : 'failed',\n duration: _calculateTestDuration(testNode.status.$.starttime, testNode.status.$.endtime),\n timestamp: moment(testNode.status.$.starttime, 'YYYYMMDD HH:mm:ss.SSS').toDate()\n };\n\n report.ancestors = _calculateTestAncestors(testNode.$.id, suites);\n\n // If test failed, provide more information on what went wrong\n if (report.result === 'failed') {\n report.failureType = 'AssertionError';\n\n // Find keyword that failed\n _.each(testNode.kw, Meteor.bindEnvironment(function(element) {\n var args = '';\n if (element.status && element.status.$.status === 'FAIL') {\n\n // List keyword arguments, if any\n if (element.arguments && element.arguments.arg) {\n for (var i = 0; i < element.arguments.arg.length; i++ ) {\n args = args.concat(' ', element.arguments.arg[i]);\n }\n }\n\n report.failureMessage = 'Keyword: ' + element.$.name + args + '\\n ';\n }\n }));\n\n report.failureMessage = report.failureMessage || '';\n report.failureMessage = report.failureMessage.concat('>>>', testNode.status.$text);\n }\n\n // Submit test results report to Velocity\n Meteor.call('velocity/reports/submit', report);\n\n }));\n\n // report test ERRORs\n xml.on('updateElement: errors msg', Meteor.bindEnvironment(function processErrors(msgNode) {\n RF_DEBUG && console.log('ERROR msg text:' + msgNode.$text);\n var options = {\n framework: FRAMEWORK_NAME,\n message: msgNode.$text\n };\n if (msgNode.$.level) {\n options.level = msgNode.$.level;\n }\n if (msgNode.$.timestamp) {\n options.timestamp = moment(msgNode.$.timestamp, 'YYYYMMDD HH:mm:ss.SSS').toDate();\n }\n\n Meteor.call('velocity/logs/submit', options);\n }));\n\n xml.on('end', Meteor.bindEnvironment(function end() {\n RF_DEBUG && console.log('[rsbatech:robotframework] Completed parsing output.xml file');\n }));\n \n } else {\n console.log('[rsbatech:robotframework] ERROR: output.xml file missing at:'+outputXMLPath);\n \n }\n }",
"getDocumentWithData(name, data) {\n data = data || {};\n var docString = this.nativeResourceLoader.loadBundleResource(name);\n var rendered = Mustache.render(docString, data);\n return this.domParser.parseFromString(rendered, \"application/xml\");\n }",
"function inject_alternatives() {\n var request = new XMLHttpRequest();\n request.addEventListener(\"load\", process_sitemap);\n request.open(\"GET\", \"/sitemap.xml\");\n request.send();\n}",
"function getData( xHRObject, xsllnk )\n{\n var READY_STATE_UNINITIALIZED = 0;\n var READY_STATE_LOADING = 1;\n var READY_STATE_LOADED = 2;\n var READY_STATE_INTERACTIVE = 3;\n var READY_STATE_COMPLETE = 4;\n\t//var xmlDocs = xHRObject.responseText;\n\t//var xmlDocs = xHRObject.responseXML;\n\t//alert('getData called ' + xHRObject.readyState + ' ' + xHRObject.status + '\\n' + xmlDocs);\n\t\n\tif ((xHRObject.readyState == READY_STATE_COMPLETE) && (xHRObject.status == 200))//check to see if the obj is rdy\n\t{\n\t\t//If there's not stylesheet to manupulate the data send the txt back\n\t\tif( xsllnk == null || xsllnk == '') return xHRObject.responseText;\n\t\tif( xsllnk.toLowerCase() == 'xml' ) return xHRObject.responseXML;\n\t\t//Load XML\n\t\tvar xmlDoc = xHRObject.responseXML;\n return applyXSL( xmlDoc, xsllnk );\n\t}\n\treturn null;\n}",
"function loadXML(e) {\n var url = e.parameter.url;\n var xml = UrlFetchApp.fetch(url).getContentText();\n var document = XmlService.parse(xml); \n var entries = document.getRootElement().getChildren();\n var all_types = new Array();\n \n for (var i = 0; i < entries.length; i++) {\n all_types[i] = new Object();\n all_types[i].name = entries[i].getChildText('name');\n all_types[i].color = entries[i].getChildText('color');\n all_types[i].attributes = new Array();\n var children = entries[i].getChildren('attribute');\n for (var j = 0; j < children.length; j++) {\n all_types[i].attributes[j] = new Object();\n all_types[i].attributes[j].name = children[j].getText();\n var char = children[j].getAttribute('char');\n if(char != null)\n all_types[i].attributes[j].char = char.getValue();\n var pattern = children[j].getAttribute('pattern');\n if(pattern != null)\n all_types[i].attributes[j].pattern = pattern.getValue();\n var overridable = children[j].getAttribute('overridable');\n if(overridable != null && overridable.getValue() == 'true') {\n all_types[i].attributes[j].overridable = overridable.getValue(); \n }\n var manual = children[j].getAttribute('manual');\n if(manual != null && manual.getValue() == 'true') {\n all_types[i].attributes[j].manual = manual.getValue(); \n }\n } \n }\n \n updateButtons(all_types);\n initCache(all_types);\n DocumentApp.getUi().alert('Sidebar customised');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
DataField and DataPack system : default DataField (customisable), many of which constitute a DataPack | function DefaultDataField(){
return {
questionname:"???", //Display name of the field question
qfield:"question", //Field name must be unique
qvalue:"", //Field value, by default
qid:GenerateId(), //id of the field question
qchoices:"", //answer options list
executeChoice:Identity, //immediate changes on toggle receives (id, choice)
defaultChoice:DefaultChoice, //choice formatting, based on itself, receives (index,choicetxt)
qtype:PlainHTML, //Format of question :receives a DataField
qplaceholder:"❤ Pedro PSI ❤", //Placeholder answer
shortcuts:Identity, //Special shortcuts
qsubmittable:true, //whether the element expects submission (true) or merely presents information (false)
qrequired:true,
qvalidator:IdentityValidator, //Receives a DataField
qerrorcustom:''
}
} | [
"function fieldFromDerivedFieldConfig(derivedFieldConfigs) {\n var dataLinks = derivedFieldConfigs.reduce(function (acc, derivedFieldConfig) {\n // Having field.datasourceUid means it is an internal link.\n if (derivedFieldConfig.datasourceUid) {\n acc.push({\n // Will be filled out later\n title: '',\n url: '',\n // This is hardcoded for Jaeger or Zipkin not way right now to specify datasource specific query object\n internal: {\n query: {\n query: derivedFieldConfig.url\n },\n datasourceUid: derivedFieldConfig.datasourceUid\n }\n });\n } else if (derivedFieldConfig.url) {\n acc.push({\n // We do not know what title to give here so we count on presentation layer to create a title from metadata.\n title: '',\n // This is hardcoded for Jaeger or Zipkin not way right now to specify datasource specific query object\n url: derivedFieldConfig.url\n });\n }\n\n return acc;\n }, []);\n return {\n name: derivedFieldConfigs[0].name,\n type: _grafana_data__WEBPACK_IMPORTED_MODULE_3__[\"FieldType\"].string,\n config: {\n links: dataLinks\n },\n // We are adding values later on\n values: new _grafana_data__WEBPACK_IMPORTED_MODULE_3__[\"ArrayVector\"]([])\n };\n}",
"pack(data) {\n Object.assign(data, {\n dataSetId: Utilities.normalizeHex(data.dataSetId.toString('hex').padStart(64, '0')),\n });\n return data;\n }",
"get defaultDataSchema() {\n\t\treturn {\n\t\t\tprefix: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdefault: this.client.config.prefix,\n\t\t\t\tmin: null,\n\t\t\t\tmax: 10,\n\t\t\t\tarray: this.client.config.prefix.constructor.name === 'Array',\n\t\t\t\tconfigurable: true,\n\t\t\t\tsql: `VARCHAR(10) NOT NULL DEFAULT '${this.client.config.prefix.constructor.name === 'Array' ? JSON.stringify(this.client.config.prefix) : this.client.config.prefix}'`\n\t\t\t},\n\t\t\tlanguage: {\n\t\t\t\ttype: 'language',\n\t\t\t\tdefault: this.client.config.language,\n\t\t\t\tmin: null,\n\t\t\t\tmax: null,\n\t\t\t\tarray: false,\n\t\t\t\tconfigurable: true,\n\t\t\t\tsql: `VARCHAR(5) NOT NULL DEFAULT '${this.client.config.language}'`\n\t\t\t},\n\t\t\tdisableNaturalPrefix: {\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdefault: false,\n\t\t\t\tmin: null,\n\t\t\t\tmax: null,\n\t\t\t\tarray: false,\n\t\t\t\tconfigurable: Boolean(this.client.config.regexPrefix),\n\t\t\t\tsql: `BIT(1) NOT NULL DEFAULT 0`\n\t\t\t},\n\t\t\tdisabledCommands: {\n\t\t\t\ttype: 'command',\n\t\t\t\tdefault: [],\n\t\t\t\tmin: null,\n\t\t\t\tmax: null,\n\t\t\t\tarray: true,\n\t\t\t\tconfigurable: true,\n\t\t\t\tsql: 'TEXT'\n\t\t\t}\n\t\t};\n\t}",
"get extractorFieldValue(){\n return{\n sbat: {\n 'extractor': function extractDataViaSbat(ds, msgData, fieldProperty, dataTypeExtractor) {\n var chain = this.getChainByBlockSmall(ds, msgData, fieldProperty);\n if (chain.length == 1) {\n return this.readDataByBlockSmall(ds, msgData, fieldProperty.startBlock, fieldProperty.sizeBlock, dataTypeExtractor);\n } else if (chain.length > 1) {\n return this.readChainDataByBlockSmall(ds, msgData, fieldProperty, chain, dataTypeExtractor);\n }\n return null;\n }.bind(this),\n dataType: {\n 'string': function extractBatString(ds, msgData, blockStartOffset, bigBlockOffset, blockSize) {\n ds.seek(blockStartOffset + bigBlockOffset);\n return ds.readString(blockSize);\n },\n 'unicode': function extractBatUnicode(ds, msgData, blockStartOffset, bigBlockOffset, blockSize) {\n ds.seek(blockStartOffset + bigBlockOffset);\n return ds.readUCS2String(blockSize / 2);\n },\n 'binary': function extractBatBinary(ds, msgData, blockStartOffset, bigBlockOffset, blockSize) {\n ds.seek(blockStartOffset + bigBlockOffset);\n var toReadLength = Math.min(Math.min(msgData.bigBlockSize - bigBlockOffset, blockSize), this.CONST.MSG.SMALL_BLOCK_SIZE);\n return ds.readUint8Array(toReadLength);\n }.bind(this)\n }\n },\n bat: {\n 'extractor': function extractDataViaBat(ds, msgData, fieldProperty, dataTypeExtractor) {\n var offset = this.getBlockOffsetAt(msgData, fieldProperty.startBlock);\n ds.seek(offset);\n return dataTypeExtractor(ds, fieldProperty);\n }.bind(this),\n dataType: {\n 'string': function extractSbatString(ds, fieldProperty) {\n return ds.readString(fieldProperty.sizeBlock);\n },\n 'unicode': function extractSbatUnicode(ds, fieldProperty) {\n return ds.readUCS2String(fieldProperty.sizeBlock / 2);\n },\n 'binary': function extractSbatBinary(ds, fieldProperty) {\n return ds.readUint8Array(fieldProperty.sizeBlock);\n }\n }\n }\n }\n }",
"async _getField(dataType){\n let css = await this._getFieldCSS(dataType);\n let type = await this._getFieldInputType(dataType);\n switch(dataType.toLowerCase()) {\n case 'text':\n case 'number':\n case 'date':\n case 'document':\n case 'email':\n case 'money-gbp':\n case 'phone-uk':\n return new CCDStringField(css, type);\n case 'textarea':\n return new CCDTextAreaField(css);\n case 'address':\n case 'complex':\n return new CCDComplexTypeField(css, type);\n case 'fixed-list':\n return new CCDFixedListField(css);\n case 'yes-no':\n return new CCDYesNoField(css);\n case 'collection':\n return new CCDCollectionField(css);\n case 'multi-select':\n return new CCDMultiSelectField(css);\n default:\n throw new CustomError(`could not find a data type called '${dataType}'`)\n }\n }",
"function packageDataToReportData(packageData, config) {\n\tlet finalData = {}\n\n\t// create only fields specified in the config\n\tconfig.fields.forEach(fieldName => {\n\t\tif ((fieldName in packageData)) {\n\t\t\tfinalData[fieldName] = packageData[fieldName]\n\t\t} else {\n\t\t\tfinalData[fieldName] = config[fieldName].value\n\t\t}\n\t})\n\n\treturn finalData\n}",
"_data() {\n return {\n nameCases: this.nameCase,\n groupCases: this.groupCase,\n tableName: this.tableName,\n tableComment: this.tableComment,\n entityClass: _string.upperFirst(_string.camelCase(this.tableName)),\n entityClassCamelCase: _string.camelCase(this.tableName),\n ...this._mapper(this.columns)\n }\n }",
"addExtraData(key, data, packOptions = {}) {\n const packedJson = packOptions.nopack ? data : packBinaryJson(data, this, null, packOptions);\n this.json.extras = this.json.extras || {};\n this.json.extras[key] = packedJson;\n return this;\n }",
"getNewData(data={}) {\n let newRow = {};\n this.fields.forEach((field)=>{\n newRow[field.id] = this.defaults[field.id];\n });\n newRow = {\n ...newRow,\n ...data,\n };\n return newRow;\n }",
"function DataContainer(data) {\n this._data = data;\n}",
"_createSnabbdomData () {\n let data = {}\n let attributes = {}\n\n if ('key' in this.attributes) {\n data.key = this.attributes.key\n delete this.attributes.key\n }\n\n // Shallow copy\n for (let p in this.attributes) {\n attributes[p] = this.attributes[p]\n }\n\n Engine.plugins.forEach((p) =>\n // This method may mutate data freely, and also\n // remove items from attributes, but not mutate\n // any of the attribute values\n p.consumeAttributes(data, attributes, this)\n )\n\n return data\n }",
"loadFieldInfo(){\n let fieldInfo = [];\n this.props.orderStore.currentOrder.templateFields.fieldlist.field.forEach(field =>\n this.props.orderStore.fieldInfo.push([field, '']));\n this.props.orderStore.fieldInfo.forEach(field =>\n {\n if(field[0].type == \"SEPARATOR\"){\n field[1] = \"**********\";\n }\n });\n }",
"getDataWithFields() {\n for (const prop in this.req.files) {\n for (let i = 0; i < this.req.files[prop].length; i++) {\n this.data.push({\n ...this.filesUploaded.splice(0, this.sizes.length),\n });\n }\n }\n\n return this.groupByFields(\n this.data.map((file) =>\n this.renameKeys({ ...this.sizes.map((size, i) => size.path) }, file)\n ),\n \"field\"\n );\n }",
"function makeDefaultDataset() {\r\n fillDefaultDataset(dataOrigin);\r\n fillDefaultDataset(dataAsylum);\r\n}",
"GetPlatformData() {}",
"createMongoDataView(currentImportTask, mongo) {\n let mongoScope = currentImportTask.mongoScopes[Object.keys(currentImportTask.mongoScopes)[0]];\n let mongoLocation = _.find(currentImportTask.mongoMetadata.locations, {dataset: mongoScope._id});\n let analyticalUnitId = mongoScope.featureLayers[0];\n let attributeSet = currentImportTask.mongoMetadata.attributeSet;\n let attributes = currentImportTask.mongoMetadata.attributes;\n let baseView = {\n _id: conn.getNextId(),\n name: currentImportTask.layer.customName,\n conf: {\n multipleMaps: false,\n years: mongoScope.years,\n dataset: mongoScope._id,\n theme: mongoScope.themes[0]._id,\n visualization: null,\n location: mongoLocation._id,\n expanded: {},\n selMap: {\n ff4c39: []\n },\n choroplethCfg: [],\n pagingUseSelected: false,\n pagingSelectedColors: [\n \"ff4c39\",\n \"34ea81\",\n \"39b0ff\",\n \"ffde58\",\n \"5c6d7e\",\n \"d97dff\"\n ],\n filterMap: {},\n filterActive: false,\n layers: [\n {\n opacity: 0.7,\n sortIndex: 0,\n type: \"selectedareasfilled\",\n attributeSet: \"\",\n attribute: \"\",\n at: \"\",\n symbologyId: \"\"\n },\n {\n opacity: 0.7,\n sortIndex: 1,\n type: \"areaoutlines\",\n attributeSet: \"\",\n attribute: \"\",\n at: \"\",\n symbologyId: \"\"\n },\n {\n opacity: 0.7,\n sortIndex: 2,\n type: \"topiclayer\",\n attributeSet: \"\",\n attribute: \"\",\n at: currentImportTask.mongoMetadata.layerTemplate._id,\n symbologyId: \"#blank#\"\n },\n {\n opacity: 1,\n sortIndex: 10000,\n type: \"terrain\",\n attributeSet: \"\",\n attribute: \"\",\n at: \"\",\n symbologyId: \"\"\n }\n ],\n trafficLayer: false,\n page: 1,\n mapCfg: {\n center: {},\n zoom: 6\n },\n cfgs: [\n {\n cfg: {\n title: \"Automatic analysis results\",\n type: \"grid\",\n attrs: _.map(attributes, attribute => {\n return {\n as: attributeSet._id,\n attr: attribute._id,\n normType: \"\",\n normAs: \"\",\n normAttr: \"\",\n normYear: \"\",\n attrNameNormalized: \"\",\n checked: true,\n numCategories: \"\",\n classType: \"\",\n zeroesAsNull: \"\",\n name: \"\",\n topic: \"\",\n parentId: null,\n index: 0,\n depth: 0,\n expanded: false,\n expandable: true,\n leaf: false,\n cls: \"\",\n iconCls: \"\",\n icon: \"\",\n root: false,\n isLast: false,\n isFirst: false,\n allowDrop: true,\n allowDrag: true,\n loaded: false,\n loading: false,\n href: \"\",\n hrefTarget: \"\",\n qtip: \"\",\n qtitle: \"\",\n children: null,\n attrName: `${attribute.name}`,\n asName: `${attributeSet.name}`,\n treeNodeText: `${attribute.name}`\n }\n }),\n featureLayerOpacity: \"70\",\n classType: \"quantiles\",\n numCategories: \"5\",\n constrainFl: [\n 0,\n 3\n ],\n stacking: \"none\",\n chartId: 7165535\n },\n queryCfg: {\n invisibleAttrs: [],\n invisibleYears: []\n }\n }\n ]\n },\n origin: \"customLayer\"\n };\n\n return new MongoDataViews(mongo).add(baseView).then(() => {\n return baseView;\n })\n }",
"static getFieldInfoByName(field_name){\n\t}",
"customFieldDocumentDbRef(uid, archiveId, customFieldName) {\n return firebase\n .firestore()\n .collection(\"archives\")\n .doc(uid)\n .collection(\"userarchives\")\n .doc(archiveId)\n .collection(\"customFields\")\n .doc(customFieldName);\n }",
"function FlavourData(aData, aLength, aFlavour) \n{\n this.supports = aData;\n this.contentLength = aLength;\n this.flavour = aFlavour || null;\n \n this._XferID = \"FlavourData\";\n}",
"function DataColumn({ header = \"\", shortHeader = \"\", CellComponent, formatFn, totalFn, column = 0, dataset = [] }) {\n const dataColumn = formatFn(dataset);\n return (\n <React.Fragment>\n <HeaderCell label={header} shortLabel={shortHeader} column={column} />\n {dataColumn.map(cellData => <CellComponent {...{...cellData, column}} />)}\n {typeof totalFn === \"function\" ? <CellComponent {...{...totalFn(dataset), column}} /> : null}\n </React.Fragment>\n );\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The graph should contain a list of vertices and an object for building an adjacency list. | function Graph() {
this.vertices = [];
this.adjacencyList = {};
} | [
"constructor(value) {\n this.value = value;\n this.adjacents = []; // Adjacency List\n }",
"constructor() {\n this.graph = {};\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 addEdgeToAdjacencyListDict(nodeList, from, to, gain) {\n if (!nodeList[from]) {\n //if node 'from''s list of edges doesn't already exist in nodeList, then \n //create one with this edge as the first edge.\n nodeList[from] = [new Edge(to, gain)];\n }\n else {\n //otherwise, add the new edge to the current entry.\n nodeList[from].push(new Edge(to, gain));\n }\n}",
"_add_service_graph_vertexes(g) {\n for (let type of this._types) {\n try {\n g.add_vertex(type)\n } catch (e) {\n if (e instanceof error.Conflict\n && e.message === 'Vertex is already existed'\n ) {\n let new_err = new error.Conflict('Duplicated service')\n new_err.service_type = type\n throw new_err\n }\n throw e\n }\n }\n }",
"addAdjacent(node) {\n this.adjacents.push(node);\n }",
"add_vertex (id=this.V.length) {\n const vert = this.V[id];\n\n if (!vert) {\n this.V[id] = new Vertex(id);\n }\n\n return this.V[id];\n }",
"removeVertex(vertex) {\n // Delete from nodes property of graph\n this.nodes.delete(vertex);\n\n // update adjacency lists of other vertices\n for (let v of vertex.adjacent){\n v.adjacent.delete(vertex);\n }\n\n // clear adjacency list of vertex\n vertex.adjacent.clear();\n }",
"graph(options) {\n return this.appendChild(new Graph(options));\n }",
"function graphMLtoCypher(jsonObj) {\n let edgeStatements = [],\n edgeParameters = [];\n let {nodeStatements, dictionary, hashMap} = nodeToCypher(jsonObj);\n if(nodeStatements.length > 0){\n //create edges\n if(jsonObj.hasOwnProperty('edges')){\n edgeParameters = _.cloneDeep(jsonObj.edges);\n edgeParameters && edgeParameters.map((item) => {\n if(hashMap.hasOwnProperty(item.toID) && hashMap.hasOwnProperty(item.fromID)){\n item[\"toType\"] = hashMap[item.toID].type;\n item[\"fromType\"] = hashMap[item.fromID].type;\n }\n });\n edgeStatements = edgeToCypher(edgeParameters);\n } \n }\n //locutions?\n return {nodeStatements, dictionary, edgeStatements, edgeParameters};\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}",
"addEdge(edge) {\n\t // is this edge connected to us at all?\n\t var nodes = edge.getNodes();\n\t if (nodes.a !== this && nodes.b !== this) {\n\t throw new Error(\"Cannot add edge that does not connect to this node\");\n\t }\n\t var edge_id = edge.getID();\n\t // Is it an undirected or directed edge?\n\t if (edge.isDirected()) {\n\t // is it outgoing or incoming?\n\t if (nodes.a === this && !this._out_edges[edge_id]) {\n\t this._out_edges[edge_id] = edge;\n\t this._out_degree += 1;\n\t // Is the edge also connecting to ourselves -> loop ?\n\t if (nodes.b === this && !this._in_edges[edge_id]) {\n\t this._in_edges[edge.getID()] = edge;\n\t this._in_degree += 1;\n\t }\n\t }\n\t else if (!this._in_edges[edge_id]) { // nodes.b === this\n\t this._in_edges[edge.getID()] = edge;\n\t this._in_degree += 1;\n\t }\n\t }\n\t else {\n\t // Is the edge also connecting to ourselves -> loop\n\t if (this._und_edges[edge.getID()]) {\n\t throw new Error(\"Cannot add same undirected edge multiple times.\");\n\t }\n\t this._und_edges[edge.getID()] = edge;\n\t this._und_degree += 1;\n\t }\n\t }",
"function createObject(vertices) {\n return { vertices: vertices };\n}",
"addEdge(u, v, weight = 1) {\n if(!(this.hasNode(u) && this.hasNode(v)))\n return;\n\n if(!this.isWeighted)\n weight = 1;\n\n if(!this.hasEdge(u,v))\n this._edgeSize++;\n\n if(this.isDirected) {\n this._nodes[u].out[v] = weight;\n this._nodes[v].in[u] = weight;\n } else {\n this._nodes[u].out[v] = weight;\n this._nodes[v].in[u] = weight;\n this._nodes[v].out[u] = weight;\n this._nodes[u].in[v] = weight;\n }\n }",
"static isValidGraph(obj) {\n\n if (obj == undefined || obj == null || typeof obj != 'object' ) {\n return false;\n }\n\n var keys = Object.keys(obj);\n\n if (keys.length == 0) {\n return false;\n }\n\n // verify the values of each key is a key\n var vertices = {};\n for (var i=0; i<keys.length; i++) {\n var key = keys[i];\n for (var n=0; n<obj[key].length; n++) {\n var vertex = obj[key][n];\n if (!obj.hasOwnProperty(vertex)) {\n return false;\n }\n }\n }\n\n return true;\n }",
"_add_service_graph_edges(g) {\n for (let type of this._types) {\n for (let neighbour of type.dependency) {\n try {\n g.add_edge(neighbour, type)\n } catch (e) {\n if (e instanceof error.Conflict\n && e.message === 'Edge is already existed'\n ) {\n let new_err = new error.Conflict('Duplicated dependency')\n new_err.dependency = [type, neighbour]\n throw new_err\n }\n throw e\n }\n }\n }\n }",
"findConnectionsBFS(vertex) {\n // If vertex does not exist, stop executing\n if (!this.graph[vertex]) {\n return []\n }\n\n // Use breadth first search to collect found items\n return this.breadthFirstSearch(vertex)\n }",
"function ZRelationGraph() {\n this.vertices = {}; // Map<ElementId, Vertex>: maps element id onto its vertex\n this.nrConnectedVertices = 0; // Integer: number of vertices that are connected to at least one other vertex\n this.relations = {}; // Map<ElementId, Map<ElementId, ZRelationSet>>: all relations between two elements\n this.suspended = []; // List<ZRelationSet>: list of suspended relation sets\n // invariant: adding any of these will cause a cycle\n this.zValues = {}; // Map<ElementId, Integer>: assigned z values\n this.changed = {}; // Map<ElementId, Integer>: elements changed since last recalc with their previous value\n this.nrChanged = 0; // Integer: cardinality this.changed\n this.newZValues = {}; // Map<ElementId, Integer>: new z-values\n this.callbackObject = undefined; // Object: used in callback\n this.callbackFunction = undefined; // Function: used in callback\n this.resolveCycleBlockRel = undefined; // For info about relation susp.\n}",
"static deserialize(json) {\n let config = json['config'] || {};\n\n let graph = new Graph(config);\n\n json['nodes'].forEach(n => {\n graph.addNode(n.id);\n });\n\n json['links'].forEach(l => {\n if('weight' in l) \n graph.addEdge(l.source, l.target, Number(l.weight));\n else\n graph.addEdge(l.source, l.target);\n });\n\n return graph;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
note of component: Title: displays the title of the page FormContainer: displays the form and takes in user input WordCloud: curates user input and displays the word cloud alert: appears when the user tries to submit without text input | render() {
return (
<LayoutDiv>
<Title/>
<CenterDiv>
<FormContainer dataReturnHandler={this.handleData}/>
{this.state.FormInputData === '' ? null : <WordCloudDisplay rawData={this.state.FormInputData}/>}
</CenterDiv>
{this.state.AlertDisplay === true ? <Alert /> : null}
</LayoutDiv>
);
} | [
"function submitWord() {\n\tif (player != \"\" && room != -1 && word != \"\") {\n\t\tdebug(\"-\");\n\t\tvar word = document.myForm.word.value.toUpperCase().replace(/Ä/g, \"a\").replace(/Ö/g, \"o\");\n\t\tvar geturl = \"/sanaruudukko/rest/sr/process?func=submitword&player=\" + player + \"&passcode=\" + passcode + \"&word=\" + word;\n\t\t//document.myForm.debug.value = geturl;\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\tdocument.myForm.word.value = \"\";\n\t}\n}",
"function onArticleSubmit()\n {\n // grab the text in the title and the content\n var title = document.getElementById('article-title').value\n var content = jQuery('div#froala-editor').froalaEditor('html.get')\n\n // Check the input values\n if( typeof title != 'string' || title == \"\" ) { \n onArticleSubmitError( \"Title is either empty or invalid.\" ) \n return \n }\n if( typeof content != 'string' || content == \"\" ) { \n onArticleSubmitError( \"Content is either empty of invalid\" ); \n return \n }\n \n // Submit the article.\n requestArticleSubmit( title, content )\n return false\n }",
"function createFormHandler(e) {\n e.preventDefault()\n// Add innerHTML apending to Brainstormer in this section\n const characterInput = document.querySelector(\"#user-edit-character\").value\n const setupInput = document.querySelector(\"#user-edit-setup\").value\n const twistInput = document.querySelector(\"#user-edit-twist\").value\n const genreInput = document.querySelector(\"#user-edit-genre_id\").value\n \n postIdea(characterInput, setupInput, twistInput, genreInput)\n }",
"function handleSubmit(event) {\n event.preventDefault(); // When event happens page refreshed, this function prevents the default reaction\n const currentValue = input.value;\n paintGreeting(currentValue);\n saveName(currentValue);\n}",
"function onResponsePageLoad() {\n KASClient.App.registerHardwareBackPressCallback(function(){\n KASClient.App.dismissCurrentScreen();\n }); \n \n KASClient.Form.getFormAsync(function (form, error) { \n if (error != null) { \n KASClient.App.showNativeErrorMessage(\"Error:getFormAsync:\" + error); \n return; \n } \n _form = form; \n \n // Document title would be the form title\n document.getElementById(\"title\").innerHTML = _form.title;\n }); \n }",
"function processBrainstormUsingForm(formObject) {\n Logger.log(\"In the brainstorm, processing the form.\");\n // blob will be encoded as a string\n Logger.log(formObject);\n var formBlob = formObject.brainstorm;\n Logger.log(formBlob);\n // returns keywords\n var keywords = analyzeText(formBlob);\n Logger.log(keywords);\n //keywords = [\"banana\"];\n var urls = [];\n Logger.log(\"Sending keywords to image API.\");\n keywords.forEach(function(query) {\n Logger.log(query);\n var result = searchImages(query);\n urls.push(result);\n });\n Logger.log(urls);\n return urls;\n //return \"https://picjumbo.com/wp-content/uploads/fresh-bananas-on-glossy-table-and-red-background_free_stock_photos_picjumbo_DSC08378.jpg\";\n}",
"function resizeWordcloud() {\n wordCloudDiv.empty();\n $scope.wordCloud = wordcloud.WordCloud(wordCloudDiv.width(), wordCloudDiv.width() * 0.75,\n 250, $scope.addSearchString, \"#wordCloud\");\n $scope.wordCloud.redraw($scope.wordCount.getWords());\n wordCloudWidth = wordCloudDiv.width();\n }",
"function showAddTopic(){\n // show form and set the form fields to null\n createForm.style.display = \"block\";\n document.getElementById(\"create-topic\").value = \"\";\n document.getElementById(\"create-description\").value = \"\";\n formType = \"addTopic\";\n}",
"function makeBooksForm(service_email, user_name) {\n var temp_str = user_name + \"'s Book Suggestion Input\";\n var input_form = FormApp.create(temp_str);\n input_form.setTitle(temp_str);\n \n temp_str = \"New book title\";\n var temp_question = input_form.addTextItem();\n temp_question.setTitle(temp_str);\n temp_question.setHelpText(temp_str);\n temp_question.setRequired(true);\n \n temp_str = \"New book author's first name\";\n temp_question = input_form.addTextItem();\n temp_question.setTitle(temp_str);\n temp_question.setHelpText(temp_str);\n temp_question.setRequired(true);\n \n temp_str = \"New book author's last name\";\n temp_question = input_form.addTextItem();\n temp_question.setTitle(temp_str);\n temp_question.setHelpText(temp_str);\n temp_question.setRequired(true);\n \n // Emails can't be delivered to a service account.\n // There's an annoying \"failed to deliver email\" email that is sent to the user if it tries.\n var form_id = input_form.getId();\n Drive.Permissions.insert(\n {\n 'role': 'writer',\n 'type': 'user',\n 'value': service_email\n },\n form_id,\n {\n 'sendNotificationEmails': 'false' //The normal way of adding editors doesn't have this option\n }\n );\n \n var form_url = input_form.getPublishedUrl();\n \n return {form_id: form_id, form_url: form_url};\n}",
"function emxCommonAutonomySearch() {\n //=================================================================\n // The URL parameters for emxFullSearch.jsp\n //=================================================================\n \n //\n //This is an optional parameter that can pass to specify the name of the function to be \n //invoked once submit button is clicked on the search component\n this.callbackFunction = null; // At this time this parameter is not working, so use onSubmit property\n\n //\n this.cancelLabel = null;\n\n //\n //List of OIDs to exclude from the search results\n this.excludeOID = null; \n\n //\n //JPO provided by Apps that returns list of OIDs to not display in results. This is used \n //to further filter the results. The method should return a StringList of OIDs to exclude \n //from the search results\n this.excludeOIDprogram = null;\n \n //\n //The parameter specifies the name of the form in the form-based search. It is an optional parameter.\n this.formName = null;\n \n //\n //The parameter specifies the name of the frame that contains the form. It is an optional parameter\n this.frameName = null;\n \n // List of indices and their default/allowed values for the initial search results\n this.field = null;\n //\n //This parameter is deprecated. It is present for the backward compatibility.\n // If user does txtType=\"type_abc\" then field is set to \"TYPES=txt_abc\"\n this.txtType = null;\n\n //\n //Optional parameter - Name of the field to which the selected value from the search results to be returned.\n this.fieldNameActual = null;\n \n //\n //Optional parameter ? If the display value is different from Actual value - Name of the field to which \n //the display value from the search results to be returned\n this.fieldNameDisplay = null;\n \n //\n //The optional parameter will be used to limit the list of indexed attributes displayed on a Form Based search.\n //This will not apply to Navigation based searches. Comma separated list\n this.formInclusionList = null;\n\n //\n //The parameter will be used to either show or hide the header on the search dialog. The header includes \n //the search text box along with the Search and Reset buttons and the page level toolbar\n this.hideHeader = null;\n \n //\n //All the selectable(s) of search criteria are optional by default. User can provide a coma separated \n //list of search criteria that are passed as part of URL parameter mandatorySearchParam to make them mandatory.\n //These refinements will be mandatory and displayed as disabled checked checkboxes in the breadcrumb display.\n //The user will not be allowed to uncheck these search criteria. The values passed as mandatorySearchParam must \n //be a part of the URL parameters.\n this.mandatorySearchParam = null;\n \n //\n //By default, the Search in Collection toolbar button will be displayed on the toolbar when in Navigate mode.\n //Can be turned off by this parameter. Recommended that this is not used when using type specific tables, \n //expandJPOs or relationships in the results table.\n this.searchCollectionEnabled = null;\n\n //\n //Controls whether the table page adds a column of check boxes or radio buttons in the left most column of \n //the search results table. The value passed can be multiple/single/none. \n //multiple ? to display a check box \n //single ? to display radio button.\n //none- no additional column is displayed for selection\n this.selection = null;\n\n //\n //The parameter value will allow display of the OOTB command ?AEFSaveQuery? on the toolbar. \n this.showSavedQuery = \"false\";\n\n //\n //If submitLabel is passed, as an URL parameter then the button will be displayed with the value passed else \n //will be displayed with label ?Done?.\n //This button will be shown only if Callback function is passed in the URL. This display can be suppressed \n //by passing additional parameter submitLink = false. \n //The value can be static text or a property key.\n //This is the existing URL parameter supported by structure browse component\n this.submitLabel = null;\n \n //\n //This parameter is used to define the callback URL. This could be the jsp page to perform the post processing \n //on an Add Existing command.\n //This is the existing URL parameter supported by structure browse component\n this.submitURL = \"../components/emxCommonAutonomySearchSubmit.jsp\";\n \n //\n //This is the table that will be passed to Indented Table to display the searched results\n this.table = \"AEFGeneralSearchResults\";\n \n //\n //This parameter is used to define a custom toolbar, if required for displaying the context \n //search using consolidated search view component. This is the toolbar that will be displayed \n //on the search results frame\n this.toolbar = null;\n\n //\n //This parameter will override the system setting for FormBased vs. Navigation Based.\n this.viewFormBased = null;\n\n \n //=================================================================\n // Other configurable parameters\n //=================================================================\n \n //\n // The height of the search window\n this.windowHeight = 600;\n \n //\n // The width of the search window\n this.windowWidth = 800;\n \n //\n // The Registered Suite parameter to be passed to JSP is needed.\n this.registeredSuite = null;\n \n //\n // The \"program\" parameter for Autonomy Search\n this.searchProgram = null;\n \n //\n //The javascript path of the callback submit javascript function.\n //Selected results will be submitted to this function. In general,\n //when the search is invoked from a chooser button on any dialog, we may pass \"getTopWindow().getWindowOpener().mySubmitCallback\"\n //where function mySubmitCallback is defined in the dialog page.\n //This is mandatory property to set.\n //\n //Example of the callback function\n //function mySubmitCallback(arrSelectedObjects) {\n // alert(\"DEBUG: ->mySubmitCallback \"+ arrSelectedObjects.length);\n // \n // for (var i = 0; i < arrSelectedObjects.length; i++) {\n // var objSelection = arrSelectedObjects[i];\n // objSelection.debug(); // Alerts the following properties\n // ...\n // objSelection.parentObjectId\n // objSelection.objectId\n // objSelection.type\n // objSelection.name\n // objSelection.revision\n // objSelection.relId\n // objSelection.objectLevel\n // ...\n // }\n //}\n this.onSubmit = null;\n \n //=================================================================\n // Opens the Autonomy Search window using the configured parameters\n //=================================================================\n this.open = function () {\n var strURL = \"../common/emxFullSearch.jsp\";\n \n // Collect the url parameters\n var arrParams = new Array;\n if (this.callbackFunction != null) {\n arrParams[arrParams.length] = \"callbackFunction=\" + this.callbackFunction;\n }\n if (this.cancelLabel != null) {\n arrParams[arrParams.length] = \"cancelLabel=\" + this.cancelLabel;\n }\n if (this.excludeOID != null) {\n arrParams[arrParams.length] = \"excludeOID=\" + this.excludeOID;\n }\n if (this.excludeOIDprogram != null) {\n arrParams[arrParams.length] = \"excludeOIDprogram=\" + this.excludeOIDprogram;\n }\n if (this.formName != null) {\n arrParams[arrParams.length] = \"formName=\" + this.formName;\n }\n if (this.frameName != null) {\n arrParams[arrParams.length] = \"frameName=\" + this.frameName;\n }\n if (this.field != null) {\n arrParams[arrParams.length] = \"field=\" + this.field;\n }\n else {\n if (this.txtType != null) {\n arrParams[arrParams.length] = \"field=TYPES=\" + this.txtType;\n }\n }\n if (this.fieldNameActual != null) {\n arrParams[arrParams.length] = \"fieldNameActual=\" + this.fieldNameActual;\n }\n if (this.fieldNameDisplay != null) {\n arrParams[arrParams.length] = \"fieldNameDisplay=\" + this.fieldNameDisplay;\n }\n if (this.formInclusionList != null) {\n arrParams[arrParams.length] = \"formInclusionList=\" + this.formInclusionList;\n }\n if (this.hideHeader != null) {\n arrParams[arrParams.length] = \"hideHeader=\" + this.hideHeader;\n }\n if (this.mandatorySearchParam != null) {\n arrParams[arrParams.length] = \"mandatorySearchParam=\" + this.mandatorySearchParam;\n }\n if (this.searchCollectionEnabled != null) {\n arrParams[arrParams.length] = \"searchCollectionEnabled=\" + this.searchCollectionEnabled;\n }\n if (this.selection != null) {\n arrParams[arrParams.length] = \"selection=\" + this.selection;\n }\n if (this.showSavedQuery != null) {\n arrParams[arrParams.length] = \"showSavedQuery=\" + this.showSavedQuery;\n }\n if (this.submitLabel != null) {\n arrParams[arrParams.length] = \"submitLabel=\" + this.submitLabel;\n }\n if (this.table != null) {\n arrParams[arrParams.length] = \"table=\" + this.table;\n }\n if (this.toolbar != null) {\n arrParams[arrParams.length] = \"toolbar=\" + this.toolbar;\n }\n if (this.viewFormBased != null) {\n arrParams[arrParams.length] = \"viewFormBased=\" + this.viewFormBased;\n }\n if (this.searchProgram != null) {\n arrParams[arrParams.length] = \"program=\" + this.searchProgram;\n }\n if (this.registeredSuite != null) {\n arrParams[arrParams.length] = \"Registered Suite=\" + this.registeredSuite;\n }\n if (this.onSubmit != null) {\n arrParams[arrParams.length] = \"onSubmit=\" + this.onSubmit;\n }\n if (this.submitURL != null) {\n arrParams[arrParams.length] = \"submitURL=\" + this.submitURL;\n }\n \n var strParams = arrParams.join(\"&\");\n strURL += \"?\" + strParams;\n\n // Open the search window\n showModalDialog(strURL, this.windowWidth, this.windowHeight, true);\n }//End: open()\n}//End: emxCommonAutonomySearch()",
"function redrawWordCloud() {\n WordCloud(document.getElementById('canvas'), OPTIONS);\n}",
"function watchForm() {\n // console.log('watchForm() ready');\n $('#js-searchForm').submit(e => {\n e.preventDefault();\n $('#js-results').html('');\n const userInput = $('#js-searchInput').val();\n refineInput(userInput);\n });\n}",
"function wordCloud (dict, cloudtype, title, color1, color2, id) {\n id.html(\"\");\n // create a tag (word) cloud chart\n var chart = anychart.tagCloud(dict);\n // set a chart title\n chart.title(title)\n // set an array of angles at which the words will be laid out\n chart.angles([0])\n // set text spacing\n chart.textSpacing(3); \n chart.container(cloudtype);\n // configure the visual settings of the chart\n // create and configure a color scale.\n var customColorScale = anychart.scales.linearColor();\n customColorScale.colors([color1, color2]);\n\n // set the color scale as the color scale of the chart\n chart.colorScale(customColorScale);\n chart.hovered().fill(\"#93bfec\");\n chart.selected().fill(\"#1f66ad\");\n chart.normal().fontWeight(600);\n chart.draw();\n}",
"render() {\n return (\n <div class=\"add-post-container\">\n <h3>Add Post</h3>\n <Form model=\"forms.addPost\" onSubmit={(val) => this.handleSubmit(val)}>\n <Control type=\"text\" model=\"forms.addPost.title\" class=\"form-control\" placeholder=\"Enter title\"/>\n <Control type=\"text\" model=\"forms.addPost.description\" class=\"form-control\" placeholder=\"Enter description\" />\n <button class=\"btn btn-default\">Add Post</button>\n </Form>\n\n {this.errorMessage()}\n </div>\n )\n }",
"function LoadDocumentBtnClicked() \n{\n\n //Initialize Viwer\n\tOnInitializeViwer();\n\t\n //get the document provided by the user\n documentId = document.getElementById(\"DocIdTB\").value;\n\n //load the document\n Autodesk.Viewing.Document.load(documentId, Autodesk.Viewing.Private.getAuthObject(), onSuccessDocumentLoadCB, onErrorDocumentLoadCB);\n //update the command line text.\n UpdateCommandLine(\"Loading document : \" + documentId);\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}",
"function doSearch(){\n document.SearchCustomer.search.value = true;\n document.SearchCustomer.curpos.value=0;\n submit('SearchCustomer');\n }",
"function processMetadataForm(theForm) {\n var props=PropertiesService.getDocumentProperties()\n //Process each form element\n var description = \"{\";\n for (var item in theForm) {\n props.setProperty(item,theForm[item]);\n description += \"\\\"\" + item + \"\\\":\\\"\" + theForm[item] + \"\\\",\";\n Logger.log(item+':::'+theForm[item]);\n }\n var size = description.length;\n description = description.substring(0,size-1);\n description += \"}\";\n var id = DocumentApp.getActiveDocument().getId();\n DriveApp.getFileById(id).setDescription(description);\n\n}",
"function onAddedWordsuite() {\r\n $('#tokenfieldWordsuites').tokenfield('setTokens', []);\r\n $('#modalAddedWordsuite').modal('hide');\r\n //document.location.reload(true);\r\n alert($('#msgItemsAdded').val());\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines the AdSize for the slot. | function adSize(slot) {
if (slot.params.cf) {
var size = slot.params.cf.toUpperCase().split('X');
var width = parseInt(slot.params.cw || size[0], 10);
var height = parseInt(slot.params.ch || size[1], 10);
return [width, height];
}
return [1, 1];
} | [
"function get_item_size() {\n var sz = 220;\n return sz;\n}",
"function banner(slot) {\n var size = adSize(slot);\n return slot.nativeParams || slot.params.video ? null : {\n w: size[0],\n h: size[1],\n battr: slot.params.battr\n };\n}",
"function computeLaneSize(lane) {\n\t\t // assert(lane instanceof go.Group && lane.category !== \"Pool\");\n\t\t var sz = computeMinLaneSize(lane);\n\t\t if (lane.isSubGraphExpanded) {\n\t\t var holder = lane.placeholder;\n\t\t if (holder !== null) {\n\t\t var hsz = holder.actualBounds;\n\t\t sz.height = Math.max(sz.height, hsz.height);\n\t\t }\n\t\t }\n\t\t // minimum breadth needs to be big enough to hold the header\n\t\t var hdr = lane.findObject(\"HEADER\");\n\t\t if (hdr !== null) sz.height = Math.max(sz.height, hdr.actualBounds.height);\n\t\t return sz;\n\t\t}",
"function getItemSize(index) {\n flushPendingChanges.call(this);\n\n var block = this.block_table[index >> this.block_shift];\n if (block) {\n var value = block.sizes[index & this.block_mask];\n return value !== value ? this._defaultSize : value;\n } else {\n return this._defaultSize;\n }\n }",
"function setnhdrwrapsizerReducedSizePX(){\r\nvar gseaInitSize = document.getElementById('gsea').offsetHeight;\r\nvar addstuffBarInitSize = document.getElementById('addstuff').offsetHeight;\r\n\r\nvar nhdrwrapsizerReducedSize = gseaInitSize - addstuffBarInitSize;\r\nreturn nhdrwrapsizerReducedSize+\"px\";\r\n}",
"get tileSize() {}",
"heightModifier(slot) {\n const pixelsPerSlot = 70;\n\n if (slot === 0) {\n return 0;\n } else if (slot % 2 === 0) { //even = below\n return -1 * (Math.ceil(slot / 2)) * pixelsPerSlot;\n } else { //odd = above\n return (Math.ceil(slot / 2)) * pixelsPerSlot;\n }\n }",
"function GetItemRectSize(out = new ImVec2()) {\r\n return bind.GetItemRectSize(out);\r\n }",
"function getSimulationSize() {\n return Math.floor(MAX_SIZE / sizePerElection);\n } // getSimulationSize",
"newAdSlot(placementName, channel, targeting, adUnitPath, slotSize, sizeMappings) {\n return new Promise(((resolve) => {\n let adSlot;\n window.freestar.queue.push(async () => {\n if (!adUnitPath) {\n const mappedName = await this.getMappedPlacementName(placementName, targeting);\n window.freestar.newAdSlots({\n slotId: mappedName,\n placementName: mappedName,\n targeting,\n }, channel);\n resolve(null);\n } else {\n this.log(0, 'adUnitPath set, creating GAM ad unit');\n adSlot = window.googletag\n .defineSlot(adUnitPath, slotSize, placementName)\n .addService(window.googletag.pubads());\n if (sizeMappings) {\n const sizeMappingArray = sizeMappings\n .reduce(\n (mapping, size) => mapping.addSize(size.viewport, size.slot),\n window.googletag.sizeMapping(),\n )\n .build();\n adSlot.defineSizeMapping(sizeMappingArray);\n }\n if (targeting) {\n Object.entries(targeting).forEach((entry) => {\n const [key, value] = entry;\n adSlot.setTargeting(key, value);\n });\n }\n window.googletag.display(adSlot);\n window.googletag.pubads().refresh([adSlot]);\n resolve(adSlot);\n }\n });\n }));\n }",
"function setCardSize(){\n if (windowHeight/rangee < gameWidth/column){\n cardSize = windowHeight/rangee*0.7;\n }\n else {\n cardSize = gameWidth/column*0.7;\n }\n}",
"function getSlotCount(device,slotcnt){\n\tif(device.SLOT != null && device.SLOT != undefined){\n\t\tfor(var t=0; t<device.SLOT.length; t++){\n\t\t\tvar slotpath = device.SLOT[t].ObjectPath.split(\".\");\n\t\t\tvar pathArr = slotpath[slotpath.length -1].split(\"_\");\n\t\t\tslotcnt = pathArr[1];\n\t\t}\n\t}\n\treturn slotcnt;\n}",
"function sizeShouldReturnDimensionsForElementWithMargin() {\n const data = element.size(fixture.el.querySelector(\".size\"))\n expect(data)\n .toEqual({\n width: 100,\n height: 100\n })\n}",
"function updateSectionSize(sSize, j) {\n\t\tif(gameState == true){\n\t\t\tvar now = Date.now();\n\n\t\t\tvar time = now - last[j];\n\t\t\tlast[j] = now;\n\t\t\treturn (sSize + (SECTIONSIZE_PER_SECOND * time) / 100.0);\n\t\t}\n\t}",
"getTileSize(tileEdge) {\n return {\n width: 2.0 * tileEdge,\n height: Math.sqrt(3.0) * tileEdge,\n }\n }",
"function getDependencySize(dependencyDump) {\n var numeric = dependencyDump.numerics[SIZE_NUMERIC_NAME];\n if (numeric === undefined)\n return 0;\n shouldDefineSize = true;\n return numeric.value;\n }",
"function calculateHeight() {\n\t\treturn (val / capacity) * bottleHeight;\n\t}",
"calculateLayoutSizes() {\n const gridItemsRenderData = this.grid.getItemsRenderData();\n this.layoutSizes =\n Object.keys(gridItemsRenderData)\n .reduce((acc, cur) => (Object.assign(Object.assign({}, acc), { [cur]: [gridItemsRenderData[cur].width, gridItemsRenderData[cur].height] })), {});\n }",
"getRectSize() {\n\t\treturn {\n\t\t\t'width':this.rectArea.width / this.horizontalPeriod.count - this.rectMargin / 2,\n\t\t\t'height':this.rectArea.height / this.verticalPeriod.count - this.rectMargin / 2\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mira si existe la carpeta ebooks, de no existir, la crea | verificaSiExisteEbooks()
{
let verificaGenerador = (function *()
{
let existeCarpeta = yield this.existe( EBOOKS, true, verificaGenerador );
if (!existeCarpeta)
{
yield this.creaCategoriaNueva( EBOOKS, verificaGenerador );
/* eslint no-console: "off" */
console.log( 'Carpeta ebooks creada.' );
}
}.bind( this ))();
verificaGenerador.next();
} | [
"findBookIndex(book) {\n let bookIndex = this.allBooks.indexOf(book);\n if (bookIndex == -1) {\n console.error(\"Book does not exist in allBooks array\")\n return false\n } else {\n return bookIndex;\n }\n\n }",
"function createWorkbook() {\n const newWb = XLSX.utils.book_new();\n return newWb;\n}",
"function validateQuizTitle(title){\r\n let dirToRead = `quizzes/${cat}/`, alrdyTaken = false;\r\n\r\n if(title == \"\") alrdyTaken = true;\r\n\r\n fs.readdir(dirToRead, (err, files) => {\r\n if(err) throw err;\r\n if(files.length != 0){\r\n files.forEach((file) => {\r\n // Remove .json from quiz names\r\n let fileName = file.replace(\".json\", \"\");\r\n if(fileName == title){\r\n console.log(\"\\nQuiz already exists, try again\");\r\n alrdyTaken = true;\r\n } \r\n })\r\n }\r\n })\r\n return !alrdyTaken;\r\n // if(alrdyTaken) return false;\r\n // else return true;\r\n }",
"function pageExists( title )\n{\n if (FILE.file_exists( pagePath( title ) ) || isSpecial( title ) ){\n return true;\n }else{\n return false;\n }\n}",
"addEpiniac() {\n return this.r.tableCreate('epiniac').run() // Create a table just for PoB supplies\n .then(() => winston.info(\"Epiniac table created.\")) // If it works\n .catch(() => winston.warn(\"Epiniac table already exists.\")) // If it already exists.\n }",
"function addBook() {\n // TODO: handles click event\n // For now just add test book to the db\n /*vm.book = {\n title: \"Gratitude\",\n author: \"Oliver Sacks\",\n genre: \"Memoir\"\n };\n\n BooksFactory.addBook(vm.book, function (response) {\n console.log('Book added')\n });*/\n }",
"function existeixEmpresa(done){\n\tconsole.log(\"existeixEmpresa()\");\n\tmyClient.query('SELECT * FROM empresa WHERE UPPER(name) \\\n\t\t\t\t\t\tLIKE UPPER(\\'%cola%\\')', \n\t\tfunction(err, result){\n\t\t\tif(err){\n\t\t\t\tconsole.log(\"Empresa no trobada\");\t\n\t\t\t}\n\t\t\tif(result){\n\t\t\t\tif(result.rows.length == 0){\n\t\t\t\t\tconsole.log(\"Empresa no trobada\");\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\t//TODO\n\t\t\t\t\t//myClient.query()\n\t\t\t\t\tconsole.log(result.rows);\n\t\t\t\t}\n\t\t\t}\n\t\t\tdone();\n\t\t\tpg.end();\n\t});\n}",
"fileExists() {\n return fs.pathExists(this.location);\n }",
"function doesApplicationExist (eb, appName) {\n return eb.describeApplications({ ApplicationNames: [appName] }).then(function (data) {\n return !!data.Applications.length;\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 addBookToLibraryTable(book) {\n\t// Add code here\n\tconst bookName = book.title\n\tconst bookID = book.bookId\n\tconst bookPatron = book.patron\n\n\t// Create BookName\n\n\tconst nameTableData = document.createElement('td')\n\tconst TableBookName = document.createTextNode(bookName)\n\tconst strong = document.createElement(\"STRONG\")\n\tstrong.appendChild(TableBookName)\n\tnameTableData.appendChild(strong)\n\n\t// Create BookID\n\n\tconst bookIdTableData = document.createElement('td')\n\tbookIdTableData.appendChild(document.createTextNode(bookID))\n\t\n\t// Creating Patron if there are any\n\n\tconst bookPatronTableData = document.createElement('td')\n\tif (bookPatron !== null) {\n\t\tbookPatronTableData.appendChild(bookPatron)\n\t}\n\n\tconst newBookRow = document.createElement('tr')\n\tnewBookRow.appendChild(bookIdTableData)\n\tnewBookRow.appendChild(nameTableData)\n\tnewBookRow.appendChild(bookPatronTableData)\n\n\tbookTable.firstElementChild.appendChild(newBookRow)\n\n}",
"function archivoSIS(nombreAD, cuerpo){\n var path = \"../archivo/\";\n var fileContent = cuerpo;\n var name = nombreAD;\n path1 = path + name;\n /*fs.stat( path + name , function(error, stats){\n console.log('verificando existe:' + stats.isFile());\n });*/\n fs.writeFile( path+name, fileContent,(err) =>{\n if(err)throw err;\n console.log(\"el file ha sido creado y llenando los datos\");\n })\n }",
"exists(objectHash) {\n return objectHash !== undefined\n && fs.existsSync(nodePath.join(Files.gitletPath(), 'objects', objectHash));\n }",
"async notExists(identifier) {\n try {\n await this.findComponent(identifier);\n } catch (e) {\n if (e.name == \"ComponentNotFoundError\") {\n return true;\n }\n throw e;\n }\n throw new Error(`Component with identifier ${identifier} was present`);\n }",
"isBookInLibrary(book){\n for (const b of this.state.books){\n if (b.id===book.id){\n return true; \n }\n }\n\n return false; \n}",
"function bacaBooks(waktu, books, indeks = 0) {\n if (indeks < books.length) {\n readBooks(waktu, books[indeks], function (sisa) {\n if (sisa > 0) {\n bacaBooks(sisa, books, indeks + 1);\n }\n });\n } else {\n console.log(\"buku habis\");\n }\n}",
"function loadBooks() {\n\t\tAPI.getBooks()\n\t\t\t.then((res) => setBooks(res.data))\n\t\t\t.catch((err) => console.log(err));\n\t}",
"async criarPessoa(pessoa) {\n this.validarPessoa(pessoa);\n\t\tconst pessoaCriada = await PessoaRepository.create(pessoa);\n\t\treturn pessoaCriada;\n }",
"async detectNew() {\n const existing = await self.db.countDocuments();\n return !existing;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reward user with badge. | function rewardBadge(codename, params){
// Remove from checkers.
delete params._userCheckers[codename];
// Add badge to user.
User.findOne({_id:params.user.id}, function(err, user){
if(err || !user) return;
// Add badge.
user.badges.push(params.badge._id);
user.markModified('badges');
// Save
user.save();
});
// Notify user!
params._socket.emit('reward', params.badge);
} | [
"function achievements_grant(id, close_payload){\n\tif (this.tsid == 'PCRN0MDLUUT195N' || config.is_dev) log.info(this+' achievements_grant '+id);\n\tif (this.achievements_has(id)) return;\n\t\n\tvar achievement = this.achievements_get(id);\n\tif (!achievement){\n\t\tlog.error(this+' unlocked invalid achievement: '+id);\n\t\treturn;\n\t}\n\t\n\tutils.http_post('callbacks/achievement_counter_by_day.php', {player: this.tsid, achievement: id, shareworthy: achievement.is_shareworthy}, this.tsid);\n\n\t//\n\t// If the player is offline, queue it\n\t//\n\t\n\tif (!this.isOnline() || ((!this.has_done_intro || this.location.is_newxp || this.location.is_skillquest) && this.location.class_tsid != 'newbie_island')){\n\t\tif (this.tsid == 'PCRN0MDLUUT195N' || config.is_dev) log.info(this+' achievements_grant queueing '+id);\n\t\treturn this.achievements_add_queue(id);\n\t}\n\t\t\n\tif (this.tsid == 'PCRN0MDLUUT195N' || config.is_dev) log.info(this+' achievements_grant giving '+id);\n\tthis.achievements.achievements[id] = time();\n\t\n\t\n\tvar status = 'You got the '+achievement.name+' badge!';\n\tif (achievement.status_text) status = achievement.status_text;\n\tthis.sendActivity(status, null, true);\n\t\n\tvar text = this.label + ' just got the '+this.achievements_linkify(id)+' badge!';\n\tthis.sendLocationActivity(text, this, this.buddies_get_ignoring_tsids());\n\t\n\tvar out = {\n\t\ttype\t\t\t: 'achievement_complete',\n\t\ttsid\t\t\t: id,\n\t\tname\t\t\t: achievement.name,\n\t\tdesc\t\t\t: achievement.desc,\n\t\tswf_url\t\t\t: achievement.url_swf,\n\t\tis_shareworthy\t: achievement.is_shareworthy,\n\t\tstatus_text\t\t: status,\n\t\turl\t\t\t\t: config.web_root+'/profiles/'+this.tsid+'/achievements/'+achievement.url+'/'\n\t};\n\n\tif (close_payload) out.close_payload = close_payload;\n\n\t// If we have the silvertongue buff, adjust achievement values accordingly\n\tvar multiplier = this.buffs_has('gift_of_gab') ? 1.2 : this.buffs_has('silvertongue') ? 1.05 : 1.0;\n\tmultiplier += this.imagination_get_achievement_modifier();\n\t\n\t// See here: http://bugs.tinyspeck.com/8804\n\t// It would be nice if we had access to the category, but luckily these completist achievements are\n\t// easy to detect.\n\tif (/completist/.exec(id)) {\n\t\tlog.info(this+\" level is \"+this.stats_get_level()+\" and multiplier is \"+multiplier);\n\t\t\n\t\tvar level = this.stats_get_level();\n\t\t\n\t\tif (level > 4){\n\t\t\tmultiplier *= (this.stats_get_level() / 4);\n\t\t}\n\t\t\n\t\tlog.info(this+\" new multiplier is \"+multiplier);\n\t}\n\t\n\tvar ac_rewards = achievement.rewards;\n\tif (ac_rewards){\n\t\t\n\t\tout.rewards = {\n\t\t\txp\t\t: round_to_5(ac_rewards.xp * multiplier),\n\t\t\tenergy\t\t: round_to_5(ac_rewards.energy * multiplier),\n\t\t\tmood\t\t: round_to_5(ac_rewards.mood * multiplier),\n\t\t\tcurrants\t: round_to_5(ac_rewards.currants * multiplier)\n\t\t};\n\n\t\tif (ac_rewards.favor){\n\t\t\tout.rewards.favor = [{\n\t\t\t\tgiant\t: ac_rewards.favor.giant,\n\t\t\t\tpoints\t: round_to_5(ac_rewards.favor.points * multiplier)\n\t\t\t}];\n\t\t}\n\n\t\tif (ac_rewards.items){\n\t\t\tout.rewards.items = ac_rewards.items;\n\t\t}\n\n\t\tif (ac_rewards.recipes){\n\t\t\tvar recipes = {};\n\t\t\tfor (var i in ac_rewards.recipes){\n\t\t\t\tif (!this.making_recipe_is_known(ac_rewards.recipes[i].recipe_id)){\n\t\t\t\t\trecipes[i] = ac_rewards.recipes[i].recipe_id;\n\t\t\t\t}\n\t\t\t}\n\t\t\tout.rewards.recipes = recipes;\n\t\t}\n\n\t\tif (out.rewards.xp){\n\t\t\tif (!out.rewards.imagination) out.rewards.imagination = 0;\n\t\t\tout.rewards.imagination += out.rewards.xp;\n\t\t\tout.rewards.imagination = round_to_5(out.rewards.imagination);\n\t\t\tdelete out.rewards.xp;\n\t\t}\n\n\t}\n\telse{\n\t\tout.rewards = {};\n\t}\n\n\tif (achievement.collection_type){\n\t\t//\n\t\t// Remove all items from the player's inventory\n\t\t//\n\t\n\t\tvar trophy_items = [];\n\t\tfor (var i in achievement.conditions){\n\t\t\tvar condition = achievement.conditions[i];\n\t\t\tif (condition.group == 'in_inventory'){\n\t\t\t\tif (achievement.collection_type == 2) this.items_destroy(condition.label, condition.value);\n\t\t\t\n\t\t\t\tvar prot = apiFindItemPrototype(condition.label);\n\t\t\t\tif (prot){\n\t\t\t\t\tvar item = {\n\t\t\t\t\t\tclass_tsid\t: condition.label,\n\t\t\t\t\t\tlabel\t\t: prot.name_single,\n\t\t\t\t\t\tdesc\t\t: prot.description\n\t\t\t\t\t};\n\t\t\t\t\n\t\t\t\t\t// Items with sounds\n\t\t\t\t\tif (prot.is_musicblock){\n\t\t\t\t\t\titem.sound = config.music_map[condition.label.toUpperCase()];\n\t\t\t\t\t}\n\t\t\t\n\t\t\t\t\ttrophy_items.push(item);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\t\tvar trophy = this.achievement_get_trophy(id);\n\t\n\t\n\t\tthis.daily_history_push('collections', id);\n\t\n\t\tout.type = 'collection_complete';\n\t\tout.trophy_items = trophy_items;\n\t\tout.trophy = trophy;\n\t\n\t\tout.sound = 'TROPHY_RECEIVED';\n\t\n\t\tapiLogAction('TROPHY_UNLOCKED', 'pc='+this.tsid, 'achievement='+id, 'xp='+intval(out.rewards.imagination), 'mood='+intval(out.rewards.mood), 'energy='+intval(out.rewards.energy), 'currants='+intval(out.rewards.currants), 'favor_giant='+(out.rewards.favor ? out.rewards.favor[0].giant : 'none'), 'favor_points='+(out.rewards.favor ? intval(out.rewards.favor[0].points) : 0));\n\t}\n\telse{\n\t\tthis.daily_history_push('achievements', id);\n\t\tout.sound = 'ACHIEVEMENT_UNLOCKED';\n\t\n\t\n\t\tapiLogAction('ACHIEVEMENT_UNLOCKED', 'pc='+this.tsid, 'achievement='+id, 'xp='+intval(out.rewards.imagination), 'mood='+intval(out.rewards.mood), 'energy='+intval(out.rewards.energy), 'currants='+intval(out.rewards.currants), 'favor_giant='+(out.rewards.favor ? out.rewards.favor[0].giant : 'none'), 'favor_points='+(out.rewards.favor ? intval(out.rewards.favor[0].points) : 0));\n\t}\n\tthis.apiSendMsgAsIs(out);\n\n\tif (achievement.onComplete) achievement.onComplete.call(achievement, this);\n\tif (achievement.on_apply) achievement.on_apply.call(achievement, this);\n\n\tthis.activity_notify({\n\t\ttype\t: 'achievement',\n\t\tid\t: id\n\t});\n}",
"async captureAge(step) {\n const user = await this.userProfile.get(step.context, {});\n if (step.result !== -1) {\n user.age = step.result;\n await this.userProfile.set(step.context, user);\n await step.context.sendActivity(`I will remember that you are ${ step.result } years old.`);\n } \n else {\n await step.context.sendActivity(`No age given.`);\n }\n return await step.endDialog();\n }",
"upd_premium () {\n return betess.post(`premium/`, {\n authorization: store.state.accesstoken,\n }).then(response => response.data)\n .catch((error) => {\n alert(error.message)\n })\n }",
"function update_badge(badgeText) {\n Log.info('update_badge', badgeText);\n chrome.browserAction.setBadgeText({ text: badgeText });\n}",
"function buddyBuys() {\n if (playerSobriety > 0) {\n var newPlayerSobriety = playerSobriety -= avcBuddy;\n var newBuddyMoney = buddyMoney -= costBuddy;\n displayPlayerSobriety(newPlayerSobriety);\n displayBuddyMoney(newBuddyMoney);\n playerSobriety = newPlayerSobriety;\n buddyMoney = newBuddyMoney;\n buddyServes();\n buddyRestore();\n //alert(buddy.type + \" buys you a \" + avcBuddy + \"% \" + buddyDrinkName + \".\");\n console.log(newPlayerSobriety);\n playerTurn = false;\n\n //drinkLoop();\n } else {\n alert(player.name + \" passed out!\");\n playerOut();\n }\n }",
"function update_badge(){\n\t//count unread notes\n\tvar count = 0;\n\tfor(var i in note_data){\n\t\tif(note_data[i].unread){ count++; }\n\t}\n\n\t//get the saved value from lastupdate\n\tstorage.get('lastUnread',function(data){\n\t\t//load the value if it exists\n\t\tif(data.hasOwnProperty('lastUnread')){ lastUnread = data.lastUnread; }\n\n\t\t//did the amount change from the last check?\n\t\tif(lastUnread < count){\n\t\t\t//try playing a sound to notify the user\n\t\t\tstorage.get('sound', function(data){\n\t\t\t\tif(data.sound){\n\t\t\t\t\tsndNewNote.play();\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\t//update the new total\n\t\tlastUnread = count;\n\t\tstorage.set({ lastUnread: lastUnread });\n\t});\n\n\t//update the badge text\n\tchrome.browserAction.setBadgeText({ text: String(count || '') });\n}",
"function setBadge(text){\n\tchrome.browserAction.setBadgeText({ text: text });\n}",
"function healingPotionMacro() {\n const speaker = ChatMessage.getSpeaker();\n let actor;\n if (speaker.token) actor = game.actors.tokens[speaker.token];\n if (!actor) actor = game.actors.get(speaker.actor);\n\n if (actor) {\n const currentDamage = parseInt(actor.data.data.characteristics.health.value);\n const healingRate = parseInt(actor.data.data.characteristics.health.healingrate);\n\n let newdamage = currentDamage - healingRate;\n if (newdamage < 0)\n newdamage = 0;\n\n actor.update({\n \"data.characteristics.health.value\": newdamage\n });\n\n\n var templateData = {\n actor: this.actor,\n token: canvas.tokens.controlled[0]?.data,\n data: {\n itemname: {\n value: game.i18n.localize('DL.DialogUseItemHealingPotion')\n },\n description: {\n value: game.i18n.localize('DL.DialogUseItemHealingPotionText').replace(\"#\", healingRate)\n }\n }\n };\n\n let chatData = {\n user: game.user._id,\n speaker: {\n actor: actor._id,\n token: actor.token,\n alias: actor.name\n }\n };\n\n let template = 'systems/demonlord/templates/chat/useitem.html';\n renderTemplate(template, templateData).then(content => {\n chatData.content = content;\n ChatMessage.create(chatData);\n });\n }\n}",
"acceptPledge() {\n this.setPledgeModalToggle();\n this.startPledgeModalToggle();\n this.state.pledge.footprintReduction = Math.round(this.state.pledge.weight * this.state.slider * 10)/10;\n this.props.addPledge(this.state.pledge);\n }",
"function displayReward () {\n var reward = document.getElementById('reward')\n if (clicks <= 50) {\n reward.textContent = \"You couldn't even beat my grandma.\";\n } else if (clicks >= 51 && clicks <= 100) {\n reward.textContent = \"Good... Not great.\";\n } else if (clicks >= 101 && clicks <= 150) {\n reward.textContent = \"Color me mildly impressed.\";\n } else if (clicks >= 151) {\n reward.textContent = \"This is your moment in the sun.\";\n }\n}",
"constructor(props){\n super(props)\n this.state = {\n isLoggedIn: sessionStorage.isLoggedIn,\n userId: sessionStorage.userId,\n userAc:[],\n user: \"\",\n availableBadges: [ \n { \n name: \"Moderate Hike\",\n img: hotdogstick,\n color: \"#464866\",\n points: 15 ,\n miles: \"4-7\"\n \n },\n { \n name: \"Strenuous Hike-Killing it!\", \n img: bear,\n color: \"#464866\",\n points: 20 ,\n miles: \"7-12\"\n }, \n {\n name: \"Ultra Hike-More than a Conqueror!\",\n img: bearpaw,\n color: \"#464866\",\n points: 25,\n miles: \"15-25\"\n },\n {\n name: \"State Park Beauties\",\n img: map,\n color:\"#464866\",\n points: 30,\n miles: \"25-40\"\n }, \n { \n name: \"National Park Hike\",\n img:compass,\n color: \"#464866\",\n points: 20 ,\n miles: \"40-60\"\n } ],\n earnedBadges: [ {\n name: \"1st Hike-You did it!\",\n img: hikingboot,\n color: \"#D79922\",\n points: 5,\n miles:\"1\"\n },\n {\n name: \"Easy Hike-Keep it up!\",\n img: backpack,\n color: \"#D79922\",\n points: 10 ,\n miles: \"1-3\"\n \n }\n // {\n // name: \"Man, that trip was in tents!\",\n // img: intents,\n // color: \"#D79922\",\n // points: 100 ,\n // miles: \"1-3\"\n \n // }],\n ],\n toggle: true\n }\n \n }",
"insertCredit(person, amount) {\n person.takeMoney(amount)\n this.credits += amount\n if(this.credits>0){\n this.status = 'credited'\n }\n }",
"function followUser() {\n UserService\n .followUser(vm.uid, vm.loggedInUser)\n .then(function (response) {\n console.log(response.data);\n $route.reload();\n });\n }",
"damage(dmg) {\n \n var newHp = (this.hp - dmg);\n if (newHp < 0) {\n this.hp = 0;\n this.die();\n }\n else this.hp = newHp;\n }",
"function agreed (msg) {\n\tsendFile(msg.channel, ['./assets/this.jpg'], msg.member.displayName + \" agrees!\")\n\tconsole.log('Agreed!')\n}",
"addScore (score) {\n this.userScore += (score * 5);\n return `User score is ${this.userScore}`;\n }",
"function payLoan() {\n totalOutstandingLoan -= totalPay;\n totalPay = 0;\n\n updateTotalOutstandingLoan();\n updateTotalPay();\n}",
"async function rateTable(user, reqBody) {\n const newRating = Number(reqBody.rating);\n if (isNaN(newRating) || newRating < 0 || newRating > 5) throw new Error('Invalid rating');\n const { table } = await getTableForCustomer(user);\n if (!table) throw new Error('You are not currently assigned to a table to rate');\n if (table.timesRated == 0) table.rating = newRating;\n else {\n table.rating = ((table.rating * table.timesRated) + newRating) / (table.timesRated + 1)\n }\n table.timesRated = table.timesRated + 1;\n return await table.save();\n}",
"function checkGold(upgradeNum){\n if(totalGold >= upgradesCost[upgradeNum]){\n //gold is spent\n totalGold -= upgradesCost[upgradeNum];\n updateGold();\n notify(upgrades[upgradeNum] + \" Purchased\");\n return true;\n }\n else{\n notify('Not rich enough!');\n return false;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
In general, you can call encodeURIComponent directly since all browsers support it | function encode(text)
{
return encodeURIComponent(text);
} | [
"function encodeURL(path)\n{\n return encodeURIComponent(path).replace(/%2F/g,'/');\n}",
"encodeParams(params) {\n return Object.entries(params).map(([k, v]) => `${k}=${encodeURI(v)}`).join('&')\n }",
"buildQuerry (query){\n var ecodedQuery = encodeURIComponent(query);\n return ecodedQuery;\n }",
"function percentEncode (value) {\n var result = encodeURIComponent(value);\n return result.replace(/\\!/g, \"%21\")\n .replace(/\\'/g, \"%27\")\n .replace(/\\(/g, \"%28\")\n .replace(/\\)/g, \"%29\")\n .replace(/\\*/g, \"%2A\");\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 percentEncode(string) {\n return encodeURIComponent(string).replace(/\\*/g, \"%2A\").replace(/\\'/g, \"%27\");\n}",
"function encodeUriPath(pathParam) { \n /*if (uriPath.indexOf(\"/\") === -1) {\n return encodeUriPathComponent(uriPath);\n }\n var slashSplitPath = uriPath.split('/');\n for (var pathCptInd in slashSplitPath) {\n slashSplitPath[pathCptInd] = encodeUriPathComponent(slashSplitPath[pathCptInd]); // encoding ! NOT encodeURIComponent\n }\n return slashSplitPath.join('/');\n //return encodeURI(idValue); // encoding !\n // (rather than encodeURIComponent which would not accept unencoded slashes)*/\n var encParts, part, parts, _i, _len;\n if (pathParam.indexOf(\"/\") === -1) {\n return encodeUriPathComponent(pathParam);\n } else if (pathParam.indexOf(\"//\") !== -1) { // else '//' (in path param that is ex. itself an URI)\n // would be equivalent to '/' in URI semantics, so to avoid that encode also '/' instead\n return encodeURIComponent(pathParam);\n } else {\n parts = pathParam.split(\"/\");\n encParts = [];\n for (_i = 0, _len = parts.length; _i < _len; _i++) {\n part = parts[_i];\n ///encParts.push(encodeURIComponent(part));\n encParts.push(encodeUriPathComponent(part));\n }\n return encParts.join(\"/\");\n }\n }",
"encodeSpecials() {\n const value = this.value;\n const regex = /(\\'|\"|\\\\x00|\\\\\\\\(?![\\\\\\\\NGETHLnlr]))/g;\n return value.replace(regex, '\\\\\\\\$0');\n }",
"function createEncodedParam (key,value) {\n return {\n key: percentEncode(key),\n value: percentEncode(value)\n }\n}",
"function urlEncodePair(key, value, str) {\n if (value instanceof Array) {\n value.forEach(function (item) {\n str.push(encodeURIComponent(key) + '[]=' + encodeURIComponent(item));\n });\n }\n else {\n str.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\n }\n }",
"function _hexEncode(data) {\n var hex\n , i\n ;\n\n var result = \"\";\n for (i = 0; i < data.length; i++) {\n hex = data.charCodeAt(i).toString(16);\n result += (\"000\" + hex).slice(-4);\n }\n\n return result;\n }",
"function encodeName (name) {\n return encode('@' + name)\n}",
"function escape_xml (str) {\n\t return (\"\"+str).replace(/&/g, \"&\")\n\t .replace(/\"/g, \""\")\n\t .replace(/\"/g, \""\")\n\t .replace(/</g, \"<\")\n\t .replace(/>/g, \">\")\n\t .replace(/'/g, \"'\");\n\t}",
"function encode_ascii85(a) {\n var b, c, d, e, f, g, h, i, j, k;\n for (!/[^\\x00-\\xFF]/.test(a), b = \"\\x00\\x00\\x00\\x00\".slice(a.length % 4 || 4), a += b,\n c = [], d = 0, e = a.length; e > d; d += 4) f = (a.charCodeAt(d) << 24) + (a.charCodeAt(d + 1) << 16) + (a.charCodeAt(d + 2) << 8) + a.charCodeAt(d + 3),\n 0 !== f ? (k = f % 85, f = (f - k) / 85, j = f % 85, f = (f - j) / 85, i = f % 85,\n f = (f - i) / 85, h = f % 85, f = (f - h) / 85, g = f % 85, c.push(g + 33, h + 33, i + 33, j + 33, k + 33)) : c.push(122);\n return function(a, b) {\n for (var c = b; c > 0; c--) a.pop();\n }(c, b.length), String.fromCharCode.apply(String, c);\n}",
"function escape(code){\n \tcode = code\n \t\t//.replace(/[\\s\\t]+/g, '') // �ո���Tab\n .replace(/('|\"|\\\\)/g, '\\\\$1')// ��˫�����뷴б��ת��\n .replace(/\\r/g, '\\\\r')// ���з�ת��(windows + linux)\n .replace(/\\n/g, '\\\\n');\n \treturn outCode + '\"' + code + '\";';\n }",
"function escapeXml(xml) \n{\n return xml.replace(/[<>&'\"]/g, function (c) {\n switch (c) {\n case '<': return '<';\n case '>': return '>';\n case '&': return '&';\n case '\\'': return ''';\n case '\"': return '"';\n }\n });\n}",
"function escapeQueryChars(unescaped, preserveWildcards) {\n if (!unescaped) {\n return '';\n }\n unescaped = unescaped.replace(/([\\\\\\+\\-\\!\\(\\)\\:\\^\\[\\]\\\"\\{\\}\\~\\|\\&\\;\\/\\s])/g, '\\\\$1');\n if (!preserveWildcards) {\n unescaped = unescaped.replace(/([\\*\\?])/g, '');\n }\n return unescaped;\n}",
"function escapeArg (value) {\n function hexencode (match) {\n return \"\\\\x\" + match.charCodeAt(0).toString(16);\n }\n return value.replace(/[\\\\\", \\n]/g, hexencode);\n}",
"encodeKey(key) {\n return `${key.hostname}+${key.rrtype}`\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send data to background script through runtime port. | function sendDataToBackground(data) {
chromePort.postMessage(data)
} | [
"function sendToSerial(data) {\n console.log(\"sending to serial: \" + data);\n myPort.write(data);\n}",
"function sendData() {\n\n // Get all PID input data and store to right index of charVal\n for(var i = 1; i <= 18; i++) {\n txCharVal[i] = select(inputMap[i]).value;\n }\n\n // Get all control input data and store to right index of exCharVal\n exCharVal[0] = select('#throttle').value;\n\n // Sending PID data with rxChar over BLE\n writeArrayToChar(txChar, txCharVal)\n .then( () => {\n console.log(\"PID data sent:\", txCharVal);\n\n // Sending throttle data with exChar over BLE\n writeArrayToChar(exChar, exCharVal)\n .then( () => {\n console.log(\"Data sent:\", exCharVal);\n })\n .catch( (error) => {\n console.log('Control data sending failed:', error)\n });\n })\n .catch( (error) => {\n console.log('PID data sending failed:', error)\n });\n}",
"function sendTempCmd() {\r\n\t// console.log(\"Sending read temperature command...\");\r\n\tsensor.writeBytes(0xe0, [1], function(err) {\r\n\t\tif(err) {\r\n\t\t\tconsole.log(\"writeBytes: 0xe0: \" + err);\r\n\t\t}\r\n\t\treadTemp();\t// No need to wait since it was computed with humidity\r\n\t});\r\n}",
"function sendMessage(message) {\n port.postMessage(message);\n}",
"_send(type, data) {\n this._midiOutput.send(type, _.extend(data, { channel: this._midiChannel } )); \n }",
"function send( type, data ) {\n\tServer.send( type, data );\n}",
"program (programNumber, speed) {\n this._sendMessage([0xbb, programNumber + 0x24, speed, 0x44])\n }",
"async _sendMsg (cmd, arg1, arg2, payload) {\n let adbPacket = generateMessage(cmd, arg1, arg2, payload);\n await this.outputEndpoint.transferAsync(adbPacket);\n if (payload !== \"\") {\n if (_.isNumber(payload)) {\n payload = payload.toString();\n } else if (typeof payload !== Buffer) {\n payload = new Buffer(payload);\n }\n await this.outputEndpoint.transferAsync(payload);\n }\n }",
"function send_tcp(addr, path, args) {\n\tvar toks = addr.split('.');\n\tif (toks[toks.length-1] == '255') {\n\t\tfor (var dev_id in dev_dict) {\n \t\tif (dev_dict.hasOwnProperty(dev_id)) {\n\t \tfor (var node_id in dev_dict[dev_id]) {\n\t\t\t\t\tif (dev_dict[dev_id].hasOwnProperty(node_id))\n\t\t\t\t\t\tsend_tcp(dev_dict[dev_id][node_id], path, args);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse {\n\t\toutlet(0, 'host', '127.0.0.1');\n\t\toutlet(0, 'port', pyport);\n\t\toutlet(0, '/tcp', addr, iotport, path, args)\n\t}\n}",
"function write2WebserverClient(type, data) {\n let obj = {\n cmdtype: type,\n cmdData: data\n };\n if (webServerSocket != null) {\n webServerSocket.write(JSON.stringify(obj));\n }\n}",
"function make_external_command({command_info,client_id,ws}) { \n\n //dynamically create the command class here \n class external_command extends base_command { \n\t\n\tconstructor(config) {\n \t super({id : command_info['id']})\n\t this.command_info = command_info //store the info within the command \n\t}\n\t\n\tstatic get_info() { \n\t return command_info \n\t}\n\t//loop read from the external receive channel and emit \n\tasync listen(receive) { \n\t this.log.i(\"Starting listen loop\")\n\t while (true) { \n\t\tlet msg = await receive.shift() //read from the receive channel \n\t\tswitch(msg['type']) { \n\t\t \n\t\tcase 'emit' : \n\t\t this.emit(msg['data'] )\n\t\t break\n\t\t \n\t\tcase 'feedback' : \n\t\t this.feedback(msg['data'] )\n\t\t break\n\t\t \n\t\t \n\t\tcase 'finish' : \n\t\t this.finish({payload : {result: msg['data']['result']},\n\t\t\t\t error : msg['data']['error']})\n\t\t break \n\n\t\tcase 'call_command' : \n\t\t this.log.i(\"Calling command\")\n\t\t this.launch_command(msg['data']) \n\t\t break \n\t\t \n\t\tdefault : \n\t\t this.log.i(\"Unrecognized msg type in listen loop:\")\n\t\t this.log.i(msg)\n\t\t break \n\t\t}\n\t }\n\t}\n\t\n\t// define the relay function \n\trelay(data) { \n\t //append id and instance id\n\t data.id = this.cmd_id.split(\".\").slice(1).join(\".\") //get rid of module name\n\t data.instance_id = this.instance_id \n\t ws.send(JSON.stringify(data)) // send it \n\t}\n\t\n\tasync run() { \n\t let id = this.command_info['id']\n\t \n\t this.log.i(\"Running external command: \" + id )\n\t \n\t //make a new channel \n\t let receive = new channel.channel()\n\t \n\t //update the global clients structure \n\t let instance_id = this.instance_id\n\t add_client_command_channel({client_id,receive,instance_id})\n\n\t \n\t //start the async input loop\n\t this.listen(receive)\n\t \n\t //notify external interface that the command has been loaded \n\t let args = this.args \n\t var call_info = {instance_id,args } \n\t //external interface does not know about the MODULE PREFIX added to ID \n\t call_info.id = id.split(\".\").slice(1).join(\".\") \n\t \n\t let type = 'init_command' \n\t this.relay({type, call_info}) \n\t this.log.i(\"Sent info to external client\")\n\t \n\t //loop read from input channel \n\t this.log.i(\"Starting input channel loop and relay\")\n\t var text \n\t while(true) { \n\t\tthis.log.i(\"(csi) Waiting for input:\")\n\t\t//text = await this.get_input()\n\t\ttext = await this.input.shift() //to relay ABORTS \n\t\tthis.log.i(\"(csi) Relaying received msg to external client: \" + text)\n\t\t//now we will forward the text to the external cmd \n\t\tthis.relay({type: 'text' , data: text})\n\t }\n\t}\n }\n //finish class definition ------------------------------ \n return external_command\n}",
"function sendTransferenciaToPageScript() {\n loadTransferenciaFromStorage()\n .then( transferencia => { \n window.postMessage({ // send message to page script\n from: \"autopac\", // from autopac extension\n transferencia: transferencia\n }, \"*\"); // to any targetOrigin\n });\n}",
"function write2BleClient(type, data) {\n let obj = {\n cmdtype: type,\n cmdData: data\n };\n if (bleClientSocket != null) {\n bleClientSocket.write(JSON.stringify(obj));\n }\n}",
"sendEvent (action) {\n let event = this.buildKiteEvent(action);\n let msg = JSON.stringify(event);\n\n this.outgoingSocket.send(msg, 0, msg.length, KiteOutgoing.PORT, KiteOutgoing.HOST);\n }",
"function foo() {\n chrome.runtime.sendMessage({ text: \"Time please!\" }, showTime);\n}",
"send(...args) {\n this._send_handler(...args)\n }",
"function listening_handler() {\n\tconsole.log(`Now Listening on Port ${port}`);\n}",
"emitter(editor, data, value) {\n // Emit code change to socket\n socket.emit('code change', value); \n }",
"function runContentScript() {\n const videotags = document.getElementsByTagName(\"video\");\n player = videotags[0]\n\n if (!player) {\n setTimeout(runContentScript, 500);\n return;\n }\n\n for (action in Actions) {\n player.addEventListener(Actions[action], handleLocalAction(Actions[action]));\n }\n\n chrome.runtime.onMessage.addListener(handleBackgroundMessage);\n /* Send message to runtime.onMessage listener in backend.js to connect to room. */\n chrome.runtime.sendMessage({ type: WebpageMessageTypes.CONNECTION });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The timestamp of this data | timestamp() {
return this._d.get("time");
} | [
"get timestamp() {\n if (this._timestamp == null) {\n this._timestamp = new Date(this.ts);\n }\n\n return this._timestamp;\n }",
"function YDataStream_get_startTime()\n {\n return this._timeStamp;\n }",
"function getTimeStamp() {\r\n\treturn extractStamp(new Date());\r\n}",
"get stampTime()\n\t{\n\t\t//dump(\"get stampTime: title:\"+this.title+\", value:\"+this._calEvent.stampTime);\n\t\treturn this._calEvent.stampTime;\n\t}",
"getUpdateTimestamp() {\n if (this.updated_ === null) {\n this.updated_ = new Date(this.json_.updated);\n }\n return this.updated_;\n }",
"timestampAsLocalString() {\n return this.timestamp().toString();\n }",
"toString() {\n return \"Timestamp(seconds=\" + this.seconds + \", nanoseconds=\" + this.nanoseconds + \")\";\n }",
"function YDataStream_get_startTimeUTC()\n {\n if(this._utcStamp == -1) this.loadStream();\n return this._utcStamp;\n }",
"get lastModifiedTime()\n\t{\n\t\t//dump(\"get lastModifiedTime: title:\"+this.title+\", value:\"+this._lastModifiedTime);\n\t\treturn this._lastModifiedTime;\n\t}",
"get dateTimeSent()\n\t{\n\t\treturn this._dateTimeSent;\n\t}",
"function YDataRun_get_startTimeUTC()\n {\n return this._startTimeUTC;\n }",
"function P(t) {\n var e = M(t.mapValue.fields.__local_write_time__.timestampValue);\n return new v(e.seconds, e.nanos);\n }",
"function timestampWithMs() {\n return Date.now() / 1000;\n}",
"get dateTimeCreated()\n\t{\n\t\treturn this._dateTimeCreated;\n\t}",
"getSystemTime () {\n return this._apiRequest('/system/utc_timestamp', 'GET',\n undefined, (res) => { return new Date(res.utc_timestamp * 1000) })\n }",
"async getUpdateTime() {\n const [match] = await this.client('lastUpdate').select('*');\n return match\n ? match.time\n : 0;\n }",
"function toTimeStamp(date) {\n\t\t\ttry {\n\t\t\t\tvar x=\"\";\n\t\t\t\tif(date!=\"\"){\n\t\t\t\t\tx= new Date(date).getTime()/1000;\n\t\t\t\t}\n\n\t\t\t\t// console.log('try'+x +' '+date);\n\t\t\t\treturn x;\n\t\t\t} catch (e) {\n\t\t\t\t// console.log(e);\n\t\t\t\tvar x= new Date().getTime()/1000;\n\t\t\t\t// console.log('catch '+x);\n\t\t\t\treturn x;\n\t\t\t}\n\t\t}",
"get latestDelta() {\n return new Date(this.latestDeltaMs);\n }",
"function extractStamp(date) {\r\n\treturn Math.round(date.getTime() / 1000);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
================================ Takes the thing to append and the location to append the thing to (elem) as parameters Removes hide class from the elem | function showAndDisplay(thing, elem){
$(elem).append(thing).addClass("show", function(){
$(this).removeClass("hide");
});
} | [
"function hideHelper(event, element) {\n element.removeAttribute(\"visible\");\n element.style.visibility = \"hidden\";\n }",
"function makeInvisible(element) {\n\telement.className = \"invisible\";\n}",
"function addWidget(id, x, y, src, hide) {\n var elt = document.createElement(\"img\");\n elt.id = id;\n that.widgets[id] = elt;\n elt.src = src;\n elt.style.cursor = \"pointer\";\n elt.style.position = \"absolute\";\n if(hide) {\n elt.style.visibility = \"hidden\"\n }\n elt.style.zIndex = 2;\n domElement.parentNode.appendChild(elt);\n placeWidget(id, x, y);\n }",
"divHollow(template) {\n const newbie = document.createElement('div');\n $(newbie).html(' ').addClass(this.brickClass[template]);\n newbie.setAttribute('aria-hidden', 'true');\n return newbie;\n }",
"function clone(obj, addInsidePanel, $whereToPut) {\n var $obj = $(obj);\n var $newElement=null;\n \n if ( addInsidePanel ) {\n $newElement=$(\"<div></div>\");\n $newElement.append($(obj.cloneNode(true)));\n } else {\n $newElement=$(obj.cloneNode(true));\n }\n \n $newElement.\n css(\"position\",\"absolute\").\n css(\"top\" ,$obj.offset().top - $obj.scrollTop()).\n css(\"left\" ,$obj.offset().left - $obj.scrollLeft() ).\n css(\"width\" ,$obj.width()).\n css(\"height\",$obj.height());\n\n if ( $whereToPut ) {\n $whereToPut.append($newElement);\n } else if ( $webSiteContainer!=null ) {\n $webSiteContainer.append($newElement);\n }\n\n $obj.hide();\n \n return $newElement;\n }",
"function appendtoCategory($taskElement){\n $(\".message >span\").css('visibility', 'visible');\n const $task = $taskElement;\n $(\".listContainer\").on(\"click\", function(event){\n $.ajax({\n url: \"/tasks/\"+$($task).data('task-id')+\"?_method=PUT\",\n method: \"PUT\",\n data : {id: $($task).data(\"task-id\"), cat_id: $(event.target).siblings().data('id')},\n success: () => {\n $(\".message > span\").css('visibility', 'hidden');\n $(event.target).siblings().prepend($task);\n }\n });\n $(\".listContainer\").unbind();\n });\n }",
"function hideUI() {\n document.getElementById(\"options\").classList.add(\"hidden\");\n document.getElementById(\"fullelement\").classList.add(\"hidden\");\n document.getElementById(\"memorywindow\").classList.add(\"hidden\");\n}",
"function checkForClassForWidgetPlacement (blormWidget) {\n\n // if classForWidgetPlacement has a class then wrap it around\n if (blormapp.postConfig.classForWidgetPlacement !== \"\") {\n\n let classForWidgetPlacement = document.createElement(\"span\");\n classForWidgetPlacement.classList.add(blormapp.postConfig.classForWidgetPlacement);\n classForWidgetPlacement.append(blormWidget);\n\n return classForWidgetPlacement;\n }\n\n // no class no wrapper\n return blormWidget;\n\n}",
"function addFav() {\r\n $(\"#favourites div.Results\").append(\r\n `<div class=\"searchResult\">${$(this).parents(\"div.searchResult\").html()}</div>`\r\n );\r\n $(\"#favourites\").css(\"display\", \"block\");\r\n}",
"function hide_important_elements(){\n\tdocument.getElementById('segment_middle_part').style.display\t= \"none\";\n\tdocument.getElementById('groupe_add_container').style.display\t= \"none\";\n\tdocument.getElementById('segment_send_part').style.display\t= \"none\";\n}",
"function hideAndSetNew(element, index, array){\n\telement.style.display = 'none';\n\tvar parentDiv = element.parentNode;\n\tvar last_input = element.querySelector('.datetime');\n\tvar name_last_input = last_input.getAttribute('name');\n\tvar date_input = name_last_input + '_date';\n\tvar time_input = name_last_input + '_time';\n\tvar last_input_value = last_input.getAttribute('value');\n\tvar last_input_date = last_input_value.split(' ')[0];\n\tvar last_input_time = last_input_value.split(' ')[1];\n\n\tvar display_date = moment(last_input_date, 'DD/MM/YYYY');\n\tvar display_time = moment(last_input_time, 'hh:mm');\n\n\n\tparentDiv.innerHTML += '<div class=\"date-time-picker\">'\n\t\t+ '</div>';\n\n\tparentDiv = parentDiv.querySelector('.date-time-picker');\n\tif(\"date\" in format){\n\t\tvar date_has_input = display_date.format(format.date.input).toString();\n\t\told_date_input = date_has_input;\n\t\tvar date = display_date.format(format.date.display).toString();\n\t\told_date_display = date;\n\t\tparentDiv.innerHTML += '<input autocomplete=\"off\" class=\"date\" id=\"1$$'+date+'\" name=\"'+date_input+'\" value=\"'+date+'\">';\n\t}\n\tif(\"time\" in format){\n\t\tvar time_has_input = display_time.format(format.time.input).toString();\n\t\told_time_input = time_has_input;\n\t\tvar time = display_time.format(format.time.display).toString();\n\t\told_time_input = time;\n\t\tparentDiv.innerHTML += '<input autocomplete=\"off\" class=\"time\" id=\"1$$'+date+'\" name=\"'+time_input+'\" value=\"'+time+'\">';\n\t}\n\n\tif(\"date\" in format){\n\t\tparentDiv.innerHTML += '<div class=\"popup-date-picker\" tabindex=\"-1\" style=\"display:none\">'\n\t\t\t+ '</div>';\n\t}\n\tif(\"time\" in format){\n\t\tparentDiv.innerHTML += '<div class=\"popup-time-picker\" tabindex=\"-1\" style=\"display:none\">'\n\t\t\t+ '</div>';\n\t}\n\n}",
"function displayBeer(beer) {\n console.log(beer);\n $(\".beerList\").hide();\n // Assign beer display stuff\n $('.singleBeer').show();\n}",
"function likedDiv() {\n $(\"#liked-row\").append(\"<div class='col m4 s12 newLiked\" + likeIndex + \" inner grid-item'>\");\n $(\".liked\" + likeIndex).appendTo(\".newLiked\" + likeIndex);\n $(\".card\").removeClass(\"liked\");\n likeIndex++;\n}",
"function addContent() {\n content.style.visibility = \"visible\";\n}",
"hide() {\n\t\tthis.element.style.visibility = 'hidden';\n\t}",
"function toggleDivs(elementToHide, elementToShow)\n{\n elementToHide.style.display = \"none\";\n elementToShow.style.display = \"block\";\n}",
"show() {\n\t\tthis.element.style.visibility = '';\n\t}",
"function hidejshideObject() {\n\tvar jshidevar = getElementsByClass(\"jshide\");\n\t\t\n\tfor ( i=0;i<jshidevar.length;i++ ) {\n\t\tjshidevar[i].style.display = 'none';\n\t}\n}",
"function prepareElementHidden() {\n\n\t var name\n\n\t if ( SETTINGS.hiddenName === true ) {\n\t name = ELEMENT.name\n\t ELEMENT.name = ''\n\t }\n\t else {\n\t name = [\n\t typeof SETTINGS.hiddenPrefix == 'string' ? SETTINGS.hiddenPrefix : '',\n\t typeof SETTINGS.hiddenSuffix == 'string' ? SETTINGS.hiddenSuffix : '_submit'\n\t ]\n\t name = name[0] + ELEMENT.name + name[1]\n\t }\n\n\t P._hidden = $(\n\t '<input ' +\n\t 'type=hidden ' +\n\n\t // Create the name using the original input’s with a prefix and suffix.\n\t 'name=\"' + name + '\"' +\n\n\t // If the element has a value, set the hidden value as well.\n\t (\n\t $ELEMENT.data('value') || ELEMENT.value ?\n\t ' value=\"' + P.get('select', SETTINGS.formatSubmit) + '\"' :\n\t ''\n\t ) +\n\t '>'\n\t )[0]\n\n\t $ELEMENT.\n\n\t // If the value changes, update the hidden input with the correct format.\n\t on('change.' + STATE.id, function() {\n\t P._hidden.value = ELEMENT.value ?\n\t P.get('select', SETTINGS.formatSubmit) :\n\t ''\n\t })\n\n\n\t // Insert the hidden input as specified in the settings.\n\t if ( SETTINGS.container ) $( SETTINGS.container ).append( P._hidden )\n\t else $ELEMENT.after( P._hidden )\n\t }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Main public function that is called to // parse the XML string and return a root element object | function cXparse(src) {
var frag = new _frag();
// remove bad \r characters and the prolog
frag.str = _prolog(src);
// create a root element to contain the document
var root = new _element();
root.name = "ROOT";
// main recursive function to process the xml
frag = _compile(frag);
// all done, lets return the root element + index + document
root.contents = frag.ary;
root.index = _Xparse_index;
_Xparse_index = new Array();
return root;
} | [
"lesx_parseElement() {\n var startPos = this.start,\n startLoc = this.startLoc;\n\n this.next();\n\n return this.lesx_parseElementAt(startPos, startLoc);\n }",
"function ProcessableXML() {\n\n}",
"parseElement() {\n const name = this.tok.take();\n if (!/^[A-Z][a-z]*$/.test(name))\n throw new Error(\"Assertion error\");\n return new ChemElem(name, this.parseOptionalNumber());\n }",
"function StringToXML(txt) {\n\tif (window.DOMParser) {\n\t\t// code for Chrome, Firefox, Opera, etc.\n\t\tparser=new DOMParser();\n\t\txml=parser.parseFromString(txt,\"text/xml\");\n\t} else {\n\t\t// code for IE\n\t\txml=new ActiveXObject(\"Microsoft.XMLDOM\");\n\t\txml.async=false;\n\t\txml.loadXML(txt); \n\t};\n\treturn xml;\n}",
"function parseConfiguration( strFileName )\n{\n var gObjFs = new ActiveXObject(\"Scripting.FileSystemObject\");\n if( !gObjFs.FileExists( strFileName) ) \n throw \"File Name '\" + strFileName + \"' does not exist\";\n\n var xmlTree = new ActiveXObject(\"Microsoft.XMLDOM\");\n xmlTree.async = false;\n if( !xmlTree.load( strFileName) ) \n throw \"Failed to load file as XML.\\n\" \n + xmlTree.parseError.url \n + \":\" \n + xmlTree.parseError.line \n + \" \" \n + xmlTree.parseError.reason;\n\n var xmlRoot = xmlTree.documentElement;\n return xmlRoot;\n}",
"parseXML(rawText) {\n // TODO: different code paths for XLIFF 1.2 vs. 2.0 (this is the only way to support both)\n // Document.init();\n // Working - just return the Document object from this function\n const deferred = $q.defer();\n const self = this;\n\n // <xliff xmlns=\"urn:oasis:names:tc:xliff:document:2.0\" version=\"2.0\"\n\n const xml = parser.parseFromString(rawText, 'text/xml');\n\n // Parsing error?\n const parserError = xml.querySelector('parsererror');\n // if (parserError !== null) {\n if (xml.documentElement.nodeName == 'parsererror') {\n console.log('Error while parsing XLIFF file');\n $log.error('Error while parsing');\n const errorString = new XMLSerializer().serializeToString(parserError);\n $log.error(errorString);\n\n $log.error(new XMLSerializer().serializeToString(xml));\n self.parsingError = true;\n return;\n } else {\n self.parsingError = false;\n }\n\n const Document = {};\n // Set Document DOM to the parsed result\n Document.DOM = xml;\n // Working - the XLIFF parser returns a Document representation of the XLIFF\n Document.segments = [];\n Document.sourceLang = sourceLang;\n Document.targetLang = targetLang;\n\n Document.segmentStates = [];\n\n const file = xml.querySelector('file');\n const xliffTag = xml.querySelector('xliff');\n\n $log.log('xliff version: ');\n $log.log(xliffTag.getAttribute('version'));\n\n // TODO: fork here, depending on xliff version -- we want to support both 2.0 and 1.2 for the time being\n\n // Read the source and target language - set defaults to English and German\n var sourceLang = file.getAttribute('source-language');\n if (!sourceLang) sourceLang = 'en';\n Document.sourceLang = sourceLang;\n\n var targetLang = file.getAttribute('target-language');\n if (!targetLang) targetLang = 'de';\n Document.targetLang = targetLang;\n\n // Working -- segmentation with <seg-source> and <mrk> tags is Optional\n // add support for pure <source> and <target>\n const sourceSegments = this.getTranslatableSegments(xml);\n\n // for every segment, get its matching target mrk, if it exists - note: it may not exist\n const targetSegments = _.map(sourceSegments,\n (seg) => {\n if (seg.nodeName === 'mrk') {\n return self.getMrkTarget(xml, seg);\n }\n // there's no mrks inside <target>, just a <target> -- TODO: do we require target nodes to exist?\n return seg.parentNode.querySelector('target');\n },\n );\n\n // we can assume that translators will want to translate every segment, so there should be at least an\n // empty target node corresponding to each source node\n const sourceWithTarget = _.zip(sourceSegments, targetSegments);\n _.each(sourceWithTarget,\n (seg) => {\n const sourceText = seg[0].textContent;\n const targetText = seg[1] ? seg[1].textContent : '';\n if (!seg[1]) {\n const mid = seg[0].getAttribute('mid');\n $log.info('Target segment missing: ' + mid);\n seg[1] = self.createNewMrkTarget(Document.DOM, seg[0], '', targetLang);\n }\n\n const segPair = {\n source: seg[0].textContent,\n target: seg[1].textContent,\n sourceDOM: seg[0],\n targetDOM: seg[1],\n // TODO: the segment state should be taken from the XLIFF see XliffTwoParser\n state: 'initial',\n };\n\n // Add the pairs so we can access both sides from a single ngRepeat\n Document.segments.push(segPair);\n\n // TODO: make this useful\n // Document.translatableNodes.push(seg);\n });\n\n // TODO: remove the document-loaded event, and use the result of the resolved promise directly\n // tell the world that the document loaded\n $log.log('Xliff parser returning');\n // $log.log(Document);\n deferred.resolve(Document);\n\n // return Document;\n return deferred.promise;\n }",
"function _generalParse(xml) {\n\t\tvar x2js = new X2JS();\n\t\tvar afterCnv = x2js.xml_str2json(xml);\n\t\tconsole.log(afterCnv);\n\t\treturn afterCnv;\n\t}",
"function parseXML(){\n var xmlhttp = new XMLHttpRequest();\n xmlhttp.open(\"GET\", \"http://quotes.rest/qod.xml\" ,true);\n xmlhttp.send();\n xmlhttp.onreadystatechange = function() {\n if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {\n var xmlDoc = xmlhttp.responseXML;\n var x = document.getElementsByTagName(\"td\");\n\n var quotes = xmlDoc.getElementsByTagName(\"quote\");\n var firstQuote = quotes[0];\n var quoteText = firstQuote.innerHTML; \n x[2].innerHTML = quoteText;\n\n var authors = xmlDoc.getElementsByTagName(\"author\");\n var firstAuthor = authors[0];\n var authorText = firstAuthor.innerHTML; \n x[3].innerHTML = authorText;\n\n }\n }\n}",
"function getXMLDocument(){\n var xDoc=null;\n\n if( document.implementation && document.implementation.createDocument ){\n xDoc=document.implementation.createDocument(\"\",\"\",null);//Mozilla/Safari \n }else if (typeof ActiveXObject != \"undefined\"){\n var msXmlAx=null;\n try{\n msXmlAx=new ActiveXObject(\"Msxml2.DOMDocument\");//New IE\n }catch (e){\n msXmlAx=new ActiveXObject(\"Msxml.DOMDocument\"); //Older Internet Explorer \n }\n xDoc=msXmlAx;\n }\n if (xDoc==null || typeof xDoc.load==\"undefined\"){\n xDoc=null;\n }\n return xDoc;\n}",
"function createXMLConciliacion( root, params )\n{\n\t var nodes;\n\t var xml = \"\";\n\t if( root )\n\t xml += \"<\" + root + \">\";\n\t for(var i=0; i<params.length; i++)\n\t {\n\t\t nodes=params[i];\n\t\t xml += \"<element>\";\n\t\t for( theNode in nodes )\n\t\t {\n\t\t xml += \"<\" + theNode + \">\" + nodes[theNode] + \"</\" + theNode + \">\";\n\t\t }\t\n\t\t xml += \"</element>\";\n\t } \n\t xml += \"</\" + root + \">\";\n\t \n\t return xml;\n\t}",
"function decompressXML(xml) {\n\n var resultXml = \"\";\n\n // Compressed XML file/bytes starts with 24x bytes of data,\n // 9 32 bit words in little endian order (LSB first):\n // 0th word is 03 00 08 00\n // 3rd word SEEMS TO BE: Offset at then of StringTable\n // 4th word is: Number of strings in string table\n // WARNING: Sometime I indiscriminently display or refer to word in\n // little endian storage format, or in integer format (ie MSB first).\n var numbStrings = LEW(xml, 4*4);\n\n // StringIndexTable starts at offset 24x, an array of 32 bit LE offsets\n // of the length/string data in the StringTable.\n var sitOff = 0x24|0; // Offset of start of StringIndexTable\n\n // StringTable, each string is represented with a 16 bit little endian\n // character count, followed by that number of 16 bit (LE) (Unicode) chars.\n var stOff = sitOff + numbStrings*4; // StringTable follows StrIndexTable\n\n // XMLTags, The XML tag tree starts after some unknown content after the\n // StringTable. There is some unknown data after the StringTable, scan\n // forward from this point to the flag for the start of an XML start tag.\n var xmlTagOff = LEW(xml, 3*4); // Start from the offset in the 3rd word.\n // Scan forward until we find the bytes: 0x02011000(x00100102 in normal int)\n for (var ii=xmlTagOff; ii<xml.length-4; ii+=4) {\n if (LEW(xml, ii) === startTag) {\n xmlTagOff = ii; break;\n }\n } // end of hack, scanning for start of first start tag\n\n // XML tags and attributes:\n // Every XML start and end tag consists of 6 32 bit words:\n // 0th word: 02011000 for startTag and 03011000 for endTag\n // 1st word: a flag?, like 38000000\n // 2nd word: Line of where this tag appeared in the original source file\n // 3rd word: FFFFFFFF ??\n // 4th word: StringIndex of NameSpace name, or FFFFFFFF for default NS\n // 5th word: StringIndex of Element Name\n // (Note: 01011000 in 0th word means end of XML document, endDocTag)\n\n // Start tags (not end tags) contain 3 more words:\n // 6th word: 14001400 meaning??\n // 7th word: Number of Attributes that follow this tag(follow word 8th)\n // 8th word: 00000000 meaning??\n\n // Attributes consist of 5 words:\n // 0th word: StringIndex of Attribute Name's Namespace, or FFFFFFFF\n // 1st word: StringIndex of Attribute Name\n // 2nd word: StringIndex of Attribute Value, or FFFFFFF if ResourceId used\n // 3rd word: Flags?\n // 4th word: str ind of attr value again, or ResourceId of value\n\n // TMP, dump string table to tr for debugging\n //tr.addSelect(\"strings\", null);\n //for (int ii=0; ii<numbStrings; ii++) {\n // // Length of string starts at StringTable plus offset in StrIndTable\n // String str = compXmlString(xml, sitOff, stOff, ii);\n // tr.add(String.valueOf(ii), str);\n //}\n //tr.parent();\n\n // Step through the XML tree element tags and attributes\n var off = xmlTagOff;\n var indent = 0;\n var startTagLineNo = -2;\n while (off < xml.length) {\n var tag0 = LEW(xml, off);\n //int tag1 = LEW(xml, off+1*4);\n var lineNo = LEW(xml, off+2*4);\n //int tag3 = LEW(xml, off+3*4);\n var nameNsSi = LEW(xml, off+4*4);\n var nameSi = LEW(xml, off+5*4);\n\n if (tag0 === startTag) { // XML START TAG\n var tag6 = LEW(xml, off+6*4); // Expected to be 14001400\n var numbAttrs = LEW(xml, off+7*4); // Number of Attributes to follow\n //int tag8 = LEW(xml, off+8*4); // Expected to be 00000000\n off += 9*4; // Skip over 6+3 words of startTag data\n var name = compXmlString(xml, sitOff, stOff, nameSi);\n //tr.addSelect(name, null);\n startTagLineNo = lineNo;\n\n // Look for the Attributes\n var sb = \"\";\n for (var ii=0; ii<numbAttrs; ii++) {\n var attrNameNsSi = LEW(xml, off); // AttrName Namespace Str Ind, or FFFFFFFF\n var attrNameSi = LEW(xml, off+1*4); // AttrName String Index\n var attrValueSi = LEW(xml, off+2*4); // AttrValue Str Ind, or FFFFFFFF\n var attrFlags = LEW(xml, off+3*4);\n var attrResId = LEW(xml, off+4*4); // AttrValue ResourceId or dup AttrValue StrInd\n off += 5*4; // Skip over the 5 words of an attribute\n\n var attrName = compXmlString(xml, sitOff, stOff, attrNameSi);\n var attrValue = attrValueSi!==-1\n ? compXmlString(xml, sitOff, stOff, attrValueSi)\n : \"resourceID 0x\"+ (attrResId>>>0).toString(16);\n sb += \" \"+attrName+\"=\\\"\"+attrValue+\"\\\"\";\n //tr.add(attrName, attrValue);\n }\n resultXml += prtIndent(indent, \"<\"+name+sb+\">\");\n indent++;\n\n } else if (tag0 === endTag) { // XML END TAG\n indent--;\n off += 6*4; // Skip over 6 words of endTag data\n var name = compXmlString(xml, sitOff, stOff, nameSi);\n resultXml += prtIndent(indent, \"</\"+name+\"> (line \"+startTagLineNo+\"-\"+lineNo+\")\");\n //tr.parent(); // Step back up the NobTree\n\n } else if (tag0 === endDocTag) { // END OF XML DOC TAG\n break;\n\n } else {\n Activity.reportError(\"decompressXML::\" + \" Unrecognized tag code '\"+tag0.toString(16)\n +\"' at offset \"+off);\n break;\n }\n } // end of while loop scanning tags and attributes of XML tree\n Activity.reportError(\"decompressXML::\" + \" end at offset \"+off);\n\n return resultXml;\n }",
"parse_start(text,context){\n\t\tfor(const parser of this.start_parsers){\n\t\t\tconst res=parser.call(this,text,context);\n\t\t\tif(res){\n\t\t\t\treturn res;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn null;\n\t}",
"function initialXML(){\n\n\tvar dialogXML = \"\";\n\tdialogXML += \tinitialTitle();\n\tdialogXML += \t'<vbox>';\n dialogXML += \t\tinitialLabel();\n dialogXML += \t\t'<label control=\"choosePostfix\" value=\"Choose a suffix to append:\"/> ';\n dialogXML += \t\t'<textbox id=\"postfix\" value=\"_ft\" width=\"50\"/> ' ;\n dialogXML += \t'</vbox>';\n\tdialogXML += '</dialog>';\n\t\n\tvar xmlPanelOutput = displayXML(dialogXML);\n\treturn xmlPanelOutput;\n}",
"function xmlStringFromDocDom(oDocDom, encodeSingleSpaceTextNodes) {\n\tvar xmlString = new String();\n\n\t// if the node is an element node\n\tif (oDocDom.nodeType == 1 && oDocDom.nodeName.slice(0,1) != \"/\") {\n\t\t// define the beginning of the root element and that element's name\n\t\txmlString = \"<\" + oDocDom.nodeName.toLowerCase();\n\n\t\t// loop through all qualified attributes and enter them into the root element\n\t\tfor (var x = 0; x < oDocDom.attributes.length; x++) {\n\t\t\tif (oDocDom.attributes[x].specified == true || oDocDom.attributes[x].name == \"value\") {\t// IE wrongly puts unspecified attributes in here\n\t\t\t\t//if (oDocDom.attributes[x].name == \"class\") {\n\t\t\t\t//\txmlString += ' class=\"' + oNode.attributes[x].value + '\"';\n\t\t\t\t//} else {\n\n\t\t\t\t// If this is not an input, then add the attribute is \"input\", then skip this.\n\t\t\t\tif (oDocDom.nodeName.toLowerCase() != \"input\" && oDocDom.attributes[x].name == \"value\" && oDocDom.attributes[x].specified == false) {\n\n\t\t\t\t// If this is an img element.\n\t\t\t\t} else if (oDocDom.nodeName.toLowerCase() == \"img\" && oDocDom.attributes[x].name == \"width\" ||\n\t\t\t\t\toDocDom.nodeName.toLowerCase() == \"img\" && oDocDom.attributes[x].name == \"height\") {\n\n\t\t\t\t} else {\n\n\t\t\t\t\txmlString += ' ' + oDocDom.attributes[x].name + '=\"' + oDocDom.attributes[x].value + '\"';\n\t\t\t\t}\n\t\t\t\t//}\n\t\t\t}\n\t\t}\n\n\t\t// if the xml object doesn't have children, then represent it as a closed tag\n//\t\tif (oDocDom.childNodes.length == 0) {\n//\t\t\txmlString += \"/>\"\n\n//\t\t} else {\n\n\t\t// if it does have children, then close the root tag\n\t\txmlString += \">\";\n\t\t// then peel through the children and apply recursively\n\t\tfor (var i = 0; i < oDocDom.childNodes.length; i++) {\n\t\t\txmlString += xmlStringFromDocDom(oDocDom.childNodes.item(i), encodeSingleSpaceTextNodes);\n\t\t}\n\t\t// add the final closing tag\n\t\txmlString += \"</\" + oDocDom.nodeName.toLowerCase() + \">\";\n//\t\t}\n\n\t\treturn xmlString;\n\n\t} else if (oDocDom.nodeType == 3) {\n\t\t// return the text node value\n\t\tif (oDocDom.nodeValue == \" \" && encodeSingleSpaceTextNodes == true) {\n\t\t\treturn \"#160;\";\n\t\t} else {\n\t\t\treturn oDocDom.nodeValue;\n\t\t}\n\t} else {\n\t\treturn \"\";\n\t}\n}",
"function handleRootElement(root, obj, attr){\r\n //name attribute should always be present for root element\r\n\r\n var ele = {};\r\n if(obj.attributes.name){\r\n ele['name']= obj.attributes.name;\r\n }\r\n //specified the name of built-in type / simpleType / complexType\r\n if(obj.attributes.type){\r\n ele['type']= obj.attributes.type;\r\n }\r\n\r\n //substitutionGroup specifies the name of an element that can be substituted with this element. Will be present for only root element.\r\n if(obj.attributes.substitutionGroup){\r\n ele['substitution']=obj.attributes.substitutionGroup;\r\n }\r\n\r\n //parse built-in types\r\n for(var i in obj.child){\r\n var node = obj.child[i];\r\n //annotation will have the documentation for this element\r\n if(node.name=='xs:annotation'){\r\n handleAnnotation(root, node, ele);\r\n }else if(node.name=='xs:simpleType'){\r\n //for restriction / list / union of simpleType, the name of referred type is in base attribute\r\n if(node.child[0].name=='xs:restriction' || node.child[0].name=='xs:list' || node.child[0].name=='xs:union'){\r\n ele['type']=node.child[0].attributes.base;\r\n }\r\n }else if(node.name=='xs:complexType'){\r\n //parse built-in complexType, and add the complexType parsed to the complexTypeList\r\n var childattr = [];\r\n var childblock = {};\r\n\r\n handleComplexType(root, node, childattr);\r\n\r\n findNamespace(root[0].attributes, childblock);\r\n childblock['attributes']=childattr;\r\n\r\n ComplexTypeList[obj.attributes.name]=childblock;\r\n //link the parsed complexType in current complexType\r\n ele['name']=obj.attributes.name;\r\n ele['type']=obj.attributes.name;\r\n\r\n }else if(node.name=='xs:unique'){\r\n // handle element unique\r\n }else if(node.name=='xs:key'){\r\n // handle element key\r\n }else if(node.name=='xs:keyref'){\r\n // handle element keyref\r\n }\r\n }\r\n attr.push(ele);\r\n}",
"function _processOutputXMLFile() {\n\n // Check if output.xml file exists\n if (fs.existsSync(outputXMLPath)) {\n // Process contents\n RF_DEBUG && console.log('[rsbatech:robotframework] Starting to parse output.xml file located at:'+outputXMLPath);\n\n var stream = fs.createReadStream(outputXMLPath),\n xml = new XmlStream(stream),\n suites = {};\n\n xml.on('startElement: suite', Meteor.bindEnvironment( function processSuite(suiteNode) {\n if (suiteNode.$.id) { // Exclude <suite> node in <statistics> sections\n suites[suiteNode.$.id] = suiteNode.$.name;\n }\n }));\n\n xml.collect('kw'); // Store individual keywords in an array\n xml.collect('arg'); // Store individual keyword arguments in an array\n xml.on('updateElement: test', Meteor.bindEnvironment( function processTestElement(testNode) {\n\n var report = {\n id: testNode.$.id,\n name: testNode.$.name,\n framework: FRAMEWORK_NAME,\n result: (testNode.status && testNode.status.$.status === 'PASS') ? 'passed' : 'failed',\n duration: _calculateTestDuration(testNode.status.$.starttime, testNode.status.$.endtime),\n timestamp: moment(testNode.status.$.starttime, 'YYYYMMDD HH:mm:ss.SSS').toDate()\n };\n\n report.ancestors = _calculateTestAncestors(testNode.$.id, suites);\n\n // If test failed, provide more information on what went wrong\n if (report.result === 'failed') {\n report.failureType = 'AssertionError';\n\n // Find keyword that failed\n _.each(testNode.kw, Meteor.bindEnvironment(function(element) {\n var args = '';\n if (element.status && element.status.$.status === 'FAIL') {\n\n // List keyword arguments, if any\n if (element.arguments && element.arguments.arg) {\n for (var i = 0; i < element.arguments.arg.length; i++ ) {\n args = args.concat(' ', element.arguments.arg[i]);\n }\n }\n\n report.failureMessage = 'Keyword: ' + element.$.name + args + '\\n ';\n }\n }));\n\n report.failureMessage = report.failureMessage || '';\n report.failureMessage = report.failureMessage.concat('>>>', testNode.status.$text);\n }\n\n // Submit test results report to Velocity\n Meteor.call('velocity/reports/submit', report);\n\n }));\n\n // report test ERRORs\n xml.on('updateElement: errors msg', Meteor.bindEnvironment(function processErrors(msgNode) {\n RF_DEBUG && console.log('ERROR msg text:' + msgNode.$text);\n var options = {\n framework: FRAMEWORK_NAME,\n message: msgNode.$text\n };\n if (msgNode.$.level) {\n options.level = msgNode.$.level;\n }\n if (msgNode.$.timestamp) {\n options.timestamp = moment(msgNode.$.timestamp, 'YYYYMMDD HH:mm:ss.SSS').toDate();\n }\n\n Meteor.call('velocity/logs/submit', options);\n }));\n\n xml.on('end', Meteor.bindEnvironment(function end() {\n RF_DEBUG && console.log('[rsbatech:robotframework] Completed parsing output.xml file');\n }));\n \n } else {\n console.log('[rsbatech:robotframework] ERROR: output.xml file missing at:'+outputXMLPath);\n \n }\n }",
"function getLatLngFromXML(xml, maps) {\n console.log(xml);\n var latBegin = xml.indexOf('<lat>');\n var latEnd = xml.indexOf('</lat>');\n var lat = xml.substring(latBegin + 5, latEnd);\n var lngBegin = xml.indexOf('<lng>');\n var lngEnd = xml.indexOf('</lng>');\n var lng = xml.substring(lngBegin + 5, lngEnd);\n console.log('lat: ', lat);\n console.log('lng: ', lng);\n return new maps.LatLng(lat, lng);\n }",
"function loadXMLDoc(url, element_id)\r\n{\r\nif (url !=\"\")\r\n{\r\nvar xhttp;\r\nif (window.XMLHttpRequest)\r\n {\r\n xhttp=new XMLHttpRequest();\r\n }\r\nelse\r\n {\r\n xhttp=new ActiveXObject(\"Microsoft.XMLHTTP\");\r\n }\r\nxhttp.open(\"GET\",url,false);\r\nxhttp.send();\r\ndocument.getElementById(element_id).innerHTML=xhttp.responseText;\r\n} else {\r\ndocument.getElementById(element_id).innerHTML=\"\";\r\n}\r\n}",
"function WordParser () {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function: validateData Check the data to geocode | function validateData() {
hideGeoportalView();
var geocoder= viewer.getVariable('geocoder');
geocoder.checkData();
} | [
"function hasValidPoint(data) {\n return (typeof data.latitude != \"undefined\" && data.longitude != \"undefined\" && data.latitude != null && data.longitude != null && !isNaN(data.latitude) && !isNaN(data.longitude));\n }",
"function validateAddress() {\n return checkPersonalInfo(\"address\", \"Address must have at least 3 characters\");\n}",
"validateInput(data, callback) {\n const value = this.getInputFromData(data);\n const result = value === undefined\n || value === null\n || typeof value === 'string'\n || (typeof value === 'object' && (typeof value.first === 'string'\n || value.first === null\n || typeof value.last === 'string'\n || value.last === null));\n utils.defer(callback, result);\n }",
"function validate(event) {\n // const needsLatAndLng = true;\n // if (needsLatAndLng) {\n // event.preventDefault()\n // alert('Selecione um ponto no mapa')\n // }\n\n // const validLat = document.querySelector('[name=\"lat\"]')\n // const validLng = document.querySelector('[name=\"lng\"]')\n // if (validLat.value && validLng.value == \"\") {\n // event.preventDefault()\n // alert('Selecione um ponto no mapa')\n // }\n}",
"function verifyTeleportDataNotEmpty(data) {\n return !jQuery.isEmptyObject(data._embedded[`city:search-results`]);\n }",
"function is_valid_latlng(address) {\n return address.match(/^([-+]?[1-8]?\\d(\\.\\d+)?|90(\\.0+)?),?\\s*([-+]?180(\\.0+)?|[-+]?((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)(,\\d+z)?$/);\n }",
"function validateBeforeReview() {\n if (!ctl.user.tempLocation.feature) { // If address fails to validate\n ctl.addressErrorMsg = 'No coordinates found for this address. Please choose a different address.';\n ctl.profile.$setValidity('locationsProfile.user.tempLocation.address', false);\n } else { // If we have both a label and an address\n var geom = ctl.user.tempLocation.feature.geometry;\n var xyString = geom.x.toString() + ',' + geom.y.toString(); // Cast to string\n ctl.user.save();\n $state.go('locationsReview', { destination: xyString }); // Use as url params\n }\n }",
"validate(invalidProperties)\n\t{\n\t\tif(typeof this.addressLine1 === \"string\" && this.addressLine1.length > 0 && this.addressLine1.length < 35)\n\t\t{\n\t\t\tdelete invalidProperties.addressLine1;\n\t\t}\n\t\tif(typeof this.addressLine2 === \"string\" && this.addressLine2.length < 35)\n\t\t{\n\t\t\tdelete invalidProperties.addressLine2;\n\t\t}\n\t\tif(typeof this.addressLine3 === \"string\" && this.addressLine3.length < 35)\n\t\t{\n\t\t\tdelete invalidProperties.addressLine3;\n\t\t}\n\t\tif(typeof this.city === \"string\" && this.city.length > 0 && this.city.length < 35)\n\t\t{\n\t\t\tdelete invalidProperties.city;\n\t\t}\n\t\t//TODO: Check to see if countryData has a list of provinces or not, if it doesn't, this is theoretically valid\n\t\tif(countryData.data[this.country] && typeof this.stateProvince === \"string\" && this.stateProvince.length < 35)\n\t\t{\n\n\t\t\tif(Object.keys(countryData.data[this.country].subdivisions).length === 0)\n\t\t\t{\n\t\t\t\tdelete invalidProperties.stateProvince;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t//TODO: FIX This hack before deploying to production.\n\t\t\t\tvar valid = false;\n\t\t\t\tObject.keys(countryData.data[this.country].subdivisions).forEach(subdiv => {\n\t\t\t\t\tif(this.stateProvince === subdiv || this.stateProvince === subdiv.split('-')[1])\n\t\t\t\t\t{\n\t\t\t\t\t\tvalid = true;\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tif(valid === true)\n\t\t\t\t{\n\t\t\t\t\tdelete invalidProperties.stateProvince;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(typeof this.country === \"string\" && this.country.length > 0 && this.country.length <= 3)\n\t\t{\n\t\t\tdelete invalidProperties.country;\n\t\t}\n\t\tif(this.country === \"CAN\" && typeof this.zipPostalCode === \"string\")\n\t\t{\n\t\t\tif(this.zipPostalCode[3] !== \" \")\n\t\t\t{\n\t\t\t\tthis.zipPostalCode = this.zipPostalCode.slice(0,3).toUpperCase()+\" \"+this.zipPostalCode.slice(3,6).toUpperCase();\n\t\t\t}\n\n\t\t\tif(/^[ABCEGHJKLMNPRSTVXY]\\d[ABCEGHJKLMNPRSTVWXYZ]( )?\\d[ABCEGHJKLMNPRSTVWXYZ]\\d$/i.test(this.zipPostalCode) === true)\n\t\t\t{\n\t\t\t\tthis.zipPostalCode = this.zipPostalCode.toUpperCase();\n\t\t\t\tdelete invalidProperties.zipPostalCode;\n\t\t\t}\n\t\t}\n\t\telse if(this.country === \"USA\" && typeof this.zipPostalCode === \"string\")\n\t\t{\n\t\t\tif(/^[0-9]{5}(?:-[0-9]{4})?$/.test(this.zipPostalCode) === true)\n\t\t\t{\n\t\t\t\tdelete invalidProperties.zipPostalCode;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(typeof this.zipPostalCode === \"string\" && this.zipPostalCode.length < 35)\n\t\t\t{\n\t\t\t\tdelete invalidProperties.zipPostalCode;\n\t\t\t}\n\t\t}\n\t}",
"function validate_coords(target) {\n target = target.trim().replace(/,/g, '').replace(/\\s/g, '').replace(/\\.\\./, '-');\n var chr = target.split(\":\")[0].trim();\n var end = target.split(\"-\")[1].trim();\n var valid_chrs = $scope.genomes[$scope.data.organism]['labels'];\n var errors = [];\n var open_p = \"<p>\";\n var close_p = \"</p>\";\n\n //check if the chr name is valid in the context of the selected ref/organism:\n if(valid_chrs.indexOf(chr) == -1) {\n msg = 'You have entered a chromosome name \"'+chr+'\" which is not valid in the context of the selected Reference.\\n \\\n The list of valid chr names is: ' + valid_chrs.toString();\n errors.push(open_p + msg + close_p);\n } else if(end > $scope.genomes[$scope.data.organism][chr]){ //check if the end coord is greater than the length of the chromosome:\n msg = 'You have entered an \"end\" coordinate ' + $filter(\"number\")(end) +' which exceeds the length of ' + chr + '. \\\n The length of ' + chr + ' is '+ $filter(\"number\")($scope.genomes[$scope.data.organism][chr]) + '.';\n errors.push(open_p + msg + close_p);\n } \n\n if (errors.length) {\n $scope.data.error = errors.join('');\n return false;\n } else {\n\t return target; \n } \n }",
"function validateCity() {\n return checkPersonalInfo(\"city\", \"City name must have at least 3 characters\");\n}",
"function isValidLatLng(latLngAddress){\n if(latLngAddress.length!==2){\n return false;\n }\n const lat = latLngAddress[0];\n const lng = latLngAddress[1];\n const isLatitudeValid = isFinite(lat) && Math.abs(lat) <= 90;\n const isLongitudeValid = isFinite(lng) && Math.abs(lat) <= 180;\n return isLatitudeValid && isLongitudeValid;\n }",
"function areaCodeFilter(Jobject) {\n for (var i = 0; i < geocodeData.length; i++) {\n if (Jobject.zipcode == geocodeData[i].postalCode) {\n return true;\n }\n }\n return false;\n }",
"function validateAddress() {\r\n var addressInput = $('#register-address');\r\n var addressInputValue = addressInput.val();\r\n var addressRegex = /^\\d+\\s([A-Z]?[a-z]+\\s){2}\\d{5}\\s[A-Z]?[a-z]+$/;\r\n\r\n if (addressInputValue.match(addressRegex)) {\r\n validInput(addressInput);\r\n } else {\r\n invalidInput(addressInput, $mustBeAnAddress)\r\n }\r\n}",
"function checkLocation(){\r\n\tif (guylocation.value == null || guylocation.value == \"\"){\r\n\t\temptyFieldsArray.push(\" Location\");\r\n\t\tborderRed(guylocation);\r\n\t\treturn true;\r\n\t}\r\n\telse{\r\n\t\treturn false;\r\n\t}\r\n}",
"function validateJointPhoneNumberField (field) {\n \n // Strip non-numeric characters from the field's value\n value = field.val().replace(/\\D/g,'');\n if ( ! isDefined(value) ) return false;\n \n // Create a variable to store the index of the character after the country code\n var slicePosition = 0;\n debugLog(\"hello\");\n \n // Loop through our country codes and see if our value begins with one of them\n for ( var i in countryDataJSON.countries ) {\n var currentCountryCode = countryDataJSON.countries[i]['phoneCode'];\n if ( value.charAt(0) == currentCountryCode )\n slicePosition = 1;\n else if ( value.slice(0,2) == currentCountryCode )\n slicePosition = 2;\n else if ( value.slice(0,3) == currentCountryCode )\n slicePosition = 3;\n }\n \n // If the splice position is still zero, our value doesn't begin with a country code and is therefore invalid\n if ( slicePosition == 0 ) {\n field.val(\"+ \" + value);\n return false;\n \n // If the splice position was set, we found our country code!\n } else {\n var countryCode = value.slice(0, slicePosition);\n var phoneNumber = value.slice(slicePosition);\n \n // Format the field appropriately\n \n if ( phoneNumber.length >= 7 )\n phoneNumber = [phoneNumber.slice(0, 3), \"-\", phoneNumber.slice(3,6), \"-\", phoneNumber.slice(6)].join('');\n else if ( phoneNumber.length > 3 && phoneNumber.length < 7 )\n phoneNumber = [phoneNumber.slice(0, 3), \"-\", phoneNumber.slice(3)].join('');\n \n if ( phoneNumber.length > 0 )\n field.val(\"+ \" + [countryCode, \"-\", phoneNumber].join('') );\n else\n field.val(\"+ \" + countryCode );\n \n // If the phone number portion is longer than five digits,the field is valid\n if ( phoneNumber.replace(/\\D/g,'').length > 5 )\n return true;\n else\n return false;\n } \n}",
"function hasAddressVal(addressTable) {\n for(var i = 0; i < 4; i++) {\n if(!addressTable[i]) {\n ui.alert(\"You must select a location before I can get your values.\");\n return false;\n } \n }\n return true;\n}",
"function checkValid() {\n\tif(!document.getElementById(\"email\").value.match(/\\S+@\\S+\\.\\S+/)){\n\t\tif (document.getElementById(\"email\").value != \"\") {\n\t\t\talert(\"Email Format is wrong!\")\n\t\t\treturn false;\n\t\t} \n\t}\n\tif (!document.getElementById(\"phone_number\").value.match(\"^\\\\d{3}-\\\\d{3}-\\\\d{4}$\")) {\n\t\tif (document.getElementById(\"phone_number\").value != \"\") {\n\t\t\talert(\"Phone Format is wrong!\")\n\t\t\treturn false;\n\t\t}\n\t}\n\tif (!document.getElementById(\"zipcode\").value.match(\"^\\\\d{5}$\")) {\n\t\tif (document.getElementById(\"zipcode\").value != \"\") {\n\t\t\talert(\"Zipcode Format is wrong!\")\n\t\t\treturn false;\n\t\t}\n\t}\n\tvar password = document.getElementById(\"password\")\n\tvar password2 = document.getElementById(\"password2\")\n\tif (password.value == \"\" && password2.value != \"\") {\n\t\talert(\"Password is empty !\")\n\t\treturn false;\n\t} else if (password2.value == \"\" && password.value != \"\"){\n\t\talert(\"Confirmation Password is empty !\")\n\t\treturn false;\n\t}\n\treturn true;\n}",
"function validate(){\n\tvar total = 0;\n\tvar raceName = document.getElementById(\"raceName_text\");\n\tvar date = document.getElementById(\"date\");\n\tvar time = document.getElementById(\"time\");\n\tvar raceNameError = document.getElementById(\"raceNameError\");\n\tvar friendsError = document.getElementById(\"friendsError\");\n\tvar dateTimeError = document.getElementById(\"dateTimeError\");\n\tvar mapError = document.getElementById(\"mapError\");\n\t\n\tif(raceName.value.length > 0){\n\t\ttotal++;\n\t\traceNameError.innerHTML = \"\";\n\t}else\n\t\traceNameError.innerHTML = \"Missing race name\";\n\t\t\n\tif(userArray.length > 0){\n\t\ttotal++;\n\t\tfriendsError.innerHTML = \"\";\n\t}else\n\t\tfriendsError.innerHTML = \"At least add 1 racer\";\n\t\t\n\tif(date.value.length > 4){\n\t\ttotal++;\n\t\tdateTimeError.innerHTML = \"\";\n\t}else\n\t\tdateTimeError.innerHTML = \"Missing date or time\";\n\t\t\n\tif(time.value.length > 4){\n\t\ttotal++;\n\t\tdateTimeError.innerHTML = \"\";\n\t}else\n\t\tdateTimeError.innerHTML = \"Missing date or time\";\n\t\t\n\tfor(var i=0; i<im.getSize(); i++){\n\t\tif(im.getElementAt(i).type == 1){\n\t\t\ttotal++;\n\t\t\tmapError.innerHTML = \"\";\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tif(im.getSize() == 0)\n\t\tmapError.innerHTML = \"Add at least a final destination\";\n\t\n\tif(total == 5)\n\t\tcreateJSON();\n}",
"function checkCity(lat, lng) {\n if (lat.toFixed(3) >= 50.000 && lat.toFixed(3) <= 52.000) {\n if (lng.toFixed(3) >= 5.000 && lng.toFixed(3) <= 7.000) {\n inCity = true;\n $('#content_overzicht').empty();\n getWeetjes();\n getKoepons();\n } else {\n if (inCity) {\n notInCity(1);\n }\n else {\n notInCity(0);\n }\n }\n } else {\n if (inCity) {\n notInCity(1);\n }\n else {\n notInCity(0);\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Logs one row of log data. | async log(logRow) {
const client = await this.queue.client;
const logsKey = this.toKey(this.id) + ':logs';
return client.rpush(logsKey, logRow);
} | [
"function writeLog(message, rowNumber)\n{\n Logger.log( \"Row: \" + rowNumber + \" : \" + message);\n}",
"_log() {\n let args = Array.prototype.slice.call(arguments, 0);\n\n if (!args.length) {\n return;\n }\n\n if (args.length > 1)\n this.emit('log', args.join(', '));\n else\n this.emit('log', args[0]);\n }",
"function appendToLogs(new_rows)\n{\n var row_per_page = getRowPerPage();\n\n window.logs = window.logs.concat(new_rows);\n\n if(window.logs.length > row_per_page)\n\twindow.logs = window.logs.slice(Math.min(window.logs.length-row_per_page, window.logs.length-new_rows.length));\n\n if (new_rows.length)\n\tupdateLastLogID(new_rows[new_rows.length-1][\"log_id\"]);\n\n window.new_rows_count = new_rows.length;\n}",
"function logArray(array) {\n\t\tfor (let i = 0; i < array.length; i++) {\n\t\t\tconsole.log(\"row \" + i);\n\t\t\tfor (let j = 0; j < array[i].length; j++) {\n\t\t\t\tconsole.log(array[i][j]);\n\t\t\t}\n\t\t}\n\t}",
"function log(log){\n console.log(log);\n logbook.push(new Date(Date.now()).toLocaleString() + \":\" + log);\n if(log_channel != null){\n log_channel.send(\"`\"+log+\"`\");\n }\n}",
"function logActivity(summary) {\n\n // concatenate data into var\n log = '\\n\\nAction chosen: ' + action + ', query: ' + queryLog + '\\n' + summary;\n\n // append log data to log.txt\n fs.appendFile('log.txt', log, function () {});\n}",
"function logEvent(data) {\n winston.log('info', data);\n}",
"function writeIt() {\n if (index < LOG.length) {\n fs.appendFile('log.txt', LOG[index++] + \"\\n\", writeIt);\n }\n }",
"log (msg) {\n if (msg === undefined) return this._log.join('\\n')\n if (this._keepLog) this._log.push(msg)\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}",
"function logStatus() {\n if (logging) {\n console.log(\"Elevator \" + index + \" | Queue: \" + floorButtonsQueue + \" | Current Floor: \" + elevator.currentFloor() + \" | Direction: \" + elevator.travelDirection + \" | Current Load: \" + elevator.loadFactor() + \" | Capacity: \" + elevator.maxPassengerCount());\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 }",
"logAPI(apiName, uniqueID){\n logger.Logger.log('API Entry','Entry raised for transaction ID ' + uniqueID + ' from ' + apiName, '' ,5,false);\n }",
"log(_a) {\n var { severity, message } = _a,\n data = __rest(_a, ['severity', 'message']);\n if (!severity) severity = 'INFO';\n this.write(Object.assign({ message }, data), 'INFO');\n }",
"function logAndWrite(entry){\n console.log(entry);\n writeHistoryEntry(entry);\n}",
"function queryLoggerData(starttime,endtime,doOnSuccess) {\n\tif(endtime!=\"now\")\n\t$.couch.db(\"dripline_logged_data\").view(\"log_access/all_logged_data\", {\n\t\tstartkey: starttime,\n\t\tendkey: endtime,\n\t\tsuccess: function(data) {\n\t\t\tdoOnSuccess(data); },\n\t\terror: function(data) {\n\t\t\tdocument.getElementById(\"error_div\").innerHTML=\"error getting data: \"+JSON.stringify(data);\n\t\t\t}\n\t\t\t});\n\telse\n\t$.couch.db(\"dripline_logged_data\").view(\"log_access/all_logged_data\", {\n\t\tstartkey: starttime,\n\t\tendkey: endtime,\n\t\tsuccess: function(data) {\n\t\t\tdoOnSuccess(data); },\n\t\terror: function(data) {\n\t\t\tdocument.getElementById(\"error_div\").innerHTML=\"error getting data: \"+JSON.stringify(data);\n\t\t\t}\n\t\t\t});\n}",
"logValues() {\n let logString = '[';\n let node = this.head;\n while(node !== null) {\n logString += node.value + ', ';\n node = node.nextNode;\n }\n if (logString.length > 1) logString = logString.slice(0, -2); // remove extra comma\n logString += ']';\n console.log(logString);\n }",
"function logFileOutput(dataToLog) {\n\n file.appendFile(\"./log.txt\", dataToLog, function (err) {\n\n if (err) {\n console.log(err);\n }\n\n });\n\n}",
"function logActivity(name, points) {\n //set the date param as the day of the week (index 0-6, (sun-0, mon-1 etc...)\n var date = new Date().getDay();\n var id = getRows()+1;\n var log = function(tx){\n tx.executeSql(\"INSERT INTO activities (id, name, date, points) VALUES (?,?,?,?)\", \n [\n id,\n name,\n date,\n points\n ]);\n };\n //add the activity to the activities table\n db.transaction(log, errorCB, successCB);\n \n //add the new activity to the healthindexDB\n healthIndexDB.logActivity(date, points);\n \n }",
"function logText(text) {\n\tif(config.dev_log) {\n\t\tvar currentTime = new Date();\n\t\tvar currentDay = ensureNumberStringLength(currentTime.getDate(), 2);\n\t\tvar currentMonth = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][currentTime.getMonth()];\n\t\tvar currentYear = currentTime.getFullYear();\n\t\tvar currentHours = ensureNumberStringLength(currentTime.getHours(), 2);\n\t\tvar currentMinutes = ensureNumberStringLength(currentTime.getMinutes(), 2);\n\t\tvar currentSeconds = ensureNumberStringLength(currentTime.getSeconds(), 2);\n\n\t\tvar timestamp = ' [{dd}/{month}/{yyyy} {hh}:{mm}:{ss}] '.format({\n\t\t\tdd: currentDay, month: currentMonth, yyyy: currentYear,\n\t\t\thh: currentHours, mm: currentMinutes, ss: currentSeconds\n\t\t});\n\n\t\tvar textArray = text.split('\\n');\n\n\t\tfor (var i = textArray.length - 1; i > 0; i--) {\n\t\t\t$('.log-pre').prepend('<span class=\"log-time\">{whitespace}</span>{text}\\n'.format({\n\t\t\t\twhitespace: ' '.repeat(24),\n\t\t\t\ttext: textArray[i]}));\n\t\t}\n\t\t$('.log-pre').prepend('<span class=\"log-time\">{stamp}</span>{text}\\n'.format({\n\t\t\tstamp: timestamp,\n\t\t\ttext: textArray[0]}));\n\t} else {\n\t\twindow.console.log(text);\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
seeMore method loops over topSongsItems array and displays all items | seeMore(){
let i = 0;
for(i=0; i<topSongsItems.length; ++i){
helper.hideOrShow(topSongsItems[i], false);
}
//Remove class used to determine buttons state
seeMoreBtn.classList.remove('see-more-js');
//Swap text out on button
seeMoreBtn.innerHTML = 'See Less';
} | [
"seeLess(){\n let i = 0;\n for(i=0; i<topSongsItems.length; ++i){\n if(i>2){\n helper.hideOrShow(topSongsItems[i], true);\n }\n }\n //Add class used to determine buttons state\n seeMoreBtn.classList.add('see-more-js');\n //Swap text out on button\n seeMoreBtn.innerHTML = 'See More';\n }",
"function showItems() {\n\t\tvar itemlist = [];\n\t\n\t\tfor (var i = 0; i < room.items.length; i++) {\n\t\t\tif (room.items[i].specialdesc) {\n\t\t\t\toutput.before(room.items[i].specialdesc + \"<br />\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\titemlist.push(room.items[i].desc);\n\t\t\t}\n\t\t}\n\t\n\t\tif (itemlist.length === 1) {\n\t\t\toutput.before(\"There is a \" + itemlist[0] + \" here.<br /><br />\");\n\t\t}\n\t\telse if (itemlist.length > 1) {\n\t\t\tvar str = \"\";\n\t\t\tfor (var i = 0; i < itemlist.length; i++) {\n\t\t\t\tif (!itemlist[i + 1]) {\n\t\t\t\t\tstr.concat(itemlist[i]);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tstr.concat(itemlist[i] + \", \");\n\t\t\t\t}\n\t\t\t}\n\t\t\toutput.before(\"There is a \" + str + \" here.<br /><br />\");\n\t\t}\n\t\n\t\tscrollDown();\n\t\n\t}",
"function printTopArtists() {\n\n var artists = getTopArtists();\n var tileList = createTileCollection(artists);\n O(\"results\").appendChild(tileList);\n\n}",
"function listUpNext (songs) {\n\n\t\tvar upNext = document.getElementById('up-next');\n\t\tvar list = document.createDocumentFragment();\n\n\t\tfor (var song of songs) {\n\n\t\t\tvar listItemTemplate = importTemplate('player-upnext-template');\n\t\t\tvar listItem = listItemTemplate.querySelector('li');\n\n\t\t\tlistItem.textContent = song.name;\n\t\t\tlist.appendChild(listItem);\n\n\t\t}\n\n\t\tclearUpNext(upNext);\n\t\tupNext.appendChild(list);\n\n\t}",
"function moreClick() {\n\t\t$.when(moreStories()).done(function(story_data) {\n\t\t\tif (story_data.hasOwnProperty('stories')) {\n\t\t\t\tif (!story_data.before_timestamp) {\n\t\t\t\t\t$(\".more\").hide();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\turlForMoreStories = story_data.before_timestamp;\n\t\t\t\t\t$(\"#moreloader\").html(\"Load more stories\"); \n\t\t\t\t}\n\t\t\t\taddStories(story_data.stories, story_data.addresses, story_data.count);\n\t\t\t\tisUpdating = false;\n\t\t\t}\n\t\t});\n\t}",
"function viewItems() {\n console.clear();\n for (var i = 0; i < stockItems.length; i++) {\n console.log(stockItems[i].itemDetails());\n }\n viewItemsVisual();\n console.log(space);\n viewItemsOption();\n}",
"function listSongDetails(songs) {\n songs.forEach(song => console.log(`${song.name}, by ${song.artist} (${song.duration})`));\n}",
"function nextClicked() {\n if (currentFeed && currentItemIndex < currentFeed.items.size - 1) {\n currentItemIndex++;\n displayCurrentItem();\n }\n }",
"function getSongs() {\n fetch(songsURL)\n .then((response) => response.json())\n .then((songs) => songs.forEach((song) => renderSong(song)));\n}",
"function _drawResults() {\n\n let template = \"\";\n store.state.songs.forEach(song => {\n template += song.SearchTemplate;\n });\n document.getElementById(\"songs\").innerHTML = template;\n}",
"function loadMoreResults(){\n results += 10 \n showTruckResults()\n}",
"async displayRecentSearches(){\n try{\n // load the recent search from the device database cache\n let recentSearchData = await utopiasoftware[utopiasoftware_app_namespace].databaseOperations.\n loadData(\"recent-searches\", utopiasoftware[utopiasoftware_app_namespace].model.appDatabase);\n\n let displayContent = \"<ons-list-title>Recent Searches</ons-list-title>\"; // holds the content of the list to be created\n // create the Recent Searches list\n for(let index = 0; index < recentSearchData.products.length; index++){\n displayContent += `\n <ons-list-item modifier=\"longdivider\" tappable lock-on-drag=\"true\">\n <div class=\"center\">\n <div style=\"width: 100%;\" \n onclick=\"utopiasoftware[utopiasoftware_app_namespace].controller.searchPageViewModel.\n recentSearchesItemClicked(${index})\">\n <span class=\"list-item__subtitle\">${recentSearchData.products[index].name}</span>\n </div>\n </div>\n <div class=\"right\" prevent-tap \n onclick=\"utopiasoftware[utopiasoftware_app_namespace].controller.searchPageViewModel.\n removeRecentSearchItem(${index}, this);\">\n <ons-icon icon=\"md-close-circle\" style=\"color: lavender; font-size: 18px;\"></ons-icon>\n </div>\n </ons-list-item>`;\n }\n // attach the displayContent to the list\n $('#search-page #search-list').html(displayContent);\n }\n catch(err){\n\n }\n }",
"function finsweetLoadMore() {\n console.log(\"Running finsweetLoadMore.\");\n (function() {\n var loadmoreList = new FsLibrary('.js--list-loadmore'); //this class defines the lists this function looks at\n loadmoreList.loadmore({\n button: \".js--button-loadmore\", // class of Webflow Pagination button\n resetIx: false, // adds Webflow interactions to newly loaded item\n loadAll: false, // this loads all elements\n animation: {\n enable: true,\n duration: .3,\n easing: 'ease',\n effects: 'fade'\n }\n })\n })();\n}",
"function getMostPopularViewed() {\n var url = 'https://api.nytimes.com/svc/mostpopular/v2/mostviewed/Magazine/7.json';\n let params = {\n q: 'query',\n 'api-key': '85b2939e3df349dd8502775e8623d350'\n }\n url += '?' + $.param(params)\n $.ajax({\n url: url,\n method: 'GET',\n }).done(function(data) {\n console.log(data);\n\n // Define which results will be displayed and display them\n for (var i = 0; i < 5; i++) {\n var title = data.results[i].title;\n $('.viewed').show();\n var article_url = data.results[i].url;\n var abstract = data.results[i].abstract;\n\n // Use bracket notation for media-metadata\n var image = data.results[i].media[0]['media-metadata'][0].url;\n console.log(image);\n \n // Display results in HTML\n $('#results-viewed').append(\"<li><h3>\" + title + \n \"</h3>\" + abstract + \"<br><br>\" + \"<a target='blank' href='\" + article_url + \"'>\" + \n \"<img src='\" + image + \"'>\" + \"</a></li>\");\n $('#summary-viewed').append(\"<a target='blank' href='\" + article_url + \"'>\" + \n \"<img src='\" + image + \"'>\" + \"</a>\");\n } \n }).fail(function(err) {\n throw err;\n });\n }",
"function loadMoreRecords(){\n if(count == 0){\n count++;\n }else{\n getAllVideos(self.videos.length,10);\n }\n }",
"function seeAllStories() {\n vm.storyLimit = vm.newsDetails.length - 1;\n }",
"static refreshList(sortBy = null) {\n if (typeof sortBy == \"string\") {\n Settings.current.sortBy = sortBy;\n }\n if (this.songListElement) {\n let sortFunc = (a, b) => { return 0; };\n try {\n switch (Settings.current.sortBy) {\n case \"title\":\n sortFunc = (a, b) => {\n if (a.details.title.toLowerCase() > b.details.title.toLowerCase()) {\n return 1;\n }\n if (a.details.title.toLowerCase() < b.details.title.toLowerCase()) {\n return -1;\n }\n return 0;\n };\n break;\n case \"length\":\n sortFunc = (a, b) => {\n if (typeof a.details.songLength == \"number\" && typeof b.details.songLength == \"number\" && a.details.songLength > b.details.songLength) {\n return 1;\n }\n if (typeof a.details.songLength == \"number\" && typeof b.details.songLength == \"number\" && a.details.songLength < b.details.songLength) {\n return -1;\n }\n return 0;\n };\n break;\n case \"artist\": // Fall-through\n default:\n sortFunc = (a, b) => {\n if (a.details.artist.toLowerCase() > b.details.artist.toLowerCase()) {\n return 1;\n }\n if (a.details.artist.toLowerCase() < b.details.artist.toLowerCase()) {\n return -1;\n }\n return 0;\n };\n break;\n }\n }\n catch (error) {\n }\n var _sort = function (a, b) {\n // Make order reversable\n return sortFunc(a, b);\n };\n SongManager.songList.sort(_sort);\n let nList = SongManager.songList;\n let opened = SongGroup.getAllGroupNames(false);\n opened = [...new Set(opened)];\n SongManager.songListElement.innerHTML = \"\";\n let noGrouping = false;\n // Group Songs\n if (typeof Settings.current.songGrouping == \"number\" && Settings.current.songGrouping > 0 && Settings.current.songGrouping <= 7) {\n let groups = {};\n let addToGroup = function (name, song, missingText = \"No group set\") {\n if (name == null || (typeof name == \"string\" && name.trim() == \"\")) {\n name = missingText;\n }\n if (groups.hasOwnProperty(name)) {\n groups[name].push(song);\n }\n else {\n groups[name] = [song];\n }\n };\n switch (Settings.current.songGrouping) {\n case 1:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.artist, s, \"[No artist set]\");\n });\n break;\n case 2:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.album, s, \"[No album set]\");\n });\n break;\n case 3:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.source, s, \"[No source set]\");\n });\n break;\n case 4:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.language, s, \"[No language set]\");\n });\n break;\n case 5:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.genre, s, \"[No genre set]\");\n });\n break;\n case 6:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.year, s, \"[No year set]\");\n });\n break;\n case 7:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.customGroup, s, \"[No group set]\");\n });\n break;\n case 8:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.artist[0].toUpperCase(), s, \"[No artist set]\");\n });\n break;\n case 9:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.title[0].toUpperCase(), s, \"[No title set]\");\n });\n break;\n default:\n noGrouping = true;\n break;\n }\n if (noGrouping == false) {\n for (const key in groups) {\n if (groups.hasOwnProperty(key)) {\n const sg = new SongGroup(key);\n sg.songList = groups[key];\n if (opened.includes(sg.name)) {\n sg.collapsed = false;\n }\n else {\n sg.collapsed = true;\n }\n sg.refreshList();\n }\n }\n }\n }\n // Don't Group Songs\n else {\n noGrouping = true;\n }\n if (noGrouping == true) {\n for (let i = 0; i < nList.length; i++) {\n const song = nList[i];\n song.refreshElement();\n SongManager.songListElement.appendChild(song.element);\n }\n }\n SongManager.search();\n }\n else {\n console.error(\"No div element applied to SongManager.songListElement\", \"SongManager.songListElement is \" + typeof SongManager.songListElement);\n }\n Toxen.resetTray();\n }",
"function topSugList() {\n var listhtml = \"\";\n var wordlist = Object.keys(displayedSugs);\n for (var i = 0; i < wordlist.length; i++) {\n listhtml += (\"<li>\" + wordlist[i] + \"</li>\");\n }\n $(\"#topsugslist\").html(listhtml);\n}",
"function getRecommendationsArtist(similarArtist) {\n\tvar queryBase = base + '/getRec?token=' +spotifyToken + '&limit=' + 50 + '&artists=' + similarArtist;\n\tvar queryTrackAtrributes = '&target_acousticness=' + targetValues.acousticness + '&target_danceability=' + targetValues.danceability\n\t\t+ '&target_energy=' + targetValues.energy + '&target_valence=' + targetValues.valence + '&target_instrumentalness='+targetValues.instrumentalness\n\t\t+'&target_tempo='+targetValues.tempo+'&userId=' + userID + '&likedSongs=' + likedSongs.length + '&dislikedSongs=' + dislikedSongs.length;\n\tvar query = queryBase.concat(queryTrackAtrributes);\n\t$.getJSON( query , function( dataObject ) {\n\t\tif (dataObject.error){\n\t\t\taddInteraction(\"recommendations\",'error', 'error')\n\n\t\t\twindow.location.href = base + '/error';\n\t\t}\n\t\tvar data = dataObject.data;\n\n\t\tvar nbAppendedArtists = 0;\n\t\tvar appendedSongslist = [];\n\t\tdata.forEach(function (d,i) {\n\t\t\tvar index = likedSongs.indexOf(d.id);\n\t\t\tvar indexDisliked = dislikedSongs.indexOf(d.id)\n\t\t\t//this is needed to know when you arrived with the last song, so you can update\n\t\t\tif(index === -1 && indexDisliked === -1 && d.preview_url !== null && nbAppendedArtists < totalNbOfRecommendations) {\n\t\t\t\tnbAppendedArtists++;\n\t\t\t\tappendedSongslist.push(d.id);\n\t\t\t}\n\t\t});\n\n\t\tnbAppendedArtists = 0;\n\t\tdata.forEach(function (d,i) {\n\t\t\t//Don't do anything if preview is null or already appended 10 songs or already liked\n\t\t\tvar index = likedSongs.indexOf(d.id);\n\t\t\tvar indexDisliked = dislikedSongs.indexOf(d.id)\n\t\t\tif(index === -1 && indexDisliked === -1 && d.preview_url !== null && nbAppendedArtists < totalNbOfRecommendations){\n\t\t\t\tnbAppendedArtists ++;\n\t\t\t\tvar artist = d.artists[0]['name'];\n\t\t\t\tvar artistId = d.artists[0]['id'];\n\t\t\t\tvar image = \"image\"\n\t\t\t\tappendSong(d.id, similarArtist, d.name, artist, d.duration_ms, d.external_urls['spotify'], d.preview_url, image, appendedSongslist);\n\n\n\n\t\t\t\t// //\tget the image of the artist\n\t\t\t\t// var query = '/getArtist?token=' + spotifyToken + '&artistId=' + artistId;\n\t\t\t\t// $.getJSON(query, function (dataObject) {\n\t\t\t\t// \tif (dataObject.error){\n\t\t\t\t// \t\taddInteraction(\"getArtist\",'error', 'error')\n\t\t\t\t// \t\twindow.location.href = base + '/error';\n\t\t\t\t// \t}\n\t\t\t\t// \tvar data = dataObject.data;\n\t\t\t\t// \tvar image = getArtistImage(data);\n\t\t\t\t// \tappendSong(d.id, similarArtist, d.name, artist, d.duration_ms, d.external_urls['spotify'], d.preview_url, image, appendedSongslist);\n\t\t\t\t// })\n\t\t\t}\n\t\t});\n\t});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads key/value store from file. | function readStore(storeFile) {
var data = fs.readFileSync(storeFile, 'utf8', function(error) {
if (error) {
console.log('Unable to read store file: ' + error);
console.log('Cleaning and resetting store file.')
}
});
return JSON.parse(data);
} | [
"function load (file) {\n var map = {};\n // read the file synchronously, this isn't a server\n var content = fs.readFileSync(file, encodingOptions);\n // split out the lines\n var lines = content && content.split(/[\\r\\n]+/g);\n if (lines) {\n // For every line\n lines.forEach(function (line) {\n // parse out the user & the hash\n var tokens = line && line.split(/: ?/);\n // if the line had a : separated string pair,\n if (tokens.length === 2) {\n var user = tokens[0];\n var hash = tokens[1];\n // update the map with the user/hash combination\n map[user] = hash;\n }\n });\n }\n // return the hash object\n return map;\n}",
"static readData(key) {\n return AsyncStorage.getItem(key)\n }",
"function read()\n\t{\n\t\ttry \n\t\t{\n\t\t\tvar json = sessionStorage.getItem(key) //retrieve database from session storage in json format\n\t\t\tjson = JSON.parse(json); //parse json into a javascript object\n\t\t\tif (json === null) //if database is null\n\t\t\t\tjson = []; //create an empty database\n\t\t\treturn json;\n\t\t} catch(e) \n\t\t{\n\t\t\treturn null;\n\t\t}\n\t}",
"async kv_data() {\r\n let query = { \"query\": JSON.stringify({ \"play\": this.search_name})};\r\n let response = await this.service.get(\"stroage/collections/data/{KV STORE NAME}\", query);\r\n if (response !== null || response !== response) {\r\n this.kv_props = JSON.parse(response)[0];\r\n return this.kv_props;\r\n }\r\n }",
"function load(key) {\n\tconst str = localStorage[key] || 'null';\n\treturn JSON.parse(str);\n}",
"async load() {\n await this.ensureExists();\n this.conf = await fs.readJSON(this.location);\n }",
"async function getKeystore () {\n logger.log('verbose', 'Importing private keys into the keystore')\n\n fs.readdirSync(keysPath).forEach(file => {\n const akeyPath = path.resolve(keysPath, file);\n if (fs.lstatSync(akeyPath).isFile()) {\n const fileNameRegExp = /(.*?)_(.*?)_(.*?)\\.pem/;\n const matches = file.match(fileNameRegExp);\n\n if (matches.length == 4) { // file naming: keydId_use_alg.pem\n try {\n const keyObj = {\n key: fs.readFileSync(akeyPath, 'utf8'),\n passphrase: secretKey\n }\n \n const opts = {\n kid: `${matches[1]}_${matches[2]}_${matches[3]}`,\n use: matches[2],\n alg: matches[3].toUpperCase()\n }\n \n // Create the key and add it to the keystore\n const key = asKey(keyObj, opts) \n ks.add(key)\n } catch (err) {\n const msg = 'Private key was not successfully added to the keystore.'\n logger.log('error', `${msg} key: ${file}, error: ${err}`)\n }\n }\n }\n });\n\n return ks\n}",
"function lsget(k) {\n k = _tokey(k);\n let v = JSON.parse(localStorage.getItem(k));\n return v;\n}",
"function read_config(){\n\tdb.each(\"SELECT * FROM settings\", \n\t\tfunction(err, row) {\n\t\t\tif(err) {\n\t\t\t\tconsole.log(\"DB error\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tsettings[row.name] = row.value;\n\t\t\t//console.log(JSON.stringify(settings, null, 4));\n\t\t}\n\t);\n}",
"checkKeyFile() {\n let dir = __dirname + \"/../.data\";\n let filepath = dir + \"/keystore.json\";\n if (!fs.existsSync(filepath)) {\n this.previousInstance = false;\n return;\n }\n\n // A keystore file exists, lets see if it contains everything we need\n try {\n let data = fs.readFileSync(filepath);\n let keyfile = JSON.parse(data);\n\n // Address of the previous contract deployed to the\n this.contractAddress = keyfile.contractAddress;\n\n this.kaleidoConfigInstance.consortiaId = keyfile.consortia;\n this.kaleidoConfigInstance.environmentId = keyfile.environment;\n\n this.kaleidoConfigInstance.userNodeUser = keyfile.user_node.username;\n this.kaleidoConfigInstance.userNodePass = keyfile.user_node.password;\n this.kaleidoConfigInstance.userNodeUrls = keyfile.user_node.urls;\n\n this.kaleidoConfigInstance.joeNodeUser = keyfile.joe_node.username;\n this.kaleidoConfigInstance.joeNodePass = keyfile.joe_node.password;\n this.kaleidoConfigInstance.joeNodeUrls = keyfile.joe_node.urls;\n\n this.kaleidoConfigInstance.storeNodeUser = keyfile.kard_store_node.username;\n this.kaleidoConfigInstance.storeNodePass = keyfile.kard_store_node.password;\n this.kaleidoConfigInstance.storeNodeUrls = keyfile.kard_store_node.urls;\n\n this.previousInstance = true;\n } catch(error) {\n console.log(error);\n this.previousInstance = false;\n }\n }",
"function loadConfig() {\n\tconfig_file = fs.readFileSync(\"./config.json\");\n\tconfig = JSON.parse(config_file);\n}",
"function readDataFile(e) {\n var file = e.target.files[0];\n if (!file) {\n return;\n }\n\n var reader = new FileReader();\n reader.onload = function(e) {\n var contents = e.target.result;\n displayContents(contents);\n parseInputData(contents);\n };\n reader.readAsText(file);\n }",
"load() {\n let database = fs.readFileSync(__dirname + '/database.json', 'utf8');\n return JSON.parse(database);\n }",
"function loadJSON(file) {\n return JSON.parse(FS.readFileSync(file, \"utf8\"));\n}",
"function readDatabase(filename) {\n //1.lue tiedosto levyltä\n //2.tallenna sisältö muuttujaan (JSON.parse(tiedostonSisalto))\n var pathToFile = path.join(__dirname, filename);\n fs.readFile(pathToFile, 'utf8', function (err, data) {\n if (err) {\n return console.log(err);\n }\n toVariable = JSON.parse(data);\n console.log(\"1) Tiedoston nimi: \"+filename);\n console.log(\"2) Tietueiden lukumäärä: \"+size());\n console.log(\"3) a) Löytyyko Jaska-niminen henkilö?: \"+containsPerson('Jaska'));\n console.log(\"3) b) Löytyyko Sarita-niminen henkilö?: \"+containsPerson('Sarita'));\n console.log(\"4) Mikä tietue vastaa tätä hakua?: \"+search('Tiia', '','','','','')+\". tietue\\n\"); \n console.log(toVariable[search('Tiia', '','','','','')]);\n })\n}",
"function ReadData() \n\t{\n MyUser = getCookie(COOKIE_NAMES.user);\n MyPass = getCookie(COOKIE_NAMES.password);\n MyZoom = getCookie(COOKIE_NAMES.zoom);\n wlat = getCookie(COOKIE_NAMES.lat);\n wlon = getCookie(COOKIE_NAMES.lng);\n myloginid = getCookie(COOKIE_NAMES.id);\n mytel = getCookie(COOKIE_NAMES.tel);\n myid = getCookie(COOKIE_NAMES.myid);\n\tconsole.log(\"reading: \"+MyUser+ \" - \"+MyPass+ \" - \"+MyZoom+ \" - \"+wlat+ \" - \"+wlon+ \" - \"+myloginid+ \" - \"+mytel+ \" - \"+myid);\n\t}",
"function read(callback) {\n fs.readFile(FILE, 'utf8', (err, data) => {\n if (err) console.log('Error:', err);\n callback(data);\n })\n}",
"function get(key) {\n console.log('Searching for: ' + key);\n storeObject.table.forEach(function(item) {\n if (item['key'] === key) {\n console.log(item['value']);\n } \n });\n }",
"function readStartingData(){\n readUser = JSON.parse(fs.readFileSync('data/user.json'));\n listDoc = JSON.parse(fs.readFileSync('data/documents.json'));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete an existing area. | function deleteArea(axios$$1, areaToken, force) {
var query = '';
if (force) {
query += '?force=true';
}
return restAuthDelete(axios$$1, 'areas/' + areaToken + query);
} | [
"async removeAreas() {\n const areas = this.ctx.request.body;\n let del = true;\n\n for (const area of areas.areas) {\n if (!await this.service.areas.delete({ id: area.id })) {\n del = false;\n }\n }\n\n if (!del) {\n this.response(404, 'delete some area info failed');\n return;\n }\n\n this.response(204, 'delete all area satisfied condition successed');\n }",
"function deleteAreaType(axios$$1, areaTypeToken, force) {\n var query = '';\n if (force) {\n query += '?force=true';\n }\n return restAuthDelete(axios$$1, 'areatypes/' + areaTypeToken + query);\n }",
"function region_delete() {\n // populate_segments();\n }",
"function gui_removeArea(id) {\n\tif (props[id]) {\n\t\t//shall we leave the last one?\n\t\tvar pprops = props[id].parentNode;\n\t\tpprops.removeChild(props[id]);\n\t\tvar lastid = pprops.lastChild.aid;\n\t\tprops[id] = null;\n\t\ttry {\n\t\t\tgui_row_select(lastid, true);\n\t\t\tmyimgmap.currentid = lastid;\n\t\t}\n\t\tcatch (err) {\n\t\t\t//alert('noparent');\n\t\t}\n\t}\n}",
"function unselectArea(area){\n\t\t\tvar id_index = selected_areas.indexOf(area.properties.STUSPS), // area.properties.STUSPS = state abbr, ie \"NV\" for Nevada\n\t\t\t\t\tname_index = sgeonames.indexOf(area.properties.NAME);\n\n\t\t\tselected_areas.splice(id_index, 1);\n\t\t\tsgeonames.splice(name_index, 1);\n\n\t\t\tif (selected_areas.length === 1) {\n\t\t\t\t$(\"#right-sidebar h3\").text(\"Please select an area.\");\n\t\t \t$(\"#area-blank2\").html(\"<h3> </h3>\");\n\t\t } else if (selected_areas.length === 0) {\n\t\t \t$(\"#left-sidebar h3\").text(\"Please select an area.\");\n\t\t\t\t$(\"#area-blank1\").html(\"<h3> </h3>\");\n\t\t }\n\n\t\t}",
"function eliminarTarea() {\n\n axios.delete(URL + 'tarea/' + tareaSeleccionada.id,\n {\n headers: { Authorization: 'Bearer ' + JSON.parse(state.token) }\n }\n )\n .then((res) => {\n\n mostrarNotificacion('Tarea eliminada exitosamente', 'success')\n buscarTareas(); //actualizar lista de tareas\n })\n .catch((err) => {\n mostrarNotificacion('Error al eliminar', 'warning')\n console.log(err)\n })\n }",
"deleteRegionById(id) {\r\n const region = this.lookupRegionByID(id);\r\n if (region != null) {\r\n this.deleteRegion(region);\r\n }\r\n if (this.callbacks.onManipulationEnd !== null) {\r\n this.callbacks.onManipulationEnd();\r\n }\r\n }",
"async addArea() {\n const area = this.ctx.request.body;\n const id = this.ctx.params.areaId;\n area.id = id;\n\n // area id doesn't exist\n if (!area.id) {\n this.response(403, 'area id must exists');\n return;\n }\n\n // area exists\n if (!await this.service.areas.insert(area)) {\n this.response(403, 'area exists');\n return;\n }\n\n this.response(203, 'add area record successed');\n }",
"function createArea(axios$$1, area) {\n return restAuthPost(axios$$1, 'areas', area);\n }",
"deleteOneLocation(id) {\n return db.none(`\n DELETE FROM location\n WHERE id = $1\n `, id);\n }",
"function updateArea(axios$$1, areaToken, payload) {\n return restAuthPut(axios$$1, 'areas/' + areaToken, payload);\n }",
"async modifyArea() {\n const id = this.ctx.params.areaId;\n\n // area without id attribute\n const area = this.ctx.request.body;\n\n // add attribute id to area\n area.id = id;\n\n if (!await this.service.areas.update(area)) {\n this.response(403, 'update area info failed');\n return;\n }\n\n this.response(203, 'update area info successed');\n }",
"function Area(identifier, label, description, type, geoLocation) {\n\tthis.identifier = identifier;\n\tthis.label = label;\n\tthis.description = description;\n\tthis.type = type;\n\tthis.geoLocation = geoLocation;\n\tthis.__environments = [];\n}",
"function handleDeletePlace() {\n\t$('main').on('click','.delete-place-button', function(event) {\n\t\tconst placeId = $(this).data('id');\n\t\tconst tripId = $(this).data('trip');\n\t\tdeletePlace(tripId, placeId);\n\t})\n}",
"function erase(e) {\n database.database_call(`DELETE FROM subnote WHERE id=${id} `);\n alerted.note(\"The current note was deleted!\", 1);\n Alloy.Globals.RenderSubNotesAgain();\n $.view_subnotes.close();\n}",
"function deleteCurrentFeature(){\n if(window.confirm(\"Delete feature?\")){\n vectorLayer.destroyFeatures(currentFeature);\n\n // Need to remove this from the side panel\n //$('#info-inner').html(\"\");\n }\n }",
"function deleteAccess(req, res) {\n db.get(\"SELECT * FROM tool WHERE user = ? AND id =? \", req.signedCookies.user_id, req.body.toolId,\n function(err, self_created_tool) {\n if (err) {\n res.status(500).send({ error: \"Failed to find self-created tool: \" + req.body.toolId });\n } else {\n if(self_created_tool) {\n db.run(\"DELETE FROM access WHERE userId = ? and toolId=?\", [ req.body.userId, req.body.toolId ],\n function(err){\n if(err) {\n res.status(500).json({ error: \"Error while trying to delete access authority.\" }); \n } else {\n res.json({ success: \"access authority is successfully deleted.\" });\n }\n });\n } else {\n res.status(500).send({ error: \"Can't delete access authority created by others. \" });\n } \n }\n });\n }",
"function deleteRouteMarker() {\n\n selectedRouteMarker.setMap(null);\n \n var index = currentRoute.markerArray.indexOf(selectedRouteMarker);\n \n currentRoute.markerArray.splice(currentRoute.markerArray.indexOf(selectedRouteMarker), 1);\n var path = currentRoute.route.getPath();\n path.forEach(function (item, index) {\n if (path.getAt(index) == selectedRouteMarker.position) {\n path.removeAt(index);\n }\n });\n \n if (index == 0) {\n \n if (currentMode == MODE.ROUTE || currentMode == MODE.DISTANCE ) {\n \n if (currentRoute.markerArray.length == 0) {\n \n currentRoute.markerInfobox.setMap(null);\n stopRouteMode();\n return;\n \n } else {\n currentRoute.markerInfobox = drawRouteInfobox(currentRoute.markerArray[index].position, currentRoute.name);\n }\n \n } else {\n currentRoute.markerInfobox = drawDistanceInfobox(currentRoute.markerArray[index].position);\n }\n }\n \n updateRouteDistance();\n}",
"function deleteStore() {\n\tif (document.querySelector(\"#stores-info\")) {\n\t\tconst confirmation = confirm(\"Are you sure you want to delete the store?\")\n\t\tif (confirmation) {\n\t\t\tlet selectStoreId = document.querySelector(\"#stores-info\").getAttribute(\"storeKey\");\n\t\t\t\n\t\t\tSTORES.splice(selectStoreId, 1)\n\t\t\tlocalStorage[\"Stores\"] = JSON.stringify(STORES);\n\n\t\t\tlocation.reload();\n\t\t}\n\t} else {\n\t\t popUpStatus(`Select the store you want to delete :)`)\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a new waypoint (as a LatLng object). | function addLocation()
{
let newWaypoint = currentRoute.routeMarker.getPosition();
currentRoute.waypoints.push(newWaypoint);
currentRoute.displayPath();
} | [
"function handleAddWaypointClick(e) {\n //id of prior to last waypoint:\n var waypointId = $(e.currentTarget).prev().attr('id');\n var oldIndex = parseInt(waypointId);\n addWaypointAfter(oldIndex, oldIndex + 1);\n theInterface.emit('ui:selectWaypointType', oldIndex);\n var numwp = $('.waypoint').length - 1;\n }",
"function buildWaypoint(mapLayer, wpType, address, viaCounter, distance, duration) {\n var directionsContainer = new Element('div', {\n 'class': 'directions-container clickable',\n 'data-layer': mapLayer,\n });\n var icon;\n if (wpType == 'start') {\n icon = new Element('i', {\n 'class': 'fa fa-map-marker'\n });\n } else if (wpType == 'via') {\n icon = new Element('span', {\n 'class': 'badge badge-inverse'\n }).update(numStopovers);\n } else {\n icon = new Element('i', {\n 'class': 'fa fa-flag'\n });\n }\n var wayPoint = new Element('div', {\n 'class': 'instr-waypoint',\n });\n wayPoint.appendChild(icon);\n var shortAddress = new Element('div', {\n 'class': 'address',\n 'waypoint-id': viaCounter\n }).update(address);\n // modeContainer\n var directionsModeContainer = new Element('div', {\n 'class': 'directions-mode-container'\n });\n var directionsBorder = new Element('div', {\n 'class': 'line'\n });\n directionsContainer.appendChild(wayPoint);\n // add info if via or endpoint\n if (wpType == 'end' || wpType == 'via') {\n var pointInfo = new Element('div', {\n 'class': 'info'\n }).update(Number(duration / 60).toFixed() + ' min' + ' / ' + Number(distance / 1000).toFixed(2) + ' km');\n directionsContainer.appendChild(pointInfo);\n }\n directionsContainer.appendChild(shortAddress);\n directionsModeContainer.appendChild(directionsBorder);\n directionsContainer.appendChild(directionsModeContainer);\n return directionsContainer;\n }",
"addPoint() {\r\n var point;\r\n if(this.points.length < this.numpoints) {\r\n point = {};\r\n this.initPoint(point);\r\n this.points.push(point);\r\n }\r\n }",
"function addWaypointAfter(idx, numWaypoints) {\n //for the current element, show the move down button (will later be at least the next to last one)\n var previous = $('#' + idx);\n previous.children()[3].show();\n //'move' all successor waypoints down from idx+1 to numWaypoints\n for (var i = numWaypoints - 1; i >= idx + 1; i--) {\n var wpElement = $('#' + i);\n if (i < numWaypoints - 1) {\n //this is not the last waypoint, show move down button\n wpElement.children()[3].show();\n }\n wpElement.attr('id', i + 1);\n }\n //generate new id\n var newIndex = parseInt(idx) + 1;\n var predecessorElement = $('#' + idx);\n var waypointId = predecessorElement.attr('id');\n waypointId = waypointId.replace(idx, newIndex);\n //generate DOM elements\n var newWp = $('#Draft').clone();\n newWp.attr('id', waypointId)\n newWp.insertAfter(predecessorElement);\n newWp.show();\n //decide which buttons to show\n var buttons = newWp.children();\n //show remove waypoint + move up button\n buttons[1].show();\n buttons[2].show();\n //including our new waypoint we are constructing here, we have one more waypoint. So we count to numWaypoints, not numWaypoints-1\n if (newIndex < numWaypoints) {\n //not the last waypoint, allow moving down\n buttons[3].show();\n } else {\n buttons[3].hide();\n }\n //add event handling\n newWp = newWp.get(0);\n newWp.querySelector('.searchWaypoint').addEventListener('keyup', handleSearchWaypointInput);\n newWp.querySelector('.moveUpWaypoint').addEventListener('click', handleMoveUpWaypointClick);\n newWp.querySelector('.moveDownWaypoint').addEventListener('click', handleMoveDownWaypointClick);\n newWp.querySelector('.removeWaypoint').addEventListener('click', handleRemoveWaypointClick);\n newWp.querySelector('.searchAgainButton').addEventListener('click', handleSearchAgainWaypointClick);\n newWp.querySelector('.waypoint-icon').addEventListener('click', handleZoomToWaypointClick);\n theInterface.emit('ui:addWaypoint', newIndex);\n }",
"function genWayPoints()\n{\n\tvar ix = 0;\n\n\tvar numWayPoints = waypoints.length\n\tvar bounds = new google.maps.LatLngBounds();\n\tvar iw = new google.maps.InfoWindow();\n\tvar totDistance = 0;\t\t// Total distance for trip\n\tvar aryPrevWpt;\n\tconsole.log(\"Starting new Waypoints:\");\n\t\n\tfor (var kx in waypoints)\n\t{ \n\t\tif(++ix >= 26) ix = 0 // 26 letters in the alphabet\n\t\tvar thisCode = String.fromCharCode(65 + ix) + \".png\"\t// Create the waypoint alphabetic label\n\t\tvar thisPath = \"icons/markers/\";\n\t\n\t\t// Assume a normal marker\n\t\tvar wptColor = thisPath + \"green_Marker\" + thisCode \n\t\n\t\t// If there was a tag associated with this, make it BLUE, unless it was queued\n\t\tif(waypoints[kx][\"tag\"] != \"0\") wptColor = thisPath + \"blue_Marker\" + thisCode\n\n\t\t// If it was queued, we lose the BLUE tag - / Indicates queued/deferred item\n\t\tif(waypoints[kx][\"flg\"] == \"1\") wptColor = thisPath + \"red_Marker\" + thisCode\n\n\t\t // Indicates first after queued/deferred items, use Yellow\n\t\t if(waypoints[kx][\"flg\"] == \"3\") wptColor = thisPath + \"yellow_Marker\" + thisCode \n\t \n\t\t // Generate the WayPoint\n\t\t var latlng = {lat: Number(waypoints[kx][\"gpslat\"]), lng: Number(waypoints[kx][\"gpslng\"])};\n\t\t bounds.extend(latlng)\n\t \n\t\t var latlngA = waypoints[kx][\"gpslat\"] + \", \" + waypoints[kx][\"gpslng\"];\n\n\t\t var wpt = new google.maps.Marker({icon: wptColor, \n\t\t\t\t\t\t\t\t\t\t position: latlng, \n\t\t\t\t\t\t\t\t\t\t title: latlngA}) \n\t\t wpt.setMap(map);\t\t// Display the waypoint\t\t \n\t\t markers.push(wpt);\t\t// Save the Waypoint\n\t\t // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\t\t // Now make sure we have the Cell Tower\n\t\t genCellTower(waypoints[kx][\"cid\"], kx);\n\t \n\t\t // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\t\t // Now generate the info for this point\n\t\t // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n\t\t// Get distance to cell tower and between waypoints\n\t\tvar arycel = {lat: Number(waypoints[kx][\"gsmlat\"]) , lng: Number(waypoints[kx][\"gsmlng\"])}\n\t\tvar distToCell = distCalc(latlng, arycel)\n\t\n\t\tvar thisDist = (aryPrevWpt == null ? 0 : distance(Number(waypoints[kx][\"gpslat\"]), Number(waypoints[kx][\"gpslng\"]), Number(aryPrevWpt[\"lat\"]), Number(aryPrevWpt[\"lng\"]), \"M\"))\n\n\t\ttotDistance += thisDist\n\t\taryPrevWpt = latlng\n\t\n\t\tif(LOG_DS == true)\n\t\t{\n\t\t\tconsole.log(\"thisDist \",thisDist);\n\t\t\tconsole.log(\"totDist \",totDistance);\n\t\t}\n\t\n\t\t// This is a function type called \"closure\" - no idea how it works, but it does\n\t\t(function(kx, wpt) {\n\t\t\t// Generate the VAR\n\t\t\taryInfoVars[\"iv\" + kx] = \n\t\t\t\t\"<div>\" +\n\t\t\t\t\"<h3>\" + (waypoints[kx][\"tag\"] != '0' ? waypoints[kx][\"tag\"] : (waypoints[kx][\"flg\"] != '0' ? 'No Svc' : 'WPT ')) + \" @ \" + Number(waypoints[kx][\"gpslat\"]) + \", \" + Number(waypoints[kx][\"gpslng\"]) + \"</h3>\" +\n\t\t\t\t\"<p>\" + waypoints[kx][\"dat\"] + \" - \" + waypoints[kx][\"tim\"] + (waypoints[kx][\"qct\"] != 0 ? ', Queued: ' + waypoints[kx][\"qct\"] : \" \") + \"</p>\" +\n\t\t\t\t\"<p>cell tower (\" + waypoints[kx][\"cid\"] + \"): \" + Math.round(distToCell,2) + \" Miles, \" + waypoints[kx][\"css\"] + \" dBm</p>\" +\n\t\t\t\t\"<p>From Start: \" + Math.round(totDistance,2) + \" mi, From Last: \" + Math.round(thisDist,2) + \" mi</p>\" +\n\t\t\t\t\"<div>\" +\n\t\t\t\t\"<p><b> Alt: \" + Math.round(waypoints[kx][\"alt\"]*3.28) + \" ft, Speed: \" + Math.round(waypoints[kx][\"spd\"]*.621371,2) + \" mph, Course: \" + waypoints[kx][\"crs\"] + \"°</b></p>\" +\n\t\t\t\t\"</div></div>\"\n\n\t\t\t// Generate the InfoWindow\n\t\t\tiw.setContent(aryInfoVars[\"iv\" + kx]);\n\n\t\t\t// Generate the Listener\n\t\t\twpt.addListener('click', function() {iw.open(map, wpt)})\n\t\t})(kx, wpt);\n\t\t//\n\t\t/*\n\t\t\t(function(kx, wpt) {\n\t\t\t// Generate the VAR\n\t\t\tgoogle.maps.event.addListener(wpt, 'click',\n\t\t\t\tfunction() {\n\t\t\t\t\tvar iw = \n\t\t\t\t\t\"<div>\" +\n\t\t\t\t\t\"<h3>\" + (waypoints[kx][\"tag\"] != '0' ? waypoints[kx][\"tag\"] : (waypoints[kx][\"flg\"] != '0' ? 'No Svc' : 'WPT ')) + \" @ \" + Number(waypoints[kx][\"gpslat\"]) + \", \" + Number(waypoints[kx][\"gpslng\"]) + \"</h3>\" +\n\t\t\t\t\t\"<p>\" + waypoints[kx][\"dat\"] + \" - \" + waypoints[kx][\"tim\"] + (waypoints[kx][\"qct\"] != 0 ? ', Queued: ' + waypoints[kx][\"qct\"] : \" \") + \"</p>\" +\n\t\t\t\t\t\"<p>cell tower (\" + waypoints[kx][\"cid\"] + \"): \" + Math.round(distToCell,2) + \" Miles, \" + waypoints[kx][\"css\"] + \" dBm</p>\" +\n\t\t\t\t\t\"<p>From Start: \" + Math.round(totDistance,2) + \" mi, From Last: \" + Math.round(thisDist,2) + \" mi</p>\" +\n\t\t\t\t\t\"<div>\" +\n\t\t\t\t\t\"<p><b> Alt: \" + Math.round(waypoints[kx][\"alt\"]*3.28) + \" ft, Speed: \" + Math.round(waypoints[kx][\"spd\"]*.621371,2) + \" mph, Course: \" + waypoints[kx][\"crs\"] + \"°</b></p>\" +\n\t\t\t\t\t\"</div></div>\"\n\t\t\t\t});\n\t\t\t// Generate the InfoWindow\n\t\t\tiw.open(map, wpt);\n\t\t\tbacs0 ----})(kx, wpt);\n\t\t*/\n\t}\t// End of For Loop\n\n\t// Now adjust the map to fit our waypoints\n\tmap.fitBounds(bounds);\n\n\t// Generate the pathways to the cell towers\n\tgenPathways(waypoints);\n\n}",
"function createWaypoints(result) {\n\n // turn overview path of route into polyline\n var pathPolyline = new google.maps.Polyline({\n path: result.routes[0].overview_path\n });\n\n // get points at intervals of 85% of range along overview path of route\n var points = pathPolyline.GetPointsAtDistance(0.85 * range);\n\n // iterate over these points\n for (var i = 0, n = points.length; i < n; i++) {\n\n // find the closest charging station to that point\n var closeStation = getClosestStation(points[i]);\n\n // create waypoint at that station\n var newWaypoint = {\n location: closeStation.latlng,\n stopover: true\n };\n\n // add it to the waypoints array\n waypoints.push(newWaypoint);\n\n // add station info to station stops array\n stationStops.push(closeStation);\n\n // create invisible marker\n var marker = new google.maps.Marker({\n position: closeStation.latlng,\n map: map,\n icon: 'img/invisible.png',\n zIndex: 3,\n });\n\n // add to markers array\n markers.push(marker);\n }\n}",
"function addPremadeRoutes() {\n layerToAdd.forEach((tablica, index) => {\n var url = 'https://api.mapbox.com/directions/v5/mapbox/driving/' + tablica + '?geometries=geojson&steps=true&&access_token=' + mapboxgl.accessToken;\n var req = new XMLHttpRequest();\n req.responseType = 'json';\n req.open('GET', url, true);\n req.onload = function () {\n var jsonResponse = req.response;\n var coords = jsonResponse.routes[0].geometry;\n console.log(coords);\n // add the route to the map\n addRoute(coords);\n };\n req.send();\n function addRoute(coords) {\n // check if the route is already loaded\n let color = \"\";\n if (index === 0) color = '#e68580';\n if (index === 1) color = '#329999';\n if (index === 2) color = '#db9000';\n addRouteToTheMap(\"route\" + index, coords, color, 0.8);\n map.setLayoutProperty(\"route\" + index, 'visibility', 'none');\n };\n })\n }",
"function addAddressToRoute(){\n\tvar place = autocomplete.getPlace();\n\n\tif(place === undefined) { //Could not find a place associated with provided address.\n\t\t//TODO replace this with something less terrible\n\t\talert(\"Unable to locate provided address\");\n\t\treturn;\n\t}\n\n\tis_new_place = true;\n\tfor(var i = 0; i < route[\"places\"].length; i++){\n\t\tif (route.places[i].place_id == place.place_id) { \n\t\t\tis_new_place = false; \n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (is_new_place){\n\t\troute.places.push(place);\n updateWeather(place.geometry.location.lat(), place.geometry.location.lng());\n\t}\n\n\tupdateRoute();\n\n // Clear the input field.\n $(\"#autocomplete\").val(\"\");\n}",
"roadLineDrawtest()\n {\n this.direction.route({\n origin:{lng:-78,lat:39.137},\n destination:{lat:39.281,lng:-76.60},\n travelMode:google.maps.TravelMode.DRIVING\n },(r,s)=>{\n var pathPoints=r.routes[0].overview_path;\n var path=new google.maps.Polyline({\n path:pathPoints\n });\n\n path.setMap(this.map);\n });\n }",
"function handleRemoveWaypointClick(e) {\n var numWaypoints = $('.waypoint').length - 1;\n var currentId = parseInt($(e.currentTarget).parent().attr('id'));\n var featureId = $(e.currentTarget).parent().get(0);\n featureId = featureId.querySelector('.address');\n if (featureId) {\n featureId = featureId.id;\n } else {\n featureId = null;\n }\n //we want to show at least 2 waypoints\n if (numWaypoints > 2) {\n //'move' all successor waypoints up from currentId to currentId-1\n for (var i = currentId + 1; i < numWaypoints; i++) {\n var wpElement = $('#' + i);\n wpElement.attr('id', (i - 1));\n }\n $(e.currentTarget).parent().remove();\n } else {\n var wpElement = $(e.currentTarget).parent();\n var wpIndex = wpElement.attr('id');\n //delete waypoint\n wpElement.remove();\n //generate an empty waypoint\n var draftWp = $('#Draft');\n var newWp = draftWp.clone();\n newWp.attr('id', wpIndex);\n if (wpIndex > 0) {\n newWp.insertAfter($('#' + (wpIndex - 1)));\n } else {\n newWp.insertAfter(draftWp);\n }\n newWp.show();\n //decide which buttons to show\n var buttons = newWp.children();\n //show remove waypoint\n buttons[1].show();\n if (wpIndex == 1) {\n //show only move down button\n buttons[3].hide();\n buttons[2].show();\n } else if (wpIndex == 0) {\n //show only move up button\n buttons[2].hide();\n buttons[3].show();\n }\n //add event handling\n newWp = newWp.get(0);\n newWp.querySelector('.searchWaypoint').addEventListener('keyup', handleSearchWaypointInput);\n newWp.querySelector('.moveUpWaypoint').addEventListener('click', handleMoveUpWaypointClick);\n newWp.querySelector('.moveDownWaypoint').addEventListener('click', handleMoveDownWaypointClick);\n newWp.querySelector('.removeWaypoint').addEventListener('click', handleRemoveWaypointClick);\n newWp.querySelector('.searchAgainButton').addEventListener('click', handleSearchAgainWaypointClick);\n newWp.querySelector('.waypoint-icon').addEventListener('click', handleZoomToWaypointClick);\n }\n theInterface.emit('ui:removeWaypoint', {\n wpIndex: currentId,\n featureId: featureId\n });\n }",
"function assignStepsToMission(title, description, GeoPoint, missionObj) {\n\n var point = new Parse.GeoPoint(GeoPoint);\n var newStep = new Step();\n newStep.set(\"title\", title);\n newStep.set(\"description\", description);\n newStep.set(\"location\", point);\n\n var query = new Parse.Query(Mission);\n\n return newStep.save().then(function(savedStep) {\n\n return query\n .get(missionObj)\n .then(function(mission) {\n\n var stepRelation = mission.get(\"steps\");\n\n stepRelation.add(savedStep);\n\n return mission.save();\n\n });\n });\n}",
"function addToTestLoc(it, x, y, geo) {\n\tvar l = new Location({tsid: 'L1', items: []}, geo);\n\tvar p = new Player({tsid: 'P1'});\n\tl.players[p.tsid] = p;\n\tl.addItem(it, x, y);\n}",
"function handleMoveUpWaypointClick(e) {\n //index of waypoint\n var waypointElement = $(e.currentTarget).parent();\n var index = parseInt(waypointElement.attr('id'));\n var prevIndex = index - 1;\n var previousElement = $('#' + prevIndex);\n waypointElement.insertBefore(previousElement);\n //adapt IDs...\n previousElement.attr('id', index);\n waypointElement.attr('id', prevIndex);\n //define the new correct order\n var currentIndex = prevIndex;\n var succIndex = index;\n //-1 because we have an invisible draft waypoint\n var numWaypoints = $('.waypoint').length - 1;\n //decide which button to show\n if (currentIndex === 0) {\n //the waypoint which has been moved up is the first waypoint: hide move up button\n $(waypointElement.get(0).querySelector('.moveUpWaypoint')).hide();\n $(waypointElement.get(0).querySelector('.moveDownWaypoint')).show();\n } else {\n //show both\n $(waypointElement.get(0).querySelector('.moveUpWaypoint')).show();\n $(waypointElement.get(0).querySelector('.moveDownWaypoint')).show();\n }\n if (succIndex == (numWaypoints - 1)) {\n //the waypoint which has been moved down is the last waypoint: hide the move down button\n $(previousElement.get(0).querySelector('.moveUpWaypoint')).show();\n $(previousElement.get(0).querySelector('.moveDownWaypoint')).hide();\n } else {\n //show both\n $(previousElement.get(0).querySelector('.moveUpWaypoint')).show();\n $(previousElement.get(0).querySelector('.moveDownWaypoint')).show();\n }\n //adapt marker-IDs, decide about wpType\n theInterface.emit('ui:movedWaypoints', {\n id1: currentIndex,\n id2: succIndex\n });\n theInterface.emit('ui:routingParamsChanged');\n }",
"function addPointsToPath(point){\r\n path.push(point);\r\n $('#coordinates-container').html('');\r\n \r\n for(var i = 0; i < path.length; i++){\r\n $('#coordinates-container').html($('#coordinates-container').html() + 'x: ' + path[i].x + ' y: ' + path[i].y + '<br/>');\r\n }\r\n}",
"function addGrammarPoint(e) {\n e.preventDefault();\n\n // const point = grammarPoint.value;\n // const grade = level.value;\n // const ques = question.value;\n // const ans = answer.value;\n\n const newGrammarPoint = {\n grammarPoint: grammarPoint.value,\n level: classLevel.value,\n ques: question.value,\n ans: answer.value\n };\n gpDB.push(newGrammarPoint);\n console.log(gpDB);\n}",
"function addLocation() {\n\n personAwardLogic.addLocation($scope.awardLocation, personReferenceKey).then(function (response) {\n\n var locationId = null;\n if (appConfig.APP_MODE == 'offline') {\n locationId = response.insertId;\n } else {\n\n locationId = response.data.InsertId;\n }\n\n addPersonAward(locationId);\n\n }, function (err) {\n appLogger.error('ERR' + err);\n });\n }",
"createRoutePDO(name)\r\n {\r\n // Construct list of location objects containing lat and lng values.\r\n let locationList = [];\r\n for (let waypointIdx = 0; waypointIdx < this._waypoints.length; waypointIdx++)\r\n {\r\n let location = {\r\n lat: this._waypoints[waypointIdx].lat(),\r\n lng: this._waypoints[waypointIdx].lng()\r\n }\r\n // Push the location's attribute into locationList array.\r\n locationList.push(location);\r\n }\r\n \r\n // Construct and return object.\r\n let routePDO = {\r\n title: name,\r\n locations: locationList\r\n }\r\n return routePDO\r\n }",
"function leafletAddLineToMap(pointFrom, pointTo) {\n\n // define coordinates for line\n var latlngs = [\n pointFrom.geometry.coordinates,\n pointTo.geometry.coordinates\n ];\n\n // add a marker to the map\n var line = turf.lineString(latlngs);\n L.geoJson(line, {color:\"red\"}).addTo(map);\n}",
"AddPolyline(points, num_points, col, closed, thickness) {\r\n this.native.AddPolyline(points, num_points, col, closed, thickness);\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a handler Create a handler for a given effect | function _new_handlerx( effect_name, reinit_fun, return_fun, finally_fun,
branches0, handler_kind, handler_tag, wrap_handler_tag)
{
// initialize the branches such that we can index by `op_tag`
// regardless if the `op_tag` is a number or string.
const branches = new Array(branches0.length);
for(let i = 0; i < branches0.length; i++) {
const branch = branches0[i];
branches[branch.op_tag] = branch;
if (typeof op_tag !== "number") branches[i] = branch;
}
var shared_hinfo = null;
// return a handler function: `action` is executed under the handler.
return (function(action,local) {
// only resources need to recreate the `hinfo` due to the handlertag
// todo: also store the handler tag in the Handler instead of the Info
var hinfo = shared_hinfo;
if (hinfo==null) {
hinfo = new HandlerInfo(effect_name, reinit_fun, return_fun, finally_fun,
branches, 0, handler_kind, handler_tag);
}
if (wrap_handler_tag==null && shared_hinfo==null) {
shared_hinfo = hinfo;
}
// the handler action gets the resource argument (the identifier of the handler)
const haction = function() {
const resource = (wrap_handler_tag==null ? hinfo.handler_tag :
wrap_handler_tag(hinfo.handler_tag));
return yield_iter( action( resource ) ); // autoconvert from iterators
};
return _handle_action(hinfo, local, haction );
});
} | [
"createEffect() {\n return new FilterEffect()\n }",
"function createHandler(eventType) {\n xhr['on' + eventType] = function (event) {\n copyLifecycleProperties(lifecycleProps, xhr, fakeXHR);\n dispatchEvent(fakeXHR, eventType, event);\n };\n }",
"get effect() {\n if (!this._effect) this._effect = this.createEffect()\n return this._effect\n }",
"function handlerMaker( type ) {\n\t\tvar input;\n\t\tif (\"post\" === type ) {\n\t\t\tinput = \"body\";\n\t\t} else if ( \"get\" === type ) {\n\t\t\tinput = \"query\";\n\t\t}\n\n\t\treturn function ( req, res ) {\n\t\t\t// get the error code\n\t\t\tvar errorCode = parseInt( req[input].error, 10 );\n\t\t\tif ( !errorCode ) {\n\t\t\t\t// no code, return a splash page\n\t\t\t\tfs.readFile( __dirname + '/splash.html', function( err, data ) {\n\t\t\t\t\tif ( err ) {\n\t\t\t\t\t\tres.writeHead( 500, { \"content-type\": \"text/html\" });\n\t\t\t\t\t\tres.end( err + \"Lol, I couldn't load the splash page\" );\n\t\t\t\t\t}\n\t\t\t\t\tres.writeHead( 200, { \"content-type\": \"text/html\" });\n\t\t\t\t\tres.end( data );\n\t\t\t\t});\n\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// get the optional content\n\t\t\tvar content = req[input].content;\n\t\t\tif ( !content ) {\n\t\t\t\tcontent = '';\n\t\t\t}\n\n\t\t\t// see if there's a request for a delay\n\t\t\tvar delay = parseInt( req[input].delay, 10 );\n\t\t\tif ( delay ) {\n\t\t\t\tsetTimeout( sendData, delay );\n\t\t\t} else {\n\t\t\t\tsendData();\n\t\t\t}\n\n\n\t\t\tfunction sendData() {\n\t\t\t\tres.writeHead( errorCode, {} );\n\t\t\t\tres.end( content );\n\t\t\t}\n\t\t}\n\t}",
"call(actionType, ...params) {\n const handler = this.actions.get(actionType);\n if (!handler) {\n throw new Error(`A handler for ${actionType} has not been registered`);\n }\n return handler(...params);\n }",
"addScript(name, handler) {\n if (entity.scripts[name] === undefined) {\n entity.scripts[name] = [];\n }\n\n if (typeof handler === 'function') {\n entity.scripts[name].push(handler);\n }\n }",
"function addEffect() {\n numElements = $('#jsplumb-container > .jsplumb-box').length - 2;\n if (numElements < 5) {\n var effect = $('#effect-select').find('option:selected').val().toString().toLowerCase();\n\n // parse form data to JSON\n var formData = JSON.stringify(parseFormData($('#addEffectForm')));\n\n effect = effect.charAt(0).toUpperCase() + effect.slice(1).toLowerCase();\n\n var box = '<div class=\"jsplumb-box\" id=\"box-' + numElements + '\" ' +\n 'data-effect=\\'' + formData + '\\' ' +\n 'ondblclick=\"$(\\'#modal\\').modal(\\'show\\'); changeEffect(this);\">\\n' +\n ' <p>' + effect + '</p>\\n' +\n ' </div>';\n\n $('#jsplumb-container').append(box);\n\n $('#box-' + numElements).css({\n 'left': (1 + (numElements % 3)) * 20 + '%',\n 'top': (20 * (1 + 3 * Math.floor(numElements / 3))) + '%'\n });\n\n addEndPoints($('#box-' + numElements));\n } else {\n alert('Je kan maximaal 5 effecten tegelijk gebruiken!');\n }\n}",
"add(handler) {\n // Give it an ECS reference and let it set up its internal data\n // structure.\n handler.init(this.ecs, this.scriptRunner, this.firer);\n // Register all events the handler is interested in to it.\n for (let et of handler.eventsHandled()) {\n this.register(et, handler);\n }\n // Add it to the internal list for updates.\n this.handlers.push(handler);\n }",
"_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 }",
"handleExplosion() {\n this.handleHitAnimation();\n this.handleExplodeSelf();\n }",
"listenToAction(action, handler, deferExecution) {\n this.listenTo('action', action, handler, deferExecution);\n }",
"use(pattern, fn) {\n this.handlerChain = this.handlerChain.concat([{ pattern, fn }]);\n this.setMiddlewares();\n }",
"function SpawnEffect(origin) {\n\tvar le = AllocLocalEntity();\n\tle.leFlags = 0;\n\tle.leType = LE.FADE_RGB;\n\tle.startTime = cg.time;\n\tle.endTime = cg.time + 500;\n\n\tle.color[0] = le.color[1] = le.color[2] = le.color[3] = 1.0;\n\n\tvar refent = le.refent;\n\trefent.reType = RT.MODEL;\n\trefent.shaderTime = cg.time / 1000;\n\trefent.hModel = cgs.media.teleportEffectModel;\n\trefent.customShader = cgs.media.teleportEffectShader;\n\tQMath.AxisClear(refent.axis);\n\tvec3.set(origin, refent.origin);\n\trefent.origin[2] -= 24;\n}",
"function createNewEvent(eventName, myEventHanderFn,targetCreature){\n\t\n\tvar evt = document.createEvent(\"Event\");\n\tevt.initEvent(eventName,true,true);\n\n\t// Go through each argument passed - since we can pass multiple handers\n\tfor (var i = arguments.length - 1; i >= 0; i--) {\n\t\tvar currentArg = arguments[i];\n\t\t// if we find a call back function add\n\t\tif(typeof(currentArg) == \"function\"){\n\t\t\taddListener(eventName,currentArg,targetCreature);\n\t\t}\n\t};\n\t\n\t//dispatching of event later\n\t// document.dispatchEvent(evt); \n\treturn evt;\n}",
"function ConventionalHandler() {\r\n}",
"function actionCreator(action){\n return action\n}",
"static create() {\n return new FastHttpMiddlewareHandler();\n }",
"getDynamicMockHandler (options) {\n\t\tconst { uri, method, handler } = options;\n\t\tlogService.info(reqFm(method, this.port, uri), '(dynamic)');\n\t\treturn (req, res) => {\n\t\t\trequestLogService.setEntryType(req.id, 'dynamic');\n\t\t\treturn handler(req, res);\n\t\t};\n\t}",
"function EffectLayer(/** The Friendly of the effect in the scene */name,scene){this._vertexBuffers={};this._maxSize=0;this._mainTextureDesiredSize={width:0,height:0};this._shouldRender=true;this._postProcesses=[];this._textures=[];this._emissiveTextureAndColor={texture:null,color:new BABYLON.Color4()};/**\n * The clear color of the texture used to generate the glow map.\n */this.neutralColor=new BABYLON.Color4();/**\n * Specifies wether the highlight layer is enabled or not.\n */this.isEnabled=true;/**\n * An event triggered when the effect layer has been disposed.\n */this.onDisposeObservable=new BABYLON.Observable();/**\n * An event triggered when the effect layer is about rendering the main texture with the glowy parts.\n */this.onBeforeRenderMainTextureObservable=new BABYLON.Observable();/**\n * An event triggered when the generated texture is being merged in the scene.\n */this.onBeforeComposeObservable=new BABYLON.Observable();/**\n * An event triggered when the generated texture has been merged in the scene.\n */this.onAfterComposeObservable=new BABYLON.Observable();/**\n * An event triggered when the efffect layer changes its size.\n */this.onSizeChangedObservable=new BABYLON.Observable();this.name=name;this._scene=scene||BABYLON.Engine.LastCreatedScene;var component=this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);if(!component){component=new BABYLON.EffectLayerSceneComponent(this._scene);this._scene._addComponent(component);}this._engine=this._scene.getEngine();this._maxSize=this._engine.getCaps().maxTextureSize;this._scene.effectLayers.push(this);// Generate Buffers\nthis._generateIndexBuffer();this._genrateVertexBuffer();}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show the TeamTelephone settings per Team if it's not a TeamTelephone team, the activate form will be shown This form will show up only if you have the role of coordinator | function show(options)
{
//TODO fix directive
var tabs = angular.element('.nav-tabs-app li:not(:last)');
if (!options || !options.adapterId)
{
if (angular.isDefined(self.activateTTForm))
{//Empty form validation by changing the team
$scope.formActivateTT.$setPristine();
}
if ($rootScope.app.resources.role == 1 && !self.data.phoneNumbers.length)
{
$rootScope.notifier.error($rootScope.ui.options.noPhoneNumbers);
}
self.activateTTForm = true;
tabs.addClass('ng-hide');
}
else
{
self.scenarios = {
voicemailDetection: options["voicemail-detection-menu"] || false,
sms: options["sms-on-missed-call"] || false,
ringingTimeOut: options["ringing-timeout"] || 20,
useExternalId: options["useExternalId"] || false,
scenarioTemplates: options['test'] || []
};
self.activateTTForm = false;
tabs.removeClass('ng-hide');
//TODO fix this in a directive
(! $rootScope.app.domainPermission.teamSelfManagement
|| $rootScope.app.resources.role > 1)
? angular.element('.scenarioTab').addClass('ng-hide')
: angular.element('.scenarioTab').removeClass('ng-hide');
}
} | [
"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 showCompanyForm(mode, callback) {\n\n }",
"function goToTeamSelection(){\n clientValuesFactory.setActiveWindow(windowViews.selectTeam);\n }",
"function setAgentsFocus() {\r\n\t$('#tcAgentForm input:visible').first().focus();\r\n\tnextEnable();\r\n}",
"function teamMemExp() {\n var isFromTeamMem = PPSTService.getAddingTeamMem();\n if (isFromTeamMem) {\n // Expand \n $scope.expandASection('team-members-section', 7);\n PPSTService.setAddingTeamMem(false);\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 goToTeamPoints(){\n clientValuesFactory.setActiveWindow(windowViews.teamPoints);\n }",
"function showHidePassportRoleDiv(){ \n\tif(document.getElementById('empPassportMenuViewId').checked==true){\n\t\tdocument.getElementById('passportMenuSubTableDivId').style.display = \"block\";\n\t}else{\n\t\tdocument.getElementById('passportMenuSubTableDivId').style.display = \"none\";\n\t}\n}",
"viewBusinessRule() {\n BusinessRulesFunctions.viewBusinessRuleForm(false, this.state.uuid)\n }",
"function openAccountSetupTab() {\n let mail3Pane = Services.wm.getMostRecentWindow(\"mail:3pane\");\n let tabmail = mail3Pane.document.getElementById(\"tabmail\");\n\n // Switch to the account setup tab if it's already open.\n for (let tabInfo of tabmail.tabInfo) {\n let tab = tabmail.getTabForBrowser(tabInfo.browser);\n if (tab?.urlbar?.value == \"about:accountsetup\") {\n let accountSetup = tabInfo.browser.contentWindow.gAccountSetup;\n // Reset the entire UI only if the previously opened setup was completed.\n if (accountSetup._currentModename == \"success\") {\n accountSetup.resetSetup();\n }\n tabmail.switchToTab(tabInfo);\n return;\n }\n }\n\n tabmail.openTab(\"contentTab\", { url: \"about:accountsetup\" });\n}",
"function openAccountProvisionerTab() {\n let mail3Pane = Services.wm.getMostRecentWindow(\"mail:3pane\");\n let tabmail = mail3Pane.document.getElementById(\"tabmail\");\n\n // Switch to the account setup tab if it's already open.\n for (let tabInfo of tabmail.tabInfo) {\n let tab = tabmail.getTabForBrowser(tabInfo.browser);\n if (tab?.urlbar?.value == \"about:accountprovisioner\") {\n tabmail.switchToTab(tabInfo);\n return;\n }\n }\n\n tabmail.openTab(\"contentTab\", { url: \"about:accountprovisioner\" });\n}",
"function switchToExistingAccount() {\n clearError();\n console.log(\"Switch to existing account\");\n document.getElementById(\"existingAccountFieldSet\").style.display = 'block';\n document.getElementById(\"newAccountFieldSet\").style.display = 'none';\n }",
"function showControls(show) {\n if (show) {\n document.getElementById(\"funnelback-controls\").style.display = \"block\";\n document.getElementById(\"funnelback-not-detected\").style.display = \"none\";\n } else {\n document.getElementById(\"funnelback-controls\").style.display = \"none\";\n document.getElementById(\"funnelback-not-detected\").style.display = \"block\";\n }\n}",
"setInFrontier() {\n this.inFocus = false\n this.inFrontier = true\n }",
"function showAccountOptions() {\n accountOptionsRef.current.classList.remove(\"hidden\");\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 setShowPendingMembership(pendingApproval) {\n SpectrumOrganisationService.setPendingApproval(pendingApproval);\n }",
"function show_payment_form() {\n var $payment_el = $(this); // Using `this` is gross.\n var $form = $payment_el.parents('form');\n var payment_type = $payment_el.val();\n var class_name = 'payment-info-' + payment_type;\n $form.find('.payment-info').each(function () {\n var $el = $(this);\n if ($el.hasClass(class_name))\n $el.show();\n else\n $el.hide();\n });\n show_element($form);\n if (payment_type == 'paypal') {\n var $email = $form.find('[name=\"paypal_email\"]');\n if ($email.val() === '')\n $email.val($form.find('[name=\"email\"]').val());\n }\n }",
"function showConfigUser() {\n\n\tdocument.getElementById('sel_editor_font_size').value = v_editor_font_size;\n\tdocument.getElementById('sel_editor_theme').value = v_theme_id;\n\n\tdocument.getElementById('txt_confirm_new_pwd').value = '';\n\tdocument.getElementById('txt_new_pwd').value = '';\n\n\t$('#div_config_user').show();\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
parse the values to the appropriate types before saving the hotel | function parseValues(hotelToSave) {
hotelToSave.noOfRooms = parseInt(hotelToSave.noOfRooms);
hotelToSave.ratePerRoom = parseInt(hotelToSave.ratePerRoom);
/*hotelToSave.noOfAvailableRooms = parseInt(hotelToSave.noOfRooms);*/
hotelToSave.location = hotel.selectedLocation;
hotelToSave.contact.phone1 = parseInt(hotelToSave.contact.phone1);
hotelToSave.contact.phone2 = parseInt(hotelToSave.contact.phone2);
return hotelToSave;
} | [
"function dataCleanUp(data,type){\n\t\tif(type == 'places'){\n\t\t\tfor (var i = 0; i < data.features.length; i++) { /*[1]*/\n\t\t\t\tvar feature = data.features[i];\n\t\t\t\tif(feature.properties.tags.constructor !== Array){/*[2]*/\n\t\t\t\t\tvar tagsAarray = feature.properties.tags.split(',');\n\t\t\t\t\tfeature.properties.tags = tagsAarray;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn data;\n\t}",
"function doSaveMonster()\r\n{\r\n\tconsole.log(\"saving monster\");\r\n\tvar blank = bestiary[0]; \r\n\tblank.name = $('#m_name').val();\r\n\tblank.classes.class1.name = $('#m_class1').val(); \r\n\tblank.classes.class2.name = $('#m_class2').val();\r\n\tblank.alignment = $('#m_alignment').val();\r\n\tblank.hitPoints.hp = $('#m_hp').val();\r\n\tblank.hitPoints.hitDie = $('#m_hitdie').val(); \r\n\tblank.spatial.size = $('#m_size').val(); \r\n\tblank.combatInfo.ac = $('#m_ac').val(); \r\n\tblank.combatInfo.cr = $('#m_cr').val(); \r\n\tblank.combatInfo.melee = $('#m_melee').val(); \r\n\tblank.combatInfo.ranged = $('#m_ranged').val(); \r\n\tblank.combatInfo.ac_touch = $('#m_actouch').val(); \r\n\tblank.combatInfo.ac_flatFooted = $('#m_acflat').val(); \r\n\tblank.savingThrows.fort = $('#m_forts').val(); \r\n\tblank.savingThrows.ref = $('#m_refs').val(); \r\n\tblank.savingThrows.wil = $('#m_wils').val(); \r\n\r\n\tblank.abilityScores.str = $('#m_str').val(); \r\n\tblank.abilityScores.dex = $('#m_dex').val(); \r\n\tblank.abilityScores.con = $('#m_con').val(); \r\n\tblank.abilityScores.int = $('#m_int').val(); \r\n\tblank.abilityScores.wis = $('#m_wis').val();\r\n\tblank.abilityScores.cha = $('#m_cha').val(); \r\n\r\n\tblank.notes = $('#notesarea').val();\r\n\r\n\tblank.classes.class1.levels = $('#m_class1levels').val(); \r\n\tblank.classes.class2.levels = $('#m_class2levels').val(); \r\n\r\n\tvar skills = $('#m_skills').val(); \r\n\tskills = skills.split(','); \r\n\tfor(var i = 0; i < skills.length; i++)\r\n\t{\r\n\t\tblank.skills.push(skills[i]);\r\n\t}\r\n\r\n\tvar feats = $('#m_feats').val(); \r\n\tfeats = feats.split(','); \r\n\tfor(var i = 0; i < feats.length; i++)\r\n\t{\r\n\t\tblank.feats.push(feats[i]);\r\n\t}\r\n\r\n\tconsole.log(blank);\r\n\r\n\r\n\t var a = document.createElement('div'); \r\n\t $(a).addClass('iconarea')\r\n\t var b = document.createElement('div'); \r\n\t $(b).addClass('monstericon genericicon');\r\n\t $(a).append(b); \r\n\t var p = document.createElement('p'); \r\n\t $(p).html(blank.name);\r\n\t $(a).append(p); \r\n\t $('#newmonster').before(a);\r\n}",
"function fuelSavings() {\n var minMaxDict = {\n 'LPG' : undefined, \n 'Diesel' : undefined, \n 'Unleaded' : undefined,\n 'Premium Unleaded 95' : undefined,\n 'Premium Unleaded 98' : undefined\n };\n\n for (var i = 0; i < $scope.stations.length; i++) {\n var temp = angular.copy($scope.stations[i].fuels_offer);\n for (var fueltype in temp) {\n if (temp[fueltype] === null) {\n continue;\n }\n if (minMaxDict[fueltype] === undefined ) {\n minMaxDict[fueltype] = {};\n minMaxDict[fueltype].min = temp[fueltype];\n minMaxDict[fueltype].max = temp[fueltype];\n continue;\n } \n \n if (temp[fueltype] < minMaxDict[fueltype].min) {\n minMaxDict[fueltype].min = temp[fueltype];\n }\n\n if (temp[fueltype] > minMaxDict[fueltype].max) {\n minMaxDict[fueltype].max = temp[fueltype];\n }\n\n }\n }\n\n for (var fueltypeDict in minMaxDict) {\n $scope.calculator.types.push({label: fueltypeDict, value: minMaxDict[fueltypeDict].max - minMaxDict[fueltypeDict].min });\n }\n }",
"function save_type() {\n\tvar type = $('#type_list').find(\":selected\").val();\n\tupdate_cue_type(event_obj.cue_list, cue_id, type);\n}",
"function prepDataToSave(inspResults) {\n var retVal = {};\n\n //change the true/false checkboxes into Yes/No for enums \n $.each(inspResults, function (key, value) {\n\n if (value instanceof Object && !(value instanceof Array)) {\n $.extend(retVal, prepDataToSave(value));\n } else {\n if (value === true) {\n retVal[key] = \"1\";\n } else if (value === false) {\n retVal[key] = \"2\";\n } else {\n retVal[key] = value;\n }\n }\n });\n\n return retVal;\n }",
"async addSensorType(info) {\n const sensorType = validate('addSensorType', info);\n //@TODO\n\t //saving value in another variable as sensorType has timestamp and value as integer not number and while adding them into the array they were getting duplicated \n\tvar obj2={\n\t\tid: info.id,\n\t\tmanufacturer: info.manufacturer,\n\t\tmodelNumber: info.modelNumber,\n\t\tquantity: info.quantity,\n\t\tunit: info.unit,\n\t\tlimits: info.limits\n\t};\n\t let e=0;\n\t var y;\n\n\t for(y of this.sensorTypes){\n if(y.id==sensorType.id){\n y.manufacturer=obj2.manufacturer;\n y.modelNumber=obj2.modelNumber;\n y.quantity=obj2.quantity;\n\t\t y.unit=obj2.unit;\n\t\t y.limits=obj2.limits;\n e=e+1;\n\t\t \n\t\t \n\t }\n\t }\n\n\n\n\n\t\n\tif(e==0||this.sensorTypes.length==0){\n\t\tthis.sensorTypes.push(obj2);\n\t\t\n\t\t\n\t}\n\t \n\t \n\t \n\t\n\t\n }",
"function initTypes() {\n // Boolean for production/file supplied/online or not\n var online = false;\n var json_raw_data = null;\n var var_types_url = null;\n if (online) {\n // Retrieve from dataverse API\n } else {\n // Read from local'\n var_types_url = \"../../data/preprocess_4_v1-0.json\";\n }\n\n d3.json(var_types_url, function(json_data) {\n var json_variables = json_data['variables'];\n // Loop through all the variables\n for(var key in json_variables) {\n var current_variable = json_variables[key];\n // Boolean\n if (current_variable['binary'] == 'yes') {\n types_for_vars[key] = 'Boolean';\n } else {\n var current_variable_nature = current_variable['nature'];\n if (current_variable_nature == 'ordinal') {\n // Numerical\n types_for_vars[key] = 'Numerical';\n } else if (current_variable_nature == 'nominal') {\n // Categorical\n types_for_vars[key] = 'Categorical';\n }\n }\n }\n generate_modal4();\n });\n}",
"saveVisit() {\n\t\tthis.errorBox.style.display = \"none\";\n\n\t\t//Assemble the names.\n\t\tvar name = \"\";\n\t\tvar nameTokens = this.namesBox.querySelectorAll(\".name-token\");\n\t\tfor (var i = 0; i < nameTokens.length; i++) {\n\t\t\tvar token = nameTokens[i];\n\t\t\tif (name != \"\") {\n\t\t\t\tname += \", \";\n\t\t\t}\n\t\t\tname += nameTokens[i].innerText;\n\t\t}\n\n\t\t//If there are no names, display an error.\n\t\tif (name == \"\") {\n\t\t\tthis.errorBox.innerText = \"Du musst mindestens einen Namen eingeben.\";\n\t\t\tthis.errorBox.style.display = \"\";\n\t\t\treturn;\n\t\t}\n\n\t\t//Gather the served meals.\n\t\tvar meals = [ ];\n\t\tvar mealRows = this.servedMealsContainer.querySelectorAll(\".meal-row\");\n\t\tfor (var i = 0; i < mealRows.length; i++) {\n\t\t\tvar row = mealRows[i];\n\t\t\tvar mealTypeField = row.querySelector(\".meal-type-field\");\n\t\t\tvar mealField = row.querySelector(\".meal-field\");\n\n\t\t\t//If both fields are empty, skip this meal row.\n\t\t\tif (!mealTypeField.value && !mealField.value) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tmeals.push({\n\t\t\t\tmeal_type: mealTypeField.value,\n\t\t\t\tmeal: mealField.value\n\t\t\t});\n\t\t}\n\n\t\tvar visit = {\n\t\t\tname: name,\n\t\t\tdate: this.dateField.value,\n\t\t\tvisit_type: this.visitTypeSelect.value,\n\t\t\tvisit_purpose: this.visitPurposeField.value,\n\t\t\tmeals: meals,\n\t\t\tbrought_items: this.broughtItemsField.value,\n\t\t\tdescription: this.descriptionField.value\n\t\t};\n\n\t\tif (this.visitId) {\n\t\t\tvisit.visit_id = this.visitId;\n\t\t}\n\n\t\tthis.saveVisitRequest.send(visit);\n\t}",
"function SaveFlightCheckInDetails(obj) {\n var ata = $(\"#__tblflightarrivalflightinformation__\").find(\"#ATA\").val();\n var arrivalDate = $(\"#ArrivalDate\").attr(\"sqldatevalue\");\n\n var AircraftRegistration = $(\"#AircraftRegistrationNo\").val();\n\n if (arrivalDate == \"\" || arrivalDate == undefined) {\n ShowMessage(\"warning\", \"Warning\", \"Kindly enter Arrival Date and save flight details.\");\n return;\n }\n if (ata == \"\" || ata == undefined) {\n ShowMessage(\"warning\", \"Warning\", \"Kindly enter ATA and save flight details.\");\n return;\n }\n\n\n if (AircraftRegistration == \"\") {\n ShowMessage(\"warning\", \"Warning\", \"Kindly enter Aircraft Registration No.\");\n return;\n }\n\n if (currentCargoClassification == 4 && $(\"#AircraftRegistrationNo\").val() == \"\") {\n ShowMessage(\"warning\", \"Warning\", \"Kindly enter Truck Plate No.\");\n return;\n }\n\n if ((/\\d/.test($(\"#AircraftRegistrationNo\").val()) == false) && currentCargoClassification == 4 && $(\"#AircraftRegistrationNo\").val() != \"\") {\n ShowMessage(\"warning\", \"Warning\", \"Kindly provide minimum one Numeric character for Truck Plate No.\");\n return;\n }\n\n // var a = GetUserLocalTime(\"L\").split(' ')[1].substr(0, 5);\n var ArrivalDateATATime = arrivalDate + ' ' + ata + ':00';\n var CurrentCityDateTime = GetUserLocalTime(\"L\");\n\n if (Date.parse(ArrivalDateATATime) > Date.parse(CurrentCityDateTime)) {\n ShowMessage(\"warning\", \"Warning\", \"ATA can not be greater than current Date & Time at the station.\");\n return;\n }\n //var ArrivalDateATATime = arrivalDate + ' ' + ata + ':00';\n //var CurrentCityDateTime = GetUserLocalTime(\"L\");\n //if (Date.parse(ArrivalDateATATime) > Date.parse(CurrentCityDateTime)) {\n // ShowMessage(\"warning\", \"Warning\", \"ATA can not be greater than current time at the station.\");\n // return;\n // }\n\n var aircraftRegistration = $(\"#__tblflightarrivalflightinformation__\").find(\"#AircraftRegistrationNo\").val();\n var vendor = $(\"#Vendor\").val();\n var AgendOrVendorName = $(\"#Text_Vendor\").val();\n var grossWT = $(\"#__tblflightarrivalflightinformation__\").find(\"#GrossWeight\").val();\n var volumeWT = $(\"#__tblflightarrivalflightinformation__\").find(\"#VolumeWeight\").val();\n var aircraftTypeSNo = $(\"#AircraftType\").val();\n var IsNil = ($(\"#IsNil\").is(':checked')) ? \"1\" : \"0\";\n var FlightType = $('#FlightType:checked').val();\n //var TruckScheduleNo = \"\";\n //if (currentCargoClassification == 4) {\n // TruckScheduleNo = $(\"#TruckScheduleNo\").val();\n //}\n\n var FlightCheckInDetails = [];\n\n var flightCheckInData = { ATA: ata, ArrivalDate: arrivalDate, AircraftRegistration: aircraftRegistration, GrossWT: (grossWT == \"\") ? 0 : grossWT, VolumeWT: (volumeWT == \"\") ? 0 : volumeWT, AircraftTypeSNo: (aircraftTypeSNo == \"\") ? 0 : aircraftTypeSNo, AccountSNo: (vendor == \"\") ? 0 : vendor, AgendOrVendorName: AgendOrVendorName == \"\" ? \"\" : AgendOrVendorName, IsNil: IsNil, TruckScheduleNo: ($(\"#TruckScheduleNo\").val() == undefined || $(\"#TruckScheduleNo\").val() == '') ? '' : $(\"#TruckScheduleNo\").val(), TruckDate: $(\"#TruckDate\").attr(\"sqldatevalue\"), IsRFSAircraftType: (IsRFSAircraftType == undefined || IsRFSAircraftType == \"\") ? 0 : IsRFSAircraftType, FlightType: FlightType }\n\n FlightCheckInDetails.push(flightCheckInData);\n $.ajax({\n url: \"Services/Import/InboundFlightService.svc/SaveFlightCheckInDetails\", async: false, type: \"POST\", dataType: \"json\", cache: false,\n data: JSON.stringify({ FlightCheckInDetails: FlightCheckInDetails, DailyFlightSNo: currentDailyFlightSno }),\n contentType: \"application/json; charset=utf-8\",\n success: function (result) {\n if (result.split('?')[0] == \"0\") {\n tempATA = ata;\n tempArrivalDate = arrivalDate;\n if (result.split('?')[1] == \"4\") {\n $(\"#Text_AircraftType\").data(\"kendoAutoComplete\").enable(false);\n $(\"#Text_Vendor\").data(\"kendoAutoComplete\").enable(false);\n $(\"#AircraftRegistrationNo\").prop('disabled', true);\n }\n ShowMessage('success', 'Success', \"Details Saved successfully\", \"bottom-right\");\n }\n else if (result.split('?')[0] == \"2\")\n {\n ShowMessage('warning', 'Warning', 'TimeZone not found for Current City: '+ userContext.CityCode, \"bottom-right\");\n \n }\n\n //if (result == \"10002\") {\n // ShowMessage('warning', 'Warning', \"Truck not found.\", \"bottom-right\");\n // return;\n //}\n //if (result == \"10003\") {\n // ShowMessage('warning', 'Warning', \"Truck already exist.\", \"bottom-right\");\n // return;\n //}\n else {\n ShowMessage('warning', 'Warning', \"Unable to save data.\");\n }\n },\n error: function () {\n ShowMessage('warning', 'Warning', \"Unable to save data.\");\n }\n });\n\n}",
"function save_options() {\n\tvar type = $('#type_list').find(\":selected\").val();\n\tif (type == \"musicFile\") {\n\t\tvar param1 = Number($(\"#decalage\").val());\n\t\tvar param2 = Number($(\"#arret\").val());\n\t\tvar paramText = $(\"#paramText\").val();\n\t}\n\telse {\n\t\tvar param1 = Number($(\"#param1\").val());\n\t\tvar param2 = Number($(\"#param2\").val());\n\t}\n\n\tupdate_cue_options(event_obj.cue_list, cue_id, type, param1, param2, paramText);\n}",
"function buildTargetTypes() {\n let url = `https://pokeapi.co/api/v2/move-target/`;\n superagent.get(url)\n .then((results) => {\n results.body.results.forEach((result) => {\n let SQL = `INSERT INTO target_type(api_id, name) VALUES($1, $2);`;\n let values = [result.url.split('/')[6], result.name];\n\n client.query(SQL, values);\n })\n })\n}",
"function saveAndStore() {\n console.log('saveAndStore was run');\n\n i = allTrips.length;\n\n var beginTrip = document.getElementById(\"beginPoint\").value;\n var endTrip = document.getElementById(\"endPoint\").value;\n var typeTrip = document.getElementById(\"mode\").value;\n var tripDistance = document.getElementById(\"distance\").innerHTML;\n var tripDuration = document.getElementById(\"duration\").innerHTML;\n var tripArticleType = document.getElementById(\"articleType\").value;\n allTrips.push({start: beginTrip, destination: endTrip, type: typeTrip, distance: tripDistance, duration: tripDuration, choice: tripArticleType, id: i++});\n\n listTrip(\"all\", allTrips);\n \n // Searches for what type of trip was taken and runs listTrip to place it into that specific tab\n if(document.getElementById(\"mode\").value == \"DRIVING\") {\n var drivingTrips = allTrips.filter(function(trip){ return trip.type === \"DRIVING\"});\n listTrip(\"driving\", drivingTrips);\n } else if(document.getElementById(\"mode\").value == \"BICYCLING\") {\n var bicyclingTrips = allTrips.filter(function(trip){ return trip.type === \"BICYCLING\"});\n listTrip(\"biking\", bicyclingTrips);\n } else if(document.getElementById(\"mode\").value == \"TRANSIT\") {\n var transitTrips = allTrips.filter(function(trip){ return trip.type === \"TRANSIT\"});\n listTrip(\"public\", transitTrips);\n } else if(document.getElementById(\"mode\").value == \"WALKING\") {\n var walkingTrips = allTrips.filter(function(trip){ return trip.type === \"WALKING\"});\n listTrip(\"walking\", walkingTrips);\n }\n\n storeTrip();\n\n $(\"#beginPoint\").val(\"\");\n $(\"#endPoint\").val(\"\");\n $(\"#mode\").val(\"\");\n $(\"#articleType\").val(\"\");\n}",
"function editTruck() {\n\t//aey - get the id the user asked for and check if it exists\n\tvar editID = $(\"#id3\").val();\n\tif(!doesTruckExist(editID)) {\n\t\toutputMessage(\"ID does not exist\");\n\t\treturn -1;\n\t} else {\n\t\t//aey - get user value input and make sure it isn't blank\n\t\tvar editFieldValue = $(\"#newField\").val();\n\t\toutputMessage(\"hiiii\");\n\t\tif(editFieldValue = ''){\n\t\t\toutputMessage(\"New value cannot be blank\");\n\t\t\treturn -1;\n\t\t} else {\n\t\t\t//aey - get the text into a variable\n\t\t\tvar userChoice = document.getElementById(\"editDrop\").value;//$(\"#editFieldsDropdown\").text;\n\t\t\tvar index = findTruckWithID(editID);\n\t\t\t//aey - based on the selected drop-down option, parse the value\n\t\t\t\n\t\t\tvar couldParse = true;\n\t\t\tswitch (userChoice) {\n\t\t\t\tcase \"name\":\n\t\t\t\t\tif(parseValue(\"text\", editFieldValue)) {\n\t\t\t\t\t\tlocalTruckArray[index].name = String(editFieldValue);\n\t\t\t\t\t} \n\t\t\t\t\tbreak;\n\t\t\t\tcase \"loca\":\n\t\t\t\t\tif(parseValue(\"text\", editFieldValue)) {\n\t\t\t\t\t\tlocalTruckArray[index].location = String(editFieldValue);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"addr\":\n\t\t\t\t\tif(parseValue(\"text\", editFieldValue)) {\n\t\t\t\t\t\tlocalTruckArray[index].address = String(editFieldValue);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"cuis\":\n\t\t\t\t\tif(parseValue(\"text\", editFieldValue)) {\n\t\t\t\t\t\tlocalTruckArray[index].cuisine = String(editFieldValue);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"lat\":\n\t\t\t\t\tif(parseValue(\"lat\", editFieldValue)) {\n\t\t\t\t\t\tlocalTruckArray[index].lat = editFieldValue;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"lng\":\n\t\t\t\t\tif(parseValue(\"lng\", editFieldValue)) {\n\t\t\t\t\t\tlocalTruckArray[index].lng = editFieldValue;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"hrO\":\n\t\t\t\t\tif(parseValue(\"hr\", editFieldValue)) {\n\t\t\t\t\t\tlocalTruckArray[index].time.open.hour = editFieldValue;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"hrC\":\n\t\t\t\t\tif(parseValue(\"hr\", editFieldValue)) {\n\t\t\t\t\t\tlocalTruckArray[index].time.closed.hour = editFieldValue;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"minO\":\n\t\t\t\t\tif(parseValue(\"min\", editFieldValue)) {\n\t\t\t\t\t\tlocalTruckArray[index].time.open.minute = editFieldValue;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"minC\":\n\t\t\t\t\tif(parseValue(\"min\", editFieldValue)) {\n\t\t\t\t\t\tlocalTruckArray[index].time.closed.minute = editFieldValue;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\toutputMessage(\"Invalid dropdown selection\");\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}",
"function saveArrivedShipment(obj) {\n if (tempArrivalDate == \"\") {\n ShowMessage(\"warning\", \"Warning\", \"Kindly enter Arrival Date and save flight details.\");\n return;\n }\n\n if (tempATA == \"\") {\n ShowMessage(\"warning\", \"Warning\", \"Kindly enter ATA and save flight details.\");\n return;\n }\n\n //var flightNo = $(\"#FlightNo span\").text();\n\n var dflightSNo = $(obj).closest(\"tr\").find(\"td[data-column='DailyFlightSNo']\").text();\n var fFlightMasterSNo = $(obj).closest(\"tr\").find(\"td[data-column='FFMFlightMasterSNo']\").text();\n var uNo = $(obj).closest(\"tr\").find(\"td[data-column='ULDNo']\").text();\n var ffmShipmentTrans1 = $(obj).closest(\"tr\").find(\"td[data-column='FFMShipmentTransSNo']\").text();\n var arrivedShipmentSNo = $(obj).closest(\"tr\").find(\"td[data-column='ArrivedShipmentSNo']\").text();\n var awbNo = $(obj).closest(\"tr\").find(\"td[data-column='AWBNo']\").text();\n var origin = $(obj).closest(\"tr\").find(\"td[data-column='ShipmentOriginAirportCode']\").text();\n var destination = $(obj).closest(\"tr\").find(\"td[data-column='ShipmentDestinationAirportCode']\").text();\n var commodity = $(obj).closest(\"tr\").find(\"td[data-column='NatureOfGoods']\").text();\n var shc = $(obj).closest(\"tr\").find(\"td[data-column='SPHC']\").text();\n //var document = $(obj).closest(\"tr\").find(\"input[id=chkDocument]\").is(\":checked\");\n var awbPieces = $(obj).closest(\"tr\").find(\"td[data-column='Pieces']\").text();\n var buildDetails = $(obj).closest(\"tr\").find(\"td[data-column='LoadDetails']\").text();\n //var ffm = $(obj).closest(\"tr\").find(\"td:eq(17)\").text();\n var recvdPieces = $(obj).closest(\"tr\").find(\"#txtFAMAWBRcdPieces\").val();\n var grossWT = $(obj).closest(\"tr\").find(\"#txtGrossWt\").val();\n var piecesGWT = $(obj).closest(\"tr\").find(\"#txtActualGrossWt\").val()\n var remarks = $(obj).closest(\"tr\").find(\"#txtFAMAWBRemarks\").val();\n\n cfi.SaveUpdateLockedProcess(\"0\", dflightSNo, \"\", \"\", userContext.UserSNo, \"0\", \"Inbound Flight\", 0, \"\");\n\n\n //if ($(obj).closest(\"tr\").find($('#Chkamended').is(\":checked\"))=false)\n //{\n // ShowMessage('warning', 'Warning', \"Kindly select Amendment.\");\n // return;\n //}\n\n\n if (recvdPieces == \"\")\n ShowMessage('warning', 'Warning', \"Received pieces can not be left blank.\");\n\n else {\n var ULDDetails = [];\n var uldData = {\n //DailyFlightSNo: dflightSNo, FFMFlightMasterSNo: fFlightMasterSNo, FFMShipmentTransSNo: ffmShipmentTrans1, ULDNo: uNo, AWBNo: awbNo, Origin: origin, Destination: destination, Commodity: commodity, SHC: '1', Document: document == true ? 'Y' : 'N', AWBPieces: awbPieces, BuildDetails: buildDetails, FFM: '', RecvdPieces: recvdPieces, GrossWT: piecesGWT, Remarks: remarks\n DailyFlightSNo: dflightSNo, FFMFlightMasterSNo: fFlightMasterSNo, FFMShipmentTransSNo: ffmShipmentTrans1, ULDNo: uNo, AWBNo: awbNo, Origin: origin, Destination: destination, Commodity: commodity, SHC: '1', AWBPieces: awbPieces, BuildDetails: buildDetails, FFM: '', RecvdPieces: recvdPieces, GrossWT: piecesGWT, Remarks: remarks\n }\n\n ULDDetails.push(uldData);\n $.ajax({\n url: \"Services/Import/InboundFlightService.svc/SaveULDDetails\", async: false, type: \"POST\", dataType: \"json\", cache: false,\n data: JSON.stringify({ UldData: ULDDetails, ArrivedShipmentSNo: (arrivedShipmentSNo == \"\") ? 0 : arrivedShipmentSNo }),\n contentType: \"application/json; charset=utf-8\",\n success: function (result) {\n var resultData = result.split(\",\")\n if (resultData[0] == \"0\") {\n\n //$(obj).closest(\"tr\").find(\"td:eq(5)\").text(resultData[1]);\n $(obj).closest(\"tr\").find(\"td[data-column='ArrivedShipmentSNo']\").text(resultData[1]);\n $(obj).attr(\"value\", \"Arrived\");\n $(obj).attr(\"class\", \"btn btn-block btn-success btn-sm\");\n\n $(\"#ATA\").prop('disabled', true);\n $(\"#ATA\").css(\"cursor\", \"not-allowed\");\n $(\"#ArrivalDate\").data(\"kendoDatePicker\").enable(false);\n $(\"#ArrivalDate\").css(\"cursor\", \"not-allowed\");\n $(obj).closest(\"table\").closest(\"tr\").prev().find(\"input[type='button'][value='L']\").prop('disabled', false).css(\"cursor\", \"auto\");\n $(obj).closest(\"table\").closest(\"tr\").prev().find(\"input[type='button'][value='D']\").prop('disabled', false).css(\"cursor\", \"auto\");\n $(obj).closest(\"table\").closest(\"tr\").prev().find(\"input[type='button'][value='C']\").prop('disabled', false).css(\"cursor\", \"auto\");\n $(obj).closest(\"tr\").find(\"input[type='button'][value='E']\").prop('disabled', true).css(\"cursor\", \"not-allowed\").attr('class', '');\n if ($(obj).closest(\"table\").closest(\"tr\").prev().find(\"input[type='checkbox'][id='chkThroughULD']\").length > 0) {\n $(obj).closest(\"table\").closest(\"tr\").prev().find(\"input[type='checkbox'][id='chkThroughULD']\").closest(\"td[data-column='IsThroughULD']\").text(\"No\");\n }\n // if (resultData[2] == \"True\") {\n // var FlightMessage = $(\"#span#FlightNo\").text() + ' ' + $(\"#span#FlightDate\").text() + ' ' + 'Flight Arrived.';\n // sendSMS(971501160101, FlightMessage);\n //}\n\n\n\n\n // foreach (KeyValuePair<string, bool> list in dict)\n // {\n // if(list.Key==\"IMPORTSHIP\")\n // {\n // if (list.Value==true)\n // {\n\n // g.NestedColumn.Add(new GridColumn { Field = \"Isamended\", Title = \"Amendment\", Template = \"#if(Isamended>0){#<input id=\\\"Chkamended\\\" type=\\\"checkbox\\\" />#} #\", DataType = GridDataType.String.ToString(), Width = 30 });\n // }\n\n // }\n //}\n\n\n\n //$(obj).closest(\"table tr\").closest(\"td\").closest(\"td[data-column='Isamended']\").append(\"<input id='Chkamended' type='checkbox' />\");\n\n\n\n if (userContext.SpecialRights.IMPORTSHIP == true)\n {\n $((obj.parentElement.parentNode)).find(\"td[data-column='Isamended']\").html('');\n $((obj.parentElement.parentNode)).find(\"td[data-column='Isamended']\").append(\"<input id='Chkamended' type='checkbox' />\");\n\n }\n\n if ($((obj.parentElement.parentNode)).find(\"td[data-column='Isamendedvalue'] span\").text() == \"0\") {\n\n $((obj.parentElement.parentNode)).find(\"td[data-column='Isamendedvalue'] span\").text('1');\n }\n\n \n if (resultData[2] == \"True\") {\n $(\"#AddShipment\").prop('disabled', true);\n }\n else {\n $(\"#AddShipment\").removeAttr(\"disabled\");\n }\n ShowMessage('success', 'Success', \"Details Saved Successfully\");\n }\n else if (resultData[0] == \"1\") {\n ShowMessage('warning', 'Warning', resultData[1]);\n return;\n }\n else if (resultData[0] == \"100\") {\n ShowMessage('warning', 'Warning', 'Terminal not assign for current user.');\n return;\n }\n else\n ShowMessage('warning', 'Warning', \"Unable to save data.\");\n },\n error: function () {\n ShowMessage('warning', 'Warning', \"Unable to save data.\");\n }\n });\n }\n}",
"function validateInputs(hotelToSave){\n\t\tvar valid = true;\n\t\tif(isNaN(hotelToSave.ratePerRoom)) {\n\t\t\thotel.validationMessages.rateShouldBeNumber = true;\n\t\t\tvalid = false;\n\t\t}\n\t\tif( hotelToSave.contact !== undefined) {\n\t\t\tif(isNaN(hotelToSave.contact.phone1)) {\n\t\t\t\thotel.validationMessages.phone1ShouldBeNumber = true;\n\t\t\t\tvalid = false;\n\t\t\t}\n\t\t\t\n\t\t\tif(isNaN(hotelToSave.contact.phone2)) {\n\t\t\t\thotel.validationMessages.phone2ShouldBeNumber = true;\n\t\t\t\tvalid = false;\n\t\t\t}\n\t\t}\n\t\treturn valid;\n\t}",
"function validateTypesToStore(expType, savedType, index, variable) {\n if (expType === savedType) {\n if (savedType === 'i') {\n emit(`istore ${index}`, -1);\n } else if (expType === 's') {\n emit(`astore ${index}`, -1);\n }\n } else {\n console.error(`ERROR: types not matching`);\n process.exit(1);\n }\n }",
"function storeFishData() {\n\tconsole.log('Storing the fishy');\n\tvar idName = makeIDName($('#commonName').val());\n\tconsole.log(idName);\n if ( $('#key').val() == \"\" ) { var id = \"fish_\" + idName }\n else { var id = $('#key').val(); };\n\tvar fish\t\t\t\t= {} //create empty object\n\t\tfish._id\t\t\t= id;\n\t\tfish.commonName\t\t= ['Common Name:', $('#commonName').val()];\n\t\tfish.scientificName = ['Scientific Name:',$('#scientificName').val()];\n\t\tfish.photo\t\t\t= ['Photo:',$('#photo').val()];\n\t\tfish.family\t\t\t= ['Family:',$('#family').val()];\n\t\tfish.species\t\t= ['Species Type:',$('#speciesType').val()];\n\t\tfish.sizeMax\t\t= ['Maximum Size:',$('#maxSize').val()];\n\t\tfish.lifeSpan\t\t= ['Life Span:',$('#lifeSpan').val()];\n\t\tfish.habitat\t\t= ['Natural Habitat:',$('#naturalHabitat').val()];\n\t\tfish.tankSize\t\t= ['Minimum Tank Size:',$('#minTank').val()];\n\t\tfish.tankRegion\t\t= ['Tank Region:',$('#tankRegion').val()];\n\t\tfish.tankMates\t\t= ['Possible Tank Mates:',$('#possibleTankMates').val()];\n\t\tfish.description\t= ['Description:',$('#desc').val()];\n\t\tfish.tempRangeL\t\t= ['Low End °F:',$('#tempRangeLow').val()];\n\t\tfish.tempRangeH\t\t= ['High End °F:',$('#tempRangeHigh').val()];\n\t\tfish.phRangeL\t\t= ['Low End PH:',$('#phRangeLow').val()];\n\t\tfish.phRangeH\t\t= ['High End PH:',$('#phRangeHigh').val()];\n\t\tfish.hardnessRangeL\t= ['Low End Hardness:',$('#hardRangeLow').val()];\n\t\tfish.hardnessRangeH\t= ['High End Hardness:',$('#hardRangeHigh').val()];\n\t\tfish.breedingInfo\t= ['Breeding Info:',$('#breedingInfo').val()];\n\t\tfish.sexingInfo\t\t= ['Sexing Info:',$('#sexingInfo').val()];\n\t\tfish.diet\t\t\t= ['Diet:',$('#diet').val()];\n\t\tfish.temperment\t\t= ['Temperment:',$('#temperment').val()];\n\t\tfish.commonDeseases\t= ['Common Deseases:',$('#commonDiseases').val()];\n\tconsole.log('Fish = ' + fish);\n\tconsole.log('RevKey on Store: ' + $('#revkey').val());\n\t\n if ($('#revkey').val() != '') {\n \tconsole.log('rev is good and = ' + $('#revkey'));\n \tfish._rev = $('#revkey').val(); \n\t console.log('Updating: ' + fish);\n\t $.couch.db('laquaria').saveDoc(fish, {\n\t \tsuccess: function(data) {\n\t \t\tconsole.log('Saved: ' + data);\n\t \t}\n\t\t});\n\t\t$.mobile.changePage( \"fish_profile.html?_id=\" + id, {\n\t\t transition: \"pop\"\n\t\t});\n\n } else {\n\t console.log('Saving: ' + fish);\n\t $.couch.db('laquaria').saveDoc(fish, {\n\t \tsuccess: function(data) {\n\t \t\tconsole.log('Saved: ' + data);\n\t \t}\n\t\t});\n\t\t$.mobile.changePage( \"fish_profile.html?_id=\" + id, {\n\t\t transition: \"pop\"\n\t\t});\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}",
"if (conv === verdadero) {\n\t\t\t\t\t\t\t\t\tconv = convertidores [conv2];\n\n\t\t\t\t\t\t\t\t// De lo contrario, inserte el tipo de datos intermedio\n\t\t\t\t\t\t\t\t}",
"loadData(fleet) {\n for (let data of fleet) {\n switch (data.type) {\n\n case 'car':\n if (this.validateCarData(data)) {\n let car = this.loadCar(data);\n\n this.cars.push(car);\n\n } else {\n let e = new DataError('invalid data at car case', data);\n this.errors.push(e);\n }\n break;\n\n case 'drone':\n if (this.validateDroneData(data)) {\n let dron = this.loadDron(data);\n this.drons.push(dron);\n }\n break;\n\n default:\n let e = new DataError('invalid data at default case', data);\n this.errors.push(e);\n break;\n\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns number of energy resource this creep could harvest in the same / duration of moving dist. | function totalPotentialHarvests(creep, dist){
var workParts = creep.getActiveBodyparts(WORK)
var harvestsPerTick = workParts * 2
// Debug log
//console.log('workParts: ' + workParts + ', totalPotentialHarvests: ' + totalPotentialHarvests)
return harvestsPerTick * dist
} | [
"function energySpent() {\n // Calculate distance moved since last subtraction.\n var moved = ballBody.position.vsub(lastPos);\n\n // Only return if moved move than one square!\n if (moved.length() >= 0.98) {\n // Also update the path in map scene.\n updateLinePath();\n lastPos.copy(ballBody.position);\n return Math.round(moved.length());\n } else {\n return 0;\n }\n}",
"getEnergyPercent() {\n return this.getNetEnergy() / this.maxEnergy\n }",
"getNetEnergy() {\n return this.maxEnergy - this.fatigue\n }",
"function getFarmersFoodGain() {\n return Math.floor(_varibale.foodGain.farmer * _varibale.other.tf * _varibale.population.farmers);\n} // get food consumed by farmers",
"get distance(){\n\t\treturn(google.maps.geometry.spherical.computeLength(this._locations))\n\t}",
"get collectiveSongLength() {\n let time = 0;\n SongManager.songList.forEach(s => {\n time += typeof s.details.songLength == \"number\" ? s.details.songLength : 0;\n });\n return time;\n }",
"function numOfTotalEnemies() {\n\tconst totalEnemies = gameState.enemies.getChildren().length;\n return totalEnemies;\n}",
"getDistance(){\n\t\tif(this.TargetPlanet!== null){\n\t\t\treturn Math.abs(this.Group.position.y - this.TargetPlanet.y);\n\t\t}\n\t\telse return 0;\n\t}",
"calcRemainingTime() {\n return (Math.round((currentGame.endTime - Date.now()) / 100));\n }",
"get capacity() {\n return this.getNumberAttribute('capacity');\n }",
"get bestGuessAtCpuCount() {\n var realCpuCount = tr.b.dictionaryLength(this.cpus);\n if (realCpuCount !== 0)\n return realCpuCount;\n return this.softwareMeasuredCpuCount;\n }",
"count() {\n return Object.keys(this.locations).reduce(\n ((total, current) => total + Object.keys(this.locations[current]).length)\n , 0);\n }",
"function calculateHeight() {\n\t\treturn (val / capacity) * bottleHeight;\n\t}",
"function partyHPS() {\n let power = 10;\n if (!character.party) return power;\n //Add priest heals\n for (let key in parent.party_list) {\n let member = parent.party_list[key];\n let entity = getCharacterData()[member] || parent.entities[member];\n if (!entity || entity.ctype !== 'priest') continue;\n power += entity.attack * entity.frequency * damage_multiplier(-entity.rpiercing || 0) * 0.925;\n }\n return power * 0.9;\n}",
"elapsed() {\n if (this.sumElapsed === 0) {\n console.error('Got level duration as 0; bookkeeping bug.');\n }\n return this.sumElapsed;\n }",
"getTotalCycleCount () {\n\t\treturn this.getTotalInterval() / this.getReferenceInterval();\n\t}",
"function numberOfNewSoldiers(player) {\n return Math.floor(numberOfSquaresControlled(player) / costOfSoldier);\n}",
"get_respawn_time ()\n {\n let num_nearby = loot.players_in_cells[this.cell.x][this.cell.y].length;\n const adjacent_cells = loot.cell.GetAdjacentCells(this.cell.x, this.cell.y);\n\n // Get number of players near the lootbox\n for (let i = 0; i < adjacent_cells.length; i++)\n {\n num_nearby += loot.players_in_cells[adjacent_cells[i].x][adjacent_cells[i].y].length;\n }\n\n\n return Math.max(loot.config.respawn_times[this.type] / 2, loot.config.respawn_times[this.type] - (num_nearby * this.type * 0.5));\n }",
"totalFood() {\n return this.passengers.reduce((accumulator, passenger) => accumulator + passenger.food, 0)\n \n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Export graph to a PNG | function exportToPNG(graphName, target) {
var plot = $("#"+graphName).data('plot');
var flotCanvas = plot.getCanvas();
var image = flotCanvas.toDataURL();
image = image.replace("image/png", "image/octet-stream");
var downloadAttrSupported = ("download" in document.createElement("a"));
if(downloadAttrSupported === true) {
target.download = graphName + ".png";
target.href = image;
}
else {
document.location.href = image;
}
} | [
"function exportPngClick() {\n const filename = Data.IsSavedDiagram ?\n Data.SavedDiagramTitle :\n decodeURIComponent(Data.Filename);\n\n const svgXml = getSvgXml();\n const background = window.getComputedStyle(document.body).backgroundColor;\n exportPng(filename + '.png', svgXml, background);\n}",
"_downloadSvgAsPng() {\n savesvg.saveSvgAsPng(document.getElementById(\"svg\"), \"timeline.png\");\n }",
"function exportGraphicFiles()\r{\r var graphics = docData.selectedDocument.allGraphics;\r $.writeln(\"exportResolution Default: \" + app.pngExportPreferences.exportResolution);\r app.pngExportPreferences.pngQuality = PNGQualityEnum.MAXIMUM; // set MAXIMUM Resolution\r app.pngExportPreferences.exportResolution = scriptSettings.exportResolution;\r $.writeln(\"exportResolution setTo: \" + app.pngExportPreferences.exportResolution);\r for (var y = 0; y < graphics.length; y++){\r var graphic = graphics[y]; \r if (graphic.itemLink != null) {\r var exportFile = new File(docData.imagesFolder + \"/\" + graphic.itemLink.name + \".png\");\r $.writeln(\"export to: \" + exportFile);\r graphic.exportFile(ExportFormat.PNG_FORMAT,exportFile);\r }\r }\r}",
"saveToPNG() {\n this.downloadEl.download = 'pattar.png';\n this.downloadEl.href = this.renderCanvas.toDataURL(\"image/png\").replace(\"image/png\", \"image/octet-stream\");\n this.downloadEl.click();\n }",
"function downloadImage() {\n var link = document.createElement('a');\n link.download = 'diagram.png';\n link.href = myDiagram.makeImage().src;\n link.click();\n}",
"function download () {\n //get svg element.\n var svg = document.getElementById(\"visual\");\n\n //get svg source.\n var serializer = new XMLSerializer();\n var source = serializer.serializeToString(svg);\n\n //add name spaces.\n if(!source.match(/^<svg[^>]+xmlns=\"http\\:\\/\\/www\\.w3\\.org\\/2000\\/svg\"/)){\n source = source.replace(/^<svg/, '<svg xmlns=\"http://www.w3.org/2000/svg\"');\n }\n if(!source.match(/^<svg[^>]+\"http\\:\\/\\/www\\.w3\\.org\\/1999\\/xlink\"/)){\n source = source.replace(/^<svg/, '<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\"');\n }\n\n //add xml declaration\n source = '<?xml version=\"1.0\" standalone=\"no\"?>\\r\\n' + source;\n\n //convert svg source to URI data scheme.\n var url = \"data:image/svg+xml;charset=utf-8,\"+encodeURIComponent(source);\n\n //set url value to a element's href attribute.\n // var downloadButton = document.getElementById(\"download\");\n\n var downloadLink = document.createElement(\"a\");\n downloadLink.href = url;\n downloadLink.download = \"graph.svg\";\n document.body.appendChild(downloadLink);\n downloadLink.click();\n // document.body.removeChild(downloadLink);\n //you can download svg file by right click menu.\n}",
"function saveDrawnGraph(){\n topNodes = topData.nodes;\n topEdges = topData.edges;\n\n nodes = addNode(nodes, newNodeID, 'T', 300, 0);\n T = newNodeID;\n N = T + 1;\n E = topEdges.length;\n\n initialiseMatrices();\n\n for(var i = 0; i < topEdges.length; i++){\n var edge = topEdges.get(i);\n var from = edge.from, to = edge.to;\n if(from == -1){\n topEdges.update({id: i, from: T});\n edges[i].from = T;\n from = T;\n }\n if(to == -1) {\n topEdges.update({id: i, to: T});\n edges[i].to = T;\n to = T;\n }\n topAdjMatrix[from][to] = i;\n }\n\n topNodes.remove(-1);\n nodes.splice(1, 1);\n\n assignDataSets(nodes, edges);\n options.manipulation.enabled = false;\n}",
"function downloadCanvas() {\n saveCanvas('ohwow', 'png');\n}",
"function exportSvgClick() {\n const filename = Data.IsSavedDiagram ?\n Data.SavedDiagramTitle :\n decodeURIComponent(Data.Filename);\n\n const svgXml = getSvgXml();\n exportSvg(filename + '.svg', svgXml);\n}",
"doExport(diagram, format, savePath, bar) {\n if (!this.javeInstalled) {\n let pms = Promise.reject(planuml_1.localize(5, null));\n return { promise: pms };\n }\n //TODO: support custom jar definition once node-plantuml supports it\n // if (!fs.existsSync(config.jar)) {\n // let pms = Promise.reject(localize(6, null, context.extensionPath));\n // return <ExportTask>{ promise: pms };\n // }\n if (bar) {\n bar.show();\n bar.text = planuml_1.localize(7, null, diagram.title + \".\" + format.split(\":\")[0]);\n }\n let opts = {\n format,\n charset: 'utf-8',\n };\n if (path.isAbsolute(diagram.dir))\n opts['include'] = diagram.dir;\n //TODO: support environment vars (e.g. -DPLANTUML_LIMIT_SIZE=8192) once node-plantuml supports them\n //TODO: support misc puml args (e.g. -nometadata) once node-plantuml supports them\n //add user args\n //params.unshift(...config.commandArgs);\n let gen = plantuml.generate(opts);\n if (diagram.content !== null) {\n gen.in.end(diagram.content);\n }\n let pms = new Promise((resolve, reject) => {\n let buffs = [];\n let bufflen = 0;\n let stderror = '';\n if (savePath) {\n let f = fs.createWriteStream(savePath);\n gen.out.pipe(f);\n }\n else {\n gen.out.on('data', function (x) {\n buffs.push(x);\n bufflen += x.length;\n });\n }\n gen.out.on('finish', () => {\n let stdout = Buffer.concat(buffs, bufflen);\n if (!stderror) {\n resolve(stdout);\n }\n else {\n stderror = planuml_1.localize(10, null, diagram.title, stderror);\n reject({ error: stderror, out: stdout });\n }\n });\n //TODO: support stderr once node-plantuml exposes it\n // process.stderr.on('data', function (x) {\n // stderror += x;\n // });\n });\n return { promise: pms };\n }",
"export() {\n let data = [];\n let totalAnimationSteps = this.stepCount + 1;\n\n writeUint8(totalAnimationSteps, data);\n \n for (var i = 0; i < totalAnimationSteps; i++) \n {\n\n let totalColorsInCurrentStep = Object.keys(this.colors[i]).length;\n\n if (totalColorsInCurrentStep === 0 && totalAnimationSteps === 0)\n {\n console.log(\"Nothing to export.\")\n return;\n }\n\n writeUint16(totalColorsInCurrentStep, data);\n\n for (const color of Object.keys(this.colors[i])) \n {\n let rgb = hexToRgb(color)\n writeUint8(rgb.r, data)\n writeUint8(rgb.g, data)\n writeUint8(rgb.b, data)\n let ledsWithThisColor = this.getLedsWithColor(i, color);\n writeUint16(ledsWithThisColor.length, data)\n ledsWithThisColor.forEach(elem => {\n writeUint16(elem, data);\n })\n }\n\n\n }\n\n var blob = new Blob(data, { type: \"application/octet-stream\" });\n var blobUrl = URL.createObjectURL(blob);\n window.location.replace(blobUrl);\n\n var fileLink = document.createElement('a');\n fileLink.href = blobUrl\n fileLink.download = \"animation.bin\"\n fileLink.click();\n\n }",
"function exportGraphicLinks(parentElement,page)\r{\r $.writeln(\"exportGraphicLinks parentElement: \" + parentElement);\r var graphics = page.allGraphics;\r for (var y = 0; y < graphics.length; y++){\r graphic = graphics[y]; \r var graphicTag = parentElement.xmlElements.add(tags.graphicTag);\r var graphicNameTag = graphicTag.xmlElements.add(tags.graphicNameTag);\r if (graphic.itemLink != null) { \r graphicNameTag.contents = graphic.itemLink.name;\r graphicLinkTag = graphicTag.xmlElements.add(tags.graphicLinkTag);\r graphicLinkTag.contents = graphic.itemLink.filePath;\r // add a reference to the image\r imageLinkTag = graphicTag.xmlElements.add(tags.imageLinkTag);\r imageLinkTag.contents = \"images/\" + graphic.itemLink.name + \".png\";\r }\r }\r}",
"function plot() {\r\n \r\n //this gets the data to plot from parseData\r\n var plotData = parseData(data)\r\n \r\n //if else is to determine if the user wants their plot saved as a jpg file\r\n if (document.getElementById(\"save\").checked == false){\r\n \r\n //this creates the plot then renders it\r\n var graph = new CanvasJS.Chart(\"chartContainer\",{\r\n title: {\r\n text: document.getElementById(\"title\").value\r\n },\r\n axisX: {\r\n title: document.getElementById(\"xLabel\").value\r\n },\r\n axisY: {\r\n title: document.getElementById(\"yLabel\").value\r\n },\r\n data: [{\r\n type: \"line\",\r\n dataPoints: plotData\r\n }]\r\n });\r\n graph.render();\r\n }else{\r\n \r\n //this creates the plot, renders it and then saves it\r\n var graph = new CanvasJS.Chart(\"chartContainer\",{\r\n title: {\r\n text: document.getElementById(\"title\").value\r\n },\r\n axisX: {\r\n title: document.getElementById(\"xLabel\").value\r\n },\r\n axisY: {\r\n title: document.getElementById(\"yLabel\").value\r\n },\r\n data: [{\r\n type: \"line\",\r\n dataPoints: plotData\r\n }]\r\n });\r\n \r\n //the only reason this render is here is incase the user wants to save before they've tried plotting atleast once\r\n graph.render();\r\n graph.exportChart({format: \"jpg\"});\r\n }\r\n}",
"toImg(svgText, orgWidth, orgHeight, imgWidth, imgHeight) {\n\t\t// Create Canvas\n\t\tlet canvas = document.createElement('canvas');\n\t\tcanvas.width = imgWidth;\n\t\tcanvas.height = imgHeight;\n\t\tlet ctx = canvas.getContext(\"2d\");\n\n\t\t// show canvas\n\t\t//this._refRenderer.current.appendChild(canvas);\n\n\t\t// Create image\n\t\tlet img = document.createElement('img');\n\t\t// when loaded draw and save\n\t\timg.addEventListener('load', e=> {\n\t\t\t// draw image\n\t\t\tctx.drawImage(img,\n\t\t\t\t0, 0, orgWidth, orgHeight,\n\t\t\t\t//0, 0, imgWidth, imgHeight\n\t\t\t\t0, 0, orgWidth, orgHeight\n\t\t\t);\n\t\t\t// save image\n\t\t\tcanvas.toBlob(function(blob) {\n\t\t\t\tFileSaver.saveAs(blob, \"magboard.png\");\n\t\t\t});\n\t\t\t// clear everything\n\t\t\tthis._refRenderer.current.innerHTML = '';\n\t\t});\n\n\t\t// prepare svg to load image\n\t\tconst encodedString = 'data:image/svg+xml;base64,' + new Buffer(svgText).toString('base64');\n\t\timg.src = encodedString;\t// start loading image\n\t}",
"addExportCanvasListener(){\n uiElements.BTN_EXPORT.addEventListener(\"click\", () => {\n uiElements.CANAVS.toBlob(function(blob){\n saveAs(blob, \"image.png\");\n });\n });\n }",
"function saveFile(contentStr) {\n var blob = new Blob([contentStr], {type: \"text/plain;charset=utf-8\"});\n saveAs(blob, \"graphEdges.txt\");\n}",
"function exportArtboards(){\n\n // Loop through artboards\n for(var e = 0; e < doc.artboards.length; e++){\n \n // Store artboard name\n var artBoardName = doc.artboards[e].name;\n\n // Function returns a new file name\n targetFile = getNewName(artBoardName);\n\n // Returns SVG options\n svgSaveOpts = getSVGOptions();\n\n // Make current artboard active\n doc.artboards.setActiveArtboardIndex(e);\n\n // Export file as SVG\n sourceDoc.exportFile(targetFile, ExportType.SVG, svgSaveOpts)\n }\n}",
"function testFile(title, colors, width, height) {\n fs.readFile(title + \".nc\", 'utf8', function (err, code) {\n if (err) {\n return console.log(err);\n }\n var svg = cnctosvg.createSVG(code, colors, title, width, height, 2, true);\n fs.writeFile(title + \".svg\", svg, \"utf8\", function(err) {\n if(err) {\n console.log(\"Cannot write \" + title + \".svg file.\");\n } else {\n console.log(title + \".svg is created.\");\n }\n });\n });\n}",
"function downloadSVG(index) {\r\n var templateName = $(\"#page-template-\" + index).val();\r\n var color = $(\"input[name='page-color-\" + index + \"']:checked\").val();\r\n var fileName = getFileName(index);\r\n \r\n // Output to blob.\r\n var stream = blobStream();\r\n \r\n // Eventually download the blob as PDF.\r\n stream.on('finish', function() {\r\n saveAs(stream.toBlob('image/svg+xml'), fileName + '.svg');\r\n });\r\n\r\n // Generate the PDF.\r\n generateSVG(stream, templates[templateName], scrapedTexts, scrapedImages, {color: color});\r\n}",
"function exportImages() {\n let frontImage = frontCanvas.toDataURL({format: 'jpeg'});\n let backImage = backCanvas.toDataURL({format: 'jpeg'});\n\n clearGuides();\n\n console.log('Exporting canvases as images...');\n\n // return front and back images\n return(\n {\n 'front' : frontImage,\n 'back': backImage\n }\n )\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add Card Helper Function Referenced In: addInterest() uses cloneNode() to create a duplicate of the main card with id = 0 updates the id of all the objects for unique and separate calculations | function add(identification) {
// Get card div object and create duplicate, reassign unique id
var installmentCard = document.getElementById("card0");
var duplicate = installmentCard.cloneNode(true);
duplicate.id = "card" + identification;
var idString = '\'' + duplicate.id + '\''; //converts id to string for use in adding delete button (line 125-126)
// Updates id and name of form object in card div
var formDuplicated = duplicate.childNodes[1].childNodes[1];
formDuplicated.id = "interestCards" + identification;
// Updates id and name of years form-group
var yearsId = duplicate.childNodes[1].childNodes[1].childNodes[1].childNodes[3];
yearsId.id = "years" + identification;
yearsId.setAttribute('name', 'years' + identification);
// Updates id and name of interest form-group
var interestId = duplicate.childNodes[1].childNodes[1].childNodes[3].childNodes[3];
interestId.id = "interest" + identification;
interestId.setAttribute('name', 'interest' + identification);
// Updates id and name of output field and ensures the previous card's output value does not get duplicated through.
var outputField = duplicate.childNodes[1].childNodes[1].childNodes[5].childNodes[3];
outputField.id = "installment" + identification;
outputField.setAttribute('name', 'installment' + identification);
outputField.setAttribute('for', 'years' + identification + ' interest' + identification);
outputField.innerHTML = '';
//Updates id and name of calculate button
var calcButton = duplicate.childNodes[1].childNodes[1].childNodes[7].childNodes[1];
calcButton.id = "calculate" + identification;
calcButton.setAttribute('name', 'calculate' + identification);
// Add delete button to non-primary buttons
duplicate.innerHTML += '<div class=\"card-footer\"><button type=\"button\" class=\"btn btn-danger\" id=\"deleteButton\" onclick=\"deleteInterest('
+ idString + ')\">ลบ (Delete)</button></div>';
// Add duplicated card to Div 2 in index.html
installmentCard.parentNode.appendChild(duplicate);
} | [
"function addCard(clickedCard){\n matches.push(clickedCard)\n}",
"function addCard(){\n\tvar id = storage.id();\n\tvar newNode = document.createElement('div');\n\tnewNode.className = \"flashcard-set\";\n\tnewNode.id = id;\n\tnewNode.innerHTML = '<div class=\"term\"><textarea name=\"card-term\" data-card-term=\"'+id+'\" placeholder=\"Term\"></textarea></div><div class=\"definition\"><textarea name=\"card-definition\" data-card-definition=\"'+id+'\" placeholder=\"Definition\"></textarea></div><div class=\"type\">'+printTypeSelect(id)+'</div><div class=\"controls\"><div class=\"edit\" title=\"Edit\" style=\"visibility: hidden;\"><i class=\"fa fa-pencil\"></i></div><div class=\"remove\" title=\"Remove\" onclick=\"removeNewCard(\\''+id+'\\')\"><i class=\"fa fa-trash-o\"></i></div></div>';\n\tdocument.getElementById(\"content\").appendChild(newNode);\n}",
"function newCard() {\n $(card)\n // add card to the list\n .appendTo(\"#list\")\n .children(\".checkBtn\")\n .hover(hoverOnCheckDone)\n .end()\n // Set functions for all card buttons\n .children(\".checkBtn\")\n .click(toggleCardDoneClass)\n .end()\n .children(\".priStarBtn\")\n .click(showPriorityMenu)\n .end()\n .children(\".deleteBtn\")\n .click(deleteCard)\n .end()\n // Move keyboard input caret to text box of new card\n .children(\".itemText\")\n .focus();\n\n}",
"add(card) {\n this.cards.push(card);\n }",
"function addCard({ signal }) {\n const newCard = {\n front: formData.front,\n back: formData.back,\n };\n createCard(deckId, newCard, signal).then(() => updateDecks(signal));\n }",
"function addOneCard(){\n\t//add another card to user's hand to replace empty if possible\n\tif(tiles.length > 0){\n\t\t//add the next card in array to your hand\n\t\tlastCard.attr(\"src\", tiles[0]);\n\t\tlastCard.css(\"visibility\", \"visible\");\n\t\t pubnub.publish({\n\t\t channel: cardsChannel, \n\t\t message: {replacement: 1},\n\t\t callback : function(m){console.log(\"publishing in submit card (2nd): \" + m)},\n\t\t error: function(e){console.log(e)}\n\t\t});\n\n\t}\n\telse{\n\t\tlastCard.attr(\"src\", \"holder.png\");\n\t\tlastCard.css(\"visibility\", \"visible\");\n\t}\n}",
"function igAddToCard (gram) {\n var card = '<div class=\"card card-ig\"><div class=\"profile\"><div class=\"media-type pull-right\">' \n + '<i class=\"fa fa-instagram\"></i></div>' \n + '<div class=\"img-wrap\"><img class= \"img-circle\" src=\"' \n + gram.userPhoto + '\"></div>' \n + '<div class=\"user-wrap\"><h2 class=\"user\">' \n + gram.userName + '</h2><h3 class=\"handle\">@' \n + gram.user + '</h3></div></div><div id=\"ig-' \n + gram.id + '\" class=\"photo\"><img src=\"' \n + gram.photo + '\" /></div><div class=\"text\"><h2 class=\"message\">' \n + gram.text + '</h2><ul class=\"stats\"><li class=\"likes\"><i class=\"fa fa-heart\"></i></span><span class=\"count\">' \n + gram.likes + '</span></li><li class=\"time pull-right\"><span class=\"glyphicon glyphicon-time\"></span><span class=\"ago\">' \n + gram.time + '</span></li></ul></div></div>';\n return card;\n}",
"onCreditAdd() {\n\t\tconst newCredit = new Credit(this.props.uuidGenerator.generate());\n\t\tthis.order.credits.push(newCredit);\n\t}",
"function addCard() {\n displayCard([\"Card Text\", \"STATEMENT\"], true)\n editId = idCounter - 1\n isAddEdit = true\n openEditor()\n markDirty()\n }",
"add(card, index = 0){\n if(card instanceof Card){\n this._cards.splice(Math.min(index, this._cards.length -1), 0, card);\n }\n }",
"addCard(obj) {\n let card = new RenderableCard(obj, this, client);\n app.stage.table.addChild(card.container);\n this.interactiveObjects.set(obj.id, card);\n }",
"function addOpenCards(card) {\n\topenCards.push(card);\n}",
"addLike(cardId) {\n return fetch(this._baseUrl + \"/cards/likes/\" + cardId, {\n method: \"PUT\",\n headers: this._headers,\n }).then((res) => {\n return this._checkResponse(res);\n });\n }",
"function makeCard() {\n let card = document.createElement(\"div\");\n card.classList.add(\"card\");\n getRandomDesign(card);\n card.addEventListener(\"click\", cardSelect);\n $(\"game\").append(card);\n }",
"function addOpenCard( newOpenCard )\n{\n //==Adding the new card to the openCards array==============================================================\n openCards.push( newOpenCard );\n\n //==If there are 2 or more cards in the openCards array call checkMatch function============================\n if( clickCardCount >= 2 )\n {\n checkMatch( );\n\n //==Reset the card count for how many cards have been clicked=============================================\n clickCardCount = 0;\n }\n}",
"function drawSmallCard(index, parent, cardData, cardConfig) {\n /* this html should be added to page */\n /*\n <div class=\"s-g-col-4\">\n <div class=\"at-card at-card-stats\">\n <div class=\"card-header\" data-background-color=\"orange\">\n <i class=\"fa fa-gear\"></i>\n </div>\n <div class=\"card-content\">\n <p class=\"category\">My Title</p>\n <h3 class=\"title\">19%</h3>\n </div>\n <div class=\"card-footer\">\n <div class=\"stats\">\n <i class=\"fa fa-gear\"></i>This is a Material Card\n </div>\n </div>\n </div>\n </div>\n */\n\n /* define new column for rows */\n var col = $(\"<div></div>\");\n col.addClass(\"s-g-col-\" + cardConfig.cardWidth);\n\n /* define card */\n var card = $(\"<div></div>\");\n card.addClass(\"at-card\");\n card.addClass(\"at-card-stats\");\n\n /* add icon to card header */\n if (util.isDefinedAndNotNull(cardData.CARD_ICON)) {\n /* define card style when nothing is set */\n var searchString = \"fa-\";\n var cardHeader = $(\"<div></div>\");\n cardHeader.addClass(\"card-header\");\n\n if (util.isDefinedAndNotNull(cardData.CARD_HEADER_CLASS)) {\n cardHeader.addClass(cardData.CARD_HEADER_CLASS);\n }\n\n var icon = $(\"<i></i>\");\n\n /* check if it should be an icon or a background image */\n if (cardData.CARD_ICON && cardData.CARD_ICON.substr(0, searchString.length) === searchString) {\n var iconColor = (util.isDefinedAndNotNull(cardData.CARD_ICON_COLOR)) ? cardData.CARD_ICON_COLOR : \"white\";\n\n icon.addClass(\"fa\");\n icon.addClass(cardData.CARD_ICON);\n icon.css(\"color\", iconColor);\n\n if (util.isDefinedAndNotNull(cardData.CARD_HEADER_STYLE)) {\n /* set header style */\n cardHeader.attr(\"style\", cardData.CARD_HEADER_STYLE);\n } else {\n /* set header style default */\n if (!util.isDefinedAndNotNull(cardData.CARD_HEADER_CLASS)) {\n cardHeader.attr(\"style\", generateDefaultCardStyle(index));\n }\n }\n } else {\n if (util.isDefinedAndNotNull(cardData.CARD_HEADER_STYLE)) {\n cardHeader.attr(\"style\", cardData.CARD_HEADER_STYLE);\n }\n cardHeader.css(\"background-image\", \"url(\" + cardData.CARD_ICON + \")\");\n }\n\n cardHeader.append(icon);\n /* append header to cards */\n card.append(cardHeader);\n }\n\n /* define card body */\n var cardBody = $(\"<div></div>\");\n cardBody.addClass(\"card-content\");\n\n /* add title to body */\n if (util.isDefinedAndNotNull(cardData.CARD_TITLE)) {\n var title = $(\"<p></p>\");\n title.addClass(\"category\");\n title.html(cardData.CARD_TITLE);\n cardBody.append(title);\n cardHeader.css(\"padding\", \"15px\");\n } else {\n cardHeader.css(\"padding\", \"5px\");\n }\n\n /* add value to body */\n var value = $(\"<h2></h2>\");\n value.addClass(\"title\");\n if (util.isDefinedAndNotNull(cardData.CARD_VALUE)) {\n value.html(cardData.CARD_VALUE);\n }\n cardBody.append(value);\n\n /* append body to card */\n card.append(cardBody);\n\n /* define footer */\n var cardFooter = $(\"<div></div>\");\n cardFooter.addClass(\"card-footer\");\n\n /* define footer text */\n var cardFooterStats = $(\"<div></div>\");\n\n if (cardData.CARD_FOOTER) {\n cardFooterStats = $(\"<div></div>\");\n cardFooterStats.addClass(\"stats\");\n cardFooterStats.append(cardData.CARD_FOOTER);\n }\n\n /* add footer text to footer */\n cardFooter.append(cardFooterStats);\n\n /* add footer to card */\n card.append(cardFooter);\n\n /* add card to column */\n col.append(card);\n\n /* if link is set make the card clickable and add column to parent (rows) */\n if (cardData.CARD_LINK) {\n var link = $(\"<a></a>\");\n link.attr(\"href\", cardData.CARD_LINK);\n link.append(col);\n parent.append(link);\n } else {\n parent.append(col);\n }\n }",
"function memoryCard(name) {\n $card = $(`<li class=\"card\">\n <i class=\"fa fa-${name}\"></i>\n </li>`);\n\n $card.on(\"click\", function() {\n\n if (!$(this).hasClass('show open')) {\n\n $moves.text(++movesCount);\n\n if (!opened_cards.includes($(this))) {\n $(this).addClass(\"show open\");\n opened_cards.push($(this));\n\n }\n\n if (opened_cards.length == 2) {\n check_for_match();\n }\n\n if (movesCount % 10 == 0) {\n if (starCounts >= 0) {\n $('.stars').children()[starCounts - 1].remove();\n $('.stars').append('<li><i class=\"fa fa-star-o\"></i></li>');\n\n starCounts -= 1;\n }\n }\n }\n\n });\n\n return $card;\n}",
"function addCardAppData(e) {\n\n// const listId =e.target.closest('.oneLists').getAttribute('data-id');\n\n // const listInAppData2 = appData.lists.board.find((list)=> listId === list.id);\n\n //\n // const cardOfAppData = {\n // members: [],\n // text: 'Add new task',\n // id: newCard.getAttribute(\"data-id\"),\n // }\n // listInAppData2.tasks.push(cardOfAppData);\n\n const title = e.target.closest('.oneLists').querySelector('.tagText').textContent\n const id =e.target.closest('.oneLists').getAttribute('data-id');\n\n const listInAppData =returnListReference(id)\n // appData.lists.board.find((bord) => id === bord.id)\n const cardId= e.target.closest('.oneLists').querySelector('.ulForCards li:last-child');\n\n const cardOfAppData = {\n members: [],\n text: 'Add new task',\n id: cardId.getAttribute('data-id'),\n }\n listInAppData.tasks.push(cardOfAppData)\n //pushnigNewCard(listInAppData, cardId);\n\n}",
"function createCards(){\n\tfor (let i = 0; i < cards.length; i++) { \n\t\tlet newCard = document.createElement('div');\n\t\tnewCard.className = 'card';\n\t\tnewCard.setAttribute('data-card', cards[i]);\n\t\tnewCard.addEventListener('click', isTwoCards);\n\n/*\nthe game-board div is appened with child elements, which are also divs. Because \nthere are two cards, we append twice.\n*/\n\n\t\ttable.appendChild(newCard);\n\t\ttable.appendChild(newCard);\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get all products. Optional: if inStock is true, only products will available inventory will be shown. | function getAllProducts(parent, args) {
if (args.inStock) {
return productList.filter(product => product.inventory_count > 0);
} else {
return productList
}
} | [
"function getAllProducts () {\r\n return db.query(`SELECT * from products`).then(result => {\r\n return result.rows\r\n })\r\n}",
"function getProducts() {\n var params = getParams();\n params[\"categoryID\"] = $scope.categoryId;\n categoryApiService.getProductsByCategoryId(params).$promise.then(function(response) {\n var result = response.result || [];\n $scope.productsList = result;\n });\n }",
"function searchAllProducts() {\n let all_products = new Promise(function(resolve, reject) {\n setTimeout(function() {\n if(catalog.length > 0) {\n resolve(catalog);\n }\n else {\n reject(\"Catalog empty.\");\n }\n }, 1000); \n });\n\n return all_products;\n }",
"function loadAllProductInShop() {\n Product.getProductLive({ SearchText: '' })\n .then(function (res) {\n $scope.products = res.data;\n });\n }",
"function getAllProducts(onResultsLoaded) {\n connection.query('SELECT * FROM products', function (err, res) {\n if (err) throw err;\n onResultsLoaded(res);\n })\n}",
"findProducts() {\n var self = this;\n var products = [];\n\n self.initShoppingCart();\n self.req.session.shoppingCart.forEach(function(elem) {\n var product = { productId : elem.productId, quantity : elem.quantity };\n products.push(product);\n });\n\n return self.res.status(200).json(products);\n }",
"static async list(req, res) {\n const variations = _.filter(\n req.product.variations,\n variation => !variation.deleted,\n );\n\n return res.products_with_additional_prices(variations);\n }",
"function allInventory() {\n\n\t//Connection to Mysql to request data\n\tconnection.query(\"SELECT * FROM bamazon_db.products\", function(err, res) {\n\t\tif (err) throw err;\n\n\t\tvar t = new Table;\n\n\t\t//Organize inventory using easy-table\n\t\tres.forEach(function(product) {\n\t\t\tt.cell('Product Id', product.id)\n\t\t\tt.cell('Description', product.product)\n\t\t\tt.cell('Price', product.price)\n\t\t\tt.cell('Quantity', product.quantity)\n\t\t\tt.newRow()\n\t\t})\n\n\t\t//Display inventory in easy-table\n\t\tconsole.log(\"\\n\")\n\t\tconsole.log(t.toString())\n\n\t\t//Returns to top of manager block\n\t\tmanage();\n\t\t}\n\t)\n}",
"function viewProducts(){\n\tconnection.query('SELECT * FROM products', function(err,res){\n\t\tif (err) throw err;\n\t\tfor (var i = 0; i < res.length; i++) {\n\t\t\tconsole.log('ID: ' + res[i].id + '| sku: ' + res[i].sku +' | name: ' + res[i].product_name + \" | Price: $\" + res[i].price + \" | Quantity: \" + res[i].stock_quantity);\n\t\t};\n\t\tconsole.log('\\n');\n\t\tmanagerView();\n\t});\n}",
"async function _list_variants (products, ids, sizes={}, email=false, only_soh=true ){\n if (typeof ids === 'undefined' || ids === null){\n throw new VError(`ids parameter not usable`);\n }\n if (typeof ids === 'undefined' || ids === null){\n throw new VError(`products parameter not usable`);\n }\n\n let ret = await tradegecko.tradegecko_get_product_variants({\"ids\": ids});\n\n const available = [];\n\n /*\n * If only_soh is true then we only want to return stock on hand.\n */\n \n if (only_soh){\n for (let i = 0; i < ret.length; i++){\n const soh = ret[i].stock_on_hand - ret[i].committed_stock;\n if (soh > 0){\n available.push(ret[i]);\n }\n }\n\n ret = available;\n }\n \n /*\n * If email parameter is not false, then filter out variants already sent to \n * customer associated with this email\n */\n \n if (email){\n ret = await _filter_out_already_shipped_variants(products, ret, email);\n }\n \n /*\n * Filter out all variants that don't match the received sixe values\n */\n \n ret = await _filter_for_sizes(ret, sizes);\n \n return ret;\n}",
"static async getStoreInventory() {\n const storeInventory = storage.get(\"products\").value()\n return storeInventory\n }",
"function requestProducts(req, res){\n Product.find({}, function(err, response){\n res.send(JSON.stringify(response));\n });\n}",
"function getProductPrices()\n {\n $.getJSON(productPricesEndpoint, function (data) {\n prices = data;\n\n updateProductPrices();\n });\n }",
"function getAllStocks() {\n var deferred = $q.defer();\n $http.get(REST_SERVICE_URI + 'stocks')\n .then(\n function (response) {\n deferred.resolve(response.data);\n },\n function (err) {\n console.error('Error while fetching Stocks');\n deferred.reject(err);\n }\n );\n return deferred.promise;\n }",
"function selectAllCarts(req, res) {\n\tDB.Cart.find()\n\t.populate('items')\n\t.exec((err, carts) => { // send all users as JSON response\n\t\tif (err) { return console.log(\"index error: \" + err); }\n\t\tres.json(carts);\n\t});\n}//end of selectAllCarts()",
"function viewProducts() {\n console.log(chalk.green(\"\\n\\nBamazon - Manager View\\n\"));\n connection.query(\"SELECT * FROM products\\n\", function (err, res) {\n if (err) throw err;\n // called the function for the goods to be displayed\n createTable(res);\n });\n connection.end();\n}",
"function listProducts()\n{\n connection.query(\"SELECT * FROM products\", function(err, res)\n {\n if (err) throw err;\n console.log(\"You can select from these items\");\n for(i=0;i<res.length;i++)\n {\n console.log('Item ID ' + res[i].item_id + ' Product:' + res[i].product_name + ' Price: ' + res[i].price);\n }\n startOrder();\n })\n}",
"function getProducts(order, callback) {\n const date = moment(order.dataValues.createdAt).format('LLLL');\n order.date = date;\n\n const { items } = order.dataValues.cart;\n const productIds = Object.keys(items);\n\n models.Product.findAll({\n attributes: ['id', 'title'],\n where: { id: productIds }\n })\n .then(products => {\n let productsObject = {};\n products.forEach(product => {\n productsObject[product.id] = product.title;\n });\n order.items = generateArray(productsObject, items);\n callback();\n }) // END .then(products => {\n .catch(err => callback(err));\n} // END (order, callback) => {",
"async function getProductsForCartHistory() {\n\ttry {\n\t\tconst { rows } = await client.query(`\n\t\tSELECT title, description, image, \"imageDescription\"\n\t\tFROM products;`);\n\t\treturn rows;\n\t} catch (error) {\n\t\tthrow error;\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if node is ObjectPattern | function isObjectPattern(node) {
return node.type === "ObjectPattern";
} | [
"function object (thing) {\n return typeof thing === 'object' && thing !== null && array(thing) === false && date(thing) === false;\n }",
"function is_tagged_object(stmt,the_tag) {\n return is_object(stmt) && stmt.tag === the_tag;\n}",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === RelationshipLink.__pulumiType;\n }",
"function checkPattern(node) {\n\n let node1= new RegExp(node.getAttribute(\"pattern\"));\n\n if (node1.test(node.value)) {\n\n valid++;\n\n } else {node.style.borderColor = \"red\"\n };\n\n}",
"function check_generator(obj) {\r\n return typeof(obj) == 'object' && typeof(obj.next) == 'function'; \r\n }",
"function hasRequiredNodes(node) {\n\t\t\tif (typeof node !== 'object') {\n\t\t\t\tthrow \"hasRequiredNodes: Expected argument node of type object, \" + typeof node + \" given.\";\n\t\t\t}\n\n\t\t\tif (node.hasChildNodes()) {\n\t\t\t\tfor (var i = 0, len = node.childNodes.length; i < len; i++) {\n\t\t\t\t\tif (options.nodeTypes.indexOf(node.childNodes[i].nodeType) !== -1) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}",
"function isObject(thing) {\n return Object.prototype.toString.call(thing) === '[object Object]';\n}",
"function isValidObjectPath(path) {\n return path.match(/^(\\/$)|(\\/[A-Za-z0-9_]+)+$/);\n}",
"function $type(obj){\n\tif (!obj) return false;\n\tvar type = false;\n\tif (obj instanceof Function) type = 'function';\n\telse if (obj.nodeName){\n\t\tif (obj.nodeType == 3 && !/\\S/.test(obj.nodeValue)) type = 'textnode';\n\t\telse if (obj.nodeType == 1) type = 'element';\n\t}\n\telse if (obj instanceof Array) type = 'array';\n\telse if (typeof obj == 'object') type = 'object';\n\telse if (typeof obj == 'string') type = 'string';\n\telse if (typeof obj == 'number' && isFinite(obj)) type = 'number';\n\treturn type;\n}",
"function IsObjectSingleLevel(object) {\n let isSingleLevel = false;\n if (!(object && typeof object == 'object')) {\n return isSingleLevel;\n }\n\n const pathSample = Object.keys(object)[0];\n if (typeof pathSample != 'string') {\n return isSingleLevel;\n }\n\n isSingleLevel = pathSample.split('.').length > 1 ? false : true;\n return isSingleLevel;\n}",
"function hasTypeAnnotation (path: NodePath): boolean {\n if (!path.node) {\n return false;\n }\n else if (path.node.typeAnnotation) {\n return true;\n }\n else if (path.isAssignmentPattern()) {\n return hasTypeAnnotation(path.get('left'));\n }\n else {\n return false;\n }\n}",
"function isMembershipPatternValid(document) {\n\t\tif (document.interactionModel !== ldp.DirectContainer) {\n\t\t\t// not a direct container, nothing to do\n\t\t\treturn true\n\t\t}\n\n\t\t// must have a membership resouce\n\t\tif (!document.membershipResource) {\n\t\t\treturn false\n\t\t}\n\n\t\t// must have hasMemberRelation or isMemberOfRelation, but can't have both\n\t\tif (document.hasMemberRelation) {\n\t\t\treturn !document.isMemberOfRelation\n\t\t}\n\t\tif (document.isMemberOfRelation) {\n\t\t\treturn !document.hasMemberRelation\n\t\t}\n\n\t\t// no membership triple pattern\n\t\treturn false\n\t}",
"function Match(pattern, object, eq, assignments) {\n\tif (!assignments) {\n\t\tassignments = {};\n\t}\n\t// pattern is an array. match each corresponding element.\n\tif (pattern instanceof Array) {\n\t\tif(!(object instanceof Array) || pattern.length !== object.length) {\n\t\t\treturn false;\n\t\t}\n\t\tfor (var i = 0; i < pattern.length; i++) {\n\t\t\tif (!Match(pattern[i], object[i], eq, assignments)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn assignments;\n\t}\n\t// pattern is a string -- a variable. it may be free,\n\t// or already bound to an expression\n\tif (\"string\" === typeof pattern) {\n\t\tif (pattern.indexOf(\"@\") >= 0) {\n\t\t\tthrow \"Warning: bad pattern used with '\" + pattern + \"'\";\n\t\t}\n\t\tif (assignments[pattern]) {\n\t\t\tif (!eq( assignments[pattern] , object)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else {\n\t\t\tassignments[pattern] = object;\n\t\t}\n\t\treturn assignments;\n\t}\n\t// pattern is an atom. match exactly\n\tif (pattern instanceof Atom) {\n\t\tif (eq(pattern, object)) {\n\t\t\treturn assignments;\n\t\t}\n\t\treturn false;\n\t}\n\t// pattern is an expression. match its operator and operands\n\tif (pattern instanceof Expression) {\n\t\tif (pattern.operator != object.operator) {\n\t\t\treturn false;\n\t\t}\n\t\treturn Match(pattern.args, object.args, eq, assignments);\n\t}\n\tthrow \"Unknown pattern type.\";\n}",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === MountTarget.__pulumiType;\n }",
"function isParsedObject(x) {\n // eslint-disable-next-line no-implicit-coercion\n return !!(x && typeof x === 'object' && PARSER_OUTPUT_SYMBOL in x);\n}",
"matches(node, props) {\n return Element$1.isElement(node) && Element$1.isElementProps(props) && Element$1.matches(node, props) || Text.isText(node) && Text.isTextProps(props) && Text.matches(node, props);\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === Resolver.__pulumiType;\n }",
"static isObject(input) {\n return input !== null && !this.isArray(input) && typeof (input) === 'object';\n }",
"static isInstance(obj) {\n if (obj === undefined || obj === null) {\n return false;\n }\n return obj['__pulumiType'] === PrivateLinkService.__pulumiType;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
replace single dots, but not multiple consecutive dots | function dotsReplacer(match) {
if (match.length > 1) {
return match;
}
return '';
} | [
"function addDot(value, selection) {\n if (config.currencyCents === 0) {\n return value;\n }\n var dotPos = value.length - config.currencyCents;\n if (selection.start > dotPos) {\n selection.start = selection.start + 1;\n }\n if (selection.end > dotPos) {\n selection.end = selection.end + 1;\n }\n var end = value.substring(dotPos);\n for (var i = end.length; i < config.currencyCents; i++) {\n end = '0' + end;\n }\n return value.substring(0, dotPos) + '.' + end;\n }",
"function trimPeriods(str)\n {\n return str.replace(/^\\./, \"\").replace(/\\.$/, \"\");\n }",
"function setUpBetterPunctuation() {\n var els = document.querySelectorAll('h1, h2, h3, div')\n\n els.forEach(function(el) {\n var html = el.innerHTML\n\n if ((!el.querySelectorAll('*:not(br)').length) && \n (!el.classList.contains('no-smart-typography'))) {\n var html = el.innerHTML\n\n html = html.replace(/,/g, '<span class=\"comma\">\\'</span>')\n html = html.replace(/\\./g, '<span class=\"full-stop\">.</span>')\n html = html.replace(/…/g, '<span class=\"ellipsis\">...</span>')\n html = html.replace(/’/g, '\\'')\n\n el.innerHTML = html\n }\n })\n}",
"function formatResult(num) {\n num = num.toString();\n\n let start = num.indexOf(\".\");\n if (start === -1) return +num;\n\n let repeatNum = num[start];\n let count = 0;\n\n for (let i = start; i < num.length; i++) {\n if (num[i] === repeatNum) {\n count++;\n if (count === 3) {\n return +num.slice(0, start + 2);\n }\n } else {\n start = i;\n repeatNum = num[i];\n count = 1;\n }\n }\n return +num;\n}",
"function addDot() {\n\t\tdiv.innerHTML = div.innerHTML + '. ';\n\t\t//on incrémente dots\n\t\tdots++;\n\t\t//la fonction s'appelle elle même\n\t\tdotLoader();\n\t}",
"function splitSentences(text) {\r\n return text.replace(/([!?]|\\.\\.\\.)\\s+/g, \"$1. \").split(/[.;]\\s/);\r\n}",
"function stringLimitDots(input,length){\n\tif(input!=undefined){\n\t\tif(input.length>length)\n\t\t\treturn input.substring(0,length)+'...';\n\t\treturn input;\n\t}\n\telse return '';\n}",
"function translateNested(x){\n var newX = x;\n if (x.indexOf(\"(\")>0){\n // Find inner and outer terms.\n var innerStart = x.indexOf(\"(\");\n var innerEnd = x.indexOf(\")\");\n var inside = x.substring(innerStart+1,innerEnd);\n var outside = x.substring(0,innerStart);\n newX = inside+\".\"+outside;\n }\n return newX;\n }",
"function removeExtraStuff(state) {\n if (config.currency) {\n state.value = removeCurrencySignAndPadding(state.value, state.selection);\n state.value = removeCommas(state.value, state.selection);\n }\n state.posFromEnd = state.value.length - state.selection.end;\n state.sign = false;\n var dotPos = -1;\n if (config.allowNegative) {\n state.sign = getSign(state.value);\n state.value = clearSign(state.value);\n }\n if (config.currency) {\n state.value = removeDot(state.value, state.selection);\n }\n }",
"function formatExtensions() {\n\n if (opt.properties.validExtensions !== \"\") {\n var extensionList = opt.properties.validExtensions.replaceAll(\"*\", \"\");\n extensionList = extensionList.replaceAll(\";\", \",\");\n\n opt.properties.processedFileExtension = extensionList;\n }\n }",
"function normalize(w) {\n w = w.toLowerCase();\n var c = has(w);\n while (c != \"\") { //keep getting rid of punctuation as long as it has it\n var index = w.indexOf(c);\n if (index == 0) w = w.substring(1, w.length);\n else if (index == w.length - 1) w = w.substring(0, w.length - 1);\n else w = w.substring(0, index) + w.substring(index + 1, w.length);\n c = has(w);\n }\n return w;\n\n}",
"function replaceLessExtension(contents) {\n\treturn contents.replace(/\\.less\\b/g, \".css\");\n}",
"function xPronounce(sentence) {\n\treturn sentence.split(\" \").map(x => x.startsWith('x') && x.length === 1 ? 'ecks' : x.startsWith('x') ? 'z' + x.slice(1, x.length) : x.replace('x', 'cks')).join(\" \");\n}",
"function oneStar(dotfile) {\r\n return dotfile ? '(?!' + dotfileGlob + ')(?=.)' + star : (nodot + star);\r\n}",
"function str_replace(haystack, needle, replacement) {var temp = haystack.split(needle);return temp.join(replacement);}",
"function translateNested2(x){\n var newX = x;\n if (x.indexOf(\"(\")>0){\n // Find inner and outer terms.\n var innerStart = x.indexOf(\"(\");\n var innerEnd = x.indexOf(\")\");\n var inside = x.substring(innerStart+1,innerEnd);\n var outside = x.substring(0,innerStart);\n newX = inside+\"_\"+outside;\n }\n return newX;\n }",
"function stripExtension(url) {\n\tvar lastDotPos = url.lastIndexOf('.');\n\tif(lastDotPos > 0)\n\t\treturn url.substring(0, lastDotPos - 1);\n\telse\n\t\treturn url;\n}",
"function removeDot() {\n const dot = document.getElementById('etave-recorder-dot');\n if (dot) dot.parentElement.removeChild(dot);\n}",
"function removeLeadingZeros(value) {\n var i = 0;\n var lastLeadingZeroPos = -1;\n for (i = 0; i < value.length; i++) {\n if (value.charAt(i) === '0') {\n\tlastLeadingZeroPos = i;\n } else {\n\tbreak;\n }\n }\n var result = value.substring(lastLeadingZeroPos + 1);\n // Add zero before . back in\n if (result === \"\" || result.charAt(0) === '.') {\n result = '0' + result;\n }\n return result;\n }",
"function splitSentence() {\n var sentences = document.getElementsByClassName('script-line active')\n var x\n for (x of sentences) {\n x.innerHTML = \"<span>\".concat(x.innerHTML)\n x.innerHTML = x.innerHTML.replace(/ /g,\"</span> <span>\")\n x.innerHTML = x.innerHTML.slice(0,-7)\n d3.selectAll('.script-line.active >span').classed('sentence-word',true)\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read the csv and import the data to elasticsearch | function importData() {
let heroes = [];
// Read CSV file
fs.createReadStream('all-heroes.csv')
.pipe(csv({
separator: ','
}))
.on('data', (data) => {
heroes.push({
'id': data.id,
'name': data.name,
'description': data.description,
'imageUrl': data.imageUrl,
'secretIdentities': data.secretIdentities,
'aliases': data.aliases,
'partners': data.partners,
'universe': data.universe,
'gender': data.gender,
'suggest': [
{
"input": data.name,
"weight": 10
},
{
"input": data.aliases,
"weight": 5
},
{
"input": data.secretIdentities,
"weight": 5
},
]
});
})
.on('end', () => {
console.log('push data');
sendData(heroes).then(() => {
console.log('End');
client.close();
}, (err) => {
console.log('End because of an error');
console.trace(err);
client.close();
});
});
} | [
"function import_data_from_csv() {\n fetch(\"input.csv\")\n .then(v => v.text())\n .then(data => init_table_from_data(data))\n}",
"function readCSV(csv) {\n logger.info(\"Reading input CSV...\");\n\n csvtojson()\n .fromFile(csv)\n .on('json', (jsonObj) => {\n posts.push(jsonObj);\n })\n .on('done', (error) => {\n logger.info('Fetching countries...');\n for (i = 0; i < posts.length; i++) {\n done[i] = posts[i];\n // if it hasn't country already\n if (!done[i].country) {\n // if it can be found locally\n if (!!gc.get_country(Number(posts[i].location_latitude), Number(posts[i].location_longitude))) {\n done[i].country = gc.get_country(Number(posts[i].location_latitude), Number(posts[i].location_longitude)).name;\n doneCounter++;\n if (doneCounter == posts.length) {\n makeCSV();\n }\n // if we must use Google's API\n } else {\n\n function fnc(j) {\n if (useKey) {\n findCountries(j, \"https://maps.googleapis.com/maps/api/geocode/json\", { latlng: posts[j].location_latitude + \",\" + posts[j].location_longitude, key: process.env.GOOGLE_API_KEY });\n } else {\n setTimeout(function() { findCountries(j, \"https://maps.googleapis.com/maps/api/geocode/json\", { latlng: posts[j].location_latitude + \",\" + posts[j].location_longitude }); }, missCounter * pause);\n }\n }\n\n fnc(i);\n\n missCounter++;\n }\n } else {\n doneCounter++;\n }\n }\n });\n}",
"function parseCSV(file, query) {\n\t\n\t// Start timer\n\ttstart = performance.now();\n\t\n\t// Initialize the counters\n\tcntrparsed = 0\n\tcntrkept = 0\n\t\n\t// Initialize years array\n\tyears = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n\t\n\t// Create reference to contents of table\n\tlet tableRef = document.getElementById(\"finalTable\").getElementsByTagName(\"tbody\")[0];\n\t// Clean table of previous data\n\t// start from index 1 to skip header\n\twhile(tableRef.rows[0]) tableRef.deleteRow(0);\n\t\n\t// Show progress\n\tdocument.getElementById(\"results\").textContent = \"Searching...\";\n\t\n\t// Parse the .csv file with PapaParse\n\tPapa.parse(file, {\n\t\tdownload: true,\n\t\tstep: function(row) {\n\t\t\t// Display progress in the footer\n\t\t\tdocument.getElementById(\"results\").textContent = String(cntrparsed - 1) + \" articles done. Searching...\"\n\t\t\t// Increment the counter of articles\n\t\t\tcntrparsed++;\n\t\t\t// Pass each row to the addRow function\n\t\t\taddRow(row.data, tableRef, query);\n\t\t},\n\t\tcomplete: function(results) {\n\t\t\t// Stop timer\n\t\t\ttfin = performance.now();\n\t\t\t// Display the results in the footer\n\t\t\tdocument.getElementById(\"results\").textContent = \"Parsed \" + String(cntrparsed - 1) + \" articles and found \" + String(cntrkept) + \" results in \" + (tfin - tstart)/1000 + \" seconds\";\n\t\t\t// Create the 'articles per year' chart (chart.js)\n\t\t\tcreateChart(query, years);\n\t\t}\n\t});\n}",
"uploadSellsCsv(fileName,data) {\n let self=this;\n let parsedData=(Papa.parse(data));\n parsedData=parsedData.data[0];\n //Check if there is a file with the same name\n if(this.localStorageService.keys().indexOf('sells.'+fileName)!=-1){\n throw \"There is already a file with the same name.\";\n }else\n //If all of the fields exists\n if(parsedData.indexOf('selldate')!=-1 && parsedData.indexOf('amount')!=-1) {\n self.localStorageService.set('sells.'+fileName, Papa.parse(data,{header: true,skipEmptyLines: true}));\n }\n //If some of the fields doesnt exist, throw error, giving feedback of which fields are required in the file\n else{\n let missingFields='';\n if(parsedData.indexOf('selldate')==-1){\n missingFields+='selldate ';\n }\n if(parsedData.indexOf('sells')==-1){\n missingFields+='sells ';\n }\n throw \"Missing fields \"+missingFields+\"in CSV file.\";\n }\n }",
"function loadCSVfile() {\n return axios.get(EXTERNAL_CSV_FILE)\n .then((res) => {\n // In my case, the columns are located on the second line of the file\n // so I split the file per line and fetch the second line, and split by column\n const data = res.data.split('\\n').slice(1).join('\\n');\n return parseCSV(data);\n })\n .catch(e => {\n console.log('e', e);\n })\n}",
"function setupCsvData() {\n d3.csv(\"./data/flying-etiquette.csv\", function(data) {\n processDotsData(data);\n //this loop saves all answers form the dataset into a temporary array that can then be sorted and provides the output we need, the first column of the data is an id, which is irrelevant at this point, so the loop starts at 1\n for(let i = 1; i < data.columns.length; i++){\n //this saves the data needed for the outer ring in a seperate array\n columnsData.push(data.columns[i]);\n \n //creates a list of all the answers from every participant for a single question\n for(let j = 0; j < data.length; j++){\n tempData.push(data[j][data.columns[i]]);\n }\n \n countArrayElements(tempData, data.columns[i]);\n //reset the temporary list of answers for the next loop\n tempData = [];\n }\n });\n }",
"function readCSV(data) {\n var dataLines = data.split('\\r\\n');\n\n for(var i = 1; i < dataLines.length; ++i) {\n if(dataLines[i] === '') continue;\n entries.push(new RawEntry(dataLines[i].split(',')));\n }\n}",
"uploadEmployeesCsv(fileName,data) {\n let self=this;\n let parsedData=(Papa.parse(data));\n parsedData=parsedData.data[0];\n //Check if there is a file with the same name\n if(this.localStorageService.keys().indexOf('employees.'+fileName)!=-1){\n throw \"There is already a file with the same name.\";\n }else\n //If all of the fields exists\n if(parsedData.indexOf('lat')!=-1 && parsedData.indexOf('lng')!=-1){\n self.localStorageService.set('employees.'+fileName, data);\n }\n //If some of the fields doesnt exist, throw error, giving feedback of which fields are required in the file\n else{\n let missingFields='';\n if(parsedData.indexOf('lat')==-1){\n missingFields+='lat ';\n }\n if(parsedData.indexOf('lng')==-1){\n missingFields+='lng ';\n }\n throw \"Missing fields \"+missingFields+\"in CSV file.\";\n }\n }",
"uploadIssuesCsv(fileName,data) {\n let self=this;\n let parsedData=(Papa.parse(data));\n parsedData=parsedData.data[0];\n //Check if there is a file with the same name\n if(this.localStorageService.keys().indexOf('issues.'+fileName)!=-1){\n throw \"There is already a file with the same name.\";\n }else\n //If all of the fields exists\n if(parsedData.indexOf('submissiondate')!=-1 && parsedData.indexOf('customername')!=-1\n && parsedData.indexOf('customeremail')!=-1\n && parsedData.indexOf('description')!=-1\n && parsedData.indexOf('status')!=-1\n && parsedData.indexOf('closeddate')!=-1\n && parsedData.indexOf('employeename')!=-1){\n self.localStorageService.set('issues.'+fileName, Papa.parse(data,{header: true,skipEmptyLines: true}));\n }\n //If some of the fields doesnt exist, throw error, giving feedback of which fields are required in the file\n else{\n let missingFields='';\n if(parsedData.indexOf('submissiondate')==-1){\n missingFields+='submissiondate ';\n }\n if(parsedData.indexOf('customername')==-1){\n missingFields+='customername ';\n }\n if(parsedData.indexOf('customeremail')==-1){\n missingFields+='customeremail ';\n }\n if(parsedData.indexOf('description')==-1){\n missingFields+='description ';\n }\n if(parsedData.indexOf('status')==-1){\n missingFields+='status ';\n }\n if(parsedData.indexOf('closeddate')==-1){\n missingFields+='closeddate ';\n }\n if(parsedData.indexOf('employeename')==-1){\n missingFields+='employeename ';\n }\n throw \"Missing fields \"+missingFields+\"in CSV file.\";\n }\n }",
"function csvImportierenSelectColumns(editor, csv, header) {\n var selectEditor = new $.fn.dataTable.Editor();\n var fields = editor.order();\n\n for (var i = 0; i < fields.length; i++) {\n var field = editor.field(fields[i]);\n\n selectEditor.add({\n label: field.label(),\n name: field.name(),\n type: 'select',\n options: header,\n def: header[i]\n });\n }\n\n selectEditor.create({\n title: 'CSV-Spalten zuordnen',\n buttons: csv.length + ' Datensätze importieren',\n message: 'Wähle bitte die CSV-Spalten und das jeweils zugehörige Datenbank-Feld aus.'\n });\n\n selectEditor.on('submitComplete', function (e, json, data, action) {\n // Use the host Editor instance to show a multi-row create form allowing the user to submit the data.\n editor.create(csv.length, {\n title: 'Import bestätigen',\n buttons: 'Bestätigen',\n message: 'Klicke auf <i>Bestätigen</i> um ' + csv.length + ' Zeilen zu importieren. Du kannst den Wert für ein Feld überschreiben indem du hier etwas änderst:'\n });\n\n for (var i = 0; i < fields.length; i++) {\n var field = editor.field(fields[i]);\n var mapped = data[field.name()];\n\n for (var j = 0; j < csv.length; j++) {\n field.multiSet(j, csv[j][mapped]);\n }\n }\n });\n}",
"function loadCities() {\n\td3.csv(\"data/City_Coordinates.csv\").then(function(data) {\n\t\tif (data == undefined) {\n\t\t\tconsole.log(\"Failed to load file\");\n\n\t\t\treturn;\n\t\t}\n\t\tdata.forEach(function(d) {\n\t\t\tif (records[d.RegionName] != undefined) {\n\t\t\t\trecords[d.RegionName][\"latitude\"] = d.Latitude != \"\" ? d.Latitude : 0;\n\t\t\t\trecords[d.RegionName][\"longitude\"] = d.Longitude != \"\" ? d.Longitude : 0;\n\t\t\t}\n\t\t});\n\t});\n\n\t// Convert the records object to an array\n\tdata = Object.keys(records).map(function(key) { \n\t\treturn records[key]; \n\t});\n}",
"static parseAnnotationCsv(inputCsv){\n var parsed_val = d3.text(inputCsv, function(text) {\n // let data = d3.csv... ; // It was that before but that variable assignment isnt needed\n d3.csv.parseRows(text, function(d) { \n return d.map(Number);\n });\n });\n \n return parsed_val.then(data => {\n return data.split(',').map(function(item){\n return parseInt(item,10);\n })\n });\n }",
"function teLoadCSVFile (filePath) {\n \n console.log(\"start loading file - \"+filePath);\n var rawFile = new XMLHttpRequest();\n rawFile.overrideMimeType('text/plain'); // override default XML reader (syntax error)\n rawFile.open(\"GET\", filePath, true);\n \n // .onreadystatechange fires after rawFile.send()\n rawFile.onreadystatechange = function ()\n { \n if(rawFile.readyState === 4)\n { \n if(rawFile.status === 200 || rawFile.status == 0)\n { \n console.log(\"loaded \"+filePath)\n \n var rawFileContent = rawFile.responseText;\n var fileData = {empty: \"default - file was not handled correctly\"};\n fileData = handleCSV(rawFileContent);\n \n var metadata = getMetadata();\n\n for (metaProp in metadata) {\n dataset[metaProp] = metadata[metaProp];\n }\n dataset.measurement = fileData;\n \n // increase file load counter\n fileLoadCount += 1;\n console.log(\"file - processed and saved\");\n \n // check if all files are loaded\n checkFinished();\n \n }\n }\n }\n \n rawFile.send();\n \n }",
"loadCSVData(CSVData) {\n let transactionStrings = CSVData.split('\\n');\n for(let i = 1; i < transactionStrings.length; i++) { // skip first row since it is header\n let lineNumber = i + 1;\n let transactionString = transactionStrings[i];\n let transactionDetails = transactionString.split(',');\n if(transactionDetails.length === 5) {\n if(!this.addTransaction(moment(transactionDetails[0], 'DD/MM/YYYY', true), transactionDetails[1], transactionDetails[2], transactionDetails[3], transactionDetails[4])) {\n logger.warn('Could not process transaction on line ' + lineNumber + ': ' + this.lastAddTransactionError);\n this.lastDataLoadErrorCount++;\n }\n } else if(transactionString.length > 0) {\n logger.warn('Could not process transaction on line ' + lineNumber + ': Not enough fields provided.');\n this.lastDataLoadErrorCount++;\n }\n }\n return true;\n }",
"function buildFromCsv(csv) {\n var dataArray = csv.split(/(\\r\\n|\\n|\\r)/);\n var reader = new rowStore.CsvReader();\n var fieldInfo = (function () {\n reader.onItem(dataArray[0]);\n var result = {};\n for (var index in reader.columnNames) {\n result[reader.columnNames[index]] = { typeOfValue: \"string\" };\n }\n reader.onEnd(); // Reset, so we can reuse it for reading data rows from dataArray\n return result;\n })();\n return build(fieldInfo, dataArray, reader);\n }",
"function csvBatchExemplar()\n{\n\tvar csv = new CSV();\n\tcsv.__csvBatchExemplar = function()\n\t{\n\t\n\t\t//\tcreate field 7120 content\n\t\t// start volume\n\t\tvar v = (csv.line['Band Beginn'] == \"\" || !csv.line['Band Beginn']) ? \"\" : \"/v\" + csv.line['Band Beginn'];\n\t\tvar v2 = (csv.line['Band Beginn'] == \"\" || !csv.line['Band Beginn']) ? \"\" : csv.line['Band Beginn'];\n\t\t\n\t\tvar b2trenner = (csv.line['Band Beginn'] == \"\" || !csv.line['Band Beginn']) ? \"\" : \".\";\n\t\t\n\t\t// issue start\n\t\tvar h = (csv.line['Heft Beginn'] == \"\" || !csv.line['Heft Beginn']) ? \"\" : \",\"+ csv.line['Heft Beginn'];\n\t\t\n\t\t// start year\n\t\tvar b = (csv.line['Jahr Beginn'] == \"\" || !csv.line['Jahr Beginn']) ? \"\" : \"/b\" + csv.line['Jahr Beginn'];\n\t\tvar b2 = (csv.line['Jahr Beginn'] == \"\" || !csv.line['Jahr Beginn']) ? \"\" : csv.line['Jahr Beginn'];\n\t\t\n\t\t// volume end\n\t\tvar V = (csv.line['Band Ende'] == \"\" || !csv.line['Band Ende']) ? \"\" : \"/V\" + csv.line['Band Ende'];\n\t\tvar V2 = (csv.line['Band Ende'] == \"\" || !csv.line['Band Ende']) ? \"\" : csv.line['Band Ende'];\n\t\t\n\t\tvar E2trenner = (csv.line['Band Ende'] == \"\" || !csv.line['Band Ende']) ? \"\" : \".\";\n\t\t\n\t\t// issue end\n\t\tvar H = (csv.line['Heft Ende'] == \"\" || !csv.line['Heft Ende']) ? \"\" : \",\"+csv.line['Heft Ende'];\n\t\t\n\t\t// year end\n\t\tvar E = (csv.line['Jahr Ende'] == \"\" || !csv.line['Jahr Ende']) ? \"\" : \"/E\" + csv.line['Jahr Ende'];\n\t\tvar E2 = (csv.line['Jahr Ende'] == \"\" || !csv.line['Jahr Ende']) ? \"\" : csv.line['Jahr Ende'];\n\t\t\n\t\tif((csv.line['Band Ende'] == \"\" || !csv.line['Band Ende']) && (csv.line['Jahr Ende'] == \"\" || !csv.line['Jahr Ende'])) {\n\t\t\tV = \"-\";\n\t\t}\n\t\t\n\t\tvar bestandsangaben = v + b + V + E;\n\t\tvar bestandsangaben2 = v2 + b2trenner + b2 + h + \" - \" + V2 + E2trenner + E2 + H;\n\t\t\n\t\tvar movingWall = false;\n\t\tvar mw7140 = \"\";\n\t\tvar mw8032 = \"\";\n\t\tif(csv.line['Moving Wall'] && csv.line['Moving Wall'] != '')\n\t\t{\n\t\t\tmovingWall = csv.line['Moving Wall'].toString();\n\t\t\tvar mwTeile = movingWall.match(/([+-])(\\d)([YVMDI])/);\n\t\t\tmw7140 = \"\\n7140 \"+mwTeile[1]+mwTeile[3]+\"00\"+mwTeile[2];\n\t\t\tswitch(mwTeile[3]){\n\t\t\t\tcase \"Y\": var entity = \"Jahre\";\n\t\t\t\tbreak;\n\t\t\t\tcase \"V\": var entity = \"Jahrgänge\";\n\t\t\t\tbreak;\n\t\t\t\tcase \"M\": var entity = \"Monate\";\n\t\t\t\tbreak;\n\t\t\t\tcase \"D\": var entity = \"Tage\";\n\t\t\t\tbreak;\n\t\t\t\tcase \"I\": var entity = \"Hefte\";\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tmw8032 = \" [\"+mwTeile[1]+mwTeile[2]+\" \"+entity+\"]\";\n\t\t}\n\n\t\t\n\t//\tcreate value for field 7135\n\t\tvar lizenz = \"\";\n\t\tswitch(csv.code){\n\t\t\tcase \"nl\": lizenz = \"=x Nationallizenz\";\n\t\t\tbreak;\n\t\t\tcase \"ad\": lizenz = \"=x DFG-geförderte Allianz-Lizenz\";\n\t\t\tbreak;\n\t\t\tcase \"al\": lizenz = \"=x Allianz-Lizenz\";\n\t\t\tbreak;\n\t\t\tcase \"nk\": lizenz = \"=x Nationalkonsortium\";\n\t\t\tbreak;\t\t\t\n\t\t\tcase \"\": lizenz = \"\";\n\t\t\tbreak;\n\t\t\tdefault: lizenz = \"\";\n\t\t}\n\t\t\n\t\t\n\t\tapplication.activeWindow.command(\"show d\", false);\n\t\t// Sichert Inhalt des Zwischenspeichers, da dieser sonst durch copyTitle() überschrieben würde\n\n\t\ttry{\n\t\t\tvar clipboard = application.activeWindow.clipboard;\n\t\t} catch(e){\n\t\t\t// do nothing\n\t\t}\n\t\t// Kopiert Titel\n\t\tvar kopie = application.activeWindow.copyTitle();\n\t\tapplication.activeWindow.clipboard = clipboard;\n\t\t//Schleife von 1 bis 99, da max. 99 Exemplare pro Bibliothek erfasst werden können\n\t\tfor (var i = 1; i <= 99; i++) {\n\t\t\tvar vergleich = 7000 + i;\n\t\t\tif (kopie.indexOf(vergleich) == -1) {\n\t\t\t\tvar eingabe = vergleich + \" x\\n4800 \" + csv.eigene_bibliothek + \"\\n7120 \" + bestandsangaben + \"\\n7135 =u \" + csv.line['URL'] + lizenz + mw7140 + \"\\n8032 \" + bestandsangaben2 + mw8032 + \"\\n8034 \" + csv.text + \"\\n\";\n\t\t\t\t// Exemplarsatz anlegen und befüllen\n\t\t\t\tapplication.activeWindow.command(\"e e\" + i, false);\n\t\t\t\tif (application.activeWindow.status != \"ERROR\") {\n\t\t\t\t\tapplication.activeWindow.title.startOfBuffer(false);\n\t\t\t\t\tapplication.activeWindow.title.insertText(eingabe);\n\t\t\t\t}\n\t\t//\t\t\tsave buffer\t\t\n\t\t\t\treturn csv.__csvSaveBuffer(true,eingabe);\n\t\t\t}\n\t\t}\n\t}\n\tcsv.__csvSetCallback(csv.__csvBatchExemplar);\t\n\ttry\n\t{\t\n\t\tcsv.__csvConfig();\n\t\tcsv.__csvBatch();\n\t} \n\tcatch(e)\n\t{\n\t\tcsv.__csvError(\"csvBatchExemplar:\" + e);\n\t}\t\n}",
"function csvJSON(csv, fieldsToSelect) {\n var lines = csv.split(\"\\n\");\n var result = [];\n var headers = lines[0].split(\",\"); // Find location of required headers. -1 indicates data doesn't contain the header\n\n var indexesToSelect = fieldsToSelect.map(function (field) {\n return headers.indexOf(field);\n });\n\n for (var i = 1; i < lines.length; i++) {\n var obj = {};\n var currentline = lines[i].split(\",\");\n\n for (var j = 0; j < headers.length; j++) {\n if (indexesToSelect.includes(j)) obj[headers[j]] = currentline[j];\n } // Add a unix date to the date from the date field\n // Only push data to the result set if it has a valid date.\n\n\n var datePosition = headers.indexOf('date');\n\n if (datePosition != -1) {\n var date = currentline[datePosition];\n\n if (date != \"\") {\n obj[\"unixDate\"] = new Date(date).getTime() / 1000;\n result.push(obj);\n }\n }\n }\n\n return result; //JSON\n}",
"function csvJSONAllFields(csv) {\n var lines = csv.split(\"\\n\");\n var result = [];\n var headers = lines[0].split(\",\");\n\n for (var i = 1; i < lines.length; i++) {\n var obj = {};\n var currentline = lines[i].split(\",\");\n\n for (var j = 0; j < headers.length; j++) {\n obj[headers[j]] = currentline[j];\n } // Add a unix date to the date from the date field\n // Only push data to the result set if it has a valid date.\n\n\n var datePosition = headers.indexOf('date');\n\n if (datePosition != -1) {\n var date = currentline[datePosition];\n\n if (date != \"\") {\n obj[\"unixDate\"] = new Date(date).getTime() / 1000;\n result.push(obj);\n }\n }\n }\n\n return result; //JSON\n}",
"function Csv () {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If it's not 'staging' or 'production', then it should be 'staging' | function defaultStage(stage) {
let staging = 'staging'
let production = 'production'
if (stage !== staging && stage !== production)
stage = staging
return stage
} | [
"_is_testing() {\n return this.env != \"production\" && this.env != \"prod\";\n }",
"getUrl() {\n return process.env.ENVIRONMENT === \"DEV\" ? \"http://localhost:3001\" : \"prod\";\n }",
"function getStage(){\n return process.env['ALICE_STAGE'];\n}",
"function toggleStatusInProduction( commit ) {\n\n\t\tvar nextTesting = \"active\";\n\t\tvar nextStatus = _.cycle( [ \"pending\", \"pass\", \"fail\" ], commit.production.status );\n\n\t\tdeploymentService\n\t\t\t.updateCommitInProduction( deploymentID, commit.hash, nextTesting, nextStatus )\n\t\t\t.then(\n\t\t\t\tfunction handleResolve() {\n\n\t\t\t\t\t$log.info( \"Production commit [ %s ] updated.\", commit.hash );\n\n\t\t\t\t}\n\t\t\t)\n\t\t;\n\n\t}",
"checkEnvironment() {\n if (\n this.system.production &&\n Config.exists(path.join(this.dir, 'config.development.json')) &&\n !Config.exists(path.join(this.dir, 'config.production.json'))\n ) {\n this.ui.log('Running in development mode', 'cyan');\n this.system.setEnvironment(true, true);\n }\n }",
"function toggleTestingInProduction( commit ) {\n\n\t\tvar nextTesting = _.cycle( [ \"inactive\", \"active\" ], commit.production.testing );\n\t\tvar nextStatus = commit.production.status;\n\n\t\t// If the testing got reset, move the status back to a pending state.\n\t\tif ( nextTesting === \"inactive\" ) {\n\n\t\t\tnextStatus = \"pending\";\n\n\t\t}\n\n\t\tdeploymentService\n\t\t\t.updateCommitInProduction( deploymentID, commit.hash, nextTesting, nextStatus )\n\t\t\t.then(\n\t\t\t\tfunction handleResolve() {\n\n\t\t\t\t\t$log.info( \"Production commit [ %s ] updated.\", commit.hash );\n\n\t\t\t\t}\n\t\t\t)\n\t\t;\n\n\t}",
"function toggleTestingInStaging( commit ) {\n\n\t\tvar nextTesting = _.cycle( [ \"inactive\", \"active\" ], commit.staging.testing );\n\t\tvar nextStatus = commit.staging.status;\n\n\t\t// If the testing got reset, move the status back to a pending state.\n\t\tif ( nextTesting === \"inactive\" ) {\n\n\t\t\tnextStatus = \"pending\";\n\n\t\t}\n\n\t\tdeploymentService\n\t\t\t.updateCommitInStaging( deploymentID, commit.hash, nextTesting, nextStatus )\n\t\t\t.then(\n\t\t\t\tfunction handleResolve() {\n\n\t\t\t\t\t$log.info( \"Staging commit [ %s ] updated.\", commit.hash );\n\n\t\t\t\t}\n\t\t\t)\n\t\t;\n\n\t}",
"getBuildType() {\n this.buildType = process.argv[2] ? process.argv[2].split('-').join('') : 'development';\n }",
"async function setProdNodeEnv() {\n $.fancyLog(\"-> Setting NODE_ENV to production\");\n return process.env.NODE_ENV = \"production\";\n}",
"function toggleStatusInStaging( commit ) {\n\n\t\tvar nextTesting = \"active\";\n\t\tvar nextStatus = _.cycle( [ \"pending\", \"pass\", \"fail\" ], commit.staging.status );\n\n\t\tdeploymentService\n\t\t\t.updateCommitInStaging( deploymentID, commit.hash, nextTesting, nextStatus )\n\t\t\t.then(\n\t\t\t\tfunction handleResolve() {\n\n\t\t\t\t\t$log.info( \"Staging commit [ %s ] updated.\", commit.hash );\n\n\t\t\t\t}\n\t\t\t)\n\t\t;\n\n\t}",
"getGeneralSystemStatus() {\n const journey = this.props.spec.journey;\n if (journey.steps.SUBPROCESS_APP_LOAD_OR_EXEC\n && journey.steps.SUBPROCESS_APP_LOAD_OR_EXEC.state === 'STEP_ERRORED')\n {\n return 'app-error';\n }\n if (journey.steps.SUBPROCESS_LISTEN\n && journey.steps.SUBPROCESS_LISTEN.state === 'STEP_ERRORED')\n {\n return 'app-error';\n }\n return 'preparation-error';\n }",
"function computeApiHostname() {\n switch (process.env.CONTEXT) {\n case 'production':\n return process.env.PROD_API;\n case 'branch-deploy':\n case 'deploy-preview': // TODO Find now.sh url for deploy-preview instead of staging API\n return process.env.STAGING_API;\n default:\n return '';\n }\n}",
"validateEnvironmentNames() {}",
"function getScheduledName(arr) {\n var name = arr.shift()\n return [`${app}-production-${name}`, `${app}-staging-${name}`]\n }",
"function getEndpointsByEnvironment(){\n const env = getEnvironmentString();\n\n const envs = {\n \"develop01\": {\n \"stage\": \"develop01\",\n \"kasEndpoint\": \"https://api-develop01.develop.virtru.com/kas\",\n \"acmEndpoint\": \"https://acm-develop01.develop.virtru.com\",\n \"easEndpoint\": \"https://accounts-develop01.develop.virtru.com\",\n },\n \"staging\": {\n \"stage\": \"staging\",\n \"kasEndpoint\": \"https://api.staging.virtru.com/kas\",\n \"acmEndpoint\": \"https://acm.staging.virtru.com\",\n \"easEndpoint\": \"https://accounts.staging.virtru.com\",\n },\n \"production\": {\n \"stage\": \"production\",\n \"kasEndpoint\": \"https://api.virtru.com/kas\",\n \"acmEndpoint\": \"https://acm.virtru.com\",\n \"easEndpoint\": \"https://accounts.virtru.com\",\n }\n };\n\n return envs[env] || envs['production'];\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}",
"level() {\n const env = process.env.NODE_ENV || 'development';\n const isDevelopment = env === 'development';\n return isDevelopment ? 'debug' : 'warn';\n }",
"function getAppname() {\n return environment.name; //dont know if called\n}",
"function isDevMode() {\n let prefBranch = Services.prefs.getBranch(\"social.provider.\").QueryInterface(Ci.nsIPrefBranch2);\n let enable_dev = false;\n try {\n enable_dev = prefBranch.getBoolPref(\"devmode\");\n } catch(e) {}\n return enable_dev;\n}",
"function shouldDisableSSO () {\n\n if (!FLAG_DISABLE_SSO) return false;\n\n if (\n // Dev mode with saved API key\n process.env.NODE_ENV !== 'production' &&\n config.get('dev.apiKey') !== 'DEFAULT_DO_NOT_CHANGE_ME'\n ) {\n\n logger.warn([\n '⚠ SSO IS DISABLED.',\n '⚠ THIS IS A MUCH LESS SECURE WAY TO RUN THE APP.',\n `⚠ All backend API requests will use the API key starting with ${config.get('dev.apiKey').toString().substr(0,3)}...`\n ].join('\\n'));\n return true;\n \n } else if (\n // Dev mode without saved API key\n process.env.NODE_ENV !== 'production' &&\n config.get('dev.apiKey') === 'DEFAULT_DO_NOT_CHANGE_ME'\n ) {\n \n logger.warn('⚠ SSO IS DISABLED BUT YOUR CONFIG IS MISSING dev.apiKey.\\n⚠ REQUESTS TO API ENDPOINTS WILL PROBABLY FAIL.');\n return true;\n\n } else if (\n // Non-dev mode\n process.env.NODE_ENV === 'production'\n ) {\n\n logger.warn('⚠ SSO CAN\\'T BE DISABLED WHEN IN PRODUCTION MODE');\n return false;\n\n }\n\n return false;\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handler for the spinner change event | function onSpinnerChange() {
var $spinner = $(this);
var value = $spinner.spinner('value');
// If the value is null and the real value in the textbox is string we empty the textbox
if (value === null && typeof $spinner.val() === 'string') {
$spinner.val('');
return;
}
// Now check that the number is in the min/max range.
var min = $spinner.spinner('option', 'min');
var max = $spinner.spinner('option', 'max');
if (typeof min === 'number' && this.value < min) {
this.value = min;
return;
}
if (typeof max === 'number' && this.value > max) {
this.value = max;
}
} | [
"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}",
"onSelectionChange(cb) {\n this.on('selection-change', cb)\n }",
"function SEC_onButtonClick(event){SpinEditControl.onButtonClick(event)}",
"function onSelectedChanged(val) {\n scope.$emit('selectedchange', val);\n }",
"_listBoxChangeHandler(event) {\n const that = this;\n\n if ((that.dropDownAppendTo && that.dropDownAppendTo.length > 0) || that.enableShadowDOM) {\n that.$.fireEvent('change', event.detail);\n }\n\n that._applySelection(that.selectionMode, event.detail);\n }",
"function processChange(value) {\n //console.log(\"Calendar clicked\");\n //If we are working with the start input\n if(cntrl.getStartCal()) {\n cntrl.setSelectedStartDate(value); \n }\n //If we are working with the end input\n else {\n cntrl.setSelectedEndDate(value);\n }\n //Autoclose after selection\n cntrl.updateDateRange();\n }",
"function SEC_onEditControlKeyDown(event){SpinEditControl.onEditControlKeyDown(event);}",
"UPDATE_USER_SPINNER(state, payload){\n state.userSpinner = payload;\n }",
"function SEC_onEditControlKeyUp(event){SpinEditControl.onEditControlKeyUp(event);}",
"function onSelectionChange(){\n if (ui.amountBox.value > 0 && ui.icosBox.selectedIndex != 0 && ui.roundBox.selectedIndex != 0 && ui.currencyBox != 0) {\n onCalculateClick();\n }\n }",
"onSelectionChange(func){ return this.eventSelectionChange.register(func); }",
"_setOnChange() {\n let self = this;\n this.onChange = function() {\n self.value = self.innerGetValue(); // Update inner value\n if (self._onChangeCB) self._onChangeCB.call(self); // call user defined callback\n };\n this.innerMapOnChange(); // Map the event that will trigger onChange\n }",
"_onChange ( value ) {\n this.setState({ value });\n\n this._endTimeout();\n this._startTimeout( value );\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 percentChangeHandler(e) {\n\tvar value = parseInt(this.value);\n\tif(isNaN(value)) value = 0;\n\tif(value < 0) value = 0;\n\tif(value > 100) value = 100;\n\tthis.value = value;\n\n // If percent changed we need send updated configuration\n var $pin = this.parentNode.parentNode;\n var data = getPinData($pin);\n\n //console.log(data.pinNumber, data.pinType, data.value);\n makeUpdateConfiguration(data.pinNumber, data.pinType, data.value); \n}",
"function ChangeHandler() {\n PreviousSelectIndex = SelectIndex; \n /* Contains the Previously Selected Index */\n\n SelectIndex = document.forms[0].lstDropDown.options.selectedIndex;\n /* Contains the Currently Selected Index */\n\n if ((PreviousSelectIndex == (document.forms[0].lstDropDown.options.length - 1)) && (SelectIndex != (document.forms[0].lstDropDown.options.length - 1)) && (SelectChange != 'MANUAL_CLICK')) \n /* To Set value of Index variables */\n {\n document.forms[0].lstDropDown[(document.forms[0].lstDropDown.options.length - 1)].selected=true;\n PreviousSelectIndex = SelectIndex;\n SelectIndex = document.forms[0].lstDropDown.options.selectedIndex;\n SelectChange = 'MANUAL_CLICK'; \n /* Indicates that the Change in dropdown selected \n\t\t\tvalue was due to a Manual Click */\n }\n }",
"hideSpinner() {\n this.spinnerVisible = false;\n }",
"changeRotation_(event) {\n //Get slider element, read and convert value\n let slider = document.getElementById('rotationRange');\n let rotationDegrees = parseInt(slider.value);\n let rotationRadians = rotationDegrees * (Math.PI / 180);\n //Update map\n this.getMap().getView().setRotation(rotationRadians);\n //Update label\n document.getElementById('rotationLabel').innerHTML = 'Change rotation: (' + rotationDegrees + '°)';\n }",
"function SEC_onEditControlBlur(event){SpinEditControl.onEditControlBlur(event);}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handles error message on form fields that are not completed when other fields below are onChange | function handleFormGridError(event) {
// Checks which required fields to not hold a value
let fieldsWithoutValue = [];
let selectedField = false;
// Gets all fields without value
props.fields.map((field, index) => {
field.required && fieldsWithoutValue.push(index);
if (event.target.name === field.name) selectedField = index;
});
let fieldsShowError = [];
// Filters only fields that are before the selected field
fieldsWithoutValue.filter(item => {
item < selectedField && fieldsShowError.push(item);
});
setErrorFields(fieldsShowError);
} | [
"function validateForm(event) {\n var success = true;\n\n if (!validateName('input[name=\"billFirstName\"]', 'input[name=\"billLastName\"]', \"#error_bill_names_div\")) {\n success = false;\n }\n if (!validateAddress('input[name=\"billAddress\"]', 'input[name=\"billCity\"]', 'input[name=\"billState\"]', 'input[name=\"billZipCode\"]', \"#error_bill_address_div\")) {\n success = false;\n }\n if (!validatePhoneNumber('input[name=\"billPhoneArea\"]', 'input[name=\"billPhone3\"]', 'input[name=\"billPhone4\"]', \"#error_bill_phone_div\")) {\n success = false;\n }\n if (checkShipping) {\n if (!validateName('input[name=\"shipFirstName\"]', 'input[name=\"shipLastName\"]', \"#error_ship_names_div\")) {\n success = false;\n }\n if (!validateAddress('input[name=\"shipAddress\"]', 'input[name=\"shipCity\"]', 'input[name=\"shipState\"]', 'input[name=\"shipZipCode\"]', \"#error_ship_address_div\")) {\n success = false;\n }\n if (!validatePhoneNumber('input[name=\"shipPhoneArea\"]', 'input[name=\"shipPhone3\"]', 'input[name=\"shipPhone4\"]', \"#error_ship_phone_div\")) {\n success = false;\n }\n }\n if (!validatePaymentType()) {\n success = false;\n }\n if (!validateCardName()) {\n success = false;\n }\n if (!validateCardNumber()) {\n success = false;\n }\n if (!validateExpiration()) {\n success = false;\n }\n\n // Reset firstError back to false to reapply focus on next validation\n firstError = false;\n\n return success;\n}",
"function formValidation() {\n let nameField = document.getElementById(\"name\");\n let emailField = document.getElementById(\"mail\");\n let bioInfo = sections[0];\n let emailErrorPresent = document.getElementById(\"emailError\");\n let nameErrorPresent = document.getElementById(\"nameError\");\n let activitiesErrorPresent = document.getElementById(\"activitiesError\");\n\n if (nameValidation(nameField.value) === false && nameErrorPresent === null) {\n let nameMessage = document.createElement(\"p\");\n nameMessage.className = \"error-message\";\n nameMessage.textContent = \"Please enter your first and last name.\";\n nameMessage.id = \"nameError\";\n nameField.className = \"error\";\n bioInfo.insertBefore(nameMessage, nameField.nextElementSibling);\n } else if (nameValidation(nameField.value) && nameErrorPresent !== null) {\n nameField.className = \"\";\n bioInfo.removeChild(nameErrorPresent);\n }\n\n if (\n emailValidation(emailField.value) === false &&\n emailErrorPresent === null\n ) {\n let emailMessage = document.createElement(\"p\");\n emailMessage.className = \"error-message\";\n emailMessage.textContent =\n \"Please enter a correctly formatted email address. Ex: name@company.com\";\n emailMessage.id = \"emailError\";\n emailField.className = \"error\";\n bioInfo.insertBefore(emailMessage, emailField.nextElementSibling);\n } else if (emailValidation(emailField.value) && emailErrorPresent !== null) {\n emailField.className = \"\";\n bioInfo.removeChild(emailErrorPresent);\n }\n\n if (activitiesValidation() === false && activitiesErrorPresent === null) {\n let activitiesMessage = document.createElement(\"p\");\n activitiesMessage.className = \"error-message\";\n activitiesMessage.id = \"activitiesError\";\n activitiesMessage.textContent = \"Please select at least one activity.\";\n let activitiesTitle = document.getElementById(\"activities-title\");\n activitiesSection[0].insertBefore(\n activitiesMessage,\n activitiesTitle.nextElementSibling\n );\n } else if (activitiesValidation() && activitiesErrorPresent !== null) {\n activitiesSection[0].removeChild(activitiesErrorPresent);\n }\n\n let emailErrorPresentNow = document.getElementById(\"emailError\");\n let nameErrorPresentNow = document.getElementById(\"nameError\");\n let activitiesErrorPresentNow = document.getElementById(\"activitiesError\");\n if (\n nameErrorPresentNow !== null ||\n emailErrorPresentNow !== null ||\n activitiesErrorPresentNow !== null\n ) {\n return false;\n }\n return true;\n}",
"function formHasErrors()\n{\n\t// Code below here\n\tlet errorFlag = false;\n\n\tlet requiredFields = [\"email\",\"password\",\"confirm\"];\n\n\n\tfor(let i=0; i < requiredFields.length; i++){\n\t\tlet textField = document.getElementById(requiredFields[i]);\n\n\t\tif(!formFieldHasInput(textField)){\n\t\t\tdocument.getElementById(requiredFields[i] + \"_error\").style.display = \"block\";\n\t\t\terrorFlag = true;\n\t\t}else{\n\n\t\t\tif(requiredFields[i] == \"email\") errorFlag = emailAddressIsInvalid(errorFlag);\n\t\t\tif(requiredFields[i] == \"confirm\") errorFlag = matchConfirmAndPassword(errorFlag);\n\t\t}\n\t}\n\n\treturn errorFlag;\n}",
"function clearErrorMessage(){\n\t$('.group input').keyup(function(){\n\t\t$('.group input').each(function(){\n\t\t\tif($(this).val().length > 0){\n\t\t\t\tdisplayErrorMessage('');\n\t\t\t}\n\t\t})\n\t})\n\t$('.group select').on('change', function(event){\n\t\tevent.preventDefault();\n\t\tdisplayErrorMessage('');\n\t})\n}",
"function fm_remove_validate_error_message(){\n jQuery(\".fm-validate\").each(function() {\n jQuery(this).on(\"keypress change\", function () {\n jQuery(this).parent().find(\".fm-validate-description\").remove();\n jQuery(this).removeClass(\"fm-validate-field\");\n });\n });\n}",
"handleNavigation(event) {\n \n let formIsValid = true;\n let newErrors = [];\n \n \n // Ensure all fields on Page 1 are filled as required\n if (this.state.currentPage === 'one') {\n \n if (this.state.ratingSelected === '') {\n formIsValid = false;\n newErrors.push(\"rating\"); \n }\n \n if (this.state.buildingSelected === '') {\n formIsValid = false;\n newErrors.push(\"building\"); \n }\n \n // Set Errors\n this.setState({ errors: newErrors })\n \n }\n \n // If form has an error we don't change the page\n if (formIsValid) {\n this.setState({currentPage: event.target.name});\n }\n \n event.preventDefault();\n }",
"function validateSlideThree() {\n\tvar motto = document.forms[\"register\"][\"businessmotto\"].value;\n\tvar mottoError = document.getElementById(\"error-businessmotto\");\n\tvar state = document.forms[\"register\"][\"state\"].value;\n\tvar area = document.forms[\"register\"][\"area\"].value;\n\tvar stateError = document.getElementById(\"error-state\");\n\tvar areaError = document.getElementById(\"error-area\");\n\n\t\n\n\t//validates business motto\n\tif (motto == \"\") {\n\t\tmottoError.innerHTML = \"This field is required\";\n\t} else {\n\t\tmottoError.innerHTML = \"\";\n\t}\n\n\tif (state == \"\") {\n\t\tstateError.innerHTML = \"This field is required\";\n\t} else {\n\t\tstateError.innerHTML = \"\";\n\t}\n\n\tif (area == \"\") {\n\t\tareaError.innerHTML = \"This field is required\";\n\t} else {\n\t\tareaError.innerHTML = \"\";\n\t}\n\n\t//if either fails validation remain on current slide else move to next slide\n\n\tif (motto == \"\" || area == \"\" || state == \"\") {\n\t\tcurrentSlide(3);\n\t} else {\n\t\tplusSlides(1);\n\t}\n}",
"function captureFormInput(e) {\n const value = e.target.value;\n if (e.target.name === 'title') {\n if (value.length > 100) {\n alert('Title is too long. Please enter 100 or fewer characters.');\n };\n } ;\n if (e.target.name === 'description') {\n if (value.length > 1000) {\n alert('Decription is too long. Please enter 1000 or fewer characters.');\n };\n };\n setValues({\n ...values,\n [e.target.name]: value,\n completed: false,\n });\n }",
"updateErrors() {\n $('#rbro_style_panel .rbroFormRow').removeClass('rbroError');\n $('#rbro_style_panel .rbroErrorMessage').text('');\n let selectedObj = this.rb.getDataObject(this.selectedObjId);\n if (selectedObj !== null) {\n for (let error of selectedObj.getErrors()) {}\n }\n }",
"updateErrors() {\n $('#rbro_page_break_element_panel .rbroFormRow').removeClass('rbroError');\n $('#rbro_page_break_element_panel .rbroErrorMessage').text('');\n let selectedObj = this.rb.getDataObject(this.selectedObjId);\n if (selectedObj !== null) {\n for (let error of selectedObj.getErrors()) {}\n }\n }",
"function error(elementInstance) {\n elementInstance.addEventListener('change', function (event) {\n let err = document.getElementById('stripe-error');\n if (event.error) err.innerHTML = event.error.message;\n else err.innerHTML = '';\n })\n }",
"function checkRegistrationFormInputs() {\n let emailValue = email.value.trim();\n let passwordValue = password.value.trim();\n let passwordConfirmationValue = passwordConfirmation.value.trim();\n\n if (emailValue === \"\") {\n setErrorFor(email, \"Email cannot be blank\");\n } else if (!isEmail(emailValue)) {\n setErrorFor(email, \"Email is not valid\");\n } else {\n setSuccessFor(email);\n }\n\n if (passwordValue === \"\") {\n setErrorFor(password, \"Password cannot be blank\");\n } else if (passwordValue.length < 8) {\n setErrorFor(password, \"Password length must be minimum 8 symbols\");\n } else {\n setSuccessFor(password);\n }\n\n if (passwordConfirmationValue === \"\") {\n setErrorFor(passwordConfirmation, \"Confirmation field cannot be blank\");\n } else if (passwordValue !== passwordConfirmationValue) {\n setErrorFor(passwordConfirmation, \"Passwords does not match\");\n } else {\n setSuccessFor(passwordConfirmation);\n }\n}",
"function validarCamposDeTransferencia0(){\n var cuentaCliente = document.getElementById(\"cuentaCliente0\").value;\n var cuentaVendedor = document.getElementById(\"cuentaVendedor0\").value;\n if (cuentaCliente == \"\" || cuentaCliente == null){\n document.getElementById(\"errorCuentaCliente0\").innerHTML = \"Debe ingresar el Número de cuenta (Cliente)\";\n document.getElementById(\"cuentaCliente0\").className = \"form-control is-invalid\";\n } else {\n document.getElementById(\"errorCuentaCliente0\").innerHTML = \"\";\n document.getElementById(\"cuentaCliente0\").className = \"form-control is-valid\";\n }\n if (cuentaVendedor == \"\" || cuentaVendedor == null){\n document.getElementById(\"errorCuentaVendedor0\").innerHTML = \"Debe ingresar el Número de cuenta (Vendedor)\";\n document.getElementById(\"cuentaVendedor0\").className = \"form-control is-invalid\";\n } else {\n document.getElementById(\"errorCuentaVendedor0\").innerHTML = \"\";\n document.getElementById(\"cuentaVendedor0\").className = \"form-control is-valid\";\n }\n if (cuentaCliente == \"\" || cuentaCliente == null || cuentaVendedor == \"\" || cuentaVendedor == null){\n document.getElementById(\"errorPago0\").innerHTML = \"Faltan llenar campos de Transferencia bancaria\";\n CamposDePago0 = false;\n } else {\n document.getElementById(\"errorPago0\").innerHTML = \"\";\n CamposDePago0 = true;\n }\n}",
"function validarCamposDeTransferencia1(){\n var cuentaCliente = document.getElementById(\"cuentaCliente1\").value;\n var cuentaVendedor = document.getElementById(\"cuentaVendedor1\").value;\n if (cuentaCliente == \"\" || cuentaCliente == null){\n document.getElementById(\"errorCuentaCliente1\").innerHTML = \"Debe ingresar el Número de cuenta (Cliente)\";\n document.getElementById(\"cuentaCliente1\").className = \"form-control is-invalid\";\n } else {\n document.getElementById(\"errorCuentaCliente1\").innerHTML = \"\";\n document.getElementById(\"cuentaCliente1\").className = \"form-control is-valid\";\n }\n if (cuentaVendedor == \"\" || cuentaVendedor == null){\n document.getElementById(\"errorCuentaVendedor1\").innerHTML = \"Debe ingresar el Número de cuenta (Vendedor)\";\n document.getElementById(\"cuentaVendedor1\").className = \"form-control is-invalid\";\n } else {\n document.getElementById(\"errorCuentaVendedor1\").innerHTML = \"\";\n document.getElementById(\"cuentaVendedor1\").className = \"form-control is-valid\";\n }\n if (cuentaCliente == \"\" || cuentaCliente == null || cuentaVendedor == \"\" || cuentaVendedor == null){\n document.getElementById(\"errorPago1\").innerHTML = \"Faltan llenar campos de Transferencia bancaria\";\n CamposDePago1 = false;\n } else {\n document.getElementById(\"errorPago1\").innerHTML = \"\";\n CamposDePago1 = true;\n }\n}",
"function validateSlideTwo() {\n\tvar bizName = document.forms[\"register\"][\"businessname\"].value;\n\tvar bizInfo = document.forms[\"register\"][\"businessinfo\"].value;\n\tvar bizPhone = document.forms[\"register\"][\"businessphone\"].value;\n\tvar bizNameError = document.getElementById(\"error-businessname\");\n\tvar bizInfoError = document.getElementById(\"error-businessinfo\");\n\tvar bizPhoneError = document.getElementById(\"error-businessphone\");\n\tvar bizAddr =document.forms[\"register\"][\"businessaddress\"].value;\n\tvar bizAddrError = document.getElementById(\"error-businessaddress\");\n\t\n\n\n\t//validates business name\n\t\tif (bizName == \"\") {\n\t\tbizNameError.innerHTML = \"This field is required\";\n\t} \n\t else {\n\t\tbizNameError.innerHTML = \"\";\n\t}\n\n\n\t//validates business info\n\tif (bizInfo == \"\") {\n\t\tbizInfoError.innerHTML = \"This field is required\";\n\t} \n\telse {\n\t\tbizInfoError.innerHTML = \"\";\n\t}\n\n\n\t//validates business phone\n\tif (bizPhone == \"\") {\n\t\tbizPhoneError.innerHTML = \"This field is required\";\n\t}\telse if (isNaN(bizPhone)) {\n\t\tbizPhoneError.innerHTML = \"Only numbers allowed\";\n\t}\n\t else if (bizPhone.length != 11){\n\t\tbizPhoneError.innerHTML = \"Number must be 11 characters long\";\n\t} else {\n\t\tbizPhoneError.innerHTML = \"\";\n\t};\n\n\tif (bizAddr == \"\") {\n\t\tbizAddrError.innerHTML = \"This field is required\";\n\t}\n\n\t//if either fails validation remain on current slide else move to next slide\n\tif (bizPhone == \"\" || bizPhone.length != 11 || bizName == \"\" || bizInfo == \"\" || isNaN(bizPhone) || bizAddr == \"\") {\n\t\tcurrentSlide(2);\n\t} else{\n\t\tplusSlides(1);\n\t};\n}",
"function validateObserverFormInputs() {\n var observer = $('select[id*=\"ObserverUser\"]'); // get the proper id input\n var messageA = $(observer).val() == '' ? 'You must select an User' : '';\n var messageB = $('#ObserverType').val() == '' ? 'You must select an Type' : '';\n var divider = (messageA != '' && messageB != '') ? '\\r\\n\\r\\n' : '';\n if (messageA != '' || messageB != '') {\n alert(messageA + divider + messageB);\n return false;\n } else {\n return true;\n }\n}",
"function validateUpdatePaymentForm()\n{\n\tvar box, i;\n\tvar form = document.update;\n\t\n\tfor(i=2; i<7; i++)\n\t{\n\t\tif(i==4 || i==5)\n\t\t\tcontinue;\n\t\telse\n\t\t{\n\t\t\tbox=form.elements[i];\n\t\t\t//if it encountered a box without a value, an alert box would appear informing the user\n\t\t\tif(!box.value)\n\t\t\t{\n\t\t\t\t$().toastmessage({position:'middle-center', stayTime:2000});\n\t\t\t\t$().toastmessage('showErrorToast', \"You haven't filled in the \"+box.name+\".\");\n\t\t\t\tbox.focus();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\t//return true if the form is complete\n\treturn true;\n}",
"function removeErrorCvv(self) {\n if (self.value.length === 3 || self.value.length === 4) {\n document.getElementById(self.parentNode.id).style.border = '1px solid #CCC';\n document.getElementById('error_' + self.id).style.display = 'none';\n } else if (self.value.length > 0 && self.value.length < 3) {\n document.getElementById(self.parentNode.id).style.border = '1px solid #FF0000';\n document.getElementById('error_' + self.id).style.display = 'block';\n document.getElementById('error_' + self.id).innerHTML = 'invalid CVV!';\n } else if (self.value.length === 0) {\n document.getElementById(self.parentNode.id).style.border = '1px solid #FF0000';\n document.getElementById('error_' + self.id).style.display = 'none';\n }\n}",
"function onSignUpClicked (event) {\n let isValid = true;\n let userType = 'student';\n\n $(getClassName(userType, 'signUpFirstNameError')).hide()\n $(getClassName(userType, 'signUpLastNameError')).hide()\n $(getClassName(userType, 'signUpCountryCodeError')).hide()\n $(getClassName(userType, 'SignUpPhoneNumberError')).hide()\n $(getClassName(userType, 'SignUpEmailError')).hide()\n $(getClassName(userType, 'SignUpPasswordError')).hide()\n const firstName = $(getClassName(userType, 'signUpFirstName'))[0].value;\n const lastName = $(getClassName(userType, 'signUpLastName'))[0].value;\n const countryCode = $(getClassName(userType, 'signUpCountryCode'))[0].value;\n const phoneNumber = $(getClassName(userType, 'signUpPhoneNumber'))[0].value;\n const emailId = $(getClassName(userType, 'signUpEmail'))[0].value;\n const password = $(getClassName(userType, 'signUpPassword'))[0].value;\n if (!firstName) {\n $(getClassName(userType, 'signUpFirstNameError')).text('Please provide First Name');\n $(getClassName(userType, 'signUpFirstNameError')).show()\n isValid = false;\n }\n if (!lastName) {\n $(getClassName(userType, 'signUpLastNameError')).text('Please provide Last Name');\n $(getClassName(userType, 'signUpLastNameError')).show()\n isValid = false;\n }\n if (countryCode === 'none') {\n $(getClassName(userType, 'signUpCountryCodeError')).text('Please select country code');\n $(getClassName(userType, 'signUpCountryCodeError')).show()\n isValid = false;\n }\n if (phoneNumber && !isPhoneNumberValid(phoneNumber)) {\n $(getClassName(userType, 'SignUpPhoneNumberError')).text('Please add valid phone number');\n $(getClassName(userType, 'SignUpPhoneNumberError')).show()\n isValid = false;\n }\n if (!emailId) {\n $(getClassName(userType, 'SignUpEmailError')).text('Please provide email');\n $(getClassName(userType, 'SignUpEmailError')).show()\n isValid = false;\n }\n if (!password) {\n $(getClassName(userType, 'SignUpPasswordError')).text('Please provide password');\n $(getClassName(userType, 'SignUpPasswordError')).show()\n isValid = false;\n }\n\n if (isValid) {\n signUpAPI(userType, firstName, lastName, `${countryCode}${phoneNumber}`, emailId, password)\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
event handler for "participantVideo added/updated/deleted in participant|localParticipant" events tracks session video state (on/off), participant video state and shows/removes video when video modality is activated/deactivated. | function onParticipantVideo(status, resource, event) {
var scope = event['in'];
if (event.sender.href == rConversation.href && scope) {
if (scope.rel == 'localParticipant') {
switch (event.type) {
case 'added':
case 'updated':
activeModalities.video = true;
if (isConferencing()) {
selfParticipant[Internal.sInternal].setMediaSourceId(event);
updateMediaRoster(selfParticipant, isInMediaRoster(selfParticipant) ? 'update' : 'add');
// check participants that are already in the conference - we need their msis
// because we won't receive "participantVideo added" events for them.
participants.each(function (p) {
if (!isInMediaRoster(p) && p[Internal.sInternal].audioSourceId() != -1)
updateMediaRoster(p, 'add');
});
}
videoState(Internal.Modality.State.Connected);
selfParticipant[Internal.sInternal].videoState(Internal.Modality.State.Connected);
break;
case 'deleted':
removeVideo(selfVideoStream, true);
activeModalities.video = false;
if (isConferencing()) {
if (isInMediaRoster(selfParticipant))
updateMediaRoster(selfParticipant, 'remove');
selfParticipant[Internal.sInternal].setMediaSourceId(event);
}
videoState(Internal.Modality.State.Disconnected);
selfParticipant[Internal.sInternal].videoState(Internal.Modality.State.Disconnected);
break;
default:
assert(false, 'unexpected event type');
}
}
else if (scope.rel == 'participant') {
Task.wait(getParticipant(scope.href)).then(function (participant) {
switch (event.type) {
case 'added':
case 'updated':
if (isConferencing()) {
participant[Internal.sInternal].setMediaSourceId(event);
updateMediaRoster(participant, isInMediaRoster(participant) ? 'update' : 'add');
participant[Internal.sInternal].videoState(Internal.Modality.State.Connected);
}
else {
participant[Internal.sInternal].setVideoStream(mainVideoStream);
participant[Internal.sInternal].videoState(Internal.Modality.State.Connected);
}
break;
case 'deleted':
if (isConferencing()) {
if (isInMediaRoster(participant))
updateMediaRoster(participant, 'remove');
participant[Internal.sInternal].setMediaSourceId(event);
removeParticipantVideo(participant);
participant[Internal.sInternal].videoState(Internal.Modality.State.Disconnected);
// if participant video is deleted not because we stopped video
// subscription explicitly (via isStarted(false)) but because
// participant left the AV call then we need to reset isStarted.
participant[Internal.sInternal].setVideoStarted(false);
}
else {
participant[Internal.sInternal].setVideoStream(null);
participant[Internal.sInternal].videoState(Internal.Modality.State.Disconnected);
}
break;
default:
assert(false, 'unexpected event type');
}
});
}
}
} | [
"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 }",
"onParticipantLeft(message)\n {\n var participant = this.participants[message.sessionId];\n\n participant.dispose();\n delete this.participants[message.sessionId];\n\n // remove video tag\n $(\"#video-\" + participant.id).remove();\n }",
"bindCustomMessageEvents() {\n // EventListener for custom event from Video IntersectionObserver\n this.videoContainer.addEventListener(\"videoObservedInView\", this.loadVideo.bind(this));\n this.videoContainer.addEventListener(\"loadVideo\", this.loadVideo.bind(this));\n\n this.videoPlayer.addEventListener(\"play\", this.playVideo.bind(this));\n this.videoPlayer.addEventListener(\"pause\", this.pauseVideo.bind(this));\n\n this.videoContainer.addEventListener(\"playbackToggled\", this.togglePlayback.bind(this));\n }",
"function registerVideoEvent(videoEvent) {\n var isNewVideoEvent = checkIfNewVideoEvent(videoEvent);\n if (isNewVideoEvent) {\n _mostRecentVideoEventTime = videoEvent.timestamp;\n videoSeekTo(videoEvent.video_time_at);\n if (videoEvent.event_type === 'play') {\n playVideo();\n _mostRecentVideoEventType = 'play';\n } else if (videoEvent.event_type === 'pause') {\n pauseVideo();\n _mostRecentVideoEventType = 'pause';\n }\n }\n\n\n}",
"function createParticipant(options) {\n extend(options, {\n ucwa: ucwa,\n isTabActive: isTabActive.asReadOnly(),\n contactManager: contactManager\n });\n var p = new Internal.Participant(options), selfEnabled = Property(), remoteEnabled = Property();\n // show or remove participant video\n function participantVideo(val) {\n var dfd = val ?\n avm.showParticipantVideo(p) :\n avm.removeParticipantVideo(p);\n return dfd.then(function () {\n return val;\n });\n }\n // show or remove self participant video\n function selfVideo(val) {\n switch (p.video.state()) {\n case Internal.Modality.State.Disconnected:\n case Internal.Modality.State.Notified:\n return val;\n case Internal.Modality.State.Connected:\n return participantVideo(val);\n default:\n throw Exception('InvalidState');\n }\n }\n if (options.isLocal) {\n // TODO: convert to p.video.state.map(...)\n p.video.state.changed(function (v) {\n selfEnabled(v != Internal.Modality.State.Connecting);\n });\n p.video.channels(0).isStarted = Property({\n set: Command(selfVideo, selfEnabled)\n });\n }\n else {\n // videoChanel.isStarted.set should be enabled for a remote participant only in a conference,\n // so we need to observe both participant video state and conversation state changes.\n p.video.state.changed(function (v) {\n remoteEnabled(isConferencing() && v == Internal.Modality.State.Connected);\n });\n isConferencing.changed(function (v) {\n remoteEnabled(v && p.video.state() == Internal.Modality.State.Connected);\n });\n p.video.channels(0).isStarted = Property({\n set: Command(participantVideo, remoteEnabled)\n });\n }\n return p;\n }",
"function videoClick(clickedVideo){\n console.log('video es'+clickedVideo);\n sessionStorage.setItem('videoid', clickedVideo);\n}",
"function AttachVisibilityHandler() {\n const { room } = Object(_hooks_useVideoContext_useVideoContext__WEBPACK_IMPORTED_MODULE_3__[\"default\"])();\n const [isVideoEnabled, toggleVideoEnabled] = Object(_hooks_useLocalVideoToggle_useLocalVideoToggle__WEBPACK_IMPORTED_MODULE_2__[\"default\"])();\n const shouldRepublishVideoOnForeground = Object(react__WEBPACK_IMPORTED_MODULE_1__[\"useRef\"])(false);\n Object(react__WEBPACK_IMPORTED_MODULE_1__[\"useEffect\"])(() => {\n if (_utils__WEBPACK_IMPORTED_MODULE_0__[\"isMobile\"]) {\n const handleVisibilityChange = () => {\n // We don't need to unpublish the local video track if it has already been unpublished\n if (document.visibilityState === 'hidden' && isVideoEnabled) {\n shouldRepublishVideoOnForeground.current = true;\n toggleVideoEnabled();\n // Don't publish the local video track if it wasn't published before the app was backgrounded\n }\n else if (shouldRepublishVideoOnForeground.current) {\n shouldRepublishVideoOnForeground.current = false;\n toggleVideoEnabled();\n }\n };\n document.addEventListener('visibilitychange', handleVisibilityChange);\n return () => {\n document.removeEventListener('visibilitychange', handleVisibilityChange);\n };\n }\n }, [isVideoEnabled, room, toggleVideoEnabled]);\n return null;\n}",
"function addVideo(e) {\n const id = (e.target.id !== 'addVideo')\n ? e.target.value\n : domCache['videoId'].value;\n const found = state.videos.filter(video => id === video.id);\n\n if (e && e.target.id === 'addVideo' && found.length > 0) {\n log('add video', `not added; id ${id} already in list`);\n return;\n }\n\n const func = (!state.player)\n ? setPlayer\n : loadVideo;\n\n func(id).then((loaded) => {\n // video is loaded, will be updated in loaded event.\n }).catch(function(error) {\n // the video did not load.\n log(`${func.name} called`, `video id ${id} not loaded.`);\n });\n }",
"function onTimeupdate(){\n //if the video has finished\n if ( this.currentTime >= this.duration ){\n //if we are offering e-mail sharing\n if (configHandler.get('showLocalShare')){\n var vidElem = document.getElementById('videoReview');\n //if we have not shown the e-mail option yet\n if (haveShownShare === false ){\n //remember that we have shown it\n haveShownShare = true;\n //transition in the other UI elements\n var container = document.getElementById('videoReviewContainer');\n container.classList.add('share');\n var btn = document.getElementById('breakButton');\n btn.classList.remove('enabled');\n btn.classList.add('disabled');\n vidElem.muted = true;\n //play the audio after the e-mail option\n // has transitioned in\n if (soundPlayer.exists()){\n soundTimeout = setTimeout(function(){\n soundPlayer.play();\n }, 1000);\n }\n }\n //replay the video\n vidElem.currentTime = 0;\n vidElem.play();\n } else {\n //if we are not offering e-mail sharing\n // just transition to the thank you screen\n window.events.dispatchEvent(new Event('special'));\n }\n }\n }",
"function onRemoteTrackRemove(track) {\n console.log(`INFO: Track removed!${track}`);\n const participant = track.getParticipantId();\n if (participant in changeList) {\n var remoteVideo = \"#remoteVideo\" +changeList[participant];\n var remoteAudio = \"#remoteAudio\" +changeList[participant];\n switch (changeList[participant]) {\n\tcase 1:\n\t $(remoteVideo).replaceWith(\n\t\t`<div id='remoteVideo${changeList[participant]}'><img src=\"resources/top-left.png\"/></div>`);\n\t break;\n\tcase 2:\n $(remoteVideo).replaceWith(\n\t\t`<div id='remoteVideo${changeList[participant]}'><img src=\"resources/top-right.png\"/></div>`);\n\t break;\n\tcase 3:\n $(remoteVideo).replaceWith(\n\t\t`<div id='remoteVideo${changeList[participant]}'><img src=\"resources/bottom-left.png\"/></div>`);\n\t break;\n\tcase 4:\n $(remoteVideo).replaceWith(\n\t\t`<div id='remoteVideo${changeList[participant]}'><img src=\"resources/bottom-right.png\"/></div>`);\n\t break;\n }\n /*\n $(remoteVideo).replaceWith(\n `<div id='remoteVideo${changeList[participant]}'><img src=\"resources/conference-chair.png\"/></div>`);\n */\n $(remoteAudio).replaceWith(\n `<div id='remoteAudio${changeList[participant]}'></div>`);\n frameArray.push(changeList[participant]);\n delete changeList[participant];\n }\n //console.log('INFO (audience.js): Participants after track remove: ' + JSON.stringify(changeList));\n}",
"isVideoTrack() {\n return this.getType() === MediaType.VIDEO;\n }",
"function onParticipantAudio(status, resource, event) {\n var scope = event['in'];\n if (event.sender.href == rConversation.href && scope) {\n if (scope.rel == 'localParticipant') {\n switch (event.type) {\n case 'added': // signal for the initial AV session\n case 'updated':\n if (isConferencing())\n selfParticipant[Internal.sInternal].setMediaSourceId(event);\n activeModalities.audio = true;\n audioState(Internal.Modality.State.Connected);\n break;\n case 'deleted':\n activeModalities.audio = false;\n audioState(Internal.Modality.State.Disconnected);\n break;\n default:\n assert(false, 'unexpected event type');\n }\n }\n else if (scope.rel == 'participant') {\n Task.wait(getParticipant(scope.href)).then(function (participant) {\n switch (event.type) {\n case 'added':\n case 'updated':\n if (isConferencing()) {\n participant[Internal.sInternal].setMediaSourceId(event);\n // In conference mode, the indication of a remote\n // participant hold/resume or mute/unmute is\n // \"participantAudio updated\" event. We need to\n // reload \"participantAudio\" resource and set the\n // properties accordingly\n if (event.type == 'updated') {\n ucwa.send('GET', event.target.href).then(function (r) {\n if (r.has('audioDirection')) {\n participant[Internal.sInternal].audioOnHold(r.get('audioDirection') ==\n AudioVideoDirection.Inactive);\n }\n if (r.has('audioMuted'))\n participant[Internal.sInternal].audioMuted(r.get('audioMuted'));\n });\n }\n }\n participant[Internal.sInternal].audioState(Internal.Modality.State.Connected);\n break;\n case 'deleted':\n participant[Internal.sInternal].audioState(Internal.Modality.State.Disconnected);\n break;\n default:\n assert(false, 'unexpected event type');\n }\n });\n }\n }\n }",
"function startVideo() {\n mini_peer.setLocalStreamToElement({ video: true, audio: true }, localVideo);\n}",
"function initializeVideoEventHandlers(videoEventType) {\n if (videoEventType === 'play' &\n videoEventType !== _mostRecentVideoEventType) {\n runPlaySequence();\n } else if (videoEventType === 'pause' &\n videoEventType !== _mostRecentVideoEventType) {\n runPauseSequence();\n }\n}",
"static isVideoPlaying(video){return video.currentTime>0&&!video.paused&&video.readyState>2;}",
"function useScreenShareParticipant() {\n const { room } = Object(_useVideoContext_useVideoContext__WEBPACK_IMPORTED_MODULE_1__[\"default\"])();\n const [screenShareParticipant, setScreenShareParticipant] = Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useState\"])();\n Object(react__WEBPACK_IMPORTED_MODULE_0__[\"useEffect\"])(() => {\n if (room.state === 'connected') {\n const updateScreenShareParticipant = () => {\n setScreenShareParticipant(Array.from(room.participants.values())\n // the screenshare participant could be the localParticipant\n .concat(room.localParticipant)\n .find((participant) => Array.from(participant.tracks.values()).find(track => track.trackName.includes('screen'))));\n };\n updateScreenShareParticipant();\n room.on('trackPublished', updateScreenShareParticipant);\n room.on('trackUnpublished', updateScreenShareParticipant);\n room.on('participantDisconnected', updateScreenShareParticipant);\n // the room object does not emit 'trackPublished' events for the localParticipant,\n // so we need to listen for them here.\n room.localParticipant.on('trackPublished', updateScreenShareParticipant);\n room.localParticipant.on('trackUnpublished', updateScreenShareParticipant);\n return () => {\n room.off('trackPublished', updateScreenShareParticipant);\n room.off('trackUnpublished', updateScreenShareParticipant);\n room.off('participantDisconnected', updateScreenShareParticipant);\n room.localParticipant.off('trackPublished', updateScreenShareParticipant);\n room.localParticipant.off('trackUnpublished', updateScreenShareParticipant);\n };\n }\n }, [room]);\n return screenShareParticipant;\n}",
"function playActorVideo(actor, time) {\n //playVideo(id, time - startTime of video)\n\n}",
"function stopVideoCapture(senderTab, callback) {\n console.log(\"stopVideoCapture\");\n\n // Clear recording state\n recordedTabID = null;\n chrome.browserAction.setBadgeText({\n text: \"\",\n });\n chrome.browserAction.setBadgeBackgroundColor({\n color: \"#F00\",\n });\n\n // Sanity check\n if (!videoConnection) \n {\n videoConnection = null;\n chrome.tabs.sendMessage(senderTab.id, {\n request: 'videoRecordingStopped',\n sourceURL: null,\n });\n return;\n }\n\n // Stop video capture and save file\n var videoData = videoRecorder.stop();\n try {\n videoConnection.stop();\n } catch (exception) {\n console.log(exception);\n } finally {\n videoConnection = null;\n }\n\n // If output was bad, don't continue\n if (!videoData || !videoData.sourceURL) \n {\n chrome.tabs.sendMessage(senderTab.id, {\n request: 'videoRecordingStopped',\n sourceURL: null,\n });\n return;\n }\n \n console.log(videoData);\n var file = new File([videoData.videoBlob], 'RecordRTC-' + (new Date).toISOString().replace(/:|\\./g, '-') + '.webm', {\n type: 'video/webm'\n });\n\n var formData = new FormData();\n formData.append('video-filename', file.name);\n formData.append('video-file', file);\n\n sendMessageToContentScript({\"loadingScreen\": true, \"messageFromContentScript1234\": true});\n chrome.cookies.getAll({'domain': 'userstory.io', 'name': 'emailUserStory'}, function(cookie) {\n console.log(cookie[0].value);\n formData.append('email', cookie[0].value);\n xhr('http://userstory.io/uploadvideo/', formData, function(data) {\n //console.log(data['url']);\n sendMessageToContentScript({\"clearLoadingScreen\": true, \"messageFromContentScript1234\": true});\n var url = \"http://userstory.io\" + data['url'];\n\n chrome.tabs.create({url: url, selected: true});\n setDefaults();\n chrome.runtime.reload();\n\n askToStopExternalStreams();\n\n try {\n peer.close();\n peer = null;\n } catch (e) {\n\n };\n\n try {\n audioPlayer.src = null;\n mediaStremDestination.disconnect();\n mediaStremSource.disconnect();\n context.disconnect();\n context = null;\n } catch (e) {\n\n }\n });\n });\n \n isRecording = false;\n tabRecordingStatus = false;\n}",
"function video_click(e) {\n\t//console.log(e);\n\t//console.log(this);\n\tif (this.paused == true) {\n\t\tthis.play();\n\t} else {\n\t\tthis.pause();\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of global script metadata for a microservice. | function listGlobalScriptMetadata(axios$$1, identifier) {
return restAuthGet(axios$$1, 'instance/microservice/' + identifier + '/scripting/scripts');
} | [
"function listTenantScriptMetadata(axios$$1, identifier, tenantToken) {\n return restAuthGet(axios$$1, 'instance/microservice/' + identifier + '/tenants/' + tenantToken + '/scripting/scripts');\n }",
"async function getScripts() {\n const url = '/api/scripts';\n const response = await fetch(url);\n const scriptFiles = await response.json();\n\n console.log(\"HUB: Script files have been recieved\");\n generateFileList(\"scriptsList\", \"delScriptsList\", scriptFiles);\n}",
"function getTenantScriptMetadata(axios$$1, identifier, tenantToken, scriptId) {\n return restAuthGet(axios$$1, 'instance/microservice/' + identifier + '/tenants/' + tenantToken + '/scripting/scripts/' + scriptId);\n }",
"function getGlobalScriptContent(axios$$1, identifier, scriptId, versionId) {\n return restAuthGet(axios$$1, 'instance/microservice/' + identifier + '/scripting/tenants/' + tenantId + '/scripts/' + identifier + '/' + scriptId + '/versions/' + versionId + '/content');\n }",
"async function ListFunctions() {\n let functionService = new fx.FunctionService(process.env.MICRO_API_TOKEN);\n let rsp = await functionService.list({});\n console.log(rsp);\n}",
"function getMetadata(dir) {\n const json = path.join(dir, 'metadata.json')\n const js = path.join(dir, 'metadata.js')\n let opts = {}\n\n if (exists(json)) {\n opts = metadata.sync(json)\n } else if (exists(js)) {\n const req = require(path.resolve(js)) // eslint-disable-line\n if (req !== Object(req)) {\n throw new Error('metadata.js needs to expose an object')\n }\n opts = req\n }\n\n return opts\n}",
"async registerApplicationServices() {\n return await this.container.loadDefinitions(`${this.getProjectDir()}/config/services/services.yml`, \"application\");\n }",
"getOwnFiles() {\n return this.cache.getOrAdd('getOwnFiles', () => {\n let result = [\n this.xmlFile\n ];\n let scriptPkgPaths = this.xmlFile.getOwnDependencies();\n for (let scriptPkgPath of scriptPkgPaths) {\n let file = this.program.getFileByPkgPath(scriptPkgPath);\n if (file) {\n result.push(file);\n }\n }\n return result;\n });\n }",
"async function retrieveAssetMetaAll() {\n try {\n const response = await axios.get(ASSETHUB_SERVER_API_BASE_URL + 'asset/meta/list');\n return await response.data\n } catch (error) {\n console.log(error);\n return {\n result: {\n code: 400,\n }\n }\n }\n}",
"function metaItems(key) {\n return findAll(meta(key));\n }",
"getMetaTags() {\n return this._currentDom.getElementsByTagName(\"meta\");\n }",
"getResources(includeTs) {\n const resources = this.data.manifest.control.resources;\n let pathsCollection = [];\n Object.keys(resources).forEach(resourceType => {\n let paths;\n if (resourceType !== constants.LIBRARY_ELEM_NAME) {\n paths = (resourceType === constants.CODE_ELEM_NAME && !includeTs) ? [] : resources[resourceType].map((resource) => resource.$.path);\n }\n else {\n paths = flatMap(resources[resourceType], (resource) => resource['packaged_library'] ? resource['packaged_library'].map((packagedLib) => packagedLib.$.path) : []);\n }\n pathsCollection.push(...paths);\n });\n return pathsCollection;\n }",
"static Get(serviceName) {\n\t if(!this.g_services) this.g_services = [];\n\t \n\t return this.g_services[serviceName];\n }",
"function getList() {\r\n // URL to access list of all Pokemon names and URLs from PokeAPI\r\n const POKEMON_LIST_URL = \"https://pokeapi.co/api/v2/pokemon/?offset=0&limit=964\";\r\n\r\n // Get data\r\n getData(POKEMON_LIST_URL);\r\n}",
"function getScripts() {\n\t\tvar result = [];\n\t\tvar scripts = targetWindow.document.scripts;\n\t\tforEach(scripts, function(script) {\n\t\t\tif (script.src) {\n\t\t\t\tresult.push({\n\t\t\t\t\ttype: script.type,\n\t\t\t\t\tsrc: script.src,\n\t\t\t\t\tasync: script.async,\n\t\t\t\t\tdefer: script.defer\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t\treturn result;\n\t}",
"listPlugins() {\n return __awaiter(this, void 0, void 0, function* () {\n const result = yield this.runPulumiCmd([\"plugin\", \"ls\", \"--json\"]);\n return JSON.parse(result.stdout, (key, value) => {\n if (key === \"installTime\" || key === \"lastUsedTime\") {\n return new Date(value);\n }\n return value;\n });\n });\n }",
"function getKeywords(){\n return gKeywords\n}",
"function getAllAssets() {\n return new Promise((resolve, reject) => {\n if (!process.env.API_URL_LIST) {\n console.log(process.env.API_URL_LIST);\n reject('No URL found to get all Assets.');\n }\n\n request(process.env.API_URL_LIST, (error, response, body) => {\n if (!error && response.statusCode === 200) {\n const json = JSON.parse(body);\n resolve(json);\n } else {\n reject(error);\n }\n });\n });\n}",
"function getParserList() {\n\n if (parserList === undefined) {\n\n var bundleParsers = [], files, bundlePath;\n\n // Application bundled\n bundlePath = path.resolve(path.join(__dirname, \"parser\"));\n files = fs.readdirSync(bundlePath);\n files.forEach(\n function (fileName) {\n\n var parser, parserPath;\n\n if (path.extname(fileName) === \".js\") {\n\n parserPath = path.join(bundlePath, fileName);\n try {\n parser = require(parserPath);\n } catch(ex) {\n console.error(\"Could not find parser %s. File not found or open error\", ex);\n }\n if (parser !== undefined && parser.disabled !== true && typeof parser.parsePage === \"function\") {\n\n fileName = path.basename(fileName, \".js\");\n parsers[fileName] = parser;\n\n bundleParsers.push(\n {\n name: fileName,\n label: parser.label,\n description: parser.description,\n isBundled: true\n }\n );\n }\n }\n }\n );\n\n // User\n // TODO : Charger les parsers du dossier utilisateur\n\n\n parserList = bundleParsers;\n }\n\n return parserList;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. / ZeroVM on Swift (ZeroCloud) client. | function ZeroCloudClient() {
this._token = null;
} | [
"async function createBackupVaultWithMsi() {\n const subscriptionId =\n process.env[\"DATAPROTECTION_SUBSCRIPTION_ID\"] || \"0b352192-dcac-4cc7-992e-a96190ccc68c\";\n const resourceGroupName = process.env[\"DATAPROTECTION_RESOURCE_GROUP\"] || \"SampleResourceGroup\";\n const vaultName = \"swaggerExample\";\n const parameters = {\n identity: { type: \"systemAssigned\" },\n location: \"WestUS\",\n properties: {\n featureSettings: { crossRegionRestoreSettings: { state: \"Enabled\" } },\n monitoringSettings: {\n azureMonitorAlertSettings: { alertsForAllJobFailures: \"Enabled\" },\n },\n securitySettings: {\n softDeleteSettings: { retentionDurationInDays: 14, state: \"Enabled\" },\n },\n storageSettings: [{ type: \"LocallyRedundant\", datastoreType: \"VaultStore\" }],\n },\n tags: { key1: \"val1\" },\n };\n const credential = new DefaultAzureCredential();\n const client = new DataProtectionClient(credential, subscriptionId);\n const result = await client.backupVaults.beginCreateOrUpdateAndWait(\n resourceGroupName,\n vaultName,\n parameters\n );\n console.log(result);\n}",
"function launchVMSimple2() {\n\n getSubnetInfo(function(err, subnetInfo) {\n if (err) {\n console.log(err);\n return false;\n }\n createNIC(subnetInfo, null, function(err, nicInfo) {\n if (err) {\n console.log(err);\n return false;\n }\n\n createVirtualMachine(nicInfo.id, function(err, vmInfo) {\n if (err) {\n console.log(err);\n return false;\n }\n\n console.log('Created VM: ', util.inspect(vmInfo, {\n depth: null\n }));\n\n });\n });\n });\n\n}",
"constructor() { \n \n ComputeInfoProtocol.initialize(this);\n }",
"async function getsTheDetailsOfAVCenter() {\n const subscriptionId = \"7c943c1b-5122-4097-90c8-861411bdd574\";\n const resourceName = \"MadhaviVault\";\n const resourceGroupName = \"MadhaviVRG\";\n const fabricName = \"MadhaviFabric\";\n const vcenterName = \"esx-78\";\n const credential = new DefaultAzureCredential();\n const client = new SiteRecoveryManagementClient(credential, subscriptionId);\n const result = await client.replicationvCenters.get(\n resourceName,\n resourceGroupName,\n fabricName,\n vcenterName\n );\n console.log(result);\n}",
"_createSandbox(){\n\n let execute = this.execute;\n //Define the sandbox for the v8 virtual machine\n let sandbox = {\n Date: Date,\n //The server global variables and functions\n // globals: serverGlobal,\n //The function that will process the custom actions\n postMessage: function(message) {\n let type = message.data[\"$type\"];\n let stripNsPrefixRe = /^(?:{(?:[^}]*)})?(.*)$/;\n let arr = stripNsPrefixRe.exec(type);\n let ns;\n let action;\n if(arr.length === 2) {\n ns = type.substring(1, type.indexOf(\"}\"));\n action = arr[1];\n } else {\n ns = \"\";\n action = arr[0];\n }\n\n execute.call(this, ns, action, sandbox, message._event, message.data);\n }\n };\n\n return vm.createContext(sandbox);\n }",
"function virtualMachineRunCommand() {\n return __awaiter(this, void 0, void 0, function* () {\n const subscriptionId = \"24fb23e3-6ba3-41f0-9b6e-e41131d5d61e\";\n const resourceGroupName = \"crptestar98131\";\n const vmName = \"vm3036\";\n const parameters = { commandId: \"RunPowerShellScript\" };\n const credential = new DefaultAzureCredential();\n const client = new ComputeManagementClient(credential, subscriptionId);\n const result = yield client.virtualMachines.beginRunCommandAndWait(resourceGroupName, vmName, parameters);\n console.log(result);\n });\n}",
"zero () {\n this.#secret.zero()\n }",
"static Zero() {\n return new Vector2(0, 0);\n }",
"function prepareVM(cb){\n // load tx\n query.getTransactionByHash(txHash, function(err, _txData){\n if (err) return cb(err)\n if (!_txData) return cb(new Error('No transaction found...'))\n txData = _txData\n // load block\n // console.log('targetTx:',txData)\n traceStream.push({\n type: 'tx',\n data: txData,\n })\n query.getBlockByHash(txData.blockHash, true, function(err, _blockData){\n if (err) return cb(err)\n blockData = _blockData\n // materialize block and tx's\n targetBlock = materializeBlock(blockData)\n const txIndex = parseInt(txData.transactionIndex, 16)\n targetTx = targetBlock.transactions[txIndex]\n // determine prepatory tx's\n prepatoryTxs = targetBlock.transactions.slice(0, txIndex)\n // create vm\n // target tx's block's parent\n const backingStateBlockNumber = parseInt(blockData.number, 16) - 1\n const backingStateBlockNumberHex = `0x${backingStateBlockNumber.toString(16)}`\n vm = createRpcVm(provider, backingStateBlockNumberHex, {\n enableHomestead: true,\n })\n vm.on('error', console.error)\n // complete\n cb()\n })\n })\n }",
"constructor(name, args, opts) {\n let inputs = {};\n opts = opts || {};\n if (!opts.id) {\n if ((!args || args.accountName === undefined) && !opts.urn) {\n throw new Error(\"Missing required property 'accountName'\");\n }\n if ((!args || args.poolName === undefined) && !opts.urn) {\n throw new Error(\"Missing required property 'poolName'\");\n }\n if ((!args || args.resourceGroupName === undefined) && !opts.urn) {\n throw new Error(\"Missing required property 'resourceGroupName'\");\n }\n if ((!args || args.volumeName === undefined) && !opts.urn) {\n throw new Error(\"Missing required property 'volumeName'\");\n }\n inputs[\"accountName\"] = args ? args.accountName : undefined;\n inputs[\"backupName\"] = args ? args.backupName : undefined;\n inputs[\"label\"] = args ? args.label : undefined;\n inputs[\"location\"] = args ? args.location : undefined;\n inputs[\"poolName\"] = args ? args.poolName : undefined;\n inputs[\"resourceGroupName\"] = args ? args.resourceGroupName : undefined;\n inputs[\"volumeName\"] = args ? args.volumeName : undefined;\n inputs[\"backupId\"] = undefined /*out*/;\n inputs[\"backupType\"] = undefined /*out*/;\n inputs[\"creationDate\"] = undefined /*out*/;\n inputs[\"name\"] = undefined /*out*/;\n inputs[\"provisioningState\"] = undefined /*out*/;\n inputs[\"size\"] = undefined /*out*/;\n inputs[\"type\"] = undefined /*out*/;\n }\n else {\n inputs[\"backupId\"] = undefined /*out*/;\n inputs[\"backupType\"] = undefined /*out*/;\n inputs[\"creationDate\"] = undefined /*out*/;\n inputs[\"label\"] = undefined /*out*/;\n inputs[\"location\"] = undefined /*out*/;\n inputs[\"name\"] = undefined /*out*/;\n inputs[\"provisioningState\"] = undefined /*out*/;\n inputs[\"size\"] = undefined /*out*/;\n inputs[\"type\"] = undefined /*out*/;\n }\n if (!opts.version) {\n opts = pulumi.mergeOptions(opts, { version: utilities.getVersion() });\n }\n const aliasOpts = { aliases: [{ type: \"azure-nextgen:netapp/v20200901:Backup\" }, { type: \"azure-native:netapp:Backup\" }, { type: \"azure-nextgen:netapp:Backup\" }, { type: \"azure-native:netapp/v20200501:Backup\" }, { type: \"azure-nextgen:netapp/v20200501:Backup\" }, { type: \"azure-native:netapp/v20200601:Backup\" }, { type: \"azure-nextgen:netapp/v20200601:Backup\" }, { type: \"azure-native:netapp/v20200701:Backup\" }, { type: \"azure-nextgen:netapp/v20200701:Backup\" }, { type: \"azure-native:netapp/v20200801:Backup\" }, { type: \"azure-nextgen:netapp/v20200801:Backup\" }, { type: \"azure-native:netapp/v20201101:Backup\" }, { type: \"azure-nextgen:netapp/v20201101:Backup\" }, { type: \"azure-native:netapp/v20201201:Backup\" }, { type: \"azure-nextgen:netapp/v20201201:Backup\" }, { type: \"azure-native:netapp/v20210201:Backup\" }, { type: \"azure-nextgen:netapp/v20210201:Backup\" }] };\n opts = pulumi.mergeOptions(opts, aliasOpts);\n super(Backup.__pulumiType, name, inputs, opts);\n }",
"getV3InternalCheck(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.InternalApi();\napiInstance.getV3InternalCheck((error, data, response) => {\n if (error) {\n console.error(error);\n } else {\n console.log('API called successfully.');\n }\n});\n }",
"function test2() {\n const v8 = require('v8');\n console.log(v8.getHeapSpaceStatistics());\n}",
"function runSample(demoCallback) {\n var resourceClient;\n var kvManagementClient;\n \n msRestAzure.loginWithServicePrincipalSecret(clientId, secret, tenantId)\n .then( (credentials) => {\n resourceClient = new ResourceManagementClient(credentials, subscriptionId);\n kvManagementClient = new KeyVaultManagementClient(credentials, subscriptionId);\n \n // Create sample resource group. \n console.log(\"Creating resource group: \" + groupName);\n return resourceClient.resourceGroups.createOrUpdate(groupName, { location: azureLocation });\n }).then( () => {\n const kvParams = {\n location: azureLocation,\n properties: {\n sku: { \n name: 'standard'\n },\n accessPolicies: [\n {\n tenantId: tenantId,\n objectId: objectId,\n permissions: {\n secrets: ['all'],\n }\n }\n ],\n enabledForDeployment: false,\n tenantId: tenantId\n },\n tags: {}\n };\n \n console.log(\"Creating key vault: \" + kvName);\n \n // Create the sample key vault using the KV management client.\n return kvManagementClient.vaults.createOrUpdate(groupName, kvName, kvParams);\n }).then( (result) => {\n console.log(\"Vault created with URI '\" + result.properties.vaultUri + \"'\");\n demoCallback(result.properties.vaultUri);\n })\n .catch( (err) => { \n console.log(err); \n });\n}",
"function ConnectToDevice(deviceIP,UserName,Password)\n{\n PasswordInfo = new dotNET.Renci_SshNet.PasswordConnectionInfo.zctor(deviceIP,UserName,Password) \n SSHClient = new dotNET.Renci_SshNet.SshClient.zctor(PasswordInfo)\n SSHClient.Connect() //method returns void\n Log.Message(\"Created SSH Connection with device.\")\n return true\n}",
"function VarinodeApi() {\n var VERSION = '0.0.0'; // TODO inject package.json\n var USER_AGENT = 'varinode-node-'+VERSION;\n var BASE_API_URL = 'http://apiv1.varinode.com';\n var BASE_API_ENDPOINT = '';\n var BASE_CAPI_URL = 'http://capiv1.varinode.com';\n var BASE_CAPI_ENDPOINT = '';\n var DEFAULT_FORMAT = 'json'; // TODO alternatives?\n var MAX_EXEC_TIME = 20000; // 20s api timeout\n var LOG_PERFORMANCE = 1;\n\n var appKey;\n var appSecret;\n var appPrivateSecret;\n\n var fileUploadSupport = false;\n var self = this;\n\n var state = {sites:{}};\n\n this.setAppKey = function(v) {\n appKey = v;\n return this;\n };\n\n this.setAppSecret = function(v) {\n appSecret = v;\n return this;\n };\n\n this.setAppPrivateSecret = function(v) {\n appPrivateSecret = v;\n return this;\n };\n\n this.getAppKey = function() { return appKey; };\n this.getAppSecret = function() { return appSecret; };\n this.getAppPrivateSecret = function() { return appPrivateSecret; };\n\n this.setFileUploadSupport = function (v) {\n fileUploadSupport = v;\n return this;\n };\n\n this.getFileUploadSupport = function() { return fileUploadSupport; };\n\n this.configure = function(config) {\n this\n .setAppKey(config.appKey)\n .setAppSecret(config.appSecret)\n .setAppPrivateSecret(config.appPrivateSecret);\n\n if (config.debug) log.level(10); \n if (config.fileUpload !== undefined) {\n this.setFileUploadSupport(config.fileUpload);\n }\n };\n\n this.isConfigured = function() {\n return appKey !== undefined && appSecret !== undefined && appPrivateSecret !== undefined;\n };\n\n function build_query(obj, num_prefix, temp_key) {\n var output_string = [];\n Object.keys(obj).forEach(function (val) {\n var key = val;\n if (num_prefix && !isNaN(key)) (key = num_prefix + key);\n key = encodeURIComponent(key.replace(/[!'()*]/g, escape));\n\n // FIXME\n //if (temp_key) key = key ? (temp_key + '[' + key + ']') : key;\n\n if (typeof obj[val] === 'object') {\n var query = build_query(obj[val], null, key);\n output_string.push(query);\n } else {\n var value = encodeURIComponent(obj[val].replace(/[!'()*]/g, escape));\n output_string.push(key + '=' + value);\n }\n });\n\n return output_string.join('&');\n }\n\n this.getState = function() {\n return state;\n };\n\n function persistState (result) {\n // store static response data for later use\n // TODO encapsulate all this\n if (!result) return;\n\n if (result.customer) state.customer_id = result.customer.customer_id;\n if (result.card) state.card_id = result.card.card_id;\n if (result.address) state.address_id = result.address.address_id;\n if (result.cart_id) state.cart_id = result.cart_id;\n if (result.pre_order_id) state.pre_order_id = result.pre_order_id;\n if (result.processed_sites) {\n var sinfo = result.processed_sites[0].site_info;\n var sid = (sinfo||{}).site_id;\n var pid = ((result.processed_sites[0].products || [])[0] || {}).product_id;\n if (sid) state.site_id = sid;\n if (pid) state.product_id = pid;\n if (sinfo && sid) {\n state.site_info = sinfo;\n state.sites[sid] = sinfo;\n }\n }\n //log.debug('persisted', this.state);\n }\n\n this.getParameters = function (site) {\n var siteInfo = state.sites[site];\n if (siteInfo) return {required: siteInfo.required_parameters, optional: siteInfo.optional_parameters};\n };\n\n /**\n * appendParamsToUrl - Gracefully appends params to the URL.\n *\n * @param string url\n * @param array params\n *\n * @return string\n */\n function appendParamsToUrl (url, params)\n {\n var path, query_string, splitUrl;\n if (!params) {\n return url;\n }\n\n //log.debug('appending', params);\n if (url.indexOf('?') === -1) {\n return url + '?' + build_query(params); \n }\n\n splitUrl = url.split('?');\n path = splitUrl.shift();\n query_string = splitUrl.slice(0).join('?');\n\n parse_str(query_string, query_array);\n\n // Favor params from the original URL over params\n params = array_merge(params, query_array);\n\n return path + '?' + build_query(params);\n }\n\n /**\n * Build the URL for given domain alias, path and parameters.\n *\n * @param base string The name of the domain\n * @param path string Optional path (without a leading slash)\n * @param params array Optional query parameters\n *\n * @return string The URL for the given parameters\n */\n function getRequestURL(base, path, params) {\n if (!base) base = '';\n if (!path) path = '';\n if (!params) params = {};\n\n var url = base + '/';\n if (path) {\n if (path[0] === '/') {\n path = path.substr(1);\n }\n url += path;\n }\n if (params) {\n url += '?' + build_query(params, null, '&');\n }\n\n return url;\n }\n\n function clean_string(input) {\n return input.trim().replace(/[^A-Za-z_0-9]/g,'');\n }\n\n function split_type_string(input) {\n var parts = input.split('.');\n return [clean_string(parts[0]),\n clean_string(parts[1])];\n }\n\n function generateSignature(sig_secret, params) {\n var s = '';\n\n for (var k in params) {\n if (params.hasOwnProperty(k)) {\n s += k + '=' + params[k];\n }\n }\n\n s += sig_secret;\n\n return md5(s);\n }\n\n /**\n * Make an API call.\n *\n * @return mixed The decoded response\n */\n this.api = function(method, params, callParams) {\n var api_base, api_endpoint, sig_secret, sig, sig_class_name, sig_method_name;\n var deferred = Q.defer();\n\n var base_url_params = {\n 'appid': self.getAppKey(),\n 'format': DEFAULT_FORMAT,\n 'method': method\n };\n\n (function(s){\n sig_class_name = s[0];\n sig_method_name = s[1];\n })(split_type_string(method));\n\n if(sig_class_name == 'cards' || sig_class_name == 'customers' || sig_class_name == 'addresses') {\n sig_secret = self.getAppPrivateSecret();\n api_base = BASE_CAPI_URL;\n api_endpoint = BASE_CAPI_ENDPOINT;\n } else {\n sig_secret = self.getAppSecret();\n api_base = BASE_API_URL;\n api_endpoint = BASE_API_ENDPOINT;\n }\n\n sig = generateSignature(sig_secret, base_url_params);\n base_url_params.tt_sig = sig;\n\n url = getRequestURL(api_base,api_endpoint,base_url_params);\n\n if (callParams && callParams.method && callParams.method === \"GET\") {\n url = appendParamsToUrl(url, params);\n params = {};\n }\n\n var st = (new Date()).getTime();\n log.debug('api request', method, JSON.stringify(params));\n request.post(url, {\n headers: {\n 'User-Agent': USER_AGENT,\n 'Accept-Encoding': '*'\n },\n json: true, /* ? */\n form: params\n }, function(error, response, result) {\n if (!response) {\n deferred.reject(analyzeAPIException(\"No response\"));\n }\n\n var rt = (new Date()).getTime();\n // Should throw `VarinodeSDKException` exception on HTTP client error.\n // Don't catch to allow it to bubble up.\n // TODO\n var responseCode = response.statusCode;\n var decodedResult = result; //JSON.parse(result);\n var headers = response.headers;\n\n log.debug('api response [' + response.statusCode + ']', method, response.body, response.statusCode > 200 ? response.socket._httpMessage._header : '');\n if (LOG_PERFORMANCE) log.debug('rt ' + ((rt - st)/1000) + 's');\n\n if (!decodedResult) {\n var out = {};\n // split result into out\n // TODO parse_str(result, out);\n log.warn('Result undecodeable', responseCode, headers);\n deferred.resolve(out);\n } else {\n if (!params.doNotPersist) {\n persistState(decodedResult);\n }\n\n if (decodedResult.err) {\n decodedResult.error_code = responseCode;\n deferred.reject(analyzeAPIException(decodedResult));\n } else {\n deferred.resolve(decodedResult);\n }\n }\n });\n\n return deferred.promise.timeout(MAX_EXEC_TIME, \"Varinode API request timed out (exceeded \"+MAX_EXEC_TIME+\"ms)\"); \n };\n\n /**\n * Analyzes the supplied result to see if it was thrown because the access token is no longer valid. If that's\n * the case, then we destroy the session.\n *\n * @deprecated Possibly? TBD.\n * @param result array A record storing the error message returned by a failed API call.\n */\n function analyzeAPIException(result) {\n var e = new VarinodeApiException(result);\n\n switch (e.getType()) {\n // OAuth 2.0 Draft 00 style\n case 'OAuthException':\n // OAuth 2.0 Draft 10 style\n case 'invalid_token':\n // REST server errors are just Exceptions\n case 'Exception':\n message = e.getMessage();\n break;\n }\n\n return e;\n }\n\n function errorHandler(result) {\n log.error('Broken promise',result);\n }\n}",
"async init() { }",
"constructor(scope, id, props) {\n super(scope, id, { type: CfnVirtualService.CFN_RESOURCE_TYPE_NAME, properties: props });\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_aws_appmesh_CfnVirtualServiceProps(props);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, CfnVirtualService);\n }\n throw error;\n }\n cdk.requireProperty(props, 'meshName', this);\n cdk.requireProperty(props, 'spec', this);\n cdk.requireProperty(props, 'virtualServiceName', this);\n this.attrArn = cdk.Token.asString(this.getAtt('Arn', cdk.ResolutionTypeHint.STRING));\n this.attrMeshName = cdk.Token.asString(this.getAtt('MeshName', cdk.ResolutionTypeHint.STRING));\n this.attrMeshOwner = cdk.Token.asString(this.getAtt('MeshOwner', cdk.ResolutionTypeHint.STRING));\n this.attrResourceOwner = cdk.Token.asString(this.getAtt('ResourceOwner', cdk.ResolutionTypeHint.STRING));\n this.attrUid = cdk.Token.asString(this.getAtt('Uid', cdk.ResolutionTypeHint.STRING));\n this.attrVirtualServiceName = cdk.Token.asString(this.getAtt('VirtualServiceName', cdk.ResolutionTypeHint.STRING));\n this.meshName = props.meshName;\n this.spec = props.spec;\n this.virtualServiceName = props.virtualServiceName;\n this.meshOwner = props.meshOwner;\n this.tags = new cdk.TagManager(cdk.TagType.STANDARD, \"AWS::AppMesh::VirtualService\", props.tags, { tagPropertyName: 'tags' });\n }",
"async _getVaultLabel(args, vaultAddress) {\n const vaultAbi = [{\"inputs\":[{\"internalType\":\"contract IStrategy\",\"name\":\"_strategy\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"balance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"internalType\":\"uint8\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"subtractedValue\",\"type\":\"uint256\"}],\"name\":\"decreaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"deposit\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"depositAll\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"getLastTimeRestaked\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"getLastTimeStaked\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getRatio\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"addedValue\",\"type\":\"uint256\"}],\"name\":\"increaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"keepMax\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"strategy\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"token\",\"outputs\":[{\"internalType\":\"contract IERC20\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_shares\",\"type\":\"uint256\"}],\"name\":\"withdraw\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"withdrawAll\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}];\n const lpAbi = [{\"inputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount0\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount1\",\"type\":\"uint256\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"}],\"name\":\"Burn\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount0\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount1\",\"type\":\"uint256\"}],\"name\":\"Mint\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount0In\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount1In\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount0Out\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"amount1Out\",\"type\":\"uint256\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"}],\"name\":\"Swap\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint112\",\"name\":\"reserve0\",\"type\":\"uint112\"},{\"indexed\":false,\"internalType\":\"uint112\",\"name\":\"reserve1\",\"type\":\"uint112\"}],\"name\":\"Sync\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"DOMAIN_SEPARATOR\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"MINIMUM_LIQUIDITY\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"PERMIT_TYPEHASH\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"}],\"name\":\"burn\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"amount0\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amount1\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"internalType\":\"uint8\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"factory\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getReserves\",\"outputs\":[{\"internalType\":\"uint112\",\"name\":\"_reserve0\",\"type\":\"uint112\"},{\"internalType\":\"uint112\",\"name\":\"_reserve1\",\"type\":\"uint112\"},{\"internalType\":\"uint32\",\"name\":\"_blockTimestampLast\",\"type\":\"uint32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_token0\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"_token1\",\"type\":\"address\"}],\"name\":\"initialize\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"kLast\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"}],\"name\":\"mint\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"liquidity\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"nonces\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"deadline\",\"type\":\"uint256\"},{\"internalType\":\"uint8\",\"name\":\"v\",\"type\":\"uint8\"},{\"internalType\":\"bytes32\",\"name\":\"r\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"permit\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"price0CumulativeLast\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"price1CumulativeLast\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"}],\"name\":\"skim\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amount0Out\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"amount1Out\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"swap\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"sync\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"token0\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"token1\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}];\n const vaultContract = new args.web3.eth.Contract(vaultAbi, vaultAddress);\n const lpToken = await vaultContract.methods.token().call();\n const lpContract = new args.web3.eth.Contract(lpAbi, lpToken);\n const tokenName = await lpContract.methods.name().call();\n if (tokenName === \"SushiSwap LP Token\") {\n const token0 = await lpContract.methods.token0().call();\n const token1 = await lpContract.methods.token1().call();\n const erc20Abi = [{\"constant\":true,\"inputs\":[],\"name\":\"mintingFinished\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_token\",\"type\":\"address\"}],\"name\":\"reclaimToken\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"unpause\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"mint\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"burn\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"claimOwnership\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"paused\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_subtractedValue\",\"type\":\"uint256\"}],\"name\":\"decreaseApproval\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"finishMinting\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"pause\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_addedValue\",\"type\":\"uint256\"}],\"name\":\"increaseApproval\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"pendingOwner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[],\"name\":\"Pause\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[],\"name\":\"Unpause\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"burner\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Burn\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"Mint\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[],\"name\":\"MintFinished\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"previousOwner\",\"type\":\"address\"}],\"name\":\"OwnershipRenounced\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"}];\n const token0Contract = new args.web3.eth.Contract(erc20Abi, token0);\n const token1Contract = new args.web3.eth.Contract(erc20Abi, token1);\n const token0Symbol = await token0Contract.methods.symbol().call();\n const token1Symbol = await token1Contract.methods.symbol().call();\n return token0Symbol + \"-\" + token1Symbol;\n }\n return tokenName;\n }",
"constructor() {\n\n V1DaskReplica.initialize(this);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructor creates a new vector drawer. Parameters: astroMap the map to draw the vectors on layer the layer to draw the vectors on (should be an OL vector layer) | function AstroVector(astroMap, layer) {
this.astroMap = astroMap;
this.layer = layer;
// for storing vectors and their state
this.storedVectors = [];
this.styles = [];
this.selectStyle = new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 128, 0, 0.2)'
}),
stroke: new ol.style.Stroke({
color: '#ff8000',
width: 2
})
});
// index into stored vectors array for vector currently being modified.
// Is -1 if currently modified vector isn't saved, or if we aren't modifying
// anything
this.savedIndex = -1;
} | [
"constructor(options, labelOptions, map) {\n //If certain options were not set then provide a default value for them\n options.style = options.style || ol.style.arcLabelStyleFunction;\n options.updateWhileAnimating = options.updateWhileAnimating || false;\n options.updateWhileInteracting = options.updateWhileInteracting || false;\n options.renderMode = options.renderMode || 'vector';\n options.source = options.source || new source.Vector();\n //No decluttering as it would hide labels randomly\n options.declutter = false;\n //Get zoom range from area type\n let minZoom = labelOptions.zoom_min;\n let maxZoom = labelOptions.zoom_max;\n //Set default options (if necessary) and call vector layer constructor\n super(options, map, minZoom, maxZoom);\n this.labelOptions = labelOptions;\n }",
"function VectormapView(html_id) {\n var DEFAULT_ID = 'energy2d-vectormap-view',\n VECTOR_SCALE = 100,\n VECTOR_BASE_LEN = 8,\n WING_COS = Math.cos(0.523598776),\n WING_SIN = Math.sin(0.523598776),\n WING_LEN = 4,\n ARROW_COLOR = \"rgb(175,175,175)\",\n $vectormap_canvas,\n canvas_ctx,\n canvas_width,\n canvas_height,\n vectormap_u,\n vectormap_v,\n grid_width,\n grid_height,\n spacing,\n enabled = true,\n //\n // Private methods.\n //\n initHTMLelement = function initHTMLelement() {\n $vectormap_canvas = $('<canvas />');\n $vectormap_canvas.attr('id', html_id || DEFAULT_ID);\n canvas_ctx = $vectormap_canvas[0].getContext('2d');\n },\n // Helper method for drawing a single vector.\n drawVector = function drawVector(x, y, vx, vy) {\n var r = 1.0 / Math.sqrt(vx * vx + vy * vy),\n arrowx = vx * r,\n arrowy = vy * r,\n x1 = x + arrowx * VECTOR_BASE_LEN + vx * VECTOR_SCALE,\n y1 = y + arrowy * VECTOR_BASE_LEN + vy * VECTOR_SCALE,\n wingx = WING_LEN * (arrowx * WING_COS + arrowy * WING_SIN),\n wingy = WING_LEN * (arrowy * WING_COS - arrowx * WING_SIN);\n canvas_ctx.beginPath();\n canvas_ctx.moveTo(x, y);\n canvas_ctx.lineTo(x1, y1);\n canvas_ctx.lineTo(x1 - wingx, y1 - wingy);\n canvas_ctx.moveTo(x1, y1);\n wingx = WING_LEN * (arrowx * WING_COS - arrowy * WING_SIN);\n wingy = WING_LEN * (arrowy * WING_COS + arrowx * WING_SIN);\n canvas_ctx.lineTo(x1 - wingx, y1 - wingy);\n canvas_ctx.stroke();\n },\n //\n // Public API.\n //\n vectormap_view = {\n // Render vectormap on the canvas.\n renderVectormap: function renderVectormap() {\n if (!enabled) return;\n var dx, dy, x0, y0, uij, vij, i, j, iny, ijny;\n\n if (!vectormap_u || !vectormap_v) {\n throw new Error(\"Vectormap: bind vectormap before rendering.\");\n }\n\n dx = canvas_width / grid_width;\n dy = canvas_height / grid_height;\n canvas_ctx.clearRect(0, 0, canvas_width, canvas_height);\n canvas_ctx.strokeStyle = ARROW_COLOR;\n canvas_ctx.lineWidth = 1;\n\n for (i = 1; i < grid_width - 1; i += spacing) {\n iny = i * grid_height;\n x0 = (i + 0.5) * dx; // + 0.5 to move arrow into field center\n\n for (j = 1; j < grid_height - 1; j += spacing) {\n ijny = iny + j;\n y0 = (j + 0.5) * dy; // + 0.5 to move arrow into field center\n\n uij = vectormap_u[ijny];\n vij = vectormap_v[ijny];\n\n if (uij * uij + vij * vij > 1e-15) {\n drawVector(x0, y0, uij, vij);\n }\n }\n }\n },\n clear: function clear() {\n canvas_ctx.clearRect(0, 0, canvas_width, canvas_height);\n },\n\n get enabled() {\n return enabled;\n },\n\n set enabled(v) {\n enabled = v; // Clear vectormap, as .renderVectormap() call won't do it.\n\n if (!enabled) vectormap_view.clear();\n },\n\n // Bind vector map to the view.\n bindVectormap: function bindVectormap(new_vectormap_u, new_vectormap_v, new_grid_width, new_grid_height, arrows_per_row) {\n if (new_grid_width * new_grid_height !== new_vectormap_u.length) {\n throw new Error(\"Heatmap: provided U component of vectormap has wrong dimensions.\");\n }\n\n if (new_grid_width * new_grid_height !== new_vectormap_v.length) {\n throw new Error(\"Heatmap: provided V component of vectormap has wrong dimensions.\");\n }\n\n vectormap_u = new_vectormap_u;\n vectormap_v = new_vectormap_v;\n grid_width = new_grid_width;\n grid_height = new_grid_height;\n spacing = Math.round(new_grid_width / arrows_per_row);\n },\n getHTMLElement: function getHTMLElement() {\n return $vectormap_canvas;\n },\n resize: function resize() {\n canvas_width = $vectormap_canvas.width();\n canvas_height = $vectormap_canvas.height();\n $vectormap_canvas.attr('width', canvas_width);\n $vectormap_canvas.attr('height', canvas_height);\n }\n }; // One-off initialization.\n\n\n initHTMLelement();\n return vectormap_view;\n}",
"constructor(options, map, minZoom, maxZoom) {\n //Call vector layer constructor and pass layer options\n super(options);\n this._minZoom = 0;\n this._maxZoom = Number.POSITIVE_INFINITY;\n this._displayIntention = true;\n this.map = map;\n //Update zoom range\n if (typeof minZoom !== \"undefined\") {\n this._minZoom = minZoom;\n }\n if (typeof maxZoom !== \"undefined\") {\n this._maxZoom = maxZoom;\n }\n let updateFunc = this.updateVisibility.bind(this);\n //Register move end event handler on map in order to check for the zoom level\n this.map.on('moveend', updateFunc);\n }",
"constructor(options, areaType, map) {\n //If certain options were not set then provide a default value for them\n options.style = options.style || ol.style.areaStyleFunction(areaType);\n options.updateWhileAnimating = options.updateWhileAnimating || false;\n options.updateWhileInteracting = options.updateWhileInteracting || false;\n options.renderMode = options.renderMode || 'image'; //'vector' is default\n options.declutter = true;\n //Get zoom range from area type\n let minZoom = areaType.zoom_min;\n let maxZoom = areaType.zoom_max;\n //Set default options (if necessary) and call vector layer constructor\n super(options, map, minZoom, maxZoom);\n this.areaType = areaType;\n //Check if labels are desired for this area type\n if (this.areaType.labels) {\n this._hasLabels = true;\n //Create label layer and add it to the map\n this.labelLayer = new ol.layer.AreaLabel({\n source: new ol.source.Vector(),\n zIndex: this.areaType.z_index + LABEL_LAYER_Z_INDEX\n }, areaType.labels, map);\n //Add label layer to map\n map.addLayer(this.labelLayer);\n }\n else {\n this._hasLabels = false;\n }\n //No highlighting yet\n this.highlightLocation = null;\n //Save reference to current scope\n let _this = this;\n //Check if area source is used\n if (!(this.getSource() instanceof ol.source.Area)) {\n return;\n }\n //Cast to area source\n let source = this.getSource();\n //Register a feature listener\n source.addFeatureListener(function (feature) {\n _this.checkFeatureForHighlight(feature);\n _this.createLabelForFeature(feature);\n });\n }",
"function VectormapWebGLView(html_id) {\n var // Get WebGL context.\n gl = gpu_context.getWebGLContext(),\n // GLSL Render program.\n render_program = new shader(vectormap_vs, vectormap_fs),\n // Plane used for rendering.\n arrows = new mesh({\n coords: true,\n lines: true\n }),\n DEFAULT_ID = 'energy2d-vectormap-webgl-view',\n VECTOR_SCALE = 100,\n VECTOR_BASE_LEN = 8,\n ARROW_COLOR = [0.7, 0.7, 0.7, 1.0],\n $vectormap_canvas,\n canvas_width,\n canvas_height,\n vectormap_tex,\n grid_width,\n grid_height,\n spacing,\n enabled = true,\n //\n // Private methods.\n //\n initGeometry = function initGeometry() {\n var i,\n j,\n idx,\n origin,\n coord,\n gdx = 2.0 / grid_width,\n gdy = 2.0 / grid_height,\n tdx = 1.0 / grid_width,\n tdy = 1.0 / grid_height;\n arrows.addVertexBuffer('origins', 'origin');\n arrows.vertices = [];\n arrows.origins = [];\n arrows.coords = [];\n arrows.lines = [];\n idx = 0;\n\n for (i = 1; i < grid_width - 1; i += spacing) {\n for (j = 1; j < grid_height - 1; j += spacing) {\n // Base arrows vertices. Origin, front and two wings. The unit is pixel.\n // Base length is 0.01 px - just for convenience (it distinguish front of the arrows from the origin).\n arrows.vertices.push([0, 0, 0], [0.01, 0, 0], [-3, 2, 0], [-3, -2, 0]); // All of these vertices have to know which vector they are representing.\n\n origin = [-1.0 + (i + 0.5) * gdx, 1.0 - (j + 0.5) * gdy, 0];\n arrows.origins.push(origin, origin, origin, origin); // Texture coordinates.\n\n coord = [(j + 0.5) * tdy, (i + 0.5) * tdx];\n arrows.coords.push(coord, coord, coord, coord); // Draw three lines. From origin to the fron of the arrows + two wings.\n\n arrows.lines.push([idx, idx + 1], [idx + 1, idx + 2], [idx + 1, idx + 3]);\n idx += 4;\n }\n } // Update buffers.\n\n\n arrows.compile();\n },\n initHTMLelement = function initHTMLelement() {\n $vectormap_canvas = $(gl.canvas);\n $vectormap_canvas.attr('id', html_id || DEFAULT_ID);\n },\n // Make sure that no FBO is bound and viewport has proper dimensions\n // (it's not obvious as this context is also used for GPGPU calculations).\n setupRenderTarget = function setupRenderTarget() {\n // Ensure that FBO is null, as GPGPU operations which use FBOs also take place.\n gl.bindFramebuffer(gl.FRAMEBUFFER, null); // This is necessary, as GPGPU operations can modify viewport size.\n\n gl.viewport(0, 0, canvas_width, canvas_height);\n },\n //\n // Public API.\n //\n vectormap_view = {\n // Render heat map on the canvas.\n renderVectormap: function renderVectormap() {\n if (!enabled) return;\n\n if (!vectormap_tex) {\n throw new Error(\"Vectormap: bind heatmap texture before rendering.\");\n }\n\n setupRenderTarget();\n vectormap_tex.bind(0);\n render_program.draw(arrows, gl.LINES);\n vectormap_tex.unbind(0);\n },\n\n get enabled() {\n return enabled;\n },\n\n set enabled(v) {\n enabled = v;\n },\n\n resize: function resize() {\n canvas_width = $vectormap_canvas.width();\n canvas_height = $vectormap_canvas.height();\n $vectormap_canvas.attr('width', canvas_width);\n $vectormap_canvas.attr('height', canvas_height); // Render ara has dimensions from -1.0 to 1.0, so its width/height is 2.0.\n\n render_program.uniforms({\n scale: [2.0 / canvas_width, 2.0 / canvas_height]\n });\n },\n // Bind vectormap to the view.\n bindVectormapTexture: function bindVectormapTexture(new_vectormap_tex, new_grid_width, new_grid_height, arrows_per_row) {\n vectormap_tex = new_vectormap_tex;\n grid_width = new_grid_width;\n grid_height = new_grid_height;\n spacing = Math.round(grid_width / arrows_per_row);\n initGeometry();\n },\n getHTMLElement: function getHTMLElement() {\n return $vectormap_canvas;\n }\n }; // One-off initialization.\n // Set render program uniforms.\n\n\n render_program.uniforms({\n // Texture units.\n vectormap_tex: 0,\n // Uniforms.\n base_length: VECTOR_BASE_LEN,\n vector_scale: VECTOR_SCALE,\n color: ARROW_COLOR\n });\n initHTMLelement();\n return vectormap_view;\n}",
"function VectorsRenderer(pixiContainer, config) {\n // Public API object to be returned.\n var api, m2px, m2pxInv, container, viewVectors, // Vectors rendering enabled or disabled.\n show, // Number of vectors to render.\n count, // Physical vector properties (functions!).\n xFunc, yFunc, vxFunc, vyFunc, // Visual vector properties.\n alphaFunc, length, width, color, dirOnly;\n\n function readOptions() {\n count = config.count;\n xFunc = config.x;\n yFunc = config.y;\n vxFunc = config.vx;\n vyFunc = config.vy;\n alphaFunc = config.alpha;\n show = config.show;\n length = config.length;\n width = config.width;\n color = config.color;\n dirOnly = config.dirOnly;\n m2px = config.m2px;\n m2pxInv = config.m2pxInv;\n }\n\n function getVectorTexture() {\n var canv = document.createElement(\"canvas\"),\n ctx = canv.getContext(\"2d\");\n canv.width = 1;\n canv.height = 1;\n ctx.fillStyle = color;\n ctx.fillRect(0, 0, 1, 1);\n return new pixi_default.a.Texture.fromCanvas(canv);\n }\n\n function getVectorArrowheadTexture() {\n var canv = document.createElement(\"canvas\"),\n ctx = canv.getContext(\"2d\"),\n dim = m2px(3.5 * width);\n canv.width = dim;\n canv.height = dim;\n ctx.fillStyle = color;\n ctx.beginPath();\n ctx.moveTo(0, 0);\n ctx.lineTo(dim, 0);\n ctx.lineTo(dim * 0.5, dim);\n ctx.closePath();\n ctx.fill();\n return new pixi_default.a.Texture.fromCanvas(canv);\n }\n\n function renderVector(i) {\n var vec = viewVectors[i],\n x = xFunc(i),\n y = yFunc(i),\n vx = vxFunc(i) * length,\n vy = vyFunc(i) * length,\n len = Math.sqrt(vx * vx + vy * vy),\n rot = Math.PI + Math.atan2(vx, vy),\n arrowHead = vec.arrowHead;\n\n if (dirOnly) {\n // 0.15 is a bit random, empirically set value to match previous rendering done by SVG.\n vx = 0.15 * length * vx / len;\n vy = 0.15 * length * vy / len;\n len = 0.15 * length;\n }\n\n var lenInPx = m2px(len);\n\n if (lenInPx < 1) {\n // Hide completely tiny vectors (< 1px).\n vec.alpha = 0;\n arrowHead.alpha = 0;\n return;\n } else if (alphaFunc) {\n vec.alpha = alphaFunc(i);\n arrowHead.alpha = alphaFunc(i);\n } else {\n vec.alpha = 1;\n arrowHead.alpha = 1;\n }\n\n if (lenInPx > 1e6) {\n // When vectors has enormous size, it can cause rendering artifacts. Limit it.\n var s = lenInPx / 1e6;\n vx /= s;\n vy /= s;\n len /= s;\n lenInPx /= s;\n } // Vector.\n\n\n vec.position.x = m2px(x);\n vec.position.y = m2pxInv(y);\n vec.scale.y = lenInPx;\n vec.rotation = rot; // Arrowhead.\n\n arrowHead.position.x = m2px(x + vx);\n arrowHead.position.y = m2pxInv(y + vy);\n arrowHead.rotation = rot;\n }\n\n api = {\n setup: function setup() {\n readOptions();\n\n if (container) {\n pixiContainer.removeChild(container);\n container = null;\n }\n\n if (!show || count === 0) return;\n container = new pixi_default.a.DisplayObjectContainer();\n pixiContainer.addChild(container);\n var i, vec, arrowHead, tex;\n viewVectors = [];\n tex = getVectorTexture();\n\n for (i = 0; i < count; ++i) {\n vec = new pixi_default.a.Sprite(tex);\n vec.anchor.x = 0.5;\n vec.scale.x = m2px(width);\n vec.i = i;\n viewVectors.push(vec);\n container.addChild(vec);\n }\n\n tex = getVectorArrowheadTexture();\n\n for (i = 0; i < count; ++i) {\n arrowHead = new pixi_default.a.Sprite(tex);\n arrowHead.anchor.x = 0.5;\n viewVectors[i].arrowHead = arrowHead;\n container.addChild(arrowHead);\n }\n\n api.update();\n },\n update: function update() {\n if (!show || count === 0) return;\n\n for (var i = 0; i < count; ++i) {\n renderVector(i);\n }\n }\n };\n return api;\n}",
"initPrintExtentLayer() {\n if (!(this.extentLayer instanceof OlLayerVector)) {\n const extentLayer = new OlLayerVector({\n name: BaseMapFishPrintManager.EXTENT_LAYER_NAME,\n source: new OlSourceVector(),\n style: new OlStyleStyle({\n fill: new OlStyleFill({\n color: 'rgba(255, 255, 130, 0)'\n })\n })\n });\n\n extentLayer.on('prerender', this.onExtentLayerPreRender.bind(this));\n extentLayer.on('postrender', this.onExtentLayerPostRender.bind(this));\n\n this.extentLayer = extentLayer;\n\n if (Shared.getLayersByName(this.map,\n BaseMapFishPrintManager.EXTENT_LAYER_NAME).length === 0) {\n this.map.addLayer(this.extentLayer);\n }\n }\n }",
"projection(other_vector) {}",
"function Renderable() {\n\tthis.mPos = new Vec2(0, 0);\n\tthis.mSize = new Vec2(0, 0);\n\tthis.mOrigin = new Vec2(0, 0);\n\tthis.mAbsolute = false;\n\t\n\tthis.mDepth = 0;\n\t\n\tthis.mTransformation = new Matrix3();\n\tthis.mScale = new Vec2(1.0, 1.0);\n\tthis.mRotation = 0;\n\tthis.mSkew = new Vec2();\n\tthis.mAlpha = 1.0;\n\tthis.mCompositeOp = \"source-over\";\n\t\n\tthis.mLocalBoundingBox = new Polygon(); // the local bounding box is in object coordinates (no transformations applied)\n\tthis.mGlobalBoundingBox = new Polygon(); // the global bounding box is in world coordinates (transformations applied)\n\t\n\tthis.mLocalMask = new Polygon();\n\tthis.mGlobalMask = new Polygon();\n}",
"function EChartsGL (zr) {\n this._layers = {};\n\n this._zr = zr;\n}",
"function drawOrientationVector(path) {\n var v = createVector((path[1].x + citySize / 2) - (path[0].x + citySize / 2), (path[1].y + citySize / 2) - (path[0].y + citySize / 2));\n v.setMag(0.5 * v.mag());\n stroke(0, 0, 255, 150);\n strokeWeight(2);\n applyMatrix();\n translate(path[0].x + citySize / 2, path[0].y + citySize / 2);\n line(0, 0, v.x, v.y);\n resetMatrix();\n strokeWeight(3);\n stroke(255, 160, 0, 150);\n}",
"function mapa_crearMapa() {\n\tvar dominio = JSON.parse(localStorage.getItem('dominio'));\n\tvar usuario_zonas = JSON.parse(localStorage.getItem('usuario_zonas'));\n\tvar zonas_codigos = {};\n\tvar zonas_colores = {};\n\tg_lista_zonas = usuario_zonas;\n\tfor (var i = 0; i < usuario_zonas.length; i++) {\n\t\tvar zona_id = usuario_zonas[i].idzona;\n\t\tvar zona_nombre = usuario_zonas[i].nombre;\n\t\tvar zona_color_hex = usuario_zonas[i].color_hex;\n\t\tvar zonas_subzonas = usuario_zonas[i].subzonas;\n\t\tfor (var j = 0; j < zonas_subzonas.length; j++) {\n\t\t\tvar subzona_estado_codigo = zonas_subzonas[j].estado_codigo;\n\t\t\tvar subzona_estado_nombre = zonas_subzonas[j].estado_nombre;\n\t\t\tif (!zonas_codigos.hasOwnProperty(subzona_estado_codigo)) {\n\t\t\t\tvar subzona_estado_escuelas = zonas_subzonas[j].escuelas;\n\t\t\t\tvar subzona_estado_escuelas_total = zonas_subzonas[j].escuelas_total;\n\t\t\t\tzonas_codigos[subzona_estado_codigo] = zona_nombre;\n\t\t\t\tg_mapa_subzonas.push({\n\t\t\t\t\tzona_id: zona_id,\n\t\t\t\t\tzona_nombre: zona_nombre,\n\t\t\t\t\testado_codigo: subzona_estado_codigo,\n\t\t\t\t\testado_nombre: subzona_estado_nombre,\n\t\t\t\t\tescuelas: subzona_estado_escuelas,\n\t\t\t\t\tescuelas_total: subzona_estado_escuelas_total\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tzonas_colores[zona_nombre] = zona_color_hex;\n\t}\n\t$('#vmap').vectorMap({\n\t\tmap: 'mx_en',\n\t\tenableZoom: true,\n\t\tshowTooltip: true,\n\t\tbackgroundColor: '#a5bfdd',\n\t\tborderColor: '#818181',\n\t\tborderOpacity: 0.25,\n\t\tborderWidth: 1,\n\t\tcolor: '#f4f3f0',\n\t\thoverColor: '#c9dfaf',\n\t\thoverOpacity: null,\n\t\tnormalizeFunction: 'polynomial',\n\t\tscaleColors: ['#b6d6ff', '#005ace'],\n\t\tselectedColor: '#c9dfaf',\n\t\tregionsSelectable: true,\n\t\tregionsSelectableOne: true,\n\t\tregionStyle: {\n\t\t\tinitial: {\n\t\t\t\tfill: '#eee',\n\t\t\t\t'fill-opacity': 1,\n\t\t\t\tstroke: 'black',\n\t\t\t\t'stroke-width': 0.5,\n\t\t\t\t'stroke-opacity': 1\n\t\t\t},\n\t\t\thover: {\n\t\t\t\tfill: '#000000',\n\t\t\t\t'fill-opacity': 0.5,\n\t\t\t\tcursor: 'pointer'\n\t\t\t},\n\t\t\tselected: {\n\t\t\t\tfill: '#3333'\n\t\t\t},\n\t\t\tselectedHover: {}\n\t\t},\n\t\tregionLabelStyle: {\n\t\t\tinitial: {\n\t\t\t\t'font-family': 'Verdana',\n\t\t\t\t'font-size': '12',\n\t\t\t\t'font-weight': 'bold',\n\t\t\t\tcursor: 'default',\n\t\t\t\tfill: 'black'\n\t\t\t},\n\t\t\thover: {\n\t\t\t\tcursor: 'pointer'\n\t\t\t}\n\t\t},\n\t\tseries: {\n\t\t\tregions: [{\n\t\t\t\tvalues: zonas_codigos,\n\t\t\t\tscale: zonas_colores,\n\t\t\t\tnormalizeFunction: 'polynomial'\n\t\t\t}]\n\t\t},\n\t\tonRegionSelected: function(element, code, region, isSelected) {\n\t\t\tif (g_mapa_interacciones == true) {\n\t\t\t\tvar regiones = $('#vmap').vectorMap('get', 'mapObject').getSelectedRegions();\n\t\t\t\tif (regiones.length === 1) {\n\t\t\t\t\t$('#vmap').vectorMap('get', 'mapObject').setFocus({\n\t\t\t\t\t\tregion: code,\n\t\t\t\t\t\tanimate: true\n\t\t\t\t\t});\n\t\t\t\t\tvar subzona = obtenerObjectoEnArreglo(g_mapa_subzonas, 'estado_codigo', code);\n\t\t\t\t\tvar zona = obtenerObjectoEnArreglo(g_lista_zonas, 'idzona', subzona.zona_id);\n\t\t\t\t\tg_mapa_zona_seleccionada_id = zona.idzona;\n\t\t\t\t\tg_mapa_subzona_seleccionada_id = subzona.estado_codigo;\n\t\t\t\t\tmapa_cargarSelectZonasSubzonasDesdeMapa(g_mapa_zona_seleccionada_id, g_mapa_subzona_seleccionada_id, true);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tonRegionTipShow: function(e, el, code) {\n\t\t\t/*var zona = zonas_codigos[code];\n\t\t\tif (zona !== undefined) {\n\t\t\t var subzona = obtenerObjectoEnArreglo(g_mapa_subzonas, 'estado_codigo', code);\n\t\t\t var subzona_escuelas_total = subzona.escuelas_total;\n\t\t\t el.html(zona + ' • ' + el.html() + ' • ' + subzona_escuelas_total + ' escuelas');\n\t\t\t} else {\n\t\t\t el.html('¡No hay escuelas de ' + dominio + ' en ' + el.html() + '!');\n\t\t\t}*/\n\t\t\tel.html('');\n\t\t}\n\t});\n}",
"assignVector( name ) {\n\n let Vector;\n\n switch( name ) {\n case 'menu' : Vector = <Menu />; break;\n case 'close' : Vector = <Close />; break;\n case 'my-rewards' : Vector = <MyRewards />; break;\n case 'shop' : Vector = <Shop />; break;\n case 'programs' : Vector = <Programs />; break;\n case 'scorecard' : Vector = <Scorecard />; break;\n case 'leaderboard' : Vector = <Leaderboard />; break;\n case 'quickhits' : Vector = <QuickHits />; break;\n case 'recognition' : Vector = <Recognition />; break;\n case 'videos' : Vector = <Videos />; break;\n case 'agenda' : Vector = <Agenda />; break;\n case 'agenda-new' : Vector = <AgendaNew />; break;\n case 'extras' : Vector = <Extras />; break;\n case 'tools' : Vector = <Tools />; break;\n case 'right-arrow' : Vector = <RightArrow />; break;\n case 'left-arrow' : Vector = <LeftArrow />; break;\n case 'up-arrow' : Vector = <UpArrow />; break;\n case 'down-arrow' : Vector = <DownArrow />; break;\n case 'right-arrow-circled' : Vector = <RightArrowCircled />; break;\n case 'list' : Vector = <List />; break;\n case 'pie-chart' : Vector = <PieChart />; break;\n case 'flip-arrow' : Vector = <FlipArrow />; break;\n case 'comments' : Vector = <Comments />; break;\n case 'smiley' : Vector = <Smiley />; break;\n case 'static-arrow' : Vector = <StaticArrow />; break;\n case 'positive-arrow' : Vector = <PositiveArrow />; break;\n case 'negative-arrow' : Vector = <NegativeArrow />; break;\n case 'info' : Vector = <Info />; break;\n case 'share' : Vector = <Share />; break;\n case 'check' : Vector = <Check />; break;\n case 'plus' : Vector = <Plus />; break;\n case 'minus' : Vector = <Minus />; break;\n case 'socialhub': Vector = <SocialHub />; break;\n case '2016-base-plan' : Vector = <DollarSign/>; break;\n case 'recognition-travel' : Vector = <Travel />; break;\n case 'goal-quest-2015-managers' : Vector = <Warehouse />; break;\n case 'goal-quest' : Vector = <Warehouse />; break;\n case 'e-recognition': Vector = <ERecognition />; break;\n case 'vz-badges': Vector = <VzBadges />; break;\n case 'quizzes-and-surveys': Vector = <Quiz />; break;\n case 'multi-media': Vector = <MultiMedia />; break;\n case 'help-center': Vector = <HelpCenter />; break;\n case 'taxes': Vector = <Taxes />; break;\n case 'miscellaneous': Vector = <Miscellaneous />; break;\n case 'awardperqs-issuance': Vector = <AwardperqsIssuance />; break;\n case 'etickets-issuance': Vector = <ETicketsIssuance />; break;\n case 'user-management-tools': Vector = <UserManagementTools />; break;\n case 'web-trend-reports': Vector = <WebTrendReports />; break;\n case 'instant-win-management': Vector = <InstantWinManagement />; break;\n case 'download': Vector = <Download />; break;\n case 'print': Vector = <Print />; break;\n case 'big-arrow': Vector = <BigArrow />; break;\n case 'mail': Vector = <Mail />; break;\n case 'customer-support': Vector = <CustomerSupport />; break;\n case 'calling': Vector = <Calling />; break;\n case 'profile-icon': Vector = <ProfileIcon />; break;\n }\n\n return Vector;\n }",
"function initOpenLayersMap() {\r\n map = new OpenLayers.Map('map', mapInitParams);\r\n \r\n }",
"function MenuOverlay(menu, position, map) {\r\n\r\n// console.info('MenuOverlay');\r\n\r\n this.menu_ = menu;\r\n\r\n this.position_ = position;\r\n\r\n this.div_ = null;\r\n\r\n this.setMap(map);\r\n}",
"initializeMap() {\n this.map.width = window.innerWidth / 3;\n this.map.height = window.innerHeight / 2;\n this.arrow = document.createElement(\"img\");\n this.arrow.src = \"./assets/arrow_up_left.svg\";\n this.cubeLength = (window.innerWidth / 3) / Math.max(this.ref.maxX, this.ref.maxY, this.ref.maxZ) / 4;\n\n }",
"get vectorLayer() {\n return this.#vectorLayer;\n }",
"constructor(centerOfMap, data) {\r\n super();\r\n this.centerOfMap = centerOfMap;\r\n this.data = data;\r\n }",
"function geometryrendering (pointsString, format, separator, geometry, vectorLayer, style, mapObjcetName, layerOptions, replace){\n var pointsArray=pointsString.split(separator);\n if(pointsArray.lenght==0)\n pointsArray[0]=pointsString; \n var i,latIndex,lonIndex,formatSeparator,tempPointSplit;\n var latFormatPosition=format.indexOf('lat');\n formatSeparator=format[3];\n if(latFormatPosition == 0){\n latIndex=0;lonIndex=1; \n }else{\n latIndex=1;lonIndex=0; \n }\n var olPointsArray=new Array();\n var olStyle;\n if (style && style!=\"\")\n olStyle=style;\n else\n olStyle = {\n fillColor: \"#ee9900\",\n fillOpacity: 0.4, \n hoverFillColor: \"white\",\n hoverFillOpacity: 0.8,\n strokeColor: \"#ee9900\",\n strokeOpacity: 1,\n strokeWidth: 1,\n strokeLinecap: \"round\",\n hoverStrokeColor: \"red\",\n hoverStrokeOpacity: 1,\n hoverStrokeWidth: 0.2,\n pointRadius: 6,\n hoverPointRadius: 1,\n hoverPointUnit: \"%\",\n pointerEvents: \"visiblePainted\",\n cursor: \"\"\n }\n for(i=0; i<pointsArray.length;i++){\n tempPointSplit=pointsArray[i].split(formatSeparator); \n olPointsArray.push(new OpenLayers.Geometry.Point(tempPointSplit[lonIndex], tempPointSplit[latIndex])); \n }\n var mapObject=eval(mapObjcetName);\n var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);\n if(layerOptions.layerFillOpacity)\n layer_style.fillOpacity = layerOptions.layerFillOpacity;\n if(layerOptions.layerGraphicOpacity)\n layer_style.graphicOpacity = layerOptions.layerGraphicOpacity;\n var feature;\n switch(geometry){\n case \"polygon\":\n var linearRing = new OpenLayers.Geometry.LinearRing(olPointsArray);\n feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([linearRing]),null,olStyle);\n break;\n case \"point\":\n feature = new OpenLayers.Feature.Vector(olPointsArray[0],null,olStyle);\n break; \n case \"line\":\n feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(olPointsArray),null,olStyle);\n break; \n }\n \n var layerName=vectorLayer;\n \n var vectorLayerObj=mapObject.getLayersByName(layerName)[0];\n\n if(!vectorLayerObj){\n vectorLayerObj=new OpenLayers.Layer.Vector(layerName, {style: layer_style, displayInLayerSwitcher: layerOptions.displayInLayerSwitcher});\n mapObject.addLayer(vectorLayerObj);\n vectorLayerObj.addFeatures([feature]);\n }else{\n if(replace){ \n mapObject.removeLayer(vectorLayerObj); \n vectorLayerObj=new OpenLayers.Layer.Vector(layerName, {style: layer_style, displayInLayerSwitcher: layerOptions.displayInLayerSwitcher});\n mapObject.addLayer(vectorLayerObj);\n vectorLayerObj.addFeatures([feature]);\n } \n else \n vectorLayerObj.addFeatures([feature]); \n } \n}",
"function ProjectionOverlay() {\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delegates requests to internalManager:RoomManager Emits events handled by NotificationRoomHandler | function NotificationRoomManager(notificationService, kcProvider) {
var self = this
EventEmitter.call(this)
self.notificationRoomHandler = new NotificationRoomHandler(notificationService)
self.internalManager = new RoomManager(self.notificationRoomHandler, kcProvider)
} | [
"handleEvents() {\n\t\tif (this.events) {\n\t\t\tfor (let event in this.events) {\n\t\t\t\tComponent.pubsub.on(event, (data) => {\n\t\t\t\t\t// We're only interested in events which match this instance's unique identifeir\n\t\t\t\t\tif (data.props.uid === this.uid) {\n\t\t\t\t\t\tthis.events[event](data);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}",
"assignCallbacks() {\n this.namespace.on('connection', (socket) => {\n this.onWhisper(socket);\n });\n }",
"_addDefaultEvents () {\n\t\tthis.discord.on('error', console.error);\n\n\t\tthis.discord.on('message', (message) => {\n\t\t\t/* Ignore other bots and self */\n\t\t\tif (message.author.bot) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfor (const caster of this._casters) {\n\t\t\t\tcaster.dispatchIncoming(\n\t\t\t\t\tnew DiscordMessageContext(caster, message, this.options.id)\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t}",
"function midiMessageHandler(m) {\n\twindow.dispatchEvent(new CustomEvent('piano', {detail:{data: m.data, source: \"midi\"}}));\n}",
"broadcastMap() {\n this.emitToRoom(\"map\", this._map);\n }",
"function autoConnectionBroadcastersHandler() {\n\tif (autoStart && !isView && !isAdmin) { // auto-join-room for broadcasters\n\t\tDEBUG && console.log('Broadcasters auto-join-room');\n\t\trecheckSetupParams();\n\t\tdisableUIElements();\n\t\tstartJoinRoom();\n\t}\n}",
"onRoomList(rooms) {\n this.store.commit('Main/SET_ROOM_LIST', rooms);\n }",
"onEventHandlerSet(room, handler, callback, identifier) {\n if (!this.handlers[handler]) {\n this.handlers[handler] = {};\n }\n\n this.handlers[handler][identifier] = callback;\n }",
"function listRooms(user) {\n user.notify(Room.getRoomList());\n}",
"onEventHandlerGet(room, handler, identifier) {\n if (this.handlers.hasOwnProperty(handler)) {\n return this.handlers[handler][identifier];\n }\n }",
"function joinRoom() {\n initSocket();\n initRoom();\n }",
"emit(event, args){\n\n if(this.listeners.has(event)){\n\n Logger.info(`Broadcasting: #${event}, Data:`, args);\n\n this.listeners.get(event).forEach((listener) => {\n listener.callback.call(listener.component, args);\n });\n\n }\n\n if(event !== 'ping' && event !== 'pong') {\n this.dispatchStore(event, args);\n }\n\n }",
"processNotification(notification) {\r\n switch (notification.Event) {\r\n case NotificationType.ReaderConnected:\r\n return this.emit(new DeviceConnected(notification.Reader));\r\n case NotificationType.ReaderDisconnected:\r\n return this.emit(new DeviceDisconnected(notification.Reader));\r\n case NotificationType.CardInserted:\r\n return this.emit(new CardInserted(notification.Reader, notification.Card));\r\n case NotificationType.CardRemoved:\r\n return this.emit(new CardRemoved(notification.Reader, notification.Card));\r\n default:\r\n console.log(`Unknown notification: ${notification.Event}`);\r\n }\r\n }",
"_emitQueryLogs(json={}){\n this.app.service('query_logs').emit('logs',json) ;\n }",
"onEventHandlerHas(room, handler, identifier) {\n return (this.handlers.hasOwnProperty(handler)\n && this.handlers[handler].hasOwnProperty(identifier));\n }",
"function registerSocketioListener() {\n\t// event listener for sending a chat message\n\t$('#send').on('click', sendChatMessage);\n\t$('#msg-input').keypress(function(e) {\n\t if (e.which == 13) {\n\t\tsendChatMessage();\n\t }\n\t});\n\n\t// listen to other players' message\n\treceiveChatMessage();\n\n\t// listen to other players' connection info\n\treceivePlayerConnect();\n\n\t// listen to other players' move\n\treceivePlayerMove();\n\n\t// listen to other players restarting\n\treceivePlayerRestart();\n\n }",
"function writeMessage() {\n\t\tnfc.ontagfound = function(event) {\n\t\t\ttagWriteOnAttach(event.tag);\n\t\t};\n\t\tnfc.ontaglost = writeOnDetach;\n\t\tnfc.onpeerfound = function(event) {\n\t\t\tpeerWriteOnAttach(event.peer);\n\t\t};\n\t\tnfc.onpeerlost = writeOnDetach;\n\t\tnfc.startPoll();\n }",
"setOnMessageHandler(handler) {\n this.wsSocket.on('data', handler);\n this.wsSocket.on('message', handler);\n }",
"function emitOnRequest(req, event, msg) {\r\n if (req.user) {\r\n var user_id = req.user._id;\r\n }\r\n else {\r\n var user_id = 'anon';\r\n }\r\n\r\n broadcastToUserId(user_id,event,msg);\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function to return even numbers | function evenNumbers(numbers) {
return numbers % 2 == 0;
} | [
"function is_even(num){\n if(num % 2 == 0){\n return true;\n }\n return false;\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 evenNumbers (randomInteger) {\n if ( randomInteger > 100 || randomInteger < 0){\n return \"number has to be between 0 and 100\";\n }\n var even =[];\n for (var i = 0; i <=randomInteger; i++) {\n if (i%2 === 0) {\n even.push(i);\n }\n }\n return even\n}",
"function oddsSmallerThan(n) {\n // Your code here\n\n return parseInt(n /2)\n\n}",
"function getEven1000() {\n var sum = 0;\n for (var i = 1; i <= 1000; i++) {\n if (i % 2 === 0) {\n sum += i;\n }\n }\n return sum;\n}",
"function isaNumberEven(array){\n\t\n}",
"function sumEven() {\n var sum = 0;\n for(var x = 1; x < 1001; x++) {\n if(x % 2 === 0){\n sum += x;\n }\n }\n return sum;\n // console.log(sum);\n}",
"function even(){\n var evenNumber = 0;\n for(var i=2; i<=100; i++){\n if(i%2==0)\n evenNumber = evenNumber+','+i;\n }\n document.getElementById('even').innerHTML = evenNumber;\n}",
"function evenDes() {\n\tfor (let i = 98; i >= 0; i--) {\n\t\tif (i % 2 === 0){\n\t\t\tconsole.log(i);\n\t\t}\n\t}\n}",
"function evenIndexedOddNumbers(arr) {\n var output = [];\n each(arr, function(e, i) {\n if ((e % 2 !== 0) && (i % 2 === 0)) {\n output.push(e)\n }\n })\n return output;\n}",
"function randomNegativeEvenNumber() {\n var randomNumber = getRandomIntInclusive(1,1000);\n if(randomNumber % 2 === 0) {\n return randomNumber;\n }\n\n return randomNegativeEvenNumber();\n}",
"function evenDigitsOnly(n) {\n const digits = n.toString().split(\"\");\n // console.log(digits);\n\n return digits.every((dig) => parseInt(dig) % 2 === 0);\n}",
"function isOdd(n) {if(!isNaN(n)){return n % 2 !== 0}}",
"function summationEven(num){\n let n = 0;\n for(var i = 1; i<= num; i++){\n\n if(i % 2 == 0){\n n += i \n }\n }\n console.log(n) \n}",
"function evenStevens (num) {\n if (num % 2 === 0) {\n return true;\n }\n else {\n return false;\n }\n}",
"function numberIndexEven(array){\r\n \r\n return map(array,function(value, index){\r\n if((typeof(value)==='number')&& (index%2===0)){\r\n return value*2;\r\n }else{ return value}\r\n })\r\n}",
"function get_even_1000(){\n var sum = 0;\n for(var i=2; i<=1000; i+=2){\n sum = sum + i;\n }\n return sum;\n}",
"function sumEvenNumbers(input) {\n let sum = 0 \n for (let i = 0; i < input.length; i += 1) {\n if (input[i] % 2 === 0 && Number.isInteger(input[i])) {\n sum += input[i]\n console.log(sum)\n }\n \n }\n return sum \n}",
"function processOddNums (arr) {\n // let finalIndex = arr.length -1;\n // let result = [];\n // for (let i = finalIndex; i > 0; i--) {\n // if (i % 2 !== 0) {\n // let num = 2 * arr[i];\n // result.push(num)\n // }\n // }\n // console.log(result.join(\" \"));\n\n console.log(\n (arr.filter((el, index) => index % 2 != 0))\n .map(e => e = 2 * e)\n .reverse()\n .join(\" \"))\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
TODO: Boot mock server and redirect to random, unused endpoint TODO: This code introduces codependencies between application and test code. Refactor! | redirect(options, cb) {
if (this.constructor.name === "BasicAuth") {
/* start basic auth server on 3001 */
/* no mock for basic auth yet, leaving empty */
cb(options);
} else if (this.constructor.name === "IdmAuth") {
/* start idm auth server on 3002 */
mocks.IdmMockServer.run(
resources.MOCK_IDM_CREDS.username,
resources.MOCK_IDM_CREDS.password,
resources.MOCK_IDM_CREDS.tenantName,
resources.MOCK_IDM_CREDS.tenantUsername,
resources.MOCK_IDM_CREDS.tenantPassword,
port => {
let redirected = _.assign(options, {url: `http://localhost:${port}/`});
cb(redirected);
});
} else {
log.error(new Error(`There's no class named ${this.constructor.name} to mock.`));
}
} | [
"request(options, callback) {\n if (server.app.get('mock_auth') === true) {\n /* redirect to mock */\n this.redirect(options, redirected => {\n request(\n redirected,\n callback\n );\n });\n } else {\n request(\n options,\n callback\n );\n }\n }",
"function getEndPoint() {\n let random = Math.floor(Math.random() * httpEndPoints.length);\n return httpEndPoints[random];\n}",
"function MockCuriousClient() { }",
"makeServer() {\n this.server = http.Server(this.app);\n }",
"function sendDefault(req, res) {\n var endpoint,\n splitPath = req.params[0].split('?')[0].split(\"/\"),\n mockPath = mockFileRoot + req.params[0] + '/' + 'default.json',\n mockResponse;\n\n if (splitPath.length > 2)\n endpoint = splitPath[splitPath.length - 2];\n \n try {\n \n res.json(getMock(mockPath))\n } catch (err) {\n console.log(\"something bad happened\", err);\n res.status(500).send(JSON.parse(err));\n }\n}",
"function wakeUpServer() {\n\tvar h = require(\"http\");\n\th.get(SERVER_URL);\n}",
"function serve(app) { \n app.use(expressip().getIpInfoMiddleware);\n \n app.get('/revelation/logs', (req, res) => {\n if (req.headers.uuid === global.revelation_session) res.status(200).send(global.revelation_logs).end();\n else res.status(401).send().end();\n });\n \n app.get('/revelation/reports', (req, res) => {\n if (req.headers.uuid === global.revelation_session) res.status(200).send(global.revelation_reports).end();\n else res.status(401).send().end();\n });\n\n app.post('/revelation/auth', (req, res) => {\n if (req.body.password === global.revelation_config.secret) {\n global.revelation_session = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);\n res.status(200).send({ uuid: global.revelation_session }).end();\n } else res.status(500).send({ error: 'Password is incorrect' }).end();\n });\n \n app.get(['/revelation', '/revelation/**'], (req, res) => {\n app.use(express.static(__dirname + '/dist'));\n res.sendFile(path.join(__dirname, 'dist/index.html'));\n });\n}",
"_setupRoutes() {\n // For requests to webhook handler path, make the webhook handler take care\n // of the requests.\n this.server.post(this.webhookOptions.path, (req, res, next) => {\n this.handler(req, res, error => {\n res.send(400, 'Error processing hook');\n this.logger.error({err: error}, 'Error processing hook');\n\n next();\n });\n });\n\n this.server.post('/builds/:bid/status/:context', restify.plugins.jsonBodyParser(), this.buildStatusController.bind(this));\n this.server.post('/update', restify.plugins.jsonBodyParser(), this.buildStatusController.bind(this));\n\n this.server.get('/pull-request/:owner/:repo/:pullRequestNumber', this.getPullRequest.bind(this));\n }",
"function start()\n{\n if(!checkSite()) return;\n types = defineTypes();\n banned = [];\n banUpperCase(\"./public/\", \"\");\n var service = https.createServer(options, authenticate);\n\n/*\nservice.listen(PORT, () => {\n console.log(\"Our app is running on port \"+PORT);\n});\n*/\n\n service.listen(PORT);\n var address = \"https://localhost\";\n if(PORT != 80) address = address+\":\"+PORT+\"/\";\n console.log(\"Server running at\", address);\n\n}",
"configureRoute(app) {\n const storeIssuer = (req, res, next) => {\n const host = req.headers['x-forwarded-host'] || req.headers.host;\n res.locals.issuer = `${req.protocol}://${host}/auth/${this.loginName}`;\n next();\n };\n // configure username/password route\n var v = this.verify.bind(this);\n this.authLib.log.info('adding route to app');\n const loginRoute = '/auth/' + this.loginName + '/verify';\n app.use(loginRoute, storeIssuer);\n app.post(loginRoute, v);\n\n // configure refreshtoken route\n if(this.verifyRefresh) {\n this.authLib.log.info('configuring refresh token route');\n var vr = this.verifyRefresh.bind(this);\n const refreshRoute = '/auth/' + this.loginName + '/token';\n app.use(refreshRoute, storeIssuer);\n app.post(refreshRoute, vr);\n }\n\n // configure well known routes if signing algorithm is RS256\n if(this.authLib.opts.signAlg === 'RS256') {\n this.authLib.log.info('adding openid + jwks routes');\n app.get(\n '/auth/' + this.loginName + '/.well-known/openid-configuration',\n this.openIDConfiguration.bind(this)\n );\n app.get(\n '/auth/' + this.loginName + '/.well-known/jwks.json',\n this.getKeySet.bind(this)\n );\n }\n }",
"function url_server () {\n return spawn('python',\n ['./lib/python/change_url.py', 'serve'], {stdio: 'inherit'})\n}",
"configureWebhookEndpoint() {\n if (this.webserver) {\n this.webserver.post(this.config.webhook_uri, async (req, res) => {\n res.send('ok')\n this.messageRouter(req.body)\n })\n }\n else {\n throw new Error('Cannot configure webhook endpoints when webserver is disabled');\n }\n }",
"start() {\n const fakeFetch = (url, params) => {\n try {\n return this.handle(url, params);\n } catch (err) {\n // errorCallback allows hooking test framework error handling utils\n // into FetchServer so that tests may be reliably failed on error:\n isFunction(this.errorCallback) && this.errorCallback(err);\n throw err; // rethrow error\n }\n };\n\n this.restore(); // clean up prior FetchServer stubs (if necessary)\n\n // stub fetch in browser environment:\n if (typeof window !== `undefined` && window.fetch && !Object.hasOwnProperty.call(window.fetch, `restore`)) {\n sinon.stub(window, `fetch`).callsFake(fakeFetch);\n }\n // stub fetch in NodeJS environment:\n if (typeof global !== `undefined` && global.fetch && !Object.hasOwnProperty.call(global.fetch, `restore`)) {\n sinon.stub(global, `fetch`).callsFake(fakeFetch);\n }\n }",
"function initialHandler(req, res) {\n res.sendFile(__dirname + '/public/weather.html');\n}",
"async redirectToProperFlow () {\n try {\n var randomString =\n Math.random()\n .toString(36)\n .substring(2, 15) +\n Math.random()\n .toString(36)\n .substring(2, 15)\n\n window.open(`${process.env.SHIPPO_OAUTH_LINK}${randomString}`)\n this.$router.push({\n name: 'orderConfirm'\n })\n } catch (error) {\n if (error) throw error\n }\n }",
"function test_endpoint(camera_id){\n if(camera_id <= 10)\n return large_data_camera_fixture(camera_id);\n else\n return large_count_camera_fixture(camera_id);\n}",
"function make_fakeUserAgent (history) {\n var fakeUserAgent = function (options) {\n var state = CodeGradX.getCurrentState();\n var i = _.findIndex(history, { path: options.path });\n if ( i >= 0 ) {\n state.debug(\"fakeUserAgent request \" + options.path);\n var item = history[i];\n history.splice(i, 1);\n if ( item.status > 0 ) {\n var js = {\n status: { code: item.status },\n headers: {}\n };\n state.debug(\"fakeUserAgent response \" + item.status);\n return when(js).delay(100 * Math.random());\n } else {\n return when.reject(\"Non responding server \" + options.path);\n }\n } else {\n // History was probably incomplete:\n return when.reject(\"Unexpected URL \" + options.path);\n }\n };\n CodeGradX.getCurrentState().log = new CodeGradX.Log();\n return fakeUserAgent;\n }",
"_beforeHandleRoute() {\n this._afterHandleRouteCalled = false;\n }",
"run()\n {\n this.httpserver = http.createServer( ( req, res ) =>\n {\n /*\n Gather our body.\n */\n req.on( \"data\", ( chunk ) =>\n {\n if( !( \"collatedbody\" in this ) )\n {\n this.collatedbody = [];\n }\n this.collatedbody.push( chunk );\n } );\n\n req.on( \"end\", () =>\n {\n var urlparts = url.parse( req.url );\n /* Remove the leading '/' */\n var path = urlparts.path.substr( 1 );\n var pathparts = path.split( '/' );\n\n if( req.method in this.handlers && pathparts[ 0 ] in this.handlers[ req.method ] )\n {\n res.writeHead( 200, { \"Content-Length\": \"0\" } );\n this.handlers[ req.method ][ pathparts[ 0 ] ]( pathparts, req, res, Buffer.concat( this.collatedbody ).toString() );\n this.collatedbody = [];\n }\n else\n {\n console.log( \"Unknown method \" + req.method + \":\" + url );\n res.writeHead( 404, { \"Content-Length\": \"0\" } );\n }\n res.end();\n } );\n\n } );\n\n this.httpserver.listen( this.us.port, this.us.host, () =>\n {\n console.log( `Project Control Server is running on ${this.us.host} port ${this.us.port}` );\n } );\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new options objects with the given fontFamily. | withTextFontFamily(fontFamily) {
return this.extend({
fontFamily,
font: ""
});
} | [
"public FontFamily(string familyName) : this(null, familyName)\r\n {}",
"function updateFontOptions() {\n styleSelectFont.innerHTML = \"\";\n for (let i = 0; i < fonts.length; i++) {\n const opt = document.createElement(\"option\");\n opt.value = i;\n const font = fonts[i].split(\":\")[0].replace(/\\+/g, \" \");\n opt.style.fontFamily = opt.innerHTML = font;\n styleSelectFont.add(opt);\n }\n}",
"public FontFamily()\r\n { \r\n _familyIdentifier = new FontFamilyIdentifier(null, null); \r\n _firstFontFamily = new CompositeFontFamily();\r\n }",
"setFontFamily() {\n const fontFamily = this.options?.tooltip?.fontFamily ?? 'Roboto';\n fontStyle = `normal normal lighter 14px ${fontFamily}`;\n this.tooltipHeaderDOM.style.fontFamily = fontFamily;\n }",
"public FontFamily(Uri baseUri, string familyName)\r\n { \r\n if (familyName == null)\r\n throw new ArgumentNullException(\"familyName\"); \r\n \r\n if (baseUri != null && !baseUri.IsAbsoluteUri)\r\n throw new ArgumentException(SR.Get(SRID.UriNotAbsolute), \"baseUri\"); \r\n\r\n _familyIdentifier = new FontFamilyIdentifier(familyName, baseUri);\r\n }",
"function initFontSizeSelectBox() {\n\tvar SelectNode = document.getElementById(\"FontSize\");\n\tvar index;\n\tfor (index = 0; index < fontSizes.length; index++) {\t\n\t\tvar option = document.createElement(\"option\");\n\t\toption.value = fontSizes[index];\n\t\toption.text = fontSizes[index] + \" pixels\";\n\t\tSelectNode.add(option);\n\t}\n}",
"function ShowFontSelector(label) {\r\n const io = GetIO();\r\n const font_current = GetFont();\r\n if (BeginCombo(label, font_current.GetDebugName())) {\r\n Selectable(font_current.GetDebugName());\r\n // TODO\r\n // for (let n = 0; n < io.Fonts->Fonts.Size; n++)\r\n // {\r\n // ImFont* font = io.Fonts->Fonts[n];\r\n // ImGui.PushID((void*)font);\r\n // if (ImGui.Selectable(font->GetDebugName(), font == font_current))\r\n // io.FontDefault = font;\r\n // ImGui.PopID();\r\n // }\r\n EndCombo();\r\n }\r\n SameLine();\r\n HelpMarker(\"- Load additional fonts with io.Fonts->AddFontFromFileTTF().\\n\" +\r\n \"- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\\n\" +\r\n \"- Read FAQ and documentation in misc/fonts for more details.\\n\" +\r\n \"- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame().\");\r\n }",
"registerEditorsWithFonts(form) {\n\t\t\t$.ajax({\n\t\t\t\turl: CONFIG.siteUrl + 'layouts/resources/fonts/fonts.json',\n\t\t\t\tmethod: 'GET',\n\t\t\t\tdataType: 'json'\n\t\t\t})\n\t\t\t\t.done((response) => {\n\t\t\t\t\tif (response.length === 0) {\n\t\t\t\t\t\treturn this.registerEditors(form);\n\t\t\t\t\t}\n\t\t\t\t\tconst fonts = response\n\t\t\t\t\t\t.map((font) => font.family)\n\t\t\t\t\t\t.filter((val, index, self) => self.indexOf(val) === index);\n\t\t\t\t\tCONFIG.fonts = fonts;\n\t\t\t\t\tthis.registerEditors(form, fonts);\n\t\t\t\t})\n\t\t\t\t.fail(() => {\n\t\t\t\t\tthis.registerEditors(form);\n\t\t\t\t\tapp.errorLog('Could not load fonts.');\n\t\t\t\t});\n\t\t}",
"withTextFontWeight(fontWeight) {\n return this.extend({\n fontWeight,\n font: \"\"\n });\n }",
"setFont(font) {\n this.ctx.font = font;\n }",
"function createTTF() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n return new Promise(function (resolve, reject) {\n options.svg2ttf = options.svg2ttf || {};\n\n var DIST_PATH = _path[\"default\"].join(options.dist, options.fontName + \".ttf\");\n\n var ttf = (0, _svg2ttf[\"default\"])(_fsExtra[\"default\"].readFileSync(_path[\"default\"].join(options.dist, options.fontName + \".svg\"), \"utf8\"), options.svg2ttf);\n var ttfBuf = Buffer.from(ttf.buffer);\n\n _fsExtra[\"default\"].writeFile(DIST_PATH, ttfBuf, function (err) {\n if (err) {\n return reject(err);\n }\n\n console.log(\"\".concat(_colorsCli[\"default\"].green('SUCCESS'), \" \").concat(_colorsCli[\"default\"].blue('TTF'), \" font successfully created!\\n \\u2570\\u2508\\u25B6 \").concat(DIST_PATH));\n resolve(ttfBuf);\n });\n });\n}",
"function handleFontFamily(font, event) {\n setFontFamily(font);\n let fontButtons = document.querySelectorAll(\".font-button\");\n fontButtons.forEach((item) => {\n item.classList.remove(\"active\");\n });\n event.target.classList.add(\"active\");\n }",
"function _loadFont(fontname){\n var canvas = document.createElement(\"canvas\");\n //Setting the height and width is not really required\n canvas.width = 16;\n canvas.height = 16;\n var ctx = canvas.getContext(\"2d\");\n\n //There is no need to attach the canvas anywhere,\n //calling fillText is enough to make the browser load the active font\n\n //If you have more than one custom font, you can just draw all of them here\n ctx.font = \"4px \"+fontname;\n ctx.fillText(\"text\", 0, 8);\n}",
"function setupAdditionalCufonFontReplacement()\r\n{\r\n Cufon.replace(\".portfolioProjectWrapper .title\", {fontWeight: 700});\r\n Cufon.replace(\".portfolioOtherHeader\", {fontWeight: 300}); \r\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 Fortune (options) {\n this.constructor(options)\n}",
"constructor(fontImg, fontInfo) {\n fontInfo = JSON.parse(fontInfo).font;\n\n function toInt(str) {\n return parseInt(str, 10);\n }\n\n this.lineHeight = toInt(fontInfo.common.lineHeight);\n this.baseline = toInt(fontInfo.common.base);\n\n // Create glyph map\n this.glyphs = {};\n for (var i=0; i<fontInfo.chars.count; ++i) {\n var cInfo = fontInfo.chars.char[i];\n var glyph = new Glyph(fontImg, cInfo.id, toInt(cInfo.x), toInt(cInfo.y), toInt(cInfo.width), toInt(cInfo.height), toInt(cInfo.xoffset), toInt(cInfo.yoffset), toInt(cInfo.xadvance));\n this.glyphs[glyph.charCode] = glyph;\n }\n }",
"function createWOFF() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var ttf = arguments.length > 1 ? arguments[1] : undefined;\n return new Promise(function (resolve, reject) {\n var DIST_PATH = _path[\"default\"].join(options.dist, options.fontName + \".woff\");\n\n var woff = Buffer.from((0, _ttf2woff[\"default\"])(ttf).buffer);\n\n _fsExtra[\"default\"].writeFile(DIST_PATH, woff, function (err) {\n if (err) {\n return reject(err);\n }\n\n console.log(\"\".concat(_colorsCli[\"default\"].green('SUCCESS'), \" \").concat(_colorsCli[\"default\"].blue('WOFF'), \" font successfully created!\\n \\u2570\\u2508\\u25B6 \").concat(DIST_PATH));\n resolve();\n });\n });\n}",
"function createOptions(game) {\n // Data\n var music = game._music;\n var playerData = game._playerData;\n\n // Background\n fadeSceneIn(game, null, null, true);\n game.add.image(0, 0, 'game-bg').setOrigin(0, 0);\n\n\n // Menu sounds\n var sounds = {\n select: game.sound.add(\"menu-select\", { volume: 0.5 } ),\n accept: game.sound.add(\"menu-accept\", { volume: 0.5 } ),\n };\n\n // Title bar\n var bar = game.add.image(0, 0, \"top-bar\").setOrigin(0, 0);\n\n var nameStyle = { font: \"50px FrizQuadrata\", fill: \"#fff\", stroke: \"#000\", strokeThickness: 1 };\n var nameText = game.add.text(512, 40, \" Options \", nameStyle).setOrigin(0.5, 0.5);\n nameText.setShadow(2, 2, \"#000\", 2);\n\n\n // Portrait\n var masterImage = playerData.image;\n if (masterImage.indexOf(\" \") >= 0) {\n masterImage = masterImage.substr(0, masterImage.indexOf(\" \"));\n }\n var portrait = game.add.sprite(250, 0, masterImage).setOrigin(0.5, 0);\n\n\n // Back button\n backButton(game, sounds.select, () => {\n game.scene.start('GameMenuScene', { playerData: playerData, music: music });\n });\n\n\n // Options\n showOptions(game, sounds.select, playerData, music);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make and insert a plot.ly object into the container in the HTML. Package the data into JS objects that are passed to plot.ly. Inputs: target target HTML container slew_traces line segments, already as a plot.ly object x,y,z,size,text star plot attributes, placed into a plot.ly object here x_way, y_way, text_way waypoint attributes, placed into a plot.ly object here TODO: Abstract this better. One way would be to pass in a few objects, each representing a plot type, rather than separate x,y,z, etc., variables. | function insertPlotly(target, slew_traces, x, y, z, size, text, x_way, y_way, text_way) {
// var plotDiv = document.getElementById('plotDiv');
// default title labels
var legend_cbar = 'Mean Cumulative Characterizations';
var plot_title = [
'Mean Cumulative Characterizations and Slew Paths Over Ensemble',
'Point Shading: Mean Visits across Ensemble; Slew Path Shading: Arbitrary',
'Diamond Indicators Show Slew Information near Slew Destination'
].join('<br>');
if (ens_path_mode === 'single') {
legend_cbar = 'Number of Characterizations';
plot_title = [
'All Attempted Characterizations and Slew Paths',
'Point Shading: Number of Visits; Slew Path Shading: Arbitrary',
'Diamond Indicators Show Slew Information near Slew Destination'
].join('<br>');
}
// holds the waypoints
var waypoints = {
type: 'scattergeo',
lon: x_way,
lat: y_way,
text: text_way,
mode: 'markers',
hoverinfo: 'text',
marker: {
color: 'rgba(30,30,30,0.4)',
size: 7,
// not all advertised symbols are available in scattergeo
symbol: 'diamond-open',
//opacity: 0.7, // opacity is set in "color" above
},
};
if (x_way.length > 0) {
slew_traces.push(waypoints);
}
// holds the plotted points (stars)
var traces = {
type: 'scattergeo',
// type: 'scatter',
lon: x,
lat: y,
text: text,
mode: 'markers',
hoverinfo: 'text',
marker: {
comment_ : 'leave cmin/cmax unspecified to auto-range',
colorscale: 'Portland',
color: z,
size: size,
opacity: 0.7,
colorbar: {
tickfont: {
family: 'Arial',
size: 16,
color: 'black'
},
title: '<br\>' + legend_cbar,
titleside: 'right',
titlefont: {
size: 16,
family: 'Arial Bold'
}
}
},
};
slew_traces.push(traces)
// geographic projection
var geo = {
//resolution: 50,
showland: false,
showcountries: false,
showlakes: false,
showocean: false,
projection: {
type: 'equirectangular'
},
coastlinewidth: 0,
lataxis: {
range: [-80, 80 ],
showgrid: true,
// axis titles do not work, alas
title: 'Longitude [deg]',
},
lonaxis:{
range: [0, 360],
showgrid: true,
title: 'Longitude [deg]',
}
};
// holds the overall plot layout
var layout = {
title: plot_title,
titlefont: {
family: "Arial Black",
size: 18,
color: 'black'
},
showlegend: false, // slew legend at right
geo: geo,
hovermode: 'closest',
}
// make the plot from the above objects
Plotly.newPlot(target, slew_traces, layout)
} | [
"function createTracesAndLayout(arr, title, jitter='all'){\n // Iterate through the formatted array [[name_of_trace, expression_data]...]\n // and create the response plotly objects, returning [plotly data object, plotly layout object]\n var data = Array();\n for(x=0;x<arr.length;x++){\n // plotly violin trace creation, adding to master array\n // get inputs for plotly violin creation\n var dist = arr[x][1];\n var name = arr[x][0];\n // if people want to change bandwidth eventually this is what we would change with a parameter\n var bandwidth = nrd0(dist);\n\n // replace the none selection with bool false for plotly\n if (jitter === ''){\n jitter = false;\n }\n // check if there is a distribution before adding trace\n if ( arrayMax(dist) !== arrayMin(dist) ) {\n // make a violin plot if there is a distribution\n data = data.concat([{\n type: 'violin',\n name: name,\n y: dist,\n \"points\": jitter,\n \"pointpos\": 0,\n \"jitter\": .85,\n \"spanmode\": 'hard',\n box: {\n visible: true,\n fillcolor: '#ffffff',\n width: .1\n },\n bandwidth: bandwidth,\n marker: {\n size: 2,\n color: '#000000',\n opacity: 0.8\n },\n fillcolor: colorBrewerSet[x % 27],\n line: {\n color: '#000000',\n width: 1.5\n },\n meanline: {\n visible: false\n }\n }])\n } else {\n // Make a boxplot for data with no distribution\n data = data.concat([{\n type: 'box',\n name: name,\n y: dist,\n boxpoints: jitter,\n marker: {\n color: colorBrewerSet[x % 27],\n size: 2,\n line: {\n color: plotlyDefaultLineColor\n }\n },\n boxmean: true,\n }])\n }\n\n }\n var layout = {\n title: title,\n yaxis: {\n zeroline: true,\n showline: true,\n title: 'Expression'\n },\n margin: {\n pad: 10,\n b: 100\n },\n autosize: true\n };\n return [data, layout]\n}",
"function setTraces(){\n\n trace1 = {\n x: w,\n y: dampl, \n name: 'Displacement',\n type: 'scatter',\n mode: \"lines\",\n marker: {color: cDisp}\n };\n trace2 = {\n x: w, \n y: vampl, \n name: 'Velocity',\n type: 'scatter',\n mode: 'lines',\n marker: {color: cVel}\n };\n trace3 = {\n x: w, \n y: aampl, \n name: 'Acceleration',\n type: 'scatter',\n mode: 'lines',\n marker:{color: cAcc}\n };\n\n trace4 = {\n x: din,\n y: dout, \n name: 'Displacement',\n type: 'scatter',\n mode: 'lines',\n marker:{color: cDisp}\n };\n trace5 = {\n x: vin, \n y: vout, \n name: 'Velocity',\n type: 'scatter',\n mode: 'lines',\n marker:{color: cVel}\n };\n trace6 = {\n x: ain, \n y: aout, \n name: 'Acceleration',\n type: 'scatter',\n mode: 'lines',\n marker:{color: cAcc}\n };\n\n trace7 = {\n x: w,\n y: phased, \n name: 'Displacement',\n type: 'scatter',\n mode: 'lines',\n marker:{color: cDisp}\n };\n trace8 = {\n x: w, \n y: phasev, \n name: 'Velocity',\n type: 'scatter',\n mode: 'lines',\n marker:{color: cVel}\n };\n trace9 = {\n x: w, \n y: phasea, \n name: 'Acceleration',\n type: 'scatter',\n mode: 'lines',\n marker:{color: cAcc}\n };\n\n \n\n data1 = [trace1, trace2, trace3];\n data2 = [trace4, trace5, trace6];\n data3 = [trace7, trace8, trace9];\n\n layout1= {\n autosize: true,\n margin:{\n l:50, r:10, b:45, t:10\n },\n xaxis:{title:'Frequency (rad/s)'},\n yaxis:{title:'Magnitude'},\n legend: {x: 0, y: 10, orientation: \"h\"},\n showlegend: false,\n font: {family: \"Fira Sans\", size:12} \n};\n\n layout2= {\n margin:{\n l:50, r:10, b:45, t:10\n },\n legend: {x: 50, y: 10, orientation: \"h\"\n },\n showlegend: false,\n xaxis: {title:'In-phase Component'},\n yaxis: {scaleanchor: \"x\",title:'Out-of-phase Component'},\n\n font: {\n family: \"Fira Sans\", size:12\n }\n};\n\nlayout3= {\n autosize: true,\n margin:{\n l:50, r:10, b:45, t:10\n },\n legend: {x: 50, y: 1, orientation: \"v\"\n },\n xaxis:{title:'Frequency (rad/s)'},\n yaxis:{title:'Phase (rad)'},\n font: {\n family: \"Fira Sans\", size:12\n }\n\n};\n\n}",
"function sparkline_charts() {\r\n\t\t\t$('.sparklines').sparkline('html');\r\n\t\t}",
"function BtcMultiLinegraph() {\n var prct_btc;\n d3.json(\"/percentbtc\").then(function(data){\n prct_dji = data;\n var priceClose = [];\n var prctClose = [];\n var prctDates = [];\n for (var i = 0; i < data.length; i++) {\n priceClose.push(data[i].close_dji);\n prctClose.push(data[i].close);\n prctDates.push(data[i].datetime);\n }\n var trace1 = {\n x: prctDates,\n y: prctClose,\n name: 'Percent Change',\n line: {\n color: \"rgb(255, 77, 77)\",\n width: 2\n },\n type: 'scatter'\n };\n \n var trace2 = {\n x: prctDates,\n y: priceClose,\n name: 'Closing prices',\n yaxis: 'y2',\n line: {\n color: \"rgb(1, 87, 155)\",\n width: 2\n },\n type: 'scatter'\n };\n \n var data = [trace1, trace2];\n \n var layout = {\n title: 'Bitcoin vs Percent Change in Closing Prices',\n xaxis: {\n rangeselector: selectorOptions,\n },\n yaxis: {title: 'Percent Change (%)', tickformat:',%',range:[-.50,.50]},\n yaxis2: {\n title: 'Value per day ($)',\n titlefont: {color: 'rgb(148, 103, 189)'},\n tickfont: {color: 'rgb(148, 103, 189)'},\n overlaying: 'y',\n side: 'right'\n }\n };\n\n Plotly.newPlot('plot', data, layout);\n // console.log(priceClose);\n // console.log(prctClose);\n // console.log(prctDates);\n });\n}",
"function plotly_log_graph_with_doubling_lines(id, traces, ymin, ymax, line_for_current_trajectory) {\n var max_xval = 0;\n for (var i in traces) {\n max_xval = Math.max(traces[i].y.length - traces[i].x.indexOf(0) - 1, max_xval);\n }\n\n var graph_boty = Math.pow(10, ymin);\n var graph_topy = Math.pow(10, ymax);\n var graph_rangey = graph_topy - graph_boty;\n\n var annotations = [];\n var shapes = [];\n var days = [1,2,3,5,7,14];\n for (var i in days) {\n var d = days[i];\n var top_hit_x = Math.log2(graph_topy / graph_boty) * d;\n // assume the line hits the top of the graph, so we need our next relative to that point\n var x = top_hit_x;\n var y = graph_topy;\n var xanchor = 'middle';\n var yanchor = 'top';\n if (top_hit_x > max_xval) {\n // the line doesn't intersect the top of the graph (not exponential enough for the scale),\n // so it intersects the right side of the graph instead\n x = max_xval;\n y = Math.pow(10, ymin) * Math.pow(2, max_xval / d);\n xanchor = 'right';\n yanchor = 'top';\n }\n annotations.push({\n text: (d == 1 ? \"doubling every day\" : \"doubling every \" + d + \" days\"),\n textangle: 0,\n x: x,\n y: Math.log10(y),\n xref: 'x',\n yref: 'y',\n showarrow: false,\n xanchor: xanchor,\n yanchor: yanchor,\n font: {\n color: '#aaaaaa',\n size: 10\n },\n bgcolor: '#ffffff'\n });\n shapes.push({\n x0: 0,\n x1: max_xval,\n type: 'line',\n y0: Math.pow(10, ymin),\n y1: Math.pow(10, ymin) * Math.pow(2, max_xval / d),\n xref: 'x',\n yref: 'y',\n line: {\n color: '#aaaaaa',\n dash: 'dot',\n width: 1\n }\n });\n }\n\n if (line_for_current_trajectory != null) {\n var start_curr = line_for_current_trajectory.x.indexOf(0);\n var start_to_end = line_for_current_trajectory.x.length - start_curr;\n var days_for_trajectory = 14;\n if (start_to_end >= days_for_trajectory) {\n // we have N days of data\n var oldest_day_index = line_for_current_trajectory.x.length - days_for_trajectory;\n var oldest_day = line_for_current_trajectory.x[oldest_day_index];\n var latest_day = line_for_current_trajectory.x[line_for_current_trajectory.x.length - 1];\n var last_n = line_for_current_trajectory.y.slice(oldest_day_index);\n var oldest = last_n[0];\n var latest = last_n[last_n.length - 1];\n var oldest_log = Math.log2(oldest);\n var latest_log = Math.log2(latest);\n var delta_log_y = latest_log - oldest_log;\n\n // work out where we would have been at day 0 given the current trajectory line\n var traj_start = latest * Math.pow(2, -latest_day * (delta_log_y / days_for_trajectory));\n \n // in 'days_for_trajectory' days (x) we've changed by 'delta_log_y' (y)\n var final_y = traj_start * Math.pow(2, max_xval * (delta_log_y / days_for_trajectory));\n shapes.push({\n x0: 0,\n x1: max_xval,\n type: 'line',\n y0: traj_start,\n y1: final_y,\n xref: 'x',\n yref: 'y',\n opacity: 0.5,\n line: {\n color: '#ff0000',\n dash: 'dot',\n width: 1\n }\n });\n\n if (Math.log10(final_y) < ymax) {\n // hits the right side, so the doubling rate matters more\n var days = parseInt(1 / (delta_log_y / days_for_trajectory));\n annotations.push({\n text: \"currently doubling every \" + days + \" days (avg last 2 weeks)\",\n textangle: 0,\n x: latest_day,\n y: Math.log10(latest),\n xref: 'x',\n yref: 'y',\n showarrow: false,\n xanchor: 'left',\n yanchor: 'top',\n opacity: 0.5,\n font: {\n color: '#ff0000',\n size: 10\n },\n bgcolor: '#ffffff'\n });\n }\n }\n }\n\n var p = Plotly.newPlot(\n id,\n traces,\n $.extend({}, default_layout, {yaxis: {type: \"log\", range: [ymin,ymax]}, xaxis: {rangemode: \"nonnegative\", autorange: true}, annotations: annotations, shapes: shapes}),\n $.extend({}, default_config)\n );\n}",
"function draw_arm_selection_history_all_algorithm(data, algorithm_number) {\n var title = \"Arm Play History of Algorithm \" + list_Algorithms_name[algorithm_number]\n var y_title = \"Percentage\"\n var String_title = [title, y_title]\n var canvas_div = create_canvas_div()\n var arm_number = 0\n var lines = []\n for (arm_number = 0; arm_number < number_of_arms; arm_number++) {\n // debugger;\n var mean = data[\"arm_selection_history_all_algorithm_list\"][algorithm_number][0][arm_number]\n var std = data[\"arm_selection_history_all_algorithm_list\"][algorithm_number][1][arm_number]\n var input_data = {'String_title': String_title, 'mean': [mean], 'std': [std], 'label': arm_number + 1, 'i': 0}\n var upper_bound = set_upper_bound_line_ROA(input_data, arm_number + 1)\n var trace = set_mean_trace_line_ROA(input_data, arm_number + 1)\n var lower_bound = set_lower_bound_line_ROA(input_data, arm_number + 1)\n lines.push(lower_bound)\n lines.push(trace)\n lines.push(upper_bound)\n }\n var layout = set_layeout_figure(String_title)\n // Plotly.plot(canvas_div, lines,layout)\n Plotly.plot(canvas_div, lines, layout)\n}",
"function updateTrace1() {\n trace1 = {\n x: [xCoords[sliderValue]],\n y: [yCoords[sliderValue]],\n error_y: {\n type: 'constant',\n value: yError3rdOrder(xCoords[sliderValue], xError)\n },\n error_x: {\n type: 'constant',\n value: xError\n },\n type: 'scatter'\n };\n}",
"function createTracers() {\n\tfor (let i = 0; i < numDots; i++) {\n\t\tlet tracer = document.createElement(\"div\")\n\t\ttracer.setAttribute(\"class\", \"dot tracer\")\n\t\tgsap.set(tracer, {scale:0.3})\n\t\tdemo.appendChild(tracer)\n\t\ttracers = document.querySelectorAll(\".tracer\")\n\t}\n}",
"function draw_arm_confidence_all_algorithm(data, algorithm_number) {\n var title = \"Confidence interval of arms for Algorithm \" + list_Algorithms_name[algorithm_number]\n var y_title = \"amount \"\n var String_title = [title, y_title]\n var canvas_div = create_canvas_div()\n var arm_number = 0\n var lines = []\n for (arm_number = 0; arm_number < number_of_arms; arm_number++) {\n // debugger;\n var mean = data[\"arm_confidence_all_algorithm_list\"][algorithm_number][0][arm_number]\n var std = data[\"arm_confidence_all_algorithm_list\"][algorithm_number][1][arm_number]\n var input_data = {'String_title': String_title, 'mean': [mean], 'std': [std], 'label': arm_number + 1, 'i': 0}\n var upper_bound = set_upper_bound_line_ROA(input_data, arm_number + 1)\n var trace = set_mean_trace_line_ROA(input_data, arm_number + 1)\n var lower_bound = set_lower_bound_line_ROA(input_data, arm_number + 1)\n lines.push(lower_bound)\n lines.push(trace)\n lines.push(upper_bound)\n }\n var layout = set_layeout_figure(String_title)\n // Plotly.plot(canvas_div, lines,layout)\n Plotly.plot(canvas_div, lines, layout)\n}",
"function buildLongStatsHtml(wrapper) {\n // lint complains otherwise, but due to chaining of functions it's mistaken\n var innerWrapper = wrapper;\n // const region = store.getStateItem('region');\n innerWrapper.innerHTML = ZonalLong; // eslint-disable-line\n var inputData = WMSLayers.filter(function (layer) {\n return layer.chartSummary;\n });\n\n // iterate the layer props to assing apporaite thml\n inputData.forEach(function (layerProps) {\n var layerElem = wrapper.querySelector('.zonal-long-' + layerProps.chartCSSSelector + '-wrapper .zonal-long-table-wrapper');\n\n if (layerElem) {\n var legendHTML = (0, _utilitys.getLegendHtml)(layerProps.chartLegendValues);\n layerElem.innerHTML = legendHTML;\n\n // get the color palette for layer, each layer can have its own\n var colorPalette = layerProps.chartCSSColor;\n\n // iterate the color palette for layer so we can assing apporaite css color to element\n Object.keys(colorPalette).forEach(function (color) {\n // convert the color number to number word 2 - two\n // this is how html elments are named.\n var colorlueWord = (0, _utilitys.numberToWord)(Number(color));\n // get the element based on the color word\n var valueELem = layerElem.querySelector('.value-' + colorlueWord);\n\n // if the element exists add css color values\n if (valueELem) {\n // set background based on mapconfig values\n valueELem.style.background = colorPalette[color];\n\n // set font color\n valueELem.style.color = '#000';\n\n // // last color tends to be to dark for dark font\n // if (parseInt(color) >= layerProps.chartLegendValues ) {\n // valueELem.style.color = '#fff';\n // }\n // add classes for region, chartCSSSelector, and source in case we want to find it later\n valueELem.classList.add(layerProps.chartCSSSelector);\n valueELem.classList.add(layerProps.region);\n valueELem.classList.add(layerProps.source);\n }\n });\n }\n });\n}",
"function setUpPageLayout(isTimeseries, data=null) {\n // Variables to help calculate the height of the divs\n var windowHeight = d3.select(\"html\")[0][0].clientHeight;\n var windowHeightOffset = 210;\n var divMargin = 10;\n var scrollBarWidth = 10;\n\n // If the CSV file contains timeseries data, create 2 independently\n // scrolling divs: one on the left for the categorized timelines for the\n // user to select from and one on the right to contain the SVG chain\n if (isTimeseries) {\n // Create an outer container\n var outerContainer = d3.select(\"body\").append(\"div\")\n .attr(\"id\", \"outerContainer\");\n \n // Capture the windowWidth to help calculate the width of the divs\n var outerContainerWidth = outerContainer[0][0].clientWidth -\n divMargin*4 - scrollBarWidth*2;\n\n // Create the container for everything on the left side of\n // the page. Append the instructions and a br to separate\n // the instructions from the leftContainer\n var leftDiv = outerContainer.append(\"div\")\n .style(\"width\", (outerContainerWidth/3) + \"px\")\n .style(\"overflow\", \"hidden\");\n var instructions = leftDiv.append(\"h4\")\n .text(\"Click on the chart with the data you wish to explore:\");\n var br = leftDiv.append(\"br\");\n\n // Append a div to contain all the searching-related elements\n // Append the instructions, input box, and button\n var searchDiv = leftDiv.append(\"div\")\n .style(\"float\", \"left\")\n .style(\"overflow\", \"hidden\");\n searchDiv.append(\"p\")\n .style(\"display\", \"inline-block\")\n .style(\"margin\", \"0px\")\n .text(\"Search for a timeline:\");\n searchDiv.append(\"input\")\n .attr(\"id\", \"searchTerm\")\n .attr(\"type\", \"text\")\n .style(\"margin\", \"0px\");\n searchDiv.append(\"button\")\n .style(\"margin\", \"0px\")\n .text(\"Search\")\n .on(\"click\", function() { searchForTimeline(data); });\n\n // The leftContainer will be shorter than the mainContainer so that the\n // bottoms of their divs line up\n var leftContainerHeightOffset = instructions[0][0].clientHeight +\n br[0][0].clientHeight + searchDiv[0][0].clientHeight + divMargin*6;\n\n // Append the leftContainer, where all the timelines will be appended\n leftDiv.append(\"div\")\n .attr(\"id\", \"leftContainer\")\n .style(\"width\", \"98%\")\n .style(\"height\",\n (windowHeight-windowHeightOffset-leftContainerHeightOffset) + \"px\")\n .style(\"overflow-y\", \"scroll\");\n\n // Append the mainContainer, where the SVG chain will be contained\n outerContainer.append(\"div\")\n .attr(\"id\", \"mainContainer\")\n .style(\"width\", (outerContainerWidth*2/3) + \"px\")\n .style(\"height\", (windowHeight-windowHeightOffset) + \"px\")\n .style(\"overflow\", \"scroll\")\n .append(\"div\").attr(\"id\", \"mainInnerContainer\");\n\n // Set the supported GRAPH_TYPES to include BARCHART_OVERVIEW and\n // TIMELINE\n GRAPH_TYPES = Object.freeze({ SCATTERPLOT: 0, HEATMAP: 1,\n BARCHART: 2, BARCHART_OVERVIEW: 3, TIMELINE: 4 });\n }\n // For non-timeseries data, only a scrolling div for the SVG chain is needed\n else {\n\n // For non-timeseries data, only the mainContainer and\n // mainInnerContainer are necessary\n d3.select(\"body\").append(\"div\")\n .attr(\"id\", \"mainContainer\")\n .style(\"width\", d3.select(\"html\")[0][0].clientWidth - divMargin*2 -\n scrollBarWidth)\n .style(\"height\", (windowHeight-windowHeightOffset) + \"px\")\n .style(\"overflow-y\", \"scroll\")\n .append(\"div\").attr(\"id\", \"mainInnerContainer\");\n\n // Support only graphs types that do not rely on timeseries data (i.e.\n // exlude BARCHART_OVERVIEW and TIMELINE)\n GRAPH_TYPES = Object.freeze({ SCATTERPLOT: 0, HEATMAP: 1,\n BARCHART: 2 });\n }\n \n // Set the default graph type to SCATTERPLOT\n defaultGraph = GRAPH_TYPES.SCATTERPLOT;\n}",
"function showTrailAndPin(trailName, clickedId) {\n\n let trailLat = 0;\n let trailLng = 0;\n \n // Check whether to display info for trails or spots\n if(clickedId === \"trailSelect\") {\n showTrailInfo(trailName, trailCircleArray);\n }\n else if(clickedId === \"spotSelect\") {\n showSpotInfo(trailName, trailCircleArray);\n }\n \n // For syncing between buttons and circles, use array generated by whichever one was\n // clicked on\n if(trailCircleArray == 0) {\n trailLat = trail_array[trailName][trailLatIndex];\n trailLon = trail_array[trailName][trailLonIndex];\n }\n else {\n trailLat = trailCircleArray[trailName][trailLatIndex];\n trailLon = trailCircleArray[trailName][trailLonIndex];\n }\n \n // Get rid of previous marker, if it exists\n if(prevMarker != 0) {\n prevMarker.remove();\n }\n prevMarker = L.marker([trailLat, trailLon]).addTo(my_map);\n\n // Center map on new pin\n my_map.panTo(prevMarker.getLatLng());\n\n trailCircleArray = 0;\n}",
"function drawHops($hopsArray, $placement) {\n if($placement === \"map\"){ //draw Hops on the map\n for (var key in $hopsArray) {\n for (var hop in $hopsArray[key]) {\n //make hop times string\n var times = \"\";\n for(var time in $hopsArray[key][hop]){\n if(!isNaN($hopsArray[key][hop][time])){\n times += \"<li>\"+$hopsArray[key][hop][time]+\"ms</li>\";\n }\n }\n\n //create hopData with hop response times\n var hopData = {\n key: key,\n timesString: times\n }\n\n // draw marker into the map\n drawMarker(hop, null, hopData);\n }\n }\n\n //create a path instance with the generated path from markers to the map\n routePath = new L.Polyline(pathLocation, {\n color: '#2980b9', //belize-hole\n weight: 8,\n opacity: 1,\n smoothFactor: 1\n });\n\n //add route path instace to the map\n routePath.addTo(mainMap);\n\n }else if($placement === \"panel\"){ //draw hops on results panel\n //remove loading state in results panel content\n $(\"#vtr-results-panel .vtr-results-panel__search-image\").remove(); //loader image\n $(\"#vtr-results-panel p\").remove(); // loader paragraph\n\n //loop trough the hops array and add them to the results panel\n for (var key in $hopsArray) {\n for (var hop in $hopsArray[key]) {\n \n //get country short from ip2 location / add marker to map to use in flag\n var countryFlag = getHostData(hop, \"country_short\");\n\n //make hop times list\n var times = \"\";\n for(var time in $hopsArray[key][hop]){\n if(!isNaN($hopsArray[key][hop][time])){\n times += \"<li>\"+$hopsArray[key][hop][time]+\"ms</li>\";\n }\n }\n\n //append to the map the result\n $(\"#vtr-results-panel .vtr-results-panel__list\").append(\n \"<li>\\\n <div class='vtr-results-panel__list__hop-number'>\\\n #\"+key+\"\\\n </div>\\\n <div class='vtr-results-panel__list__hop-info'>\\\n <div class='vtr-results-panel__list__hop-info__host'>\\\n \"+hop+\"\\\n </div>\\\n <ul class='vtr-results-panel__list__hop-info__time'>\\\n \"+times+\"\\\n </ul>\\\n </div>\\\n <div class='vtr-results-panel__list__hop-country-flag' style='background-image: url(dist/images/country_flags/64/\"+countryFlag+\"_64.png)'></div>\\\n </li>\"\n );\n }\n }\n }\n}",
"function displayLineGraph_DomConsumption(Data, countryName) {\n\n // Filter Consumption Data to return only data for matching country name\n let consumptionData = Data.filter(consumption => consumption.Attribute == \"Domestic Consumption\");\n let countryConsumption = consumptionData.filter(country => country.Country_Name == countryName);\n countryConsumption = countryConsumption.filter(country => country.Year >= 1990);\n\n // Filter Roast,Ground Consumption to return only data for matching country name\n let roastData = Data.filter(consumption => consumption.Attribute == \"Rst,Ground Dom. Consum\");\n let roastConsumption = roastData.filter(country => country.Country_Name == countryName);\n roastConsumption = roastConsumption.filter(country => country.Year >= 1990);\n\n // Filter Soluble Consumption Data to return only data for matching country name\n let solubleData = Data.filter(consumption => consumption.Attribute == \"Soluble Dom. Cons.\");\n let solubleConsumption = solubleData.filter(country => country.Country_Name == countryName);\n solubleConsumption = solubleConsumption.filter(country => country.Year >= 1990);\n\n\n let yearsC = [];\n let consumptionValues = [];\n\n for (let i=0; i < countryConsumption.length; i++) {\n yearsC.push(countryConsumption[i].Year);\n consumptionValues.push(countryConsumption[i].Value);\n }\n\n let yearsRG = [];\n let roastValues = [];\n\n for (let i=0; i < roastConsumption.length; i++) {\n yearsRG.push(roastConsumption[i].Year);\n roastValues.push(roastConsumption[i].Value);\n }\n\n let yearsS = [];\n let solubleValues = [];\n\n for (let i=0; i < solubleConsumption.length; i++) {\n yearsS.push(solubleConsumption[i].Year);\n solubleValues.push(solubleConsumption[i].Value);\n }\n\n\n\n\n // Plot Consumption data points\n let lineData_cons = {\n x: yearsC,\n y: consumptionValues,\n line: { color: \"gray\"},\n name: \"Total Domestic Consumption\",\n type: \"scatter\",\n mode: \"lines+markers\"\n };\n \n\n // Plot Roast Consumption points\n let lineData_roast = {\n x: yearsRG,\n y: roastValues,\n line: { color: \"brown\"},\n name: \"Roast, Ground\",\n type: \"line\"\n };\n\n // Plot Soluble Consumption points\n let lineData_soluble = {\n x: yearsS,\n y: solubleValues,\n line: { color: \"black\"},\n name: \"Soluble\",\n type: \"line\"\n };\n\n\n // // Place both data sets together in array\n let lineData2 = [lineData_cons, lineData_roast, lineData_soluble]; \n\n // Set title for line graph and x and y axes\n let lineLayout2 = {\n title: countryName + \" - Coffee Domestic Consumption Total, Roast-Ground and Soluble Separate 1990 to 2020\",\n xaxis: { title: \"Years\" },\n yaxis: { title: \"Domestic Consumption (1000 * 60 Kg Bags)\" }\n };\n \n // Use plotly to display line graph at div with lineData and lineLayout\n Plotly.newPlot('consLine', lineData2, lineLayout2);\n}",
"async function transformToTLJson() {\n var timelineJson = {}\n timelineJson.events = [];\n // list of slide objects (each slide is an event)\n\n //wikiDate is in iso-8601 format \n function parseDate(wikiDate) {\n var wdate = new Date(wikiDate);\n\n return {\n year: wdate.getUTCFullYear(),\n month: wdate.getUTCMonth(),\n day: wdate.getUTCDate(),\n hour: wdate.getUTCHours(),\n minute: wdate.getUTCMinutes(),\n second: wdate.getUTCSeconds(),\n display_date: `Date of discovery: ${wdate.getUTCFullYear()}`\n };\n\n }\n\n function newSlide(wikiElement) {\n var slide = {};\n\n if (wikiElement.dateOfDiscovery) {\n if (wikiElement.dateOfDiscovery.startsWith('-')) {\n let year = wikiElement.dateOfDiscovery.match(/(-\\d+)-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z/);\n if (year) {\n slide.start_date = {\n year: year[1]\n };\n } else {\n slide.start_date = parseDate(\"0000-00-00T:00:00:00Z\");\n slide.start_date.display_date = \"Unknown discovery date\";\n }\n } else {\n slide.start_date = parseDate(wikiElement.dateOfDiscovery);\n if (isNaN(slide.start_date.year)) {\n slide.start_date = parseDate(\"0000-00-00T:00:00:00Z\");\n slide.start_date.display_date = \"Unknown discovery date\";\n }\n }\n } else {\n slide.start_date = parseDate(\"0000-00-00T:00:00:00Z\");\n slide.start_date.display_date = \"Unknown discovery date\";\n }\n\n slide.text = {\n headline: ` <a href=\"${wikiElement.elementWikiUrl}\">${wikiElement.elementLabel}</a>`,\n text: createTable(selectTableData(wikiElement))\n };\n\n slide.media = {\n url: wikiElement.elementWikiUrl,\n thumbnail: wikiElement.picture\n };\n slide.unique_id = \"a\" + wikiElement.anum;\n slide.autolink = false;\n return slide;\n }\n\n var wikiData = await getData();\n for (var ekey in wikiData) {\n timelineJson.events.push(newSlide(wikiData[ekey]));\n }\n return timelineJson;\n}",
"function initSparkline(el, values, opts) {\r\n el.sparkline(values, $.extend(sparkOpts, el.data()));\r\n }",
"function handleHover(data) {\n var flightInfo = $('#flight-info')\n var pn;\n data.points.forEach((point, index) => {\n pn = point.pointNumber;\n var flight = currentData[pn];\n $('#ref-id').html(flight.ref);\n $('#fatalities').html(flight.fat);\n $('#date').html(flight.date);\n $('#aircraft').html(flight.plane_type);\n $('#location').html(flight.country);\n $('#airline').html(flight.airline);\n $('#phase').html(flight.phase.split('_').join(' '));\n if (flight.meta.toLowerCase() != \"unknown\") {\n $('#meta').html((flight.meta.split('_').join(' ')));\n $('#cause').html(\"- \" + flight.cause);\n } else {\n $('#meta').html(\"Unknown\");\n }\n $('#certainty').html(flight.cert);\n $('#story-label').html(\"STORY\");\n $('#story').html( flight.notes);\n if (flight.notes !== \"\") {\n $('#story-label').css('display', 'inline-block');\n $('#story').css('display', 'inline-block');\n } else {\n $('#story-label').css('display', 'none');\n $('#story').css('display', 'none');\n }\n })\n $('#hover-helper').css('display', 'none');\n flightInfo.css('display', 'inline-block');\n }",
"function SegmentInfo(SegmentId, routeName, segmentName, oneWay, Color, tracks, dash, routeType, trackUsage )\n{\n this.type = \"SegmentInfo\";\n this.line = null;\n var grayLine = null;\n webViewBridge.debug(\"segment \" + SegmentId + \" usage: \" + trackUsage);\n var icons = [\n [{\n icon: lineSymbol, //0 Single track\n offset: '0%',\n repeat: '6px'\n }],\n [{\n icon: lineSymbol, //1 Incline\n offset: '.5',\n repeat: '15px'\n }],\n [{\n icon: doubleLine, // 2 double track street\n offset: '0%',\n repeat: '6px'\n }],\n [{\n icon: singleTick, // 3 Single track PRW\n offset: '0%',\n repeat: '6px'\n }],\n [{\n icon: doubleTick, //4 Double track PRW\n offset: '0%',\n repeat: '6px'\n }],\n [{\n icon: doubleLine, //5 Subway\n offset: '70%',\n repeat: '10px'\n }]\n [{\n icon: lineL, // 6 left line\n offset: '0%',\n repeat: '6px'\n }],\n [{\n icon: lineR, // 7 right line\n offset: '0%',\n repeat: '6px'\n }],\n [{\n icon: lineLT, // 8 left line\n offset: '0%',\n repeat: '6px'\n }],\n [{\n icon: lineRT, // 9 right line\n offset: '0%',\n repeat: '6px'\n }],\n ];\n\n var j = 0; // Single track street\n if(tracks === 2) j=2; // double track street\n if(tracks===2 && dash ===2 ) j= 4; // double track PRW\n if(tracks ===1 && dash ===2) j= 3; // single track PRW\n if(dash === 1) j = 1; // incline\n if(dash === 3) j = 5; // Subway\n if(trackUsage === \"L\")\n {\n var iconIx = 7;\n var symbol = [{icon: lineR, // 7 right line\n offset: '0%',\n repeat: '6px', strokeColor: color\n }/*,\n {icon: lineL, // left line\n offset: '0%',\n repeat: '6px',\n strokeOpacity: .5\n }*/]\n ;\n if(routeType === 1)\n {// PRW\n iconIx = 9;\n symbol = [{icon: lineRT, // 7 right line\n offset: '0%',\n repeat: '6px', strokeColor: color\n }/*,\n {icon: lineL, // left line\n offset: '0%',\n repeat: '6px',\n strokeOpacity: .5\n }*/]\n ;\n\n }\n this.line = new google.maps.Polyline(\n {\n strokeColor: Color,\n strokeOpacity: 0,\n icons: symbol, //icons[iconIx],\n segmentId: SegmentId,\n zIndex: 100\n });\n\n this.grayLine = new google.maps.Polyline(\n {\n strokeColor: \"#A9A9A9\",\n strokeOpacity: 0,\n //strokeWeight: weight,\n icons: [{icon: lineL, // 7 right line\n offset: '0%',\n repeat: '6px'\n }],\n segmentId: SegmentId,\n zIndex: 50\n });\n webViewBridge.debug(\"segment= \" + SegmentId + \" trackUsage = '\" + trackUsage + \"' routeType=\"+ routeType + \" icon index=\" +iconIx );\n }\n if(trackUsage === \"R\")\n {\n iconIx = 6;\n symbol = [{icon: lineL, // 7 right line\n offset: '0%',\n repeat: '6px', strokeColor: color}/*,\n {\n icon: lineR, // left line\n offset: '0%',\n repeat: '6px',\n strokeOpacity: .5}*/\n ];\n if(routeType === 1) // PRW\n {\n iconIx = 8;\n symbol = [{icon: lineLT, // 7 right line\n offset: '0%',\n repeat: '6px', strokeColor: color}/*,\n {\n icon: lineL, // left line\n offset: '0%',\n repeat: '6px',\n strokeOpacity: .5}*/\n ];\n }\n this.line = new google.maps.Polyline(\n {\n strokeColor: Color,\n strokeOpacity: 0,\n icons: symbol,//icons[iconIx],\n segmentId: SegmentId, zIndex: 100\n });\n\n this.grayLine = new google.maps.Polyline(\n {\n strokeColor: \"#A9A9A9\",\n strokeOpacity: 0,\n //strokeWeight: weight,\n icons: [{icon: lineR, // 7 right line\n offset: '0%',\n repeat: '6px'\n }],\n segmentId: SegmentId, zIndex: 50\n });\n webViewBridge.debug(\"segment= \" + SegmentId + \" trackUsage =\" + trackUsage + \" routeType=\"+ routeType + \" icon index=\" +iconIx );\n\n }\n const symbolThree = {\n path: \"M -2,-2 2,2 M 2,-2 -2,2\",\n strokeColor: \"#292\",\n strokeWeight: 4,\n };\n if(trackUsage === 'B' || trackUsage === ' ')\n {\n //console.error(\"tracks =\" + tracks + \" index = \" + j);\n this.line = new google.maps.Polyline(\n {\n strokeColor: Color,\n strokeOpacity: 0,\n //strokeWeight: weight,\n icons: icons[j],\n segmentId: SegmentId\n });\n }\n\n this.line.segmentId = SegmentId;\n this.segmentId = SegmentId;\n this.routeName = routeName;\n this.segmentName = segmentName;\n this.oneWay = oneWay;\n this.Color = Color;\n var arrow = null;\n this.getLine = function(){\n return newline;\n }\n\n this.getGrayLine = function(){\n return newGrayLine;\n }\n\n this.getArrow = function(){\n if(arrow)\n {\n //alert(\"getArrow \" + Arrow.getInfo());\n }\n return arrow;\n }\n\n this.getColor = function (){\n return Color;\n }\n\n var points = 0;\n var newline = this.line;\n var newGrayLine = this.grayLine;\n\n this.getInfo = function () {\n return this.segmentName + \" route:\" + this.routeName;\n }\n\n this.setArrow = function (Arrow){\n arrow = Arrow;\n }\n var info=this.segmentName + \" route\" + this.routeName;\n\n // function to determine if the supplied point is on a begining or end linesegement of a segment\n this.isPointOnEnd = function(pt)\n {\n var line =newline;\n var path = line.getPath();\n var len = path.getLength();\n webViewBridge.setLen(len);\n var i;\n var mIx = 1;\n var b1 = bearing(pt.lat(), pt.lng(), path.getAt(0).lat(), path.getAt(0).lng());\n if(b1.getDistance() < .020)\n return 0;\n var b2 = bearing(pt.lat(), pt.lng(), path.getAt(len-1).lat(), path.getAt(len-1).lng());\n if(b2.getDistance() < .020)\n return len-1;\n //alert(\"segment \" + SegmentId + \" distance = \" + b1.getDistance() + \" \" + b2.getDistance());\n webViewBridge.setDebug(\"segment \" + SegmentId + \" distance = \" + b1.getDistance() + \" \" + b2.getDistance());\n\n return -1;\n }\n // events\n // Select segment (click)\n google.maps.event.addListener(this.line, \"click\", function(e){\n webViewBridge.setDebug(\"sId = \" + SegmentId + \" \" + segmentName);\n line = newline;\n Arrow = arrow;\n color = Color;\n //currSegment = this;\n hiLiteSelectedLine();\n\n var path = line.getPath();\n var len = path.getLength();\n var begin, end,bounds;\n webViewBridge.setLen(len);\n var i;\n var mIx = 1;\n for(i=0; i < path.getLength()-1; i++)\n {\n begin = path.getAt(i);\n end = path.getAt(i+1);\n bounds = setBounds( begin, end);\n if( bounds.contains(e.latLng)){\n break;\n }\n }\n if(i>0)\n mIx=0;\n //addMarker(i, e.latLng.lat(), e.latLng.lng(), mIx, segmentName + \" route:\" + routeName);\n addMarker(i, begin.lat(), begin.lng(), mIx, segmentName + \" route:\" + routeName, SegmentId);\n //OK window.external.selectSegment(i, SegmentId);\n webViewBridge.selectSegment(i, SegmentId);\n addModeOff();\n });\n\n if(grayLine)\n google.maps.event.addListener(this.line, \"click\", function(e){\n webViewBridge.setDebug(\"sId = \" + SegmentId + \" \" + segmentName);\n line = newline;\n Arrow = arrow;\n color = Color;\n //currSegment = this;\n hiLiteSelectedLine();\n\n// var path = grayLine.getPath();\n var len = path.getLength();\n var begin, end,bounds;\n webViewBridge.setLen(len);\n var i;\n var mIx = 1;\n for(i=0; i < path.getLength()-1; i++)\n {\n begin = path.getAt(i);\n end = path.getAt(i+1);\n bounds = setBounds( begin, end);\n if( bounds.contains(e.latLng)){\n break;\n }\n }\n if(i>0)\n mIx=0;\n //addMarker(i, e.latLng.lat(), e.latLng.lng(), mIx, segmentName + \" route:\" + routeName);\n// addMarker(i, begin.lat(), begin.lng(), mIx, segmentName + \" route:\" + routeName, SegmentId);\n //OK window.external.selectSegment(i, SegmentId);\n webViewBridge.selectSegment(i, SegmentId);\n addModeOff();\n });\n\n\n // right click to add a point\n google.maps.event.addListener(this.line, \"rightclick\", function(e)\n {\n line = newline;\n Arrow = arrow;\n color = Color;\n //currSegment = this;\n if(selectedLine != null)\n selectedLine.setOptions({strokeColor: selectedLineClr});\n line.setOptions({strokeColor: \"#04b4B4\"});\n selectedLineClr = Color;\n selectedLine = line;\n var path = line.getPath();\n var len = path.getLength();\n //OK window.external.setLen(len);\n\n webViewBridge.setLen(len);\n var i;\n for(i=0; i < path.getLength()-1; i++)\n {\n begin = path.getAt(i);\n end = path.getAt(i+1);\n bounds = setBounds( begin, end);\n if( bounds.contains(e.latLng)){\n break;\n }\n }\n //OK window.external.selectSegment(i, SegmentId);\n //webViewBridge.selectSegment(i, SegmentId);\n\n insertPoint(e, line, SegmentId);\n });\n\n // doubleclick to add a station (stop)\n google.maps.event.addListener(this.line, \"dblclick\", function(e)\n {\n line = newline;\n Arrow = arrow;\n color = Color;\n var path = line.getPath();\n var i;\n for(i=0; i < path.getLength()-1; i++)\n {\n begin = path.getAt(i);\n end = path.getAt(i+1);\n bounds = setBounds( begin, end);\n if( bounds.contains(e.latLng)){\n break;\n }\n }\n // window.external.setStation(e.latLng.lat(), e.latLng.lng(), SegmentId, i);\n webViewBridge.setStation(e.latLng.lat(), e.latLng.lng(), SegmentId, i);\n });\n\n\n} // end SegmentInfo",
"function buildTimeline() {\n timelineImages.map(function(item) {\n // This sets the left x value to be in the middle of the fade in and fade out points\n const xPosition = item.x1 + (item.x2 - item.x1);\n \n /*\n Build the HTML item for each object in the array.\n \n Variables are inserted dynamically with the ${} notation.\n \n Styles for each item's\n position are applied dynamically via inline styling\n with the \"style\" attribute. Values are inserted after the CSS property and a \"px\" is added directly after. Inspect the HTML\n source in the console.log to see how the final\n rendering looks.\n */\n\n\n\n\n /* This was commented out for sept 16 test */ \n const html = `\n <div id=\"${item.id}\" class=\"timeline-image\" style=\"left: ${xPosition}px; top: ${item.y}px;\">\n </div>\n `;\n \n /*\n Append the HTML block to the timeline div.\n \n See more here:\n https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML\n */\n return timelineDiv.insertAdjacentHTML('beforeend', html);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inser a library function in the currently active grid | function insertLibFunc() {
var pO = CurProgObj;
var sel1 = document.getElementById('selWin');
var libind = sel1.selectedIndex;
var sel2 = document.getElementById('selWin2');
var funcind = sel2.selectedIndex;
// alert("TODO: Lib ind:" + libind + " funcind:" + funcind);
displayAtLastGrid("");
// Create a function call expression and insert it
//
removeGridHighlight();
// main root expression for the function
//
var libM = pO.libModules[libind];
var libF = libM.allFuncs[funcind];
var libFexpr = libF.funcCallExpr;
var fname = libM.name + "." + libFexpr.str;
var funcExpr = new ExprObj(false, ExprType.LibFuncCall, fname);
// Insert the dummy args so that user knows the number/type of args
// required
//
for (var i = 0; i < libFexpr.exprArr.length; i++) {
var argE = new ExprObj(true,
libFexpr.exprArr[i].type,
libFexpr.exprArr[i].str);
funcExpr.addSubExpr(argE);
}
replaceOrAppendExpr(funcExpr);
drawCodeWindow(CurStepObj); // redraw code window
} | [
"function addLibFuncExpr() {\r\n\r\n drawLibSelWin(0);\r\n}",
"function addFeature() {\n\n}",
"function addNewFuncExpr() {\r\n\r\n // if any grid is currently highlighted, remove that highlight first\r\n // This is important if the user replaces a grid expression with an\r\n // operator\r\n //\r\n removeGridHighlight();\r\n\r\n\r\n // Get the new function name from the user and check for duplicate names\r\n // TODO: Check among grid names of function and let names of the step\r\n //\r\n var isdup = true;\r\n\r\n do {\r\n var fname = prompt(\"Name of new function\", DefFuncName);\r\n\r\n // If user pressed cancel, just return\r\n //\r\n if (!fname)\r\n return;\r\n\r\n isdup = isExistingFuncName(CurModObj, fname);\r\n\r\n if (isdup) {\r\n alert(\"Function name \" + fname + \" already exists!\");\r\n }\r\n\r\n } while (isdup);\r\n\r\n\r\n // main root expression for the function\r\n //\r\n var funcExpr = new ExprObj(false, ExprType.FuncCall, fname);\r\n\r\n // Create a new func obj and record in the current module\r\n //\r\n var fO = new FuncObj();\r\n fO.funcCallExpr = funcExpr; // set reference to func expr\r\n\r\n CurModObj.allFuncs.push(fO); // add function to current module\r\n\r\n assert((fO.argsAdded < 0), \"Can't have any args yet\");\r\n\r\n // STEP A: -------------------------------------------------- \r\n //\r\n // Add return value (scalar grid).\r\n // NOTE: Return value is always a scalar. \r\n //\r\n // Create a scalar grid and add it to the Function Grids/Header\r\n //\r\n var newGId = fO.allGrids.length;\r\n //\r\n var newgO = new GridObj(newGId, DefRetValName, 1, 1,\r\n\t\t\t 1, 1, false, false, false, false);\r\n newgO.isRetVal = true;\r\n //\t\r\n // Record this grid in function header\r\n // Note: We add return value as the very first grid to function.\r\n // This is necessary for having a unique grid ID for each \r\n // Grid (return value is a grid). This is useful in showing\r\n // return *data* value. Also, user can directly assign to this.\r\n //\r\n fO.allGrids.push(newgO);\r\n fO.allSteps[FuncHeaderStepId].allGridIds.push(newGId);\r\n //\r\n fO.argsAdded = 0; // indicates return value added\r\n\r\n // Add the data type to the arg grid. Return value is always integer\r\n //\r\n newgO.dataTypes.push(DataTypes.Integer);\r\n assert((newgO.dataTypes.length == 1), \"must have only global type\");\r\n newgO.typesInDim = -1;\r\n\r\n // Redraw step to reflect the addition of the function\r\n //\r\n drawProgStructHead(); // update program structre heading\r\n replaceOrAppendExpr(funcExpr);\r\n drawCodeWindow(CurStepObj); // redraw code window\r\n}",
"function drawLibSelWin(lib_ind) {\r\n\r\n var pO = CurProgObj;\r\n\r\n // STEP:\r\n // Create the list of all libraries to select\r\n //\r\n var str = \"<table class='selectWin'>\"\r\n str += \"<tr><td> Select Library: <select id='selWin' \" +\r\n \" onchange='drawLibSelWin(this.selectedIndex)'> \";\r\n //\r\n for (var i = 0; i < pO.libModules.length; i++) {\r\n str += \"<option value='\" + i + \"'\";\r\n if (i == lib_ind)\r\n str += \"selected\";\r\n\r\n str += \">\" + pO.libModules[i].name + \"</option>\";\r\n }\r\n\r\n //\r\n str += \"</select>\";\r\n str += \"<BR><BR><div></div>\";\r\n str += \"</td></tr>\"\r\n\r\n\r\n\r\n // STEP:\r\n // Create a list of all functions in the selected library\r\n // \r\n str += \"<tr><td> Select Function: <select id='selWin2'>\";\r\n\r\n //\t+ \" onc='libFuncPicked(\"+ lib_ind + \",this.selectedIndex)'> \";\r\n //\r\n var libM = pO.libModules[lib_ind];\r\n\r\n for (var i = 0; i < libM.allFuncs.length; i++) {\r\n str += \"<option value='\" + i + \"'\";\r\n str += \">\" + getFuncCallStr(libM.allFuncs[i].funcCallExpr) +\r\n \"</option>\";\r\n }\r\n //\r\n str += \"</select>\";\r\n\r\n\r\n str += \"<BR><BR><div></div>\";\r\n str +=\r\n \"<input type='button' value='Cancel' onclick='cancelLibFunc()'>\";\r\n str +=\r\n \"<input type='button' value='Insert' onclick='insertLibFunc()'>\";\r\n\r\n\r\n str += \"<BR><BR><div></div>\";\r\n str += \"</td></tr>\"\r\n\r\n\r\n str += \"</table>\";\r\n\r\n displayAtLastGrid(str);\r\n\r\n // change the innerHTML of the HTML object \r\n //\r\n\r\n\r\n\r\n}",
"function load_ipython_extension () {\r\n events.on('create.Cell',create_cell);\r\n\r\n Jupyter.toolbar.add_buttons_group([\r\n {\r\n \r\n label : 'Input Excel',\r\n icon : 'fa-compress',\r\n callback : run_it\r\n }\r\n \r\n ]);\r\n }",
"function cancelLibFunc() {\r\n\r\n displayAtLastGrid(\"\");\r\n}",
"function insertFuncArg(fcallexpr, arg) {\r\n\r\n var ind = getFuncIdByName(CurModObj, fcallexpr.str);\r\n var fO = CurModObj.allFuncs[ind]; // change CurFuncObj\r\n var sO = CurStepObj;\r\n\r\n assert((arg < fcallexpr.exprArr.length), \"invalid arg position \" +\r\n arg);\r\n\r\n // Particular argument expr in the function *call*\r\n //\r\n var argexpr = fcallexpr.exprArr[arg];\r\n assert(argexpr, \"ERROR: argexpr cannot be null\");\r\n\r\n // arg pos in the header. We add 1 because the first expr is the return\r\n // expression\r\n //\r\n var arggrid = arg + 1;\r\n\r\n // Point the default functionCallExpr in function to this function call\r\n // because updateOtherFuncCalls() depend on this \r\n //\r\n fO.funcCallExpr = fcallexpr;\r\n\r\n // STEP:\r\n //\r\n // Process arg expr in the func *call* and add the corresponding grid\r\n // to function grids (and header step) \r\n //\r\n if (argexpr.isScalarExpr() || argexpr.isGridCell() || argexpr.isLetName()) {\r\n\r\n // SCALAR args\r\n // if this is a number. Create a scalar grid and add push\r\n // to arg list\r\n //\r\n var newGId = fO.allGrids.length; // grid id at the end\r\n\r\n var newgO = new GridObj(newGId, \"param\" + arg, 1, 1,\r\n 1, 1, false, false, false, false);\r\n\r\n // Add the new grid to new function\r\n // Note: newGId is for adding at the end (for pushing)\r\n //\r\n fO.allGrids.push(newgO);\r\n fO.argsAdded += 1;\r\n newgO.inArgNum = arg;\r\n newgO.isConst = true; // incoming arg const by default\r\n\r\n // Record this grid in function header\r\n //\r\n fO.allSteps[FuncHeaderStepId].allGridIds.splice(arggrid, 0,\r\n newGId);\r\n\r\n // If this is a grid cell AND user needs a reference (Don't know\r\n // how to detect this yet), create an *additional* reference\r\n // grid object and record it in newgO (scalar grid). \r\n // We do this to enable an arg to be used as either a scalar\r\n // value or a reference\r\n //\r\n if (0 && argexpr.isGridCell()) { // <--- NOTE 0 \r\n\r\n alert(\"TODO: Handle this case if necessary\");\r\n\r\n /*\r\n\t // TODO: Currently we don't use this 'hidden' reference\r\n\t // grid. Allow switching to this.\r\n\r\n\t // If we pass a grid cell as a *reference* \r\n\t // (not as a sclar val)\r\n\t // it is similar to passing a whole grid reference plus\r\n\t // a set of indices to point to the correct cell\r\n\t // So, this case is similar to isGridRef case.\r\n\t //\r\n\t // NOTE: We use the same 'newGId' as the scalar because\r\n\t // this represents the same grid as scalar arg\r\n\t //\r\n\t var refgO = new cloneGridObj(newGId, argexpr.gO);\r\n\t refgO.caption = \"param\" + arg; // same name as salar\r\n\r\n\r\n\t // This is a grid cell reference. Which will indicate to \r\n\t // draw index values in the arg like Src[arg1,arg2,arg3]\r\n\t //\r\n\t refgO.isGridCellRef = true;\r\n\t \r\n\t // record this reference grid obj in the scalar grid\r\n\t //\r\n\t newgO.refgO = refgO;\r\n\r\n\t // Add the global data type to newgO\r\n\t //\r\n\t newgO.dataTypes.push(findDataTypeOfGridCellExpr(argexpr));\r\n\t */\r\n\r\n } else if (argexpr.isGridCell()) {\r\n\r\n // scalar grid cell (passed by value)\r\n //\r\n newgO.dataTypes.push(findDataTypeOfGridCellExpr(argexpr));\r\n\r\n } else if (argexpr.isLetName()) {\r\n\r\n // alert(\"ARGUMENT IS LET\");\r\n // Here do what needs to be done w.r.t. finding type of new grid\r\n\r\n var letType = findLetType(argexpr, CurModObj);\r\n newgO.dataTypes.push(letType);\r\n\r\n } else {\r\n\r\n // Add the global data type to newgO\r\n // NOTE: For all scalar types (even for a Number), we add type \r\n // integer. For a number, updateFuncArgType() is called\r\n // just after this so it's type will be updated correctly\r\n // \r\n newgO.dataTypes.push(DataTypes.Integer);\r\n }\r\n\r\n // Mark that scalar grid arg has globla data type\r\n //\r\n assert((newgO.dataTypes.length == 1),\r\n \"must have only global type\");\r\n newgO.typesInDim = -1;\r\n\r\n\r\n } else if (argexpr.isGridRef()) {\r\n\r\n // This is a grid reference. So, make a cloned grid \r\n // and insert it to arg list and step\r\n // NOTE: When we genrate code for this new function, the caller\r\n // generates something like func( _out), where \r\n // _out = out.data. So, on the caller side, just introduce\r\n // an argumnet called argX. JavaScript will make\r\n // argX = _out = out.data automatically. There is nothing\r\n // more to do. Within the argument, we can refer to \r\n // the grid cells as argX[i][j] and it will point to \r\n // proper caller's data[]. \r\n //\r\n var newGId = fO.allGrids.length;\r\n var newgO = new cloneGridObj(newGId, argexpr.gO);\r\n newgO.caption = \"param\" + arg;\r\n newgO.isGridRef = true; // mark this as a ref arg\r\n\r\n // Add the new grid to new function\r\n // Note: newGId is for adding at the end (for pushing)\r\n //\r\n fO.allGrids.push(newgO);\r\n fO.argsAdded += 1;\r\n newgO.inArgNum = arg;\r\n newgO.isConst = true; // a ref grid is constat by default\r\n\r\n // Record this grid in function header\r\n //\r\n fO.allSteps[FuncHeaderStepId].allGridIds.splice(arggrid, 0,\r\n newGId);\r\n\r\n } else {\r\n\r\n alert(\"TODO: Create grid for other ... arg\");\r\n }\r\n\r\n // if there are any other function call expressions that call the same\r\n // function update them -- i.e., insert a NeedUpdate argument, or \r\n // replace corresponding arg with a NeedUpdate arg\r\n //\r\n updateOtherFuncCalls(fO, arg, false);\r\n\r\n}",
"function placeInlineLibs(){\r\n //displayMSG(\"Placing libraries - starts\");\r\n try { \r\n var allLib = app.libraries;\r\n var allLibLen = allLib.length;\r\n for (var lb = allLibLen - 1; lb >= 0; lb --){\r\n var closeLib = allLib[lb].close();//closing all opened libraries\r\n }\r\n var libVar = myDoc.textVariables.item(\"LIB_NAME\");\r\n if (libVar.isValid){\r\n var libVarName = libVar.variableOptions.contents;//library name\r\n var libFilePath = File(layerTemplateScript+ \"\\\\\" + libVarName +\".indl\");\r\n if (libFilePath.exists){\r\n var libFile = app.open(libFilePath);\r\n var libVarInserts = myDoc.textVariables.item(\"LIB_INSERTS\");\r\n var libVarInsertsConts = libVarInserts.variableOptions.contents;//library name\r\n libVarInsertsConts = libVarInsertsConts.split('|');\r\n var libVarInsertsContsLen = libVarInsertsConts.length;\r\n for (var li = 0; li < libVarInsertsContsLen; li ++){\r\n var currLibInsert = libVarInsertsConts[li].split(',');\r\n var currAssestName = currLibInsert[0];\r\n var currPstyle = currLibInsert[1];\r\n insertingLibs(libFile, currAssestName, currPstyle);\r\n }//end of for\r\n }//end of if\r\n }//end of if \r\n var allLib = app.libraries;\r\n var allLibLen = allLib.length;\r\n for (var lb = allLibLen - 1; lb >= 0; lb --){\r\n var closeLib = allLib[lb].close();//closing all opened libraries\r\n }//end of for\r\n } catch(e){ \r\n //displayMSG(\"Placing libraries - failed\"); app.activeDocument.close(SaveOptions.YES); exit();\r\n } \r\n //displayMSG(\"Placing libraries - ends\");\r\n}",
"function addGenExpr(expr) {\r\n\r\n var sO = CurStepObj;\r\n\r\n // if any grid is currently highlighted, remove that highlight first\r\n // This is important if the user replaces a grid expression with an\r\n // operator\r\n //\r\n removeGridHighlight();\r\n resetOnInput();\r\n replaceOrAppendExpr(expr);\r\n drawCodeWindow(sO); // redraw code window\r\n}",
"function sharedLibrary (state) {\n return function (row, cb) {\n const [\n /* event */, lib, start, end, slide\n ] = row\n const name = lib[0] === '\"' ? lib.substr(1, lib.length - 2) : lib\n const type = 'LIB'\n const startn = parseInt(start, 16)\n state.code[startn] = { name, start, end, slide, type }\n sorted.add(state.addresses, startn)\n cb()\n }\n}",
"enablePlugin() {\n if (this.enabled) {\n return;\n }\n\n if (this.hot.hasColHeaders()) {\n this.addHook('afterGetColHeader', (col, TH) => this.onAfterGetColHeader(col, TH));\n } else {\n this.addHook('afterRenderer', (TD, row, col) => this.onAfterGetColHeader(col, TD));\n }\n\n this.addHook('afterContextMenuDefaultOptions', options => this.onAfterContextMenuDefaultOptions(options));\n this.addHook('afterGetCellMeta', (row, col, cellProperties) => this.onAfterGetCellMeta(row, col, cellProperties));\n this.addHook('modifyColWidth', (width, col) => this.onModifyColWidth(width, col));\n this.addHook('beforeSetRangeStartOnly', coords => this.onBeforeSetRangeStart(coords));\n this.addHook('beforeSetRangeEnd', coords => this.onBeforeSetRangeEnd(coords));\n this.addHook('hiddenColumn', column => this.isHidden(column));\n this.addHook('beforeStretchingColumnWidth', (width, column) => this.onBeforeStretchingColumnWidth(width, column));\n this.addHook('afterCreateCol', (index, amount) => this.onAfterCreateCol(index, amount));\n this.addHook('afterRemoveCol', (index, amount) => this.onAfterRemoveCol(index, amount));\n this.addHook('init', () => this.onInit());\n\n // Dirty workaround - the section below runs only if the HOT instance is already prepared.\n if (this.hot.view) {\n this.onInit();\n }\n\n super.enablePlugin();\n }",
"addDataLayers(){\n }",
"function fnReloadGrid() {\n $boxGrid.paragonGridReload();\n }",
"function insertNewGenre() {\n // Add code here\n}",
"enablePlugin() {\n if (this.enabled) {\n return;\n }\n let bindStrategy = this.hot.getSettings().bindRowsWithHeaders;\n\n if (typeof bindStrategy !== 'string') {\n bindStrategy = BindStrategy.DEFAULT_STRATEGY;\n }\n this.bindStrategy.setStrategy(bindStrategy);\n this.bindStrategy.createMap(this.hot.countSourceRows());\n\n this.addHook('modifyRowHeader', row => this.onModifyRowHeader(row));\n this.addHook('afterCreateRow', (index, amount) => this.onAfterCreateRow(index, amount));\n this.addHook('beforeRemoveRow', (index, amount) => this.onBeforeRemoveRow(index, amount));\n this.addHook('afterRemoveRow', () => this.onAfterRemoveRow());\n this.addHook('afterLoadData', firstRun => this.onAfterLoadData(firstRun));\n\n super.enablePlugin();\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 }",
"function load_ipython_extension() {\n // Attach WYSIWYG buttons to existing cells when a notebook is loaded\n attach_buttons();\n\n // Attach WYSIWYG button when a new cell is created\n $([Jupyter.events]).on('create.Cell', function(event, target) {\n add_wysiwyg_button(target.cell);\n setTimeout(function() {\n if (!target.cell.rendered) show_wysiwyg_button(target.cell);\n }, 100);\n });\n $([Jupyter.events]).on('edit_mode.Cell', function(event, target) {\n show_wysiwyg_button(target.cell);\n });\n $([Jupyter.events]).on('command_mode.Cell', function(event, target) {\n if (target.cell.rendered) hide_wysiwyg_button(target.cell);\n });\n }",
"function addNewModule() {\r\n\r\n // Prompt user for the new module name\r\n //\r\n var modname = prompt(\"Name of the new module\", \"Module\");\r\n\r\n // if the user pressed cancel, just return\r\n //\r\n if (!modname)\r\n return;\r\n\r\n if (isExistingModuleOrLibName(modname) || isKeyword(modname)) {\r\n alert(\"Name \" + name + \" already exists!\");\r\n return;\r\n }\r\n\r\n // TODO: Check duplicate module/lib/grid/func name\r\n //\r\n\r\n // Create a new module and init it. Make it the current module\r\n //\r\n initCurModule(modname); // init module\r\n\r\n initMainFunc(DefMainFuncName); // add main function and init it\r\n\r\n initCurStep(); // add and init a step\r\n\r\n changeModule(CurProgObj.curModNum);\r\n}",
"function fnReloadGrid(){\n $ibPtLabelPrintGrid.paragonGridReload();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a location with at least `lat` and `lng`, compute its `octant` and its first `x`, `y`, `max`; then set `levels` to an empty array. | function computeOctant(location) {
if (location.lat > 0) {
if (location.lng < -90) {
location.octant = 0;
} else if (location.lng < 0) {
location.octant = 1;
} else if (location.lng < 90) {
location.octant = 2;
} else {
location.octant = 3;
}
} else {
if (location.lng < -90) {
location.octant = 4;
} else if (location.lng < 0) {
location.octant = 5;
} else if (location.lng < 90) {
location.octant = 6;
} else {
location.octant = 7;
}
}
// Compute remainder x,y mapping them to [0,1]
location.x = ((location.lng + 180) % 90) / 90;
location.y = Math.abs(location.lat) / 90;
location.x *= (1-location.y);
location.levels = [];
return location;
} | [
"function computeLatLng(location) {\n\tlet l = location.levels.length;\n\tlet x = location.x;\n\tlet y = location.y;\n\t\n\tfor (let i=l-1; i>=0; i--) {\n\t\tlet level = +location.levels[i];\n\t\tif (level === 1) {\n\t\t\tx /= 2;\n\t\t\ty = y/2 + 0.5;\n\t\t} else if (level === 2) {\n\t\t\tx /= 2;\n\t\t\ty /= 2;\n\t\t} else if (level === 3) {\n\t\t\tx = x/2 + 0.5;\n\t\t\ty /= 2;\n\t\t} else if (level === 0) {\n\t\t\tx = (1 - x)/2;\n\t\t\ty = (1 - y)/2;\n\t\t}\n// \t\tconsole.log(level, x,y);\n\t}\n\t\n\tx /= 1 - y;\n\tx *= 90;\n\ty *= 90;\n\t\n\tif (location.octant == 0) {\n\t\tx -= 180;\n\t} else if (location.octant == 1) {\n\t\tx -= 90;\n\t} else if (location.octant == 2) {\n\t\tx += 0;\n\t} else if (location.octant == 3) {\n\t\tx += 90;\n\t} else if (location.octant == 4) {\n\t\tx -= 180;\n\t\ty = -y;\n\t} else if (location.octant == 5) {\n\t\tx -= 90;\n\t\ty = -y;\n\t} else if (location.octant == 6) {\n\t\tx += 0;\n\t\ty = -y;\n\t} else if (location.octant == 7) {\n\t\tx += 90;\n\t\ty = -y;\n\t}\n\t\n\tlocation.lat = y;\n\tlocation.lng = x;\n\t\n\treturn location;\n}",
"function levelsToLocation(octant, levels, x, y) {\n\tif (x === undefined) x = 0.3;\n\tif (y === undefined) y = 0.3;\n\t\n\tlet location = {\n\t\toctant: octant,\n\t\tlevels: typeof levels === 'String' ? levels.split() : levels,\n\t\tx: x,\n\t\ty: y\n\t}\n\t\n\treturn computeLatLng(location);\n}",
"function LatLongToPixelXY(latitude, longitude, levelOfDetail)\n\t{\n\t\tlatitude = Clip(latitude, MinLatitude, MaxLatitude);\n\t\tlongitude = Clip(longitude, MinLongitude, MaxLongitude);\n\n\t\tvar x = (longitude + 180) / 360; \n\t\tvar sinLatitude = Math.sin(latitude * Math.PI / 180);\n\t\tvar y = 0.5 - Math.log((1 + sinLatitude) / (1 - sinLatitude)) / (4 * Math.PI);\n\n\t\tvar mapSize = MapSize(levelOfDetail);\n\t\tvar pixelX = Clip(x * mapSize + 0.5, 0, mapSize - 1);\n\t\tvar pixelY = Clip(y * mapSize + 0.5, 0, mapSize - 1);\n\t\t\n\t\treturn [ Math.floor(pixelX), Math.floor(pixelY) ];\n\t}",
"function clearLon() {\n lon = [];\n}",
"function locationToNumericHash(location) {\n\tlet acc = location.octant;\n\tlet mult = 8;\n\t\n\tfor (let i in location.levels) {\n\t\tacc += mult * location.levels[i];\n\t\tmult *= 4;\n\t}\n\treturn acc;\n}",
"function setMapLevel(data) {\n\tvar lat_max = 0, lat_min = 1000, lng_max = 0, lng_min = 1000;\n\tvar lat_range = 0, lng_range = 0, level;\n\n\t$.each( data.restaurants, function( i, restaurant ) {\n\t\tlat_max = Math.max(lat_max, restaurant.lat);\n\t\tlat_min = Math.min(lat_min, restaurant.lat);\n\t\tlng_max = Math.max(lng_max, restaurant.lng);\n\t\tlng_min = Math.min(lng_min, restaurant.lng);\n\t});\n\n\tlat_range = lat_max - lat_min;\n\tlng_range = lng_max - lng_min;\n\n\tif ( lat_range > 0.28 || lng_range > 0.18 ) {\n\t\tlevel = 5;\n\t} else if ( lat_range > 0.15 || lng_range > 0.09 ) {\n\t level = 6;\n\t} else if ( lat_range > 0.075 || lng_range > 0.04 ) {\n\t level = 7;\n\t} else if ( lat_range > 0.035 || lng_range > 0.02 ) {\n\t level = 8;\n\t} else if ( lat_range > 0.02 || lng_range > 0.013 ) {\n\t level = 9;\n\t} else if ( lat_range > 0.01 || lng_range > 0.005 ) {\n\t level = 10;\n\t} else {\n\t level = 11;\n\t};\n\t\n\toMap.setLevel(level);\n}",
"function addNoiseToLocation(latlong) {\n latlong.coordinates[0] += generateNoise()\n latlong.coordinates[1] += generateNoise()\n}",
"function PixelXYToLatLong( pixelX, pixelY, levelOfDetail)\n\t{\n\t\tvar mapSize = MapSize(levelOfDetail);\n\t\tvar x = (Clip(pixelX, 0, mapSize - 1) / mapSize) - 0.5;\n\t\tvar y = 0.5 - (Clip(pixelY, 0, mapSize - 1) / mapSize);\n\n\t\tvar latitude = 90 - 360 * Math.atan(Math.exp(-y * 2 * Math.PI)) / Math.PI;\n\t\tvar longitude = 360 * x;\n\t\t\n\t\treturn [ latitude, longitude ];\n\t}",
"function clearLat() {\n lat = [];\n}",
"longitudeToPixelX(longitude, zoom) {\n return (longitude + 180) / 360 * (this.TileSize << zoom);\n }",
"function checkCity(lat, lng) {\n if (lat.toFixed(3) >= 50.000 && lat.toFixed(3) <= 52.000) {\n if (lng.toFixed(3) >= 5.000 && lng.toFixed(3) <= 7.000) {\n inCity = true;\n $('#content_overzicht').empty();\n getWeetjes();\n getKoepons();\n } else {\n if (inCity) {\n notInCity(1);\n }\n else {\n notInCity(0);\n }\n }\n } else {\n if (inCity) {\n notInCity(1);\n }\n else {\n notInCity(0);\n }\n }\n}",
"function latLngToPrecisionLocation(lat, lng, precision){\n\tlet location = {lat: lat, lng: lng};\n\t\n\tcomputeOctant(location);\n\tlet currPrecision = 3;\n\t\n\twhile (currPrecision < precision) {\n\t\tcomputeLevel(location);\n\t\tcurrPrecision += 2;\n\t}\n\treturn (location);\n}",
"function CHtoWGSlat(y, x) {\n\n // Converts military to civil and to unit = 1000km\n // Auxiliary values (% Bern)\n var y_aux = (y - 600000)/1000000;\n var x_aux = (x - 200000)/1000000;\n \n // Process lat\n lat = 16.9023892\n + 3.238272 * x_aux\n - 0.270978 * Math.pow(y_aux,2)\n - 0.002528 * Math.pow(x_aux,2)\n - 0.0447 * Math.pow(y_aux,2) * x_aux\n - 0.0140 * Math.pow(x_aux,3);\n \n // Unit 10000\" to 1 \" and converts seconds to degrees (dec)\n lat = lat * 100/36;\n \n return lat;\n \n}",
"function get_city_dxy_to_index(dx, dy) \n{\n city_tile_map = {};\n city_tile_map[\" 00\"] = 0;\n city_tile_map[\" 10\"] = 1;\n city_tile_map[\" 01\"] = 2;\n city_tile_map[\" 0-1\"] = 3;\n city_tile_map[\" -10\"] = 4;\n city_tile_map[\" 11\"] = 5;\n city_tile_map[\" 1-1\"] = 6;\n city_tile_map[\" -11\"] = 7;\n city_tile_map[\" -1-1\"] = 8;\n city_tile_map[\" 20\"] = 9;\n city_tile_map[\" 02\"] = 10;\n city_tile_map[\" 0-2\"] = 11;\n city_tile_map[\" -20\"] = 12;\n city_tile_map[\" 21\"] = 13;\n city_tile_map[\" 2-1\"] = 14;\n city_tile_map[\" 12\"] = 15;\n city_tile_map[\" 1-2\"] = 16;\n city_tile_map[\" -12\"] = 17;\n city_tile_map[\" -1-2\"] = 18;\n city_tile_map[\" -21\"] = 19;\n city_tile_map[\" -2-1\"] = 20;\n\n return city_tile_map[\" \"+dx+\"\"+dy];\n\n}",
"function cprNLFunction (lat) {\n if (lat < 0) lat = -lat /* Table is simmetric about the equator. */\n if (lat < 10.47047130) return 59\n if (lat < 14.82817437) return 58\n if (lat < 18.18626357) return 57\n if (lat < 21.02939493) return 56\n if (lat < 23.54504487) return 55\n if (lat < 25.82924707) return 54\n if (lat < 27.93898710) return 53\n if (lat < 29.91135686) return 52\n if (lat < 31.77209708) return 51\n if (lat < 33.53993436) return 50\n if (lat < 35.22899598) return 49\n if (lat < 36.85025108) return 48\n if (lat < 38.41241892) return 47\n if (lat < 39.92256684) return 46\n if (lat < 41.38651832) return 45\n if (lat < 42.80914012) return 44\n if (lat < 44.19454951) return 43\n if (lat < 45.54626723) return 42\n if (lat < 46.86733252) return 41\n if (lat < 48.16039128) return 40\n if (lat < 49.42776439) return 39\n if (lat < 50.67150166) return 38\n if (lat < 51.89342469) return 37\n if (lat < 53.09516153) return 36\n if (lat < 54.27817472) return 35\n if (lat < 55.44378444) return 34\n if (lat < 56.59318756) return 33\n if (lat < 57.72747354) return 32\n if (lat < 58.84763776) return 31\n if (lat < 59.95459277) return 30\n if (lat < 61.04917774) return 29\n if (lat < 62.13216659) return 28\n if (lat < 63.20427479) return 27\n if (lat < 64.26616523) return 26\n if (lat < 65.31845310) return 25\n if (lat < 66.36171008) return 24\n if (lat < 67.39646774) return 23\n if (lat < 68.42322022) return 22\n if (lat < 69.44242631) return 21\n if (lat < 70.45451075) return 20\n if (lat < 71.45986473) return 19\n if (lat < 72.45884545) return 18\n if (lat < 73.45177442) return 17\n if (lat < 74.43893416) return 16\n if (lat < 75.42056257) return 15\n if (lat < 76.39684391) return 14\n if (lat < 77.36789461) return 13\n if (lat < 78.33374083) return 12\n if (lat < 79.29428225) return 11\n if (lat < 80.24923213) return 10\n if (lat < 81.19801349) return 9\n if (lat < 82.13956981) return 8\n if (lat < 83.07199445) return 7\n if (lat < 83.99173563) return 6\n if (lat < 84.89166191) return 5\n if (lat < 85.75541621) return 4\n if (lat < 86.53536998) return 3\n if (lat < 87.00000000) return 2\n else return 1\n}",
"function getWebMercatorBoundingBoxFromXYZ (x, y, zoom) {\n const tilesPerSide = tilesPerSideWithZoom(zoom)\n const tileSize = tileSizeWithTilesPerSide(tilesPerSide)\n let minLon = (-1 * WEB_MERCATOR_HALF_WORLD_WIDTH) + (x * tileSize)\n let maxLon = (-1 * WEB_MERCATOR_HALF_WORLD_WIDTH) + ((x + 1) * tileSize)\n let minLat = WEB_MERCATOR_HALF_WORLD_WIDTH - ((y + 1) * tileSize)\n let maxLat = WEB_MERCATOR_HALF_WORLD_WIDTH - (y * tileSize)\n\n minLon = Math.max((-1 * WEB_MERCATOR_HALF_WORLD_WIDTH), minLon)\n maxLon = Math.min(WEB_MERCATOR_HALF_WORLD_WIDTH, maxLon)\n minLat = Math.max((-1 * WEB_MERCATOR_HALF_WORLD_WIDTH), minLat)\n maxLat = Math.min(WEB_MERCATOR_HALF_WORLD_WIDTH, maxLat)\n\n return { minLon, maxLon, minLat, maxLat }\n}",
"function fixLatLng(latlng) {\n\t\t\tlatlng[0] = latlng[0] * 2.6232 - 80.1968;\n\t\t\tlatlng[1] = latlng[1] * 1.964 + 159.8395;\n\t\t\treturn latlng;\n\t\t}",
"function CHtoWGSlng(y, x) {\n\n // Converts military to civil and to unit = 1000km\n // Auxiliary values (% Bern)\n var y_aux = (y - 600000)/1000000;\n var x_aux = (x - 200000)/1000000;\n \n // Process long\n lng = 2.6779094\n + 4.728982 * y_aux\n + 0.791484 * y_aux * x_aux\n + 0.1306 * y_aux * Math.pow(x_aux,2)\n - 0.0436 * Math.pow(y_aux,3);\n \n // Unit 10000\" to 1 \" and converts seconds to degrees (dec)\n lng = lng * 100/36;\n \n return lng;\n \n}",
"getRegionValue(label, cityInfo1){\n let labelArr = label.split(\"/\");\n for (let y in cityInfo1) {\n if (labelArr[0] !== undefined && labelArr[0] === cityInfo1[y].label) {\n for (let z in cityInfo1[y].children) {\n if (labelArr[1] !== undefined && labelArr[1] === cityInfo1[y].children[z].label) {\n for (let i in cityInfo1[y].children[z].children) {\n if (labelArr[2] !== undefined && cityInfo1[y].children[z].children[i].label === labelArr[2]) {\n return [parseInt(cityInfo1[y].value), parseInt(cityInfo1[y].children[z].value), parseInt(cityInfo1[y].children[z].children[i].value)];\n }\n }\n }\n }\n }\n }\n }",
"getRegionForPos(p) {\n let x = p.x;\n let y = p.y;\n return {\n x: Math.floor(x / CELLS_IN_REGION),\n y: Math.floor(y / CELLS_IN_REGION)\n };\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List all persons in a person group, and retrieve person information (including personId, name, userData and persistedFaceIds of registered faces of the person). Http Method GET | personListPersonsInAPersonGroupGet(queryParams, headerParams, pathParams) {
const queryParamsMapped = {};
const headerParamsMapped = {};
const pathParamsMapped = {};
Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, PersonListPersonsInAPersonGroupGetQueryParametersNameMap));
Object.assign(headerParamsMapped, convertParamsToRealParams(headerParams, PersonListPersonsInAPersonGroupGetHeaderParametersNameMap));
Object.assign(pathParamsMapped, convertParamsToRealParams(pathParams, PersonListPersonsInAPersonGroupGetPathParametersNameMap));
return this.makeRequest('/persongroups/{personGroupId}/persons', 'get', queryParamsMapped, headerParamsMapped, pathParamsMapped);
} | [
"async index({ params, response }) {\n const group = await Group.find(params.group_id)\n if (!group) return response.notFound({ message: 'group not found!' })\n\n return group.users()\n .orderBy('id', 'desc')\n .fetch()\n }",
"personGroupGetAPersonGroupGet(queryParams, headerParams, pathParams) {\n const queryParamsMapped = {};\n const headerParamsMapped = {};\n const pathParamsMapped = {};\n Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, PersonGroupGetAPersonGroupGetQueryParametersNameMap));\n Object.assign(headerParamsMapped, convertParamsToRealParams(headerParams, PersonGroupGetAPersonGroupGetHeaderParametersNameMap));\n Object.assign(pathParamsMapped, convertParamsToRealParams(pathParams, PersonGroupGetAPersonGroupGetPathParametersNameMap));\n return this.makeRequest('/persongroups/{personGroupId}', 'get', queryParamsMapped, headerParamsMapped, pathParamsMapped);\n }",
"personGetAPersonFaceGet(queryParams, headerParams, pathParams) {\n const queryParamsMapped = {};\n const headerParamsMapped = {};\n const pathParamsMapped = {};\n Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, PersonGetAPersonFaceGetQueryParametersNameMap));\n Object.assign(headerParamsMapped, convertParamsToRealParams(headerParams, PersonGetAPersonFaceGetHeaderParametersNameMap));\n Object.assign(pathParamsMapped, convertParamsToRealParams(pathParams, PersonGetAPersonFaceGetPathParametersNameMap));\n return this.makeRequest('/persongroups/{personGroupId}/persons/{personId}/persistedFaces/{persistedFaceId}', 'get', queryParamsMapped, headerParamsMapped, pathParamsMapped);\n }",
"function loadSearchPerson(req, res){\r\n // Search keyword entered by user\r\n let name = req.query.name;\r\n console.log(\"Search name = \" + name);\r\n\r\n // Peform searching\r\n if(name === undefined){\r\n // no search term, return all people\r\n searched_people = filter_people(\"\", people);\r\n } else {\r\n console.log(\"searching for people relating to '\" + name + \"'\");\r\n\r\n searched_people = filter_people(name, people);\r\n\r\n // console.log(\"Search Results: \");\r\n // for(let i = 0; i < searched_people.length; i++){\r\n // console.log(searched_people[i].name)\r\n // }\r\n }\r\n\r\n // only contributing users should be allowed to see the add movie button\r\n let user;\r\n if(req.session.loggedin){\r\n user = getUser(req.session.username);\r\n } else {\r\n // user is not logged in so they cannot see the \r\n user = {\"contributing\" : false}\r\n }\r\n\r\n // REST API\r\n res.format({\r\n \"application/json\": function(){\r\n let send_people = [];\r\n\r\n for(let i = 0; i < searched_people.length; i++){\r\n let person = searched_people[i];\r\n personObj = {name: person.name};\r\n send_people.push(personObj);\r\n }\r\n res.send(searched_people);\r\n },\r\n \"text/html\": function(){\r\n res.render(\"search_people.pug\", {peopleList: searched_people, user: user});\r\n }\r\n });\r\n}",
"function loadPersons() {\n return RestApi\n .getState(restApiUrl, Address.HCHAIN1_NAMESPACE)\n .then(function(body) {\n\n\n // the body of a state response will have the an array of addresses with their state entries\n // let's map the raw person data into a processed version using the\n // encoding library\n return body.data\n .map(function(personStateEntry) {\n\n // get the raw base64 data for the state entry\n const base64Data = personStateEntry.data\n\n // convert it from base64 into a CSV string\n const rawPersonData = Encoding.fromBase64(base64Data)\n\n // convert the CSV string into a person object\n return Encoding.deserialize(rawPersonData)\n })\n })\n }",
"function getPersonDetails(cb, personId) {\n\tlet url = `${API_URL}person/${personId}?api_key=${API_KEY}`;\n\tfetch(url, {\n\t\tmethod: 'GET'\n\t}).then(response => response.json()).then(data => {\n\t\tcb(data);\n\t}).catch(err => {\n\t\tconsole.log('error while fetching details', err);\n\t})\n}",
"function getPeople(){\n $.ajax({\n url:'/bios',\n type: 'GET',\n success:appendPerson\n });\n}",
"function htmlPersonsIndex(data)\n{\n\treturn PrintIndex('I', _('Persons Index'), Dwr.search.IndexTypeI, htmlPersonsIndexTable, htmlPersonsIndexList, data);\n}",
"function getDemographicList(personReferenceKey) {\n\n personDemographicsLogic.getDemographics(personReferenceKey).then(function (response) {\n $scope.demographicList = response;\n generateUUID();\n }, function (err) {\n appLogger.log(err);\n appLogger.error('ERR', err);\n\n });\n\n }",
"list(_, res) {\n return pacientes\n .findAll({\n })\n .then(pacientes => res.status(200).send(pacientes))\n .catch(error => res.status(400).send(error))\n }",
"listAllGroups () {\n return this._apiRequest('/groups/all')\n }",
"function createSamplePersons() {\n var personsDS = Entity.Stores.get(DemoApp.Person);\n var p1 = DemoApp.Person.create({\n id:123,\n firstName:\"Aaron\",\n lastName:\"Bourne\",\n DOB:new Date()\n });\n personsDS.add(p1);\n var serialized = p1.serialize();\n personsDS.add(DemoApp.Person.create({\n id:234,\n firstName:\"Bonnie\",\n lastName:\"Highways\"\n })\n );\n personsDS.add(DemoApp.Person.create({\n id:345,\n firstName:\"Daddy\",\n lastName:\"Peacebucks\"\n })\n );\n personsDS.add(DemoApp.Person.create({\n id:456,\n firstName:\"Cotton\",\n lastName:\"Kandi\"\n })\n );\n}",
"personGroupGetPersonGroupTrainingStatusGet(queryParams, headerParams, pathParams) {\n const queryParamsMapped = {};\n const headerParamsMapped = {};\n const pathParamsMapped = {};\n Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, PersonGroupGetPersonGroupTrainingStatusGetQueryParametersNameMap));\n Object.assign(headerParamsMapped, convertParamsToRealParams(headerParams, PersonGroupGetPersonGroupTrainingStatusGetHeaderParametersNameMap));\n Object.assign(pathParamsMapped, convertParamsToRealParams(pathParams, PersonGroupGetPersonGroupTrainingStatusGetPathParametersNameMap));\n return this.makeRequest('/persongroups/{personGroupId}/training', 'get', queryParamsMapped, headerParamsMapped, pathParamsMapped);\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 getPatients() {\n $.get(\"/api/patients\", function(data) {\n var rowsToAdd = [];\n for (var i = 0; i < data.length; i++) {\n rowsToAdd.push(createPatientRow(data[i]));\n }\n renderPatientList(rowsToAdd);\n nameInput.val(\"\");\n });\n }",
"function showAll(request){\n\tnamesDB.getAll(gotNames);\n\tfunction gotNames(names){\n\t\tnamesText = \"\";\n\t\tif (names.length > 0){\n\t\t\tfor (i =0; i < names.length; i++) {\n\t\t\t\t// create a link like: <a href=\"/view/1DlDQu55m85dqNQJ\">Joe</a><br/>\n\t\t\t namesText += '<a href=\"/view/' + names[i]._id + '\">' + names[i].name + \"</a><br/>\";\n\t\t\t}\n\t\t} else {\n\t\t\tnamesText = \"No people in the database yet.\";\n\t\t}\n\t\t\n\t\t//console.log(namesText);\n\t\tvar footerText = '<hr/><p><a href=\"/search\">Search</a>';\n\t\trequest.respond( namesText + footerText);\n\t}\t\n}",
"function getFamilyNames() {\n\treturn new Promise(async(resolve, reject) => {\n\t\tlet retVal = {};\n\t\t\n\t\tlet request = {\n\t\t\ttable: \"Users\",\n\t\t\tcols: [\"group_concat(firstName || ' ' || lastName, ', ') AS names\", \"familyId\"],\n\t\t\tgroup: \"familyId\"\n\t\t}\n\n\t\ttry {\n\t\t\tlet rows = await db.get(request);\n\t\t\treturn resolve(rows);\n\t\t} catch(err) {\n\t\t\treject(err);\n\t\t}\n\t});\n}",
"function getGroup() {\n\n for(var i = 0; i < data.length; i++) {\n\n $('<option value=' + data[i].id + '>' + data[i].firstName + ' ' + data[i].surname + '</option>').appendTo(\"#friendPicker\");\n }\n\n }",
"function entityGroups() {\n // Define the data object and include needed parameters.\n // Make the groups API call and assign a callback function.\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getNotificationRequest: Build GetNotification's request | getNotificationRequest() {
let operation = {
'api': 'GetBucketNotification',
'method': 'GET',
'uri': '/<bucket-name>?notification',
'params': {
},
'headers': {
'Host': this.properties.zone + '.' + this.config.host,
},
'elements': {
},
'properties': this.properties,
'body': undefined
};
this.getNotificationValidate(operation);
return new Request(this.config, operation).build();
} | [
"static getClientNotification(entryId, type){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\tkparams.type = type;\n\t\treturn new kaltura.RequestBuilder('notification', 'getClientNotification', kparams);\n\t}",
"deleteNotificationRequest() {\n let operation = {\n 'api': 'DeleteBucketNotification',\n 'method': 'DELETE',\n 'uri': '/<bucket-name>?notification',\n 'params': {\n },\n 'headers': {\n 'Host': this.properties.zone + '.' + this.config.host,\n },\n 'elements': {\n },\n 'properties': this.properties,\n 'body': undefined\n };\n this.deleteNotificationValidate(operation);\n return new Request(this.config, operation).build();\n }",
"function getRequest(event) {\n //code\n return request = {\n headers: event.headers,\n body: JSON.parse(event.body)\n };\n}",
"function getNotification(){\n\tvar data = {\n\t\t\"session\" : localStorage.sessionId\n\t}\n\tperformPostRequest(\"get-notifications.php\", data, function(data){\n\t\tswitch(data.status) {\n\t\t\tcase 470:\n\t\t\t\tlogOut();\n\t\t\t\tbreak;\n\t\t\tcase 200:\n\t\t\t\tgetGameInvitation(data);\n\t\t\t\tbreak;\n\t\t\tcase 201:\n\t\t\t\tlocalStorage.setItem(\"gameAreaClickCounter\", 1);\n\t\t\t\tlocalStorage.setItem(\"gameTurn\", 1);\n\t\t\t\tlocalStorage.setItem(\"currentGameNum\", data.gameNum);\n\t\t\t\tbeginGame(data.creatorName);\n\t\t\t\tbreak;\n\t\t}\n\t});\n}",
"static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('eventnotification_eventnotificationtemplate', 'get', kparams);\n\t}",
"function getNotification()/*:Notification*/ {\n return this.getNotificationVE$yRG0().getValue();\n }",
"getNotification() {\n return this._notification;\n }",
"function getRequest(event) {\n\n return {\n headers: event.headers,\n body: JSON.parse(event.body)\n };\n}",
"getNotifications(url, trip_id) {\n return axios.get(`${url}notify/${trip_id}`).then(res => {\n return res.data;\n });\n }",
"function newRequest(data){\n var request = createNewRequestContainer(data.requestId);\n createNewRequestInfo(request, data);\n }",
"function getPendingRequests() {\n return {\n 'foia:PendingRequestQuantity': { '$t': 0 },\n 'foia:PendingRequestMedianDaysValue': { '$t': 0 },\n 'foia:PendingRequestAverageDaysValue': { '$t': 0 },\n }\n}",
"getPolicyRequest() {\n let operation = {\n 'api': 'GetBucketPolicy',\n 'method': 'GET',\n 'uri': '/<bucket-name>?policy',\n 'params': {\n },\n 'headers': {\n 'Host': this.properties.zone + '.' + this.config.host,\n },\n 'elements': {\n },\n 'properties': this.properties,\n 'body': undefined\n };\n this.getPolicyValidate(operation);\n return new Request(this.config, operation).build();\n }",
"function GenericRequest() {}",
"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 newItemRequest(endpoint, payload) {\n var request = baseRequest;\n request.url = endpoint;\n request.type = \"POST\";\n request.contentType = \"application/json;odata=verbose\";\n request.headers = {\n \"ACCEPT\": \"application/json;odata=verbose\",\n \"X-RequestDigest\": $(\"#__REQUESTDIGEST\").val()\n };\n request.data = payload;\n return request;\n }",
"async getInitialNotification () {\n if (!isIos()) {\n return this._notifications.getInitialNotification()\n }\n }",
"function getApprovedChangeRequest(employeeId, changeType) {\r\n log.debug('employeeId', employeeId);\r\n log.debug('changeType', changeType);\r\n // Look for Approved and \r\n var mySearch = search.create({\r\n type: 'customrecord_change_approval_request',\r\n columns: ['custrecord_cr_change_type', 'custrecord_cr_approval_status', 'custrecord_cr_completion_status'],\r\n filters: [\r\n ['custrecord_cr_affected_employee', 'is', employeeId] // Affected Employee\r\n ,'and', \r\n ['custrecord_cr_change_type', 'is', changeType] // Matching Change Type\r\n ,'and', \r\n ['custrecord_cr_approval_status', 'is', 3] // Approved\r\n ,'and', \r\n ['custrecord_cr_completion_status', 'is', 1] // Open\r\n ]\r\n });\r\n \r\n var approvalResult = mySearch.run().getRange({\r\n start: 0,\r\n end: 1\r\n });\r\n\r\n log.debug('approvalResult', JSON.stringify(approvalResult));\r\n\r\n // Check for Policy Approver Types\r\n if(approvalResult.length > 0 && approvalResult[0]) {\r\n return approvalResult[0];\r\n }\r\n \r\n return null;\r\n }",
"GetRequest (requestId) {\n\t\tvar req = this.requests[requestId]\n\t\tif (req && req.done) {\n\t\t\tif (req.error) {\n\t\t\t\treturn null\n\t\t\t}\n\n\t\t\tvar s = typeof req.value === 'object' ? req.value : `${req.value}`\n\n return s\n\t\t}\n\t\telse\n\t\t\treturn null\n\t}",
"customRequest (data) {\n return http(data)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Instantiates a new keyboard pre info. This class is used to store keyboard related info for the onPreKeyboardObservable event. | function KeyboardInfoPre(/**
* Defines the type of event (BABYLON.KeyboardEventTypes)
*/type,/**
* Defines the related dom event
*/event){var _this=_super.call(this,type,event)||this;_this.type=type;_this.event=event;_this.skipOnPointerObservable=false;return _this;} | [
"function KeyboardInfo(/**\n * Defines the type of event (BABYLON.KeyboardEventTypes)\n */type,/**\n * Defines the related dom event\n */event){this.type=type;this.event=event;}",
"function PointerInfoPre(type,event,localX,localY){var _this=_super.call(this,type,event)||this;/**\n * Ray from a pointer if availible (eg. 6dof controller)\n */_this.ray=null;_this.skipOnPointerObservable=false;_this.localPosition=new BABYLON.Vector2(localX,localY);return _this;}",
"function prepareApplication(){\n\taddKnPanel();\n\tvar keynapse = window.keynapse;\n\tkeynapse.listener = new window.keypress.Listener();\n\tregisterStartKeys(keynapse);\n}",
"function PrepositionalPhrase(preposition) {\n this.preposition = preposition;\n this.active = true;\n this.amount = undefined;\n this.unit = undefined;\n this.targets = [];\n }",
"constructor () {\n super()\n window.addEventListener('keydown', evt => this.onKeyDown(evt))\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}",
"create() {\n this.scene.bringToTop('CursorScene');\n console.log('Starting screen:', this.key);\n // this.layers.setLayersDepth();\n }",
"function InputManager(){\n\t/**\n\t * @var private attr\n\t */\n\tvar prv={};\n\n\t/**\n\t * @var public attr\n\t */\n\tvar pub=this;\n\n\t/**\n\t * Constructor\n\t */\n\tprv.init=function(){ \n\t\tpub.KEY_ARROW_LEFT=37;\n\t\tpub.KEY_ARROW_UP=38;\n\t\tpub.KEY_ARROW_RIGHT=39;\n\t\tpub.KEY_SPACE=32;\n\t\tprv.keyDown=[];\n\n\t\tdocument.addEventListener('keydown',function(e){\n\t\t\tif(prv.keyDown.indexOf(e.keyCode)==-1){\n\t\t\t\tprv.keyDown.push(e.keyCode);\n\t\t\t}\n\t\t});\n\n\n\t\tdocument.addEventListener('keyup',function(e){\n\t\t\tif(prv.keyDown.indexOf(e.keyCode)!=-1){\n\t\t\t\tprv.keyDown.splice(prv.keyDown.indexOf(e.keyCode));\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Check press key\n\t *\n\t * @param int key key code\n\t * @return boolean\n\t */\n\tpub.isPress=function(key){\n\t\treturn prv.keyDown.indexOf(key)!=-1;\n\t}\n\n\n\tprv.init();\n\n}",
"function initKeyboard(){\r\n\t\tmyKeyboard = null;\r\n\t\tmyKeyboard = input.Keyboard();\r\n\r\n\t\tvar fireKey = JSON.parse(localStorage.getItem('fireKey'));\r\n\t\tvar rotateLeftKey = JSON.parse(localStorage.getItem('rotateLeftKey'));\r\n\t\tvar rotateRightKey = JSON.parse(localStorage.getItem('roateRightKey'));\r\n\t\tvar accelKey = JSON.parse(localStorage.getItem('accelKey'));\r\n\r\n\r\n\t\tif(fireKey != null){\r\n\t\t\tmyKeyboard.registerCommand(fireKey, myShip.fire);\r\n\t\t}\r\n\t\telse{\r\n\t\t\tlocalStorage['fireKey'] = JSON.stringify(KeyEvent.DOM_VK_W);\r\n\t\t\tlocalStorage['fireChar'] = 'w';\r\n\t\t\tmyKeyboard.registerCommand(KeyEvent.DOM_VK_W, myShip.fire);\r\n\t\t}\r\n\r\n\t\tif(rotateLeftKey != null){\r\n\t\t\tmyKeyboard.registerCommand(rotateLeftKey, myShip.rotateLeft);\r\n\t\t}\r\n\t\telse{\r\n\t\t\tlocalStorage['rotateLeftKey'] = JSON.stringify(KeyEvent.DOM_VK_A);\r\n\t\t\tlocalStorage['rotateLeftChar'] = 'a';\r\n\t\t\tmyKeyboard.registerCommand(KeyEvent.DOM_VK_A, myShip.rotateLeft);\r\n\t\t}\r\n\r\n\t\tif(rotateRightKey != null){\r\n\t\t\tmyKeyboard.registerCommand(rotateRightKey, myShip.rotateRight);\r\n\t\t}\r\n\t\telse{\r\n\t\t\tlocalStorage['roateRightKey'] = JSON.stringify(KeyEvent.DOM_VK_D);\r\n\t\t\tlocalStorage['roateRightChar'] = 'd';\r\n\t\t\tmyKeyboard.registerCommand(KeyEvent.DOM_VK_D, myShip.rotateRight);\r\n\t\t}\r\n\r\n\t\tif(accelKey != null){\r\n\t\t\tmyKeyboard.registerCommand(accelKey, myShip.moveUp);\r\n\t\t}\r\n\t\telse{\r\n\t\t\tlocalStorage['accelKey'] = JSON.stringify(KeyEvent.DOM_VK_S);\r\n\t\t\tlocalStorage['accelChar'] = 's';\r\n\t\t\tmyKeyboard.registerCommand(KeyEvent.DOM_VK_S, myShip.moveUp);\r\n\t\t}\r\n\t\t//register escape key for exit game\r\n\t\tmyKeyboard.registerCommand(KeyEvent.DOM_VK_ESCAPE,pauseGame);\r\n\r\n\t\t\r\n\t\t\t\t\r\n\t}",
"init() {\n\t\t'use strict';\n\t\tthis.createRenderer();\n\t\tthis.createScene();\n\n\t\tthis.clock = new THREE.Clock;\n this.clock.start();\n\n\n\t\twindow.addEventListener(\"keydown\", KeyDown);\n window.addEventListener(\"keyup\", KeyUp);\n\t}",
"function initKeyboard(){\n\tkeyStates = {\n\t\t'Left': false,\n\t\t'Right': false,\n\t\t'Up': false,\n\t\t'Down': false,\n\t\t'Shift': false,\n\t\t'Control': false,\n\t\t'Space': false,\n\t\t'E': false,\n\t}\n\n\tconsole.log(\"Now listening for keyboard presses...\");\n\tdocument.addEventListener('keydown', function(event) {\n\t\tlet keyPressed = event.code;\n\t\tif (event.repeat){\n\t\t\t// ignore repeat (held down) key presses\n\t\t\treturn;\n\t\t}\n\t\tif (keyPressed === 'KeyA' || keyPressed === 'ArrowLeft'){\n\t\t\tkeyStates['Left'] = true;\n\t\t}\n\t\telse if (keyPressed === 'KeyW' || keyPressed === 'ArrowUp'){\n\t\t\tkeyStates['Up'] = true;\n\t\t}\n\t\telse if (keyPressed === 'KeyD' || keyPressed === 'ArrowRight'){\n\t\t\tkeyStates['Right'] = true;\n\t\t}\n\t\telse if (keyPressed === 'KeyS' || keyPressed === 'ArrowDown'){\n\t\t\tkeyStates['Down'] = true;\n\t\t}\n\t\telse if (keyPressed === 'ShiftLeft' || keyPressed === 'ShiftRight'){\n\t\t\tkeyStates['Shift'] = true;\n\t\t}\n\t\telse if (keyPressed === 'ControlLeft' || keyPressed === 'ControlRight'){\n\t\t\tkeyStates['Control'] = true;\n\t\t}\n\t\telse if (keyPressed === \"KeyR\" ){\n\t\t\tresetFunction();\n\t\t}\n\n\t\t// note space is queued up and only unset by the player and not keyup event\n\t\telse if (keyPressed === \"Space\" ){\n\t\t\tkeyStates['Space'] = true;\n\t\t}\n\n\t\telse if (keyPressed === \"KeyE\"){\n\t\t\tkeyStates['E'] = true;\n\t\t\tendGame()\n\t\t}\n\n\t})\n\t/* when a key is realeased, remove it from the keystates list */\n\tdocument.addEventListener('keyup', function(event) {\n\t\tlet keyReleased = event.code;\n\n\t\tif (keyReleased === 'KeyA' || keyReleased === 'ArrowLeft'){\n\t\t\tkeyStates['Left'] = false;\n\t\t}\n\t\telse if (keyReleased === 'KeyW' || keyReleased === 'ArrowUp'){\n\t\t\tkeyStates['Up'] = false;\n\t\t}\n\t\telse if (keyReleased === 'KeyD' || keyReleased === 'ArrowRight'){\n\t\t\tkeyStates['Right'] = false;\n\t\t}\n\t\telse if (keyReleased === 'KeyS' || keyReleased === 'ArrowDown'){\n\t\t\tkeyStates['Down'] = false;\n\t\t}\n\t\telse if (keyReleased === 'ShiftLeft' || keyReleased === 'ShiftRight'){\n\t\t\tkeyStates['Shift'] = false;\n\t\t}\n\t})\n}",
"startKeyboardControl() {\n this.state.keyboardEnabled = true;\n }",
"function initPreviews()\r\n {\r\n // remove all previous events\r\n removeEventHandlers();\r\n\r\n // attach click events\r\n var $prev = $qtip.find(\".ilPreviewTooltipPrev\");\r\n var $next = $qtip.find(\".ilPreviewTooltipNext\");\r\n var $items = $qtip.find(\".ilPreviewItem\");\r\n var itemCount = $items.length;\r\n\r\n var currentIdx = -1;\r\n var previewSize = self.previewSize + 2; // add 2 because the image has a border\r\n\r\n /**\r\n * Show the preview image at the specified index.\r\n */\r\n function showIndex(index)\r\n {\r\n log(\"Preview.showIndex(): current=%s, idx=%s\", currentIdx, index);\r\n\r\n // same index as before?\r\n if (index == currentIdx)\r\n return;\r\n\r\n log(\"Preview.showIndex(%s)\", index);\r\n\r\n $items.hide();\r\n\r\n $item = $items.eq(index);\r\n var height = $item.children().height();\r\n $item.css(\"margin-top\", ((previewSize - height) / 2) + \"px\");\r\n $item.show();\r\n\r\n // more than one item?\r\n if (itemCount > 1)\r\n {\r\n $tooltip.qtip(\"api\").set(\"content.title\", self.texts.preview + \" \" + (index + 1) + \" / \" + itemCount);\r\n if (index < 1)\r\n $prev.addClass(\"ilPreviewDisabled\");\r\n else\r\n $prev.removeClass(\"ilPreviewDisabled\");\r\n\r\n if (index >= itemCount - 1)\r\n $next.addClass(\"ilPreviewDisabled\");\r\n else\r\n $next.removeClass(\"ilPreviewDisabled\");\r\n }\r\n else\r\n {\r\n $tooltip.qtip(\"api\").set(\"content.title\", self.texts.preview);\r\n }\r\n\r\n currentIdx = index;\r\n }\r\n\r\n /**\r\n * Show the next preview image.\r\n */\r\n function showNext()\r\n {\r\n if (currentIdx < itemCount - 1)\r\n showIndex(currentIdx + 1);\r\n }\r\n\r\n /**\r\n * Show the previous preview image.\r\n */\r\n function showPrevious()\r\n {\r\n if (currentIdx > 0)\r\n showIndex(currentIdx - 1);\r\n }\r\n\r\n /**\r\n * Handles the events when a key was released.\r\n */\r\n function handleKeyUp(e)\r\n {\r\n // key already pressed? only execute once\r\n if (e.type == \"keydown\")\r\n {\r\n if (isKeyPressed)\r\n {\r\n // prevent default if up or down arrow\r\n if (e.which == 38 || e.which == 40)\r\n e.preventDefault();\r\n\r\n return;\r\n }\r\n\r\n isKeyPressed = true;\r\n\r\n // which key was pressed?\r\n switch (e.which)\r\n {\r\n case 38: // up arrow key\r\n e.preventDefault();\r\n showPreviousPreview();\r\n break;\r\n\r\n case 40: // down arrow key\r\n e.preventDefault();\r\n showNextPreview();\r\n break;\r\n }\r\n }\r\n else\r\n {\r\n isKeyPressed = false;\r\n\r\n // which key was pressed?\r\n switch (e.which)\r\n {\r\n case 37: // left arrow key\r\n e.preventDefault();\r\n showPrevious();\r\n break;\r\n\r\n case 39: // right arrow key\r\n e.preventDefault();\r\n showNext();\r\n break;\r\n\r\n case 36: // HOME\r\n e.preventDefault();\r\n showIndex(0);\r\n break;\r\n\r\n case 35: // END\r\n e.preventDefault();\r\n showIndex(itemCount - 1);\r\n break;\r\n\r\n case 27: // ESC\r\n e.preventDefault();\r\n $tooltip.qtip(\"hide\");\r\n hideTooltip();\r\n break;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Handles the events when the mouse wheel was rotated.\r\n */\r\n function handleMouseWheel(e, delta, deltaX, deltaY)\r\n {\r\n if (deltaY != 0)\r\n {\r\n e.preventDefault();\r\n if (deltaY < 0)\r\n showNext();\r\n else\r\n showPrevious();\r\n }\r\n }\r\n\r\n // more than one item?\r\n if (itemCount > 1)\r\n {\r\n // set number\r\n $items.each(function (index, elem)\r\n {\r\n $(elem).attr(\"data-index\", index);\r\n });\r\n\r\n // click events\r\n $prev.click(showPrevious);\r\n $next.click(showNext);\r\n\r\n $prev.show();\r\n $next.show();\r\n\r\n // attach mouse wheel\r\n // (assign to variable is important that it can be removed later on)\r\n mouseWheelHandler = handleMouseWheel;\r\n $qtip.bind(\"mousewheel\", mouseWheelHandler);\r\n $label.bind(\"mousewheel\", mouseWheelHandler);\r\n }\r\n else\r\n {\r\n $prev.hide();\r\n $next.hide();\r\n }\r\n\r\n // key handlers\r\n // (assign to variable is important that it can be removed later on)\r\n keyHandler = handleKeyUp;\r\n $(document).bind(\"keydown keyup\", keyHandler);\r\n\r\n // hide items and show first\r\n showIndex(0);\r\n }",
"createNote(){\n let note = Text.createNote(this.activeColor);\n this.canvas.add(note);\n this.notifyCanvasChange(note.id, \"added\");\n }",
"_preload () {\n const preloader = new Preloader();\n\n preloader.run().then(() => { this._start() });\n }",
"function virtual_keyboard_set_up() {\r\n\t//populate all key buttons array\r\n\tfor (i = 0; i < 46; i++) {\r\n\t\tkey_array[i] = document.getElementsByClassName(\"key_button_and_name\")[i];\r\n\t\tkey_button_array[i] = document.getElementsByClassName(\"key_button\")[i];\r\n\t}\r\n\t//populate alphanumeric_puncutation key names arrays with lowrcase text\r\n\tfor (i = 0; i < 28; i++) {\r\n\t\tmirrored_font_alphanumeric_punctuation_key_names_arrray[i] = document.getElementsByClassName(\"mirrored_font_key_name alphanumeric_punctuation\")[i];\r\n\t\tmirrored_font_alphanumeric_punctuation_key_names_arrray[i].textContent = String.fromCharCode(lowercase_letter_comma_period_utf_8_array[i]); \r\n\t\tmirrored_alphanumeric_punctuation_key_names_arrray[i] = document.getElementsByClassName(\"mirrored_key_name alphanumeric_punctuation\")[i];\r\n\t\tmirrored_alphanumeric_punctuation_key_names_arrray[i].textContent = String.fromCharCode(lowercase_letter_comma_period_utf_8_array[i]); \r\n\t}\r\n \t//populate single state key names array\r\n\tfor (i = 0; i < 4; i++) {\r\n\t\tmirrored_font_single_state_key_names_array[i] = document.getElementsByClassName(\"single_state_key_names mirrored_font_key_name\")[i];\r\n\t\tmirrored_single_state_key_names_array[i] = document.getElementsByClassName(\"single_state_key_names mirrored_key_name\")[i];\r\n\t}\r\n\t//populate two state key names array\r\n\tfor (i = 0; i < 12; i++) {\r\n\t\tmirrored_font_two_state_key_names_array[i] = document.getElementsByClassName(\"two_state_key_names mirrored_font_key_name\")[i];\r\n\t\tmirrored_two_state_key_names_array[i] = document.getElementsByClassName(\"two_state_key_names mirrored_key_name\")[i];\r\n\t}\r\n\t//populate options key names arrays\r\n\tfor (i = 0; i < 7; i++) {\r\n\t\tmirrored_font_option_key_names_array[i] = document.getElementsByClassName(\"option_key_names mirrored_font_key_name\")[i];\r\n\t\tmirrored_option_key_names_array[i] = document.getElementsByClassName(\"option_key_names mirrored_key_name\")[i];\r\n\t}\r\n\r\n\t//populate mirrored_font_key_name_array\r\n\tmirrored_font_key_name_array.push(mirrored_font_alphanumeric_punctuation_key_names_arrray);\r\n\tmirrored_font_key_name_array.push(mirrored_font_single_state_key_names_array);\r\n\tmirrored_font_key_name_array.push(mirrored_font_two_state_key_names_array);\r\n\tmirrored_font_key_name_array.push(mirrored_font_option_key_names_array);\r\n\t//populate mirrored_key_name_array\r\n\tmirrored_key_name_array.push(mirrored_alphanumeric_punctuation_key_names_arrray);\r\n\tmirrored_key_name_array.push(mirrored_single_state_key_names_array);\r\n\tmirrored_key_name_array.push(mirrored_two_state_key_names_array);\r\n\tmirrored_key_name_array.push(mirrored_option_key_names_array);\r\n\r\n\tmirror_text_type_selection();\r\n\r\n\tinput(\"click\"); //mouse click events\r\n\tinput(\"touchend\"); //touch screen events\r\n\tinput(\"keydown\"); //physical keyboard events\r\n\r\n\tdocument.addEventListener(\"keydown\", function(event) {\r\n\t\tif (event.defaultPrevented) {\r\n\t\t\treturn; // Do nothing if event already handled\r\n\t\t}\r\n\t\tif (event.key == \"Control\" || event.key == \"Alt\" || event.key == \"Shift\"){\r\n\t\t\ttoggle_button(event.target);\r\n\t\t\tmodifier_key_pressed = true;\r\n\t\t\tevent.preventDefault();\r\n\t\t}\r\n\t});\r\n\r\n\tdocument.addEventListener(\"keyup\", function(event) {\r\n\t\tif (event.defaultPrevented) {\r\n\t\t\treturn; // Do nothing if event already handled\r\n\t\t}\r\n\t\tif (event.key == \"Control\" || event.key == \"Alt\" || event.key == \"Shift\") {\r\n\t\t\ttoggle_button(event.target);\r\n\t\t\tmodifier_key_pressed = false;\r\n\t\t\tevent.preventDefault();\r\n\t\t}\r\n\t});\r\n\r\n\t//switch arrow key directions because the textarea is mirrored\r\n textarea_element.addEventListener(\"keydown\", function(event) {\r\n if (event.defaultPrevented) {\r\n\t\t\treturn; // Do nothing if event already handled\r\n\t\t}\r\n if (event.code == \"ArrowLeft\") {\r\n start = textarea_element.selectionStart;\r\n textarea_element.selectionEnd++;\r\n textarea_element.selectionStart = textarea_element.selectionEnd;\r\n scroll_to_cursor();\r\n event.preventDefault();\r\n }\r\n if (event.code == \"ArrowRight\") {\r\n end = textarea_element.selectionEnd;\r\n\t\t\tif (textarea_element.selectionStart > 0) {\r\n\t\t\t\ttextarea_element.selectionStart--;\r\n } else if (textarea_element.selectionStart <= 0) {\r\n\t\t\t\ttextarea_element.selectionStart = 0;\r\n\t\t\t}\r\n textarea_element.selectionEnd = textarea_element.selectionStart;\r\n scroll_to_cursor();\r\n event.preventDefault();\r\n }\r\n\t\t//Select with arrow keys\r\n if (event.code == \"ArrowLeft\" && modifier_key_pressed == true) {\r\n end = textarea_element.selectionEnd++;\r\n textarea_element.setSelectionRange(start, end);\r\n scroll_to_cursor();\r\n event.preventDefault();\r\n }\r\n if (event.code == \"ArrowRight\" && modifier_key_pressed == true) {\r\n\t\t\tif (textarea_element.selectionStart > 0) {\r\n\t\t\t\tstart = textarea_element.selectionStart--;\r\n } else if (textarea_element.selectionStart <= 0) {\r\n\t\t\t\tstart = 0;\r\n\t\t\t}\r\n textarea_element.setSelectionRange(start, end);\r\n scroll_to_cursor();\r\n event.preventDefault();\r\n }\r\n });\r\n}",
"function preRenderCallback(preRenderConfig) {\n\t\tvar chart = preRenderConfig.moonbeamInstance;\n\n\t\t// Example of manually loading a file in this extension's folder path and using it.\n\t\tvar info = tdgchart.util.ajax(preRenderConfig.loadPath + 'lib/extra_properties.json', {asJSON: true});\n\n\t\t// Example of using the chart engine's built in title properties\n\t\tchart.title.visible = false;\n\t\tchart.title.text = info.custom_title;\n//\t\tchart.title.text = 'Cool Visualisation!';\n\t\tchart.footnote.visible = false;\n\t\tchart.footnote.text = 'xxxxxxxx';\n\t\tchart.footnote.align = 'right';\n\t}",
"function keyboard(keyCode) {\n /**\n * Wrapper around HTML keyboard event\n * return the key object \n */\n var key = {};\n key.code = keyCode;\n key.isDown = false;\n key.isUp = true;\n key.press = undefined;\n key.release = undefined;\n //The `downHandler`\n key.downHandler = function (event) {\n if (event.keyCode === key.code) {\n if (key.isUp && key.press) key.press();\n key.isDown = true;\n key.isUp = false;\n }\n event.preventDefault();\n };\n\n //The `upHandler`\n key.upHandler = function (event) {\n if (event.keyCode === key.code) {\n if (key.isDown && key.release) key.release();\n key.isDown = false;\n key.isUp = true;\n }\n event.preventDefault();\n };\n\n //Attach event listeners\n window.addEventListener(\"keydown\", key.downHandler.bind(key), false);\n window.addEventListener(\"keyup\", key.upHandler.bind(key), false);\n\n //Return the key object\n return key;\n}",
"function runPrevKeyDownEvent() {\n /*\n Check to see if the current playlist has been set\n or null and set the previous song.\n */\n if (config.active_playlist == \"\" || config.active_playlist == null) {\n AudioNavigation.setPrevious();\n } else {\n AudioNavigation.setPreviousPlaylist(config.active_playlist);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
resolve orgs into repos before processing | function load_orgs() {
if (orgs.length > 0) {
var org_list = [];
orgs.forEach(function(item) {
(item.type === 'repo') ? repos.push(item) : org_list.push(item);
});
if (org_list.length > 0) {
org_list.forEach(function(item){
var t = new Object();
t.opts = clone(optionsgit);
t.func = get_repos;
var org = item.name;
t.opts = clone(optionsgit);
t.opts.path = '/' + item.type + 's/' + org + '/repos?per_page=100' + '&access_token=' + gittoken + '&call=get_repos';
t.source = 'load_orgs';
throttle(t);
});
}
// start fetching data once the orgs have been enumerated
monitor = setInterval(function(){
if ((timer === null) && (timer_db === null) && (repos.length > 0)) {
fetch_git_data(repos.shift());
}
logger.info('Repo Q:', repos.length, 'GitHub Q:',stack.length, 'Cloudant Q:',stack_db.length);
},2000);
}
} | [
"fetchOrgs() {\n this.orgsSerivce.find({query: this.defaultQuery})\n .then(message => {\n this.setState({orgs: message.data, orgsLoaded: true});\n })\n .catch(err => {\n printToConsole(err);\n displayErrorMessages('fetch', 'organizers', err, this.updateMessagePanel, 'reload');\n this.setState({orgsLoaded: false});\n });\n }",
"function defineLazyLoadedRepos() {\r\n repoNames.forEach(function(name) {\r\n Object.defineProperty(service, name, {\r\n configurable: true, // will redefine this property once\r\n get: function() {\r\n // The 1st time the repo is request via this property,\r\n // we ask the repositories for it (which will inject it).\r\n var repo = getRepo(name);\r\n // Rewrite this property to always return this repo;\r\n // no longer redefinable\r\n Object.defineProperty(service, name, {\r\n value: repo,\r\n configurable: false,\r\n enumerable: true\r\n });\r\n return repo;\r\n }\r\n });\r\n });\r\n }",
"async function getPkgReleases({ lookupName }) {\n logger.debug({ lookupName }, 'orb.getPkgReleases()');\n const cacheNamespace = 'orb';\n const cacheKey = lookupName;\n const cachedResult = await renovateCache.get(cacheNamespace, cacheKey);\n // istanbul ignore if\n if (cachedResult) {\n return cachedResult;\n }\n const url = 'https://circleci.com/graphql-unstable';\n const body = {\n query: `{orb(name:\"${lookupName}\"){name, homeUrl, versions {version, createdAt}}}`,\n variables: {},\n };\n try {\n const res = (await got.post(url, {\n body,\n json: true,\n retry: 5,\n })).body.data.orb;\n if (!res) {\n logger.info({ lookupName }, 'Failed to look up orb');\n return null;\n }\n // Simplify response before caching and returning\n const dep = {\n name: lookupName,\n versions: {},\n };\n if (res.homeUrl && res.homeUrl.length) {\n dep.homepage = res.homeUrl;\n }\n dep.homepage =\n dep.homepage || `https://circleci.com/orbs/registry/orb/${lookupName}`;\n dep.releases = res.versions.map(v => v.version);\n dep.releases = dep.releases.map(version => ({\n version,\n }));\n logger.trace({ dep }, 'dep');\n const cacheMinutes = 15;\n await renovateCache.set(cacheNamespace, cacheKey, dep, cacheMinutes);\n return dep;\n } catch (err) /* istanbul ignore next */ {\n logger.debug({ err }, 'CircleCI Orb lookup error');\n if (err.statusCode === 404 || err.code === 'ENOTFOUND') {\n logger.info({ lookupName }, `CircleCI Orb lookup failure: not found`);\n return null;\n }\n logger.warn({ lookupName }, 'CircleCI Orb lookup failure: Unknown error');\n return null;\n }\n}",
"function getRepos(userHandle) {\n const searchURL = `https://api.github.com/users/${userHandle}/repos`\n \n\n fetch(searchURL)\n .then(response => {\n if (response.ok) return response.json()\n return response.json().then((e) => Promise.reject(e))\n })\n .then(responseJson => displayResults(responseJson))\n .catch(error => {\n console.error(error)\n\n alert(error.message)\n });\n}",
"function compileURLsToFetch (newRepoUrlsToFetch, updatedRepoUrlsToFetch) {\n if (findNewReposComplete === true && getURLsForUpdtdReposComplete === true) {\n combinedArr = newRepoUrlsToFetch.concat(updatedRepoUrlsToFetch)\n console.log(combinedArr.length)\n splitArryToURLs(combinedArr)\n }\n}",
"resolve() {\n this.resolver.resolveAll(this.sources.definitions);\n }",
"function resolveRecurse(options, done) {\n\n //if only one argument was passed, and it's a function, then it's a callback\n // and the user wants the default options\n if (!done && typeof options === 'function') {\n done = options;\n options = {};\n }\n\n if (!options && !done) {\n options = {};\n }\n\n //get the default options, and then get the dependent modules\n //nodify it, to conform to a typical node API but still return a promise\n return mergeDefaultOptions(options).then(function(options) {\n return dependentModules(options.path, null, options);\n }).nodeify(done);\n}",
"function recommendRepos(repoOwner, repoName) {\n // Given a repo name and repo owner.\n // Set repo name and owner into the options for an API request\n // for info on on the given repo's contributors\n const options = {\n url: `https://api.github.com/repos/${repoOwner}/${repoName}/contributors`,\n headers : {\n 'User-Agent': 'request',\n 'Authorization': 'token ' + process.env.GITHUB_API_TOKEN\n }\n };\n request(options, function(err, res, body) {\n let namesOfContributors = [];\n // Put the results in the container as a JSON object\n //\n // Create object that holds info on all the repos contributors,\n // each item is another object holding info about the contributor.\n let repoContribInfo = JSON.parse(body);\n // Iterate over each item in the object\n for (let contribEntry in repoContribInfo) {\n let theEntry = repoContribInfo[contribEntry];\n // Put the login into the array of contributor names.\n namesOfContributors.push(theEntry.login);\n }\n // Return results as an array of logins as strings.\n getStarredRepos(namesOfContributors);\n });\n}",
"function archiveRepositories(devData, githubRepoArray) {\n // console.log('in archiveRepositories', githubRepoArray.length)\n devData.repositories.forEach((repositiesID) => {\n db.Repositories.findById(repositiesID).exec((err, repositiesData) => {\n // If the repoID is not null, find it in the github array of repos.\n if (err) {\n return res.json(err);\n }\n if (repositiesData.repoID) {\n indexNum = githubRepoArray.indexOf(repositiesData.repoID);\n // console.log('indexNum ', indexNum + \" \" + repositiesData.repoID)\n // If you do not find it, delete it.\n // TODO: This needs to be tested! To test this, add a repository to github. Make sure the mongodb is up to date. Delete the github repository. Sign back into your account (to run this code). And make sure the mongodb has marked in inactive and the active flag is false.\n if (indexNum < 0) {\n db.Repositories.findOneAndUpdate(\n { repoID: repositiesData.repoID },\n {\n $set: {\n archiveFlag: true,\n activeFlag: false,\n },\n }\n ).catch((err) => {\n return console.log('error archiving');\n });\n console.log('archived repo ', repositiesData.repoID)\n }\n }\n });\n });\n}",
"function processRepoState() {\n //Error if arg value missing for -repo. Error if folder path resolves\n //to root or is invalid. Otherwise, store value and move on to the next\n //argument.\n if ('-repo' !== sword) {\n if (CDIVUTILS.validateFolderPath(sword)) {\n oresult.srepo = sword;\n bok = true;\n sstate = '';\n } else {\n throw 'Invalid value for command -repo. Invalid statement: ' +\n sword;\n }\n }\n }",
"function getRepoLinks(html) {\n let selTool = cheerio.load(html);\n let topicNameElem = selTool(\".h1-mktg\");\n let repolinks = selTool(\"a.text-bold\");\n // console.log(topicNameElem.text());\n let topicName = topicNameElem.text().trim();\n dirCreater(topicName);\n for (let i = 0; i < 8; i++) {\n let repoPageLink = selTool(repolinks[i]).attr(\"href\");\n //console.log(repoPageLink);\n let repoName = repoPageLink.split(\"/\").pop();\n //let repoName = repoPageLink.split(\"/\");\n //console.log(repoName);\n repoName = repoName.trim();\n // console.log(repoName);\n createFile(repoName, topicName);\n let fullRepoLink = \"https://github.com\" + repoPageLink + \"/issues\";\n //console.log(fullRepoLink);\n getIssues(repoName, topicName, fullRepoLink);\n }\n console.log(\"`````````````````````````\");\n}",
"function getStarredRepos(users) {\n\n let loopEndPoint = users.length;\n let loopCounter = 0;\n let namesOfStarredRepos = [];\n\n// Given an array of github user names\n users.forEach(function(user) {\n // Make an API request\n const options = {\n url: `https://api.github.com/users/${user}/starred`,\n headers : {\n 'User-Agent': 'request',\n 'Authorization': 'token ' + process.env.GITHUB_API_TOKEN\n }\n };\n request(options, function(err, res, body) {\n // Put the results in the container as a JSON object\n // Create object that holds info on all the repos contributors,\n // each item is another object holding info about the contributor.\n let repoListing = JSON.parse(body);\n // console.log(repoListing);\n // Iterate over each item in the object\n for (let starredRepo in repoListing) {\n let theEntry = repoListing[starredRepo];\n // Put the repo names into the array of all starred repos.\n namesOfStarredRepos.push(theEntry.full_name);\n }\n loopCounter += 1;\n\n // Return all of the user's starred repos\n // as an array of repo names as strings.\n\n if (loopCounter >= loopEndPoint) {\n printTopFive(namesOfStarredRepos);\n }\n });\n });\n}",
"async function getRandomGithubRepository() {\n const availablesGithubRepos = [];\n\n githubRepositories.map((repoGithub) => {\n // Check if the GitHub repository exist in our back-end\n const isAvailable = !repositories.some(\n (repo) => repo.title.toLowerCase() === repoGithub.name.toLowerCase()\n );\n\n // If the GitHub repository does not exist in our back-end then we set this repository as available\n if (isAvailable) {\n availablesGithubRepos.push(repoGithub);\n }\n });\n\n // Check if there is an available Github repositories\n if (availablesGithubRepos.length === 0) {\n throw new Error(\"None Github repository available 😕\");\n }\n\n // Get a random integer between 0 and amount of available GitHub repositories\n const randomIndex = Math.floor(\n Math.random() * availablesGithubRepos.length\n );\n\n // Prepare an object to send the params to the getGithubRepositoryLanguages function\n const params = {\n owner: availablesGithubRepos[randomIndex].owner.login,\n name: availablesGithubRepos[randomIndex].name,\n };\n\n // Get techs (languages) from the repository\n const techs = (await getGithubRepositoryLanguages(params)).data;\n\n /**\n * The return of techs variable is something like this:\n *\n * {\n * \"Dart\": 13244,\n * \"Java\": 367,\n * \"JavaScript\": 753\n * }\n *\n * So in this case we are grabbing only the Key of each element and converting it in an Array\n *\n * The result of techsArray should be:\n * [\"Dart\", \"Java\", \"JavaScript\"]\n */\n // Convert techs to an Array\n var techsArray = Object.keys(techs).map((key) => {\n return key;\n });\n\n const repo = {\n title: availablesGithubRepos[randomIndex].name,\n url: availablesGithubRepos[randomIndex].url,\n techs: techsArray,\n };\n\n return repo;\n }",
"function addReposToCard(repos) {\n const reposParent = document.querySelector('.repos')\n repos.slice(0,10).forEach(repo =>{\n const repoEl = document.createElement('a')\n \n repoEl.classList.add('repo')\n repoEl.href = repo.html_url\n repoEl.innerText = repo.name\n repoEl.target = '_blank'\n reposParent.appendChild(repoEl)\n })\n}",
"async getAll(args) {\n if (!args.gist || !args.gist.gist_url || (!args.repoId && !args.orgId)) {\n throw new Error('Wrong arguments, gist url or repo id are missing')\n }\n let selection = {\n gist_url: args.gist.gist_url\n }\n const options = {\n sort: {\n user: 1,\n userId: 1\n }\n }\n if (args.gist.gist_version) {\n selection.gist_version = args.gist.gist_version\n options.sort = {\n 'created_at': -1\n }\n }\n if (args.repoId) {\n selection.repoId = args.repoId\n }\n if (args.orgId) {\n selection.ownerId = args.orgId\n }\n selection = this._updateQuery(selection, args.sharedGist)\n\n if (!args.gist.gist_version) {\n try {\n return CLA.find(selection, {}, options)\n } catch (error) {\n logger.warn('Error occured when getting all signed CLAs for given repo without gist version' + error)\n logger.warn('Api cla.getAll failed with selection ' + selection)\n // eslint-disable-next-line no-console\n console.log('Api cla.getAll failed with selection from console log ' + selection)\n }\n }\n try {\n const clas = await CLA.find(selection, {}, options)\n if (!clas) {\n throw new Error('no clas found')\n }\n return clas\n } catch (error) {\n logger.warn('Error occured when getting all signed CLAs for given repo ' + error)\n }\n\n\n }",
"async function getGitHubBranches($userLogin, $reposName) {\n\n\n}",
"searchRepos() {\n\n if (this.refs.gitUser.refs.input.value === '') {\n return;\n }\n\n this.setState({loading: true});\n\n // Assign user for get their repos\n const gitUSer = this.refs.gitUser.refs.input.value;\n\n // prepare data, use data key!\n let query = JSON.stringify({\n query: `query {\n user(login: \"${gitUSer}\") {\n bio\n url\n company\n email\n avatarUrl\n name\n followers(last: 100) {\n totalCount\n }\n websiteUrl\n starredRepositories(last: 100) {\n totalCount\n }\n repositories(last: 100, orderBy: {field: UPDATED_AT, direction: DESC}) {\n edges {\n node {\n id\n name\n description\n url\n primaryLanguage {\n name\n color\n }\n }\n }\n }\n }\n }`\n });\n\n // use the github endpoint\n fetch(process.env.REACT_APP_GRAPHQL_GITHUB_ENDPOINT, {\n method: 'POST',\n body: query,\n headers: {\n \"Authorization\": process.env.REACT_APP_GITHUB_TOKEN\n }\n }).then(response => {\n return response.json()\n }).then(res => {\n this.setState({\n user: res.data ? res.data.user : null,\n repos: res.data && res.data.user && res.data.user.repositories ? res.data.user.repositories : [],\n loading: false\n })\n })\n }",
"function checkRepo() {\n\t\tif (!pkg.repository) {\n\t\t\tproblems.push({\n\t\t\t\tmessage: `cannot found \"repository\" in package.json.`\n\t\t\t});\n\t\t}\n\t}",
"function updateAllLatest() {\n\tlet r = run('git submodule update -f', __dirname).stdout;\n\tr = r.split('\\n');\n\tr.pop();\n\tlet o = {};\n\tfor (let e of r) {\n\t\tlet nameR = /(?<=projects\\/)([A-Za-z0-9]+)(?=\\/)/,\n\t\t\thashR = /(?<=out ')([A-Za-z0-9]+)(?=')/,\n\t\t\tname = e.match(nameR)[0],\n\t\t\thash = e.match(hashR)[0];\n\t\tif (name && hash)\n\t\t\to[name] = hash;\n\t}\n\tresolve(o);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Accounts for the exemption phaseout at high incomes. It should return the defaultExemptionAmount at lower incomes and 0 for very high incomes, while returning a value in between the two if income is in the phaseout range. | function calculateExemptionAmount(year, filingStatus, income){
var incomeAbovePhaseoutStart = Math.max(0, income - exemptionPhaseoutStart[year][filingStatus]);
var stepsAbovePhaseoutStart = Math.ceil(incomeAbovePhaseoutStart / 2500);
var exemptionPercent = Math.max(0, 1 - (stepsAbovePhaseoutStart * .02));
return Math.round(exemptionPercent * defaultExemptionAmount[year]);
} | [
"salaryFromTakeHome(income) {\n let salary;\n\n const nILowerLimit = this.nILowerLimit * 12;\n const nIUpperLimit = this.nIUpperLimit * 12;\n\n // 1) Income less than NI lower limit\n if (income <= nILowerLimit) {\n salary = income;\n }\n\n // 2) Income within NI Lower limit\n // 2a) Income still in personal allowance\n else if (income <= this.takeHomePay(this.pA)) {\n salary =\n (income - this.nILowerRate * nILowerLimit) / (1 - this.nILowerRate);\n }\n // 2b) Income within basic range\n else if (income <= this.takeHomePay(this.higherRateStart)) {\n salary =\n (income - this.nILowerRate * nILowerLimit - this.basicRate * this.pA) /\n (1 - this.nILowerRate - this.basicRate);\n }\n // 2c) Income within higher rate\n else if (income <= this.takeHomePay(nIUpperLimit)) {\n salary =\n (income -\n this.nILowerRate * nILowerLimit +\n this.basicRate * this.higherRateStart -\n this.basicRate * this.pA -\n this.higherRate * this.higherRateStart) /\n (1 - this.nILowerRate - this.higherRate);\n }\n\n // 3) Income above NI UEL\n // 3a) Higher income rate\n else if (income <= this.takeHomePay(this.pAReductionStart)) {\n salary =\n (income +\n this.nILowerRate * (nIUpperLimit - nILowerLimit) +\n this.basicRate * this.higherRateStart -\n this.basicRate * this.pA -\n this.nIUpperRate * this.nIUpperLimit * 12 -\n this.higherRate * this.higherRateStart) /\n (1 - this.nIUpperRate - this.higherRate);\n }\n\n // 3b) Personal allowance reducing\n else if (\n income <=\n this.takeHomePay(this.pAReductionStart + this.pA / this.pAReductionRate)\n ) {\n salary =\n (-(1 / this.pAReductionRate) *\n (income +\n this.nILowerRate * (nIUpperLimit - nILowerLimit) -\n this.nIUpperRate * nIUpperLimit +\n this.basicRate * (this.higherRateStart - this.pA) -\n this.higherRateStart * this.higherRate -\n (this.basicRate * this.pAReductionStart) /\n (1 / this.pAReductionRate))) /\n (-(1 / this.pAReductionRate) +\n this.basicRate +\n (1 / this.pAReductionRate) * (this.nIUpperRate + this.higherRate));\n }\n\n // 3c) Personal allowance is zero\n else if (income <= this.takeHomePay(this.additionalRateStart)) {\n salary =\n (income +\n this.nILowerRate * (nIUpperLimit - nILowerLimit) +\n this.basicRate * this.higherRateStart -\n this.nIUpperRate * nIUpperLimit -\n this.higherRateStart * this.higherRate) /\n (1 - this.nIUpperRate - this.higherRate);\n }\n\n // 3d) Highest rate\n else {\n salary =\n (income +\n this.nILowerRate * (nIUpperLimit - nILowerLimit) +\n this.basicRate * this.higherRateStart +\n (this.additionalRateStart - this.higherRateStart) * this.higherRate -\n this.nIUpperRate * nIUpperLimit -\n this.additionalRateStart * this.additionalRate) /\n (1 - this.nIUpperRate - this.additionalRate);\n }\n\n return _.round(salary);\n }",
"function alternateInvestment(propertyLoan, propertyPurchase, globalData, yearlyChanges, selScen, month){\n\tvar altInvestment = ((propertyLoan.downPayment/100 + propertyPurchase[selScen].closingCost/100) * propertyPurchase[selScen].purchasePrice + \n\t\t\t propertyPurchase[selScen].capitalImprovement);\n\tvar altInvestmentApp = altInvestment * Math.pow((1 + yearlyChanges[selScen].alternateInvestmentReturn/100/12), month); //B48\n\tvar taxesPaid = (altInvestmentApp - altInvestment) * globalData[selScen].longTermCapitalGain/100; //B49\n\t\n\treturn (altInvestmentApp - taxesPaid - altInvestment); \n}//alternateInvestment",
"async promptOveralExp(step) {\n return await step.prompt(FULL_EXPERIENCE, `How was your overal experience ? on a scale from 1 to 5`, ['1','2','3','4','5']);\n }",
"EstimationSaving () {\n if (this.CheckInput()) {\n let offsetMoney = this.offsetMoney\n let salary = this.monthSalary\n let fixCost = this.fixCost\n let calculationDuration = Math.ceil(this.calculationDuration)\n ? Math.ceil(this.calculationDuration) : 1 // the smallest duration is 1 YEAR\n let bankInterest = this.bankInterest / 100 + 1\n let salaryIncrement = this.salaryIncrement / 100 + 1\n let fixCostIncrement = this.fixCostIncrement / 100 + 1\n let totalAsset = [salary - fixCost + offsetMoney * bankInterest]\n let currentMonth = 1\n // totalAsset in first month = first monthSalary\n\n for (let month = 2; month <= 12; month++) {\n if (month !== this.monthReceiveBonus) {\n currentMonth++\n totalAsset[currentMonth - 1] = totalAsset[currentMonth - 2] *\n bankInterest + salary - fixCost\n } else {\n currentMonth++\n totalAsset[month - 1] = totalAsset[month - 2] *\n bankInterest + salary + this.bonusReward - fixCost\n }\n }\n // Bonus - 13th month salary.\n totalAsset[currentMonth - 1] += salary\n // from the 2nd year - if it exist\n for (let year = 1; year < calculationDuration; year++) {\n salary *= salaryIncrement\n fixCost *= fixCostIncrement\n for (let month = 1; month <= 12; month++) {\n if (month !== this.monthReceiveBonus) {\n currentMonth++\n totalAsset[currentMonth - 1] = totalAsset[currentMonth - 2] *\n bankInterest + salary - fixCost\n } else {\n currentMonth++\n totalAsset[currentMonth - 1] = (totalAsset[currentMonth - 2] *\n bankInterest + salary + this.bonusReward - fixCost)\n }\n }\n }\n return totalAsset\n } else {\n return Promise.reject(\n {err: { msg: 'Invalid input! Please input possitive number ' +\n 'or check again the Bonus salary.'}})\n }\n }",
"addExpense(expenseObj, expenseOut) {\r\n budgetParams['expenses'] += parseInt(expenseObj.amount); \r\n expenseOut.textContent = budgetParams['expenses'];\r\n }",
"calculateNonApreciatedEquity() {\n let yearlyPrinciplePaydown = this.calculatePrinciplePaydown()\n let downpayment = this.calculateDownPayment();\n let equity = []\n for (let i = 1; i <= yearlyPrinciplePaydown.length; i++) {\n let array = yearlyPrinciplePaydown\n let sum = array.slice(0, i).reduce((a, b) => a + b, 0) + downpayment;\n equity.push(Math.floor(sum))\n }\n return equity\n }",
"function getHouseholdIncome(input){\n let money = input.split(\"-$\");\n\n let Average = 0\n\n if (input ===\"$200,000+\"){\n Average = 200000\n }\n else if(input ===\"$0-$9,999\"){\n Average = 5000\n }else{\n \n let minMoney = money[0].slice(1,money[0].length-1).replace(\",\",\"\")\n console.log(money[1])\n let maxMoney = money[1].replace(\",\",\"\")\n Average = (parseInt(minMoney) + parseInt(maxMoney)+1 ) / 2\n }\n\n return Average\n \n}",
"function getWithholdings() {\n const inc = formData[\"estimatedIncome\"];\n if (inc < 9875) {\n setWithholdings(inc * 0.1);\n } else if (inc < 40125) {\n setWithholdings(987.5 + (inc - 9875) * 0.12);\n } else if (inc < 85525) {\n setWithholdings(4617.5 + (inc - 40125) * 0.22);\n } else if (inc < 163301) {\n setWithholdings(14605.5 + (inc - 85525) * 0.24);\n } else if (inc < 207350) {\n setWithholdings(33271.5 + (inc - 163300) * 0.32);\n } else if (inc < 518400) {\n setWithholdings(47367.5 + (inc - 207350) * 0.35);\n } else {\n setWithholdings(156235 + (inc - 518400) * 0.37);\n }\n }",
"function currentlyInfectedCalc(reportedCases, type, population) {\n // if (type === severeImpact) {\n // return Math.min(reportedCases * 50, population);\n // }\n // return Math.min(reportedCases * 10, population);\n console.log(population);\n if (type === severeImpact) {\n return reportedCases * 50;\n }\n return reportedCases * 10;\n}",
"static async getMinBalanceRentForExemptMint(\n connection: Connection,\n ): Promise<number> {\n return await connection.getMinimumBalanceForRentExemption(MintLayout.span);\n }",
"balance() {\n\t\tif (this.dead) {\n\t\t\tthrow new BankError('Account is shut down');\n\t\t} else {\n\t\t\treturn this.credits + this.investments.reduce((s,i) => s += i.principle, 0);\n\t\t}\n\t}",
"function payoutDistFn(n) {\n return Math.exp(-1 * n);\n}",
"static async getMinBalanceRentForExemptAccount(\n connection: Connection,\n ): Promise<number> {\n return await connection.getMinimumBalanceForRentExemption(\n AccountLayout.span,\n );\n }",
"function calculateTaxes(income) {\n if (income < 10000) {\n return (income * .05);\n } else if (income >10000 <20000) {\n return (income * .10);\n } else if (income > 20000) {\n return (income * 15);\n } \n}",
"calculateDownPayment() { return this.getVariable().getPercentDown() * this.getAsset().getValue() }",
"async function convertMetToEth (value, minReturn) {\n console.log('Approving')\n await METToken.methods.approve(AutonomousConverter.options.address, value).send({ from: myAddresses[0], gasPrice })\n var output = await METToken.methods.balanceOf(myAddresses[0]).call()\n console.log('My MET balance before', output)\n output = await web3.eth.getBalance(myAddresses[0])\n console.log('My ETH balance before', output)\n var tx = await AutonomousConverter.methods.convertMetToEth(value, minReturn).send({ from: myAddresses[0], gasPrice })\n console.log('transaction hash', tx.transactionHash)\n output = await METToken.methods.balanceOf(myAddresses[0]).call()\n console.log('My MET balance after', output)\n output = await web3.eth.getBalance(myAddresses[0])\n console.log('My ETH balance After', output)\n process.exit(0)\n}",
"bankSalery(){\n if( this.bankLoan > 0 ){\n let deduction = (this.payBalance * 0.10) \n this.payBalance = this.payBalance - deduction\n if(deduction > this.bankLoan){\n this.bankBalance = this.bankBalance + (deduction - this.bankLoan)\n this.bankLoan = 0\n } else {\n this.bankLoan = this.bankLoan - deduction\n }\n }\n this.bankBalance = this.bankBalance + this.payBalance \n this.payBalance = 0\n }",
"function noMoney() {\n\tlet x = parseInt(balanceText.innerText);\n\tif (x < 0) {\n\t\talert(`no MONEY!!!`);\n\t}\n}",
"function infectionsByRequestedTimeCalc(\n currentlyInfected,\n noOfDays,\n population\n) {\n const factor = Math.trunc(noOfDays / 3);\n // const infectionsByRequestedTime = Math.min(\n // currentlyInfected * (2 ** factor),\n // population\n // );\n console.log(population);\n const infectionsByRequestedTime = currentlyInfected * (2 ** factor);\n\n return infectionsByRequestedTime;\n}",
"async depositMoneyForUser(req, res) {\n const {profile} = req;\n const { userId } = req.params;\n const { amount } = req.body;\n\n if(!userId)\n return this.unprocessableEntity(res, 'You must specify the userId param.')\n if(amount === null || typeof amount === 'undefined')\n return this.unprocessableEntity(res, 'No amount specified.')\n if(amount === 0)\n return this.unprocessableEntity(res, 'Amount must be greater than 0.')\n \n if(!profile)\n return this.unauthorized(res);\n\n const contractsBelongingToUser = await Contract.findAll({\n where: {\n ...Contract.queryUserBelongingContracts(userId),\n ...Contract.queryActiveContracts()\n }\n });\n\n const unpaidJobs = await Job.findAll({\n where: {\n [Op.or]: [{\n paid: {\n [Op.eq]: null\n }\n },{\n paid: {\n [Op.ne]: true\n }\n }],\n ContractId: {\n [Op.in]: contractsBelongingToUser.map((contract) => contract.id)\n }\n }\n });\n\n const totalUnpaidPrice = unpaidJobs.reduce((sum, job) => sum + job.price, 0);\n const upperLimit = 0.25 * totalUnpaidPrice;\n\n if(amount > upperLimit)\n return this.unprocessableEntity(res, 'You can only deposit at most 25% of the unpaid jobs prices sum at the deposit moment.')\n \n const user = await Profile.findOne({\n where: {\n id: userId\n }\n });\n\n if(!user)\n return this.notFound(res, 'User not found');\n \n const newBalance = user.balance + amount;\n\n await Profile.update({\n balance: newBalance\n }, {\n where: {\n id: user.id\n }\n })\n \n return this.ok(res, {\n oldBalance: user.balance,\n newBalance: newBalance\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
New Perspectives on HTML5 and CSS3, 7th Edition Tutorial 10 Case Problem 3 Author: Date: Filename: ah_report.js Functions: calcSum(donorAmt) A callback function that adds the current donation amount in the array to the donationTotal variable findMajorDonors(donorAmt) A callback function that returns the value true only if the current donation amount in the array is greater than or equal to 1000 donorSortDescending(a, b) A callback function used to sort the donation amounts from the array in descending order writeDonorRow(value) A callback function that writes the HTML code for each table row that provides the contact information for the donor | function calcSum(donorAmt) {
donationTotal += donorAmt[9];
} | [
"function outliers_summary(aggregator_id) {\n var start_date = new Date(payments_start_date);\n var start_date_time = new Date(start_date.getFullYear() + \"-\" + (start_date.getMonth() + 1) + \"-\" + start_date.getDate()).getTime();\n var diff = start_date.getTime() - start_date_time;\n var end_date = new Date(payments_to_date);\n var dates = [];\n while (start_date.getTime() <= (end_date.getTime() + diff)) {\n dates.push(start_date.getTime());\n start_date.setDate(start_date.getDate() + 1);\n }\n\n var quantites = new Array(dates.length).fill(0);\n var farmers = new Array(dates.length).fill(0);\n\n for (var i = 0; i < outliers_data.length; i++) {\n if (aggregator_id == outliers_data[i][USER_CREATED__ID]) {\n var index = dates.indexOf(new Date(outliers_data[i]['date']).getTime());\n quantites[index] += (outliers_data[i][QUANTITY__SUM]);\n farmers[index] += (outliers_data[i]['farmer__count']);\n }\n }\n\n transport_data = new Array(dates.length).fill(0);\n\n for (var i = 0; i < outliers_transport_data.length; i++) {\n if (aggregator_id == outliers_transport_data[i][USER_CREATED__ID]) {\n var index = dates.indexOf(new Date(outliers_transport_data[i]['date']).getTime());\n transport_data[index] += outliers_transport_data[i]['transportation_cost__sum'];\n }\n }\n\n var cpk = [];\n $(\"#outliers\").html(\"\");\n for (var i = 0; i < dates.length; i++) {\n // cpk.push(quantites[i] > 0 ? transport_data[i] / quantites[i] : 0.0);\n if (farmers[i] == 0) {\n $('<td class=\"center\" onclick=\"create_outliers_table(' + dates[i] + ',' + aggregator_id + ')\">' + new Date(dates[i]).getDate() + '</td>').appendTo('#outliers');\n } else if (farmers[i] < 3) { //cpk[i] > 0.6\n $('<td class=\"center\" style=\"background-color:rgba(255,0,0,0.2)\" onclick=\"create_outliers_table(' + dates[i] + ',' + aggregator_id + ')\">' + new Date(dates[i]).getDate() + '</td>').appendTo('#outliers');\n } else {\n $('<td class=\"center\" style=\"background-color:rgba(0,255,0,0.2)\" onclick=\"create_outliers_table(' + dates[i] + ',' + aggregator_id + ')\">' + new Date(dates[i]).getDate() + '</td>').appendTo('#outliers');\n }\n }\n}",
"function calculateTotalTransaction(docNumber, journal, report) {\n \n var tDebit = \"\";\n var tCredit = \"\";\n var arr = [];\n\n for (var i = 0; i < journal.rowCount; i++) {\n var tRow = journal.row(i);\n if (tRow.value('Doc') === docNumber) {\n var amount = Banana.SDecimal.abs(tRow.value('JAmount'));\n if (Banana.SDecimal.sign(tRow.value('JAmount')) > 0 ) {\n tDebit = Banana.SDecimal.add(tDebit, amount, {'decimals':2});\n } else {\n tCredit = Banana.SDecimal.add(tCredit, amount, {'decimals':2});\n }\n }\n }\n arr.push(tDebit);\n arr.push(tCredit);\n return arr;\n}",
"function getTotalDue(studentObjArray) {\n let totalDue = 0.0;\n for (let student of studentObjArray) {\n /*JB second error calling sum function expects two numbers/arguments. There's three numbers were looping through in the array,\n so this function doesn't make sense. Right now only one number is getting passed.\n we also aren't storing the result from calling sum into the totalDue variable, so we need to add total += sum(student.tuition)*/\n //totalDue += student.tuition;\n totalDue += sum(student.tuition);\n }\n return totalDue;\n}",
"function ratioRevenue() {\n\nvar i;\nvar ratioRevenue =\"\";\nfor (c in employees) employees[c]['2013 Revenue'] = \"\"; // RESETTING OLD REVENUE2013 VALUES\n\n//TABLE HEADER\n\tratioRevenue += \"<table><th>Internal ID</th><th>Name</th><th>Supervisor</th><th>2012 Revenue</th><th>2013 Revenue</th><th>Revenue Ratio</th>\"; \n\t\n//CALCULATING EACH EMPLOYEE'S REVENUE\t\n\tfor (i in employees){ \n\t\n\t\tfor (r in revenue2013) {\n\t\t\t\n\t\t\tif (employees[i].internalid == revenue2013[r].Employee) {\n\t\t\t\n\t\t\t\temployees[i]['2013 Revenue'] += Number(revenue2013[r].amount);\n\t\t\t\temployees[i]['2013 Revenue'] = Number(employees[i]['2013 Revenue']);\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t}\n\t\t\n// CALCULATING SUPERVISOR'S REVENUE\n\t\tif (employees[i].supervisor) { \n\t\t\t\n\t\t\temployees[employees[i].supervisor-1]['2013 Revenue'] += employees[i]['2013 Revenue'];\n\t\t\temployees[employees[i].supervisor-1]['2013 Revenue'] = parseInt(employees[employees[i].supervisor-1]['2013 Revenue']);\n\t\t}\n\t\t\n\t}\n\t\n// POPULATING PERFORMANCE RATIO OF EMPLOYEES\n\t\n\tfor (i in employees) {\n\t\n\t\temployees[i].ratio = ((((employees[i]['2013 Revenue'].toFixed(2)/employees[i]['2012 Revenue']))*100)-100).toExponential(2).slice(0,-3);\n\t\t\n\t\tconsole.log(employees[i].ratio);\n\t\n\t\tif (employees[i].ratio > 0) {\n\t\t\n\t\t\temployees[i].ratio = \"<span style='color:green; font-size:18px;'>\" + employees[i].ratio + \"% ↑</span>\";\n\t\t\t\n\t\t} else if (employees[i].ratio < 0) {\n\t\t\t\n\t\t\temployees[i].ratio = \"<span style='color:red; font-size:18px;'>\" + employees[i].ratio + \"% ↓</span>\";\n\t\t\t\n\t\t} else {\n\t\t\n\t\t\temployees[i].ratio = \"<span style='color:yellow; font-size:18px;'>\" + employees[i].ratio + \"% </span>\";\n\t\t}\n\t\n\t\n\t\tratioRevenue += \"<tr><td>\" + employees[i].internalid + \"</td><td>\" + employees[i].name + \"</td><td>\" + employees[i].supervisor + \"</td><td>\" + \"$\" + employees[i]['2012 Revenue'].replace(/\\d(?=(\\d{3})+\\.)/g, '$&,') + \"</td><td>\" + \"$\" + employees[i]['2013 Revenue'].toFixed(2).replace(/\\d(?=(\\d{3})+\\.)/g, '$&,') + \"</td><td>\" + employees[i].ratio + \"</td></tr>\";\n\t\n\t}\n\t\t\n// SENDING DATA TO HTML\n\t\tdocument.getElementById(\"ratioRevenue\").innerHTML = ratioRevenue;\n\t\tratioRevenue +=\"</table>\";\n\t\n}",
"function FillCalculator(tablediv, inputYear, myinstitute, stats) {\n var thisYear;\n if (inputYear === \"Shifts All Time\") {\n thisYear = 0;\n } else {\n thisYear = parseInt(inputYear);\n }\n stats = JSON.parse(stats);\n console.log(stats);\n var totalThisYear = 0;\n var totalShifts = 0;\n\n var html = '';\n // iterate through the stats object\n const keys = Object.keys(stats[thisYear]);\n for (const institute of keys) {\n let estimateShifts = stats[thisYear][institute][1];\n let shiftsDone = stats[thisYear][institute][0];\n let percentageDone = shiftsDone/estimateShifts;\n let phdHeadCount = stats[thisYear][institute][2];\n totalThisYear += shiftsDone;\n totalShifts += estimateShifts;\n html += '<tr';\n if (institute.includes(myinstitute)) {\n html += ' style=\"background-color:#e5e5ea;\"';\n }\n // set column to institute name\n html += `><td>${institute}</td>`; \n // set first column\n html += `<td>${shiftsDone}</td>`;\n // set second column\n html += `<td>${phdHeadCount}</td>`;\n // set third column\n html += `<td>${estimateShifts.toFixed(2)}</td>`;\n // set fourth column\n html += `<td>${Math.round(percentageDone * 100)}%</td>`;\n // set fifth column\n let color = \"\";\n let diff = estimateShifts - shiftsDone;\n if (diff > 0) {\n color = \"red\";\n } else {\n color = \"green\";\n }\n html += `<td style=\"color:${color}\">${diff.toFixed(2)}</td></tr>`;\n }\n\n // column with total counts\n html += \"<tr style='border-bottom:1px solid black'><td colspan='100%'>\" + \n \"</td></tr>\";\n html += `<tr><td></td><td><strong>${totalThisYear}</strong></td>` +\n `<td></td><td><strong>${totalShifts.toFixed(2)}</strong></td></tr>`;\n $(tablediv).html(html);\n}",
"function salaryMath () {\n for (let eachEmployee of employeeList) {\n // console.log('At salaryMath beginning salarySum is:', salarySum);\n let increaseSalaryCount = Math.floor((parseInt(eachEmployee.annualSalary)/12));\n salarySum += increaseSalaryCount;\n // console.log(\"now salarySum is\", salarySum);\n $('#grandTotal').empty();\n $('#grandTotal').append('$' + salarySum);\n greaterThanTwentyThousand();\n }\n}",
"function reporter (donuts, guests) {\n if (donuts >= guests) {\n return `There are ${donuts} donuts and ${guests}, so there are enough!`\n }\n else {\n return `There are ${donuts} donuts and ${guests}, so there aren't enough...`\n }\n}",
"function outputOrder(order){\n \"use strict\";\n \n var i;\n var table = \"\";\n var sum = 0;\n \n // Build the heading row of the table\n table += \"<tr>\";\n table += \"<th>#</th><th>Tea</th><th>Milk</th><th>Toppings</th><th>Cost</th>\";\n table += \"</tr>\";\n \n // Build the drink rows of the table\n for(i = 0; i < order.length; i += 1){\n var total = 0;\n total = calculateCost(order[i]);\n \n table += \"<tr>\";\n \n // Drink #\n table += \"<td>Drink \" + (i + 1) + \"</td>\"; \n // Tea\n table += \"<td>\" + order[i].teaType + \"</td>\";\n // Milk\n table += \"<td>\" + order[i].milkOption + \"</td>\";\n // Toppings List\n table += \"<td style='width: 10%'>\" + buildList(order[i].toppingsList, \"\", \" \") + \"</td>\";\n // Drink Cost\n table += \"<td>$\" + total.toFixed(2) + \"</td>\";\n \n table += \"</tr>\";\n \n sum += total;\n }\n \n // Build the final row / total cost row of the table\n table += \"<tr><th></th><th></th><th>Total</th><th></th><th>$\" + sum.toFixed(2) + \"</th></tr>\";\n \n return table;\n}",
"function calculateEstimation() {\n var ADR = 133.21;\n var ACR = 10.13;\n // radio slection sliders\n var travelers = peopleVisit.noUiSlider.get()/12;\n var eventAttendees = eventAttendeeSlider.noUiSlider.get()/12;\n var attendees = attendeeSlider.noUiSlider.get()/12;\n var uniques = uniqueVisitors.noUiSlider.get();\n var travelingPercentage = outOfTown.noUiSlider.get()/100;\n var nights = nightStay.noUiSlider.get();\n var engagementPercentage = engagement.noUiSlider.get()/100;\n\n var selectWho = $('input[name=who]:checked', '#earnings-form').val();\n var visitors = selectWho == 1 ? travelers : selectWho == 2 ? eventAttendees : selectWho == 3 ? attendees : uniques;\n var royaltyMultiplier = parseFloat($('input[name=provide]:checked', '#earnings-form').val());\n\n //Start Calculation\n var numTravelers = visitors*travelingPercentage*12*engagementPercentage;\n var grossSales = numTravelers*nights*ADR;\n console.log('grossSales', grossSales);\n var grossRevenue = grossSales*(ACR/ADR);\n var royalty = grossRevenue * 0.1;\n royalty = royaltyMultiplier > 0 ? (royalty * royaltyMultiplier) : royalty; // estimate should be doubled\n var split = (\"\"+royalty.toFixed(0)).split(\"\");\n\n var html = '';\n var commaCounter = 0;\n for (var i = split.length-1; i >= 0; i--) {\n commaCounter += 1;\n html = '<div class=\"number\">'+split[i]+'</div>' + html;\n if (commaCounter == 3 && i > 0){\n html = '<div class=\"coma\">,</div>' + html;\n commaCounter = 0;\n }\n }\n html = '<div class=\"number-alt\">$</div>'+html;\n $('.earnings-figure').html(html);\n}",
"function PrintDebugConsole() {\n\n let delegateHandlers = {\n giveDelegate: (name, amount) => {\n return name + \" ma dac ogolnie \" + amount.toFixed(2) + \" zl\\r\\n\";\n },\n receiveDelegate: (name, amount) => {\n return name + \" ma dostac ogolnie \" + amount.toFixed(2) + \" zl\\r\\n\";\n },\n tradeDelegate: (from, to, amount) => {\n return from + \" ma odddac \" + amount.toFixed(2) + \" zl dla \" + to + \"\\r\\n\";\n },\n };\n\n let arr = ExampleData();\t//array of people\n People.Add(arr);\n let res = People.Calculate(/*delegateHandlers*/);\t\t//calculate all\n\n //print statistics\n console.log(\"L. os: \" + res.PersonCount\t\t\t\t\t\t//liczba osob skladajacych sie\n + \"\\r\\nSuma: \" + res.Sum \t\t\t\t\t\t//suma wszystkich hajsow za prezent\n + \"\\r\\nZl/Os: \" + res.SumPerOs + \"\\r\\n\");\t\t//ile przypada na osobe\n\n\n console.log(res.ResultText);\t//print result of calculations\n}",
"function calculateDistributorCommission()\n{\n\n\ttry\n\t{\n\t\t// work out the distributor commission\n\t\tdistComm = lookupDistributorCommissionRate();\n\n\t\t// version 1.0.2 , version 1.0.3\n\t\tif(voucherTypeName != 'Physical Voucher')\n\t\t{\n\t\t\tdistribCommission = parseFloat(distComm)/100;\n\t\t\tcomTotal = topUpValue * distribCommission;\n\t\t\tcomTotal = Math.round(comTotal*100)/100;\n\t\t}\n\t\telse if(voucherTypeName == 'Physical Voucher' && voucherPartnerIntID > 0)\n\t\t{\n\t\t\tif(simPartnerIntID != voucherPartnerIntID ) \n\t\t\t{\n\t\t\t\tdistComm = 1;\n\t\t\t\tdistribCommission = parseFloat(distComm)/100;\n\t\t\t\tcomTotal = topUpValue * distribCommission;\n\t\t\t\tcomTotal = Math.round(comTotal*100)/100;\t\t\n\t\t\t\tdiffSimVoucherPartners = 'T';\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\terrorMsg = 'The physical voucher has not been sold yet';\n\n\t\t}\n\n\t}\n\tcatch(e)\n\t{\n\t\terrorHandler(\"calculateDistributorCommission\", e);\t\t\n\t}\n\n\n}",
"function _totalTaxTable() {\n \ttry {\n \t\tvar total_header \t=\t$('.total-header').text().trim();\n \t\tvar freight_val\t\t=\t0;\n \t\tvar insurance_val\t=\t0;\n \t\tvar tax_jp \t\t\t=\t0;\n \t\tif (!$('.value-freight').hasClass('hidden')) {\n\t \t\tfreight_val \t= \t$('.value-freight').val().trim();\n\t\t}\n \t\tif (!$('.value-insurance').hasClass('hidden')) {\n\t\t\tinsurance_val \t= \t$('.value-insurance').val().trim();\n\t\t}\n \t\tif (!$('.value-jp').hasClass('hidden')) {\n\t\t\ttax_jp \t\t\t= \t$('.value-jp').val().trim();\n\t\t}\n\t\tvar total_footer \t=\tparseFloat(freight_val) + parseFloat(insurance_val) + parseFloat(tax_jp) + parseFloat(total_header);\n\t\t$('.total-footer').text(_convertMoneyToIntAndContra(total_footer));\n\t} catch (e) {\n alert('_totalTaxTable' + e.message);\n }\n }",
"function update2013Revenue() {\n\nvar i;\nvar update2013Revenue =\"\";\nfor (c in employees) employees[c]['2013 Revenue'] = \"\"; // RESETTING OLD REVENUE2013 VALUES\n\n//TABLE HEADER\n\tupdate2013Revenue += \"<table><th>Internal ID</th><th>Name</th><th>Supervisor</th><th>2012 Revenue</th><th>2013 Revenue</th>\"; \n\t\n//CALCULATING EACH EMPLOYEE'S REVENUE\t\n\tfor (i in employees){ \n\t\n\t\tfor (r in revenue2013) {\n\t\t\t\n\t\t\tif (employees[i].internalid == revenue2013[r].Employee) {\n\t\t\t\n\t\t\t\temployees[i]['2013 Revenue'] += Number(revenue2013[r].amount);\n\t\t\t\temployees[i]['2013 Revenue'] = Number(employees[i]['2013 Revenue']);\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t}\n\t\t\n// CALCULATING SUPERVISOR'S REVENUE\n\t\tif (employees[i].supervisor) { \n\t\t\t\n\t\t\temployees[employees[i].supervisor-1]['2013 Revenue'] += employees[i]['2013 Revenue'];\n\t\t\temployees[employees[i].supervisor-1]['2013 Revenue'] = parseInt(employees[employees[i].supervisor-1]['2013 Revenue']);\n\t\t}\n\t\t\n\t}\n\n// POPULATING REVENUE 2013 BY EMPLOYEES AND SUPERVISORS\n\tfor (i in employees) update2013Revenue += \"<tr><td>\" + employees[i].internalid + \"</td><td>\" + employees[i].name + \"</td><td>\" + employees[i].supervisor + \"</td><td>\" + \"$\" + employees[i]['2012 Revenue'].replace(/\\d(?=(\\d{3})+\\.)/g, '$&,') + \"</td><td>\" + \"$\" + employees[i]['2013 Revenue'].toFixed(2).replace(/\\d(?=(\\d{3})+\\.)/g, '$&,') + \"</td></tr>\";\n\t\n\t\t\n// SENDING DATA TO HTML\n\t\tdocument.getElementById(\"update2013Revenue\").innerHTML = update2013Revenue;\n\t\tupdate2013Revenue +=\"</table>\";\n\t\n}",
"function balancedSums(arr) {\n /*var len = arr.length, i = 0, j = len - 1, nl_sum = 0, nr_sum = 0, pl_sum = 0,\n pr_sum = 0;\n for (i = 0; i < len; i++) {\n pr_sum = pr_sum + arr[i];\n }\n i = 0;\n while (i<len) {\n nl_sum = nl_sum + arr[i];\n nr_sum = pr_sum - arr[i];\n\n if (pr_sum > nr_sum) {\n console.log(nl_sum + \" \" + pl_sum + \"--\" + nr_sum + \" \" + pr_sum);\n pr_sum = nr_sum;\n pl_sum = nl_sum;\n } else if (pr_sum <= nr_sum) {\n console.log(\"hello\");\n pr_sum = nr_sum;\n pl_sum = nl_sum;\n break;\n }\n\n i++;\n }\n console.log(nl_sum + \" \" + nr_sum + \"bahar\" + pl_sum + \" \" + pr_sum);\n if (pl_sum == nr_sum && pr_sum == nl_sum)\n return \"YES\";\n else\n return \"NO\";\n */\n var len = arr.length, i = 0, l_sum = 0, r_sum = 0, j;\n for (i = 0; i < len; i++){\n l_sum = 0;\n r_sum = 0;\n for (j = 0; j < i; j++) {\n l_sum = l_sum + arr[j];\n }\n console.log(\"l_sum\"+ l_sum);\n for (j = i + 1; j < len; j++) {\n r_sum = r_sum + arr[j];\n }\n console.log(\"r_sum\" + r_sum);\n if (l_sum == r_sum) {\n return \"YES\";\n }\n } \n return \"NO\";\n}",
"function createTableTotal(){\n\n var footer = document.getElementById('cookie-table');\n\n var tableRow = document.createElement('tr');\n\n var tableCell = document.createElement('td');\n\n tableCell.textContent = 'hourly Totals';\n\n tableRow.appendChild(tableCell);\n\n var array = hourlyTotals(); \n\n for(var i = 0; i < array.length; i ++){\n tableCell = document.createElement('td');\n tableCell.textContent = array[i];\n tableRow.appendChild(tableCell);\n }\n footer.appendChild(tableRow);\n\n}",
"function calc(income, days, isTuberculosis) {\r\n let compensation = 0.7 * income; // Compensation is 70% of income\r\n let dailyAllowance = (compensation / 30) * 0.8; // There are 30 days in bank month and 20% is the income tax(100% - 20% = 80% = 0.8)\r\n\r\n let total = 0; // Compensation total\r\n let employerDays = 0; // Amount of employer compensated days\r\n let insuranceDays = 0; // Amount of Health Insurance compensated days\r\n let employerComp = 0; // Compensation by employer (euros)\r\n let insuranceComp = 0; // Compensation by insurance (euros)\r\n\r\n const maxEventLength = isTuberculosis ? 240 : 182; // Max Event length based on either the user has or has not tuberculosis\r\n\r\n // Event can't be bigger than max\r\n if(days > maxEventLength) {\r\n alert(\"Days can't be bigger than max allowed!\");\r\n return \"\";\r\n }\r\n\r\n // Get employer and insurance days\r\n if(days < 4) {\r\n total = 0;\r\n }\r\n else if (days >= 4 && days <= 8) {\r\n employerDays = days - 3;\r\n }\r\n else if (days > 8) {\r\n insuranceDays = days - 8;\r\n employerDays = 5;\r\n }\r\n\r\n // Calculate totals\r\n employerComp = employerDays * dailyAllowance;\r\n insuranceComp = insuranceDays * dailyAllowance;\r\n\r\n total = (employerDays + insuranceDays) * dailyAllowance;\r\n\r\n // Return object of data (if all checks passed)\r\n return {\r\n dailyAllowance,\r\n employerDays,\r\n employerComp,\r\n insuranceDays,\r\n insuranceComp,\r\n total,\r\n };\r\n}",
"function orderSummary(){\r\n\t\r\n\tvar fltSub = fltBase;\r\n\tvar intSize = 1;\r\n\tvar intCrust = 0;\r\n\tvar fltTax = 0;\r\n\tvar fltTotal = 0;\r\n\tvar intOptionCount = 0;\r\n\tvar strPizza = \"<br />\";\r\n\tvar strSummary = \"\";\r\n\tvar strPriceSum = \"\";\r\n\tvar intWhichSpec = 0;\r\n\t\r\n\t// check to see which size is selected\r\n\tfor (var i = 0; i < document.forms[0].rdoSize.length; i++){\r\n\t\tif (document.forms[0].rdoSize[i].checked){\r\n\t\t\tintSize = i;\r\n\t\t}\r\n\t}\r\n\t\r\n\t// set the DHTML display to include pizza size\r\n\tswitch(intSize){\r\n\t\tcase 0:\r\n\t\t strPizza = strPizza + '12\" Pizza Size';\r\n\t\t fltSub = 16.00;\r\n\t\t break;\r\n\t\tcase 1:\r\n\t\t strPizza = strPizza + '16\" Pizza Size';\r\n\t\t fltSub = 20.00;\r\n\t\t break;\r\n\t\tcase 2:\r\n\t\t strPizza = strPizza + '20\" Pizza Size';\r\n\t\t fltSub = 24.00;\r\n\t\t break;\r\n\t}\r\n\t\r\n\t// check to see which pizza crust is chosen\r\n\tfor (var i = 0; i < document.forms[0].rdoCrust.length; i++){\r\n\t\tif (document.forms[0].rdoCrust[i].checked){\r\n\t\t\tintCrust = i;\r\n\t\t}\r\n\t}\r\n\t\r\n\t// set the DHTML display to include crust type\r\n\tswitch(intCrust){\r\n\t\tcase 0:\r\n\t\t strPizza = strPizza + \"<br />\" + \"Thin Crust\"; \r\n\t\t break;\r\n\t\tcase 1:\r\n\t\t strPizza = strPizza + \"<br />\" + \"Pan Crust\";\r\n\t\t fltSub += 2;\r\n\t\t break;\r\n\t}\r\n\r\n\t\t\t\r\n\t// check the toppings that have been requested\r\n\tvar intTopCount = 0;\r\n\tfor (var i = 0; i < document.forms[0].chkToppings.length; i++){\t\r\n\t\tif (document.forms[0].chkToppings[i].checked){\r\n\t\t\tintTopCount += 1;\r\n\t\t\tstrTopID = \"topID\" + i;\r\n\t\t\tstrPizza = strPizza + \" \" +\"<br />\" + document.forms[0].chkToppings[i].value;\r\n\t\t}\r\n\t}\r\n\t\r\n\t\t\r\n\tfltSub = fltSub.toFixed(2);\r\n\t\r\n\tfltTax = fltSub * fltTaxRate;\r\n\t\r\n\tfltTax = fltTax.toFixed(2);\r\n\tfltTotal = parseFloat(fltSub) + parseFloat(fltTax);\r\n\t\r\n\tfltTotal = parseFloat(fltTotal);\r\n\tfltTotal = fltTotal.toFixed(2);\r\n\t\t\r\n\tSetCookie(\"strPizza\", strPizza);\r\n\tSetCookie(\"fltSub\", fltSub);\r\n\tSetCookie(\"fltTax\", fltTax);\r\n\tSetCookie(\"fltTotal\", fltTotal);\r\n\t\r\n\tstrSummary = strPizza;\r\n\t\r\n\tstrPriceSum = \"<table> <tr><td>Subtotal:</td> <td align='right'>$\" + fltSub + \"</td></tr><tr><td>\" + \"Tax:</td> <td align='right' style='border-bottom-color: White; border-bottom-width: 1px; border-bottom-style: solid;'>\" + fltTax + \"</td></tr><tr> <td>Total:</td> <td align='right'>$\" + fltTotal + \"</td></tr></table>\"\r\n\t\r\n\tdocument.getElementById(\"orderSum\").innerHTML = strSummary;\r\n\tdocument.getElementById(\"priceSum\").innerHTML = strPriceSum;\r\n\t\r\n\treturn true;\r\n\r\n}",
"function calcTotal(){\n\n //Variable to hold total of all expense rows\n var totalExp = 0;\n\n //Adds values from row to totalExp\n for (j = 1; j <= 4; j++){\n totalExp += calcRow(j);\n }\n\n return totalExp;\n}",
"function interestCalculator(arr) {\n\tarr.forEach(element => {\n\t\tif (element.principal >= 2500 && element.time > 1 && element.time < 3) {\n\t\t\telement.rate = 3;\n\t\t} else if (element.principal >= 2500 && element.time >= 3) {\n\t\t\telement.rate = 4;\n\t\t} else if (element.principal < 2500 || element.time <= 1) {\n\t\t\telement.rate = 2;\n\t\t} else {\n\t\t\telement.rate = 1;\n\t\t}\n\t\telement.interest = (element.principal * element.rate * element.time) / 100;\n });\n \n\t// With the use of array.map() to create and store the results in \"interestData\"\n\n\tinterestData = data.map(element => {\n\t\treturn element;\n\t});\n\tconsole.log(interestData);\n\treturn interestData;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a [HammerJS Manager]( and attaches it to a given HTML element. | buildHammer(element) {
const mc = new Hammer(element, this.options);
mc.get('pinch').set({ enable: true });
mc.get('rotate').set({ enable: true });
for (const eventName in this.overrides) {
mc.get(eventName).set(this.overrides[eventName]);
}
return mc;
} | [
"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 attachOnDOM(){\n\tdocument.getElementsByTagName('body')[0].appendChild(getComponent())\n}",
"static attach(element) {\n return new DomBuilder(element);\n }",
"function attachPopper(anchor, element) {\n if (popper !== null) {\n popper.destroy();\n }\n\n popper = new Popper(anchor, element, {\n placement: 'auto-start',\n modifiers: {\n preventOverflow: {\n enabled: true,\n },\n shift: {\n enabled: true,\n },\n flip: {\n enabled: true,\n }\n },\n });\n }",
"function addEventListeners() {\n // pan watch point event\n var hammerPointer = new Hammer(document.querySelector('#pointer'));\n hammerPointer.on('pan', onPanPointer);\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 addToDOM(element, someHTML) {\n var div = document.createElement('div');\n div.id = \"b\";\n div.innerHTML = someHTML;\n element.appendChild(div);\n}",
"setHtml(element, html){\n element.html(html);\n }",
"injectElement() {\n document.body.innerHTML = `\n <${this.tagName}></${this.tagName}>\n `;\n mount(this.tagName);\n }",
"function MonsterManager() {\n Manager.call(this);\n}",
"_initFormBehaviorManager() {\n FormBehaviorManager.add(MediaChoice);\n }",
"createHTMLElement(parent){\n let htmlElement=document.createElement(this.htmlTagName);\n this.parent=parent;\n this.parent.appendChild(htmlElement);\n this.htmlElementId=getUniqueId(parent,this.htmlTagName);\n htmlElement.id=this.htmlElementId;\n this.applyStyleToElement();\n widgets[this.htmlElementId]=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}",
"createLayout(){\n const container = createComponent('div', {class: 'container'})\n const pageContent = createComponent('div', {id: 'pageContent', class: 'my-5'})\n const welcomeImage = createComponent('img', {src: \"./images/home.png\", style: \"max-width: 100%\"})\n pageContent.append(welcomeImage)\n nav()\n container.append(pageContent)\n document.getElementById('app').append(container)\n }",
"function addWidgetFor(aItem, aAlarm) {\n let widget = document.createElement(\"calendar-alarm-widget\");\n let alarmRichlist = document.getElementById(\"alarm-richlist\");\n alarmRichlist.appendChild(widget);\n\n widget.item = aItem;\n widget.alarm = aAlarm;\n widget.addEventListener(\"snooze\", onSnoozeAlarm, false);\n widget.addEventListener(\"dismiss\", onDismissAlarm, false);\n widget.addEventListener(\"itemdetails\", onItemDetails, false);\n\n setupTitle();\n\n if (alarmRichlist.selectedIndex < 0) {\n alarmRichlist.selectedIndex = 0;\n }\n\n window.focus();\n window.getAttention();\n}",
"function TabbedElement(containerDiv, managementData, styleClass) {\n var tabContainer = containerDiv.appendChild(document.createElement(\"div\"));\n \n containerDiv.className = styleClass || \"tabbedElement\";\n tabContainer.className = \"tab-container\";\n \n this._containerDiv = containerDiv;\n this._tabContainerDiv = tabContainer;\n this._tabs = new Array();\n this._managementData = managementData;\n this._flashingFunctions = new Object();\n this._selectedIndex = -1;\n}",
"setDomElements() {\n this.dom.header = this.dom.el.querySelector('.mf-tabs__header');\n this.dom.tabs = this.dom.el.querySelectorAll('.mf-tabs__tab');\n this.dom.content = this.dom.el.querySelector('.mf-tabs__content');\n this.dom.panels = this.dom.el.querySelectorAll('.mf-tabs__panel');\n }",
"function GizmoManager(scene){var _this=this;this.scene=scene;this._gizmosEnabled={positionGizmo:false,rotationGizmo:false,scaleGizmo:false,boundingBoxGizmo:false};this._pointerObserver=null;this._attachedMesh=null;this._boundingBoxColor=BABYLON.Color3.FromHexString(\"#0984e3\");/**\n * When bounding box gizmo is enabled, this can be used to track drag/end events\n */this.boundingBoxDragBehavior=new BABYLON.SixDofDragBehavior();/**\n * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)\n */this.attachableMeshes=null;/**\n * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)\n */this.usePointerToAttachGizmos=true;this._defaultKeepDepthUtilityLayer=new BABYLON.UtilityLayerRenderer(scene);this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=false;this._defaultUtilityLayer=new BABYLON.UtilityLayerRenderer(scene);this.gizmos={positionGizmo:null,rotationGizmo:null,scaleGizmo:null,boundingBoxGizmo:null};// Instatiate/dispose gizmos based on pointer actions\nthis._pointerObserver=scene.onPointerObservable.add(function(pointerInfo,state){if(!_this.usePointerToAttachGizmos){return;}if(pointerInfo.type==BABYLON.PointerEventTypes.POINTERDOWN){if(pointerInfo.pickInfo&&pointerInfo.pickInfo.pickedMesh){var node=pointerInfo.pickInfo.pickedMesh;if(_this.attachableMeshes==null){// Attach to the most parent node\nwhile(node&&node.parent!=null){node=node.parent;}}else{// Attach to the parent node that is an attachableMesh\nvar found=false;_this.attachableMeshes.forEach(function(mesh){if(node&&(node==mesh||node.isDescendantOf(mesh))){node=mesh;found=true;}});if(!found){node=null;}}if(node instanceof BABYLON.AbstractMesh){if(_this._attachedMesh!=node){_this.attachToMesh(node);}}else{_this.attachToMesh(null);}}else{_this.attachToMesh(null);}}});}",
"init() {\n this._createShadowRoot()\n this._attachStyles()\n this._createElements()\n }",
"createCommandManager() {\n this.commandManager = new CommandManager({\n editor: this,\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.