query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Hides the participants list | function participants_view_hide() {
DOM("PARTICIPANTS_CLOSE").style.backgroundColor = "rgba(0,0,0,.2)";
setTimeout(function() {
DOM("PARTICIPANTS_CLOSE").style.backgroundColor = "transparent";
participants_view_visible = false;
DOM("PARTICIPANTS_VIEW").style.top = "-100%";
setTimeout(function() {
DOM("PARTICIPANTS_VIEW").style.display = "none";
}, 500);
}, 50);
} | [
"function showParticipant() {\n if (document.getElementsByClassName('participant').classList.contains('hide')){\n document.getElementsByClassName('chat').classList.add('hide');\n document.getElementsByClassName('participant').classList.remove('hide');\n }\n }",
"function hideStudents()\n{\n for(let i=0; i<studentsList.length; i++)\n studentsList[i].style.display = 'none';\n}",
"function hidePlayer() {\r\n setBlockVis(\"annotations\", \"none\");\r\n setBlockVis(\"btnAnnotate\", \"none\");\r\n if (hideSegmentControls == true) { setBlockVis(\"segmentation\", \"none\"); }\r\n setBlockVis(\"player\", \"none\");\r\n}",
"hideFromUser(user1,user2){\n this.users[user1].friendsDontShow.push({name: this.users[user2].name, id: user2});\n return true;\n }",
"function otherLoansShowFeedback() {\n \n // TO DO\n // populate feedback based on the displayed user\n \n document.getElementById('block-other-loans-show-feedback').style.display = \"\";\n \n}",
"unhideFromUser(user1,user2){\n let changed=false;\n for(var i=0;i<this.users[user1].friendsDontShow.length;i++){\n if(this.users[user1].friendsDontShow[i].id == user2){\n this.users[user1].friendsDontShow.splice(i,1);\n changed=true;\n break;\n }\n }\n return changed;\n }",
"function hideSecondPersonRow() {\n let row = document.getElementById('person2')\n row.classList.toggle('show')\n row.style.display = 'none'\n hideMinusPersonButton()\n showAddPersonButton()\n}",
"function hide() {\n // First things first: we don't show it anymore.\n scope.chatIsOpen = false;\n chat.remove();\n }",
"function hidePlayersWinMsgs() {\t\n\t$('#p1WinMessage').hide();\n\t$('#p2WinMessage').hide();\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 showParticipants() {\n var participantContainer = document.getElementById('participant-container');\n\n //This will be used to create a new div for every participant grabbed from Datastore:\n allParticipants.forEach(participant => {\n var newDiv = document.createElement('div');\n newDiv.classList.add('participant');\n\n var name = document.createElement('p');\n name.classList.add('participant-name');\n name.appendChild(document.createTextNode(participant.name));\n newDiv.appendChild(name);\n\n var location = document.createElement('p');\n location.classList.add('participant-info');\n location.appendChild(document.createTextNode(participant.location));\n newDiv.appendChild(location);\n\n participantContainer.appendChild(newDiv);\n });\n}",
"hide() {\n\t\tthis.element.style.visibility = 'hidden';\n\t}",
"function hideInviteMemberSection() {\n var element = document.getElementById('inviteMemberSection');\n jQuery(document).ready(function() {\n\tjQuery(element).hide(300);\n });\n setElementBackgroundColor('#inviteMemberTextField', '#ffffff');\n}",
"function _hideHello() {\n Main.uiGroup.remove_actor(text);\n text = null;\n}",
"hideVisit() {\n\t\tthis.modalContainer.classList.remove(\"visible\");\n\t}",
"function div_hide_learn() {\n\t\tdocument.getElementById('ghi').style.display = \"none\";\n\t}",
"function hideAddPersonButton() {\n let button = document.getElementById('add-person-button-row')\n button.style.display = 'none'\n}",
"function hideInvitationsSection() {\n var element = document.getElementById('invitationsSection');\n jQuery(document).ready(function() {\n\tjQuery(element).hide(300);\n });\n}",
"function hideQuestions() {\n $(\"#question\").hide();\n $(\"#answers\").hide();\n $(\"#timer\").hide();\n $(\"#playAgain\").hide();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find all imports in the code, extracting their filename to populate combo with | extractImports(code) {
const
regex = /'\.\/(.*)';/g,
imports = [];
let result;
while ((result = regex.exec(code)) !== null) {
imports.push(result[1]);
}
return imports;
} | [
"static GetImporters() {}",
"searchUsedImportAlldModules(name) {\n for (let scope of this._importAllModules) {\n let resolve = scope.tryResolveExportedName(name);\n if (resolve !== null)\n return wrapInImportIfNecessary(resolve);\n }\n let matchingUsings = [];\n for (let scope of this._usingModules) {\n let resolve = scope.tryResolveExportedName(name);\n if (resolve !== null) {\n matchingUsings.push([scope, resolve]);\n }\n }\n if (matchingUsings.length === 0) {\n return null;\n }\n if (matchingUsings.length === 1) {\n return wrapInImportIfNecessary(matchingUsings[0][1]);\n }\n // conflicts between multiple usings\n let msg = \"Modules used (\";\n msg += matchingUsings.map((item) => { return item[0].moduleShortName; }).join(\", \");\n msg += \") all export '\" + name + \"'. Must invoke qualify with module name.\";\n console.log(msg);\n return null;\n }",
"findImportDeclaration(name) {\n if (this._importOverrideMapArray.some(importOverrideMap => {\n return Array.from(importOverrideMap.keys()).some(importKey => importKey === name);\n })) {\n return undefined;\n }\n return this.importMap.get(name);\n }",
"function extractDependencies(code, filename) {\n const ast = babylon.parse(code, {sourceType: 'module'});\n const dependencies = new Set();\n const dependencyOffsets = [];\n\n function pushDependency(nodeArgs, parentType) {\n const arg = nodeArgs[0];\n if (nodeArgs.length != 1 || arg.type !== 'StringLiteral') {\n // Dynamic requires directly inside of a try statement are considered optional dependencies\n if (parentType === 'TryStatement') {\n return;\n }\n throw new Error(\n `require() must have a single string literal argument: ${filename}:${arg.loc.start.line - 1}`);\n\n }\n dependencyOffsets.push(arg.start);\n dependencies.add(arg.value);\n }\n\n babel.traverse(ast, {\n CallExpression(path) {\n const node = path.node;\n const callee = node.callee;\n const parent = path.scope.parentBlock;\n if (callee.type === 'Identifier' && callee.name === 'require') {\n pushDependency(node.arguments, parent.type);\n }\n if (callee.type !== 'MemberExpression') {\n return;\n }\n const obj = callee.object;\n const prop = callee.property;\n if (\n obj.type === 'Identifier' &&\n obj.name === 'require' &&\n !callee.computed &&\n prop.name === 'async') {\n pushDependency(node.arguments);\n }\n }\n });\n\n\n return {dependencyOffsets, dependencies: Array.from(dependencies)};\n}",
"transformImportsCore(lines: string[], matchers: RegExp[])\n {\n let changed = false, opts = this.opts;\n for (var l = 0; l < lines.length; l++) {\n for (var m = 0; m < matchers.length; m++) {\n let stop = false;\n for (var i = 0; !stop && i < lines[l].length;) {\n stop = true;\n let match = lines[l].slice(i).match(matchers[m]);\n if (match != null) {\n let importFn = match[1];\n if (importFn === undefined)\n break;\n\n // Check if a test file is imported (which should be left unchanged)\n // Ugh: ./test.js does NOT match *test.*, so strip off ./ prefix\n // TODO: In general I guess we should \"adapt\" the path to the root folder ... or something\n let importFn2 = importFn.match(/^.[/\\\\]/) ? importFn.slice(2) : importFn;\n if (opts[\"replace-test-imports\"] ||\n !opts[\"test-files\"].some(tp => \n globmatch(importFn2 + \".js\", tp) || globmatch(importFn2, tp)) ||\n (opts.nontest || []).some(ig => globmatch(importFn, ig)))\n {\n // Apply replacement patterns\n for (var [from, to] of this.replacementPairs) {\n if ((importFn = importFn.replace(from, to)) !== match[1])\n break;\n };\n if (opts.verbose)\n console.log(`============ replacement on line ${l}: ${match[1]} ==> ${importFn}`);\n if (importFn !== match[1]) {\n // A replacement was made. Insert it into the original line and redo\n let iStart = i + match.index! + match[0].lastIndexOf(match[1]);\n let iEnd = iStart + match[1].length;\n lines[l] = lines[l].slice(0, iStart) + importFn + lines[l].slice(iEnd);\n changed = true;\n stop = false;\n i = iStart + importFn.length;\n }\n }\n }\n }\n }\n }\n return changed;\n }",
"visitImport_name(ctx) {\r\n console.log(\"visitImport_name\");\r\n return {\r\n type: \"ImportName\",\r\n imported: this.visit(ctx.dotted_as_names()),\r\n };\r\n }",
"async function resolveImportSpecifiers({\n importer,\n importSpecifierList,\n exportConditions,\n warn,\n packageInfoCache,\n extensions,\n mainFields,\n preserveSymlinks,\n useBrowserOverrides,\n baseDir,\n moduleDirectories\n}) {\n for (let i = 0; i < importSpecifierList.length; i++) {\n // eslint-disable-next-line no-await-in-loop\n const resolved = await resolveId({\n importer,\n importPath: importSpecifierList[i],\n exportConditions,\n warn,\n packageInfoCache,\n extensions,\n mainFields,\n preserveSymlinks,\n useBrowserOverrides,\n baseDir,\n moduleDirectories\n });\n if (resolved) {\n return resolved;\n }\n }\n return null;\n}",
"async function main() {\n return [Promise.resolve(/*! import() eager */).then(__webpack_require__.bind(__webpack_require__, /*! ./all-imports.js */ \"./src/all-imports.js\"))];\n}",
"function findMigrations(app) {\n var\n dirname = path.join(app.root, MIGRATIONS_DIR),\n results = [];\n\n fstools.walkSync(dirname, /\\d{14}_\\w*\\.js$/, function (file) {\n // skip:\n // - dirname in path starts with underscore, e.g. /foo/_bar/baz.js\n if (file.match(/(^|\\/|\\\\)_/)) { return; }\n\n results.push(path.basename(file));\n });\n\n return results;\n }",
"static get DEFINITION_FILES() {\n return [\n 'core-concepts.js',\n 'layout.js',\n 'flexbox-and-grid.js',\n 'spacing.js',\n 'sizing.js',\n 'typography.js',\n 'backgrounds.js',\n 'borders.js',\n 'effects.js',\n 'filters.js',\n 'tables.js',\n 'transitions-and-animation.js',\n 'transforms.js',\n 'interactivity.js',\n 'svg.js',\n 'accessibility.js',\n ]\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 }",
"function getAllIncludedJS(foldername, filenames) {\n // Default binding\n let JSfilenames = ['assert.js', 'sta.js'];\n filenames.forEach(filename =>\n JSfilenames = JSfilenames.concat(getIncludedJS(foldername, filename)));\n //Deduplication\n JSfilenames = JSfilenames.filter((item, pos) => JSfilenames.indexOf(item) === pos);\n let harnessfoldername = `${process.env.JISET_HOME}/tests/test262/harness/`;\n let includedcontents = \"\";\n JSfilenames.forEach(filename =>\n includedcontents += getFileContent(harnessfoldername, filename))\n return includedcontents\n}",
"visitImport_stmt(ctx) {\r\n console.log(\"visitImport_stmt\");\r\n if (ctx.import_name() !== null) {\r\n return this.visit(ctx.import_name());\r\n } else {\r\n return this.visit(ctx.import_from());\r\n }\r\n }",
"function src(...modules) {\n return filter(...modules).map(d => d.src)\n}",
"transformAllImports(testFiles: string[]) {\n var editCount = 0;\n for (var filename of testFiles) {\n if (this.transformImports(filename, filename))\n editCount++;\n }\n return editCount;\n }",
"async function getSrcFiles() {\n const result = []\n const files = await treeToList(SRC_DIR)\n for (const f of files) {\n if (!f.file) continue\n const isTS = f.file.endsWith('.ts') && !f.file.endsWith('.d.ts')\n const isVUE = f.file.endsWith('.vue')\n if (!isTS && !isVUE) continue\n\n const srcPath = path.join(f.dir, f.file)\n const outDir = path.join(OUTPUT_DIR, f.dir.replace(NORM_SRC_DIR, ''))\n const outFile = isTS ? f.file.slice(0, -3) + '.js' : f.file + '.js'\n const outPath = path.join(outDir, outFile)\n\n result.push({ srcDir: f.dir, srcFile: f.file, srcPath, outDir, outFile, outPath, isTS, isVUE })\n }\n\n return result\n}",
"function parseCodeDir (data) {\n var files = [], $dom = $(data);\n $dom.find(\"a\").each(function () {\n var url, name, timestamp, $a;\n //$a = $(this).find(\"a\");\n $a = $(this);\n url = $a.attr(\"href\");\n name = $a.html();\n timestamp = new Date($(this).find(\"td:nth-child(4)\").html());\n if (/^.+\\.js$/i.test(name)) {\n files.push({url: url, name: name, timestamp: timestamp});\n }\n });\n files.sort(function (a, b) {\n return (a.timestamp < b.timestamp ? 1 : -1); \n });\n return files;\n }",
"importFromBookmarksFile() {}",
"enterImportList(ctx) {\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
parse through file and separate contacts into individual objects | function csvParse(fileContent) {
var lines = fileContent.split('\n');
var contacts = [];
for (var i = 1; i < lines.length; i++) {
var line = lines[i].split(',');
var info = {};
info.firstName = line[0];
info.lastName = line[1];
info.numMonthsSinceContact = line[2];
info.emailAddress = line[3];
contacts.push(info);
}
return contacts;
} | [
"function saveCSVContactInPhone(mContact) {\n var contact = new mozContact();\n \n var adr = [\n {\n type: [\"home\"],\n streetAddress: mContact[24],\n locality: mContact[28],\n region: mContact[29],\n postalCode: mContact[30],\n countryName: mContact[31]\n },\n {\n type: [\"work\"],\n streetAddress: mContact[49],\n locality: mContact[54],\n region: mContact[55],\n postalCode: mContact[56],\n countryName: mContact[57]\n },\n {\n type: [\"other\"],\n streetAddress: mContact[61],\n locality: mContact[65],\n region: mContact[66],\n postalCode: mContact[67],\n countryName: mContact[68]\n }\n ];\n\n var tel = [\n {\n type: [\"primary\"],\n value: mContact[17],\n },\n {\n type: [\"home\"],\n value: mContact[18],\n },\n {\n type: [\"home 2\"],\n value: mContact[19],\n },\n {\n type: [\"mobile\"],\n value: mContact[20],\n },\n {\n type: [\"company main\"],\n value: mContact[37],\n },\n {\n type: [\"business\"],\n value: mContact[38],\n },\n {\n type: [\"business 2\"],\n value: mContact[39],\n },\n {\n type: [\"assistant\"],\n value: mContact[41],\n },\n {\n type: [\"other\"],\n value: mContact[58],\n },\n {\n type: [\"car\"],\n value: mContact[70],\n },\n {\n type: [\"radio\"],\n value: mContact[72],\n },\n {\n type: [\"tty/ttd\"],\n value: mContact[73],\n }\n ];\n\n var email = [\n {\n type: [\"email\"],\n value: mContact[14],\n },\n {\n type: [\"email 2\"],\n value: mContact[15],\n },\n {\n type: [\"email 3\"],\n value: mContact[16],\n }\n ];\n\n contact.init({\n name: mContact[0] + \" \" + mContact[2],\n honorificPrefix: mContact[3],\n givenName: mContact[0],\n additionalName: mContact[1],\n familyName: mContact[2],\n honorificSuffix: mContact[4],\n email: email,\n url: mContact[6],\n adr: adr,\n tel: tel,\n jobTitle: mContact[43],\n bday: mContact[8],\n note: mContact[13],\n anniversary: mContact[9],\n genderIdentity: mContact[7]\n });\n\n var request = navigator.mozContacts.save(contact);\n\n request.onsuccess = function() {\n alert(\"ok: \" + request);\n };\n\n request.onerror = function() {\n alert(\"failure\");\n };\n\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 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}",
"function populateContacts(contacts) {\n setContacts(contacts);\n setFilteredContacts(contacts);\n }",
"function test_read_contact() {\n const kSomeID = 905;\n let contact = new Contact();\n contact.id = kSomeID;\n\n let done = false;\n contact.dba = {\n handleSync: function(aMethod, aModel, aOptions) {\n assert_equals(aMethod, \"read\");\n assert_equals(aModel.id, kSomeID);\n\n let retrieved = new Contact(kTestFields);\n aOptions.success(retrieved);\n done = true;\n },\n };\n\n contact.fetch();\n\n mc.waitFor(function() done);\n\n // Because the contact has been updated, we have to stringify, parse\n // and then grab the attributes like this. Lame, I know.\n assert_items_equal(JSON.parse(JSON.stringify(contact)).attributes,\n kResultingFields);\n}",
"function readProiectJson() \n{\n return JSON.parse(fs.readFileSync(\"proiect.json\"))[\"DetaliiContact\"];\n}",
"function add_google_contact_create_xml_from_vcard(hcard) {\n var i;\n var full_address;\n var email;\n var tel;\n var url;\n var xml = \"\";\n\n xml += \"<atom:entry xmlns:atom='http://www.w3.org/2005/Atom' xmlns:gd='http://schemas.google.com/g/2005'>\" + \"\\n\";\n xml += \" <atom:category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/contact/2008#contact' />\" + \"\\n\";\n\n //Parse name\n xml += \" <atom:title type='text'>\" + hcard.fn + \"</atom:title> \" + \"\\n\";\n\n xml += \" <atom:content type='text'>Notes</atom:content>\" + \"\\n\";\n\n if (hcard.email) {\n for (i = 0; i < hcard.email.length; i++) {\n email = hcard.email[i];\n\n type = 'home';\n if (email.type && email.type[0] == 'work') {\n type = 'work';\n }\n\n xml += \" <gd:email rel='http://schemas.google.com/g/2005#\" + type + \"' address='\" + email.value + \"' />\" + \"\\n\";\n }\n }\n\n\n if (hcard.tel) {\n for (i = 0; i < hcard.tel.length; i++) {\n tel = hcard.tel[i];\n\n type = 'home';\n if (tel.type && tel.type[0] == 'work') {\n type = 'work';\n }\n xml += \" <gd:phoneNumber rel='http://schemas.google.com/g/2005#\" + type + \"'>\" + tel.value + \"</gd:phoneNumber>\" + \"\\n\";\n }\n }\n\n // Not yet implemented :(\n if (hcard.url) {\n for (i = 0; i < hcard.url.length; i++) {\n /*\n url = hcard.url[i];\n if ('xmpp:' == url.substring(0, 5)) {\n xml += \" <gd:im address='\" + url.substring(5) + \"' protocol='http://schemas.google.com/g/2005#GOOGLE_TALK' rel='http://schemas.google.com/g/2005#home' />\" + \"\\n\";\n }\n */\n\n\n /** @todo If I ever find the way to tell google about the right bit of api */\n /*\n if ('aim:goim?screenname=' == url.substring(0, 20)) {\n //xml += \" <gd:im address='\" + url + \"' protocol='http://schemas.google.com/g/2005#GOOGLE_TALK' rel='http://schemas.google.com/g/2005#home' />\" + \"\\n\";\n }\n if ('ymsgr:sendIM?' == url.substring(0, 13)) {\n //xml += \" <gd:im address='\" + url + \"' protocol='http://schemas.google.com/g/2005#GOOGLE_TALK' rel='http://schemas.google.com/g/2005#home' />\" + \"\\n\";\n }\n */\n }\n }\n\n if (hcard.adr) {\n for (i = 0; i < hcard.adr.length; i++) {\n adr = hcard.adr[i];\n full_address = \"\";\n if (adr[\"street-address\"]) {\n full_address += adr[\"street-address\"] + \" \";\n }\n\n if (adr[\"locality\"]) {\n full_address += adr[\"locality\"] + \" \";\n }\n\n if (adr[\"region\"]) {\n full_address += adr[\"region\"] + \" \";\n }\n\n if (adr[\"postal-code\"]) {\n full_address += adr[\"postal-code\"] + \" \";\n }\n\n if (adr[\"country-name\"]) {\n full_address += adr[\"country-name\"] + \" \";\n }\n\n if (full_address != \"\") {\n xml += \" <gd:postalAddress rel='http://schemas.google.com/g/2005#work'>\" + full_address + \"</gd:postalAddress>\" + \"\\n\";\n }\n }\n }\n\n\n xml += \"</atom:entry>\" + \"\\n\";\n\n return xml;\n}",
"fetchContactList() {\n\t\tfetchContacts({ accountIds : this.recordId })\n\t\t.then(result => {\n\t\t\tthis.contactList = result;\n\t\t\tthis.error = undefined;\n\n\t\t}) .catch(error => {\n\t\t\tthis.error = error;\n\t\t\tthis.contactList = undefined;\n\t\t});\n\t}",
"add(info) {\n this.contacts.push(new Contact(info[0], info[1], info[2], info[3]));\n }",
"function getContacts() {\n\t\t\tContactApi.getAllContacts().then(function(data, status) {\n\t\t\t\tvm.contacts = [];\n\t\t\t\tangular.forEach(data.data, function(value, key) {\n\t\t\t\t\tvm.contacts.push(value);\n\t\t\t\t});\n\t\t\t})\n\t\t}",
"parseEntries() {}",
"static searchContacts(searchStr) {\n const searchStrLowerCase = searchStr.toLowerCase();\n const searchContacts = ContactsStorage.getContacts().then((contacts) => {\n const matches = [];\n contacts.forEach((contact) => {\n const firstNameLower = contact.first_name.toLowerCase();\n const lastNameLower = contact.last_name.toLowerCase();\n const emailLower = contact.email.toLowerCase();\n if (\n firstNameLower.startsWith(searchStrLowerCase) ||\n lastNameLower.startsWith(searchStrLowerCase) ||\n contact.email.startsWith(searchStrLowerCase)\n ) {\n matches.push(contact);\n }\n });\n const contactsRow = document.querySelector(\"#contacts-row\");\n contactsRow.innerHTML = \"\";\n if (matches.length === 0) UserInterface.errorMessage(\"No contacts found\");\n matches.forEach((match) => UserInterface.addContactsToDisplay(match));\n });\n }",
"function proccessXML(zipResults){\n\n for (var key in zipResults.files) {\n\n if( zipResults.files.hasOwnProperty(key) ) {\n\n // filter for custom meta data objects\n if(key.indexOf('__mdt') !== -1){\n\n var objectName = key.substring((key.lastIndexOf('/') + 1),key.indexOf('__mdt'));\n \n if(cmToCustomObjectMapper.hasOwnProperty(objectName) === false){\n cmToCustomObjectMapper[objectName] = {};\n }\n\n cmToCustomObjectMapper[objectName].customObjectAsText = zipResults.file(key).asText();\n $log.info(cmToCustomObjectMapper[objectName].customObjectAsText = zipResults.file(key).asText());\n cmToCustomObjectMapper[objectName].qualifiedName = objectName;\n }\n\n // filter for custom metadata types\n if(key.indexOf('.md') !== -1){\n\n // get the objectName and the record instance name form the key\n var objectName = key.substring((key.lastIndexOf('/') + 1),key.indexOf('.'));\n var recordInstance = key.substring((key.indexOf('.') + 1),key.indexOf('.md'));\n\n $log.info('The record instance name', recordInstance);\n\n // allways check for the existance of the object name as key first.\n if(cmToCustomObjectMapper.hasOwnProperty(objectName) === false){\n cmToCustomObjectMapper[objectName] = {};\n }\n\n // again check for the existance of the customMetaDataAsText name as key first.\n if(cmToCustomObjectMapper[objectName].hasOwnProperty('customMetaDataAsText') === false){\n cmToCustomObjectMapper[objectName].customMetaDataAsText = {};\n }\n\n cmToCustomObjectMapper[objectName].customMetaDataAsText[recordInstance] = zipResults.file(key).asText();\n\n $log.info(cmToCustomObjectMapper[objectName].customMetaDataAsText[recordInstance]);\n }\n\n \n // output the contents of the package.xml for dev...\n if(key.indexOf('package.xml') !== -1){\n $log.info(zipResults.file(key).asText());\n }\n \n\n }\n \n }\n\n\n $log.info('object keys', Object.keys(cmToCustomObjectMapper).length );\n // if no cm types are found set the default\n if(Object.keys(cmToCustomObjectMapper).length === 0){\n setDefault();\n }\n\n // once the mapping is complete\n // use the xml parser to convert the strings to objects\n // call the merge method to complete the transistion to the required object pattern\n for(var key in cmToCustomObjectMapper){\n\n $log.info('cmToCustomObjectMapper', cmToCustomObjectMapper[key]);\n \n var xml = cmToCustomObjectMapper[key].customObjectAsText;\n parseString(xml,{ignoreAttrs: true}, function (err, result) {\n cmToCustomObjectMapper[key].customObject = result.CustomObject;\n });\n\n\n for(var rKey in cmToCustomObjectMapper[key].customMetaDataAsText){\n\n if(cmToCustomObjectMapper[key].hasOwnProperty('customMetaData') === false){\n cmToCustomObjectMapper[key].customMetaData = {};\n }\n\n var rXml = cmToCustomObjectMapper[key].customMetaDataAsText[rKey]; \n parseString(rXml,{ignoreAttrs: true, trim: true}, function (err, result) {\n\n cmToCustomObjectMapper[key].customMetaData[rKey] = result.CustomMetadata;\n \n });\n\n }\n\n \n mergeMetaDataToCustomObject(cmToCustomObjectMapper[key]);\n\n }\n\n }",
"function phoneBookToArray(item, PhoneBookItemsArray) {\n var PhoneBookItems = PhoneBookItemsArray || [];\n\n if (!item) {\n item = root;\n }\n\n if (item) {\n var itemJson;\n if (item.firstName) {\n //this means it's a contact\n itemJson = {\n \"firstName\": item.firstName,\n \"lastName\": item.lastName,\n \"phoneNumbers\": item.phoneNumbers,\n \"items\": 0\n };\n PhoneBookItems.push(itemJson);\n }\n else if (item.name) {\n //this means it's a group\n itemJson = {\n \"name\": item.name,\n \"items\": item.items.length\n };\n PhoneBookItems.push(itemJson);\n item.items.forEach(function (childItem) {\n phoneBookToArray(childItem, PhoneBookItems);\n });\n }\n return PhoneBookItems;\n }\n }",
"function getCommonEntryServices()\r\n{\r\n\tvar current = eval(\"record6\");\r\n\r\n\t//iterate through the data from the text file and store into an array\r\n\tfor(var i=0; i < record6.length; i++){\r\n\t\tcommonEntryServices[i] = current[i];\r\n\t}\r\n}//end getCommonEntryServices",
"function pickContact() {\n var contacts = new Appworks.AWContacts(\n function (contact) {\n var output = \"\";\n if(contact == null) {\n output += \"No contact found\";\n } else {\n output += contactObjectToString(contact);\n }\n out(output);\n },\n function (contactError) {\n out(contactError);\n }\n );\n\n contacts.pickContact();\n}",
"function processResults(geoNamesResponse){\n\n const cities = {capital: null, secondCity: null, thirdCity: null};\n\n for (const location of geoNamesResponse){\n\n if (location.fclName == 'city, village,...' && location.fcodeName == 'capital of a political entity'){\n cities.capital = location.name.split(' ').join('%20');\n continue;\n }\n\n if (location.fclName == 'city, village,...' && location.fcodeName != 'capital of a political entity' && cities.secondCity == null){\n cities.secondCity = location.name.split(' ').join('%20');\n continue;\n }\n \n if (location.fclName == 'city, village,...' && location.fcodeName != 'capital of a political entity'){\n cities.thirdCity = location.name.split(' ').join('%20');\n continue;\n }\n \n if (cities.capital != null && cities.secondCity != null && cities.thirdCity != null) {\n break;\n }\n\n }\n\n return cities\n\n}",
"function lookUpProfile(firstName, prop){\n// Only change code below this line\n var countFN=0;\n var countProp=0;\n //test = contacts[2].firstName\n //return test;\n \n for(var i=0; i<contacts.length; i++){\n if((contacts[i].firstName === firstName) && (contacts[i].hasOwnProperty(prop)))\n {\n return contacts[i][prop];\n }\n }\n \n for(var j=0; j<contacts.length; j++){\n if(contacts[j].firstName !== firstName){\n countFN++;\n if(countFN===contacts.length){\n return \"No such contact\";\n }\n }\n }\n \n for(var k=0; k<contacts.length; k++){\n if(contacts[k].hasOwnProperty(prop)===false){\n countProp++;\n if(countProp===contacts.length){\n return \"No such property\";\n }\n }\n }\n \n// Only change code above this line\n}",
"function extractEmails(data){\n let emails = data[Column.emails];\n emails = unaccent(emails).trim();\n emails = emails.replace(new RegExp(/[,; ]/g), \"\")\n emails = emails.split(\"\\n\");\n let emailsObj = emails.reduce((acc, email, index) => {\n if(index === 0){\n acc.primaryEmail = email;\n } \n if(!acc.emails) {\n acc.emails = [];\n }\n acc.emails.push({\n address: email,\n // primary: false,\n type: \"work\"\n });\n return acc;\n },{})\n return emailsObj;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If this.stubs == null, fetch the secrets from AWS Secrets Manager. | static async fetch(region, secrets) {
if (this.stubs) {
// find any unstubbed secrets
const unstubbedSecrets = secrets.filter(secret => {
return !Object.keys(this.stubs).includes(secret);
});
if (unstubbedSecrets.length) {
// if there are any secrets that do not have equivalent stubs
// raise an informative error.
throw {
message: `.fetch() errored. You have unstubbed secrets: [${unstubbedSecrets}]`
};
}
} else {
// Use AWS Secrets Manager if stubs haven't been set.
await this._fetchAWSSecrets(region, secrets);
}
this.fetched = true;
return;
} | [
"async prepareCredentials() {\n if (this.env[DEFAULT_ENV_SECRET]) {\n const secretmanager = new SecretManager({\n projectId: this.env.GCP_PROJECT,\n });\n const secret = await secretmanager.access(this.env[DEFAULT_ENV_SECRET]);\n if (secret) {\n const secretObj = JSON.parse(secret);\n if (secretObj.token) {\n this.oauthToken = secretObj;\n } else {\n this.serviceAccountKey = secretObj;\n }\n this.logger.info(`Get secret from SM ${this.env[DEFAULT_ENV_SECRET]}.`);\n return;\n }\n this.logger.warn(`Cannot find SM ${this.env[DEFAULT_ENV_SECRET]}.`);\n }\n // To be compatible with previous solution.\n const oauthTokenFile = this.getContentFromEnvVar(DEFAULT_ENV_OAUTH);\n if (oauthTokenFile) {\n this.oauthToken = JSON.parse(oauthTokenFile);\n }\n const serviceAccountKeyFile =\n this.getContentFromEnvVar(DEFAULT_ENV_KEYFILE);\n if (serviceAccountKeyFile) {\n this.serviceAccountKey = JSON.parse(serviceAccountKeyFile);\n }\n }",
"static _getSecretValue(client, secretId) {\n return new Promise(resolve => {\n client.getSecretValue({ SecretId: secretId }, (err, data) => {\n // If AWS returns an error, raise it\n if (err) {\n throw err;\n }\n // Grab the secret from the data returned from AWS\n const secrets = data.SecretString;\n // If AWS returns no secret for some reason, raise an error\n if (!secrets) {\n // throw new Error(\"Missing secrets\")\n throw { message: \"Missing secrets\" };\n }\n // Otherwise, set the secrets on our singleton...\n this.secrets[secretId] = JSON.parse(secrets);\n // ...and resolve the promise\n resolve();\n });\n });\n }",
"get secretKey() {\n return this._secret_key;\n }",
"getSecretValue() {\n return __awaiter(this, void 0, void 0, function* () {\n yield this.refresh();\n if (null == this.data) {\n if (null != this.exception) {\n throw this.exception;\n }\n }\n let gsv = yield this.getSecretValueInternal(this.getResult());\n // If there is no cached result, return null.\n if (null == gsv) {\n return null;\n }\n return gsv;\n });\n }",
"function Secret(props) {\n return __assign({ Type: 'AWS::SecretsManager::Secret' }, props);\n }",
"function loadClientSecrets() {\n fs.readFile('client_secret.json', (err, content) => {\n if (err) {\n console.log('Error loading client secret file: ' + err);\n return;\n }\n // Authorize a client with the loaded credentials, then call the\n // Google Sheets API.\n authorize(JSON.parse(content), getPackageData);\n });\n}",
"static getSecrets(partnerId, adminEmail, cmsPassword, otp = null){\n\t\tlet kparams = {};\n\t\tkparams.partnerId = partnerId;\n\t\tkparams.adminEmail = adminEmail;\n\t\tkparams.cmsPassword = cmsPassword;\n\t\tkparams.otp = otp;\n\t\treturn new kaltura.RequestBuilder('partner', 'getSecrets', kparams);\n\t}",
"toDescriptor() {\n return {\n apiVersion: 'v1',\n kind: 'Secret',\n metadata: this.metadata,\n data: Object.entries(this.data).reduce((hash, entry) => {\n const [ key, value ] = entry;\n if (value !== undefined) hash[key] = toBase64(value);\n return hash;\n }, {})\n };\n }",
"constructor(secretsFile) {\n let fileContents = fs.readFileSync(secretsFile);\n let secrets = JSON.parse(fileContents);\n\n // set up the URL for making requests\n let apiKey = secrets.nutrition_api_key;\n this.urlRoot = 'https://api.nal.usda.gov/ndb/search/?format=json&api_key=' + apiKey;\n }",
"config() {\n if (this.isBound(exports.names.APP_SERVICE_CONFIG)) {\n return this.get(exports.names.APP_SERVICE_CONFIG);\n }\n else {\n throw new Error('configuration object not yet loaded!');\n }\n }",
"function fetchCredentials() {\n fetch(url, {\n credentials: `include`\n })\n}",
"function isConfigSecret(k) {\n const { config } = state_1.getStore();\n const envConfigSecretKeys = config[exports.configSecretKeysEnvKey];\n if (envConfigSecretKeys) {\n const envConfigSecretArray = JSON.parse(envConfigSecretKeys);\n if (Array.isArray(envConfigSecretArray)) {\n return envConfigSecretArray.includes(k);\n }\n }\n return false;\n}",
"function getConfigValue (configName, target, done) {\n if (/^ENCRYPTED/.test(configName)) {\n const kms = new AWS.KMS()\n const encrypted = process.env[configName]\n kms.decrypt({ CiphertextBlob: new Buffer(encrypted, 'base64') }, (err, data) => {\n if (err) done(err)\n else done(null, data.Plaintext.toString('ascii'))\n })\n } else {\n done(null, process.env[configName])\n }\n}",
"function getConsumerKey(){\n prompt( 'Enter OAuth consumer key:', function( key ){\n consumerKey = key;\n getConsumerSecret();\n } );\n }",
"async ensureAppCredentials(appLookupParams) {\n var _this$credentials2, _this$credentials2$ac, _this$credentials2$ac2;\n\n const appCredentialsIndex = this.getAppCredentialsCacheIndex(appLookupParams);\n const {\n accountName\n } = appLookupParams;\n\n if (this.isPrefetched[accountName] || (_this$credentials2 = this.credentials) !== null && _this$credentials2 !== void 0 && (_this$credentials2$ac = _this$credentials2[accountName]) !== null && _this$credentials2$ac !== void 0 && (_this$credentials2$ac2 = _this$credentials2$ac.appCredentials) !== null && _this$credentials2$ac2 !== void 0 && _this$credentials2$ac2[appCredentialsIndex]) {\n return;\n }\n\n await this.refetchAppCredentials(appLookupParams);\n }",
"function fromCognitoIdentityPool(_a) {\n var _this = this;\n var accountId = _a.accountId, _b = _a.cache, cache = _b === void 0 ? Object(_localStorage__WEBPACK_IMPORTED_MODULE_4__[\"localStorage\"])() : _b, client = _a.client, customRoleArn = _a.customRoleArn, identityPoolId = _a.identityPoolId, logins = _a.logins, _c = _a.userIdentifier, userIdentifier = _c === void 0 ? !logins || Object.keys(logins).length === 0 ? \"ANONYMOUS\" : undefined : _c;\n var cacheKey = userIdentifier ? \"aws:cognito-identity-credentials:\" + identityPoolId + \":\" + userIdentifier : undefined;\n var provider = function () { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__awaiter\"])(_this, void 0, void 0, function () {\n var identityId, _a, _b, IdentityId, _c, _d, _e, _f;\n var _g;\n return Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__generator\"])(this, function (_h) {\n switch (_h.label) {\n case 0:\n _a = cacheKey;\n if (!_a) return [3 /*break*/, 2];\n return [4 /*yield*/, cache.getItem(cacheKey)];\n case 1:\n _a = (_h.sent());\n _h.label = 2;\n case 2:\n identityId = _a;\n if (!!identityId) return [3 /*break*/, 7];\n _d = (_c = client).send;\n _e = _aws_sdk_client_cognito_identity__WEBPACK_IMPORTED_MODULE_1__[\"GetIdCommand\"].bind;\n _g = {\n AccountId: accountId,\n IdentityPoolId: identityPoolId\n };\n if (!logins) return [3 /*break*/, 4];\n return [4 /*yield*/, Object(_resolveLogins__WEBPACK_IMPORTED_MODULE_5__[\"resolveLogins\"])(logins)];\n case 3:\n _f = _h.sent();\n return [3 /*break*/, 5];\n case 4:\n _f = undefined;\n _h.label = 5;\n case 5: return [4 /*yield*/, _d.apply(_c, [new (_e.apply(_aws_sdk_client_cognito_identity__WEBPACK_IMPORTED_MODULE_1__[\"GetIdCommand\"], [void 0, (_g.Logins = _f,\n _g)]))()])];\n case 6:\n _b = (_h.sent()).IdentityId, IdentityId = _b === void 0 ? throwOnMissingId() : _b;\n identityId = IdentityId;\n if (cacheKey) {\n Promise.resolve(cache.setItem(cacheKey, identityId)).catch(function () { });\n }\n _h.label = 7;\n case 7:\n provider = Object(_fromCognitoIdentity__WEBPACK_IMPORTED_MODULE_3__[\"fromCognitoIdentity\"])({\n client: client,\n customRoleArn: customRoleArn,\n logins: logins,\n identityId: identityId,\n });\n return [2 /*return*/, provider()];\n }\n });\n }); };\n return function () {\n return provider().catch(function (err) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__awaiter\"])(_this, void 0, void 0, function () {\n return Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__generator\"])(this, function (_a) {\n if (cacheKey) {\n Promise.resolve(cache.removeItem(cacheKey)).catch(function () { });\n }\n throw err;\n });\n }); });\n };\n}",
"jsonread(guid) {\n return __awaiter(this, void 0, void 0, function* () {\n const jsondata = this.jsonreadall();\n const result = jsondata.filter((el) => el.guid === guid);\n if (result.length !== 0) {\n return result[0].secret.toString();\n }\n else\n return 'The secret is already burnt!';\n });\n }",
"async getConfigProperties() {\n return super.get_auth(`/config`);\n }",
"function fetchTokens() {\n _.each(['fbtoken', 'dropboxtoken', 'livetoken'], function(key) {\n var token = localStorage.getItem(key);\n if (token != null) {\n Storage.getInstance().set(key, token);\n } \n Storage.getInstance().get(key).then(function (value) {\n console.log(key + \" \" + value);\n })\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
helpers for the path of the next / previous route | get nextPath() { return this.next && this.next.path } | [
"next(path) {\n if (path.length === 0) {\n throw new Error(\"Cannot get the next path of a root path [\".concat(path, \"], because it has no next index.\"));\n }\n\n var last = path[path.length - 1];\n return path.slice(0, -1).concat(last + 1);\n }",
"function navigateToPrevUrl() {\n if (document.referrer) {\n VeAPI.Utils.Shell.info('navigating to ' + document.referrer);\n window.location.replace(document.referrer);\n } else if (history && history.go) {\n history.go(-2);\n }\n }",
"previous(path) {\n if (path.length === 0) {\n throw new Error(\"Cannot get the previous path of a root path [\".concat(path, \"], because it has no previous index.\"));\n }\n\n var last = path[path.length - 1];\n\n if (last <= 0) {\n throw new Error(\"Cannot get the previous path of a first child path [\".concat(path, \"] because it would result in a negative index.\"));\n }\n\n return path.slice(0, -1).concat(last - 1);\n }",
"getNextPrevTrack(index, direction){\n\t\tvar tracks = this.props.tracks;\n\t\tswitch (direction) {\n\t\t\tcase 'next': return tracks[(index + 1) % tracks.length];\n\t\t\tcase 'prev': return tracks[(index == 0) && tracks.length - 1 || index - 1];\n\t\t \tdefault: return tracks[index];\n\t\t}\n\t}",
"nextPage(){\n BusinessActions.nextPage();\n }",
"function _buildPreviousLink(options, tp){\n\t\tif (options.cp == 1) return '';\n\t\tvar optionsPaging = {};\n\t\tdicUtilObj.deepCopyProperty(options, optionsPaging);\n\t\toptionsPaging.cp = parseInt(optionsPaging.cp) - 1;\n\t\tconsole.log(options);\n return '<a id=\"dic-edi-mailbox-previous\" href=\"'+dicUtilUrl.buildUrlObjQuery(null, optionsPaging)+'\" class=\"navig-prev\" aria-label=\"Previous\">' +\n\t\t\t\t\t'<span class=\"content\" style=\"right: -14px;\">' +\n\t\t\t\t\t'<b>' +\n\t\t\t\t\t\t'Prev: '+ (parseInt(options.ps, 10) * (optionsPaging.cp - 1) + 1) + ' - ' + (parseInt(options.ps, 10) * (optionsPaging.cp)) + \n\t\t\t\t\t '</b>'+\n\t\t\t\t\t'<span/>'+\n\t\t\t\n\t\t\t\t\t'</span>' +\n\t\t\t\t'</a>';\n\t\t\n\t\t\n\t}",
"function getLastPath() {\n if (url.path.components.length > 0) {\n return url.path.components[url.path.components.length - 1];\n }\n }",
"function setNavigationEndpoints () {\n const previous = document.querySelector('.navbar__link--previous')\n const next = document.querySelector('.navbar__link--next')\n const resume = document.querySelector('.resume__action')\n const go = {}\n\n if (next !== null) {\n go.next = next.href\n } else if (resume && resume.href) {\n go.next = resume.href\n } else {\n go.next = '/introduction/'\n }\n\n if (previous !== null) {\n go.previous = previous.href\n } else if (resume && resume.href) {\n go.previous = resume.href\n } else {\n go.previous = '/introduction/'\n }\n\n go.home = () => {\n window.location.href = '/'\n }\n go.search = () => document.querySelector('.search__input').focus()\n\n return go\n}",
"goToPreviousSlide() {\n this._goToSlide(this.previousSlideIndex, false, false);\n }",
"function _buildNextLink(options, tp){\n\t\t\t\n\t\tif (options.cp == tp) return '';\n\t\tvar optionsPaging = {};\n\t\tdicUtilObj.deepCopyProperty(options, optionsPaging);\n\t\t\n\t\toptionsPaging.cp = parseInt(optionsPaging.cp) + 1;\n\t\treturn '<a id=\"dic-edi-mailbox-next\" href=\"'+dicUtilUrl.buildUrlObjQuery(null, optionsPaging)+'\" aria-label=\"Next\" class=\"navig-next\">'+\n\t \t\t\t'<span class=\"content\" style=\"right: -77px;\">'+\n\t \t\t\t'<b>Next: '+ (parseInt(options.ps, 10) * (optionsPaging.cp - 1)+ 1) + ' - ' + (parseInt(options.ps, 10) * (optionsPaging.cp)) +\n\t \t\t\t '</b>'+\n\t \t\t\t'<span></span>'+\n\t \t\t\t'</span>'+\n\t \t\t'</a>';\n\t\t\n\n\t}",
"function handleNextBtn() {\n // Move the pointer back\n util.movePtr(\"next\");\n\n // Extract the index and url at ptr using object deconstruction\n const { idx, url } = ptr.value;\n\n // Update the index\n util.updateIdx(idx);\n\n // Update the carousel's image\n util.updateImage(url);\n }",
"function returnToPath(req, res) {\n let returnTo = req.body.returnTo;\n // leading slash followed by any non-slash character\n const localPathRegex = new RegExp('^/[^/]');\n\n if (typeof returnTo != 'string' || !localPathRegex.test(returnTo))\n returnTo = '/';\n res.redirect(returnTo);\n}",
"prev() {\n\t\t\tif (this.currPage > 1) {\n\t\t\t\tthis.currPage--;\n\t\t\t\tthis._loadPage();\n\t\t\t}\n\t\t}",
"function onPrevButtonClick() {\n\t\tgotoPrevSlide()\n\t}",
"previousPage(currentPage) {\n if (currentPage > 1) {\n this.getArticles(currentPage-1);\n }\n }",
"function build_prev_nav(item) {\n\t\t\tif (item.prev_index >= 0) {\n\t\t\t\treturn nav_link(options.prev_link_class, item.prev_href, options.prev_link_text);\n\t\t\t} else {\n\t\t\t\treturn '';\n\t\t\t}\n\t\t}",
"function goToPreviousImage() {\n clearInterval(automaticSlideInstance);\n var oldIndex = currentIndex;\n var oldDot = carouselNavigationContainer[oldIndex];\n\n currentIndex = currentIndex === 0 ? numberOfImages - 1 : currentIndex - 1;\n var currentDot = carouselNavigationContainer[currentIndex];\n\n changeNavigationDot(oldDot, currentDot);\n animateSlide(oldIndex, currentIndex);\n\n setTimeout(automaticSlide, 0);\n}",
"hasPrevious() {\n return this.page > 1;\n }",
"function adelante() {\r\n history.forward();\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Halt a running instance of a monitor thread | function stop() {
if (monitorThread) {
clearInterval(monitorThread);
monitorThread = null;
} else {
console.err("ERR: Attempted to halt monitor thread but no instance existed.")
}
} | [
"function stop_install_monitor(div_id){\n install.updater.stop();\n}",
"function maybeHalt() {\n taskEnding();\n maybeExit();\n return null;\n}",
"stop() {\n if (!this.stopped) {\n for (let timeout of this.timeouts) {\n clearTimeout(timeout);\n }\n clearTimeout(this.mainLoopTimeout);\n this.stopped = true;\n }\n }",
"stopTale(tale) {\n const self = this;\n return new Promise((resolve, reject) => {\n if (tale.instance) {\n if (tale.instance.status === 2) {\n // TODO: Previous instance creation failed, proceed with caution\n } else if (tale.instance.status === 0) {\n // TODO: Instance is still launching... wait and then shut down\n }\n \n // TODO: Create Job to destroy/cleanup instance\n self.set('deletingInstance', true);\n const model = tale.instance;\n model.destroyRecord({\n reload: true,\n backgroundReload: false\n }).then((response) => {\n // TODO replace this workaround for deletion with something more robust\n self.get('store').unloadRecord(model);\n tale.set('instance', null);\n resolve(response);\n });\n \n } \n });\n }",
"_terminate() {\n console.log(\"terminate\");\n /*if (this.state !== or === ? GameStates.Terminating) {\n return; //error\n }*/\n\n this.state = GameStates.Terminating;\n clearTimeout(this.tick);\n this._clearTurn();\n this.destroy();\n }",
"function stop (cb) {\n got.post(killURL, { timeout: 1000, retries: 0 }, (err) => {\n console.log(err ? ' Not running' : ' Stopped daemon')\n\n debug(`removing ${startupFile}`)\n startup.remove('hotel')\n\n cb()\n })\n}",
"stopExecution() {\n this.worker_.postMessage({'command': JobCommand.STOP});\n }",
"function stop_tcpdump(){\n\tobject.AGNetworkTookitTcpdump(stop_succeed_back, stop_error_back, 1, null);\n}",
"stop() {\n this.target = undefined;\n // @ts-expect-error\n const pathfinder = this.bot.pathfinder;\n pathfinder.setGoal(null);\n // @ts-expect-error\n this.bot.emit('stoppedAttacking');\n }",
"abort() { \n this.reset = true;\n }",
"function stop_monitoring()\n {\n browser.idle.onStateChanged.removeListener(on_idle_state_change);\n }",
"function interruptAs(fiberId, __trace) {\n return (0, _core3.haltWith)(trace => Cause.traced(Cause.interrupt(fiberId), trace()), __trace);\n}",
"handleRunStopped () {\n const priv = privs.get(this)\n if (priv.state === State.Done) privm.wrapup.call(this)\n }",
"unsuspend(stop_reason=false){\n if (this.status_code == \"suspended\"){\n if(stop_reason){\n this.stop_for_reason(\"interruped\", stop_reason)\n this.set_up_next_do(0)\n }\n else {\n this.set_status_code(\"running\")\n this.set_up_next_do(1)\n }\n }\n }",
"function DriveStop() {\n wheels.both.stop();\n driveCmds = {};\n cmdCount = 0;\n}",
"_terminate() {\n if (this._instance) {\n this._instance.close();\n this._instance = null;\n this._stopListeningForTermination();\n this._options.onStop(this);\n }\n\n process.exit();\n }",
"abortSession() {\n if (this.isRunning) {\n this.abort = true;\n }\n }",
"stopRobotSimulation() {\n\t\tthis.status = false;\n\t}",
"stop() {\n dbg.log0('Stopping hosted_agents');\n this._started = false;\n //stop all running agents\n _.each(this._started_agents, (agent, node_name) => this._stop_agent(node_name));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creditCARow calls creditCARow in index.aspx.cs clears any error message, displays Crediting message and disables buttons | function creditCARow(row){
if (formatAmount(document.getElementById('amtCreditCA_'+row),'CA')){
CCT.index.creditCARow(row,gOldCACreditAmt[row],document.getElementById('emailCreditCA_'+row).value
,document.getElementById('notesCreditCA_'+row).value,creditCARowCallback);
document.getElementById("mCreditCATableDiv").style.display = 'none';
errorMessage("Crediting ...","CreditCA","Message");
document.mForm.mCreditButton.disabled = true;
}
} | [
"function creditCARowCallback(res){ \n document.getElementById(\"mCreditCATableDiv\").style.display = '';\n document.mForm.mCreditButton.disabled = false; \n \n if (!res.error && !res.value.error){ \n if (res.value.message == \"REFRESH\"){\n reloadSession();\n }\n else{ \n document.getElementById('mCreditCATableDiv').innerHTML = res.value.caHTML;\n errorMessage(res.value.message,\"CreditCA\",\"Message\");\n gOldCACreditAmt = res.value.caAmt;\n gCACreditEmailUpdated = res.value.caEmail;\n //get new files\n getFiles(false,\"CACredit\");\n //open file\n if (res.value.filePath != null && res.value.filePath != \"\"){\n printPage(\"F\",res.value.filePath);\n }\n }\n }\n else{\n document.getElementById('mCreditCATableDiv').innerHTML = \"\";\n errorMessage(\"Error Crediting Transaction\",\"CreditCA\",\"Error\");\n }\n }",
"function creditUSRowCallback(res){ \n document.getElementById(\"mCreditUSTableDiv\").style.display = '';\n document.mForm.mCreditButton.disabled = false;\n \n if (!res.error && !res.value.error){ \n if (res.value.message == \"REFRESH\"){\n reloadSession();\n }\n else{ \n document.getElementById('mCreditUSTableDiv').innerHTML = res.value.usHTML;\n errorMessage(res.value.message,\"CreditUS\",\"Message\");\n gOldUSCreditAmt = res.value.usAmt;\n gUSCreditEmailUpdated = res.value.usEmail;\n }\n }\n else{\n document.getElementById('mCreditUSTableDiv').innerHTML = \"\";\n errorMessage(\"Error Crediting Transaction\",\"CreditUS\",\"Error\");\n } \n }",
"function creditUSRow(row){ \n if (formatAmount(document.getElementById('amtCreditUS_'+row),'US')){\n CCT.index.creditUSRow(row,gOldUSCreditAmt[row],document.getElementById('emailCreditUS_'+row).value\n ,document.getElementById('notesCreditUS_'+row).value,creditUSRowCallback);\n \n document.getElementById(\"mCreditUSTableDiv\").style.display = 'none';\n errorMessage(\"Crediting ...\",\"CreditUS\",\"Message\");\n document.mForm.mCreditButton.disabled = true; \n }\n }",
"function creditSearchCallback(res){\n document.getElementById('mCreditLoadingDiv').style.display = 'none';\n document.getElementById('creditTabSet').style.display = '';\n document.mForm.mCreditButton.disabled = false;\n \n if (!res.error && !res.value.error){ \n if (res.value.message == \"REFRESH\"){\n reloadSession();\n }\n else{ \n document.getElementById('mCreditUSTableDiv').innerHTML = res.value.usHTML;\n document.getElementById('mCreditCATableDiv').innerHTML = res.value.caHTML;\n gOldUSCreditAmt = res.value.usAmt;\n gOldCACreditAmt = res.value.caAmt; \n gUSCreditEmailUpdated = res.value.usEmail;\n gCACreditEmailUpdated = res.value.caEmail;\n errorMessage(\" \",\"CreditUS\",\"\");\n //clicks the ca tab if no us results, not the best way of ref which tabset to click\n //but the code in ws-lib doesn't seem to ref them anyother way\n if (gUSCreditEmailUpdated.length == 0) { clickTab(2,1); } \n else { clickTab(2,0); } \n }\n }\n else{\n document.getElementById('mCreditUSTableDiv').innerHTML = '';\n document.getElementById('mCreditCATableDiv').innerHTML = '';\n errorMessage(\"Error Loading US Credit Results\",\"CreditUS\",\"Error\");\n errorMessage(\"Error Loading Canada Credit Results\",\"CreditCA\",\"Error\");\n } \n }",
"function buyCard(){\n \n //receivers email validation\n var emailRegex = /^[a-zA-Z0-9.!#$%&'+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)$/;\n if(!emailRegex.test(receiver.value)){\n receiver.style.background = \"red\";\n receiver.focus();\n return false;\n }\n else\n {\n receiver.style.background = \"white\"; \n }\n \n //Sender's email validation\n var emailRegex2 = /^[a-zA-Z0-9.!#$%&'+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)$/;\n if(!emailRegex2.test(sender.value)){\n sender.style.background = \"red\";\n sender.focus();\n return false;\n }\n else\n {\n sender.style.background = \"white\"; \n }\n \n //Thanks message after ordering gift card\n submitForm.style.display = \"none\";\n hidden.style.display = \"block\";\n hidden.style.fontSize= \"36px\";\n hidden.style.fontStyle = \"bold\";\n return false;//prevent form to submit untill its not validated\n }",
"function getCreditCards(){\n\tif(paymentScreenProps.windowType==\"Modal\" && !isUserLoggedIn()){\n\t\treturn false;\n\t}\n\ttogglePaymentAndIFrameBlock(false);\n\t\n\t\t$('#cancelButton').attr(\"disabled\", true);\n\t\t$.ajax({\n \t\t\ttype: \"POST\",\n \t\t\turl: \"/listCreditCards.do?operation=retrieveCreditCardList\",\n \t\t\tdata: \"displayRadioButtons=\"+paymentScreenProps.displayRadioButtons,\n \t\t\tsuccess: \n\t\t\t\tfunction(data){\t\t\n\t\t\t\t\t\t$('#ccRows').html(data);\n\t\t\t\t\t\t$(\"#profileRow1\").attr(\"checked\", \"checked\");\n\t\t\t\t\t $(\"#profileRow1\").click();\n\t\t\t\t\t\tinit();\t\n\t\t\t\t\t}\n\t\t});\t\n\t\t//highlightExpiredCards();\t\t\t\n}",
"function handleBpBillerCorpCredsOnSuccess(isMsg) {\n\t/* show the div */ \n $('#billerFormData').show();\n $('#addOrEditSaveBtnDiv').show();\n $('#addBil_billerType').show();\n $('#addBil_postingCategoryLanguage').show();\n $('#addBil_instruction2').show();\n $('#addBil_rightSection').show(); \n \n printBillerData();\n createTableNew();\n \n hideShowCreateAccountForGuestUser();\n if (isMsg) {\n \tshowGeneralErrorMsg(msgType);\n }\n}",
"function creditClear(){\n CCT.index.creditClear();\n \n document.mForm.mCreditTransID.value = \"\";\n document.mForm.mCreditCustNum.value = \"\";\n document.mForm.mCreditCustName.value = \"\";\n document.mForm.mCreditCSNum.value = \"\";\n document.mForm.mCreditODOC.value = \"\";\n document.mForm.mCreditOrderNum.value = \"\";\n document.mForm.mCreditDCT.value = \"\";\n document.mForm.mCreditDOC.value = \"\";\n document.mForm.mCreditKCO.value = \"\";\n document.mForm.mCreditCCSufix.value = \"\";\n document.mForm.mCreditSentFrom.value = \"\";\n document.mForm.mCreditSentTo.value = \"\";\n document.mForm.mCreditTypeSelect.value = \"\"; \n }",
"function sortCreditCACallBack(res){ \n document.getElementById(\"mCreditCATableDiv\").style.display = '';\n document.mForm.mCreditButton.disabled = false; \n \n if (!res.error && !res.value.error){ \n if (res.value.message == \"REFRESH\"){\n reloadSession();\n }\n else{ \n document.getElementById('mCreditCATableDiv').innerHTML = res.value.caHTML;\n errorMessage(\" \",\"CreditCA\",\"\");\n gOldCACreditAmt = res.value.caAmt;\n gCACreditEmailUpdated = res.value.caEmail;\n \n gCACreditAmountUpdated = new Array();\n gCACreditNotesUpdated = new Array();\n }\n }\n else{\n document.getElementById('mCreditCATableDiv').innerHTML = \"\";\n errorMessage(\"Error Sorting Transactions\",\"CreditCA\",\"Error\");\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 cancelBtnOfCreateAccCheckout(frmDiv) {\n\t/* To be called from fieldValidator.js*/\n\t$('#emailIdPromoCode').val($(\"#emailIdChkOut\").val());\n\t$('#confrmEmailIdPromoCode').val($(\"#confrmEmailIdChkOut\").val());\n\t$('#passwordPromoCode').val($(\"#passwordChkOut\").val());\n\t$('#mobileNoPromoCode').val($(\"#mobileNoChkOut\").val());\n\t$('#zipCodePromoCode').val($(\"#zipCodeChkOut\").val());\n\t$('#promoCodeDiscount1').val($(\"#promoCodeDiscount2\").val());\n\tclearFormField(\"createAccountBoxChkOut\");\n\t$(\"#passwordChkOut\").val(\"\");\n\tvar count = 1;\n\tvar $inputFields = $('#'+ frmDiv + ' :input');\n\t$inputFields.each(function() {\n\t\tif($(this).hasClass('error_red_border')) {\n\t\t\t$(this).removeClass('error_red_border');\n\t\t\t$('#moberrorPromoCode'+ count).hide();\n\t\t\t$('#errorPromoCode'+ (count)).hide();\n\t\t} \n\t\tcount++;\n\t});\n}",
"function sortCreditUSCallBack(res){ \n document.getElementById(\"mCreditUSTableDiv\").style.display = '';\n document.mForm.mCreditButton.disabled = false; \n \n if (!res.error && !res.value.error){ \n if (res.value.message == \"REFRESH\"){\n reloadSession();\n }\n else{ \n document.getElementById('mCreditUSTableDiv').innerHTML = res.value.usHTML;\n errorMessage(\" \",\"CreditUS\",\"\");\n gOldUSCreditAmt = res.value.usAmt;\n gUSCreditEmailUpdated = res.value.usEmail;\n \n gUSCreditAmountUpdated = new Array();\n gUSCreditNotesUpdated = new Array();\n\n }\n }\n else{\n document.getElementById('mCreditUSTableDiv').innerHTML = \"\";\n errorMessage(\"Error Sorting Transactions\",\"CreditUS\",\"Error\");\n } \n }",
"function handleBpSaveBillerCorpAcctCredsOnSuccess() {\n\t/* Storing the biller boxes data into tempBillArray so that is can be populated later after BP_ACCOUNT_LITE API call */\n\tsetTempBillArray(); \n\tif (isGuestMsg) {\n\t\tgettingInfoOfBillerAcc();\n\t\t$('#myAccountBox').show();\n $('#guestUserMyAccountBox').hide();\n isGuestMsg = false;\n\t\tshowGeneralSuccessMsg(messages['addEditBiller.GuestUserBillerSaved'],\n messages['inLine.message.successMessage']);\n } else {\n \t/* Checking for scheduled biller edited and updated credentials it will raise pop up */\n \tif(bp_save_biller_corp_acct_creds_obj.scheduled === true){\n \t\tsuccessfulCredUpdatePopup();\t\n \t\tgettingInfoOfBillerAcc();\n \t} else {\n \t\tgettingInfoOfBillerAcc();\n \t\tshowGeneralSuccessMsg(messages['addEditBiller.alert.billerSaved'],\n \t\t messages['inLine.message.successMessage']);\n \t}\n }\n}",
"function validateDebitCard(self, type, charCode) {\n if (!(typeof charCode === 'boolean' || (charCode >= 48 && charCode <= 57))) {\n return false;\n } else if (self.value.length === 6 || !charCode) {\n var cardtype = document.getElementById('cardtype_dc').value;\n if (!charCode) {\n if (cardtype === '') {\n return false;\n } else if (inValidType(self.value.length, type.toLowerCase())) {\n return false;\n }\n }\n document.getElementById('ccnum_dc').style.border = '1px solid #337ab7';\n document.getElementById('error-ccnum_dc').style.display = 'none';\n document.getElementById('amex_dc').style.display = 'none';\n document.getElementById('visa_dc').style.display = 'none';\n document.getElementById('master_dc').style.display = 'none';\n\n var data = {\n \"bin\" : self.value.substring(0,6),\n \"errorBlock\" : document.getElementById('error-ccnum_dc'),\n \"ccnum\" : document.getElementById('ccnum_dc'),\n \"ccvv\" : document.getElementById('ccvv_dc'),\n \"btn\" : document.getElementById('checkoutprocess_dc'),\n \"amex\" : document.getElementById('amex_dc'),\n \"visa\" : document.getElementById('visa_dc'),\n \"master\" : document.getElementById('master_dc'),\n \"processing\" : document.getElementById('processing_dc'),\n \"cardtype\" : document.getElementById('cardtype_dc'),\n \"errorMsg\" : 'Invalid debit card type!'\n };\n processAjaxRequest(data, type);\n\n return true;\n\n } else {\n if (self.value.length < 6) {\n document.getElementById('ccnum_dc').style.border = '1px solid #337ab7';\n document.getElementById('error-ccnum_dc').style.display = 'none';\n document.getElementById('amex_dc').style.display = 'none';\n document.getElementById('visa_dc').style.display = 'none';\n document.getElementById('master_dc').style.display = 'none';\n }\n\n return false;\n }\n}",
"function thankYou() {\r\n\tyes.style.display = \"none\";\r\n\tno.style.display = \"none\";\r\n\tfeedback.style.display = \"none\";\r\n\tfadeSubmit();\r\n\tsubmit_button.style.cursor = \"not-allowed\";\r\n\tsubmit_clickable = false;\r\n\tthanks_text.innerHTML = \"Thank you for your feedback!\";\r\n\t//makeThanksText();\r\n}",
"migrateCreditCards() {}",
"function liveCreditCardError(){\n //declare then modify creditError's properties (I think they're called properties)\n let creditError = document.createElement('p');\n creditError.style.color = 'red';\n creditError.style.fontSize = 'small';\n // attaching the credit error message to the parent of ccNum\n ccNum.parentNode.appendChild(creditError);\n // hide the message at first\n creditError.style.display = 'none';\n // listener based on focusout added to ccNum for the live message\n ccNum.addEventListener('focusout', (e) => {\n //store the length of the ccNum value in cardN\n // if credit card number is less than 13 but greater than 8 show error message\n let cardN = ccNum.value.length;\n if(cardN <= 13 && cardN >= 8){\n creditError.textContent = 'Please enter a number that is between 13 and 16 digits long'; \n creditError.style.display = '';\n } else if(cardN == 0){\n creditError.textContent = 'Credit Card field is empty';\n creditError.style.display = '';\n } else {\n //hide the message otherwise\n creditError.style.display = 'none';\n }\n })\n}",
"function sortCreditCA(col){ \n CCT.index.sortCreditCA(col,gCACreditEmailUpdated,gCACreditAmountUpdated,gCACreditNotesUpdated,sortCreditCACallBack);\n\n document.getElementById(\"mCreditCATableDiv\").style.display = 'none';\n errorMessage(\"Sorting ...\",\"CreditCA\",\"Message\");\n document.mForm.mCreditButton.disabled = true; \n }",
"function returnCredit() {\n console.clear()/**/\n /*If statement which displays users current credit and informs that they must have available funds in order to recieve a refund. */\n if(credit <= 0) {\n console.log('Your balace is '.red.bold + '£' + credit + ', you must have credit to refund.'.red.bold);\n console.log(space);\n console.log('Press Enter to return to the Main Menu'.red.bold);\n readline.question();\n mainMenu();\n }\n /*Else the user is presented with their current credit, and asked if they would like a refund. Once again this is handled with a switch statement*/\n else {\n console.log('Your current balance is: '.blue.bold + '£' + credit);\n console.log(space);\n console.log('Would you like to return your credit? '.blue.bold + '(Y/N) ');\n console.log(space);\n var choice = readline.question('Selection: '.blue.bold);\n switch (choice.toUpperCase()) {\n /*if the user enters Y or y users are thanked and informed of the amount returned. The balnce of global credit is restarted and set to 0. Users are presented\n with this information and asked if they would like to exit the vending machine.*/\n case \"Y\":\n console.clear();\n console.log('Thank you, '.blue.bold + '£' + credit + ' has been returned.'.blue.bold);\n credit = 0;\n console.log(space);\n console.log('Current balance is now '.blue.bold + '£' + credit);\n console.log(space);\n console.log('Would you like to exit the Vending Machine? '.blue.bold + '(Y/N) ');\n console.log(space);\n var choices = readline.question('Selection: '.blue.bold);\n /* Additonal switch statment asking users if they would like to exit the vending machine. If Y or y is entered users are thanked for their custom\n and the vending machine ends */\n switch (choices.toUpperCase()) {\n case \"Y\":\n console.clear();\n console.log(' '.white.bold.underline);\n console.log(' ');\n console.log('Thank you for your custom, come back soon!'.bold.blue);\n console.log(' '.white.bold.underline);\n console.log(space);\n return;\n case \"N\": mainMenu(); break;\n default:\n /*if any other input is given, the user is returned to the main menu*/\n mainMenu();\n break;\n }\n case \"N\": mainMenu(); break;\n default:\n /*if any other input is given, the user is returned to the main menu*/\n mainMenu();\n break;\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decodes the given IndexedDbcompatible string form of a resource path into a ResourcePath instance. Note that this method is not suitable for use with decoding resource names from the server; those are One Platform format strings. | function decode(path) {
// Event the empty path must encode as a path of at least length 2. A path
// with exactly 2 must be the empty path.
var length = path.length;
assert(length >= 2, 'Invalid path ' + path);
if (length === 2) {
assert(path.charAt(0) === escapeChar && path.charAt(1) === encodedSeparatorChar, 'Non-empty path ' + path + ' had length 2');
return ResourcePath.EMPTY_PATH;
}
// Escape characters cannot exist past the second-to-last position in the
// source value.
var lastReasonableEscapeIndex = length - 2;
var segments = [];
var segmentBuilder = '';
for (var start = 0; start < length;) {
// The last two characters of a valid encoded path must be a separator, so
// there must be an end to this segment.
var end = path.indexOf(escapeChar, start);
if (end < 0 || end > lastReasonableEscapeIndex) {
fail('Invalid encoded resource path: "' + path + '"');
}
var next = path.charAt(end + 1);
switch (next) {
case encodedSeparatorChar:
var currentPiece = path.substring(start, end);
var segment = void 0;
if (segmentBuilder.length === 0) {
// Avoid copying for the common case of a segment that excludes \0
// and \001
segment = currentPiece;
}
else {
segmentBuilder += currentPiece;
segment = segmentBuilder;
segmentBuilder = '';
}
segments.push(segment);
break;
case encodedNul:
segmentBuilder += path.substring(start, end);
segmentBuilder += '\0';
break;
case encodedEscape:
// The escape character can be used in the output to encode itself.
segmentBuilder += path.substring(start, end + 1);
break;
default:
fail('Invalid encoded resource path: "' + path + '"');
}
start = end + 2;
}
return new ResourcePath(segments);
} | [
"function Resource(wfsUrl) {\n this.uri = URI(wfsUrl);\n this.fsid = this.uri.host();\n this.wfs = new WebidaFS(this.fsid);\n this.pathname = decodeURI(this.uri.pathname());\n this.basename = Path.basename(this.pathname);\n this.localPath = getPathFromUrl(wfsUrl);\n}",
"function resourceToInstanceAndPath(resource) {\n let resourceRegex = `projects/([^/]+)/instances/([^/]+)/refs(/.+)?`;\n let match = resource.match(new RegExp(resourceRegex));\n if (!match) {\n throw new Error(`Unexpected resource string for Firebase Realtime Database event: ${resource}. ` +\n 'Expected string in the format of \"projects/_/instances/{firebaseioSubdomain}/refs/{ref=**}\"');\n }\n let [, project, dbInstanceName, path] = match;\n if (project !== '_') {\n throw new Error(`Expect project to be '_' in a Firebase Realtime Database event`);\n }\n let dbInstance = 'https://' + dbInstanceName + '.firebaseio.com';\n return [dbInstance, path];\n}",
"function parsePath(str) {\n var cutpos = str && str.length? str.lastIndexOf('/'):0;\n // console.log('parsePath.cutpos', cutpos)\n //-- verify this switch! (Orion)\n var songpath = '';\n if (cutpos && cutpos !== -1){\n songpath = str.slice(0,cutpos);\n }\n return songpath;\n}",
"function doubleBackwardSlashes(path) {\r\n\treturn path.replace(/\\\\/g, \"\\\\\\\\\");\r\n}",
"function internal_getContainerPath(resourcePath) {\n const resourcePathWithoutTrailingSlash = resourcePath.substring(resourcePath.length - 1) === \"/\"\n ? resourcePath.substring(0, resourcePath.length - 1)\n : resourcePath;\n const containerPath = resourcePath.substring(0, resourcePathWithoutTrailingSlash.lastIndexOf(\"/\")) + \"/\";\n return containerPath;\n}",
"function decode (string) {\n\n var body = Buffer.from(string, 'base64').toString('utf8')\n return JSON.parse(body)\n}",
"function Resource(uri) {\n this._init(uri);\n}",
"stringOrObject( obj, objPath/*, rez */) {\n if (_.isString(obj)) { return obj; } else { return LO.get(obj, objPath); }\n }",
"function fileURLToPath(path) {\n Check.defined('path', path);\n\n if (typeof path === 'string') {\n path = new URL(path);\n }\n\n if (path.protocol !== 'file:') {\n throw new RuntimeError('Expected path.protocol to start with file:');\n }\n return isWindows ? getPathFromURLWin32(path) : getPathFromURLPosix(path);\n}",
"function parseUri(resourceUri) {\n var matchInd, matches, containerUrl;\n if (resourceUri.indexOf('http') !== 0) { // relative uri case\n if (resourceUri.indexOf('/dc/') !== 0) { // assuming modelType and optional query case\n resourceUri = '/dc/type/' + resourceUri;\n }\n matches = /^\\/+dc\\/+(type|h)\\/+([^\\/\\?]+)\\/*([^\\?]+)?\\??(.*)$/g.exec(resourceUri);\n containerUrl = dcConf.containerUrl;\n matchInd = 0;\n } else {\n matches = /^(http[s]?):\\/\\/+([^\\/]+)\\/+dc\\/+(type|h)\\/+([^\\/\\?]+)\\/*([^\\?]+)?\\??(.*)$/g.exec(resourceUri);\n containerUrl = matches[1] + '://' + matches[2];\n matchInd = 2;\n }\n /*var pInd = resourceUri.indexOf('/dc/type/');\n var containerUrl = resourceUri.substring(0, pInd);\n var mInd = pInd + '/dc/type/'.length;\n var nextSlashInd = resourceUri.indexOf('/', mInd);\n var encModelType = resourceUri.substring(mInd, (nextSlashInd !== -1) ? nextSlashInd : resourceUri.length);\n var encId = resourceUri.substring(resourceUri.indexOf('/', mInd) + 1);\n if (containerUrl.length === 0) {\n containerUrl = dcConf.containerUrl;\n resourceUri = containerUrl + resourceUri;\n }\n return {\n containerUrl : containerUrl,\n modelType : decodeURIComponent(encModelType),\n id : decodeURI(encId),\n uri : resourceUri\n };*/\n \n var isHistory = matches[matchInd + 1] // else is a find\n && matches[matchInd + 1] === 'h';\n var encodedModelType = matches[matchInd + 2];\n var modelType = decodeURIComponent(encodedModelType); // required ; assuming that never contains %\n // NB. modelType should be encoded as URIs, BUT must be decoded before used as GET URI\n // because swagger.js re-encodes\n var encodedId = matches[matchInd + 3];\n var query = matches[matchInd + 4]; // no decoding, else would need to be first split along & and =\n var version = null;\n if (isHistory) {\n try {\n var versionSlashIndex = encodedId.lastIndexOf('/');\n version = parseInt(encodedId.substring(versionSlashIndex + 1));\n if (encodedId) {\n encodedId = encodedId.substring(0, versionSlashIndex);\n }\n } catch (e) {}\n }\n\n var uri = containerUrl + '/dc/type/' + encodedModelType;\n \n var id = null;\n if (encodedId) {\n id = decodeURIComponent(encodedId); // and not decodeURI else an URI won't be decoded at all\n // ex. \"https%3A%2F%2Fwww.10thingstosee.com%2Fmedia%2Fphotos%2Ffrance-778943_HjRL4GM.jpg\n uri += '/' + encodedId;\n }\n if (!query) {\n query = null;\n }\n if (query !== null) {\n uri += '?' + query;\n }\n return {\n containerUrl : containerUrl,\n modelType : modelType, // decoded\n id : id,\n encodedId : encodedId,\n version : version, // only if isHistory\n query : query, // encoded\n uri : uri // resourceUri\n };\n }",
"function decodeUtf8ToString(bytes) {\n // XXX do documentation\n return encodeCodePointsToString(decodeUtf8ToCodePoints(bytes));\n }",
"function fromDotSeparatedString(path) {\n var found = path.search(RESERVED);\n if (found >= 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not contain \" +\n \"'~', '*', '/', '[', or ']'\");\n }\n try {\n return new (FieldPath$1.bind.apply(FieldPath$1, [void 0].concat(path.split('.'))))();\n }\n catch (e) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not be empty, \" +\n \"begin with '.', end with '.', or contain '..'\");\n }\n}",
"function resolve (cid, path, callback) {\n let value\n\n doUntil(\n (cb) => {\n self.block.get(cid, (err, block) => {\n if (err) return cb(err)\n\n const r = self._ipld.resolvers[cid.codec]\n\n if (!r) {\n return cb(new Error(`No resolver found for codec \"${cid.codec}\"`))\n }\n\n r.resolver.resolve(block.data, path, (err, result) => {\n if (err) return cb(err)\n value = result.value\n path = result.remainderPath\n cb()\n })\n })\n },\n () => {\n const endReached = !path || path === '/'\n\n if (endReached) {\n return true\n }\n\n if (value) {\n cid = new CID(value['/'])\n }\n\n return false\n },\n (err) => {\n if (err) return callback(err)\n if (value && value['/']) return callback(null, new CID(value['/']))\n callback()\n }\n )\n }",
"function decode(queryStr, shouldTypecast) {\n\tvar queryArr = (queryStr || '').replace('?', '').split('&'),\n\t n = queryArr.length,\n\t obj = {},\n\t item, val;\n\twhile (n--) {\n\t item = queryArr[n].split('=');\n\t val = shouldTypecast === false? item[1] : typecast(item[1]);\n\t obj[item[0]] = isString(val)? decodeURIComponent(val) : val;\n\t}\n\treturn obj;\n }",
"function decodeConnectionData (connectionDataString) {\n const buff = new Buffer(connectionDataString, 'base64')\n const text = buff.toString('ascii')\n const connectionData = JSON.parse(text)\n return connectionData\n}",
"resolvePath(currentPathDictionary, resolvedPath) {\n\t\treturn storageObject;\n\t}",
"parsePath() {\n var protocol = goog.array.contains(this.map_['schemes'], 'https') ?\n 'https' : 'http';\n var host = this.map_['host'];\n var basepath = goog.isString(this.map_['basePath']) ?\n this.map_['basePath'] : '';\n var uri = new goog.Uri();\n uri.setScheme(protocol);\n uri.setDomain(host);\n uri.setPath(basepath);\n this.path = uri.toString();\n }",
"uriParse(value) {\n return vscode.Uri.parse(value);\n }",
"function ResourceLoader() {}",
"async resolvePath(x, y) {\n assert(typeof x === 'string');\n assert(typeof y === 'string');\n\n // Convert URL to path.\n if (isFileURL(x)) {\n x = fromFileURL(x);\n\n if (x == null)\n return null;\n }\n\n const yy = `${y}`;\n\n // Hit the cache for start directory.\n if (hasOwnProperty(this.cache, yy)) {\n y = this.cache[yy];\n } else {\n // Ensure y is absolute.\n y = resolve(y);\n\n // Ensure y is a directory. Note:\n // module.createRequire _always_\n // seems to go one directory up.\n if ((await stat(y)) === 0)\n y = dirname(y);\n\n this.cache[yy] = y;\n }\n\n const xy = `${x}\\0${y}`;\n\n // Hit the resolution cache next.\n if (hasOwnProperty(this.cache, xy))\n return this.cache[xy];\n\n // Possible redirection.\n x = await this.redirect(x, y);\n\n if (x == null) {\n this.cache[xy] = null;\n return null;\n }\n\n if (typeof x !== 'string')\n throw new TypeError('Redirection must return a string.');\n\n // Resolve path.\n let z = await this.requireX(x, y);\n\n if (z == null) {\n this.cache[xy] = null;\n return null;\n }\n\n // An actual path (not a core module).\n if (isAbsolute(z)) {\n // Normalize.\n z = resolve(z, '.');\n y = dirname(z);\n }\n\n // Possible field aliases.\n z = await this.alias(z, y);\n\n // Get realpath and normalize.\n if (isAbsolute(z)) {\n if (!this.preserve)\n z = await realpath(z);\n z = resolve(z, '.');\n }\n\n this.cache[xy] = z;\n\n return z;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs a term from the given internal string ID | function termFromId(id, factory) {
factory = factory || DataFactory; // Falsy value or empty string indicate the default graph
if (!id) return factory.defaultGraph(); // Identify the term type based on the first character
switch (id[0]) {
case '?':
return factory.variable(id.substr(1));
case '_':
return factory.blankNode(id.substr(2));
case '"':
// Shortcut for internal literals
if (factory === DataFactory) return new Literal(id); // Literal without datatype or language
if (id[id.length - 1] === '"') return factory.literal(id.substr(1, id.length - 2)); // Literal with datatype or language
const endPos = id.lastIndexOf('"', id.length - 1);
return factory.literal(id.substr(1, endPos - 1), id[endPos + 1] === '@' ? id.substr(endPos + 2) : factory.namedNode(id.substr(endPos + 3)));
case '<':
const components = quadId.exec(id);
return factory.quad(termFromId(unescapeQuotes(components[1]), factory), termFromId(unescapeQuotes(components[2]), factory), termFromId(unescapeQuotes(components[3]), factory), components[4] && termFromId(unescapeQuotes(components[4]), factory));
default:
return factory.namedNode(id);
}
} // ### Constructs an internal string ID from the given term or ID string | [
"getById(id) {\n return TermGroup(this, id);\n }",
"function idOf(word) {\n return \".word_\" + word;\n}",
"constructor(term,nbUse){\r\n this.term = term;\r\n this.nbUse = nbUse;\r\n }",
"function crearLabel(id) {\n let label = document.createElement(\"LABEL\");\n label.setAttribute(\"for\", id);\n label.innerHTML = id;\n return label;\n\n}",
"function createTermSelect(terms) {\r\n try { \r\n let helperText = $('<span />', {class: 'bc-ms-helper', style: 'padding-left: 3px', text: 'Term: ' } ),\r\n term_select = $( '<select />', {class: 'bc-ms', id: 'term-select'} );\r\n term_select.append(createSelectOption( '0', 'Select Term'));\r\n\r\n $.each(terms, function(key, value) { \r\n term_select.append().append($(\"<option></option>\").attr(\"value\", key).text(value));\r\n });\r\n helperText.appendTo('#discussion');\r\n term_select.appendTo('#discussion');\r\n } catch (e) {\r\n console.error(e);\r\n }\r\n}",
"getById(id) {\n return tag.configure(FieldLink(this).concat(`(guid'${id}')`), \"fls.getById\");\n }",
"function appendTerm( item )\n{\n\t// Add a new row to the table below that's already been added\n\t// Avoid the heading row\n\tvar newRow = document.getElementById( \"termTable\" ).insertRow( 1 );\n\n\t// Add two cells to this new row\n \tvar termCell = newRow.insertCell( 0 );\n \tvar defCell = newRow.insertCell( 1 );\n\n \t// Give the new cells their IDs\n \ttermCell.setAttribute( \"class\", \"term\" + item.cat );\n \tdefCell.setAttribute( \"class\", \"definition\" );\n\n \ttermCell.innerHTML = item.term;\n \tdefCell.innerHTML = item.definition;\n}",
"atom(ctx) {\n\t\tif (this.lexer.skip(Token.LPAREN)) {\n\t\t\tconst term = this.term(ctx);\n\t\t\tthis.lexer.match(Token.RPAREN);\n\t\t\treturn term;\n\t\t} else if (this.lexer.next(Token.LCID)) {\n\t\t\tconst id = this.lexer.token(Token.LCID)\n\t\t\treturn new AST.Identifier(ctx.indexOf(id));\n\t\t} else {\n\t\t\treturn undefined;\n\t\t}\n\t}",
"function generateSong(id) {\n return {\n id,\n name: `The song ${id}`,\n artists: [\n {\n name: 'The Artist',\n },\n ],\n };\n}",
"function termSlug( term, prefix ){\n var slug = term.replace(/[^a-zA-Z ]/g, \"\");\n return prefix ? prefix+slug : slug;\n}",
"getById(id) {\n return ContentType(this).concat(`('${id}')`);\n }",
"function item( term, definition, cat, cat2 )\n{\n\tthis.term = term;\n\tthis.definition = definition;\n\tthis.cat = cat;\n\tthis.cat2 = cat2;\n}",
"getById(id) {\n return NavigationNode(this).concat(`(${id})`);\n }",
"getById(id) {\n return FieldLink(this).concat(`(guid'${id}')`);\n }",
"function makeid() {\n var text = \"\";\n var possible = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\n for (var i = 0; i < 1000; i++) {\n text += possible.charAt(Math.floor(Math.random() * possible.length));\n return text;\n }\n }",
"gen_id(type){\n\n var str_prefix = \"\";\n var num_id = null;\n var arr_elems = null;\n switch (type) {\n case 'tool': str_prefix = \"t-\"; arr_elems= this.get_nodes('tool'); break;\n case 'data': str_prefix = \"d-\"; arr_elems= this.get_nodes('data'); break;\n case 'edge': str_prefix = \"e-\"; arr_elems= this.get_edges(); break;\n }\n\n var ids_taken = [];\n for (var i = 0; i < arr_elems.length; i++) {\n ids_taken.push(parseInt(arr_elems[i]._private.data.id.substring(2)));\n }\n\n var num_id = 1;\n while (num_id <= arr_elems.length) {\n if (ids_taken.indexOf(num_id) == -1) {\n break;\n }else {\n num_id++;\n }\n }\n\n var num_zeros = 3 - num_id/10;\n var str_zeros = \"\";\n for (var i = 0; i < num_zeros; i++) {\n str_zeros= str_zeros + \"0\";\n }\n return str_prefix+str_zeros+num_id;\n }",
"function idComponent(v) {\n return id[v];\n }",
"constructor(id, caret, colour) {\n this.id = id;\n this.caret = caret.copy();\n this.colour = colour;\n }",
"function AttributeTerm (text) {\n this._not = false;\n\n var parts = text.toLowerCase().split(':');\n this._name = parts[0];\n this._value = StringConvert.unquoteIfNecessary(parts[1]);\n\n this.not = function (not) {\n this._not = not;\n };\n\n this.isRelatedTo = function (term) {\n return (this._name === term._name);\n };\n\n this.matches = function (item) {\n var result = ((this._not || 'null' === this._value) ? true : false);\n _.forOwn(item, function (value, name) {\n if ('attributes' === name) {\n result = this.matches(value);\n if (result || this._not) {\n return false;\n }\n } else {\n if (name.toLowerCase() === this._name &&\n ((value && value.toLowerCase() === this._value) ||\n (! value && 'null' === this._value))) {\n result = (this._not ? false : true);\n return false;\n }\n }\n }, this);\n if (result && TRACE_MATCHING && item.uri) {\n console.log('!!! ATTRIBUTE', result, item.uri, this._not ? 'NOT' : '', this._name, this._value);\n }\n return result;\n };\n\n this.toString = function (prefix) {\n return prefix + (this._not ? ' not ' : '') + this._name + ':' + this._value;\n };\n}",
"setTopicID( id ) {\n return 'topic-' + parseInt( id );\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
family(id) Checks if the a prop or building family exists with the given IID and if so returns the family array. | family(id) {
let arr = this.families.get(id);
return arr || null;
} | [
"function load_family_ids() {\r\n\t\tids=[];\r\n\t\trequest('xw_controller=clan&xw_action=view&xw_city=1&xw_person='+User.id.substr(2)+'&mwcom=1&xw_client_id=8',function(page) {\r\n\t\t\tvar jpage=$('<div>'+page+'</div>');\r\n\t\t\tjpage.find('#member_list').find('.member_info').each(function(){\r\n\t\t\t\ttry {\r\n\t\t\t\t\tvar fbid = 0, m;\r\n\t\t\t\t\tif (m = /\\d+_(\\d+)_\\d+/.exec($(this).find('.clan_member_pic').attr('src'))) {\r\n\t\t\t\t\t\tfbid = m[1];\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif(fbid) {\r\n\t\t\t\t\t\tids.push(fbid);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcatch (uglybypass) {}\r\n\t\t\t});\r\n\t\t\t$('#'+spocklet+'_list').val(ids.join(','));\r\n\t\t\t$('#'+spocklet+'_numids').text(ids.length);\r\n\t\t\tlog('Family Loaded');\r\n\t\t});\r\n\t}",
"function finditembyid (id) {\n\tfor (var i = 0; i < food_pickup.length; i++) {\n\t\tif (food_pickup[i].id == id) {\n\t\t\treturn food_pickup[i]; \n\t\t}\n\t}\n\treturn false; \n}",
"function validateFamilyId(family_id) {\n return family_id.match(/[A-Z]+\\d{8}-\\d{2}/);\n}",
"function extGroup_getFamily(groupName, paramObj)\n{\n var retVal = dw.getExtDataValue(groupName, \"family\");\n\n if (paramObj)\n {\n retVal = extUtils.replaceParamsInStr(retVal, paramObj);\n }\n\n return retVal;\n}",
"function gotFamily(xmlDoc)\n{\n // alert(\"CensusForm.js: gotFamily: xmlDoc=\" + new XMLSerializer().serializeToString(xmlDoc));\n\n let rootNode = xmlDoc.documentElement;\n let msgs = xmlDoc.getElementsByTagName(\"msg\");\n if (msgs.length > 0)\n { // error messages\n alert(\"CensusForm.gotFamily: error response: \" + msgs[0].textContent);\n return;\n } // error messages\n\n // get the parameters used to invoke the script into an array\n let parms = xmlDoc.getElementsByTagName(\"parms\");\n if (parms.length > 0)\n parms = getParmsFromXml(parms[0]);\n else\n parms = null;\n\n // display the dialog relative to the button\n let buttonId = rootNode.getAttribute(\"buttonId\");\n let button = document.getElementById(buttonId);\n let form = button.form;\n let actionButton = null;\n\n let msgDiv = document.getElementById('IdirDialog');\n if (msgDiv)\n { // have popup <div> to display selection dialog in\n while(msgDiv.hasChildNodes())\n { // remove contents of cell\n msgDiv.removeChild(findButton.firstChild);\n } // remove contents of cell\n\n let matches = xmlDoc.getElementsByTagName(\"indiv\");\n if (matches.length > 0)\n { // have some matching entries\n return displayFamilyDialog('FamilyEntryForm$sub',\n parms,\n button,\n closeFamilyDialog,\n matches);\n } // have some matching entries\n else\n { // have no matching entries\n // This should never occur because the response must\n // contain all individuals in the identified family: CYA\n return displayDialog('idirNullForm$sub',\n parms,\n button,\n null); // default close dialog\n } // have no matching entries\n\n } // support for dynamic display of messages\n}",
"function findMembro(id) {\n var result = null\n $.each(membrosFamiliaJson, function(key, value) {\n if (value.id == id)\n result = value;\n });\n return result\n }",
"function getChildNamesForFamily(familyId) {\n return new Promise(async (resolve, reject) => {\n if(!familyId)\n return reject(\"Family ID is required.\");\n\t\ttry {\n\t\t\trows = await db.get({table: \"Children\", cols: [\"childId\", \"name\"], filter:{col: \"familyId\", value: familyId}});\n\t\t\treturn resolve(rows);\n\t\t} catch(err) {\n\t\t\tconsole.log(\"Unable to get children for family \" + familyId + \". Error: \" + dbErr);\n\t\t\treturn reject(dbErr);\n\t\t}\n\t});\n}",
"function searchRfid (rfid, peopleArr) {\n /*jslint plusplus: true */\n for (var i = 0; i < peopleArr.length; i++) {\n if (peopleArr[i].rfid === rfid) {\n return peopleArr[i];\n }\n }\n }",
"function findPerson(id) {\n var foundPerson = null;\n for (var i = 0; i < persons.length; i++) {\n var person = persons[i];\n if (person.id == id) {\n foundPerson = person;\n break;\n }\n }\n\n return foundPerson;\n }",
"function lookupPersonByID(id, people) {\n let person = people.find(function (person) {\n if (person.id === id) {\n return person;\n } else {\n return undefined;\n }\n });\n console.log('selected: ', person);\n return person; // person\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 getFamiliesCount(project) {\n\n return findProjectNodeByType(project, \"Family\").count;\n}",
"function displayFamily(templateId,\n parms,\n element,\n action,\n matches)\n{\n if (displayDialog(templateId,\n parms,\n element,\n action,\n true))\n {\n // update the selection list with the matching individuals\n let nextNode = document.getElementById(\"FamilyButtonLine\");\n let parentNode = nextNode.parentNode;\n\n // add the matches\n for (var i = 0; i < matches.length; ++i)\n { // loop through the matches\n let indiv = matches[i];\n\n // get the contents of the object\n let fields = getParmsFromXml(indiv);\n let member;\n if (fields['idir'].length > 0)\n member = createFromTemplate(\"Match$idir\",\n fields,\n null);\n else\n member = createFromTemplate(\"NoMatch$sub\",\n fields,\n null);\n parentNode.insertBefore(member,\n nextNode);\n } // loop through the matches\n\n // show the dialog\n dialog.style.display = 'block';\n return true;\n } // template OK\n else\n return false;\n}",
"function GetFreelancerById(id) {\n var URL = API_HOST + API_PROFILS_PATH +'/'+id\n Axios.get(URL)\n .then((response) => response.data);\n \n}",
"function doesEntryExist(id, scope)\n\t{\n\t\t// Iterate reference table and return whether a match was found\n\t\tfor(key in referenceTable)\n\t\t{\n\t\t\t// Find the matching entry, and return true\n\t\t\tif(referenceTable[key].id === id && referenceTable[key].scope === scope)\n\t\t\t\treturn true;\n\t\t}\n\n\t\t// No entry was found...\n\t\treturn false;\n\t}",
"function getChampionInfo(id) {\n if (id in champion)\n return champion[id]\n else\n throw new Error (\"No champion with id \" + id)\n }",
"FindPieceFaces() {\n let pieceFaces = [];\n this.location.forEach((element, index) => {\n if (element != 0) {\n let orientation = [0,0,0];\n orientation[index] = element;\n pieceFaces.push(new Face(orientation));\n }\n })\n return pieceFaces;\n }",
"findObject(id) {\n\t\tfor (var i in this.gameobjects) {\n\t\t\tif (this.gameobjects[i].id == id) {\n\t\t\t\treturn this.gameobjects[i];\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}",
"function mapFamily(arr) {\n console.log('FAM'.green, arr);\n var husbands = arr.filter(node => node.tag === 'HUSB'),\n wives = arr.filter(node => node.tag === 'WIFE'),\n parents = [],\n married = extractValue('MARR', arr),\n children = arr.filter(node => node.tag === 'CHIL');\n pino.info('HUSB'.red, husbands);\n\n if (husbands.length > 0) parents.push(husbands[0]);\n if (wives.length > 0) parents.push(wives[0]);\n //\n parents = parents.map(p => p.data);\n\n var events = ['MARR','DIV']\t// what else?\n .map(key => ({\n type: key,\n nodeList: arr.filter(node => node.tag === key)\n }));\n events = events.filter(obj => obj.nodeList.length > 0)\n .map(obj => ({\n id: 'e_' + treeData.eventId++,\n type: obj.type,\n date: Date.parse(extractValue('DATE', obj.nodeList)),\t// to milliseconds\n place: extractValue('PLAC', obj.nodeList)\n }));\n pino.info('EVENT'.rainbow, events);\n\n var marriages = events.filter(e => e.type === \"MARR\");\n var marriageDate = (marriages.length > 0) ? marriages[0].date : \"\";\n\n return {\n parents: parents,\n married: married || \"unknown\",\n marriageDate: marriageDate,\n children: children.length > 0 ? children.map(obj => obj.data) : [],\n events: events,\n notes: []\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
solveInverseDynamics: produces wheel velocities, torques and voltages, given a chassisVel and chassisAccel | solveInverseChassisDynamics(chassisVel, chassisAccel) {
let dynamics = new DriveDynamics();
dynamics.chassisVel = chassisVel;
dynamics.curvature = chassisVel.angular / chassisVel.linear;
if (Number.isNaN(dynamics.curvature))
dynamics.curvature = 0;
dynamics.chassisAccel = chassisAccel;
dynamics.dcurvature = chassisAccel.angular -
chassisAccel.linear * dynamics.curvature;
dynamics.dcurvature /= (chassisVel.linear * chassisVel.linear);
if (Number.isNaN(dynamics.dcurvature))
dynamics.dcurvature = 0;
dynamics.wheelVel = this.solveInverseKinematics(chassisVel);
dynamics.wheelAccel = this.solveInverseKinematics(chassisAccel);
this.solveInverse(dynamics);
return dynamics;
} | [
"solveInverseKinematics(chassisState) {\n let wheelState = new WheelState(chassisState.usage);\n wheelState.left = (chassisState.linear -\n this.effWheelbaseRad * chassisState.angular) /\n this.wheelRadius;\n wheelState.right = (chassisState.linear +\n this.effWheelbaseRad * chassisState.angular) /\n this.wheelRadius;\n return wheelState;\n }",
"solveFwdDynamicsFromChassis(chassisVel, wheelVolts) {\n let dynamics = new DriveDynamics();\n dynamics.wheelVel = this.solveInverseKinematics(chassisVel);\n dynamics.chassisVel = chassisVel;\n dynamics.curvature = chassisVel.angular / chassisVel.linear;\n if (!Number.isNaN(dynamics.curvature))\n dynamics.curvature = 0;\n dynamics.wheelVolts = wheelVolts;\n this.solveFwd(dynamics);\n return dynamics;\n }",
"getMinMaxAccel(chassisVel, curvature, maxAbsVolts) {\n let minmax = [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY];\n let wheelVel = this.solveInverseKinematics(chassisVel);\n\n // Math:\n // (Tl + Tr) / r_w = m*a\n // (Tr - Tl) / r_w * r_wb - drag*w = i*(a * k + v^2 * dk)\n // 2 equations, 2 unknowns.\n // Solve for a and (Tl|Tr)\n let linearTerm, angularTerm;\n if (Number.isFinite(curvature)) {\n linearTerm = this.mass * this.effWheelbaseRad;\n angularTerm = this.moi * curvature;\n }\n else {\n // turning in place\n linearTerm = 0;\n angularTerm = this.moi;\n }\n\n const dragTorque = chassisVel.angular * this.angularDrag;\n\n // Check all four cases and record the min and max valid accelerations.\n for (let left of [false, true]) {\n for (let sign of [1, -1]) {\n const fixedTrans = left ? this.leftTrans : this.rightTrans;\n const variableTrans = left ? this.rightTrans : this.leftTrans;\n const fixedTorque = fixedTrans.getTorqueForVolts(wheelVel.get(left),\n sign * maxAbsVolts);\n let variableTorque;\n // NOTE: variableTorque is wrong. Units don't work out correctly. \n // We made a math error somewhere... Leaving this \"as is\" for \n // code release so as not to be disingenuous, but this whole \n // function needs revisiting in the future...\n if (left) {\n variableTorque =\n ((/*-moi_ * chassis_velocity.linear * chassis_velocity.linear * dcurvature*/ -dragTorque) * this.mass * this.wheelRadius,\n + fixedTorque * (linearTerm + angularTerm))\n / (linearTerm - angularTerm);\n }\n else {\n variableTorque =\n ((/* moi_ * chassis_velocity.linear * chassis_velocity.linear * dcurvature */ +dragTorque) * this.mass * this.wheelRadius,\n + fixedTorque * (linearTerm - angularTerm))\n / (linearTerm + angularTerm);\n }\n const variableVolts = variableTrans.getVoltsForTorque(wheelVel.get(!left),\n variableTorque);\n if (Math.abs(variableVolts) <= (maxAbsVolts + kEpsilon)) {\n let accel = 0.0;\n if (!Number.isFinite(curvature)) {\n // turn in place\n accel = (left ? -1.0 : 1.0) *\n (fixedTorque - variableTorque) * this.effWheelbaseRad\n / (this.moi * this.wheelRadius) - dragTorque / this.moi /*- chassis_velocity.linear * chassis_velocity.linear * dcurvature*/;\n }\n else {\n accel = (fixedTorque + variableTorque) /\n (this.mass * this.wheelRadius);\n }\n minmax[0] = Math.min(minmax[0], accel);\n minmax[1] = Math.max(minmax[1], accel);\n }\n }\n }\n return minmax;\n }",
"inverseVelocity() {\n this.enemyVelocity *= -1;\n }",
"solve() {\n let edgeLength, edge;\n let dx, dy, fx, fy, springForce, distance;\n const edges = this.body.edges;\n const factor = 0.5;\n\n const edgeIndices = this.physicsBody.physicsEdgeIndices;\n const nodeIndices = this.physicsBody.physicsNodeIndices;\n const forces = this.physicsBody.forces;\n\n // initialize the spring force counters\n for (let i = 0; i < nodeIndices.length; i++) {\n const nodeId = nodeIndices[i];\n forces[nodeId].springFx = 0;\n forces[nodeId].springFy = 0;\n }\n\n // forces caused by the edges, modelled as springs\n for (let i = 0; i < edgeIndices.length; i++) {\n edge = edges[edgeIndices[i]];\n if (edge.connected === true) {\n edgeLength =\n edge.options.length === undefined\n ? this.options.springLength\n : edge.options.length;\n\n dx = edge.from.x - edge.to.x;\n dy = edge.from.y - edge.to.y;\n distance = Math.sqrt(dx * dx + dy * dy);\n distance = distance === 0 ? 0.01 : distance;\n\n // the 1/distance is so the fx and fy can be calculated without sine or cosine.\n springForce =\n (this.options.springConstant * (edgeLength - distance)) / distance;\n\n fx = dx * springForce;\n fy = dy * springForce;\n\n if (edge.to.level != edge.from.level) {\n if (forces[edge.toId] !== undefined) {\n forces[edge.toId].springFx -= fx;\n forces[edge.toId].springFy -= fy;\n }\n if (forces[edge.fromId] !== undefined) {\n forces[edge.fromId].springFx += fx;\n forces[edge.fromId].springFy += fy;\n }\n } else {\n if (forces[edge.toId] !== undefined) {\n forces[edge.toId].x -= factor * fx;\n forces[edge.toId].y -= factor * fy;\n }\n if (forces[edge.fromId] !== undefined) {\n forces[edge.fromId].x += factor * fx;\n forces[edge.fromId].y += factor * fy;\n }\n }\n }\n }\n\n // normalize spring forces\n springForce = 1;\n let springFx, springFy;\n for (let i = 0; i < nodeIndices.length; i++) {\n const nodeId = nodeIndices[i];\n springFx = Math.min(\n springForce,\n Math.max(-springForce, forces[nodeId].springFx)\n );\n springFy = Math.min(\n springForce,\n Math.max(-springForce, forces[nodeId].springFy)\n );\n\n forces[nodeId].x += springFx;\n forces[nodeId].y += springFy;\n }\n\n // retain energy balance\n let totalFx = 0;\n let totalFy = 0;\n for (let i = 0; i < nodeIndices.length; i++) {\n const nodeId = nodeIndices[i];\n totalFx += forces[nodeId].x;\n totalFy += forces[nodeId].y;\n }\n const correctionFx = totalFx / nodeIndices.length;\n const correctionFy = totalFy / nodeIndices.length;\n\n for (let i = 0; i < nodeIndices.length; i++) {\n const nodeId = nodeIndices[i];\n forces[nodeId].x -= correctionFx;\n forces[nodeId].y -= correctionFy;\n }\n }",
"solveForwardKinematics(wheelState) {\n let chassisState = new ChassisState(wheelState.usage);\n chassisState.linear = this.wheelRadius *\n (wheelState.right + wheelState.left) / 2;\n chassisState.angular = this.wheelRadius *\n (wheelState.right - wheelState.left) /\n (2 * this.effWheelbaseRad);\n return chassisState;\n }",
"luSolve(circuitMatrix, pivotVector, circuitRightSide) {\n // Find first nonzero element of circuitRightSide\n var j, row;\n var i = 0;\n var numRows = circuitRightSide.length;\n\n while (i < numRows) {\n row = pivotVector[i];\n var swap = circuitRightSide[row];\n circuitRightSide[row] = circuitRightSide[i];\n circuitRightSide[i] = swap;\n if (swap !== 0)\n break;\n\n ++i;\n }\n\n var bi = i++;\n while (i < numRows) {\n row = pivotVector[i];\n var tot = circuitRightSide[row];\n circuitRightSide[row] = circuitRightSide[i];\n\n // Forward substitution by using the lower triangular matrix\n j = bi;\n while (j < i) {\n tot -= circuitMatrix[i][j] * circuitRightSide[j];\n ++j;\n }\n circuitRightSide[i] = tot;\n ++i;\n }\n\n i = numRows - 1;\n\n while (i >= 0) {\n var total = circuitRightSide[i];\n\n // back-substitution using the upper triangular matrix\n j = i + 1;\n while (j !== numRows) {\n total -= circuitMatrix[i][j] * circuitRightSide[j];\n ++j;\n }\n\n circuitRightSide[i] = total / circuitMatrix[i][i];\n\n i--;\n }\n }",
"function integrateExplicitEuler(p, v, a, t, out_p, out_v) {\n // update position with *current* veloctiy\n // x_{t+1} = x_t + v_t * delta\n out_p.x = p.x + v.x * t;\n out_p.y = p.y + v.y * t;\n // update velocity with current acceleration\n // v_{t+1} = v_t + a_t * delta\n out_v.x = v.x + a.x * t;\n out_v.y = v.y + a.y * t;\n // clamp small velocities\n // if (out_v.l2Squared() < 2000) {\n //\tout_v.x = 0;\n //\tout_v.y = 0;\n // }\n }",
"function inv()\n {\n\n let i = undefined ;\n let j = undefined ;\n let k = undefined ;\n let akk = undefined ;\n let akj = undefined ;\n let aik = undefined ;\n\n let r = new Matrix( this.nr , this.nc ) ;\n\n console.log( 'r=' , r ) ;\n\n for( i = 0; i < this.nr; ++i )\n\n for( j = 0; j < this.nc; ++j )\n \n if( this.idx( i , j ) < this.nv )\n \n r.v[ r.idx( i , j ) ] = this.v[ this.idx( i , j ) ] ;\n\n for( k = 0; k < r.nr; ++k )\n\n if( akk = r.v[ r.idx( k , k ) ] )\n {\n\n for( i = 0; i < r.nc; ++i )\n\n for( j = 0; j < r.nr; ++j )\n\n if( (i != k) && (j != k) )\n {\n\n akj = r.v[ r.idx( k , j ) ] ;\n\n aik = r.v[ r.idx( i , k ) ] ;\n\n r.v[ r.idx( i , j ) ] -= ( (akj * aik) / akk ) ;\n\n } ;\n\n for( i = 0; i < r.nc; ++i )\n\n if( i != k )\n\n r.v[ r.idx( i , k ) ] /= (- akk ) ;\n\n for( j = 0; j < r.nr; ++j )\n\n if( k != j )\n\n r.v[ r.idx( k , j ) ] /= akk ;\n\n r.v[ r.idx( k , k ) ] = ( 1.0 / akk ) ;\n\n } // end if{} +\n\n else\n\n r.v[ r.idx( k , k ) ] = undefined ;\n\n for( i = 0; i < this.nr; ++i )\n\n for( j = 0; j < this.nc; ++j )\n \n if( this.idx( i , j ) < this.nv )\n \n this.v[ this.idx( i , j ) ] = r.v[ r.idx( i , j ) ];\n\n return ;\n\n }",
"applyFriction(){\n\t\tthis.vel.x *= ((0.8 - 1) * dt) + 1;\n\t}",
"invert() {\n quat.invert(this, this);\n return this.check();\n }",
"function inv_stereo(v)\r\n{\r\n var x = v[0];\r\n var y = v[1];\r\n var x3 = (2*x)/(1+x**2+y**2);\r\n var y3 = (2*y)/(1+x**2+y**2);\r\n var z3 = (x**2+y**2-1)/(1+x**2+y**2);\r\n\r\n var temp = new THREE.Vector3(x3, y3, z3).normalize();\r\n // var threeV = temp.multiplyScalar(sphereRadius);\r\n //return threeV;\r\n return temp;\r\n\r\n //return preprocessing.normalize(np.asarray([(2*x)/(1+x**2+y**2), (2*y)/(1+x**2+y**2), (x**2+y**2-1)/(1+x**2+y**2)]).reshape(1, -1), norm='l2')[0]\r\n}",
"solveKeplers(t) {\n // 1) from r0Vec, v0Vec, determine r0 and a\n // these are used within other functions used below\n\n // 2) given t-t0 (usually t0 is assumed to be zero), solve the universal\n // time of flight equation for x using a Newton iteration scheme\n // const x = this.x(t);\n const x = this.xNewton(t);\n\n // 3) Evaluate f and g from quations (4.4-31) and (4.4-34); then compute\n // rVec and r from equation (4.4-18).\n const f = this.f(x);\n const g = this.g(x, t);\n const rVec = new THREE.Vector3();\n\n rVec.addScaledVector( this.r0Vec, f );\n rVec.addScaledVector( this.v0Vec, g );\n\n this.rVec.copy(rVec);\n\n // 4) Evaluate fPrime and gPrime from equations (4.4-35) and (4.4-36);\n // then compute vVec from equation (4.4-19).\n const r = this.rVec.length();\n const fPrime = this.fPrime(x, r);\n const gPrime = this.gPrime(x, r);\n const vVec = new THREE.Vector3();\n\n vVec.addScaledVector( this.r0Vec, fPrime );\n vVec.addScaledVector( this.v0Vec, gPrime );\n\n this.vVec.copy(vVec);\n }",
"function inverseGravity() \n{ \n if (player.inverted === false) \n { \n player.angle = -180; \n player.body.gravity.y = -2000; \n player.inverted = true; \n } \n else if (player.inverted ===true)\n { \n player.angle = 0; \n player.body.gravity.y = 2000; \n player.inverted = false; \n }\n}",
"invertRows() {\n // flip \"up\" vector\n // we flip up first because invertColumns update projectio matrices\n this.up.multiplyScalar(-1);\n this.invertColumns();\n\n this._updateDirections();\n }",
"function erf_from_body_solar_flux(solar_flux, body_absorptivity=0.7, body_emissivity=0.95){\n return solar_flux * (body_absorptivity / body_emissivity)\n}",
"handleInverse() {\n const matrix = this.getMatrices(this.getSelectValue(\"inverse\"));\n if (matrix !== null) {\n const inverse = matrix.inverse().last();\n if (inverse.equals(matrix)) {\n this.displayResults(\"Inverse\", matrix, \"=\", \"This matrix is not invertible.\");\n } else {\n this.displayResults(\"Inverse\", matrix, \"=\", inverse);\n }\n }\n }",
"enactPhysics(physObj)\r\n {\r\n if(!physObj.ignoreGravity) {\r\n let dV = Vector2.scale(this.deltaTime, this.physics.gravity);\r\n physObj.velocity = Vector2.sum(dV, physObj.velocity);\r\n }\r\n\r\n let dP = Vector2.scale(this.deltaTime, physObj.velocity);\r\n physObj.position = Vector2.sum(dP, physObj.position);\r\n }",
"updateGroundSpeedPhysics() {\n // TODO: Much of this should be abstracted to helper functions\n\n // Calculate true air speed vector\n const indicatedAirspeed = this.speed;\n const trueAirspeedIncreaseFactor = this.altitude * ENVIRONMENT.DENSITY_ALT_INCREASE_FACTOR_PER_FT;\n const trueAirspeed = indicatedAirspeed * (1 + trueAirspeedIncreaseFactor);\n const flightThroughAirVector = vscale(vectorize2dFromRadians(this.heading), trueAirspeed);\n\n // Calculate ground speed and direction\n const windVector = AirportController.airport_get().getWindVectorAtAltitude(this.altitude);\n const flightPathVector = vadd(flightThroughAirVector, windVector);\n const groundSpeed = vlen(flightPathVector);\n let groundTrack = vradial(flightPathVector);\n\n // Prevent aircraft on the ground from being blown off runway centerline when too slow to crab sufficiently\n if (this.isOnGround()) {\n // TODO: Aircraft crabbing into the wind will show an increase in groundspeed after they reduce to slower than\n // the wind speed. This should be corrected so their groundspeed gradually reduces from touchdown spd to 0.\n groundTrack = this.targetGroundTrack;\n }\n\n // Calculate new position\n const hoursElapsed = TimeKeeper.getDeltaTimeForGameStateAndTimewarp() * TIME.ONE_SECOND_IN_HOURS;\n const distanceTraveled_nm = groundSpeed * hoursElapsed;\n\n this.positionModel.setCoordinatesByBearingAndDistance(groundTrack, distanceTraveled_nm);\n\n this.groundTrack = groundTrack;\n this.groundSpeed = groundSpeed;\n this.trueAirspeed = trueAirspeed;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Call `setDefaultAssetId` on the parent `ScratchStorage` instance to register all builtin default assets. | registerDefaultAssets() {
const numAssets = DefaultAssets.length;
for (let assetIndex = 0; assetIndex < numAssets; ++assetIndex) {
const assetRecord = DefaultAssets[assetIndex];
this.parent.setDefaultAssetId(assetRecord.type, assetRecord.id);
}
} | [
"_onResetDefaults(event) {\n event.preventDefault();\n game.settings.set(\"core\", DrawingsLayer.DEFAULT_CONFIG_SETTING, {});\n this.object.data = canvas.drawings._getNewDrawingData({});\n this.render();\n }",
"async loadDefaults () {\n // No default config files for seeded assets right now.\n const walletDef = app().walletDefinition(this.currentAsset.id, this.currentWalletType)\n if (walletDef.seeded) return\n const loaded = app().loading(this.form)\n const res = await postJSON('/api/defaultwalletcfg', {\n assetID: this.currentAsset.id,\n type: this.currentWalletType\n })\n loaded()\n if (!app().checkResponse(res)) {\n this.setError(res.msg)\n return\n }\n this.subform.setLoadedConfig(res.config)\n }",
"function setDefaultUid() {\n\n\t//Set \"default\" UID to current hardcoded version - for >= 2.26 we could leave it out and point to null, though this wouldn't work with custom forms\n\tvar currentDefault, defaultDefault, types = [\"categoryOptions\", \"categories\", \"categoryOptionCombos\", \"categoryCombos\"];\n\tfor (var k = 0; k < types.length; k++) {\n\t\tfor (var i = 0; metaData[types[k]] && i < metaData[types[k]].length; i++) {\n\t\t\tif (metaData[types[k]][i].name === \"default\") currentDefault = metaData[types[k]][i].id;\n\t\t}\n\n\t\tif (!currentDefault) continue;\n\n\t\tswitch (types[k]) {\n\t\tcase \"categoryOptions\":\n\t\t\tdefaultDefault = \"xYerKDKCefk\";\n\t\t\tbreak;\n\t\tcase \"categories\":\n\t\t\tdefaultDefault = \"GLevLNI9wkl\";\n\t\t\tbreak;\n\t\tcase \"categoryOptionCombos\":\n\t\t\tdefaultDefault = \"HllvX50cXC0\";\n\t\t\tbreak;\n\t\tcase \"categoryCombos\":\n\t\t\tdefaultDefault = \"bjDvmb4bfuf\";\n\t\t\tbreak;\n\t\t}\n\n\t\t//search and replace metaData as text, to make sure customs forms are included\n\t\tvar regex = new RegExp(currentDefault, \"g\");\n\t\tmetaData = JSON.parse(JSON.stringify(metaData).replace(regex, defaultDefault));\n\t}\n}",
"loadEngineDefaults() {\n for (let key in DEFAULT_SETTINGS) {\n const setting = new Setting(key, DEFAULT_SETTINGS[key]);\n super.set(setting.getName(), setting);\n }\n }",
"static setAsDefault(captionAssetId){\n\t\tlet kparams = {};\n\t\tkparams.captionAssetId = captionAssetId;\n\t\treturn new kaltura.RequestBuilder('caption_captionasset', 'setAsDefault', kparams);\n\t}",
"function setDefaultAttrs(attrs) {\n defaultAttrs = attrs;\n}",
"function setDefaultImages() {\n if (imageIndex == 1) {\n index = 8;\n r = 260;\n }\n else if (imageIndex == 2) {\n index = 2;\n r = 429;\n }\n else if (imageIndex == 3) {\n index = 9; \n r = 2384;\n }\n}",
"function default_webpack_assets() {\n\tvar webpack_assets = {\n\t\tjavascript: {},\n\t\tstyles: {}\n\t};\n\n\treturn webpack_assets;\n}",
"function setHomeDefaults() {\n sessionStorage[\"datacen\"] = \"All\";\n sessionStorage[\"network\"] = -1;\n sessionStorage[\"farm\"] = -1;\n}",
"function addDefaultAssets () {\n // Skip this step on the browser, or if emptyRepo was supplied.\n const isNode = require('detect-node')\n if (!isNode || opts.emptyRepo) {\n return callback(null, true)\n }\n\n const blocks = new BlockService(self._repo)\n const dag = new DagService(blocks)\n\n const initDocsPath = path.join(__dirname, '../../init-files/init-docs')\n const index = __dirname.lastIndexOf('/')\n\n pull(\n pull.values([initDocsPath]),\n pull.asyncMap((val, cb) => {\n glob(path.join(val, '/**/*'), cb)\n }),\n pull.flatten(),\n pull.map((element) => {\n const addPath = element.substring(index + 1, element.length)\n if (fs.statSync(element).isDirectory()) return\n\n return {\n path: addPath,\n content: file(element)\n }\n }),\n pull.filter(Boolean),\n importer(dag),\n pull.through((el) => {\n if (el.path === 'files/init-docs/docs') {\n const hash = mh.toB58String(el.multihash)\n opts.log('to get started, enter:')\n opts.log()\n opts.log(`\\t jsipfs files cat /ipfs/${hash}/readme`)\n opts.log()\n }\n }),\n pull.onEnd((err) => {\n if (err) return callback(err)\n\n callback(null, true)\n })\n )\n }",
"function makeDefaultDataset() {\r\n fillDefaultDataset(dataOrigin);\r\n fillDefaultDataset(dataAsylum);\r\n}",
"function onSetDefault(idx) {\n Y.log('Setting default item: ' + idx, 'info', NAME);\n dcList.selected = idx;\n renderItems();\n callWhenChanged(Y.dcforms.listToString(dcList));\n }",
"loadDefaultFile () {\n this.file = '.sassdocrc'\n this.tryLoadCurrentFile()\n }",
"reset(){\n\t\tDEFAULT_BUCKET['*'].handlers = []\n\t\tthis.Bucket = Object.assign({}, DEFAULT_BUCKET)\n\t}",
"function setStorageDefaultValues() {\n chrome.storage.sync.get(null, function (items) {\n try {\n if (chrome.runtime.lastError) {\n console.warn(chrome.runtime.lastError.message);\n } else {\n\n //console.log(items);\n if (isEmpty(items)) {\n //console.log('storage empty');\n //Set Default showNotifications value to options\n chrome.storage.sync.set({\n showNotifications: options.showNotifications,\n clearActivity: options.clearActivity,\n intervalTimeout: options.intervalTimeout\n });\n } else {\n //console.log('storage has data');\n // Equal options default value to storage\n options.showNotifications = items.showNotifications;\n options.clearActivity = items.clearActivity;\n changeTime(items.intervalTimeout);\n }\n\n }\n } catch (exception) {\n //window.alert('exception.stack: ' + exception.stack);\n console.error((new Date()).toJSON(), \"exception.stack:\", exception.stack);\n }\n });\n}",
"addDefaultRenderers() {\r\n this.addRenderer(new FlowRendererText(this.settings));\r\n this.addRenderer(new FlowRendererImage(this.settings));\r\n this.addRenderer(new FlowRendererHero(this.settings));\r\n this.addRenderer(new FlowRendererThumbnail(this.settings));\r\n this.addRenderer(new FlowRendererCarousel(this.settings));\r\n this.addRenderer(new FlowRendererList(this.settings));\r\n this.addRenderer(new FlowRendererPrompt(this.settings));\r\n this.addRenderer(new FlowRendererReceipt(this.settings));\r\n }",
"function restoreDefaultBookmarks() {\n const TOPIC_BOOKMARKS_RESTORE_SUCCESS = \"bookmarks-restore-success\";\n\n var importSuccessful = false;\n var observer = {\n observe: function(aSubject, aTopic, aData) {\n importSuccessful = true;\n }\n }\n\n // Fire off the import and ensure we do an initially import\n try {\n Services.obs.addObserver(observer, TOPIC_BOOKMARKS_RESTORE_SUCCESS, false);\n\n BookmarkHTMLUtils.importFromURL(BOOKMARKS_RESOURCE, true);\n\n // Wait for it to be finished\n assert.waitFor(function () {\n return importSuccessful;\n }, \"Default bookmarks have been imported\", BOOKMARKS_TIMEOUT);\n }\n finally {\n Services.obs.removeObserver(observer, TOPIC_BOOKMARKS_RESTORE_SUCCESS);\n }\n}",
"function generateDefaultShibeImgs() {\n const shibeImg = document.getElementsByClassName(\"img-bk\")\n\n for(let i = 0; i < shibeImg.length; i++) {\n shibeImg[i].style.backgroundImage = `url(${shibeImgs[Math.floor(\n Math.random() * shibeImgs.length)]}\n )`\n }\n}",
"function default_repository (id) {\r\n if (id && DataRepositories[id]) {\r\n DataRepositoryDefault = DataRepositories[id];\r\n }\r\n}",
"static setAsDefault(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('conversionprofile', 'setAsDefault', kparams);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Double checks that dynamic content interpolated into a heredoc string does not include the end word. If it does, rewrites content on the buffer to use nonconflicting start and end words. If this functions fails to avoid a collision, it will fail with an exception, but this should not reliably occur unless an attacker can generate hash collisions. | function fixupHeredoc (buf, heredocContext) {
const [ delim, contextStart, contextOffset, delimLength ] = heredocContext
let chunkLeft = 0
let startChunkIndex = -1
for (let i = 0, len = buf.length; i < len; ++i) {
chunkLeft += buf[i].length
if (chunkLeft >= contextStart) {
startChunkIndex = i
break
}
}
if (startChunkIndex < 0) {
throw fail`Cannot find heredoc start for ${heredocContext}`
}
const label = heredocLabel(delim)
const endChunkIndex = buf.length - 1
// Figure out how much of the last chunk is part of the body.
const bodyRe = heredocBodyRegExp(label)
const endChunk = buf[endChunkIndex]
const lastBodyMatch = bodyRe.exec(endChunk)
if (lastBodyMatch[0].length === endChunk.length) {
throw fail`Could not find end of ${delim}`
}
const startChunk = buf[startChunkIndex]
let body = startChunk.substring(contextOffset + delimLength)
for (let i = startChunkIndex + 1; i < endChunkIndex; ++i) {
body += buf[i]
}
body += lastBodyMatch[0]
// Look for a premature end delimiter by looking at newline followed by body.
const testBody = `\n${body}`
if (bodyRe.exec(testBody)[0].length !== testBody.length) {
// There is an embedded delimiter.
// Choose a suffix that an attacker cannot predict.
// An attacker would need to be able to generate sha256
// collisions to embed both NL <label> and NL <label> <suffix>.
let suffix = '_'
suffix += crypto.createHash('sha256')
.update(body, 'utf8')
.digest('base64')
.replace(/[=]+$/, '')
const newLabel = label + suffix
const newBodyRe = heredocBodyRegExp(newLabel)
if (!newBodyRe.exec(testBody)[0].length === testBody.length) {
throw fail`Cannot solve embedding hazard in ${body} in heredoc with ${label} due to hash collision`
}
const endDelimEndOffset = lastBodyMatch[0].length +
endChunk.substring(lastBodyMatch[0].length)
// If the \w+ part below changes, also change the \w+ in the lexer
// after the check for << and <<- start delimiters.
.match(/[\r\n]\w+/)[0].length
const before = startChunk.substring(0, contextOffset + delimLength)
.replace(/[\r\n]+$/, '')
const after = startChunk.substring(contextOffset + delimLength)
buf[startChunkIndex] = `${before}${suffix}\n${after}`
buf[endChunkIndex] = (
endChunk.substring(0, endDelimEndOffset) +
suffix +
endChunk.substring(endDelimEndOffset))
}
} | [
"async cleanUpDocString() {\n const removeStreams = /stream(.*?)endstream/gs\n const removeComments = /%(.[^(PDF)][^%EOF]*?)\\n/g\n const removeMultiSpace = /[^\\S\\n\\r]{2,}/g\n const addNewLine = /(%%EOF)/gms\n\n return this.docString = this.docString\n .replace(addNewLine, '%%EOF\\n')\n .replace(removeStreams, '\\nstream\\nendstream\\n')\n .replace(removeMultiSpace, ' ')\n .replace(removeComments, '\\n')\n }",
"function formatDynamicDataRef(str, format)\n{\n var ret = str;\n var iStart = str.indexOf(\"<%#\", 0);\n\n if (iStart > -1)\n {\n var iEnd = str.indexOf(\"%>\", iStart+1);\n \n\tif (iEnd > -1)\n {\n \t var dataRef = dwscripts.trim(str.substring(iStart+3, iEnd));\n \n\t // Replace ([\\s\\S]+) with dataRef\n\t // Replace \\s* with a space\n\t // Replace single quotes with double quotes\n\t // Remove rest of backslashes\n\n\t ret = format.expression;\n\n\t ret = ret.replace(/\\(\\[\\\\s\\\\S\\]\\+\\)/g, dataRef);\n\t ret = ret.replace(/\\\\s\\*/g, \" \");\n\t ret = ret.replace(/"/g, \"\\\"\");\n\t ret = ret.replace(/\\\\/g, \"\");\n }\n else\n {\n // Error: no termination of the ASP.Net block.\n }\n }\n else\n {\n // Error: no start of ASP.Net block.\n }\n \n return ret;\n}",
"function composeShellString ({ contexts, raw }, staticStrings, untrusted) {\n const trusted = raw\n // A buffer onto which we accumulate output.\n const buf = [ trusted[0] ]\n let [ currentContext ] = contexts\n for (let i = 0, len = untrusted.length; i < len; ++i) {\n const newContext = contexts[i + 1]\n const value = untrusted[i]\n let [ delim ] = currentContext\n if (delim[0] === '<') {\n delim = '<<'\n }\n const embedder = DELIMS[delim].embed\n const chunk = trusted[i + 1]\n buf.push(embedder(value, buf, currentContext), chunk)\n if (currentContext !== newContext &&\n delim[0] === '<' && delim[1] === '<') {\n fixupHeredoc(buf, currentContext, newContext)\n }\n currentContext = newContext\n }\n\n return new ShFragment(buf.join(''))\n}",
"function docEdits_canMergeBlock(insertText)\n{\n var retVal = null;\n\n var dom = dw.getDocumentDOM();\n var delimInfo = dom.serverModel.getDelimiters();\n var myDelim;\n\n // Create the mergePattern and noMergePatterns\n\n var mergePattern = \"^\\\\s*(?:\";\n var noMergePattern = \"^\\\\s*(\";\n var len1 = mergePattern.length;\n var len2 = noMergePattern.length;\n\n if (delimInfo && delimInfo.length && insertText && insertText.length)\n {\n for (var i=0; i < delimInfo.length; i++)\n {\n myDelim = delimInfo[i];\n if (myDelim.participateInMerge)\n {\n if (mergePattern.length > len1)\n {\n mergePattern += \"|\";\n }\n mergePattern += \"(?:(\" + myDelim.startPattern + \")[\\\\S\\\\s]*(\" + myDelim.endPattern + \"))\";\n }\n else\n {\n if (noMergePattern.length > len2)\n {\n noMergePattern += \"|\";\n }\n noMergePattern += \"(\" + myDelim.startPattern + \"[\\\\S\\\\s]*\" + myDelim.endPattern + \")\";\n }\n }\n\n // Check the insertText to determine if it can participate in a merge\n\n var mergeRe = null;\n var noMergeRe = null;\n\t\n\tif( mergePattern.length > len1 ){\n\t\ttry{\t\n\t\t\tmergePattern += \")\\\\s*$\";\n\t\t\tmergeRe= new RegExp (mergePattern, \"i\");\n\t\t} \n\t\tcatch(e){\n\t\t\talert( e.description );\n\t\t\tmergeRe = null;\n\t\t}\n\t}\n\tif( noMergePattern.length > len2 ){\n\t\ttry{\t\n\t\t\tnoMergePattern += \")\\\\s*$\";\n\t\t\tnoMergeRe= new RegExp (noMergePattern, \"i\");\n\t\t} \n\t\tcatch(e){\n\t\t\talert( e.description );\n\t\t\tnoMergeRe = null;\n\t\t}\n\t}\n\n if (mergeRe != null && (noMergeRe == null || !noMergeRe.test(insertText))) //exclude non-mergeable blocks\n {\n var match = insertText.match(mergeRe); //try to extract delims\n if (match)\n {\t\t\t\n for (var i=0; i < delimInfo.length; i++)\n {\n //check the sub-expression pairs stating at item 1\n if (match[2*i+1] && match[2*i+2] && match[2*i+1].length > 0 && match[2*i+2].length > 0)\n {\n var retVal = new Array();\n retVal.push(match[2*i+1]);\n retVal.push(match[2*i+2]);\n break;\n }\n }\n }\n }\n }\n\n return retVal;\n}",
"function myExtractContents(range) {\n // \"Let frag be a new DocumentFragment whose ownerDocument is the same as\n // the ownerDocument of the context object's start node.\"\n var ownerDoc = range.startContainer.nodeType == Node.DOCUMENT_NODE\n ? range.startContainer\n : range.startContainer.ownerDocument;\n var frag = ownerDoc.createDocumentFragment();\n\n // \"If the context object's start and end are the same, abort this method,\n // returning frag.\"\n if (range.startContainer == range.endContainer\n && range.startOffset == range.endOffset) {\n return frag;\n }\n\n // \"Let original start node, original start offset, original end node, and\n // original end offset be the context object's start and end nodes and\n // offsets, respectively.\"\n var originalStartNode = range.startContainer;\n var originalStartOffset = range.startOffset;\n var originalEndNode = range.endContainer;\n var originalEndOffset = range.endOffset;\n\n // \"If original start node is original end node, and they are a Text,\n // ProcessingInstruction, or Comment node:\"\n if (range.startContainer == range.endContainer\n && (range.startContainer.nodeType == Node.TEXT_NODE\n || range.startContainer.nodeType == Node.PROCESSING_INSTRUCTION_NODE\n || range.startContainer.nodeType == Node.COMMENT_NODE)) {\n // \"Let clone be the result of calling cloneNode(false) on original\n // start node.\"\n var clone = originalStartNode.cloneNode(false);\n\n // \"Set the data of clone to the result of calling\n // substringData(original start offset, original end offset − original\n // start offset) on original start node.\"\n clone.data = originalStartNode.substringData(originalStartOffset,\n originalEndOffset - originalStartOffset);\n\n // \"Append clone as the last child of frag.\"\n frag.appendChild(clone);\n\n // \"Call deleteData(original start offset, original end offset −\n // original start offset) on original start node.\"\n originalStartNode.deleteData(originalStartOffset,\n originalEndOffset - originalStartOffset);\n\n // \"Abort this method, returning frag.\"\n return frag;\n }\n\n // \"Let common ancestor equal original start node.\"\n var commonAncestor = originalStartNode;\n\n // \"While common ancestor is not an ancestor container of original end\n // node, set common ancestor to its own parent.\"\n while (!isAncestorContainer(commonAncestor, originalEndNode)) {\n commonAncestor = commonAncestor.parentNode;\n }\n\n // \"If original start node is an ancestor container of original end node,\n // let first partially contained child be null.\"\n var firstPartiallyContainedChild;\n if (isAncestorContainer(originalStartNode, originalEndNode)) {\n firstPartiallyContainedChild = null;\n // \"Otherwise, let first partially contained child be the first child of\n // common ancestor that is partially contained in the context object.\"\n } else {\n for (var i = 0; i < commonAncestor.childNodes.length; i++) {\n if (isPartiallyContained(commonAncestor.childNodes[i], range)) {\n firstPartiallyContainedChild = commonAncestor.childNodes[i];\n break;\n }\n }\n if (!firstPartiallyContainedChild) {\n throw \"Spec bug: no first partially contained child!\";\n }\n }\n\n // \"If original end node is an ancestor container of original start node,\n // let last partially contained child be null.\"\n var lastPartiallyContainedChild;\n if (isAncestorContainer(originalEndNode, originalStartNode)) {\n lastPartiallyContainedChild = null;\n // \"Otherwise, let last partially contained child be the last child of\n // common ancestor that is partially contained in the context object.\"\n } else {\n for (var i = commonAncestor.childNodes.length - 1; i >= 0; i--) {\n if (isPartiallyContained(commonAncestor.childNodes[i], range)) {\n lastPartiallyContainedChild = commonAncestor.childNodes[i];\n break;\n }\n }\n if (!lastPartiallyContainedChild) {\n throw \"Spec bug: no last partially contained child!\";\n }\n }\n\n // \"Let contained children be a list of all children of common ancestor\n // that are contained in the context object, in tree order.\"\n //\n // \"If any member of contained children is a DocumentType, raise a\n // HIERARCHY_REQUEST_ERR exception and abort these steps.\"\n var containedChildren = [];\n for (var i = 0; i < commonAncestor.childNodes.length; i++) {\n if (isContained(commonAncestor.childNodes[i], range)) {\n if (commonAncestor.childNodes[i].nodeType\n == Node.DOCUMENT_TYPE_NODE) {\n return \"HIERARCHY_REQUEST_ERR\";\n }\n containedChildren.push(commonAncestor.childNodes[i]);\n }\n }\n\n // \"If original start node is an ancestor container of original end node,\n // set new node to original start node and new offset to original start\n // offset.\"\n var newNode, newOffset;\n if (isAncestorContainer(originalStartNode, originalEndNode)) {\n newNode = originalStartNode;\n newOffset = originalStartOffset;\n // \"Otherwise:\"\n } else {\n // \"Let reference node equal original start node.\"\n var referenceNode = originalStartNode;\n\n // \"While reference node's parent is not null and is not an ancestor\n // container of original end node, set reference node to its parent.\"\n while (referenceNode.parentNode\n && !isAncestorContainer(referenceNode.parentNode, originalEndNode)) {\n referenceNode = referenceNode.parentNode;\n }\n\n // \"Set new node to the parent of reference node, and new offset to one\n // plus the index of reference node.\"\n newNode = referenceNode.parentNode;\n newOffset = 1 + indexOf(referenceNode);\n }\n\n // \"If first partially contained child is a Text, ProcessingInstruction, or\n // Comment node:\"\n if (firstPartiallyContainedChild\n && (firstPartiallyContainedChild.nodeType == Node.TEXT_NODE\n || firstPartiallyContainedChild.nodeType == Node.PROCESSING_INSTRUCTION_NODE\n || firstPartiallyContainedChild.nodeType == Node.COMMENT_NODE)) {\n // \"Let clone be the result of calling cloneNode(false) on original\n // start node.\"\n var clone = originalStartNode.cloneNode(false);\n\n // \"Set the data of clone to the result of calling substringData() on\n // original start node, with original start offset as the first\n // argument and (length of original start node − original start offset)\n // as the second.\"\n clone.data = originalStartNode.substringData(originalStartOffset,\n nodeLength(originalStartNode) - originalStartOffset);\n\n // \"Append clone as the last child of frag.\"\n frag.appendChild(clone);\n\n // \"Call deleteData() on original start node, with original start\n // offset as the first argument and (length of original start node −\n // original start offset) as the second.\"\n originalStartNode.deleteData(originalStartOffset,\n nodeLength(originalStartNode) - originalStartOffset);\n // \"Otherwise, if first partially contained child is not null:\"\n } else if (firstPartiallyContainedChild) {\n // \"Let clone be the result of calling cloneNode(false) on first\n // partially contained child.\"\n var clone = firstPartiallyContainedChild.cloneNode(false);\n\n // \"Append clone as the last child of frag.\"\n frag.appendChild(clone);\n\n // \"Let subrange be a new Range whose start is (original start node,\n // original start offset) and whose end is (first partially contained\n // child, length of first partially contained child).\"\n var subrange = ownerDoc.createRange();\n subrange.setStart(originalStartNode, originalStartOffset);\n subrange.setEnd(firstPartiallyContainedChild,\n nodeLength(firstPartiallyContainedChild));\n\n // \"Let subfrag be the result of calling extractContents() on\n // subrange.\"\n var subfrag = myExtractContents(subrange);\n\n // \"For each child of subfrag, in order, append that child to clone as\n // its last child.\"\n for (var i = 0; i < subfrag.childNodes.length; i++) {\n clone.appendChild(subfrag.childNodes[i]);\n }\n }\n\n // \"For each contained child in contained children, append contained child\n // as the last child of frag.\"\n for (var i = 0; i < containedChildren.length; i++) {\n frag.appendChild(containedChildren[i]);\n }\n\n // \"If last partially contained child is a Text, ProcessingInstruction, or\n // Comment node:\"\n if (lastPartiallyContainedChild\n && (lastPartiallyContainedChild.nodeType == Node.TEXT_NODE\n || lastPartiallyContainedChild.nodeType == Node.PROCESSING_INSTRUCTION_NODE\n || lastPartiallyContainedChild.nodeType == Node.COMMENT_NODE)) {\n // \"Let clone be the result of calling cloneNode(false) on original\n // end node.\"\n var clone = originalEndNode.cloneNode(false);\n\n // \"Set the data of clone to the result of calling substringData(0,\n // original end offset) on original end node.\"\n clone.data = originalEndNode.substringData(0, originalEndOffset);\n\n // \"Append clone as the last child of frag.\"\n frag.appendChild(clone);\n\n // \"Call deleteData(0, original end offset) on original end node.\"\n originalEndNode.deleteData(0, originalEndOffset);\n // \"Otherwise, if last partially contained child is not null:\"\n } else if (lastPartiallyContainedChild) {\n // \"Let clone be the result of calling cloneNode(false) on last\n // partially contained child.\"\n var clone = lastPartiallyContainedChild.cloneNode(false);\n\n // \"Append clone as the last child of frag.\"\n frag.appendChild(clone);\n\n // \"Let subrange be a new Range whose start is (last partially\n // contained child, 0) and whose end is (original end node, original\n // end offset).\"\n var subrange = ownerDoc.createRange();\n subrange.setStart(lastPartiallyContainedChild, 0);\n subrange.setEnd(originalEndNode, originalEndOffset);\n\n // \"Let subfrag be the result of calling extractContents() on\n // subrange.\"\n var subfrag = myExtractContents(subrange);\n\n // \"For each child of subfrag, in order, append that child to clone as\n // its last child.\"\n for (var i = 0; i < subfrag.childNodes.length; i++) {\n clone.appendChild(subfrag.childNodes[i]);\n }\n }\n\n // \"Set the context object's start and end to (new node, new offset).\"\n range.setStart(newNode, newOffset);\n range.setEnd(newNode, newOffset);\n\n // \"Return frag.\"\n return frag;\n}",
"function formatDynamicDataRef(str, format)\r\n{\r\n var ret = str;\r\n var iStart = getIndexOfEchoForResponseWrite(str);\r\n\r\n if (iStart > -1)\r\n {\r\n var iEnd = str.search(/;\\s*\\?>/);\r\n if (iEnd == -1)\r\n {\r\n iEnd = str.search(/\\s*\\?>/);\r\n }\r\n \r\n if (iEnd > -1)\r\n {\r\n // The one and only argument is the function to ASP function to call.\r\n \r\n ret = str.substring(0, iStart) + \r\n ((str.charAt(iStart-1) != \" \")? \" \" : \"\") + \r\n format.func + \"(\" + str.substring(iStart, iEnd) + \")\" + \r\n str.substr(iEnd);\r\n }\r\n else\r\n {\r\n // Error: no termination of the PHP block.\r\n // alert(\"no end to PHP\");\r\n }\r\n }\r\n else\r\n {\r\n // Error: no start of PHP block.\r\n // alert(\"no equals\");\r\n }\r\n\r\n\treturn ret;\r\n}",
"function BREAK_WORD$static_(){OverflowBehaviour.BREAK_WORD=( new OverflowBehaviour(\"break-word\"));}",
"wpml( txt, inline ) {\n if (!txt) { return ''; }\n inline = (inline && !inline.hash) || false;\n txt = XML(txt.trim());\n txt = inline ? MD(txt).replace(/^\\s*<p>|<\\/p>\\s*$/gi, '') : MD(txt);\n txt = H2W( txt );\n return txt;\n }",
"function processSourceCode(doc) {\n var body = doc.getBody();\n\n var startingTripleTick = body.findText('```');\n if (!startingTripleTick) return;\n var endTripleTick = body.findText('```', startingTripleTick);\n if (!endTripleTick) return;\n\n var firstLine = startingTripleTick.getElement();\n var lastLine = endTripleTick.getElement();\n\n var rangeBuilder = doc.newRange();\n rangeBuilder.addElementsBetween(firstLine, lastLine);\n var range = rangeBuilder.build();\n var lineRanges = range.getRangeElements();\n var lines = [];\n\n var firstLineIndex = body.getChildIndex(lineRanges[0].getElement());\n var code = \"\";\n\n // Don't iterate over 0th and last line because they are the tripleticks\n lineRanges[0].getElement().removeFromParent();\n for (var i = 1; i < lineRanges.length - 1; ++i) {\n code += lineRanges[i].getElement().asText().getText() + '\\n';\n lineRanges[i].getElement().removeFromParent();\n }\n lineRanges[lineRanges.length-1].getElement().removeFromParent();\n\n var cell = body.insertTable(firstLineIndex)\n .setBorderWidth(0)\n .appendTableRow()\n .appendTableCell();\n\n var params = {\n 'code': code.trim(),\n 'lexer': /```(.*)/.exec(firstLine.asText().getText())[1],\n 'style': 'monokai'\n };\n var response = UrlFetchApp.fetch(\n \"http://hilite.me/api\",\n {\n 'method': 'post',\n 'payload': params\n }\n );\n\n var xmlDoc = XmlService.parse(response.getContentText());\n // The XML document is structured as\n // - comment\n // - div\n // - pre\n // - spans\n var divTag = xmlDoc.getAllContent()[1];\n var preTag = divTag.getAllContent()[0];\n var spans_or_texts = preTag.getAllContent();\n var span_ranges = [];\n\n var startCharIdx = 0;\n for (var i = 0; i < spans_or_texts.length; ++i) {\n var span_or_text = spans_or_texts[i];\n if (span_or_text.getType() == XmlService.ContentTypes.ELEMENT) {\n // We are seeing a span (spans are styled while texts are not)\n var span_range = {\n start: startCharIdx,\n endInclusive: startCharIdx + span_or_text.getValue().length - 1,\n span: span_or_text\n };\n span_ranges.push(span_range);\n }\n startCharIdx += span_or_text.getValue().length;\n }\n\n var getTagColor = function (tag) {\n return tag.getAttribute('style').getValue().match(/#[0-9 a-f A-F]{6}/);\n };\n\n cell.setText(preTag.getValue().trim());\n\n var cellText = cell.editAsText();\n for (var i = 0; i < span_ranges.length; ++i) {\n var span_range = span_ranges[i];\n cellText.setForegroundColor(\n span_range.start,\n span_range.endInclusive,\n getTagColor(span_range.span)\n );\n }\n cell.setBackgroundColor(getTagColor(divTag));\n cell.setFontFamily('Consolas');\n\n processSourceCode(doc);\n}",
"function handlePosHtml(){\n htmlOriginalPos = htmlOriginal;\n htmlOriginalPos = htmlOriginalPos.replace(/(<script[^>]*>)[\\s\\S]*?(<\\/script>)/ig, \"$1███NOT_MATCHING███$2\");\n htmlOriginalPos = htmlOriginalPos.replace(/(<noscript[^>]*>)[\\s\\S]*?(<\\/noscript>)/ig, \"$1███NOT_MATCHING███$2\");\n htmlOriginalPos = htmlOriginalPos.replace(/(<\\!--)[\\s\\S]*?(-->)/ig, \"$1███NOT_MATCHING███$2\");\n htmlOriginalPos = htmlOriginalPos.replace(/(<xmp[^>]*>)[\\s\\S]*?(<\\/xmp>)/ig, \"$1███NOT_MATCHING███$2\");\n}",
"hasDocstring(line){\n if (typeof line == 'undefined'){ return false;}\n return line.indexOf('*/')>=0\n}",
"function replaceChunk( str, start, end, sub )\n{\n\tvar r = getChunkRange( str, start, end );\n\treturn r ? str.substring(0,r[0]) + sub + str.substring(r[1]) : str;\n}",
"function isInlineTex(content) {\n\t return content[0] !== '\\n';\n\t}",
"function isWord(\n sourceDoc,\n begin,\n end,\n isDelimiterFunc\n ) {\n const precedingChar = sourceDoc.charAt(begin - 1)\n const followingChar = sourceDoc.charAt(end)\n\n return isDelimiterFunc(precedingChar) && isDelimiterFunc(followingChar)\n } // CONCATENATED MODULE: ./src/lib/Editor/AnnotationData/getReplicationRanges/index.js",
"function fail(hash) {\n return `<script>console.error(\"LaTeX for ${hash} failed.\");</script>`;\n}",
"function ends_with(s, post) /* (s : string, post : string) -> maybe<sslice> */ {\n if (xends_with(s, post)) {\n return Just(Sslice(s, 0, (((s.length) - (post.length))|0)));\n }\n else {\n return Nothing;\n }\n}",
"function replacer(match, type, offset) {\r\n\t\r\n\t\t// Find start position (all positions here are relative to the matched substring,\r\n\t\t// not the entire original document (which is available as a 4th parameter btw))\r\n\t\tvar start = type.length;\r\n\t\t\r\n\t\t// Ensure we haven't already parsed this line\r\n\t\tif ( match.substr(start, 5) == 'parse' ) {\r\n\t\t\treturn match;\r\n\t\t}\r\n\r\n\t\t// And end position\r\n\t\tvar end = analyze_js(match, start);\r\n\t\t\r\n\t\t// Determine the wrapper to use. First clear any whitespace.\r\n\t\ttype = type.replace(/\\s/g, '');\r\n\t\t\r\n\t\t// If .innerHTML, parse HTML. Otherwise, it's a URL.\r\n\t\tvar wrapperFunc = ( type == '.innerHTML=' ) ? 'parseHTML' : 'parseURL';\r\n\r\n\t\t// Create the wrapped statement\r\n\t\tvar wrapped = wrapperFunc + '(' + match.substring(start, end) + ')';\r\n\r\n\t\t// And make the starting replacement \r\n\t\treturn substr_replace(match, wrapped, start, end-start);\r\n\r\n\t}",
"static wrap(origin) {\n if (origin == null) {\n return origin;\n }\n if (origin.match(/\\b[-\\.]\\b/ig)\n || origin.match(/^(if|key|desc|length)$/i)) {\n return `\\`${origin}\\``;\n }\n return origin;\n }",
"isRangeCommented(state, range) {\n let textBefore = state.sliceDoc(range.from - SearchMargin, range.from);\n let textAfter = state.sliceDoc(range.to, range.to + SearchMargin);\n let spaceBefore = /\\s*$/.exec(textBefore)[0].length, spaceAfter = /^\\s*/.exec(textAfter)[0].length;\n let beforeOff = textBefore.length - spaceBefore;\n if (textBefore.slice(beforeOff - this.open.length, beforeOff) == this.open &&\n textAfter.slice(spaceAfter, spaceAfter + this.close.length) == this.close) {\n return { open: { pos: range.from - spaceBefore, margin: spaceBefore && 1 },\n close: { pos: range.to + spaceAfter, margin: spaceAfter && 1 } };\n }\n let startText, endText;\n if (range.to - range.from <= 2 * SearchMargin) {\n startText = endText = state.sliceDoc(range.from, range.to);\n }\n else {\n startText = state.sliceDoc(range.from, range.from + SearchMargin);\n endText = state.sliceDoc(range.to - SearchMargin, range.to);\n }\n let startSpace = /^\\s*/.exec(startText)[0].length, endSpace = /\\s*$/.exec(endText)[0].length;\n let endOff = endText.length - endSpace - this.close.length;\n if (startText.slice(startSpace, startSpace + this.open.length) == this.open &&\n endText.slice(endOff, endOff + this.close.length) == this.close) {\n return { open: { pos: range.from + startSpace + this.open.length,\n margin: /\\s/.test(startText.charAt(startSpace + this.open.length)) ? 1 : 0 },\n close: { pos: range.to - endSpace - this.close.length,\n margin: /\\s/.test(endText.charAt(endOff - 1)) ? 1 : 0 } };\n }\n return null;\n }",
"redact(parameters) {\n // Converted to a promise now\n let promise = this.$q((resolve, reject) => {\n // Setup and defaults\n let replacementChar = parameters.replacementChar || 'X';\n // Here is a little example of type checking variables and defaulting if it isn't as expected.\n let caseSensitive =\n typeof parameters.caseSensitive === typeof true\n ? parameters.caseSensitive\n : true;\n if (parameters.phrases === undefined || parameters.phrases.length === 0) {\n return parameters.inputText;\n }\n\n let phrases = parameters.phrases;\n let searchText = parameters.inputText;\n if (!caseSensitive) {\n phrases = parameters.phrases.map(p => p.toLowerCase());\n searchText = parameters.inputText.toLowerCase();\n }\n\n // loop through the phrases array\n let indicies = [];\n phrases.map(p => {\n // should just use for loop here now\n let pos = -1;\n do {\n pos = searchText.indexOf(p, pos + 1); // use the start index to reduce search time on subsequent searches\n if (pos === -1) break; // No more matches, abandon ship!\n // Track the starting index and length of the redacted area\n indicies.push({ index: pos, length: p.length });\n } while (pos != -1);\n });\n\n // Ok now go replace everything in the original text.\n // Overlapping phrases should be handled properly now.\n // we really need a splice method for strings\n // quick google search and guess what? There is an underscore string library ... neat! Now I don't have to write one.\n let redactedText = parameters.inputText;\n for (let i = 0, len = indicies.length; i < len; i++) {\n redactedText = _string.splice(\n redactedText,\n indicies[i].index,\n indicies[i].length,\n this.buildReplacement(replacementChar, indicies[i].length)\n );\n }\n\n // Go home strings, you're drunk\n resolve(redactedText);\n });\n return promise;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the FIPS for the given city in the state with the given info. | async function fetchCityFips(city, stateFips, stateAcronym) {
// Remove periods from city name (e.g. "St. Paul") for easier comparison
const removePeriodsRegex = /[\.]/g;
city = city.replace(removePeriodsRegex, '');
const fileName = 'states/st' + stateFips + '_' + stateAcronym.toLowerCase() + '_places.txt';
const url = chrome.runtime.getURL(fileName);
const response = await fetch(url);
const text = await response.text();
const regex = new RegExp(stateAcronym + '\\|' + stateFips + '\\|([0-9]+?)\\|' + city + '.*');
const lines = text.split("\n");
const matchingLines = [];
for (let line of lines) {
line = line.replace(removePeriodsRegex, '');
const matches = line.match(regex);
if (!matches || matches.length !== 2) {
continue;
}
matchingLines.push(line);
}
// If there are multiple matches, find the most preferential as ordered in PLACE_TYPES
for (let place of PLACE_TYPES) {
for (let line of matchingLines) {
if (line.includes(`${city} ${place}`)) {
return line.match(regex)[1];
}
}
}
// If none of the matches were in PLACE_TYPES, just return the first match
if (matchingLines.length > 0) {
const line = matchingLines[0];
return line.match(regex)[1];
}
console.log('Error: City FIPS not found');
return null;
} | [
"function change_city(findCity) {\n let apiURL = `https://api.openweathermap.org/data/2.5/weather?q=${findCity}&appid=${apiKey}&units=${units}`;\n axios.get(apiURL).then(ShowCityTemp);\n//this portion is for forecast\n apiURL = `https://api.openweathermap.org/data/2.5/forecast?q=${findCity}&appid=${apiKey}&units=${units}`;\n axios.get(apiURL).then(ShowForecast);\n\n}",
"function getZip(city, state)\n {\n var zip;\n \n $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + city + ',' + state + '&sensor=true', function(json)\n {\n console.log(json);\n \n zip = json.results[0].address_components[4].long_name;\n console.log(zip);\n \n //if the city and state are invalid, json.status = ZERO_RESULTS\n \n });\n \n return zip;\n \n }",
"function citySearch(cityInput) {\n let units = \"imperial\";\n let apiKey = \"2c3b195efbedc960ba063392d31bc9bd\";\n let apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${cityInput}&units=${units}&appid=${apiKey}`;\n axios.get(apiUrl).then(showWeather);\n}",
"function convertCityLatLong(inputCity){\n let directGeocodingAPI = 'https://api.openweathermap.org/geo/1.0/direct?q=' + inputCity + '&limit=5&appid=fe69a8ae1bfba9fa932a4b4358617cbf'\n fetch(directGeocodingAPI)\n .then(function(response){\n return response.json();\n })\n .then(function(data){\n var lat = data[0].lat\n var long = data[0].lon\n fiveDayForecastAPI(lat,long)\n })\n \n \n}",
"function getCityCurrent(){\n \n}",
"function searchCityAndGetWeather(){\n city = $(searchInput).val()\n getWeatherAndForecast()\n }",
"function cityFacts(city) {\n let output = city.name + \" has a population of \" + city.population + \" and is situated in \" + city.continent;\n console.log(output); // v\n return output;\n}",
"function formatLocation(city, state, country, zipCode) {\n return (\n city + \", \" + state + \" \" + zipCode + \" \" + country\n );\n}",
"function getTeleportCityInfo(city) {\n const link = city[`_links`][`city:item`][`href`];\n let cityDetails = ``;\n const general_settings = {\n url : link ,\n dataType : `json` ,\n type : `GET` ,\n async : false ,\n success : function(data) {\n cityDetails = getTeleportCityDetails(data);\n } ,\n error : failedSearch \n };\n $.ajax(general_settings);\n\n return cityDetails;\n }",
"getWeather (currentCity) {\n this.setState({ isLoading: ! this.state.isLoading })\n const apiKey = '1072dfe12c2f4f7e8ddfa30683df95ca';\n fetch(`https://api.weatherbit.io/v1.0/forecast/3hourly/geosearch?city=${currentCity}&days=1&key=${apiKey}`)\n .then( response => response.json())\n .then( response => {\n this.setState({ city: response.city_name,\n countryCode: response.country_code, \n items: response.data, \n error: false,\n temp: response.data[0].temp,\n isLoading: ! this.state.isLoading ,\n unit: 'C'})\n })\n //No response\n .catch( err => {\n this.setState({ error: true, isLoading: ! this.state.isLoading });\n })\n }",
"function baynote_fexp(tag) {\n\tvar city1 = baynote_getCommentTagValue(\"TravelHookOrig\");\n\tif (!city1){ return;}\n\n\tvar city2 = baynote_getCommentTagValue(\"TravelHookDest\");\n\tif (!city2){ return;}\n\n\ttag.url = BN_BASE_URL + \"/qscr=fexp/city1=\" + \n\t\t\t\tcity1 + \"/citd1=\" + city2 + \"/flag=q/rdct=1/\";\n}",
"async function cityFinder(city) {\n const date = await fetch(`https://geocode.xyz/${city}?json=1`)\n .then((response) => response.json())\n .then((data) =>\n console.log(`${city} : Longtitude: ${data.longt} Lattitude: ${data.latt}`)\n )\n .catch((onErr) => new Error(onErr));\n}",
"getPlaceInfo(pos) {\n\t\tlet venueID = '';\n\t\tlet lat = pos.lat, lng = pos.lng;\t\t\n\n\t\t//this fetch's purpose is to find the venueID of the given position\n\t\treturn fetch(`https://api.foursquare.com/v2/venues/search?client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}&v=${VERSION}&ll=${lat},${lng}`)\n\t\t .then(data => data.json())\n\t\t .then(data => {\n\t\t \tvenueID = data.response.venues[0].id;\n\t\t \treturn this.getPlaceTip(venueID);\n\t\t })\n\t\t .catch(function(e) {\n\t\t console.log(e);\n\t\t return null;\n\t\t });\t \n\t}",
"function fill_country_from_state(state_fld_name, country_fld_name) {\n\n var state_sel = '[name=\"' + state_fld_name + '\"]'\n var country_sel = '[name=\"' + country_fld_name + '\"]'\n $(document).on('blur', state_sel, function() {\n var country_ob = $(country_sel)\n // Only change country if there's nothing there yet.\n if (!country_ob.val()) {\n var state = $.trim($(state_sel).val().toLowerCase())\n var country = state_country_map[state]\n if (country != undefined) {\n country_ob.val(country);\n }\n }\n })\n}",
"static calculateShippingPrice(shippingAddress, productCost, shippingProvider, daysToDeliver) {\n return 42;\n }",
"function getTeleportCityDetails(data) {\n let cityDetails = {\n cityName : data.name ,\n closestUrbanCity : null ,\n fullName : data.full_name ,\n latLng : { lat : data[`location`][`latlon`][`latitude`] , lng : data[`location`][`latlon`][`longitude`] } ,\n geohash : data[`location`][`geohash`]\n };\n if (data[`_links`].hasOwnProperty(`city:urban_area`)) {\n cityDetails[`closestUrbanCity`] = data[`_links`][`city:urban_area`].name;\n }\n return cityDetails;\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 getCity(address) {\r\n\tvar lastCommaPos = address.lastIndexOf(\",\", address.length);\r\n\tvar firstCommaPos = address.indexOf(\",\");\r\n\tif (lastCommaPos != firstCommaPos)\r\n\t\treturn address.substring(firstCommaPos + 8, lastCommaPos);\r\n\telse\r\n\t\treturn address.substring(0, lastCommaPos);\r\n}",
"function loadCountyData(state, callback) {\n // for now let's always load the county data all at once. later we can again split\n // into single-state files if that turns out to be useful for performance.\n if(!countyData.has('USA')) {\n d3.json(\"data/county_boundaries_USA.json\", function(error, allCountiesTopo) {\n if(error) callback(error);\n \n // extract the topojson to geojson\n allCountiesGeo = topojson.feature(allCountiesTopo, allCountiesTopo.objects.counties);\n \n // cache in countyData\n countyData.set('USA', allCountiesGeo);\n \n cacheCountyData(state, callback);\n });\n } else {\n cacheCountyData(state, callback);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check to see if we should try to compress a file with gzip. | function shouldCompressGzip(req) {
const headers = req.headers;
return headers && headers['accept-encoding'] &&
headers['accept-encoding']
.split(',')
.some(el => ['*', 'compress', 'gzip', 'deflate'].indexOf(el.trim()) !== -1)
;
} | [
"function isGzip (buf) {\n if (!buf || buf.length < 3) return false\n\n return buf[0] === 0x1f && buf[1] === 0x8b && buf[2] === 0x08\n}",
"function gzipResponseHandler(request, response) {\n var urlPath = request.url.split('?')[0];\n var file = compressedFiles[ urlPath.replace('/base', '') ];\n\n if (!file) {\n log.error('Gzipped file not found: ' + request.url);\n throw new Error('Gzipped file not found: ' + request.url);\n }\n\n if (acceptsGzip(request)) {\n log.debug('found file, serving (gzip): ' + file.path);\n setGzipHeaders(response);\n response.writeHead(200);\n response.end(file.content);\n } else {\n // TODO: fix this — fall back to non-gzipped response\n log.error('Client does not accept gzipped responses');\n throw new Error();\n }\n}",
"function tryServeWithBrotli(shouldTryGzip) {\n fs.stat(brotliFile, (err, stat) => {\n if (!err && stat.isFile()) {\n file = brotliFile;\n serve(stat);\n } else if (shouldTryGzip) {\n tryServeWithGzip();\n } else {\n statFile();\n }\n });\n }",
"function isTar (buf) {\n if (!buf || buf.length < 262) return false\n\n return buf[257] === 0x75\n && buf[258] === 0x73\n && buf[259] === 0x74\n && buf[260] === 0x61\n && buf[261] === 0x72\n}",
"async function gzipAtomic(fileName, inputFile) {\n const tempPath = util_1.tempFile();\n await gunzip_1.default(tempPath, inputFile);\n return move_1.default(tempPath, fileName, { overwrite: true });\n}",
"function handleGzip(proxyRes, req, res) {\n res.write = (function(override) {\n return function(chunk, encoding, callback) {\n override.call(res, chunk, \"binary\", callback);\n };\n })(res.write);\n res.end = (function(override) {\n return function(chunk, encoding, callback) {\n override.call(res, chunk, \"binary\", callback);\n };\n })(res.end);\n }",
"function compress_dist() {\n try {\n fs.accessSync(DIST_DIR, fs.constants.R_OK);\n } catch (err) {\n return console.log(`Cannot compress. Directory ${DIST_DIR} not found.\\n`);\n }\n\n return gulp.src(`${DIST_DIR}/**`).pipe(tar(`${DIST_DIR}.tar`)).pipe(gzip()).pipe(gulp.dest(\".\"));\n}",
"visitLob_compression_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitKey_compression(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function zippedShapefile(file) {\n\n //Require .zip extension\n if (file.name.match(/[.]zip$/i)) {\n\n //Create form with file upload\n var formData = new FormData();\n formData.append(file.name.substring(file.name.length-3).toLowerCase(), file);\n\n if (file.size > 15000000) {\n if (currentFile.name) body.classed(\"blanked\",false);\n msg(\"shp-too-big\");\n uploadComplete();\n return true;\n }\n\n //Pass file to a wrapper that will cURL the real converter, gets around cross-domain\n //Once whole server is running on Node this won't be necessary\n d3.xhr(\"/convert/shp-to-geo/\").post(formData,function(error,response) {\n\n try {\n var newFile = {name: file.name.replace(/[.]zip$/i,\".geojson\"), size: response.responseText.length, data: {topo: null, geo: fixGeo(JSON.parse(response.responseText))}, type: \"geojson\"};\n } catch(err) {\n if (currentFile.name) body.classed(\"blanked\",false);\n msg(\"invalid-file\");\n uploadComplete();\n return false;\n }\n\n loaded(newFile);\n\n return true;\n\n\n });\n\n } else {\n if (currentFile.name) body.classed(\"blanked\",false);\n msg(\"invalid-file\");\n uploadComplete();\n\n }\n}",
"function requestAndZipFile(fileUrl, fileName, onBadResponse) {\r\n var fileSize = 0;\r\n zip.loadedLast = 0;\r\n zip.activeZipThreads++;\r\n\r\n fileName = zip.getValidIteratedName(removeDoubleSpaces(fileName.replace(/\\//g, ' ')));\r\n\r\n GM_xmlhttpRequest({\r\n method: 'GET',\r\n url: fileUrl,\r\n responseType: 'arraybuffer',\r\n binary: true,\r\n onload: function (res) {\r\n if (zip.file(fileName)) {\r\n console.warn('ZIP already contains the file: ', fileName);\r\n return;\r\n }\r\n try {\r\n console.debug(\r\n 'onload:' +\r\n '\\nreadyState: ' + res.readyState +\r\n '\\nresponseHeaders: ' + res.responseHeaders +\r\n '\\nstatus: ' + res.status +\r\n '\\nstatusText: ' + res.statusText +\r\n '\\nfinalUrl: ' + res.finalUrl +\r\n '\\nresponseText: ' + res.responseText.slice(0, 100) + '...'\r\n );\r\n } catch (e) {\r\n }\r\n\r\n if (typeof onBadResponse === 'function' && onBadResponse(res, fileUrl)) {\r\n zip.current++;\r\n return;\r\n }\r\n // you'll get a match like this: [\"content-type: image/png\", \"image\", \"png\"]\r\n const [fullMatch, mimeType1, mimeType2] = res.responseHeaders.match(/content-type: ([\\w]+)\\/([\\w\\-]+)/);\r\n const contentType = [mimeType1, mimeType2].join('/');\r\n var blob = new Blob([res.response], {type: contentType});\r\n const fileExtension = mimeTypesJSON.hasOwnProperty(contentType) && mimeTypesJSON[contentType] ?\r\n mimeTypesJSON[contentType].extensions[0] :\r\n mimeType2;\r\n\r\n console.debug('contentType:', contentType);\r\n zip.file(`${fileName.trim()}_${zip.current + 1}.${fileExtension}`, blob);\r\n console.log('Added file to zip:', fileName, fileUrl);\r\n zip.responseBlobs.add(blob);\r\n zip.current++;\r\n\r\n // if finished, stop\r\n if (zip.current < zip.zipTotal || zip.zipTotal <= 0) {\r\n return;\r\n }\r\n\r\n // Completed!\r\n if (zip.current >= zip.zipTotal - 1) {\r\n console.log('Generating ZIP...\\nFile count:', Object.keys(zip.files).length);\r\n zip.zipTotal = -1;\r\n if (zip.progressBar)\r\n zip.progressBar.destroy();\r\n zip.genZip();\r\n }\r\n zip.activeZipThreads--;\r\n },\r\n onreadystatechange: function (res) {\r\n console.debug('Request state changed to: ' + res.readyState);\r\n if (res.readyState === 4) {\r\n console.debug('ret.readyState === 4');\r\n }\r\n },\r\n onerror: function (res) {\r\n if (typeof onBadResponse === 'function' && onBadResponse(res, fileUrl)) {\r\n return;\r\n }\r\n\r\n console.error(`An error occurred.\r\nreadyState: ${res.readyState}\r\nresponseHeaders: ${res.responseHeaders}\r\nstatus: ${res.status}\r\nstatusText: ${res.statusText}\r\nfinalUrl: ${res.finalUrl}\r\nresponseText: ${res.responseText}`\r\n );\r\n zip.activeZipThreads--;\r\n },\r\n onprogress: function (res) {\r\n if (zip.files.hasOwnProperty(fileName) || zip.current < zip.zipTotal || zip.zipTotal <= 0) {\r\n //TODO: stop the GM_xmlrequest at this point\r\n /*if(res.abort)\r\n res.abort();\r\n else\r\n console.error('res.abort not defined');\r\n if(this.abort)\r\n this.abort();\r\n else\r\n console.error('this.abort not defined');\r\n return;*/\r\n }\r\n\r\n if (res.lengthComputable) {\r\n if (fileSize === 0) { // happens once\r\n fileSize = res.total;\r\n zip.totalSize += fileSize;\r\n }\r\n const loadedSoFar = res.loaded;\r\n const justLoaded = loadedSoFar - zip.loadedLast; // What has been added since the last progress call\r\n const fileprogress = loadedSoFar / res.total; //\r\n\r\n zip.totalLoaded += justLoaded;\r\n const totalProgress = zip.totalLoaded / zip.totalSize;\r\n\r\n if (false) {\r\n console.debug(\r\n 'loadedSoFar:', res.loaded,\r\n '\\njustLoaded:', loadedSoFar - zip.loadedLast,\r\n '\\nfileprogress:', loadedSoFar / res.total\r\n );\r\n }\r\n\r\n const progressText = `Files in ZIP: (${Object.keys(zip.files).length} / ${zip.zipTotal}) Active threads: ${zip.activeZipThreads} (${zip.totalLoaded} / ${zip.totalSize})`;\r\n if (typeof progressBar !== 'undefined') {\r\n progressBar.set(totalProgress);\r\n progressBar.setText(progressText);\r\n } else {\r\n var progressbarContainer = q('#progressbar-cotnainer');\r\n if (progressbarContainer) {\r\n progressbarContainer.innerText = progressText;\r\n }\r\n }\r\n\r\n zip.loadedLast = loadedSoFar;\r\n }\r\n }\r\n });\r\n }",
"function isGeoJSON(results, next) {\n var jsons = [];\n var max = results.length;\n var isMax = 0;\n results.forEach(function(file) {\n var parts = file.split('.');\n if (parts.length >= 3) {\n var ext = parts[parts.length -2];\n var ext2 = parts[parts.length -1]\n if ((ext.toLowerCase() === 'geo') && \n (ext2.toLowerCase() === 'json')) { jsons.push(file); };\n }\n isMax++;\n if (isMax === max) {\n if (jsons) next(null, jsons);\n else console.log(\"problem with isGeoJSON\");\n }\n });\n}",
"function onMetaDone(comprBytes, metaInfo) {\n self.metaCache[metaInfo.name] = comprBytes;\n var ArrType = cbUtil.makeType(metaInfo.arrType);\n\n var bytes = comprBytes; // some Apache/InternetBrowser combinations silently uncompress\n var comprView = new Uint8Array(comprBytes);\n // magic bytes of gzip are 1f, 8b, and we assume little endianess\n if (comprView[0]===0x1f && comprView[1]===0x8b) {\n try {\n bytes = pako.ungzip(comprBytes);\n }\n catch(err) {\n alert(\"Error when decompressing a file. This has to do with your Apache config or your \"+\n \" internet browser and incorrect compresssion http headers. \"+\n \"Please contact cells@ucsc.edu, we can help you solve this. \"+err);\n }\n }\n\n var buffer = bytes.buffer;\n var arr = new ArrType(buffer);\n if (metaInfo.arrType===\"float32\") {\n // numeric arrays have to be binned on the client. They are always floats.\n console.time(\"discretize \"+metaInfo.name);\n var discRes = discretizeArray(arr, self.exprBinCount, FLOATNAN);\n console.timeEnd(\"discretize \"+metaInfo.name);\n metaInfo.origVals = arr; // keep original values, so we can later query for them\n arr = discRes.dArr;\n metaInfo.binInfo = discRes.binInfo;\n //metaInfo.valCounts = binInfoToValCounts(discRes.binInfo);\n }\n onDone(arr, metaInfo, otherInfo);\n }",
"function shouldEmit(compiler, file, cache) {\n\tif (isNodeOutputFS(compiler)) {\n\t\ttry {\n\t\t\tconst src = fs.statSync(file);\n\t\t\tconst dest = fs.statSync(\n\t\t\t\tpath.join(compiler.options.output.path, transformPath(compiler.options.context, file))\n\t\t\t);\n\t\t\treturn src.isDirectory() || src.mtime.getTime() > dest.mtime.getTime() || !cache;\n\t\t} catch (e) {\n\t\t\treturn true;\n\t\t}\n\t} else {\n\t\treturn true;\n\t}\n}",
"function withZipFsPerform(callback, onerror) {\n\n if (_zipFs) {\n\n callback(_zipFs, onerror);\n\n } else {\n\n // The Web Worker requires standalone inflate/deflate.js files in libDir (i.e. cannot be aggregated/minified/optimised in the final generated single-file build)\n zip.useWebWorkers = true; // (true by default)\n zip.workerScriptsPath = libDir;\n \n _zipFs = new zip.fs.FS();\n _zipFs.importHttpContent(baseUrl, true, function () {\n\n callback(_zipFs, onerror);\n\n }, onerror)\n }\n }",
"function isFileTransfer(transfer) {\n return transfer.files.length > 0;\n}",
"function squish(compressors) {\n\t\tvar types = [];\n\n\t\tif (!compressors || !(compressors instanceof Array)) {\n\t\t\tthrow 'Invalid parameter. First argument must be an array.';\n\t\t}\n\n\t\tcompressors.forEach(function (compressor, i) {\n\t\t\tif (!compressor.type || typeof compressor.type !== 'string') {\n\t\t\t\tthrow 'Invalid compressor at index ' + i + '. The type property must be a string.';\n\t\t\t}\n\n\t\t\tif (!compressor.constructor || typeof compressor.constructor !== 'function') {\n\t\t\t\tthrow 'Invalid compressor at index ' + i + '. The compressor property must be a function.';\n\t\t\t}\n\n\t\t\t// make sure there aren't any spaces to begin with\n\t\t\tcompressor.type = compressor.type.trim();\n\n\t\t\ttypes.push(compressor.type);\n\t\t});\n\n\t\treturn function (req, res, next) {\n\t\t\tvar best,\n\t\t\t\tencodings = req.headers['accept-encoding'],\n\t\t\t\tidentity,\n\t\t\t\tmatchFound = false;\n\n\t\t\t// if the header is not set or if the header is *, the requester doesn't care\n\t\t\tif (typeof encodings === 'undefined' || encodings.trim() === '*') {\n\t\t\t\t// just use the first\n\t\t\t\tregisterCompressor(res, compressors[0]);\n\t\t\t\treturn next();\n\t\t\t} else if (encodings.trim() === '') {\n\t\t\t\t// the user obviously doesn't want our compression ='(\n\t\t\t\treturn next();\n\t\t\t}\n\n\t\t\tencodings = encodings.split(',');\n\n\t\t\t// fix up the encodings so I can read them\n\t\t\tencodings.forEach(function (encoding, i) {\n\t\t\t\tvar t = encoding.split(';'),\n\t\t\t\t\ttype = t[0].trim(),\n\t\t\t\t\tq = t[1] ? +t[1].split('=')[1] : 1;\n\n\t\t\t\tencodings[i] = {\n\t\t\t\t\t\"type\": type,\n\t\t\t\t\t\"q\": q\n\t\t\t\t};\n\n\t\t\t\t// special case for identity\n\t\t\t\tif (type === 'identity') {\n\t\t\t\t\tif (!identity || q === 0 || q > identity.q) {\n\t\t\t\t\t\tidentity = encodings[i];\n\t\t\t\t\t}\n\t\t\t\t} else if (type === '*' && q === 0 && !identity) {\n\t\t\t\t\tidentity = {\n\t\t\t\t\t\t'type': type,\n\t\t\t\t\t\t'q': q\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// see if we have a compressor that will work\n\t\t\tcompressors.some(function (compressor) {\n\t\t\t\tvar match;\n\n\t\t\t\tencodings.some(function (enc) {\n\t\t\t\t\t// quality control; first supported q=1 or highest supported q wins\n\t\t\t\t\tif (enc.type === compressor.type || enc.type === '*') {\n\t\t\t\t\t\tif (enc.q === 0) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (enc.q === 1) {\n\t\t\t\t\t\t\tmatch = enc.type;\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t} else if (!best || enc.q > best.q) {\n\t\t\t\t\t\t\tbest = compressor;\n\t\t\t\t\t\t\tbest.q = enc.q;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tif (match) {\n\t\t\t\t\tregisterCompressor(res, compressor)\n\t\t\t\t\tbest = undefined;\n\t\t\t\t\tmatchFound = true;\n\n\t\t\t\t\t// break out of the loop\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tif (best) {\n\t\t\t\tregisterCompressor(res, best);\n\t\t\t\tmatchFound = true;\n\t\t\t}\n\t\n\t\t\tif (!matchFound && identity && identity.q === 0) {\n\t\t\t\tres.writeHead(406, {\n\t\t\t\t\t'Content-Type': 'application/json'\n\t\t\t\t});\n\n\t\t\t\tres.end(JSON.stringify(types));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\treturn next();\n\t\t};\n\t}",
"is_image() {\n if (\n this.file_type == \"jpg\" ||\n this.file_type == \"png\" ||\n this.file_type == \"gif\"\n ) {\n return true;\n }\n return false;\n }",
"function isScriptFile(filename) {\n var ext = path.extname(filename).toLowerCase();\n return ext === '.js' || ext === '.json';\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
moves the object to the specified coordinates | moveTo(x, y) {
let coordinates = this.getXY();
this.x = x + coordinates.x;
this.y = y + coordinates.y;
} | [
"moveAround() {\r\n\r\n\r\n }",
"moveToStartingPosition() {\r\n this.currentLocation.x = this.startingPosition.x;\r\n this.currentLocation.y = this.startingPosition.y;\r\n }",
"move() {\n this.change = this.mouthGap == 0 ? -this.change : this.change;\n this.mouthGap = (this.mouthGap + this.change) % (Math.PI / 4) + Math.PI / 64;\n this.x += this.horizontalVelocity;\n this.y += this.verticalVelocity;\n }",
"placeAt(xx, yy, obj) {\r\n var xc = this.cw * xx + this.cw / 2;\r\n var yc = this.ch * yy + this.ch / 2;\r\n obj.x = xc;\r\n obj.y = yc;\r\n }",
"function moveOrigin(points, newOriginX, newOriginY){\n for(var i = 0; i<points.length; i+=2){\n points[i] -= newOriginX;\n points[i+1] -= newOriginY;\n }\n}",
"function moveToDoorLocation() {\n penUp();\n turnRight(24);\n moveForward(50);\n turnRight(90);\n moveForward(20);\n turnRight(90);\n penDown();\n}",
"function South() {\n props.setMoveLocation(true);\n props.setLocation((latMove -= 0.002), longMove);\n }",
"function moveOriginForPoints(points, newOriginX, newOriginY){\n for(var i = 0; i<points.length; i++){\n points[i].x -= newOriginX;\n points[i].y -= newOriginY;\n }\n}",
"function SetPositionObjectByOtherObject(objToubication, objReference,diffX,diffY)\n {\n \tvar posx = findPosX(objReference);\n\tvar posy = findPosY(objReference);\n\t\n\n\t\n\tnewposx = posx + diffX;\n\tnewposty = posy + diffY;\n\t\n\t\n\tobjToubication.style.left = newposx + 'px';\n\tobjToubication.style.top=newposty + 'px';\n\t\t\n\t\n }",
"function moveTo(position, value) {\r\n\t\tif (api.flip) value = 1 - value;\r\n\t\tcenter[api.orientation] = position[api.orientation] + ((0.5 - value) * api.size);\r\n\t}",
"move()\n\t{\n\t\t// For every SnakePart in the body array make the SnakePart take on\n\t\t// the direction and x- and y-coordinates of the SnakePart ahead\n\t\t// of it.\n\t\tfor (let index = this.length - 1; index > 0; index--)\n\t\t{\n\t\t\tthis.body[index].x = this.body[index - 1].x;\n\t\t\tthis.body[index].y = this.body[index - 1].y;\n\t\t\tthis.body[index].direction = this.body[index - 1].direction;\n\t\t}\n\n\t\t// In case the snake needs to teleport to other side of the grid...\n\t\tif (this.needsTeleport)\n\t\t{\n\t\t\t// ...assign the head of the snake new coordinates accordingly\n\t\t\t// based on its direction.\n\t\t\tswitch(this.body[0].direction)\n\t\t\t{\n\t\t\t\tcase \"UP\":\n\t\t\t\t{\n\t\t\t\t\tthis.body[0].y = canvas.height - tileSize;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"RIGHT\":\n\t\t\t\t{\n\t\t\t\t\tthis.body[0].x = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"DOWN\":\n\t\t\t\t{\n\t\t\t\t\tthis.body[0].y = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"LEFT\":\n\t\t\t\t{\n\t\t\t\t\tthis.body[0].x = canvas.width - tileSize;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// After its been assigned new coordinates, \n\t\t\t// it no longer needs be teleported.\n\t\t\tthis.needsTeleport = false;\n\t\t}\n\t\t// If not, then move snake head 1 tileSize in its direction.\n\t\telse\n\t\t{\n\t\t\tswitch(this.body[0].direction)\n\t\t\t{\n\t\t\t\tcase \"UP\":\n\t\t\t\t{\n\t\t\t\t\tthis.body[0].y -= tileSize;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"RIGHT\":\n\t\t\t\t{\n\t\t\t\t\tthis.body[0].x += tileSize;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"DOWN\":\n\t\t\t\t{\n\t\t\t\t\tthis.body[0].y += tileSize;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"LEFT\":\n\t\t\t\t{\n\t\t\t\t\tthis.body[0].x -= tileSize;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// If the Tile at the snake head's new position \n\t\t// contains a food item then eat it.\n\t\tif (this.body[0].tile.element == \"FOOD\")\n\t\t{\n\t\t\tthis.eatFood();\n\t\t}\n\t}",
"function moveAll() {\n moveClouds();\n \n // check is screen needs to move - move if necesary\n checkScreenBoundaries();\n \n // move all objects\n for(var i = 0; i < objects.length; i++){\n objects[i].move();\n }\n}",
"function moveBeam(x, y) {\n\n var dx = x - beam.x;\n var dy = y - beam.y;\n\n beam.body.moveRight(dx * 10);\n beam.body.moveDown(dy * 10);\n}",
"turnAround() {\n this.left(180);\n }",
"move(direction) {\r\n\t\tlet somethingChanged = this.moveMap(direction);\r\n\t\tif (somethingChanged) {\r\n\t\t\tthis.spawnNew();\r\n\t\t}\r\n\t}",
"press(x,y) {\n this.pressing = true;\n this.moveLinear(x,y-100,x,y);\n }",
"move() {\n //this.xVel += xVel;\n this.x = this.x + this.xVel;\n this.y = this.y + this.yVel;\n this.checkWalls();\n this.checkBalls();\n }",
"move3d(x1, y1, z1)\n {\n this.x=x1; this.y=y1; this.z=z1;\n this.rotate();\n\n this.cx=Math.floor(this.x);\n this.cy=Math.floor(this.y);\n }",
"function MoveEvent(oldX, oldY, x, y) {\n _super.call(this, 'move');\n this._m_oldX = oldX;\n this._m_oldY = oldY;\n this._m_x = x;\n this._m_y = y;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Construct a new session. id Session id, used for error reporting config Queue server configuration, used to establish connection notify Logging and errors setup The setup function, see below Beanstalkd requires setup to either use or watch a tube, depending on the session. The setup function is provided when creating the session, and is called after the connection has been established (and for Iron.io, authenticated). The setup function is called with two arguments: client Fivebeans client being setup callback Call with error or nothing | constructor(server, id, setup) {
this.id = id;
this.setup = setup;
this._config = server.config;
this._notify = server.notify;
this._connectPromise = null;
} | [
"function setupSessionController() {\n\n\tvar self = this;\n\tvar priv = PRIVATE.get(this);\n\n\t\n\tlogger.debug(\"connecting to Redis endpoint \" + JSON.stringify(priv.redis));\n\tpriv.redisClient = RedisConnection(\"DEFAULT\", priv.redis);\n\n\tpriv.redisClient.on(\"error\", function (err) {\n\t\tlogger.error(\"Redis connection Error : \" + err);\n\t});\n\tlogger.info(\"connected to redis.\");\n\n\t// setup redis-smq producer\n\tpriv.redissmqConfig = new RedisSMQConfig(priv.redis.host, priv.redis.port, \"0.0.0.0\", 4002);\n\tlogger.debug(\"Reliable queue config: \", JSON.stringify(priv.redissmqConfig.getConfig()));\n\tpriv.syncCrtlQProducer = new Producer(kSyncControllerQueueKey, priv.redissmqConfig.getConfig()); \n\n\t// priv.syncCrtlQMonitor = new Monitor(priv.redissmqConfig.getConfig());\n\n\tmonitor(priv.redissmqConfig.getConfig()).listen(()=>{\n\t\tlogger.info(\"SyncController Queue monitor running on port 4002\");\n\t});\n\n\n\tpriv.msgAdapter = new MessagingAdapter(priv.mosquitto.host, priv.mosquitto.port, \"sessioncontroller_\" + uuidv4());\n\tpriv.msgAdapter.on(\"connectionestablished\", handleAdapterConnected.bind(null, priv.mosquitto));\n\tpriv.msgAdapter.on(\"connectionfailure\", handleAdapterConnectionFailure);\n\t\t\n\t\t\n\tpriv.messenger = new Messenger(priv.msgAdapter);\n\tpriv.messenger.on(\"request\", handleIncomingRequest.bind(self));\n\tpriv.messenger.on(\"message\", handleIncomingMessage.bind(self));\n\t\t\n\t\n\tpriv.messenger.listen(priv.onBoardingChannel);\n\tpriv.channels.push(priv.onBoardingChannel);\n\t\t\n\tlogger.info(\"Listening to requests on channel: \", priv.onBoardingChannel);\n\n\tpriv.sessionREQTopic = kSessionREQTopic;\n\tpriv.sessionRESPTopic = kSessionRESPTopic;\n\tpriv.sessionLastWillTopic = kSessionLastWillTopic;\n\n\tpriv.messenger.listen(kSessionREQTopic);\n\tpriv.channels.push(kSessionREQTopic);\n\tpriv.messenger.listen(kSessionRESPTopic);\n\tpriv.channels.push(kSessionRESPTopic);\n\tpriv.messenger.listen(kSessionLastWillTopic);\n\tpriv.channels.push(kSessionLastWillTopic);\n\t\t\n\tlogger.info(\"SessionController listening to session REQ channel:\", kSessionREQTopic);\n\tlogger.info(\"SessionController listening to session RESP channel:\", kSessionRESPTopic);\n\tlogger.info(\"SessionController listening to session lastwill channel:\", kSessionLastWillTopic);\n\n\treturn Promise.resolve(true);\t\n}",
"function sessionSetup(req, res, next){\n console.log(req.cookies.sid);\n if (req.cookies.sid === undefined){\n var uuid = uuidv4();\n var isAuthenticated = false;\n var id = false;\n var email = false;\n var username = false;\n var src = false;\n var client = redis.createClient();\n client.HMSET(uuid, {\n \"isAuthenticated\": isAuthenticated,\n \"id\": id,\n \"email\": email,\n \"username\": username,\n \"src\": src,\n \"sid\": uuid,\n \"videoCreated\": false,\n \"videoUpdated\": false,\n \"videoDeleted\": false,\n \"userCreated\": false,\n \"userUpdated\": false,\n }, function(){\n client.quit();\n req.session = {\n \"isAuthenticated\": isAuthenticated,\n \"id\": id,\n \"email\": email,\n \"username\": username,\n \"src\": src,\n \"sid\": uuid,\n \"videoCreated\": false,\n \"videoUpdated\": false,\n \"videoDeleted\": false,\n \"userCreated\": false,\n \"userUpdated\": false,\n }\n res.cookie('sid', uuid, { signed: false, maxAge: 60 * 1000, httpOnly: true });\n next();\n });\n } else {\n var client = redis.createClient();\n client.hgetall(req.cookies.sid, function (err, obj) {\n req.session = obj;\n client.quit();\n next();\n });\n\n\n }\n}",
"_buildClient() {\n var metadata = (0, _frames.encodeFrame)({\n type: _frames.FrameTypes.DESTINATION_SETUP,\n majorVersion: null,\n minorVersion: null,\n group: this._config.setup.group,\n tags: this._tags,\n accessKey: this._accessKey,\n accessToken: this._accessToken,\n connectionId: this._connectionId,\n additionalFlags: this._additionalFlags\n });\n var transport = this._config.transport.connection !== undefined ? this._config.transport.connection : new _rsocketWebsocketClient.default({\n url: this._config.transport.url ? this._config.transport.url : 'ws://',\n wsCreator: this._config.transport.wsCreator\n }, _rsocketCore.BufferEncoders);\n var responder = this._config.responder || new _rsocket.UnwrappingRSocket(this._requestHandler);\n var finalConfig = {\n setup: {\n keepAlive: this._keepAlive,\n lifetime: this._lifetime,\n metadata,\n connectionId: this._connectionId,\n additionalFlags: this._additionalFlags\n },\n transport,\n responder\n };\n\n if (this._config.serializers !== undefined) {\n finalConfig.serializers = this._config.serializers;\n }\n\n this._client = new _FlowableRpcClient.default(finalConfig);\n }",
"async function createSession() {\n const idvClient = new IDVClient(config.YOTI_CLIENT_SDK_ID, config.YOTI_PEM);\n\n const sessionSpec = new SessionSpecificationBuilder()\n .withClientSessionTokenTtl(600)\n .withResourcesTtl(90000)\n .withUserTrackingId('some-user-tracking-id')\n // For zoom liveness check [only one type of liveness check to be enabled at a time]\n .withRequestedCheck(new RequestedLivenessCheckBuilder()\n .forZoomLiveness()\n .build())\n // For static liveness check\n // .withRequestedCheck(\n // new RequestedLivenessCheckBuilder()\n // .forStaticLiveness()\n // .build()\n // )\n .withRequestedCheck(new RequestedFaceComparisonCheckBuilder()\n .withManualCheckNever()\n .build())\n .withSdkConfig(new SdkConfigBuilder()\n .withSuccessUrl(`${config.YOTI_APP_BASE_URL}/success`)\n .withErrorUrl(`${config.YOTI_APP_BASE_URL}/error`)\n .withPrivacyPolicyUrl(`${config.YOTI_APP_BASE_URL}/privacy-policy`)\n .withJustInTimeBiometricConsentFlow() // or withEarlyBiometricConsentFlow()\n .build())\n .build();\n\n return idvClient.createSession(sessionSpec);\n}",
"startNew(options) {\n let serverSettings = this.serverSettings;\n return session_1.Session.startNew(Object.assign({}, options, { serverSettings })).then(session => {\n this._onStarted(session);\n return session;\n });\n }",
"function sessionIdCreator() {\r\n let idLength = 8;\r\n sessionStorage.userType = 1;\r\n let chars = \"abcdefghijklmnopqrstuvwxyz1234567890\";\r\n for (let x = 0; x < idLength; x++) {\r\n let i = Math.floor(Math.random() * chars.length);\r\n sessionId += chars.charAt(i);\r\n }\r\n sessionStorage.sessionId = sessionId;\r\n}",
"_initSessionWatchdogs() {\n // test messages\n\n this._sessionTestMessagesWatchdog = new Watchdog();\n this._sessionTestMessagesWatchdog.debug = this.debug;\n this._sessionTestMessagesWatchdog.name = 'test-messages';\n this._sessionTestMessagesWatchdog.timeout =\n this.extraTestTimeout + parseFloat(this._impTestFile.values.timeout);\n\n this._sessionTestMessagesWatchdog.on('timeout', () => {\n this._onError(new Errors.SesstionTestMessagesTimeoutError());\n this._session.stop = this._stopSession;\n });\n\n // session start\n\n this._sessionStartWatchdog = new Watchdog();\n this._sessionStartWatchdog.debug = this.debug;\n this._sessionStartWatchdog.name = 'session-start';\n this._sessionStartWatchdog.timeout = this.sessionStartTimeout;\n\n this._sessionStartWatchdog.on('timeout', () => {\n this._onError(new Errors.SessionStartTimeoutError());\n this._session.stop = this._stopSession;\n });\n\n this._sessionStartWatchdog.start();\n }",
"function buildInitialSession() {\n const session = {\n start: Date.now(),\n currentState: 'notebook',\n projectId: '',\n currentStateParams: {}\n };\n\n\n // session.currentStateParams.user = '';\n // session.currentStateParams.corpus = 'default';\n\n\n return new Promise((resolve, reject) => {\n Session.insert(session, (err, data) => {\n if (err) {\n console.log('Error creating initial session', err);\n reject(err)\n }\n resolve(data)\n })\n });\n\n}",
"function SetupClient ()\n{\n client.registry.registerDefaults ();\n client.registry.registerGroups ([\n [\"bot\", \"Bot\"],\n [\"user\", \"User\"],\n [\"admin\", \"Admin\"],\n [\"social\", \"Social\"],\n [\"search\", \"Search\"],\n [\"random\", \"Random\"],\n [\"utility\", \"Utility\"],\n [\"reaction\", \"Reaction\"],\n [\"decision\", \"Decision\"],\n ]);\n client.registry.registerCommandsIn (__dirname + \"/Commands\");\n\n client.commandPrefix = config.Prefix;\n\n LogClient ();\n}",
"function createSessionFromTemplate(templatePartialPath, options) {\n\toptions = options || {};\n\tconst syncServerUrl = options.server || 'http://localhost:3000';\n\n\tconst reqOptions = {\n\t\turl: urlJoin(syncServerUrl, 'api/session'),\n\t\tmethod: 'POST',\n\t\tdata: {\n\t\t\ttemplate: {\n\t\t\t\tname: path.basename(templatePartialPath, path.extname(templatePartialPath)),\n\t\t\t\tpath: path.dirname(templatePartialPath)\n\t\t\t}\n\t\t}\n\t};\n\tif (options.environment) {\n\t\treqOptions.data.environment = options.environment;\n\t}\n\tif (options.actorTags) {\n\t\treqOptions.data.actorTags = options.actorTags;\n\t}\n\tif (options.sessionLabel) {\n\t\treqOptions.data.sessionLabel = options.sessionLabel;\n\t}\n\n\treturn new Promise(function (resolve, reject) {\n\t\taxios(reqOptions)\n\t\t\t.then(function (res) {\n\t\t\t\tconst sessionId = res.data.sessionId;\n\t\t\t\tconsole.log(\"Started test session \" + sessionId);\n\t\t\t\tresolve(sessionId);\n\t\t\t})\n\t\t\t.catch(function (err) {\n\t\t\t\tconsole.log('Error: ', err.message);\n\t\t\t\tif (err.response && err.response.data) {\n\t\t\t\t\tconsole.log('Response payload: ', err.response.data);\n\t\t\t\t}\n\t\t\t\treject(err);\n\t\t\t});\n\t});\n}",
"connect(){\n // add a session\n App.core.use(bodyParser.urlencoded({extended: true}));\n App.core.use(bodyParser.json());\n App.core.use(cookieParser());\n\n // init store\n this.config.store = new sessionStore({\n database: App.db.connection, // there will be stablished connection in lazyLoad mode\n sessionModel: App.db.models.sessions,\n transform: function (data) {\n return data;\n },\n ttl: (60 * 60 * 24),\n autoRemoveInterval: (60 * 60 * 3)\n });\n\n // run session \n App.core.use(session(this.config));\n }",
"function setupClient() {\n _client = new signalR.client(\n settingsHelper.settings.hubUri + '/signalR',\n ['integrationHub'],\n 10, //optional: retry timeout in seconds (default: 10)\n true\n );\n\n // Wire up signalR events\n /* istanbul ignore next */\n _client.serviceHandlers = {\n bound: function () {\n log(\"Connection: \" + \"bound\".yellow);\n },\n connectFailed: function (error) {\n log(\"Connection: \" + \"Connect Failed: \".red + error.red);\n let faultDescription = \"Connect failed from mSB.com. \" + error;\n let faultCode = '00098';\n trackException(faultCode, faultDescription);\n microServiceBusNode.ReportEvent(faultDescription);\n settingsHelper.isOffline = true;\n },\n connected: function (connection) {\n let connectTime = new Date().getTime();\n if (_lastConnectedTime) {\n if (connectTime - _lastConnectedTime < 3000) {\n log(\"Reconnection loop detected. Restarting\");\n microServiceBusNode.ReportEvent(\"Reconnection loop detected\");\n restart();\n return;\n }\n }\n _lastConnectedTime = connectTime;\n log(\"Connection: \" + \"Connected\".green);\n\n if (!settingsHelper.settings.policies) {\n settingsHelper.settings.policies = {\n \"disconnectPolicy\": {\n \"heartbeatTimeout\": 120,\n \"missedHearbeatLimit\": 3,\n \"disconnectedAction\": \"RESTART\",\n \"reconnectedAction\": \"NOTHING\",\n \"offlineMode\": true\n }\n };\n }\n _signInState = \"INPROCESS\";\n microServiceBusNode.settingsHelper = settingsHelper;\n if (settingsHelper.isOffline) { // We are recovering from offline mode\n log('Connection: *******************************************'.bgGreen.white);\n log('Connection: RECOVERED FROM OFFLINE MODE...'.bgGreen.white);\n log('Connection: *******************************************'.bgGreen.white);\n settingsHelper.isOffline = false;\n _missedHeartBeats = 0;\n _lastHeartBeatReceived = true;\n\n\n switch (settingsHelper.settings.policies.disconnectPolicy.reconnectedAction) {\n case \"UPDATE\":\n microServiceBusNode.Stop(function () {\n microServiceBusNode.SignIn(_existingNodeName, _temporaryVerificationCode, _useMacAddress, false);\n });\n break;\n case \"NOTHING\":\n microServiceBusNode.SignIn(_existingNodeName, _temporaryVerificationCode, _useMacAddress, true);\n _signInState = \"SIGNEDIN\";\n default:\n break;\n }\n }\n else {\n microServiceBusNode.SignIn(_existingNodeName, _temporaryVerificationCode, _useMacAddress, null, _useAssert);\n }\n microServiceBusNode.ReportEvent(\"Connected to mSB.com\");\n startVulnerabilitiesScan();\n },\n disconnected: function () {\n\n log(\"Connection: \" + \"Disconnected\".yellow);\n let faultDescription = 'Node has been disconnected.';\n let faultCode = '00098';\n trackException(faultCode, faultDescription);\n microServiceBusNode.ReportEvent(\"Disconnected from mSB.com\");\n settingsHelper.isOffline = true;\n },\n onerror: function (error) {\n log(\"Connection: \" + \"Error: \".red, error);\n\n if (!error) {\n return;\n }\n\n let faultDescription = error;\n let faultCode = '00097';\n trackException(faultCode, faultDescription);\n\n try {\n if (error.endsWith(\"does not exist for the organization\")) {\n if (self.onStarted)\n self.onStarted(0, 1);\n }\n }\n catch (e) { }\n },\n onUnauthorized: function (error) {\n log(\"Connection: \" + \"Unauthorized: \".red, error);\n },\n messageReceived: function (message) {\n //console.log(\"Connection: \" + \"messageReceived: \".yellow + message.utf8Data);\n },\n bindingError: function (error) {\n log(\"Connection: \" + \"Binding Error: \".red + error);\n // Check if on offline mode\n if ((error.code === \"ECONNREFUSED\" || error.code === \"EACCES\" || error.code === \"ENOTFOUND\") &&\n !settingsHelper.isOffline &&\n settingsHelper.settings.offlineSettings) {\n\n log('*******************************************'.bgRed.white);\n log('SIGN IN OFFLINE...'.bgRed.white);\n log('*******************************************'.bgRed.white);\n\n settingsHelper.isOffline = true;\n\n microServiceBusNode.SignInComplete(settingsHelper.settings.offlineSettings);\n }\n startHeartBeat();\n },\n connectionLost: function (error) { // This event is forced by server\n log(\"Connection: \" + \"Connection Lost\".red);\n },\n reconnected: function (connection) {\n // This feels like it would be a good idea, but I have't got around to test it...\n // _client.invoke('integrationHub', 'reconnected', settingsHelper.settings.id);\n log(\"Connection: \" + \"Reconnected \".green);\n },\n reconnecting: function (retry /* { inital: true/false, count: 0} */) {\n log(\"Connection: \" + \"Retrying to connect (\".yellow + retry.count + \")\".yellow);\n return true;\n }\n };\n\n // Wire up signalR inbound events handlers\n _client.on('integrationHub', 'errorMessage', function (message, errorCode) {\n OnErrorMessage(message, errorCode);\n });\n _client.on('integrationHub', 'ping', function (message) {\n OnPing(message);\n });\n _client.on('integrationHub', 'getEndpoints', function (message) {\n OnGetEndpoints(message);\n });\n _client.on('integrationHub', 'updateItinerary', function (updatedItinerary) {\n OnUpdateItinerary(updatedItinerary);\n });\n _client.on('integrationHub', 'changeState', function (state) {\n OnChangeState(state);\n });\n _client.on('integrationHub', 'changeDebug', function (debug) {\n OnChangeDebug(debug);\n });\n _client.on('integrationHub', 'changeTracking', function (enableTracking) {\n OnChangeTracking(enableTracking);\n });\n _client.on('integrationHub', 'sendMessage', function (message, destination) {\n OnSendMessage(message, destination);\n });\n _client.on('integrationHub', 'signInMessage', function (response) {\n OnSignInMessage(response);\n });\n _client.on('integrationHub', 'nodeCreated', function (nodeData) {\n OnNodeCreated(nodeData);\n });\n _client.on('integrationHub', 'heartBeat', function (id) {\n log(\"Connection: Heartbeat received\".grey);\n _missedHeartBeats = 0;\n _lastHeartBeatReceived = true;\n\n });\n _client.on('integrationHub', 'forceUpdate', function () {\n log(\"forceUpdate\".red);\n restart();\n });\n _client.on('integrationHub', 'restart', function () {\n log(\"restart\".red);\n restart();\n });\n _client.on('integrationHub', 'reboot', function () {\n log(\"reboot\".red);\n reboot();\n });\n _client.on('integrationHub', 'shutdown', function () {\n log(\"shutdown\".red);\n shutdown();\n });\n _client.on('integrationHub', 'refreshSnap', function (snap, mode, connId) {\n log(\"Refreshing snap \".yellow + snap.gray);\n log(`devmode = ${snap.indexOf(\"microservicebus\") === 0}`);\n OnRefreshSnap(snap, mode, connId);\n });\n _client.on('integrationHub', 'reset', function (id) {\n OnReset(id);\n });\n _client.on('integrationHub', 'resetKeepEnvironment', function (id) {\n OnResetKeepEnvironment(id);\n });\n _client.on('integrationHub', 'updateFlowState', function (itineraryId, environment, enabled) {\n OnUpdateFlowState(itineraryId, environment, enabled);\n });\n _client.on('integrationHub', 'enableDebug', function (connId) {\n OnEnableDebug(connId);\n });\n _client.on('integrationHub', 'stopDebug', function (connId) {\n OnStopDebug();\n });\n _client.on('integrationHub', 'reportState', function (id) {\n OnReportState(id);\n });\n _client.on('integrationHub', 'uploadSyslogs', function (connectionId, fileName, account, accountKey) {\n OnUploadSyslogs(connectionId, fileName, account, accountKey);\n });\n _client.on('integrationHub', 'resendHistory', function (req) {\n OnResendHistory(req);\n });\n _client.on('integrationHub', 'requestHistory', function (req) {\n OnRequestHistory(req);\n });\n _client.on('integrationHub', 'transferToPrivate', function (req) {\n OnTransferToPrivate(req);\n });\n _client.on('integrationHub', 'updatedToken', function (token) {\n OnUpdatedToken(token);\n });\n _client.on('integrationHub', 'updateFirmware', function (force, connid) {\n OnUpdateFirmware(force, connid);\n });\n _client.on('integrationHub', 'grantAccess', function () {\n OnGrantAccess();\n });\n _client.on('integrationHub', 'runTest', function (testDescription) {\n OnRunTest(testDescription);\n });\n _client.on('integrationHub', 'pingNodeTest', function (connid) {\n OnPingNodeTest(connid);\n });\n _client.on('integrationHub', 'updatePolicies', function (policies) {\n OnUpdatePolicies(policies);\n });\n _client.on('integrationHub', 'setBootPartition', function (partition, connid) {\n OnSetBootPartition(partition, connid);\n });\n _client.on('integrationHub', 'executeScript', function (patchScript, connid) {\n OnExecuteScript(patchScript, connid);\n });\n }",
"function initializeOpcuaClient(){\n client = new OPCUAClient({keepSessionAlive:true});\n client.connect(\"opc.tcp://\" + os.hostname() + \":\" + port, onClientConnected);\n}",
"constructor(hostname, stage, origin, apikey)\n {\n if (!hostname && !(\"INOMIAL_HOSTNAME\" in process.env))\n throw new Error(\"No hostname given (INOMIAL_HOSTNAME is unset)\");\n\n hostname = hostname || process.env.INOMIAL_HOSTNAME;\n stage = stage || process.env.INOMIAL_STAGE || \"live\";\n apikey = apikey || process.env.INOMIAL_APIKEY;\n\n this.clientConfig = websocketClientConfig;\n\n // If the connection is down, queries are added to this queue.\n // When the connection comes back up, the queries are executed.\n this.requestQueue = [];\n\n // Set of outstanding queries, indexed by request ID.\n this.responseQueue = {};\n\n // Request ID generator.\n this.nextRequestId = 1000000;\n\n // URL We'll be connecting to.\n this.url = \"wss://\" + hostname + \"/\" + stage + \"/api/events\";\n\n // WSS Origin header, for non-browser clients.\n this.origin = origin;\n\n // API key, for non-browser clients. Browser clients will inherit the\n // HTTP session credentials.\n this.apikey = apikey;\n\n // The connection will be set once we connect.\n this.connection = null;\n\n // USN caches for accounts and subscriptions\n this.accountUuidCache = {};\n this.subscriptionUuidCache = {};\n\n this.reconnectPolicy = false;\n }",
"function initializeTokboxSession() {\n session = OT.initSession(projectAPIKey, sessionID);\n session.on('sessionDisconnected', (event) => {\n console.log('You were disconnected from the session.', event.reason);\n });\n\n // Connect to the session\n session.connect(token, (error) => {\n if (error) {\n handleError(error);\n }\n });\n}",
"function setSSIDCookie(req, res) {\n // res.cookie('ssid', id, { httpOnly: true });\n //when we get a new user, we get a new SSID cookie with userID\n //then we create a session with the cookie/ssid id\n sessionController.startSession(req.newSSID);\n \n}",
"function mqtt_setup(clientid, topiclist, handlerfunc, errorfunc) {\n if (typeof mqtt_setup.topiclist == 'undefined') {\n // initialize\n mqtt_setup.topiclist = [];\n\n\t\tmqtt_setup.clientid = clientid;\n\t\tmqtt_setup.handlerfunc = handlerfunc;\n\t\tmqtt_setup.errorfunc = errorfunc;\n\n for (n in topiclist) {\n mqtt_setup.topiclist.push(topiclist[n]);\n }\n\n }\n}",
"create(params) {\n return __awaiter(this, void 0, void 0, function* () {\n const session = new session_1.Session();\n this.sessions.set(params.launchId, session);\n session.onClose(() => this.sessions.delete(params.launchId));\n session.onError(err => {\n vscode.window.showErrorMessage(`Error running browser: ${err.message || err.stack}`);\n this.sessions.delete(params.launchId);\n });\n yield Promise.all([\n this.addChildSocket(session, params),\n params.attach\n ? this.addChildAttach(session, params.attach)\n : this.addChildBrowser(session, params),\n ]);\n });\n }",
"function createSession(username){\n var now = Date.now();\n sessions.set(username, now);\n console.log('session created for ' + username);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Render a chart visual on dashboard page for tracking class visits by date | function drawBasic() {
// Set up the data table to have a class name and visits associated w/ that specific class
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Visits');
// Organize visit data through visit-by-date servlet
getToken().then(tok => {
fetch(`/visit-date?classCode=${getParam("classCode")}&idToken=${tok}`)
.then(response => response.json()).then(visits=> {
var dates = visits.dates;
// Convert JSON date format to Date type
for (var k = 0; k < dates.length; k++) {
var dateStr = dates[k];
var realDate = new Date(dateStr);
dates[k] = realDate;
}
var numVisits = visits.classVisits;
var tempDataHolder = []; // To be pushed into datatable after updating
// Loop through both lists and add info sets for each class
for (var i = 0; i < dates.length; i++) {
tempDataHolder.push([dates[i], numVisits[i]]);
}
data.addRows(tempDataHolder); // Populate datatable with final data
var options = {
title: 'Number of Student Office Hour Visits',
hAxis: {
format: 'M/d/yy',
title: 'Date',
textStyle: {
bold:true
},
},
vAxis: {
title: 'Number of Visits',
textStyle: {
bold:true
},
},
backgroundColor: {
fill: '#D6EBFF',
stroke: '#031430',
strokeWidth: 5
},
};
var chart = new google.visualization.LineChart(
document.getElementById("visit-chart"));
chart.draw(data, options);
});
});
} | [
"function drawTime() {\n\n // Set up the data table to have a class name and wait average associated w/ that specific class\n var data = new google.visualization.DataTable();\n data.addColumn('date', 'Date');\n data.addColumn('number', 'Wait');\n \n // Organize wait data through wait-time servlet\n getToken().then(tok => {\n fetch(`/wait-time?classCode=${getParam(\"classCode\")}&idToken=${tok}`)\n .then(response => response.json()).then(waits=> {\n \n var dates = waits.dates;\n\n // Convert JSON date format to Date type\n for (var k = 0; k < dates.length; k++) {\n var dateStr = dates[k];\n var realDate = new Date(dateStr);\n dates[k] = realDate;\n }\n\n var waitAverages = waits.waitTimes;\n\n // Convert all times to minutes\n for (var j = 0; j < waitAverages.length; j++) {\n var timeInSeconds = waitAverages[j];\n var timeInMinutes = timeInSeconds / 60.0;\n waitAverages[j] = timeInMinutes.toFixed(2); // Round to 2 decimal places\n }\n\n var tempDataHolder = []; // To be pushed into datatable after updating\n\n // Loop through both lists and add info sets for each class \n for (var i = 0; i < dates.length; i++) {\n tempDataHolder.push([dates[i], Number(waitAverages[i])]);\n }\n \n data.addRows(tempDataHolder); // Populate datatable with final data\n\n var options = {\n title: 'Average Wait Time by Date',\n hAxis: {\n format: 'M/d/yy',\n title: 'Date',\n textStyle: {\n bold:true\n },\n },\n vAxis: {\n title: 'Wait Time (minutes)',\n format: '0.00',\n textStyle: {\n bold:true\n },\n },\n backgroundColor: {\n fill: '#D6EBFF',\n stroke: '#031430',\n strokeWidth: 5\n },\n };\n\n const waitChart = document.getElementById(\"wait-chart\");\n waitChart.classList.remove(\"hidden\");\n var chart = new google.visualization.LineChart(waitChart);\n\n chart.draw(data, options);\n waitChart.classList.add(\"hidden\");\n });\n });\n}",
"function renderChartStatistics() {\n //we only want to draw the chart once.\n //populate data for the chart.\n populateChartNames();\n populateVotes();\n populateViews();\n if(!chartDrawn){\n drawChart();\n showChart();\n console.log('chart was drawn');\n }else{\n imageChart.update();\n showChart();\n }\n}",
"function drawCategoryChart() {\n\t\n\tvar entertainmentnum = 0\n\tvar productivitynum = 0\n\tvar othernum = 0\n\tvar shoppingnum = 0\n\tvar data\n\tif(!useDateRangeSwitch)\n\t\tdata = listSiteData(globsiteData)\n\telse \n\t\tdata = listSiteData(dateRangeData)\n\n\tfor (i=1; i<data.length; i++){\n\t\ttemp = String(data[i][0]).trim()\n\t\tif(globCategoriesHostname.includes(temp)){\n\t\t\tif(globCategoriesCategory[globCategoriesHostname.indexOf(temp)].trim() === \"Entertainment\")\n\t\t\t\tentertainmentnum += data[i][1]\n\t\t\telse if(globCategoriesCategory[globCategoriesHostname.indexOf(temp)].trim() === \"Productivity\")\n\t\t\t\tproductivitynum+=data[i][1]\n\t\t\telse if(globCategoriesCategory[globCategoriesHostname.indexOf(temp)].trim() === \"Shopping\")\n\t\t\t\tshoppingnum+=data[i][1]\n\t\t}\n\t\telse \n\t\t\tothernum+=data[i][1]\n\t}\n\tvar catData = [\n\t\t['Task', 'Hours per Day'],\n\t\t['Entertainment', entertainmentnum],\n\t\t['Productivity', productivitynum],\n\t\t['Shopping', shoppingnum],\n\t\t['Other', othernum],\n\t];\n\n\tcatData.sort(function(a,b){\n\t\treturn b[1]-a[1] //high to low\n\t});\n\t\n\tvar processeddata = google.visualization.arrayToDataTable(catData);\n\n\tvar options = {\n\t title: 'Daily Screentime By Category'\n\t};\n\n\t//piechart\n\tvar piechart_options = {\n\t\ttitle: 'Pie Chart: My Daily Screentime'\n\t\t};\n\tvar piechart = new google.visualization.PieChart(document.getElementById('piechart'));\n\tpiechart.draw(processeddata, piechart_options);\n\n\t//barchart\n\tvar barchart_options = {\n\t\ttitle: 'Bar Chart: My Daily Screentime'\n\t}\n\tvar barchart = new google.visualization.BarChart(document.getElementById('barchart'));\n\tbarchart.draw(processeddata, barchart_options);\n}",
"function show_activity_distances(ndx) {\n var date_dim = ndx.dimension(dc.pluck('date'));\n var total_distance_km_per_date = date_dim.group().reduceSum(dc.pluck('distance_km'));\n var minDate = date_dim.bottom(1)[0].date;\n var maxDate = date_dim.top(1)[0].date;\n dc.lineChart(\"#distance\")\n .width(570)\n .height(300)\n .margins({ top: 10, right: 50, bottom: 30, left: 50 })\n .dimension(date_dim)\n .group(total_distance_km_per_date)\n .transitionDuration(500)\n .x(d3.time.scale().domain([minDate, maxDate]))\n .yAxisLabel(\"Distance of Activity\")\n .xAxisLabel(\"Month\")\n .brushOn(false)\n .yAxis().ticks(10);\n}",
"function showAccidentsMonth(dataFor2017) {\n let dim = dataFor2017.dimension(dc.pluck(\"date\"));\n\n let totalAccByHour = dim.group().reduceSum(dc.pluck(\"number_of_accidents\"));\n let totalCasByHour = dim.group().reduceSum(dc.pluck(\"number_of_casualties\"));\n let totalVehByHour = dim.group().reduceSum(dc.pluck(\"number_of_vehicles\"));\n\n let minDate = dim.bottom(1)[0].date;\n let maxDate = dim.top(1)[0].date;\n\n let composite = dc.compositeChart(\"#composite-month\");\n\n composite\n .width(840)\n .height(310)\n .margins({ top: 10, right: 60, bottom: 50, left: 45 })\n .dimension(dim)\n .elasticY(true)\n .legend(dc.legend().x(230).y(320).itemHeight(15).gap(5)\n .horizontal(true).itemWidth(100))\n .x(d3.time.scale().domain([minDate, maxDate]))\n .y(d3.scale.linear())\n .transitionDuration(500)\n .shareTitle(false)\n .on(\"renderlet\", (function(chart) {\n chart.selectAll(\".dot\")\n .style(\"cursor\", \"pointer\");\n }))\n .on(\"pretransition\", function(chart) {\n chart.selectAll(\"g.y text\")\n .style(\"font-size\", \"12px\");\n chart.selectAll(\"g.x text\")\n .style(\"font-size\", \"12px\");\n chart.select(\"svg\")\n .attr(\"height\", \"100%\")\n .attr(\"width\", \"100%\")\n .attr(\"viewBox\", \"0 0 840 340\");\n chart.selectAll(\".dc-chart text\")\n .attr(\"fill\", \"#E5E5E5\");\n chart.selectAll(\".dc-legend-item text\")\n .attr(\"font-size\", \"15px\")\n .attr(\"fill\", \"#ffffff\");\n chart.selectAll(\"line\")\n .style(\"stroke\", \"#E5E5E5\");\n chart.selectAll(\".domain\")\n .style(\"stroke\", \"#E5E5E5\");\n chart.selectAll(\".line\")\n .style(\"stroke-width\", \"2.5\");\n })\n .compose([\n dc.lineChart(composite)\n .group(totalAccByHour, \"Accidents\")\n .interpolate(\"monotone\")\n .title(function(d) {\n let numberWithCommas = d.value.toLocaleString();\n return numberWithCommas + \" accidents\";\n })\n .colors(\"#ff7e0e\")\n .dotRadius(10)\n .renderDataPoints({ radius: 4 }),\n dc.lineChart(composite)\n .interpolate(\"monotone\")\n .group(totalCasByHour, \"Casualties\")\n .title(function(d) {\n let numberWithCommas = d.value.toLocaleString();\n return numberWithCommas + \" casualties\";\n })\n .colors(\"#d95350\")\n .dotRadius(10)\n .renderDataPoints({ radius: 4 }),\n dc.lineChart(composite)\n .group(totalVehByHour, \"Vehicles involved\")\n .interpolate(\"monotone\")\n .title(function(d) {\n let numberWithCommas = d.value.toLocaleString();\n return numberWithCommas + \" vehicles involved\";\n })\n .colors(\"#1e77b4\")\n .dotRadius(10)\n .renderDataPoints({ radius: 4 })\n ])\n .brushOn(false)\n .yAxisPadding(\"5%\")\n .elasticX(true)\n .xAxisPadding(\"8%\")\n .xAxis().ticks(12).tickFormat(d3.time.format(\"%b\")).outerTickSize(0);\n\n composite.yAxis().ticks(5).outerTickSize(0);\n}",
"function renderDayCountChart() {\n //Day keys\n days = [];\n //Count values\n counts = [];\n\n //Split the day_counts into keys and values for the line chart\n for (var day in day_counts) {\n days.push(day);\n counts.push(day_counts[day]);\n }\n\n var ctx = document.getElementById('dispatchDayCountsChart').getContext('2d');\n\n var dispatchDayCountChart = new Chart(ctx, {\n type: 'line',\n data: {\n labels: days,\n\n datasets: [{\n label: \"Dispatch Counts per Day\",\n data: counts,\n borderColor: '#ea6a2e',\n backgroundColor: '#ea6a2e',\n fill: false\n }]\n },\n options: {\n elements: {\n line: {\n tension: 0, // disables bezier curves\n }\n },\n scales: {\n xAxes: [{\n scaleLabel: {\n display: true,\n labelString: \"Dates\",\n fontSize: 14,\n fontColor: '#000000'\n }\n }],\n yAxes: [{\n scaleLabel: {\n display: true,\n labelString: \"Count\",\n fontSize: 14,\n fontColor: '#000000'\n }\n }]\n }\n }\n });\n}",
"function renderStat(stats, limit){\n var dates = [],\n values = [];\n\n if (limit > stats.data.length) limit = stats.data.length\n\n var i, len, stat, date;\n len=stats.data.length;\n for (i=len-limit ; i < len; i++) {\n stat = stats.data[i];\n console.log(i)\n dates.push( new Date(stat.date).toDateString());\n values.push(stat.value)\n }\n\n var ctx = document.getElementById(stats.name).getContext(\"2d\");\n\n var data = {\n labels: dates,\n datasets: [\n {\n label: stats.name,\n fillColor: \"rgba(220,220,220,0.2)\",\n strokeColor: \"rgba(220,220,220,1)\",\n pointColor: \"rgba(220,220,220,1)\",\n pointStrokeColor: \"#fff\",\n pointHighlightFill: \"#fff\",\n pointHighlightStroke: \"rgba(220,220,220,1)\",\n data: values\n }\n ]\n };\n\n var myLineChart = new Chart(ctx).Line(data);\n\n\n}",
"function drawVehicleReservations() {\n var data = google.visualization.arrayToDataTable([\n ['Ditet', 'Nr i Makinave', {role: 'style'}],\n ['E Hene', 1000, 'fill-color: #4285F4'],\n ['E Marte', 2000, 'fill-color: #DB4437'],\n ['E Merkure', 3000, 'fill-color: #F4B400'],\n ['E Enjte', 4000, 'fill-color: #1B9E77'],\n ['E Premte', 300, 'fill-color: #D95F02'],\n ['E Shtune', 1500, 'fill-color: #7570B3'],\n ['E Diele', 1500, 'fill-color: #DB4437']\n ]);\n\n var options = {\n chart: {\n title: 'Car Reservations',\n subtitle: '2015'\n },\n hAxis: {\n baselineColor: 'red'\n }\n };\n\n var chart = new google.visualization.ColumnChart(document.getElementById('weekly-statistics'));\n chart.draw(data, options);\n }",
"function drawVotesChart() {\n fetch(DISHES_URL).then(response => response.json())\n .then((dishVotes) => {\n const data = new google.visualization.DataTable();\n data.addColumn('string', 'Dish');\n data.addColumn('number', 'Votes');\n Object.keys(dishVotes).forEach((dish) => {\n data.addRow([dish, dishVotes[dish]]);\n });\n\n const options = {\n 'title': CHARTS_TITLES.DISHES_BAR_CHART,\n 'width': 600,\n 'height': 500\n };\n\n const chart = new google.visualization.ColumnChart(\n document.getElementById(DOM_CONTAINARS_IDS.DISHES_CHART));\n chart.draw(data, options);\n });\n}",
"function ClickThroughsTimeSeries() {\n var self = this;\n this.loading = false;\n\n this.loadData = function() {\n self.loading = true;\n Restangular\n .one('campaign_reports', ctrl.campaignId)\n .customGET('clickthroughs_time_series')\n .then(function(response) {\n self.loading = false;\n self.data = [];\n self.data[0]={};\n var _count = [],_date = [];\n self.clicks = numberWithCommas(response.totalClicks);\n for(var i= 0; i<response.timeSeries.length; i++){\n _count.push(response.timeSeries[i].count);\n _date.push(response.timeSeries[i].date);\n }\n self.data[0].count = _count.toString();\n self.data[0].date = _date.toString();\n console.log(\"row--fourth ClickThroughsTimeSeries::\", self.data);\n });\n };\n this.loadData();\n }",
"function makeGraphs(data) {\n \n var ndx = crossfilter(data);\n \n has_website(ndx);\n pieChart(ndx);\n barChart(ndx);\n table(ndx, 10);\n \n dc.renderAll();\n $(\".dc-select-menu\").addClass(\"custom-select\");\n\n}",
"function drawTermDatesGraph() {\n // Get the elements we need\n var graphContainer = $('.term_dates_graph');\n var tableContainer = $('.term_dates_table');\n if (graphContainer.length === 0 || tableContainer.length === 0)\n return;\n\n var results = $.parseJSON(window.json_data);\n\n // Make a DataTable object\n var data = new google.visualization.DataTable();\n var rows = results.data;\n\n data.addColumn('number', results.year_header);\n data.addColumn('number', results.value_header);\n data.addRows(rows);\n\n // Make the line chart object\n var w = $(window).width();\n if (w > 750) {\n w = 750;\n }\n\n var h;\n if (w > 480) {\n h = 480;\n } else {\n h = w;\n }\n\n var options = { width: w, height: h,\n legend: { position: 'none' },\n hAxis: { format: '####',\n title: results.year_header },\n vAxis: { title: results.value_header },\n pointSize: 3 };\n\n var chart = new google.visualization.LineChart(graphContainer[0]);\n chart.draw(data, options);\n\n graphContainer.trigger('updatelayout');\n\n // Make a pretty table object\n var table = new google.visualization.Table(tableContainer[0]);\n table.draw(data, { page: 'enable', pageSize: 20, sortColumn: 0,\n width: '20em' });\n}",
"renderliveOperationalStatisticsPie() {\n let me = this;\n this.loadingliveOperationalStatistics = true;\n this.loadingliveOperationalStatisticsPie = true;\n this.client.get('/statistics/liveoperationalstatistic').then(res => {\n if (res) {\n if (res.data) {\n this.opStatistics = res.data.current;\n this.opStatisticsPrevious = res.data.previous\n ? res.data.previous\n : null;\n //render pie chart\n let ctx = document.getElementById('operationalPie');\n me.cards.liveoperationalstatistics = new Chart(ctx, {\n type: 'pie',\n data: {\n labels: ['Not Operational', 'Operational', 'Unknown'],\n datasets: [\n {\n data: [\n me.opStatistics.notOperational,\n me.opStatistics.operational,\n me.opStatistics.unknown\n ],\n backgroundColor: ['#00838f', '#00acc1', '#b2ebf2', '#e0f7fa'],\n hoverBackgroundColor: ['#00838f', '#00acc1', '#b2ebf2', '#e0f7fa']\n }\n ]\n }\n });\n }\n }\n this.loadingliveOperationalStatisticsPie = false;\n });\n }",
"function trend_periodically_update_graph () {\n\t$.ajax({\n\t\ttype: 'GET',\n\t\turl: '/dashboard/trend_data',\n\t\tdataType: 'json',\n\t\tsuccess: trend_generate_graph\n\t});\n}",
"function drawCharts(event) {\r\n\tfetchLineChart(event.target.textContent).then(res => {\r\n\t\tconsole.log(res);\r\n\t\t//updating the chart with the data of the selected activity\r\n\t\tline.data.datasets[0].data = res;\r\n\t\tline.update();\r\n\t});\r\n\r\n\tfetchBarChart(event.target.textContent).then(res => {\r\n\t\tconsole.log(res);\r\n\t\t//updating the chart with the data of the selected activity\r\n\t\tbar.data.datasets[0].data = res;\r\n\t\tbar.update();\r\n\t});\r\n}",
"function showAccidentsHour(dataFor2017) {\n let dim = dataFor2017.dimension(dc.pluck(\"hour\"));\n\n let totalAccByHour = dim.group().reduceSum(dc.pluck(\"number_of_accidents\"));\n let totalCasByHour = dim.group().reduceSum(dc.pluck(\"number_of_casualties\"));\n let totalVehByHour = dim.group().reduceSum(dc.pluck(\"number_of_vehicles\"));\n\n let composite = dc.compositeChart(\"#composite-hour\");\n\n composite\n .width(840)\n .height(310)\n .margins({ top: 20, right: 60, bottom: 50, left: 45 })\n .dimension(dim)\n .elasticY(true)\n .legend(dc.legend().x(230).y(320).itemHeight(15).gap(5)\n .horizontal(true).itemWidth(100))\n .x(d3.scale.linear().domain([0, 23]))\n .y(d3.scale.linear())\n .transitionDuration(500)\n .shareTitle(false)\n .on(\"renderlet\", (function(chart) {\n chart.selectAll(\".dot\")\n .style(\"cursor\", \"pointer\");\n }))\n .on(\"pretransition\", function(chart) {\n chart.selectAll(\"g.y text\")\n .style(\"font-size\", \"12px\");\n chart.selectAll(\"g.x text\")\n .style(\"font-size\", \"12px\")\n .attr(\"dx\", \"-30\")\n .attr(\"dy\", \"-5\")\n .attr(\"transform\", \"rotate(-90)\");\n chart.select(\"svg\")\n .attr(\"height\", \"100%\")\n .attr(\"width\", \"100%\")\n .attr(\"viewBox\", \"0 0 840 340\");\n chart.selectAll(\".dc-chart text\")\n .attr(\"fill\", \"#E5E5E5\");\n chart.selectAll(\".dc-legend-item text\")\n .attr(\"font-size\", \"15px\")\n .attr(\"fill\", \"#ffffff\");\n chart.selectAll(\"line\")\n .style(\"stroke\", \"#E5E5E5\");\n chart.selectAll(\".domain\")\n .style(\"stroke\", \"#E5E5E5\");\n chart.selectAll(\".line\")\n .style(\"stroke-width\", \"2.5\");\n })\n .compose([\n dc.lineChart(composite)\n .group(totalAccByHour, \"Accidents\")\n .interpolate(\"monotone\")\n .title(function(d) {\n let numberWithCommas = d.value.toLocaleString();\n if (d.key < 10) {\n return numberWithCommas + \" accidents at \" + \"0\" +\n d.key + \":00\";\n }\n else {\n return numberWithCommas + \" accidents at \" +\n d.key + \":00\";\n }\n })\n .colors(\"#ff7e0e\")\n .dotRadius(10)\n .renderDataPoints({ radius: 4 }),\n dc.lineChart(composite)\n .group(totalCasByHour, \"Casualties\")\n .interpolate(\"monotone\")\n .title(function(d) {\n let numberWithCommas = d.value.toLocaleString();\n if (d.key < 10) {\n return numberWithCommas + \" casualties at \" + \"0\" +\n d.key + \":00\";\n }\n else {\n return numberWithCommas + \" casualties at \" +\n d.key + \":00\";\n }\n })\n .colors(\"#d95350\")\n .dotRadius(10)\n .renderDataPoints({ radius: 4 }),\n dc.lineChart(composite)\n .group(totalVehByHour, \"Vehicles involved\")\n .interpolate(\"monotone\")\n .title(function(d) {\n let numberWithCommas = d.value.toLocaleString();\n if (d.key < 10) {\n return numberWithCommas + \" vehicles involved at \" + \"0\" +\n d.key + \":00\";\n }\n else {\n return numberWithCommas + \" vehicles involved at \" +\n d.key + \":00\";\n }\n })\n .colors(\"#1e77b4\")\n .dotRadius(10)\n .renderDataPoints({ radius: 4 })\n ])\n .brushOn(false)\n .yAxisPadding(\"5%\")\n .elasticX(true)\n .xAxisPadding(\"2%\")\n .xAxis().ticks(24).tickFormat(function(d) {\n if (d < 10) {\n return \"0\" + d + \":00\";\n }\n else { return d + \":00\"; }\n }).outerTickSize(0);\n composite.yAxis().ticks(5).outerTickSize(0);\n}",
"function CumulativeImpressionsTimeSeries() {\n var self = this;\n this.loading = false;\n\n this.loadData = function() {\n self.loading = true;\n Restangular\n .one('campaign_reports', ctrl.campaignId)\n .customGET('cumulative_impressions_time_series')\n .then(function(response) {\n self.loading = false;\n self.data = [];\n self.data[0]={};\n var _count = [],_date = [];\n self.totalImpressions = response.totalImpressions;\n for(var i= 0; i<response.timeSeries.length; i++){\n _count.push(response.timeSeries[i].count);\n _date.push(response.timeSeries[i].date);\n }\n self.data[0].count = _count.toString();\n self.data[0].date = _date.toString();\n self.data[0].minDate = response.timeSeries[0].date;\n self.data[0].maxDate = response.timeSeries[response.timeSeries.length-1].date;\n console.log(\"row--fourth cumulative_impressions_time_series::\", self.data);\n });\n };\n this.loadData();\n }",
"function sparkline_charts() {\r\n\t\t\t$('.sparklines').sparkline('html');\r\n\t\t}",
"function renderChart() {\n requestAnimationFrame(renderChart);\n\n analyser.getByteFrequencyData(frequencyData);\n\n if(colorToggle == 1){\n //Transition the hexagon colors\n svg.selectAll(\".hexagon\")\n .style(\"fill\", function (d,i) { return colorScaleRainbow(colorInterpolateRainbow(frequencyData[i])); })\n }\n\n if(colorToggle == 2){\n //Transition the hexagon colors\n svg.selectAll(\".hexagon\")\n .style(\"fill\", function (d,i) { return colorScaleGray(colorInterpolateGray(frequencyData[i])); })\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the key manager's active item to the given option. | setActiveOption(option) {
this._listKeyManager.updateActiveItem(option);
this._updateActiveOption();
} | [
"_updateActiveOption() {\n if (!this._listKeyManager.activeItem) {\n return;\n }\n this._activeOption?.deactivate();\n this._activeOption = this._listKeyManager.activeItem;\n this._activeOption.activate();\n if (!this.useActiveDescendant) {\n this._activeOption.focus();\n }\n }",
"_toggleActiveOption() {\n const activeOption = this._listKeyManager.activeItem;\n if (activeOption && !activeOption.disabled) {\n activeOption.toggle();\n }\n }",
"_focusActiveOption() {\n var _a;\n if (!this.useActiveDescendant) {\n (_a = this.listKeyManager.activeItem) === null || _a === void 0 ? void 0 : _a.focus();\n }\n this.changeDetectorRef.markForCheck();\n }",
"_onApplicationSelect() {\n this._selected = 'appsco-application-add-settings';\n }",
"function DDLightbarMenu_SetItemHotkey(pIdx, pHotkey)\n{\n\tif ((typeof(pIdx) == \"number\") && (pIdx >= 0) && (pIdx < this.items.length) && (typeof(pHotkey) == \"string\"))\n\t\tthis.items[pIdx].hotkeys = pHotkey;\n}",
"_optionSelected(e) {\n let local = e.target;\n // fire that an option was selected and about what operation\n let ops = {\n element: this,\n operation: this.activeOp,\n option: local.getAttribute(\"id\"),\n };\n this.dispatchEvent(\n new CustomEvent(\"item-overlay-option-selected\", {\n bubbles: true,\n cancelable: true,\n composed: true,\n detail: ops,\n })\n );\n // don't reset for movement, just confirm / reject actions\n if (this.activeOp != \"move\") {\n this._resetActive();\n this.activeOp = null;\n }\n }",
"updateActiveAccount (state, activeAccount) {\n state.activeAccount = activeAccount;\n }",
"function updateActiveLink() {\n\tif (this==activeLink){\n\t\treturn;\n\t}\n\t// loops over all li elements\n\tsliderLinks.forEach((link, index) => {\n\t\t// removes 'active' from each\n\t\tlink.classList.remove('active');\n\t\tsliderStack[index].classList.remove('active');\n\t});\n\t// adds 'active' to clicked item\n\tthis.classList.add('active');\n\tsliderStack[sliderLinks.indexOf(this)].classList.add('active');\n\t// stores clicked item\n\tactiveLink = this;\n\tmoveSlides();\n}",
"setOption(option, value) {\n this.options_[option] = value;\n return this.store();\n }",
"function setPrevItemActive() {\n var items = getItems();\n\n var activeItem = document.getElementsByClassName(\"active\")[0];\n var prevElement = activeItem.previousElementSibling;\n\n if (!prevElement) {\n prevElement = items[items.length - 1];\n }\n\n changeActiveState(activeItem, prevElement);\n}",
"_selectCurrentActiveItem() {\n const currentActive = this._getActiveListItemElement();\n const suggestionId =\n currentActive && currentActive.getAttribute('data-suggestion-id');\n const selection = this.state.list.filter(item => {\n return item.__suggestionId === suggestionId;\n })[0];\n\n if (selection) {\n this.options.onSelect(selection);\n this._filterAndToggleVisibility();\n this.setState({\n activeId: null,\n });\n }\n }",
"function markActiveItem(objItem) {\n $('.item').removeClass('active-item');\n\n if (objItem == null)\n objItem = getItemObjByNameAndFeed(getFeedObjByName(activeFeed), activeItem);\n\n if (objItem == null)\n objItem = $('.item:first');\n\n if (objItem.length == 0) {\n $('#rules').html('');\n $('#welcome-title').css({'display': 'block'});\n $('#active-item-name').html('');\n }\n else {\n $('#welcome-title').css({'display': 'none'});\n var thisItemName = objItem.find('a').text();\n objItem.addClass('active-item');\n activeItem = thisItemName;\n $('#active-item-name').html(activeItem);\n activeFeed = objItem.parents('.feed').data('feed-name');\n loadActiveItemRules();\n }\n}",
"setBreakfastItem(state, breakfast) {\n state.selectedBreakfast[breakfast.index] = breakfast.data\n }",
"function updateActiveGame() {\n // Return if we're not logged in\n if(!Dworek.state.loggedIn)\n return;\n\n // Request new game info if the same game is still active\n if(Dworek.state.activeGame != null && (Dworek.state.activeGame == Dworek.utils.getGameId() || !Dworek.utils.isGamePage()))\n requestGameInfo();\n\n // Return if we're not on a game page\n if(!Dworek.utils.isGamePage()) {\n Dworek.utils.lastViewedGame = null;\n return;\n }\n\n // Get the ID of the game page\n const gameId = Dworek.utils.getGameId();\n\n // Return if the last viewed game is this game\n if(Dworek.state.lastViewedGame == gameId)\n return;\n\n // Check whether this game is different than the active game\n if(Dworek.state.activeGame != gameId) {\n // Automatically select this as active game if we don't have an active game now\n if(Dworek.state.activeGame === null) {\n // Set the active game\n setActiveGame(gameId);\n\n } else {\n // Ask the user whether to select this as active game\n showDialog({\n title: 'Change active game',\n message: 'You may only have one active game to play at a time.<br /><br />Would you like to change your active game to this game now?',\n actions: [\n {\n text: 'Activate this game',\n value: true,\n state: 'primary',\n icon: 'zmdi zmdi-swap',\n action: function() {\n // Set the active game\n setActiveGame(gameId);\n }\n },\n {\n text: 'View current game',\n value: true,\n icon: 'zmdi zmdi-long-arrow-return',\n action: function() {\n // Navigate to the game page\n Dworek.utils.navigateToPath('/game/' + Dworek.state.activeGame);\n }\n },\n {\n text: 'Ignore'\n }\n ]\n\n }, function(value) {\n // Return if the action is already handled\n if(!!true)\n return;\n\n // Show a notification to switch to the active game\n showNotification('Switch to your active game', {\n action: {\n text: 'Switch',\n action: function() {\n $.mobile.navigate('/game/' + Dworek.state.activeGame, {\n transition: 'flow'\n });\n }\n }\n });\n });\n }\n }\n\n // Update the status labels\n updateStatusLabels();\n\n // Update the last viewed game\n Dworek.state.lastViewedGame = gameId;\n}",
"updateTabNav () {\n const tab = this.tabNavItems[this.currentTab.position]\n this.setAriaSelected(tab)\n }",
"function setNextItemActive() {\n var items = getItems();\n\n var activeItem = document.getElementsByClassName(\"active\")[0];\n var nextElement = activeItem.nextElementSibling;\n\n if (!nextElement) {\n nextElement = items[0];\n }\n\n changeActiveState(activeItem, nextElement);\n}",
"triggerOption(option) {\n if (option && !option.disabled) {\n this._lastTriggered = option;\n const changed = this.multiple\n ? this.selectionModel.toggle(option.value)\n : this.selectionModel.select(option.value);\n if (changed) {\n this._onChange(this.value);\n this.valueChange.next({\n value: this.value,\n listbox: this,\n option: option,\n });\n }\n }\n }",
"SET_ACTIVE_CHAR(state, char) {\n state.activeChar = char;\n }",
"_setActiveList(list)\n {\n this.activeList = list;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the true offsetLeft position of an anchor | function getOffsetLeft(anchorId) {
var anchorObject = atgCalendar_findElementById(anchorId);
var curleft = 0;
if (anchorObject.offsetParent)
{
while (anchorObject.offsetParent)
{
curleft += anchorObject.offsetLeft
anchorObject = anchorObject.offsetParent;
}
}
else if (anchorObject.x)
curleft += anchorObject.x;
return curleft;
} | [
"function calculateOffsetLeft(r){\n return absolute_offset(r,\"offsetLeft\")\n}",
"function getLeftPosition() {\n return randomFunction(0, viewportWidth - 100);\n}",
"getElementX(el) {\n var parent = this.myRef.current;\n var center = parent.clientWidth / 2;\n var left = el.offsetLeft - parent.offsetLeft;\n return left - center;\n }",
"get_top_left() {\n this.__top_left_c = this.__top_left_c || this.__position.clone();\n return this.__top_left_c;\n }",
"matchBefore(expr) {\n let line = this.state.doc.lineAt(this.pos)\n let start = Math.max(line.from, this.pos - 250)\n let str = line.text.slice(start - line.from, this.pos - line.from)\n let found = str.search(ensureAnchor(expr, false))\n return found < 0\n ? null\n : { from: start + found, to: this.pos, text: str.slice(found) }\n }",
"getLeftCornerPos() {\n return new THREE.Vector3(\n (-CLOTH_SIZE * this.guiOptions.particle_distance) / 2,\n CLOTH_SIZE * this.guiOptions.particle_distance + CLOTH_TO_FLOOR_DISTANCE,\n 0\n );\n }",
"matchBefore(expr) {\n let line = this.state.doc.lineAt(this.pos);\n let start = Math.max(line.from, this.pos - 250);\n let str = line.slice(start - line.from, this.pos - line.from);\n let found = str.search(ensureAnchor(expr, false));\n return found < 0 ? null : { from: start + found, to: this.pos, text: str.slice(found) };\n }",
"function getFixedPosition(_a) {\n var container = _a.container, element = _a.element, _b = _a.anchor, propAnchor = _b === void 0 ? {} : _b, initialX = _a.initialX, initialY = _a.initialY, _c = _a.vwMargin, vwMargin = _c === void 0 ? 16 : _c, _d = _a.vhMargin, vhMargin = _d === void 0 ? 16 : _d, _e = _a.xMargin, xMargin = _e === void 0 ? 0 : _e, _f = _a.yMargin, yMargin = _f === void 0 ? 0 : _f, _g = _a.width, widthType = _g === void 0 ? \"auto\" : _g, _h = _a.preventOverlap, preventOverlap = _h === void 0 ? false : _h, _j = _a.transformOrigin, transformOrigin = _j === void 0 ? false : _j, _k = _a.disableSwapping, disableSwapping = _k === void 0 ? false : _k, _l = _a.disableVHBounds, disableVHBounds = _l === void 0 ? false : _l;\n container = findSizingContainer_1.default(container);\n var anchor = {\n x: propAnchor.x || \"center\",\n y: propAnchor.y || \"below\",\n };\n if (process.env.NODE_ENV !== \"production\") {\n if (widthType !== \"auto\" && anchor.x !== \"center\") {\n throw new Error('Unable to use a calculated width when the horizontal anchor is not `\"center\"`.');\n }\n if (preventOverlap && anchor.y !== \"above\" && anchor.y !== \"below\") {\n throw new Error('Unable to prevent overlap when the vertical anchor is not `\"above\"` or `\"below\"`');\n }\n }\n if (!container || !element) {\n return {\n actualX: anchor.x,\n actualY: anchor.y,\n };\n }\n var containerRect = container.getBoundingClientRect();\n var vh = getViewportSize_1.default(\"height\");\n var vw = getViewportSize_1.default(\"width\");\n var _m = getElementRect_1.default(element), height = _m.height, elWidth = _m.width;\n if (disableVHBounds) {\n var dialog = element.closest(\"[role='dialog']\");\n if (!dialog) {\n initialY = (initialY !== null && initialY !== void 0 ? initialY : 0) + window.scrollY;\n }\n }\n var _o = createHorizontalPosition_1.default({\n x: anchor.x,\n vw: vw,\n vwMargin: vwMargin,\n xMargin: xMargin,\n width: widthType,\n elWidth: elWidth,\n initialX: initialX,\n containerRect: containerRect,\n disableSwapping: disableSwapping,\n }), left = _o.left, right = _o.right, width = _o.width, minWidth = _o.minWidth, actualX = _o.actualX;\n var _p = createVerticalPosition_1.default({\n y: anchor.y,\n vh: vh,\n vhMargin: vhMargin,\n yMargin: yMargin,\n initialY: initialY,\n elHeight: height,\n containerRect: containerRect,\n disableSwapping: disableSwapping,\n preventOverlap: preventOverlap,\n disableVHBounds: disableVHBounds,\n }), top = _p.top, bottom = _p.bottom, actualY = _p.actualY;\n return {\n actualX: actualX,\n actualY: actualY,\n style: {\n left: left,\n top: top,\n right: right,\n bottom: bottom,\n width: width,\n minWidth: minWidth,\n position: disableVHBounds ? \"absolute\" : \"fixed\",\n transformOrigin: transformOrigin\n ? getTransformOrigin_1.default({ x: actualX, y: actualY })\n : undefined,\n },\n };\n}",
"function getRelativeLeft(element, parent) {\n if (element === null) {\n return 0;\n }\n var elementPosition = getTopLeftOffset(element);\n var parentPosition = getTopLeftOffset(parent);\n return elementPosition.left - parentPosition.left;\n}",
"_lookLeft(start, contextWords) {\n let charToToken = this._charToToken;\n let tokenOffsets = this._tokenOffsets;\n if (tokenOffsets.length === 0) {\n return start;\n };\n\n // If we landed between tokens, look left for token number.\n let onToken = 0;\n let correct_for_start = 0;\n while ((start >= 0) && (onToken = charToToken[start]) < 0) {\n start--;\n correct_for_start = 1;\n };\n let goalToken = Math.max(0, onToken - contextWords + correct_for_start);\n return tokenOffsets[goalToken].start;\n }",
"function getTabLeftPosition(container, tab) { \n\t\tvar w = 0; \n\t\tvar b = true; \n\t\t$('>div.tabs-header ul.tabs li', container).each(function(){ \n\t\t\tif (this == tab) { \n\t\t\t\tb = false; \n\t\t\t} \n\t\t\tif (b == true) { \n\t\t\t\tw += $(this).outerWidth(true); \n\t\t\t} \n\t\t}); \n\t\treturn w; \n\t}",
"function findAbsolutePosX(obj)\n{\n var curleft = 0;\n if (document.getElementById || document.all)\n {\n while (obj.offsetParent)\n {\n curleft += obj.offsetLeft;\n if (obj.offsetParent != document.body)\n curleft -= obj.offsetParent.scrollLeft;\n obj = obj.offsetParent;\n }\n }\n else if (document.layers)\n curleft += obj.x;\n var isWindowContainedInDivFrame = window.parentAccesible && false;\n return (isWindowContainedInDivFrame ? parent.Ext.WindowMgr.getActive().x+curleft : curleft);\n}",
"function getHorizontalPosition(offsetInGridRectangles) {\n var percentageGridWidth = (100.0 - HORIZONTAL_EDGE_PADDING_PERCENT * 2) / totalColumns;\n return HORIZONTAL_EDGE_PADDING_PERCENT + percentageGridWidth * offsetInGridRectangles;\n }",
"positionOnTimeline(posX) {\n let rect = this.timelineNode.getBoundingClientRect();\n let posClickedX = posX - rect.left + this.timelineNode.scrollLeft;\n return posClickedX;\n }",
"get left() {\n return this.pos.x - this.size.x / 2; // ball reflects\n }",
"function tooltipXposition(d){\n\t\t\treturn x(d)+leftOffset(\"stage_wrapper\")+\"px\";\n\t\t}",
"function getXmovement(fromIndex,toIndex){if(fromIndex==toIndex){return'none';}if(fromIndex>toIndex){return'left';}return'right';}",
"function getLeftmost( start ) {\n \n var p = start,\n leftmost = start;\n do {\n \n if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;\n p = p.next;\n \n } while ( p !== start );\n \n return leftmost;\n \n }",
"_calculateOverlayOffsetX() {\n const overlayRect = this._overlayDir.overlayRef.overlayElement.getBoundingClientRect();\n const viewportSize = this._viewportRuler.getViewportSize();\n const isRtl = this._isRtl();\n const paddingWidth = this.multiple\n ? SELECT_MULTIPLE_PANEL_PADDING_X + SELECT_PANEL_PADDING_X\n : SELECT_PANEL_PADDING_X * 2;\n let offsetX;\n // Adjust the offset, depending on the option padding.\n if (this.multiple) {\n offsetX = SELECT_MULTIPLE_PANEL_PADDING_X;\n }\n else if (this.disableOptionCentering) {\n offsetX = SELECT_PANEL_PADDING_X;\n }\n else {\n let selected = this._selectionModel.selected[0] || this.options.first;\n offsetX = selected && selected.group ? SELECT_PANEL_INDENT_PADDING_X : SELECT_PANEL_PADDING_X;\n }\n // Invert the offset in LTR.\n if (!isRtl) {\n offsetX *= -1;\n }\n // Determine how much the select overflows on each side.\n const leftOverflow = 0 - (overlayRect.left + offsetX - (isRtl ? paddingWidth : 0));\n const rightOverflow = overlayRect.right + offsetX - viewportSize.width + (isRtl ? 0 : paddingWidth);\n // If the element overflows on either side, reduce the offset to allow it to fit.\n if (leftOverflow > 0) {\n offsetX += leftOverflow + SELECT_PANEL_VIEWPORT_PADDING;\n }\n else if (rightOverflow > 0) {\n offsetX -= rightOverflow + SELECT_PANEL_VIEWPORT_PADDING;\n }\n // Set the offset directly in order to avoid having to go through change detection and\n // potentially triggering \"changed after it was checked\" errors. Round the value to avoid\n // blurry content in some browsers.\n this._overlayDir.offsetX = Math.round(offsetX);\n this._overlayDir.overlayRef.updatePosition();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
show polar chart of artist traits | function showPolarArea(traits, selector) {
var labels = [], data = [], graph = []
, traitsCanvas = $$(selector)
, traitsCx = traitsCanvas.getContext('2d')
, traitsChart
, traitsLegend = $$('.traits-legend');
traits.map(function(trait) {
graph.push({
value: trait.percentage * 100
, color: getColour(trait.percentage)
, highlight: getColour(trait.percentage)
, label: trait.name
});
});
traitsChart = new Chart(traitsCx).PolarArea(graph, {responsive:true});
traitsLegend.innerHTML = traitsChart.generateLegend();
} | [
"function drawRadar(data, overall, pronouns, theword, extras) {\n for (i = 0; i < data.length; i++) {\n var p = \".s3-\" + i;\n RadarChart(p, data[i].dataset[0], data[i], radarChartOptions, overall[i], pronouns, theword[i], extras[i]);\n }\n}",
"toggleChart() {\n this.pie.type = (this.pie.type == 'pie') ? 'polarArea' : 'pie';\n }",
"function visualize() {\n\n visualizer.updatePitchChart(audioProcessor.getPitches(), audioProcessor.getTimestamps());\n visualizer.updateRateChart(audioProcessor.getVibratoRates(), audioProcessor.getTimestamps());\n visualizer.updateWidthChart(audioProcessor.getVibratoWidths(), audioProcessor.getTimestamps());\n calcPitch();\n}",
"function renderPieChart() {\n var i, x, y, r, a1, a2, set, sum;\n\n i = 0;\n x = width / 2;\n y = height / 2;\n r = Math.min(x, y) - 2;\n a1 = 1.5 * Math.PI;\n a2 = 0;\n set = sets[0];\n sum = sumSet(set);\n\n for (i = 0; i < set.length; i++) {\n ctx.fillStyle = getColorForIndex(i);\n ctx.beginPath();\n a2 = a1 + (set[i] / sum) * (2 * Math.PI);\n\n // TODO opts.wedge\n ctx.arc(x, y, r, a1, a2, false);\n ctx.lineTo(x, y);\n ctx.fill();\n a1 = a2;\n }\n }",
"function draw_g_cake(data) {\n let series = [];\n let labels = [];\n for (let i = 0; i < data.length; i++) {\n series.push(data[i]['n_avistamientos'])\n labels.push(data[i]['tipo'])\n }\n // console.log(series);\n // console.log(labels);\n\n let options = {\n chart: {\n height: 380,\n width: \"100%\",\n type: 'pie',\n animations: {\n initialAnimation: {\n enabled: false\n }\n }\n },\n series: series,\n labels: labels\n };\n document.getElementById('grafico_torta_placeholder').innerText = \"\";\n let chart = new ApexCharts(document.getElementById('grafico_torta_placeholder'), options);\n\n chart.render();\n\n}",
"function drawRadarChart(canvas, container, data) {\n let tooltipTemplate = \"<%if(label)\\u007B%><%=label%>: <%}%><%=value%>%\";\n let ctx = canvas[0].getContext(\"2d\"),\n opts = {populateSparseData:true, tooltipTemplate: tooltipTemplate},\n chart = new Chart(ctx).Radar(data, opts);\n chart.draw();\n return chart;\n}",
"function zeppelin_circle(rotation) {\n if (rotation > 0.06) rotation = 0.06;\n zepMarker.rotateY(rotation);\n}",
"function RadarChart(id, data, options) {\n var cfg = {\n w: 600,\t\t\t\t//Width of the circle\n h: 600,\t\t\t\t//Height of the circle\n margin: { top: 50, right: 50, bottom: 50, left: 50 }, //The margins of the SVG\n levels: 3,\t\t\t\t//How many levels or inner circles should there be drawn\n maxValue: 0, \t\t\t//What is the value that the biggest circle will represent\n labelFactor: 1.25, \t//How much farther than the radius of the outer circle should the labels be placed\n wrapWidth: 60, \t\t//The number of pixels after which a label needs to be given a new line\n opacityArea: 0.35, \t//The opacity of the area of the blob\n dotRadius: 4, \t\t\t//The size of the colored circles of each blog\n opacityCircles: 0.1, \t//The opacity of the circles of each blob\n strokeWidth: 2, \t\t//The width of the stroke around each blob\n roundStrokes: false,\t//If true the area and stroke will follow a round path (cardinal-closed)\n color: d3.scale.category10()\n };\n\n //Put all of the options into a variable called cfg\n if ('undefined' !== typeof options) {\n for (var i in options) {\n if ('undefined' !== typeof options[i]) { cfg[i] = options[i]; }\n }//for i\n }//if\n\n var _dateIndex = _maxDateIndex = data.length - 1;\n //console.log(_dateIndex);\n //console.log(_maxDateIndex);\n\n var tooltip = d3.select(\"#main\").append(\"div\").attr(\"class\", \"tooltip\").style(\"opacity\", 0);\n\n var region_list = [\n { \"Region\": \"Global\", \"Color\": \"#7AF67A\", \"IsHidden\": false },\n { \"Region\": \"AMEA\", \"Color\": \"#FFC81E\", \"IsHidden\": false },\n { \"Region\": \"Americas\", \"Color\": \"#FF0000\", \"IsHidden\": false },\n { \"Region\": \"Europe\", \"Color\": \"#A30FE2\", \"IsHidden\": false },\n { \"Region\": \"JP\", \"Color\": \"#50D6FF\", \"IsHidden\": false }\n ];\n function regionColor(regionName) {\n var result = \"#ccc\";\n region_list.forEach(function (d) {\n if (d.Region == regionName) {\n result = d.Color;\n }\n });\n return result;\n }\n function isHidden(regionName) {\n var cssName = \"\";\n region_list.forEach(function (d) {\n if (d.Region == regionName && d.IsHidden) {\n cssName = \"hidden\";\n }\n });\n return cssName;\n }\n function getRegion(regionName) {\n var result = undefined;\n region_list.forEach(function (d) {\n if (d.Region == regionName) {\n result = d;\n }\n });\n return result;\n }\n function drawRegion(dateIndex) {\n d3.select(\"#regionList\").html(\"\");\n region_list.forEach(function (d, i) {\n var lbl = d3.select(\"#regionList\").append(\"label\");\n lbl.append(\"input\").attr(\"type\", \"checkbox\").attr(\"checked\", function () { return (d.IsHidden ? \"\" : \"checked\"); }).attr(\"value\", function () { return returnNULL(d.Region); });\n //lbl.append(\"span\").text(function () { return returnNULL(d.Region); }).style(\"background-color\", cfg.color(i));\n lbl.append(\"span\").text(function () { return returnNULL(d.Region); })\n .style(\"background-color\", function () {\n var c = d3.rgb(d.Color);\n return \"rgba(\" + c.r + \",\" + c.g + \",\" + c.b + \",\" + cfg.opacityArea + \")\";\n })\n .style(\"border\",\"solid 2px \" + d.Color);\n\n //d3.select(\"#regionList\").append(\"br\");\n\n d3.selectAll(\"#regionList input[type=checkbox]\").on(\"click\", function () {\n // console.log(\"got\");\n // console.log(this);\n //console.log(d3.select(this).attr(\"value\"));\n var _region = getRegion(d3.select(this).attr(\"value\"));\n if (_region != undefined) {\n _region.IsHidden = !_region.IsHidden;\n }\n \n //dd.IsHidden = !dd.IsHidden;\n toggleRegion(d3.select(this).attr(\"value\"));\n\n //console.log(region_list);\n });\n });\n //data[dateIndex].Data.forEach(function (d, i) {\n // //console.log(d);\n // var lbl = d3.select(\"#regionList\").append(\"label\");\n // lbl.append(\"input\").attr(\"type\", \"checkbox\").attr(\"checked\", \"checked\").attr(\"value\", function () { return returnNULL(d.region); });\n // lbl.append(\"span\").text(function () { return returnNULL(d.region); }).style(\"background-color\", cfg.color(i));\n\n // //d3.select(\"#regionList\").append(\"br\");\n\n // d3.selectAll(\"#regionList input[type=checkbox]\").on(\"click\", function (d, i) {\n // // console.log(i);\n // // console.log(\"got\");\n // // console.log(this);\n // //console.log(d3.select(this).attr(\"value\"));\n // toggleRegion(d3.select(this).attr(\"value\"));\n // });\n //});\n }\n\n function toggleRegion(region) {\n //console.log(region);\n var p = d3.selectAll(\"g.\" + region),\n\t //console.log(p);\n c = p.classed(\"hidden\"),\n n = c ^ true;\n\n p.classed(\"hidden\", n);\n }\n\n function returnNULL(val) { return (val == null ? \"NULL\" : val); }\n //If the supplied maxValue is smaller than the actual one, replace by the max in the data\n var maxValue = Math.max(cfg.maxValue, d3.max(data, function (i) {\n //console.log(i.axises);\n return d3.max(i.Data[0].axes.map(function (o) { return o.value; }))\n }));\n\n var allAxis = (data[_dateIndex].Data[0].axes.map(function (i, j) { return i.axis })),\t//Names of each axis\n\t\ttotal = allAxis.length,\t\t\t\t\t//The number of different axes\n\t\tradius = Math.min(cfg.w / 2, cfg.h / 2), \t//Radius of the outermost circle\n\t\tFormat = d3.format('%'),\t\t\t \t//Percentage formatting\n\t\tangleSlice = Math.PI * 2 / total;\t\t//The width in radians of each \"slice\"\n\n //Scale for the radius\n var rScale = d3.scale.linear()\n\t\t.range([0, radius])\n\t\t.domain([0, maxValue]);\n\n /////////////////////////////////////////////////////////\n //////////// Create the container SVG and g /////////////\n /////////////////////////////////////////////////////////\n\n //Remove whatever chart with the same id/class was present before\n d3.select(id).select(\"svg\").remove();\n\n //Initiate the radar chart SVG\n var svg = d3.select(id).append(\"svg\")\n\t\t\t.attr(\"width\", cfg.w + cfg.margin.left + cfg.margin.right)\n\t\t\t.attr(\"height\", cfg.h + cfg.margin.top + cfg.margin.bottom)\n\t\t\t.attr(\"class\", \"radar\" + id);\n //Append a g element\t\t\n var g = svg.append(\"g\")\n\t\t\t.attr(\"transform\", \"translate(\" + (cfg.w / 2 + cfg.margin.left) + \",\" + (cfg.h / 2 + cfg.margin.top) + \")\");\n\n /////////////////////////////////////////////////////////\n ////////// Glow filter for some extra pizzazz ///////////\n /////////////////////////////////////////////////////////\n\n //Filter for the outside glow\n var filter = g.append('defs').append('filter').attr('id', 'glow'),\n\t\tfeGaussianBlur = filter.append('feGaussianBlur').attr('stdDeviation', '2.5').attr('result', 'coloredBlur'),\n\t\tfeMerge = filter.append('feMerge'),\n\t\tfeMergeNode_1 = feMerge.append('feMergeNode').attr('in', 'coloredBlur'),\n\t\tfeMergeNode_2 = feMerge.append('feMergeNode').attr('in', 'SourceGraphic');\n\n /////////////////////////////////////////////////////////\n /////////////// Draw the Circular grid //////////////////\n /////////////////////////////////////////////////////////\n\n function drawAxis() {\n d3.select(id).select(\"g.axisWrapper\").remove();\n\n //Wrapper for the grid & axes\n var axisGrid = g.append(\"g\").attr(\"class\", \"axisWrapper\");\n\n //Draw the background circles\n axisGrid.selectAll(\".levels\")\n .data(d3.range(1, (cfg.levels + 1)).reverse())\n .enter()\n .append(\"circle\")\n .attr(\"class\", \"gridCircle\")\n .attr(\"r\", function (d, i) { return radius / cfg.levels * d; })\n .style(\"fill\", \"#CDCDCD\")\n .style(\"stroke\", \"#CDCDCD\")\n .style(\"fill-opacity\", cfg.opacityCircles)\n .style(\"filter\", \"url(#glow)\");\n\n //Text indicating at what % each level is\n axisGrid.selectAll(\".axisLabel\")\n .data(d3.range(1, (cfg.levels + 1)).reverse())\n .enter().append(\"text\")\n .attr(\"class\", \"axisLabel\")\n .attr(\"x\", 4)\n .attr(\"y\", function (d) { return -d * radius / cfg.levels; })\n .attr(\"dy\", \"0.4em\")\n .style(\"font-size\", \"10px\")\n .attr(\"fill\", \"#737373\")\n .text(function (d, i) { return Format(maxValue * d / cfg.levels); });\n\n /////////////////////////////////////////////////////////\n //////////////////// Draw the axes //////////////////////\n /////////////////////////////////////////////////////////\n\n //Create the straight lines radiating outward from the center\n var axis = axisGrid.selectAll(\".axis\")\n .data(allAxis)\n .enter()\n .append(\"g\")\n .attr(\"class\", \"axis\");\n //Append the lines\n axis.append(\"line\")\n .attr(\"x1\", 0)\n .attr(\"y1\", 0)\n .attr(\"x2\", function (d, i) { return rScale(maxValue * 1.1) * Math.cos(angleSlice * i - Math.PI / 2); })\n .attr(\"y2\", function (d, i) { return rScale(maxValue * 1.1) * Math.sin(angleSlice * i - Math.PI / 2); })\n .attr(\"class\", \"line\")\n .style(\"stroke\", \"white\")\n .style(\"stroke-width\", \"2px\");\n\n //Append the labels at each axis\n axis.append(\"text\")\n .attr(\"class\", \"legend\")\n .style(\"font-size\", \"11px\")\n .attr(\"text-anchor\", \"middle\")\n .attr(\"dy\", \"0.35em\")\n .attr(\"x\", function (d, i) { return rScale(maxValue * cfg.labelFactor) * Math.cos(angleSlice * i - Math.PI / 2); })\n .attr(\"y\", function (d, i) {\n //console.log(\" ==== = \");\n //console.log(maxValue);\n //console.log(cfg.labelFactor);\n //console.log(angleSlice);\n //console.log(i);\n //console.log(Math.PI);\n //console.log(rScale(maxValue * cfg.labelFactor));\n //console.log(Math.sin(angleSlice * i - Math.PI / 2));\n //console.log(rScale(maxValue * cfg.labelFactor) * Math.sin(angleSlice * i - Math.PI / 2) + 30);\n return rScale(maxValue * cfg.labelFactor) * Math.sin(angleSlice * i - Math.PI / 2) - 40;\n })\n .text(function (d) { return d })\n .call(wrap, cfg.wrapWidth);\n }\n /////////////////////////////////////////////////////////\n ///////////// Draw the radar chart blobs ////////////////\n /////////////////////////////////////////////////////////\n\n //The radial line function\n var radarLine = d3.svg.line.radial()\n\t\t.interpolate(\"linear-closed\")\n\t\t.radius(function (d) { return rScale(d.value); })\n\t\t.angle(function (d, i) { return i * angleSlice; });\n\n if (cfg.roundStrokes) {\n radarLine.interpolate(\"cardinal-closed\");\n }\n\n function drawWrapper(dateIndex) {\n d3.select(id).selectAll(\"g.radarWrapper\").remove();\n //Create a wrapper for the blobs\n var g = d3.select(id).select(\"svg > g\");\n //console.log(\" > dateIndex : \" + dateIndex);\n //console.log(data[dateIndex])\n var blobWrapper = g.selectAll(\".radarWrapper\")\n .data(data[dateIndex].Data)\n .enter().append(\"g\")\n .attr(\"class\", function (d) { return \"radarWrapper \" + returnNULL(d.region) + \" \" + isHidden(d.region)});\n //console.log(blobWrapper);\n //console.log(blobWrapper);\n //Append the backgrounds\t\n blobWrapper\n .append(\"path\")\n .attr(\"class\", \"radarArea\")\n .attr(\"d\", function (d, i) {\n //console.log(d);\n return radarLine(d.axes);\n })\n //.style(\"fill\", function (d, i) { return cfg.color(i); })\n .style(\"fill\", function (d, i) { return regionColor(d.region); })\n .style(\"fill-opacity\", cfg.opacityArea)\n .on('mouseover', function (d, i) {\n //Dim all blobs\n d3.selectAll(\".radarArea\")\n .transition().duration(200)\n .style(\"fill-opacity\", 0.1);\n //Bring back the hovered over blob\n d3.select(this)\n .transition().duration(200)\n .style(\"fill-opacity\", 0.7);\n //console.log(d);\n tooltip.transition()\n .duration(200)\n .style(\"opacity\", .9);\n console.log(d);\n var _html = d.region + \" : <br />\";\n for (var i = 0; i < d.axes.length; i++) {\n _html += d.axes[i].axis + \" : \" + Format(d.axes[i].value) + \"<br />\";\n }\n \n tooltip.html(_html)\n .style(\"left\", (d3.event.pageX) + \"px\")\n .style(\"top\", (d3.event.pageY - 28) + \"px\");\n })\n .on('mouseout', function () {\n //Bring back all blobs\n d3.selectAll(\".radarArea\")\n .transition().duration(200)\n .style(\"fill-opacity\", cfg.opacityArea);\n tooltip.transition()\n .duration(200)\n .style(\"opacity\", 0);\n });\n\n //Create the outlines\t\n blobWrapper.append(\"path\")\n .attr(\"class\", \"radarStroke\")\n .attr(\"d\", function (d, i) {\n //console.log(d.axises[dateIndex].axes);\n //console.log(d);\n return radarLine(d.axes);\n })\n .style(\"stroke-width\", cfg.strokeWidth + \"px\")\n //.style(\"stroke\", function (d, i) { return cfg.color(i); })\n .style(\"stroke\", function (d, i) { return regionColor(d.region); })\n .style(\"fill\", \"none\")\n .style(\"filter\", \"url(#glow)\");\n\n //Append the circles\n blobWrapper.selectAll(\".radarCircle\")\n .data(function (d, i) {\n //console.log(d);\n return d.axes;\n })\n .enter().append(\"circle\")\n .attr(\"class\", \"radarCircle\")\n .attr(\"r\", cfg.dotRadius)\n .attr(\"cx\", function (d, i) { return rScale(d.value) * Math.cos(angleSlice * i - Math.PI / 2); })\n .attr(\"cy\", function (d, i) { return rScale(d.value) * Math.sin(angleSlice * i - Math.PI / 2); })\n //.style(\"fill\", function (d, i, j) { return cfg.color(j); })\n .style(\"fill\", function (d, i, j) { return regionColor(d.region); })\n .style(\"fill-opacity\", 0.8);\n }\n /////////////////////////////////////////////////////////\n //////// Append invisible circles for tooltip ///////////\n /////////////////////////////////////////////////////////\n\n function drawCircleWrapper(dateIndex) {\n //console.log(id);\n d3.select(id).selectAll(\"g.radarCircleWrapper\").remove();\n //Wrapper for the invisible circles on top\n var blobCircleWrapper = g.selectAll(\".radarCircleWrapper\")\n .data(data[dateIndex].Data)\n .enter().append(\"g\")\n .attr(\"class\", function (d) { return \"radarCircleWrapper \" + d.region; });\n\n //Append a set of invisible circles on top for the mouseover pop-up\n blobCircleWrapper.selectAll(\".radarInvisibleCircle\")\n .data(function (d, i) { return d.axes; })\n .enter().append(\"circle\")\n .attr(\"class\", \"radarInvisibleCircle\")\n .attr(\"r\", cfg.dotRadius * 1.5)\n .attr(\"cx\", function (d, i) { return rScale(d.value) * Math.cos(angleSlice * i - Math.PI / 2); })\n .attr(\"cy\", function (d, i) { return rScale(d.value) * Math.sin(angleSlice * i - Math.PI / 2); })\n .style(\"fill\", \"none\")\n .style(\"pointer-events\", \"all\");\n //.on(\"mouseover\", function (d, i) {\n // newX = parseFloat(d3.select(this).attr('cx')) - 10;\n // newY = parseFloat(d3.select(this).attr('cy')) - 10;\n\n // tooltip\n // .attr('x', newX)\n // .attr('y', newY)\n // .text(Format(d.value))\n // .transition().duration(200)\n // .style('opacity', 1);\n //})\n //.on(\"mouseout\", function () {\n // tooltip.transition().duration(200)\n // .style(\"opacity\", 0);\n //});\n }\n\n\n //Set up the small tooltip for when you hover over a circle\n //var tooltip = g.append(\"text\")\n\t//\t.attr(\"class\", \"tooltip\")\n\t//\t.style(\"opacity\", 0);\n\n /////////////////////////////////////////////////////////\n /////////////////// Helper Function /////////////////////\n /////////////////////////////////////////////////////////\n\n //Taken from http://bl.ocks.org/mbostock/7555321\n //Wraps SVG text\t\n //var _play_state = 0;\n\n function wrap(text, width) {\n text.each(function () {\n var text = d3.select(this),\n words = text.text().split(/\\s+/).reverse(),\n word,\n line = [],\n lineNumber = 0,\n lineHeight = 1.4, // ems\n y = text.attr(\"y\"),\n x = text.attr(\"x\"),\n dy = parseFloat(text.attr(\"dy\")),\n tspan = text.text(null).append(\"tspan\").attr(\"x\", x).attr(\"y\", y).attr(\"dy\", dy + \"em\");\n\n while (word = words.pop()) {\n line.push(word);\n tspan.text(line.join(\" \"));\n if (tspan.node().getComputedTextLength() > width) {\n line.pop();\n tspan.text(line.join(\" \"));\n line = [word];\n tspan = text.append(\"tspan\").attr(\"x\", x).attr(\"y\", y).attr(\"dy\", ++lineNumber * lineHeight + dy + \"em\").text(word);\n }\n }\n });\n }//wrap\t\n\n function changeTimeFrame(newDateIndex) {\n if (newDateIndex == _dateIndex) return;\n _dateIndex = newDateIndex;\n if (newDateIndex > _maxDateIndex) {\n _dateIndex = _maxDateIndex;\n } else if (newDateIndex < 0) {\n _dateIndex = 0;\n }\n allAxis = (data[_dateIndex].Data[0].axes.map(function (i, j) { return i.axis })),\t//Names of each axis\n total = allAxis.length,\t\t\t\t\t//The number of different axes\n angleSlice = Math.PI * 2 / total;\t\t//The width in radians of each \"slice\"\n //drawAxis();\n //drawRegion(newDate);\n drawWrapper(_dateIndex);\n //drawCircleWrapper(newDate);\n }\n\n function drawTimeSlider(minDate, maxDate, callback) {\n var _minDate = new Date(minDate), _maxDate = new Date(maxDate);\n var curDate = _maxDate;\n var _isPlaying = false;\n var _interval = 1;\n var playAct;\n\n var svg = d3.select(\"svg#timeSlider\"),\n margin = { right: 30, left: 30 },\n width = +svg.attr(\"width\") - margin.left - margin.right,\n height = +svg.attr(\"height\");\n\n var months = monthDiff(_minDate, _maxDate);\n //console.log(_minDate);\n //console.log(_maxDate);\n //console.log(months);\n var _curVal = months + 1;\n var x = d3.scale.linear()\n .domain([0, _curVal])\n .range([0, width])\n .clamp(true);\n\n var slider = svg.append(\"g\")\n .attr(\"class\", \"slider\")\n .attr(\"transform\", \"translate(\" + margin.left + \",\" + 10 + \")\");\n //.attr(\"transform\", \"translate(\" + margin.left + \",\" + height / 2 + \")\");\n //var _startDate = new Date(minDate);\n\n slider.append(\"line\")\n .attr(\"class\", \"track\")\n .attr(\"x1\", x.range()[0])\n .attr(\"x2\", x.range()[1])\n .select(function () { return this.parentNode.appendChild(this.cloneNode(true)); })\n .attr(\"class\", \"track-inset\")\n .select(function () { return this.parentNode.appendChild(this.cloneNode(true)); })\n .attr(\"class\", \"track-overlay\")\n .call(d3.behavior.drag()\n //.on(\"start.interrupt\", function () { slider.interrupt(); })\n .on(\"dragstart\", function () {\n //console.log(\"start \" + x.invert(d3.mouse(this)[0]));\n updateValue(x.invert(d3.mouse(this)[0]));\n //slider.interrupt();\n })\n .on(\"drag\", function () {\n //slider.interrupt();\n //console.log(\"drag \" + d3.event.x);\n updateValue(x.invert(d3.event.x));\n //hue(x.invert(d3.event.x));\n if ((callback != undefined) && (typeof callback == \"function\")) callback(_curVal);\n })\n .on(\"dragend\", function () {\n //console.log(Math.round(x.invert(d3.event.x)));\n //console.log(_curVal);\n if ((callback != undefined) && (typeof callback == \"function\")) {\n callback(_curVal);\n }\n }));\n\n var _startMonth = _minDate.getMonth();\n //console.log(\"Start Month : \" + _startMonth);\n\n var timeticks = slider.insert(\"g\", \".track-overlay\")\n .attr(\"class\", \"ticks\")\n .attr(\"transform\", \"translate(0,\" + 18 + \")\")\n .selectAll(\"text\")\n .data(x.ticks(months + 1))\n .enter();\n timeticks.append(\"text\")\n .attr(\"x\", x)\n .attr(\"y\", function (d, i) {\n if ((_startMonth == 0 && (d % 12) == 0) || (d % 12) == (12 - _startMonth)) {\n return 10;\n } else {\n return 0;\n }\n //var dt = addMonths(_minDate, d);\n //console.log(\"m : \" + dt.getMonth() + \" : \" + (d % 12) + \" : \" + _startMonth);\n //if (dt.getMonth() == 1) {\n // return 0;\n //}\n //else {\n // return -5;\n //}\n })\n .attr(\"text-anchor\", \"middle\")\n .text(function (d) {\n var dt = addMonths(_minDate, d);\n //if (dt.getMonth() == 1) {\n\n if ((_startMonth == 0 && (d % 12) == 0) || (d % 12) == (12 - _startMonth)) {\n return formatDate(dt);\n }\n else {\n return formatDate(dt, \"m\");\n }\n\n });\n timeticks.append(\"line\")\n .attr(\"x1\", x).attr(\"y1\", -25)\n .attr(\"x2\", x).attr(\"y2\", function (d) { return (((_startMonth == 0 && (d % 12) == 0) || (d % 12) == (12 - _startMonth)) ? \"-2\" : \"-10\"); })\n .attr(\"class\", function (d, i) {\n return ((_startMonth == 0 && (d % 12) == 0) || (d % 12) == (12 - _startMonth)) ? \"tickdot\" : \"tickline\";\n });\n\n var handle = slider.insert(\"circle\", \".track-overlay\")\n .attr(\"class\", \"handle\")\n .attr(\"r\", 5);\n\n slider.transition() // Gratuitous intro!\n .duration(750)\n .tween(\"hue\", function () {\n //var i = d3.interpolate(0, 70);\n //console.log(i);\n return function (t) {\n //console.log(t);\n updateValue(_curVal);\n //updateValue(t);\n // hue(i(t));\n };\n });\n\n updateDate(_maxDate);\n\n\n document.getElementById(\"btnPlay\").addEventListener(\"click\", function () {\n if (_isPlaying) {\n //console.log(\"stop\");\n window.clearInterval(playAct);\n _isPlaying = false;\n d3.select(\"#btnPlay>i\").classed(\"fa-play\",true).classed(\"fa-pause\",false);\n } else {\n //console.log(\"play\");\n _isPlaying = true;\n if (_curVal == _maxDateIndex) _curVal = 0;\n //_dateIndex = 0;\n //document.getElementById(\"rangeControlledByDate\").value = _dateIndex;\n //updateValue(_dateIndex);\n //if (callback && (typeof callback === \"function\")) callback(_dateIndex);\n //updateTimeFrame(_dateIndex);\n d3.select(\"#btnPlay>i\").classed(\"fa-play\", false).classed(\"fa-pause\", true);\n playAct = window.setInterval(function () {\n //console.log(\"playing\");\n //console.log(\"curval : \" + _curVal);\n _curVal++;\n //document.getElementById(\"rangeControlledByDate\").value = _dateIndex;\n //updateTimeFrame(_dateIndex);\n //console.log(_dateIndex);\n if (_curVal > _maxDateIndex) {\n _curVal = _maxDateIndex;\n window.clearInterval(playAct);\n _isPlaying = false;\n d3.select(\"#btnPlay>i\").classed(\"fa-play\", true).classed(\"fa-pause\", false);\n } else {\n updateValue(_curVal);\n //console.log(\"curval : \" + _curVal);\n if (callback && (typeof callback === \"function\")) callback(_curVal);\n }\n }, (_interval * 1000));\n }\n });\n\n function updateDate(date) {\n curDate = date;\n var _months = monthDiff(_minDate, curDate);\n hue(_months);\n }\n function updateValue(data) {\n var val = Math.round(data);\n _curVal = val;\n //console.log(\"val\" + val);\n hue(val);\n //handle.attr(\"cx\", x(val));\n //var newDate = addMonths(_minDate, val);\n //d3.select(\"#divInfo\").text(newDate);\n curDate = addMonths(_minDate, val);\n //d3.select(\"#divInfo\").text(formatDate(curDate));\n d3.select(\"#divDate > .year\").text(curDate.getFullYear());\n d3.select(\"#divDate > .month\").text(pad(curDate.getMonth() + 1, 2));\n }\n function hue(h) {\n //console.log(h);\n handle.attr(\"cx\", x(h));\n //svg.style(\"background-color\", d3.hsl(h, 0.8, 0.8));\n }\n function addMonths(curDate, monthInterval) {\n var result = new Date(_minDate);\n //console.log(result);\n return new Date(result.setMonth(result.getMonth() + monthInterval));\n }\n function pad(n, width, z) {\n z = z || '0';\n n = n + '';\n return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;\n }\n function formatDate(curDate, ft) {\n var result;\n if (ft == undefined) {\n result = curDate.getFullYear() + \"-\";\n } else if (ft == \"m\") {\n result = \"\";\n } else {\n result = \"'\" + curDate.getFullYear().toString().substring(2, 4) + \"-\";\n }\n var month = (curDate.getMonth() + 1);\n result += (month < 10 ? \"0\" + month : month);\n return result;\n //return curDate.getFullYear() + \"-\" + curDate.getMonth();// + \"-\" + date.getDate();\n }\n function monthDiff(d1, d2) {\n var months;\n months = (d2.getFullYear() - d1.getFullYear()) * 12;\n months -= d1.getMonth() + 1;\n months += d2.getMonth();\n return months <= 0 ? 0 : months;\n }\n }\n\n //drawTimeFrame();\n drawTimeSlider(data[0].FileMonth, data[data.length - 1].FileMonth, changeTimeFrame);\n drawRegion(_dateIndex);\n drawAxis();\n drawWrapper(_dateIndex);\n drawCircleWrapper(_dateIndex);\n}//RadarChart",
"function RadarPlot(num) {\n var radarMode = 1; // 0=teal(static); 1 = average score fill; 2 = score cluster fill\n var hilite = -1;\n \n var nRadar; // Number of dimensions in Radar Plot\n var scores;\n var names;\n var avgScore;\n\n nRadar = num;\n scores = new Array();\n names = new Array();\n avgScore = 0;\n \n for (var i=0; i<nRadar; i++) {\n names.push(\"\");\n scores.push(0.5);\n }\n \n \n this.setName = function(index, name) {\n if (index < nRadar) {\n names[index] = name;\n }\n }\n \n this.setScore = function(index, value) {\n if (index < nRadar) {\n scores[index] = min(value, 1.0);\n }\n }\n \n this.updateAvg = function() {\n avgScore = 0;\n for (var i=0; i<nRadar; i++) {\n avgScore += scores[i];\n }\n avgScore /= nRadar;\n }\n \n var rot = 0.25*PI;\n this.draw = function(x, y, d) { \n\n strokeWeight(2); \n if (nRadar > 2) {\n \n //Draws radar plot\n for (var i=0; i<nRadar; i++) {\n \n //Draws axes\n stroke(\"#999999\");\n line(x, y, d*cos(rot+i*2*PI/nRadar) + x, d*sin(rot+i*2*PI/nRadar) + y);\n \n //Determine color\n \n \n //draw fills\n noStroke();\n fill(textColor, 100);\n triangle(x, y, (scores[i])*d*cos(rot+i*2*PI/nRadar) + x, \n (scores[i])*d*sin(rot+i*2*PI/nRadar) + y, \n (scores[(i+1)%nRadar])*d*cos(rot+(i+1)%nRadar*2*PI/nRadar) + x, \n (scores[(i+1)%nRadar])*d*sin(rot+(i+1)%nRadar*2*PI/nRadar) + y);\n \n //scores\n textAlign(CENTER, CENTER);\n //recolor for the scores\n if((scores[i]) <= .5){\n RG = lerpColor(color(250, 0, 0),color(255, 255, 0), (scores[i]));}\n else{\n RG = lerpColor(color(255, 255, 0),color(0, 200, 0), (scores[i]));}\n \n fill(RG); \n if((d+12)*sin(rot+i*2*PI/nRadar) + y < y){\n text(int(100*(scores[i])) + \"%\", (d+12)*cos(rot+i*2*PI/nRadar) + x, (d+12)*sin(rot+i*2*PI/nRadar) + y + 15);\n }\n else{\n text(int(100*(scores[i])) + \"%\", (d+12)*cos(rot+i*2*PI/nRadar) + x, (d+12)*sin(rot+i*2*PI/nRadar) + y + 13 + 15);\n }\n \n //names\n fill(textColor);\n textAlign(CENTER);\n if((d+12)*sin(rot+i*2*PI/nRadar) + y - 7 < y){\n text(names[i], (d+12)*cos(rot+i*2*PI/nRadar) + x, (d+12)*sin(rot+i*2*PI/nRadar) + y - 7);\n }\n else{\n text(names[i], (d+12)*cos(rot+i*2*PI/nRadar) + x, (d+12)*sin(rot+i*2*PI/nRadar) + y + 5);\n }\n }\n\n }\n }\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 draw_optimal_arm_percentage_graph(data) {\n var title = \"Percentage of Optimal Arm Play\"\n var y_title = \"Percentage\"\n var String_title = [title, y_title]\n var mean = data[\"optimal_arm_percentage\"][0]\n var std = data[\"optimal_arm_percentage\"][1]\n var input_data = {'String_title': String_title, 'mean': mean, 'std': std}\n draw_ROA(input_data)\n}",
"function drawChart() {\n\n let data = google.visualization.arrayToDataTable([\n ['City', 'Number of Employees'],\n ['Boston', boston],\n ['Orlando', orlando],\n ['Chicago', chicago],\n ['San Francisco', sanfran]\n ]);\n\n let options = {\n title: 'Number & Percentage of Employees',\n pieHole: 0.5,\n pieSliceText: 'value'\n };\n\n let chart = new google.visualization.PieChart(document.getElementById('donutchart'));\n chart.draw(data, options);\n }",
"function displayEliminatePlantIconWithCursor(e) {\n if ( !ambientMode ) { \n var displayIcon = false;\n for ( var i=0; i<plants.length; i++ ) {\n var p = plants[i];\n if ( p.isAlive || (!p.hasCollapsed && !p.hasBeenEliminatedByPlayer) ) {\n for ( var j=0; j<p.segments.length; j++) {\n var s = p.segments[j];\n var xDiffPct1 = pctFromXVal( s.ptE1.cx ) - mouseCanvasXPct;\n var yDiffPct1 = pctFromYVal( s.ptE1.cy ) - mouseCanvasYPct;\n var distancePct1 = Math.sqrt( xDiffPct1*xDiffPct1 + yDiffPct1*yDiffPct1 );\n var xDiffPct2 = pctFromXVal( s.ptE2.cx ) - mouseCanvasXPct;\n var yDiffPct2 = pctFromYVal( s.ptE2.cy ) - mouseCanvasYPct;\n var distancePct2 = Math.sqrt( xDiffPct2*xDiffPct2 + yDiffPct2*yDiffPct2 );\n var selectRadiusPct = selectRadius*100/canvas.width;\n if ( distancePct1 <= selectRadiusPct*2 || distancePct2 <= selectRadiusPct*2 ) {\n displayIcon = true;\n }\n }\n }\n }\n if ( displayIcon ) {\n var xo = selectRadius*0.06; // x offset\n var yo = selectRadius*0.1; // y offset\n ctx.fillStyle = \"rgba(232,73,0,0.5)\";\n ctx.strokeStyle = \"rgba(232,73,0,1)\";\n //circle\n ctx.beginPath();\n ctx.lineWidth = 1;\n ctx.arc( xValFromPct(mouseCanvasXPct), yValFromPct(mouseCanvasYPct-yo), selectRadius, 0, 2*Math.PI );\n ctx.fill();\n ctx.stroke();\n //bar\n ctx.beginPath();\n ctx.lineWidth = selectRadius*0.3;\n ctx.lineCap = \"butt\";\n ctx.moveTo( xValFromPct(mouseCanvasXPct-xo), yValFromPct(mouseCanvasYPct-yo) );\n ctx.lineTo( xValFromPct(mouseCanvasXPct+xo), yValFromPct(mouseCanvasYPct-yo) );\n ctx.fill();\n ctx.stroke();\n }\n }\n}",
"function DrawChord(trips){\n\tvar streetnames = []\n\tfor (var i = 0; i < trips.length; i++) {\n\t\tfor (var j = 0; j < trips[i].streetnames.length; j++) {\n\t\t\tstreetnames.push(trips[i].streetnames[j]);\n\t\t}\n\t}\n\t\n\tvar myConfig = {\n\t\t\"type\": \"chord\",\n\t\tplot:{\n\t\t\tanimation:{\n\t\t\t effect: 4,\n\t\t\t method: 0,\n\t\t\t sequence: 1\n\t\t\t}\n\t\t},\n\t\t\"options\": {\n\t\t \"radius\": \"90%\"\n\t\t},\n\t\t\"plotarea\": {\n\t\t \"margin\": \"dynamic\"\n\t\t},\n\t\t\"series\": [{\n\t\t \"values\": [trips[0].streetnames.length,trips[1].streetnames.length,trips[2].streetnames.length,trips[3].streetnames.length],\n\t\t \"text\": \"Street Names\"\n\t\t}, {\n\t\t \"values\": [trips[0].streetnames.length,trips[1].streetnames.length,trips[2].streetnames.length,trips[3].streetnames.length],\n\t\t \"text\": \"Average Speed\"\n\t\t}, {\n\t\t \"values\": [trips[0].streetnames.length,trips[1].streetnames.length,trips[2].streetnames.length,trips[3].streetnames.length],\n\t\t \"text\": \"Distance\"\n\t\t}, {\n\t\t \"values\": [trips[0].streetnames.length,trips[1].streetnames.length,trips[2].streetnames.length,trips[3].streetnames.length],\n\t\t \"text\": \"Duration\"\n\t\t}]\n\t };\n\t \n\t zingchart.render({\n\t\tid: 'myChart',\n\t\tdata: myConfig,\n\t\theight: \"100%\",\n\t\twidth: \"100%\",\n\t });\n}",
"function initChart(jsonarray) {\n plotedPoints=plotedPoints+jsonarray.length;\n //c3.js é uma biblioteca para plotar gráficos\n //veja a documentação do C3 em http://c3js.org/reference.html e exemplos em http://c3js.org/examples.html\n chart = c3.generate({\n transition: {\n //duration: 200//tempo do efeito especial na hora de mostrar o gráfico\n },\n bindto: \"#\" + chart_bindToId,//indica qual o ID da div em que o gráfico deve ser desenhado\n zoom: {\n enabled: true //permite ou não o zoom no gráfico\n },\n point: {\n show: false//mostra ou esconde as bolinhas na linha do gráfico\n },\n\n data: {\n json:jsonarray,// dados json a serem plotados\n\n keys: {\n x: chart_XData,//item do json correspondente ao eixo X\n value: [chart_YData] ,//item do json correspondente ao eixo Y\n },\n names: {\n [chart_YData]: chart_LineName//nome da linha plotada\n }\n ,\n colors: {\n [chart_YData]: '#E30613'//cor da linha\n }\n\n },\n axis: {\n x: {\n type : 'timeseries',//tipo do gráfico a ser plotado\n tick: {\n format: chart_Xformat,//formato dos dados no eixo X\n rotate: 45//rotação do texto dos dados no eixo X\n },\n label: {\n text: chart_XLabel,//nome do eixo X\n position: 'inner-middle'//posição do nome do eixo X\n }\n\n },\n\n y: {\n label: {\n text: chart_YLabel,//nome do eixo Y\n position: 'outer-middle'//posição do nome do eixo Y\n }\n }\n },\n\n tooltip: {\n show: true,\n format: {\n value: function (value, ratio, id, index) { return value + \" \" + chart_TooltipUnit; }\n }\n }\n });\n }",
"function displayChartTopProperty1(topProperty, position, index,chartWidth,chartHeight,fontSize,notePosition) {\n\t\tvar props = indicators[topProperty];\n\t\t//console.log(topProperty);\n\n\t\tvar data = new google.visualization.DataTable();\n data.addColumn('string', 'Location');\n data.addColumn('number', 'value'/*props[0].proplabel*/);\n\t\tdata.addColumn('number', 'value'/*props[0].proplabel*/);\n\t\tdata.addColumn('number', 'value'/*props[0].proplabel*/);\n\t\tdata.addRows(props.length);\n\n\t\tfor (var i=0; i<props.length; i++) {\n\t\t\tdata.setValue(i, 0, props[i].geolabel);\n\t\t\tif (props[i].geo == locationURI) \n\t\t\t\tdata.setValue(i, 3, parseFloat(props[i].val));\t\t\t\n\t\t\telse if (props[i].geo == 'Average') \n\t\t\t\tdata.setValue(i, 2, parseFloat(props[i].val));\n\t\t\telse\n\t\t\t\tdata.setValue(i, 1, parseFloat(props[i].val));\n\t\t}\n\t\t\n\t\t$('#top-1-position').html(\"# \" + position +\" \");\n\t\t$('#top-1-position-description').html(\"<ul><li>\" + props[0].top1label + \"<\\/li><ul><li>\" + props[0].top2label + \"</li><ul><li>\" + props[0].proplabel + \"<\\/li><\\/ul><\\/ul><\\/ul>\");\n\t\t\n\t\tvar legend = \"<div style=\\\"float:left; font-family: 'Tienne', serif; font-size: 14px;\\\"><div style=\\\"width: 15px; height: 15px; background: #736F6E; float:left;\\\"> </div> All counties/cities </div>\" +\n\t\t\t\t\t \"<div style=\\\"float:left; font-family: 'Tienne', serif; font-size: 14px;\\\"><div style=\\\"width: 15px; height: 15px; background: #382D2C; float:left;\\\"> </div> Average </div> \" +\n\t\t\t\t\t \"<div style=\\\"float:left; font-family: 'Tienne', serif; font-size: 14px;\\\"><div style=\\\"width: 15px; height: 15px; background: #306754; float:left;\\\"> </div> Current County/City </div>\";\n\n\t\t$('#top-1-chart-legend-container').html(legend);\n\t\t\n\t\tvar barsVisualization = new google.visualization.ColumnChart(document.getElementById('chart_div_top_'+index));\n\t\tbarsVisualization.draw(data, { /*chartArea: {left:25,top:10,width:\"75%\",height:\"70%\"},*/ width: chartWidth, height: chartHeight, colors:['#736F6E','#382D2C','#306754'], legend:'none', isStacked:'true', backgroundColor: '#F7F7F7', hAxis:{textStyle: {color: \"black\", fontName: \"sans-serif\", fontSize: fontSize} } }); //, vAxis: {title:'hola', titleTextStyle:'', color: '#FF0000' }\n\n\t\t$('#top-1-chart-notes-description').css(\"top\",\"\"+notePosition+\"px\");\n\t\t$('#top-1-chart-notes-description').html(\"Place your mouse over each bar to get more information.\");\n\t\t\n\t\n\t}",
"function drawRadar(rings, sectors){\n\n\t\t// calculate pie segments for equal sized sectors\n\t\tvar pie = d3.layout.pie()\n\t\t\t.value(function() { return 1; })\n\t\t\t.sort(null);\n\n\t\t// setup arc functions for all rings\n \tvar arcs = [];\n\t\tvar ringRadius = (radius / rings.length + 1);\n\t\tfor (var i = 0; i < rings.length; i++){\n\t\t\tvar arc = d3.svg.arc()\n\t\t\t\t.innerRadius(i * ringRadius)\n\t\t\t\t.outerRadius((i * ringRadius) + ringRadius);\n\t\t\tarcs.push(arc);\n\t\t}\n\n\t\t// draw all rings / sectors\n\t\tfor (i = 0; i < rings.length; i++){\n\t\t\tvar g = container.selectAll(\"empty\")\n\t\t\t\t.data(pie(sectors))\n\t\t\t\t.enter()\n\t\t\t\t.append(\"g\")\n\t\t\t\t.attr(\"class\", function(d,si){return rings[i].name + \" \" + sectors[si].name;})\n\n\t\t\tg.append(\"path\")\n\t\t\t\t.attr(\"d\", arcs[i])\n\n\t\t\tg.attr(\"transform\", \"translate(\" + width / 2 + \",\" + height / 2 + \")\");\n\t\t}\n\t}",
"function draw_trajectories() {\n\tcancelAnimationFrame(animation_enabled);\n\tblue = 0x4A56FF;\n\tred = 0xFC5656;\n\n\tfor(var i = 0; i < waterpolarity_particles.length; i++) {\n\t\tcharge = waterpolarity_particles[i].charge;\n\t\tmarker_color = (charge == -1.0) ? blue : red;\n\t\tpositions = waterpolarity_positions[i];\n\t\t\n\t\tfor(var j = 0; j < positions.length; j++) {\n\t\t\tmarker = new PIXI.Graphics();\n\t\t\tmarker.beginFill(marker_color);\n\t\t\tmarker.drawCircle(positions[j].x,positions[j].y,2);\n\t\t\tmarker.endFill();\n\t\t\t\n\t\t\twaterpolarity_stage.addChild(marker);\n\t\t}\n\t}\n\twaterpolarity_renderer.render(waterpolarity_stage);\n}",
"generatePieChart(res) {\n const inputs = res.queryInput;\n const characteristicGroups = res.results[0].values;\n // const indicator = Utility.getStringById(inputs.indicators[0][\"label.id\"]);\n const dataPoints = res.results;\n const precision = res.chartOptions.precision;\n return {\n chart: this.generateChartSettings(),\n title: this.generateTitle(inputs),\n subtitle: this.generateSubtitle(),\n tooltip: this.generateToolTip(precision),\n plotOptions: {\n pie: {\n allowPointSelect: true,\n cursor: 'pointer',\n dataLabels: {\n enabled: true,\n format: '<b>{point.name}</b>: {point.percentage:.'+precision+'f} %',\n },\n // showInLegend: true\n }\n },\n series: this.generatePieData(\n Selectors.getSelectedValue('select-characteristic-group'),\n characteristicGroups,\n dataPoints\n ),\n credits: this.generateCredits(inputs),\n legend: this.generateLegend(),\n exporting: this.generateExporting(),\n };\n // plotOptions: this.generatePlotOptions(precision),\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
new GL.HitTest([t, hit, normal]) This is the object used to return hit test results. If there are no arguments, the constructed argument represents a hit infinitely far away. | function HitTest(t, hit, normal) {
this.t = arguments.length ? t : Number.MAX_VALUE;
this.hit = hit;
this.normal = normal;
} | [
"function HitDetector() {\r\n this.xOverlap = [0, 0];\r\n this.yOverlap = [0, 0];\r\n this.overlap = [0, 0, null]; // start, end, axis if any\r\n}",
"function new_Hitbox(hitbox)\n{\n\tif(null == hitbox)\n\t\treturn null;\n\treturn new Hitbox(hitbox.width, hitbox.height);\t\n}",
"evaluateHit(ray, source) {\n\t\tlet superHit = super.evaluateHit(ray, source);\n\t\tif (superHit.isHit) {\n\t\t\tlet hitLocation = source.add(ray.scalarMult(superHit.distance));\n\t\t\tif (this.pointIsInThisTriangle(hitLocation)) {\n\t\t\t\treturn superHit;\n\t\t\t} else {\n\t\t\t\treturn new Contact(false);\n\t\t\t}\n\t\t} else {\n\t\t\treturn superHit;\n\t\t}\n\t}",
"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 onHit() {\n this.classList.remove(\"active\");\n this.classList.add(\"target\");\n scoreIncrement();\n time = time - 10;\n}",
"isAlive() {\n if (this.hitPoints = 0){\n \n }\n }",
"createHitbox(obj, func)\r\n {\r\n let adjustedScale = Vector2.scale(Helpers.cssPerPx, obj.scale);\r\n let adjustedPos = Vector2.scale(Helpers.cssPerPx, obj.position);\r\n\r\n let hb = document.createElement(\"div\");\r\n\r\n hb.style.width = adjustedScale.x + \"px\";\r\n hb.style.height = adjustedScale.y + \"px\";\r\n\r\n hb.style.position = \"absolute\";\r\n hb.style.left = adjustedPos.x + \"px\";\r\n hb.style.top = adjustedPos.y + \"px\";\r\n\r\n hb.style.borderRadius = Math.round(Math.max(adjustedScale.x, adjustedScale.y) / 2) + \"px\";\r\n\r\n hb.style.pointerEvents = \"auto\";\r\n\r\n hb.addEventListener(\"click\", (event) => {\r\n this.mouseEvent(event);\r\n func(this.mouse.position);\r\n });\r\n\r\n this.wrapper.appendChild(hb);\r\n }",
"function ConstructHitBoxes() {\n\t\tfunction CreateHitBox(w, h, d, x, y, z, rotx = 0.0, roty = 0.0, rotz = 0.0, area = \"\") {\n\t\t\tvar geo = new THREE.BoxGeometry(w, h, d);\n\t\t\tvar mat = new THREE.MeshBasicMaterial({ color: 0xFFFFFF });\n\t\t\tmat.transparent = true;\n\t\t\tmat.opacity = 0.0;\n\n\t\t\tvar cube = new THREE.Mesh(geo, mat);\n\t\t\tcube.name = \"hitbox\";\n\t\t\tcube[\"selected\"] = false;\n\t\t\tcube[\"hovering\"] = true;\n\t\t\tcube[\"area\"] = area;\n\t\t\tcube.frustumCulled = false;\n\t\t\tscene.add(cube);\n\n\n\t\t\tcube.rotation.x = rotx;\n\t\t\tcube.rotation.y = roty;\n\t\t\tcube.rotation.z = rotz;\n\n\t\t\tcube.position.x = x;\n\t\t\tcube.position.y = y;\n\t\t\tcube.position.z = z;\n\n\t\t}\n\n\t\tCreateHitBox(3.5, 3.2, 0.1, 0.01, 0.5, 1.2, 0.1, 0, 0.0, \"front\"); // front\n\t\tCreateHitBox(3.4, 2.6, 0.1, 0.2, 0.6, -0.17, 0.2, 0.0, 0.0, \"back\"); // back\n\t\tCreateHitBox(0.5, 2.5, 2.4, -1.90, 0.1, 0.4, 0, 0, 0.21, \"frills\"); // left\n\t\tCreateHitBox(0.5, 2.7, 2.4, 2.095, 0.80, 0.4, 0, 0, 0, \"frills\"); // right\n\t\tCreateHitBox(3.4, 1.0, 2.4, 0.2, -1.0, 0.4, 0.0, 0.0, 0.1, \"frills\"); // bottom\n\t}",
"function emitOnHit(event) {\r\n if (self.onHit) {\r\n self.onHit(event);\r\n }\r\n }",
"function enemyHit(enemy, projectile) {\n touch = enemy.intersect(projectile);\n \n if (touch == true) {\n /*Generate new enemy in the game world*/\n points += 1;\n genNewEnemy(enemy);\n \n return true;\n }\n \n return false;\n}",
"function registerHit(node)\n{\n if (node.hit == undefined)\n {\n $.get(\"/hit/\" + node.name, {},\n function(count)\n {\n node.hitCount = count;\n });\n node.hit = true;\n }\n}",
"function RaycastResult(){/**\n\t * @property {Vec3} rayFromWorld\n\t */this.rayFromWorld=new Vec3();/**\n\t * @property {Vec3} rayToWorld\n\t */this.rayToWorld=new Vec3();/**\n\t * @property {Vec3} hitNormalWorld\n\t */this.hitNormalWorld=new Vec3();/**\n\t * @property {Vec3} hitPointWorld\n\t */this.hitPointWorld=new Vec3();/**\n\t * @property {boolean} hasHit\n\t */this.hasHit=false;/**\n\t * The hit shape, or null.\n\t * @property {Shape} shape\n\t */this.shape=null;/**\n\t * The hit body, or null.\n\t * @property {Body} body\n\t */this.body=null;/**\n\t * The index of the hit triangle, if the hit shape was a trimesh.\n\t * @property {number} hitFaceIndex\n\t * @default -1\n\t */this.hitFaceIndex=-1;/**\n\t * Distance to the hit. Will be set to -1 if there was no hit.\n\t * @property {number} distance\n\t * @default -1\n\t */this.distance=-1;/**\n\t * If the ray should stop traversing the bodies.\n\t * @private\n\t * @property {Boolean} _shouldStop\n\t * @default false\n\t */this._shouldStop=false;}",
"function hitTest(node, x, y) {\n var rect = node.getBoundingClientRect();\n return x >= rect.left && x < rect.right && y >= rect.top && y < rect.bottom;\n }",
"function checkHit() {\r\n \"use strict\";\r\n // if torp left and top fall within the ufo image, its a hit!\r\n let ymin = ufo.y;\r\n let ymax = ufo.y + 65;\r\n let xmin = ufo.x;\r\n let xmax = ufo.x + 100;\r\n\r\n\r\n console.log(\"torp top and left \" + torpedo.y + \", \" + torpedo.x);\r\n console.log(\"ymin: \" + ymin + \"ymax: \" + ymax);\r\n console.log(\"xmin: \" + xmin + \"xmax: \" + xmax);\r\n console.log(ufo);\r\n\r\n if (!bUfoExplode) {\r\n // not exploded yet. Check for hit...\r\n if ((torpedo.y >= ymin && torpedo.y <= ymax) && (torpedo.x >= xmin && torpedo.x <= xmax)) {\r\n // we have a hit.\r\n console.log(\" hit is true\");\r\n\r\n bUfoExplode = true; // set flag to show we have exploded.\r\n }// end if we hit\r\n\r\n }// end if not exploded yet\r\n\r\n // reset fired torp flag\r\n bTorpFired = false;\r\n\r\n // call render to update.\r\n render();\r\n\r\n}// end check hit",
"function Ray (\n o = new Point3(),\n d = new Vector3(),\n tMax = Infinity,\n time = 0,\n medium = null\n) {\n this.o = o // Point3\n this.d = d // Vector3\n\n this.tMax = tMax // Number\n this.time = time // Number\n\n this.medium = medium // Medium\n}",
"hitBox(collision){\n\t\tswitch(collision.closestEdge(this.pos.minus(new vec2(this.vel.x, 0)))){\n\t\t\tcase 't': this.hitGround(collision.top()); break;\n\t\t\tcase 'l': this.hitRWall(collision.left()); break;\n\t\t\tcase 'r': this.hitLWall(collision.right()); break;\n\t\t\tcase 'b': this.hitCeiling(collision.bottom()); break;\n\t\t}\n\t}",
"function getHitSuccess(attackType, exposureLevel, attackerSkill, attackerDex, attackerWis, attackerCha, targetAgi, targetWis){\n\n var attackerSkillAverage;\n var defenderSkillAverage;\n \n if(attackType == 1){\n\n attackerSkillAverage = (attackerDex+attackerSkill)/2;\n defenderSkillAverage = targetAgi;\n }else if(attackType == 2){\n //ranged\n }else if(attackType == 3){\n attackerSkillAverage = (attackerWis+attackerSkill)/2;\n defenderSkillAverage = (targetWis+targetAgi)/2;\n }else if(attackType == 4){\n //This is a mild altering attack\n //Charisma should be used by attacker.\n //Agi is not used in defending\n attackerSkillAverage = (attackerWis+attackerSkill+attackerCha)/3;\n defenderSkillAverage = targetWis;\n }\n \n var hitSuccess = calculateDamageHitSuccess(defenderSkillAverage, attackerSkillAverage);\n \n if(hitSuccess < 10) {\n hitSuccess = 0;\n }\n\n hitSuccess = hitSuccess + exposureLevel*10;\n \n\n return hitSuccess;\n}",
"function Predator(x,y,radius,maxSpeed,fillColor) {\n Entity.call(this,x,y,radius,maxSpeed,fillColor);\n}",
"function Enemy(name) {\n this.name = name\n if (name === \"Boogie\") {\n this.hitPoints = 90\n this.item = \"dragon glass dagger\"\n } else if (name === \"Woogie\") {\n this.hitPoints = 70 \n this.item = \"bag o gems\"\n } else {\n this.hitPoints = 50\n this.item = \"silver loot\"\n }\n}",
"_attack() {\n let itemToHitMod = this.inventory.getAllItemStats(\"toHit\");\n let totalToHitMod = this.toHitMod + itemToHitMod\n console.debug(`Player has a toHitMod of ${totalToHitMod} (inc ${itemToHitMod} from items)`);\n return new Attack(this, this.toHitDie, totalToHitMod, this.dmgDie, this.dmgMod);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
normalise_date is a function that sets the timing of the loan to 8am sharp, no matter the time of the actual borrowing. The reason for this is so that messages can be sent promptly at 8am in the morning. | function normalise_date(date) {
// console.log(date);
date.setHours(8,0,0,0);
// console.log(date);
// console.log(Date.parse(date));
return(date);
} | [
"function reset_date() {\n\tconsole.log('resetting or initing date format');\n\tconst RESET = '%q %d, %Y %I:%m%p';\n\tdocument.getElementById('dateFormat').value = RESET;\n\tsaveThing(LS_KEY_DATE, document.getElementById('dateFormat').value);\n\treturn RESET;\n}",
"function FixDateObject (date) {\n\tvar base = new Date(0)\n\tvar skew = base.getTime() // should be zero except on the Mac\n\tif (skew > 0) {\n\t\tdate.setTime(date.getTime() - skew)\n\t}\n}",
"function transformDate(d) {\n return d.substr(6) + '-' + d.substr(3, 2) + '-' + d.substr(0, 2);\n }",
"function format_exercise_date() {\n const field = document.getElementById(\"timestamp\");\n\n if (typeof (field) != 'undefined' && field != null) {\n const m_utc = moment.utc(field.value, \"DD/MM/YYYY HH:mm\");\n const m_local = m_utc.clone().local().format(\"DD/MM/YYYY HH:mm\");\n field.value = m_local;\n }\n}",
"function FixCookieDate(date) {\n var base = new Date(0);\n var skew = base.getTime(); // dawn of (Unix) time - should be 0\n if (skew > 0) // Except on the Mac - ahead of its time\n date.setTime(date.getTime() - skew);\n}",
"function setInitialDate() {\n \n // CREATE A NEW DATE OBJECT (WILL GENERALLY PARSE CORRECT DATE EXCEPT WHEN \".\" IS USED AS A DELIMITER)\n // (THIS ROUTINE DOES *NOT* CATCH ALL DATE FORMATS, IF YOU NEED TO PARSE A CUSTOM DATE FORMAT, DO IT HERE)\n calDate = new Date(inDate);\n\n // IF THE INCOMING DATE IS INVALID, USE THE CURRENT DATE\n if (isNaN(calDate) || inDate == \"\" || inDate == null) {\n\n // ADD CUSTOM DATE PARSING HERE\n // IF IT FAILS, SIMPLY CREATE A NEW DATE OBJECT WHICH DEFAULTS TO THE CURRENT DATE\n calDate = new Date();\n }\n\n // KEEP TRACK OF THE CURRENT DAY VALUE\n calDay = calDate.getDate();\n\n // SET DAY VALUE TO 1... TO AVOID JAVASCRIPT DATE CALCULATION ANOMALIES\n // (IF THE MONTH CHANGES TO FEB AND THE DAY IS 30, THE MONTH WOULD CHANGE TO MARCH\n // AND THE DAY WOULD CHANGE TO 2. SETTING THE DAY TO 1 WILL PREVENT THAT)\n calDate.setDate(1);\n}",
"function normaliseEvent(evt) {\n var duration = {};\n\n if (!evt.dtend) {\n if (evt.duration) {\n duration.original = evt.duration;\n duration.minutes = evt.duration.match(/^PT(\\d+)M$/)[1];\n evt.dtend = new Date();\n evt.dtend.setTime(\n evt.dtstart.getTime() + duration.minutes * 60000);\n } else {\n evt.dtend = evt.dtstart;\n duration.minutes = 0;\n }\n } else {\n duration.minutes = (evt.dtend.getTime() - evt.dtstart.getTime());\n duration.minutes /= 60000;\n }\n\n if (duration.minutes >= 60) {\n duration.hours = Math.floor(duration.minutes / 60);\n duration.minutes -= duration.hours * 60;\n } else {\n duration.hours = 0;\n }\n\n duration.str = pad(duration.hours) + pad(duration.minutes);\n evt.duration = duration;\n\n evt.dtstart.iso8601 = iso8601(evt.dtstart);\n evt.dtend.iso8601 = iso8601(evt.dtend);\n }",
"cutDate(num) {\n return num.substr(1,1);\n }",
"function xmlDateToNormal(x) {\n let day = x.substr(2,2);\n if (day <10)\n day = day.replace(\"0\",\"\");\n let month = x.substr(0,2);\n if (month <10)\n month = month.replace(\"0\",\"\");\n return day + \".\" + month+ \".\";\n}",
"function date_styler(date) {\n var d = new Date(date);\n return d.getFullYear() + '/' + (d.getMonth() + 1) + '/' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();\n }",
"function undayify(n) {\n if (n <= 167) { return splur(n, \"day\") }\n if (n <= 182) { return \"almost 6 months\" }\n if (n <= 197) { return \"over 6 months\" }\n if (n <= 213) { return \"almost 7 months\" }\n if (n <= 228) { return \"over 7 months\" }\n if (n <= 243) { return \"almost 8 months\" }\n if (n <= 258) { return \"over 8 months\" }\n if (n <= 273) { return \"almost 9 months\" }\n if (n <= 289) { return \"over 9 months\" }\n if (n <= 364) { return \"almost a year\" }\n if (n <= 365) { return \"365 days\" }\n if (n <= 511) { return \"over a year\" } // 511d = 1.399y\n if (n <= 547) { return \"almost 1.5 years\" } // 547d = 1.498y\n if (n <= 639) { return \"over 1.5 years\" } // 639d = 1.749y\n if (n <= 729) { return \"almost 2 years\" } // 730d = 1.999y\n if (n <= 731) { return \"~2 years\" } // 366*2 = 732\n if (n <= 913) { return \"over 2 years\" } // 913d = 2.4997y\n var y = Math.floor(n/365.25)\n if (n >= 365*y && n <= 365.25*y) { return `~${y} years` }\n if (n >= 365*(y+1) && n <= 365.25*(y+1)) { return `~${y+1} years` }\n if (n/365.25 - y >= .5) { return `almost ${y+1} years` }\n return `over ${y} years`\n}",
"function formatDateInput(date) {\n if(scope.isDate(date)) {\n var date = moment(date);\n var dateOutputFormat = scope.dateOutputFormat;\n if(date.isSame(new Date, 'year')) {\n dateOutputFormat = scope.dateOutputNoYearFormat;\n }\n return date.format(dateOutputFormat);\n }\n return \"\";\n }",
"function handleClick(){\n sanitizeDateInput();\n sanitizeDepDateInput();\n }",
"dateformat(date) { return \"\"; }",
"function _autoFormattingDate(target){\n\t$(target).focusout(function(){\n\t\tvar string = $(this).val();\n\tif(string.length == 8){\n\t\tstring = string.substring(0, 4) + '/' + string.substring(4, 6) + '/' + string.substring(6);\n\t}\n\tvar reg = /^((19|[2-9][0-9])[0-9]{2})[\\/.](0[13578]|1[02])[\\/.]31|((19|[2-9][0-9])[0-9]{2}[\\/.](01|0[3-9]|1[0-2])[\\/.](29|30))|((19|[2-9][0-9])[0-9]{2}[\\/.](0[1-9]|1[0-2])[\\/.](0[1-9]|1[0-9]|2[0-8]))|((((19|[2-9][0-9])(04|08|[2468][048]|[13579][26]))|2000)[\\/.](02)[\\/.]29)$/;\n\tif (string.match(reg)){\n\t\t$(this).val(string);\n\t} else {\n\t\t$(this).val('');\n\t}\n\t});\n}",
"function datePrecedente(date) {\n var dt = date.split('/');\n var myDate = new Date(dt[2] + '-' + dt[1] + '-' + dt[0]);\n myDate.setDate(myDate.getDate() + -1);\n newDate = formatDateSlash(myDate);\n return newDate;\n}",
"function convertDateInput(input){\n return new Date(input.replace(/-/g, '/'));\n}",
"function Date2StandardFmt( date_string ) {\n if (date_string == \"\")\n return;\n var date_src_string = date_string\n if ((date_string.length!=8 && date_string.length!=10)\n || (date_string.length==10 && date_string.indexOf(\"-\")<0) ) {\n return date_src_string;\n }\n\n // no split character\n if ( date_string.indexOf(\"-\")<0 ) {\n date_string = date_string.substring(0, 4) +\"-\"+date_string.substring(4, 6)+\"-\"+date_string.substring(6);\n }\n\n var date_year = date_string.substring(0, 4);\n var date_month = date_string.substring(5, 7);\n var date_day = date_string.substring(8);\n if ( CheckDate(date_year, date_month, date_day)==false ) {\n return date_src_string;\n }\n return date_string;\n\n}",
"function bookingBefore(e) {\n // Do not allow viewing bookings in the past\n var now = Math.ceil(new Date().getTime() / 1000);\n if(closeDateTime - 86400 * 2 < now)\n document.getElementById(\"bookingBefore\").classList.remove(\"show\");\n if(closeDateTime - 86400 < now)\n return;\n\n // Advance the unix time by one day\n openDateTime -= 86400;\n closeDateTime -= 86400;\n vmMainScreen.now = new Date(vmMainScreen.now.getFullYear(), vmMainScreen.now.getMonth(), vmMainScreen.now.getDate() - 1, vmMainScreen.now.getHours(), vmMainScreen.now.getMinutes());\n refreshBooking();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a WebID and a Resource that exposes information about the owner of the Pod it is in, returns whether the given WebID is the owner of the Pod. Data about the owner of the Pod is exposed when the following conditions hold: The Pod server supports exposing the Pod owner The current user is allowed to see who the Pod owner is. If one or more of those conditions are false, this function will return `null`. | function isPodOwner(webId, resource) {
const podOwner = getPodOwner(resource);
if (typeof podOwner !== "string") {
return null;
}
return podOwner === webId;
} | [
"'entries.isOwner' (entryId) {\n console.log('see if user can access this entry');\n\n // If no user is logged in, throw an error\n if (!Meteor.user()) {\n console.log(\"No user is logged in!\");\n return false;\n }\n \n // Locate the entry\n let entry = JournalEntryCollection.findOne({_id: entryId});\n\n // If no entry exists, the logged in user can't access it\n if (!entry) {\n console.log(`entry with ID ${entryId} wasn't found`);\n return false;\n }\n\n console.log(`Entry found: ${entry._id}, ${entry.text}`);\n\n // If the entry's owner is not the logged in user, they\n // can't access it\n if (entry.ownerId != Meteor.userId()) {\n console.log(`This entry belongs to ${entry.ownerId} but the logged in user is ${Meteor.userId()}`);\n return false;\n }\n\n // The entry exists and the logged in user is the owner,\n // so they can access it\n return true;\n }",
"async function checkOwner(presentationid, userid) {\n let queryIfOwner = `SELECT * FROM public.presentations t\n WHERE id = '${presentationid}' and user_id = '${userid}'`;\n let isOwner = await db.select(queryIfOwner);\n if (isOwner) {\n return true;\n } else {\n return false;\n }\n}",
"isOwner(user) {\n return this.json_.owner._account_id === user._account_id;\n }",
"function isRouteOwner(req, res, next) {\n if (!req.params.user) {\n next(new Error('Invalid route: missing user parameter.'));\n } else if (req.params.user != req.user.username) {\n next(new Error('Is not owner'));\n } else {\n req.isOwner=true;\n next(null);\n }\n}",
"get isOneToOneOwner() {\n return this.isOneToOne && this.isOwning;\n }",
"function find_missing_owners(resp) {\r\n\tlet ledger = (resp) ? resp.parsed : [];\r\n\tlet user_base = helper.getPartUsernames();\r\n\r\n\tfor (let x in user_base) {\r\n\t\tlet found = false;\r\n\t\tlogger.debug('Looking for part owner:', user_base[x]);\r\n\t\tfor (let i in ledger.owners) {\r\n\t\t\tif (user_base[x] === ledger.owners[i].username) {\r\n\t\t\t\tfound = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (found === false) {\r\n\t\t\tlogger.debug('Did not find part username:', user_base[x]);\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}",
"function checkUserOwnsUrl(userID, shortURL) {\n for (var id in urlDatabase) {\n if ((urlDatabase[id].userID === userID) && (urlDatabase[id].shortURL === shortURL)) return true;\n }\n return false;\n}",
"static hasRightToWrite(){\n var idProject = Router.current().params._id\n var project = Projects.findOne(idProject)\n if(!project){\n return false;\n }\n var username = Meteor.user().username\n var participant = $(project.participants).filter(function(i,p){\n return p.username == username && p.right == \"Write\"\n })\n if(project.owner == username || participant.length > 0){\n return true\n }else{\n return false\n }\n }",
"function ensureOwner(req, res, next) {\n\tvar scoreId = req.params.scoreId;\n\tvar userId = req.user.id;\n\tif (!scoreId && !userId) {\n\t\tdebug('ensureOwner Invalid[' + scoreId + '] or userId[' + userId + ']');\n\t\treturn res.status(500).send('Invalid user or score');\n\t}\n\t\n\tdaoScore.getById(scoreId, function(err, score) {\n\t\tif (err) {\n\t\t\tdebug('ensureOwner error: ' + err);\n\t\t\treturn res.status(500).send('error');\n\t\t}\n\t\t\n\t\tif (!score) {\n \t\tdebug('invalid score');\n\t\t\treturn res.status(500).send('invalid score');\n\t\t}\n\t\t\n\t\tif (!score || score.owner !== userId) {\n\t\t\tdebug('invalid owner score[' + score.owner + ' logged user[' + userId + ']');\n\t\t\treturn res.status(500).send('invalid owner');\n\t\t}\n\t\t\n\t\tnext(null);\n\t});\n}",
"async function checkForPlaylistOwner(req, res, next){\n try{\n const {id} = req.params;\n const extistedtokenId = await userDb.findBytoken((req.get('Authorization')));\n const tokenId = extistedtokenId.id;\n const userId = await playlistDb.findUserByPlaylistId(id);\n if (!userId) {\n res.status(400).json({ error: 'there is no playlist with this id' });\n return;\n }\n if (tokenId !== userId.user_id) { \n res.status(403).json({ message: \"you are not Authorized to perform this operation\" });\n } else {\n next();\n }\n } catch(err){\n console.log(\"Error\", err);\n\n }\n}",
"checkUserContributor (userId) {\n console.log('checkUserContributor:', userId);\n let user = Auth.requireAuthentication();\n \n // Validate\n check(userId, String);\n \n // Check for the presense of a contributor record\n return Users.findOne(userId).contributor() !== null\n }",
"function getOwner(payload) {\n return ( payload.repo || payload.repository ).owner.login;\n}",
"function isResponsible(person) {\n\t\treturn ((person.status === \"single\" || \n\t\t\t\t person.name === \"Eko\") ? false : true);\n\t}",
"get isOneToOneNotOwner() {\n return this.isOneToOne && !this.isOwning;\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 }",
"function displayAddOwner(){\n getToken().then((token) => {\n var params = window.location.search + \"&idToken=\" + token;\n\n const displayRequest = new Request(\"/get-role\" + params, {method: \"GET\"});\n fetch(displayRequest).then(response => response.json()).then((role) => {\n var elem = document.getElementById(\"ownerForm\");\n if (role === \"owner\"){\n elem.style.display = \"inline-block\";\n }\n });\n });\n}",
"getOwner() {\n this.logger.debug(GuildService.name, this.getOwner.name, \"Executing\");\n this.logger.debug(GuildService.name, this.getOwner.name, \"Getting owner and exiting.\");\n return this.guild.owner.user;\n }",
"waitFor_horseProfile_Overview_OwnerContent() {\n this.horseProfile_Overview_OwnerContent.waitForExist();\n }",
"function isPrivateRepo() {\n var outlineLabels = document.querySelectorAll(\n \"span.Label.Label--outline.v-align-middle\"\n );\n for (const label of outlineLabels) {\n if (label.innerText == \"Private\") {\n return true;\n }\n }\n return false;\n }",
"get isOwning() {\n return !!(this.isManyToOne ||\n (this.isManyToMany && this.joinTable) ||\n (this.isOneToOne && this.joinColumn));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handles what to do when the user presses 'select'. If multiple actions are available for the currently highlighted node, opens the action menu. Otherwise performs the node's default action. | static onSelect() {
const node = Navigator.byItem.currentNode;
if (MenuManager.isMenuOpen() || node.actions.length <= 1 ||
!node.location) {
node.doDefaultAction();
return;
}
ActionManager.instance.menuStack_ = [];
ActionManager.instance.menuStack_.push(MenuType.MAIN_MENU);
ActionManager.instance.actionNode_ = node;
ActionManager.instance.openCurrentMenu_();
} | [
"function performSelectedAction(){\r\n\tswitch(selectedAction){\r\n\tcase GameScreenActionType.mainmenu:\r\n\t\tperformQuit();\r\n\t\tbreak;\r\n\tcase GameScreenActionType.hints:\t\r\n\t\ttoggleHints();\r\n\t\tbreak;\r\n\tcase GameScreenActionType.difficulty:\r\n\t\tperformDifficultyAction();\r\n\t\tbreak;\r\n\tcase GameScreenActionType.gamestate:\r\n\t\t\r\n\t\tbreak;\r\n\t}\r\n}",
"function testHandlesItemActions() {\n select.render(sandboxEl);\n var item1 = new goog.ui.MenuItem('item 1');\n var item2 = new goog.ui.MenuItem('item 2');\n select.addItem(item1);\n select.addItem(item2);\n\n item1.dispatchEvent(goog.ui.Component.EventType.ACTION);\n assertEquals(item1, select.getSelectedItem());\n assertEquals(item1.getCaption(), select.getCaption());\n\n item2.dispatchEvent(goog.ui.Component.EventType.ACTION);\n assertEquals(item2, select.getSelectedItem());\n assertEquals(item2.getCaption(), select.getCaption());\n}",
"function select_control(evt) {\n var mode,\n ctl = $(evt.target),\n action = ctl.attr('action'),\n entry = ctl.closest('.entry'),\n id = entry.attr('annotation-id'),\n annotation = layer.annotationById(id);\n switch (action) {\n case 'validate':\n layer.mode(null);\n query.editing = undefined;\n setQuery(query)\n layer.draw();\n handleAnnotationChange(evt);\n break;\n case 'adjust':\n layer.mode(layer.modes.edit, annotation);\n query.editing = id;\n setQuery(query)\n layer.draw();\n handleAnnotationChange(evt);\n break;\n case 'remove':\n layer.removeAnnotation(annotation);\n break;\n case 'remove-all':\n fromButtonSelect = true;\n mode = layer.mode();\n layer.mode(null);\n layer.removeAllAnnotations();\n layer.mode(mode);\n fromButtonSelect = false;\n break;\n }\n }",
"_optionSelected(e) {\n let local = e.target;\n // fire that an option was selected and about what operation\n let ops = {\n element: this,\n operation: this.activeOp,\n option: local.getAttribute(\"id\"),\n };\n this.dispatchEvent(\n new CustomEvent(\"item-overlay-option-selected\", {\n bubbles: true,\n cancelable: true,\n composed: true,\n detail: ops,\n })\n );\n // don't reset for movement, just confirm / reject actions\n if (this.activeOp != \"move\") {\n this._resetActive();\n this.activeOp = null;\n }\n }",
"function walkSelection() {\n //set the optionKey\n var optionKey = Menu.optionArray[Menu.optionSelected].optionKey;\n switch (optionKey) {\n case 'talkTo':\n var found = false;\n game.mapData.npcs.forEach(function(npc) {\n if (game.player.gridLocation.x - game.playerDirection.x === npc.x && game.player.gridLocation.y - game.playerDirection.y === npc.y) {\n //there is an NPC in the direction the player is facing\n found = true;\n //make the dialog panel\n game.dialogPanel.new({\n w: 800,\n h: 270,\n x: game.width / 2 - 400,\n y: game.height - 270 - 50,\n type: 'dialog',\n dialog: game.dialog[npc.nameKey]\n });\n }\n });\n if (!found) {\n //nobody there\n game.infoPanel.new({\n w: 400,\n h: 200,\n x: game.width / 2 - 200,\n y: 50,\n type: 'infoPanel',\n text: [\"There's nobody there!\"]\n });\n }\n break;\n case 'items':\n game.dialogPanel.new({\n w: 800,\n h: 450,\n x: game.width / 2 - 400,\n y: game.height / 2 - 300,\n type: 'itemPanel',\n callback: null\n });\n break;\n default:\n //temporary display for unfinished menus\n game.infoPanel.new({\n w: 400,\n h: 200,\n x: game.width / 2 - 200,\n y: 50,\n type: 'infoPanel',\n text: [\"That menu isn't finished yet!\", \"Stop clicking it.\", \"Please.\"]\n });\n // code\n }\n\n }",
"_onSelectedChanged() {\n if (this._selected !== 'appsco-application-add-search') {\n this.$.addApplicationAction.style.display = 'block';\n this.playAnimation('entry');\n this._addAction = true;\n }\n else {\n this._addAction = false;\n this.playAnimation('exit');\n }\n }",
"add_select(func) {\n this.add_event(\"select\", func);\n }",
"function createSelectController()\r\n{\r\n\t\r\n\t\r\n\treturn new ol.interaction.Select({\r\n\tcondition: ol.events.condition.click,\r\n\t});\t\t\t\r\n}",
"selectHandler(){\n \n this.props.onSelect(this.state.selected)\n }",
"action() {\n if (this.selectedRows().length > 0) {\n dispatch.action(this.element, this.selectedRows());\n }\n }",
"function menuHighlightClick() {\n Data.Edit.Mode = EditModes.Highlight;\n updateMenu();\n}",
"function performActions() {\n\n // prepare event data\n event_data = $.integrate( entry_data, event_data );\n event_data.content = content_elem;\n event_data.entry = entry_elem;\n delete event_data.actions;\n\n // perform menu entry actions\n if ( entry_data.actions )\n if ( typeof ( entry_data.actions ) === 'function' )\n entry_data.actions( $.clone( event_data ), self );\n else\n entry_data.actions.forEach( action => $.action( action ) );\n\n // perform callback for clicked menu entry\n self.onclick && $.action( [ self.onclick, $.clone( event_data ), self ] );\n\n }",
"static start_job_menu_item_action() {\n let full_src = Editor.get_javascript()\n let selected_src = Editor.get_javascript(true)\n let sel_start_pos = Editor.selection_start()\n let sel_end_pos = Editor.selection_end()\n let start_of_job_maybe = Editor.find_backwards(full_src, sel_start_pos, \"new Job\")\n let start_of_job_pos\n let end_of_job_pos\n let job_src = null //if this is not null, we've got a valid job surrounds (or is) the selection.\n let sel_is_instructions = false\n if(start_of_job_maybe !== null){\n [start_of_job_pos, end_of_job_pos] = Editor.select_call(full_src, start_of_job_maybe)\n }\n if(end_of_job_pos && (end_of_job_pos > sel_start_pos)){ //sel is within a job, but we don't know if its\n //instruction selection or just within the job yet.\n job_src = full_src.substring(start_of_job_pos, end_of_job_pos)\n let do_list_start_pos = full_src.indexOf(\"do_list:\", start_of_job_pos)\n if((do_list_start_pos === -1) || (do_list_start_pos > end_of_job_pos)) {} //weird, looks like Job has no do_list,\n //but ok, we just have the whole Job to execute.\n else if (do_list_start_pos < sel_start_pos) { //our selected_src should be instructions in the do_list\n sel_is_instructions = true\n }\n }\n if (job_src === null) { //no job def so we're going to make our own.\n //warning(\"There's no Job definition surrounding the cursor.\")\n var selection = Editor.get_javascript(true).trim()\n if (selection.endsWith(\",\")) { selection = selection.substring(0, selection.length - 1) }\n if (selection.length > 0){\n //if (selection.startsWith(\"[\") && selection.endsWith(\"]\")) {} //perhaps user selected the whole do_list. but\n //bue we can also have a single instr that can be an array.\n //since it's ok for a job to have an extra set of parens wrapped around its do_list,\n //just go ahead and do it.\n //else {\n //plus\n selection = \"[\" + selection + \"]\"\n sel_start_pos = sel_start_pos - 1\n //}\n var eval2_result = eval_js_part2(selection)\n if (eval2_result.error_type) {} //got an error but error message should be displayed in output pane automatmically\n else if (Array.isArray(eval2_result.value)){ //got an array, but is it a do_list of multiple instructions?\n let do_list\n if(!Instruction.is_instructions_array(eval2_result.value)){ //might never hit, but its an precaution\n do_list = [eval2_result.value]\n }\n if (Job.j0 && Job.j0.is_active()) {\n Job.j0.stop_for_reason(\"interrupted\", \"Start Job menu action stopped job.\")\n setTimeout(function() {\n Job.init_show_instructions_for_insts_only_and_start(sel_start_pos, sel_end_pos,\n do_list, selection)},\n (Job.j0.inter_do_item_dur * 1000 * 2) + 10) //convert from seconds to milliseconds\n }\n else {\n Job.init_show_instructions_for_insts_only_and_start(sel_start_pos, sel_end_pos,\n eval2_result.value, selection)\n }\n }\n else {\n shouldnt(\"Selection for Start job menu item action wasn't an array, even after wrapping [].\")\n }\n }\n else {\n warning(\"When choosing the Eval&Start Job menu item<br/>\" +\n \"with no surrounding Job definition,<br/>\" +\n \"you must select exactly those instructions you want to run.\")\n }\n }\n //we have a job.\n else {\n const eval2_result = eval_js_part2(job_src)\n if (eval2_result.error_type) { } //got an error but error message should be displayed in Output pane automatically\n else {\n let job_instance = eval2_result.value\n if(!sel_is_instructions){\n job_instance.start()\n }\n else if (selected_src.length > 0){ //sel is instructions\n let do_list_result = eval_js_part2(\"[\" + selected_src + \"]\") //even if we only have one instr, this is still correct, esp if that one starts with \"function().\n //if this wraps an extra layer of array around the selected_src, that will still work pretty well.\n if (do_list_result.error_type) { } //got an error but error message should already be displayed\n else {\n job_instance.start({do_list: do_list_result.value})\n }\n }\n else { //no selection, so just start job at do_list item where the cursor is.\n const [pc, ending_pc] = job_instance.init_show_instructions(sel_start_pos, sel_end_pos, start_of_job_pos, job_src)\n job_instance.start({show_instructions: true, inter_do_item_dur: 0.5, program_counter: pc, ending_program_counter: ending_pc})\n }\n }\n }\n }",
"function handlePopupSelectOptions() {\n\t\tif (selectCount === 0) {\n\t\t\tdisplaySelectAll();\n\t\t} else if (selectCount === listLength) {\n\t\t\tdisplayDeselectAll();\n\t\t} else {\n\t\t\tdisplayBoth();\n\t\t}\n\n\t}",
"function selectItem(e) {\n removeBorder();\n removeShow();\n // Add Border to current feature\n this.classList.add('feature-border');\n // Grab content item from DOM\n const featureContentItem = document.querySelector(`#${this.id}-content`);\n // Add show\n featureContentItem.classList.add('show');\n}",
"_startChoose(e) {\n let target = e.target;\n if (target.nodeName !== 'BUTTON') {\n target = target.parentElement;\n }\n this._chosenServer = target.dataset.server;\n let choices = this._state.packages[target.dataset.app];\n let chosen = choices.findIndex(choice => choice.Name === target.dataset.name);\n this._push_selection.choices = choices;\n this._push_selection.chosen = chosen;\n this._push_selection.show();\n }",
"selectViewIndex(aViewIndex) {\n let treeSelection = this.treeSelection;\n // if we have no selection, we can't select something\n if (!treeSelection) {\n return;\n }\n let rowCount = this.view.dbView.rowCount;\n if (\n aViewIndex == nsMsgViewIndex_None ||\n aViewIndex < 0 ||\n aViewIndex >= rowCount\n ) {\n this.clearSelection();\n return;\n }\n\n // Check whether the index is already selected/current. This can be the\n // case when we are here as the result of a deletion. Assuming\n // nsMsgDBView::NoteChange ran and was not suppressing change\n // notifications, then it's very possible the selection is already where\n // we want it to go. However, in that case, nsMsgDBView::SelectionChanged\n // bailed without doing anything because m_deletingRows...\n // So we want to generate a change notification if that is the case. (And\n // we still want to call ensureRowIsVisible, as there may be padding\n // required.)\n if (\n treeSelection.count == 1 &&\n (treeSelection.currentIndex == aViewIndex ||\n treeSelection.isSelected(aViewIndex))\n ) {\n // Make sure the index we just selected is also the current index.\n // This can happen when the tree selection adjusts itself as a result of\n // changes to the tree as a result of deletion. This will not trigger\n // a notification.\n treeSelection.select(aViewIndex);\n this.view.dbView.selectionChanged();\n } else {\n // Previous code was concerned about avoiding updating commands on the\n // assumption that only the selection count mattered. We no longer\n // make this assumption.\n // Things that may surprise you about the call to treeSelection.select:\n // 1) This ends up calling the onselect method defined on the XUL 'tree'\n // tag. For the 3pane this is the ThreadPaneSelectionChanged method in\n // threadPane.js. That code checks a global to see if it is dealing\n // with a right-click, and ignores it if so.\n treeSelection.select(aViewIndex);\n }\n\n if (this._active) {\n this.ensureRowIsVisible(aViewIndex);\n }\n\n // The saved selection is invalidated, since we've got something newer\n this._savedSelection = null;\n\n // Do this here instead of at the beginning to prevent reentrancy issues\n this._aboutToSelectMessage = false;\n\n let tabmail = document.getElementById(\"tabmail\");\n if (tabmail) {\n tabmail.setTabTitle(this._tabInfo);\n }\n }",
"function goToGene(e) {\n selectNode(e.currentTarget.innerHTML); // select based on which one was clicked\n }",
"updateActionStates() {\n ssui.originalUpdateActionStatesFunc.call(this);\n \tlet graph = this.editor.graph;\n this.actions.get('group').setEnabled(graph.getSelectionCount() >= 1);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function opens Storj(V3) project using access grant and custom configuration. Input : None Output : Project(Object) | async configOpenProject(){
var project = await uplink.config_open_project(this.access).catch((error) => {
errorhandle.storjException(error.error.code,error.error.message);
});
var projectResultReturn = new ProjectResultStruct(project.project);
return(projectResultReturn);
} | [
"async openProject(){\n var project = await uplink.open_project(this.access).catch((error) => {\n errorhandle.storjException(error.error.code,error.error.message);\n });\n var projectResultReturn = new ProjectResultStruct(project.project);\n return(projectResultReturn);\n }",
"function getProjectbyId(project_id){\n\n}",
"function openProject(path) {\n\n\t\t// Load project\n\t\tloadProject( path, function() {\n\n\t\t\t// if everything go right show build screen\n\t\t\t$('#screen-main').fadeOut(300, function() {\n\n\t\t\t\t// Close project name if opened\n\t\t\t\tcloseProjectName();\n\n\t\t\t\t// Resize logo\n\t\t\t\t$('header').animate({padding : '20px'}, 300, function () {\n\n\t\t\t\t\t// Show project name\n\t\t\t\t\t$('.project-title').text(require('./js/models.js').project.name);\n\n\t\t\t\t\t// Show next screen\n\t\t\t\t\t$('#screen-build').fadeIn(300);\n\n\t\t\t\t\t// Enable last project button\n\t\t\t\t\t$('#open-last-project-button').removeAttr('disabled')\n\n\t\t\t\t});\n\n\t\t\t});\n\n\t\t}, function (err) {\n\t\t\t// If there is any error reading the json file\n\t\t\tshowAlert('error', err);\n\t\t});\n\n\t}",
"import() {\n var promise;\n\n // set name and description for imported project\n if (!this.isChangeableDescription) {\n this.importProjectData.project.description = angular.copy(this.projectDescription);\n }\n if (!this.isChangeableName) {\n this.importProjectData.project.name = angular.copy(this.projectName);\n }\n // check workspace is selected\n if (!this.workspaceSelected || !this.workspaceSelected.workspaceReference) {\n this.$mdDialog.show(\n this.$mdDialog.alert()\n .title('No workspace selected')\n .content('No workspace is selected')\n .ariaLabel('Project creation')\n .ok('OK')\n );\n return;\n }\n\n // mode\n this.importing = true;\n\n var mode = '';\n\n // websocket channel\n var channel = 'importProject:output:' + this.workspaceSelected.workspaceReference.id + ':' + this.importProjectData.project.name;\n\n\n // select mode (create or import)\n if (this.currentTab === 'blank' || this.currentTab === 'config') {\n // no source, data is .project subpart\n //TODO This values are hardcoded, cause required to create project. Need to fix in 4.0:\n if (this.currentTab === 'blank' && this.importProjectData.project.type === 'maven') {\n let name = this.importProjectData.project.name;\n this.importProjectData.project.attributes = {'maven.artifactId' : [name], 'maven.groupId' : [name], 'maven.version' : ['1.0-SNAPSHOT']};\n }\n\n //TODO This values are hardcoded, cause required to create project. Need to fix in 4.0:\n if (this.currentTab === 'blank' && this.importProjectData.project.type === 'ant') {\n this.importProjectData.project.attributes = {'ant.source.folder': ['src'], 'ant.test.source.folder': ['test']};\n }\n\n\n promise = this.codenvyAPI.getProject().createProject(this.workspaceSelected.workspaceReference.id, this.importProjectData.project.name, this.importProjectData.project);\n mode = 'createProject';\n } else {\n mode = 'importProject';\n // on import\n this.messageBus.subscribe(channel, (message) => {\n this.importingData = message.line;\n });\n promise = this.codenvyAPI.getProject().importProject(this.workspaceSelected.workspaceReference.id, this.importProjectData.project.name, this.importProjectData);\n }\n promise.then((data) => {\n this.importing = false;\n this.importingData = '';\n\n if (mode === 'importProject') {\n data = data.projectDescriptor;\n }\n\n // need to redirect to the project details as it has been created !\n this.$location.path('project/' + data.workspaceId + '/' + data.name);\n\n this.messageBus.unsubscribe(channel);\n\n }, (error) => {\n this.messageBus.unsubscribe(channel);\n this.importing = false;\n this.importingData = '';\n // need to show the error\n this.$mdDialog.show(\n this.$mdDialog.alert()\n .title('Error while creating the project')\n .content(error.statusText + ': ' + error.data.message)\n .ariaLabel('Project creation')\n .ok('OK')\n );\n });\n\n\n }",
"openProject(event) {\n const controller = event.data.controller;\n ListDialog.type = 'openProject';\n const warning = new WarningDialog(() => {\n const dialog = new ListDialog(() => {\n if (dialog.selectedItems.length != 0) {\n dialog.selectedItems\n .forEach((value) => {\n controller.loadProject(value);\n });\n if (controller.persistenceController.getCurrentProject().version > BeastController.BEAST_VERSION) {\n InfoDialog.showDialog('This BEAST-version is older than the version this project was created with!<br>Some of of the components may be incompatible with this version.');\n }\n }\n }, controller.listProjects());\n dialog.show();\n }, () => {\n MenubarController.openAfterWarning = true;\n $('#saveProject')\n .click();\n }, () => {\n MenubarController.openAfterWarning = true;\n $('#exportProject')\n .click();\n }, null);\n if (controller.isDirty()) {\n warning.show();\n }\n else {\n warning.callbackContinue();\n }\n MenubarController.openAfterWarning = false;\n }",
"openProjectOptionsDialog(project) {\n this.projectOptionsSelected = project;\n\n // reset the dialog\n this.shadowRoot.getElementById(\"connected-group-name\").style.removeProperty(\"display\");\n this.shadowRoot.getElementById(\"input-edit-group-name\").style.setProperty(\"display\", \"none\");\n\n this.shadowRoot.getElementById(\"connected-group-project-name\").innerText = project.name;\n this.shadowRoot.getElementById(\"connected-group-name\").innerText = project.groupName;\n\n // open the dialog\n this.shadowRoot.getElementById(\"dialog-project-options\").open();\n }",
"grantWriteAccess () {\n\n\t\t\tlet clientId = appConfig.auth[process.env.NODE_ENV === 'production' ? 'prod' : 'dev'],\n\t\t\t\turl = 'https://api.github.com/authorizations';\n\n\t\t\treturn transport.request(url)//, null, this.buildAuthHeader())\n\t\t\t.then(\n\t\t\t\tresponse => {\n\t\t\t\t\tlet openRedistApp = response.find(authedApp => authedApp.app.client_id === clientId);\n\n\t\t\t\t\tif (!openRedistApp) throw new Error('User is not currently authed.');\n\n\t\t\t\t\tif (openRedistApp.scopes.includes('public_repo')) {\n\t\t\t\t\t\treturn { userHasWriteAccess: true };\n\t\t\t\t\t} else {\n\t\t\t\t\t\turl = `https://api.github.com/authorizations/${ openRedistApp.id }`;\n\t\t\t\t\t\treturn transport.request(url, null, {\n\t\t\t\t\t\t\t...this.buildAuthHeader(),\n\t\t\t\t\t\t\tmethod: 'PATCH',\n\t\t\t\t\t\t\tbody: {\n\t\t\t\t\t\t\t\tadd_scopes: [ 'public_repo' ]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\t\t\t.then(\n\t\t\t\tresponse => {\n\t\t\t\t\treturn { userHasWriteAccess: true };\n\t\t\t\t}\n\t\t\t)\n\t\t\t.catch(error => {\n\t\t\t\t// fail loudly if the application errors further down the promise chain.\n\t\t\t\tthis.handleError(error);\n\t\t\t\tthrow error;\n\t\t\t});\n\n\t\t}",
"function displayProject(index) {\r\n localStorage.setItem(\"aProjectIndex\", index);\r\n window.open(\"ProjectsInfo.html\",\"_self\");\r\n}",
"async function connectProjectFolder() {\n //Allow the user to select a directory (requests read access)\n projectDirectoryHandle = await window.showDirectoryPicker();\n document.getElementById(\"connect-folder-button\").innerHTML = `connected to: ${projectDirectoryHandle.name}`;\n\n //Creates the directory structure if non-existant and build references (requests write access to entire project \n //directory)\n projectFeaturesDirectoryHandle = await projectDirectoryHandle.getDirectoryHandle(\"Features\", {create: true});\n projectRenderersDirectoryHandle = await projectDirectoryHandle.getDirectoryHandle(\"Renderers\", {create: true});\n projectSymbolsDirectoryHandle = await projectDirectoryHandle.getDirectoryHandle(\"Symbols\", {create: true});\n projectLayersDirectoryHandle = await projectDirectoryHandle.getDirectoryHandle(\"Layers\", {create: true});\n\n //Read contents of each directory, adding any files to the project.\n //Order is impportant to ensure that appropriate objects are created before being called.\n for await (const entry of projectSymbolsDirectoryHandle.values()) {\n if (entry.kind == \"file\") {\n const entryHandle = await projectSymbolsDirectoryHandle.getFileHandle(entry.name);\n await ProjectSymbol.create(entryHandle);\n }\n }\n\n for await (const entry of projectRenderersDirectoryHandle.values()) {\n if (entry.kind == \"file\") {\n const entryHandle = await projectRenderersDirectoryHandle.getFileHandle(entry.name);\n await ProjectRenderer.create(entryHandle);\n }\n }\n\n for await (const entry of projectFeaturesDirectoryHandle.values()) {\n if (entry.kind == \"file\") {\n const entryHandle = await projectFeaturesDirectoryHandle.getFileHandle(entry.name);\n await ProjectFeature.create(entryHandle);\n }\n }\n\n for await (const entry of projectLayersDirectoryHandle.values()) {\n if (entry.kind == \"file\") {\n const entryHandle = await projectLayersDirectoryHandle.getFileHandle(entry.name);\n await ProjectLayer.create(entryHandle);\n }\n }\n\n //Pan the map to the extents of all features in the project\n const allFeatures = [];\n projectLayers.forEach( (layer) => {\n allFeatures.push(layer.sourceFS.features);\n });\n await view.goTo( allFeatures );\n }",
"function _projectOpen() {\n // get the current/active project\n var project = ProjectManager.getProjectRoot(),\n name,\n rootPath;\n\n if (project) {\n name = project.name;\n rootPath = project.fullPath;\n\n _bowerProject = new BowerProject(name, rootPath, exports);\n } else {\n _bowerProject = null;\n }\n\n _configureBowerProject();\n\n // by default on project open, the default active path is set to project root path\n exports.trigger(ACTIVE_DIR_CHANGED, \"\", \"\");\n }",
"function Project(props) {\n return __assign({ Type: 'AWS::IoT1Click::Project' }, props);\n }",
"async function createProject(name, goalInETH, durationInHours) {\n // Transforming the parameters to the \"contract-friendly\" format\n const goalInWei = goalInETH * ethWei;\n const durationInSeconds = durationInHours * 3600;\n\n // Asking the user to confirm his donation.\n if (!confirm(`Opravdu chcete založit projekt jménem ${name}, s cílem ${goalInETH} ETH a dobou trvání ${durationInHours} hodin?`)) {\n return\n }\n\n // Initialising the contract and account connection through Web3\n // If the connection cannot be set up, notify the user and stop the function\n // BEWARE: the function we are calling is asynchronous, therefore the keyword \"await\"\n let [contract, accounts] = await connectWithContractAndAccounts(contractABI, contractAddress);\n if (contract === undefined) {\n alert(\"Nejste připojení k ethereovému blockchainu!\");\n return;\n }\n\n // Calling the method on the blockchain responsible for creating th project\n try {\n contract.methods.createProject(name, goalInWei, durationInSeconds)\n .send({from: accounts[0], gas: \"300000\", gasPrice: gasPriceForTransactions})\n .on('transactionHash', function(hash) {\n console.log ('hash', hash);\n })\n .on('receipt', function(receipt) {\n console.log ('receipt', receipt);\n alert(\"Transakce byla úspěšná - projekt vytvořen.\");\n // Refreshing the page with updated information\n refreshTheDataInTable();\n })\n .on('error', function(error) {\n $(\"#error\").html('error - Is MetaMask set to the correct address ' + accounts[0]);\n })\n } catch (error) {\n console.log ('error',error);\n alert(\"Transakce se nepovedla a projekt nebyl vytvořen - zkuste to prosím znovu!\");\n }\n}",
"function open(alias) {\n // if opened after init, it should just set the config object directly\n internals.assertNoCurrentWorkingAlias();\n const folderpath = path.join(internals.DOCIT_PATH, alias);\n\n if (!fse.pathExistsSync(folderpath)) {\n // printUtils.error(\n // `Docit: no project with the alias ${alias} exists. Create a new project with \"docit init <path-to-document>\"`\n // );\n\n throw new Error(\n `Docit: no project with the alias ${alias} exists. Create a new project with \"docit init <path-to-document>\"`\n );\n }\n\n internals.currentWorkingAlias = alias;\n \n}",
"function ClientProject(name, companyName) {\n this.name = name;\n this.companyName = companyName;\n\n this.frontReq = getRandomNum(10, 60);\n this.clientReq = getRandomNum(10, 60);\n this.serverReq = getRandomNum(10, 60);\n console.log(\"Project created! \");\n}",
"function NewProjectNode()\n{\n\tvar projectNode : ProjectNode = new ProjectNode();\n\t\n\t//Take the current instance of the project\n\t//projectNode.project = Instantiate(project);\n\tprojectNode.project = new ProjectStatsList();\n\tprojectNode.project.Add(project.GetStats());\n\tprojectNode.project.first.credits = player.GetSaldo();\n\t\n\t//Create the lists for all slots\n\tprojectNode.slot01 = new EmployeeList();\n\tprojectNode.slot02 = new EmployeeList();\n\tprojectNode.slot03 = new EmployeeList();\n\tprojectNode.slot04 = new EmployeeList();\n\tprojectNode.slot05 = new EmployeeList();\n\tprojectNode.slot06 = new EmployeeList();\n\tprojectNode.slot07 = new EmployeeList();\n\tprojectNode.slot08 = new EmployeeList();\n\t\n\t//Create the Employee Node for each slot\n\tNewEmployeeNode(employee01, projectNode.slot01);\n\tNewEmployeeNode(employee02, projectNode.slot02);\n\tNewEmployeeNode(employee03, projectNode.slot03);\n\tNewEmployeeNode(employee04, projectNode.slot04);\n\tNewEmployeeNode(employee05, projectNode.slot05);\n\tNewEmployeeNode(employee06, projectNode.slot06);\n\tNewEmployeeNode(employee07, projectNode.slot07);\n\tNewEmployeeNode(employee08, projectNode.slot08);\n\t\n\tprojectList.Add(projectNode);\t\n\t\n\tproject.ProjectProvenance();\t\n}",
"function createProject(name){\n let thisproj = document.createElement('BUTTON');\n Object.assign(thisproj,{\n className: 'projects',\n id: 'projects'\n })\n\n let project_text = document.createTextNode(name);\n thisproj.appendChild(project_text);\n document.getElementById(\"here\").appendChild(thisproj);\n\n // Add event handler\n thisproj.addEventListener (\"click\", function() {\n projectClicked = String(thisproj.innerText); // projectClicked will store the name of the project we clicked on\n $.post('/select_project', { projectClicked }) // send the variable projectClicked to the server\n\n location.href = \"/select_group\" // when user clicks on a project, user will go to this page\n });\n \n}",
"getV3ProjectsStarred(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.ProjectsApi()\n/*let opts = {\n 'orderBy': \"'created_at'\", // String | Return projects ordered by field\n 'sort': \"'desc'\", // String | Return projects sorted in ascending and descending order\n 'archived': true, // Boolean | Limit by archived status\n 'visibility': \"visibility_example\", // String | Limit by visibility\n 'search': \"search_example\", // String | Return list of authorized projects matching the search criteria\n 'page': 56, // Number | Current page number\n 'perPage': 56, // Number | Number of items per page\n 'simple': true // Boolean | Return only the ID, URL, name, and path of each project\n};*/\napiInstance.getV3ProjectsStarred(incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"function loadProject(project){\n\n\t\t\tvar projectDirectory = projectLocation.format(project.id);\n\t\t\tvar projectDataFile = projectDirectory + '/index.html';\n\n\t\t\t// load the file\n\t\t\treturn fsp.readFile(projectDataFile, 'utf8')\n\t\t\t\t.then(createProjectFromFile)\n\t\t\t\t.then(parseFrontMatter)\n\t\t\t\t.catch(error);\n\n\n\t\t\t// split it into front matter and content\n\t\t\tfunction createProjectFromFile(fileString){\n\n\t\t\t\tconsole.log('service: createProjectFromFile (1st)');\n\n\t\t\t\tvar fileParts = fileString.split('---\\n');\n\n\t\t\t\t// fileParts[0] is an empty string\n\t\t\t\tproject.frontMatter = fileParts[1];\n\t\t\t\tproject.content = fileParts[2];\n\n\t\t\t\treturn project;\n\t\t\t}\n\n\n\t\t\t// parse the front matter into an object\n\t\t\tfunction parseFrontMatter(project){\n\n\t\t\t\tconsole.log('service: parseFrontMatter (2nd)');\n\n\t\t\t\tproject.frontMatter = yaml.parse(project.frontMatter);\n\n\t\t\t\treturn project;\n\t\t\t}\n\n\n\t\t\t// catch any error\n\t\t\tfunction error(err) {\n $log.error(err);\n }\n\n\t\t}",
"exportProject(event) {\n const controller = event.data.controller;\n InputDialog.type = 'exportProject';\n const exportDialog = new InputDialog((input) => {\n const p = controller.persistenceController.getCurrentProject();\n p.setName(input);\n controller.persistenceController.downloadCurrentProject();\n if (MenubarController.createAfterWarning) {\n $('#createProject')\n .click();\n }\n if (MenubarController.importAfterWarning) {\n $('#importProject')\n .click();\n }\n if (MenubarController.openAfterWarning) {\n $('#openProject')\n .click();\n }\n }, controller.persistenceController.getCurrentProject()\n .getName(), null);\n exportDialog.show();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
setup bootstrap multiselect input for region (kommun) | function setupRegionSelectBox(){
$(document).ready(function() {
$('#RegionId').multiselect({
buttonText: function(options, select) {
if (options.length === 0) {
return 'Välj kommuner ';
}
else if (options.length > 3) {
// Disable all other checkboxes.
var nonSelectedOptions = $('#RegionId option').filter(function() {
return !$(this).is(':selected');
});
nonSelectedOptions.each(function() {
var input = $('input[value="' + $(this).val() + '"]');
input.prop('disabled', true);
input.parent('li').addClass('disabled');
});
}
else {
// Enable all checkboxes.
$('#RegionId option').each(function() {
var input = $('input[value="' + $(this).val() + '"]');
input.prop('disabled', false);
input.parent('li').addClass('disabled');
});
}
var labels = [];
options.each(function() {
if ($(this).attr('label') !== undefined) {
labels.push($(this).attr('label'));
}
else {
labels.push($(this).html());
}
});
return labels.join(', ') + '';
}
});
});
} | [
"function multipleSelectControlCreate(element, parent_div_id, control_name, control_label, has_cascaded_element, jsondata, appearance, username) {\n if (jsondata == null) {\n console.log(control_label + \" element cannot be created -mpower\");\n return;\n }\n var col_md = 12;\n if ('col_md' in appearance)\n col_md = appearance['col_md'];\n var wrapper_class = \"\"\n if ('wrapper_class' in appearance)\n wrapper_class = appearance['wrapper_class'];\n var start_wrapper = '<div class =\" \"> <div class =\"col-md-' + col_md + ' ' + wrapper_class + '\" >';\n var end_wrapper = '</div></div>';\n var label = '<label class=\"control-label\">' + control_label + '</label> <div >';\n var multiple_select_html = start_wrapper + label + '<select multiple=\"multiple\" onchange=\"' + has_cascaded_element + '\" id=\"' + element + '\" name=\"' + control_name + '\" class=\"form-control\">';\n for (var i = 0; i < jsondata.length; i++) {\n multiple_select_html += '<option value=\"' + jsondata[i].id + '\">' + jsondata[i].name + '</option>';\n }\n multiple_select_html += '</select></div>' + end_wrapper;\n $(\"#\" + parent_div_id).append(multiple_select_html);\n console.log(\"here In multiselect \" + element);\n handleMultipleSelect(element);\n}",
"function registerSearchableSelect() {\n\n}",
"function datagrid_activate_mselect_ui(jq_select) {\n var all_opt = $(jq_select).find('option[value=\"-1\"]');\n var use_all_opt = (all_opt.text() == _('-- All --', 'webgrid'));\n if ( use_all_opt ) {\n $(all_opt).detach();\n }\n if (jq_select.data('multipleSelect')) {\n jq_select.hide();\n } else {\n jq_select.webgridMultipleSelect({\n minumimCountSelected: 2,\n filter: true\n });\n jq_select.parent().find('.ms-parent > button, .ms-drop').each(function() {\n $(this).css('width', $(this).width() + 60);\n });\n }\n jq_select.siblings('.ms-parent').show();\n jq_select.attr('multiple', 'multiple');\n if ( use_all_opt ) {\n $(all_opt).prependTo(jq_select);\n }\n}",
"function MultiSelectDropdownManager() {\n if (!(this instanceof MultiSelectDropdownManager)) {\n return new MultiSelectDropdownManager();\n }\n\n\n\n /** @private @type {!Object} */ var _elements;\n\n\n\n /** @constructor */\n ;(function _constructor() {\n _elements = {};\n\n\n this.init = init;\n this.reload = reload;\n }.bind(this))();\n\n\n\n /**\n * TODO : Add description\n *\n * @param {HTMLElement|HTMLElement[]|String} [$select] - TODO: Add description\n * @returns {MultiSelectDropdownElement|MultiSelectDropdownElement[]} TODO: Add description\n *\n * @public\n */\n function init($select) {\n if ($select instanceof HTMLElement) {\n return _addSelectElement($select);\n }\n\n var ret = [];\n var msdSelectElements = (($select instanceof Array) ? $select.splice() : document.querySelectorAll(($select instanceof String) ? $select : 'select.msd'));\n\n for (var i = 0; i < msdSelectElements.length; i++) {\n ret.push(_addSelectElement(msdSelectElements[i]));\n }\n\n return ret;\n }\n\n\n /**\n * TODO : Add description\n *\n * @param {HTMLElement|HTMLElement[]|String} [$select] - TODO: Add description\n * @returns {MultiSelectDropdownElement|MultiSelectDropdownElement[]} TODO: Add description\n *\n * @public\n */\n function reload($el) {\n // TODO: Implement\n }\n\n\n\n // region Private Functions\n\n /**\n * @param {HTMLElement} $select\n * @returns {HTMLElement}\n * @private\n */\n function _addSelectElement($select) {\n var selector = MSDInternalUtils.getElementSelector($select);\n\n if (!Object.hasOwnProperty(_elements, selector)) {\n _elements[selector] = [];\n }\n\n var msdElement = new MultiSelectDropdownElement({ element: $select });\n _elements[selector].push(msdElement);\n\n return msdElement;\n }\n\n // endregion\n}",
"function resetInputs() {\n $(\"select[data-role=tagsinput]\").tagsinput();\n}",
"function BindFranchiseeName(dept, customUrlIT) { \n $('.FranchiseeName option').remove();\n $.ajax({ \n type: \"POST\",\n url: customUrlIT,\n data: '{}',\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n success: function (r) {\n console.log(r);\n //var dept = $(\"#ddlFranchiseeNameIT\");\n //dept.empty().append('<option selected=\"selected\" value=\"0\">--Select--</option>');\n $.each(r.d, function (key, value) {\n dept.append($(\"<option></option>\").val(value.FranchiseeID).text(value.FirmName));\n }); \n dept.multiselect('rebuild');\n }\n });\n}",
"setMatrixSelectValues() {\n // generate the matrix names based on the number of matrix inputs, e.g. A, B, C...\n const names = this.matrixInputs.map((_, i) => String.fromCharCode('A'.charCodeAt(0) + i));\n let options = \"\";\n names.forEach((name, i) => options += `<option value=${i}>${name}</option>`);\n this.matrixSelects.forEach(select => select.innerHTML = options);\n }",
"renderSelects(optObject, multipleSelect){\n let selects = [];\n for(let key in optObject){\n let keyLength = optObject[key].length;\n let opts = [];\n opts.push(<option key=\"dummy\" value='unselected'>Select...</option>)\n for(let i = 0; i < keyLength; i++){\n opts.push(<option key={optObject[key][i][0]} value={optObject[key][i][0]}>{optObject[key][i][1]}</option>);\n }\n if(!multipleSelect){\n selects.push(<div key={key} className=\"col-xs-12\"><label>{key}</label><select size={keyLength} id={key} onChange={() => this.updateSourceSelection(key)} className='selectpicker sourcePicker form-control'>{opts}</select></div>);\n }\n else {\n selects.push(<div key={key} className=\"col-xs-12\"><label>{key}</label><select size={keyLength + 1} id={key} onChange={() => this.updateSourceSelection(key)} className='selectpicker sourcePicker form-control' multiple>{opts}</select></div>);\n }\n }\n return selects;\n }",
"_updateSelectionOnMultiSelectionChange(value) {\n if (this.multiple && !value) {\n // Deselect all options instead of arbitrarily keeping one of the selected options.\n this.setAllSelected(false);\n }\n else if (!this.multiple && value) {\n this._selectionModel = new SelectionModel(value, this._selectionModel?.selected);\n }\n }",
"function SelectConditionEditor(args) {\n var $select;\n var defaultValue;\n var scope = this;\n var current_cond_text = args.item.CONDITION;\n var current_cond_id = args.item.CONDITION_ID;\n var current_group_id = args.item.GROUPID;\n this.init = function () {\n if (0 == current_cond_id) {\n option_str = '<option selected=\"selected\" value=0> ' + i18n.rlimport.NONE + '</option>';\n }\n else {\n option_str = '<option value=0> ' + i18n.rlimport.NONE + '</option>';\n }\n var condition_height = 30;\n \n for (var cidx = 0, len = pageCriteria.CRITERION.DEF.length; cidx < len; cidx++) {\n // for (var cidx = 0; cidx < pageCriteria.CRITERION.DEF.length; cidx++) {\n if (pageCriteria.CRITERION.DEF[cidx].DEF_TYPE == 2) {\n condition_height += 26;\n if (pageCriteria.CRITERION.DEF[cidx].DEF_ID == current_cond_id) {\n option_str += '<option selected=\"selected\" value=\"' + pageCriteria.CRITERION.DEF[cidx].DEF_ID + '\">' + pageCriteria.CRITERION.DEF[cidx].DEF_DISP + '</option>';\n }\n else {\n option_str += '<option value=\"' + pageCriteria.CRITERION.DEF[cidx].DEF_ID + '\">' + pageCriteria.CRITERION.DEF[cidx].DEF_DISP + '</option>';\n }\n }\n }\n if (condition_height > 180) { condition_height = 180; }\n $select = $('<SELECT tabIndex=\"0\" id=\"conditiongrid\" multiple=\"multiple\">' + option_str + \"</SELECT>\");\n $select.appendTo(args.container);\n var parentWidth = $(\"#conditiongrid\").parents('.slick-cell').width()\n $(\"#conditiongrid\").css(\"width\", parentWidth)\n $(\"#conditiongrid\").multiselect({\n height: condition_height,\n header: false,\n multiple: false,\n minWidth: \"50\",\n classes: \"mp_dcp_import_select_box_grid\",\n noneSelectedText: \"\",\n selectedList: 1,\n position: {\n my: \"top\",\n at: \"bottom\",\n collision: \"flip\"\n }\n });\n $(\"#conditiongrid\").on(\"multiselectclick\", function (event, ui) {\n scope.loadValue(args.item)\n scope.applyValue(args.item, ui.value)\n });\n if (args.item.IGNORE_IND != 0) {\n //$select.attr(\"disabled\",\"disabled\")\n $(\"#conditiongrid\").multiselect(\"disable\")\n }\n else {\n $(\"#conditiongrid\").multiselect(\"open\")\n }\n };\n this.destroy = function () {\n $select.remove();\n };\n this.focus = function () {\n $select.focus();\n };\n this.loadValue = function (item) {\n $select.val(defaultValue = item[args.column.field]);\n };\n this.serializeValue = function () {\n return ($select.val());\n };\n this.applyValue = function (item, state) {\n //Check to see if the value selected was none, not an actual condition loaded in the criterion object\n if (state != null) {\n if (state == 0) {\n item[args.column.field] = \"NONE\";\n //item[args.column.field] = newConditiondisp.DEF_DISP;\n }\n else {\n //look up the corresponding condition display for the selected condition ID to correctly populate the condition display\n var newConditiondisp = findInObject(pageCriteria.CRITERION.DEF, { DEF_ID: state }, true);\n item[args.column.field] = newConditiondisp.DEF_DISP;\n }\n //update the CONDITION_ID in the array to the newly selected condition_id\n var rowRemoved = 0;\n if (args.item[\"MATCH_PERSON_ID\"] > 0) {\n args.item[\"GROUPID\"] = 0;\n var PersonMatchObjs = findInObject(displayData, { MATCH_PERSON_ID: args.item[\"MATCH_PERSON_ID\"] }, false);\n if (PersonMatchObjs.length > 0) {\n var DuplicateObj = findInObject(PersonMatchObjs, { CONDITION_ID: parseFloat(state) }, false);\n if (DuplicateObj.length > 0) {\n dataView.deleteItem(item.id);\n rowRemoved = 1;\n if (current_group_id == 0) {\n mp_import_success_data_cnt -= 1;\n $('#mp-dcp-import-success-cnt').text(mp_import_success_data_cnt);\n } else {\n mp_import_dirty_data_cnt -= 1;\n $('#mp-dcp-import-failure-cnt').text(mp_import_dirty_data_cnt);\n }\n mp_import_patient_cnt -= 1\n $('#mp-dcp-import-patient-cnt').text(mp_import_patient_cnt);\n grid.invalidate();\n }\n else {\n if (current_cond_id < 0) {\n mp_import_success_data_cnt += 1;\n $('#mp-dcp-import-success-cnt').text(mp_import_success_data_cnt);\n mp_import_dirty_data_cnt -= 1;\n $('#mp-dcp-import-failure-cnt').text(mp_import_dirty_data_cnt);\n }\n args.item[\"CONDITION_ID\"] = parseFloat(state);\n }\n }\n else {\n if (current_cond_id < 0) {\n mp_import_success_data_cnt += 1;\n $('#mp-dcp-import-success-cnt').text(mp_import_success_data_cnt);\n mp_import_dirty_data_cnt -= 1;\n $('#mp-dcp-import-failure-cnt').text(mp_import_dirty_data_cnt);\n }\n args.item[\"CONDITION_ID\"] = parseFloat(state);\n }\n\n if (set_Organization != 0 && mp_dcp_import_set_registry != 0 && mp_import_dirty_data_cnt == 0) {\n $('#mp_dcp_import_status_commit_button button').removeAttr(\"disabled\")\n }\n }\n else {\n args.item[\"CONDITION_ID\"] = parseFloat(state);\n }\n if (rowRemoved == 0) {\n dataView.updateItem(item.id, item);\n grid.render();\n }\n grid.navigateNext();\n }\n };\n this.isValueChanged = function () {\n return ($select.val() != defaultValue);\n };\n this.validate = function () {\n return {\n valid: true,\n msg: null\n };\n };\n this.init();\n }",
"function inputProducts(data){\n data = sortAsc(data, \"name\")\n var htm = selectInput(data, \"_id\", \"name\")\n $('select[role=\"product-list\"]').each(function() {\n $(this).html(htm);\n });\n var template = $('#heroTemplate').html().replace('<option value=\"0\" disabled=\"\">Select One...</option>', htm);\n $('#heroTemplate').html(template);\n}",
"function _move_between_selects(block, myForm, multiselect1, multiselect2) {\n\n\tvar ida = (block ? multiselect1 : multiselect2);\n\tvar idb = (block ? multiselect2 : multiselect1);\n\n\tvar sa = myForm.getSelect(ida);\n\tvar sb = myForm.getSelect(idb);\n\n\tvar t = myForm.getItemValue(ida);\n\tif (t.length == 0)\n\t\treturn;\n\teval(\"var k={'\" + t.join(\"':true,'\") + \"':true};\");\n\n\tvar w = 0;\n\tvar ind = -1;\n\twhile (w < sa.options.length) {\n\t\tif (k[sa.options[w].value] && sa.options[w].value != 'rhumanos@silencor.pt' && sa.options[w].value != 'administracao@silencor.pt') {\n\t\t\tsb.options.add(new Option(sa.options[w].text, sa.options[w].value));\n\t\t\tsa.options.remove(w);\n\t\t\tind = w;\n\t\t} else {\n\t\t\tw++;\n\t\t}\n\t}\n\n\tif (sa.options.length > 0 && ind >= 0)\n\t\tif (sa.options.length > 0)\n\t\t\tsa.options[t.length > 1 ? 0 : Math.min(ind, sa.options.length - 1)].selected = true;\n}",
"function initializeDropDown(div, data, selectAllText) {\n\tvar dataLength = data.length, i, dataIndex, html = '';\n\tfor(i = 0; i < dataLength; i = i + 1) {\n\t\tdataIndex = data[i];\n\t\thtml = html + '<option value=\"' + dataIndex.text + '\" selected=selected>' + dataIndex.text + '</option>';\n\t}\n\t$(div).html(html);\n\t$(div).multipleSelect({\n\t\tonClick: $.proxy(dropdownSelect, window, div),\n\t\tonCheckAll: $.proxy(dropdownSelect, window, div),\n\t\tonUncheckAll: $.proxy(dropdownSelect, window, div)\n\t});\n}",
"function populateSelect(optionSetCollection)\n{\n var functionName = \"populateSelect\";\n try\n {\n // clear the multiselect options \n $(\"#multiSelect\").empty();\n\n // Bind the multiselect options with the optionset data\n for (var i in optionSetCollection)\n {\n $('#multiSelect').append($('<option>', {\n value: optionSetCollection[i].Label,\n text: optionSetCollection[i].Label,\n title: optionSetCollection[i].Label\n }));\n }\n }\n catch (e) {\n // throw error\n throwError(e, functionName);\n }\n}",
"function commerceProviderSelectedHandler() {\n const commerceProvider = getSelectedCommerceProvider();\n if (commerceProvider !== '') {\n const catalogs = getCatalogIdentifiers(commerceProvider);\n\n catalogIdentifierCoralSelectComponent.items.clear();\n const items = buildSelectItems(catalogs);\n items.forEach(item => {\n catalogIdentifierCoralSelectComponent.items.add(item);\n });\n catalogIdentifierCoralSelectComponent.disabled = false;\n } else {\n catalogIdentifierCoralSelectComponent.disabled = true;\n }\n }",
"_closeAllLists() {\n let elements = document.getElementsByClassName('multi-select__select');\n for (let i = 0; i < elements.length; i++) {\n if (elements[i] !== this._select.get()) {\n if (elements[i].classList.contains('multi-select__select--opened')) {\n elements[i].classList.remove('multi-select__select--opened');\n }\n }\n }\n }",
"function customSelectsAdjust() {\n $('.sel').each(function () {\n let value = ($(this).find('.sel__opt-val').length > 0) // if .sel__opt-val exists\n ? $(this).find('.sel__opt-val').first().text()\n : $(this).find('.sel__opt').first().text();\n $(this).find('.sel__rslt').text(value);\n \n $(this).width($(this).find('.sel__opts').width());\n })\n }",
"function setOptionLabels(mthis) {\n var products = [];\n var optVal = mthis.val();\n var attrId = parseInt(mthis.prop(\"id\").replace(/[^\\d.]/g, \"\"));\n var data = JSON.parse(getAllData());\n var options = data.attributes[attrId].options;\n options.forEach(function (cObj) {\n if (cObj.id == optVal) {\n cObj.products.forEach(function (cPro) {\n var selectIndex = jQuery(\"select\").index(mthis);\n if (selectIndex > 0) {\n var prevSelect = jQuery(\"select\").eq(selectIndex - 1);\n var prevSelectAttrId = parseInt(\n prevSelect.prop(\"id\").replace(/[^\\d.]/g, \"\")\n );\n if (!isNaN(prevSelectAttrId)) {\n var prevSelectOptions = data.attributes[prevSelectAttrId].options;\n prevSelectOptions.forEach(function (subObj) {\n if (subObj.id == prevSelect.val()) {\n if (subObj.products.indexOf(cPro) != -1) {\n products.push(cPro);\n }\n }\n });\n }\n } else {\n products.push(cPro);\n }\n });\n }\n });\n var selectIndex = jQuery(\".input-box select\").index(mthis);\n var nextSelect = jQuery(\".input-box select\").eq(selectIndex + 1);\n if (nextSelect.length > 0) {\n var nextSelectAttrId = parseInt(\n nextSelect.prop(\"id\").replace(/[^\\d.]/g, \"\")\n );\n var nextSelectOptions = data.attributes[nextSelectAttrId].options;\n nextSelect.empty();\n nextSelect.append(\"<option value>Choose an Option...</option>\");\n nextSelect.removeAttr(\"disabled\");\n nextSelectOptions.forEach(function (cObj) {\n cObj.products.forEach(function (cPro) {\n if (products.indexOf(cPro) != -1) {\n if (jQuery(\"option[value=\" + cObj.id + \"]\").length <= 0) {\n nextSelect.append(\n '<option value=\"' + cObj.id + '\">' + cObj.label + \"</option>\"\n );\n }\n }\n });\n });\n }\n}",
"function createGenresSelect(container, genres) {\n for (var i = 0; i < genres.length; i++) {\n var option = $(\".template option\").clone();\n option.val(genres[i][\"id\"]).text(genres[i][\"name\"])\n container.append(option);\n }\n}",
"function showSelectManufacturer() {\n var msg = callAPI(uRLBase + \"Manufacturer\", \"GET\");\n $('#commodity-owner').html('<option value=\"\"> --- Chọn nhà sản xuất ---</option>');\n\n if(msg)\n {\n $.each(msg, function(key, value){\n var newRow = '<option value=\"' + value['$class'] + '#' +value['tradeId'] + '\">' + value['companyName'] + '</option>';\n $('#commodity-owner').append(newRow);\n });\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Opens a dialog, where a new workspace can be chosen | newWorkspaceDialog() {
let Dialog_SelectWorkspace = require(path.join(__rootdir, "js", "dialogs", "selworkspace.js"))
new Dialog_SelectWorkspace(600, "", (result) => {
if(result === false)
return
let ws = wmaster.addWorkspace(result)
this.setWorkspace(ws)
// display loading indicator
this.body.innerHTML = `<div class="abs-fill flex-col" style="justify-content: center"><div style="align-self: center">...</dib></div>`
})
} | [
"showDeleteProjectDialog() {\n // hide project options dialog\n this.shadowRoot.getElementById(\"dialog-project-options\").close();\n\n // open delete dialog\n this.shadowRoot.getElementById(\"dialog-delete-project\").open();\n }",
"openProject(event) {\n const controller = event.data.controller;\n ListDialog.type = 'openProject';\n const warning = new WarningDialog(() => {\n const dialog = new ListDialog(() => {\n if (dialog.selectedItems.length != 0) {\n dialog.selectedItems\n .forEach((value) => {\n controller.loadProject(value);\n });\n if (controller.persistenceController.getCurrentProject().version > BeastController.BEAST_VERSION) {\n InfoDialog.showDialog('This BEAST-version is older than the version this project was created with!<br>Some of of the components may be incompatible with this version.');\n }\n }\n }, controller.listProjects());\n dialog.show();\n }, () => {\n MenubarController.openAfterWarning = true;\n $('#saveProject')\n .click();\n }, () => {\n MenubarController.openAfterWarning = true;\n $('#exportProject')\n .click();\n }, null);\n if (controller.isDirty()) {\n warning.show();\n }\n else {\n warning.callbackContinue();\n }\n MenubarController.openAfterWarning = false;\n }",
"openProjectOptionsDialog(project) {\n this.projectOptionsSelected = project;\n\n // reset the dialog\n this.shadowRoot.getElementById(\"connected-group-name\").style.removeProperty(\"display\");\n this.shadowRoot.getElementById(\"input-edit-group-name\").style.setProperty(\"display\", \"none\");\n\n this.shadowRoot.getElementById(\"connected-group-project-name\").innerText = project.name;\n this.shadowRoot.getElementById(\"connected-group-name\").innerText = project.groupName;\n\n // open the dialog\n this.shadowRoot.getElementById(\"dialog-project-options\").open();\n }",
"function openCreateLayerModal() {\n layerManagementWidget.expanded = false; //Close the widget that opens the window so it won't be in the way.\n\n //Create the list of features and renderers that available to create a layer from.\n const featureOptions = projectFeatures.map( (feature) => {\n const elem = document.createElement(\"option\");\n elem.value = feature.name;\n elem.text = feature.name;\n return elem;\n });\n\n const layerSelect = document.getElementById(\"layer-feature-select\");\n layerSelect.replaceChildren(...featureOptions);\n layerSelect.appendChild(new Option(\"None\", false));\n\n const rendererOptions = projectRenderers.map( ( renderer ) => {\n const elem = document.createElement(\"option\");\n elem.value = renderer.name;\n elem.text = renderer.name;\n return elem;});\n\n const rendererSelect = document.getElementById(\"layer-renderer-select\");\n rendererSelect.replaceChildren(...rendererOptions);\n rendererSelect.appendChild(new Option(\"None\", false));\n\n //Open the window\n document.getElementById(\"create-layer-modal\").style.display = \"block\";\n }",
"function displayChooseProjDialog(resource_id,link_to_project_id) {\r\n\t// If project_id is supplied, then pre-select the drop-down when the dialog appears\r\n\tif (link_to_project_id > 0) {\r\n\t\t$('#choose_project_select').val(link_to_project_id);\r\n\t\t// Make sure current user has access to the project that is current set (if not, don't allow them to change).\r\n\t\tif ($('#choose_project_select').val() != link_to_project_id) {\r\n\t\t\talert('NOTICE: It appears that you do not have access to this particular REDCap project, so you will not be able to modify the link here that points to that project. However, you may delete the link to that project, if you wish.');\r\n\t\t\tenableResourceTableEdit();\r\n\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\tenableResourceTableEdit();\r\n\t// Open the dialog\r\n\t$('#choose_project_div').dialog({ bgiframe: true, modal: true, width: 700, open: function(){fitDialog(this)}, buttons: { \r\n\t\tClose: function() { $(this).dialog('close'); },\r\n\t\tSave: function() { \r\n\t\t\tif ($('#choose_project_select').val().length < 1) {\r\n\t\t\t\talert(\"Please choose a project\");\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\tif (resource_id != 0) {\r\n\t\t\t\t// Edit existing link\r\n\t\t\t\t$.post(app_path_webroot+'ExternalLinks/edit_resource_ajax.php?pid='+pid, { link_to_project_id: $('#choose_project_select').val(), action: 'edit', link_type: 'REDCAP_PROJECT', ext_id: resource_id }, function(data){\r\n\t\t\t\t\tif (data != '0') {\r\n\t\t\t\t\t\t$('#table-resources-parent').html(data);\r\n\t\t\t\t\t\tenableResourceTableEdit();\r\n\t\t\t\t\t\thighlightResourceRow(resource_id);\r\n\t\t\t\t\t\tupdateResourcePanel();\r\n\t\t\t\t\t\t$('#choose_project_div').dialog('close');\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\talert(woops);\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t} else {\r\n\t\t\t\t// Creating new link (will get saved but not here)\r\n\t\t\t\tvar newprojtitle = $(\"#choose_project_select option:selected\").text();\t\r\n\t\t\t\t$('#new_projtitle_id_0').html(newprojtitle);\r\n\t\t\t\t$('#input_Resourceprojectlink_id_0').val( $(\"#choose_project_select\").val() );\r\n\t\t\t\tenableResourceTableEdit();\r\n\t\t\t\t$(this).dialog('close');\r\n\t\t\t}\r\n\t\t} \r\n\t}});\r\n}",
"function addProject(){\n\n\t\t\t\tvar addProjWindow = new Window(\"palette\", \"Add Project\");\n\n\t\t\t\t// group for custom project\n\t\t\t\tvar customProjGroup = addProjWindow.add(\"group\");\n\t\t\t\t\tcustomProjGroup.orientation = \"column\";\n\t\t\t\t\tcustomProjGroup.alignChildren = ['left', 'fill']\n\n\t\t\t\t\t// Project name group\n\t\t\t\t\tvar projNameGroup = customProjGroup.add(\"group\");\n\n\t\t\t\t\t\tprojNameGroup.add(\"statictext\", undefined, \"Project Name:\")\n\t\t\t\t\t\t// Project Name\n\t\t\t\t\t\tvar projName = projNameGroup.add(\"edittext\", undefined, \"Project Name\");\n\t\t\t\t\t\t\tprojName.characters = 32;\n\n\t\t\t\t\t// Project location group\n\t\t\t\t\tvar projLocGroup = customProjGroup.add(\"group\");\n\n\t\t\t\t\t\tprojLocGroup.add(\"statictext\", undefined, \"Project Location:\")\n\n\t\t\t\t\t\t// Project Location\n\t\t\t\t\t\tvar projLoc = projLocGroup.add(\"edittext\", undefined, \"Project Location\");\n\t\t\t\t\t\t\tprojLoc.characters = 24;\n\n\t\t\t\t\t\tvar getProjLoc = projLocGroup.add(\"button\", undefined, \"...\");\n\t\t\t\t\t\t\tgetProjLoc.preferredSize = [31, 20];\n\n\t\t\t\t// group for buttons\n\t\t\t\tvar addProjBtns = addProjWindow.add(\"group\");\n\n\t\t\t\t\t// button for current project\n\t\t\t\t\tvar setCurProjBtn = addProjBtns.add(\"button\", undefined, \"Set Current\");\n\n\t\t\t\t\t// button to add the project\n\t\t\t\t\tvar addProjBtn = addProjBtns.add(\"button\", undefined, \"Add Project\");\n\t\t\t\t\t\n\t\t\t\t\t// button to cancel\n\t\t\t\t\tvar cancelAddBtn = addProjBtns.add(\"button\", undefined, \"Close\");\n\n\t\t\t\t// ----- SHOW WINDOW -----\n\t\t\t\taddProjWindow.show();\n\t\t\t\t\n\t\t\t\t// ----- Add Project Window Functionality -----\n\t\t\t\tgetProjLoc.onClick = function(){\n\t\t\t\t\tvar getAEP = File.openDialog(\"Please select the location of an AEP.\");\n\t\t\t\t\tif (getAEP != null){\n\n\t\t\t\t\t\tif (getAEP.fsName.split(\".\").pop() == \"aep\"){\n\n\t\t\t\t\t\t\tprojName.text = getAEP.fsName.split(\"/\").pop();\n\t\t\t\t\t\t\tprojLoc.text = getAEP.fsName;\n\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\talert(getAEP.name.split(\".\")[0] + \" is a \" + getAEP.fsName.split(\".\").pop() + \" file. Please select an AEP!\")\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\talert(\"Could not open file. Please make sure you selected something!\")\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tsetCurProjBtn.onClick = function(){\n\n\t\t\t\t\tif (app.project){\n\n\t\t\t\t\t\tprojName.text = String(app.project.file).split(\"/\").pop();\n\t\t\t\t\t\tprojLoc.text = app.project.file;\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\talert(\"Please open a Project!\");\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\taddProjBtn.onClick = function(){\n\n\t\t\t\t\tif (new File(projLoc.text).exists){\n\t\t\t\t\t\tif(projName.text.length > 0 && projName.text != \"Project Name\"){\n\t\t\t\t\t\t\ttheList[projName.text] = projLoc.text;\n\t\t\t\t\t\t\tupdateProjList(getProjectNames(theList));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\talert(\"The name \\'\" + projName.text + \"\\' is not valid. Please choose a better name.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\talert(\"File at \" + projLoc.text + \" does not exist. Please double check that you've selected the correct file.\")\n\t\t\t\t\t}\n\n\t\t\t\t\t\n\t\t\t\t}\n\n\t\t\t\tcancelAddBtn.onClick = function(){\n\n\t\t\t\t\treturn addProjWindow.close();\n\t\t\t\t}\n\n\t\t\t} // ----- End Add Project Window -----",
"function setupCreateNewPathwayButton() {\n var newItem;\n $(\"div[name='createNewPathway']\").click(function(){\n if ( newItem == undefined )\n newItem = \n\t\tcreateDialog(\"div.createPathway\", \n\t\t\t\t{position:[250,150], width: 700, height: 350, \n\t\t\t\ttitle: \"Create a New Pathway Analysis\"});\n $.get(\"pathway.jsp\", function(data){\n newItem.dialog(\"open\").html(data);\n\t\tcloseDialog(newItem);\n });\n });\n}",
"function tb_add_clipping_to_workspace(){\n $(\"#TB_window input.link\").link_button();\n\t$(\"#project_name\").clear_search();\n $(\"form.new_clipping\").select_project_to_add();\n}",
"createProject(event) {\n const controller = event.data.controller;\n const warning = new WarningDialog(() => {\n controller.createNewProject();\n }, () => {\n MenubarController.createAfterWarning = true;\n $('#saveProject')\n .click();\n }, () => {\n MenubarController.createAfterWarning = true;\n $('#exportProject')\n .click();\n }, null);\n if (controller.isDirty()) {\n warning.show();\n }\n else {\n warning.callbackContinue();\n }\n MenubarController.createAfterWarning = false;\n }",
"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 }",
"_closeCreateProjectDialogClicked() {\n this.shadowRoot.getElementById(\"dialog-create-project\").close();\n\n // clear input field for project name in the dialog\n this.shadowRoot.getElementById(\"input-project-name\").value = \"\";\n }",
"function openSelectRoomDialog() {\n\tvar roomPanel = View.panels.get(\"roomPanel\");\n\tvar buildingId = roomPanel.getFieldValue(\"reserve_rs.bl_id\");\n\tvar floorId = roomPanel.getFieldValue(\"reserve_rs.fl_id\");\n\t\n\tView.openDialog(\"ab-rr-select-room.axvw\", null, false, {\n\t\ttitle: getMessage(\"selectRoom\"),\n\t\tbuildingId: buildingId,\n\t\tfloorId: floorId\n\t});\n}",
"function showSetupDialog() {\n openDialog('/html/setup.html', 500, 660);\n}",
"showAddExerciseDialog()\n {\n this.addDialog.MaterialDialog.show();\n this.addExerciseName.focus();\n }",
"function goToTeamSelection(){\n clientValuesFactory.setActiveWindow(windowViews.selectTeam);\n }",
"function displayProject(index) {\r\n localStorage.setItem(\"aProjectIndex\", index);\r\n window.open(\"ProjectsInfo.html\",\"_self\");\r\n}",
"exportProject(event) {\n const controller = event.data.controller;\n InputDialog.type = 'exportProject';\n const exportDialog = new InputDialog((input) => {\n const p = controller.persistenceController.getCurrentProject();\n p.setName(input);\n controller.persistenceController.downloadCurrentProject();\n if (MenubarController.createAfterWarning) {\n $('#createProject')\n .click();\n }\n if (MenubarController.importAfterWarning) {\n $('#importProject')\n .click();\n }\n if (MenubarController.openAfterWarning) {\n $('#openProject')\n .click();\n }\n }, controller.persistenceController.getCurrentProject()\n .getName(), null);\n exportDialog.show();\n }",
"function createNewCarWindow() {\n if (newCarWin) {\n return;\n }\n\n newCarWin = new BrowserWindow({width: 450, height: 400, webPreferences :{nodeIntegration : true}});\n newCarWin.loadFile(path.join('src', 'addCar.html'));\n\n // Listen when the window will be closed for destroy it\n newCarWin.on('closed', () => {\n newCarWin = null\n })\n}",
"function showOpenSeed (opts) {\n setTitle(opts.title)\n const selectedPaths = dialog.showOpenDialogSync(windows.main.win, opts)\n resetTitle()\n if (!Array.isArray(selectedPaths)) return\n windows.main.dispatch('showCreateTorrent', selectedPaths)\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Moves the language down in the list. | onMoveDownTap_() {
/** @type {!CrActionMenuElement} */ (this.$.menu.get()).close();
this.languageHelper.moveLanguage(
this.detailLanguage_.language.code, false /* upDirection */);
settings.recordSettingChange();
} | [
"onMoveUpTap_() {\n /** @type {!CrActionMenuElement} */ (this.$.menu.get()).close();\n this.languageHelper.moveLanguage(\n this.detailLanguage_.language.code, true /* upDirection */);\n settings.recordSettingChange();\n }",
"function moveDown() {\n\tmoveWrapper(this.ancestor(fieldWrapperSelector), 'down');\n}",
"function updateLanguage(select_language, select_dialect) {\n var list = langs[select_language.selectedIndex];\n select_dialect.style.visibility = list[1].length == 1 ? 'hidden' : 'visible';\n localStorage['dialect'] = select_dialect.selectedIndex; \n document.getElementById('voiceBtn').setAttribute('lang', list[select_dialect.selectedIndex + 1][0]);\n}",
"function goDown() {\n if (currentSectionIndex + 1 <= allSections.length - 1) {\n goToSection(currentSectionIndex + 1);\n } else {\n goToSection(0);\n }\n playRandomPeelingSound();\n }",
"function moveSoundDown(e) {\n var thisSound,\n nextSound,\n playlist;\n e.preventDefault();\n thisSound = this.parentNode.parentNode;\n nextSound = thisSound.nextElementSibling;\n playlist = thisSound.parentNode;\n\n if ( nextSound ) {\n nextNextSound = nextSound.nextElementSibling;\n if ( nextNextSound ) {\n playlist.insertBefore( thisSound, nextNextSound ); // there's no insertAfter.\n } else {\n playlist.appendChild(thisSound); // we're at the end.\n }\n }\n }",
"function moveSelectedItemsDown(src) {\r\n var i;\r\n for (i = src.options.length - 1; i >= 0; --i) {\r\n var thisitem = src.options[i];\r\n if (thisitem.selected == true) {\r\n // already at the end\r\n if (i == src.options.length - 1) {\r\n return;\r\n } else {\r\n // move the item down\r\n var nextItem = src.options[i + 1];\r\n\r\n thisoption = new Option(thisitem.text, thisitem.value, false, false);\r\n swapoption = new Option(nextItem.text, nextItem.value, false, false);\r\n src.options[i] = swapoption;\r\n src.options[i + 1] = thisoption;\r\n thisoption.selected = true;\r\n }\r\n }\r\n }\r\n}",
"function goUp() {\n if (currentSectionIndex > 0) {\n goToSection(currentSectionIndex - 1);\n }\n }",
"decrementCipherOffset(state) {\n\t\t\tstate.cipherOffset = state.cipherOffset - 1;\n\n\t\t\tstate.cipherText = encodeText(state.sourceText, state.cipherOffset);\n\t\t}",
"slideBack() {\n this.slideBy(-this.getSingleStep());\n }",
"function setLang(l){\n\tif(lockLangButtons == true){\n\t\treturn;\n\t}\n\tdisableNav();\n\t$('.zone').empty();\n\t$(\".zone\").slideUp(1000);\n\t$(\".zone\").slideDown(1000);\n\tlang = l;\n\tsetTimeout(function(){\n\t\t\n\t\tnewGame();\n\t}, 1100);\n}",
"function moveDown(notebook) {\n if (!notebook.model || !notebook.activeCell) {\n return;\n }\n const state = Private.getState(notebook);\n const cells = notebook.model.cells;\n const widgets = notebook.widgets;\n cells.beginCompoundOperation();\n for (let i = cells.length - 2; i > -1; i--) {\n if (notebook.isSelectedOrActive(widgets[i])) {\n if (!notebook.isSelectedOrActive(widgets[i + 1])) {\n cells.move(i, i + 1);\n if (notebook.activeCellIndex === i) {\n notebook.activeCellIndex++;\n }\n notebook.select(widgets[i + 1]);\n notebook.deselect(widgets[i]);\n }\n }\n }\n cells.endCompoundOperation();\n Private.handleState(notebook, state, true);\n }",
"function nextWord(){\n currentWord = currentList.pop();\n $('#front').text(currentWord.nativeWord);\n setTimeout(function(){\n $('#back').text(currentWord.foreignWord);\n }, 500);\n $('#next-question').hide();\n $('#quiz-answer').show();\n $('.flashcard').toggleClass('flipped');\n}",
"postLanguageToChildren() {\n this.postMessageToChild(MessageType.language, this.translationManagementService.language);\n }",
"function clearLanguages() {\n\t\tlangs = [];\n\t}",
"function scrollDown(amount) {\n moveTo(current - amount);\n scope.selected = item();\n }",
"moveDown(){\n\t\tthis.aimDir = vec2.down();\n\t}",
"setDefaultWordlist(language) {\n bip39.setDefaultWordlist(language);\n }",
"function moveOptionDown(obj) {\n\tfor (i=obj.options.length-1; i>=0; i--) {\n\t\tif (obj.options[i].selected) {\n\t\t\tif (i != (obj.options.length-1) && ! obj.options[i+1].selected) {\n\t\t\t\tswapOptions(obj,i,i+1);\n\t\t\t\tobj.options[i+1].selected = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"function moveDown (){\n\t\tunDraw();\n\t\tcurrentPosition += width;\n\t\tdraw();\n\t\tfreeze();\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
IMGUI_API bool BeginTabItem(const char label, bool p_open = NULL, ImGuiTabItemFlags flags = 0);// create a Tab. Returns true if the Tab is selected. | function BeginTabItem(label, p_open = null, flags = 0) {
// return bind.BeginTabItem(label, p_open, flags);
if (p_open === null) {
return bind.BeginTabItem(label, null, flags);
}
else if (Array.isArray(p_open)) {
return bind.BeginTabItem(label, p_open, flags);
}
else {
const ref_open = [p_open()];
const ret = bind.BeginTabItem(label, ref_open, flags);
p_open(ref_open[0]);
return ret;
}
} | [
"addTab() {\n this._insertItem(FdEditformTab.create({\n caption: `${this.get('i18n').t('forms.fd-editform-constructor.new-tab-caption').toString()} #${this.incrementProperty('_newTabIndex')}`,\n rows: A(),\n }), this.get('selectedItem') || this.get('controlsTree'));\n }",
"function createTabCtrl(meta) {\n \n }",
"function doOpenTool_newTab(url)\n{\n var br = getBrowser();\n br.selectedTab = br.addTab(url);\n}",
"function menuHandler(){\n if(command.getChecked()){\n command.setChecked(false);\n prefs.set('enabled',false);\n return;\n }\n command.setChecked(true); \n prefs.set('enabled',true);\n var st = startTabEx();\n }",
"_focusFirstTab () {\n this.tabs[0].focus()\n }",
"function displayUserTab() {\n\n}",
"function selectItem(e) {\r\n removeBorder();\r\n removeShow();\r\n // Add border to current tab\r\n this.classList.add('tab-border');\r\n // Grab content from DOM\r\n console.log(this.id);\r\n const tabContentItem = document.querySelector(`#${this.id}-content`);\r\n\t// Add show class\r\n\ttabContentItem.classList.add('show');\r\n\r\n}",
"function poTabClicked()\n{\n\t$( \"#rfq_tab\" ).removeClass( 'tab_orange' );\n\t$( \"#rfq_tab\" ).addClass( 'tab_gray' );\n\t\n\t$( \"#quote_tab\" ).removeClass( 'tab_orange' );\n\t$( \"#quote_tab\" ).addClass( 'tab_gray' );\n\t\n\t$( \"#po_tab\" ).removeClass( 'tab_gray' );\n\t$( \"#po_tab\" ).addClass( 'tab_orange' );\n\t\n\t$( \"#invoice_tab\" ).removeClass( 'tab_orange' );\n\t$( \"#invoice_tab\" ).addClass( 'tab_gray' );\n\t\n\tselectedTab = \"PO\";\n\t\n\t $(\"#transet_label_content\").val(poText);\n\t $(\"#transet_titile\").text(\"PO Terms and Conditions\");\n\t\t\n\tif(poText==\"\")\n\t{\n\t\t$(\"#no_tc\").show();\n\t\t $(\"#tc_content\").hide();\n\t}\n\telse\n\t{\n\t\t$(\"#tc_content\").show(); \n\t\t $(\"#no_tc\").hide();\n\t}\n}",
"focusFirst(){\r\n const tab = this.tabControl.querySelector('.glu_verticalTabs-tab');\r\n if (!tab)\r\n return;\r\n\r\n this.focusTab(tab);\r\n }",
"function WMEAutoUR_Create_TabbedUI() {\n\tWMEAutoUR_TabbedUI = {};\n\t/**\n\t *@since version 0.11.0\n\t */\n\tWMEAutoUR_TabbedUI.init = function() {\n // See if the div is already created //\n\t\tvar urParentDIV = null;\n\t\tif ($(\"#WME_AutoUR_TAB_main\").length===0) {\n urParentDIV = WMEAutoUR_TabbedUI.ParentDIV();\n $(urParentDIV).append(WMEAutoUR_TabbedUI.Title());\n //$(ParentDIV).append($('<span>').attr(\"id\",\"WME_AutoUR_Info\")\n //\t\t\t\t\t\t\t\t.click(function(){$(this).html('');})\n //\t\t\t\t\t\t\t\t.css(\"color\",\"#000000\"));\n\n $(urParentDIV).append(WMEAutoUR_TabbedUI.TabsHead());\n\n var TabBody = WMEAutoUR_TabbedUI.TabsBody();\n\n $(TabBody).append(WMEAutoUR_TabbedUI.EditorTAB);\n //$(TabBody).append(WMEAutoUR_TabbedUI.MessagesTAB);\n $(TabBody).append(WMEAutoUR_TabbedUI.SettingsTAB);\n\n $(urParentDIV).append(TabBody);\n\n\t\t// See if the div is already created //\n\t\t//if ($(\"#WME_AutoUR_TAB_main\").length===0) {\n\n\t\t\tconsole.info(\"WME-WMEAutoUR_TabbedUI: Loaded Pannel\");\n\t\t\t//ScriptKit.GUI.addImage(1,icon,WMEAutoUR_TabbedUI.hideWindow);\n }\n\n\t\t$(\"div.tips\").after(urParentDIV);\n\t};\n\n\t//--------------------------------------------------------------------------------------------------------------------------------------------\n\t/**\n\t *@since version 0.11.0\n\t */\n\t// ---------- MAIN DIV TOGGLE --------- //\n\tWMEAutoUR_TabbedUI.hideWindow = function() {\n\n\t\tswitch($(\"#WME_AutoUR_TAB_main\").css(\"height\")) {\n\t\t\tcase '30px': \t$(\"#WME_AutoUR_TAB_main\").css(\"height\",\"auto\");\n\t\t\t\t\t\t\t$(\"#WMEAutoUR_TabbedUI_toggle\").html(\"-\");\n\t\t\t\t\t\t\tWMEAutoUR.on();\t\tbreak;\n\t\t\tdefault:\t\t$(\"#WME_AutoUR_TAB_main\").css(\"height\",\"30px\");\n\t\t\t\t\t\t\t$(\"#WMEAutoUR_TabbedUI_toggle\").html(\"+\");\n\t\t\t\t\t\t\tWMEAutoUR.off();\tbreak;\n\t\t}\n\t};\n\n\t//--------------------------------------------------------------------------------------------------------------------------------------------\n\t/**\n\t *@since version 0.11.0\n\t */\n\t// ---------- MAIN DIV --------- //\n\tWMEAutoUR_TabbedUI.ParentDIV = function() {\n\n\t\tvar MainTAB = $('<div>').attr(\"id\",\"WME_AutoUR_TAB_main\")\n\t\t\t\t\t\t\t\t.css(\"color\",\"#FFFFFF\")\n\t\t\t\t\t\t\t\t.css(\"border-bottom\",\"2px solid #E9E9E9\")\n\t\t\t\t\t\t\t\t.css(\"margin\",\"21px 0\")\n\t\t\t\t\t\t\t\t.css(\"padding-bottom\",\"10px\")\n\t\t\t\t\t\t\t\t.css(\"max-width\",\"275px\")\n\t\t\t\t\t\t\t\t.css(\"height\",\"30px\")\n\t\t\t\t\t\t\t\t.css(\"overflow\",\"hidden\")\n\t\t\t\t\t\t\t\t.css(\"display\",\"block\");\n\n\t\treturn MainTAB;\n\t};\n\n\t//--------------------------------------------------------------------------------------------------------------------------------------------\n\t/**\n\t *@since version 0.11.0\n\t */\n\t// ---------- MAIN DIV --------- //\n\tWMEAutoUR_TabbedUI.Title = function() {\n\t\tconsole.info(\"WME-WMEAutoUR_TabbedUI: create main div \");\n\n\t\t// ------- TITLE ------- //\n\t\tvar mainTitle = $(\"<div>\")\n\t\t\t\t\t\t.attr(\"id\",\"WME_AutoUR_TAB_title\")\n\t\t\t\t\t\t.css(\"width\",\"100%\")\n\t\t\t\t\t\t.css(\"text-align\",\"center\")\n\t\t\t\t\t\t.css(\"background-color\",\"rgb(93, 133, 161)\")\n\t\t\t\t\t\t.css(\"border-radius\",\"5px\")\n\t\t\t\t\t\t.css(\"padding\",\"3px\")\n\t\t\t\t\t\t.css(\"margin-bottom\",\"3px\")\n\t\t\t\t\t\t.html(\"WME-AutoUR \" + WMEAutoUR.version)\n\t\t\t\t\t\t.dblclick(WMEAutoUR.showDevInfo)\n\t\t\t\t\t\t.attr(\"title\",\"Click for Development Info\");\n\n\t\t$(mainTitle).append($('<div>').attr(\"id\",\"WMEAutoUR_TabbedUI_toggle\")\n\t\t\t\t\t\t\t\t\t .html(\"+\")\n\t\t\t\t\t\t\t\t\t .css(\"float\",\"right\")\n\t\t\t\t\t\t\t\t\t .css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t .css(\"color\",\"#ffffff\")\n\t\t\t\t\t\t\t\t\t .css(\"right\",\"3px\")\n\t\t\t\t\t\t\t\t\t .css(\"top\",\"0\")\n\t\t\t\t\t\t\t\t\t .css(\"background\",\"#000000\")\n\t\t\t\t\t\t\t\t\t .css(\"height\",\"16px\")\n\t\t\t\t\t\t\t\t\t .css(\"width\",\"16px\")\n\t\t\t\t\t\t\t\t\t .css(\"display\",\"block\")\n\t\t\t\t\t\t\t\t\t .css(\"line-height\",\"14px\")\n\t\t\t\t\t\t\t\t\t .css(\"border-radius\",\"5px\")\n\t\t\t\t\t\t\t\t\t .click(WMEAutoUR_TabbedUI.hideWindow));\n\n\t\treturn mainTitle;\n\t};\n\n\t//--------------------------------------------------------------------------------------------------------------------------------------------\n\t/**\n\t *@since version 0.11.0\n\t */\n\t// ---------- MAIN DIV --------- //\n\tWMEAutoUR_TabbedUI.TabsHead = function() {\n\n\t\t// ------- TABS ------- //\n\t\tvar mainTabs = $(\"<div>\")\n\t\t\t\t\t\t.attr(\"id\",\"WME_AutoUR_TAB_head\")\n\t\t\t\t\t\t.css(\"padding\",\"3px\")\n\t\t\t\t\t\t.css(\"margin-bottom\",\"3px\")\n\t\t\t\t\t\t.attr(\"title\",\"Click for Development Info\");\n\t\tvar tabs = $(\"<ul>\").addClass(\"nav\")\n\t\t\t\t\t\t\t.addClass(\"nav-tabs\");\n\n\t\t$(tabs).append($(\"<li>\").append($(\"<a>\").attr(\"data-toggle\",\"tab\")\n\t\t\t\t\t\t\t\t\t\t\t\t.attr(\"href\",\"#WMEAutoUR_EDIT_TAB\")\n\t\t\t\t\t\t\t\t\t\t\t\t.html(\"Editor\")\n\t\t\t\t\t\t\t\t\t ).addClass(\"active\")\n\t\t\t\t\t );\n\n\t\t//$(tabs).append($(\"<li>\").append($(\"<a>\").attr(\"data-toggle\",\"tab\")\n\t\t//\t\t\t\t\t\t\t\t\t\t.attr(\"href\",\"#WMEAutoUR_MSG_TAB\")\n\t\t//\t\t\t\t\t\t\t\t\t\t.html(\"Messages\")\n\t\t//\t\t\t\t\t\t\t )\n\t\t//\t\t\t );\n\n\t\t$(tabs).append($(\"<li>\").append($(\"<a>\").attr(\"data-toggle\",\"tab\")\n\t\t\t\t\t\t\t\t\t\t\t\t.attr(\"href\",\"#WMEAutoUR_SET_TAB\")\n\t\t\t\t\t\t\t\t\t\t\t\t.html(\"Settings\")\n\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t );\n\n\t\t$(mainTabs).append(tabs);\n\n\t\treturn mainTabs;\n\t};\n\n\t//--------------------------------------------------------------------------------------------------------------------------------------------\n\t/**\n\t *@since version 0.11.0\n\t */\n\t// ---------- MAIN DIV --------- //\n\tWMEAutoUR_TabbedUI.TabsBody = function() {\n\n\t\t// ------- TABS ------- //\n\t\tvar TabsBodyContainer = $(\"<div>\")\n\t\t\t\t\t\t\t .attr(\"id\",\"WME_AutoUR_TAB_tabs\")\n\t\t\t\t\t\t\t .attr(\"style\",\"padding: 0 !important;\")\n\t\t\t\t\t\t\t .addClass(\"tab-content\");\n\n\t\treturn TabsBodyContainer;\n\t};\n\n\t//--------------------------------------------------------------------------------------------------------------------------------------------\n\n\t/**\n\t *@since version 0.8.1\n\t */\n\tWMEAutoUR_TabbedUI.EditorTAB = function() {\n\n\t\tvar editTAB = $('<div>').attr(\"id\",'WMEAutoUR_EDIT_TAB')\n\t\t\t\t\t\t\t\t.addClass(\"tab-pane\")\n\t\t\t\t\t\t\t\t.addClass(\"active\");\n\n\t\t$(editTAB).append($(\"<span id='WME_AutoUR_Info'>\")\n\t\t\t\t\t\t\t//.css(\"float\",\"right\")\n\t\t\t\t\t\t\t.css(\"text-align\",\"left\")\n\t\t\t\t\t\t\t.css(\"display\",\"block\")\n\t\t\t\t\t\t\t.css(\"max-width\",\"275px\")\n\t\t\t\t\t\t\t//.css(\"height\",\"150px\")\n\t\t\t\t\t\t\t.css(\"color\",\"#000000\")\n\t\t\t\t\t\t\t.css(\"clear\",\"both\"));\n\n\t\tvar autoBar = $('<div>').css(\"width\",\"100%\")\n\t\t\t\t\t\t\t\t.css(\"clear\",\"both\")\n\t\t\t\t\t\t\t\t.css(\"padding-top\",\"10px\");\n\t\t$(editTAB).append($(autoBar));\n\n\t\t$(autoBar).append($(\"<button>Prev</button>\")\n\t\t\t\t\t\t\t.click(WMEAutoUR.Auto.Prev)\n\t\t\t\t\t\t\t.css(\"position\",\"relative\")\n\t\t\t\t\t\t\t.css(\"float\",\"left\")\n\t\t\t\t\t\t\t.css(\"height\",\"24px\")\n\t\t\t\t\t\t\t.attr(\"title\",\"Previous UR\"));\n\n\t\t$(autoBar).append($(\"<button>Next</button>\")\n\t\t\t\t\t\t\t.click(WMEAutoUR.Auto.Next)\n\t\t\t\t\t\t\t.css(\"position\",\"relative\")\n\t\t\t\t\t\t\t.css(\"float\",\"right\")\n\t\t\t\t\t\t\t.css(\"height\",\"24px\")\n\t\t\t\t\t\t\t.attr(\"title\",\"Next UR\"));\n\n\t\t$(autoBar).append($(\"<span id='WME_AutoUR_Count'>\")\n\t\t\t\t\t\t\t.css(\"text-align\",\"center\")\n\t\t\t\t\t\t\t.css(\"display\",\"block\")\n\t\t\t\t\t\t\t.css(\"width\",\"60px\")\n\t\t\t\t\t\t\t.css(\"margin\",\"0 auto\")\n\t\t\t\t\t\t\t.css(\"padding\",\"3px\")\n\t\t\t\t\t\t\t.css(\"background-color\",\"#000000\")\n\t\t\t\t\t\t\t.css(\"border-radius\",\"3px\")\n\t\t\t\t\t\t\t.html(\"Auto Off\")\n\t\t\t\t\t\t\t.dblclick(WMEAutoUR.Auto.getIDs)\n\t\t\t\t\t\t\t.attr(\"title\",\"Double click to load/reload list of URs\"));\n\n\n\t\tvar actsBar = $('<div>').css(\"width\",\"100%\")\n\t\t\t\t\t\t\t\t.css(\"clear\",\"both\")\n\t\t\t\t\t\t\t\t.css(\"font-size\",\"12px\")\n\t\t\t\t\t\t\t\t.css(\"padding-top\",\"2px\");\n\t\t$(editTAB).append($(actsBar));\n\n\t\t$(actsBar).append($(\"<button>None</button>\")\n\t\t\t\t\t\t\t .attr(\"id\",\"WME_AutoUR_Filter_button\")\n\t\t\t\t\t\t\t .click(WMEAutoUR.Auto.filterButton)\n\t\t\t\t\t\t\t .val(2)\n\t\t\t\t\t\t\t .css(\"float\",\"left\")\n\t\t\t\t\t\t\t .css(\"background-color\",\"White\")\n\t\t\t\t\t\t\t .css(\"color\",\"Black\")\n\t\t\t\t\t\t\t .css(\"border-radius\",\"5px\")\n\t\t\t\t\t\t\t .css(\"width\",\"55px\")\n\t\t\t\t\t\t\t .attr(\"title\",\"Change filter between Initial-Stale-Dead.\"));\n\n\t\t$(actsBar).append($(\"<button>Send</button>\")\n\t\t\t\t\t\t\t .click(WMEAutoUR.Messages.Send)\n\t\t\t\t\t\t\t .css(\"float\",\"left\")\n\t\t\t\t\t\t\t .css(\"width\",\"55px\")\n\t\t\t\t\t\t\t .attr(\"title\",\"Insert message. \"));\n\n\t\t$(actsBar).append($(\"<button>Solve</button>\")\n\t\t\t\t\t\t\t .click(WMEAutoUR.Messages.changeStatus)\n\t\t\t\t\t\t\t .attr(\"data-state\",\"0\")\n\t\t\t\t\t\t\t .css(\"float\",\"right\")\n\t\t\t\t\t\t\t .css(\"width\",\"55px\")\n\t\t\t\t\t\t\t .attr(\"title\",\"Mark Solved.\"));\n\n\t\t$(actsBar).append($(\"<button>Not ID</button>\")\n\t\t\t\t\t\t\t .click(WMEAutoUR.Messages.changeStatus)\n\t\t\t\t\t\t\t .attr(\"data-state\",\"1\")\n\t\t\t\t\t\t\t .css(\"float\",\"right\")\n\t\t\t\t\t\t\t .css(\"width\",\"55px\")\n\t\t\t\t\t\t\t .attr(\"title\",\"Mark Not Identified.\"));\n\n\n\t\tvar setsBar = $('<div>').css(\"width\",\"275px\")\n\t\t\t\t\t\t\t\t.css(\"margin-top\",\"2px\")\n\t\t\t\t\t\t\t\t.css(\"clear\",\"both\");\n\t\t$(editTAB).append($(setsBar));\n\n\t\tvar setsBarSub1 = $('<div>').css(\"width\",\"55px\")\n\t\t\t\t\t\t\t\t\t.css(\"height\",\"24px\")\n\t\t\t\t\t\t\t\t\t.css(\"float\",\"left\");\n\t\t//$(setsBar).append($(setsBarSub1));\n\n\n\t\tvar setsBarSub2 = $('<div>').css(\"width\",\"55px\")\n\t\t\t\t\t\t\t\t\t.css(\"height\",\"24px\")\n\t\t\t\t\t\t\t\t\t.css(\"float\",\"left\");\n\t\t$(setsBar).append($(setsBarSub2));\n\t\t$(setsBarSub2).append($(\"<label>\")\n\t\t\t\t\t\t\t .html(\"Adv.\")\n\t\t\t\t\t\t\t .attr(\"for\",\"WMEAutoUR_AutoAdvance_CB\")\n\t\t\t\t\t\t\t .attr(\"title\",\"Enable auto advance with Send/Solve/NI buttons.\")\n\t\t\t\t\t\t\t .css(\"color\",\"black\")\n\t\t\t\t\t\t\t .css(\"float\",\"left\"));\n\n\t\t$(setsBarSub2).append($(\"<input>\")\n\t\t\t\t\t\t\t .attr(\"id\",\"WMEAutoUR_AutoAdvance_CB\")\n\t\t\t\t\t\t\t .attr(\"type\",\"checkbox\")\n\t\t\t\t\t\t\t .css(\"float\",\"left\")\n\t\t\t\t\t\t\t .css(\"margin-left\",\"5px\")\n\t\t\t\t\t\t\t .attr(\"title\",\"Enable auto advance with Send/Solve/NI buttons.\"));\n\n\n\t\tvar setsBarSub3 = $('<div>').css(\"width\",\"55px\")\n\t\t\t\t\t\t\t\t\t.css(\"height\",\"24px\")\n\t\t\t\t\t\t\t\t\t.css(\"float\",\"left\");\n\t\t$(setsBar).append($(setsBarSub3));\n\t\t$(setsBarSub3).append($(\"<label>\")\n\t\t\t\t\t\t\t .html(\"Send\")\n\t\t\t\t\t\t\t .attr(\"for\",\"WMEAutoUR_SendMessage_CB\")\n\t\t\t\t\t\t\t .attr(\"title\",\"Send message with Solve/NI buttons.\")\n\t\t\t\t\t\t\t .css(\"color\",\"black\")\n\t\t\t\t\t\t\t .css(\"float\",\"left\"));\n\n\t\t$(setsBarSub3).append($(\"<input>\")\n\t\t\t\t\t\t\t .attr(\"id\",\"WMEAutoUR_SendMessage_CB\")\n\t\t\t\t\t\t\t .attr(\"type\",\"checkbox\")\n\t\t\t\t\t\t\t .css(\"float\",\"left\")\n\t\t\t\t\t\t\t .css(\"margin-left\",\"5px\")\n\t\t\t\t\t\t\t .attr(\"title\",\"Send message with Solve/NI buttons.\"));\n\n\n\n\n\t\tvar edit_select = $(\"<select>\").attr(\"id\",\"WMEAutoUR_Insert_Select\")\n\t\t\t\t\t\t\t\t\t .attr(\"title\",\"Select message to be inserted\")\n\t\t\t\t\t\t\t\t\t .css(\"width\",\"100%\")\n\t\t\t\t\t\t\t\t\t .css(\"float\",\"left\")\n\t\t\t\t\t\t\t\t\t .change(WMEAutoUR.Messages.insertFromSelect)\n\t\t\t\t\t\t\t\t\t .css(\"padding-top\",\"5px\");\n\n\t\tWMEAutoUR_TabbedUI.createSelect(edit_select);\n\n\t\t$(editTAB).append(edit_select);\n\n\t\t$(editTAB).append($(\"<span id='WME_AutoUR_MSG_Display'>\")\n\t\t\t\t\t\t\t.css(\"text-align\",\"left\")\n\t\t\t\t\t\t\t.css(\"display\",\"block\")\n\t\t\t\t\t\t\t.css(\"width\",\"275px\")\n\t\t\t\t\t\t\t.css(\"padding\",\"10px 0\")\n\t\t\t\t\t\t\t.css(\"color\",\"#000000\")\n\t\t\t\t\t\t\t.css(\"clear\",\"both\"));\n\n\n\t\t$(editTAB).append($(\"<div>\").css(\"clear\",\"both\"));\n\n\n\t\treturn editTAB;\n\t};\n\n\t//--------------------------------------------------------------------------------------------------------------------------------------------\n\t/**\n\t *@since version 0.8.1\n\t */\n\t// ------- SETTINGS TAB ------- //\n\tWMEAutoUR_TabbedUI.SettingsTAB = function() {\n\n\t\tvar setTAB = $('<div>').attr(\"id\",'WMEAutoUR_SET_TAB')\n\t\t\t\t\t\t\t\t//.css(\"padding\",\"10px\")\n\t\t\t\t\t\t\t\t.css(\"max-width\",\"275px\")\n\t\t\t\t\t\t\t\t.css(\"text-align\",\"center\")\n\t\t\t\t\t\t\t\t.html(\"coming soon\")\n\t\t\t\t\t\t\t\t.addClass(\"tab-pane\");\n\n\t\tvar select = $(\"<select>\").attr(\"id\",\"WMEAutoUR_Settings_Select\")\n\t\t\t\t\t\t\t\t.attr(\"title\",\"Select Message\")\n\t\t\t\t\t\t\t\t.css(\"width\",\"225px\")\n\t\t\t\t\t\t\t\t.css(\"float\",\"left\")\n\t\t\t\t\t\t\t\t.change(WMEAutoUR.Messages.ChangeSettingSelect)\n\t\t\t\t\t\t\t\t.focus(WMEAutoUR.Messages.SaveSettingSelect)\n\t\t\t\t\t\t\t\t.css(\"padding-top\",\"5px\");\n\n\t\tWMEAutoUR_TabbedUI.createSelect(select);\n\n\n\t\t// --- MESSAGES --- //\n\t\t$(setTAB).append($(\"<div>\").css(\"clear\",\"both\")\n\t\t\t\t\t\t\t\t\t.css(\"margin-bottom\",\"10px\")\n\t\t\t\t\t\t\t\t\t.append($(\"<h3>\").html(\"Messages\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"color\",\"black\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"text-align\",\"left\")\n\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t.append($(\"<textarea>\").attr(\"id\",\"WMEAutoUR_Settings_Comment\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .val(WMEAutoUR.Options.messages[6])\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"float\",\"left\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"height\",\"125px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"float\",\"left\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"margin-top\",\"5px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"width\",\"100%\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"clear\",\"both\")\n\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t.append(select)\n\t\t\t\t\t\t\t\t\t.append($(\"<button>\").html(\"Save\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"width\",'50px')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"float\",'left')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .click(WMEAutoUR.Messages.SaveSettingSelect)\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t.append($(\"<button>\").html(\"Custom Msg\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"width\",'35%')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"float\",'left')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .click(WMEAutoUR.Messages.addCustom)\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t.append($(\"<input>\").attr('type','text')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .attr(\"id\",'WMEAutoUR_Settings_customName')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"width\",'65%')\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t.append($(\"<div>\").css(\"clear\",\"both\"))\n\t\t\t\t\t\t);\n\n\t\t// --- FILTERS --- //\n\t\t$(setTAB).append($(\"<div>\").css(\"clear\",\"both\")\n\t\t\t\t\t\t\t\t\t.css(\"margin-bottom\",\"10px\")\n\t\t\t\t\t\t\t\t\t.append($(\"<h3>\").html(\"Filters\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"color\",\"black\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"text-align\",\"left\")\n\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t.append($(\"<div>\").attr(\"id\",\"UR_Stale_Dead\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"width\",\"135px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"float\",\"left\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"padding-top\",\"5px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .append($(\"<span>\").html('Stale Days')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.attr(\"title\",\"Days since first editor comment.\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"text-align\",\"center\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"float\",\"left\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"height\",\"24px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"width\",\"99px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"color\",\"black\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t .append($(\"<input>\").attr(\"type\",\"text\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .attr(\"id\",\"UR_Stale_Days\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .attr(\"value\",WMEAutoUR.Options.settings.staleDays)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"height\",\"24px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"width\",\"36px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"text-align\",\"center\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"float\",\"right\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"padding-top\",\"5px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t .append($(\"<span>\").html('Dead Days')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.attr(\"title\",\"Days since second editor comment.\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"text-align\",\"center\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"float\",\"left\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"height\",\"24px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"width\",\"99px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"color\",\"black\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t .append($(\"<input>\").attr(\"type\",\"text\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .attr(\"id\",\"UR_Dead_Days\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .attr(\"value\",WMEAutoUR.Options.settings.deadDays)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"height\",\"24px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"width\",\"36px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"text-align\",\"center\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"float\",\"right\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"padding-top\",\"5px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t.append($(\"<div>\").css(\"clear\",\"both\"))\n\t\t\t\t\t\t );\n\n\t\t// --- Advanced --- //\n\t\t//console.info(WMEAutoUR.Options.settings.staleDays);\n\t\t//console.info(WMEAutoUR.Options.settings.deadDays);\n\t\t//console.info(WMEAutoUR.Options.settings.firstURTextareaTime);\n\t\t//console.info(WMEAutoUR.Options.settings.nextURTextareaTime);\n\n\t\t$(setTAB).append($(\"<div>\").css(\"clear\",\"both\")\n\t\t\t\t\t\t\t\t\t.css(\"margin-bottom\",\"10px\")\n\t\t\t\t\t\t\t\t\t.append($(\"<h3>\").html(\"Advanced\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"color\",\"black\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"text-align\",\"left\")\n\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t.append($(\"<div>\").attr(\"id\",\"UR_TA_Timers\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"width\",\"135px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"float\",\"left\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"padding-top\",\"5px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t .append($(\"<span>\").html('1st UR TA')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.attr(\"title\",\"Offset before attempting to insert into UR comment textarea for first loaded UR.\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"text-align\",\"center\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"float\",\"left\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"height\",\"24px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"width\",\"99px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"color\",\"black\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t .append($(\"<input>\").attr(\"type\",\"text\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .attr(\"id\",\"UR_First_TA_Time\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .attr(\"value\",WMEAutoUR.Options.settings.firstURTextareaTime)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"height\",\"24px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"width\",\"36px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"text-align\",\"center\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"float\",\"right\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"padding-top\",\"5px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t .append($(\"<span>\").html('Next UR TA')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.attr(\"title\",\"Offset before attempting to insert into UR comment textarea for consecutive URs.\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"text-align\",\"center\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"float\",\"left\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"height\",\"24px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"width\",\"99px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.css(\"color\",\"black\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t\t\t .append($(\"<input>\").attr(\"type\",\"text\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .attr(\"id\",\"UR_Next_TA_Time\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .attr(\"value\",WMEAutoUR.Options.settings.nextURTextareaTime)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"height\",\"24px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"width\",\"36px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"text-align\",\"center\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"position\",\"relative\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"float\",\"right\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t .css(\"padding-top\",\"5px\")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t )\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t.append($(\"<div>\").css(\"clear\",\"both\"))\n\t\t\t\t\t\t );\n\n\n\n\t\t$(setTAB).append($(\"<button>Save</button>\")\n\t\t\t\t .click(WMEAutoUR.Settings.Save)\n\t\t\t\t .css(\"float\",\"left\")\n\t\t\t\t .attr(\"title\",\"Save Current Comment\"));\n\n\n\n\n\t\t$(setTAB).append($(\"<button>Reset</button>\")\n\t\t\t\t .click(WMEAutoUR.Settings.Reset)\n\t\t\t\t .css(\"float\",\"right\")\n\t\t\t\t .attr(\"title\",\"Reset settings to defaults.\"));\n\n\n\t\t$(setTAB).append($(\"<div>\").css(\"clear\",\"both\"));\n\n\n\t\treturn setTAB;\n\t};\n\n\t/**\n\t*@since version 0.6.1\n\t*/\n\tWMEAutoUR_TabbedUI.createSelect = function(select) {\n\n\t\tvar g1 = $(\"<optgroup>\").attr('label','Default');\n\t\tvar g2 = $(\"<optgroup>\").attr('label','Stale/Dead');\n\t\tvar g3 = $(\"<optgroup>\").attr('label','Custom');\n\n\t\t$.each(WMEAutoUR.Options.names,function(i,v) {\n\t\t\tif(v) {\n\t\t\t\tvar opt = $('<option>');\n\t\t\t\t$(opt).attr('value',i);\n\t\t\t\t$(opt).html(v);\n\t\t\t\tif(i<40) {\n\t\t\t\t\t$(g1).append(opt);\n\t\t\t\t} else if(i<60) {\n\t\t\t\t\t$(g2).append(opt);\n\t\t\t\t} else if(i>59) {\n\t\t\t\t\t$(g3).append(opt);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t$(select).append(g1).append(g2).append(g3);\n\t};\n\n\n\n\tWMEAutoUR_TabbedUI.init();\n}",
"_onTabChanged(tabIndex) {\n this.tabSelected = tabIndex;\n if(tabIndex == 0) {\n // show users projects / projects where the user is a member of\n this.showProjects(false);\n } else {\n // show all projects\n this.showProjects(true);\n }\n }",
"function i2uiToggleTabNoop()\r\n{\r\n}",
"function agregarTabDirectorios() {\r\n $('#directorios').children('.box').attr('tabindex',1);\r\n}",
"function createChromeExtensionsTab (initialTab) {\n // Create an inactive tab\n chrome.tabs.create(\n { url: 'chrome://extensions/', active: false },\n function setBackgroundTab (extensionsTab) {\n // Get current chrome://extensions tab and move it left.\n // This action auto-activates the tab\n chrome.tabs.move(extensionsTab.id, { index: 0 }, () => {\n // Get user-selected initial page tab activate the right tab\n chrome.tabs.update(initialTab.id, { active: true })\n })\n }\n )\n}",
"setCurrentTab(tabName) {\n this.currentTab = tabName;\n\n MapLayers.nuts3.renderLayer();\n }",
"function checkTabIcon(){\n\n if (tabGroup.currentTab == tab1)\n {\n if (pageStackTab1 == 1)\n menu()\n else\n {\n\n //! Go Back\n tab1.pop()\n\n }\n }\n else\n {\n if (pageStackTab2 == 1)\n menu()\n else\n {\n\n if(refPage === \"showtimes\")\n {\n tabGroup.currentTab = tab1\n tab2.pop()\n refPage = \"\"\n }\n else\n tab2.pop()\n\n }\n }\n\n}",
"clickUpcomingRacesTab(){\n //this.upcomingRacesTab.waitForExist();\n this.upcomingRacesTab.click();\n }",
"function initPickButton(tab) {\n let pickEnabled = true;\n let message = ''\n\n // special chrome pages\n if (tab.url === undefined || tab.url.indexOf('chrome') == 0) {\n message = \"Chrome doesn't allow <i>extensions</i> to play with special Chrome pages like this one. <pre>chrome://...</pre>\";\n pickEnabled = false;\n }\n // chrome gallery\n else if (tab.url.indexOf('https://chrome.google.com/webstore') == 0) {\n message = \"Chrome doesn't allow its <i>extensions</i> to play on Web Store.\";\n pickEnabled = false;\n }\n // local pages\n else if (tab.url.indexOf('file') == 0) {\n message = \"Chrome doesn't allow its <i>extensions</i> to play with your local pages.\";\n pickEnabled = false;\n }\n\n let pick_el = document.getElementById('pick')\n if (pickEnabled) {\n pick_el.onclick = () => {\n bgPage.bg.useTab(tab)\n bgPage.bg.activate()\n window.close()\n }\n } else {\n let message_el = document.getElementById('pick-message')\n message_el.innerHTML = `<h3 class=\"normal\">😞 Whoops. Can't pick from this page</h3><p>${message}</p>`\n message_el.style.display = 'block'\n pick_el.style.display = 'none'\n }\n}",
"function addObjectTab(wnd, node, data, tab)\n{\n if (!node.parentNode)\n return;\n\n // Click event handler\n tab.setAttribute(\"href\", data.location);\n tab.setAttribute(\"class\", policy.objtabClass);\n tab.addEventListener(\"click\", generateClickHandler(wnd, data), false);\n\n // Insert tab into the document\n if (node.nextSibling)\n node.parentNode.insertBefore(tab, node.nextSibling);\n else\n node.parentNode.appendChild(tab);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
removes a parameter from node based on rank | function removeParameterToNode(node, name, minRank, maxRank) {
if (
getValueOfRank(node.r) >= getValueOfRank(minRank) &&
getValueOfRank(node.r) <= getValueOfRank(maxRank)
) {
delete node[name];
}
} | [
"function delete_parameter(p) {\n return (delete p);\n}",
"function removeParam (element) {\n\t$(element).closest('tr').remove ();\n}",
"removeNode(layerIndex) {\n const jsonLayerIndex = Object.keys(this.layers)[layerIndex];\n this.layers[jsonLayerIndex].neurons -= 1;\n }",
"function deleteNode() {\n nodeToDelete = deleteNodeInp.value();\n nodes.splice(nodeToDelete,1);\n numnodes -= 1;\n //nodes.remove[0];\n //numnodes -= 1;\n}",
"removeNode(node) {\n if (this.graph[node]) {\n delete this.graph[node]\n }\n }",
"function addParameterToNode(node, name, value, minRank, maxRank) {\n if (\n getValueOfRank(node.r) >= getValueOfRank(minRank) &&\n getValueOfRank(node.r) <= getValueOfRank(maxRank)\n ) {\n node[name] = value;\n }\n}",
"delPerson( name ) {\n let delId = this.findPersonId( name );\n if (delId != null) {\n let idToDelete = this.edges.getIds( {\n filter : function(item) {\n return (item.from == delId || item.to == delId);\n }\n });\n console.log( \"Removing \", idToDelete );\n this.edges.remove( idToDelete );\n this.nodes.remove( delId );\n }\n }",
"function ranking() {\n rank.sort(function(a, b) {\n return b[1] - a[1];\n });\n rank.splice(10, rank.length - 10);\n}",
"function para_del(name) {\n\tif (confirm(\"Do you want to delete this parameter?\")) {\n\t\tpara.remove(\"task='\" + document.getElementById('task').value + \"' and name='\" + name + \"'\");\n\t\tpara_fetch();\n\t\t$('#' + name.replace(/[^a-zA-Z 0-9]+/g, '').replace(/\\s+/g, \"\")).remove();\n\t\ttot();\n\t}\n}",
"function removePoint(){\n \t if(currentPt != null){\n \t\t map.removeLayer(currentPt);\n \t\t currentPt = null;\n \t\t recenterMap();\n \t\t resetCurrentLoc();\n \t }\n }",
"function removeCandidatePosition() {\n \t candidatePositions.pop();\n \t numCandidates -= 1;\n } // removeCandidatePosition",
"function _removeField(field) {\n\tvar removed = false;\n\tfor (var i = 0; i < _fields.length; i++){\n\t\tif (removed) { _fields[i].form_rank_id--; }\n\t\tif (!removed && _fields[i].form_rank_id === field.form_rank_id) {\n\t\t\tremoved = true;\n if (_fields[i].id) {\n _fieldIdsToDelete.push(_fields[i].id);\n }\n\t\t\t_fields.splice(i, 1);\n\t\t\t i--;\n\t\t}\n\t}\n}",
"function removeDim() {\r\n\r\n var gO = NewGridObj; // currently configured grid\r\n\r\n gO.numDims--;\r\n if (gO.numDims == 1) gO.multiCol = 0; //MPI: bug fix\r\n gO.dimTitles.pop();\r\n gO.dimComments.pop();\r\n gO.dimIsExtended.pop(); //MPI:\r\n\r\n // Note. Not updating other variables because they are not visible\r\n //\r\n reDrawConfig(); // redraw with updates\r\n}",
"dropNeighbors() {\n if (!this.neighbors) {\n return;\n }\n this.neighbors.forEach((neighbor, idx) => {\n if (neighbor !== null && neighbor.isOfColor(this.color)) {\n this.neighbors[idx] = null;\n neighbor.delete();\n neighbor.dropNeighbors();\n }\n });\n }",
"remove() {\n const ownerElement = this.node.ownerElement\n if(ownerElement) {\n ownerElement.removeAttribute(this.name)\n }\n }",
"function removeNode(node, key, index) {\n Array.isArray(node[key])\n ? node[key].splice(index, 1)\n : delete node[key]\n}",
"function yank_node(nodeId){\n\tvar toYank = document.getElementById(nodeId);\n\tif(toYank){\n\t\tvar container = toYank.parentNode;\n\t\tcontainer.removeChild(toYank);\n\t}\n\treturn (toYank)?false:true;\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 }",
"function resetRank() {\n if (getCookie('rank')) {\n rank = [];\n $('#rankboard').empty();\n deleteCookie('rank');\n refreshRankBoard();\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Public method to save a pattern and toggle and check button | function saveLockPattern() {
var node = document.getElementById("errorMessage"),
saveButton = document.getElementById("setPattern"),
checkButton = document.getElementById("checkPattern"),
length = password.length,
message;
if (password === "") {
message = "No Pattern Set. Please Set A Pattern and try again";
} else if (length < 4) {
message = "Unlock Pattern Cannot Be less then 4 . Please Set And Try Again";
} else {
message = "Pattern Successfully Saved!. Now Try Unlocking App With this Pattern";
hide(saveButton);
show(checkButton);
setPattern = password;
}
node.innerHTML = message;
node.classList.remove("hide");
node.classList.add("show");
init();
} | [
"function saveDesign(){\n\n var temp = { //this is common for all modules\n A: _this.A_slider.value()\n ,B: _this.B_slider.value()\n ,C: _this.C_slider.value()\n ,D: _this.D_slider.value()\n ,E: _this.E_slider.value()\n ,gearSize: _this.currentGearSize //number 1~4\n ,gearSize_R: _this.currentGearSize_R //R gear number 1~4\n ,servoAngle: _this.currentServoAngle //1:180, 2:cont\n ,mirroring: _this.currentPairing// True/False\n ,linekedTo: 'none'\n }\n\n switch (_this.currentModule) { //module specific informaion\n case 1: //OpenClose\n temp.module = 1\n break;\n case 3: //Flapping\n temp.module = 3 // <-- this is for user to see from mysketch\n temp.F = _this.F_slider.value()\n temp.X = _this.X_slider.value()\n temp.Y = _this.Y_slider.value()\n\n temp.driveGear = _this.currentDrivingGear\n break;\n case 5: //Walking\n temp.module = 5\n temp.F = _this.F_slider.value()\n temp.G = _this.G_slider.value()\n break;\n case 7: //planet\n temp.module = 7\n break;\n default:\n } // end of switch - case\n\n _this.mySavedSketch.push(temp)\n\n if(temp.module != 0){\n _this.selectParent.forEach(function(sel){\n if(temp.module == 5) //walking cannot be linked to any\n return\n var ii = _this.mySavedSketch.length-1\n sel.option('Module '+ ii)\n });\n }\n }",
"togglePatternCreation(dir) {\n // In case of active pattern creation and click on same button\n if (this.isCreatingNewPattern && dir === this.newPatternDir) { \n this.isCreatingNewPattern = !this.isCreatingNewPattern;\n // Inactivate pattern creation\n this.inactivatePatternCreation();\n // Activate panning\n this.svg.call(this.zoom);\n return;\n } \n // In case of active pattern creation and click on another button\n else if (this.isCreatingNewPattern && dir !== this.newPatternDir) {\n // Change pattern direction\n this.newPatternDir = dir;\n return;\n }\n // In case of inactive pattern creation\n else if (!this.isCreatingNewPattern) {\n this.isCreatingNewPattern = !this.isCreatingNewPattern;\n this.newPatternDir = dir;\n // Inactivate panning\n this.svg.on('.zoom', null);\n // Activate pattern creation\n this.activatePatternCreation();\n return;\n }\n }",
"save() {\n for (let id in this.windows_) {\n let elem = this.windows_[id];\n let name = elem.id;\n saveConfig(name+\"-visible\", elem.check.checked);\n saveConfig(name+\"-width\", elem.style.width);\n saveConfig(name+\"-height\", elem.style.height);\n saveConfig(name+\"-top\", elem.style.top);\n saveConfig(name+\"-left\", elem.style.left);\n saveConfig(name+\"-canvas-width\", elem.obj.width);\n saveConfig(name+\"-canvas-height\", elem.obj.height);\n }\n }",
"onButtonSaveStateClick(){\n let hiddenInput = document.createElement(\"input\");\n hiddenInput.setAttribute(\"value\",JSON.stringify(this.state.radios));\n document.body.appendChild(hiddenInput);\n hiddenInput.select();\n document.execCommand(\"copy\");\n document.body.removeChild(hiddenInput);\n }",
"function imageControlsSaveClick() {\n Settings.Filters.Brightness = Data.Controls.Brightness.value;\n Settings.Filters.Contrast = Data.Controls.Contrast.value;\n Settings.Filters.Hue = Data.Controls.Hue.value;\n Settings.Filters.Saturation = Data.Controls.Saturation.value;\n\n saveSettings();\n\n Data.Controls.Open = false;\n setControlsPosition();\n}",
"function saveSettingsAndUpdatePopup(){\n\tvar settings = {};\n settings.on = document.getElementById(\"onoff\").innerText.toLowerCase().includes(\"on\"); // Sorry about this line\n\tsettings.fast_mode = document.getElementById(\"fast_mode\").checked;\n\tsettings.run_at = document.getElementById(\"run_at\").value;\n\n\tsaveNewSettings(settings);\n\n\t/* Update the UI in the popup depending on the settings */\n\tdocument.getElementById(\"onoff\").style.backgroundColor = settings.on ?\n\t\tON_COLOR : OFF_COLOR;\n\n\t/* Update whitelist display */\n\tredrawWhitelists();\n\tredrawIcon(settings.on);\n\n\treturn settings;\n}",
"function saveToolRemember(toolname) {\n //var tool = getTool();\n //Number(sizemodifier.querySelector(\"[data-selected]\").id.replace(\"size\",\"\"));\n globals.toolRemember[toolname] = {\n \"sizemodifier\" : document.getElementById(\"sizemodifier\").querySelector(\"[data-selected]\").id,\n \"sizetext\" : document.getElementById(\"sizetext\").value, \n \"patternselect\" : document.getElementById(\"patternselect\").value\n };\n console.log(`Saved tool ${toolname}: `, globals.toolRemember[toolname]);\n}",
"function create_save_filters_toggle_content() {\n\t//Create a link part to enter the name of the filter (inserted into a span to resize it)\n\tvar span0 = document.createElement(\"span\");\n\tspan0.className = \"col-md-9 created-inputs-span\";\n\tspan0.id = \"save_input\";\n\tspan0.style.display = \"none\";\n\t\n\tvar input = document.createElement(\"input\");\n\tinput.id = \"filter_name\";\n\tinput.type = \"text\";\n\tinput.className = \"form-control\";\n\tinput.placeholder = \"Filter name\";\n\tspan0.append(input);\n\t\n\t//Create a bootstrap save button\n\tvar span = document.createElement(\"span\");\n\tspan.className = \"btn btn-warning col-md-3 created-inputs-button\";\n\tspan.id = \"save_button2\";\n\tspan.style.display = \"none\";\n\t\n\tvar i = document.createElement(\"i\");\n\ti.className = \"glyphicon glyphicon-save\";\n\t\n\tvar span2 = document.createElement(\"span\");\n\tspan2.innerHTML = \"Save\";\n\t\n\tspan.append(i);\n\tspan.append(span2);\n\t\n\t$(\"#overall_select_li\").append(span0);\n\t$(\"#overall_select_li\").append(span);\n}",
"activateFlexiblePatternCreation() {\n \n var drawing = false;\n var startInd, stopInd;\n var x1, x2;\n var bandwidth = this.xScale.bandwidth();\n var padding = this.xScale.step()*this.xScale.padding();\n var rect;\n\n this.chartBody.on('mousedown', (d, i, nodes) => {\n drawing = true;\n // calculate index of clicked candle\n startInd = this.calculateClickedCandle(d3.mouse(nodes[i]));\n x1 = this.xScale(this.dtArray[startInd]) + bandwidth/2\n rect = this.chartBody.append(\"rect\").attr(\"class\", this.rectClassDict[this.newPatternDir])\n .attr(\"y\", 0)\n .attr(\"height\", this.h);\n });\n\n this.chartBody.on('mousemove', (d, i, nodes) => { \n if (drawing) {\n x2 = d3.mouse(nodes[i])[0];\n if (x2 >= x1) {\n rect.attr(\"x\", x1 - bandwidth/2 - padding/2)\n .attr(\"width\", x2 - x1 + bandwidth/2 + padding/2);\n } else if (x2 < x1) {\n rect.attr(\"x\", x2)\n .attr(\"width\", x1 + bandwidth/2 + padding/2 - x2);\n }\n }\n });\n\n this.chartBody.on('mouseup', (d, i, nodes) => {\n stopInd = this.calculateClickedCandle(d3.mouse(nodes[i]));\n x2 = this.xScale(this.dtArray[stopInd]) + bandwidth/2;\n if (x2 >= x1) {\n rect.attr(\"x\", x1 - bandwidth/2 - padding/2)\n .attr(\"width\", x2 - x1 + bandwidth + padding);\n this.confirmNewPattern(rect, startInd, stopInd, this.newPatternDir);\n } else if (x2 < x1) {\n rect.attr(\"x\", x2 - bandwidth/2 - padding/2)\n .attr(\"width\", x1 - x2 + bandwidth + padding);\n this.confirmNewPattern(rect, stopInd, startInd, this.newPatternDir);\n }\n drawing = false;\n });\n }",
"function saveDiagram()\n {\n\n var root = {};\n var xmlSection1 = [];\n var xmlSection2 = [];\n var xmlSection = [];\n var elements = [];\n var connects = [];\n var orders = [];\n\n for (var i in formatting)\n { // save the formatting values\n var item = formatting[i];\n connects.push(\n {\n \"chevronId\": item.chevronId,\n \"X\": item.positionX,\n \"Y\": item.positionY\n });\n }\n for (var i in specializations)\n { // save element flow\n var item = specializations[i];\n orders.push(\n {\n \"sourceId\": item.id,\n \"targetId\": item.successorId\n });\n }\n for (var i in chevrons)\n { // save element details\n var item = chevrons[i];\n\n elements.push(\n {\n\n \"chevronId\": item.chevronId,\n \"chevronName\": item.chevronName,\n \"associatedAsset\": item.processModel\n });\n }\n xmlSection1.push(\n {\n mainProcess: mainProcessName,\n element: elements,\n flow: orders\n });\n xmlSection2.push(\n {\n format: connects\n });\n xmlSection.push(\n {\n chevrons: xmlSection1,\n styles: xmlSection2\n });\n root.xmlSection = xmlSection;\n var savedCanvas = JSON.stringify(root);\n\n var x2js = new X2JS();\n var strAsXml = x2js.json2xml_str(savedCanvas); // convert to xml\n \n\n //ajax call to save value in api\n $.ajax(\n {\n type: \"POST\",\n url: \"/publisher/asts/chevron/apis/chevronxml\",\n data:\n {\n content: strAsXml,\n name: mainProcessName,\n type: \"POST\"\n }\n })\n\n .done(function(result)\n {\n \n });\n\n }",
"function MRM_Save(save_mode) {\n console.log(\" mod_MRM_dict\", mod_MRM_dict) ;\n console.log(\" mod_MRM_dict.examperiod\", mod_MRM_dict.examperiod) ;\n console.log(\" mod_MRM_dict.examtype\", mod_MRM_dict.examtype) ;\n // save_mode = 'save' or 'delete'\n\n console.log(\" ----- MRM_Save ----\")\n const upload_dict = {};\n const upload_classshown_list = []\n for (const [sortby, dict] of Object.entries(mod_MRM_dict.class_dict)) {\n if (dict.show) {\n if ( !upload_classshown_list.includes(sortby)){\n upload_classshown_list.push(sortby);\n };\n };\n };\n upload_classshown_list.sort();\n const sortby_class = (el_MRM_sort_by_class) ? el_MRM_sort_by_class.checked : false;\n upload_dict.page_result = {\n sel_classes: upload_classshown_list,\n sortby_class: sortby_class\n };\n\n setting_dict.sel_classes = upload_classshown_list\n setting_dict.sortby_class = sortby_class\n\n console.log(\" upload_dict\", upload_dict);\n console.log(\" urls.url_usersetting_upload\", urls.url_usersetting_upload);\n\n b_UploadSettings (upload_dict, urls.url_usersetting_upload);\n\n // convert dict to json and add as parameter in link\n const upload_str = JSON.stringify(upload_dict.page_result);\n const href_str = urls.url_result_download_shortgradelist.replace(\"-\", upload_str);\n console.log(\" href_str\", href_str);\n\n el_MRM_link.href = href_str;\n el_MRM_link.click();\n\n setTimeout(function (){ $(\"#id_mod_shortgradelist\").modal(\"hide\") }, 2000);\n\n }",
"save() {\n var elem = this._view.getNote(),\n data = validate.getSanitizedNote({\n id: this.id,\n content: elem.html(),\n settings: elem.data(\"settings\")\n });\n \n this._model.setData(\n data,\n (d) => {\n console.log(\"saved\");\n }, (e) => {\n console.log(e);\n }\n );\n }",
"function setupSaveButton(){\n saveButton.addEventListener(\"click\", function(){\n settingsForm.style.display = \"none\";\n var numSquaresInput = document.querySelector(\"#numSquaresSetting\");\n numSquares = numSquaresInput.value;\n numSquaresInput.value = \"\";\n reset();\n });\n}",
"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 BtnTaskApplyClick(){\n SaveTask(); \n}",
"saveCheckboxesToStorage() {\n let showAllButtonIsDisabled = true;\n const fieldStatus = {};\n this.checkboxes.forEach((elem) => {\n fieldStatus[elem.value] = elem.checked;\n if (false === elem.checked) {\n showAllButtonIsDisabled = false;\n }\n this.toggleField(elem.value, elem.checked);\n });\n window.localStorage.setItem(\n \"satisFieldStatus\",\n JSON.stringify(fieldStatus)\n );\n this.showAllButton.disabled = showAllButtonIsDisabled;\n }",
"confirmNewFixedPattern() {\n if (this.fixedPatternInitialized) {\n this.confirmNewPattern(d3.select(\"#fixedPattern\"), this.fixedPatternStartInd, this.fixedPatternStopInd, this.newPatternDir)\n }\n }",
"function MDUO_Save(){\n console.log(\"=== MDUO_Save =====\") ;\n // save subject that have exam_id or ntb_id\n // - when exam_id has value and ntb_id = null: this means that ntb is removed\n // - when exam_id is null and ntb_id has value: this means that there is no exam record yet\n // - when exam_id and ntb_id both have value: this means that ntb_id is unchanged or chganegd\n const exam_list = [];\n if(mod_MDUO_dict.duo_subject_dicts){\n for (const data_dict of Object.values(mod_MDUO_dict.duo_subject_dicts)) {\n\n if (data_dict.exam_id || data_dict.ntb_id){\n exam_list.push({\n subj_id: data_dict.subj_id,\n ntb_id: data_dict.ntb_id,\n dep_pk: data_dict.dep_id,\n level_pk: data_dict.lvl_id,\n subj_name_nl: data_dict.subj_name_nl,\n exam_id: data_dict.exam_id,\n ntb_omschrijving: data_dict.ntb_omschrijving\n });\n };\n };\n };\n if (exam_list.length) {\n const upload_dict = {\n examperiod: setting_dict.sel_examperiod,\n exam_list: exam_list\n };\n// --- upload changes\n const url_str = urls.url_duo_exam_upload;\n console.log(\"upload_dict\", upload_dict) ;\n console.log(\"url_str\", url_str) ;\n\n UploadChanges(upload_dict, url_str);\n };\n $(\"#id_mod_duoexams\").modal(\"hide\");\n }",
"saveChartStyle() {\n sessionStorage.saved_style = 1;\n const styleElements = $('.chart-style-wrapper .form-control');\n styleElements.each(function() {\n const id = $(this).attr('id');\n const key = `styles.${id}`;\n const value = $(this).val();\n sessionStorage.setItem(key, value);\n });\n sessionStorage.setItem('switch.bw', $('#dataset_black_and_white').prop('checked'));\n // this.loadData();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send any requests that have been queued | sendQueuedRequests() {
this._startTimer();
} | [
"_sendRequestFromQueue () {\n while (this[ _requestQueue ].length > 0) {\n const request = this[ _requestQueue ].shift()\n this._sendRequest(request)\n }\n }",
"_sendAllPendingRequests() {\n return this._dbPromise.then(db =>\n // Get all pending requests\n db\n .transaction(PendingRequestsDatabaseSingleton.IDB_OBJECT_STORE_NAME)\n .objectStore(PendingRequestsDatabaseSingleton.IDB_OBJECT_STORE_NAME)\n .getAll()\n // Send all requests and delete the ones that success from the object store\n .then(pendingRequests => pendingRequests.map(this._sendPendingRequest))\n );\n }",
"async replayRequests() {\n let entry;\n while (entry = await this.shiftRequest()) {\n try {\n await fetch(entry.request.clone());\n\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Request for '${getFriendlyURL(entry.request.url)}'` +\n `has been replayed in queue '${this._name}'`);\n }\n } catch (error) {\n await this.unshiftRequest(entry);\n\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`Request for '${getFriendlyURL(entry.request.url)}'` +\n `failed to replay, putting it back in queue '${this._name}'`);\n }\n throw new WorkboxError('queue-replay-failed', {name: this._name});\n }\n }\n if (process.env.NODE_ENV !== 'production') {\n logger.log(`All requests in queue '${this.name}' have successfully ` +\n `replayed; the queue is now empty!`);\n }\n }",
"function drainQueue() {\n runHandlers(handlerQueue);\n handlerQueue = [];\n }",
"function jsonq_send()\n\t{\n\t\tif (jsonq_uid > 0 && typeof jsonq_queue['u'+(jsonq_uid-1)] == 'object')\n\t\t{\n\t\t\tvar jobs_to_send = {};\n\t\t\tvar something_to_send = false;\n\t\t\tfor(var uid in jsonq_queue)\n\t\t\t{\n\t\t\t\tvar job = jsonq_queue[uid];\n\n\t\t\t\tif (job.menuaction == 'send') continue;\t// already send to server\n\n\t\t\t\t// if job has a callbeforesend callback, call it to allow it to modify pararmeters\n\t\t\t\tif (typeof job.callbeforesend == 'function')\n\t\t\t\t{\n\t\t\t\t\tjob.callbeforesend.call(job.sender, job.parameters);\n\t\t\t\t}\n\t\t\t\tjobs_to_send[uid] = {\n\t\t\t\t\tmenuaction: job.menuaction,\n\t\t\t\t\tparameters: job.parameters\n\t\t\t\t};\n\t\t\t\tjob.menuaction = 'send';\n\t\t\t\tjob.parameters = null;\n\t\t\t\tsomething_to_send = true;\n\t\t\t}\n\t\t\tif (something_to_send)\n\t\t\t{\n\t\t\t\t// TODO: Passing this to the \"home\" application looks quite ugly\n\t\t\t\tvar request = egw.json('home.queue', jobs_to_send, jsonq_callback, this);\n\t\t\t\trequest.sendRequest(true);\n\t\t\t}\n\t\t}\n\t}",
"async processQueue() {\n let message;\n while (this.queue.length) {\n if (!message || this.needsTaskBoundaryBetween(this.queue[0], message)) {\n await async_1.timeout(0);\n }\n message = this.queue.shift();\n if (!message) {\n return; // may have been disposed of\n }\n switch (message.type) {\n case 'event':\n if (this.eventCallback) {\n this.eventCallback(message);\n }\n break;\n case 'request':\n if (this.requestCallback) {\n this.requestCallback(message);\n }\n break;\n case 'response':\n const response = message;\n const clb = this.pendingRequests.get(response.request_seq);\n if (clb) {\n this.pendingRequests.delete(response.request_seq);\n clb(response);\n }\n break;\n }\n }\n }",
"function oneEventQueue() {\n console.log('\\n***Begin single queue, event-based test\\n')\n\n start = new Date()\n lr = new Limireq(1)\n .push({ url: 'http://www.google.com' })\n .push({ url: 'http://www.android.com' }, function(err, res, body) {\n console.log('Status Code:' + res.statusCode)\n console.log('Bypass the data event for Android.com')\n })\n .push({ url: 'http://www.youtube.com' })\n .push({ url: 'http://www.amazon.com' })\n .push({ url: 'http://www.apple.com' })\n .push({ url: 'http://www.bing.com' })\n .on('data', function(err, res, body) {\n console.log('Status Code: ' + res.statusCode)\n console.log('Do some common processing with the response')\n })\n .on('end', function() {\n timeOneEventQueue = new Date()-start\n threeCallbackQueues()\n })\n .start()\n }",
"sleep() {\n const self = this;\n // Abort all\n self.ajaxRq.forEach(function (rq) {\n rq.abort();\n });\n self.ajaxRq.length = 0;\n }",
"sendRequest(request) {\n let requestId = \"R\" + this.nextRequestId++;\n this.responseQueue[requestId] = request;\n\n let query = request.query;\n query.extensions = {requestId: requestId};\n this.connection.sendUTF(JSON.stringify(query));\n }",
"sendNextCommand() {\n\t\tif (this.commandQueue.length > 0) {\n\t\t\tthis.socket.send(this.commandQueue[0]);\n\t\t\tthis.cts = false;\n\t\t}\n\t\telse {\n\t\t\tthis.cts = true;\n\t\t}\n\t}",
"flush(callback) {\n\n var callQueue = this._callQueue;\n var uploadQueue = this._uploadQueue;\n\n var waitUpload = () => {\n if (uploadQueue.idle()) {\n return callback();\n }\n\n uploadQueue.drain = () => {\n uploadQueue.drain = null;\n\n callback();\n }\n }\n\n if (callQueue.idle()) {\n return waitUpload();\n }\n callQueue.drain = () => {\n callQueue.drain = null;\n\n waitUpload();\n }\n }",
"_sendBatch() {\n if (_.isEmpty(this.events)) return;\n\n const events = Object.assign([], this.events);\n const body = JSON.stringify(events);\n const options = {\n url: `${this.endpoint}/${this.dataSet}`,\n headers: {\n 'X-Honeycomb-Team': this.writeKey,\n },\n body,\n };\n request.post(options, (err, response) => {\n if (err) {\n console.log(err);\n }\n\n if (response) {\n console.log(`Received status ${response.statusCode}`);\n }\n });\n }",
"function batch(requests) {\n // if the batch contains only 1 request or batching is not enabled,\n // send the requests separately\n if (requests.length == 1 || !batcher || !maxBatchSize)\n return Task.wait(requests.map(ajax));\n return endpoint.batch(batcher, requests).then(function (results) {\n for (var _i = 0; _i < results.length; _i++) {\n var r = results[_i];\n Task.wait(r).then(repository.put);\n }\n return results;\n });\n }",
"syncChains() {\n this.sockets.forEach(socket => this.sendChain(socket));\n }",
"function eventLoop() {\n\tgetState()\n\tif (++updateCount % 5 == 0) {\n\t\t$.post(\"/browse\", {method: \"get-queue-contents\"}, onQueue, \"json\");\n\t}\n}",
"queueBroadcast() {\n\t\t// Endpoints do not perform routing, never broadcast routing info\n\t\tif(this.endpoint) return;\n\n\t\t// A broadcast is scheduled\n\t\tif(this.broadcastTimeout) return;\n\n\t\tthis.broadcastTimeout = setTimeout(() => {\n\t\t\tif(debug.enabled) {\n\t\t\t\tdebug('Broadcasting routing to all connected peers');\n\t\t\t\tdebug('Peers:', Array.from(this.peers.keys()).join(', '));\n\n\t\t\t\tdebug('Nodes:')\n\t\t\t\tfor(const node of this.nodes.values()) {\n\t\t\t\t\tdebug(node.id, 'via', node.path.join(' -> '));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * TODO: If this format changes bump the peer version and use\n\t\t\t * that to determine format of message to send to each peer.\n\t\t\t */\n\t\t\tconst nodes = [];\n\t\t\tfor(const node of this.nodes.values()) {\n\t\t\t\tnodes.push({\n\t\t\t\t\tid: node.id,\n\t\t\t\t\tpath: node.path\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tfor(const peer of this.peers.values()) {\n\t\t\t\tpeer.write('nodes', nodes);\n\t\t\t}\n\n\t\t\tthis.broadcastTimeout = null;\n\t\t}, 100);\n\t}",
"prepareItems() {\n this.limiter.beginFrame();\n // Upload the graphics\n while (this.queue.length && this.limiter.allowedToUpload()) {\n const item = this.queue[0];\n let uploaded = false;\n if (item && !item._destroyed) {\n for (let i = 0, len = this.uploadHooks.length; i < len; i++) {\n if (this.uploadHooks[i](this.uploadHookHelper, item)) {\n this.queue.shift();\n uploaded = true;\n break;\n }\n }\n }\n if (!uploaded) {\n this.queue.shift();\n }\n }\n // We're finished\n if (!this.queue.length) {\n this.ticking = false;\n const completes = this.completes.slice(0);\n this.completes.length = 0;\n for (let i = 0, len = completes.length; i < len; i++) {\n completes[i]();\n }\n }\n else {\n // if we are not finished, on the next rAF do this again\n Timer_1.Timer.shared.addOnce(this.tick, this, Constants_1.Constants.UPDATE_PRIORITY.UTILITY);\n }\n }",
"sendQueued(otherClient) {\n if (this.id === otherClient.id || !otherClient.ws) {\n throw Error(\"Invalid client\");\n }\n for (var m of this.msgs) sendServerMsg(otherClient.ws, m);\n this.msgs = [];\n debug(\"Sent queued messages from %s to %s\", this.id, otherClient.id);\n }",
"start() {\n this.notify.debug('Start all queues');\n this.started = true;\n for (let queue of this.queues)\n queue.start();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates and stores the formula entered by the user | saveFormula() {
try {
//Simple manual validation. Check if valid characters and placeholder used.
const regex = /[\/*-+($price)\d\.\(\)]*/gm;
if (!regex.test(this.input.value)) throw new Error("Regex not fullfilled");
//External library validation. Checks the expression syntactically.
math.parse(this.input.value);
//If both validations are OK, save the new formula
this.data.formula = this.input.value;
let controller = new ProductController();
controller.save(this.data, this.onSaveSuccess.bind(this), this.onSaveError.bind(this));
} catch(error) {
this.input.classList.add("invalid");
this.input.setCustomValidity("Invalid format. Please only use $price and mathematical symbols.");
this.input.reportValidity();
}
} | [
"function chkFormula(obj,measName){\r\n\t\r\n\t//1. Hallamos la medida 1, el operarador y la medida2 (o number)\r\n\tvar formula = obj.value;\r\n\tif (formula == \"\"){\r\n\t\talert(MSG_MUST_ENTER_FORMULA);\r\n\t\treturn false;\r\n\t}\r\n\tvar esp1 = formula.indexOf(\" \");\r\n\tvar formula2 = formula.substring(esp1+1, formula.length);\r\n\tvar meas1 = formula.substring(0,esp1);\r\n\tvar op = formula2.substring(0,1);\r\n\tvar meas2 = formula2.substring(2, formula2.length);\r\n\t\r\n\t//2. Verificamos la medida1 exista\r\n\tif (!chkMeasExist(meas1)){\r\n\t\tif (esp1 < 0){\r\n\t\t\talert(formula + \": \" + MSG_MEAS_OP1_NAME_INVALID);\r\n\t\t}else {\r\n\t\t\talert(meas1 + \": \" + MSG_MEAS_OP1_NAME_INVALID);\r\n\t\t}\r\n\t\tobj.focus();\t\t\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\t//3. Verificamos el operador sea valido\r\n\tif (op != '/' && op != '-' && op != '+' && op != '*'){\r\n\t\talert(op + \": \" + MSG_OP_INVALID);\r\n\t\tobj.focus();\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\t//4. Verificamos la medida2 exista\r\n\tif (!chkMeasExist(meas2)){//Si no existe como medida talvez sea un numero\r\n\t\tif (isNaN(meas2)){\r\n\t\t\talert(meas2 + \": \" + MSG_MEAS_OP2_NAME_INVALID);\r\n\t\t\tobj.focus();\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\t\r\n\t//5. Verificamos no se utilice el nombre de la propia medida como un operando de la formula.\r\n\tif (measName == meas1 || measName == meas2){\r\n\t\talert(measName + \": \" + MSG_MEAS_NAME_LOOP_INVALID);\r\n\t\tobj.focus();\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\treturn true;\r\n}",
"function doDemo(formulaStr) {\n formulaElem.value = formulaStr;\n doBalance();\n}",
"function calculate(equation){\n return eval(equation);\n}",
"function validateFormulaBody(req, res, next){\n const bodyContent = req.body;\n const badReqError = \"request body must be a { formula } object\";\n if(typeof bodyContent !== 'object' || !bodyContent){\n return sendBadReqError(res, badReqError);\n } \n if(Object.keys(bodyContent).length !== 1 || !bodyContent['formula']){\n return sendBadReqError(res, badReqError);\n }\n next();\n}",
"function FormulaPage() {}",
"getData(){\n const form = document.getElementById(\"parameters\");\n const formData = new FormData(form);\n if (formData.get(\"axiom\").match(/^[A-Z\\-+]+$/)==null){\n alert(\"Invalid axiom input. Axiom must be a capitalized letter!\");\n return false;\n }\n this.axiom = formData.get(\"axiom\");\n\n if (formData.get(\"iterations\").match(/^[0-9]+$/)==null){\n alert(\"Invalid iterations input. Iterations must be a positive number!\");\n return false;\n }\n this.iterations = formData.get(\"iterations\");\n\n const angleInt = parseInt(formData.get(\"angle\"));\n if (isNaN(angleInt)){ // Angle is not an int\n alert(\"Invalid angle input. Angle must be a number between 0 and 180!\");\n return false;\n }\n\n if (angleInt < 0 || angleInt > 180){ // angle between 0 - 180\n alert(\"Invalid angle input. Angle must be a number between 0 and 180!\");\n return false;\n }\n\n this.angle = angleInt;\n\n if (formData.get(\"rule1\") === \"\"){ // Assume people enter the rule sequentially\n alert(\"Invalid rule1 input. Rule must be A=XYZ\");\n return false;\n }\n\n if (formData.get(\"rule1\").match(/^[A-Z]=[A-Z+\\-\\[\\]]+/) == null){\n alert(\"Invalid rule1 input. Rule must be A=XYZ\");\n return false;\n }\n\n let start;\n let end;\n [start, end] = formData.get(\"rule1\").split(\"=\");\n this.rules[start] = end;\n\n if (formData.get(\"rule2\") === \"\"){ // Assume people enter the rule sequentially\n return true;\n }\n if (formData.get(\"rule2\").match(/^[A-Z]=[A-Z+\\-\\[\\]]+/) == null) {\n alert(\"Invalid rule2 input. Rule must be A=XYZ\");\n return false;\n }\n [start, end] = formData.get(\"rule2\").split(\"=\");\n this.rules[start] = end;\n\n if (formData.get(\"rule3\") === \"\"){ // Assume people enter the rule sequentially\n return true;\n }\n if (formData.get(\"rule3\").match(/^[A-Z]=[A-Z+\\-\\[\\]]+/) == null) {\n alert(\"Invalid rule3 input. Rule must be A=XYZ\");\n return false;\n }\n [start, end] = formData.get(\"rule3\").split(\"=\");\n this.rules[start] = end;\n return true;\n }",
"function calc() {\n \n if(document.getElementById(\"screen\").value === \"Error\") {\n return;\n }\n \n try {\n if (document.getElementById(\"screen\").value.includes('.')) {\n document.getElementById(\"screen\").value = eval(document.getElementById(\"screen\").value).toFixed(2);\n } else {\n document.getElementById(\"screen\").value = eval(document.getElementById(\"screen\").value);\n }\n calced = true;\n } catch (err) {\n document.getElementById(\"screen\").value = \"Error\";\n calced = true;\n }\n}",
"function checkFormulaMass(){\n var myAns2 = document.getElementById(\"answerbox2\").value;\n var myAns2Float = parseFloat(myAns2);\n if (myAns2Float === relativeFormulaMass){\n var myReply = \"That is correct! The Relative Formula Mass of \" + molecule + \" is: \";\n }\n else{\n myReply = \"The Relative Atomic Mass of \" + molecule + \" is: \";\n }\n document.getElementById(\"RFMAnswer\").innerHTML = myReply + relativeFormulaMass; \n}",
"function calculate() {\n var calculationResult = '';\n\n try {\n calculationResult = model.calculate();\n calculationResult = addSeparators(calculationResult);\n showResult('= ' + calculationResult);\n } catch (e) {\n if (e instanceof errors.EquationInvalidFormatError) {\n showResult('Wrong format');\n } else if (e instanceof errors.CalculationError) {\n showResult('Invalid operation');\n } else if (e instanceof errors.InfinityError) {\n showResult(\n (e.positive ? '' : '−') + '∞'\n );\n } else {\n showError('Unknown error.');\n console.warn(e);\n }\n }\n }",
"cancelModification() {\n this.input.value = this.getFormula();\n }",
"function eventosReiniciarFormula() {\n /*\n * En el momento en que se envia el formulario se toma el ingreso y se actualiza el evento para volver a correr la formula\n */\n $(document).on(\"click\", \"#send-form\", function () {\n var ingresos = $(\"#EstudioIngreso\").val();\n if (ingresos != \"\") {\n $(\"#EstudioIngresoCapacidad\").val(ingresos);\n calculoCapacidad();\n }\n });\n\n $(document).on(\"change\", \"#porcentajeGastoFijo\", function () {\n calculoCapacidad();\n })\n}",
"function checkNNandMN(formula) {\n if (\n nickName &&\n nickName != \"\" &&\n nickName != firstName &&\n middleName != \"\" &&\n middleName != middleInitial\n ) {\n emailOutput.push(formula);\n }\n}",
"function UserInput(){\n let Input = READLINE.question(\"what operation do you want addition, subtraction, multiplication, or division?\")\n\nif (input == \"addition\"){\n\tlet addinput1 = READLINE.question(\"what is your first number?\");\n\tlet addinput2 = READLINE.question(\"what is your second number?\");\n\treturn addNumbers((parselnt (addinput1), parselnt (addinput2)));\n}\n\nelse if ( input == \"subtraction\"){\n\tlet subinput1 = READLINE.question(\"what is your first number?\");\n\tlet subinput2 = READLINE.question(\"what is your second number?\");\n\treturn subNumbers((parselnt (subinput1), parselnt (subinput2)));\n}\n\nelse if (input == \"multiplication\"){\n\tlet multiplyinput1 = READLINE.question(\"what is your first number?\");\n\tlet multiplyinput2 = READLINE.question(\"what is your second number?\");\n\treturn multiplyNumbers((parselnt (multiplyinput1), parselnt (multiplyinput2)));\n}\n\nelse if (input == \"division\"){\n\tlet divideinput1 = READLINE.question(\"what is your first number?\");\n\tlet divideinput2 = READLINE.question(\"what is your second number?\");\n\treturn divideNumbers((parselnt (divideinput1), parselnt (divideinput2)));\n\t}\n}",
"function calculate() {\n if (operator == 1) {\n currentInput = eval(memory) * eval(currentInput);\n }\n if (operator == 2) {\n currentInput = eval(memory) / eval(currentInput);\n }\n if (currentInput == memory / 0) {\n currentInput = \"ERROR! You can't divide by zero.\";\n }\n if (operator == 3) {\n currentInput = eval(memory) + eval(currentInput);\n }\n if (operator == 4) {\n currentInput = eval(memory) - eval(currentInput);\n }\n if (operator == 5) {\n currentInput = Math.pow(memory, currentInput);\n }\n if (operator == 6) {\n var num = currentInput;\n currentInput = memory * Math.pow(10, currentInput);\n if (num > 15) {\n currentInput = memory + \"e\" + num;\n }\n }\n\n operator = 0; // clear operator\n memory = \"0\"; // clear memory\n displayCurrentInput();\n}",
"function calculate() {\n\t\t'use strict';\n\t\n\t\t// For storing the volume:\n\t\tvar volume;\n \n // Get a reference to the form values:\n var length = document.getElementById('length').value;\n var width = document.getElementById('width').value;\n var height = document.getElementById('height').value;\n \n // Convert strings into numbers\n length = parseFloat(length);\n width = parseFloat(width);\n height = parseFloat(height);\n \n // Assertions\n try {\n \t\tassertCheck(((typeof length == 'number') && (length > 0)), 'The length must be a positive number.');\n \t\tassertCheck(((typeof width == 'number') && (width > 0)), 'The width must be a positive number.');\n \t\tassertCheck(((typeof height == 'number') && (height > 0)), 'The height must be a positive number.');\n } catch (err) {\n \t\tconsole.log('Caught: ' + err.name + ', because: ' + err.message);\n }\n\n\t\t// Verify box measurements\n console.log('length: ' + length);\n console.log('width: ' + width);\n console.log('height: ' + height);\n \n\t\t// Format the volume:\n\t\tvolume = parseFloat(length) * parseFloat(width) * parseFloat(height);\n\t\tvolume = volume.toFixed(4);\n\t\n\t\t// Display the volume:\n\t\tdocument.getElementById('volume').value = volume;\n\t\n\t\t// Return false to prevent submission:\n\t\treturn false;\n \n} // End of calculate() function.",
"function evalDoubleInput() {\n // Check validity of both input strings\n if (!funcObj.validInput(evalInputFirstStr)) {\n alert(\"First input '\" + evalInputFirstStr + \"' is not valid for this function\")\n return\n }\n if (!funcObj.validInput(evalInputSecondStr)) {\n alert(\"Second input '\" + evalInputSecondStr + \"' is not valid for this function\")\n return\n }\n // Parse the inputs to objects\n var firstParsed = funcObj.parseInput(evalInputFirstStr)\n var secondParsed = funcObj.parseInput(evalInputSecondStr)\n var evaluated = funcObj.function(firstParsed, secondParsed)\n // Get formatted strings for use in the database\n var firstDBstr = funcObj.inputDBStr(firstParsed)\n var secondDBstr = funcObj.inputDBStr(secondParsed)\n\n // Check to see if input being evaluated is allowed to be evaluated (if it was seen during a quiz)\n var gens = funcObj.inputGenerators()\n var forbiddenInputs = []\n gens.forEach((g) => {forbiddenInputs.push(g())})\n var currentlyForbidden = forbiddenInputs.slice(0, getNextQ())\n var forbiddenFound = false\n currentlyForbidden.forEach((inputs) => { \n if (funcObj.equivalentInputs(inputs[0], firstParsed) === true && funcObj.equivalentInputs(inputs[1], secondParsed) === true) {\n alert(\"Cannot evaluate inputs seen during a quiz attempt!\")\n var action = {}\n action.id = localStorage.getItem('userID')\n action.fcn = funcObj.description()\n action.type = \"cheat_attempt\"\n action.time = Util.getCurrentTime()\n action.in = firstDBstr + \" \" + secondDBstr\n action.out = funcObj.outputDBStr(evaluated)\n if (localStorage.getItem(funcObj.description()) === null) {\n action.key = Util.newServerKey()\n Util.sendToServer(action)\n }\n forbiddenFound = true\n }\n })\n if (forbiddenFound === true) {\n return\n }\n\n // Send an input evaluation log action to the server, and also build an\n // action object for use in displaying the evaluation in the guessing screen console\n var serverGuess = {}\n var displayGuess = {}\n serverGuess.id = localStorage.getItem('userID')\n displayGuess.id = localStorage.getItem('userID')\n serverGuess.fcn = funcObj.description()\n displayGuess.fcn = funcObj.description()\n serverGuess.type = \"eval_input\"\n displayGuess.type = \"eval_input\"\n displayGuess.key = Util.newDisplayKey()\n serverGuess.time = Util.getCurrentTime()\n displayGuess.time = Util.getCurrentTime()\n\n serverGuess.in = firstDBstr + \" \" + secondDBstr\n\n var firstDisplayStr = funcObj.inputDisplayStr(firstParsed)\n var secondDisplayStr = funcObj.inputDisplayStr(secondParsed)\n displayGuess.in = firstDisplayStr + \", \" + secondDisplayStr\n\n serverGuess.out = funcObj.outputDBStr(evaluated)\n displayGuess.out = funcObj.outputDisplayStr(evaluated)\n\n serverGuess.finalGuess = funcGuess.trim()\n displayGuess.finalGuess = funcGuess.trim()\n\n // Only if this function wasn't already done (description not already seen)\n if (localStorage.getItem(funcObj.description()) === null) {\n // console.log(\"sent to server\", serverGuess)\n serverGuess.key = Util.newServerKey()\n Util.sendToServer(serverGuess)\n }\n\n // Update the display console\n guesses.push(displayGuess)\n updateFunc()\n }",
"function evaluateExpression(equation, inputs) {\n //I'm pretty sure this removes all whitespace.\n equation = equation.replace(/\\s/g, \"\");\n //if equation is an input (like 't'), return the value for that input.\n if (equation in inputs) {\n return inputs[equation];\n }\n //make each variable x like (x) so that 5(x) can work\n //to avoid infinite recursion, make sure each substring like (((x))) is turned into (x)\n for (var variable in inputs) {\n var prevLength = 0;\n while (prevLength!=equation.length) {\n //it looks like this will only go through the loop once, but actually the length of equation might change before the end of the loop\n prevLength = equation.length;\n equation = equation.replace(\"(\"+variable+\")\", variable);//first remove parenthesis from ((x)), if they exist\n }\n \n equation = equation.replace(variable, \"(\"+variable+\")\");//then add parenthesis back\n }\n //if start with - or $ (my negative replacement), negate entire expression\n if (equation.indexOf(\"-\")==0 || equation.indexOf(\"$\")==0) {\n return -1*evaluateExpression(equation.slice(1), inputs);\n }\n for (var i=1; i<equation.length; i++) {//phantom multiplication (first char cannot have a phantom *)\n //5(3) should become 5*(3)\n //5cos(3) should become 5*cos(3)\n if (equation.charAt(i)==\"(\") {\n var insertionIndex = i;\n //size of unary operation\n for (var size=MAX_FUNCTION_LENGTH; size>=MIN_FUNCTION_LENGTH; size--) {\n if (i>=size) {\n var charsBefore = equation.slice(i-size,i);\n if (charsBefore in functions) {\n insertionIndex = i-size;\n break;\n }\n }\n }\n if (insertionIndex) {\n var prevChar = equation.charAt(insertionIndex-1);\n if (prevChar==\"*\" || prevChar==\"+\" || prevChar==\"/\" || prevChar==\"-\" || prevChar==\"^\" || prevChar==\"(\") {\n \n } else {\n equation=equation.slice(0,insertionIndex).concat(\"*\",equation.slice(insertionIndex));\n i++;\n }\n }\n }\n }\n //parenthesis\n //get rid of all parentheses\n while (equation.indexOf(\"(\")>=0) {\n //use for (a*(m+a)) and (a+m)*(a+a). thus you can't just take the first '(' and last ')' and you can't take the first '(' and first ')' parentheses. You have to make sure the nested parentheses match up\n //start at the first '('\n var startIndex = equation.indexOf(\"(\");\n var endIndex = startIndex+1;\n var nestedParens = 0;\n //find end index\n //stop when outside of nested parentheses and the character is a ')'\n while (equation.charAt(endIndex)!=\")\" || nestedParens) {\n if (equation.charAt(endIndex)==\")\") {\n nestedParens--;\n }\n if (equation.charAt(endIndex)==\"(\") {\n nestedParens++;\n }\n endIndex++;\n }\n //find what's in the parentheses and also include the parenthesis.\n var inParens = equation.slice(startIndex+1, endIndex);\n var includingParens = equation.slice(startIndex, endIndex+1);\n \n var value = evaluateExpression(inParens, inputs);\n //size of unary operation\n //in range. Must enumerate backwards so acos(x) does not get interpreted as a(cos(x))\n for (var size=4; size>=2; size--) {\n if (startIndex>=size) {\n var charsBefore = equation.slice(startIndex-size, startIndex);\n if (charsBefore in functions) {\n value = functions[charsBefore](value);\n includingParens=equation.slice(startIndex-size, endIndex+1);\n break;\n }\n }\n }\n \n if (includingParens==equation) {//like (5) or cos(3)\n return value;\n } else {\n //replace in equation.\n equation = equation.replace(includingParens, value);\n }\n }\n //done with parentheses\n \n //deal with negatives. replace with dollar sign\n //this is so 4/-7 doesn't get interpreted as (4/)-7, which could raise a divide by zero error\n equation = equation.replace(\"*-\", \"*$\");\n equation = equation.replace(\"--\", \"+\");//minus negative is plus\n equation = equation.replace(\"+-\", \"-\");//add negative is minus\n equation = equation.replace(\"/-\", \"/$\");\n equation = equation.replace(\"(-\", \"($\");\n \n //now the divide and conquer algorithm (or whatever this is)\n \n //check if equation contains any operations like \"+\", \"-\", \"/\", etc.\n\tif (equation.indexOf(\"+\")>=0) {\n //start at zero and add from there\n var sum = 0;\n var toAdd = equation.split(\"+\");//divide\n for (var operand in toAdd) {\n sum += evaluateExpression(toAdd[operand], inputs);//conquer\n }\n //everything has been taken care of.\n return sum;\n }\n if (equation.indexOf(\"-\")>=0) {\n var diff = 0;\n var toSub = equation.split(\"-\");\n var first = true; //if looking at the first operand, it's positive. Subtract all others.\n //this is much easier in Haskell\n //first:toSum = first - (sum toSub)\n for (var op in toSub) {\n if (first) diff = evaluateExpression(toSub[op], inputs);\n else diff -= evaluateExpression(toSub[op], inputs);\n first=false;\n }\n return diff;\n }\n\tif (equation.indexOf(\"*\")>=0) {\n\t\tvar multiple = 1;//start with one (multiplicative identity)\n\t\tvar toMultiply = equation.split(\"*\");\n\t\tfor (var factor in toMultiply) {\n\t\t\tmultiple *= evaluateExpression(toMultiply[factor], inputs);\n\t\t}\n\t\treturn multiple;\n\t}\n if (equation.indexOf(\"/\")>=0) {\n var quot = 0;\n var toDiv = equation.split(\"/\");\n var first = true;\n for (var op in toDiv) {\n if (first) quot = evaluateExpression(toDiv[op], inputs);\n else quot /= evaluateExpression(toDiv[op], inputs);\n first=false;\n }\n return quot;\n }\n if (equation.indexOf(\"^\")>=0) {\n var exp = 0;\n var toPow = equation.split(\"^\");\n var first = true;\n for (var op in toPow) {\n if (first) exp = evaluateExpression(toPow[op], inputs);\n else exp = Math.pow(exp, evaluateExpression(toPow[op], inputs));\n first=false;\n }\n return exp;\n }\n \n //no function. assume it's a number (base 10 of course)\n var value = parseFloat(equation, 10);\n if (equation.charAt(0)==\"$\") {//negative\n value = parseFloat(equation.slice(1), 10) * -1;\n }\n\treturn value;\n}",
"function calculate() {\n\tlet result = document.getElementById(\"result\");\n\n\tif(savedOperation == \"1\") {\n\t\tresult.value = eval(savedNum) + eval(displayedNum);\n\t} else if(savedOperation == \"2\") {\n\t\tresult.value = eval(savedNum) - eval(displayedNum);\n\t} else if(savedOperation == \"3\") {\n\t\tresult.value = eval(savedNum) * eval(displayedNum);\n\t} else if(savedOperation == \"4\") {\n\t\tif(displayedNum == \"0\") {\n\t\t\tclr(\"undefined\");\n\t\t} else {\n\t\t\tresult.value = eval(savedNum) / eval(displayedNum);\n\t\t}\n\t} else {\n\t\tresult.value = \"Invalid Operation\";\n\t}\n\tsavedNum = result.value;\n\tdisplayedNum = \"0\";\n\tsavedOperation = operation;\n\toperation = \"0\";\n\tcalculationDone = true;\n\toverrideOp = true;\n}",
"function calculateCell(row, column) {\r\n // begin by getting the formula parts\r\n var tokenArray = getFormula(tblArray[row][column]);\r\n\r\n // tokenArray[1] and tokenArray[2] contain the from and to references\r\n // need more validation if this was a production level app\r\n\r\n if (tokenArray !== null) {\r\n var fromColumn = tokenArray[1].substr(0, 1);\r\n var fromRow = tokenArray[1].substr(1, tokenArray[1].length - 1);\r\n\r\n var toColumn = tokenArray[2].substr(0, 1);\r\n var toRow = tokenArray[2].substr(1, tokenArray[2].length - 1);\r\n\r\n // assign the actual row/column index values for the tblArray\r\n var fromRowIndex = parseFloat(fromRow) - 1;\r\n var fromColIndex = fromColumn.charCodeAt(0) - 65;\r\n\r\n var toRowIndex = parseFloat(toRow) - 1;\r\n var toColIndex = toColumn.charCodeAt(0) - 65;\r\n\r\n var sumTotal = 0;\r\n\r\n for (var i = fromRowIndex; i <= toRowIndex; i++) {\r\n for (var j = fromColIndex; j <= toColIndex; j++) {\r\n // make sure we have a number for addition\r\n // Assume value 0 if there is no information on this cell\r\n if (!tblArray[i][j]) {\r\n tblArray[i][j] = \"0\";\r\n }\r\n if (tblArray[i][j].startsWith(\"=\")) {\r\n let cell = document.getElementById(Number(i + 1) + \"_\" + Number(j + 1));\r\n sumTotal += parseFloat(cell.textContent);\r\n }\r\n if (isFloat(tblArray[i][j])) {\r\n sumTotal += parseFloat(tblArray[i][j]);\r\n }\r\n }\r\n }\r\n\r\n // we now have the total... insert into spreadsheet cell\r\n // ... get the cell id\r\n var cellID = (row + 1) + \"_\" + (column + 1);\r\n var ref = document.getElementById(cellID)\r\n ref.innerHTML = sumTotal;\r\n }\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if request URL is in provided basePaths | isUrlInBasePaths(request) {
const url = request.url.toLowerCase();
const path = this.basePaths.find(path => url.startsWith(path));
return Boolean(path);
} | [
"function isHttpEndpoint(pathname) {\n for (let index in httpEndpoints) {\n if (httpEndpoints[index][0] == pathname) {\n return true;\n }\n }\n return false;\n}",
"function isLocalhost(){\n return window.location.origin.includes(\"localhost:8088\");\n}",
"function CheckUrlEnd(checkUrl){\r\n var path = window.location.pathname;\r\n var pathSplit = path.split(\"/\");\r\n var urlEnd = pathSplit[pathSplit.length - 1];\r\n\r\n if(urlEnd == checkUrl){\r\n return true;\r\n }\r\n\r\n return false;\r\n}",
"function isPath(path) {\n\treturn path === window.location.pathname.slice(-path.length);\n}",
"function isDelayEndpoint(pathname) {\n for (let index in delayEndpoints) {\n if (delayEndpoints[index][0] == pathname) {\n return true;\n }\n }\n return false;\n}",
"function public_view(){\n\t\tvar path = $location.path();\n\t\tvar pub = config.access.public_views;\n\t\tfor( var i=0; i<pub.length; i++ ){\n\t\t\tif ( path.indexOf( pub[i] ) == 0 ){\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}",
"function starts_with_domain(url) {\n return url[0] != \"/\";\n}",
"function isCurrentUrlFacebook() {\n return window.location.host === 'facebook.com' || window.location.host === 'www.facebook.com'\n}",
"function checkURL()\n{\n if (/\\bfull\\b/.test(location.search)) toggleMode();\n if (/\\bstatic\\b/.test(location.search)) interactive = false;\n}",
"function isLocalUrl(url)\n{\n return url.indexOf(\"http\") != 0;\n}",
"function coreScript(src) {\n\t\tvar i;\n\t\tvar coreScriptLocations = [\"WebResource.axd\", \"_layouts\"];\n\t\tfor(i=0; i < coreScriptLocations.length; i++) {\n\t\t\tif(src.indexOf(coreScriptLocations[i]) > -1) {\n\t\t\t\treturn true;\t\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t} // End of function coreScript",
"function matchPath(ctx) {\n const pathname = parseurl_1.default(ctx).pathname;\n const cookiePath = cookieOptions.path || \"/\";\n if (cookiePath === \"/\") {\n return true;\n }\n if (pathname.indexOf(cookiePath) !== 0) {\n // cookie path not match\n return false;\n }\n return true;\n }",
"function isInCurrentSite(path) {\n\tvar siteRoot = dw.getSiteRoot();\n\tvar inCurSite = false;\n\t\n\tif (siteRoot) {\n\t\tvar siteRootForURL = dwscripts.filePathToLocalURL(site.getSiteRootForURL(path));\n\t\tinCurSite = (siteRoot == siteRootForURL);\n\t}\n\t\n\treturn inCurSite;\n}",
"checkForValidTokenPath(validTokens) {\n const pathName = window.location.pathname.replace('/', '');\n\n if (!pathName) {\n return;\n }\n\n if (validTokens.includes(pathName)) {\n this.getTokenDetails(pathName, this.state.lookupDate);\n }\n else {\n window.history.pushState({}, null, '/');\n this.setState({ renderDashboard: false });\n }\n }",
"function isUrlAffected() {\n let urlType = getUrlType()\n\n if(urlType === 'playlist' && AFFECTED_URL_TYPES.includes('playlists'))\n return true\n\n if(urlType === 'album' && AFFECTED_URL_TYPES.includes('albums'))\n return true\n\n if(urlType === 'collection' && AFFECTED_URL_TYPES.includes('collection'))\n return true\n\n return false\n}",
"function 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}",
"function isOnLearn() {\n return window.location.href.indexOf(\"learn.uwaterloo.ca/d2l\") != -1;\n}",
"function getSPSitePath() {\n\tvar url = window.location.origin;\n\tvar path_arr = window.location.pathname.split(\"/\");\n\tvar path = \"\";\n\t// This part needs to be tested\n\tfor (var x = 0; x < path_arr.length - 2; x++) {\n\t\t// Only append valid strings\n\t\tif (path_arr[x]) {\n\t\t\tpath += \"/\" + path_arr[x];\n\t\t}\n\t}\n\treturn (url+path);\n}",
"function isAdRequest(request) {\n return request.request.url.startsWith('https://securepubads.g.doubleclick.net/gampad/ads');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
When the user goes back to the home screen, the sessionStorage values for datacenter, network, and farm are set to default values. | function setHomeDefaults() {
sessionStorage["datacen"] = "All";
sessionStorage["network"] = -1;
sessionStorage["farm"] = -1;
} | [
"function restoreSessionStorageFromLocalStorage() {\n var backupText = localStorage[\"sessionStorageBackup\"],\n backup;\n\n if (backupText) {\n backup = JSON.parse(backupText);\n\n for (var key in backup) {\n sessionStorage[key] = backup[key];\n }\n\n localStorage.removeItem(\"sessionStorageBackup\");\n }\n }",
"function initLocalStorage(){\n if (!localStorage.hasOwnProperty('closeLoginWarning')){\n localStorage['closeLoginWarning'] = false;\n }\n \n if (!localStorage.hasOwnProperty('list')){\n localStorage['list'] = JSON.stringify([DEFAULT_ITEM]);\n }\n \n if (!localStorage.hasOwnProperty('loginStatus')){\n localStorage['loginStatus'] = false;\n }\n}",
"function store(){\n amplify.store.sessionStorage( settings.historyStorageItemsName + \"-past\", past );\n amplify.store.sessionStorage( settings.historyStorageItemsName + \"-future\", future );\n }",
"function archiveSessionStorageToLocalStorage() {\n var backup = {};\n\n for (var i = 0; i < sessionStorage.length; i++) {\n backup[sessionStorage.key(i)] = sessionStorage[sessionStorage.key(i)];\n }\n\n localStorage[\"sessionStorageBackup\"] = JSON.stringify(backup);\n sessionStorage.clear();\n }",
"testiavaan() {\n sessionStorage.setItem('jokuvalue', sessionStorage.getItem('meh123'))\n // sessionStorage.setItem('value', false)\n }",
"function SessionState()\n{\n if(localStorage.getItem(MY_VALUES.SESSION)==MY_VALUES.LOGGEDIN) \n {\n if(localStorage.getItem(\"idname\")==\"admin\") {\n window.location.href = MY_VALUES.ADMIN;\n return false;\n }\n else {\n window.location.href = MY_VALUES.TEACHER;\n return false;\n }\n }\n else if (localStorage.getItem(MY_VALUES.SESSION)==MY_VALUES.LOGGEDINHOD) {\n window.location.href =MY_VALUES.HOD;\n return false;\n }\n else if (localStorage.getItem(MY_VALUES.SESSION)==MY_VALUES.LOGGEDINSTUDENT) {\n window.location.href = MY_VALUES.STUDENT;\n return false;\n }\n}",
"clearSession() {\n ['accessToken', 'expiresAt', 'idToken'].forEach(key => {\n sessionStorage.removeItem(key);\n });\n\n this.accessToken = '';\n this.idToken = '';\n this.expiresAt = '';\n }",
"function setDatacenter(id) {\n sessionStorage[\"datacen\"] = id;\n sessionStorage[\"changed\"] = true;\n}",
"logout() {\n this._mealPlan = null\n this._userId = null\n this._token = null\n this._diet = null\n this._intolerances = null\n\n sessionStorage.removeItem('mealPlan')\n sessionStorage.removeItem('userId')\n sessionStorage.removeItem('token')\n sessionStorage.removeItem('diet')\n sessionStorage.removeItem('intolerances')\n }",
"function setNetwork(id) {\n\tsessionStorage[\"network\"] = id;\n\tsessionStorage[\"farm\"] = -1;\n\tsessionStorage[\"changed\"] = true;\n\twindow.location.href = \"../Home/PercentData\";\n}",
"goBack() {\n sessionStorage.setItem(\"feedsub\",false)\n this.setState({\n feedSub:false\n })\n }",
"function setStorageDefaultValues() {\n chrome.storage.sync.get(null, function (items) {\n try {\n if (chrome.runtime.lastError) {\n console.warn(chrome.runtime.lastError.message);\n } else {\n\n //console.log(items);\n if (isEmpty(items)) {\n //console.log('storage empty');\n //Set Default showNotifications value to options\n chrome.storage.sync.set({\n showNotifications: options.showNotifications,\n clearActivity: options.clearActivity,\n intervalTimeout: options.intervalTimeout\n });\n } else {\n //console.log('storage has data');\n // Equal options default value to storage\n options.showNotifications = items.showNotifications;\n options.clearActivity = items.clearActivity;\n changeTime(items.intervalTimeout);\n }\n\n }\n } catch (exception) {\n //window.alert('exception.stack: ' + exception.stack);\n console.error((new Date()).toJSON(), \"exception.stack:\", exception.stack);\n }\n });\n}",
"function populateStorage() {\n localStorage.setItem('bgcolor', document.getElementById('bgcolor').value);\n sessionStorage.setItem('font', document.getElementById('font').value);\n // localStorage.setItem('font', document.getElementById('font').value);\n\n setStyles();\n}",
"function clearWebStorage(){\r\n\t\t\t//Clearing session storage\r\n\t\t\tsessionStorage.clear();\r\n\t\t\t//Clearing local storage \r\n\t\t\tlocalStorage.clear();\r\n\t\t\t//Removing localstorage data from browser cache\r\n\t\t\tstore.remove('loggedonuser');\r\n\t\t\tstore.remove('authtoken');\r\n\t\t\tstore.remove('IsRememberMe');\r\n\t\t}",
"function saveToLocalStorage() {\n localStorage.setItem(\"startTime\", startTime);\n localStorage.running = running;\n localStorage.paused = paused;\n localStorage.tableSize = tableSize;\n localStorage.setItem(\"historyTable\", historyTable.innerHTML);\n localStorage.setItem(\"timeDisplay\", timeDisplay.innerHTML);\n localStorage.useStorage = 1;\n}",
"loadUserSession() {\n const storedUserSession = localStorage.getItem('userSession');\n const userSession = storedUserSession\n ? UserSession.deserialize(storedUserSession)\n : null;\n\n this.userSession = userSession;\n this.resetRenewalTimer(userSession);\n this.emit('user-session-changed', userSession);\n }",
"function loginStatusToStorage() {\n\tlocalStorage.loggedIn = loggedIn;\n\tlocalStorage.loggedInID = loggedInID;\n}",
"get sessData() {\n return this._sessData || {};\n }",
"function setFarm(id) {\n\tsessionStorage[\"farm\"] = id;\n\tsessionStorage[\"network\"] = $(\"#\" + id).parent().attr('id');\n\tsessionStorage[\"changed\"] = true;\n\twindow.location.href = \"../Home/PercentData\";\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
handleSubmit makes ajax request to send newUser to db. dispatches addUser action to change state. this.state is data passing along | handleSubmit(e) {
e.preventDefault();
axios.post('/api/users', this.state)
.then(res => res.data)
.then(newUser => {
store.dispatch(addUser(newUser))
console.log("new user dispatched:", newUser)
})
.catch(err => console.error(err))
} | [
"handleSubmit(event) {\n event.preventDefault();\n this.fetchUsers();\n }",
"handleSubmit(evt) {\n evt.preventDefault()\n const userId = this.props.singleUser.id\n this.props.modifyExistingUser(userId, this.state)\n this.setState({buttonDisabled: true})\n }",
"function addUser() {\n $state.go('useradd');\n }",
"handleFormSubmit() {\n\t\tlet newEntry = {\n\t \"first\": this.state.first,\n\t \"last\": this.state.last,\n\t \"email\": this.state.email,\n\t \"interest\": this.state.interest\n\t\t};\n\n\t\tlet newUidRef = this.props.mlRef.push();\n\n\t\t/* send data to Firebase mailing list. entry stored at auto generated UID */\n\t\tlet p1 = new Promise ( (resolve, reject) => {\n\t\t\tnewUidRef.set(newEntry);\n\t\t\tresolve(\"Success!\");\n\t\t});\n\n\t\tp1.then( msg => {\n\t\t\talert(\"You have sucessfully joined our mailing list!\");\n\t\t\tthis.setState({isSignedUp: true});\n\t\t});\n\n\t}",
"onNewUser() {\r\n this.setState({\r\n register: true\r\n });\r\n }",
"function initAddUserToBuddylistForm(){\n $('#adduserform').submit(function (){\n if(!$('#add-user-to-buddylist-input').hasClass('ui-autocomplete-loading') && $('#add-user-to-buddylist-inputholder span.name').size() > 0){\n $('#add-user-to-buddylist-input').addClass('ui-autocomplete-loading')\n $.ajax({\n url: \"/private_messenger.php\",\n data: $('#adduserform').serialize() + '&action=add-user-to-buddylist',\n type: 'post',\n dataType: 'xml',\n success: function (rsp){\n if($(rsp).find('status').text() == 'error'){\n showMessage($('#adduserform'), $(rsp).find('message').text(), true);\n hideMessage($('#adduserform'), 3);\n }else{\n $('#add-user-to-buddylist-inputholder span.name').remove();\n $('#private_messenger_buddies_list').html($(rsp).find('html').text());\n }\n },\n error: function (err){\n\n },\n complete: function (){\n $('#add-user-to-buddylist-input').removeClass('ui-autocomplete-loading');\n }\n });\n }\n $('#')\n return false;\n })\n\n //Use autocomplete for add buddy list form\n $('#add-user-to-buddylist-input').click(function (){\n $('#add-user-to-buddylist-inputholder span.name').remove();\n })\n $('#add-user-to-buddylist-input').autocomplete({\n appendTo: '#add-user-to-buddylist', source: function (request, response){\n $.ajax({\n url: '/private_messenger.php',\n data: {term: request.term, action: 'get-users'},\n dataType: 'json',\n type: 'post',\n success: response\n })\n }, search: function (){\n // custom minLength\n var term = this.value;\n if(term.length < 1){\n return false;\n }\n }, focus: function (){\n // prevent value inserted on focus\n return false;\n }, select: function (event, ui){\n //Add New Item\n $('#add-user-to-buddylist-inputholder').append('<span class=\"name\">' + ui.item.label + ' <a href=\"#\">x</a><input type=\"hidden\" name=\"added-id\" value=\"' + ui.item.id + '\" /><input type=\"hidden\" name=\"added-id-hash\" value=\"' + ui.item.hash + '\" /></span>');\n $('#add-user-to-buddylist-inputholder').find('.name a').click(function (){\n $(this).parent().remove();\n })\n $('body').click();\n return false;\n }, close: function (){\n $('#add-user-to-buddylist-input').val('');\n }\n });\n }",
"handleAddNew(event){\n this.props.addNew(this.state.newFriend)\n \n this.setState({\n newFriend: ''\n })\n\n }",
"function handleFormSubmit() {\n\t// Get values of inputs\n\t// Pass values to addNewPost()\n var inputName = document.getElementById(\"input-username\").value;\n var inputCaption = document.getElementById(\"input-caption\").value;\n var inputPicture = document.getElementById(\"input-picture\").value;\n addNewPost(inputName, inputPicture, inputCaption);\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}",
"async function createUser() {\n const response = await fetch(`/api/users/`, {\n method: 'POST',\n body: JSON.stringify(userData),\n headers:{\n 'Content-Type': 'application/json'\n }\n });\n\n if (response.status !== 200) {\n // A server side error occured. Display the\n // error messages.\n handleServerError(response);\n } else {\n clearUserForm();\n // Re-fetch users after creating new\n fetchUsers()\n }\n }",
"handleSubmit(event) \n { \n // Call the signIn function with the values from the form input\n this.signIn(this.state.email, this.state.password);\n\n // Prevent default action\n event.preventDefault();\n }",
"static async processAdd(ctx) {\n if (ctx.state.auth.user.Role != 'admin') {\n ctx.flash = { _error: 'Team management requires admin privileges' };\n return ctx.response.redirect('/login'+ctx.request.url);\n }\n\n const body = ctx.request.body;\n\n try {\n\n const validation = { // back-end validation matching HTML5 validation\n Name: 'required',\n };\n\n if (validationErrors(body, validation)) {\n throw new Error(validationErrors(body, validation));\n }\n\n const id = await Team.insert(body);\n ctx.response.set('X-Insert-Id', id); // for integration tests\n\n // return to list of members\n ctx.response.redirect('/teams');\n\n } catch (e) {\n // stay on same page to report error (with current filled fields)\n ctx.flash = { formdata: body, _error: e.message };\n ctx.response.redirect(ctx.request.url);\n }\n }",
"handleSubmit(event) {\n // Post to database\n this.getNumberOfPosts();\n\n // Prevent page from refreshing\n event.preventDefault()\n }",
"onAddCompanySubmit(event){\n /*\n 1. getting the company name\n 2. getting the industry id\n 3. call this.props.addNewCompany to update the db\n */\n event.preventDefault();\n let companyName = event.target.newCompName.value;\n\n let industry = event.target.industry.value;\n let industryId = this.findIndustryId(industry);\n if(industryId){\n const company = {\n name: companyName,\n account_state: 'trial',\n industry_id: industryId\n\n };\n this.props.addNewCompany(company);\n\n }\n\n }",
"addUser (userid, firstname, lastname) {\n\t\tlet userRef = state.db.collection('users')\n\n\t\t// Add to remote database\n\t\tuserRef.doc(userid).set({\n\t\t\tfirstName : firstname,\n\t\t\tlastName : lastname,\n\t\t})\n\n\t\t// Add to local state\n\t\tstate.allUsers[userid] = {\n\t\t\tfirstName : firstname,\n\t\t\tlastName : lastname,\n\t\t}\n\n\t\tconsole.log(\"Users info: \", state.allUsers);\n\t\tconsole.log(\"Users count: \", Object.keys(state.allUsers).length);\n\t}",
"async function addingBreakfast (evt, username) {\n\tevt.preventDefault();\n\n\tconst $column = $(evt.target).parents('div').last().prevObject;\n\tconst $name = $column.children('h3').text();\n\tconst $calories = $column.children('p').text().replace(/\\D/g, '');\n\n\taxios.defaults.withCredentials = true;\n\n\tawait axios({\n\t\tmethod: 'post',\n\t\turl: `${BASE_URL}/users/add_breakfast`,\n\t\theaders: {\n\t\t\t'Content-Type': 'application/json',\n\t\t\t'Access-Control-Allow-Origin': '*',\n\t\t},\n\t\tdata: {\n\t\t\tname: $name,\n\t\t\tusername: username,\n\t\t\tcalories: $calories,\n\t\t},\n\t\twithCredentials: true,\n\t\tcredentials: 'same-origin',\n\t});\n}",
"function processAddMemberForm(data)\n{\n var member_index = memberIndex(data);\n insertMember(data, member_index);\n}",
"function handleSubmit(e) {\r\n e.preventDefault();\r\n let formData = [\r\n {\r\n addItem: addItemRef.current.value,\r\n },\r\n ];\r\n // console.log(formData.addItem)\r\n // console.log(formData)\r\n\r\n /* This inner function adds task to todo list [ie. array]\r\n\r\n parameter prevState is array \"todo\"\r\n parameter formData is the user's input\r\n reset value in the form input user bar */\r\n setTodo((prevState) => prevState.concat(formData));\r\n addItemRef.current.value = \"\";\r\n console.log(todo);\r\n }",
"function handleFormSubmit(event){\n event.preventDefault();\n if (formObject.title && formObject.owner){\n API.saveJob({\n title: formObject.title,\n owner: formObject.owner,\n description: formObject.description\n })\n .then(res => loadJobs())\n .catch(err => console.log(err))\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If true, the results will not be displayed in the popup. However, if a default index is specified, the default item will still be completed in the input. readonly attribute boolean typeAheadResult; | get typeAheadResult()
{
return true;
} | [
"function typeAhead(response) {\n\t\t// save the response in the parent scope\n\t\tarr = response;\n\t\t// Reset result list index to -1 (nothing selected)\n\t\tlIndex = -1;\n\t\t// Stop the waiting animation \n\t\tclearInterval(leftWaitingInterval);\n\t\tclearInterval(rightWaitingInterval);\n\t\t// Reset the text in search button\n\t\t$('#' + column + '-button').val('search');\n\t\t// Clear previous typeahead results\n\t\t$('#' + column + '-type-result').html('');\n\t\t// If there is something in the response array\n\t\tif (arr !== null) {\n\t\t\t// For each result in response array\n\t\t\tarr.forEach(function(value, index) {\n\t\t\t\t// If not in the Bats exchange\n\t\t\t\tif (value.Exchange[0] !== 'B') {\n\t\t\t\t\t// Truncate the displayed name if it is longer than 21 character\n\t\t\t\t\tif (value.Name.length < 22) {\n\t\t\t\t\t\tname = value.Name;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tname = value.Name.slice(0, 20) + '...';\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\texchange = value.Exchange;\n\t\t\t\t\t\n\t\t\t\t\t// Truncate the displayed symbol if it is longer than 5 characters\n\t\t\t\t\tif (value.Symbol.length < 6) {\n\t\t\t\t\t\tsymbol = value.Symbol;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsymbol = value.Symbol.slice(0, 4) + '...';\n\t\t\t\t\t}\n\t\t\t\t\t// Add it to the result dropdown list\n\t\t\t\t\t$('#' + column + '-type-result').append('<li class=\"' + column + '-result-li row\" data-name=\"' + value.Name + '\" data-symbol=\"' + value.Symbol + '\" data-exchange=\"' + value.Exchange + '\"><span class=\"full-name\">' + name + '</span><span class=\"exchange\">' + exchange + ': <span class=\"ticker\">' + symbol + '</span></span></li>');\n\t\t\t\t}\n\t\t\t})\n\t\t\t\n\t\t\t// Set a click handler for the results\n\t\t\tsetResultClickHandler();\n\t\t}\n\t}",
"function displayNoResults() {\n\t\t\t\tmoreLikeThisBlock.find('.loading').remove();\n\t\t\t\tmoreLikeThisBlock.find('.content').append('<p>' + options.no_results_text + '</p>');\n\t\t\t}",
"function showSuggestions() {\n var v = getNeedle();\n\n if (v.length == 0) {\n box.css('display', 'none');\n return;\n }\n\n suggestions = 0;\n\n box.empty();\n\n options.filters.each(function(i, f) {\n if (suggestions == options.size) {\n return;\n }\n\n list.every(function(o) {\n if (f(options.get(o).toLowerCase(), v)) {\n var li = suggestions++;\n\n box.append($('<div \\>', {\n 'events': {\n 'mousemove': function() { // don't use mouseover since that will bug when the user has the mouse below the input box while typing\n if (!hiding) {\n hover = li;\n showHover();\n }\n }\n }\n }).append(options.render(o)).store('val', o));\n\n if (suggestions == options.size) {\n return false;\n }\n }\n\n return true;\n });\n });\n\n updatePosition();\n\n // If no suggestions, no need to show the box\n if (suggestions > 0) {\n box.css('display', 'block');\n } else {\n box.css('display', 'none');\n }\n }",
"function ensureSelectionInView() {\n\n //Only if open\n if (!$ctrl.isShowingResults) {\n return;\n }\n\n //Check index\n if (!$ctrl.isNullable && selectionIndex < 0) {\n return;\n }\n\n //Find options\n const $container = $input.next().next();\n const $options = $container.find('li');\n\n //Get option now, taking into account the additional nullable element\n const option = $options[selectionIndex + ($ctrl.isNullable ? 1 : 0)];\n if (!option) {\n return;\n }\n\n //Determine container and element top and bottom\n const cTop = $container[0].scrollTop;\n const cBottom = cTop + $container[0].clientHeight;\n const eTop = option.offsetTop;\n const eBottom = eTop + option.clientHeight;\n\n //Check if out of view\n if (eTop < cTop) {\n $container[0].scrollTop -= (cTop - eTop);\n }\n else if (eBottom > cBottom) {\n $container[0].scrollTop += (eBottom - cBottom);\n }\n }",
"function checkParcelSearchInput(defaultTextInput){\n\tvar inputTextVal = jQuery('.ptSearchCriteriaDiv').find('.ghostText').val();\n\tvar term=trim(inputTextVal);\n\tif (term!=defaultTextInput){ \n\t\tcallSearchParcel();\n\t} else {\n\t\treturn false;\n\t}\n}",
"function displayNoSearchResults() {\n $(\".info_section\").html(`<h1 aria-live=\"assertive\">There is no information for this city in our database.</h1>`);\n removeHiddenClass(\".exit_button\");\n\n setUserFocus(`.exit_button`);\n }",
"renderSuggestions() {\n const { value, matched, showList, selectedIndex } = this.state;\n\n if (!showList || matched.length < 1) {\n return null; // Nothing to render\n }\n\n return (\n <ul className=\"suggestions\">\n {matched.map((item, index) => (\n <li\n key={`item-${item}-${index}`}\n className={index === selectedIndex ? 'selected' : ''}\n dangerouslySetInnerHTML={{ __html: this.renderHighlightedText(item, value) }}\n onClick={this.handleOnItemClick}\n />\n ))}\n </ul>\n );\n }",
"getItems() {\n if (this.keyword.trim() === '') {\n this.suggestions = [];\n return;\n }\n let result = this.dataProvider.getResults(this.keyword);\n // if query is async\n if (result instanceof rxjs_1.Observable) {\n result\n .subscribe((results) => {\n this.suggestions = results;\n this.showItemList();\n }, (error) => console.error(error));\n }\n else {\n this.suggestions = result;\n this.showItemList();\n }\n // emit event\n this.ionAutoInput.emit(this.keyword);\n }",
"function checkSearchTip () {\n if (!$scope.userDontShowSearchTip &&\n !$scope.noSearchQuery &&\n !$scope.noSearchResults) {\n $scope.showSearchTip = true;\n } else {\n $scope.showSearchTip = false;\n }\n }",
"if (value.length === 0) {\n this.cancelAllSearchRequests();\n }",
"function do_search() {\n var query = input_box.val().toLowerCase();\n\n if (query && query.length) {\n if (selected_token) {\n deselect_token($(selected_token), POSITION.AFTER);\n }\n\n if (query.length >= settings.minChars) {\n show_dropdown_searching();\n clearTimeout(timeout);\n\n timeout = setTimeout(function () {\n run_search(query);\n }, settings.searchDelay);\n } else {\n hide_dropdown();\n }\n }\n }",
"searchQuery (value) {\n let result = this.tableData\n if (value) result = this.fuseSearch.search(this.searchQuery)\n else result = []\n this.searchedData = result\n }",
"onFocusAutosuggest(event) {\n event.target.select();\n }",
"function do_search() {\n var query = input_box.val();\n\n if((query && query.length) || !$(input).data(\"settings\").minChars) {\n if(selected_token) {\n deselect_token($(selected_token), POSITION.AFTER);\n }\n\n if(query.length >= $(input).data(\"settings\").minChars) {\n show_dropdown_searching();\n clearTimeout(timeout);\n\n timeout = setTimeout(function(){\n run_search(query);\n }, $(input).data(\"settings\").searchDelay);\n } else {\n hide_dropdown();\n }\n }\n }",
"async function searchButtonClicked () {\n var response\n if (toggleValue === 'Name') {\n response = await getNppesDataFirstName(searchText)\n setShowNameSearchResults(true)\n setShowOrgSearchResults(false)\n }\n else {\n response = await getNppesDataOrgName(searchText)\n setShowOrgSearchResults(true)\n setShowNameSearchResults(false)\n }\n if (response.length === 0) {\n setSearchResults(['No results found'])\n }\n else {\n setSearchResults(response)\n }\n setSearchText('')\n }",
"get _shouldAutofill() {\n // First of all, check for the autoFill pref.\n if (!Prefs.autofill)\n return false;\n\n if (!this._searchTokens.length == 1)\n return false;\n\n // autoFill can only cope with history or bookmarks entries.\n if (!this.hasBehavior(\"history\") &&\n !this.hasBehavior(\"bookmark\"))\n return false;\n\n // autoFill doesn't search titles or tags.\n if (this.hasBehavior(\"title\") || this.hasBehavior(\"tag\"))\n return false;\n\n // Don't try to autofill if the search term includes any whitespace.\n // This may confuse completeDefaultIndex cause the AUTOCOMPLETE_MATCH\n // tokenizer ends up trimming the search string and returning a value\n // that doesn't match it, or is even shorter.\n if (/\\s/.test(this._originalSearchString))\n return false;\n\n if (this._searchString.length == 0)\n return false;\n\n return true;\n }",
"resetSearchType() {\n this.set('searchType.name', true);\n this.set('searchType.nameLF', true);\n this.set('searchType.date', true);\n this.set('searchType.ssn', true);\n this.set('searchType.prn', true);\n }",
"get searchResult()\n\t{\n//dump(\"searchResult:\"+this._searchResult+\"\\n\");\n\t\treturn this._searchResult;\n\t}",
"function returnToSearchResults() {\n $('.returnSearch').on('click', function() {\n $('.js-search-results').show();\n $('.oneResult').hide();\n $('.returnSearch').hide();\n })\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes userId cookie Redirects to login page | function logout() {
$.removeCookie("userId");
/// redirect to login
window.location.replace("/");
} | [
"function logout() {\n sessionStorage.removeItem(\"userId\");\n sessionStorage.removeItem(\"jwt\");\n }",
"static clearCookie() {\n var cookies = document.cookie.split(\";\");\n\n for (var i = 0; i < cookies.length; i++) {\n var cookie = cookies[i];\n var eqPos = cookie.indexOf(\"=\");\n var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;\n if (name.trim().toLowerCase() == 'voting-username')\n document.cookie = name + \"=;expires=Thu, 01 Jan 1970 00:00:00 GMT\";\n }\n \n }",
"function logout(){\n tokenFactory.deleteToken();\n $window.location.reload();\n }",
"static tamper() {\n del(\"user\").then(() => {\n localStorage.removeItem(\"role\");\n location.reload();\n });\n }",
"logoutUser() {\n this.get('session').invalidate();\n }",
"function removeRedirectFromStorage() {\n sessionStorage.removeItem('authSuccessRedirect')\n}",
"function logOff(all) {\n removeJwtToken();\n document.location.assign(\"/login\")\n}",
"function logOut() {\n localStorage.removeItem('token');\n newView();\n}",
"function DeleteUser(id) {\n\tvar confirmed = confirm(\"Are you sure you want to remove this user?\");\n\t\n\tif (confirmed) {\n\t\t// We could make an AJAX call here. That goes a little beyond what is expected in CIT 336.\n\t\t// Instead, let's redirect them through some other actions.\n\t\twindow.location = '/?action=deleteuser&id=' + id;\n\t}\t\n}",
"function facebookLogoutHandler(e) {\n if (e.success) {\n var client = Titanium.Network.createHTTPClient();\n client.clearCookies('https://login.facebook.com');\n } else if (e.error) {\n // Error!\n } \n}",
"function removeCookies() {\n Cookies.remove(`selection`);\n}",
"function logout() {\r\n $window.localStorage.removeItem('jwtToken');\r\n delete $window.localStorage['jwtToken'];\r\n $rootScope.$broadcast('loggedOut');\r\n }",
"function deleteJwtCookie(response) {\n response.unstate(_appConfig.settings.get('/JWT/COOKIE/NAME'), {\n ttl: 0, // In milliseconds\n path: _appConfig.settings.get('/JWT/COOKIE/PATH'),\n domain: _appConfig.settings.get('/JWT/COOKIE/DOMAIN')\n });\n}",
"removeToken() {\n Cookies.remove(TOKEN_KEY);\n }",
"function logout() {\n localStorage.setItem(\"isLoggedIn\", false)\n localStorage.removeItem('username')\n showPantryList()\n location.reload()\n}",
"function spotifyLogout() {\n // Wipe localStorage values.\n localStorage.removeItem(SPOTIFY_ACCESS_TOKEN_KEY);\n localStorage.removeItem(SPOTIFY_REFRESH_TOKEN_KEY);\n localStorage.removeItem(SPOTIFY_VOLUME_KEY);\n\n // Refresh the page.\n window.location.href = window.location.href;\n}",
"function lockLogoutAndRedirect() {\n if (window.env === \"dev\" || window.env === \"stage\") {\n lock.logout({\n returnTo: 'http://' + window.env + '.www.philly.com'\n });\n } else {\n lock.logout({\n returnTo: 'http://www.philly.com'\n });\n }\n }",
"logout({ commit }) {\n commit('clearUser');\n localStorage.setItem('token', null);\n localStorage.setItem('userId', null);\n }",
"function deleteUser(id) {\n // if it is NOT the same id return a list of all the users without that ID\n const updatedUsers_forDelete = usersInDanger_resc.filter(user => user.userID !== id);\n const deletedUser = usersInDanger_resc.filter(user => user.userID === id);\n setUsersInDanger_resc(updatedUsers_forDelete);\n console.log(deletedUser[0].userID);\n props.markSafe(deletedUser[0].userID);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handles key presses on a namevalue list (such as item options). Hitting on a namevalue list popsup its options dialog. The call to this handler is set up in NLField.java (NLField.getInputTag()) | function NLNameValueList_onKeyPress(evt, sFieldName, sOptionHelperSuffix)
{
var keyCode = getEventKeypress(evt);
if( keyCode == 32 ) // <SPACE>
{
// if the user hit <SPACE> find the helper icon which pops-up the options dialog and click it
var ndAction = document.getElementById(sFieldName + '_helper_' + sOptionHelperSuffix);
if( ndAction && ndAction.click)
{
ndAction.click();
}
}
return true;
} | [
"function setup_input (input_field) {\n var name = input_field.attr('name');\n var values_input = $('<input type=\"hidden\" class=\"ub-values\" name=\"' + name\n + '\" id=\"ub-values-' + name + '\" />');\n\n var ul_box = $('<ul id=\"ub-drop-'+name+'\" class=\"ub-inputlist\"></ul>');\n ul_box.width( input_field.width() ); // respect the original input width\n input_field.wrap(ul_box);\n input_field.wrap('<li class=\"ub-original\"></li>');\n input_field.after(values_input);\n input_field.width( opts.new_text_width );\n\n ul_box = $('#ub-drop-'+name); // need to reset this, otherwise ul_box doesn't actually point\n // to anything\n\n // make all clicks anywhere in the \"improved input list\" go to the actual input text box\n ul_box.click(function(){\n input_focus = true;\n input_field.focus();\n }).mousedown(function(){ input_focus = false; });\n\n // TODO: change 188 to the opts.separator instead\n input_field.keydown(function(event) {\n switch (event.keyCode) {\n\n // when we think input is done, turn the input into a ub-item\n case 188: // comma\n event.preventDefault();\n // and fall through to ...\n case 9: // tab\n case 13: // return\n var i_input = input_field.val().replace(/(,)/g, '').replace(/^\\s+|\\s+$/g, '');\n if (i_input == '') break;\n add_item_to_field(i_input, name);\n input_field.val('');\n break;\n\n // we can use the delete key to remove the last ub-item in the list\n case 8: // delete\n if (input_field.val() == '' && $('#ub-drop-' + name + ' > .ub-item').length) {\n var last_item = $('#ub-drop-' + name + ' > .ub-item').last();\n if (last_item.hasClass('ub-item-active')){\n last_item.data('removing')();\n } else {\n last_item.addClass('ub-item-active');\n }\n }\n break;\n \n // for any other keypress, remove the \"ready to delete\" class\n default:\n var last_item = $('#ub-drop-' + name + ' > .ub-item').last();\n last_item.removeClass('ub-item-active');\n break;\n }\n }).blur(function(event) {\n // remove the \"ready to delete\" class, copied from above\n var last_item = $('#ub-drop-' + name + ' > .ub-item').last();\n last_item.removeClass('ub-item-active');\n\n // turn any text into a ub-item, mostly copied from above\n var i_input = input_field.val().replace(/(,)/g, '').replace(/^\\s+|\\s+$/g, '');\n if (i_input == '') return;\n add_item_to_field(i_input, name);\n input_field.val('');\n });\n return ul_box;\n }",
"function addToListOnEnter(e) {\r\n\tif (inputLength() > 0 && e.keyCode === 13) {\r\n\t\tadd_to_list({ id: items.length, name: input.value.trim(), bought: false });\r\n\t}\r\n}",
"onFieldTagsKeyDown(event) {\n let me = this;\n\n if (event.key === 'Enter') {\n Neo.main.DomAccess.getAttributes({\n id : event.target.id,\n attributes: 'value'\n }).then(data => {\n VNodeUtil.findChildVnode(me.vnode, {className: 'field-tags'}).vnode.attributes.value = data.value;\n me.tagList = [...me._tagList, data.value];\n });\n }\n }",
"function inputBoxKeydown(e) {\r\n var acList = document.getElementById(\"ac-list\");\r\n if(acList) {\r\n var acItems = acList.childNodes;\r\n var acItemNum = acItems.length;\r\n if(e.keyCode == 40) { //move down\r\n e.preventDefault();\r\n if(listIndex < acItemNum - 1) {\r\n if(listIndex != -1) { \r\n acItems[listIndex].className = \"\";\r\n }\r\n listIndex++;\r\n acItems[listIndex].className = \"ac-active\";\r\n } else {\r\n acItems[listIndex].className = \"\";\r\n listIndex = -1;\r\n }\r\n changeSuggest();\r\n return true;\r\n } else if(e.keyCode == 38) { //move up\r\n e.preventDefault();\r\n if(listIndex > -1) { \r\n acItems[listIndex].className = \"\";\r\n listIndex--;\r\n if(listIndex != -1) acItems[listIndex].className = \"ac-active\";\r\n } else {\r\n listIndex = acItemNum - 1;\r\n acItems[listIndex].className = \"ac-active\";\r\n }\r\n changeSuggest();\r\n return true;\r\n } else if(e.keyCode == 13) { //enter\r\n e.preventDefault();\r\n curPattern = \"\";\r\n completeFlag = 0;\r\n closeACList();\r\n return true;\r\n }\r\n }\r\n return true;\r\n }",
"function itemlist() {\n var no = document.getElementById(\"items\");\n var option = no.options[no.selectedIndex].value;\n var list = document.getElementById(\"list\"); \n list.innerHTML=''; \n list.appendChild(document.createTextNode(\"Item Name: Item Value:\"));\n //list.appendChild(document.createTextNode(\"Item Value:\"));\n\tfor (var i=0; i<option; i++){\n\t var input_label = document.createElement(\"INPUT\");\n\t var input_value = document.createElement(\"INPUT\"); \n\t input_label.setAttribute(\"type\", \"text\");\n\t input_label.setAttribute(\"class\", \"name\");\n\t input_value.setAttribute(\"type\", \"number\");\n\t input_value.setAttribute(\"class\", \"values\");\n\t list.appendChild(document.createElement(\"BR\"));\n\t list.appendChild(document.createTextNode(i+1+'. \\t'));\n\t list.appendChild(input_label);\n\t list.appendChild(input_value); \n\t} \t\t\n}",
"function handleAutoCompleteEntryClick(tag) {\n\t\t// Get all tag entries\n\t\tconst tags = ref.current.value.split(/\\s/);\n\t\t// Set the input text to the clicked tag name.\n\t\tref.current.value = [\n\t\t\t// Get the text content of the input, excluding the last word.\n\t\t\t...tags.slice(0, -1),\n\t\t\t// Append the tag name to the list of tags.\n\t\t\t(tags[tags.length - 1].match(/[^a-z0-9]/gi)?.[0] ?? \"\") + tag.name,\n\t\t\t// And a little spacey.\n\t\t\t\"\"\n\t\t].join(\" \");\n\n\t\t// Clear the auto complete entries.\n\t\tsetAutoCompleteEntries([]);\n\n\t\t// Wait for the next frame because JavaScript is shitting through the screen.\n\t\tsetImmediate(() => {\n\t\t\t// Set the selection index to the end of the list.\n\t\t\tref.current.selectionStart =\n\t\t\t\tref.current.selectionEnd = ref.current.value.length;\n\n\t\t\t// Focus the input field element.\n\t\t\tref.current.focus();\n\t\t});\n\t}",
"_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 ACListClick(e) {\r\n var ele = e.target;\r\n if(ele.tagName == \"STRONG\") ele = ele.parentNode;\r\n if(ele.tagName != \"LI\") return true;\r\n e.stopPropagation();\r\n changeSuggest();\r\n curPattern = \"\";\r\n completeFlag = 0;\r\n closeACList();\r\n }",
"function promptengine_addValueFromPickList(\r\n form,\r\n type,\r\n promptID)\r\n{\r\n var AvailableList, SelectedList;\r\n AvailableList = form[promptID + \"AvailableList\"];\r\n SelectedList = form[promptID + \"ListBox\"];\r\n\r\n promptengine_deselectAllItems(SelectedList);\r\n\r\n var changed = false;\r\n\r\n var lastSelected = -1;\r\n for (var i = 0; i < AvailableList.length; i++)\r\n {\r\n if (AvailableList.options[i].selected)\r\n {\r\n var added = promptengine_addAvailableItem(AvailableList, i, SelectedList);\r\n if (added == true)\r\n changed = true;\r\n lastSelected = i;\r\n }\r\n }\r\n\r\n // set focus to the next item on the available list\r\n if (lastSelected++ >= 0 && lastSelected < AvailableList.length)\r\n {\r\n promptengine_deselectAllItems(AvailableList);\r\n AvailableList.options[lastSelected].selected = true;\r\n }\r\n\r\n return changed;\r\n}",
"function handleEditItem() {\n $('.js-shopping-list').on('input', '.js-shopping-item', function(event) {\n let itemIndex = getItemIndexFromElement(event.currentTarget); //assigning the index of the the editted item to itemIndex\n let updatedItem = STORE.items[itemIndex];\n updatedItem.name = event.currentTarget.innerHTML;\n $(event.currentTarget).blur(renderShoppingList())\n //renderShoppingList();\n });\n}",
"handleOList(){\n this.sliceString();\n var list = this.selection.split(/\\n/);\n var text = \"\";\n var i = 1;\n list.map(function(word){\n text = text + \" \" + i.toString() + \". \" + word + \"\\n\";\n i = i + 1;\n })\n this.post.value = this.beg + text + this.end;\n }",
"function MailListName_changeHandler(element) {\n if(!MailListName_isMailListNameValid(element.value)) {\n top.code.error_invalidElement(element, top.code.string_substitute(element.invalidMessage, \"[[VAR.invalidValue]]\", element.value));\n return false;\n }\n\n return true;\n}",
"function setAutocompleteListHandlers(list){\n \n // Handle clicking on an autocomplete list option\n \n $(list).find('button').on('click', function(event){\n \n selectAutocompleteOption(this);\n \n });\n \n // Handle clicking outside of time picker/field\n \n $(document).on('mousedown', function(event){\n \n if($(list).parent().has(event.target).length == 0){\n \n $(list).hide();\n \n }\n \n });\n \n}",
"function DDLightbarMenu_AddAdditionalSelectItemKeys(pAdditionalAddItemKeys)\n{\n\tthis.additionalSelectItemKeys += pAdditionalAddItemKeys;\n}",
"function inputElem_add_byKey(e) {\n\t\n}",
"function setOptions( e ) {\n\t\t\n\t\t\tif ( !e ) { e = window.event; }\n\t\t\n\t\t\tvar i,\n\t\t\t\tthisClicked = e.target.value;\n\t\t\t\n\t\t\tif ( thisClicked !== 0 ) {\n\t\t\t\t\t\n\t\t\t\tfor ( i = 0; i < this.options_list.length; i++ ) {\n\t\t\t\t\tthis.options_list_elements[i].style.display = \"none\";\n\t\t\t\t\t\n\t\t\t\t\tif ( thisClicked === this.options_list[i] ) {\n\t\t\t\t\t\tthis.options_list_elements[i].style.display = \"block\";\n\t\t\t\t\t}\t\t\t\t\n\t\t\t\t}\n\t\t\t}\t\t\t\n\t\t}",
"_handleFocus() {\n // Options can wind up getting focused in active descendant mode if the user clicks on them.\n // In this case, we push focus back to the parent listbox to prevent an extra tab stop when\n // the user performs a shift+tab.\n if (this.listbox.useActiveDescendant) {\n this.listbox._setActiveOption(this);\n this.listbox.focus();\n }\n }",
"onSuggestChange(event, o) {\n switch(o.method) {\n // this is necessary for the input to show each letter as its typed\n case 'type':\n this.setState({\n value: o.newValue\n });\n break;\n // one of the suggests was selected\n case 'click':\n let items = this.items;\n items.push({id: o.newValue.id, name: o.newValue.name});\n this.props.setModuleEditingPiece({items: items});\n // clear the input\n this.setState({\n value: ''\n });\n break;\n }\n }",
"keyupListener() {\n\t\tconst {value} = this;\n\t\tconst {keyCode} = event;\n\t\tif (this.pvalue === value) { return; }\n\t\tthis.updateCaret();\n\t\tthis.lastIndex = 0;\n\t\tconst head = value.substring(0, this.caret);\n\t\t_.forEach(Code.SEPARATORS, (separator) => {\n\t\t\tconst m = head.match(separator);\n\t\t\tif (!m) { return; }\n\t\t\tconst i = (m[1] || m[2]).length + m.index;\n\t\t\tif (this.caret < i) { return; }\n\t\t\tthis.lastIndex = _.max([i, this.lastIndex]);\n\t\t});\n\t\tthis.list.update(_.trim(value.substring(this.lastIndex, this.caret)), this.getCaretVisual(value));\n\n\t\tthis.files[this.path].value = value;\n\t\tthis.pvalue = value;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
displayShapes() When we press space bar, sets the central position of the ellipse and handles mouse and keys inputs to change size, colors and sound | displayShapes() {
// Displays shapes when the space bar is pressed
if (keyIsDown(32)) {
// If the central position of the shape is not given...
if (this.positionIsGiven === false) {
// Set it to the mouse position
this.x = mouseX;
this.y = mouseY;
// And change state so the central position stays the same as long as the space bar is pressed
this.positionIsGiven = true;
}
// If the central position is given...
else if (this.positionIsGiven === true) {
// Handle keys inputs to change the color of the stroke
this.changeColor();
// Play breath in sound when the width of the shape is increasing and oplay the breath out sound if the width is decreasing
this.handleSound();
// Change the size of the shape according to the mouse position
this.changeSize();
// Display the ellipse from the center, color the stroke with the rgb values and don't fill it
ellipseMode(CENTER);
stroke(this.red, this.green, this.blue);
noFill();
// Draw the ellipse
ellipse(this.x, this.y, this.width, this.height);
}
}
// If the space bar is released, change the state of positionIsGiven to false to be able to set a new position when we press space bar again
else {
this.positionIsGiven = false;
}
} | [
"function displayControls(){\n noStroke();\n fill(fgColor);\n text(\"left player: WASD. right player: Arrow keys.\", width/2, height-15);\n}",
"display() {\n push();\n fill(255,0,0);\n ellipse(this.x, this.y, this.size);\n pop();\n // if (x < 0 || x > width || y < 0 || y > height) {\n // var removed = obstacles.splice(this.index, 1);\n // }\n }",
"changeSize() {\n // Calculate the distance between the mouse and the center of the shape\n this.distanceFromCenterX = mouseX - this.x;\n this.distanceFromCenterY = mouseY - this.y;\n // Change width and height according to the mouse position\n this.width = 2 * (this.distanceFromCenterX);\n this.height = 2 * (this.distanceFromCenterY);\n }",
"function keyPressed() {\n if (keyCode == 32) {\n if (strokeToggle) {\n stroke(0);\n } else {\n noStroke();\n }\n strokeToggle = !strokeToggle;\n }\n if (keyCode == LEFT_ARROW) {\n circleSize = circleSize - 10;\n }\n if (keyCode == RIGHT_ARROW) {\n circleSize = circleSize + 10;\n }\n if (keyCode == UP_ARROW) {\n toggle++;\n toggle = toggle % 3;\n }\n if (keyCode == DOWN_ARROW) {\n toggle++;\n toggle = toggle % 3;\n }\n}",
"function drawclouds(){\n noStroke();\n ellipse(50,50,60,50);\n ellipse(80,40,60,50);\n ellipse(130,50,60,50);\n ellipse(70,70,60,50);\n ellipse(110,65,60,50);\n}",
"function draw2Dkeyboard()\n{\n imageMode(CORNER);\n image(keyboard, width/2 - 2.0*PPCM, height/2 - 1.0*PPCM, 4.0*PPCM, 3.0*PPCM);\n \n textFont(\"Arial\", 0.35*PPCM);\n textStyle(BOLD);\n fill(0);\n noStroke();\n text(\"S\" , width/2 - 1.32*PPCM, height/2 + 0.63*PPCM);\n textFont(\"Arial\", 0.25*PPCM);\n textStyle(NORMAL);\n text(\"Q\" , width/2 - 1.74*PPCM, height/2 + 0.10*PPCM);\n text(\"W\" , width/2 - 1.32*PPCM, height/2 + 0.10*PPCM);\n text(\"E\" , width/2 - 0.89*PPCM, height/2 + 0.10*PPCM);\n text(\"A\" , width/2 - 1.74*PPCM, height/2 + 0.60*PPCM);\n text(\"D\" , width/2 - 0.89*PPCM, height/2 + 0.60*PPCM);\n text(\"Z\" , width/2 - 1.74*PPCM, height/2 + 1.08*PPCM);\n text(\"X\" , width/2 - 1.32*PPCM, height/2 + 1.08*PPCM);\n text(\"C\" , width/2 - 0.89*PPCM, height/2 + 1.08*PPCM);\n \n textFont(\"Arial\", 0.35*PPCM);\n textStyle(BOLD);\n fill(0);\n noStroke();\n text(\"G\" , width/2 + 0.0*PPCM, height/2 + 0.63*PPCM);\n textFont(\"Arial\", 0.25*PPCM);\n textStyle(NORMAL);\n text(\"R\" , width/2 - 0.42*PPCM, height/2 + 0.10*PPCM);\n text(\"T\" , width/2 - 0*PPCM, height/2 + 0.10*PPCM);\n text(\"Y\" , width/2 + 0.42*PPCM, height/2 + 0.10*PPCM);\n text(\"H\" , width/2 + 0.42*PPCM, height/2 + 0.60*PPCM);\n text(\"F\" , width/2 - 0.44*PPCM, height/2 + 0.60*PPCM);\n text(\"V\" , width/2 - 0.42*PPCM, height/2 + 1.08*PPCM);\n text(\"B\" , width/2 - 0*PPCM, height/2 + 1.08*PPCM);\n text(\"N\" , width/2 + 0.42*PPCM, height/2 + 1.08*PPCM);\n \n textFont(\"Arial\", 0.35*PPCM);\n textStyle(BOLD);\n fill(0);\n noStroke();\n text(\"K\" , width/2 + 1.30*PPCM, height/2 + 0.63*PPCM);\n textFont(\"Arial\", 0.25*PPCM);\n textStyle(NORMAL);\n text(\"U\" , width/2 + 0.88*PPCM, height/2 + 0.10*PPCM);\n text(\"I\" , width/2 + 1.30*PPCM, height/2 + 0.10*PPCM);\n text(\"O\" , width/2 + 1.72*PPCM, height/2 + 0.10*PPCM);\n text(\"J\" , width/2 + 0.88*PPCM, height/2 + 0.60*PPCM);\n text(\"P\" , width/2 + 1.72*PPCM, height/2 + 0.60*PPCM);\n text(\"M\" , width/2 + 0.88*PPCM, height/2 + 1.08*PPCM);\n text(\"L\" , width/2 + 1.72*PPCM, height/2 + 1.08*PPCM);\n}",
"function drawControl_SS(ypos_in)\r\n{\r\n // draw the rectangle outline to stand out\r\n Hcontext.fillStyle = 'rgb(255,255,255)';\r\n //Hcontext.lineWidth = 12;\r\n Hcontext.fillRect(control_margin,ypos_in-320+326,button_width,65*4+33);\r\n \r\n // set up fonts\r\n Hcontext.fillStyle = 'rgb(0,0,0)';\r\n Hcontext.font = 'bold ' + (40.0).toString() + 'px '+fonttype;\r\n Hcontext.textAlign = 'center';\r\n // draw the main text\r\n Hcontext.fillText (\"Touch the\" , control_margin+(control_width-control_margin-2)/2, ypos_in-335+390);\r\n Hcontext.fillText (\"Screen to\" , control_margin+(control_width-control_margin-2)/2, ypos_in-335+455);\r\n Hcontext.fillText (\"Explore the\" , control_margin+(control_width-control_margin-2)/2, ypos_in+520-335);\r\n Hcontext.fillText (\"Tree of Life\" , control_margin+(control_width-control_margin-2)/2, ypos_in+585-335);\r\n \r\n \r\n Hcontext.fillStyle = 'rgb(0,0,0)';\r\n Hcontext.font = (18.0).toString() + 'px '+fonttype;\r\n Hcontext.textAlign = 'left';\r\n \r\n skipper = 22\r\n \r\n \r\n header_ypos = myHeader.height-450;\r\n \r\n \r\n temp_txt = [\" \",\r\n \"Each leaf respresents a species.\",\r\n \"Branches show evolutionary\",\r\n \"links between these species,\",\r\n \"connecting them to common\",\r\n \"ancestors. The colours\",\r\n \"show extinction risk.\",\r\n \" \",\r\n \"Pinch two fingers together\",\r\n \"or apart on the screen to\",\r\n \"zoom in and out and explore\",\r\n \"the tree like you would a map.\",\r\n \"You can also tap areas of\",\r\n \"the screen to zoom in there.\",\r\n \" \",\r\n \"For more information press\",\r\n \"the 'Introduction' button.\",\r\n \"Or just start exploring\",\r\n \"and experiment with the\",\r\n \"other buttons above.\"];\r\n \r\n \r\n for (var iii = 0 ; iii < temp_txt.length ; iii ++)\r\n {\r\n //Hcontext.fillText (temp_txt[iii] , control_margin+(control_width-control_margin-2)/2, header_ypos+skipper*iii);\r\n Hcontext.fillText (temp_txt[iii] , control_margin, header_ypos+skipper*iii);\r\n }\r\n \r\n \r\n \r\n \r\n}",
"function draw() {\n // Clear the background to black\n background(0);\n\n // Handle input for the tiger\n tiger.handleInput();\n lion.handleInput();\n // Move all the \"animals\"\n tiger.move();\n lion.move();\n antelope.move();\n zebra.move();\n bee.move();\n\n // Handle the tiger eating any of the prey\n tiger.handleEating(antelope);\n tiger.handleEating(zebra);\n tiger.handleEating(bee);\n\n lion.handleEating(antelope);\n lion.handleEating(zebra);\n lion.handleEating(bee);\n\n // Display all the \"animals\"\n tiger.display();\n lion.display();\n antelope.display();\n zebra.display();\n bee.display();\n}",
"function generateShibeShape() {\n const showShape = document.getElementById('shape-preview')\n\n $(document).ready(function() {\n $('#generate').on(\"click\", function(event) {\n event.preventDefault()\n inputSelectColor()\n inputSelectShape()\n fillWithShibe()\n showShape.style.display = \"block\"\n })\n })\n}",
"pushShapes(e) {\r\n const pointer = this.pointer;\r\n\r\n this.pointer.updateCoords(e);\r\n let nearbyShapes = this.pointer.nearbyShapes(this);\r\n nearbyShapes.forEach((shape) => {\r\n // Set new shape direction to opposite of pointer\r\n shape.direction = Math.atan2(shape.y - this.pointer.y, shape.x - this.pointer.x) * 180 / Math.PI;\r\n shape.step = 6;\r\n shape.draw();\r\n });\r\n }",
"function manage_morse() {\n\n\n morse.set_drawing_position()\n morse.detect_input()\n morse.display_background()\n morse.display_text()\n morse.display_dash_button()\n morse.display_dot_button()\n morse.display_led()\n morse.clear_drawing_position()\n}",
"function drawShapes() {\n\tfor (var i = 0; i < shapes.length; i++) {\n\t\tvar points = shapes[i];\n\t\tdrawFinishedShape(points);\n\t}\n}",
"function keyPressed() {\n\tif (keyCode == 32) {\n\t\t// reset canvas\n\t\tclear();\n\t\tcount = 0;\n\t\tbutton.hide(); \n\t\tparticleCount = 0;\n\t\t// load next image in paintings array\n\t\tpainting = loadImage(paintings[paintingCount]);\n\t\t// move on to next painting. Go back to first one if the last one is complete\n\t\tif (paintingCount == 4) {\n\t\t\tpaintingCount = 0;\n\t\t} else {\n\t\t\tpaintingCount++;\n\t\t}\n\t\t// fix the position\n\t\tif(isTranslate == true) {\n\t\t\ttranslate(0, 50);\n\t\t\tisTranslate = false;\n\t\t}\n\t\t// reload background and frame (because of the reset)\n\t\tbackground(bg);\n\t\timage(frame, 55, -65);\n\t\t// start next painting \n\t\tstart = true;\n\t}\n}",
"display() {\n this.scene.pushMatrix();\n this.spritesheet.activateShader();\n\n this.scene.translate(this.center_shift, 0, 0)\n\n for (let i = 0; i < this.text.length; i++) {\n this.spritesheet.activateCellp(this.getCharacterPosition(this.text.charAt(i)));\n this.rectangle.display();\n this.scene.translate(1, 0, 0);\n }\n\n this.scene.setActiveShaderSimple(this.scene.defaultShader);\n this.scene.popMatrix();\n }",
"function shapegroup3() {\n circle(-150, shapeY3, bgshapesize);\n ellipse(-50, shapeY3, 40, bgshapesize);\n rect(50, shapeY3, 30, bgshapesize);\n square(150, shapeY3, bgshapesize, 5);\n}",
"function drawbasiclayout()\n {\n points = []; // for storng title area points inorder\n linepoints = []; // for storing linegap points in discription area\n dispoints = []; // for storng title area points inorder\n\n // Initially titlearea and discriptionarea disabled\n titlekeyactive = false;\n diskeyactive = false;\n\n // Starting cursor positions for title and discription area\n pretitleposx = 0.25 * width;\n predisposx = 0.05 * width;\n pretitleposy = 0.7*0.1*height;\n predisposy = 0.3 * height;\n \n // Drawing Title , line and , Discription on each note \n ctx.clearRect(0,0,width,height);\n ctx.fillStyle = \"bisque\";\n ctx.fillRect(0,0,width,height);\n ctx.fillStyle = \"#141e30\";\n ctx.font = \"30px Pacifico\"; \n ctx.fillText(\"TITLE --\",4,0.7*0.1*height);\n ctx.beginPath();\n ctx.moveTo(0,0.12*height);\n ctx.lineTo(width,0.12*height);\n ctx.stroke();\n ctx.fillStyle='#141e30';\n ctx.font = \"30px Oleo Script\";\n ctx.fillText('DESCRIPTION' , 0.4*width , 0.17*height);\n }",
"show() {\n var pos = this.body.position;\n var angle = this.body.angle;\n\n push();\n translate(pos.x, pos.y);\n rotate(angle);\n rectMode(CENTER);\n\n drawSprite(this.birdspr);\n /* strokeWeight(1);\n stroke(255);\n fill(127);\n ellipse(0, 0, this.r * 2);\n line(0, 0, this.r, 0);*/\n pop();\n }",
"function expandedShape(){\n if(Object.keys(currentSelection).length > 2){\n noFill()\n stroke(\"rgba(\" + colors.red + \",\" + colors.green + \",\" + colors.blue + \",\" + vol + \")\")\n strokeWeight(3)\n beginShape();\n for(x in currentSelection){\n var sel = currentSelection[x]\n vertex(h+(h*sel[\"vert\"][0]*(fcount/4)), h+(h*sel[\"vert\"][1]*(fcount/4)))\n bezierVertex(h+(h*sel[\"vert\"][2]*(fcount/4)),h+(h*sel[\"vert\"][3]*(fcount/4)),\n h+(h*sel[\"vert\"][4]*(fcount/4)),h+(h*sel[\"vert\"][5]*(fcount/4)),\n h*sel[\"vert\"][6],h*sel[\"vert\"][7])\n }\n endShape(CLOSE);\n }\n}",
"function toggleShapes(){\n\tif (shapesOn) {\n\t\tshapesOn = false;\n\t} else {\n\t\tshapesOn = true;\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
9.Write a program that deletes a given element e from the array a. Input: e = 2, a = [4, 6, 2, 8, 2, 2] | function deleteElement(a, e) {
var newArray = [];
for (var i = 0; i < a.length; i++) {
if (a[i] !== e) {
newArray[newArray.length] = a[i];
} else {
continue;
}
}
return newArray;
} | [
"function remove(array, element) {\n const index = array.indexOf(element);\n var item = array.splice(index, 1);\n return item;\n}",
"removeItem (array, item, f) {\n const i = this.indexOf(array, item, f)\n if (i >= 0) array.splice(i, 1)\n }",
"function removeArray(array, index)\n{\n array.splice(index,1)\n}",
"function removeElement(nums, val) {\r\n let index = 0\r\n for (let i = 0; i < nums.length; i++) {\r\n if (nums[i] != val) {\r\n nums[index++] = nums[i]\r\n }\r\n }\r\n return index\r\n}",
"function arrayRemove(arr, value) { return arr.filter(function (ele) { return ele != value; }); }",
"remove(element) {\n this.set.splice(this.set.indexOf(element), 1);\n console.log(\"element removed successfully\");\n }",
"function delTable(table){\r\n\tvar size = tablearr.length;\r\n\tvar indice = -1;\r\n\tvar pos = 0;\r\n\tvar found = false;\r\n\t\r\n\tif (size > 0){\r\n\t\twhile (found == false && pos < size){\r\n\t\t\tif (tablearr[pos] == table){\r\n\t\t\t\tfound = true;\r\n\t\t\t\tindice = pos;\t\r\n\t\t\t}else{\r\n\t\t\t\tpos = pos + 1;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (found){\r\n\t\ttablearr.splice(indice, 1) //borra a partir de la posicion indice 1 elemento\r\n\t}\r\n}",
"function removeSmallest(arr) {\n\tconst a = arr.splice(arr.indexOf(Math.min(...arr)), 1);\t\n\treturn arr.filter(x => x !== a);\n}",
"function remove_note(e, i){\n \n e.parentNode.parentNode.removeChild(e.parentNode);\n const task=localStorage.getItem(\"array\");\n const note=JSON.parse(task);\n note.splice(i, 1);\n localStorage.setItem('array',JSON.stringify(note));\n location.reload();\n }",
"eraseEvent(state, num) {\n state.events.splice(num, 1);\n\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}",
"function deleteNth(arr) {\n\n return [];\n}",
"function deleteToDo(position){\r\ntoDos.splice(position, 1);\r\ndisplayToDos();\r\n}",
"function spliceMethod() {\n\tvar a=['man', 'animan', 1, 2, \"This is a statement\", 0.505, null, NaN];\n\tvar b=a.splice(1,2,'parrot', 1, 3, null);\n\tconsole.log(b);\t\n}",
"function deleteObject(array,index){\n delete(array[index]);\n array.splice(index, 1);\n}",
"function gemSplice(){\n // Remove array gemNum item i\n gemNum.splice(i, 1);\n // Console log updated array\n //(\"Gem Array Updated: \" +gemNum); \n }",
"function deleteFromMPO(product) {\n //Search for the index of the product in the array\n let index = singleProducts.indexOf(product);\n\n let input = document.querySelector(`.mijn-producten-label${product.id}`).querySelector('input');\n input.checked = false;\n input.classList.remove('added');\n //Remove product\n singleProducts.splice(index, 1)\n computeMPOProducts();\n updateCounter();\n}",
"function removeVals(arr,start,end) {\n var temp=end-1;\n arr.splice(start,temp);\n return arr;\n }",
"removeEntry(t) {\n const e = this.docs.get(t);\n e && (this.docs = this.docs.remove(t), this.size -= e.size);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
main function to retrieve, format, and send cgm data | function fetchCgmData(lastReadTime, lastBG) {
// declare local constants for time differences
var TIME_5_MINS = 5 * 60 * 1000,
TIME_10_MINS = 10 * 60 * 1000,
TIME_15_MINS = 15 * 60 * 1000,
TIME_30_MINS = TIME_15_MINS * 2;
// declare local constants for arrow trends
var NO_ARROW = 0,
DOUBLE_UP = 1,
SINGLE_UP = 2,
FORTYFIVE_UP = 3,
FLAT_ARROW = 4,
FORTYFIVE_DOWN = 5,
SINGLE_DOWN = 6,
DOUBLE_DOWN = 7,
NOT_COMPUTABLE = 8,
RATE_OUT_OF_RANGE = 9,
LOGO = 10;
// hard code name of T1D person, for now
var NameofT1DPerson = "";
// declare local variables for message data
var response, message;
//call options & started to get endpoint & start time
var opts = options( );
var started = new Date( ).getTime( );
//if endpoint is invalid, return error msg to watch
if (!opts.endpoint) {
message = {
icon: [0,LOGO],
bg: '---',
readtime: timeago(new Date().getTime() - started),
alert: 0,
time: formatDate(new Date()),
delta: 'CHECK ENDPOINT',
battlevel: "",
t1dname: ""
};
console.log("sending message", JSON.stringify(message));
MessageQueue.sendAppMessage(message);
return;
}
// call XML
var req = new XMLHttpRequest();
//console.log('endpoint: ' + opts.endpoint);
// get cgm data
req.open('GET', opts.endpoint, true);
req.onload = function(e) {
if (req.readyState == 4) {
if(req.status == 200) {
// Load response
response = JSON.parse(req.responseText);
response = response.bgs;
// check response data
if (response && response.length > 0) {
// response data is good; send log with response
console.log('got response', JSON.stringify(response));
// see if we're in a Rajat build
var RajatBuild = isRajatBuild(opts.endpoint, "heroku");
if (RajatBuild) {
// set Rajat arrow constants
DOUBLE_UP = 0;
SINGLE_UP = 1;
FORTYFIVE_UP = 2;
FLAT_ARROW = 3;
NO_ARROW = 4;
}
// initialize message data
var now = new Date().getTime(),
sinceLastAlert = now - lastAlert,
alertValue = 0,
currentBG = response[0].sgv,
currentBGDelta = response[0].bgdelta,
currentTrend = response[0].trend,
delta = (currentBGDelta > 0 ? '+' : '') + currentBGDelta + " mmol",
readingtime = new Date(response[0].datetime).getTime(),
readago = now - readingtime,
// battery not included in response yet, so have to send no battery for now
// once battery is included, uncomment out line and erase "111" line
//currentBattery = response[0].battery;
currentBattery = "111";
// see if we're in a Rajat build
var RajatBuild = isRajatBuild(opts.endpoint, "heroku");
if (RajatBuild) {
// set Rajat arrow constants
DOUBLE_UP = 0;
SINGLE_UP = 1;
FORTYFIVE_UP = 2;
FLAT_ARROW = 3;
NO_ARROW = 4;
delta = (currentBGDelta > 0 ? '+' : '') + (currentBGDelta/ 18.01559).toFixed(1) + " mmol";
// can't read battery so set to 111 to indicate Rajat build
currentBattery = "111";
}
// debug logs; uncomment when need to debug something
//console.log("now: " + now);
//console.log("sinceLastAlert: " + sinceLastAlert);
//console.log("current BG: " + currentBG);
//console.log("current BG delta: " + currentBGDelta);
//console.log("arrow: " + currentTrend);
//console.log('RajatBuild?: ' + RajatBuild);
//console.log("readingtime: " + readingtime);
//console.log("readago: " + readago);
//console.log("current Battery: " + currentBattery);
// set vibration pattern; alert value; 0 nothing, 1 normal, 2 low, 3 high
if (currentBG < 2) {
if (sinceLastAlert > TIME_10_MINS) alertValue = 2;
} else if (currentBG < 3)
alertValue = 2;
else if (currentBG < 3.5 && currentBGDelta < 0)
alertValue = 2;
else if (currentBG < 4 && sinceLastAlert > TIME_15_MINS)
alertValue = 2;
else if (currentBG < 6.5 && currentTrend == DOUBLE_DOWN && sinceLastAlert > TIME_5_MINS)
alertValue = 2;
else if (currentBG == 5.5 && currentTrend == FLAT_ARROW && sinceLastAlert > TIME_15_MINS) //Perfect Score - a good time to take a picture :)
alertValue = 1;
else if (currentBG > 6.5 && currentTrend == DOUBLE_UP && sinceLastAlert > TIME_15_MINS)
alertValue = 3;
else if (currentBG > 10 && sinceLastAlert > TIME_30_MINS && currentBGDelta > 0)
alertValue = 3;
else if (currentBG > 14 && sinceLastAlert > TIME_30_MINS)
alertValue = 3;
else if (currentBG > 17 && sinceLastAlert > TIME_15_MINS)
alertValue = 3;
if (alertValue === 0 && readago > TIME_10_MINS && sinceLastAlert > TIME_15_MINS) {
alertValue = 1;
}
if (alertValue > 0) {
lastAlert = now;
}
// load message data
message = {
icon: [RajatBuild,currentTrend],
bg: currentBG,
readtime: timeago(new Date().getTime() - (new Date(response[0].datetime).getTime())),
alert: alertValue,
time: formatDate(new Date()),
delta: delta,
battlevel: currentBattery,
t1dname: NameofT1DPerson
};
// send message data to log and to watch
console.log("message: " + JSON.stringify(message));
MessageQueue.sendAppMessage(message);
// response data is no good; format error message and send to watch
} else {
message = {
icon: [0,LOGO],
bg: '---',
readtime: timeago(new Date().getTime() - (now)),
alert: 1,
time: formatDate(new Date()),
delta: 'DATA OFFLINE',
battlevel: "",
t1dname: ""
};
console.log("sending message", JSON.stringify(message));
MessageQueue.sendAppMessage(message);
}
}
}
};
req.send(null);
} | [
"function parserWebserverClientData(data) {\n let rx = JSON.parse(data);\n let protocolData = {\n cmdtype: rx.cmdtype,\n cmdData: rx.cmdData\n };\n if (protocolData.cmdtype == \"SensorDataNow\") {\n writeSensorDataNow2WebserverClient();\n }\n else if (protocolData.cmdtype == \"lightOn\") {\n ControllBleLight(\"lightOn\");\n writeLightControlNow2WebserverClient(\"lightOn\", \"ok\");\n }\n //code here for webserver request\n}",
"parse(data) {\n // Check the `data`\n let buf = null;\n if (typeof (data) === 'string') {\n data = data.toLowerCase();\n if (/^[a-f0-9]+$/.test(data) === false || data.length === 0 || data.length % 2 !== 0) {\n return { error: new Error('The `data` must be hexadecimal representation.') };\n }\n let byte_list = [];\n for (let i = 0; i < data.length; i += 2) {\n let h = data.substring(i, i + 2);\n let n = parseInt(h, 16);\n byte_list.push(n);\n }\n buf = Buffer.from(byte_list);\n } else if (Buffer.isBuffer(data)) {\n if (data.length === 0) {\n return { error: new Error('The `data` must be a non-empty data.') };\n }\n buf = data;\n } else {\n return { error: new Error('The `data` must be a string or an Buffer object.') };\n }\n\n // Parse the data\n let details = null;\n try {\n details = this._parseDetails(buf);\n } catch (e) {\n return { error: e };\n }\n\n // Compose the response\n let res = {};\n\n let smsc = null;\n if (details.sca.digit > 0) {\n smsc = details.sca.address;\n if (details.sca.international) {\n smsc = '+' + smsc;\n }\n }\n res.smsc = smsc;\n\n if (details.pduType.mti === 0) {\n res.type = 'SMS-DELIVER';\n\n if (details.oa && details.oa.digit > 0) {\n let val = details.oa.address;\n if (details.oa.international) {\n val = '+' + val;\n }\n res.origination = val;\n } else {\n res.origination = null;\n }\n\n if (details.scts) {\n res.timestamp = details.scts;\n } else {\n res.timestamp = null;\n }\n\n } else if (details.pduType.mti === 1) {\n res.type = 'SMS-SUBMIT';\n\n res.reference = details.mr;\n\n if (details.da && details.da.digit > 0) {\n let val = details.da.address;\n if (details.da.international) {\n val = '+' + val;\n }\n res.destination = val;\n } else {\n res.destination = null;\n }\n\n if (details.vp) {\n res.period = details.vp.period + details.vp.unit;\n } else {\n res.period = null;\n }\n } else {\n return { error: new Error('Unknown PDU Type: MTI=' + details.pduType.mti) };\n }\n\n if (details.ud.udh) {\n res.concat = {\n reference: details.ud.udh.reference,\n total: details.ud.udh.total,\n sequence: details.ud.udh.sequence\n };\n } else {\n res.concat = null;\n }\n\n if (details.ud.text) {\n res.text = details.ud.text;\n } else {\n res.text = null;\n }\n\n res.details = details;\n return res;\n }",
"function GetAdmDomainTypeCCLRequestWrapper(criterion) {\n var adm_domain_type = \"UNDEFINED\";\n var sendAr= [];\n\t\n var get_adm_domain_type_by_encounter_id_request = new Object();\n get_adm_domain_type_by_encounter_id_request.qualifiers = new Object();\n get_adm_domain_type_by_encounter_id_request.qualifiers.encounter_id = criterion.encntr_id + \".0\";\n\n var json_object = new Object();\n json_object.get_adm_domain_type_by_encounter_id_request = get_adm_domain_type_by_encounter_id_request;\n\n var json_request = JSON.stringify(json_object);\n\n sendAr.push(\"^MINE^\", \"^GET_ADM_DOMAIN_DETAILS^\", \"^\" + json_request + \"^\");\n\t\t\t\n var info = new XMLCclRequest();\n info.onreadystatechange = function () {\n //4 is completed and 200 is success\n if (info.readyState == 4 && info.status == 200) {\n try {\n var jsonEval = JSON.parse(info.responseText);\n var recordData = jsonEval.RECORD_DATA;\n if (recordData.STATUS_DATA.STATUS == \"S\") {\t\n adm_domain_type = jsonEval.RECORD_DATA.REPLY_DATA.ADM_TYPE_FLAG;\t\n }\n } catch (err) { \n } finally {\n }\n } \n }\n //do a synchronized call to ccl script \n\t//because need to wait on the result before rendering mPage\n info.open('GET', \"ADM_ADAPTER_CCL_DRIVER\",0);\n info.send(sendAr.join(\",\"));\n\t\n\t//what if the value returned is not 0,1 or 2?\n\tif(adm_domain_type == \"UNDEFINED\" || adm_domain_type ==\"undefined\"){\n\t\treturn -1;//unknown adm_domain_type\n\t}\n\n return adm_domain_type;\n}",
"function parserBleClientData(data) {\n let rx = JSON.parse(data);\n let protocolData = {\n cmdtype: rx.cmdtype,\n cmdData: rx.cmdData\n };\n if (protocolData.cmdtype == 'SensorHT') {\n let content = protocolData.cmdData.toString().split(\";\");\n temperature = parseInt(content[0]);\n humidity = parseInt(content[1]);\n console.log((new Date().toLocaleString()));\n console.log('temperature:' + temperature.toString(10));\n console.log('humidity:' + humidity.toString(10));\n write2BleClient('replyOK', 'ok');\n //codeing for saving data to database and updating sensor status here\n }\n else if (protocolData.cmdtype == 'SensorPIR') {\n let content = protocolData.cmdData.toString().split(\";\");\n pirValue = parseInt(content[0]);\n console.log((new Date().toLocaleString()));\n console.log('PIR:' + pirValue);\n write2BleClient('replyOK', 'ok');\n //codeing for saving data to database and updating sensor status here\n }\n}",
"function Comic(comicRawData) {\n}",
"function buildSyncMessage()\n{\n // Get a reference to our paddle.\n var thePaddle = getOurPaddle();\n\n // Get a reference to the ball.\n var theBall = getOurBall();\n\n // Extract the salient details for each brick from the bricks objects container and\n // convert it to an array of tuples. Each tuple carries the ID, \n // current collision count, color, and location X/Y for each brick.\n var aryBrickSummaries = [];\n\n var aryBricks = objects['bricks'].objects;\n\n aryBrickSummaries.forEach(\n function (brick)\n {\n aryBrickSummaries.push(\n {\n id: brick.id,\n collsion_count: brick.collsionCount,\n x: brick.mesh.x,\n y: brick.mesh.y,\n color: brick.color\n });\n });\n\n var syncMsg = {\n // The master flag status.\n master_flag: g_i_am_master_flag ? 'Y' : 'N',\n // Our paddle X/Y location.\n paddleLocXY:\n {\n x: thePaddle.mesh.x,\n y: thePaddle.mesh.y\n },\n // The ball X/Y location, velocity X/Y, and radius.\n ballDetails:\n {\n x: theBall.mesh.x,\n y: theBall.mesh.y,\n vel_x: theBall.velX,\n vel_y: theBall.velY,\n radius: theBall.radius\n },\n // The bricks summary map.\n bricks: aryBrickSummaries,\n\n // The current score\n scoreDetails:\n {\n player_1: gPlayerScore1,\n player_2: gPlayerScore2\n }\n \n } // syncMsg\n\n return syncMsg;\n}",
"_send(type, data) {\n this._midiOutput.send(type, _.extend(data, { channel: this._midiChannel } )); \n }",
"function mitecall(data, config, callback) {\n var thisoptions = options;\n thisoptions.headers['User-Agent'] = pack.name + \"/\" + pack.version;\n thisoptions[\"path\"] = data.path;\n \n if (data.key == \"source\") {\n thisoptions[\"host\"] = config.source.host;\n thisoptions.headers[\"X-MiteApiKey\"] = config.source.apikey;\n \n console.log(thisoptions);\n \n var req = https.request(thisoptions, function(res)\n {\n var output = '';\n console.log(thisoptions.host + ':' + res.statusCode);\n res.setEncoding('utf8');\n\n res.on('data', function (chunk) {\n output += chunk;\n });\n\n res.on('end', function() {\n parseString(output, function (err, result) {\n callback(JSON.stringify(result));\n });\n });\n });\n \n req.on('error', function(err) {\n console.log(err.message);\n //res.send('error: ' + err.message);\n });\n\n req.end();\n } else {\n console.log(data.key);\n }\n \n}",
"returnData(data) {\n EnigmailLog.DEBUG(\n \"mimeVerify.jsm: returnData: \" + data.length + \" bytes\\n\"\n );\n\n let m = data.match(/^(content-type: +)([\\w/]+)/im);\n if (m && m.length >= 3) {\n let contentType = m[2];\n if (contentType.search(/^text/i) === 0) {\n // add multipart/mixed boundary to work around TB bug (empty forwarded message)\n let bound = EnigmailMime.createBoundary();\n data =\n 'Content-Type: multipart/mixed; boundary=\"' +\n bound +\n '\"\\n' +\n \"Content-Disposition: inline\\n\\n--\" +\n bound +\n \"\\n\" +\n data +\n \"\\n--\" +\n bound +\n \"--\\n\";\n }\n }\n\n this.mimeSvc.outputDecryptedData(data, data.length);\n }",
"_feed(chars) {\n\n var delimiter_pos;\n this._buffer = Buffer.concat([this._buffer, chars]);\n\n while((delimiter_pos = this._buffer.indexOf(DELIMITER)) != -1) {\n // Read until delimiter\n var buff = this._buffer.slice(0, delimiter_pos);\n this._buffer = this._buffer.slice(delimiter_pos + 1);\n\n // Check data are json\n var data = null;\n try {\n data = JSON.parse(buff.toString());\n } catch(e) {\n log.info(\"Bad data, not json\", buff, \"<raw>\", buff.toString(), \"</raw>\");\n continue;\n }\n\n // Send to client\n if(data)\n this.emit(\"transport_message\", data).catch(log.error);\n }\n }",
"function gmToBuffer (data) {\n return new Promise((resolve, reject) => {\n data.stream((err, stdout, stderr) => {\n if (err) { return reject(err) }\n const chunks = []\n stdout.on('data', (chunk) => { chunks.push(chunk) })\n // these are 'once' because they can and do fire multiple times for multiple errors,\n // but this is a promise so you'll have to deal with them one at a time\n stdout.once('end', () => { resolve(Buffer.concat(chunks)) })\n stderr.once('data', (data) => { reject(String(data)) })\n })\n })\n}",
"function process_message_from_monitor(mtype,mvalue){\n if (mtype==\"connected\"){\n console.log(\"Monitor connected\");\n } else if(mtype==\"start_experiment\"){\n var tiempo = new Date().getTime();\n insertRecord_js(\"timeMarks\",\"timeStamp, name\",` '${tiempo}', 'start_exp' `);\n } else if(mtype==\"time_marks\"){\n var tiempo_server = new Date().getTime();\n insertRecord_js(\"timeMarks\",\"timeStamp,timeStampLocal, name\",` '${tiempo_server}', '${mvalue}', 'stamp' `);\n } else if(mtype==\"update_game_vars\"){\n console.log(\"updating_game_vars\");\n load_game_parameters();\n } else {\n console.log(\"Type of Messsage from Monitor not recognised: \" + mtype);\n }\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 }",
"function generateXML(){\n\t\t\t\tconsole.log(\"###### FUNCTION generateXML START\");\n\t\t\t\tvar xml2Send = '';\n\t\t\t\txml2Send += '<?xml version=\"1.0\" encoding=\"UTF-8\"?><simpledc xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dct=\"http://purl.org/dc/terms/\" xmlns:geonet=\"http://www.fao.org/geonetwork\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://purl.org/dc/elements/1.1/ http://dublincore.org/schemas/xmls/qdc/2006/01/06/simpledc.xsd http://purl.org/dc/terms/ http://dublincore.org/schemas/xmls/qdc/2006/01/06/dcterms.xsd\">';\n\t\t\t\txml2Send += '<dc:identifier>' + $scope.metadata.identifier + '</dc:identifier>';\n\t\t\t\txml2Send += '<dc:title>' + $scope.metadata.title + '</dc:title>';\n\t\t\t\tif($scope.metadata.alttitle){\n\t\t\t\t\txml2Send += '<dct:alternative>' + $scope.metadata.alttitle + '</dct:alternative>';\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\txml2Send += '<dct:alternative></dct:alternative>';\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t$scope.metadata.pubdate = $filter('date')($scope.metadata.pubdate, \"yyyy-MM-dd\");\n\t\t\t\tif($scope.metadata.pubdate){\n\t\t\t\t\txml2Send += '<dct:dateSubmitted>' + $scope.metadata.pubdate + '</dct:dateSubmitted>';\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\txml2Send += '<dct:dateSubmitted></dct:dateSubmitted>';\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t$scope.metadata.date = $filter('date')($scope.metadata.date, \"yyyy-MM-dd\");\n\t\t\t\txml2Send += '<dc:created>' + $scope.metadata.date + '</dc:created>';\n\t\t\t\tif($scope.metadata.dataidentifier){\n\t\t\t\t\txml2Send += '<dc:identifier>' + $scope.metadata.dataidentifier + '</dc:identifier>';\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\txml2Send += '<dc:identifier></dc:identifier>';\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\txml2Send += '<dc:description>' + $scope.metadata.abstract + '</dc:description>';\n\t\t\t\txml2Send += '<dc:creator>' + $scope.metadata.contact + ';' + $scope.metadata.email + '</dc:creator>';\n\t\t\t\tif ($scope.metadata.keywords) {\n\t\t\t\t\tvar keywordsString = $scope.metadata.keywords.toString();\n\t\t\t\t\tvar keywords = keywordsString.split(\",\");\n\t\t\t\t\t$.each(keywords, function (i) {\n\t\t\t\t\t\txml2Send += '<dc:subject>' + keywords[i] + '</dc:subject>';\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\txml2Send += '<dc:subject>' + $scope.metadata.keywords + '</dc:subject>';\n\t\t\t\t}\n\t\t\t\txml2Send += '<dc:type>' + $scope.metadata.theme + '</dc:type>';\n\t\t\t\tif($scope.metadata.accessuse){\n\t\t\t\t\txml2Send += '<dc:rights>' + $scope.metadata.accessuse + '</dc:rights>';\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\txml2Send += '<dc:rights></dc:rights>';\n\t\t\t\t}\n\t\t\t\tif($scope.metadata.publicaccess){\n\t\t\t\t\txml2Send += '<dct:accessRights>' + $scope.metadata.publicaccess + '</dct:accessRights>';\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\txml2Send += '<dct:accessRights></dct:accessRights>';\n\t\t\t\t}\n\t\t\t\txml2Send += '<dc:language>' + $scope.metadata.language.name + '</dc:language>';\n\t\t\t\txml2Send += '<dc:coverage>North ' + $scope.geolocation.bounds[3] + ',South ' + $scope.geolocation.bounds[1] + ',East ' + $scope.geolocation.bounds[2] + ',West ' + $scope.geolocation.bounds[0] + '. (Global)</dc:coverage>';\n\t\t\t\txml2Send += '<dc:format>' + $scope.metadata.format + '</dc:format>';\n\t\t\t\tif ($scope.metadata.url) {\n\t\t\t\t\tvar urlsString = $scope.metadata.url.toString();\n\t\t\t\t\tvar urls = urlsString.split(\",\");\n\t\t\t\t\t$.each(urls, function (i) {\n\t\t\t\t\t\txml2Send += '<dct:references>' + urls[i] + '</dct:references>';\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\txml2Send += '<dct:references>' + $scope.metadata.url + '</dct:references>';\n\t\t\t\t}\n\t\t\t\txml2Send += '<dc:source>' + $scope.metadata.lineage + '</dc:source>';\n\t\t\t\txml2Send += '</simpledc>';\n\t\t\t\tconsole.log(\"###### FUNCTION generateXML END\");\n\t\t\t\tconsole.log(\"###### FUNCTION generateXML RESULT: \" + xml2Send);\n\t\t\t\treturn xml2Send;\n\t\t\t}",
"downloadCid(cid) {\n let ic = this.icn3d,\n me = ic.icn3dui\n let thisClass = this\n\n let uri =\n 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/' +\n cid +\n '/record/SDF/?record_type=3d&response_type=display'\n\n ic.ParserUtilsCls.setYourNote('PubChem CID ' + cid + ' in iCn3D')\n\n ic.bCid = true\n\n $.ajax({\n url: uri,\n dataType: 'text',\n cache: true,\n tryCount: 0,\n retryLimit: 1,\n beforeSend: function () {\n ic.ParserUtilsCls.showLoading()\n },\n complete: function () {\n //ic.ParserUtilsCls.hideLoading();\n },\n success: function (data) {\n let bResult = thisClass.loadSdfAtomData(data, cid)\n\n // ic.opts['pk'] = 'atom';\n // ic.opts['chemicals'] = 'ball and stick';\n\n if (me.cfg.align === undefined && Object.keys(ic.structures).length == 1) {\n $('#' + ic.pre + 'alternateWrapper').hide()\n }\n\n if (!bResult) {\n alert('The SDF of CID ' + cid + ' has the wrong format...')\n } else {\n ic.setStyleCls.setAtomStyleByOptions(ic.opts)\n ic.setColorCls.setColorByOptions(ic.opts, ic.atoms)\n\n ic.ParserUtilsCls.renderStructure()\n\n if (me.cfg.rotate !== undefined) ic.resizeCanvasCls.rotStruc(me.cfg.rotate, true)\n\n //if(me.deferred !== undefined) me.deferred.resolve(); if(ic.deferred2 !== undefined) ic.deferred2.resolve();\n }\n },\n error: function (xhr, textStatus, errorThrown) {\n this.tryCount++\n if (this.tryCount <= this.retryLimit) {\n //try again\n $.ajax(this)\n return\n }\n return\n },\n }).fail(function () {\n alert('This CID may not have 3D structure...')\n })\n }",
"function sendData (client, method, data) {\n\t\tvar packet = { methodName : method, data : data };\n\t\t\n\t\tclient.fn.send(\"PROJECT\", packet);\n\t}",
"async function parentProcessMessage (m) {\n if (m.type == \"config\") {\n main = m.config;\n for (i in children) children[i].send(m);\n } else if (m.type == \"CS\") {\n parseControl(m.data);\n } else if (m.type == \"activeLink\" && main != null && main.sock != null) {\n main.sock.activeLink = m.activeLink;\n } else if (m.type == \"QUIT\") {\n stop();\n process.exit(1);\n } else if (m.type == \"STOP\") {\n console.log(\"Transfer Stop Called\");\n stop();\n }\n}",
"fromQR(qr) {\r\n\r\n // Check the type of the parameter: string, String or UInt8Array\r\n\r\n // Convert to string\r\n\r\n // The QR should start with the context identifier: \"HC1:\"\r\n if (!qr.startsWith(\"HC1:\")) {\r\n // Raise an exception\r\n }\r\n\r\n // Decode from Base45\r\n let coseDeflated = decodeB45(qr.slice(4)) // Skip the context identifier\r\n\r\n // Decompress (inflate) from zlib-compressed\r\n let coseEU = pako.inflate(coseDeflated)\r\n\r\n // Decode the first layer of CVD COSE\r\n let c = new COSE(coseEU)\r\n let cvd_layer1 = c.decode()\r\n\r\n // We should have an array with 4 elements: protected, unprotected, payload and signature\r\n console.log(\"CVD first layer:\", cvd_layer1)\r\n if (cvd_layer1.length != 4) {\r\n // ERROR: raise an exception\r\n }\r\n\r\n // Decode the payload which is a CBOR object\r\n let payload = new COSE(cvd_layer1[2])\r\n payload = payload.cbor2json()\r\n\r\n // Check that is is well-formed: a CBOR Map with 4 elements\r\n // key 1: \"iss\", CBOR type 2 (bstr). Issuer Country Code\r\n // key 6: \"iat\", CBOR type 2 (bstr). Issuance date\r\n // key 4: \"exp\", CBOR type 2 (bstr). Expiration date\r\n // key -260: \"hcert\", CBOR type 5 (map). CVD data depending on the type\r\n if (payload.size != 4) {\r\n // ERROR: raise an exception\r\n }\r\n\r\n // Get the Issuer\r\n let iss = payload.get(1)\r\n console.log(\"Issuer:\", iss)\r\n if (!iss) {\r\n //ERROR: \r\n }\r\n\r\n // Get the Issuance date\r\n let iat = payload.get(6)\r\n console.log(\"Issuance date:\", iat)\r\n\r\n // Get the Expiration date\r\n let exp = payload.get(4)\r\n console.log(\"Issuance date:\", exp)\r\n\r\n // Get the hcert, the envelope for the certificate data\r\n let hcert = payload.get(-260)\r\n console.log(\"Hcert:\", hcert)\r\n\r\n let p = payload\r\n\r\n\r\n return p\r\n\r\n\r\n }",
"function add_google_contact_create_xml_from_vcard(hcard) {\n var i;\n var full_address;\n var email;\n var tel;\n var url;\n var xml = \"\";\n\n xml += \"<atom:entry xmlns:atom='http://www.w3.org/2005/Atom' xmlns:gd='http://schemas.google.com/g/2005'>\" + \"\\n\";\n xml += \" <atom:category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/contact/2008#contact' />\" + \"\\n\";\n\n //Parse name\n xml += \" <atom:title type='text'>\" + hcard.fn + \"</atom:title> \" + \"\\n\";\n\n xml += \" <atom:content type='text'>Notes</atom:content>\" + \"\\n\";\n\n if (hcard.email) {\n for (i = 0; i < hcard.email.length; i++) {\n email = hcard.email[i];\n\n type = 'home';\n if (email.type && email.type[0] == 'work') {\n type = 'work';\n }\n\n xml += \" <gd:email rel='http://schemas.google.com/g/2005#\" + type + \"' address='\" + email.value + \"' />\" + \"\\n\";\n }\n }\n\n\n if (hcard.tel) {\n for (i = 0; i < hcard.tel.length; i++) {\n tel = hcard.tel[i];\n\n type = 'home';\n if (tel.type && tel.type[0] == 'work') {\n type = 'work';\n }\n xml += \" <gd:phoneNumber rel='http://schemas.google.com/g/2005#\" + type + \"'>\" + tel.value + \"</gd:phoneNumber>\" + \"\\n\";\n }\n }\n\n // Not yet implemented :(\n if (hcard.url) {\n for (i = 0; i < hcard.url.length; i++) {\n /*\n url = hcard.url[i];\n if ('xmpp:' == url.substring(0, 5)) {\n xml += \" <gd:im address='\" + url.substring(5) + \"' protocol='http://schemas.google.com/g/2005#GOOGLE_TALK' rel='http://schemas.google.com/g/2005#home' />\" + \"\\n\";\n }\n */\n\n\n /** @todo If I ever find the way to tell google about the right bit of api */\n /*\n if ('aim:goim?screenname=' == url.substring(0, 20)) {\n //xml += \" <gd:im address='\" + url + \"' protocol='http://schemas.google.com/g/2005#GOOGLE_TALK' rel='http://schemas.google.com/g/2005#home' />\" + \"\\n\";\n }\n if ('ymsgr:sendIM?' == url.substring(0, 13)) {\n //xml += \" <gd:im address='\" + url + \"' protocol='http://schemas.google.com/g/2005#GOOGLE_TALK' rel='http://schemas.google.com/g/2005#home' />\" + \"\\n\";\n }\n */\n }\n }\n\n if (hcard.adr) {\n for (i = 0; i < hcard.adr.length; i++) {\n adr = hcard.adr[i];\n full_address = \"\";\n if (adr[\"street-address\"]) {\n full_address += adr[\"street-address\"] + \" \";\n }\n\n if (adr[\"locality\"]) {\n full_address += adr[\"locality\"] + \" \";\n }\n\n if (adr[\"region\"]) {\n full_address += adr[\"region\"] + \" \";\n }\n\n if (adr[\"postal-code\"]) {\n full_address += adr[\"postal-code\"] + \" \";\n }\n\n if (adr[\"country-name\"]) {\n full_address += adr[\"country-name\"] + \" \";\n }\n\n if (full_address != \"\") {\n xml += \" <gd:postalAddress rel='http://schemas.google.com/g/2005#work'>\" + full_address + \"</gd:postalAddress>\" + \"\\n\";\n }\n }\n }\n\n\n xml += \"</atom:entry>\" + \"\\n\";\n\n return xml;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Listener for debug mode: Saves variables to storage when the extension window is closed (this means the browser can be left open). | function addDebugListener() {
chrome.windows.onRemoved.addListener(winId => {
if (winId == windowId) {
chrome.storage.sync.set({
dailyCounts: dailyCounts,
lastUse: lastUse,
todayCount: todayCount
});
}
});
} | [
"function deactivate() {\n // this method is called when your extension is deactivated\n}",
"function saveUrlsOnWindowClosing(windowId) {\n chrome.storage.local.set({\"saved-urls\": urls}, null);\n}",
"function onClosed() {\n\t// dereference the window\n\t// for multiple windows store them in an array\n\tmainWindow = null;\n}",
"function DebugController($scope, $localStorage)\n{\n $scope.debugEnabled = angular.isDefined($localStorage.debugEnabled);\n}",
"function saveSettings(){\n localStorage[\"pweGameServerStatus\"] = gameselection;\n //console.log('saved: ' + gameselection);\n}",
"function deleteExtensionStorage() {\n var deleteStorageContent = document.getElementById(\"deleteExtStorage\");\n deleteExtStorage.addEventListener(\"click\", function() {\n chrome.storage.local.clear();\n location.reload();\n });\n}",
"saveWindowState () {\n clearTimeout(this.mailboxWindowSaver)\n this.mailboxWindowSaver = setTimeout(() => {\n const state = {\n fullscreen: this.mailboxWindow.isFullScreen(),\n maximized: this.mailboxWindow.isMaximized()\n }\n if (!this.mailboxWindow.isMaximized() && !this.mailboxWindow.isMinimized()) {\n const position = this.mailboxWindow.getPosition()\n const size = this.mailboxWindow.getSize()\n state.x = position[0]\n state.y = position[1]\n state.width = size[0]\n state.height = size[1]\n }\n\n this.localStorage.setItem('mailbox_window_state', JSON.stringify(state))\n }, 2000)\n }",
"function addDarkModeListener() {\n document.getElementById(\"dark-mode-btn\").addEventListener(\"click\", function(){\n userPreferences.darkMode = !userPreferences.darkMode;\n chrome.storage.local.set({\"preferences\": userPreferences}, function(){\n darkMode(userPreferences.darkMode);\n });\n });\n}",
"async afterBrowserStopped() {}",
"_cleanupFrame() {\n // Uninstall the listener.\n if (this._frame) {\n this._frame.messageManager.removeMessageListener(\"icqStudyMsg\", this._chromeHandler);\n this._frame = null;\n this._chromeHandler = null;\n }\n\n // Dispose of the hidden browser.\n if (this._browser !== null) {\n this._browser.remove();\n this._browser = null;\n }\n\n if (this._hiddenFrame) {\n this._hiddenFrame.destroy();\n this._hiddenFrame = null;\n }\n }",
"function notifyExtensionScrollingStopped(){\n browser.runtime.sendMessage({'message': 'stopped'});\n}",
"function init() {\n\ttoken=localStorage.token; \n\tidle=localStorage.idle; //idle upload interval in minutes (float)\n\n\t//if no token yet, then show the option page, and quit the init for now\n\t//as the options page will call the init when ready\n\tif(!token) {\n\t\tchrome.tabs.create({\"url\": \"options.html\"});\n\t\treturn;\n\t}\n\n\t//at this point, idle and token are set\n\tconsole.log(\"token:\"+token);\n\tconsole.log(\"idle:\"+idle);\n\n\tvar idleSecs=Math.floor(parseFloat(idle)*60);\n\tconsole.log(\"idleSecs:\"+idleSecs);\n\t//update the idle detection interval\n\tchrome.idle.setDetectionInterval(idleSecs); \n\n\t//check if running already, don't add the listener twice\n\tconsole.log(\"running:\"+running);\n\tif(!running) {\n\t\trunning=true;\n\n\n\t\t//create and/or open database\n\t\tdb=window.openDatabase(\"history\",\"1.0\",\"Supplemental Chrome History Database\",1073741824); //max size 1GB\n\t\t//create the urls table if it doesn't exist yet\n\t\tdb.transaction(function(tx) {\n\t\t\ttx.executeSql(\"CREATE TABLE urls (id INTEGER PRIMARY KEY,url LONGVARCHAR,title LONGVARCHAR,visit_count INTEGER DEFAULT 0 NOT NULL,typed_count INTEGER DEFAULT 0 NOT NULL,last_visit_time INTEGER NOT NULL,hidden INTEGER DEFAULT 0 NOT NULL,favicon_id INTEGER DEFAULT 0 NOT NULL)\");\n\t\t\ttx.executeSql(\"CREATE INDEX IF NOT EXISTS last_visit_time_idx ON urls (last_visit_time)\");\n\t\t});\n\n\t\t//add listener to listen for history items\n\t\tchrome.history.onVisited.addListener(function(historyItem) {\n\t\t\tconsole.log(\"NEW HISTORY_ITEM:\"+JSON.stringify(historyItem));\n\t\t\t//upsert the history item to the current database\n\t\t\tdb.transaction(function(tx) {\n\t\t\t\ttx.executeSql(\"INSERT OR REPLACE INTO urls (id,url,title,visit_count,typed_count,last_visit_time) VALUES(?,?,?,?,?,?)\",[historyItem.id,historyItem.url,historyItem.title,historyItem.visitCount,historyItem.typedCount,historyItem.lastVisitTime]);\n\t\t\t});\n\t\t});\n\n\t\t//add listener to check for idle\n\t\tchrome.idle.onStateChanged.addListener(function(newState) {\n\t\t\tconsole.log(\"newState:\"+newState);\n\n\t\t\t//check if chrome has been idle and it is not currently processing from a previous idle\n\t\t\tif(newState==\"idle\" && !processing) {\n\t\t\t\tprocessing=true;\n\n\t\t\t\tlastUpdate=parseFloat(localStorage.lastUpdate) || 0.0;\n\t\t\t\tthisUpdate=(new Date).getTime();\t\n\n\t\t\t\t//clear the upload list\n\t\t\t\tuploadItems=[];\n\n\t\t\t\t//search all the recent history items\n\t\t\t\tdb.transaction(function (tx) {\n\t\t\t\t\ttx.executeSql(\"SELECT * FROM urls WHERE last_visit_time>=?\",[lastUpdate],function(tx,results) {\n\t\t\t\t\t\tvar historyItems=[];\n\t\t\t\t\t\tvar len=results.rows.length,i;\n\t\t\t\t\t\tfor(i=0;i<len;i++){\n\t\t\t\t\t\t\tr=results.rows.item(i);\n\t\t\t\t\t\t\thistoryItems.push({\"id\":r.id,\"url\":r.url,\"title\":r.title,\"visitCount\":r.visit_count,\"typedCount\":r.typed_count,\"lastVisitTime\":r.last_visit_time});\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t//OPTIONAL: empty the supplemental history table, after every use\n\t\t\t\t\t\t//tx.executeSql(\"DELETE FROM urls\");\n\n\t\t\t\t\t\tfor(var n=0;n<historyItems.length;n++) {\n\t\t\t\t\t\t\tconsole.log(\"HISTORY id:\"+historyItems[n].id+\" url:\"+historyItems[n].url);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t//save all the history items because we need these urls to get all the visits\n\t\t\t\t\t\tallHistoryItemsTemp=historyItems;\n\n\t\t\t\t\t\t//get all history items with matching url\n\t\t\t\t\t\tfor(var i=0;i<historyItems.length;i++) {\n\t\t\t\t\t\t\tvar historyItem=historyItems[i];\n\n\t\t\t\t\t\t\t//is nih.gov or wikipedia.org\n\t\t\t\t\t\t\tif(/^https?:\\/\\/(.+\\.)?(wikipedia\\.org|nih\\.gov)\\//.test(historyItem.url)) {\n\t\t\t\t\t\t\t\tuploadItems.push(historyItem);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t//get the history items (look up wikipedia links and verify they are medical\n\t\t\t\t\t\tverifiedItems=[];\n\t\t\t\t\t\tverifyUploadItems(function(success) {\n\t\t\t\t\t\t\tif(success && verifiedItems.length>0) {\n\t\t\t\t\t\t\t\tallVisitItems=[];\n\t\t\t\t\t\t\t\tallHistoryItems=[];\n\n\t\t\t\t\t\t\t\tgetAllVisits(function(success) {\n\t\t\t\t\t\t\t\t\tif(success) {\n\t\t\t\t\t\t\t\t\t\t//at this point allHistoryItems, allVisitItems, and verifiedItems are filled\n\t\t\t\t\t\t\t\t\t\t//so just need to extract the trees\n\t\t\t\t\t\t\t\t\t\ttraverseAndPost(function(success) {\n\t\t\t\t\t\t\t\t\t\t\t//all verifiedItems have been posted at this point\n\t\t\t\t\t\t\t\t\t\t\tlocalStorage[\"lastUpdate\"]=thisUpdate; //comment out for testing of all links\n\t\t\t\t\t\t\t\t\t\t\tprocessing=false;\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tprocessing=false;\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} else {\n\t\t\t\t\t\t\t\tprocessing=false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t},null);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n}",
"onChromeVoxDisconnect_() {\n this.port_ = null;\n this.log_('onChromeVoxDisconnect', chrome.runtime.lastError);\n }",
"function saveOptions() {\n\t\t\tif (supported('localStorage') && options.saving) {\n\t\t\t\tlocalStorage.setItem('ADI.options', JSON.stringify(options));\n\t\t\t}\n\t\t}",
"function save_options() {\n\t\n\tchrome.extension.getBackgroundPage().userSettings.ip = document.getElementById('ip').value; \n\tchrome.extension.getBackgroundPage().userSettings.port = document.getElementById('port').value; \n\tchrome.extension.getBackgroundPage().userSettings.username = document.getElementById('username').value; \n\tchrome.extension.getBackgroundPage().userSettings.password = document.getElementById('password').value; \n\n\tconsole.log(\"save_options\");\n\t//console.log(chrome.extension.getBackgroundPage().userSettings.ip);\n\t//console.log(chrome.extension.getBackgroundPage().userSettings.port);\n\t//console.log(chrome.extension.getBackgroundPage().userSettings.username);\n\t//console.log(chrome.extension.getBackgroundPage().userSettings.password);\n\n\tchrome.storage.sync.set({\n\t\tip: chrome.extension.getBackgroundPage().userSettings.ip,\n\t\tport: chrome.extension.getBackgroundPage().userSettings.port,\n\t\tusername: chrome.extension.getBackgroundPage().userSettings.username,\n\t\tpassword: chrome.extension.getBackgroundPage().userSettings.password || \"\",\n\t}, function() {\n\t\t\n\t\tif (chrome.runtime.lastError)\n\t\t{\n\t\t\tconsole.log(chrome.runtime.lastError);\n\t\t}\n\t\telse\n\t\t{\n\t\t// Notify that we saved.\n\t\tconsole.log('Settings saved!!!');\n\t}\n});\n}",
"function passiveModeWindowSizeListener() {\n var passiveModeWindowSize = document.getElementById(\"passiveModeWindowSize\");\n passiveModeWindowSize.addEventListener(\"input\", function() {\n var newVal = passiveModeWindowSize.value;\n chrome.storage.local.get(function(storage) {\n var cachedSettings = storage[\"cachedSettings\"];\n var oldSettings = storage[\"settings\"];\n if (!cachedSettings) {\n if (!oldSettings) {\n // Use default Settings\n oldSettings = initialSettings;\n }\n cachedSettings = oldSettings;\n }\n\n cachedSettings[\"passiveModeWindowSize\"] = newVal;\n var passiveModeWindowSizeVal = document.getElementById(\"passiveModeWindowSizeVal\");\n passiveModeWindowSizeVal.innerHTML = newVal;\n chrome.storage.local.set({ \"cachedSettings\": cachedSettings });\n });\n });\n}",
"onAllWindowsClosed() {\r\n // Stub\r\n }",
"function saveStarred(tabId, info) {\n var url = tabToUrl[tabId.toString()];\n if (info.isWindowClosing && starredTabs[tabId]) {\n if (typeof url != \"undefined\") {\n urls[url] = true;\n chrome.storage.local.set({\"saved-urls\": urls}, null);\n }\t\n }\n else {\n delete urls[url];\n chrome.storage.local.set({\"saved-urls\": urls}, null);\n }\n}",
"function debug() {\n // Nothing to test, yay :D\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
======================================================================== 2. startServant: No existing servants were found, start a new servant. Get the EED public key. If the request fails the problem might be due to the EED certificate issue. ======================================================================== | function startServant(adviseLaunchInfo) {
showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_GET_PUBKEY'));
var eedTicket = adviseLaunchInfo.eedTicket,
eedURL = adviseLaunchInfo.eedURL,
pubKey = "",
pubKeyUrl = eedURL + '/execution/pubkey',
that = this;
// FIXME : verify the noServant code
adviseLaunchInfo.noServant = localStorage.getItem('noServant') === null? false : true;
if(adviseLaunchInfo.noServant){
startApp(adviseLaunchInfo);
return;
}
$simjq.when(getCOSConfigurations(adviseLaunchInfo)).then(
function(){
jQuery.support.cors = true;
jQuery.ajax({
url : pubKeyUrl,
type : "GET",
beforeSend : function(request) {
request.setRequestHeader("EEDTicket", eedTicket);
request.setRequestHeader("Credentials", "");
},
contentType : "text/plain",
success : function(returndata, status, xhr) {
console.log(returndata);
pubKey = $simjq(returndata).find("KeyRep").text().trim();
// Store decoded key to use as sp-encryption component
adviseLaunchInfo.eedPublicKeyDecoded = pubKey;
pubKey = encodeURIComponent(pubKey);
adviseLaunchInfo.eedPublicKey = pubKey;
getEncryptedCredentials(adviseLaunchInfo);
},
error : function(jqXHR, textStatus, errorThrown) {
handleEEDCommFailure(
eedURL,
startServant.bind(that, adviseLaunchInfo),
adviseLaunchInfo.translator);
}
});
},
function(error){
createLaunchPopOver({
'message': translator.translate('LAUNCH_EED_COMM_FAILURE') + '<br/>'
+ error,
'close-callback': returnToRALanding
});
});
} | [
"function start() {\n test();\n var httpService = http.createServer(serve);\n httpService.listen(ports[0], '0.0.0.0');\n\n var options = {\n key: key,\n cert: cert\n };\n var httpsService = https.createServer(options, serve);\n httpsService.listen(ports[1], '0.0.0.0');\n\n var clients = clientService(httpsService);\n clients.onNewPos(updateEvents);\n\n printAddresses();\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}",
"function startOTP() {\n console.log('Starting OTP service');\n var child = childProcess.exec('java -Xmx2g -jar '\n + globalvars.otpJarPath\n + ' --server -p 8080 -v',\n function (error, stdout, stderr) {\n console.log('OTP ERROR: ' + stderr);\n if (error !== null) {\n console.log('OTP ERROR: ' + error);\n }\n });\n\n child.stdout.on('data', function (data) {\n console.log('CHILD OTP SERVER: ' + data);\n });\n\n child.stderr.on('data', function (data) {\n console.log('CHILD OTP SERVER: ' + data);\n });\n\n child.on('close', function(code) {\n console.log('child closed: ' + code);\n });\n }",
"function initStartServer(){\n startServer();\n checkServerStatus(1);\n}",
"function start() {\n const server = new SMTPServer({\n // always authorize\n onAuth: (auth, session, cb) => cb(null, { user: {} }),\n onData: (stream, session, cb) => {\n const chunks = []\n stream.on('data', chunk => chunks.push(chunk))\n stream.on('end', () => {\n if (!resolveQueue.length) makePromise()\n const resolve = resolveQueue.shift()\n resolve(chunks.join(''))\n cb()\n })\n },\n })\n\n server.listen(transport.port)\n}",
"async start () {\n if (this.status !== ServerStatus.OFFLINE) {\n throw new ServerException('The server is already running!');\n }\n \n this.logger.info('The server is now starting.');\n this.updateStatus(ServerStatus.STARTING);\n await this.container.start();\n \n const inspect = await this.container.inspect();\n this.port = inspect.port;\n\n await this.container.attach();\n this.logger.info('Attached to the container, waiting for it to fully start.');\n }",
"function start () {\n let node = process.execPath\n let daemonFile = path.join(__dirname, '../daemon')\n let daemonLog = path.resolve(untildify('~/.hotel/daemon.log'))\n\n debug(`creating ${startupFile}`)\n startup.create('hotel', node, [daemonFile], daemonLog)\n\n console.log(` Started http://localhost:${conf.port}`)\n}",
"function generateKeyPair() {\n\n // check if an active public key has been set for us in the server side\n $.ajax({\n type: 'POST',\n url: '/publicKeyExists',\n success: function(data) {\n\n if ( data == false ) {\n\n // generate our keys\n var keySize = 2048;\n var crypt = new JSEncrypt({default_key_size: keySize});\n crypt.getKey();\n\n // set a new private RSA key\n var privateKey = crypt.getPrivateKey();\n localStorage.setItem('privateKey', privateKey);\n\n // set a new public RSA key\n var publicKey = crypt.getPublicKey();\n localStorage.setItem('publicKey', publicKey);\n\n // send the public key to the server\n $.ajax({\n type: 'POST',\n url: '/publicKeyStore',\n data: { publicKey: publicKey },\n success: function(data) {\n if ( data == \"OK\" ) {\n // everything is ok, remove the loader\n loaded();\n }\n else {\n // Something went wrong\n alertError(\"Something went wrong\")\n }\n }\n });\n\n }\n else {\n // The public key is already created and stored\n loaded();\n }\n\n }\n });\n\n}",
"function startServer() {\n\troutes.setup(router); //Set the route\n\tapp.listen(port); //Passing port for the server\n\t\n\tconsole.log('\\n Server started \\n Mode: ' + env + ' \\n URL: localhost:' + port);\n}",
"startEMR() {\n this.express = express();\n this.middleware();\n this.routes();\n this.setNodeConfiguartionFromDockerCommand();\n }",
"startDiscovery() {}",
"start() {\n return P.resolve()\n .then(() => {\n if (!this._started) {\n this._started = true;\n return this.reload()\n .then(() => {\n dbg.log0('Started hosted_agents');\n this._monitor_stats();\n });\n }\n dbg.log1(`What is started may never start`);\n })\n .catch(err => {\n this._started = false;\n dbg.error(`failed starting hosted_agents: ${err.stack}`);\n throw err;\n })\n .then(() => {\n // do nothing. \n });\n }",
"async function fnStartRemoteAPI(){\n if (fs.existsSync(\"/share/config.json\") !== true && fs.existsSync(\"/share/config.gen.js\") !== true && fs.existsSync(\"/share/remote-api.json\")){\n try {\n if (fs.existsSync(\"/startup/remote-api.started\") !== true || fnIsRunning(\"node /startup/remote-api/index.js\") !== true){\n console.log(`[LOG] EasySamba Remote API is enabled and is starting...`);\n fnKill(\"node /startup/remote-api/index.js\");\n fnDeleteFile(\"/startup/remote-api.started\");\n fnSpawn(\"node\", [\"/startup/remote-api/index.js\"]);\n await fnSleep(2000);\n if (fs.existsSync(\"/startup/remote-api.started\")){\n console.log(`[LOG] EasySamba Remote API started successfully.\\n`);\n }\n else {\n console.log(`[ERROR] EasySamba Remote API could not be started.\\n`);\n }\n }\n }\n catch (error){\n if (fnIsRunning(\"node /startup/remote-api/index.js\") !== true){\n fnDeleteFile(\"/startup/remote-api.started\");\n console.log(`[ERROR] EasySamba Remote API could not be started.\\n`);\n }\n }\n }\n else {\n if (fs.existsSync(\"/startup/remote-api.started\") || fnIsRunning(\"node /startup/remote-api/index.js\")){\n console.log(`[LOG] EasySamba Remote API is not enabled and won't be started.\\n`);\n fnKill(\"node /startup/remote-api/index.js\");\n fnDeleteFile(\"/startup/remote-api.started\");\n }\n }\n}",
"function startServer(){\n if(isDev()){\n var options = {\n scriptPath: path.join(__dirname, '../../../engine/'),\n args: [TEMP_PATH],\n pythonPath: 'python'\n };\n\n PythonShell.run('dash_server.py', options, function (err, results) {\n if(err){\n window.showAlertMessage({title: 'Dash Server Error', message: \"An error occured while trying to start the Dash Server\"});\n console.error(err);\n }\n if (results) console.log('Results from dash server: ', results);\n });\n }else{\n var opt = function(){\n execFile(DASH_PATH, [TEMP_PATH], function(err, results) { \n if(err){\n window.showAlertMessage({title: 'Dash Server Error', message: \"An error occured while trying to start the Dash Server\"});\n console.error(err);\n }\n if(results) console.log('Results from dash server: ', results.toString()); \n });\n }\n opt();\n }\n\n}",
"static enable(serverNodeId){\n\t\tlet kparams = {};\n\t\tkparams.serverNodeId = serverNodeId;\n\t\treturn new kaltura.RequestBuilder('servernode', 'enable', kparams);\n\t}",
"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 startServer() {\n console.log('*** Starting demo for developer prototyping' +\n ' kit for BeagleBone Green ***');\n\n // Starts the server.\n webserver.start();\n\n // Checks internet connection on board.\n utils.checkInternetConnection(function(result) {\n webserver.sendEventToClient('hasInternet', result);\n hasInternet = result;\n });\n}",
"function startApp(adviseLaunchInfo) {\n \n $simjq.when(checkServantURLValidity(adviseLaunchInfo))\n .then(function(token){\n\t\t\tif (token.length > 0){\n \n if(!adviseLaunchInfo.noServant){\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_READING_DATA'),\n setStationNameToSplash(adviseLaunchInfo));\n }\n else{\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_LOAD_LITE'));\n }\n \n $simjq('#widgetframe').attr('src', \"../webapps/SMAAnalyticsUI/smaResultsAnalyticsLaunched.html\").load(function(){\n var widgetWindow = window.frames['widgetframe'];\n if(!widgetWindow.setServantFromParent) {\n widgetWindow = widgetWindow.contentWindow; // needed for FF\n }\n if(widgetWindow.setServantFromParent) {\n $simjq('.embeddedWidget').show();\n if(!adviseLaunchInfo.noServant){\n widgetWindow.setServantFromParent(adviseLaunchInfo);\n }\n } else {\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_PAGE_LOAD_ERROR'));\n adviseGoBack(adviseLaunchInfo.translator.translate('LAUNCH_PAGE_LOAD_ERROR'));\n }\n });\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tadviseGoBack(adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_ERROR'));\n\t\t\t}\n\n });\n}",
"function getRunningServant(caseID, adviseLaunchInfo) {\n \n var def = jQuery.Deferred(),\n clearStg = function(){\n delete localStorage['smaAnalyticsCase' + caseID];\n def.resolve(null);\n };\n\n if (typeof (Storage) !== 'undefined') {\n \n var currTime = Date.now();\n var previousSessionString = localStorage['smaAnalyticsCase' + caseID];\n \n if (previousSessionString && previousSessionString.length > 5) {\n \n var previousSession = JSON.parse(previousSessionString);\n var prevTime = previousSession.lastUpdateTime;\n var servantURL = previousSession.servantURL;\n adviseLaunchInfo['servantURL'] = servantURL;\n adviseLaunchInfo['caseID'] = caseID;\n \n $simjq.when(checkServantURLValidity(adviseLaunchInfo))\n .then(function(token){\n \n\t\t\t\t\tif (typeof token !== 'undefined' && token !== null && token.length > 0){\n createLaunchPopOver({\n 'message': adviseLaunchInfo.translator.translate('LAUNCH_EXISTING_SERVANT') ,\n 'header': adviseLaunchInfo.translator.translate('LAUNCH_RA_HEADER_EXS_SERVANT'),\n 'confirm-mode': true,\n 'close-label': adviseLaunchInfo.translator.translate('Cancel') ,\n 'ok-callback': function(){\n def.resolve({\n 'servantURL': servantURL,\n 'stationName': previousSession.stationName,\n 'stationIP' : previousSession.stationIP,\n 'token' : token });\n }.bind(this),\n \n 'close-callback': function(){\n \n var promise = jQuery.ajax({ url:servantURL + 'stop',\n crossDomain: true,\n data: { 't': Date.now() }\n })\n .done(clearStg)\n .fail(function(){\n console.error('Attempt to stop the running servant failed.');\n clearStg();\n });\n }.bind(this)\n });\n\t\t\t\t\t} else {\n\t\t\t\t\t\tclearStg();\n\t\t\t\t\t}\n }.bind(this));\n } else {\n clearStg();\n }\n } else {\n def.resolve(null);\n }\n return def;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get indices of regular expression matches in the string. | function matchIndices(str, re) {
var result, indices = [];
while(result = re.exec(str)) {
indices.push(result.index); // Match found, push its index in the array
}
return indices; // return matches indices
} | [
"function allIndexOf(str, toSearch) {\n var indices = [];\n for (var pos = str.indexOf(toSearch); pos !== -1; pos = str.indexOf(toSearch, pos + 1)) {\n indices.push(pos);\n }\n return indices;\n}",
"function getIndicesOf(str, keywords) {\n\tvar searchlength = keywords.length;\n\tif (searchlength == 0) return [];\n\tvar startIndex = 0, index, indices = [];\n\twhile ((index = str.indexOf(keywords, startIndex)) > -1) {\n\t\tindices.push(index);\n\t\tstartIndex = index + searchlength;\n\t}\n\treturn indices;\n}",
"function all_matched_slices(string, regexp) {\n var slices = [];\n var pos;\n while ((pos = string.search(regexp)) >= 0) {\n\tslices.push(string.slice(pos)); \n\tstring = string.slice(pos+1); }\n return slices; }",
"function searchArray(input, array){\n //creates new RegExp\n //g = flag to make search global, i means ignore case\n let regex = new RegExp(input, 'gi');\n //filters by matching strings\n \n //match can only be used on strings\n let result = array.filter(current => current.match(regex));\n\n // stores index numbers of match\n let match = [];\n for(i = 0; i < result.length; i++){\n match.push(\n array.indexOf(\n result[i]));\n }\n \n //returns indexes of matches in array\n return match;\n}",
"function GetMatches(targetPattern, dnaString, maxMisMatches){\n\n\tvar targetKmerLength = targetPattern.length; //casting for correct behavior\n\t\n\t//get all Kmers\n\tvar loopLength = dnaString.length - targetKmerLength + 1;//do loop length calculatiion here as it is faster then recalculating for each loop itteration\n\tvar matchedIndexes = ''; \n\tfor (var i = 0; i < loopLength; i++) {\n\t\tvar upperBound = targetKmerLength+i;\n\t\tvar tempKmer = dnaString.substring(i,upperBound).toString();\n\t\tif(matchesWithInMargin(tempKmer, targetPattern, maxMisMatches))\n\t\t\t//console.log('match at index: '+ i +' ');\n\t\t\tmatchedIndexes += i +' ';\n\t};\n\t//console.log('Done');\n\treturn matchedIndexes;\n}",
"function spoccures(string, regex) {\n return (string.match(regex) || []).length;\n }",
"function strWordsIndices(str) {\r\n str = nbsp_to_spaces(str); // replace html characters if found by text characters\r\n var re = /(http|ftp|https):\\/\\/[\\w-]+(\\.[\\w-]+)+([\\w.,@?^=%&:\\/~+#-]*[\\w@?^=%&\\/~+#-])?|((([^\\x00-\\x80]+|\\w+)+)?(-|')(([^\\x00-\\x80]+|\\w+)+)?)+|([^\\x00-\\x80]+|\\w+)+/gi; // Match url | words(including non english characters)\r\n return matchIndices(str, re); // return words indices\r\n}",
"function mapSanitizedIndices(originalString) {\n var escapeMatch;\n var mappedIndices = {};\n var mappedUpTo = 0;\n var offset = 0;\n\n ANSI_ESCAPE_MATCHER.lastIndex = 0;\n while ((escapeMatch = ANSI_ESCAPE_MATCHER.exec(originalString)) !== null) {\n while (mappedUpTo + offset < escapeMatch.index) {\n mappedIndices[mappedUpTo] = offset + mappedUpTo++;\n }\n offset += escapeMatch[0].length;\n }\n while (mappedUpTo + offset < originalString.length) {\n mappedIndices[mappedUpTo] = offset + mappedUpTo++;\n }\n return mappedIndices;\n }",
"contains(text, pattern) {\n if (!pattern || !text || pattern.length > text.length) return -1;\n\n const pTable = [];\n pTable.push(0);\n\n let length = 0;\n for (let i = 1, left = 0; i < pattern.length; ) {\n if (\n i + length < pattern.length &&\n pattern.charAt(left + length) === pattern.charAt(i + length)\n ) {\n length++;\n } else {\n pTable.push(length);\n i++;\n length = 0;\n }\n }\n\n for (let i = 0, p = 0; i < text.length; ) {\n if (text.charAt(i) === pattern.charAt(p)) {\n p++;\n i++;\n } else {\n p = Math.max(pTable[p] - 1, 0);\n if (p === 0) i++;\n }\n\n if (p === pattern.length) return i - p;\n }\n\n return -1;\n }",
"function findAllOccurances(arr, searchTerm, startIndex = 0) {\n let indexArray = [];\n for (let i = startIndex; i < arr.length; i++) {\n if (arr[i] == searchTerm) {\n indexArray.push(i)\n }\n }\n\n return indexArray;\n}",
"function findMatchingLine(lines, re, startIndex) {\n re = new RegExp(re);\n if (!startIndex) startIndex = 0;\n\n var found = false, index;\n\n for (index = startIndex; index < lines.length; index++) {\n if (re.test(lines[index])) {\n found = true;\n break;\n }\n }\n\n return found ? index : -1;\n}",
"function myIndexOf(string, searchTerm) {}",
"function indices(value) {\n var result = [];\n var index = value.indexOf('\\n');\n\n while (index !== -1) {\n result.push(index + 1);\n index = value.indexOf('\\n', index + 1);\n }\n\n result.push(value.length + 1);\n\n return result\n }",
"function extUtils_findPatternsInString(nodeStr, quickSearch, searchPatterns, findMultiple)\n{\n var pos = null;\n\n //if something to search and quick search matches (or is empty)\n // Note that the quickSearch is NOT case sensitive\n if ( nodeStr && quickSearch!=null\n && (nodeStr.toUpperCase().indexOf(quickSearch.toUpperCase()) != -1\n || !quickSearch)\n )\n {\n //pos is 0 if there are no patterns (returns true)\n var pos = new Array(0,0);\n\n // Build up a nodeInfo object which stores off the innerHTML, begin tag string,\n // and attribute values. This is useful for patterns that have\n // the limitSearch property defined.\n var callback = new Object();\n callback.tagCount = 0;\n callback.tagStart = -1\n callback.innerStart = -1;\n callback.innerEnd = -1;\n callback.attributes = new Object();\n callback.openTagBegin = new Function(\"tag,offset\",\"if (this.tagCount == 0) { this.tagStart = offset;}\");\n callback.attribute = new Function(\"name,val\", \"if (this.tagCount == 0) { this.attributes[name] = val;}\");\n callback.openTagEnd = new Function(\"offset\",\"if (this.tagCount == 0) { this.innerStart = offset; } this.tagCount++;\");\n callback.closeTagBegin = new Function(\"tag,offset\",\" this.innerEnd = offset\");\n\n dw.scanSourceString(nodeStr, callback);\n\n var nodeInfo = new Object();\n nodeInfo.outerHTML = nodeStr;\n nodeInfo.tagOnly = nodeStr.substring(callback.tagStart, callback.innerStart);\n nodeInfo.attributes = callback.attributes;\n nodeInfo.innerHTML = nodeStr.substring(callback.innerStart, callback.innerEnd);\n\n //Tries each pattern. If patterns exist and any\n //patterns are not found, breaks and returns null.\n //Otherwise remembers position of last match (used for \"nodeAttribute\" insertLocation).\n for (var i=0; i < searchPatterns.length; i++)\n {\n //get the search pattern\n var pattern = searchPatterns[i].pattern;\n var isOptional = (searchPatterns[i].isOptional == \"true\")\n\n // Limit the string we search over using the limitSearch property.\n var limitSearch = searchPatterns[i].limitSearch;\n var theStr = nodeInfo.outerHTML;\n if (limitSearch)\n {\n if (limitSearch.toUpperCase() == \"TAGONLY\")\n {\n theStr = nodeInfo.tagOnly;\n }\n else if (limitSearch.toUpperCase() == \"INNERONLY\")\n {\n theStr = nodeInfo.innerHTML;\n }\n else\n {\n var attrPatt = /attribute\\+(\\w+)/i;\n var match = attrPatt.exec(limitSearch);\n if (match && match.length > 1 && nodeInfo.attributes[match[1]])\n {\n theStr = nodeInfo.attributes[match[1]];\n }\n }\n }\n\n //clear any old match information\n searchPatterns[i].match = '';\n\n //if pattern starts with \"/\", must be regular expression\n if (pattern.length > 2 && pattern.charAt(0)==\"/\") //if regular expression, search for that\n {\n pattern = eval(pattern); //convert /string/ to regular expression\n\n if (!findMultiple)\n {\n var match = theStr.match(pattern); //search for it as RegExp\n if (match)\n {\n pos[0] = match.index; //remember position\n pos[1] = pos[0]+match[0].length;\n searchPatterns[i].match = match;\n }\n else\n {\n if (!isOptional)\n {\n pos = null;\n break;\n }\n }\n }\n else\n {\n var match;\n var attributes = \"g\" + ((pattern.ignoreCase) ? \"i\" : \"\");\n var globalPattern = new RegExp(pattern.source,attributes);\n searchPatterns[i].match = new Array();\n\n while ( (match = globalPattern.exec(theStr)) != null )\n {\n searchPatterns[i].match.push(match);\n }\n\n if (searchPatterns[i].match.length == 0)\n {\n if (!isOptional)\n {\n pos = null;\n break;\n }\n }\n }\n\n //if no \"/\", do straight search\n }\n else\n {\n var offsetPos = theStr.indexOf(pattern); //search for string with indexOf()\n if (offsetPos != -1)\n {\n pos[0] = offsetPos;\n pos[1] = pos[0]+pattern.length;\n }\n else\n {\n if (!isOptional)\n {\n pos = null;\n break;\n }\n }\n }\n }\n }\n return pos;\n}",
"function count(regex, str) {\n return str.length - str.replace(regex, '').length;\n }",
"match(word) {\n if (this.pattern.length == 0)\n return [0];\n if (word.length < this.pattern.length)\n return null;\n let { chars, folded, any, precise, byWord } = this;\n // For single-character queries, only match when they occur right\n // at the start\n if (chars.length == 1) {\n let first = codePointAt(word, 0);\n return first == chars[0] ? [0, 0, codePointSize(first)]\n : first == folded[0] ? [-200 /* CaseFold */, 0, codePointSize(first)] : null;\n }\n let direct = word.indexOf(this.pattern);\n if (direct == 0)\n return [0, 0, this.pattern.length];\n let len = chars.length, anyTo = 0;\n if (direct < 0) {\n for (let i = 0, e = Math.min(word.length, 200); i < e && anyTo < len;) {\n let next = codePointAt(word, i);\n if (next == chars[anyTo] || next == folded[anyTo])\n any[anyTo++] = i;\n i += codePointSize(next);\n }\n // No match, exit immediately\n if (anyTo < len)\n return null;\n }\n let preciseTo = 0;\n let byWordTo = 0, byWordFolded = false;\n let adjacentTo = 0, adjacentStart = -1, adjacentEnd = -1;\n for (let i = 0, e = Math.min(word.length, 200), prevType = 0 /* NonWord */; i < e && byWordTo < len;) {\n let next = codePointAt(word, i);\n if (direct < 0) {\n if (preciseTo < len && next == chars[preciseTo])\n precise[preciseTo++] = i;\n if (adjacentTo < len) {\n if (next == chars[adjacentTo] || next == folded[adjacentTo]) {\n if (adjacentTo == 0)\n adjacentStart = i;\n adjacentEnd = i;\n adjacentTo++;\n }\n else {\n adjacentTo = 0;\n }\n }\n }\n let ch, type = next < 0xff\n ? (next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 /* Lower */ : next >= 65 && next <= 90 ? 1 /* Upper */ : 0 /* NonWord */)\n : ((ch = fromCodePoint(next)) != ch.toLowerCase() ? 1 /* Upper */ : ch != ch.toUpperCase() ? 2 /* Lower */ : 0 /* NonWord */);\n if (type == 1 /* Upper */ || prevType == 0 /* NonWord */ && type != 0 /* NonWord */ &&\n (this.chars[byWordTo] == next || (this.folded[byWordTo] == next && (byWordFolded = true))))\n byWord[byWordTo++] = i;\n prevType = type;\n i += codePointSize(next);\n }\n if (byWordTo == len && byWord[0] == 0)\n return this.result(-100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0), byWord, word);\n if (adjacentTo == len && adjacentStart == 0)\n return [-200 /* CaseFold */, 0, adjacentEnd];\n if (direct > -1)\n return [-700 /* NotStart */, direct, direct + this.pattern.length];\n if (adjacentTo == len)\n return [-200 /* CaseFold */ + -700 /* NotStart */, adjacentStart, adjacentEnd];\n if (byWordTo == len)\n return this.result(-100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0) + -700 /* NotStart */, byWord, word);\n return chars.length == 2 ? null : this.result((any[0] ? -700 /* NotStart */ : 0) + -200 /* CaseFold */ + -1100 /* Gap */, any, word);\n }",
"function gather(regex, replacement) {\n\ttext = String(this);\n\tmatches = [ ];\n\twhile ((match = regex.exec(text)) !== null) {\n\t\ttext = text.substring(0, match.index) + replacement + text.substring(match.index + match[0].length);\n\t\tmatches.push(match.slice(1).filter(x => x != undefined)[0]);\n\t}\n\treturn [ matches, text ];\n}",
"function getCodePoints(string) {\n var newArray = [];\n for (i = 0; i < string.length; i++) {\n newArray.push(string.codePointAt(i));\n\n }\n return newArray;\n}",
"function SEARCH(find_text, within_text, position) {\n if (!within_text) {\n return null;\n }\n position = typeof position === 'undefined' ? 1 : position;\n\n // The SEARCH function translated the find_text into a regex.\n var find_exp = find_text.replace(/([^~])\\?/g, '$1.') // convert ? into .\n .replace(/([^~])\\*/g, '$1.*') // convert * into .*\n .replace(/([~])\\?/g, '\\\\?') // convert ~? into \\?\n .replace(/([~])\\*/g, '\\\\*'); // convert ~* into \\*\n\n position = new RegExp(find_exp, \"i\").exec(within_text);\n\n if (position) {\n return position.index + 1;\n }\n return error$2.value;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set a mem address of a bitmask Generalizes all the "SET 2, (HL)" etc. instructions | setMem(bitmask) {
MMU.wb(regHL[0], MMU.rb(regHL[0]) | bitmask);
return 16;
} | [
"function setBit(number,i) {\n\treturn number | (1 << i);\n}",
"access(n, addr) {\n this.sets[addr.idx][n].access = 0;\n }",
"function setThirdBit(num) {\n\treturn (num | 4).toString(2)\n}",
"pollute(n, addr) {\n this.sets[addr.idx][n].dirty = true;\n }",
"function setargM( argz, name, p ) {\n var hash = argz.argN ? argz.argN : argz.argv[0];\n if (hash[name] === undefined) throw new Error(\"missing named argument %(\" + name + \") at offset \" + p);\n return argz.argN = hash[name];\n}",
"makeValid(n, addr) {\n this.sets[addr.idx][n].valid = true;\n }",
"AND() { this.A = this.eqFlags_(this.M & this.A); }",
"function set_permissions(abs_path) {\n var p = 0;\n $.each($('.popover .explorer-popover-perm-body input:checked'), function(idx, e) {\n p |= 1 << (+$(e).attr('data-bit'));\n });\n\n var permission_mask = p.toString(8);\n\n // PUT /webhdfs/v1/<path>?op=SETPERMISSION&permission=<permission>\n var url = '/webhdfs/v1' + encode_path(abs_path) +\n '?op=SETPERMISSION' + '&permission=' + permission_mask;\n\n $.ajax(url, { type: 'PUT'\n }).done(function(data) {\n browse_directory(current_directory);\n }).fail(network_error_handler(url))\n .always(function() {\n $('.explorer-perm-links').popover('destroy');\n });\n }",
"function mutateSimpleAddress(node){\n const start = node.range[0]\n const end = node.range[1]\n mutations.push(new Mutation(file, start, end + 1, \"address(this)\"))\n mutations.push(new Mutation(file, start, end + 1, \"address(0)\")) \n //Swap the literal address with each declared literal address\n literalAddress.forEach(a => {\n if(a !== node.number)\n mutations.push(new Mutation(file, start, end + 2, a+';'))\n }); \n }",
"set LightmapStatic(value) {}",
"function setAddress(address) {\n if (tabControl.isTabShowing(tabControl.TABS.EXPLORE)) {\n directionsFormControl.setError('origin');\n }\n if (address) {\n exploreLatLng = [address.location.y, address.location.x];\n if (tabControl.isTabShowing(tabControl.TABS.EXPLORE)) {\n mapControl.setDirectionsMarkers(exploreLatLng);\n }\n } else {\n exploreLatLng = null;\n $(options.selectors.alert).remove();\n mapControl.isochroneControl.clearIsochrone();\n }\n }",
"EOR() { this.A = this.eqFlags_(this.M ^ this.A); }",
"set PhonePad(value) {}",
"function fSetcode(obj, sc) {\n\n var val = obj.setcode,\n hexA = val.toString(16),\n hexB = sc.toString(16);\n if (val === sc || parseInt(hexA.substr(hexA.length - 4), 16) === parseInt(hexB, 16) || parseInt(hexA.substr(hexA.length - 2), 16) === parseInt(hexB, 16) || (val >> 16).toString(16) === hexB) {\n return true;\n } else {\n return false;\n }\n }",
"cursorSet(cursor, value) {\n if (cursor.buffer)\n this.setBuffer(cursor.buffer.buffer, cursor.index, value)\n else this.map.set(cursor.tree, value)\n }",
"function set (str, value) {\n if (registers.hasOwnProperty(str))\n registers[str] = Number(value);\n else if (str === \"$zero\")\n return;\n else\n output(\"Error getting register \" + str + \" on Line \" + line, 'e');\n}",
"function setPlace(x, y, place) {\n board[getBoardCoord(x, y)] = place;\n}",
"function setPattern({ y, x, value }) {\n const patternCopy = [...pattern];\n patternCopy[y][x] = +!value;\n updatePattern(patternCopy);\n }",
"function setCpuDifficulty(lobby, n) {\n getGame(lobby).cpus[0] = n;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called when user wants to save chosen application. It calls addApplication method of appscoapplicationaddsettings page. | _onAddApplication() {
this._showLoader();
this.$.appscoApplicationAddSettings.addApplication();
} | [
"_onApplicationSelect() {\n this._selected = 'appsco-application-add-settings';\n }",
"function setAppData(appData) {\n self.LApp.data = appData;\n $log.debug('success storing application data');\n }",
"function saveProgram() {\n var programName=programNameField.value;\n if (programName==\"\") {\n\talert(\"Enter a program name first\");\n\treturn;\n }\n window.localStorage.setItem(getProgramHTMLKey(programName),htmlSrc.value);\n window.localStorage.setItem(getProgramJSKey(programName),jsSrc.value);\n if (window.localStorage.getItem(getProgramAccessTokenKey(programName))==null) {\n\t// Generate an access token if there isn't one yet\n\tvar tokenValuesArray=new Uint32Array(4);\n\twindow.crypto.getRandomValues(tokenValuesArray);\n\tvar accessToken=\"\"+tokenValuesArray[0];\n\tfor (i=1;i<4;i++) {\n\t accessToken=accessToken+\",\"+tokenValuesArray[i];\n\t}\n\twindow.localStorage.setItem(getProgramAccessTokenKey(programName),accessToken);\n }\n setModified(false);\n generateProgramList(programName);\n updateLinks();\n}",
"function saveConfigtoDBTestbed(confName){\n\tif(globalDeviceType==\"Mobile\"){\n\t\tloading(\"show\");\n\t}\n//\tMainFlag = 0;\n\t//FileType = \"Dynamic\";\n\tfor(var a=0; a< globalMAINCONFIG.length;a++){\n\t\tglobalMAINCONFIG[a].MAINCONFIG[0].Flag = 0;\n\t\tif(globalMAINCONFIG[a].MAINCONFIG[0].PageCanvas == pageCanvas){\n\t\t\tglobalMAINCONFIG[a].MAINCONFIG[0].FileType = $('#saveConfFileTypeDBType > option:selected').html().toString();\n\t\t\tglobalMAINCONFIG[a].MAINCONFIG[0].Name = confName;\n\t\t}\n\t}\n\n\tvar qry = getStringJSON(globalMAINCONFIG[pageCanvas]);\n\t$.ajax({\n\t\turl: getURL(\"ConfigEditor\", \"JSON\"),\n\t\tdata : {\n\t\t\t\"action\": \"savetopology\",\n\t\t\t\"query\": qry\n\t\t},\n\t\tmethod: 'POST',\n\t\tproccessData: false,\n\t\tasync:false,\n\t\tdataType: 'html',\n\t\tsuccess: function(data) {\n\t\t\tvar dat=data.replace(/'/g,'\"');\n\t\t\tvar data = $.parseJSON(dat);\n\t\t\tvar result = data.RESULT[0].Result;\n\t\t\tif(result == 1){\n\t\t\t\tif(globalDeviceType==\"Mobile\"){\n\t\t\t\t\tloading(\"hide\");\n\t\t\t\t}\n\t\t\t\talerts(\"Configuration saved to the database.\", \"todo\", \"graph\");\n\t\t\t\tMainFlag =1;\n\t\t\t\tFileType =\"\";\n\t\t\t\tvar todo = \"if(globalDeviceType!='Mobile'){\";\n\t\t\t\ttodo +=\t\"$('#deviceMenuPopUp').dialog('destroy');\";\n\t\t\t\ttodo += \"$('#configPopUp').dialog('destroy');\";\n\t\t\t\ttodo += \"}else{\";\n\t\t\t\ttodo +=\t\"$('#saveConfig').dialog('destroy');\";\n\t\t\t\ttodo += \"}\";\n\t\t\t}else{\n\t\t\t\talerts(\"Something went wrong, configuration could not be save.\");\n\t\t\t}\n\t\t}\n\t});\n}",
"_onDialogClosed() {\n this._selectedApplication = {};\n this.$.appscoApplicationAddSearch.reset();\n this.$.appscoApplicationAddSettings.reset();\n this._selected = 'appsco-application-add-search';\n this._dialogTitle = 'Add application';\n this._hideLoader();\n }",
"function addApplication(admin, app, applicationName) {\n //will find the application with the name in params\n app.db.models.applications.find({\n where: { applicationName: applicationName }\n })\n .then(appToAdd => {admin.addApplications([appToAdd]);})\n .catch(error => res.status(412).json({ msg: error.message }));\n}",
"function saveProtocolEntry() {\r\n clearErrors();\r\n var dataToSend = prepareDataForAddProtocolEntry();\r\n if(dataToSend == null) {\r\n return;\r\n }\r\n enableInput(false);\r\n execAjax(dataToSend, protocolEntrySaved);\r\n loadProtocolList();\r\n }",
"onSaveActiveItemOptions(event) {\n console.log('triggerSaveFieldOptions:stub', event);\n }",
"function saveConfigtoDB(confName,ftype){\n\tfor(var a=0; a< globalMAINCONFIG.length;a++){\n\t\tglobalMAINCONFIG[a].MAINCONFIG[0].Flag = 0;\n\t\tif(globalMAINCONFIG[a].MAINCONFIG[0].PageCanvas == pageCanvas){\n\t\t\tglobalMAINCONFIG[a].MAINCONFIG[0].FileType = $('#saveConfFileTypeDBType > option:selected').html().toString();\n\t\t\tglobalMAINCONFIG[a].MAINCONFIG[0].Name = confName;\n\t\t}\n\t}\n\tvar qry = getStringJSON(globalMAINCONFIG[pageCanvas]);\n\t$.ajax({\n\t\turl: getURL(\"ConfigEditor\", \"JSON\"),\n\t\tdata : {\n\t\t\t\"query\": qry,\t\t\t\n\t\t\t\"action\": \"insert\"\n\t\t},\n\t\tmethod: 'POST',\n\t\tproccessData: false,\n\t\tasync:false,\n\t\tdataType: 'html',\n\t\tsuccess: function(data) {\n\t\t\tvar dat = data.replace(/'/g, '\"');\n\t\t\tvar data = $.parseJSON(dat);\n\t\t\tvar result = data.RESULT[0].Result;\n\t\t\tif(result==1){\n\t\t\t\talerts(\"Configuration saved to the database.\",\"todo\", \"graph\");\n\t\t\t\tglobalMAINCONFIG[pageCanvas].MAINCONFIG[0].Flag =1;\n\t\t\t\tFileType =\"\";\n\t\t\t\tvar todo = \"if(globalDeviceType=='Mobile'){\";\n\t\t\t\t\ttodo += \"$('#saveConfig').dialog('destroy');\";\n\t\t\t\t\ttodo +=\t\"}else{\";\n\t\t\t\t\ttodo +=\t\"$('#configPopUp').dialog('destroy');\"\n\t\t\t\t\ttodo += \"}\";\n\t\t\t}else{\n\t\t\t\talerts(\"Something went wrong. \\nConfiguration NOT saved on the database.\");\n\t\t\t}\n\t\t}\n\t});\n}",
"static add(req, res) {\n // Make sure we have everything\n if(req.body.name && req.body.assertion_endpoint) {\n // Add the application into database\n let app = new Application({\n userId: req.user._id,\n name: req.body.name,\n assertionEndpoint: req.body.assertion_endpoint\n });\n app.save()\n .then(app => {\n req.flash('success', 'Application created with ID ' + app._id.toString());\n res.redirect(getRealUrl('/developer'));\n })\n .catch(e => {\n req.flash('error', 'Unknown Error: ' + JSON.stringify(e));\n ApplicationController._backToAddPage(res);\n })\n } else {\n req.flash('error', 'Name and Assertion Endpoint are required parameters.');\n ApplicationController._backToAddPage(res);\n }\n }",
"function userApply () {\n updateMe().then(function() {\n $scope.listingId // Push listingId into User Applications Array\n // Push userId into Listing Applications Array\n var user = Parse.User.current();\n if (user){\n user.addUnique(\"applications\", $scope.listingId)\n user.save();\n } else {\n alert(\"Yikes! For some reason the little magic elves aren't working hard enougha and your application did not submit. Try again later. Every good elf needs a break.\")\n }\n });\n }",
"function menuSaveClick() {\n requestSave();\n}",
"function save() {\n\twriteFile(config, CONFIG_NAME);\n\tglobal.store.dispatch({\n\t\ttype: StateActions.UPDATE_CONFIGURATION,\n\t\tpayload: {\n\t\t\t...config\n\t\t}\n\t})\n}",
"formSave() {\n $(document).off('click', '#form-save');\n $(document).on('click', '#form-save', $.proxy(function(){\n //convert form to json object\n var formInJSON = save.saveData(\".\"+this.options.subElement);\n\n var title = formInJSON.title;\n //if sid on the url params then it will become the filename of the editor\n if (\"sid\" in this.params && this.params.sid !== undefined) {\n title = this.params.sid;\n }\n //options for the pcapi\n var options = {\n remoteDir: \"editors\",\n path: encodeURIComponent(title)+\".json\",\n data: JSON.stringify(formInJSON)\n };\n\n //check if the survey is public\n if(this.params.public === 'true'){\n options.urlParams = {\n 'public': 'true'\n };\n }\n\n //store the form to pcapi\n pcapi.updateItem(options).then(function(result){\n utils.giveFeedback(\"Your form has been saved successfully\");\n });\n\n }, this));\n }",
"function processNextApp() {\n\t\t\tif (appIds.length > 0) {\n\t\t\t\tcurrentApp = appIds.shift();\n\t\t\t\tcurrentPage = firstPage;\n\t\t\t\tqueuePage();\n\t\t\t} else {\n\t\t\t\temit('done with apps');\n\t\t\t}\n\t\t}",
"function saveFrameworkPublish() {\n hideModalError(FWK_PUBLISH_MODAL);\n if (isValidPublishDataFromFrameworkPublish()) {\n showModalBusy(FWK_PUBLISH_MODAL,\"Publishing framework...\");\n setTimeout(function() {\n hideModalBusy(FWK_PUBLISH_MODAL);\n enableModalInputsAndButtons();\n },\n 3000);\n }\n}",
"function SaveACPSettings(savePath)\r\n{\r\n\tConsole.PrintLine(\"\");\r\n\tConsole.PrintLine (\"Saving ACP Settings\");\r\n\tfor (var i in ACP_File_List)\r\n\t\t{\r\n\t\tvar fileName = ACP_File_List[i];\r\n\t\tif (FSO.FileExists(ACPApp.Path + \"\\\\\" + fileName))\r\n\t\t\t{ // Copy FilterInfo.txt\r\n\t\t\tFSO.CopyFile(ACPApp.Path + \"\\\\\" + fileName, savePath + \"\\\\\" + fileName);\r\n\t\t\tConsole.PrintLine(\" \" + fileName + \" saved\");\r\n\t\t\t}\r\n\t\t}\r\n\t\r\n\t// Copy Active.clb file \r\n\t// need to delete previously saved Active.clb \r\n\tSafeDeleteFile(savePath + \"\\\\Active.clb\");\r\n\tvar srcFile = Util.PointingModelDir + \"\\\\Active.clb\";\r\n\tif (FSO.FileExists(srcFile))\r\n\t\t{ // Copy Active.clb\r\n\t\tFSO.CopyFile(srcFile, savePath + \"\\\\Active.clb\");\r\n\t\tConsole.PrintLine(\" Active.clb saved\");\r\n\t\t}\r\n\t\t\r\n\t// Create Settings file\r\n\t/************************* Don't need this for now\r\n\tvar fileOK = false;\r\n\ttry {\r\n\t\tvar settingFile = FSO.CreateTextFile(savePath + \"\\\\Settings.txt\", true); // Make new Settings file\r\n\t\tfileOK = true;\r\n\t} catch(e) {\r\n Console.PrintLine(\"**Failed to create ACP Settings file: \" + \r\n (e.description ? e.description : e));\r\n }\t\r\n \r\n // Write ACP settings\r\n\tif (fileOK)\r\n\t\t{\r\n\t\tsettingFile.WriteLine(\"Setting 1: 123\"); \r\n\t\r\n\t\tsettingFile.Close();\r\n\t\t}\r\n\t****************/\r\n \r\n\t// Create ACP Registry file\r\n\tExportRegistryFile (savePath + \"\\\\\" + ACPREGFILE);\r\n\tVerifyRegistryFile (savePath + \"\\\\\" + ACPREGFILE);\r\n\t\r\n}",
"function addProgram() {\n\tlocation = \"EditPage.php?mode=add&what=program\";\n}",
"InstallApplication(string, string, int, string, string, string) {\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
1.2 connect make the process of subscribling to store, checking for updated data, and triggering a rerender can be made more genetic c and resuable Each wrapper component is an individual subscriber to the Redux store | function connect(mapSteteToProps, mapDispatchToProps) {
return function(WrappedComponent) {
return class extends React.Component {
render() {
return (
<WrappedComponent
{...this.props}
{/*and addtitonal props calculated from redux store */}
{...mapStateToProps(store.getState(), this.props)}
{...mapDispatchToProps(store.dispatch, this.props)}
/>
)
}
componentDidMount() {
// it remembers to subscribe to the store so it doesn't miss updates
this.unsubscribe = store.subscribe(this.handleChange.bind(this));
}
componentWillUnmount() {
this.unsubscribe();
}
handleChange() {
// whenever the store state changes, it re-renders
this.forceUpdate();
}
}
}
} | [
"initConnectedComponent (withRef) {\n let result = connect(\n // note that we do not pass this.mapDispatchToProps directly since connect() needs to know that the function\n // has a single parameter, and this.mapDispatchToProps (being the result of calling bind() in the constructor) has zero parameters\n // in other words: this.mapDispatchToProps.length is zero, whereas ((dispatch) => this.mapDispatchToProps(dispatch)).length is one.\n this.mapStateToProps, (dispatch) => this.mapDispatchToProps(dispatch), this.mergeProps,\n {withRef: withRef}\n )(Adapter);\n result.displayName = 'Connect(Adapter)';\n return result;\n }",
"function selectorFactory(dispatch, mapStateToProps, mapDispatchToProps) {\n //cache the DIRECT INPUT for the selector\n //the store state\n let state\n //the container's own props\n let ownProps\n\n //cache the itermediate results from mapping functions\n //the derived props from the state\n let stateProps\n //cache the derived props from the store.dispatch\n let dispatchProps\n\n //cache the output\n //the return merged props(stateProps + dispatchProps + ownProps) to be injected to wrappedComponent\n let mergedProps\n\n // the source selector is memorizable.\n return function selector(nextState, nextOwnProps) {\n //before running the actual mapping function, compare its arguments with the previous one\n const propsChanged = !shallowEqual(nextOwnProps, ownProps)\n const stateChanged = !strictEqual(nextState, state)\n\n state = nextState\n ownProps = nextOwnProps\n \n //calculate the return mergedProps based on different scenarios \n //to MINIMIZE the call to actual mapping functions\n //notice: the mapping function itself can be optimized by Reselect, but it is not the concern here\n \n //case 1: both state in redux and own props change\n if (propsChanged && stateChanged) {\n //derive new props based on state\n stateProps = mapStateToProps(state, ownProps)\n //since the ownProps change, update dispatch callback if it depends on props\n if (mapDispatchToProps.length !== 1) dispatchProps = mapDispatchToProps(dispatch, ownProps)\n //merge the props\n mergedProps = mergeProps(stateProps, dispatchProps, ownProps)\n return mergedProps\n }\n\n //case 2: only own props changes\n if (propsChanged) {\n //only update stateProps and dispatchProps if they rely on ownProps\n if (mapStateToProps.length !== 1) stateProps = mapStateToProps(state, ownProps) //it just call the mapping function\n if (mapDispatchToProps.length !== 1) dispatchProps = mapDispatchToProps(dispatch, ownProps)\n mergedProps = mergeProps(stateProps, dispatchProps, ownProps)\n return mergedProps\n }\n\n //case 3: only store state changes\n // 1.since stateProps depends on state so must run mapStateToProps again\n // 2.for dispatch, since store.dispatch and ownProps remain the same, no need to update\n if (stateChanged) {\n const nextStateProps = mapStateToProps(state, ownProps)\n const statePropsChanged = !shallowEqual(nextStateProps, stateProps)\n stateProps = nextStateProps\n //if stateProps changed, update mergedProps by calling the mergeProps function\n if (statePropsChanged) mergedProps = mergeProps(stateProps, dispatchProps, ownProps)\n return mergedProps\n }\n\n //case 4: no change, return the cached result if no change in input\n return mergedProps;\n }\n}",
"handlePublished() {\n this.setState({ status: 'PUBLISHED' });\n const data = {\n userId: this.props.reduxStore.user.id,\n status: 'PUBLISHED'\n }\n this.props.dispatch({ type: 'FETCH_DASHBOARD', payload: data });\n }",
"function connect(mapStateToProps, mapDispatchToProps) {\n for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n args[_key - 2] = arguments[_key];\n }\n\n return _reactRedux.connect.apply(undefined, [mapStateToProps ? function (state, props) {\n /**\n * If props.slice is set then call the underlying\n * mapStateToProps with the slice as the state argument,\n * extended with the current state as the root. If\n * there is no props.slice (typically the top level)\n * then use state directly.\n **/\n if (props.slice) return mapStateToProps(props.slice, props);\n return mapStateToProps(state, props);\n } : null, mapDispatchToProps ? function (dispatch, props) {\n /**\n * Call the underlying mapDispatchToProps passing the\n * slice as the second argument (with the same check\n * as above).\n **/\n if (props.slice) return mapDispatchToProps(dispatch, props.slice, props);\n return mapDispatchToProps(dispatch, props, props);\n } : null].concat(args));\n}",
"function mapStateToProps(state) {\n return {\n store: state,\n };\n}",
"function mapStateToProps(state) {\n return{\n data:state.activeData\n };\n}",
"function mapActionCreatorsToProps(dispatch) {\n return bindActionCreators({}, dispatch)\n}",
"subscription() {\n const currState = this.store.getState();\n const schema = _store.getIfChanged(\"schema\");\n if (schema) {\n this.visualization1.setSchema(JSON.parse(schema));\n this.visualization2.setSchema(JSON.parse(schema));\n }\n this.visualization1.setViewOptions({\n ...currState\n });\n this.visualization2.setViewOptions({\n ...currState\n });\n }",
"_copyReactRedux() {\n var reactReduxContext = this._getReactReduxContext();\n\n this.fs.copyTpl(\n this.templatePath(appConfig.config.path.reactRedux.templatePath + '/' + reactReduxContext.indexHTML),\n this.destinationPath(appConfig.config.path.reactRedux.destinationPath + '/' + reactReduxContext.indexHTML),\n {\n appName: _.startCase(this.appname)\n }\n );\n\n this.fs.copyTpl(\n this.templatePath(appConfig.config.path.reactRedux.templatePath + '/' + reactReduxContext.indexJS),\n this.destinationPath(appConfig.config.path.reactRedux.destinationPath + '/' + reactReduxContext.indexJS),\n {\n appName: this._formatAppName(this.appname),\n styleFramework: this.styleframework\n }\n );\n\n this.fs.copyTpl(\n this.templatePath(appConfig.config.path.reactRedux.templatePath + '/' + reactReduxContext.components + '/' + 'RootComponent.js'),\n this.destinationPath(appConfig.config.path.reactRedux.destinationPath + '/' + reactReduxContext.components + '/' + this.appname + '.js'),\n {\n appName: this.appname,\n styleFramework:this.styleframework\n }\n );\n\n this.fs.copy(\n this.templatePath(appConfig.config.path.reactRedux.templatePath + '/' + reactReduxContext.constant),\n this.destinationPath(appConfig.config.path.reactRedux.destinationPath + '/' + reactReduxContext.constant)\n );\n\n\n this.fs.copy(\n this.templatePath(appConfig.config.path.reactRedux.templatePath + '/' + reactReduxContext.actions),\n this.destinationPath(appConfig.config.path.reactRedux.destinationPath + '/' + reactReduxContext.actions)\n );\n\n this.fs.copy(\n this.templatePath(appConfig.config.path.reactRedux.templatePath + '/' + reactReduxContext.store),\n this.destinationPath(appConfig.config.path.reactRedux.destinationPath + '/' + reactReduxContext.store)\n );\n\n this.fs.copy(\n this.templatePath(appConfig.config.path.reactRedux.templatePath + '/' + reactReduxContext.reducer),\n this.destinationPath(appConfig.config.path.reactRedux.destinationPath + '/' + reactReduxContext.reducer)\n );\n\n this.fs.copy(\n this.templatePath(appConfig.config.path.reactRedux.templatePath + '/' + reactReduxContext.images),\n this.destinationPath(appConfig.config.path.reactRedux.destinationPath + '/' + reactReduxContext.images)\n );\n\n this.fs.copy(\n this.templatePath(appConfig.config.path.pureReact.templatePath + '/' + reactReduxContext.styles+'/'+'scss'),\n this.destinationPath(appConfig.config.path.pureReact.destinationPath + '/' + reactReduxContext.styles+'/'+'scss')\n );\n\n if(this.styleframework === 'uxframework'){\n this.fs.copy(\n this.templatePath(appConfig.config.path.pureReact.templatePath + '/' + reactReduxContext.styles+'/'+'main-ux-frmwrk.scss'),\n this.destinationPath(appConfig.config.path.pureReact.destinationPath + '/' + reactReduxContext.styles+'/'+'main.scss')\n );\n }else{\n this.fs.copy(\n this.templatePath(appConfig.config.path.pureReact.templatePath + '/' + reactReduxContext.styles+'/'+'main.scss'),\n this.destinationPath(appConfig.config.path.pureReact.destinationPath + '/' + reactReduxContext.styles+'/'+'main.scss')\n );\n }\n }",
"render() {\n\n return (<Provider store={store}><Root><MainLayout/></Root></Provider>);\n\n }",
"function mapActionCreatorsToProps(dispatch) {\n return bindActionCreators(GalleryActions, dispatch);\n}",
"subscribeRedis() {\n const self = this;\n Y.log( `Redis client subscribing to channel: ${self.CHANNEL_NAME}`, 'debug', NAME );\n self.redisIn.subscribe( self.CHANNEL_NAME );\n }",
"function mapDispatchToProps(dispatch){\n//action creator binds it with action Fetch Weather! \n return bindActionCreators({ fetchWeather} , dispatch)\n}",
"subscribe(receiver) {\n const manager = getLiveCollectionManager();\n return manager.subscribeCollection(this.collection, receiver);\n }",
"componentDidMount() {\n this.props.dispatch(loadDiscounts())\n }",
"componentDidMount() {\n const action = { type: 'FETCH_HOP_USAGE' };\n this.props.dispatch(action);\n }",
"_registerUpdates() {\n const update = this.updateCachedBalances.bind(this);\n this.accountTracker.store.subscribe(update);\n }",
"function mapDispatchToProps(dispatch) {\n // whenever the action is called, bindActionCreators will pass the result to all of our reducers\n return bindActionCreators({\n generateBoard,\n placeBombs,\n setRemainingTiles,\n markTile,\n revealBombs,\n }, dispatch);\n}",
"componentWillMount() {\n if (this.props.locations) {\n locationStore.handleUpdateLocations(this.props.locations);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets up menu selection events. | function menuEvents () {
var chooseLibrary = document.getElementById('choose-library');
var viewArtists = document.getElementById('view-artists');
var viewAlbums = document.getElementById('view-albums');
var viewSongs = document.getElementById('view-songs');
chooseLibrary.addEventListener('click', emitEvent('menu: choose-lib'));
viewArtists.addEventListener('click', emitEvent('menu: artists'));
viewAlbums.addEventListener('click', emitEvent('menu: albums'));
viewSongs.addEventListener('click', emitEvent('menu: songs'));
} | [
"function initSelection() {\n canvas.on({\n \"selection:created\": function __listenersSelectionCreated() {\n global.console.log(\"**** selection:created\");\n setActiveObject();\n toolbar.showActiveTools();\n },\n \"before:selection:cleared\": function __listenersBeforeSelectionCleared() {\n global.console.log(\"**** before:selection:cleared\");\n },\n \"selection:cleared\": function __listenersSelectionCleared() {\n global.console.log(\"**** selection:cleared\");\n toolbar.hideActiveTools();\n },\n \"selection:updated\": function __listenersSelectionUpdated() {\n global.console.log(\"**** selection:updated\");\n setActiveObject();\n toolbar.showActiveTools();\n },\n });\n}",
"static onSelect() {\n const node = Navigator.byItem.currentNode;\n if (MenuManager.isMenuOpen() || node.actions.length <= 1 ||\n !node.location) {\n node.doDefaultAction();\n return;\n }\n\n ActionManager.instance.menuStack_ = [];\n ActionManager.instance.menuStack_.push(MenuType.MAIN_MENU);\n ActionManager.instance.actionNode_ = node;\n ActionManager.instance.openCurrentMenu_();\n }",
"function menuClicks () {\n\n\t\tvar menuIcon = document.getElementById('menu-icon');\n\n\t\tmenuIcon.addEventListener('click', Views.showMenu);\n\t\tmenuLinks();\n\n\t}",
"init() {\n this._eventLoop.on(EventNames.APP_NAVIGATION_MENU_LOAD, () => this._loadMenu());\n this._eventLoop.on(EventNames.MENUITEMS_OPENPREFERENCES, (evt) => this._handleOpenPreferences(evt.evtData));\n this._eventLoop.on(EventNames.MENUITEMS_OPENGENIUS, (evt) => this._handleOpenGenius(evt.evtData));\n }",
"static initMainMenuEvents() {\n\n // Event for hiding modal and clear all inputs\n\n $('.modal').on('hidden.bs.modal', function () {\n $(this).find('input[type=text]').each((index, elem) => {\n elem.value = \"\";\n });\n $(this).find('input[type=number]').each((index, elem) => {\n elem.value = \"\";\n });\n $(this).find('img').each((index, elem) => {\n $(elem).attr('src', '');\n });\n\n // Let's clear validation's signs\n\n Validator.clearSigns($(this));\n\n });\n\n // Event for showing new tab and hiding previous tab\n\n let that = this;\n\n $('#mainMenu>ul>li:not(:last-of-type)').click(function () {\n\n // Let's show the tab\n\n that.showTab($(this).index());\n\n // Let's hide the prev tab\n\n $(\"#mainMenu>ul>li.active\").removeClass('active');\n\n $(this).addClass('active');\n\n });\n\n // Event for exiting the program\n\n $('#mainMenu>ul>li:last-of-type').click(() => {\n this.exitProgram();\n })\n\n }",
"add_select(func) {\n this.add_event(\"select\", func);\n }",
"onSelectionChange(cb) {\n this.on('selection-change', cb)\n }",
"function attachMenuMouseEvents(menu) {\n\n\t// Adding mouse events to toggle visibility on mouse over/out.\n\tmenu.onmouseover = function() {toggleSubMenu(this);};\n\tmenu.onmouseout = function() {toggleSubMenu(this);};\n\n}",
"selectionSetDidChange() {}",
"_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 onSelectStart(event){\n\n if (event instanceof MouseEvent && !renderer.xr.isPresenting()){\n\t// Handle mouse click outside of VR.\n\t// Determine screen coordinates of click.\n\tvar mouse = new THREE.Vector2();\n\tmouse.x = (event.clientX / window.innerWidth) * 2 - 1;\n\tmouse.y = - (event.clientY / window.innerHeight) * 2 + 1;\n\t// Create raycaster from the camera through the click into the scene.\n\tvar raycaster = new THREE.Raycaster();\n\traycaster.setFromCamera(mouse, camera);\n\n\t// Register the click into the GUI.\n\tGUIVR.intersectObjects(raycaster);\n }\n\n}",
"function onSelectStart(event){\n\n if (event instanceof MouseEvent && !renderer.xr.isPresenting()){\n\t// Handle mouse click outside of VR.\n\n\t// Determine screen coordinates of click.\n\tvar mouse = new THREE.Vector2();\n\tmouse.x = (event.clientX / window.innerWidth) * 2 - 1;\n\tmouse.y = - (event.clientY / window.innerHeight) * 2 + 1;\n\t// Create raycaster from the camera through the click into the scene.\n\tvar raycaster = new THREE.Raycaster();\n\traycaster.setFromCamera(mouse, camera);\n\n\t// Register the click into the GUI.\n\tGUIVR.intersectObjects(raycaster);\n\n } else if (!(event instanceof MouseEvent) && renderer.xr.isPresenting()){\n\t// Handle controller click in VR.\n\n\t// Bug workaround, Oculus Go browser doubles onSelectStart\n\t// event.\n\tif (navigator.platform == \"Linux armv8l\"){\n\t if (oculus_double_click_skip){\n\t\tconsole.log(\"SKIPPING\");\n\t\toculus_double_click_skip = false;\n\t\treturn;\n\t }\n\t oculus_double_click_skip = true;\n\t}\n\n\t// Retrieve the pointer object.\n\tvar controller = event.target;\n\tvar controllerPointer = controller.getObjectByName('pointer');\n\n\t// Create raycaster from the controller position along the\n\t// pointer line.\n\tvar tempMatrix = new THREE.Matrix4();\n\ttempMatrix.identity().extractRotation(controller.matrixWorld);\n\tvar raycaster = new THREE.Raycaster();\n\traycaster.ray.origin.setFromMatrixPosition(controller.matrixWorld);\n\traycaster.ray.direction.set(0, 0, -1).applyMatrix4(tempMatrix);\n\n\t// Register the click into the GUI.\n\tGUIVR.intersectObjects(raycaster);\n\n\t//DEBUG.displaySession(renderer.xr);\n\t//DEBUG.displaySources(renderer.xr);\n\t//DEBUG.displayNavigator(navigator);\n\n }\n}",
"function bindMenuItemEvent(item){ \n\t\t\titem.hover( \n\t\t\t\tfunction(){ \n\t\t\t\t\t// hide other menu \n\t\t\t\t\titem.siblings().each(function(){ \n\t\t\t\t\t\tif (this.submenu){ \n\t\t\t\t\t\t\thideMenu(this.submenu); \n\t\t\t\t\t\t} \n\t\t\t\t\t\t$(this).removeClass('menu-active'); \n\t\t\t\t\t}); \n\t\t\t\t\t \n\t\t\t\t\t// show this menu \n\t\t\t\t\titem.addClass('menu-active'); \n\t\t\t\t\tvar submenu = item[0].submenu; \n\t\t\t\t\tif (submenu){ \n\t\t\t\t\t\tvar left = item.offset().left + item.outerWidth() - 2; \n\t\t\t\t\t\tif (left + submenu.outerWidth() > $(window).width()){ \n\t\t\t\t\t\t\tleft = item.offset().left - submenu.outerWidth() + 2; \n\t\t\t\t\t\t} \n\t\t\t\t\t\tshowMenu(submenu, { \n\t\t\t\t\t\t\tleft: left, \n\t\t\t\t\t\t\ttop:item.offset().top - 3 \n\t\t\t\t\t\t}); \n\t\t\t\t\t} \n\t\t\t\t}, \n\t\t\t\tfunction(e){ \n\t\t\t\t\titem.removeClass('menu-active'); \n\t\t\t\t\tvar submenu = item[0].submenu; \n\t\t\t\t\tif (submenu){ \n\t\t\t\t\t\tif (e.pageX>=parseInt(submenu.css('left'))){ \n\t\t\t\t\t\t\titem.addClass('menu-active'); \n\t\t\t\t\t\t} else { \n\t\t\t\t\t\t\thideMenu(submenu); \n\t\t\t\t\t\t} \n\t\t\t\t\t\t \n\t\t\t\t\t} else { \n\t\t\t\t\t\titem.removeClass('menu-active'); \n\t\t\t\t\t} \n\t\t\t\t\t \n\t\t\t\t} \n\t\t\t); \n\t\t}",
"_loadMenu() {\n const menuData = requireRaw(kMenuFileName);\n\n this._eventLoop.emit(EventNames.APP_NAVIGATION_MENU_LOADED, this._buildEventData(menuData));\n }",
"function FileList::SelectionChanged() \r\n\t\t{\r\n\t\t\tSelChanged();\r\n\t\t}",
"function setupMenuHandlers()\n {\n document.querySelector('#menu_english').onclick = function()\n {\n tableHelper.countriesToTable(countries.getByLanguage('English'));\n document.querySelector('#subtitle').innerHTML =\n 'List of Countries and Dependencies - \tCountry/Dep. Name is in English (English)';\n };\n document.querySelector('#menu_arabic').onclick = function()\n {\n tableHelper.countriesToTable(countries.getByLanguage('Arabic'));\n document.querySelector('#subtitle').innerHTML =\n 'List of Countries and Dependencies - \tCountry/Dep. Name is in Arabic (عربى)';\n };\n document.querySelector('#menu_chinese').onclick = function()\n {\n tableHelper.countriesToTable(countries.getByLanguage('Chinese'));\n document.querySelector('#subtitle').innerHTML =\n 'List of Countries and Dependencies - \tCountry/Dep. Name is in Chinese (中文 )';\n };\n document.querySelector('#menu_french').onclick = function()\n {\n tableHelper.countriesToTable(countries.getByLanguage('French'));\n document.querySelector('#subtitle').innerHTML =\n 'List of Countries and Dependencies - \tCountry/Dep. Name is in French (Française)';\n };\n document.querySelector('#menu_hindi').onclick = function()\n {\n tableHelper.countriesToTable(countries.getByLanguage('Hindi'));\n document.querySelector('#subtitle').innerHTML =\n 'List of Countries and Dependencies - \tCountry/Dep. Name is in Hindi (हिंदी)';\n };\n document.querySelector('#menu_korean').onclick = function()\n {\n tableHelper.countriesToTable(countries.getByLanguage('Korean'));\n document.querySelector('#subtitle').innerHTML =\n 'List of Countries and Dependencies - \tCountry/Dep. Name is in Korean (한국어)';\n };\n document.querySelector('#menu_japanese').onclick = function()\n {\n tableHelper.countriesToTable(countries.getByLanguage('Japanese'));\n document.querySelector('#subtitle').innerHTML =\n 'List of Countries and Dependencies - \tCountry/Dep. Name is in Japanese (日本語)';\n };\n document.querySelector('#menu_russian').onclick = function()\n {\n tableHelper.countriesToTable(countries.getByLanguage('Russian'));\n document.querySelector('#subtitle').innerHTML =\n 'List of Countries and Dependencies - \tCountry/Dep. Name is in Russian (русский)';\n };\n document.querySelector('#menu_population_100_000_000m').onclick = function()\n {\n tableHelper.countriesToTable(countries.getByPopulation(100000000));\n document.querySelector('#subtitle').innerHTML =\n 'List of Countries and Dependencies - \tPopulation ( >=1000000000)';\n };\n document.querySelector('#menu_population_1m_2m').onclick = function()\n {\n tableHelper.countriesToTable(countries.getByPopulation(1000000, 2000000));\n document.querySelector('#subtitle').innerHTML =\n 'List of Countries and Dependencies - \tPopulation ( 1~2 Million )';\n };\n document.querySelector('#menu_americas_1mkm').onclick = function()\n {\n tableHelper.countriesToTable(countries.getByAreaAndContinent('Americas', 1000000));\n document.querySelector('#subtitle').innerHTML =\n 'List of Countries and Dependencies - \t1 million Km' + '2'.sup() + ' area in America';\n };\n document.querySelector('#menu_asia_all').onclick = function()\n {\n tableHelper.countriesToTable(countries.getByAreaAndContinent('Asia'));\n document.querySelector('#subtitle').innerHTML =\n 'List of Countries and Dependencies - \tAll size, Asia';\n };\n }",
"_onSelectedChanged() {\n if (this._selected !== 'appsco-application-add-search') {\n this.$.addApplicationAction.style.display = 'block';\n this.playAnimation('entry');\n this._addAction = true;\n }\n else {\n this._addAction = false;\n this.playAnimation('exit');\n }\n }",
"function menuHighlightClick() {\n Data.Edit.Mode = EditModes.Highlight;\n updateMenu();\n}",
"onSelectionChange(func){ return this.eventSelectionChange.register(func); }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implemet some performance test cases. The makeid function is from to generate 100 character string composed of characters picked randomly from the set [azAZ09] . | function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 1000; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
} | [
"function generateIdChar(){\n var elegibleChars = \"abcdefghijklmnopqrstubwxyz\";\n var range = elegibleChars.length;\n var num = Math.floor(Math.random() * range);\n return elegibleChars.charAt(num);\n}",
"function makeGameId(){\n let result = '';\n let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n let charactersLength = characters.length;\n for ( let i = 0; i < 6; i++ ) {\n \tresult += characters.charAt(Math.floor(Math.random() * charactersLength));\n\t}\n\treturn result;\n}",
"function _makeChangeId() {\n var arr = 'a,b,c,d,e,f,0,1,2,3,4,5,6,7,8,9'.split(',');\n var rnd = '';\n for (var i = 0; i < 40; i++) {\n rnd += arr[Math.floor(Math.random() * arr.length)];\n }\n\n return rnd;\n }",
"function makeId (){\n function s4() {\n //generate random number to create a unique id for every item sent to the checkout page\n return Math.floor((1 + Math.random()) * 0x10000)\n .toString(16)\n .substring(1);\n }\n //return a random long random number generated above\n return s4() + s4() + '-' + s4() + '-' + s4() + '-' +\n s4() + '-' + s4() + s4() + s4();\n}",
"gen_id(type){\n\n var str_prefix = \"\";\n var num_id = null;\n var arr_elems = null;\n switch (type) {\n case 'tool': str_prefix = \"t-\"; arr_elems= this.get_nodes('tool'); break;\n case 'data': str_prefix = \"d-\"; arr_elems= this.get_nodes('data'); break;\n case 'edge': str_prefix = \"e-\"; arr_elems= this.get_edges(); break;\n }\n\n var ids_taken = [];\n for (var i = 0; i < arr_elems.length; i++) {\n ids_taken.push(parseInt(arr_elems[i]._private.data.id.substring(2)));\n }\n\n var num_id = 1;\n while (num_id <= arr_elems.length) {\n if (ids_taken.indexOf(num_id) == -1) {\n break;\n }else {\n num_id++;\n }\n }\n\n var num_zeros = 3 - num_id/10;\n var str_zeros = \"\";\n for (var i = 0; i < num_zeros; i++) {\n str_zeros= str_zeros + \"0\";\n }\n return str_prefix+str_zeros+num_id;\n }",
"function generateIdentifierFromSeed(s)\n{\n\t// generate first char\n\tlet s1 = s % USE_CHARS.length;\n\tlet ret = USE_CHARS[s1];\n\ts = Math.floor((s - s1) / USE_CHARS.length);\n\t\n\twhile (s > 0)\n\t{\n\t\tlet s2 = (s - 1) % USE_CHARS.length;\n\t\tret = USE_CHARS[s2] + ret;\t\t// ensures the change is always the last char, which probably helps gzip\n\t\ts = Math.floor((s - (s2 + 1)) / USE_CHARS.length);\n\t}\n\t\n\treturn identifierPrefix + ret;\n}",
"function generateUID() {\n return String(~~(Math.random()*Math.pow(10,8)))\n}",
"function _randId() {\n\t\t// Return a random number\n\t\treturn (new Date().getDate())+(''+Math.random()).substr(2)\n\t}",
"GenerateInstanceID() {\n var text = \"\";\n\n for (var i = 0; i < 16; i++)\n text += this.ValidIDChars.charAt(Math.floor(Math.random() * this.ValidIDChars.length));\n\n return text;\n }",
"generateCode() {\n return (Math.random().toString(16).substr(2, 4) + \"-\" \n + Math.random().toString(16).substr(2, 4) + \"-\" \n + Math.random().toString(16).substr(2, 4)).toUpperCase();\n }",
"function doGenerateUniqueID(studyID, caseID) {\n let newCID = caseID.includes('-') ? caseID.replace('-','') : caseID;\n return `${studyID}-${newCID}`\n}",
"function generateUID(length) {\n var rtn = '';\n for (let i = 0; i < UID_LENGTH; i++) {\n rtn += ALPHABET.charAt(Math.floor(Math.random() * ALPHABET.length));\n }\n return rtn;\n}",
"function generateTestStrings(cnt, len) {\n\tlet test = [];\n\tfor(let i=0; i<cnt; i++) {\n\t\t// generate a string of the specified len\n\t\ttest[i] = getRandomString(len, 0, 65535);\n//\t\ttest[i] = getRandomString(len, 0, 55295);\n\t}\n\treturn test;\n}",
"function define_id() {\n var iddef = 0;\n while ( iddef == 0 || iddef > 9999 || FIN_framework.STORYWALKERS.checkids(iddef) ) {\n iddef = Math.floor(Math.random()*10000);\n }\n return iddef;\n }",
"function makeTuid() {\n return crypto.randomBytes(16).toString('hex')\n}",
"function generate_discount_code() {\n var text = \"\";\n var possible = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\n for (var i = 0; i < 10; i++)\n text += possible.charAt(Math.floor(Math.random() * possible.length));\n\n return \"#\" + text;\n}",
"static generateId() {\n return cuid_1.default();\n }",
"function build_unique_id(options) {\n\t\t\toptions._iter = options._iter ? ++options._iter : 1;\n\t\t\tif (options._iter >= 1000) {\t\t\t\t\t\t\t\t\t\t\t\t// monitor loop count, all stop after excessive loops\n\t\t\t\tlogger.warn('[component lib] yikes, recursive loop exceeded trying to build unique id:', options.id_str, options._iter);\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tif (Array.isArray(options.taken_ids) && options.taken_ids.includes(options.id_str)) {\t\t// is this id taken?\n\t\t\t\tconst regex_last_numb = RegExp(/(\\d*)$/);\t\t\t\t\t\t\t\t// find the last number in a string\n\t\t\t\tconst matches = options.id_str.match(regex_last_numb);\n\t\t\t\tconst last_number = (matches && matches[1]) ? Number(matches[1]) : null;\n\n\t\t\t\tif (last_number === null) {\t\t\t\t\t\t\t\t\t\t\t\t// no suffix delim... but we found a number, increment last pos by 1\n\t\t\t\t\toptions.id_str += '_0';\n\t\t\t\t\tlogger.warn('[component lib] id is already taken, appending id suffix', options.id_str);\n\t\t\t\t} else {\n\t\t\t\t\toptions.id_str = options.id_str.replace(regex_last_numb, Number(last_number) + 1);\n\t\t\t\t\tlogger.warn('[component lib] id is already taken, incrementing id suffix', options.id_str);\n\t\t\t\t}\n\t\t\t\treturn build_unique_id(options);\t\t\t\t\t\t\t\t\t\t// repeat, check if its still taken...\n\t\t\t}\n\n\t\t\treturn options.id_str;\n\t\t}",
"function shortId() {\n\treturn crypto\n\t\t.randomBytes(5)\n\t\t.toString(\"base64\")\n\t\t.replace(/\\//g, \"_\")\n\t\t.replace(/\\+/g, \"-\")\n\t\t.replace(/=+$/, \"\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Opens the tab and returns the sheet name | function getTab(spreadsheetId,tabNumber) {
var tab = tabNumber;
var id = spreadsheetId;
var ss = SpreadsheetApp.openById(id);
var sheet = ss.getSheets()[tab];
sheet.activate();
Logger.log("readTab: " + sheet.getName());
return sheet;
} | [
"function openTab(sport){\n url = sport.concat(\"_calc.html\")\n const link = document.createElement('a');\n link.href = url;\n window.open(url, \"_self\");\n}",
"function gotoTab() {\n let url_string = window.location.href;\n let url = new URL(url_string);\n let tab = url.searchParams.get(\"open\");\n // console.log('url', tab);\n if (tab) {\n // console.log('has tab');\n let idName = '#' + tab;\n let idTabName = idName + 'Tab';\n // console.log('name', idName, idTabName);\n switchTab($(idTabName), idName);\n }\n}",
"function excel_define_sheet_name(excel) {\n var excel = excel || $JExcel.new();\n sheet_name = sheet_name || \"Summary\"\n sheet_number = sheet_number || 0\n excel.set(sheet_number, undefined, undefined, sheet_name);\n return excel\n}",
"function showTab(tabName) {\n var template = document.querySelector(tabName);\n\n const params = new URLSearchParams(window.location.search);\n if (tabName === '#announcements') {\n template.content.querySelector('#club-name').value = params.get('name');\n template.content.querySelector('#schedule-club-name').value = params.get('name');\n template.content.querySelector('#timezone').value = Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n\n const node = document.importNode(template.content, true);\n document.getElementById('tab').innerHTML = '';\n document.getElementById('tab').appendChild(node);\n\n if (tabName === '#about-us') {\n getClubInfo();\n } else if (tabName === '#announcements') {\n getClubInfo();\n loadAnnouncements();\n showHidePostAnnouncement();\n loadScheduledAnnouncements();\n } else if (tabName === '#calendar') {\n loadCalendar();\n }\n}",
"function NewTab() {\n window.open(url, \"_blank\");\n }",
"function SpreadsheetTest(){\n this.sheets = [new SheetTest(\"Sheet1\", this)];\n this.activeSheet = 0;\n}",
"function show_job(page, process_name) {\n // Save info of the opened tab\n msg_or_job = 'Job';\n ProcessJobUpdate(page, process_name, true);\n}",
"function openImport()\n{\n // navigates the user to import.html\n chrome.tabs.update({'url': chrome.extension.getURL('import.html')});\n}",
"function makeRecruitSheet(){\nvar sheetname = 'BUILDING - Recruits Sheet'\nvar ss = SpreadsheetApp.getActiveSpreadsheet(), newSheet;\nnewSheet = ss.insertSheet();\nnewSheet.setName(sheetname);\n}",
"function BAGetActiveCSSTitle() {\n\tvar sheets = BAGetStyleSheets();\n\tvar ret = '';\n\tif (sheets) {\n\t\tfor (var i = 0, n = sheets.length; i < n; i++) {\n\t\t\tif (!sheets[i].disabled && sheets[i].title) {\n\t\t\t\tret = sheets[i].title;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn ret;\n}",
"function doOpenTool_newTab(url)\n{\n var br = getBrowser();\n br.selectedTab = br.addTab(url);\n}",
"function activeTabIntoPanel() {\n chrome.tabs.query({\n active: true,\n currentWindow: true\n }, function(tabs) {\n tabIntoPanel(tabs[0]);\n });\n}",
"_focusFirstTab () {\n this.tabs[0].focus()\n }",
"function articleSheet(){\n if(!articleSheetInstance) articleSheetInstance = sheet(\"articles\")\n return articleSheetInstance\n}",
"function SheetName(){\r\n var d = new Date();\r\n //return d.getFullYear().toString() + \"-\" + (d.getMonth() + 1).toString().padStart(2, '0') + \"-\" + LastSunday();\r\n return d.getFullYear().toString().substr(-2) + WeekOfYear();\r\n}",
"downloadSpreadsheet() {\n if (this.reportKey !== null) {\n window.open(this.properties.reportServerUrl + '?key=' + this.reportKey + '&outputFormat=xlsx', '_blank');\n }\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 getSelectedTab(tabs) {\n const childId = window.location.hash.split(\"=\")[1];\n return tabs.find(tab => tab.get(\"actor\").includes(childId));\n}",
"function viewWelcomeSheet(args) {\r\n // Run a batch operation against the Excel object model\r\n Excel.run(function (ctx) {\r\n // Check App logging\r\n Checklog(ctx);\r\n return ctx.sync()\r\n .then(function () {\r\n if (logRange.values[0] == \"Off\") {\r\n loggingFlag = 0;\r\n } else {\r\n loggingFlag = 1;\r\n }\r\n // Queue commands to select and activate Welcome sheet\r\n var sheet = ctx.workbook.worksheets.getItem(\"Welcome\");\r\n sheet.activate();\r\n var range = sheet.getRange(\"A1\");\r\n range.select();\r\n logEntry(ctx, \"Welcome\", \"Welcome sheet is active.\");\r\n //Run the queued-up commands, and return a promise to indicate task completion\r\n return ctx.sync();\r\n })\r\n })\r\n .catch(function (error) {\r\n handleError(error);\r\n });\r\n args.completed();\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates new Square.js at x, y | function genSquare(xP, yP) {
let s = new Square(xP, yP);
stage.addChild(s.view);
} | [
"function createSquare(x, y) {\ngameAreaContext.fillStyle = \"#568000\";\ngameAreaContext.fillRect(x * cellWidth, y * cellWidth, cellWidth, cellWidth)\n}",
"function Square() {}",
"constructor(x = 0, y = 0) {\n this.x = x; // position for x \n this.y = y; // position for y\n }",
"function addSquare() {\n var square = document.createElement(\"div\");\n square.className = \"square\";\n square.style.left = parseInt(Math.random() * 650) + \"px\";// 0 ~ (700 -50)\n square.style.top = parseInt(Math.random() * 250) + \"px\";//0 ~ (300-50)\n square.style.backgroundColor = getRandomColor();\n square.onclick = squareClick;\n \n var squarearea = document.getElementById(\"squarearea\");\n squarearea.appendChild(square);\n }",
"constructor (size) {\n /* Constructor function to create new instance of Square through Rectangle attributes and methods */\n super(size, size);\n }",
"function Terrain_Square(x,y,w,h,type,which_sprite_array,name_of_sprite_sheet){\n\n\tthis.x = x * w;\n\tthis.y = y * h; \n\tthis.w = w;\n\tthis.h = h;\n\n\t//console.log(\"1which_sprite_array is: \" + which_sprite_array);\n\t\n\t//so that these 4 values dont need to be calculated over and over again. \n\tthis.ulc_x = this.x;\n\tthis.urc_x = this.x + this.w;\n\tthis.ulc_y = this.y;\n\tthis.llc_y = this.y + this.h;\n\n\tthis.contains_mouse = false;\n\tthis.color = \"black\";//random default. not associated with any type currently. \n\n\tif(type == 0){\n\t\tthis.color = \"yellow\";\n\t}\n\telse if(type == 1){\n\t\tthis.color = \"red\";\n\t}\n\n\t\n\tthis.type = type; //can it be walked on.\n\tthis.sprite_sheet = document.getElementById(name_of_sprite_sheet);\n\tthis.ssi = new SSI();\n\tthis.ssi.set_x_y_w_h_dw_and_dh(which_sprite_array[0],\n\t\t\t\t\t\t\t\t which_sprite_array[1],\n\t\t\t\t\t\t\t\t which_sprite_array[2],\n\t\t\t\t\t\t\t\t which_sprite_array[3],\n\t\t\t\t\t\t\t\t this.w,\n\t\t\t\t\t\t\t\t this.h\n\t\t\t\t\t\t\t\t );\n\n}",
"spawnBlock(x, y) {\n let block = new Block(this, x, y);\n }",
"function makeSquares() {\n squareSize = sizeArray[j];\n //squareSize = sizeArray[j];\n for (let x = 0; x < width; x += squareSize) {\n for (let y = 0; y < height; y += squareSize) {\n fill(int(random(200, 255)), 0, int(random(100, 150)));\n rect(x, y, squareSize, squareSize);\n }\n }\n}",
"function createVertex(x, y) {\n return { x: x, y: y };\n}",
"toCoordinate() {\n assertParameters(arguments);\n \n return new Coordinate(this._width, this._height);\n }",
"constructor(x,y,w,h,r,g,b,)\n {\n this.x = x;\n this.y = y;\n this.w = w;\n this.h = h;\n this.r = r;\n this.g = g;\n this.b = b;\n }",
"function getSquare(x, y) {\n const full_id = \"square_\" + x + \"_\" + y;\n const square = document.getElementById(full_id);\n if (square) {\n return square;\n } return \"none\";\n }",
"set(x, y, value) {\n const index = this.linear(x, y);\n\n return new Matrix2D(this.xSize, this.ySize, [\n ...this.data.slice(0, index),\n value,\n ...this.data.slice(index + 1)\n ])\n }",
"updateSquares() {\n if(this.squareProps.length !== this.squares.length) {\n const diff = this.squareProps.length - this.squares.length;\n if(diff > 0) {\n for (let i = 0; i < diff; i++) {\n let newSquareInstance = this.baseSquare.createInstance(\"\" + i);\n this.squares.push(newSquareInstance);\n }\n } else {\n while(this.squares.length > this.squareProps.length) {\n const inst = this.squares[this.squares.length - 1];\n inst.dispose();\n this.squares.pop();\n }\n }\n }\n for (let i = 0; i < this.squareProps.length; i++) {\n const props = this.squareProps[i];\n const square = this.squares[i];\n square.position.x = props.x;\n square.position.y = -props.y;\n square.scaling.x = props.w;\n square.scaling.y = props.h;\n }\n\n this.scene.executeWhenReady(() => {\n this.scene.render();\n })\n }",
"function makeSnakeSquare(row, column) {\n // make the snakeSquare jQuery Object and append it to the board\n let snakeSquare = document.createElement('div');\n snakeSquare.setAttribute('class', 'snakeSquare');\n board.appendChild(snakeSquare);\n\n // set the position of the snake on the screen\n repositionSquare(snakeSquare, row, column);\n \n // add snakeSquare to the end of the body Array and set it as the new tail\n snake.body.push(snakeSquare);\n snake.tail = snakeSquare;\n \n return snakeSquare;\n}",
"function point(xx,yy){\nthis.x = xx;\nthis.y = yy;\n}",
"function updateSquare(width, height, x, y, color, graphics) {\n const rect = new Phaser.Geom.Rectangle(width, height, x, y);\n graphics.clear();\n graphics.fillStyle = { color: `0x${color}` };\n graphics.fillRectShape(rect);\n}",
"placeAt(xx, yy, obj) {\r\n var xc = this.cw * xx + this.cw / 2;\r\n var yc = this.ch * yy + this.ch / 2;\r\n obj.x = xc;\r\n obj.y = yc;\r\n }",
"function drawSquare(xCoord, yCoord, boxWidth, whiteBox) {\n \tborderWidth;\n \tstroke(borderColor); // grey\n \tfill(whiteBox); // white\n \trect(xCoord, yCoord, boxWidth, boxHeight); //drawing white box\n \n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get groups that userId is in | static async getByUser(userId) {
const result = await db.query(
`SELECT user_id, group_id
FROM user_groups
WHERE user_id = $1`,
[userId]);
return result.rows;
} | [
"userGroups (id) {\n return this._apiRequest(`/user/${id}/groups`)\n }",
"listGroupUsers (id) {\n assert.equal(typeof id, 'number', 'id must be number')\n return this._apiRequest(`/group/${id}/users`)\n }",
"function getGroupInfo(body){\n\t\treturn new Promise(function(resolve, reject) {\n\t\t\tvar sql = 'SELECT region_id, region_type_id FROM region_groups WHERE id = ?';\n\t\t\tdatabase.mysql.query(sql, [body.group_id], databaseHandler);\n\t\t\tfunction databaseHandler(err, result) {\n\t\t\t\tif(err) {\n\t\t\t\t\treject({message: \"internal database error: \" + err.message});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (result.length == 0){\n\t\t\t\t\treject({message: \"error finding group for id \" + group_id});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tbody.region_id = result[0].region_id;\n\t\t\t\tbody.region_type_id = result[0].region_type_id;\n\t\t\t\tresolve(body);\n\t\t\t\treturn;\n\t\t\t}\n\t\t})\n\t}",
"getGroup (id) {\n assert.equal(typeof id, 'number', 'id must be number')\n return this._apiRequest(`/group/${id}`)\n }",
"checkUserExistenceInGroup(hub, group, userId, options) {\n const operationOptions = coreHttp.operationOptionsToRequestOptionsBase(options || {});\n return this.client.sendOperationRequest({ hub, group, userId, options: operationOptions }, checkUserExistenceInGroupOperationSpec);\n }",
"listAllGroups () {\n return this._apiRequest('/groups/all')\n }",
"get groupsObject () {\n const result = {}\n for (const [key, val] of this.groups) {\n result[key] = Array.from(val)\n }\n return result\n }",
"function getGroupChannelsForUser(username, groupname){\n var ret = [];\n var user = getUserByName(name);\n var group = getGroupByName(groupname);\n for(ch in group.channelList){\n var isValid = false;\n for(u in ch.users){\n if(u.name == username){\n isValid = true;\n }\n }\n if(user.perms >= 1 || isValid){\n ret.push(ch.name);\n }\n }\n return ret;\n}",
"isGroupMember (groupId) {\n let user = this.get('currentUser');\n if (!Ember.isArray(user.groups)) {\n // if the provider has not been configured to load groups, show a warning...\n Ember.debug('Session.isGroupMember was called, but torii-provider-arcgis has not been configured to fetch user groups. Please see documentation. (https://github.com/dbouwman/torii-provider-arcgis#ember-cli-torii-provider-arcgis)');\n return false;\n } else {\n // look up the group in the groups array by it's Id\n let group = user.groups.find((g) => {\n return g.id === groupId;\n });\n if (group) {\n return true;\n } else {\n return false;\n }\n }\n }",
"removeUserFromGroup (id, userId) {\n assert.equal(typeof id, 'number', 'id must be number')\n assert.equal(typeof userId, 'number', 'userId must be number')\n return this._apiRequest(`/group/${id}/user/${userId}`, 'DELETE')\n }",
"function userform_addGroupToUser() {\n\tvar RN = \"userform_addGroupToUser\";\n\tvar su = userform_lookupSelectedUser();\n\tvar agl = document.getElementById('AvailableGroupList');\n\tvar gl = document.getElementById('GroupList');\n\tif (agl && gl) {\n\t\tunHighLightList(\"GroupList\");\n\t\tunHighLightList(\"AccessControlList\");\n\t\tfor (var i = agl.options.length-1 ; i > 0 ; i--) {\n\t\t\tdbg (1, RN + \": move agl/\" + i + \" to gl\");\n\t\t\tif (agl.options[i].selected) {\n\t\t\t\tvar opt = agl.options[i];\n\t\t\t\tif (browserType_IE) agl.options[i] = null;\n\t\t\t\tgl.options[gl.options.length] = opt;\n\t\t\t\tuserhash[su][opt.value] = new Object;\n\t\t\t}\n\t\t}\n\t\tenableList(\"AccessControlList\");\n\t\tDBG_objDump(userhash, \"userhash\");\n\t\tuserform_setAclHash();\n\t\tsortList(\"GroupList\");\n\t\tsortList(\"AvailableGroupList\");\n\t} else {\n\t\tdbg (1, RN + \": cant find AvailableGroupList and/or GroupList object\");\n\t}\n\treturn false;\n}",
"function getFamilyUserIds(userId, callback)\n{\n if(userId)\n { \n relationModule.findOne({ hooksForUserId: userId }).then(function (relation) {\n if(relation && relation.trees && relation.trees.length > 0)\n { \n var userDetails;\n for(var treeCount=0;treeCount<relation.trees.length;treeCount++)\n {\n if(relation.trees[treeCount].relations && relation.trees[treeCount].relations.length > 0)\n {\n for(var relCount=0;relCount<relation.trees[treeCount].relations.length;relCount++)\n {\n userDetails = (userDetails) ? userDetails + \",'\" + relation.trees[treeCount].relations[relCount].userId+\"'\" : \n \"'\" +relation.trees[treeCount].relations[relCount].userId+\"'\";\n //userDetails = (userDetails) ? userDetails + \",\" + relation.trees[treeCount].relations[relCount].userId : \n //relation.trees[treeCount].relations[relCount].userId;\n }\n }\n \n if(treeCount == (relation.trees.length - 1))\n {\n callback(null, userDetails);\n }\n } \n }\n else\n {\n var error = new Error(\"No records found for members.\"); \n callback(error);\n }\n }).catch(function(err){\n callback(err); \n });\n }\n else\n { \n var error = new Error(\"User not logged in\"); \n callback(error);\n }\n}",
"function findFormsByUserID (userId) {\n userId_temp = userId;\n var userForms = [];\n for (var i in forms) {\n if (userId == forms[i].userId) {\n userForms.push(forms[i]);\n }\n }\n return userForms;\n }",
"function getOtherUsersAt(roomid, userid) {\n var otherUsers = [];\n for (var i in users) {\n if (users[i].roomid == roomid && i != userid) {\n otherUsers.push(users[i]);\n }\n }\n return otherUsers;\n}",
"function getJewelGroup(jewel){\n\tvar jewelGroup = [];\n\tgetGroup(jewel, jewelGroup);\n\treturn jewelGroup;\n}",
"viewPosts (userId) {\n const treeOfGroupsForMember = this.allChildGroups().query(q => {\n q.select('groups.id')\n q.join('group_memberships', 'group_memberships.group_id', 'groups.id')\n q.where('group_memberships.user_id', userId)\n })\n\n return Post.collection().query(q => {\n q.queryContext({ primaryGroupId: this.id }) // To help with sorting pinned posts\n q.join('users', 'posts.user_id', 'users.id')\n q.where('users.active', true)\n q.andWhere(q2 => {\n q2.where('groups_posts.group_id', this.id)\n q2.orWhere(q3 => {\n q3.whereIn('groups_posts.group_id', treeOfGroupsForMember.query())\n q3.andWhere('posts.user_id', '!=', User.AXOLOTL_ID)\n })\n })\n })\n }",
"function getGroupNames(){\n var ret = [];\n for (var i = 0; i < this.groups.length; i++) {\n ret.push(this.groups[i].name);\n }\n return ret;\n}",
"function findUserSessions(userId) {\n let db = mongoStore.db;\n let regexp = new RegExp(`.*?\\\"userId\\\":\\\"${userId}\\\".*?`);\n let query = { \"session\": { $regex: regexp } };\n if (!logoutAll) query._id = reqSessionId;\n // - - - - - - - - console.log(' ===== query ===== \\n', query);\n return new Promise((resolve, reject) => {\n db.collection('sessions').find(query).toArray( (err, res) => {\n if (err) return reject(err);\n return resolve(res);\n });\n })\n }",
"function searchUserGameList(userId) {\n return ($.ajax({\n url: urlSearchUserGameList,\n data: {\n steamid : userId,\n key : token\n }\n })\n )}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
when a post is deleted, decrement counter | function updateCategoryCountOnDelete (post) {
Categories.update({_id: {$in: post.categories}}, {$inc: {"postsCount": -1}}, {multi: true});
} | [
"function decrementCount(key) {\n if (counts[key] < 2) {\n delete counts[key];\n } else {\n counts[key] -= 1;\n }\n }",
"onDeleteClick(id){\r\n\t\tthis.props.removePost(id)\r\n\t}",
"async removePostFromUser(userId, postId) {\n let currentUser = await this.getUserById(userId);\n\n const userCollection = await users();\n const updateInfo = await userCollection.updateOne(\n { _id: userId },\n { $pull: { posts: ObjectId(postId) } }\n );\n if (!updateInfo.matchedCount && !updateInfo.modifiedCount) {\n throw 'Update failed';\n }\n }",
"removeUsersFromPosts() {\n const usersPostsRef = firebaseDB.database().ref(`/Users/${this.state.userId}/Posts`)\n usersPostsRef.on('value', snapshot => {\n let usersPosts = snapshot.val();\n for (let usersPost in usersPosts) {\n var postRef = firebaseDB.database().ref(`/Posts/${usersPost}`)\n postRef.update({\n author: \"[deleted]\"\n })\n }\n })\n }",
"downVoted() {\r\n console.log('Downvoted the page');\r\n this._articlesSeen[this.pageTitle].vote = -1;\r\n this.setStorage(Constants.STORAGE_ARTICLES, this._articlesSeen);\r\n }",
"updateNextMessageAfterDelete() {\n this.hintAboutToDeleteMessages();\n }",
"function DeletePostTrigger(){\n var triggerIDs = [properties.getProperty('scheduledPost_ID'), properties.getProperty('deleteTrigger_ID')];\n var allTriggers = ScriptApp.getProjectTriggers();\n for(var i = 0; i < allTriggers.length; i++){\n for(var j = 0; j < triggerIDs.length; j++){\n var trigger = allTriggers[i]\n var triggerID = trigger.getUniqueId();\n if(triggerID == triggerIDs[j]){\n ScriptApp.deleteTrigger(trigger);\n }\n }\n }\n DeleteProperty('scheduledPost_ID');\n DeletePropery('deleteTrigger_ID');\n}",
"function prevMsgDelete() {\n message.delete([300])\n .then(msg => console.log(`Deleted message from ${msg.author.username}`))\n .catch(console.error);\n }",
"function decrement(){\n\ttimeNumber--;\n\n\t//Show time in time span\n\t$(\".time\").html(timeNumber);\n\n\t//if time runs out, set question to unanswered. \n\tif(timeNumber === 0){\n\t\tsetQuestionUnanswered();\n\t}\n}",
"function deleteButtonPressed(entity) {\n db.remove(entity);\n }",
"countDecrease(item) {\n if (item.count <= 1) {\n this.msg2;\n }\n else {\n item.count = item.count - 1;\n this.isErrorMsg = false;\n }\n }",
"'click #delete'() {\n Meteor.call('setStatusCatador', this._id, '', 'D');\n }",
"function decrease() {\n\t_interval && clearInterval( _interval );\n\t_interval = setInterval(function(){\n\t\t_counter = parseInt(_counter) - 5;\n\t\tif( _counter <= 0 ){\n\t\t\t_counter = 0;\n\t\t\tif( _cinterval++ > 25 ){\n\t\t\t\t_interval && clearInterval( _interval );\n\t\t\t\t_cinterval = 0;\n\t\t\t}\n\t\t}\n\t\t_headerbar.refresh_advice.setHeight( _counter + '%' );\n\t\t_headerbar.refresh_counter.setWidth( _counter + '%' );\n\t\t/**** /\tTi.API.info( 'decrease >>> _counter:' + _counter ); /****/\n\t\treturn true;\n\t}, 20);\n\treturn true;\n}",
"function removeFromDeck() {\n\tvar name = \"count_\" + deckCounter;\n\tshowImage('deckImage', name, 'deckHolder');\n}",
"function decrement() {\n qTimer--;\n $(\"#timer\").html(\"<h2>\" + qTimer + \"</h2>\");\n\n if (qTimer === 0) {\n stop();\n } \n }",
"getNewPostId() {\n const store = model.getLocalStore();\n\n // Get the current highest post id\n let latestPost = _.max(store.posts, post => {\n return post.id;\n });\n // Return new unique id\n return latestPost.id + 1;\n }",
"async deleteIfMoreThan(maxNum) {\n console.log(`== Try to delete data if the stored records is more than ${maxNum} ==`);\n\n const count = await this.baseModel.model.count();\n\n if (count > maxNum) {\n await this.delete([{\n $sort: {\n timestap: -1\n },\n }, {\n $limit: count - maxNum\n }]);\n }\n\n console.log(`== Success to delete data if the stored records is more than ${maxNum} ==`);\n }",
"function fixCommentsCounters( oldPostId, newPostId, mod ){\n //Fix old post \n var $cc = $( \"#post-\" + oldPostId ).find( \".comment-count\" );\n var currentNoc = parseInt( $cc.text() );\n $cc.text( currentNoc - mod );\n\n //Fix new post\n $cc = $( \"#post-\" + newPostId ).find( \".comment-count\" );\n currentNoc = parseInt( $cc.text() );\n $cc.text( currentNoc + mod );\n\n //Fix comment counter for every comment \n $( \"#the-comment-list tr:not(.wptc-special-drop)\" ).each( function(){\n var thisPostComCount = $( this ).find( \".post-com-count\" );\n if( thisPostComCount.length ){\n var thisPostId = $( this ).wptc().getData( \"postId\" );\n if( thisPostId == oldPostId ){\n var $cc = thisPostComCount.find( \".comment-count\" );\n var currentNoc = parseInt( $cc.text() );\n $cc.text( currentNoc - mod );\n } else if( thisPostId == newPostId ){\n var $cc = thisPostComCount.find( \".comment-count\" );\n var currentNoc = parseInt( $cc.text() );\n $cc.text( currentNoc + mod );\n }\n }\n });\n }",
"enterPostDecrementExpression(ctx) {\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setter for details The setter method is expecting a details sting The method will create a Details object and set the value to the detail string | set details(details) {
if (Lang.isNull(details)) return;
let detailsObj = new Details();
detailsObj.value = details;
this._study.details = detailsObj;
} | [
"setDetails ( googlePlaceDetails ) {\n this.phoneNumber = googlePlaceDetails.international_phone_number || 'unavailable';\n this.url = googlePlaceDetails.website || 'unavailable';\n this.detailsLoaded = true;\n }",
"get details() {\n if (this._study.details) {\n return this._study.details.value;\n } else {\n return \"\";\n }\n }",
"add(name, detail){\n // add a contact detail by the name\n // This mimics Map.set(key, value)\n this.details[name] = detail;\n }",
"function setDetails(imageUrl, titleText) {\n 'use strict';\n var detailImage = document.querySelector(DETAIL_IMAGE_SELECTOR);\n detailImage.setAttribute('src', imageUrl);\n\n var detailTitle = document.querySelector(DETAIL_TITLE_SELECTOR);\n detailTitle.textContent = titleText;\n}",
"function addDetail(key, val) {\n var obj = instructorData.additionalData.moreDetails;\n\n obj[key] = val;\n\n return obj;\n}",
"updateReservationDetails(state, details) {\n Object.assign(state.reservationDetails, details);\n }",
"generateDetailData() {\n const userLabel = this.i18n.name;\n const emailLabel = this.i18n.email;\n const contactLabel = this.i18n.contact;\n const statusLabel = this.i18n.status;\n const roleLabel = this.i18n.role;\n let role = '';\n if (this.detailPageData.unitDetailsData.roles[0] === this.i18n.b2badmingroup) {\n role = this.detailPageData.unitDetailsData.leaseSigner\n ? this.i18n.adminWithLeaseSigner\n : this.i18n.admin;\n } else if (this.detailPageData.unitDetailsData.roles[0] === this.i18n.b2bcustomergroup) {\n role = this.detailPageData.unitDetailsData.leaseSigner\n ? this.i18n.buyerWithLeaseSigner\n : this.i18n.buyer;\n }\n\n Object.assign(this.detailPageData.detailsData, {\n id: this.detailPageData.unitDetailsData.uid,\n status: this.detailPageData.unitDetailsData.active,\n parent: this.detailPageData.unitDetailsData.parent,\n displayData: {\n [userLabel]: this.detailPageData.unitDetailsData.name,\n [emailLabel]: this.detailPageData.unitDetailsData.displayUid,\n [contactLabel]: this.detailPageData.unitDetailsData.cellPhone\n ? this.detailPageData.unitDetailsData.cellPhone\n : this.i18n.phoneMessage,\n [statusLabel]: this.detailPageData.unitDetailsData.active\n ? this.i18n.enabled\n : this.i18n.disabled,\n [roleLabel]: role,\n },\n userApprovalStatus: this.detailPageData.unitDetailsData.userApprovalStatus,\n });\n\n Object.assign(this.editUserData, {\n firstName: this.detailPageData.unitDetailsData.firstName,\n lastName: this.detailPageData.unitDetailsData.lastName,\n uid: this.detailPageData.unitDetailsData.uid,\n email: this.detailPageData.unitDetailsData.displayUid,\n oldEmail: this.detailPageData.unitDetailsData.displayUid,\n parentUnit: {\n label: this.detailPageData.unitDetailsData.unit.name,\n value: this.detailPageData.unitDetailsData.unit.uid,\n },\n role: this.detailPageData.unitDetailsData.roles[0],\n leaseSigner: this.detailPageData.unitDetailsData.leaseSigner,\n userApprovalStatus: this.detailPageData.unitDetailsData.userApprovalStatus,\n });\n\n this.existingUserData = Object.assign({}, this.editUserData);\n }",
"set description(aValue) {\n this._logger.debug(\"description[set]\");\n this._description = aValue;\n }",
"function setTripDetails() {\n\t\t\t\t\t// Trip Name\n\t\t\t\t\t$('#edit-trip-form-trip-name').val(trip.name);\n\t\t\t\t\t// Dates\n\t\t\t\t\t$('#edit-trip-form-start-date').data(\"DateTimePicker\").date(trip.start_date);\n\t\t\t\t\tstart_date = trip.start_date;\n\t\t\t\t\t$('#edit-trip-form-end-date').data(\"DateTimePicker\").minDate(start_date);\n\t\t\t\t\t$('#edit-trip-form-end-date').data(\"DateTimePicker\").date(trip.end_date);\n\t\t\t\t\tend_date = trip.end_date;\n\t\t\t\t\t$('#edit-trip-form-start-date').data(\"DateTimePicker\").maxDate(end_date);\n\t\t\t\t // Flexible Dates\n\t\t\t\t if (trip.are_dates_flexible) {\n\t\t\t\t \t$('#flexible-dates-checkbox').prop('checked', true);\n\t\t\t\t }\n\t\t\t\t // Companions\n\t\t\t\t $(\"#edit-trip-form-companion-count\").val(trip.companion_count);\n\t\t\t\t // Notes\n\t\t\t\t $('#edit-trip-form-notes').val(trip.notes);\n\t\t\t\t}",
"updateSummary() {\n const summary = this.details.drupalGetSummary();\n this.detailsSummaryDescription.html(summary);\n this.summary.html(summary);\n }",
"function show_edit_location_details (detail_type, detail_id) {\n\t\t$(\"#modal_title_location_details\").html(\"Edit \" + detail_type);\n\t\t$(\"#location_detail_name_label\").html( \"Location \" + detail_type + \" name\");\n\t\t$(\"#location_detail_type\").val(detail_type);\n\t\t$(\"#location_detail_id\").val(detail_id);\n\t\t$(\"#location_detail_name\").val($(\"#\" + detail_type + \"_name_\" + detail_id).html());\n\t\t$(\"#active_ld\").val($(\"#\" + detail_type + \"_active_\" + detail_id).val());\n\t\t$(\"#action_ld\").val(\"edit_location_details\");\n\t\t$(\"select\").trigger(\"chosen:updated\");\n\t\t$(\"#modal_dialog_location_details\").modal(\"show\");\n\t}",
"updateDescription(newDesc) {\n this.description = newDesc;\n }",
"function renderDetails () {\n $('#item_wrapper').append(\n $('#details_template').render( info )\n );\n }",
"function makeDetailsVisible() {\n setDetailView(\"show-details\");\n setBlurry(\"blurred-out\");\n }",
"function _genericInfo({ title, value }) {\n return HtmlBuilder.div().addClass('mt-2')\n .append(HtmlBuilder.div(HtmlBuilder.strong(title)))\n .append(HtmlBuilder.div(value))\n }",
"function show_add_new_location_details (detail_type) {\n\t\t$(\"#modal_title_location_details\").html(\"Add new \" + detail_type);\n\t\t$(\"#location_detail_name_label\").html( \"Location \" + detail_type + \" name\");\n\t\t$(\"#location_detail_type\").val(detail_type);\n\t\t$(\"#location_detail_id\").val(\"\");\n\t\t$(\"#location_detail_name\").val(\"\");\n\t\t$(\"#active_ld\").val(\"yes\");\n\t\t$(\"#action_ld\").val(\"add_location_details\");\n\t\t$(\"select\").trigger(\"chosen:updated\");\n\t\t$(\"#modal_dialog_location_details\").modal(\"show\");\n\t}",
"function viewDetails(marker) {\n\tvar tdate = new Date(marker.info.date.valueDateTime);\n\ttdate = formatDate(tdate,\"MMM, dd, yyyy, hh:mm:ss a\");\n\t//dateFormat(now, \"dddd, mmmm dS, yyyy, h:MM:ss TT\");\n\tvar tag =\"\";\n\tvar amt = parseFloat(marker.info.amount.signed).toFixed(2)\n\ttry{\n\tif(marker.info.tags.tag.text){tag =marker.info.tags.tag.text}\n\t}catch(err){}\n\tvar result ={transactionDate:tdate,transactionName:marker.info.description.cleaned,transactionAddress:marker.info.location.friendly,transactionTag:tag,amount:amt};\n\t\n\t$('ul.transList').html($('#contextItemTemplate').render(result));\n\t$.mobile.changePage('#details',{\n\t\ttransition: \"slideup\",\n\t\treverse: true,\n\t\tchangeHash: true\n\t\t\n\t});\n}",
"closeDetails() {\n this.setDetailsView(0);\n }",
"function createCreditNoteDetailLine()\n{\n\ttry\n\t{\n\t\t// create credit note line\n\t\tcreditNoteRecord.selectNewLineItem('item');\n\t\tcreditNoteRecord.setCurrentLineItemValue('item', 'item', COMMISSIONITEMINTID); \n\t\tcreditNoteRecord.setCurrentLineItemValue('item', 'amount', comTotal);\n\t\tcreditNoteRecord.setCurrentLineItemValue('item', 'taxcode', TAXINTID);\n\t\tcreditNoteRecord.commitLineItem('item');\n\t\t\n\t}\n\tcatch(e)\n\t{\n\t\terrorHandler(\"createCreditNoteDetailLine\", e);\t\t\t\t\n\t} \n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Internaul function to check variables role IDs aginst a role id array and see matching ones and return the name of the at one | function checkVariables(values, roles, i){ // Take in a role ID and see if it matches any of the IDs in the provided array of values, if it does, return the name, otherwise return undefined
const result = values.find( ({ id }) => id === roles[i] );
if (result === undefined) {
} else {
return result.name
}
} | [
"function roleExists(roleName){\r\n for (i = 0; i < Z_ROLES.length; i++) {\r\n var z_userrole = Z_ROLES[i].toString().substring(0,25).trim();\r\n\t if(z_userrole.toUpperCase() == roleName.toUpperCase()) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}",
"function checkRoles(roles){\n var possibleRoles = [\"service provider\", \"device owner\", \"infrastructure operator\", \"administrator\", \"system integrator\", \"devOps\", \"user\", \"superUser\"];\n for(var i = 0, l = roles.length; i < l; i++){\n if(possibleRoles.indexOf(roles[i]) === -1){\n return {invalid: true, message: roles[i]};\n }\n }\n return {invalid: false, message: null};\n}",
"function get_roles() {\n var retained_roles = [];\n var roles_count = $('input[type=number]');\n roles_count.each((index, r) => {\n for (var i = 0; i < r.value; i++) {\n //console.log(r.id.substring(5, retained_roles_id[i].id.length));\n retained_roles.push(roles[r.id.substring(5, r.id.length)][0]);\n }\n });\n return retained_roles;\n}",
"function seperateRole(){\n\n}",
"function getUserIdsFromRoleId(role_id) {\n var membershipProperties = openidm.read('config/commons').membershipProperties;\n if (!membershipProperties) {\n __.requestError('commons.json configuration for membershipProperties cannot be read.', 400)\n }\n \n var userIds = [];\n // Determine reverseProps based on commons.json membershipProperties\n var reverseProps = [];\n if (membershipProperties.indexOf('roles') >= 0) {\n reverseProps.push('members');\n }\n if (membershipProperties.indexOf('authzRoles') >= 0) {\n reverseProps.push('authzMembers');\n }\n \n var result = openidm.read(role_id, null, reverseProps);\n _.forEach(reverseProps, function(prop) {\n if (result && result[prop]) {\n userIds = _.union(userIds, _.map(result[prop], '_ref'));\n }\n });\n return userIds;\n}",
"function getUserRole(name, role){\n switch (role) {\n case \"admin\":\n return `${name} is admin with all access`\n break; //this is not neccesary\n\n case \"subadmin\":\n return `${name} is sub-admin acess to delete and create courses`\n break;\n\n case \"testprep\":\n return `${name} is test-prep access with to delete and create tests `\n break;\n case \"user\":\n return `${name} is a user to consume content`\n break;\n \n default:\n return `${name} is admin access with to delete and create tests `\n break;\n }\n}",
"get roleId() {\n return this.getStringAttribute('role_id');\n }",
"function getLevelRole(level) {\n let roleID;\n for (const reward of role_rewards) {\n if (level >= reward[0]) roleID = reward[1];\n }\n return roleID;\n}",
"function findRole(roleID) {\n let cost = 0;\n let roleName = \"\";\n\n db.findOne({ guildID: guildID, buyableRanks: { $elemMatch: { roleID: roleID } } }, (err, exists) => {\n if (err) console.log(err)\n if (exists) {\n cost = (exists.buyableRanks[exists.buyableRanks.map(role => role.roleID).indexOf(roleID)].cost);\n roleName = (exists.buyableRanks[exists.buyableRanks.map(role => role.roleID).indexOf(roleID)].roleName);\n sell(cost, roleName, roleID)\n } else return message.reply(\"This rank is not able to be bought or sold\").then(m => del(m, 7500));\n })\n }",
"async function isReferee(user_id) {\n const is_referee = await DButils.execQuery(`SELECT * FROM dbo.Roles WHERE userId=${user_id} and roleId=${process.env.refereeRole}`);\n return is_referee.length == 1;\n}",
"getRole (roleId) {\n assert.equal(typeof roleId, 'string', 'roleId must be string')\n return this._apiRequest(`/role/${roleId}`)\n }",
"function manageRoles(cmd){\n try{\n\t//console.log(cmd.message.channel instanceof Discord.DMChannel);\n\t//if (cmd.message.channel instanceof Discord.DMChannel) { sendMessage(cmd, \"This command currently only works in guild chats\"); return \"failure\"; }\n\tconst openRoles = roleNames.openRoles, voidRoles = roleNames.voidRoles;\n const guild = client.guilds.find(\"name\", \"Terra Battle\");\n\tconst guildRoles = guild.roles; //cmd.message.guild.roles;\n\tvar roles = cmd.details.split(\",\"), guildMember = guild.members.get(cmd.message.author.id);\n \n var feedback = \"\";\n\t//console.log(guildMember);\n\t\n\t//Check to make sure the requested role isn't forbidden\n\t//Find role in guild's role collection\n\t//Assign role (or remove role if already in ownership of)\n\t//Append response of what was done to \"feedback\"\n\troles.forEach(function(entry){\n\t\tentry = entry.trim();\n\t\tlowCaseEntry = entry.toLowerCase();\n\t\t\n\t\t//Ignore any attempts to try to get a moderator, admin, companion, bot, or specialty role.\n\t\t//Ignore: metal minion, wiki editor, content creator, pvp extraordinare\n /*voidRoles.forEach(\n function(currentValue){\n \n }\n );*/ //TODO: Manage Void Role rejection more elegantly\n\t\tif (!(voidRoles.some( x => lowCaseEntry.includes(x) )) ){\n\t\t\t\n\t\t\t//run requested role name through the roleName DB\n\t\t\tvar roleCheck = openRoles.get(lowCaseEntry); //TODO: Make a DB that allows for server-specific role name checks\n\t\t\tvar role;\n\t\t\t\n\t\t\ttry{ role = guildRoles.find(\"name\", roleCheck); }\n\t\t\tcatch (err) { \n\t\t\t\t//Role didn't exist\n\t\t\t\tconsole.log(err.message);\n console.log(\"User: \" + cmd.message.author.name);\n\t\t\t}\n\t\t\t\n\t\t\tif( typeof role === 'undefined' || role == null ){ feedback += \"So... role '\" + entry + \"' does not exist\\n\"; }\n\t\t\telse if( guildMember.roles.has(role.id) ) {\n\t\t\t\tguildMember.removeRole(role);\n\t\t\t\tfeedback += \"I removed the role: \" + role.name + \"\\n\"; }\n\t\t\telse {\n\t\t\t\tguildMember.addRole(role);\n\t\t\t\tfeedback += \"I assigned the role: \" + role.name + \"\\n\"; }\n\t\t} else { feedback += \"FYI, I cannot assign '\" + entry + \"' roles\"; }\n\t\t//guildMember = cmd.message.member;\n\t});\n\t//return feedback responses\n\t( feedback.length > 0 ? cmd.message.channel.send(feedback) : \"\" );\n } catch (err) {\n console.log(err.message);\n console.log(\"User: \" + cmd.message.author.name);\n }\n}",
"function matchMovieGenres(genreIds) {\n let movieGenresS = \"\";\n genreIds.forEach(genreId => {\n let foundGenre = allGenres.find(function(genre) {\n return genre[\"id\"] == genreId;\n });\n\n movieGenresS += foundGenre[\"name\"] + \", \";\n });\n\n return movieGenresS.substring(0, movieGenresS.length - 2);\n}",
"function employeeId(employees, employeeName) {\n for (let i=0; i<employees.length; i++) {\n if (`${employees[i].first_name} ${employees[i].last_name}` === employeeName) {\n return employees[i].id;\n };\n };\n }",
"function getOrganisationIdsByRole(user, role) {\n const organisations = user.organisations;\n return _.filter(Object.keys(organisations),\n value => organisations[value][consts.role] === role &&\n organisations[value][consts.state] === consts.states.approved);\n}",
"function cleanRoles(roles) {\n var res = [];\n roles.forEach(function (item) {\n if (item === 'standard' || item === 'guest' || item === 'admin') {\n res.push(item);\n }\n });\n return res;\n}",
"function removeRole() {\n let roleList = [], roleTitles = [], employeeList = [];\n let roleIDUpdated, roleIDSelected;\n\n // Get the role list\n let query1 = \"SELECT id, title FROM role\";\n connection.query(query1, (err, res) => {\n if (err) throw err;\n if (res.length == 0) { // Check for empty exists\n console.log(\"The role list is empty. Nothing to remove.\\n\");\n // Pause 1s\n setTimeout(() => {\n init();\n }, 1000);\n } else {\n res.forEach((val) => {\n roleList.push({ id: val.id, title: val.title });\n roleTitles.push(val.title);\n });\n inquirer.prompt([\n {\n name: \"title\",\n type: \"list\",\n message: `Choose a role to delete: `,\n choices: roleTitles // List of all current roles\n }\n ]).then((answer1) => {\n // Find the role ID for the answer\n roleList.forEach((val) => {\n if (answer1.title == val.title) {\n roleIDSelected = val.id;\n };\n });\n\n // Delete role from DB\n let query2 = `DELETE FROM role WHERE id=${roleIDSelected} `\n connection.query(query2, (err) => {\n if (err) throw err\n console.log(`${answer1.title} has been deleted.\\n`);\n // Remove role from the list\n roleTitles = roleTitles.filter((e) => { // TO DO: add a If loop for empty roleTitles\n return e != answer1.title;\n }); \n // Check if any employee is affected by the change \n let query3 = `SELECT id, role_id FROM employee WHERE role_id=${roleIDSelected}`;\n connection.query(query3, (err, res3) => {\n if (err) throw err;\n if (res3.length == 0) { // Check if exists\n console.log(\"No employee affected by the change.\\n\");\n // Pause 1s\n setTimeout(() => {\n init();\n }, 1000);\n } else {\n res3.forEach((val) => {\n if (roleIDSelected == val.role_id) {\n employeeList.push({ id: val.id, role_id: val.role_id });\n }\n });\n inquirer\n .prompt([\n {\n name: \"title\",\n type: \"list\",\n message: \"Choose a new role: \",\n choices: roleTitles // List of all current roles minus the deleted role\n }\n ]).then((answer2) => {\n // Find new role ID \n roleList.forEach((val) => {\n if (answer2.title == val.title) {\n roleIDUpdated = val.id;\n };\n });\n // Update employee role in DB\n let query4 = `UPDATE employee SET role_id=${roleIDUpdated} WHERE role_id=${roleIDSelected}`;\n connection.query(query4, (err) => {\n if (err) throw err;\n console.log(\"Employees roles updated.\\n\");\n });\n // Pause 1s\n setTimeout(() => {\n init();\n }, 1000);\n }); \n };\n });\n });\n });\n };\n });\n}",
"function extractCurrentRole() {\r\n shuffle(currentRoles);\r\n rolePopup = currentRoles.pop();\r\n playersAlive[playerPopup] = rolePopup;\r\n\r\n return rolePopup;\r\n}",
"function MAG_get_sel_auth_index() { // PR2023-02-03\n //console.log(\"=== MAG_get_sel_auth =====\") ;\n\n let sel_auth_index = null;\n\n// --- get list of auth_index of requsr\n const requsr_auth_list = [];\n if (permit_dict.usergroup_list.includes(\"auth1\")){\n requsr_auth_list.push(1)\n };\n if (permit_dict.usergroup_list.includes(\"auth2\")){\n requsr_auth_list.push(2)\n };\n\n //console.log(\" requsr_auth_list\", requsr_auth_list) ;\n // get selected auth_index (user can be chairperson / secretary and examiner at the same time)\n if (requsr_auth_list.length) {\n if (requsr_auth_list.includes(setting_dict.sel_auth_index)) {\n sel_auth_index = setting_dict.sel_auth_index;\n } else {\n sel_auth_index = requsr_auth_list[0];\n setting_dict.sel_auth_index = sel_auth_index;\n };\n };\n mod_MAG_dict.requsr_auth_list = requsr_auth_list;\n mod_MAG_dict.auth_index = sel_auth_index;\n\n //console.log(\" >> mod_MAG_dict.requsr_auth_list\", mod_MAG_dict.requsr_auth_list) ;\n //console.log(\" >> mod_MAG_dict.auth_index\", mod_MAG_dict.auth_index) ;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getEventArgs returns the event args from the transaction result, filtered by event_name. Returns the boolean `false` if no event with the given name was found. | function getEventArgs(transaction_result, event_name) {
for (var i = 0; i < transaction_result.logs.length; i++) {
var log = transaction_result.logs[i];
if (log.event == event_name) {
return log.args;
}
}
return false;
} | [
"function getEventAttendees(calendarName, eventid)\n{\n\tvar attendees = {\n\t\t\t'firstName': 'Test',\n\t\t\t'lastName': 'User'\n\t\t\t};\n\t\t\t\n\tvar myEvent = getEvent( calendarName, eventid );\n\t\n\treturn myEvent.attendees;\n}",
"function hasEvent(eventsNames, oneEvent){\n\t\t for (var i=0; i<eventsNames.length; i++) {\n\t\t if ( eventsNames[i] == oneEvent ) {\n\t\t return true;\n\t\t }\n\t\t }\n\t\t return false;\n\t\t}",
"function normalizeOnEventArgs(args) {\n if (typeof args[0] === 'object') {\n return args;\n }\n \n var selector = null;\n var eventMap = {};\n var callback = args[args.length - 1];\n var events = args[0].split(\" \");\n \n for (var i = 0; i < events.length; i++) {\n eventMap[events[i]] = callback;\n }\n \n // Selector is the optional second argument, callback is always last.\n if (args.length === 3) {\n selector = args[1];\n }\n \n return [ eventMap, selector ];\n }",
"function checkMember(name) {\n let newArr = [];\n\n name !== 'All members' ?\n arrEVs.map((w) => {\n if (w.parts.includes(name)) {\n newArr.push(w);\n }\n }) : newArr = [...arrEVs];\n clearEvents();\n trs.length ? drawEvent(newArr) : null;\n}",
"getFilterEvents() {\n\n let events = this.state.events;\n\n // Include Filtered Events\n if (this.state.filtering) {\n const eventHashes = events.map(function(e) {return e.hash;});\n const isNotCurrentEvent = (e) => eventHashes.indexOf(e.hash) === -1;\n const filteredEvents = this.state.filteredEvents.filter(isNotCurrentEvent);\n events = events.concat(filteredEvents);\n }\n\n // Remove Addressed Events\n const hiddenEvents = this.state.hiddenEvents;\n const hiddenLeads = this.state.hiddenLeads;\n const isNotHiddenEvent = (e) => hiddenEvents.indexOf(e.hash) === -1 && hiddenLeads.indexOf(e.data.lead.id) === -1; \n return events.filter(isNotHiddenEvent);\n }",
"isUserEvent(event) {\n let e = this.annotation(Transaction.userEvent)\n return !!(\n e &&\n (e == event ||\n (e.length > event.length &&\n e.slice(0, event.length) == event &&\n e[event.length] == '.'))\n )\n }",
"function hasEvent(event, entry){\n return entry.events.indexOf(event) != -1;\n}",
"function getEventDateSearch(eventName, date) {\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 index = store.index('title');\n var request = index.getAll(eventName.toString());\n return request;\n }).then( function (request) {\n if(request && request.length>0) {\n var results = [];\n //check event date against date inserted by the user\n for (var event of request) {\n if (event.date == date) {\n results.push(event);\n }\n }\n }\n displayEvents(results);\n });\n }\n}",
"async function get_event_id(tournament_name, event_name, token) {\n let variables = {\"tourneySlug\": tournament_name};\n let response = await run_query(t_queries.EVENT_ID_QUERY, variables, token);\n return filters.event_id_filter(response.data, event_name);\n}",
"function getEventSearch(eventName) {\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 index = store.index('title');\n var request = index.getAll(eventName.toString());\n return request;\n }).then( function (request) {\n displayEvents(request)\n });\n }\n}",
"supports(name) {\r\n const isEvent = this.supportedEvents.includes(name);\r\n const isMethod = typeof this[name] === 'function';\r\n return isEvent || isMethod;\r\n }",
"function is_in_guest_list(event, guest){\n var guests = event.getGuestList();\n for (var j=0; j<guests.length; j++) {\n //Logger.log(\"Check guest \"+guests[j].getEmail());\n if(guests[j].getEmail()==guest){\n var answer = guests[j].getGuestStatus();\n //Logger.log(\"Answer of \"+guest+\": \"+answer)\n return answer;\n }\n }\n return false;\n}",
"allEventABIs() {\n const allEventABIs = [];\n const { contracts, libraries, related, } = this.repoData;\n if (contracts) {\n mergeDefs(contracts);\n }\n if (libraries) {\n mergeDefs(libraries);\n }\n if (related) {\n mergeDefs(related);\n }\n return allEventABIs;\n // inner utility function for allEventABIs\n function mergeDefs(abiDefs) {\n for (const key of Object.keys(abiDefs)) {\n const defs = abiDefs[key].abi;\n for (const def of defs) {\n if (def.type === \"event\") {\n allEventABIs.push(def);\n }\n }\n }\n }\n }",
"function getEvents(){\nreturn events;\n}",
"function processArgs( a ){\n\t\t// If is from a standard GTM UA template tag, automatically allow hit.\n\t\tif( a[0] && a[0].substr && a[0].substr( 0, 3 ) == 'gtm' )\n\t\t\treturn true;\n\t\t// Call listener, return false only if listener returns false.\n\t\treturn callback( a ) !== false;\n\t}",
"static isFailedTx(result) {\n if (!result) {\n return true;\n }\n if (CommonUtil.isDict(result.result_list)) {\n for (const subResult of Object.values(result.result_list)) {\n if (CommonUtil.isFailedTxResultCode(subResult.code)) {\n return true;\n }\n if (subResult.func_results) {\n if (CommonUtil.isFailedFuncTrigger(subResult.func_results)) {\n return true;\n }\n }\n }\n return false;\n }\n if (CommonUtil.isFailedTxResultCode(result.code)) {\n return true;\n }\n if (result.func_results) {\n if (CommonUtil.isFailedFuncTrigger(result.func_results)) {\n return true;\n }\n }\n return false;\n }",
"emit(args, scope) {\n constants_1.debug('Emitting \"%s%s\" as bail', this.name, scope ? `:${scope}` : '');\n return Array.from(this.getListeners(scope)).some(listener => listener(...args) === false);\n }",
"function findElementsWithListener(eventName) {\n var registeredListeners;\n var attributeListeners;\n\n // Check the registry for listeners.\n if (_elementsWithListeners.hasOwnProperty(eventName)) {\n registeredListeners = _elementsWithListeners[eventName];\n } else {\n registeredListeners = [];\n }\n\n debugLog('Found ' + registeredListeners.length +\n ' listeners in the registry for ' + eventName + ' event.',\n registeredListeners);\n\n eventAttributeName = '[on' + eventName + ']';\n attributeListeners = Array.prototype.slice.call(\n document.querySelectorAll(eventAttributeName)\n );\n\n debugLog('Found ' + attributeListeners.length +\n ' attribute listeners for ' + eventName + ' event.',\n attributeListeners);\n\n return registeredListeners.concat(attributeListeners);\n }",
"function expectedEventsDispatched()/* : Boolean*/\n {\n for (var i/*:uint*/ = 0; i < this._expectedEventTypes$_LKQ.length; ++i )\n {\n var expectedEvent/* : String*/ = this._expectedEventTypes$_LKQ[i];\n \tif ( this.expectedEventDispatched( expectedEvent ) == false )\n \t\treturn false;\n }\n return true;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a channel which passes the react and receive results whenever react changes | createChannel(executeChannel = false) {
this.includeAggQuery();
// create a channel and listen the changes
const channelObj = manager.create(this.context.appbaseRef, this.context.type, this.react, 100, 0, false, this.props.componentId);
this.channelId = channelObj.channelId;
this.channelListener = channelObj.emitter.addListener(channelObj.channelId, (res) => {
if (res.error) {
this.setState({
queryStart: false
});
}
if (res.appliedQuery) {
const data = res.data;
let rawData;
if (res.mode === "streaming") {
rawData = this.state.rawData;
rawData.hits.hits.push(res.data);
} else if (res.mode === "historic") {
rawData = data;
}
this.setState({
queryStart: false,
rawData
});
this.setData(rawData);
}
});
this.listenLoadingChannel(channelObj);
} | [
"createChannel() {\n\t\tlet depends = this.props.depends ? this.props.depends : {};\n\t\tvar channelObj = manager.create(depends);\n\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 }",
"function notifyChannel(){\n var pushstream = new PushStream({\n host: window.location.hostname,\n port: window.location.port,\n modes: GUI.mode\n });\n pushstream.onmessage = renderMSG;\n pushstream.addChannel('notify');\n pushstream.connect();\n}",
"function createChannel(){\n return notificationsApi.postNotificationsChannels()\n .then(data => {\n console.log('---- Created Notifications Channel ----');\n console.log(data);\n\n channel = data;\n let ws = new WebSocket(channel.connectUri);\n ws.onmessage = () => {\n let data = JSON.parse(event.data);\n\n topicCallbackMap[data.topicName](data);\n };\n });\n}",
"createChannelListForGuild(guild){\n console.log(guild)\n this.setState((state, props) => ({\n guildChannels: guild.channels.cache\n }), ()=>console.log(this.state.guildChannels))\n }",
"selectChannel(id){\n console.log(id);\n this.setState((state, props) => ({\n selectedChannel: this.state.channels[id]\n }), ()=>{\n this.updateMessages();\n this.startListeningToMessages();\n })\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 idToChannel() {\n updateConfig()\n setTimeout(() => {\n AddChannel()\n }, 1000);\n }",
"function queueChannel(){\n var pushstream = new PushStream({\n host: window.location.hostname,\n port: window.location.port,\n modes: GUI.mode\n });\n pushstream.onmessage = getPlaylist;\n // pushstream.onstatuschange = function(status) {\n // force queue rendering (backend-call)\n // if (status === 2) sendCmd('renderpl');\n // };\n pushstream.addChannel('queue');\n pushstream.connect();\n}",
"function handleReceiveChannelStatusChange(event) {\n if (receiveChannel) {\n console.log(\"Receive channel's status has changed to \" +\n receiveChannel.readyState);\n }\n\n }",
"async 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}",
"listen(channel, callback) {\n this.app.logger.info('Starting listening on: ' + channel)\n this.app.db.ipfs.pubsub.subscribe(\n channel,\n message => {\n callback(message)\n this.app.logger.silly(\n 'Msg : ' +\n Buffer.from(message.data) +\n ' received from ' +\n message.from +\n ' to ' +\n channel\n )\n },\n err => {\n if (err) {\n this.app.logger.error(err)\n }\n }\n )\n }",
"function watch(sync, e, events, channel) {\n for (var i = 0; i < events.length; ++i) {\n addEventListener(e, events[i], function () {\n channel.ready = true;\n sync.update();\n });\n }\n }",
"function dataChannelStateChange() {\n if (dataChannel.readyState === 'open') {\n trace('DataChannel Opened');\n dataChannel.onmessage = receivedDataChannelMessage;\n }\n}",
"function pullChannelHistory(token, channel){\nslack.channels.history({token, channel},\n (err, data) => {\n if (err)\n console.log(err)\n else\n var messages = data.messages\n var grabAllText = messages.map((key)=> {\n return (key.text)\n })\n var obj = makeIntoObj(grabAllText)\n sendToWatson(obj)\n })\n}",
"post_to_channel(channel, message) {\n if (this.ready)\n this.instance.postMessageToChannel(channel, message);\n }",
"function libraryChannel(){\n var pushstream = new PushStream({\n host: window.location.hostname,\n port: window.location.port,\n modes: GUI.mode\n });\n pushstream.onmessage = libraryHome;\n pushstream.addChannel('library');\n pushstream.connect();\n}",
"componentWillMount() {\n this.pusher = new Pusher(process.env.PUSHER_APP_KEY, {\n cluster: process.env.PUSHER_APP_CLUSTER,\n encrypted: true\n });\n\n this.channel = this.pusher.subscribe(\"map-geofencing\");\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}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verifies that a value is a valid 65Hex Public Key string | function isValidPublicKey(value) {
if (typeof value == 'string') {
return /^[0-9a-f]{65}$/.test(value);
}
return false;
} | [
"validPublicKey(publicKey){}",
"function isValidHexCode(str) {\n\treturn /^#[a-f0-9]{6}$/i.test(str);\n}",
"validateKeyFormat(key) {\n if (key.split('-').length !== 3) {\n console.error('Invalid key format. Please try your command again.');\n process.exit(1);\n }\n return;\n }",
"function basic(cp){\r\n return cp < 0x80;\r\n // ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./\r\n }",
"function isHex(value) {\n if (value.length == 0) return false;\n if (value.startsWith('0x') || value.startsWith('0X')) {\n value = value.substring(2);\n }\n let reg_exp = /^[0-9a-fA-F]+$/;\n if (reg_exp.test(value) && value.length % 2 == 0) {\n return true;\n } else {\n return false;\n }\n}",
"static isFioPublicKeyValid(fioPublicKey) {\n const validation = (0, validation_1.validate)({ fioPublicKey }, { fioPublicKey: validation_1.allRules.fioPublicKey });\n if (!validation.isValid) {\n throw new ValidationError_1.ValidationError(validation.errors);\n }\n return true;\n }",
"function isHexPrefixed(str){return str.slice(0,2)==='0x';}",
"validPrivateKey(privateKey){}",
"function validateSecurityCode(elem){\r\n const value = elem.val();\r\n return validateTextField(elem,\r\n [(value.length === 3 || value.length === 4) && (value.match(/^\\d+$/))],\r\n [value.length >4 || !(value.match(/^\\d+$/))]\r\n );\r\n}",
"function isValidDictionaryKey(key){\n if(key == \"\") return false;\n if(key.indexOf(\"\\\"\") != -1) return false;\n return true;\n}",
"function verifyHash(hash , message , pubKey){\n \n //pubKey = forge.pki.setRsaPublicKey(new forge.jsbn.BigInteger(pubKey.n) , new forge.jsbn.BigInteger(pubKey.e));\n try{\n var md = forge.md.sha1.create();\n md.update((message));\n var success = pubKey.verify(md.digest().getBytes() , hash);\n return success;\n }\n catch(err){\n return false;\n }\n\n}",
"function checkSafePassword()\n{\n if (this.pass.length < 7) notSafe();\n var passwordArray = pass.split(\"\");\n var containBigLetter = false;\n var containSmallLetter = false;\n var containNumber = false;\n for(var i = 0; i<this.pass.length; i++)\n {\n if(passwordArray[i] >= 'A' && passwordArray[i] <= 'Z') containBigLetter = true;\n if(passwordArray[i] >= 'a' && passwordArray[i] <= 'z') containSmallLetter = true;\n if(passwordArray[i] >= '0' && passwordArray[i] <= '9') containNumber = true;\n }\n if(!containBigLetter || !containSmallLetter || !containNumber) notSafe();\n}",
"function pubKey2pubKeyHash(k){ return bytes2hex(Bitcoin.Util.sha256ripe160(hex2bytes(k))); }",
"InitializeFromEncodedPublicKeyInfo(string, EncodingType) {\n\n }",
"function isMD5Encrypted(inputString) {\r\n return /[a-fA-F0-9]{32}/.test(inputString);\r\n }",
"static isPublicAddressValid(publicAddress) {\n const validation = (0, validation_1.validate)({ publicAddress }, { publicAddress: validation_1.allRules.nativeBlockchainPublicAddress });\n if (!validation.isValid) {\n throw new ValidationError_1.ValidationError(validation.errors);\n }\n return true;\n }",
"function hex2hexKey(s){ return bigInt2hex(hex2bigIntKey(removeWhiteSpace(s))); }",
"function invalid_char(val) {\n if (val.match('^[a-zA-z0-9_]+$') == null) {\n return true\n } else {\n return false\n }\n}",
"function validateKey() {\n if ($(this).val()) {\n if ($(this).val().match(/^[A-Za-z0-9]*$/)) return hideError($(this).parent().children(\".error\"));\n else return validationError($(this).parent().children(\".error\"), i18n.KEY_VALIDATION_MESSAGE)\n }\n else return validationError($(this).parent().children(\".error\"), i18n.EMPTY_KEY_MESSAGE)\n }",
"function isMAC48Address(inputString) {\n return !!inputString.match(/^[0-9A-F]{2}(-[0-9A-F]{2}){5}$/g);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make a search tree from frequents for each list. Each node represents a prefix of a item text and contains the suggestions for that prefix. | function freqtreeInsert(tree, text, i) {
if (tree.items.length < nrOfSuggestions)
tree.items.push(text);
if (i >= Math.min(text.length, nrOfInitials))
return;
var c = text[i];
if (tree[c] == undefined)
tree[c] = {items: []};
freqtreeInsert(tree[c], text, i+1)
} | [
"function PrefixTrie() {\n\tthis._index = {};\n\tthis._root = new PrefixTrieNode();\n}",
"function makeLists() {\n\t// get reference to the list elements\n\tvar searchList = document.getElementById('searchList');\n\tvar selectedList = document.getElementById('selectedList');\n\n\t// iterate through the parsed dataset of flora (parsedFurbishData.js)\n\tfor (var i = 0; i < dataset.length; i++) {\n\n\t\t// ADDING ELEMENTS TO SEARCH RESULTS LIST\n\n\t\t// create the list item\n\t\tvar flora = document.createElement('li');\n\n\t\t// create a span element that will wrap around the common name\n\t\t// of the flora and make it bold\n\t\tvar comNameBold = document.createElement('span');\n\t\tcomNameBold.setAttribute('style', 'font-weight: bold');\n\t\tcomNameBold.appendChild(document.createTextNode(dataset[i].comName));\n\n\t\t// create another span element that will wrap around the scientific name\n\t\t// and italicize it\n\t\tvar sciNameItal = document.createElement('span');\n\t\tsciNameItal.setAttribute('style', 'font-style: italic');\n\t\tsciNameItal.appendChild(document.createTextNode(dataset[i].sciName));\n\n\t\t// set contents of the list element\n\t\tflora.appendChild(comNameBold);\n\t\tflora.appendChild(sciNameItal);\n\n\t\t// set the id of the list element to be the scientific name of the flora.\n\t\t// (remove quotes to make sure that there are no issues when using the id\n\t\t// as a function parameter)\n\t\tflora.setAttribute(\"id\", \"\" + removeQuotes(dataset[i].sciName) + \"\");\n\n\t\t// when the list element is clicked, this will call a function to select\n\t\t// that flora\n\t\tflora.setAttribute(\"onclick\", \"selectFlora('\" + removeQuotes(dataset[i].sciName) + \"')\");\n\t\t\n\t\t// Add it to the list\n\t\tsearchList.appendChild(flora);\n\n\t\t// ADDING ELEMENTS TO SELECTED FLORA LIST\n\n\t\tvar selectFlora = document.createElement('li');\n\n\t\t// adding \"sel\" to the scientific name for the id, to distinguish it from\n\t\t// the same flora in the search results list\n\t\tselectFlora.setAttribute(\"id\", \"sel\" + removeQuotes(dataset[i].sciName) + \"\");\n\n\t\t// add the bold common name and italic scientific name (must clone them, \n\t\t// otherwise the elements will be pulled from the first list)\n\t\tselectFlora.appendChild(comNameBold.cloneNode(true));\n\t\tselectFlora.appendChild(sciNameItal.cloneNode(true));\n\t\tselectFlora.setAttribute(\"onclick\", \"deselectFlora('\" + \"sel\" + \n\t\t\t\t\t\t\t\t\tremoveQuotes(dataset[i].sciName) + \"')\");\n\t\t// start off by hiding all of the elements in the selected list, \n\t\t// since none are selected at the start\n\t\tselectFlora.style.display = 'none';\n\n\t\t// Add it to the list\n\t\tselectedList.appendChild(selectFlora);\n\t}\n}",
"function matchFoodToWine(uSearch, indexer){\n var terms = uSearch.split(\" \"); //break the user search into an array of words\n var items = []; //Holds list of all wine matches based on search terms \n var i = terms.length - 1; //Iterator\n \n //Goes through search terms to find if there are paired wines in our matching table\n while(i > -1){\n if(indexer[terms[i]]){\n items = items.concat(indexer[terms[i]]);\n }\n i--;\n }\n\n //If no matches were found take the default wines\n if(items.length === 0){\n items = items.concat(indexer.default);\n }\n items.sort();//sort items by alpha\n items = getMode(items);//get item(s) that appear most frequently\n\n //If there are more than 2 varietals to search then select 2\n //at random. In the future this would be more sophisticated for \n //selection mechanism \n if (items.length > 1){\n items = pickRandom(items); //returns an item from the array to search\n }\n varietalInformation = extractVarietalInfo(items);\n return items;\n }",
"function suggest(trie_level, word, word_position, build_word, build_array) {\n\t//console.log(word, build_word, build_dist);\n\t// first check and make sure this path is okay\n\tlet curr_dist = build_array[build_array.length - 1][build_array[0].length - 1];\n\tconsole.log(\"\\n\\n\", word, build_word, curr_dist);\n\tprintMultiArray(build_array);\n\tif (word.length <= 2) {\n\t\tif (build_word != word) return suggest(trie_level.childs[word.charCodeAt(build_word.length) - 97], word, word_position + 1, build_word + word[build_word.length], new_array(build_array, word, word[build_word.length]));\n\t\treturn [...auto_complete(trie_level, word, curr_dist)];\n\t}\n\n\tif (curr_dist > 3 && Math.abs(word.length - build_word.length) < 3){\n\t\treturn []; // dud track\n\t}\n\n\tif (word_position >= word.length - 1)\n\t\t// start searching for a auto-complete\n\t\treturn [auto_complete(trie_level, build_word, curr_dist)];\n\n\t// difference between the two current words is less than 2\n\tif (Math.abs(word.length - build_word.length) < 2 && trie_level.finished) { // return\n\t\treturn [{\n\t\t\tword: build_word,\n\t\t\tload: trie_level.finished,\n\t\t\tdist: curr_dist // grab bottom right distance\n\t\t}];\n\t}\n\n\t// otherwise start looking for good paths to travel down\n\t// we can try a certain amount of levels - until the first two letters are off we can continue looking\n\tlet all_suggests = [];\n\tfor (let check_children = 0; check_children < trie_level.childs.length; check_children++)\n\t\tall_suggests = trie_level.childs[check_children] ? [...all_suggests, ...suggest(trie_level.childs[check_children], word, word_position + 1, build_word + String.fromCharCode(check_children + 97), build_array[0].length != build_array.length ? new_array(build_array, word, String.fromCharCode(check_children + 97)) : build_array)] : all_suggests;\n\n\tif (build_word.length == 0 && all_suggests.length) {\n\t\tfor (let i = 0; i < all_suggests.length; i++)\n\t\t\tall_suggests[i].signifigance = all_suggests[i].load - (all_suggests[i].dist * 3);\n\t\tquicksort(all_suggests, 0, all_suggests.length - 1, \"signifigance\");\n\t\tall_suggests = all_suggests.splice(0, 5);\n\t}\n\treturn all_suggests;\n}",
"function Autocomplete ({input, data}) {\n let tree = new Trie(data)\n console.log(tree.strings())\n console.log(tree.complete(input))\n const corpus = tree.complete(input) //save the autocomplete items inside corpus\n \n //map each item inside corpus into option for datalist\n const options = corpus.map((item) => {\n return <option value={item} />\n })\n\n return (\n <div>\n <input \n list=\"browsers\" \n name=\"browser\" \n id=\"browser\" \n />\n <datalist id=\"browsers\">\n {options}\n </datalist>\n </div>\n )\n}",
"function setUpDT() {\n filters = {\"left\":[], \"right\":[]};\n \n if (! newText ) {\n newText = \"\";\n }\n \n textInfo = new textmodel.TextHash( newText, caseSensitive, fieldNames, fieldDelim, distinguishingFieldsArray, baseField );\n if (dev) {\n saveTextHash();\n //rhx3 = null;\n }\n if (rhx3) {\n textInfo.fromJSON(rhx3); //load the precalculated info\n rhx3 = null; //free up memory\n }\n \n uniqItems = textInfo.getUniqItemsWithCounts();\n \n if (!currRt || ! textInfo.containsIndex(currRt)) {\n var which = Math.round( uniqItems.length/2 );\n currRt = uniqItems[ which ].replace(/\\t.+$/,\"\");\n }\n document.getElementById(\"toUse\").value = currRt;\n \n var arrays = textInfo.getItem(currRt, context);\n dt = new doubletree.DoubleTree();\n dt.init(\"#doubletree\").visWidth(w).handlers(handlers).showTokenExtra(showTokenExtras).sortFun(sortFun).filters(filters).nodeText(nodeFormat).rectColor(bgColor).rectBorderColor(borderColor);\n dt.setupFromArrays(arrays[0], arrays[1], arrays[2], arrays[3], caseSensitive, fieldNames, fieldDelim, distinguishingFieldsArray);\n pushHistory(currRt, false, arrays[1].length);\n }",
"autocomplete(start){\n // code here\n // We need to get to the end of our starting position ex: if we're passed \"CA\" we need to get down to the A node and search from there\n let runner = this.root;\n let word = \"\";\n let wordsArray = [];\n // For loop to check if the start is in the trie\n for(let letter = 0; letter < start.length; letter++){\n let idx = start[letter].toLowerCase().charCodeAt(0) - 97;\n if(runner.children[idx]){\n // if there is something there, head down\n word+=runner.children[idx].val;\n runner = runner.children[idx];\n console.log(`The word is currently ${word}`);\n } else {\n // If nothing is there, return the blank array because we never found anything\n console.log(\"We don't seem to have that route available, no words to show!\");\n return wordsArray;\n }\n }\n // If the place we stopped is a word, add it to the array\n if(runner.isWord){\n wordsArray.push(word);\n }\n // Call our recursive function\n for(let i = 0; i < runner.children.length; i++){\n this.autoHelper(runner.children[i], word, wordsArray);\n }\n return wordsArray;\n}",
"function createSearchIndex(items){\n const builder = new lunr.Builder();\n let fields = null;\n if (CFG.search_fields){\n fields = CFG.search_fields.slice();\n } else {\n for (const [id, item] of Object.entries(items)) {\n const cur = Object.keys(item);\n if (fields === null){\n fields = cur;\n } else {\n fields = fields.filter(f => cur.includes(f));\n }\n }\n }\n console.log('Got search fields', fields);\n fields.forEach(field => builder.field(field));\n for (const [id, item] of Object.entries(items)) {\n item.id = id;\n builder.add(item);\n }\n return builder.build();\n}",
"function initList(){\n\t\t\treturn RuffleDB.allDocs({\n\t\t\t\tlimit: 8,\n\t\t\t\tinclude_docs: true,\n\t\t\t\tdescending: true,\n\t\t\t\tstartkey: '\\uffff', // descending from last of the prefix\n\t\t\t\tendkey: ''\n\t\t\t}).then(function(items){\n\t\t\t\taddLocalRuffles(items.rows);\n\t\t\t});\n\t\t}",
"function fuzz () {\n let len = 10\n let alpha = 'abcdfghijk'\n for (let v = 0; v < len; v++) {\n for (let w = 0; w < len; w++) {\n for (let x = 0; x < len; x++) {\n for (let y = 0; y < len; y++) {\n for (let z = 0; z < len; z++) {\n let str = [alpha[v], alpha[w], alpha[x], alpha[y], alpha[z]].join('')\n let tree = STree.create(str)\n testSuffixes(tree, str)\n }\n }\n }\n }\n }\n console.log('all ok')\n}",
"function suggestedTerms(terms) {\n\n let suggested = terms.data;\n autoComp.innerHTML = `\n <li class=\"suggested\"> <i class=\"fas fa-search\"></i> <p class=\"suggested__text\">${suggested[0].name}</p></li>\n <li class=\"suggested\"> <i class=\"fas fa-search\"></i> <p class=\"suggested__text\">${suggested[1].name}</p></li>\n <li class=\"suggested\"> <i class=\"fas fa-search\"></i> <p class=\"suggested__text\">${suggested[2].name}</p></li>\n `\n\n}",
"function create_frequency_container(frequency_value, parent_table, freq_flag) {\n\tvar new_row = document.createElement('tr');\n\tnew_row.className = 'space_under';\n\tvar freq_data = document.createElement('td');\n\tfreq_data.style.width = '12em';\n\tfreq_data.style.verticalAlign = 'top';\n\tvar freq_value = document.createElement('span');\n\tvar span_class = \"word_span\";\n\tif (WORD_FREQ_CLASSES[freq_flag]) {\n\t\tspan_class += WORD_FREQ_CLASSES[freq_flag];\n\t}\n\tfreq_value.className = span_class;\n\tfreq_value.innerHTML = \"Frequency: \" + frequency_value;\n\tfreq_data.appendChild(freq_value);\n\twords_data = document.createElement('td');\n\twords_data.style.width = '75%';\n\tnew_row.appendChild(freq_data);\n\tnew_row.appendChild(words_data);\n\tparent_table.appendChild(new_row);\n\treturn words_data;\n}",
"function buildQueryList() {\n var searchString = $(\"#restaurant_search_form_searchtext_input\").val();\n if (typeof(searchstring) !== \"Undefined\" || searchString.trim.length !== 0) {\n searchString = searchString.split(\" \");\n }\n // We retrieve the list of selected select options, and then place them all in an array\n var cuisines = [];\n $(\".cuisine_select :selected\").each(function (i, selected) { cuisines[i] = $(selected).val(); });\n var diets = [];\n $(\".dietary_restriction_select :selected\").each(function (i, selected) { diets[i] = $(selected).val(); });\n // Concatenate the arrays together to get one list of keywords to search for\n searchString = searchString.concat(cuisines, diets);\n return searchString;\n}",
"function generateSuggestionsTerms(userArticleText) {\n\n var button = $('#analyze-text');\n var containerSuggestionsTerms = $('#container-suggestions-terms');\n var containerProgressiveBar = $('#container-progress-bar');\n var progressiveBar = containerProgressiveBar.find('.progress-bar');\n var tinyText = (userArticleText.length < 500) ? true : false;\n var progresBarPercentage = 0;\n var waitingTime = 0;\n\n // Performs requisition for to send data sobek.\n $.ajax({\n url: 'arfinder.php?execute=arfinder_api',\n type: 'POST',\n data: {\n 'controller': 'TextAnalyzer',\n 'task': 'analyzeText',\n 'textToSobek': userArticleText\n },\n beforeSend: function () {\n button.attr('disabled', 'disabled');\n // Hidden previous suggestions.\n containerSuggestionsTerms.addClass('d-none').removeClass('d-block');\n // Insert loader.\n containerProgressiveBar.removeClass('d-none').addClass('d-block'); \n\n progresBarPercentage = (tinyText) ? 50 : 10;\n waitingTime = (tinyText) ? 0 : 500;\n \n // Wait milseconds.\n setTimeout(function () {\n // Set progressive bar init process.\n progressiveBar.css('width', progresBarPercentage+'%');\n }, waitingTime);\n\n },\n success: function (requestResults) {\n \n waitingTime = (tinyText) ? 0 : 500;\n setTimeout(function () {\n progresBarPercentage = (tinyText) ? 100 : 30;\n progressiveBar.css('width', progresBarPercentage+'%');\n \n waitingTime = (tinyText) ? 0 : 500;\n setTimeout(function () {\n progresBarPercentage = (tinyText) ? 100 : 100;\n progressiveBar.css('width', progresBarPercentage+'%');\n \n waitingTime = (tinyText) ? 0 : 500;\n setTimeout(function () {\n // Hidden progressive bar.\n containerProgressiveBar.removeClass('d-block').addClass('d-none');\n \n // Set bar progressive to init.\n progressiveBar.css('width', '0%');\n \n requestResults = $.parseJSON(requestResults);\n // Set and display suggestions terms.\n containerSuggestionsTerms.find('#list-suggestions-terms').html(requestResults.html);\n containerSuggestionsTerms.addClass('d-block').removeClass('d-none').hide();\n\n // Show content slowly.\n containerSuggestionsTerms.show(\"slow\");\n $('html, body').animate({\n scrollTop: containerSuggestionsTerms.offset().top\n }, 500);\n\n button.removeAttr('disabled');\n\n }, waitingTime);\n }, waitingTime);\n }, waitingTime);\n\n\n // setTimeout(function(){\n // loader.remove();\n // $('#resultado').html(dataReturn);\n // }, 1000);\n }\n });\n}",
"function init_suggestedTags() {\n\n\t\tli_data = settings.suggestedTags;\n\t\tif(li_data && li_data.length) {\n\n\t\t\tfor(var i in li_data) {\n\n\t\t\t\tsuggestedTag = li_data[i].name;\n\t\t\t\tif($('li p', token_list).filter(\":contains('\" + suggestedTag + \"')\").length==0) {\n\n\t\t\t\t\t/*size adjust will increase/decrease tag size*/\n\t\t\t\t\tvar sizeAdjust = 0;\n\t\t\t\t\tif(typeof(li_data[i].size) != 'undefined') {\n\t\t\t\t\t\tsizeAdjust = li_data[i].size;\n\t\t\t\t\t}\n\n\t\t\t\t\tvar this_token = $('<li><a href=\"#\" style=\"font-size: ' + (settings.defaultSuggestTagSize+sizeAdjust) + settings.defaultSuggestTagSizeUnit + '\">'+suggestedTag+'</a></li>')\n\t\t\t\t\t.addClass(settings.classes.suggestedTag)\n\t\t\t\t\t.appendTo(suggested_tags)\n\t\t\t\t\t.click(function() {\n\n\t\t\t\t\t\tvar li = this;\n\t\t\t\t\t\tadd_new_token($('a', li).text());\n\t\t\t\t\t\t$(li).remove();\n\n\t\t\t\t\t\t//Should the whole ul be removed?\n\t\t\t\t\t\tif($('li',suggested_tags).length==0) {\n\t\t\t\t\t\t\t$(suggested_tags_container).remove();\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn false;\n\n\t\t\t\t\t});;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif($('li',suggested_tags).length==0) {\n\t\t\t\t$(suggested_tags_container).remove();\n\t\t\t}\n\t\t }\n\n\t}",
"rebuildTreeIndex() {\n let columnIndex = 0;\n\n this.#rootsIndex.clear();\n\n arrayEach(this.#rootNodes, ([, { data: { colspan } }]) => {\n // Map tree range (colspan range/width) into visual column index of the root node.\n for (let i = columnIndex; i < columnIndex + colspan; i++) {\n this.#rootsIndex.set(i, columnIndex);\n }\n\n columnIndex += colspan;\n });\n }",
"relevance(that){cov_25grm4ggn6.f[9]++;let total=(cov_25grm4ggn6.s[47]++,0);let words=(cov_25grm4ggn6.s[48]++,Object.keys(this.count));cov_25grm4ggn6.s[49]++;words.forEach(w=>{cov_25grm4ggn6.f[10]++;cov_25grm4ggn6.s[50]++;total+=this.rank(w)*that.rank(w);});//return the average rank of my words in the other vocabulary\ncov_25grm4ggn6.s[51]++;return total/words.length;}",
"function mountTree(lst) {\n\tvar tree = [];\n\tfor (var i = 0; i < lst.length; i++) {\n\t\tvar it = lst[i];\n\t\tif (!it.parentId && !it.parents) {\n\t\t\tvar res = createChildren(it, lst);\n\t\t\ttree.push(res);\n\t\t}\n\t}\n\treturn tree;\n}",
"function createWebsiteTree() {\n let finalListUI = '';\n websiteList.reverse().forEach(website => {\n if(website.url.length > 40)\n website.displayURL = website.url.substring(0, 40) + \"....\";\n else\n website.displayURL = website.url;\n const listItem = `\n <div class=\"list__item\">\n <h3>${website.displayURL}</h3>\n <svg id=\"${hashCode(website.url)}\" width=\"14\" height=\"18\" viewBox=\"0 0 14 18\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M1 16C1 17.1 1.9 18 3 18H11C12.1 18 13 17.1 13 16V4H1V16ZM3 6H11V16H3V6ZM10.5 1L9.5 0H4.5L3.5 1H0V3H14V1H10.5Z\" fill=\"#C18888\"/>\n </svg>\n </div>`;\n finalListUI += listItem\n });\n websiteListUI.innerHTML = finalListUI;\n websiteList.forEach(website => {\n getElement('#' + hashCode(website.url)+'').addEventListener('click', () => removeFromList(website.url));\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dispatches a pointer event on the current element if the browser supports it. | _dispatchPointerEventIfSupported(name, clientX, clientY, button) {
// The latest versions of all browsers we support have the new `PointerEvent` API.
// Though since we capture the two most recent versions of these browsers, we also
// need to support Safari 12 at time of writing. Safari 12 does not have support for this,
// so we need to conditionally create and dispatch these events based on feature detection.
if (typeof PointerEvent !== 'undefined' && PointerEvent) {
dispatchPointerEvent(this.element, name, clientX, clientY, { isPrimary: true, button });
}
} | [
"function PointerEventsPolyfill(t){if(this.options={selector:\"*\",mouseEvents:[\"click\",\"dblclick\",\"mousedown\",\"mouseup\"],usePolyfillIf:function(){if(\"Microsoft Internet Explorer\"==navigator.appName){if(null!=navigator.userAgent.match(/MSIE ([0-9]{1,}[\\.0-9]{0,})/)){if(parseFloat(RegExp.$1)<11)return!0}}return!1}},t){var e=this;$.each(t,function(t,n){e.options[t]=n})}this.options.usePolyfillIf()&&this.register_mouse_events()}",
"function measurement_handler(event){\n\tpointer_select_handler(event);\n}",
"function isReallyTouch(e){//if is not IE || IE is detecting `touch` or `pen`\nreturn typeof e.pointerType==='undefined'||e.pointerType!='mouse';}",
"function pointerUp(e) {\n let newMouse = {x: (e.clientX/window.innerWidth)*2-1, y: (e.clientY/window.innerHeight)*-2+1};\n if (mouse.x == newMouse.x && mouse.y == newMouse.y) { onClick(e) }\n}",
"function addEventListeners() {\n // pan watch point event\n var hammerPointer = new Hammer(document.querySelector('#pointer'));\n hammerPointer.on('pan', onPanPointer);\n}",
"startTrackingMouse() {\n if (!this._pointerWatch) {\n let interval = 1000 / Clutter.get_default_frame_rate();\n this._pointerWatch = PointerWatcher.getPointerWatcher().addWatch(interval, this.scrollToMousePos.bind(this));\n }\n }",
"function clickOnPoint() {\n var x = 58,\n y = 275;\n _DygraphOps[\"default\"].dispatchMouseDown_Point(g, x, y);\n _DygraphOps[\"default\"].dispatchMouseMove_Point(g, x, y);\n _DygraphOps[\"default\"].dispatchMouseUp_Point(g, x, y);\n }",
"function sendMouse() {\n document.addEventListener(\"mousemove\", sendSomeData);\n document.addEventListener(\"click\", sendClick);\n document.addEventListener(\"keypress\", sendKey);\n}",
"function createPointerEvent(type, clientX = 0, clientY = 0, options = { isPrimary: true }) {\n return new PointerEvent(type, {\n bubbles: true,\n cancelable: true,\n composed: true,\n view: window,\n clientX,\n clientY,\n ...options,\n });\n}",
"#addOnHelpIconClickEventListener() {\n const questionMarkDiv = this.qm;\n if (questionMarkDiv) {\n questionMarkDiv.addEventListener('click', () => {\n this.#triggerEventOnGuideBridge(this.ELEMENT_HELP_SHOWN)\n })\n }\n }",
"function onPointerUp() {\n recordDelay(delay, evt);\n removeListeners();\n }",
"implementMouseInteractions() {\t\t\n\t\t// mouse click interactions\n\t\tthis.ctx.canvas.addEventListener(\"click\", this.towerStoreClick, false);\n\t\t\n\t\t// mouse move interactions\n\t\tthis.ctx.canvas.addEventListener(\"mousemove\", this.towerStoreMove, false);\t\n\t}",
"function onPointerCancel() {\n removeListeners();\n }",
"__removeParticleEventListener(){\n Utils.changeCursor(this.myScene.canvasNode, \"pointer\");\n this.myScene.canvasNode.addEventListener(\"mousedown\", this.__removeParticleDisposableEvent);\n }",
"function f(a){/* jshint expr:true */\nif(a.target===me.video.renderer.getScreenCanvas()){\n// create a (fake) normalized event object\nvar b={deltaMode:1,type:\"mousewheel\",deltaX:a.deltaX,deltaY:a.deltaY,deltaZ:a.deltaZ};\n// dispatch mouse event to registered object\nif(\"mousewheel\"===l&&(b.deltaY=-1/40*a.wheelDelta,\n// Webkit also support wheelDeltaX\na.wheelDeltaX&&(b.deltaX=-1/40*a.wheelDeltaX)),d(b))\n// prevent default action\nreturn i._preventDefault(a)}return!0}",
"function simulateEvent($event, eventElement) {\n $(eventElement).trigger($event);\n}",
"function $ffc54430b1dbeee65879852feaaff07d$var$isVirtualClick(event) {\n // JAWS/NVDA with Firefox.\n if (event.mozInputSource === 0 && event.isTrusted) {\n return true;\n }\n\n return event.detail === 0 && !event.pointerType;\n}",
"function mousedown (event) {\n activeElement = event.target\n }",
"function OnMouseLeftButtonUp(/*object*/ sender, /*MouseButtonEventArgs*/ e) \r\n {\r\n /*IInputElement*/var element = sender; \r\n /*DependencyObject*/var dp = sender; \r\n\r\n if (element.IsMouseCaptured) \r\n {\r\n element.ReleaseMouseCapture();\r\n }\r\n\r\n //\r\n // ISSUE - Leave this here because of 1111993. \r\n // \r\n if (dp.GetValue(IsHyperlinkPressedProperty))\r\n { \r\n dp.SetValue(IsHyperlinkPressedProperty, false);\r\n\r\n // Make sure we're mousing up over the hyperlink\r\n if (element.IsMouseOver) \r\n {\r\n if (e.UserInitiated) \r\n { \r\n DoUserInitiatedNavigation(sender);\r\n } \r\n else\r\n {\r\n DoNonUserInitiatedNavigation(sender);\r\n } \r\n }\r\n } \r\n\r\n e.Handled = true;\r\n }",
"startup() {\r\n var el = this.canvas[0];\r\n el.addEventListener(\"touchstart\", e => this.handleStart(e), false);\r\n el.addEventListener(\"touchend\", e => this.handleEnd(e), false);\r\n el.addEventListener(\"touchmove\", e => this.handleMove(e), false);\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this gets the active stylesheet which has been set to disabled false | function getActiveStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
}
return null;
} | [
"disable_style() {\n this.enabledStyles.pop();\n }",
"function initStyleSwitcher() {\n var isInitialzed = false;\n var sessionStorageKey = 'activeStylesheetHref';\n var titlePrefix = 'style::';\n\n function handleSwitch(activeTitle) {\n var activeElm = document.querySelector('link[title=\"' + activeTitle +'\"]');\n setActiveLink(activeElm);\n }\n\n function setActiveLink(activeElm) {\n var activeHref = activeElm.getAttribute('href');\n var activeTitle = activeElm.getAttribute('title');\n var inactiveElms = document.querySelectorAll(\n 'link[title^=\"' + titlePrefix + '\"]:not([href*=\"' + activeHref +'\"]):not([title=\"' + activeTitle +'\"])');\n\n // CUSTOM OVERRIDE to allow all Simple Dark titled CSS to be activated together\n // so now all CSS tag with same activeTitle will all be activated together in group\n var activeElms = document.querySelectorAll('link[title=\"' + activeTitle +'\"]');\n activeElms.forEach(function(activeElm){\n // Remove \"alternate\" keyword\n activeElm.setAttribute('rel', (activeElm.rel || '').replace(/\\s*alternate/g, '').trim());\n\n // Force enable stylesheet (required for some browsers)\n activeElm.disabled = true;\n activeElm.disabled = false;\n })\n\n // Store active style sheet\n sessionStorage.setItem(sessionStorageKey, activeTitle);\n\n // Disable other elms\n inactiveElms.forEach(function(elm){\n elm.disabled = true;\n\n // Fix for browsersync and alternate stylesheet updates. Will\n // cause FOUC when switching stylesheets during development, but\n // required to properly apply style updates when alternate\n // stylesheets are enabled.\n if (window.browsersyncObserver) {\n var linkRel = elm.getAttribute('rel') || '';\n var linkRelAlt = linkRel.indexOf('alternate') > -1 ? linkRel : (linkRel + ' alternate').trim();\n\n elm.setAttribute('rel', linkRelAlt);\n }\n });\n\n // CSS custom property ponyfil\n if ((window.$docsify || {}).themeable) {\n window.$docsify.themeable.util.cssVars();\n }\n }\n\n // Event listeners\n if (!isInitialzed) {\n isInitialzed = true;\n\n // Restore active stylesheet\n document.addEventListener('DOMContentLoaded', function() {\n var activeTitle = sessionStorage.getItem(sessionStorageKey);\n\n if (activeTitle) {\n handleSwitch(activeTitle);\n }\n });\n\n // Update active stylesheet\n /** \n * @OPTIMIZE: this will add event listener on all click\n */\n document.addEventListener('click', function(evt) {\n var dataTitle = evt.target.getAttribute('title');\n if(!dataTitle){ return 0; }\n var dataTitleIncludePrefix = dataTitle.toLowerCase().includes(titlePrefix);\n if(!dataTitleIncludePrefix){ return 0; }\n\n dataTitle = dataTitle\n || evt.target.textContent\n || '_' + Math.random().toString(36).substr(2, 9); // UID\n\n handleSwitch(dataTitle);\n evt.preventDefault();\n });\n }\n }",
"cramp() {\n return styles[cramp[this.id]];\n }",
"get themeCSS(){\n\t\t\treturn CURRENT_THEME.BASETHEME_CACHE + CURRENT_THEME.THEME_CACHE;\n\t\t}",
"function getStyle (pageName)\n{\n\tvar style = doAction ('DATA_GETCONFIGDATA', 'ObjectName', gSITE_ED_FILE, 'RowName', \n\t\t\t\t\t\t\t\t\tpageName, 'ColName', gSTYLE);\n\treturn (style);\n}",
"getStyleByName(name){\n\t\treturn this.styles[this.findIndexByName(name)];\n\t}",
"function BAGetActiveCSSTitle() {\n\tvar sheets = BAGetStyleSheets();\n\tvar ret = '';\n\tif (sheets) {\n\t\tfor (var i = 0, n = sheets.length; i < n; i++) {\n\t\t\tif (!sheets[i].disabled && sheets[i].title) {\n\t\t\t\tret = sheets[i].title;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn ret;\n}",
"function toggleStylesheet(stylesheet, toggle) {\n stylesheet.disabled = toggle;\n stylesheet.disabled = toggle; // force the browser to action right now\n}",
"function splNvslApplyDynamicStyles() {\n var styles = splNvslConfig.styleSheet;\n\n $('.spl-nvsl-tab').css(styles.nvslTab);\n $('.spl-nvsl-tab a').css(styles.nvslTabAnchor);\n $('.spl-nvsl-tab a').hover(function() {\n $(this).css(styles.nvslTabAnchorHover);\n }, function() {\n $(this).css(styles.nvslTabAnchor);\n });\n\n $('.spl-nvsl-tab-active').css(styles.nvslTabActive);\n $('.spl-nvsl-tab-active a').css(styles.nvslTabActiveAnchor);\n $('.spl-nvsl-tab-active a').hover(function() {\n $(this).css(styles.nvslTabActiveAnchorHover);\n }, function() {\n $(this).css(styles.nvslTabActiveAnchor);\n });\n\n }",
"function findStyleSheet(styleSheetId,styleSheetUrl)\r\n{\r\n\tvar styleSheets = dw.getDocumentDOM().browser.getWindow().document.styleSheets;\r\n\tif(styleSheetId > -1)\r\n {\r\n\t\treturn styleSheets[styleSheetId];\r\n\t}\r\n\t\r\n\tfor(var i=0;i<styleSheets.length;i++)\r\n\t{\t\r\n\t\tif(dw.compareURLs(styleSheets[i].href,styleSheetUrl))\r\n\t\t{\r\n\t\t\treturn styleSheets[i];\r\n\t\t}\r\n\t\telse\r\n\t\t{\t\t\t\r\n\t\t\tvar styleSheet = findNestedStyleSheet(styleSheets[i],styleSheetUrl);\r\n\t\t\tif(styleSheet)\r\n\t\t\t\treturn styleSheet;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}",
"sub() {\n return styles[sub[this.id]];\n }",
"function isStylesheet(link) {\n return stylesheet.test($(link).attr(\"rel\"));\n}",
"getStyleByID(styleID){\n\t\treturn this.styles[this.findIndexByID(styleID)];\n\t}",
"function getVerseLayout() {\n var layoutDir, i, link_tag;\n if (elements.verseLayout.value.startsWith(\"horizontal\")) {\n layoutDir = \"horizontal\";\n markupVerse = window.verseMarkupHorizontal;\n } else {\n layoutDir = \"vertical\";\n markupVerse = window.verseMarkupVertical;\n }\n // Adapted from https://www.thesitewizard.com/javascripts/change-style-sheets.shtml\n var i, link_tag ;\n for (i = 0, link_tag = document.getElementsByTagName('link') ;\n i < link_tag.length ; i++ ) {\n if ((link_tag[i].rel.indexOf('stylesheet') != -1) && link_tag[i].title) {\n link_tag[i].disabled = true ;\n if (link_tag[i].title == layoutDir) {\n link_tag[i].disabled = false ;\n }\n }\n }\n getVerse();\n }",
"function getThemeStyleList (bCustomOnly, bThemes, bStyles)\n{\n\tvar styles = new Array(), themes = new Array();\n\tvar supStyles = new Array(), supThemes = new Array();\n\tvar custStyles = new Array(), custThemes = new Array();\n\tvar out = new Array();\n\tif(bStyles)\n\t{\n\t\tvar dirList = doActionBDO (\"DATA_DIRECTORYLIST\", \"ObjectName\", gPUBLIC,\n\t\t\t\t\t\t\t\t\t\"SubDirectoryPath\", gSTYLES_DIR+\"*.css\");\n\t\tvar labels = dirList.GetLabels();\n\t\tfor (var n = 0; n < labels.length; n++)\n\t\t{\n\t\t\tif (dirList[labels[n]].indexOf (\"SC_\") == 0)\n\t\t\t\tcustStyles.push (dirList[labels[n]]);\n\t\t}\n\t\tif (!bCustomOnly)\n\t\t{\n\t\t\tvar globalDirList = doActionBDO (\"DATA_DIRECTORYLIST\", \"ObjectName\", gSTYLE_OBJ);\n\t\t\tvar globalLabels = globalDirList.GetLabels();\n\t\t\tfor (var n = 0; n < globalLabels.length; n++)\n\t\t\t\tif (globalDirList[globalLabels[n]].indexOf (\"SS_\") == 0)\n\t\t\t\t\tsupStyles.push (globalDirList[globalLabels[n]]);\n\t\t}\n\t}\n\tif (bThemes)\n\t{\n\t\tvar dirList = doActionBDO (\"DATA_DIRECTORYLIST\", \"ObjectName\", gPUBLIC,\n\t\t\t\t\t\t\t\t\t\"SubDirectoryPath\", gTHEMES_DIR+\"*.css\");\n\t\tvar labels = dirList.GetLabels();\n\t\tfor (var n = 0; n < labels.length; n++)\n\t\t{\n\t\t\tif (dirList[labels[n]].indexOf (\"TC_\") == 0)\n\t\t\t\tcustThemes.push (dirList[labels[n]]);\n\t\t}\n\t\tif (!bCustomOnly)\n\t\t{\n\t\t\tvar themeLevel = doActionEx(\"DATA_GETLITERAL\",\"Result\",\"ObjectName\",gLICENSE_CFG,\"LiteralID\",\"THEME_CHOICE\");\n\t\t\tif (themeLevel)\n\t\t\t{\n\t\t\t\tthemeLevel += \".txt\";\n\t\t\t\tvar themeList = doActionEx\t('DATA_READFILE',themeLevel, 'FileName', themeLevel,\n\t\t\t\t\t\t\t\t\t\t\t'ObjectName',gTHEME_OBJ, 'FileType', 'txt');\n\t\t\t\tif (themeList)\n\t\t\t\t{\n\t\t\t\t\tthemeList = themeList.replace (/\\r|\\f/g, \"\");\n\t\t\t\t\tvar themeArray = themeList.split (\"\\n\");\n\t\t\t\t\tfor (var n = 0; n < themeArray.length; n++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (themeArray[n].length > 0)\n\t\t\t\t\t\t\tsupThemes.push (themeArray[n]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tstyles [\"customStyles\"] = custStyles;\n\tstyles [\"suppliedStyles\"] = supStyles;\n\tout[\"styles\"] = styles;\n\tthemes [\"customThemes\"] = custThemes;\n\tthemes [\"suppliedThemes\"] = supThemes;\n\tout[\"themes\"] = themes;\n\treturn (out);\n}",
"function isCssLoaded(name) {\n\n for (var i = 0; i < document.styleSheets.length; ++i) {\n\n var styleSheet = document.styleSheets[i];\n\n if (styleSheet.href && styleSheet.href.indexOf(name) > -1)\n return true;\n }\n ;\n\n return false;\n }",
"sup() {\n return styles[sup[this.id]];\n }",
"function disabledCssCheck() {\n // check color style of 'cssCheck' div tag (should be set to red)\n if(window.getComputedStyle(document.getElementById(\"cssCheck\"), null)[\"color\"] == \"rgb(255, 39, 39)\" || \n window.getComputedStyle(document.getElementById(\"cssCheck\"), null)[\"color\"] == \"rgb(255, 0, 0)\"){\n return true;\n }\n return false;\n}",
"get actualBaseTheme() {\n return this.i.z;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return a map of cids to how many miners count it as heads | get heads () {
const heads = {}
this.miners.forEach(m => {
const head = this.minersHeads[m]
if (!heads[head]) {
heads[head] = 0
}
heads[head]++
})
return heads
} | [
"getPlayersCardNums(state) {\n let players = (state || this).players, playerCardNums = {}\n for (let i in players) {\n if (players[i]) {\n playerCardNums[i] = players[i].cards.length\n }\n else {\n playerCardNums[i] = null\n }\n }\n return playerCardNums\n }",
"function getPiecesCount(parts) {\n return parts.reduce((map, part) => {\n map[part] = (map[part] || 0) + 1;\n return map;\n }, {});\n}",
"function getAliveCount() {\n\tvar count = 0;\n\tcells.map(function(alive) {\n\t\tif (alive) count++;\n\t});\n\treturn count;\n}",
"function countConstellations(points, print = false) {\n let connies = new Map();\n\n for (let rawpt of points) {\n let point = rawpt.split(',').map(Number);\n if (point.length === 1) break;\n\n let closeKeys = [...connies.entries()].map(e => [e[0], Math.min(...e[1].map(v => manhattanDistance(point, v)))]).filter(e => e[1] < 4).map(e => e[0]);\n\n let newCon = closeKeys.map(k => connies.get(k)).reduce((v, e) => v.concat(e), [point]);\n\n closeKeys.forEach(k => connies.delete(k));\n\n connies.set(String(point), newCon);\n }\n\n return connies.size;\n}",
"function setMinesNegsCount(board) {\r\n var currSize = gLevels[gChosenLevelIdx].SIZE;\r\n for (var i = 0; i < currSize; i++) {\r\n for (var j = 0; j < currSize; j++) {\r\n var cell = board[i][j];\r\n var count = calculateNegs(board, i, j)\r\n cell.minesAroundCount = count;\r\n }\r\n }\r\n\r\n\r\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 countryKillers(){\n // init country object with country names as jeys\n for(let i = 0; i < countryNames.length; i++){\n let name = countryNames[i];\n countries[name] = {\"victim count\": 0, \"killer count\": 0, \"killer names\": []};\n }\n\n for(let i = 0; i < killerNames.length; i++){\n let name = killerNames[i]\n let info = killersInfo[name];\n\n for(let c of info[\"countries\"]){\n if(!(c in countries)) continue;\n countries[c][\"victim count\"] += info[\"Proven Victims\"];\n countries[c][\"killer count\"] ++;\n countries[c][\"killer names\"].push(name);\n\n }\n }\n\n for(let c of countryNames){\n let v = countries[c][\"victim count\"];\n if(v > maxVictims) maxVictims = v;\n }\n}",
"function countSuitsBlazerMwiPlus() {\n\t\t\tinstantObj.noOfSuitsBlazerMWI = instantObj.noOfSuitsBlazerMWI + 1;\n\t\t\tcountTotalBill();\n\t\t}",
"function createTxMap(txs){\n\tvar map = new Map();\n\n\ttxs.forEach(function(tx){\n\t\t\tif (!map.has(tx.from)){\n\t\t\t\tmap.set(tx.from, 1);\n\t\t\t} else {\n\t\t\t\tmap.set(tx.from, map.get(tx.from)+1);\n\t\t\t}\n\t});\n\treturn map;\n}",
"countMines(board, w, h) {\n let count = 0\n for (let i = 0; i < w; i++) {\n for (let j = 0; j < h; j++) {\n count += board[j][i];\n }\n }\n return count;\n }",
"getCardsLeft() {\n var cardsLeft = {};\n\n for (var key in this.cards) {\n const card = this.cards[key];\n const cardType = card.cardType;\n\n if (card.isFlipped) continue;\n\n if (cardType in cardsLeft) cardsLeft[cardType]++;\n else cardsLeft[cardType] = 1;\n }\n\n return cardsLeft;\n }",
"function getCountedObjects(){\n var counted = {};\n for (var i = 0; i < detections.length; i++){\n var lbl = detections[i].label;\n if (!counted[lbl]) counted[lbl] = 0;\n counted[lbl]++;\n }\n return counted;\n}",
"function gemstones(arr) {\n let n = arr.length;\n let obj = {};\n let count = 0;\n for(let i = 0; i < n; i++){\n for(let j = 0; j < arr[i].length; j++){\n if((!obj[arr[i][j]] && i == 0) | obj[arr[i][j]] == i) {\n obj[arr[i][j]] = i + 1;\n if(obj[arr[i][j]] == n) count++;\n }\n }\n }\n return count;\n}",
"function _processNodesCnt() {\n if (firstCntFlag) {\n _processNodesGlobalCnt();\n firstCntFlag = false;\n }\n\n const {nodeMap} = processedGraph;\n Object.keys(nodeMap).forEach((id) => {\n if (isNaN(id)) return;\n const node = nodeMap[id];\n const iterator = node.scope.split(SCOPE_SEPARATOR);\n\n if (!node.parent) return;\n do {\n const name = iterator.join(SCOPE_SEPARATOR);\n const scopeNode = nodeMap[name];\n if (_checkShardMethod(node.parallel_shard)) {\n if (scopeNode.specialNodesCnt.hasOwnProperty('hasStrategy')) {\n scopeNode.specialNodesCnt['hasStrategy']++;\n } else {\n scopeNode.specialNodesCnt['hasStrategy'] = 1;\n }\n }\n if (node.instance_type !== undefined) {\n if (scopeNode.specialNodesCnt.hasOwnProperty(node.instance_type)) {\n scopeNode.specialNodesCnt[node.instance_type]++;\n } else {\n scopeNode.specialNodesCnt[node.instance_type] = 1;\n }\n }\n iterator.pop();\n } while (iterator.length);\n });\n}",
"function getNumCandidates() {\n return numCandidates;\n } // getNumCandidates",
"function setupMines(map){\n \n // Amount of mines required\n var mines = map.mines;\n \n // Array of fields to add mines to\n var fields = map.fields;\n \n for (var n = 0; n < mines; n++ ) {\n \n // Generate a random number to turn into a mine\n var random = Math.floor(Math.random() * (map.size )) + 0;\n\n // If can't be marked as a mine find another random number\n if(!markAsMine(map, random)){\n n--;\n }\n }\n}",
"function increaseLeastMap() {\n\tfeedArray.map(function(allElement){\n\t\tif(mini==allElement.upvotes)\n\t\t\tallElement.upvotes++;\n\t})\n\n\tconsole.log(feedArray);\n}",
"function computeRefererCounts() {\n \n var referrerCounts = {};\n for (var key in visitorsData) {\n var referringSite = visitorsData[key].referringSite || '(direct)';\n if (referringSite in referrerCounts) {\n referrerCounts[referringSite]++;\n } else {\n referrerCounts[referringSite] = 1;\n }\n }\n return referrerCounts; \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}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Executes a MySQL query to delete a artist specified by its ID. Returns a Promise that resolves to true if the artist specified by `id` existed and was successfully deleted or to false otherwise. | async function deleteArtistById(id) {
const [ result ] = await mysqlPool.query(
'DELETE FROM artist WHERE id = ?',
[ id ]
);
return result.affectedRows > 0;
} | [
"async function replaceArtistById(id, artist) {\n artist = extractValidFields(artist, ArtistSchema);\n const [ result ] = await mysqlPool.query(\n 'UPDATE artist SET ? WHERE id = ?',\n [ artist, id ]\n );\n return result.affectedRows > 0;\n}",
"async function deleteLikeById(id) {\n const [result] = await mysqlPool.query(\"DELETE FROM likes WHERE likeId = ?\", [\n id,\n ]);\n return result.affectedRows > 0;\n}",
"function DeleteTrackById(req, res) {\n\t// Deletes the artist by ID, get ID by req.params.artistId\n}",
"deleteOneLocation(id) {\n return db.none(`\n DELETE FROM location\n WHERE id = $1\n `, id);\n }",
"async function deleteLikesByPostId(id) {\n const [result] = await mysqlPool.query(\"DELETE FROM likes WHERE postId = ?\", [\n id,\n ]);\n return result.affectedRows > 0;\n}",
"deleteById(id) {\n return this.del(this.getBaseUrl() + '/' + id);\n }",
"async function getArtistById(id) {\n const [ results ] = await mysqlPool.query(\n 'SELECT * FROM artist WHERE id = ?',\n [ id ]\n );\n return results[0];\n}",
"function remove(id) {\n return db(\"todos\")\n .where({ id })\n .del();\n}",
"destroy(id) {\n return db.none(`\n DELETE FROM parks\n WHERE id = $1`, id);\n }",
"async deleteTrackByID(ctx) {\n await Model.track\n .deleteOne({ _id: ctx.params.id })\n .then(result => {\n if(result.deletedCount > 0) { ctx.body = \"Delete Successful\"; }\n else { throw \"Error deleting track\"; }\n })\n .catch(error => {\n throw new Error(error);\n });\n }",
"function del(kind, id) {\n var entity = store[kind];\n if (! entity) {\n return false;\n }\n\n var found = false;\n entity.rows = entity.rows.filter(function(row) {\n if (id === row.id) {\n found = true;\n return false; // return false delete this record\n }\n return true;\n });\n\n if (found) {\n writeData();\n }\n\n return found;\n}",
"deleteQuestion(id) {\n const promise = this._ajaxDeleteQuestion(id);\n promise.then((response) => {\n const status = response.status;\n if (status >= 200 && status < 300) {\n this._localDeleteQuestion(id);\n } else {\n throw Error(`Unexpected DELETE response: ${status}`);\n }\n });\n return promise;\n }",
"async function removeCan(id) {\n try {\n return db('cans')\n .where({ id })\n .del();\n } catch (error) {\n throw error; \n }\n\n}",
"deleteEvent(db, id){\n return db\n .from('events')\n .where(id)\n .delete();\n }",
"function deleteTictactoe(id) {\n console.log(\"delete Tictactoe: \" + id);\n return axios\n .delete(\"/api/tictactoe/\" + id)\n .then((res) => loadTictactoes())\n .catch((err) => console.log(err));\n }",
"deleteMovie( userId, id ) {\n\n\t\tvar promise = new Promise(\n\t\t\t( resolve, reject ) => {\n\n\t\t\t\tvar movies = this._paramMovies( userId );\n\t\t\t\tvar matchingIndex = movies.findIndex(\n\t\t\t\t\t( item ) => {\n\n\t\t\t\t\t\treturn( item.id === id );\n\n\t\t\t\t\t}\n\t\t\t\t);\n\n\t\t\t\tif ( matchingIndex === -1 ) {\n\n\t\t\t\t\tthrow( new Error( \"Not Found\" ) );\n\n\t\t\t\t}\n\n\t\t\t\tmovies.splice( matchingIndex, 1 );\n\t\t\t\tresolve();\n\n\t\t\t}\n\t\t);\n\n\t\treturn( promise );\n\n\t}",
"function DeleteSkill(id) {\n var URL = API_HOST + API_SKILLS_PATH +'/'+ id;\n Axios.delete(URL).then(() => console.log(\"skill is deleted\"));\n return true;\n}",
"function destroy(id) {\n\treturn db.none(`DELETE FROM tours WHERE id=$1`, [id]);\n}",
"async function deleteCart(cartId, sessionId) {\n\treturn await genericActions.deleteById(baseUrl, property, cartId, sessionId);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Event handler for adding a new time zone | function handleAdd() {
if (selectedTimeZone) {
let newTimeZones = [...myTimeZones, selectedTimeZone]
setMyTimeZones(newTimeZones)
localStorage.setItem(TIME_ZONE_KEY, JSON.stringify(newTimeZones))
}
} | [
"function add_tz_to_fields() {\n add_user_tz();\n add_user_tz_to_form();\n format_exercise_date();\n}",
"function evAppendNewZone (event) {\n\tvar $button = $(event.target);\n\tvar $table = $button.parents('table');\n\tvar zn = getZoneCount();\n\taddZone();\n\t// zn is the number of the new zone\n\tvar $tbody = getTBody($table);\n\tvar $tr = createZone(zn).append(zoneParamForm(zn))\n\t\t.appendTo($tbody);\n}",
"function add_user_tz_to_form() {\n const tz = moment.tz.guess();\n const field = document.getElementById(\"user_tz\");\n\n if (typeof (field) != 'undefined' && field != null) {\n field.value = tz;\n }\n}",
"function storeTimezone() {\n var model = vm.modelGetter($scope);\n if (model && angular.isDefined(model.timezone)) {\n vm.currentTimezone = model.timezone;\n }\n }",
"function calculate_time_zone() {\n\tvar rightNow = new Date();\n\tvar jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0); // jan 1st\n\tvar june1 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0); // june 1st\n\tvar temp = jan1.toGMTString();\n\tvar jan2 = new Date(temp.substring(0, temp.lastIndexOf(\" \")-1));\n\ttemp = june1.toGMTString();\n\tvar june2 = new Date(temp.substring(0, temp.lastIndexOf(\" \")-1));\n\tvar std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);\n\tvar daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);\n\tvar dst;\n\tif (std_time_offset == daylight_time_offset) {\n\t\tdst = \"0\"; // daylight savings time is NOT observed\n\t} else {\n\t\t// positive is southern, negative is northern hemisphere\n\t\tvar hemisphere = std_time_offset - daylight_time_offset;\n\t\tif (hemisphere >= 0)\n\t\t\tstd_time_offset = daylight_time_offset;\n\t\tdst = \"1\"; // daylight savings time is observed\n\t}\n\tvar i;\n\t// check just to avoid error messages\n\tif (document.getElementById('timezone')) {\n\t\tfor (i = 0; i < document.getElementById('timezone').options.length; i++) {\n\t\t\tif (document.getElementById('timezone').options[i].value == convert(std_time_offset)+\",\"+dst) {\n\t\t\t\tdocument.getElementById('timezone').selectedIndex = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}",
"function zoneForward(){\r\n\twindow.cnt += 1;\r\n\t//alert(window.cnt);\r\n\tvar e = document.getElementById(\"zone\"); // contains zone list.\r\n\tvar zoneCode = e.options[e.selectedIndex].value;\r\n\tvar zoneDesc = e.options[e.selectedIndex].text;\r\n\tvar fromDate = document.getElementById(\"fromDate\").value; // contains fromDate value.\r\n\tvar toDate = document.getElementById(\"toDate\").value; // contains toDate value.\r\n\r\n\t\t\r\n\t// -------- Collection of already selected zone codes.\r\n\tvar len1 = $(\"#selected_zone option\").length; // length of already selected zone.\r\n\tvar html = '';\r\n\tvar zoneCodeAll = \"\";\r\n\t\r\n\tif (len1 > 0){\r\n\t\tvar e1 = document.getElementById(\"selected_zone\"); // contains selected_zone list\r\n\t\t\r\n\t\tfor (var i=0; i<len1; i++){\r\n\t\t\thtml += '<option value=\"' + e1.options[i].value + '\">'+ e1.options[i].text+ '</option>';\r\n\t\t\tzoneCodeAll += \"'\" + e1.options[i].value + \"',\"; // include already selected zones.\r\n\t\t}\r\n\t}\r\n\t// Add currently selected zone in the selected_zone map.\r\n\thtml += '<option value=\"' + zoneCode + '\">'+ zoneDesc + '</option>';\r\n\thtml += '</option>';\r\n\tzoneCodeAll += \"'\" + zoneCode + \"'\"; // include currently selected zone.\r\n\t\r\n\t$('#selected_zone').html(html); // populate selected zone map.\r\n\t// ------ End.\r\n\t\r\n\t// ------ Remove the selected zone from zone map.\r\n\tvar len2 = $(\"#zone option\").length; // length of zone map.\r\n\tvar html = '';\r\n\t\r\n\tif (len2 > 0){\r\n\t\tvar e2 = document.getElementById(\"zone\"); // contains zone list.\r\n\t\t\r\n\t\tfor (var i=0; i<len2; i++){\r\n\t\t\tif (e2.options[i].value != zoneCode)\r\n\t\t\t html += '<option value=\"' + e2.options[i].value + '\">'+ e2.options[i].text+ '</option>';\r\n\t\t}\r\n\t}\r\n\thtml += '</option>';\r\n\t$('#zone').html(html); // populate zone map after removal of selected zone.\r\n\t$('#contract').html('');\r\n\t\r\n\t// zoneCode = \"'\"+zoneCode+\"'\"; // e.g. '02'.\r\n\t\r\n\t// ------ End.\r\n\t\r\n\t// ------ Populate contract code map of selected zone.\r\n\t// Fetching contract codes of the selected zone from database,\r\n\t// and then add the contracts into the contract drop down list.\r\n\t$.ajax({\r\n\t\ttype: \"POST\",\r\n\t\turl: \"securityDeposit.htm\",\r\n\t\tdata : \"zoneCode=\" + zoneCodeAll + \"&fromDate=\" + fromDate + \"&toDate=\"\t+ toDate + \"&_target11=contract\",\r\n\t\t// data: \"zoneCode=\"+zoneCode+\"&_target11=contract\",\r\n\t\tsuccess: function(response){\r\n\t\t\tvar data= $.parseJSON(response);\r\n\t\t\t\r\n\t\t\t// checking for already populated contracts for previously selected zone.\r\n\t\t\t/*var len3 = $(\"#contract option\").length;\r\n\t\t\tvar html = '';\r\n\t\t\t\r\n\t\t\t// display of contract code instead of contract description in the map.\r\n\t\t\tif (len3 > 0){\r\n\t\t\t\tvar e3 = document.getElementById(\"contract\");\r\n\t\t\t\t\r\n\t\t\t\tfor (var i=0; i<len3; i++){\r\n\t\t\t\t\thtml += '<option value=\"' + e3.options[i].value + '\">'+ e3.options[i].value+ '</option>';\r\n\t\t\t\t}\r\n\t\t\t}*/\r\n\t\t\t\r\n\t\t\t// display of contract code instead of contraction desc in the map.\r\n\t\t\tvar len = data.length;\r\n\t\t\tvar html = '';\r\n\t\t\tfor (var i=0; i<len; i++){\r\n\t\t\t\thtml += '<option value=\"' + data[i].contractCode + '\">'+ data[i].contractName+ '</option>';\r\n\t\t\t}\r\n\t\t\thtml += '</option>';\r\n\t\t\t$('#contract').html(html); // populate contract map.\r\n\t\t},\r\n\t\terror: function(e){\r\n\t\t\t// alert('Error: ' + e);\r\n\t\t}\r\n\t}); // End of data fetching.\r\n\t\r\n\t// Removal of already selected_contract from newly sorted contracted list.\r\n\t// on 24-03-2017.\r\n\tvar len1 = $(\"#selected_contract option\").length; \r\n\tvar html='';\r\n\t//alert(\"Contracts to be adjusted: \"+len1);\t//Without this alert the contracts are not removed.\r\n\tif (len1 > 0){\r\n\t\tvar e1 = document.getElementById(\"selected_contract\");\r\n\t\tfor (var i = 0; i < len1; i++) {\r\n\t\t\tvar contcd = e1.options[i].value;\r\n\t\t\talert(\"Adjusting contract #: \"+contcd);\t\t\t//Without this alert the contracts are not removed.\r\n\t\t\t//dummyFunction();\r\n\t\t\tvar src = document.getElementById('contract');\r\n\t\t\tfor (var count = 0; count < src.options.length; count++) {\r\n\t\t\t\tif (src.options[count].value == contcd) {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tsrc.remove(count, null);\r\n\t\t\t\t\t} catch (error) {\r\n\t\t\t\t\t\tsrc.remove(count);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcount--;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t} // end of inner for loop\r\n\t\t} // end of outer for loop\r\n\t}\r\n}",
"get timeZone()\n\t{\n\t\treturn this._timeZone;\n\t}",
"function setTimezoneCookie(timezone) {\n var date = new Date(2099, 1, 1);\n document.cookie = 'timezone=' + timezone + '; path=/; expires=' + date.toUTCString();\n }",
"function usersTimeZone( usersTime ) {\n $(\"#timezone-select option\").each(function() {\n if ($(this).attr(\"value\") === usersTime) {\n $(this).attr(\"selected\", \"true\");\n }\n });\n }",
"function addTemporal(id,value) {\n\t\tTemporalData[id] = value;\n\t\tdevi.debug('[TEMP] Stored \"'+id+'\"');\n\t\treturn true;\n\t}",
"function setTimezone(timezone) {\n var oldTz = process.env.TZ;\n var tz = tzset(timezone);\n var zoneInfo = bindings.localtime(this / 1000);\n this._timezone = timezone;\n if (oldTz) {\n tzset(oldTz);\n oldTz = null;\n }\n\n // If we got to here without throwing an Error, then\n // a valid timezone was requested, and we should have\n // a valid zoneInfo Object.\n\n // Returns the day of the month (1-31) for the specified date according to local time.\n this.getDate = function getDate() {\n return zoneInfo.dayOfMonth;\n }\n // Returns the day of the week (0-6) for the specified date according to local time.\n this.getDay = function getDay() {\n return zoneInfo.dayOfWeek;\n }\n // Deprecated. Returns the year (usually 2-3 digits) in the specified date according\n // to local time. Use `getFullYear()` instead.\n this.getYear = function getYear() {\n return zoneInfo.year;\n }\n // Returns the year (4 digits for 4-digit years) of the specified date according to local time.\n this.getFullYear = function getFullYear() {\n return zoneInfo.year + 1900;\n }\n // Returns the hour (0-23) in the specified date according to local time.\n this.getHours = function getHours() {\n return zoneInfo.hours;\n }\n // Returns the minutes (0-59) in the specified date according to local time.\n this.getMinutes = function getMinutes() {\n return zoneInfo.minutes;\n }\n // Returns the month (0-11) in the specified date according to local time.\n this.getMonth = function getMonth() {\n return zoneInfo.month;\n }\n // Returns the seconds (0-59) in the specified date according to local time.\n this.getSeconds = function getSeconds() {\n return zoneInfo.seconds;\n }\n // Returns the timezone offset from GMT the Date instance currently is in,\n // in minutes. Also, left of GMT is positive, right of GMT is negative.\n this.getTimezoneOffset = function getTimezoneOffset() {\n return -zoneInfo.gmtOffset / 60;\n }\n // NON-STANDARD: Returns the abbreviation (e.g. EST, EDT) for the specified time zone.\n this.getTimezoneAbbr = function getTimezoneAbbr() {\n return tz.tzname[zoneInfo.isDaylightSavings ? 1 : 0];\n }\n\n this.toDateString = function toDateString() {\n return exports.DAYS_OF_WEEK[this.getDay()].substring(0, 3) + ' ' + exports.MONTHS[this.getMonth()].substring(0, 3) + ' ' + pad(this.getDate(), 2) + ' ' + this.getFullYear();\n }\n\n this.toTimeString = function toTimeString() {\n var offset = zoneInfo.gmtOffset / 60 / 60;\n return this.toLocaleTimeString() + ' GMT' + (offset >= 0 ? '+' : '-') + pad(Math.abs(offset * 100), 4)\n + ' (' + tz.tzname[zoneInfo.isDaylightSavings ? 1 : 0] + ')';\n }\n\n this.toString = function toString() {\n return this.toDateString() + ' ' + this.toTimeString();\n }\n\n this.toLocaleDateString = function toLocaleDateString() {\n return exports.DAYS_OF_WEEK[this.getDay()] + ', ' + exports.MONTHS[this.getMonth()] + ' ' + pad(this.getDate(), 2) + ', ' + this.getFullYear();\n }\n\n this.toLocaleTimeString = function toLocaleTimeString() {\n return pad(this.getHours(), 2) + ':' + pad(this.getMinutes(), 2) + ':' + pad(this.getSeconds(), 2);\n }\n\n this.toLocaleString = this.toString;\n}",
"function changeToServerTimezone(scheduledTime, userTimezone) {\n var time = scheduledTime.split(\":\");\n var date = time[1] + ' ' + (parseInt(time[0])-userTimezone) + ' * * *';\n return date;\n}",
"get zoneType() {\n return this.getStringAttribute('zone_type');\n }",
"function zoneReverse(){\r\n\twindow.cnt += 1; // global variable.\r\n\t//alert(window.cnt);\r\n\tvar e = document.getElementById(\"selected_zone\"); // contains selected zone list.\r\n\tvar fromDate = document.getElementById(\"fromDate\").value; // contains fromDate value.\r\n\tvar toDate = document.getElementById(\"toDate\").value; // contains toDate value.\r\n\r\n\tvar zoneCode = e.options[e.selectedIndex].value;\r\n\tvar zoneDesc = e.options[e.selectedIndex].text;\r\n\t//alert(zoneCode + '---' + zoneDesc);\r\n\t\r\n\t// Step-1:\r\n\t// -------- Collection of not selected zone codes from zone map.\r\n\tvar len1 = $(\"#zone option\").length; // length of not selected zone.\r\n\tvar html = '';\r\n\t\r\n\tif (len1 > 0){\r\n\t\tvar e1 = document.getElementById(\"zone\"); // contains zone list\r\n\t\t\r\n\t\tfor (var i=0; i<len1; i++){\r\n\t\t\thtml += '<option value=\"' + e1.options[i].value + '\">'+ e1.options[i].text+ '</option>';\r\n\t\t}\r\n\t}\r\n\t// Add currently selected zone in the zone map.\r\n\thtml += '<option value=\"' + zoneCode + '\">'+ zoneDesc + '</option>';\r\n\thtml += '</option>';\r\n\t\t\r\n\t$('#zone').html(html); // populate zone map.\r\n\t// ------ End.\r\n\t\r\n\t// Step-2:\r\n\t// ------ Remove the selected zone from selected_zone map.\r\n\tvar len2 = $(\"#selected_zone option\").length; // length of zone map.\r\n\tvar html = '';\r\n\tvar zoneCodeAll=\"\";\r\n\t\r\n\tif (len2 > 0){\r\n\t\tvar e2 = document.getElementById(\"selected_zone\"); // contains selected_zone list.\r\n\t\t\r\n\t\tfor (var i=0; i<len2; i++){\r\n\t\t\tif (e2.options[i].value != zoneCode){\r\n\t\t\t\thtml += '<option value=\"' + e2.options[i].value + '\">'+ e2.options[i].text+ '</option>';\r\n\t\t\t\tzoneCodeAll += \"'\"+e2.options[i].value+\"',\";\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\thtml += '</option>';\r\n\t$('#selected_zone').html(html); // populate selected_zone map after removal of selected zone.\r\n\t\r\n\t// Step-3.\r\n\tif (zoneCodeAll != \"\")\r\n\t{\r\n\t\tzoneCodeAll = zoneCodeAll.substring(0, zoneCodeAll.length - 1);\r\n\t\tzoneCode = \"'\"+ zoneCode + \"'\";\r\n\t\t\r\n\t\t// to remove contract code from already selected_contract map\r\n\t\t// as well as contract map who are under the removed zone code.\r\n\t\t$.ajax({\r\n\t\t\ttype: \"POST\",\r\n\t\t\turl: \"securityDeposit.htm\",\r\n\t\t\tdata : \"zoneCode=\" + zoneCode + \"&fromDate=\" + fromDate + \"&toDate=\" + toDate + \"&_target11=contract\",\r\n\t\t\t// data: \"zoneCode=\"+zoneCode+\"&_target11=contract\",\r\n\t\t\tsuccess: function(response){\r\n\t\t\t\tvar data= $.parseJSON(response);\r\n\t\t\t\tvar html = '';\r\n\t\t\t\t\r\n\t\t\t\t// display of contract code instead of contract desc in the map.\r\n\t\t\t\tvar len = data.length;\r\n\t\t\t\tfor (var i=0; i<len; i++){\r\n\t\t\t\t\tcontcd = data[i].contractCode;\r\n\t\t\t\t\tvar src=document.getElementById('selected_contract');\r\n\t\t\t\t\tfor(var count=0;count<src.options.length;count++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif(src.options[count].value ==contcd)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\ttry{\r\n\t\t\t\t\t\t\t\tsrc.remove(count,null);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tcatch(error)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tsrc.remove(count);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tcount--;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tvar dest=document.getElementById('contract');\r\n\t\t\t\t\tfor(var count=0;count<dest.options.length;count++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif(dest.options[count].value ==contcd) // if exists, then delete.\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\ttry{\r\n\t\t\t\t\t\t\t\tdest.remove(count,null);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tcatch(error)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tdest.remove(count);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tcount--;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tpopulateContract ('selected_contract', 'selected_contract', src, src);\r\n\t\t\t},\r\n\t\t\terror: function(e){\r\n\t\t\t\t// alert('Error: ' + e);\r\n\t\t\t}\r\n\t\t}); // End of data fetching.\r\n\t}\r\n\telse{\r\n\t\t$('#contract').html('');\r\n\t\t$('#selected_contract').html('');\r\n\t\t$('#contract_desc').html(html); // Free contract_desc map.\r\n\t}\r\n\t\t\r\n}",
"function createDate(yr, mon, day, hr, min, zone) {\n\n // interpret date as utc date\n var utc = new Date( Date.UTC(yr,mon-1, day, hr, min) );\n var entries = \n\tfindZoneEntries(zone, utc.getTime())\n\t.map(function(e){\n\n\t return new Date(utc.getTime() - 1000*(e.offset))})\n\n\t.filter(function(tm){\n\n\t var tzes = findZoneEntries(zone, tm.getTime(), 0);\n\n\t if (tzes.length != 1) \n\t\treturn false;\n\n\t var tze = tzes[0];\n\n\t var check = new Date(tm.getTime() + 1000*(tze.offset));\n\t return check.getUTCFullYear() == yr\n\t\t&& check.getUTCMonth()+1 == mon\n\t\t&& check.getUTCDate() == day\n\t\t&& check.getUTCHours() == hr\n\t\t&& check.getUTCMinutes() == min;\n\n\t});\n\n if (entries.length == 0)\n\tthrow \"illegal date: \"+ yr +\"-\"+ mon +\"-\"+ day +\" \"+ hr +\":\"+ min\n\t+ \" in zone \" + zone.name;\n\n if (entries.length > 2)\n\tthrow \"something must be seriously wrong with the time zone data!\";\n\n if (entries.length > 1) \n\tentries[0].state=\"AMBIGUOUS\";\n\n if (entries.length == 1)\n\tentries[0].state=\"OK\";\n\n return entries[0];\n\n}",
"function updateZone(axios$$1, zoneToken, payload) {\n return restAuthPut(axios$$1, '/zones/' + zoneToken, payload);\n }",
"function addLocation()\r\n{\r\n let newWaypoint = currentRoute.routeMarker.getPosition();\r\n currentRoute.waypoints.push(newWaypoint);\r\n currentRoute.displayPath();\r\n}",
"function tzExists(tzArray,selectedname){\n\t\tvar status = false;\n\t\tfor(var t=0;t<tzArray.length;t++){\n\t\t\tif(tzArray[t].name === selectedname){\n\t\t\t\tstatus = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn status;\n\t}",
"addAppointment(date,time,title) {\n const appointment = new Appointment(date,time,title)\n\n if (this.map.has(date)) {\n this.map.get(date).push(appointment)\n }\n else {\n this.map.set(date,[appointment])\n }\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add unique keys to the slot children (vue requires a unique key when the slot is the descendant of a transitiongroup) | addSlotKeys() {
this.$slots.default.forEach((item, index) => {
item.key = item.key!=null?item.key:index;
});
} | [
"function shiftSlotNodeDeeper(node) {\n if (!node.children) {\n return;\n }\n\n node.children.forEach((child) => {\n const vslotShorthandName = getVslotShorthandName(child);\n if (vslotShorthandName && child.name !== 'template') {\n const newSlotNode = cheerio.parseHTML('<template></template>')[0];\n\n const vslotShorthand = `#${vslotShorthandName}`;\n newSlotNode.attribs[vslotShorthand] = '';\n delete child.attribs[vslotShorthand];\n\n newSlotNode.parent = node;\n child.parent = newSlotNode;\n\n newSlotNode.children.push(child);\n\n // replace the shifted old child node with the new slot node\n node.children.forEach((childNode, idx) => {\n if (childNode === child) {\n node.children[idx] = newSlotNode;\n }\n });\n }\n });\n}",
"#setActiveStepAttributes() {\n let { activeStep } = this;\n for (let step of this.children) {\n let name = step.getAttribute(\"name\");\n if (name === activeStep) {\n step.slot = \"active\";\n } else {\n step.slot = \"\";\n }\n }\n }",
"function transformOldSlotSyntax(node) {\n if (!node.children) {\n return;\n }\n\n node.children.forEach((child) => {\n if (_.has(child.attribs, 'slot')) {\n const vslotShorthandName = `#${child.attribs.slot}`;\n child.attribs[vslotShorthandName] = '';\n delete child.attribs.slot;\n }\n });\n}",
"function createSlots(slots, dynamicSlots) {\n for (let i = 0; i < dynamicSlots.length; i++) {\n const slot = dynamicSlots[i];\n // array of dynamic slot generated by <template v-for=\"...\" #[...]>\n if ((0,_vue_shared__WEBPACK_IMPORTED_MODULE_1__.isArray)(slot)) {\n for (let j = 0; j < slot.length; j++) {\n slots[slot[j].name] = slot[j].fn;\n }\n }\n else if (slot) {\n // conditional single slot generated by <template v-if=\"...\" #foo>\n slots[slot.name] = slot.key\n ? (...args) => {\n const res = slot.fn(...args);\n // attach branch key so each conditional branch is considered a\n // different fragment\n if (res)\n res.key = slot.key;\n return res;\n }\n : slot.fn;\n }\n }\n return slots;\n}",
"_processNodes(){\n this.shadowRoot\n .querySelector('slot')\n .assignedNodes()\n .forEach((n) => this._processNode(n));\n }",
"disableGroupAdjustmentWhenChildrenChange() {\n this._adjustGroupWhenChildrenChange++;\n }",
"removeAllSlots() {\n var size = this.closet_slots_faces_ids.length;\n for (let i = 0; i < size; i++) {\n this.removeSlot();\n }\n }",
"addKeys () {\n this._eachPackages(function (_pack) {\n _pack.add()\n })\n }",
"checkKeys() {\n if (this.interface.isKeyPressed(CHANGE_MATERIAL)) {\n let keys = Object.keys(this.graph.components);\n for (let key of keys) {\n let component = this.graph.components[key];\n component.materialID++;\n if (component.materialID >= component.materials.length) {\n component.materialID = 0;\n }\n }\n this.interface.releaseKey(CHANGE_MATERIAL);\n }\n }",
"createShowSlotComponents() {\n let showSlots = [];\n for (var day in this.state.data) {\n let curDay = [];\n curDay.push(this.createLabelSlot(day));\n for (let i = 0; i < this.state.data[day].length; i++) {\n curDay.push(<ScheduleShowSlot {...this.state.data[day][i]}/>)\n }\n showSlots.push(curDay);\n }\n return showSlots;\n }",
"@computed get uniqueKey(): string {\n const hash = this.block == null ? 'undefined' : this.block.Hash;\n return `${this.txid}-${this.state}-${hash}`;\n }",
"visitUnique_key_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"disableChildrenAdjustmentWhenGroupChanges() {\n this._adjustChildrenWhenGroupChanges++;\n }",
"renderTabs() {\n\t const { currentTabIndex } = this.state;\n\t const { children, accent, onTabChange } = this.props;\n\t return React.Children.map(children, (child, index) => {\n\t return React.cloneElement(child, {\n\t onClick: this.handleTabChange,\n\t tabIndex: index,\n\t isActive: index === currentTabIndex,\n\t onTabChange,\n\t });\n\t });\n\t}",
"slot$(name,ctx){\n\t\tvar slots_;\n\t\tif (name == '__' && !this.render) {\n\t\t\treturn this;\n\t\t}\t\t\n\t\treturn (slots_ = this.__slots)[name] || (slots_[name] = imba$1.createLiveFragment(0,null,this));\n\t}",
"_addSlot() {\n if (this[_value]) {\n this[_fillElement].appendChild(this[_slotElement]);\n } else {\n this[_trackElement].appendChild(this[_slotElement]);\n }\n }",
"enableChildrenAdjustmentWhenGroupChanges() {\n this._adjustChildrenWhenGroupChanges--;\n }",
"visitHash_subparts_by_quantity(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"get subMenus() {\n\t\tconst slot = this.shadowRoot.querySelector('slot[name=\"sub-menu\"]');\n\t\treturn slot.assignedElements();\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the input for selected invitations | function updateSelectedInvitationsInput() {
// Loop through all the invitation checkbox and get the value
var selectedInvitations = [];
if (typeof($inputSelectedInvitations) != 'undefined' && $inputSelectedInvitations != null) {
$('.checkbox-invitation').each(function (i, obj) {
if(obj.checked) {
selectedInvitations.push(obj.value);
}
});
// Set the length into the count container
var selectedInvitationsCount = selectedInvitations.length;
$('.selected-invitation-container').each(function() {
$(this).html(selectedInvitationsCount);
var $button = $(this).closest('button');
// Enable/disable the button based on the count
if(selectedInvitationsCount <= 0) {
$button.prop("disabled", true);
} else {
$button.prop("disabled", false);
}
});
$inputSelectedInvitations.value = JSON.stringify(selectedInvitations);
}
} | [
"function updateInvites() {\n var result = null;\n var xmlhttp = null;\n var element = document.getElementById('invitationsSection');\n\n if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari\n\txmlhttp=new XMLHttpRequest();\n } else {// code for IE6, IE5\n\txmlhttp=new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n\n xmlhttp.onreadystatechange=function() {\n\tif (xmlhttp.readyState==4 && xmlhttp.status==200) {\n\t result = xmlhttp.responseText;\n\t addInvitesResult(result, element);\n\t}\n }\n \n xmlhttp.open(\"POST\", \"resources/update-invites.php\", true);\n xmlhttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n xmlhttp.send(null);\n}",
"function initInvitationsReceived() {\n var tmpUser, tmpGroup, tmpChannel;\n vm.invitationsReceived = angular.copy(vm.user.pendingInvitations);\n vm.invitationsReceived.forEach(function (invitation) {\n\n // Add some data about the user\n tmpUser = usersFactory.getUserByUsername(invitation.sentBy);\n invitation.givenName = tmpUser.givenName;\n invitation.surname = tmpUser.surname;\n\n // Add some data about the group\n if (invitation.tag == 'group') {\n tmpGroup = groupsFactory.getGroupById(invitation.groupId);\n invitation.groupName = tmpGroup.name;\n }\n\n // Add some data about the channel\n else if (invitation.tag == 'channel') {\n tmpGroup = groupsFactory.getGroupById(invitation.groupId);\n invitation.groupName = tmpGroup.name;\n tmpChannel = groupsFactory.getChannelById(tmpGroup.name, invitation.channelId);\n invitation.channelName = tmpChannel.name;\n }\n });\n }",
"function updateHiddenInput() {\n var result = [];\n $('#included-items > li').each(function(index) {\n result.push( $(this).attr('data-item-id') );\n });\n $('input[name=items]').val(result.join(','));\n }",
"updatePendingInvites(userInvites){\n for(let i of userInvites){\n if(!this.session.settings.invites.hasOwnProperty(i)){\n this.session.settings.invites[i] = {}\n }\n }\n for (let i of Object.keys(this.session.settings.invites)){\n if(!userInvites.includes(i)){\n delete this.session.settings.invites[i];\n }\n }\n\n this.saveClientSettings(this.session.settings, this.session.privateKey);\n }",
"@action.bound updateSelectedByAnswerId(ansId) {\n this.filterText = '';\n const filteredInd = this.filteredAnswers.findIndex(ans => (ans.id === ansId));\n this.updateSelectedSubGraphIndex(filteredInd);\n }",
"updatePrompt() {\n this.fields.forEach(field => {\n if (field.property && field.property !== \"\") {\n this.value[field.property] = this.__selectionContents.getAttribute(\n field.property\n );\n } else if (field.property && field.property !== \"\") {\n this.value[field.slot] = this.__selectionContents.querySelector(\n field.slot\n );\n } else {\n this.value[\"\"] = this.__selectionContents.innerHTML;\n }\n });\n }",
"function updateIncomingChallengeUI(slicedChallenges) {\n for (var i = 0; i < slicedChallenges.length; i++) {\n let challenge = slicedChallenges[i];\n let key = challenge.key;\n\n challenge = challenge.val();\n let challengerId = challenge.challengerId;\n let challenger = challenge.challenger;\n let quiz = challenge.quiz;\n\n var buttonId = buttonIds[i];\n var playerId = playerIds[i];\n document.getElementById(playerId).innerHTML = \"<p><b>\" + quiz.name + \"</b> By \" + challenger;\n document.getElementById(numIds[i]).innerHTML = i + 1;\n document.getElementById(buttonId).innerHTML = \"Accept Challenge\";\n setEventListener2(key, challengerId, buttonId, playerId);\n // TODO: Fix this\n // challengeIdMap[challengeIds[i]] =key;\n // ownerIdMap[challengeIds[i]] = challengerId;\n }\n}",
"function setEmails(ele)\r\n{\r\n\tvar str = '';\r\n\tvar counter = 0;\r\n\t\r\n\t$('.invite-email').each(function()\r\n\t{\r\n\t\tif (counter != 0) {\r\n\t\t\tstr += ',';\r\n\t\t}\r\n\t\t\r\n\t\tstr += $(this).text();\r\n\t\tcounter++;\r\n\t})\r\n\t\r\n\tif (typeof ele == 'undefined') {\r\n\t\tele = $('#emails');\r\n\t}\r\n\t\r\n\r\n\tele.val(str);\r\n}",
"function processInvitation(r) {\n rInvitation = r;\n isIncoming = rInvitation.get('direction') == 'Incoming';\n setResource(ucwa.get(rInvitation.link('conversation').href));\n threadId.set(rInvitation.get('threadId') + '');\n // in outgoing invitation /from points to the local participant\n // which must not be added to the .participants collection\n if (rInvitation.hasLink('from') && isIncoming) {\n var senderHref = rInvitation.link('from').href; // rel=participant\n var senderName = ucwa.get(senderHref).get('name', void 0);\n resolveParticipant(senderHref, senderName);\n }\n else if (rInvitation.hasLink('to') && !isIncoming) {\n var receiverHref = rInvitation.link('to').href; // rel=person\n var matchingParticipants = participants.filter(function (p) { return p.person[Internal.sHref] == receiverHref; });\n if (matchingParticipants.size() == 0) {\n var person = contactManager.get(receiverHref);\n var participant = createParticipantFromPersonOrUri(person);\n addParticipant(participant);\n }\n }\n state(isIncoming ? Conversation.State.Incoming : Conversation.State.Connecting);\n if (rInvitation.rel == 'onlineMeetingInvitation') {\n self.meeting = new Internal.OnlineMeeting({\n ucwa: ucwa,\n rInvitation: rInvitation,\n from: isIncoming ? participants(0) : localParticipant,\n conversation: self,\n contactManager: contactManager\n });\n changed.fire();\n }\n }",
"function sendInvites(json, statusText) {\n\t$(\"table.team tr:last\").after(json.members_html);\n for (i = 0; i < json.members_ids.length; i++) {\n\t\t$(\"#member_\"+ json.members_ids[i]).highlightFade({start: '#FFFF99', speed: 2000});\n\t $(\"#member_\"+ json.members_ids[i] +\" a.tip\").link_tips();\n\t};\n\t$(\"div.list-people\").after(\"<div class='invited-sent'><h3>Invites sent!</h3><p>Sent invites to \"+ json.members_names+\". Don't forget to edit their permissions on the left.</p></div>\");\t \n\tresetInviteQueue();\n\tcloseContactSelect();\n\t$(\"input[name='invites[]']\").remove();\n\tremove_this_after($(\"div.invited-sent\"), 7000);\n}",
"function updateNumberOfGuests() {\n \tcontainer.find(\"#numberOfGuests\").html(model.getNumberOfGuests());\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}",
"function updateSelectedList(emailID) {\n let newSelected = [...selectedEmails];\n if (newSelected.includes(emailID)) {\n newSelected = newSelected.filter((id) => id !== emailID);\n } else {\n newSelected.push(emailID);\n }\n setSelectedEmails(newSelected);\n }",
"cancel(invitation) {\n axios.delete(`/settings/invitations/${invitation.id}`)\n .then(() => {\n this.$parent.$emit('updateInvitations');\n });\n }",
"edit() {\n\t\tvar value = this.input.val();\n\n\t\tthis.$el.addClass('editing');\n\t\tthis.input.val(value).focus();\n\t}",
"function sendInvite(newfriendname) {\n\t// post to /addfriend/ where database takes care of sending invite\n\t\n\t\n\t$(\" <div />\" ).attr(\"id\",'confirm_invitation')\n\t.attr(\"title\", 'Confirm Invitation')\n\t.html(\n\t\t'<div id=\"myconfirmationinvitation\">' + \n\t\t'<table width=100%> <tr style=\"text-align: center;\"><td colspan=\"2\" style=\"height: 50px;\">' +\n\t\t'Do you want to send an invitation email? </td></tr>' +\n\t\t'<tr style=\"text-align: center;\">' +\n\t\t'<td style=\"width: 100px;\"> <a id=\"sendInvitebutton\" class=\"btn btn-success\" style=\"width: 60px;\"> <i class=\"icon-ok icon-white\"></i></a> </td>' +\n\t\t'<td style=\"width: 100px\"> <a id=\"nosendInvitebutton\" class=\"btn btn-danger\" style=\"width: 60px;\"> <i class=\"icon-remove icon-white\"></i></a></td> ' +\n\t\t'</tr></table></div>'\n\t\t\n\t)\n\t.appendTo($( \"#boxes\" ));\n\n\t$('#sendInvitebutton').click(\n\t\tfunction() {\n\t\t\tinvite(newfriendname);\n\t\t\t$('#confirm_invitation').dialog('destroy').remove()\n\t\t}\n\t);\n\t$('#nosendInvitebutton').click(\n\t\tfunction() {\n\t\t\t$('#confirm_invitation').dialog('destroy').remove()\n\t\t}\n\t);\n\t\n\t$('#confirm_invitation').dialog( {\n autoOpen: true,\n modal: true\n });\n}",
"function updateClinicianList() {\r\n\r\n // Null out current selected item and clear list.\r\n $scope.exportDataFormBean.clinicianId = \"\";\r\n //console.log(\">> \"+ $scope.exportDataFormBean.clinicianId);\r\n $scope.clinicanList = [];\r\n\r\n // Create the request parameters we will post.\r\n var requestPayload = {};\r\n if ($scope.exportDataFormBean.showDeletedClinicians) {\r\n requestPayload = $.param({\"includeAll\": true});\r\n }\r\n else {\r\n requestPayload = $.param({\"includeAll\": false});\r\n }\r\n\r\n // Call the web service and update the model.\r\n $http({\r\n method: \"POST\",\r\n url: \"exportData/services/user/clinicians\",\r\n responseType: \"json\",\r\n headers: {'Content-Type': 'application/x-www-form-urlencoded'},\r\n data: requestPayload\r\n })\r\n .success(function (data, status, headers, config) {\r\n $scope.clinicanList = data;\r\n })\r\n .error(function (data, status) {\r\n //\r\n });\r\n }",
"function changeFriendElement(friendKey){\n var friendData;\n for (var i = 0; i < userArr.length; i++){\n if(friendKey == userArr[i].uid){\n friendData = userArr[i];\n break;\n }\n }\n\n if(friendData != null) {\n var userUid = friendData.uid;\n var friendName = friendData.name;\n var friendUserName = friendData.userName;\n var friendShareCode = friendData.shareCode;\n var liItemUpdate = document.getElementById(\"user\" + userUid);\n liItemUpdate.innerHTML = friendName;\n liItemUpdate.className = \"gift\";\n liItemUpdate.onclick = function () {\n var span = document.getElementsByClassName(\"close\")[0];\n var friendSendMessage = document.getElementById('sendPrivateMessage');\n var friendInviteRemove = document.getElementById('userInviteRemove');\n var friendNameField = document.getElementById('userName');\n var friendUserNameField = document.getElementById('userUName');\n var friendShareCodeField = document.getElementById('userShareCode');\n\n if (friendShareCode == undefined) {\n friendShareCode = \"This User Does Not Have A Share Code\";\n }\n\n friendNameField.innerHTML = friendName;\n friendUserNameField.innerHTML = \"User Name: \" + friendUserName;\n friendShareCodeField.innerHTML = \"Share Code: \" + friendShareCode;\n\n friendSendMessage.onclick = function() {\n generatePrivateMessageDialog(friendData);\n };\n\n friendInviteRemove.onclick = function () {\n modal.style.display = \"none\";\n deleteFriend(userUid);\n };\n\n //show modal\n modal.style.display = \"block\";\n\n //close on close\n span.onclick = function () {\n modal.style.display = \"none\";\n };\n\n //close on click\n window.onclick = function (event) {\n if (event.target == modal) {\n modal.style.display = \"none\";\n }\n }\n };\n }\n }",
"function updateAttendees(event) {\n\tvar attendee_name = $(this).attr(\"value\");\n\tvar attendee_email = \"\";\n\n\tvar contacts_list = JSON.parse(localStorage.getItem(\"contacts\"));\n\tfor(var count = 0; count < contacts_list.length; count++) {\n\t\tif(contacts_list[count].name === attendee_name) {\n\t\t\tattendee_email = contacts_list[count].email;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif($(this).prop(\"checked\")) {\n\t\tfor(var count = 0; count < attendees.length; count++) { //make sure you don't add duplicates\n\t\t\tif(attendees[count].name === attendee_name) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n attendees.push({ name: attendee_name, email: attendee_email });\n\t}\n\telse {\n\t\tfor(var count = 0; count < attendees.length; count++) { //find contact to be removed\n\t\t\tif(attendees[count].name === attendee_name) {\n\t\t\t\tattendees.splice(count, 1);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tupdateRecipientLists();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get name from fullname | function getName(fullname) {
let result = '';
const fullnameCut = fullname.split(' ');
result = fullnameCut[fullnameCut.length-1];
return result;
} | [
"function getFullName(first, middle, last) {\r\n\tvar fullname = first;\r\n\tif (middle) {\r\n\t\tfullname += \" \" + middle\r\n\t}\r\n\treturn fullname + \" \" + last;\r\n}",
"getNames( fullName ) {\n \"use strict\";\n // Return firstName, middleName and lastName based on fullName components ([0],[1],[2])\n }",
"getShortName() {\n let shortName = this.firstName + ' ' + this._getInitial(this.lastName) + '.';\n return shortName;\n }",
"function formatName(person){\n\treturn person.fullName;\n}",
"function getFullName (name, surname) {\n var fullName = name + ' ' + surname\n return 'Your name is ' + fullName\n}",
"function abbreviatedFun(fullname) {\n let array = fullname.split(' ');\n let result = array[0];\n for (i = 1; i < array.length; i++) {\n result += ' ' + (array[i])[0];\n }\n result += '.';\n return result;\n \n}",
"function getMiddleName(fullName) {\n fullName = fullName.trim();\n fullName = fullName.split(\" \");\n\n // console.log(fullName)\n if (fullName.length > 2) {\n middleName = fullName[1];\n // middleName = student.fullName.substring(0, 1).toUpperCase() + student.fullName.substring(1).toLowerCase();\n\n // console.log(middleName)\n }\n // console.log(middleName)\n // if (middleName.includes(\" \") == true) {\n // middleName = student.middleName.substring(0, 1).toUpperCase() + student.middleName.substring(1).toLowerCase();\n else {\n middleName = \" \";\n }\n\n return middleName;\n}",
"function fullName(array, index) {\n if (array[index].name.middle === undefined) {\n return array[index].name.first + \" \" + array[index].name.last;\n } else {\n return (\n array[index].name.first +\n \" \" +\n array[index].name.middle +\n \" \" +\n array[index].name.last\n );\n }\n}",
"function fullName (firstName, lastName) {\n return firstName + \" \" + lastName;\n}",
"_getInitial(name) {\n return name[0].toUpperCase();\n }",
"function getDisplayName(generatorName) {\n // Breakdown of regular expression to extract name (group 3 in pattern):\n //\n // Pattern | Meaning\n // -------------------------------------------------------------------\n // (generator-)? | Grp 1; Match \"generator-\"; Optional\n // (polymer-init)? | Grp 2; Match \"polymer-init-\"; Optional\n // ([^:]+) | Grp 3; Match one or more characters != \":\"\n // (:.*)? | Grp 4; Match \":\" followed by anything; Optional\n return generatorName.replace(/(generator-)?(polymer-init-)?([^:]+)(:.*)?/g, '$3');\n}",
"nameFormat(name) {\n return name;\n }",
"function findfullName() {\n console.log('\\n\\n======================================================================================');\n console.log('Return full name of employee:');\n console.log(\"======================================================================================\");\n for (var _i = 0, emp_1 = exports.emp; _i < emp_1.length; _i++) {\n var fullName = emp_1[_i];\n // var fname = fullName.firstname;\n // var lname = fullName.lastname;\n // var wholeName = `${fname} ${lname}`;\n // return wholeName;\n var fname = fullName.firstname;\n var lname = fullName.lastname;\n console.log(fname + \" \" + lname);\n // var empfullname = fullName.firstname +\" \"+fullName.lastname;\n // console.log(empfullname);\n }\n}",
"function renderFullName( name ) {\n \n\n spanResultElement.innerHTML = name;\n}",
"function sayName() {\r\n console.log(splitName[0]);\r\n}",
"function getLocalName(iri) {\n return splitIri(iri)[1];\n}",
"parseName() {\n return ionMarkDown_1.Imd.MarkDownToHTML(this.details.artist) + \" - \" + ionMarkDown_1.Imd.MarkDownToHTML(this.details.title);\n }",
"async function getName(ctx) {\n await CONTEXT_SCHEMA.validate(ctx);\n if (ctx.sub.length < 1) {\n return ctx.name;\n }\n\n return `${ctx.name}(${ctx.sub.join(',')})`;\n}",
"function getFullName(firstName, lastName) {\n\n let fullName = firstName + \" \" + lastName;\n\n for (let i = 2; i < arguments.length; i++) {\n arguments[i];\n fullName = fullName + \" \" + arguments[i];\n }\n\n return fullName;\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts the math node into a MathMLnamespaced DOM element. | toNode() {
const node = document.createElementNS("http://www.w3.org/1998/Math/MathML", this.type);
for (const attr in this.attributes) {
if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
node.setAttribute(attr, this.attributes[attr]);
}
}
for (let i = 0; i < this.children.length; i++) {
node.appendChild(this.children[i].toNode());
}
return node;
} | [
"toNode() {\n if (this.character) {\n return document.createTextNode(this.character);\n } else {\n const node = document.createElementNS(\"http://www.w3.org/1998/Math/MathML\", \"mspace\");\n node.setAttribute(\"width\", this.width + \"em\");\n return node;\n }\n }",
"function buildMathML(tree, texExpression, options) {\n const expression = buildExpression$1(tree, options); // Wrap up the expression in an mrow so it is presented in the semantics\n // tag correctly, unless it's a single <mrow> or <mtable>.\n\n let wrapper;\n\n if (expression.length === 1 && expression[0] instanceof MathNode && utils.contains([\"mrow\", \"mtable\"], expression[0].type)) {\n wrapper = expression[0];\n } else {\n wrapper = new mathMLTree.MathNode(\"mrow\", expression);\n } // Build a TeX annotation of the source\n\n\n const annotation = new mathMLTree.MathNode(\"annotation\", [new mathMLTree.TextNode(texExpression)]);\n annotation.setAttribute(\"encoding\", \"application/x-tex\");\n const semantics = new mathMLTree.MathNode(\"semantics\", [wrapper, annotation]);\n const math = new mathMLTree.MathNode(\"math\", [semantics]); // You can't style <math> nodes, so we wrap the node in a span.\n // NOTE: The span class is not typed to have <math> nodes as children, and\n // we don't want to make the children type more generic since the children\n // of span are expected to have more fields in `buildHtml` contexts.\n // $FlowFixMe\n\n return buildCommon.makeSpan([\"katex-mathml\"], [math]);\n }",
"toText() {\n // To avoid this, we would subclass documentFragment separately for\n // MathML, but polyfills for subclassing is expensive per PR 1469.\n // $FlowFixMe: Only works for ChildType = MathDomNode.\n const toText = child => child.toText();\n\n return this.children.map(toText).join(\"\");\n }",
"function convertToMath() {\n\treturn eval(getId('result').value);\n}",
"function formatMath(expr) {\n\treturn `${expr} = ${eval(expr.replace(\"x\", \"*\"))}`\n}",
"function MathRenderer() {\n scope.AbstractRenderer.call(this);\n }",
"function Math(props) {\n let value;\n\n // Assign value based on the operator\n switch (props.operator) {\n case \"+\":\n value = props.num1 + props.num2;\n break;\n case \"-\":\n value = props.num1 - props.num2;\n break;\n case \"*\":\n value = props.num1 * props.num2;\n break;\n case \"/\":\n value = props.num1 / props.num2;\n break;\n default:\n value = NaN;\n }\n\n // Return a span element containing the calculated value\n // Set the fontSize to the value in pixels\n return <span style={{ fontSize: value }}>{value}</span>;\n}",
"function svgSetTransform(elSvg, objSvgProperties) {\n var bolUseStringMethod = true;\n\n if (bolUseStringMethod) {\n /* String method */\n // var strTransformValue='translate('+objSvgProperties['translatex']+', '+objSvgProperties['translatey']+') scale('+objSvgProperties['scale']+')';\n if (objSvgProperties.scale === 'Infinity') objSvgProperties.scale = 1;\n var strTransformValue = 'matrix(' + objSvgProperties.scale + ',0,0,' + objSvgProperties.scale + ',' + objSvgProperties.translatex + ',' + objSvgProperties.translatey + ')';\n\n elSvg.setAttributeNS(null, 'transform', strTransformValue);\n } else {\n /* Native method */\n\n // Set the new values for the transform matrix\n objSvgProperties.transformmatrix.a = objSvgProperties.scale;\n objSvgProperties.transformmatrix.b = 0;\n objSvgProperties.transformmatrix.c = 0;\n objSvgProperties.transformmatrix.d = objSvgProperties.scale;\n objSvgProperties.transformmatrix.e = objSvgProperties.translatex;\n objSvgProperties.transformmatrix.f = objSvgProperties.translatey;\n\n // console.log(objSvgProperties.transformmatrix);\n\n // someitem.ownerSVGElement.createSVGTransformFromMatrix(m)\n var svgTransform = elSvg.ownerSVGElement.createSVGTransformFromMatrix(objSvgProperties.transformmatrix);\n\n // console.log(bla);\n\n elSvg.transform.baseVal.initialize(svgTransform);\n }\n\n}",
"toHtml() {\n let node = createSpan(\"term\");\n if (this.items.length == 0 && this.charge == -1) {\n node.textContent = \"e\";\n node.append(createElem(\"sup\", MINUS));\n }\n else {\n for (const item of this.items)\n node.append(item.toHtml());\n if (this.charge != 0) {\n let s;\n if (Math.abs(this.charge) == 1)\n s = \"\";\n else\n s = Math.abs(this.charge).toString();\n if (this.charge > 0)\n s += \"+\";\n else\n s += MINUS;\n node.append(createElem(\"sup\", s));\n }\n }\n return node;\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}",
"toNODE() {\n switch (this._type) {\n case \"NODE\":\n return this._value;\n case \"STRING\":\n let parser = new DOMParser();\n let doc = parser.parseFromString(this._value, \"text/html\");\n return doc.body.firstChild;\n case \"YNGWIE\":\n return this._value.render();\n default:\n throw new _Transform_main_js__WEBPACK_IMPORTED_MODULE_3__.default(\"Cannot transform to NODE from unsuppoted type\", this._value);\n }\n }",
"function wrapNode(n, v) {\n\t\tvar thisValue = v !== undefined ? v : \"\";\n\t\treturn \"<\" + n + \">\" + thisValue + \"</\" + n + \">\";\n\t}",
"function processMath(text, { mathInlineDelimiters, mathBlockDelimiters, mathRenderingOnlineService }) {\n let line = text.replace(/\\\\\\$/g, \"#slash_dollarsign#\");\n const inline = mathInlineDelimiters;\n const block = mathBlockDelimiters;\n const inlineBegin = \"(?:\" +\n inline\n .map((x) => x[0])\n .join(\"|\")\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/([\\(\\)\\[\\]\\$])/g, \"\\\\$1\") +\n \")\";\n const inlineEnd = \"(?:\" +\n inline\n .map((x) => x[1])\n .join(\"|\")\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/([\\(\\)\\[\\]\\$])/g, \"\\\\$1\") +\n \")\";\n const blockBegin = \"(?:\" +\n block\n .map((x) => x[0])\n .join(\"|\")\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/([\\(\\)\\[\\]\\$])/g, \"\\\\$1\") +\n \")\";\n const blockEnd = \"(?:\" +\n block\n .map((x) => x[1])\n .join(\"|\")\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/([\\(\\)\\[\\]\\$])/g, \"\\\\$1\") +\n \")\";\n // display\n line = line.replace(new RegExp(`(\\`\\`\\`(?:[\\\\s\\\\S]+?)\\`\\`\\`\\\\s*(?:\\\\n|$))|(?:${blockBegin}([\\\\s\\\\S]+?)${blockEnd})`, \"g\"), ($0, $1, $2) => {\n if ($1) {\n return $1;\n }\n let math = $2;\n math = math.replace(/\\n/g, \"\").replace(/\\#slash\\_dollarsign\\#/g, \"\\\\$\");\n math = utility.escapeString(math);\n return `<p align=\"center\"><img src=\\\"${mathRenderingOnlineService}?${math\n .trim()\n .replace(/ /g, \"%20\")}\\\"/></p> \\n`;\n });\n // inline\n line = line.replace(new RegExp(`(\\`\\`\\`(?:[\\\\s\\\\S]+?)\\`\\`\\`\\\\s*(?:\\\\n|$))|(?:${inlineBegin}([\\\\s\\\\S]+?)${inlineEnd})`, \"g\"), ($0, $1, $2) => {\n if ($1) {\n return $1;\n }\n let math = $2;\n math = math.replace(/\\n/g, \"\").replace(/\\#slash\\_dollarsign\\#/g, \"\\\\$\");\n math = utility.escapeString(math);\n return `<img src=\\\"${mathRenderingOnlineService}?${math\n .trim()\n .replace(/ /g, \"%20\")}\\\"/>`;\n });\n line = line.replace(/\\#slash\\_dollarsign\\#/g, \"\\\\$\");\n return line;\n}",
"function vml(tag,attr){return createEl('<'+tag+' xmlns=\"urn:schemas-microsoft.com:vml\" class=\"spin-vml\">',attr);}// No CSS transforms but VML support, add a CSS rule for VML elements:",
"add(noodle, container, constr, label, pos, noodleExp) {\n var node = constr(noodle, container, label, pos, noodleExp);\n container.forest.push(node);\n var nodeNoodle = node.noodle || noodle.expr.eval(noodle, node.noodleExp);\n nodeNoodle.node.render(node, container);\n nodeNoodle.graphics.transformable.setActive(nodeNoodle, node.html); //Should this be inside render?\n\n return node;\n }",
"function getSvgXml() {\n return new XMLSerializer().serializeToString(Data.Svg.Node);\n}",
"function makeNode(javaNode) {\n if (!javaNode) {\n return null;\n }\n if (_domNodes.containsKey(javaNode)) {\n return _domNodes.get(javaNode);\n }\n const isElement = javaNode.getNodeType() === org.w3c.dom.Node.ELEMENT_NODE;\n const jsNode = isElement ? new window.DOMElement(javaNode) : new window.DOMNode(javaNode);\n _domNodes.put(javaNode, jsNode);\n return jsNode;\n }",
"function LogicNodeFloat() {\n\tLogicNode.call(this);\n\tthis.logicInterface = LogicNodeFloat.logicInterface;\n\tthis.type = 'LogicNodeFloat';\n}",
"function loadMathLibrary(pO) {\r\n\r\n var mM = new ModuleObj(\"Math\");\r\n\r\n // Set current module object to this module. This is necessary for\r\n // creating expressions. As a result the expressions in this library\r\n // get seq numbers starting from 1. See description at ModuleObj.\r\n //\r\n // VERIFY: TODO:\r\n //\r\n CurModObj = mM;\r\n\r\n // All math library names are listed here. Firs list functions without\r\n // no args. Then use 'ADDARG' tag to move to functions with one additional\r\n // arg\r\n //\r\n var mathFnames = ['random',\r\n 'ADDARG',\r\n 'abs', 'ceil', 'cos', 'exp', 'floor', 'log',\r\n 'sqrt', 'round', 'random', 'sin', 'tan',\r\n 'ADDARG',\r\n 'min', 'max', 'pow', 'mod'\r\n ];\r\n\r\n var number_args = 0;\r\n\r\n // Go thru all math functions listed \r\n //\r\n for (var i = 0; i < mathFnames.length; i++) {\r\n\r\n var name = mathFnames[i];\r\n //\t\r\n if (name == 'ADDARG') { // if 'ADDARG' tag, increment args\r\n number_args++;\r\n continue;\r\n }\r\n\r\n // Create a function object, add a function call expression (header)\r\n // \r\n var fPI = new FuncObj(true);\r\n fPI.funcCallExpr = new ExprObj(false, ExprType.LibFuncCall, name);\r\n fPI.isLibFunc = true;\r\n //\r\n // Add 'number_args' args. Since this is the Math library, all args\r\n // are numbers\r\n //\r\n for (var a = 0; a < number_args; a++) {\r\n\r\n var arg1 = new ExprObj(true, ExprType.Number, 'number');\r\n fPI.funcCallExpr.addSubExpr(arg1);\r\n }\r\n\r\n // Push the added function to the Math module\r\n //\r\n mM.allFuncs.push(fPI);\r\n }\r\n\r\n\r\n // Add the Math module to the program object\r\n //\r\n pO.libModules.push(mM);\r\n\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update existing delivery profile. | static update(id, delivery){
let kparams = {};
kparams.id = id;
kparams.delivery = delivery;
return new kaltura.RequestBuilder('deliveryprofile', 'update', kparams);
} | [
"static update(id, distributionProfile){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.distributionProfile = distributionProfile;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_distributionprofile', 'update', kparams);\n\t}",
"function updateDriver() {\n profileFactory.updateProfile(vm.profile).then(\n function() {}\n );\n }",
"SET_PROFILE_EMAIL(state, payload) {\n state.Profile.email = payload;\n }",
"static update(storageProfileId, storageProfile){\n\t\tlet kparams = {};\n\t\tkparams.storageProfileId = storageProfileId;\n\t\tkparams.storageProfile = storageProfile;\n\t\treturn new kaltura.RequestBuilder('storageprofile', 'update', kparams);\n\t}",
"static update(id, conversionProfile){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.conversionProfile = conversionProfile;\n\t\treturn new kaltura.RequestBuilder('conversionprofile', 'update', kparams);\n\t}",
"async update ({ params, request, response, auth }) {\n const establishment = await Establishment.findOrFail(params.id)\n\n if (establishment.user_id !== auth.user.id) {\n return response.status(401).send({ error: 'Not authorized' })\n }\n\n const data = request.only([\n 'title',\n 'state',\n 'city',\n 'country',\n 'description',\n 'classification',\n 'facebook',\n 'twitter',\n 'instagram',\n 'telephone',\n 'website',\n 'category',\n ])\n\n establishment.merge(data)\n\n await establishment.save()\n\n return establishment\n }",
"static update(id, reachProfile){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.reachProfile = reachProfile;\n\t\treturn new kaltura.RequestBuilder('reach_reachprofile', 'update', kparams);\n\t}",
"static update(id, scheduledTaskProfile){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.scheduledTaskProfile = scheduledTaskProfile;\n\t\treturn new kaltura.RequestBuilder('scheduledtask_scheduledtaskprofile', 'update', kparams);\n\t}",
"static update(id, EmailIP){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.EmailIP = EmailIP;\n\t\treturn new kaltura.RequestBuilder('emailingestionprofile', 'update', kparams);\n\t}",
"function addDelivery () {\n\tvar settings = [];\n\tsettings.from = lastFrom = (widget.preferenceForKey('store')) ? \n\t\twidget.preferenceForKey('store') : 'www.amazon.com';\n\n\teditingDelivery = new Delivery(settings);\n\tupdateEditForm(editingDelivery.from);\n\tfillEditForm(editingDelivery,true);\n\tswitchToView('back','edit');\n}",
"function UpdateWcOrder() {\n console.log('UpdateWcOrder()')\n console.assert(window._wcOrder.id != null)\n\n var $select = $('[name=\"ship_method\"]').find(':selected')\n var props = {\n shipping_lines: [\n {\n method_id: $select.val(),\n method_title: $select.data('title'),\n total: numeral($select.data('cost')).format('0.00')\n }\n ]\n }\n\n return $.ajax({\n type: 'PUT',\n url: 'ws/update_order',\n // headers: { 'Content-Type': 'application/json' },\n data: {\n userId: window._userId,\n recipientId: window._recipientId,\n orderId: window._orderId,\n updateProps: JSON.stringify(props)\n }\n })\n}",
"async update(req, res) {\n const schema = Yup.object().shape({\n name: Yup.string().required(),\n address: Yup.string().required(),\n number: Yup.number().required(),\n address_2: Yup.string(),\n city: Yup.string().required(),\n state: Yup.string().required(),\n zip_code: Yup.string().required(),\n });\n\n if (!(await schema.isValid(req.body))) {\n return res.status(400).json({ error: 'Validation failed' });\n }\n\n const recipient = await Recipient.findByPk(req.params.id);\n\n if (!recipient) {\n return res.status(400).json({ error: 'Recipient not found' });\n }\n\n try {\n const updatedRecipient = await recipient.update(req.body);\n return res.json(updatedRecipient);\n } catch (err) {\n return res.status(400).json({ error: `Something went wrong - ${err}` });\n }\n }",
"static update(id, accessControlProfile){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.accessControlProfile = accessControlProfile;\n\t\treturn new kaltura.RequestBuilder('accesscontrolprofile', 'update', kparams);\n\t}",
"function saveDeliveryAddress(delivery_address){\n var cart_data = JSON.parse(localStorage.getItem('cart_data'));\n var delivery_method = document.getElementById(\"shippingMethodInput\").value;\n\n cart_data[\"delivery_address\"] = delivery_address;\n cart_data[\"delivery_method\"] = delivery_method;\n\n localStorage.setItem('cart_data', JSON.stringify(cart_data));\n\n console.log(\"Update delivery address and method to cart_data\");\n console.log(cart_data);\n}",
"setProfileEmail({ commit }, data) {\n commit(\"SET_PROFILE_EMAIL\", data);\n }",
"_update() {\n var i, pr, inn=0, mer=0, ban=0, bui=0;\n\n for (i in this.profiles) {\n pr = this.profiles[i];\n bui += pr.builder;\n mer += pr.merchant;\n inn += pr.innovator;\n ban += pr.banker;\n }\n \n /* update the average */\n if (this.profiles.length > 0) {\n this.builder = bui / this.profiles.length;\n this.merchant = mer / this.profiles.length;\n this.innovator = inn / this.profiles.length;\n this.banker = ban / this.profiles.length;\n }\n else {\n this.builder = 0;\n this.merchant = 0\n this.innovator = 0;\n this.banker = 0;\n }\n }",
"static updateStatus(id, status){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.status = status;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_distributionprofile', 'updateStatus', kparams);\n\t}",
"updateMeetup(state, payload) {\n // search for the meetup that has changes\n const meetup = state.loadedMeetUps.find(meetup => {\n return meetup.id === payload.id;\n });\n\n if (payload.title) {\n meetup.title = payload.title;\n }\n if (payload.description) {\n meetup.description = payload.description;\n }\n if (payload.date) {\n meetup.date = payload.date;\n }\n if (payload.time) {\n meetup.time = payload.time;\n }\n }",
"function updateCampaign() {\n if (hasChanged(data.Campaign, vm.campaign)) {\n CampaignService.updateCampaign(vm.campaign)\n .then(closeModal)\n .catch(handleError);\n } else {\n closeModal();\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Output private & public part of the key in PKCS1 PEM format. | function _rsapem_privateKeyToPkcs1PemString() {
return hex2b64(_rsapem_privateKeyToPkcs1HexString(this));
} | [
"getPrivKey() {\n var output = PrivKeyAsn1.encode({\n d: this.key.priv.toString(10),\n }, \"der\")\n return output.toString('hex')\n }",
"showPrivateKey() {\n this.showKey(this.privateKey, true);\n }",
"async _publicKeyFromCertificate (crtPath) {\n let output = '';\n await this.opensslCommand(\n ['x509', '-noout', '-in', crtPath, '-pubkey', '-outform', 'pem'],\n (o => { output += o; })\n );\n return output;\n }",
"function indcpaPackPrivateKey(privateKey, paramsK) {\r\n return polyvecToBytes(privateKey, paramsK);\r\n}",
"function importPrivateKey(pem) {\n const binaryDer = pem2derArr(pem);\n \n return window.crypto.subtle.importKey(\n \"pkcs8\",\n binaryDer,\n {\n name: \"RSASSA-PKCS1-v1_5\",\n // Consider using a 4096-bit key for systems that require long-term security\n //modulusLength: 2048,\n //publicExponent: new Uint8Array([1, 0, 1]),\n hash: \"SHA-256\",\n },\n false,\n [\"sign\"]\n );\n }",
"function generateKeypair(cmd) {\n\tlet keypair_path = cmd.output;\n\n\tif (keypair_path == null) {\n\t\tlet cfg_dir = configdir(\"webhookify\");\n\t\tif (!fs.existsSync(cfg_dir)) {\n\t\t\tmkdirp.sync(cfg_dir);\n\t\t}\n\t\tkeypair_path = path.join(cfg_dir, \"key.pem\");\n\t}\n\n\tif (fs.existsSync(keypair_path)) {\n\t\tconsole.log(\"The specified keyfile already exists.\");\n\t\treturn;\n\t}\n\n\tconsole.log(\"Generating keypair with 2048 bit modulus...\");\n\tlet keypair = rsa_utils.generateKeyPair();\n\n\tconsole.log(`Writing keypair to ${keypair_path}...`);\n\tfs.writeFileSync(keypair_path, keypair.privateKey, { mode: 0o400 });\n\n\tconsole.log(\"The public component of your keypair is as follows:\");\n\tconsole.log();\n\tconsole.log(keypair.publicKey);\n\tconsole.log();\n\tconsole.log(\"Please copy & paste this to the webhookify website.\");\n}",
"function generateAndSetKeypair () {\n opts.log(`generating ${opts.bits}-bit RSA keypair...`, false)\n var keys = peerId.create({\n bits: opts.bits\n })\n config.Identity = {\n PeerID: keys.toB58String(),\n PrivKey: keys.privKey.bytes.toString('base64')\n }\n opts.log('done')\n opts.log('peer identity: ' + config.Identity.PeerID)\n\n writeVersion()\n }",
"function getPublicKey(req, res) {\n var key_path = './server/keystore/key/public_key.pem';\n return g_fs.readFileAsync(key_path, \"ascii\")\n .then(function (content) {\n return res.send(content);\n })\n .catch(function (exception) {\n console.log(\"error fetching key\");\n res.sendStatus(400);\n });\n }",
"function getP12Properties(p12Path, p12Pwd) {\n return __awaiter(this, void 0, void 0, function* () {\n //openssl pkcs12 -in <p12Path> -nokeys -passin pass:\"<p12Pwd>\" | openssl x509 -noout -fingerprint –subject -dates\n let opensslPath = tl.which('openssl', true);\n let openssl1 = tl.tool(opensslPath);\n if (!p12Pwd) {\n // if password is null or not defined, set it to empty\n p12Pwd = '';\n }\n openssl1.arg(['pkcs12', '-in', p12Path, '-nokeys', '-passin', 'pass:' + p12Pwd]);\n let openssl2 = tl.tool(opensslPath);\n openssl2.arg(['x509', '-noout', '-fingerprint', '-subject', '-dates']);\n openssl1.pipeExecOutputToTool(openssl2);\n let fingerprint;\n let commonName;\n let notBefore;\n let notAfter;\n function onLine(line) {\n if (line) {\n const tuple = splitIntoKeyValue(line);\n const key = tuple.key;\n const value = tuple.value;\n if (key === 'SHA1 Fingerprint') {\n // Example value: \"BB:26:83:C6:AA:88:35:DE:36:94:F2:CF:37:0A:D4:60:BB:AE:87:0C\"\n // Remove colons separating each octet.\n fingerprint = value.replace(/:/g, '').trim();\n }\n else if (key === 'subject') {\n // Example value1: \"/UID=E848ASUQZY/CN=iPhone Developer: Chris Sidi (7RZ3N927YF)/OU=DJ8T2973U7/O=Chris Sidi/C=US\"\n // Example value2: \"/UID=E848ASUQZY/CN=iPhone Developer: Chris / Sidi (7RZ3N927YF)/OU=DJ8T2973U7/O=Chris Sidi/C=US\"\n // Example value3: \"/UID=E848ASUQZY/OU=DJ8T2973U7/O=Chris Sidi/C=US/CN=iPhone Developer: Chris Sidi (7RZ3N927YF)\"\n // Extract the common name.\n const matches = value.match(/\\/CN=.*?(?=\\/[A-Za-z]+=|$)/);\n if (matches && matches[0]) {\n commonName = matches[0].trim().replace(\"/CN=\", \"\");\n }\n }\n else if (key === 'notBefore') {\n // Example value: \"Nov 13 03:37:42 2018 GMT\"\n notBefore = new Date(value);\n }\n else if (key === 'notAfter') {\n notAfter = new Date(value);\n }\n }\n }\n // Concat all of stdout to avoid shearing. This can be updated to `openssl1.on('stdline', onLine)` once stdline mocking is available.\n let output = '';\n openssl1.on('stdout', (data) => {\n output = output + data.toString();\n });\n try {\n yield openssl1.exec();\n // process the collected stdout.\n let line;\n for (line of output.split('\\n')) {\n onLine(line);\n }\n }\n catch (err) {\n if (!p12Pwd) {\n tl.warning(tl.loc('NoP12PwdWarning'));\n }\n throw err;\n }\n tl.debug(`P12 fingerprint: ${fingerprint}`);\n tl.debug(`P12 common name (CN): ${commonName}`);\n tl.debug(`NotBefore: ${notBefore}`);\n tl.debug(`NotAfter: ${notAfter}`);\n return { fingerprint, commonName, notBefore, notAfter };\n });\n}",
"encodeTBS()\n\t{\n\t\t//region Create array for output sequence\n\t\tconst outputArray = [];\n\t\t\n\t\tif((\"version\" in this) && (this.version !== Certificate.defaultValues(\"version\")))\n\t\t{\n\t\t\toutputArray.push(new asn1js.Constructed({\n\t\t\t\toptional: true,\n\t\t\t\tidBlock: {\n\t\t\t\t\ttagClass: 3, // CONTEXT-SPECIFIC\n\t\t\t\t\ttagNumber: 0 // [0]\n\t\t\t\t},\n\t\t\t\tvalue: [\n\t\t\t\t\tnew asn1js.Integer({ value: this.version }) // EXPLICIT integer value\n\t\t\t\t]\n\t\t\t}));\n\t\t}\n\t\t\n\t\toutputArray.push(this.serialNumber);\n\t\toutputArray.push(this.signature.toSchema());\n\t\toutputArray.push(this.issuer.toSchema());\n\t\t\n\t\toutputArray.push(new asn1js.Sequence({\n\t\t\tvalue: [\n\t\t\t\tthis.notBefore.toSchema(),\n\t\t\t\tthis.notAfter.toSchema()\n\t\t\t]\n\t\t}));\n\t\t\n\t\toutputArray.push(this.subject.toSchema());\n\t\toutputArray.push(this.subjectPublicKeyInfo.toSchema());\n\t\t\n\t\tif(\"issuerUniqueID\" in this)\n\t\t{\n\t\t\toutputArray.push(new asn1js.Primitive({\n\t\t\t\toptional: true,\n\t\t\t\tidBlock: {\n\t\t\t\t\ttagClass: 3, // CONTEXT-SPECIFIC\n\t\t\t\t\ttagNumber: 1 // [1]\n\t\t\t\t},\n\t\t\t\tvalueHex: this.issuerUniqueID\n\t\t\t}));\n\t\t}\n\t\tif(\"subjectUniqueID\" in this)\n\t\t{\n\t\t\toutputArray.push(new asn1js.Primitive({\n\t\t\t\toptional: true,\n\t\t\t\tidBlock: {\n\t\t\t\t\ttagClass: 3, // CONTEXT-SPECIFIC\n\t\t\t\t\ttagNumber: 2 // [2]\n\t\t\t\t},\n\t\t\t\tvalueHex: this.subjectUniqueID\n\t\t\t}));\n\t\t}\n\t\t\n\t\tif(\"extensions\" in this)\n\t\t{\n\t\t\toutputArray.push(new asn1js.Constructed({\n\t\t\t\toptional: true,\n\t\t\t\tidBlock: {\n\t\t\t\t\ttagClass: 3, // CONTEXT-SPECIFIC\n\t\t\t\t\ttagNumber: 3 // [3]\n\t\t\t\t},\n\t\t\t\tvalue: [new asn1js.Sequence({\n\t\t\t\t\tvalue: Array.from(this.extensions, element => element.toSchema())\n\t\t\t\t})]\n\t\t\t}));\n\t\t}\n\t\t//endregion\n\t\t\n\t\t//region Create and return output sequence\n\t\treturn (new asn1js.Sequence({\n\t\t\tvalue: outputArray\n\t\t}));\n\t\t//endregion\n\t}",
"function _rsapem_publicKeyToX509HexString(rsaKey) {\n var encodedIdentifier = \"06092A864886F70D010101\";\n var encodedNull = \"0500\";\n var headerSequence = \"300D\" + encodedIdentifier + encodedNull;\n\n var keys = _rsapem_derEncodeNumber(rsaKey.n);\n keys += _rsapem_derEncodeNumber(rsaKey.e);\n\n var keySequence = \"0030\" + _rsapem_encodeLength(keys.length / 2) + keys;\n var bitstring = \"03\" + _rsapem_encodeLength(keySequence.length / 2) + keySequence;\n\n var mainSequence = headerSequence + bitstring;\n\n return \"30\" + _rsapem_encodeLength(mainSequence.length / 2) + mainSequence;\n}",
"function sec1EncodePoint(P) {\n const pointBits = P.toBits();\n const xyBytes = sjcl.codec.bytes.fromBits(pointBits);\n return [0x04].concat(xyBytes);\n}",
"function issueKeyPair(accessPointId) {\n\tconst keys = keypair(),\n \t publicKey = forge.pki.publicKeyFromPem(keys.public)\n\n \tkeys.public_ssh = forge.ssh.publicKeyToOpenSSH(publicKey, accessPointId)\n \t\n \treturn keys;\n}",
"function genKeys(cb){\n // gen private\n cp.exec('openssl genrsa 368', function(err, priv, stderr) {\n // tmp file\n var randomfn = './' + Math.random().toString(36).substring(7);\n fs.writeFileSync(randomfn, priv);\n // gen public\n cp.exec('openssl rsa -in '+randomfn+' -pubout', function(err, pub, stderr) {\n // delete tmp file\n fs.unlinkSync(randomfn);\n // callback\n cb(JSON.stringify({public: pub, private: priv}, null, 4));\n });\n\n });\n}",
"get encryptedPrivateKey() {\n return this.getStringAttribute('encrypted_private_key');\n }",
"function _getPrivateKey(params) {\n var privateKeyString = params.privateKeyString;\n var pem;\n\n if (params.privateKeyPath) {\n pem = fs.readFileSync(params.privateKeyPath);\n privateKeyString = pem.toString('ascii');\n }\n\n return privateKeyString;\n}",
"function generateKeyFiles() {\n const keyPair = crypto.generateKeyPairSync('rsa', {\n modulusLength: 2048,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem',\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem',\n cipher: 'aes-256-cbc',\n passphrase: 'pass',\n },\n });\n\n // Creating private key file\n fs.writeFileSync('private_key', keyPair.privateKey);\n}",
"async sign(privateKey, publicKey) {\n const signer = new xmldsigjs.SignedXml();\n\n // https://nodejs.org/api/crypto.html#crypto_crypto_generatekeypair_type_options_callback\n // see https://www.w3.org/TR/xmldsig-core/#sec-KeyValue\n // const privateKey = undefined;\n // const publicKey = undefined;\n\n const rawXml = await this.object.manifest.getXml();\n const xmlData = xmldsigjs.Parse(rawXml);\n const algorithm = { name: \"RSASSA-PKCS1-v1_5\" };\n const options = {\n id: this.id, // id of signature\n keyValue: publicKey,\n references: [\n {\n id: \"ref_id\", // ref id,\n uri: `#${this.object.manifest.id}`, // ref uri\n hash: \"SHA-256\", // hash algo to use\n transforms: [\"c14n\"] // array of transforms to use\n }] };\n\n\n await signer.Sign(algorithm, privateKey, xmlData, options);\n\n // TODO find better allternative to this is hacky way to interoperate between xml2js and xmlsigjs's own xml lib.\n const xmlsigjsXml = signer.toString();\n const reparsedXmlData = await (0, _xml.parseXml)(xmlsigjsXml);\n\n const signatureValueData = reparsedXmlData['ds:signature']['ds:signaturevalue'];\n const keyInfoData = reparsedXmlData['ds:signature']['ds:keyinfo'];\n\n this.signatureValue = await this.parseXmlObj({ SignatureValue: signatureValueData });\n this.keyInfo = await this.parseXmlObj({ KeyInfo: keyInfoData });\n\n console.log(\"Sign result\", this.getXml(true));\n }",
"generatePrivateKey() {\n // Generates 64 hexadecimal values then concatenates all 64 values\n let r = [];\n for (let i = 0; i < 64; i++) {\n r.push(this.random.integer(0, 15).toString(16));\n }\n return r.join('');\n }",
"function pubKey2pubKeyHash(k){ return bytes2hex(Bitcoin.Util.sha256ripe160(hex2bytes(k))); }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get catecaches by categoryId | function getCateCacheByCategory() {
return new Promise((resolve, reject) => {
CateCache.findOne({ 'key': _categoryId }).exec((err, data) => {
if (err) return reject(err);
if (!data) return reject(err);
resolve(data.value);
})
});
} | [
"static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('category', 'get', kparams);\n\t}",
"function findByKeywordAndCategory() {\n getCateCacheByCategory()\n .then(catecaches => {\n // Check pagination\n _findQuery = _pageNumber === undefined ? Dictionary.find({ 'keyword': { $regex: new RegExp(_keyword, \"i\") }, 'categoryid': { $in: catecaches } }).sort('keyword').limit(_pageSize)\n : Dictionary.find({ 'keyword': { $regex: new RegExp(_keyword, \"i\") }, 'categoryid': { $in: catecaches } }).sort('keyword').skip((_pageNumber - 1) * _pageSize).limit(_pageSize);\n var countQuery = Dictionary.count({ 'keyword': { $regex: new RegExp(_keyword, \"i\") }, 'categoryid': { $in: catecaches } });\n\n // Execute the queries\n executeCountQuery(countQuery)\n .then(totalRecord => {\n executeFindQuery(totalRecord);\n })\n .catch(err => {\n logger.error(\"Error at function: DictionaryController.findAll->findByKeywordAndCategory\", err);\n return res.send({ code: 400, message: \"Data not found!\" });\n })\n })\n .catch(err => {\n logger.error(\"Error at function: DictionaryController.findAll->findByKeywordAndCategory\", err);\n return res.send({ code: 400, message: \"Data not found!\" });\n })\n }",
"getSingleCategory(categoryId) {\n return this.webRequestService.get(\"categories/\".concat(categoryId));\n }",
"function expensesByCategories(ds, categories) {\n // Liste des depenses (dataSource)\n var dsExpensesInterval = ds;\n // Liste des categories (array)\n var categoryList = categories;\n var result = [];\n categoryList.forEach(function (category) {\n var ds = new kendo.data.DataSource({\n data: dsExpensesInterval.data(),\n filter: {\n logic: 'and',\n filters: [{\n field: 'ExpenseCategory.Id',\n operator: 'eq',\n value: category\n }]\n }\n });\n var view;\n ds.fetch(function () {\n view = this.view();\n });\n var resultCat = view;\n resultCat = resultCat.toJSON();\n result.push.apply(result, resultCat);\n });\n var dsResult = new kendo.data.DataSource({\n data: result\n });\n dsResult.read();\n return dsResult;\n}",
"static index(id, shouldUpdate = true){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.shouldUpdate = shouldUpdate;\n\t\treturn new kaltura.RequestBuilder('category', 'index', kparams);\n\t}",
"function getMealFromCache(meal_id, connection, callback=()=>{})\n {\n connection.query(`SELECT * FROM MealEntry m WHERE m.mid=${meal_id};`, function(err, result, fields){\n if (err) throw err;\n callback(result);\n });\n }",
"static showCachedReviews(id) {\n \n return RestaurantDBHelper.openDatabase().then(function(db) {\n if (!db ) return;\n \n var index = db.transaction('reviews')\n .objectStore('reviews');\n return index.getAll().then((allReviews) => {\n // Filter reviews to have only given id\n const reviews = allReviews.filter(r => r.restaurant_id == id);\n return reviews;\n \n });\n });\n }",
"getRecipes(categoryId) {\n return this.webRequestService.get(\"categories/\".concat(categoryId, \"/recipes\"));\n }",
"function getListOfContentsOfAllcategories(categories) {\r\n $scope.dlListOfContentsOfAllcategories = [];\r\n var sortField = 'VisitCount';\r\n var sortDirAsc = false;\r\n\r\n if (categories instanceof Array) {\r\n categories.filter(function(category) {\r\n var dlCategoryContent = {};\r\n dlCategoryContent.isLoading = true;\r\n dlCategoryContent = angular.extend(Utils.getListConfigOf('pubContent'), dlCategoryContent);\r\n $scope.dlListOfContentsOfAllcategories.push(dlCategoryContent);\r\n\r\n pubcontentService.getContentsByCategoryName(category.name, sortField, sortDirAsc, dlCategoryContent.pagingPageSize).then(function(response) {\r\n if (response && response.data) {\r\n var contents = new EntityMapper(Content).toEntities(response.data.Contents);\r\n var category = new Category(response.data.Category);\r\n var totalCount = response.data.TotalCount;\r\n\r\n dlCategoryContent.items = contents;\r\n dlCategoryContent.headerTitle = category && category.title || '';\r\n dlCategoryContent.headerRightLabel = totalCount + '+ articles';\r\n dlCategoryContent.pagingTotalItems = totalCount;\r\n dlCategoryContent.footerLinkUrl = [dlCategoryContent.footerLinkUrl, category && category.name].join('/');\r\n dlCategoryContent.tags = pubcontentService.getUniqueTagsOfContents(contents);\r\n } else {\r\n resetContentList(dlCategoryContent);\r\n }\r\n dlCategoryContent.isLoading = false;\r\n }, function() {\r\n resetContentList(dlCategoryContent);\r\n });\r\n });\r\n }\r\n\r\n function resetContentList(dlCategoryContent) {\r\n dlCategoryContent.items = new EntityMapper(Content).toEntities([]);\r\n dlCategoryContent.headerRightLabel = '0 articles';\r\n dlCategoryContent.pagingTotalItems = 0;\r\n dlCategoryContent.tags = [];\r\n dlCategoryContent.isLoading = false;\r\n }\r\n }",
"function cachedFetch(cacheKeySelector, fetchFn) {\n return this.scan((cache, item) => {\n const cacheKey = cacheKeySelector(item);\n if (cache.has(cacheKey)) {\n return cache;\n }\n\n return cache.set(cacheKey, fetchFn(cacheKey));\n }, new Map())\n .flatMap(cache => Promise.all(\n cache\n .entrySeq()\n // dematerialize map\n .map(([key, promise]) => promise.then(value => [key, value]))\n )\n // and materialize again\n .then(reduce((acc, [key, value]) => acc.set(key, value), new Map()))\n )\n .map(cache => cache.filter(complement(isNull)));\n}",
"static index(entryId, categoryId, shouldUpdate = true){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\tkparams.categoryId = categoryId;\n\t\tkparams.shouldUpdate = shouldUpdate;\n\t\treturn new kaltura.RequestBuilder('categoryentry', 'index', kparams);\n\t}",
"function fetchcategories() {\n API.getCategories().then(res => {\n const result = res.data.categories;\n console.log(\"RESULT: \", result);\n // alert(result[1].name);\n if (res.data.success == false) {\n } else {\n\n setFetchedCategories(res.data.categories);\n }\n }).catch(error => console.log(\"error\", error));\n }//end of fetch categories from backend",
"getCategoryMap() {\n var result = new utils.Map();\n var user = this.getAccount();\n var onlyAttentionSet = this.options_.onlyAttentionSet;\n this.data_.forEach(function(cl) {\n var attention\n if (onlyAttentionSet !== config.OPTION_DISABLED) {\n attention = cl.getCategoryFromAttentionSet(user);\n } else {\n attention = cl.getCategory(user);\n }\n if (!result.has(attention)) {\n result.put(attention, []);\n }\n var cls = result.get(attention);\n if (!cls.includes(cl)) {\n cls.push(cl);\n }\n });\n return result;\n }",
"function get_channel(id){\n return guild.channels.cache.get(id);\n}",
"function getMatchingCategories(categoryId, categories){\n console.log(matchingCategories);\n angular.forEach(categories, function(category) {\n if(category.parentCategory === categoryId)\n {\n this.push(category);\n if(category.parentCategory != 0) {\n getMatchingCategories(category.categoryId, categories);\n }\n }\n }, matchingCategories);\n }",
"function byCache(key, fn) {\n\n\t// the timestamp key\n\tvar timestamp_key = key + '.timestamp';\n\n\t// get by the key\n\tchrome.storage.local.get([ key, timestamp_key ], function(result) {\n\n\t\t// did we find anything\n\t\tif(result) {\n\n\t\t\t// current time\n\t\t\tvar current_timestamp = new Date().getTime();\n\n\t\t\t// check the timestamp\n\t\t\tif( result[timestamp_key] &&\n\t\t\t\t( current_timestamp - result[timestamp_key] ) <= 1000 * 60 * CONSTANTS.CACHE ) {\n\n\t\t\t\t// output our item ..\n\t\t\t\tfn( JSON.parse(result[key]) )\n\n\t\t\t} else {\n\n\t\t\t\t// remove it\n\t\t\t\tchrome.storage.local.remove([ key, timestamp_key ], function() {\n\n\t\t\t\t\t// signal done and that nothing was found from cache ...\n\t\t\t\t\tfn(null);\n\n\t\t\t\t});\n\n\t\t\t}\n\n\t\t} else fn(null);\n\n\t});\n\n}",
"function loadOtherCredits(user_id, func) {\n let xhttp = new XMLHttpRequest();\n\n xhttp.onreadystatechange = function() {\n if (this.readyState === 4 && this.status === 200) { // If ok set up day field\n let credits_raw;\n try {\n credits_raw = JSON.parse(this.responseText);\n } catch (e) {\n console.log('error:', e);\n credits_raw = [];\n }\n\n let credits = groupByUnique(credits_raw, 'id');\n\n cache['credits'] = credits;\n\n func();\n }\n };\n\n xhttp.open(\"GET\", \"/credits?id=\" + user_id, true);\n xhttp.withCredentials = true; // To receive cookie\n xhttp.send();\n}",
"function fetchFromCache(neLat, neLng, swLat, swLng, type, season) {\n\tvar neLat_floor = Math.floor(neLat);\n\tvar neLng_floor = Math.floor(neLng);\n\tvar swLat_floor = Math.floor(swLat);\n\tvar swLng_floor = Math.floor(swLng);\n\tvar new_data = [];\n\t\n\tif (type == \"WIND\") {\n\t\tconsole.log(\"ACCESSING WIND CACHE\");\n\t\tfor (var lat = swLat_floor; lat <= neLat_floor; lat++) {\n\t\t\tfor (var lng = swLng_floor; lng <= neLng_floor; lng++) {\n\t\t\t\tnew_data.push(wind_cache[lat][lng][parseSeason(season)]);\n\t\t\t}\n\t\t}\n\t} else if (type == \"SOLAR\") {\n\t\tconsole.log(\"ACCESSING SOLAR CACHE\");\n\t\tnew_data = solar_cache[parseSeason(season)];\n\t} else if (type == \"HYDRO\") {\n\t\tconsole.log(\"ACCESSING HYDRO CACHE\");\n\t\tfor (var lat = swLat_floor; lat <= neLat_floor; lat++) {\n\t\t\tfor (var lng = swLng_floor; lng <= neLng_floor; lng++) {\n\t\t\t\tnew_data.push(hydro_cache[lat][lng]);\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn new_data;\n}",
"function setPostsByCategories(){\n postsData.map((post) =>{\n console.log(post);\n let arr = [];\n if(postsByCategories.has(post.categories[0])){\n arr = postsByCategories.get(post.categories[0]); \n }\n\n arr.push(post);\n postsByCategories.set(post.categories[0], arr); \n });\n\n //Save data to local storage with today's time stamp, so in next time we won't use fetch to bring data\n localStorage.setItem(\"lastLoadDataCompletedTime\", new Date().getTime().toString())\n localStorage.setItem(\"postsByCategories\",JSON.stringify(mapToObj(postsByCategories)));\n localStorage.setItem(\"fetchNumber\",fetchNumber);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
endregion region sendRenegotiationOffer Composes an SDP offer from the OFFER_READY media plugin event data and sends it to the server to renegotiate the AV session. | function sendRenegotiationOffer(sdp) {
var url = asSession.relatedHref('renegotiations');
assert(url, '"renegotiations" link is missing');
// cache operation id
var operationId = guid();
outAsRenegoOpIds[operationId] = "";
return ucwa.send('POST', url, {
headers: { 'Content-Type': 'application/sdp' },
query: { operationId: operationId },
data: sdp,
nobatch: true
});
} | [
"function sendOffer(offers) {\n assert(offers.length > 0);\n // construct content that contains all offers given by the media plugin\n function createOfferOptions(context) {\n var boundary = '9BCE36B8-2C70-44CA-AAA6-D3D332ADBD3F', mediaOffer, options = { nobatch: true };\n if (isConferencing()) {\n if (escalateAudioVideoUri) {\n mediaOffer = Internal.multipartSDP(offers, boundary);\n options = {\n headers: {\n 'Content-Type': 'multipart/alternative;boundary=' + boundary +\n ';type=\"application/sdp\"',\n 'Content-Length': '' + mediaOffer.length\n },\n query: {\n operationId: operationId,\n sessionContext: sessionContext\n },\n data: mediaOffer,\n nobatch: true\n };\n }\n else {\n options.data = Internal.multipartJsonAndSDP({\n offers: offers,\n boundary: boundary,\n operationId: operationId,\n sessionContext: sessionContext,\n threadId: threadId,\n context: context\n });\n options.headers = {\n 'Content-Type': 'multipart/related;boundary=' + boundary +\n ';type=\"application/vnd.microsoft.com.ucwa+json\"'\n };\n }\n }\n else {\n // P2P mode\n options.data = Internal.multipartJsonAndSDP({\n to: remoteUri,\n offers: offers,\n boundary: boundary,\n operationId: operationId,\n sessionContext: sessionContext,\n threadId: threadId,\n context: context\n });\n options.headers = {\n 'Content-Type': 'multipart/related;boundary=' + boundary +\n ';type=\"application/vnd.microsoft.com.ucwa+json\"'\n };\n }\n if (context)\n extend(options.headers, { 'X-MS-RequiresMinResourceVersion': 2 });\n return options;\n }\n return async(getStartAudioVideoLink).call(null).then(function (link) {\n var options = createOfferOptions(link.revision >= 2 && invitationContext), dfdPost, dfdCompleted;\n dfdPost = ucwa.send('POST', link.href, options).then(function (r) {\n // POST to startAudioVideo/addAudioVideo returns an empty response with an AV invitation\n // URI in the Location header. The UCWA stack constructs and returns an empty resource\n // with href set to that URI.\n if (!rAVInvitation)\n rAVInvitation = r;\n });\n // wait for the \"audioVideoInvitation completed\" event that corresponds to the given conversation\n dfdCompleted = ucwa.wait({\n type: 'completed',\n target: { rel: 'audioVideoInvitation' },\n resource: { direction: 'Outgoing', threadId: threadId, operationId: operationId, sessionContext: sessionContext }\n }).then(function (event) {\n if (event.status == 'Failure') {\n // if remote SIP uri is invalid we won't receive \"audioVideoInvitation started\" event,\n // thus we won't have a full rAVInvitation resource cached. It will be either undefined or\n // just an empty resource with an href returned by a response to startAudioVideo POST (if\n // that response arrived before this event). So we cache the invitation resource here,\n // since it may be used by other event handlers.\n rAVInvitation = event.resource;\n // Technically we may need to complete the negotiation if it was started (i.e. if the call\n // reached the remote party and was declined).\n completeNegotiation(event.status, event.reason);\n throw Internal.EInvitationFailed(event.reason);\n }\n completeNegotiation(event.status, event.reason);\n });\n return Task.waitAll([dfdPost, dfdCompleted]);\n });\n }",
"receiveOffer(pair, desc) {\n var e, offer, sdp;\n try {\n offer = JSON.parse(desc);\n dbg('Received:\\n\\n' + offer.sdp + '\\n');\n sdp = new RTCSessionDescription(offer);\n if (pair.receiveWebRTCOffer(sdp)) {\n this.sendAnswer(pair);\n return true;\n } else {\n return false;\n }\n } catch (error) {\n e = error;\n log('ERROR: Unable to receive Offer: ' + e);\n return false;\n }\n }",
"function handleofferFromPC1(){\n\n var x = document.getElementById('pc1LocalOffer').value;\n\n var offerDesc = new RTCSessionDescription(JSON.parse(x))\n\n pc2.setRemoteDescription(offerDesc)\n pc2.createAnswer(function (answerDesc) {\n \n console.log('Created local answer: ', answerDesc)\n\n pc2.setLocalDescription(answerDesc)\n },\n function () { console.warn(\"Couldn't create offer\") },\n sdpConstraints)\n\n}",
"function ViewClient(recipient) {\n let pc = new RTCPeerConnection({'iceServers': [{'urls': 'stun:stun.l.google.com:19302'}]});\n\n // Local ICE candidate\n pc.onicecandidate = function(event) {\n if (event.candidate) {\n camera_sent(recipient, ice_candidate_key(event.candidate));\n send_message(recipient,\n {type: 'ice-candidate',\n from: 'replay-camera',\n candidate: event.candidate});\n }\n };\n\n let self = this;\n pc.onnegotiationneeded = function(event) {\n console.log('onnegotiationneeded fires');\n self.convey_offer();\n };\n\n this.connection = pc;\n \n this.setstream = function(stream) {\n let senders = pc.getSenders();\n for (var k = 0; k < senders.length; ++k) {\n pc.removeTrack(senders[k]);\n }\n stream.getTracks().forEach(function(track) {\n console.log(' adding track');\n pc.addTrack(track, stream);\n });\n };\n\n this.on_message = function(msg) {\n console.log('on_message ' + msg.type + ' from ' + msg.from);\n if (msg.type == 'answer') {\n this.on_answer(msg);\n } else if (msg.type == 'ice-candidate') {\n this.on_ice_candidate(msg);\n } else {\n console.error('Unrecognized message ' + msg);\n console.trace();\n }\n };\n this.on_answer = function(msg) {\n camera_received(recipient, 'answer');\n pc.setRemoteDescription(new RTCSessionDescription(msg.sdp));\n };\n this.on_ice_candidate = function(msg) { // Remote ICE candidate signaled\n let candidate = new RTCIceCandidate(msg.candidate);\n camera_received(recipient, ice_candidate_key(candidate));\n pc.addIceCandidate(candidate);\n };\n\n let ideal = {width: 0, height: 0};\n this.on_solicitation = function(msg) {\n if (msg.hasOwnProperty('ideal')) {\n ideal = msg.ideal;\n }\n this.convey_offer();\n };\n this.ideal = function() { return ideal; }\n \n this.convey_offer = function() {\n pc.createOffer()\n .then(function(offer) {\n return pc.setLocalDescription(offer);\n })\n .then(function() {\n camera_sent(recipient, 'offer');\n send_message(recipient,\n {type: 'offer',\n from: 'replay-camera',\n sdp: pc.localDescription});\n });\n };\n}",
"function sendAck(receivedFrame, ackType) {\n\n // Get the frame SN\n var sn = sequenceNo(receivedFrame);\n\n // Create RR ACK frame\n var ackFrameType = \"\";\n if (ackType == \"RR\")\n ackFrameType = \"ackRRFrame\"\n else\n ackFrameType = \"ackREJFrame\";\n\n var ack = createFrame(ackFrameType, ackType + \" \" + rcvrExptedSn, sn, rcvrExptedSn);\n\n //Receiver transmits RR Ack frame into medium\n transmitFrame(ack, rfSlots[0].position().top, rfSlots[sn].position().left);\n\n // Start propagation, medium calls sender on delivery\n propagateFrame(ack, senderAddress(), function() {\n handleAck($(this));\n });\n\n}",
"negotiate() {\n\t\t// Write the hello message\n\t\tthis.write('hello', {\n\t\t\tid: this.networkId,\n\t\t\tversion: CURRENT_VERSION\n\t\t});\n\n\t\t// Wait a few seconds for the hello from the other side\n\t\tif(this.helloTimeout) {\n\t\t\tclearTimeout(this.helloTimeout);\n\t\t}\n\t\tthis.helloTimeout = setTimeout(\n\t\t\t() => this.requestDisconnect(new Error('Time out during negotiation')),\n\t\t\t5000\n\t\t);\n\t}",
"sendMediaStream(self, peer, media, friendtkn, isAnswer, call) {\n if (isAnswer) {\n friendtkn = call.peer;\n console.log('Connected to ' + friendtkn);\n console.log(call.metadata);\n this.createNotif('Member joined', `${call.metadata} joined the call`, 'info');\n }\n var tracks = media.getTracks();\n var track = tracks[0];\n var thiscall = call;\n\n // triggered when our stream being sent ends.\n track.addEventListener('ended', () => {\n console.log('My stream ended. Please show this');\n thiscall.close();\n self.deleteVideoElement(thiscall.peer);\n // self.sendRequestToEndCall();\n // self.startConnection(friendtkn, peer, self);\n });\n\n // Can't figure out the exact conditions which cause this event to be handled,\n // but this handler maybe useful, if we are enabling and disabling streams.\n track.addEventListener('mute', () => {\n console.log('My stream muted. Please show this');\n });\n\n if (isAnswer) {\n thiscall.answer(media);\n } else {\n console.log(media.getTracks());\n thiscall = peer.call(friendtkn, media, { metadata: this.state.myUsername });\n }\n self.addHandlersToCall(\n self,\n thiscall,\n friendtkn,\n thiscall.metadata,\n peer,\n isAnswer\n );\n //console.log('exit4d');\n }",
"function writeRejectedMediaSection(transceiver) {\n var sdp = '';\n if (transceiver.kind === 'application') {\n if (transceiver.protocol === 'DTLS/SCTP') { // legacy fmt\n sdp += 'm=application 0 DTLS/SCTP 5000\\r\\n';\n } else {\n sdp += 'm=application 0 ' + transceiver.protocol +\n ' webrtc-datachannel\\r\\n';\n }\n } else if (transceiver.kind === 'audio') {\n sdp += 'm=audio 0 UDP/TLS/RTP/SAVPF 0\\r\\n' +\n 'a=rtpmap:0 PCMU/8000\\r\\n';\n } else if (transceiver.kind === 'video') {\n sdp += 'm=video 0 UDP/TLS/RTP/SAVPF 120\\r\\n' +\n 'a=rtpmap:120 VP8/90000\\r\\n';\n }\n sdp += 'c=IN IP4 0.0.0.0\\r\\n' +\n 'a=inactive\\r\\n' +\n 'a=mid:' + transceiver.mid + '\\r\\n';\n return sdp;\n}",
"function makeCall() {\n callButton.disabled = true;\n hangupButton.disabled = false;\n var servers = null;\n localConnection = new RTCPeerConnection(servers);\n localConnection.onicecandidate = localCandidate;\n \n remoteConnection = new RTCPeerConnection(servers);\n remoteConnection.onicecandidate = remoteCandidate;\n \n remoteConnection.onaddstream = remoteStream;\n \n localConnection.addStream(localStream);\n \n localConnection.createOffer(localDescription, signalError);\n}",
"function writeMediaSection(transceiver, caps, type, stream, dtlsRole) {\n var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps);\n\n // Map ICE parameters (ufrag, pwd) to SDP.\n sdp += SDPUtils.writeIceParameters(\n transceiver.iceGatherer.getLocalParameters());\n\n // Map DTLS parameters to SDP.\n sdp += SDPUtils.writeDtlsParameters(\n transceiver.dtlsTransport.getLocalParameters(),\n type === 'offer' ? 'actpass' : dtlsRole);\n\n sdp += 'a=mid:' + transceiver.mid + '\\r\\n';\n\n if (transceiver.rtpSender && transceiver.rtpReceiver) {\n sdp += 'a=sendrecv\\r\\n';\n } else if (transceiver.rtpSender) {\n sdp += 'a=sendonly\\r\\n';\n } else if (transceiver.rtpReceiver) {\n sdp += 'a=recvonly\\r\\n';\n } else {\n sdp += 'a=inactive\\r\\n';\n }\n\n if (transceiver.rtpSender) {\n var trackId = transceiver.rtpSender._initialTrackId ||\n transceiver.rtpSender.track.id;\n transceiver.rtpSender._initialTrackId = trackId;\n // spec.\n var msid = 'msid:' + (stream ? stream.id : '-') + ' ' +\n trackId + '\\r\\n';\n sdp += 'a=' + msid;\n // for Chrome. Legacy should no longer be required.\n sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +\n ' ' + msid;\n\n // RTX\n if (transceiver.sendEncodingParameters[0].rtx) {\n sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +\n ' ' + msid;\n sdp += 'a=ssrc-group:FID ' +\n transceiver.sendEncodingParameters[0].ssrc + ' ' +\n transceiver.sendEncodingParameters[0].rtx.ssrc +\n '\\r\\n';\n }\n }\n // FIXME: this should be written by writeRtpDescription.\n sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +\n ' cname:' + SDPUtils.localCName + '\\r\\n';\n if (transceiver.rtpSender && transceiver.sendEncodingParameters[0].rtx) {\n sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +\n ' cname:' + SDPUtils.localCName + '\\r\\n';\n }\n return sdp;\n}",
"function pursueOffer(offerId) {\n\t// show the offer as selected\n\tdocument.getElementById(offerId).className = \"selectedOfferDiv\";\n\t\n\t//disable persuing the offer again \n\tdocument.getElementById(offerId).onclick = \"\";\n\t\n\tif (window.XMLHttpRequest)\n\t\t\t{// IE7+, Firefox, Chrome, Opera, Safari\n\t\t\t pursueOffer_xmlhttp = new XMLHttpRequest();\n\t\t\t}\n\t\t\telse\n\t\t\t{// IE6, IE5\n\t\t\t pursueOffer_xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n\t\t\t}\n\t\t\t \n\t\t\tpursueOffer_xmlhttp.onreadystatechange=function()\n\t\t\t{\n\t\t\t\tif (pursueOffer_xmlhttp.readyState==4 && pursueOffer_xmlhttp.status==200)\n\t\t\t\t{\n\t\t\t\t\t// check if an error message has been returned \n\t\t\t\t\tif(pursueOffer_xmlhttp.responseText != \"\")\n\t\t\t\t\t{\n\t\t\t\t\t\tshowError(\"A Small Problem...\", pursueOffer_xmlhttp.responseText);\n\t\t\t\t\t\tgetMatchingExchanges();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tpursueOffer_xmlhttp.open(\"GET\", \"./php/pursueOffer.php?netId=\" + document.getElementById(\"netId\").value + \"&offerId=\" + offerId, true);\n\t\t\tpursueOffer_xmlhttp.send();\n}",
"function setFinalAnswer(resource, remoteEndpoint) {\n var mediaAnswer = resource.relatedHref('mediaAnswer'), sdp = DataUri(mediaAnswer).data;\n log('Final answer from the remote party:\\n' + sdp);\n appSharing.setFinalAnswer(remoteEndpoint, sdp);\n }",
"function getMediaOffers() {\n /* The \"mediaOffer\" link may have the following form:\n *\n * data:multipart/alternative;charset=utf-8;boundary=e47d80f2,\n * --e47d80f2\n * Content-Type:+application/sdp\n * Content-ID:+<9544aa8a8ac9dfe08fad74893bd1095e@contoso.com>\n * Content-Disposition:+session;+handling=optional;+proxy-fallback\n *\n * v=0\n * o=-+0+0+IN+IP4+127.0.0.1\n * s=session\n * ...\n *\n * --e47d80f2\n * Content-Type:+application/sdp\n * Content-ID:+<cdfd6188fd977372c577873b03dd580d@contoso.com>\n * Content-Disposition:+session;+handling=optional\n *\n * v=0\n * o=-+0+1+IN+IP4+127.0.0.1\n * s=session\n * c=IN+IP4+127.0.0.1\n * ...\n *\n * --e47d80f2\n */\n var href, dataUri, responses;\n href = resource.relatedHref('mediaOffer');\n if (!href)\n return [];\n dataUri = DataUri(href);\n try {\n responses = parseMultipartRelatedResponse({\n status: null,\n responseText: dataUri.data,\n headers: 'Content-Type:multipart/related;boundary=' + dataUri.attributes.boundary\n });\n return map(responses, function (response) {\n var headers = HttpHeaders(response.headers);\n return {\n sdp: response.responseText,\n id: headers.get('Content-ID')\n };\n });\n }\n catch (error) {\n // if the media offer is not a multipart/alternate-encoded\n // set of SDPs, consider it as a single SDP\n return [{\n sdp: dataUri.data,\n id: ''\n }];\n }\n }",
"sendAttendeeHandState() {\n let data = {\n handRaised: attendee.handRaised,\n session_id: attendee.session_id\n };\n callFrame.sendAppMessage(data, '*');\n }",
"extend() {\n\t\t// create this.next to the next peer\n\t\tthis.next = network.getChannel(peer_id, this.circID);\n\t\tthis.next.on(types.RELAY, this.relay_backward);\n\t\t// do a DH exchange\n\n\t}",
"function manageOffer(offer, action, them) {\n var counter = 0;\n var maxTries = 10;\n var retryInterval = 1000;\n var alreadyUpdating = false; //prevents offer.update spam\n\n var offerFunc = function() { //extra function to sort Everything\n if (counter < maxTries) { //dont retry forever\n if (offer.isGlitched() == true && !alreadyUpdating) { //if glitched\n alreadyUpdating = true; //prevents offer.update spam\n offer.update(function(err) {\n if (err) {\n alreadyUpdating = false; //prevents offer.update spam\n } else {\n accept(); //tries to accept\n }\n });\n } else {\n accept(); //tries to accept\n }\n } else {\n logInfo('Offer of ' + them.personaName + ' (' + offer.id + ') cancelled. Accepting/Declining failed.'); //limit of retries reached\n clearInterval(interval); //stops the retry interval\n }\n };\n\n var accept = function() {\n if (offer.state == TradeOfferManager.ETradeOfferState.Active) { //if the trade is active -> acceptable|declineable\n if (action == 'accept') {\n offer.accept(function(err) {\n if (err) { //accepting failed\n logError('Accepting the offer of ' + them.personaName + ' (' + offer.id + ') failed. Error: ' + err);\n counter++; //used for the limit of retries\n } else {\n logSuccess('Offer of ' + them.personaName + ' (' + offer.id + ') sucessfully accepted.');\n clearInterval(interval); //stops the retry interval because of success\n }\n });\n } else {\n offer.decline(function(err) {\n if (err) { //declining failed\n logError('Declining the offer of ' + them.personaName + ' (' + offer.id + ') failed. Error: ' + err);\n counter++; //used for the limit of retries\n } else {\n logInfo('Offer of ' + them.personaName + ' (' + offer.id + ') sucessfully declined.');\n clearInterval(interval); //stops the retry interval because of success\n }\n });\n }\n } else {\n clearInterval(interval); //stops the retry interval because its not active anymore\n }\n };\n\n offerFunc(); //instantly runs the Function\n var interval = setInterval(offerFunc, retryInterval); // & runs it in an interval\n}",
"function C101_KinbakuClub_RopeGroup_PluggedAccept() {\n\tC101_KinbakuClub_RopeGroup_PlugMood = \"Accept\";\n\tC101_KinbakuClub_RopeGroup_PlayerPlugged();\n}",
"constructor(opts) {\n super();\n (0, _defineProperty2.default)(this, \"roomId\", void 0);\n (0, _defineProperty2.default)(this, \"type\", void 0);\n (0, _defineProperty2.default)(this, \"callId\", void 0);\n (0, _defineProperty2.default)(this, \"state\", void 0);\n (0, _defineProperty2.default)(this, \"hangupParty\", void 0);\n (0, _defineProperty2.default)(this, \"hangupReason\", void 0);\n (0, _defineProperty2.default)(this, \"direction\", void 0);\n (0, _defineProperty2.default)(this, \"ourPartyId\", void 0);\n (0, _defineProperty2.default)(this, \"client\", void 0);\n (0, _defineProperty2.default)(this, \"forceTURN\", void 0);\n (0, _defineProperty2.default)(this, \"turnServers\", void 0);\n (0, _defineProperty2.default)(this, \"candidateSendQueue\", void 0);\n (0, _defineProperty2.default)(this, \"candidateSendTries\", void 0);\n (0, _defineProperty2.default)(this, \"sentEndOfCandidates\", void 0);\n (0, _defineProperty2.default)(this, \"peerConn\", void 0);\n (0, _defineProperty2.default)(this, \"localVideoElement\", void 0);\n (0, _defineProperty2.default)(this, \"remoteVideoElement\", void 0);\n (0, _defineProperty2.default)(this, \"remoteAudioElement\", void 0);\n (0, _defineProperty2.default)(this, \"screenSharingStream\", void 0);\n (0, _defineProperty2.default)(this, \"remoteStream\", void 0);\n (0, _defineProperty2.default)(this, \"localAVStream\", void 0);\n (0, _defineProperty2.default)(this, \"inviteOrAnswerSent\", void 0);\n (0, _defineProperty2.default)(this, \"waitForLocalAVStream\", void 0);\n (0, _defineProperty2.default)(this, \"config\", void 0);\n (0, _defineProperty2.default)(this, \"successor\", void 0);\n (0, _defineProperty2.default)(this, \"opponentMember\", void 0);\n (0, _defineProperty2.default)(this, \"opponentVersion\", void 0);\n (0, _defineProperty2.default)(this, \"opponentPartyId\", void 0);\n (0, _defineProperty2.default)(this, \"opponentCaps\", void 0);\n (0, _defineProperty2.default)(this, \"inviteTimeout\", void 0);\n (0, _defineProperty2.default)(this, \"remoteOnHold\", void 0);\n (0, _defineProperty2.default)(this, \"unholdingRemote\", void 0);\n (0, _defineProperty2.default)(this, \"micMuted\", void 0);\n (0, _defineProperty2.default)(this, \"vidMuted\", void 0);\n (0, _defineProperty2.default)(this, \"callStatsAtEnd\", void 0);\n (0, _defineProperty2.default)(this, \"makingOffer\", void 0);\n (0, _defineProperty2.default)(this, \"ignoreOffer\", void 0);\n (0, _defineProperty2.default)(this, \"remoteCandidateBuffer\", new Map());\n (0, _defineProperty2.default)(this, \"gotUserMediaForInvite\", async stream => {\n if (this.successor) {\n this.successor.gotUserMediaForAnswer(stream);\n return;\n }\n\n if (this.callHasEnded()) {\n this.stopAllMedia();\n return;\n }\n\n this.localAVStream = stream;\n\n _logger.logger.info(\"Got local AV stream with id \" + this.localAVStream.id);\n\n this.setState(CallState.CreateOffer);\n\n _logger.logger.debug(\"gotUserMediaForInvite -> \" + this.type);\n\n const videoEl = this.getLocalVideoElement();\n\n if (videoEl && this.type === CallType.Video) {\n videoEl.autoplay = true;\n\n if (this.screenSharingStream) {\n _logger.logger.debug(\"Setting screen sharing stream to the local video element\");\n\n videoEl.srcObject = this.screenSharingStream;\n } else {\n videoEl.srcObject = stream;\n }\n\n videoEl.muted = true;\n\n try {\n await videoEl.play();\n } catch (e) {\n _logger.logger.info(\"Failed to play local video element\", e);\n }\n } // why do we enable audio (and only audio) tracks here? -- matthew\n\n\n setTracksEnabled(stream.getAudioTracks(), true);\n\n for (const audioTrack of stream.getAudioTracks()) {\n _logger.logger.info(\"Adding audio track with id \" + audioTrack.id);\n\n this.peerConn.addTrack(audioTrack, stream);\n }\n\n for (const videoTrack of (this.screenSharingStream || stream).getVideoTracks()) {\n _logger.logger.info(\"Adding video track with id \" + videoTrack.id);\n\n this.peerConn.addTrack(videoTrack, stream);\n } // Now we wait for the negotiationneeded event\n\n });\n (0, _defineProperty2.default)(this, \"gotUserMediaForAnswer\", async stream => {\n if (this.callHasEnded()) {\n return;\n }\n\n const localVidEl = this.getLocalVideoElement();\n\n if (localVidEl && this.type === CallType.Video) {\n localVidEl.autoplay = true;\n localVidEl.srcObject = stream;\n localVidEl.muted = true;\n\n try {\n await localVidEl.play();\n } catch (e) {\n _logger.logger.info(\"Failed to play local video element\", e);\n }\n }\n\n this.localAVStream = stream;\n\n _logger.logger.info(\"Got local AV stream with id \" + this.localAVStream.id);\n\n setTracksEnabled(stream.getAudioTracks(), true);\n\n for (const track of stream.getTracks()) {\n this.peerConn.addTrack(track, stream);\n }\n\n this.setState(CallState.CreateAnswer);\n let myAnswer;\n\n try {\n myAnswer = await this.peerConn.createAnswer();\n } catch (err) {\n _logger.logger.debug(\"Failed to create answer: \", err);\n\n this.terminate(CallParty.Local, CallErrorCode.CreateAnswer, true);\n return;\n }\n\n try {\n await this.peerConn.setLocalDescription(myAnswer);\n this.setState(CallState.Connecting); // Allow a short time for initial candidates to be gathered\n\n await new Promise(resolve => {\n setTimeout(resolve, 200);\n });\n this.sendAnswer();\n } catch (err) {\n _logger.logger.debug(\"Error setting local description!\", err);\n\n this.terminate(CallParty.Local, CallErrorCode.SetLocalDescription, true);\n return;\n }\n });\n (0, _defineProperty2.default)(this, \"gotLocalIceCandidate\", event => {\n if (event.candidate) {\n _logger.logger.debug(\"Call \" + this.callId + \" got local ICE \" + event.candidate.sdpMid + \" candidate: \" + event.candidate.candidate);\n\n if (this.callHasEnded()) return; // As with the offer, note we need to make a copy of this object, not\n // pass the original: that broke in Chrome ~m43.\n\n if (event.candidate.candidate !== '' || !this.sentEndOfCandidates) {\n this.queueCandidate(event.candidate);\n if (event.candidate.candidate === '') this.sentEndOfCandidates = true;\n }\n }\n });\n (0, _defineProperty2.default)(this, \"onIceGatheringStateChange\", event => {\n _logger.logger.debug(\"ice gathering state changed to \" + this.peerConn.iceGatheringState);\n\n if (this.peerConn.iceGatheringState === 'complete' && !this.sentEndOfCandidates) {\n // If we didn't get an empty-string candidate to signal the end of candidates,\n // create one ourselves now gathering has finished.\n // We cast because the interface lists all the properties as required but we\n // only want to send 'candidate'\n // XXX: We probably want to send either sdpMid or sdpMLineIndex, as it's not strictly\n // correct to have a candidate that lacks both of these. We'd have to figure out what\n // previous candidates had been sent with and copy them.\n const c = {\n candidate: ''\n };\n this.queueCandidate(c);\n this.sentEndOfCandidates = true;\n }\n });\n (0, _defineProperty2.default)(this, \"gotLocalOffer\", async description => {\n _logger.logger.debug(\"Created offer: \", description);\n\n if (this.callHasEnded()) {\n _logger.logger.debug(\"Ignoring newly created offer on call ID \" + this.callId + \" because the call has ended\");\n\n return;\n }\n\n try {\n await this.peerConn.setLocalDescription(description);\n } catch (err) {\n _logger.logger.debug(\"Error setting local description!\", err);\n\n this.terminate(CallParty.Local, CallErrorCode.SetLocalDescription, true);\n return;\n }\n\n if (this.peerConn.iceGatheringState === 'gathering') {\n // Allow a short time for initial candidates to be gathered\n await new Promise(resolve => {\n setTimeout(resolve, 200);\n });\n }\n\n if (this.callHasEnded()) return;\n const eventType = this.state === CallState.CreateOffer ? _event.EventType.CallInvite : _event.EventType.CallNegotiate;\n const content = {\n lifetime: CALL_TIMEOUT_MS\n }; // clunky because TypeScript can't folow the types through if we use an expression as the key\n\n if (this.state === CallState.CreateOffer) {\n content.offer = this.peerConn.localDescription;\n } else {\n content.description = this.peerConn.localDescription;\n }\n\n if (this.client._supportsCallTransfer) {\n content.capabilities = {\n 'm.call.transferee': true\n };\n } // Get rid of any candidates waiting to be sent: they'll be included in the local\n // description we just got and will send in the offer.\n\n\n _logger.logger.info(`Discarding ${this.candidateSendQueue.length} candidates that will be sent in offer`);\n\n this.candidateSendQueue = [];\n\n try {\n await this.sendVoipEvent(eventType, content);\n } catch (error) {\n _logger.logger.error(\"Failed to send invite\", error);\n\n if (error.event) this.client.cancelPendingEvent(error.event);\n let code = CallErrorCode.SignallingFailed;\n let message = \"Signalling failed\";\n\n if (this.state === CallState.CreateOffer) {\n code = CallErrorCode.SendInvite;\n message = \"Failed to send invite\";\n }\n\n if (error.name == 'UnknownDeviceError') {\n code = CallErrorCode.UnknownDevices;\n message = \"Unknown devices present in the room\";\n }\n\n this.emit(CallEvent.Error, new CallError(code, message, error));\n this.terminate(CallParty.Local, code, false); // no need to carry on & send the candidate queue, but we also\n // don't want to rethrow the error\n\n return;\n }\n\n this.sendCandidateQueue();\n\n if (this.state === CallState.CreateOffer) {\n this.inviteOrAnswerSent = true;\n this.setState(CallState.InviteSent);\n this.inviteTimeout = setTimeout(() => {\n this.inviteTimeout = null;\n\n if (this.state === CallState.InviteSent) {\n this.hangup(CallErrorCode.InviteTimeout, false);\n }\n }, CALL_TIMEOUT_MS);\n }\n });\n (0, _defineProperty2.default)(this, \"getLocalOfferFailed\", err => {\n _logger.logger.error(\"Failed to get local offer\", err);\n\n this.emit(CallEvent.Error, new CallError(CallErrorCode.LocalOfferFailed, \"Failed to get local offer!\", err));\n this.terminate(CallParty.Local, CallErrorCode.LocalOfferFailed, false);\n });\n (0, _defineProperty2.default)(this, \"getUserMediaFailed\", err => {\n if (this.successor) {\n this.successor.getUserMediaFailed(err);\n return;\n }\n\n _logger.logger.warn(\"Failed to get user media - ending call\", err);\n\n this.emit(CallEvent.Error, new CallError(CallErrorCode.NoUserMedia, \"Couldn't start capturing media! Is your microphone set up and \" + \"does this app have permission?\", err));\n this.terminate(CallParty.Local, CallErrorCode.NoUserMedia, false);\n });\n (0, _defineProperty2.default)(this, \"onIceConnectionStateChanged\", () => {\n if (this.callHasEnded()) {\n return; // because ICE can still complete as we're ending the call\n }\n\n _logger.logger.debug(\"Call ID \" + this.callId + \": ICE connection state changed to: \" + this.peerConn.iceConnectionState); // ideally we'd consider the call to be connected when we get media but\n // chrome doesn't implement any of the 'onstarted' events yet\n\n\n if (this.peerConn.iceConnectionState == 'connected') {\n this.setState(CallState.Connected);\n } else if (this.peerConn.iceConnectionState == 'failed') {\n this.hangup(CallErrorCode.IceFailed, false);\n }\n });\n (0, _defineProperty2.default)(this, \"onSignallingStateChanged\", () => {\n _logger.logger.debug(\"call \" + this.callId + \": Signalling state changed to: \" + this.peerConn.signalingState);\n });\n (0, _defineProperty2.default)(this, \"onTrack\", ev => {\n if (ev.streams.length === 0) {\n _logger.logger.warn(`Streamless ${ev.track.kind} found: ignoring.`);\n\n return;\n } // If we already have a stream, check this track is from the same one\n\n\n if (this.remoteStream && ev.streams[0].id !== this.remoteStream.id) {\n _logger.logger.warn(`Ignoring new stream ID ${ev.streams[0].id}: we already have stream ID ${this.remoteStream.id}`);\n\n return;\n }\n\n if (!this.remoteStream) {\n _logger.logger.info(\"Got remote stream with id \" + ev.streams[0].id);\n } // Note that we check by ID above and always set the remote stream: Chrome appears\n // to make new stream objects when tranciever directionality is changed and the 'active'\n // status of streams change\n\n\n this.remoteStream = ev.streams[0];\n\n _logger.logger.debug(`Track id ${ev.track.id} of kind ${ev.track.kind} added`);\n\n if (ev.track.kind === 'video') {\n if (this.remoteVideoElement) {\n this.playRemoteVideo();\n }\n } else {\n if (this.remoteAudioElement) this.playRemoteAudio();\n }\n });\n (0, _defineProperty2.default)(this, \"onNegotiationNeeded\", async () => {\n _logger.logger.info(\"Negotation is needed!\");\n\n if (this.state !== CallState.CreateOffer && this.opponentVersion === 0) {\n _logger.logger.info(\"Opponent does not support renegotiation: ignoring negotiationneeded event\");\n\n return;\n }\n\n this.makingOffer = true;\n\n try {\n const myOffer = await this.peerConn.createOffer();\n await this.gotLocalOffer(myOffer);\n } catch (e) {\n this.getLocalOfferFailed(e);\n return;\n } finally {\n this.makingOffer = false;\n }\n });\n (0, _defineProperty2.default)(this, \"onHangupReceived\", msg => {\n _logger.logger.debug(\"Hangup received for call ID \" + this.callId); // party ID must match (our chosen partner hanging up the call) or be undefined (we haven't chosen\n // a partner yet but we're treating the hangup as a reject as per VoIP v0)\n\n\n if (this.partyIdMatches(msg) || this.state === CallState.Ringing) {\n // default reason is user_hangup\n this.terminate(CallParty.Remote, msg.reason || CallErrorCode.UserHangup, true);\n } else {\n _logger.logger.info(`Ignoring message from party ID ${msg.party_id}: our partner is ${this.opponentPartyId}`);\n }\n });\n (0, _defineProperty2.default)(this, \"onRejectReceived\", msg => {\n _logger.logger.debug(\"Reject received for call ID \" + this.callId); // No need to check party_id for reject because if we'd received either\n // an answer or reject, we wouldn't be in state InviteSent\n\n\n const shouldTerminate = // reject events also end the call if it's ringing: it's another of\n // our devices rejecting the call.\n [CallState.InviteSent, CallState.Ringing].includes(this.state) || // also if we're in the init state and it's an inbound call, since\n // this means we just haven't entered the ringing state yet\n this.state === CallState.Fledgling && this.direction === CallDirection.Inbound;\n\n if (shouldTerminate) {\n this.terminate(CallParty.Remote, CallErrorCode.UserHangup, true);\n } else {\n _logger.logger.debug(`Call is in state: ${this.state}: ignoring reject`);\n }\n });\n (0, _defineProperty2.default)(this, \"onAnsweredElsewhere\", msg => {\n _logger.logger.debug(\"Call ID \" + this.callId + \" answered elsewhere\");\n\n this.terminate(CallParty.Remote, CallErrorCode.AnsweredElsewhere, true);\n });\n this.roomId = opts.roomId;\n this.client = opts.client;\n this.type = null;\n this.forceTURN = opts.forceTURN;\n this.ourPartyId = this.client.deviceId; // Array of Objects with urls, username, credential keys\n\n this.turnServers = opts.turnServers || [];\n\n if (this.turnServers.length === 0 && this.client.isFallbackICEServerAllowed()) {\n this.turnServers.push({\n urls: [FALLBACK_ICE_SERVER]\n });\n }\n\n for (const server of this.turnServers) {\n utils.checkObjectHasKeys(server, [\"urls\"]);\n }\n\n this.callId = genCallID();\n this.state = CallState.Fledgling; // A queue for candidates waiting to go out.\n // We try to amalgamate candidates into a single candidate message where\n // possible\n\n this.candidateSendQueue = [];\n this.candidateSendTries = 0;\n this.sentEndOfCandidates = false;\n this.inviteOrAnswerSent = false;\n this.makingOffer = false;\n this.remoteOnHold = false;\n this.unholdingRemote = false;\n this.micMuted = false;\n this.vidMuted = false;\n }",
"function respond(message, gateway, request, response, number) {\n console.log('[' + number + '] sending ' + message.length + 'c: ' + message);\n if (gateway === 'telerivet') {\n // Telerivet requires JSON response\n var res = {\n messages: [ { content: message } ]\n };\n response.send(res);\n } else {\n // Render Twilio-style response \n var twiml = new twilio.TwimlResponse();\n twiml.message(message);\n response.type('text/xml');\n response.send(twiml.toString());\n }\n}",
"resend() {\n this.streamStatus = 'initialize';\n this.requester.addToSendList(this.data);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Walk through the MIME message structure and decrypt the body if there is something to decrypt | async decryptMimeTree(mimePart) {
EnigmailLog.DEBUG("persistentCrypto.jsm: decryptMimeTree:\n");
if (this.isBrokenByExchange(mimePart)) {
this.fixExchangeMessage(mimePart);
}
if (this.isSMIME(mimePart)) {
this.decryptSMIME(mimePart);
} else if (this.isPgpMime(mimePart)) {
this.decryptPGPMIME(mimePart);
} else if (isAttachment(mimePart)) {
this.pgpDecryptAttachment(mimePart);
} else {
this.decryptINLINE(mimePart);
}
for (let i in mimePart.subParts) {
await this.decryptMimeTree(mimePart.subParts[i]);
}
} | [
"function file_decrypt(username, message) {\n if (rtc.crypto_verified[username]) {\n hash = CryptoJS.SHA256(message).toString(CryptoJS.enc.Base64); \n \n message = RabbitCryptoJS.Rabbit.decrypt(JSON.parse(message),\n rtc.crypto_receive_symmetric_keys[username] + rtc.request_chunk_decrypt_rand[username])\n .toString(CryptoJS.enc.Utf8);\n process_binary(username, base64DecToArr(message).buffer, hash); /* send back a hash as well to send back to the original host with the next request */\n }\n }",
"function decodeMessage() {\n// new RegExp( \"(\\\\d)(\\\\d{2})(.{\" + smash._securityTokenLength + \"})(.{\" + smash._securityTokenLength + \"})(\\\\d)(\\\\d{2})(.*)\" )\n\t\tvar type=currentHash.substr(0,1);\n\t\tvar msn=currentHash.substr(1,2);\n\t\tvar nextStart = 3;\n\t\tvar tokenParent=currentHash.substr(nextStart,smash._securityTokenLength);\n\t\tnextStart += smash._securityTokenLength;\n\t\tvar tokenChild=currentHash.substr(nextStart,smash._securityTokenLength);\n\t\tnextStart += smash._securityTokenLength;\n\t\tvar ack=currentHash.substr(nextStart,1);\n\t\tnextStart += 1;\n\t\tvar ackMsn=currentHash.substr(nextStart,2);\n\t\tnextStart += 2;\n\t\t// The payload needs to stay raw since the uri decoding needs to happen on the concatenated data in case of a large message\n\t\tvar payload=currentHash.substr(nextStart);\n\t\tlog( \"In : Type: \" + type + \" msn: \" + msn + \" tokenParent: \" + tokenParent + \" tokenChild: \" + tokenChild + \" ack: \" + ack + \" msn: \" + ackMsn + \" payload: \" + payload );\n\t\tmessageIn={type: type, msn: msn, tokenParent: tokenParent, tokenChild: tokenChild, ack: ack, ackMsn: ackMsn, payload: payload};\n\t\treturn true;\n\t}",
"function decrypt(buffer, params) {\n var key = extractKey(params);\n var rs = determineRecordSize(params);\n var start = 0;\n var result = new Buffer(0);\n\n for (var i = 0; start < buffer.length; ++i) {\n var end = start + rs + TAG_LENGTH;\n if (end === buffer.length) {\n throw new Error('Truncated payload');\n }\n end = Math.min(end, buffer.length);\n if (end - start <= TAG_LENGTH) {\n throw new Error('Invalid block: too small at ' + i);\n }\n var block = decryptRecord(key, i, buffer.slice(start, end));\n result = Buffer.concat([result, block]);\n start = end;\n }\n return result;\n}",
"mimeToString(mimePart, includeHeaders) {\n EnigmailLog.DEBUG(\n \"persistentCrypto.jsm: mimeToString: part: '\" + mimePart.partNum + \"'\\n\"\n );\n\n let msg = \"\";\n let rawHdr = mimePart.headers._rawHeaders;\n\n if (includeHeaders && rawHdr.size > 0) {\n for (let hdr of rawHdr.keys()) {\n let formatted = formatMimeHeader(hdr, rawHdr.get(hdr));\n msg += formatted;\n if (!formatted.endsWith(\"\\r\\n\")) {\n msg += \"\\r\\n\";\n }\n }\n\n msg += \"\\r\\n\";\n }\n\n if (mimePart.body.length > 0) {\n let encoding = getTransferEncoding(mimePart);\n if (!encoding) {\n encoding = \"8bit\";\n }\n\n if (encoding === \"base64\") {\n msg += EnigmailData.encodeBase64(mimePart.body);\n } else {\n let charset = getCharset(mimePart, \"content-type\");\n if (charset) {\n msg += EnigmailData.convertFromUnicode(mimePart.body, charset);\n } else {\n msg += mimePart.body;\n }\n }\n }\n\n if (mimePart.subParts.length > 0) {\n let boundary = EnigmailMime.getBoundary(\n rawHdr.get(\"content-type\").join(\"\")\n );\n\n for (let i in mimePart.subParts) {\n msg += `--${boundary}\\r\\n`;\n msg += this.mimeToString(mimePart.subParts[i], true);\n if (msg.search(/[\\r\\n]$/) < 0) {\n msg += \"\\r\\n\";\n }\n msg += \"\\r\\n\";\n }\n\n msg += `--${boundary}--\\r\\n`;\n }\n return msg;\n }",
"function decrypt (encryptedBuffer) {\n var nonce = encryptedBuffer.slice(0, sodium.crypto_box_NONCEBYTES)\n var encryptedMessage = encryptedBuffer.slice(sodium.crypto_box_NONCEBYTES)\n return sodium.crypto_secretbox_open_easy(encryptedMessage, nonce, secret, 'text')\n}",
"returnData(data) {\n EnigmailLog.DEBUG(\n \"mimeVerify.jsm: returnData: \" + data.length + \" bytes\\n\"\n );\n\n let m = data.match(/^(content-type: +)([\\w/]+)/im);\n if (m && m.length >= 3) {\n let contentType = m[2];\n if (contentType.search(/^text/i) === 0) {\n // add multipart/mixed boundary to work around TB bug (empty forwarded message)\n let bound = EnigmailMime.createBoundary();\n data =\n 'Content-Type: multipart/mixed; boundary=\"' +\n bound +\n '\"\\n' +\n \"Content-Disposition: inline\\n\\n--\" +\n bound +\n \"\\n\" +\n data +\n \"\\n--\" +\n bound +\n \"--\\n\";\n }\n }\n\n this.mimeSvc.outputDecryptedData(data, data.length);\n }",
"async function additiveDecryption( shares )\n{\n\t// There should only be two messages with the same subject line.\n\t// If there are more, only take the two most recent messages.\n\tif( shares.length != 2 )\n\t{\n\t\tif( shares.length <= 1 )\n\t\t{\n\t\t\tconsole.error( \"ERROR: \" + \"There are no other messages with matching subject. Can not decrypt.\" );\n\t\t\treturn \"ERROR: There are no other messages with matching subject. Can not decrypt.\"\n\t\t}\n\t\telse\n\t\t{\n\t\t\tconsole.error( \"ERROR: \" + \"There are \" + shares.length + \" messages with matching subjects, but only two are accepted. Can not decrypt.\" );\n\t\t\treturn \"ERROR: There are \" + shares.length + \" messages with matching subjects, but only two are accepted. Can not decrypt.\"\n\t\t}\n\t}\n\n\n\t// The length of either share is the length of the message.\n\t// Simply take the length of the first.\n\tlet length = shares[ 0 ].length;\n\n\t// Create Uint8Array to hold decrypted Uint8 values.\n\tlet decryptedUint = new Uint8Array( length );\n\tlet i;\n\tfor( i = 0; i < length; i++ )\n\t{\n\t\tdecryptedUint[ i ] = shares[ 0 ].charCodeAt( i ) ^ shares[ 1 ].charCodeAt( i );\n\t}\n\n\n\t// Return the the secret string including the attachment information.\n\treturn getMessageDecoding( decryptedUint );\n}",
"loginDecryptData(request, self){\n\n let decryptBlob = (privateKey, blob, lengthChars = 4)=>{\n let icn = new iCrypto();\n let symLength = parseInt(blob.substr(-lengthChars))\n let blobLength = blob.length;\n let symk = blob.substring(blobLength- symLength - lengthChars, blobLength-lengthChars );\n let cipher = blob.substring(0, blobLength- symLength - lengthChars);\n icn.addBlob(\"symcip\", symk)\n .addBlob(\"cipher\", cipher)\n .asym.setKey(\"priv\", privateKey, \"private\")\n .asym.decrypt(\"symcip\", \"priv\", \"sym\", \"hex\")\n .sym.decrypt(\"cipher\", \"sym\", \"blob-raw\", true)\n return icn.get(\"blob-raw\")\n };\n\n let encryptBlob = (publicKey, blob, lengthChars = 4)=>{\n let icn = new iCrypto();\n icn.createSYMKey(\"sym\")\n .asym.setKey(\"pub\", publicKey, \"public\")\n .addBlob(\"blob-raw\", blob)\n .sym.encrypt(\"blob-raw\", \"sym\", \"blob-cip\", true)\n .asym.encrypt(\"sym\", \"pub\", \"symcip\", \"hex\")\n .encodeBlobLength(\"symcip\", 4, \"0\", \"symcipl\")\n .merge([\"blob-cip\", \"symcip\", \"symcipl\"], \"res\")\n return icn.get(\"res\");\n };\n\n if (!self.session){\n console.log(\"invalid island request\");\n return;\n }\n\n let clientHSPrivateKey, taPrivateKey, taHSPrivateKey;\n let token = request.body.token;\n let loginData = request.body.dataForDecryption;\n let ic = new iCrypto();\n ic.asym.setKey(\"priv\", self.session.privateKey, \"private\");\n\n //Decrypting client Hidden service key\n if (loginData.clientHSPrivateKey){\n clientHSPrivateKey = decryptBlob(self.session.privateKey, loginData.clientHSPrivateKey)\n }\n\n if (loginData.topicAuthority && loginData.topicAuthority.taPrivateKey){\n taPrivateKey = decryptBlob(self.session.privateKey, loginData.topicAuthority.taPrivateKey )\n }\n\n if (loginData.topicAuthority && loginData.topicAuthority.taHSPrivateKey){\n taHSPrivateKey = decryptBlob(self.session.privateKey, loginData.topicAuthority.taHSPrivateKey)\n }\n\n let preDecrypted = {};\n\n if (clientHSPrivateKey){\n preDecrypted.clientHSPrivateKey = encryptBlob(token, clientHSPrivateKey)\n }\n if (taPrivateKey || taHSPrivateKey){\n preDecrypted.topicAuthority = {}\n }\n if (taPrivateKey){\n preDecrypted.topicAuthority.taPrivateKey = encryptBlob(token, taPrivateKey)\n }\n if (taHSPrivateKey){\n preDecrypted.topicAuthority.taHSPrivateKey = encryptBlob(token, taHSPrivateKey)\n }\n\n let decReq = new Message(self.version);\n decReq.headers.pkfpSource = self.session.publicKeyFingerprint;\n decReq.body = request.body;\n decReq.body.preDecrypted = preDecrypted;\n decReq.headers.command = \"login_decrypted_continue\";\n decReq.signMessage(self.session.privateKey);\n console.log(\"Decryption successfull. Sending data back to Island\");\n\n self.chatSocket.emit(\"request\", decReq);\n }",
"function consumeMessage(msgBody) {\n var content = new Array();\n var deletionArray = new Array();\n var nextLinkCluster = new Array();\n var breaks = 0;\n var n = msgBody.firstChild;\n\n for (; n; n = n.nextSibling) {\n if (n.nodeType === Node.ELEMENT_NODE) {\n if (n.tagName === \"A\" && n.classList.contains(\"quotelink\") && breaks >= 1) {\n nextLinkCluster.push(n);\n continue;\n } else if (n.tagName === \"BR\") {\n breaks++;\n }\n\n // If new content is found after the next link cluster, ignore what\n // we've acculumated and break, leaving everything for the future\n // calls of consumeXXXX functions.\n } else if (nextLinkCluster.length > 0 ) {\n var nextLinkCluster = new Array();\n break;\n } else {\n breaks = 0;\n }\n\n deletionArray.push(n);\n content.push(n);\n }\n\n // If we fall off the end and nextLinkCluster has any contents, this post\n // has trailing links. The poster is not replying to these but is instead\n // only citing them. Treat them as normal content.\n if (nextLinkCluster.length > 0) {\n deletionArray = deletionArray.concat(nextLinkCluster);\n content = content.concat(nextLinkCluster);\n }\n\n while (content.length > 0 &&\n content[content.length - 1].nodeType === Node.ELEMENT_NODE &&\n content[content.length - 1].tagName === \"BR\") {\n content.pop();\n }\n\n deletionArray.map(function(n) { msgBody.removeChild(n) });\n return content;\n}",
"function getMessageBody() {\n // If selected message is a system message then returns the corresponding language json file entry\n if (props.message.examBodyMessageTypeId != null && props.message.examBodyMessageTypeId !== enums.SystemMessage.None) {\n return translatedMessageContents.content;\n }\n else {\n return props.messageDetails.body;\n }\n }",
"function verifySMIME()\r\n{\r\n\t//region Parse MIME contents to find signature and detached data\r\n\tconst parser = new MimeParser();\r\n\tparser.write(document.getElementById(\"smime_message\").value);\r\n\tparser.end();\r\n\t//endregion\r\n\t\r\n\tif((\"_childNodes\" in parser.node) || (parser.node._childNodes.length !== 2))\r\n\t{\r\n\t\tconst lastNode = parser.getNode(\"2\");\r\n\t\tif((lastNode.contentType.value === \"application/x-pkcs7-signature\") || (lastNode.contentType.value === \"application/pkcs7-signature\"))\r\n\t\t{\r\n\t\t\t// Get signature buffer\r\n\t\t\tconst signedBuffer = utilConcatBuf(new ArrayBuffer(0), lastNode.content);\r\n\t\t\t\r\n\t\t\t// Parse into pkijs types\r\n\t\t\tconst asn1 = asn1js.fromBER(signedBuffer);\r\n\t\t\tif(asn1.offset === (-1))\r\n\t\t\t{\r\n\t\t\t\talert(\"Incorrect message format!\");\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tlet cmsContentSimpl;\r\n\t\t\tlet cmsSignedSimpl;\r\n\t\t\t\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tcmsContentSimpl = new ContentInfo({ schema: asn1.result });\r\n\t\t\t\tcmsSignedSimpl = new SignedData({ schema: cmsContentSimpl.content });\r\n\t\t\t}\r\n\t\t\tcatch(ex)\r\n\t\t\t{\r\n\t\t\t\talert(\"Incorrect message format!\");\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t// Get signed data buffer\r\n\t\t\tconst signedDataBuffer = stringToArrayBuffer(parser.nodes.node1.raw.replace(/\\n/g, \"\\r\\n\"));\r\n\t\t\t\r\n\t\t\t// Verify the signed data\r\n\t\t\tlet sequence = Promise.resolve();\r\n\t\t\tsequence = sequence.then(\r\n\t\t\t\t() => cmsSignedSimpl.verify({ signer: 0, data: signedDataBuffer, trustedCerts: trustedCertificates })\r\n\t\t\t);\r\n\t\t\t\r\n\t\t\tsequence.then(\r\n\t\t\t\tresult =>\r\n\t\t\t\t{\r\n\t\t\t\t\tlet failed = false;\r\n\t\t\t\t\tif(typeof result !== \"undefined\")\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif(result === false)\r\n\t\t\t\t\t\t\tfailed = true;\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\talert(`S/MIME message ${(failed) ? \"verification failed\" : \"successfully verified\"}!`);\r\n\t\t\t\t},\r\n\t\t\t\terror =>\r\n\t\t\t\t\talert(`Error during verification: ${error}`)\r\n\t\t\t);\r\n\t\t}\r\n\t}\r\n\telse\r\n\t\talert(\"No child nodes!\");\r\n}",
"function eveCrack() {\n\n let keyBob = document.getElementById(\"eveBPriv\").innerHTML.split(\" \");\n let keyAlice = document.getElementById(\"eveAPriv\").innerHTML.split(\" \");\n\n let form = /^[0-9 ]+$/;\n for (let i = 0; i < messageList.names.length; i++) {\n let name = messageList.names[i];\n let message = messageList.messages[i];\n\n // if the input isn't a number, don't bother decrypting\n if (!form.exec(message)) {\n messageList.messages[i] = message;\n continue;\n }\n\n if (name === \"Bob\") {\n if (bobKey) {\n getMessage(message, keyBob[1], keyBob[0], \"Bob\", i);\n } else {\n messageList.messages[i] = message;\n }\n } else if (name === \"Alice\") {\n if (aliceKey) {\n getMessage(message, keyAlice[1], keyAlice[0], \"Alice\", i);\n } else {\n messageList.messages[i] = message;\n }\n } else {\n messageList.messages[i] = message;\n }\n }\n }",
"function getMessageDecoding( msg )\n{\n\tlet dec = new TextDecoder();\n\treturn dec.decode( msg );\n}",
"function privateDecrypt(_ref4) {\n var privateKeyPath = _ref4.privateKeyPath,\n toDecrypt = _ref4.toDecrypt;\n var privateKey = fs__WEBPACK_IMPORTED_MODULE_1___default.a.readFileSync(privateKeyPath, {\n encoding: 'utf8'\n });\n var buffer = Buffer.from(toDecrypt, 'base64');\n var decrypted = crypto__WEBPACK_IMPORTED_MODULE_0___default.a.privateDecrypt(privateKey, buffer);\n return decrypted.toString('utf8');\n}",
"decrypt(file, fileMeta, passphrase, callback) {\n this.isDecrypting = true;\n var workers = window.secureShared.spawnWorkers(window.secureShared\n .workerCount),\n i;\n for (i = 0; i < workers.length; i++) {\n workers[i].addEventListener('message', onWorkerMessage,\n false);\n }\n\n var slices = file.split(window.secureShared.chunkDelimiter);\n\n // Send slices to workers\n for (i = 0; i < slices.length; i++) {\n workers[i % workers.length].postMessage({\n fileData: slices[i],\n fileName: i === 0 ? fileMeta.fileName : '', // only send this once\n passphrase: passphrase,\n decrypt: true,\n index: i\n });\n }\n\n var decryptedFile = {\n fileData: []\n };\n var receivedCount = 0;\n\n function onWorkerMessage(e) {\n // got a slice. Process it.\n if (!_.isObject(e.data)) {\n // error message\n window.alert(\"Incorrect password. Refresh this page to try again.\");\n return;\n }\n receivedCount++;\n onSliceReceived(e.data);\n\n if (receivedCount === slices.length) {\n // last slice, finalize\n onFinish();\n }\n }\n\n function onSliceReceived(slice) {\n if (slice.fileName) decryptedFile.fileName = slice.fileName;\n decryptedFile.fileData[slice.index] = slice.fileData;\n }\n\n function onFinish() {\n // Create blob\n var binaryData = decryptedFile.fileData.join(\"\");\n var blob = new Blob([window.secureShared.str2ab(binaryData)], {\n type: fileMeta.contentType\n });\n\n if (!/Safari/i.test(window.BrowserDetect.browser)) {\n var URL = window.URL || window.webkitURL;\n var url = URL.createObjectURL(blob);\n\n callback(url);\n\n $(\"<a>\").attr(\"href\", url).attr(\"download\",\n decryptedFile.fileName).addClass(\n \"btn btn-success\")\n .html(\n '<i class=\"icon-download-alt icon-white\"></i> Download'\n ).appendTo(\"#downloaded-content\").hide().fadeIn();\n } else {\n // Safari can't open blobs, create a data URI\n // This will fail if the file is greater than ~200KB or so\n // TODO figure out what's wrong with the blob size in safari\n // TODO Why doesn't safari want a dataview here?\n if (blob.size > 200000) return window.alert(\n \"Sorry, this file is too big for Safari. Please try to open it in Chrome.\"\n );\n var fileReader = new FileReader();\n fileReader.readAsDataURL(blob);\n }\n\n this.isDecrypting = false;\n }\n }",
"function RSADecrypt(ctext) {\n var c = parseBigInt(ctext, 16);\n var m = this.doPrivate(c);\n if (m == null) return null;\n return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3);\n }",
"getEncryptedELLData(telegram) {\n let packet = telegram.getPacket();\n let startIndex = 17;\n let length = packet.getBuffer().length - startIndex;\n\n return this.fetchData(packet, {\n BLOCK2_ENCRYPTED_ELL_DATA: {\n start: startIndex,\n length: length\n }\n });\n }",
"isBrokenByExchange(mime) {\n EnigmailLog.DEBUG(\"persistentCrypto.jsm: isBrokenByExchange:\\n\");\n\n try {\n if (\n mime.subParts &&\n mime.subParts.length === 3 &&\n mime.fullContentType.toLowerCase().includes(\"multipart/mixed\") &&\n mime.subParts[0].subParts.length === 0 &&\n mime.subParts[0].fullContentType.search(/multipart\\/encrypted/i) < 0 &&\n mime.subParts[0].fullContentType.toLowerCase().includes(\"text/plain\") &&\n mime.subParts[1].fullContentType\n .toLowerCase()\n .includes(\"application/pgp-encrypted\") &&\n mime.subParts[1].fullContentType\n .toLowerCase()\n .search(/multipart\\/encrypted/i) < 0 &&\n mime.subParts[1].fullContentType\n .toLowerCase()\n .search(/PGPMIME Versions? Identification/i) >= 0 &&\n mime.subParts[2].fullContentType\n .toLowerCase()\n .includes(\"application/octet-stream\") &&\n mime.subParts[2].fullContentType.toLowerCase().includes(\"encrypted.asc\")\n ) {\n EnigmailLog.DEBUG(\n \"persistentCrypto.jsm: isBrokenByExchange: found message broken by MS-Exchange\\n\"\n );\n return true;\n }\n } catch (ex) {}\n\n return false;\n }",
"function getAttachmentData( data )\n{\n\t// Get list of raw attachments. First index is previous portion of raw message,\n\t// so length is one less than array length.\n\tlet rawAttachments = data.split( \"Content-Disposition: attachment;\" );\n\tlet numAttachments = rawAttachments.length - 1;\n\n\t// Create array to hold string contents and file titles.\n\tlet contents = [];\n\tlet titles = [];\n\n\tlet rawAttachment;\n\tlet i, j;\n\n\tfor( i = 1; i <= numAttachments; i++ )\n\t{\n\t\t// Verify that an attachment exists. Break if it doesn't.\n\t\tif( rawAttachments[ i ] === undefined )\n\t\t{\n\t\t\treturn -1;\n\t\t}\n\n\n\t\t// Get portion of raw message relating to the 'ith' \n\t\t// attachment then get lines of raw attachment.\n\t\tlet rawAttachmentLines = rawAttachments[ i ].split( \"\\n\" );\n\n\n\t\t// The second line contains the filename in the format 'filename=\"<filename>\"'.\n\t\t// Parse this out to get the filename.\n\t\tlet filename = rawAttachmentLines[ 1 ].substring( 11, rawAttachmentLines[ 1 ].length - 2 );\n\t\t\n\n\t\t// Only add the file if it is a share, tag-x-x, or k-x-x.\n\t\tif( /(share|tag-[0-9]+-[0-9]+|k-[0-9]+-[0-9]+)/.exec( filename ) )\n\t\t{\n\t\t\t// Get Base64 content from raw message by looping through the attachment lines.\n\t\t\t// First three lines are blank line, filename, and blank line. So we must skip those\n\t\t\t// before parsing the rest of the text (i.e., start at j = 3).\n\t\t\tlet content = \"\";\n\t\t\tfor( j = 3; j <= rawAttachmentLines.length - 1; j++ )\n\t\t\t{\n\t\t\t\t// Boundary in raw message with attachment begins with fourteen hyphens.\n\t\t\t\t// If line begins with this, then stop parsing and break out of loop.\n\t\t\t\tif( rawAttachmentLines[ j ].startsWith( \"--------------\" ) ) break;\n\n\n\t\t\t\t// Add current line to content.\n\t\t\t\tcontent += rawAttachmentLines[ j ];\n\t\t\t}\n\n\n\t\t\t// Attachment area ends with an extra newline.\n\t\t\t// This needs to be removed before decryption.\n\t\t\tcontent = content.substring( 0, content.length - 1 );\n\n\n\n\t\t\tcontents.push( content );\t// Store the current content string.\n\t\t\ttitles.push( filename );\t// Store the current filename.\n\t\t}\n\t}\n\n\treturn [ contents, titles ];\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
5. Define a function called evenNumbers that takes a random integer, from 0 to 100, and outputs all the even integers from 0 to that random number. | function evenNumbers (randomInteger) {
if ( randomInteger > 100 || randomInteger < 0){
return "number has to be between 0 and 100";
}
var even =[];
for (var i = 0; i <=randomInteger; i++) {
if (i%2 === 0) {
even.push(i);
}
}
return even
} | [
"function randomNegativeEvenNumber() {\n var randomNumber = getRandomIntInclusive(1,1000);\n if(randomNumber % 2 === 0) {\n return randomNumber;\n }\n\n return randomNegativeEvenNumber();\n}",
"function evenNumbers(numbers) {\n return numbers % 2 == 0;\n\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 oddEven() {\n for (let i = 0; i <= 15; i++) {\n if (i % 2 == 0) {\n console.log(`${i} is even`);\n } else {\n console.log(`${i} is odd`);\n }\n }\n}",
"function randomNegativeOddNumber() {\n var randomNumber = getRandomIntInclusive(1,1000);\n if(randomNumber % 2 === 0) {\n return randomNegativeOddNumber();\n }\n\n return randomNumber;\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 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 oddOrEven(){\n for (let i = 0; i <= 20; i++) {\n if (i % 2 === 0) {\n console.log(i + ' is even');\n } else {\n console.log(i + ' is odd');\n }\n }\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 is_even(num){\n if(num % 2 == 0){\n return true;\n }\n return false;\n}",
"function randomPositiveOddNumber() {\n var randomNumber = getRandomIntInclusive(1,1000);\n if(randomNumber % 2 === 0) {\n return randomPositiveOddNumber();\n }\n\n return randomNumber;\n}",
"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 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 sum_odd_5000(){\n var sum = 0;\n for(var i=1; i<5000; i+=2){\n sum = sum + i;\n }\n return sum;\n}",
"function printNums() {\n var num = 0\n while ( num <=15 ) {\n if(num % 2 === 0) {\n console.log(num + \" is even\");\n }\n else {\n console.log(num + \" is odd\");\n }\n num += 1;\n }\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 randomOddSmallers (limit, min, max) {\n function getRandomInt (min, max) {\n min = Math.ceil(min)\n max = Math.floor(max)\n return Math.floor(Math.random() * (max - min + 1)) + min\n }\n var random = getRandomInt(min, max)\n if (random > 40) {\n limit = (limit % 2 === 0) ? (limit + 1) : limit\n for (var i = limit; i <= random; i += 2) console.log(i)\n } else {\n for (var j = limit; j >= random; j--) console.log(j)\n }\n}",
"function prog14()\n{\n\tvar n= prompt(\"Enter Even No\");\n\tn=parseInt(n);\n\t\n\t\tfor( var i=n+2;i<=n+10;i=i+2)\n\t\t{\n\t\tconsole.log(i);\n\t\t}\n\t\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}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
==========Today and future date function end here======== /==========Start and end time valid function start here======== | start_end_date($eve) {
var beginningDate = this.newRequestForm.value.event_start_date;
var endDate = this.newRequestForm.value.event_end_date;
if (beginningDate > endDate) {
this.newRequestForm.controls['event_start_date'].setValue('');
this.newRequestForm.controls['event_end_date'].setValue('');
this.toastr.error("Invalid Time", '', { timeOut: 2000 });
}
if (beginningDate == endDate) {
this.newRequestForm.controls['event_start_date'].setValue('');
this.newRequestForm.controls['event_end_date'].setValue('');
this.toastr.error("Invalid Time", '', { timeOut: 2000 });
}
if (beginningDate < endDate) {
// this.toastr.success("Valid Time ",'', { timeOut: 2000 });
}
} | [
"function isTestSchedule()\r\n{\r\n\t//alert (\"aaa\");\r\n\tvar currentTime=new Date();\r\n\t//console.log(currentTime + \" - \" + myQaObj.quizObj.startTime + \" - \" + myQaObj.quizObj.endTime);\r\n\tvar uStartTime = ((myQaObj.quizObj.startTime).split(\"-\")).join(\"/\");\r\n\tvar uEndTime = ((myQaObj.quizObj.endTime).split(\"-\")).join(\"/\");\r\n\t//console.log(\">> \"+currentTime + \" - \" + uStartTime + \" - \" + uEndTime);\r\n\tvar testStartTime = new Date(uStartTime); //(myQaObj.quizObj.startTime);\r\n\tvar testEndTime = new Date(uEndTime); //(myQaObj.quizObj.endTime);\r\n\t//console.log(currentTime + \" - \" + testStartTime + \" - \" + testEndTime);\r\n //if currentTime is less than start time than msg=test is not active yet\r\n if(currentTime < testStartTime)\r\n\t{\r\n\t\tmyQaObj.quizObj.testStatus = \"INACTIVE\";\r\n\t}\r\n //else if currentTime is greater than start time and less than end time than msg=test is active\r\n else if(currentTime > testStartTime && currentTime < testEndTime)\r\n\t{\r\n\t\tmyQaObj.quizObj.testStatus = \"ACTIVE\";\r\n\t}\r\n //else msg = test has expired\r\n else if(currentTime > testEndTime)\r\n\t{\r\n\t\tmyQaObj.quizObj.testStatus = \"EXPIRED\";\t\r\n\t}\r\n\telse\r\n\t{\r\n\t\tconsole.log(\"invalid test status...please check with admin - \" + currentTime + \" - \" + testStartTime + \" - \" + testEndTime);\r\n return false;\r\n\t}\r\n return true;\r\n}",
"function create_time_range_inputs(input_args) {\n //\n // defining static inputs\n var date_range_onclick = \"toggle_view_element_button('show_date_range','date_range','Hide Date Range','Show Date Ranage'); toggle_disabled('time-range,st-day,st-month,st-year,en-day,en-month,en-year');\";\n var st_img_onclick = \"create_calander('calander','0','st-day','st-month','st-year'); show_hide('calander');\";\n var end_img_onclick = \"create_calander('calander','0','en-day','en-month','en-year'); show_hide('calander');\";\n //\n // initializing variable inputs\n var time_range_onchange = '';\n var day_onkeyup = '';\n var month_onchange = '';\n var year_onchange = '';\n //\n // creating date objects for time range inputs\n var today = new Date();\n var first = new Date(today.getFullYear(),today.getMonth(),1);\n var curr_wk = [new Date(today.getFullYear(),today.getMonth(),(today.getDate()-today.getDay()))];\n curr_wk[1] = new Date(curr_wk[0].getFullYear(),curr_wk[0].getMonth(),(curr_wk[0].getDate()+6))\n var last_2wk = [new Date(today.getFullYear(),today.getMonth(),(today.getDate()-today.getDay()-7)),curr_wk[1]];\n var last_4wk = [new Date(today.getFullYear(),today.getMonth(),(today.getDate()-today.getDay()-21)),curr_wk[1]];\n var curr_mth = [new Date(first.getFullYear(),first.getMonth(),(first.getDate()-first.getDay()))];\n curr_mth[1] = new Date(first.getFullYear(),first.getMonth()+1,1);\n curr_mth[1] = new Date(curr_mth[1].getFullYear(),curr_mth[1].getMonth(),(curr_mth[1].getDate()+(6-curr_mth[1].getDay())));\n var curr_pp = new Date(CONSTANTS.FIRST_BUSINESS_DAY[0],+CONSTANTS.FIRST_BUSINESS_DAY[1]-1,CONSTANTS.FIRST_BUSINESS_DAY[2]);\n var test_date = curr_pp;\n curr_pp = [curr_pp]\n for (var w = 0; w < 60; w+=2) {\n test_date = new Date(test_date.getFullYear(),test_date.getMonth(),(test_date.getDate()+14));\n curr_pp[1] = new Date(test_date.getFullYear(),test_date.getMonth(),(test_date.getDate()-1));\n if (test_date > today) {break;}\n curr_pp = [test_date];\n }\n var prev_pp = [new Date(curr_pp[0].getFullYear(),curr_pp[0].getMonth(),(curr_pp[0].getDate()-14))];\n prev_pp[1] = new Date(curr_pp[0].getFullYear(),curr_pp[0].getMonth(),(curr_pp[0].getDate()-1));\n curr_wk = curr_wk[0].yyyymmdd()+ '|' +curr_wk[1].yyyymmdd();\n last_2wk = last_2wk[0].yyyymmdd()+'|' +last_2wk[1].yyyymmdd();\n last_4wk = last_4wk[0].yyyymmdd()+'|' +last_4wk[1].yyyymmdd();\n curr_mth = curr_mth[0].yyyymmdd()+'|' +curr_mth[1].yyyymmdd();\n curr_pp = curr_pp[0].yyyymmdd()+ '|' +curr_pp[1].yyyymmdd();\n prev_pp = prev_pp[0].yyyymmdd()+ '|' +prev_pp[1].yyyymmdd();\n //\n // processing input args\n if (!!(input_args.time_range_onchange)) {time_range_onchange = input_args.time_range_onchange;}\n if (!!(input_args.day_onkeyup)) {day_onkeyup = input_args.day_onkeyup;}\n if (!!(input_args.month_onchange)) {month_onchange = input_args.month_onchange;}\n if (!!(input_args.year_onchange)) {year_onchange = input_args.year_onchange;}\n if (!!(input_args.add_date_range_onclick)) {date_range_onclick += input_args.add_date_range_onclick;}\n if (!!(input_args.add_st_img_onclick)) {st_img_onclick += input_args.st_img_onclick;}\n if (!!(input_args.add_end_img_onclick)) {end_img_onclick += input_args.add_end_img_onclick;}\n //\n // creating output fields\n var output = ''+\n '<label class=\"label\">Time Range:</label>'+\n '<select id=\"time-range\" class=\"dropbox-input\" name=\"time-range\" onchange=\"'+time_range_onchange+'\">'+\n '<option value=\"'+curr_wk+'\">Current Week</option>'+\n '<option value=\"'+curr_pp+'\">Current Pay Period</option>'+\n '<option value=\"'+prev_pp+'\">Previous Pay Period</option>'+\n '<option value=\"'+last_2wk+'\">Last 2 Weeks</option>'+\n '<option value=\"'+last_4wk+'\">Last 4 Weeks</option>'+\n '<option value=\"'+curr_mth+'\">Current Month</option>'+\n '</select>'+\n ' '+\n '<button id=\"show_date_range\" type=\"button\" name=\"show_date_range\" onclick=\"'+date_range_onclick+'\">Show Date Range</button>'+\n '<div id=\"date_range\" class=\"hidden-elm\" name=\"date_range\">'+\n '<span id=\"calander\" class=\"cal-span hidden-elm\"></span>'+\n '<label class=\"label-4em\">From:</label>'+\n '<input id=\"st-day\" class=\"text-input-xsmall\" type=\"text\" name=\"st-day\" maxlength=2 value=\"01\" onkeyup=\"'+day_onkeyup+'\" disabled>'+\n ' '+\n '<select id=\"st-month\" class=\"dropbox-input\" name=\"st-month\" onchange=\"'+month_onchange+'\" disabled>'+\n '<option id=\"1\" value=\"01\">January</option>'+\n '<option id=\"2\" value=\"02\">February</option>'+\n '<option id=\"3\" value=\"03\">March</option>'+\n '<option id=\"4\" value=\"04\">April</option>'+\n '<option id=\"5\" value=\"05\">May</option>'+\n '<option id=\"6\" value=\"06\">June</option>'+\n '<option id=\"7\" value=\"07\">July</option>'+\n '<option id=\"8\" value=\"08\">August</option>'+\n '<option id=\"9\" value=\"09\">September</option>'+\n '<option id=\"10\" value=\"10\">October</option>'+\n '<option id=\"11\" value=\"11\">November</option>'+\n '<option id=\"12\" value=\"12\">December</option>'+\n '</select>'+\n ' '+\n '<select id=\"st-year\" class=\"dropbox-input\" name=\"st-year\" onchange=\"'+year_onchange+'\" disabled>'+\n '</select>'+\n ' '+\n '<a onclick=\"'+st_img_onclick+'\"><image id=\"cal_st_image\" class=\"cal-image\" src=\"http://www.afwendling.com/operations/images/calander.png\"></a>'+\n '<br>'+\n '<label class=\"label-4em\">To:</label>'+\n '<input id=\"en-day\" class=\"text-input-xsmall\" type=\"text\" name=\"en-day\" maxlength=2 value=\"01\" onkeyup=\"'+day_onkeyup+'\" disabled>'+\n ' '+\n '<select id=\"en-month\" class=\"dropbox-input\" name=\"en-month\" onchange=\"'+month_onchange+'\" disabled>'+\n '<option id =\"1\" value=\"01\">January</option>'+\n '<option id =\"2\" value=\"02\">February</option>'+\n '<option id =\"3\" value=\"03\">March</option>'+\n '<option id =\"4\" value=\"04\">April</option>'+\n '<option id =\"5\" value=\"05\">May</option>'+\n '<option id =\"6\" value=\"06\">June</option>'+\n '<option id =\"7\" value=\"07\">July</option>'+\n '<option id =\"8\" value=\"08\">August</option>'+\n '<option id =\"9\" value=\"09\">September</option>'+\n '<option id =\"10\" value=\"10\">October</option>'+\n '<option id =\"11\" value=\"11\">November</option>'+\n '<option id =\"12\" value=\"12\">December</option>'+\n '</select>'+\n ' '+\n '<select id=\"en-year\" class=\"dropbox-input\" name=\"en-year\" onchange=\"'+year_onchange+'\" disabled>'+\n '</select>'+\n ' '+\n '<a onclick=\"'+end_img_onclick+'\"><image id=\"cal_en_image\" class=\"cal-image\" src=\"http://www.afwendling.com/operations/images/calander.png\"></a>'+\n '';\n //\n document.getElementById(input_args.output_id).innerHTML = output;\n //\n populate_year_dropboxes('st-year');\n populate_year_dropboxes('en-year');\n}",
"function validDates() {\n if (checkIn.val() != '' && checkOut.val() != '') {\n inDate = new Date(checkIn.val())\n outDate = new Date(checkOut.val())\n if (inDate < outDate) {\n return true\n }\n }\n return false\n }",
"function validateStandardDate(due){\n var mess = \"\";\n if (due == \"\") {\n return mess;\n }\n var patt = /^20[0-9]{2}\\/[01][0-9]\\/[0-3][0-9]$/;\n var tmp = patt.exec(due);\n if (tmp == \"\") {\n return \"Date must take form YYYY/MM/DD.\";\n }\n return tmp;\n\n var DDcap = new Array();\n DDcap[0] = 31;\n DDcap[1] = 28;\n DDcap[2] = 31;\n DDcap[3] = 30;\n DDcap[4] = 31;\n DDcap[5] = 30;\n DDcap[6] = 31;\n DDcap[7] = 31;\n DDcap[8] = 30;\n DDcap[9] = 31;\n DDcap[10] = 30;\n DDcap[11] = 31;\n var PYY = /^[0-9]{1,4}/;\n var YY = parseInt(PYY.exec(due), 10);\n var PTMM = /\\/[0-9]{1,2}\\//;\n var TMM = PTMM.exec(due);\n var PMM = /[0-9]{1,2}/;\n var MM = parseInt(PMM.exec(TMM), 10);\n var PDD = /[0-9]{1,2}$/;\n var DD = parseInt(PDD.exec(due), 10);\n var t = new Date();\n //var et = (t.getTime() - t.getMilliseconds())/1000 - 1293840000; // time since 0:00:00 on Jan 1, 2011\n var bau = true;\n if(YY < 2013){\n mess = \"Date must take form YYYY/MM/DD. \";\n }\n if(MM > 12 || MM < 1){\n mess = \"Date must take form YYYY/MM/DD. \";\n }\n if(DD > DDcap[MM-1] && !(DD==29 && MM==2 && YY % 4 == 0) || DD == 0){\n mess += \"The date you entered is invalid for the month selected\";\n }\n return mess;\n}",
"function validateDateFilter() {\n var startEra = getEra(\"start\");\n var endEra = getEra(\"end\");\n var startDate = getDate(\"start\");\n var endDate = getDate(\"end\");\n\n if ((!startEra && startDate) || (startEra && !startDate)) {\n return false;\n }\n if ((!endEra && endDate) || (endEra && !endDate)) {\n return false; \n }\n if ((startEra && startDate) && !(endEra && endDate)) {\n return true;\n }\n if (!(startEra && startDate) && (endEra && endDate)) {\n return true;\n }\n return (compareDates(startDate, startEra, endDate, endEra) <= 0);\n}",
"function ValidateAppointment()\n{\n AptDate = document.getElementById(\"IdDate\").value;\n today = new Date().toISOString().slice(0, 10);\n \n // reject past date\n if (AptDate < today) {\n document.getElementById(\"error\").innerHTML = \"Cannot create past appointments!\";\n document.getElementById(\"IdDate\").focus();\n return false; \n }\n \n return true;\n}",
"function ValidateWorkAvailability(currentDay) {\n try {\n /* Retrieve required properties with user-entered values.*/\n var fromHour = currentDay.get(\"FromHour\") ? parseFloat(currentDay.get(\"FromHour\").getValue()) : 0.00;\n var fromMinute = currentDay.get(\"FromMinute\") ? parseFloat(currentDay.get(\"FromMinute\").getValue()) : 0.00;\n var fromPeriod = currentDay.get(\"FromPeriod\") ? currentDay.get(\"FromPeriod\").getValue() : \"\";\n var toHour = currentDay.get(\"ToHour\") ? parseFloat(currentDay.get(\"ToHour\").getValue()) : 0.00;\n var toMinute = currentDay.get(\"ToMinute\") ? parseFloat(currentDay.get(\"ToMinute\").getValue()) : 0.00;\n var toPeriod = currentDay.get(\"ToPeriod\") ? currentDay.get(\"ToPeriod\").getValue() : \"\";\n var inHours = currentDay.get(\"InHours\") ? parseFloat(currentDay.get(\"InHours\").getValue()) : 0.00;\n\n /* BEGIN REPLICATION OF CalculateTimeInMinutes DATATRANSFORM.*/\n /* Default the total minutes to minutes entered; particularly useful in case of 12:30AM = 0 Hours + 30 Minutes.*/\n fromTimeInMinutes = fromMinute;\n toTimeInMinutes = toMinute;\n\n /*DELETE?-KCJ*/\n if (Number.isNaN(fromTimeInMinutes)) {\n fromTimeInMinutes = 0.00;\n }\n /*DELETE?-KCJ*/\n if (Number.isNaN(toTimeInMinutes)) {\n toTimeInMinutes = 0.00;\n }\n\n /* IF the given From time is in the afternoon and not special case of 12PM.*/\n if ((fromPeriod === \"PM\") && (fromHour != 12.0)) {\n fromHour += 12.0;\n fromTimeInMinutes += (fromHour * 60.0);\n }\n /* IF the given From time is in the morning and is not the special case of 12 AM.*/\n else if ((fromPeriod === \"AM\") && (fromHour != 12.0)) {\n fromTimeInMinutes += (fromHour * 60.0);\n }\n /* IF the given To time is in the afternoon and not special case of 12PM.*/\n if ((toPeriod === \"PM\") && (toHour != 12.0)) {\n toHour += 12.0;\n toTimeInMinutes += (toHour * 60.0);\n }\n /* IF the given To time is in the morning and is not the special case of 12 AM.*/\n else if ((toPeriod === \"AM\") && (toHour != 12.0)) {\n toTimeInMinutes += (toHour * 60.0);\n }\n\n /* Insert properties with appropriate values.*/\n currentDay.put('ToTimeInMinutes', toTimeInMinutes);\n currentDay.put('FromTimeInMinutes', fromTimeInMinutes);\n /* END REPLICATION OF CalculateTimeInMinutes DATATRANSFORM.*/\n\n /* BEGIN REPLICATION OF SingleDayValidations VALIDATION.*/\n /* Check if user entered a value for the required field, InHours. Part of US-346.*/\n if (inHours === \"\" || Number.isNaN(inHours)) { /* If InHours is blank (\"\").*/\n /* InHours is required */\n currentDay.get(\"InHours\").addMessage(ALMCensus.Messages.InHoursRequired);\n }\n /*US-1498:\n -AC#2: If \"From\" time before 9:00AM or \"To\" time later than 9:00PM.\"\n -AC#3: If \"From\" time after 8:45PM\" or \"To\" time later than 9:00PM.\"*/\n /* 'Magic Numbers' found below correspond to the hour limits specified when converted to minutes for easy comparision.*/\n if ((fromTimeInMinutes < 540) || (fromTimeInMinutes > 1245)) {\n currentDay.get(\"FromHour\").addMessage(ALMCensus.Messages.OutsideAcceptedTimeWindow);\n }\n /*US-1498:\n -AC#4: If \"To\" time before 9:15AM.\n -AC#5: If \"To\" time after 9:00PM\" */\n /* 'Magic Numbers' found below correspond to the hour limits specified when converted to minutes for easy comparison.*/\n else if ((toTimeInMinutes < 555) || (toTimeInMinutes > 1260)) {\n currentDay.get(\"ToHour\").addMessage(ALMCensus.Messages.OutsideAcceptedTimeWindow);\n }\n /*US-1498:\n -AC#6: If \"To\" time that is earlier than a \"From\" time.\n -AC#8: If\"From\" time that is the same as a \"To\" time.*/\n if (fromTimeInMinutes >= toTimeInMinutes) {\n currentDay.get(\"FromHour\").addMessage(ALMCensus.Messages.ToTimeFromTimeWrongOrder);\n }\n /*US-1498:\n -AC#7: If \"From\" time that is later than a \"To\".\n -AC#8: If \"From\" time that is the same as a \"To\" time.*/\n else if (toTimeInMinutes <= fromTimeInMinutes) {\n currentDay.get(\"ToHour\").addMessage(ALMCensus.Messages.ToTimeFromTimeWrongOrder);\n }\n /*US-1498:\n -AC#9: If more Availability Hours than exist between the time inputted within the \"From\" and \"To\" fields or negative entry.*/\n enteredTimeInterval = (toTimeInMinutes - fromTimeInMinutes) / 60.0; /* Amount of time expired between entered from and to times.*/\n if ((!Number.isNaN(inHours) && inHours > enteredTimeInterval) || (inHours < 0.0)) {\n currentDay.get(\"InHours\").addMessage(ALMCensus.Messages.InvalidTotalHours);\n }\n /* END REPLICATION OF SingleDayValidations VALIDATION.*/\n } catch (e) {\n console.log(\"Uncaught exception in ValidateWorkAvailability: \" + e.message);\n try {\n /* Try to bubble error to currentDay object (maybe the error is something we can recover from) */\n currentDay.addMessage(\"Uncaught exception in ValidateWorkAvailability: \" + e.message);\n } catch (e) {}\n }\n}",
"function dayAndTimeValidation(req, res, next) {\n const { reservation_date, reservation_time } = res.locals.body;\n const dateObject = new Date(reservation_date + \"T\" + reservation_time);\n const today = new Date();\n const [year, month, day] = [\n today.getFullYear(),\n today.getMonth(),\n today.getDate(),\n ];\n const todayObject = new Date(year, month, day);\n todayObject.setHours(0);\n\n const reservationTimeTruncated = reservation_time.match(/\\d\\d:\\d\\d/)[0];\n const timeNow = today.toTimeString().match(/\\d\\d:\\d\\d/)[0];\n\n let message = \"\";\n if (dateObject < today) {\n message = \"Only future and present reservation dates are allowed\";\n }\n if (dateObject.getDay() === 2) {\n message = \"Reservation date must not be a Tuesday since business is closed\";\n }\n if (\n reservationTimeTruncated < specifiedTimeString(10, 30) ||\n reservationTimeTruncated > specifiedTimeString(21, 30)\n ) {\n message = \"Reservation time must be between 10:30 AM and 9:30 PM\";\n }\n if (message.length) {\n next({\n status: 400,\n message: message,\n });\n }\n return next();\n}",
"function stOrderPlanRecptStartDateQuery(dp){\r\n\t$(\"#planRecptDateEnd\").attr('title','');\r\n\t$(\"#planRecptDateEnd\").removeClass('errorInput');\r\n\tvar planRecptEndDate=$(\"#planRecptDateEnd\").val();\r\n\tvar planRecptBeginDate= dp.cal.getNewDateStr();\r\n\tif(planRecptEndDate){\t\t\r\n\t\tvar subDays=getSubDays(planRecptBeginDate,planRecptEndDate);\r\n\t\tif(subDays<0){\r\n\t\t\t$(\"#planRecptDateEnd\").attr('title','结束日期小于开始日期');\r\n\t\t\t$(\"#planRecptDateEnd\").addClass('errorInput');\r\n\t\t\treturn false;\r\n\t\t}\r\n\t} \r\n}",
"function validateDateAndTime(req, res, next) {\n const { reservation_date, reservation_time } = req.body.data;\n const reservationDate = new Date(`${reservation_date}T${reservation_time}:00.000`);\n const todaysDate = new Date();\n const reservationTime = Number(reservation_time.replace(\":\", \"\"));\n\n if (!reservation_date.match(/\\d{4}-\\d{2}-\\d{2}/)) {\n return next({ status: 400, message: 'reservation_date is invalid!' });\n };\n\n if (reservationDate < todaysDate) {\n return next({status: 400, message: \"Requested reservation is in the future\"})\n };\n\n if (reservationDate.getDay() === 2) {\n return next({status: 400, message: \"Restaurant is closed on Tuesdays\"})\n };\n \n if (!reservation_time.match(/\\d{2}:\\d{2}/)) {\n return next({ status: 400, message: 'reservation_time is invalid!' });\n };\n \n if (reservationTime < 1030 || reservationTime > 2130) {\n return next({ status: 400, message: 'Restaurant is closed during requested reservation time.'})\n };\n \n next();\n}",
"function parseInputs(e) {\r\n e.preventDefault();\r\n let startDate = document.querySelector(\"#startDate\");\r\n let endDate = document.querySelector(\"#endDate\");\r\n startDate = new Date(startDate.value).getTime();\r\n endDate = new Date(endDate.value).getTime();\r\n\r\n if (!startDate || ! endDate || endDate - startDate <= 0) {\r\n alert(\"start date must be > end date\");\r\n return;\r\n } else {\r\n onSubmit(startDate, endDate)\r\n }\r\n }",
"function checkDate(time) {\r\n let today = new Date();\r\n today = today.getTime() - (today.getTime() % oneDayInMilliseconds); // Convert 'today' in multiple of a entire date\r\n let errors = []\r\n\r\n if (isNaN(time)) errors.push(\"Must provide a date.\");\r\n\r\n if (time < today) errors.push(\"Date must be in the future.\");\r\n\r\n // Search for a date conflict\r\n for (let i = 0; i < travelDates.length; i++) {\r\n if (travelDates[i].date == time) {\r\n errors.push(\"Date conflict.\");\r\n break;\r\n }\r\n }\r\n\r\n return errors;\r\n}",
"constructor(title,days,time,duration,relative_time,relative_to,till,relative_to_till)\r\n {\r\n this.m_start = '' //moment object for start time\r\n this.title = title;\r\n this.days = days;\r\n this.time = time;\r\n this.duration = duration;\r\n this.relative_time = relative_time;\r\n this.relative_to = relative_to;\r\n this.till = till;\r\n this.relative_to_till = relative_to_till;\r\n this.type = ''; //i not put in constructor yet\r\n }",
"function stOrderRealRecptEndDateQuery(dp){\r\n\t$(\"#realRecptDateEnd\").attr('title','');\r\n\t$(\"#realRecptDateEnd\").removeClass('errorInput');\r\n\tvar realRecptBeginDate=$(\"#realRecptDateBegin\").val();\r\n\tvar realRecptEndDate= dp.cal.getNewDateStr();\r\n\tif(realRecptBeginDate){\t\t\r\n\t\tvar subDays=getSubDays(realRecptBeginDate,realRecptEndDate);\r\n\t\tif(subDays<0){\r\n\t\t\t$(\"#realRecptDateEnd\").attr('title','结束日期小于开始日期');\r\n\t\t\t$(\"#realRecptDateEnd\").addClass('errorInput');\r\n\t\t\treturn false;\r\n\t\t}\r\n\t} \r\n}",
"function handleUpcomingMatch() {\n var today = new Date();\n var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+ (\"0\" + today.getDate()).slice(-2)+'T'+today.getHours()+\":\"+today.getMinutes();\n handleUpcoming(date);\n}",
"function checkBookingAvailableClosedPassed () {\n\t \t var sliderSeconds = 15*60*parseInt(place_slider_from); // 15 minutes * slider steps\n var sliderSecondsTo = 15*60*parseInt(place_slider_to); // 15 minutes * slider steps\n\n\t var TimeOfTheDatePicker_1970 = +$(\"#datepicker_fe\").datepicker( \"getDate\" ).getTime();\n\t var placeOffset = document.getElementById(\"server_placeUTC\").value;\n\t var dndt = TimeOfTheDatePicker_1970/1000;\n\t var d = new Date();\n\t var utc = d.getTime() + (d.getTimezoneOffset() * 60000);\n\t var nd = new Date(utc + (3600000 * placeOffset));\n\t var ndt = nd.getTime()/1000;\n var diff = ndt - dndt; // seconds passed from the start of the selected date\n if (diff - 60 > sliderSeconds) {\n \t // If less than minute to book return \"place_passed\"\n \t return 1;\n }\n // Else slider is after the place time passed , check if place closed on selected range\n var TimePeriod = sliderSecondsTo - sliderSeconds; // Chosen period of booking\n var endOfBooking = parseInt(sliderSeconds) + parseInt(TimePeriod);\n\t var placeOpen = bookingVars.placeOpen;\n\t var anyOpenRangeValid = false;\n\t for (var ind in placeOpen) { \t\t \n\t\t\t var from = placeOpen[ind].from;\n\t\t\t var to = placeOpen[ind].to;\n\t\t\t if (from <= sliderSeconds && endOfBooking <= to) {\n\t\t\t\t anyOpenRangeValid = true;\n\t\t\t }\n\t }\n\tif(anyOpenRangeValid) {\n\t //Some range valid\n\t return 0;\n\t} else {\n\t // No valid open range\t\n\t return 2;\n\t}\n}",
"function validateTime(start, end) {\n var startParts = start.split(':');\n var endParts = end.split(':');\n if (!/^\\d{2}:\\d{2}$/.test(start) ||\n !/^\\d{2}:\\d{2}$/.test(end) ||\n startParts[0] > 23 || startParts[1] > 59 ||\n endParts[0] > 23 || endParts[1] > 59) {\n alert(\"Time entered is in incorrect format (e.g. 23:59 or 00:01)\");\n return false;\n } else if (startParts[0] > endParts[0] ||\n startParts[0] === endParts[0] && startParts[1] > endParts[1]) {\n alert(\"Start time can't be greter then end time\");\n return false;\n }\n return true;\n }",
"_getSearchEndTime() {\n const now = new Date();\n const endDate = new Date();\n endDate.setHours(12);\n endDate.setMinutes(0);\n\n if (endDate < now) {\n endDate.setHours(now.getHours() + 1);\n endDate.setMinutes(now.getMinutes());\n }\n return endDate;\n }",
"createAppointment(event) {\n event.preventDefault()\n const selectedDate = this.refs.selectedDate.value;\n const selectedTime = this.refs.selectedTime.value;\n var patientDescription = this.refs.selectedPatient.value;\n var patient = this.findPatientIndex(patientDescription, this.state.patientsList);\n var fullTime = selectedDate + \" \" + selectedTime;\n var finalTime = moment(fullTime, \"YYYY-MM-DD hh:mm A\").unix();\n\n if(!patient){\n alert(\"Please select a valid patient!\");\n }else if(moment(selectedDate).isValid() === false\n || moment(selectedDate).isSameOrAfter(moment(), 'day') === false){\n alert(\"Please check if the date is valid and not in the past!\");\n }else if(moment.unix(finalTime).isSameOrAfter(moment(), 'minute') === false){\n alert(\"Please select a valid time!\");\n }else{\n var appt = {\n patientUuid: patient.patientUUID,\n doctorUuid: sessionStorage.userUUID,\n dateScheduled: finalTime\n }\n\n requests.postFutureAppointment(appt)\n .then((res) => {\n console.log(\"created future appointment sucessfully\");\n location.reload();\n })\n .catch((e) =>{\n console.log(\"Could not create future appointment\");\n });\n }\n }",
"function CalculateDueDate(sumbit_date, turnaround) {\n var working_hours = {\n \"start\": 9,\n \"end\": 17\n }\n \n // If sumbit_date is not a Date then error\n if (Object.prototype.toString.call(sumbit_date) === \"[object Date]\" && isNaN(sumbit_date.getTime())) {\n return \"Not valid format please try again with valid Date format\"\n }\n // If turnaround is not number then error\n if (isNaN(turnaround) || turnaround == null) { \n return \"The turnaround must be a number time please try again with a number\"\n }\n // If the submit date is not in the specified time interval then error\n if (sumbit_date.getDay() % 6 == 0) {\n return \"You can't subbmit on weekends, please try again on working days\"\n }\n // If the submit is not on working day then error\n if (sumbit_date.getHours() < working_hours.start || sumbit_date.getHours() >= working_hours.end) {\n return \"You can't subbmit out of working hours (9AM-5PM) please try again in working hours\"\n } \n\n // If everything is OK: \n var return_date;\n // We need to add the weekends if it's predictable \n let turnaround_days = Math.floor(turnaround / 8) + Math.floor(turnaround / 8 / 5) * 2;\n // We need to calculate the time we had besides from the wohole days\n var left_tunroround_millisecond = (turnaround - Math.floor(turnaround / 8) * 8) * 60 * 60 * 1000;\n // We calculate the time we left from the submit day in millisecond \n const remain_from_submit_day_millisecond = new Date(new Date(sumbit_date).setHours(working_hours.end, 0, 0) - sumbit_date).getTime();\n\n // If we don't had enough time durring the day it will push it tommmorw \n if (remain_from_submit_day_millisecond <= left_tunroround_millisecond) {\n turnaround_days++;\n left_tunroround_millisecond -= remain_from_submit_day_millisecond;\n }\n\n\n // We create the return date beacuse we need to see it's on weekend or not\n return_date = new Date(sumbit_date.setDate(sumbit_date.getDate() + turnaround_days));\n // We adding the remaining time to the return date \n return_date.setHours(Math.floor(working_hours.start + left_tunroround_millisecond / (60 * 60 * 1000)));\n\n // If the returning date is on weekend then this will push it to the next week \n if (return_date.getDay() % 6 == 0) {\n let ballance;\n if (return_date.getDay() == 0) {\n ballance = 1\n } else {\n ballance = 2\n }\n return_date = new Date(return_date.setDate(return_date.getDate() + ballance));\n }\n\n // Here we can format the returning date \n return return_date\n \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
end set attribute form div remove label form | function myFunctionLabel(){
const labelForm = document.querySelector('.screen-reader-text');
const elementLabel = document.getElementsByTagName('label')[0];
elementLabel.setAttribute('id', 'label-id');
elementLabel.remove();
} | [
"function clickClearWarnings(label) {\n $(label + ' #input').validate().resetForm()\n $(\"div.ui-tooltip\").remove();\n}",
"function removeFormField() \n{\n\tid = parseInt(jQuery(\"#cont\").val());\n\tif(id >= 0){\n\t\tid = id - 1;\n\t\t\n\t\t/* pega valor inicial pelas ids dos elementos e guarda em vaiaveis */\n\t\tvar noFaixaEtaria = \"noFaixaEtaria\"+id;\n\t\tvar nuValor\t\t = \"nuValor\"+id;\n\t\t\n\t\tjQuery(\"#\"+noFaixaEtaria).remove();\n\t\tjQuery(\"#\"+nuValor).remove();\n\t\t\n\t\tjQuery(\"#cont\").val(id);\n\t}\n}",
"function removeFrom() {\n form.style.display = 'none';\n }",
"render() {\n const html = `<label id=\"${this.target.replace('#', '')}\" class=\"btn btn-primary text-light \" title=\"${this.hoverText}\">\n <input type=\"radio\" name=\"options\" autocomplete=\"off\"> ${this.iconStr()}\n </label>`;\n $(this.target).replaceWith(html);\n }",
"function hideLabel() { \n marker.set(\"labelVisible\", false); \n }",
"_label(label) {\n return `${label}${label && this.required ? '*' : ''}`;\n }",
"function resetCampos(contexto){\r\n\t\t$(\":input\", contexto).each(function(){\r\n\t\t\t$(this).val(\"\").removeClass(\"req\");\r\n\t\t});\t\t\r\n\t\t$(\"div\", contexto).each(function(){\r\n\t\t\t$(this).text(\"\");\r\n\t\t});\t\t\t\t\r\n\t}",
"function addLabelProperties()\n\t{\n\t\t//\tCollect all label elements in form, init vars\t\t\n\t\tif ( typeof f.getElementsByTagName == 'undefined' ) return;\n\t\tvar labels = f.getElementsByTagName( \"label\" );\n\t\tvar label, i = j = 0;\n\t\tvar elem;\n\n\t\t//\tLoop through labels retrieved\n\t\twhile ( label = labels[i++] )\n\t\t{\n\t\t\t//\tFor Opera 6\n\t\t\tif ( typeof label.htmlFor == 'undefined' ) return;\n\t\t\tif (typeof f.elements[label.htmlFor] == 'undefined') continue;\n\t\t\t\n\t\t\t//\tRetrieve element\n\t\t\telem = f.elements[label.htmlFor];\n\t\t\tif ( typeof elem == 'undefined' )\n\t\t\t{\t//\tNo element found for label\t\t\t\t\n\t\t\t\tself.devError( [label.htmlFor], 'noLabel' );\n\t\t\t}\n\t\t\telse if ( typeof elem.label != 'undefined' )\n\t\t\t{\t//\tlabel property already added\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse if ( typeof elem.length != 'undefined' && elem.length > 1 && elem.nodeName != 'SELECT' )\n\t\t\t{\t//\tFor arrayed elements\n\t\t\t\tfor ( j = 0; j < elem.length; j++ )\n\t\t\t\t{\n\t\t\t\t\telem.item( j ).label = label;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//\tRegular label\n\t\t\telem.label = label;\n\t\t}\n\t}",
"function gestioneLabelAnnoNumeroAtto(event) {\n \tvar anno = $(\"#annoAttoAmministrativo\").val();\n \tvar numero = $(\"#numeroAttoAmministrativo\").val();\n \tvar valorizzato = anno || numero;\n \tif(valorizzato){\n \t\t$(\"label[for='annoAttoAmministrativo']\").html(\"Anno *\");\n \t\t$(\"label[for='numeroAttoAmministrativo']\").html(\"Numero *\");\n \t}else{\n \t\t$(\"label[for='annoAttoAmministrativo']\").html(\"Anno\");\n \t\t$(\"label[for='numeroAttoAmministrativo']\").html(\"Numero \");\n \t}\n \t\n }",
"_hideFormElements()\r\n {\r\n $(this.el).find('#filter-inputs div input').val('');\r\n $(this.el).find('#filter-inputs div select').val('');\r\n $(this.el).find('#filter-inputs').children().hide();\r\n }",
"function TKR_prepLabelAC() {\n var i = 0;\n while ($('label'+i)) {\n TKR_validateLabel($('label'+i));\n i++;\n }\n}",
"#syncLabel() {\n let labelElement = typeof this.getLabel === 'function' ? this.getLabel() : null;\n if (labelElement) {\n labelElement.setAttribute('for', this.getWidgetId());\n }\n }",
"function resetFormColors() {\n\t$(\".shirt legend p\").remove();\n\t$(\"label[for='name']\").text(\"Name:\").css(\"color\", \"black\");\n\t$(\"label[for='mail']\").text(\"Email:\").css(\"color\", \"black\");\n\t$(\".activities legend\").css(\"color\", \"black\");\n\t$(\"fieldset:last legend\").css(\"color\", \"black\");\n\t$(\"#credit-card label[for='cc-num']\").css(\"color\", \"black\");\n\t$(\"#credit-card label[for='zip']\").css(\"color\", \"black\");\n\t$(\"#credit-card label[for='cvv']\").css(\"color\", \"black\");\n}",
"unCheck(){\n //let { $input, $label } = PRIVATE.get(this);\n\n PRIVATE.get(this).$input.checked = false;\n markChoiceField.call(this);\n //domRemoveClass($label, CSS_MS_IS_CHECKED);\n }",
"function resetStepForm() {\n editingStep = -1;\n stepType = 'script';\n clearStepForm();\n $('#script-form').addClass('hidden');\n }",
"function setDescription(label) {\n let desBox = descriptionBox[0];\n desBox.style.width = 'auto';\n $(desBox).empty();\n\n let severity = label.getAuditProperty('severity');\n let temporary = label.getAuditProperty('temporary');\n let description = label.getAuditProperty('description');\n let tags = label.getAuditProperty('tags');\n\n desBox.style['background-color'] = util.misc.getLabelColors(label.getAuditProperty('labelType'));\n\n if (severity && severity != 0) {\n let span = document.createElement('span');\n let htmlString = document.createTextNode(i18next.t('severity') + severity + ' ');\n desBox.appendChild(htmlString);\n let img = document.createElement('img');\n img.setAttribute('src', smileyScale[severity]);\n if (isMobile()) {\n img.setAttribute('width', '20px');\n img.setAttribute('height', '20px');\n } else {\n img.setAttribute('width', '12px');\n img.setAttribute('height', '12px');\n }\n\n img.style.verticalAlign = 'middle';\n span.appendChild(img);\n desBox.appendChild(span);\n desBox.appendChild(document.createElement(\"br\"));\n }\n\n if (temporary) {\n let htmlString = document.createTextNode(i18next.t('temporary'));\n desBox.appendChild(htmlString);\n desBox.appendChild(document.createElement(\"br\"));\n }\n\n if (tags && tags.length > 0) {\n // Translate to correct language and separate tags with a comma.\n let tag = tags.map(t => i18next.t('center-ui.tag.' + t)).join(', ');\n let htmlString = document.createTextNode('tags: ' + tag);\n desBox.appendChild(htmlString);\n desBox.appendChild(document.createElement(\"br\"));\n }\n\n if (description && description.trim().length > 0) {\n let htmlString = document.createTextNode(description);\n desBox.appendChild(htmlString);\n }\n\n if (!severity && !temporary && (!description || description.trim().length == 0) &&\n (!tags || tags.length == 0)) {\n let htmlString = document.createTextNode(i18next.t('center-ui.no-info'));\n desBox.appendChild(htmlString);\n }\n\n // Set the width of the des box.\n let bound = desBox.getBoundingClientRect();\n let width = ((bound.right - bound.left) * (isMobile() ? window.devicePixelRatio : 1)) + 'px';\n desBox.style.width = width;\n\n if (isMobile()) {\n desBox.style.fontSize = '30px';\n }\n }",
"function resetImgForm() {\n $('#local-opt, #library-opt, #link-opt').removeClass('selected');\n $('#local-upload, #library-upload, #link-upload').addClass('hidden');\n}",
"function resetForm() {\n $leaveComment\n .attr('rows', '1')\n .val('');\n $cancelComment\n .closest('.create-comment')\n .removeClass('focused');\n }",
"function resetForm(sl) {\n document.querySelector(sl).reset();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an entry and attach files if there are any | async function createEntry(model, entry, files) {
try {
const createdEntry = await strapi.query(model).create(entry);
if (files) {
await strapi.entityService.uploadFiles(createdEntry, files, {
model
});
}
} catch (e) {
console.log(e);
}
} | [
"async function createEntry({ model, entry, files }) {\n try {\n if (_.has(entry, 'files') || _.has(entry, 'featured_image') || _.has(entry, 'logo')) {\n delete entry.files;\n delete entry.featured_image;\n delete entry.logo;\n }\n\n if (model === 'article' || model === 'destination' || model === 'customer') {\n if ('customer' in entry && entry.customer !== null) {\n const result = await strapi.query('customer').findOne({ old_customer_id: entry.customer });\n\n if (result)\n entry.customer = { id: result.id };\n else\n delete entry.customer;\n }\n else {\n delete entry.customer;\n }\n\n // category\n if ('category' in entry && entry.category !== null) {\n const result = await strapi.query('category').findOne({ name: entry.category });\n\n if (result)\n entry.category = { id: result.id };\n else\n delete entry.category;\n }\n else {\n delete entry.category;\n }\n\n //sites\n if ('sites' in entry && entry.sites !== null) {\n const result = await strapi.query('site').findOne({ uid: entry.sites });\n\n if (result)\n entry.sites = [{ id: result.id }];\n else\n delete entry.sites;\n }\n else {\n delete entry.sites;\n }\n }\n\n const createdEntry = await strapi.query(model).create(entry);\n if (files) {\n await strapi.entityService.uploadFiles(createdEntry, files, {\n model,\n });\n }\n } catch (e) {\n if (model === 'article' && 'message' in e && e.message === 'Duplicate entry') {\n const t = Date.now();\n const nData = {\n ...entry,\n slug: `${entry.slug}-${t}`,\n };\n await createEntry({ model, entry: nData, files });\n }\n else {\n console.log('model', entry, e);\n }\n }\n}",
"async function addFile(){\n\t\trouter.push(`/files/${filetype}/create${filetype}/${fileFolderID}`)\n\t}",
"function create(e) {\n\t\tvar fullPath = path.join(e.watch, e.name), i;\n\n\t\t// if it's in a watched directory or in the set of watches\n\t\tif (watches[e.watch] || watches[fullPath]) {\n\t\t\t// TODO: not sure if this will ever fail\n\t\t\tif (createQueue.indexOf(fullPath) < 0) {\n\t\t\t\tcreateQueue.push(fullPath);\n\t\t\t}\n\t\t\t\n\t\t\t// just in case the file was moved onto\n\t\t\ti = removeQueue.indexOf(fullPath);\n\t\t\tif (i >= 0) {\n\t\t\t\tremoveQueue.splice(i, 1);\n\t\t\t}\n\n\t\t\tcreateWatches(createQueue);\n\t\t}\n\t}",
"function addFile(file) {\n files.set(file._template, file);\n fileView.appendChild(file.getTemplate());\n}",
"upsertAttachments(files) {\n return this.getAttachmentMetadata()\n .then((expecteds) => Promise.all(files\n .filter((file) => expecteds.some((expected) => file.fieldname === expected.name))\n .map((file) => Blob.fromFile(file.path, file.mimetype)\n .then((blob) => blob.ensure())\n .then((blob) => submissionAttachments\n .update(new SubmissionAttachment({\n submissionDefId: this.id, blobId: blob.id, name: file.fieldname\n }))))));\n }",
"static addFromUploadedFile(entry, uploadTokenId, type = null){\n\t\tlet kparams = {};\n\t\tkparams.entry = entry;\n\t\tkparams.uploadTokenId = uploadTokenId;\n\t\tkparams.type = type;\n\t\treturn new kaltura.RequestBuilder('baseentry', 'addFromUploadedFile', kparams);\n\t}",
"function writeFile(fldr, fileBlob, scrnBlob, username, usrClass, respForm, doFbPost, message) {\r\n \r\n // create file on google drive. Save the drive\r\n // file object and send it to be renamed to match\r\n // <username>_<class>_<form>.<extension> format\r\n if (fileBlob.getName()) {\r\n var drive_file = fldr.createFile(fileBlob)\r\n // get the file extension:\r\n var extension = getExtension(fileBlob)\r\n // rename file:\r\n drive_file.setName(username + \"_\" + usrClass + \r\n \"_\" + respForm + \"_geoselfie.\" + extension);\r\n }\r\n \r\n // if image was uploaded:\r\n if (scrnBlob.getName()) {\r\n var drive_file_scrn = fldr.createFile(scrnBlob)\r\n var extension_scrn = getExtension(scrnBlob)\r\n \r\n drive_file_scrn.setName(username + \"_\" + usrClass + \"_\" + respForm + \"_screenshot.\" + extension);\r\n }\r\n \r\n // update spreadsheeet to include class:\r\n update_sheet(respForm, usrClass); \r\n \r\n Logger.log(\"doFbPost: \" + doFbPost);\r\n Logger.log(\"message: \" + message);\r\n if (doFbPost == 'doFbPost') {\r\n drive_file.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.EDIT);\r\n var url = 'https://docs.google.com/uc?id=' + drive_file.getId();\r\n Logger.log('photo url: ' + url);\r\n fncPostItemFB(url, message);\r\n }\r\n}",
"addFileRef(user_id, file_info) {\n logger.log('info', 'add file', {user_id: user_id, file_info: file_info})\n\n return FileReference.create({\n UserID: user_id,\n Info: file_info,\n LastUpdated: new Date(),\n }).then(function (file_ref) {\n logger.log('debug', 'file reference added', file_ref.toJSON())\n return file_ref\n }).catch(function (err) {\n logger.log('error', 'add file reference failed', err)\n return err\n })\n }",
"function newFilesToShareInNewFolder() {\n var ss = SpreadsheetApp.getActiveSpreadsheet(),\n rootFolder = DriveApp.getRootFolder(),\n newFolder = \n DriveApp.createFolder('ToShareWithMick'),\n sh = SpreadsheetApp.create('mysheet'),\n shId = sh.getId(),\n shFile =\n DriveApp.getFileById(shId),\n doc = DocumentApp.create('mydocument'),\n docId = doc.getId(),\n docFile = DriveApp.getFileById(docId);\n newFolder.addFile(shFile);\n newFolder.addFile(docFile);\n rootFolder.removeFile(shFile);\n rootFolder.removeFile(docFile);\n}",
"function GistCreateFile() {\n var name = $(\"div#overlay-body input\").val().trim();\n CloseOverlay();\n // Make sure the Filename is at least 1 charater long and ends with .js\n if (endsWith(name, \".js\")) {\n if (name.length == 3) {\n Logger.error(\"Please enter a valid Filename.\");\n return;\n }\n }\n else if (name.length == 0) {\n Logger.error(\"Please enter a valid Filename.\");\n return;\n }\n else {\n name += \".js\";\n }\n\n // Check if Gist is selected and File doesn't exist.\n var gist = gisty.getCurrentGist();\n if (gist === null) {\n Logger.error(\"Please select a Script first.\");\n return;\n }\n\n if (gist.files.hasOwnProperty(name)) {\n Logger.error(\"A File with this name is already present. Please choose another one.\");\n return;\n }\n\n // Add the File to the Gist\n gisty.addFile(name);\n}",
"function addActivityAttachments(blobs, names, picked) {\n blobs.forEach(function(blob, i) {\n if (picked.indexOf(names[i]) === -1) {\n return;\n }\n return pushAttachment(blob, names[i]);\n });\n bugChanged();\n}",
"static add(entry){\n\t\tlet kparams = {};\n\t\tkparams.entry = entry;\n\t\treturn new kaltura.RequestBuilder('externalmedia_externalmedia', 'add', kparams);\n\t}",
"function addMediaFilePoster() {\n if (!vm.modelContentNew || !vm.modelContentNew.mediaFile) {\n return;\n }\n\n // create a canvas (HTML5) element\n var elCanvas = document.createElement('canvas');\n\n // get the media file element (tag)\n var elMediaFile = document.getElementById('media-file-new');\n\n // define size depending on the media file\n var numWidth = elMediaFile.clientWidth;\n var numHeight = elMediaFile.clientHeight;\n\n // set the canvas element's size\n elCanvas.width = numWidth;\n elCanvas.height = numHeight;\n\n // get the 2D context of the canvas to manipulate it\n var context = elCanvas.getContext('2d');\n\n // draw the screenshot of the media file into the context\n context.drawImage(elMediaFile, 0, 0, numWidth, numHeight);\n\n // display the image in the view\n var objUrl = elCanvas.toDataURL('image/jpeg');\n vm.modelContentNew.mediaFilePoster = objUrl;\n vm.modelContentNew.mediaFilePosterTmp = $sce.trustAsResourceUrl(objUrl);\n }",
"function postEntries(entries){\n\tvar display = document.getElementById(\"display\");\n\tvar newSection = document.createElement(\"section\");\n\tvar header = document.createElement(\"h2\");\n\tvar deleteButton = document.createElement(\"button\");\n\tdeleteButton.innerHTML = \"X\";\n\tdeleteButton.setAttribute(\"class\", \"close\");\n\tnewSection.appendChild(deleteButton);\n\tdeleteButton.addEventListener(\"click\", function(){\n\t\tdeletePost(entries.Name);\n\t});\n\theader.innerHTML = entries.Name;\n\tnewSection.appendChild(header);\n\n\tfor(var key in entries) {\n\t\tlet container = document.createElement(\"div\");\n\t\tcontainer.innerHTML = `<h5>${key}:</h5> ${entries[key]}`;\n\t\tnewSection.appendChild(container);\n\t}\n\tdisplay.appendChild(newSection);\n}",
"static addContent(entryId, resource){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\tkparams.resource = resource;\n\t\treturn new kaltura.RequestBuilder('baseentry', 'addContent', kparams);\n\t}",
"function addFileToProject(path, id, icon) {\n\tvar projFolder = air.EncryptedLocalStore.getItem( 'directory' );\n\tvar filename = id + '.png';\n\tvar newPNG = new air.File(path);\n\tvar device = air.EncryptedLocalStore.getItem( 'device' );\n\tif(!device) return;\n\tstr = imageFolder(device, icon) + filename;\n\tvar proj = new air.File( projFolder + str);\n\tnewPNG.copyTo(proj, true);\n}",
"static add(entry, type = null){\n\t\tlet kparams = {};\n\t\tkparams.entry = entry;\n\t\tkparams.type = type;\n\t\treturn new kaltura.RequestBuilder('baseentry', 'add', kparams);\n\t}",
"static addContent(entryId, resource = null){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\tkparams.resource = resource;\n\t\treturn new kaltura.RequestBuilder('media', 'addContent', kparams);\n\t}",
"_contentTypeEntry(_stackApiKey, _stackCreationCompletionCb) {\n // Loops through the number of content types requested\n return async.timesSeries(this._dataConfig.content_type, (_cN, _cDone) => {\n // Creates the content type\n return _contentType.build({\n apiKey: _stackApiKey\n }, (_contentTypeErr, _contentTypeData) => {\n if (_contentTypeErr) {\n // In case of title not unique error, the entry creation will be skipped\n if ((_.has(_contentTypeErr, 'errors.title') && /not\\s+unique/i.test(_contentTypeErr.errors.title[0])) ||\n (_.has(_contentTypeErr, 'errors.uid') && /not\\s+unique/i.test(_contentTypeErr.errors.uid[0]))) {\n return _cDone(null, {});\n }\n return _cDone(_contentTypeErr);\n }\n let _contentTypeUid = _contentTypeData.content_type.uid;\n global.uidHolder.entry[_stackApiKey][_contentTypeUid] = [];\n global.uidHolder.content_type[_stackApiKey].push(_contentTypeUid);\n // If the content type is single, then only one entry will be created\n let _entryNumbers = _contentTypeData.content_type.options.singleton ? 1 : this._dataConfig.entry;\n let _entryEntity = _entry(_contentTypeData);\n // Loops through the number of entries requested\n return async.timesLimit(_entryNumbers, 100, (_eN, _eDone) => {\n // Creates the entry\n return _entryEntity.build({\n apiKey: _stackApiKey,\n _entryIteration: _eN\n }, (_entryErr, _entryData) => {\n if (_entryErr) {\n return _eDone(_entryErr);\n }\n global.uidHolder.entry[_stackApiKey][_contentTypeData.content_type.uid].push(_entryData.entry.uid);\n return _eDone(null, _entryData);\n })\n }, _cDone)\n })\n }, _stackCreationCompletionCb)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that getCountriesByE164Code works correctly if multiple entries have the same e164_cc code. | function testGetCountriesByE164Code_multipleMatches() {
var countries = firebaseui.auth.data.country.getCountriesByE164Code('44');
var actualKeys = countries.map(function(country) {
return country.e164_key;
});
assertSameElements(['44-GG-0', '44-IM-0', '44-JE-0', '44-GB-0'], actualKeys);
} | [
"function testGetCountriesByIso2_multipleMatches() {\n var countries = firebaseui.auth.data.country.getCountriesByIso2('xk');\n var actualCodes = countries.map(function(country) {\n return country.e164_cc;\n });\n assertSameElements(['377', '381', '386'], actualCodes);\n}",
"function getCountryNames(){\n for(let i = 0; i < country_info[\"ref_country_codes\"].length; i++){\n let country = country_info[\"ref_country_codes\"][i][\"country\"];\n countryNames.push(country);\n countryCodes[country] = country_info[\"ref_country_codes\"][i][\"alpha2\"];\n }\n}",
"function assertStateCode(code) {\n if (![\"\", \"at\", \"be\", \"bg\", \"ch\", \"cy\", \"cz\", \"de\", \"dk\", \"ee\", \"es\", \"fi\", \"fr\",\n \"gb\", \"gr\", \"hr\", \"hu\", \"ie\", \"is\", \"it\", \"li\", \"lt\", \"lu\", \"lv\", \"mt\",\n \"nl\", \"no\", \"pl\", \"pt\", \"ro\", \"se\", \"si\", \"sk\", \"tr\", \"mk\"].includes(code)) {\n throw(\"Invalid country code \\\"\" + code + \"\\\".\");\n }\n}",
"function e164(value, country_code, metadata)\n{\n\tif (!value)\n\t{\n\t\treturn undefined\n\t}\n\n\t// If the phone number is being input in an international format\n\tif (value[0] === '+')\n\t{\n\t\t// If it's just the `+` sign\n\t\tif (value.length === 1)\n\t\t{\n\t\t\treturn undefined\n\t\t}\n\n\t\t// If there are some digits, the `value` is returned as is\n\t\treturn value\n\t}\n\n\t// For non-international phone number a country code is required\n\tif (!country_code)\n\t{\n\t\treturn undefined\n\t}\n\n\t// The phone number is being input in a country-specific format\n\n\tconst partial_national_number = parse_partial_number(value, country_code).national_number\n\n\tif (!partial_national_number)\n\t{\n\t\treturn undefined\n\t}\n\n\t// The value is converted to international plaintext\n\treturn format(partial_national_number, country_code, 'International_plaintext', metadata)\n}",
"function get_country_id(country) {\n\tfor(var i = 0; i < country_codes.length; i++) {\n\t\tvar current_country = country_codes[i][2];\n\t\tif(country == current_country) {\n\t\t\treturn country_codes[i][0];\n\t\t};\n\t\t/*\n\t\t * Alternative: Split the country name on whitespace to obtain the\n\t\t * individual words. Then check if all those words occur in the\n\t\t * name of the current country ('current_country'). If so, return the\n\t\t * ID of the current country. Continue otherwise.\n\t\t *\n\t\t * This works in most cases, but not always, for example:\n\t\t *\n\t\t * \"Russia\" matches with \"Russian Federation\", correct.\n\t\t * \"Iran\" matches with \"Iran, Islamic Republic of\", correct.\n\t\t * \"Guinea\" matches with \"Equatorial Guinea\", correct.\n\t\t * \"India\" matches with \"British Indian Ocean Territory\", incorrect.\n\t\t * \"Bonaire\", \"Sint Eustatius\", and \"Saba\" all match with \"Bonaire, Sint Eustatius and Saba\", incorrect.\n\t\t *\n\t\t * Since the alternative does not always work, it was left out. \n\t\t */\n\t\t// country_words = country.split(\" \");\n\t\t// var match = true;\n\t\t// for(var j = 0; j < country_words.length; j++) {\n\t\t// \tif(current_country.indexOf(country_words[j]) == -1) {\n\t\t// \t\tmatch = false;\n\t\t// \t\tbreak;\n\t\t// \t}\n\t\t// };\n\t\t// if(match) {\n\t\t// \tconsole.log(\"Country: \" + country + \"; Match: \" + country_codes[i][2] + \"; Country code: \" + country_codes[i][0]);\n\t\t// \treturn country_codes[i][0];\n\t\t// }\n\t};\n\treturn undefined;\n}",
"function loadCasesComfirmed(data){\r\n\tcasesComfirmed.push(data); \r\n}",
"function getCountryFromRegionsMap(country) {\n for (var r in regionsMap) {\n var region = regionsMap[r];\n\n var countryCurrency = getCountryFromRegion(region, country);\n\n if (countryCurrency) {\n return countryCurrency;\n }\n }\n\n return null;\n}",
"async function checkForValidIndAndCo(ind, co) {\n const indResult = await db.query(`SELECT code FROM industries`);\n const industries = indResult.rows.map(val => val.code);\n\n const compResult = await db.query(`SELECT code FROM companies`);\n const companies = compResult.rows.map(val => val.code);\n\n if (!(industries.includes(ind) && companies.includes(co))) {\n throw new ExpressError('Please enter valid industry and company codes!', 400);\n }\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}",
"getTranslatedEnums() {\n if (this.translatedEnumCache) {\n return this.translatedEnumCache;\n }\n\n let result = map(this.rule.in || [], (value) => {\n let translated;\n if (\n this.rule.fieldName === this.FIELD_NAME_LIST.area &&\n this.newAccountForm.model.country\n ) {\n translated = this.$translate.instant(\n `signup_enum_${this.newAccountForm.model.country}_${this.rule.fieldName}_${value}`,\n );\n } else if (this.rule.fieldName === this.FIELD_NAME_LIST.timezone) {\n translated = value;\n } else if (this.rule.fieldName === this.FIELD_NAME_LIST.managerLanguage) {\n translated = get(find(LANGUAGES.available, { key: value }), 'name');\n } else {\n translated = this.$translate.instant(\n `signup_enum_${this.rule.fieldName}_${value}`,\n );\n }\n return {\n key: value,\n translated,\n };\n });\n\n result = this.$filter('orderBy')(\n result,\n 'translated',\n this.rule.fieldName === this.FIELD_NAME_LIST.phoneType,\n (a, b) => String(a.value).localeCompare(String(b.value)),\n );\n\n // if there is only a single value, auto select it\n if (\n result.length === 1 &&\n this.value !== head(result).key &&\n !this.autoSelectPending\n ) {\n this.autoSelectPending = true;\n this.value = head(result);\n this.$timeout(() => {\n this.onChange();\n this.autoSelectPending = false;\n });\n }\n\n this.translatedEnumCache = result;\n return result;\n }",
"function casesByCountry (){\n\n let today = dateToday();\n let endPoint = 'https://api.covid19tracking.narrativa.com/api/' \n let queryCountriesUrl = endPoint + today; \n let URL = {\n url: queryCountriesUrl,\n method: \"GET\" \n } \n\n // making request to pull all Covid data by countries\n $.ajax(URL).then(function(response){\n countriesData(response.dates[today].countries); \n });\n}",
"function data_cleaning_countries_name(suicideData, countriesJson) {\n let all_countries_in_cjson = _.uniqBy(countriesJson.features, 'properties.name');\n for (let c of all_countries_in_cjson) {\n let currentCjsonCountry = c.properties.name;\n let entry = _.filter(suicideData, function(d) {\n\n if (d.country.indexOf(currentCjsonCountry) != -1) {\n d.country = currentCjsonCountry;\n }\n });\n }\n\n let all_countries_in_sjson = _.uniqBy(suicideData, 'country');\n for (let i of all_countries_in_sjson) {\n let currentSjsonCountry = i.country;\n let entry = _.filter(countriesJson.features, function(d) {\n\n if (d.properties.name.indexOf(currentSjsonCountry) != -1) {\n d.properties.name = currentSjsonCountry;\n }\n });\n }\n}",
"function checkCountryResultTelemetry(aExpectedValue) {\n let histogram = Services.telemetry.getHistogramById(\"SEARCH_SERVICE_COUNTRY_FETCH_RESULT\");\n let snapshot = histogram.snapshot();\n // The probe is declared with 8 values, but we get 9 back from .counts\n let expectedCounts = [0,0,0,0,0,0,0,0,0];\n if (aExpectedValue != null) {\n expectedCounts[aExpectedValue] = 1;\n }\n deepEqual(snapshot.counts, expectedCounts);\n}",
"async _validateCountry(countryDef) {\n if (!this._valid(countryDef)) return false;\n\n // countryId overrides country, because countryId is indexed whereas country is not!\n let referenceCountry = null;\n if (countryDef.countryId) {\n referenceCountry = await models.country.findOne({\n where: {\n id: countryDef.countryId\n },\n attributes: ['id', 'country'],\n });\n } else {\n referenceCountry = await models.country.findOne({\n where: {\n country: countryDef.country\n },\n attributes: ['id', 'country'],\n });\n }\n\n if (referenceCountry && referenceCountry.id) {\n // found a country match\n return {\n countryId: referenceCountry.id,\n country: referenceCountry.country\n };\n } else {\n return false;\n }\n }",
"function filterCountries(countries, includedCountryCodes) {\n if (!includedCountryCodes) {\n return countries;\n }\n\n return countries.filter((country) => {\n return includedCountryCodes.indexOf(country.code) !== -1;\n });\n}",
"async validateCouponCode(code) {\n let response = await axios.getCatalog(\"http://127.0.0.1:5000/api/couponCodes/\" + code);\n return response.data;\n }",
"function updateCultures(choosenEventName) {\n\t\t\tfor (var i=0; i<cultures.length; i++) {\n\t\t if ( hasEvent(cultures[i].events, choosenEventName)) {\n\t\t markCulture(i);\n\t\t }\n\t\t }\n\t\t}",
"function verifyCodesSame()\n{\n gebi('makechange').disabled = true;\n var codeOne = gebi('pscd').value;\n var codeTwo = gebi('pscd2').value;\n if ((codeOne == codeTwo) && codeOne != \"\")\n {\n gebi('makechange').disabled = false;\n }\n}",
"function validCountryProvided(c) {\n return typeof c === 'string' && c.length < 501;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To keep things simple, series ['cpu','memory','disk'] have been assumed Create graph using Chart.JS. Inserts html needed into page, creates JSON object and initializes graph | function createGraph(canvas){
var data={};
data["labels"]=[];
data["datasets"]=[];
var data_array=[];
for (var i=0; i<20; i++){
data.labels.push("");
data_array.push(0);
}
var categories = ['cpu','memory','disk'];
var colors = ['#f44336','#3f51b5','#4caf50']
for (var i = 0; i < categories.length; i++) { //repeat for each series
var seriesData = {
fill: false,
lineTension: 0.3,
backgroundColor: colors[i],
borderColor: colors[i],
borderCapStyle: 'butt',
borderJoinStyle: 'miter',
pointBorderColor: colors[i],
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointRadius: 1,
data: data_array };
seriesData.label = categories[i]; //set label
data.datasets.push(JSON.parse(JSON.stringify(seriesData))); //make a copy
};
var lineChart = new Chart(canvas, {
type: 'line',
data: data,
options: {
scales: {
yAxes: [{
ticks: { //set scale 0-100 as showing percentage
max: 100,
min: 0,
stepSize: 10
}
}]
}
}
});
return lineChart;
} | [
"createGraph (){\n let selector = document.getElementById('container-graph');\n let html = '';\n let array = this.arrayDataObjects;\n for (let key in array) {\n this.createElementGraph(selector, `chart-${key}`);\n let title = array[key].title;\n let total = array[key].total;\n let items = array[key].items;\n for (let i in items) {\n this.labels.push(items[i].name);\n this.data.push(items[i].quantity);\n this.colors.push(items[i].color);\n this.createElementInfo(document.getElementById(`container-chart-${key}`), items[i].name, items[i].quantity, items[i].percent, items[i].color);\n }\n this.canvasGraph(this.labels, this.data, `chart-${key}`, this.colors);\n this.labels = [];\n this.data = [];\n this.colors = [];\n }\n\n }",
"function build_run_chart(N, js, php, php_mt, online) {\n load_chart('chart', {\n title: {\n text: \"Random generators runs\"\n },\n yAxis: {\n title: {\n text: \"runs on \" + N + \" numbers\"\n }\n },\n series: [{\n name: 'Generators',\n colorByPoint: true,\n data: [{\n name: 'JS Math.random()',\n y: js,\n drilldown: 'JS Math.random()'\n }, {\n name: 'PHP rand()',\n y: php,\n drilldown: 'PHP rand()'\n }, {\n name: 'PHP mt_rand()',\n y: php_mt,\n drilldown: 'PHP mt_rand()'\n }, {\n name: 'Online random.org',\n y: online,\n drilldown: 'Online random.org'\n }]\n }],\n tooltip: {\n headerFormat: \"<span style=\\\"font-size:11px\\\">{series.name}</span><br>\",\n pointFormat: \"<span style=\\\"color:{point.color}\\\">{point.name}</span> runs<br/>\"\n }\n });\n}",
"function fillJsonDataTimeseries(financeDataJson, _div_id, _text_id) {\n\n var financeData = toDataJsonTimeseries(financeDataJson, true);\n var container = document.getElementById(_div_id), options;\n\n $('#' + _text_id).text(financeDataJson.dataset.name + \":\");\n\n options = {\n container : container,\n data : {\n detail : financeData.price,\n summary : financeData.price\n },\n // An initial selection\n selection : {\n data : {\n x : {\n min : 100,\n max : 200\n }\n }\n }\n };\n\n chart = new envision.templates.TimeSeries(options);\n\n window.onresize = function (event) {\n chart.vis.components.forEach(function(component){\n component.draw();\n $(\".envision-timeseries-connection\").find(\"canvas\").hide();\n $('#' + _div_id).css(\"background\",\"none\");\n });\n };\n \n}",
"function createChart(cls, title, container, series_names) {\n var chart,\n date = [], // Stores the dates as categories for the xAxis\n months = [\"Janvier\", \"Février\", \"Mars\", \"Avril\", \"Mai\", \"Juin\", \"Juillet\", \"Août\",\n \"Septembre\", \"Octobre\", \"Novembre\", \"Décembre\"];\n \n $(document).ready(function() {\n $.getJSON(\"~/../ajax.php?class=\"+ cls, function(data) {\n\n // Load all the existent series\n function loadSeries()\n {\n for(var i = 2, j = 0; i < data.length, j < series_names.length; i++, j++)\n {\n chart.addSeries({name: series_names[j], data : data[i]});\n }\n }\n\n // Format the date in the xAxis\n for(var i = 0; i < data[0].length; i++)\n {\n date.push(months[data[1][i] - 1] + ' ' + data[0][i]);\n }\n\n // Convert all the elements of the series to Integers since we get Strings \n for(i = 2; i < data.length; i++)\n {\n convertToInt(data[i]);\n }\n\n // Create the chart\n chart = new Highcharts.Chart({\n chart: {\n renderTo: container,\n type: 'spline',\n events: { \n load: function() {\n chart = this;\n loadSeries();\n }\n },\n plotBorderWidth: 1,\n plotBorderColor: '#3F4044',\n marginTop: 10,\n marginRight: 0,\n spacingLeft: 30,\n spacingBottom: 0\n },\n title: {\n text: title\n },\n subtitle: {\n text: 'Depuis ' + date[0]\n },\n xAxis: {\n title: {\n text: 'Date'\n },\n categories: date, // This is the dates array\n tickInterval: 1,\n gridLineDashStyle: 'dot',\n gridLineWidth: 1,\n lineWidth: 2,\n lineColor: '#92A8CD',\n tickWidth: 3,\n tickLength: 6,\n tickColor: '#92A8CD'\n },\n yAxis: {\n title: {\n text: 'Nombre'\n },\n min: 0,\n gridLineColor: \"#8AB8E6\",\n alternateGridColor: {\n linearGradient: {\n x1: 0, y1: 1,\n x2: 1, y2: 1\n },\n stops: [ [0, '#FAFCFF'],\n [0.5, '#F5FAFF'],\n [0.8, '#E0F0FF'],\n [1, '#D6EBFF'] ]\n },\n lineWidth: 2,\n lineColor: '#92A8CD',\n tickWidth: 3,\n tickLength: 6,\n tickColor: '#92A8CD'\n },\n tooltip : {\n crosshairs: [{\n color: '#8D8D8D',\n dashStyle: 'dash'\n }, {\n color: '#8D8D8D',\n dashStyle: 'dash'\n }],\n formatter: function() {\n return '<span style=\"color:#039;font-weight:bold\">' + this.point.category + \n '</span><br/><span style=\"color:' + this.series.color + '\">' +\n this.series.name + '</span>: <span style=\"color:#D15600;font-weight:bold\">' + \n this.point.y + '</span>';\n }\n }, \n plotOptions: {\n series: {\n lineWidth: 2\n }\n },\n series: []\n });\n });\n \n // Convert to Integers\n function convertToInt(array) {\n for(var i = 0; i < array.length; i++)\n {\n array[i] = parseInt(array[i], 10);\n }\n }\n });\n}",
"init() {\n const series = this.chartData.series;\n const seriesKeys = Object.keys(series);\n\n for (let ix = 0, ixLen = seriesKeys.length; ix < ixLen; ix++) {\n this.addSeries(seriesKeys[ix], series[seriesKeys[ix]]);\n }\n\n if (this.chartData.data.length) {\n this.createChartDataSet();\n }\n }",
"function loadSeries()\n {\n for(var i = 2, j = 0; i < data.length, j < series_names.length; i++, j++)\n {\n chart.addSeries({name: series_names[j], data : data[i]});\n }\n }",
"function generateCharts () {\n\tgenerateTemperatureChart();\n\tgenerateQPFChart();\n\tgenerateDailyWeatherChart($('#weatherChartDays'), 1, 7); //Also reused by zone available water\n\tgenerateProgramsChart();\n\tbindChartsSyncToolTipEvents();\n}",
"function createChart(quantity) {\n\treturn new Highcharts.Chart({\n\t\tchart : {\n\t\t\trenderTo : 'container',\n\t\t\tdefaultSeriesType : 'bar',\n\t\t\tevents : {\n\t\t\t\tload : updateChart(quantity)\n\t\t\t}\n\t\t},\n\t\tcredits : {\n\t\t\tenabled : true,\n\t\t\thref : \"http://nest.lbl.gov/products/spade/\",\n\t\t\ttext : 'Spade Data Management'\n\t\t},\n\t\ttitle : {\n\t\t\ttext : 'Total Counts for SPADE'\n\t\t},\n\t\tsubtitle : {\n\t\t\ttext : 'Loading ...'\n\t\t},\n\t\txAxis : {\n\t\t\ttitle : {\n\t\t\t\ttext : 'Activity',\n\t\t\t\tstyle : {\n\t\t\t\t\tcolor : Highcharts.theme.colors[0]\n\t\t\t\t}\n\t\t\t},\n\t\t\tlabels : {\n\t\t\t\tstyle : {\n\t\t\t\t\tminWidth : '140px'\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tyAxis : [ {\n\t\t\ttitle : {\n\t\t\t\ttext : 'counts',\n\t\t\t\tstyle : {\n\t\t\t\t\tcolor : Highcharts.theme.colors[0]\n\t\t\t\t}\n\t\t\t},\n\t\t\tlabels : {\n\t\t\t\tstyle : {\n\t\t\t\t\tcolor : Highcharts.theme.colors[0]\n\t\t\t\t}\n\t\t\t}\n\t\t}],\n\t\tseries : [ {\n\t\t\tname : 'suspended'\n\t\t}, {\n\t\t\tname : 'pending'\n\t\t}, {\n\t\t\tname : 'executing'\n\t\t}, {\n\t\t\tname : 'total'\n\t\t} ]\n\t});\n}",
"function createChart() {\n getSettings();\n $scope.chart = picasso.chart({\n element: $element.find('.adv-kpi-chart')[0],\n data: ds,\n settings: picassoSettings,\n beforeRender() { qlik.resize(); }\n });\n }",
"function sparkline_charts() {\r\n\t\t\t$('.sparklines').sparkline('html');\r\n\t\t}",
"function createLiveChart(){ \n\t\tchart = new Highcharts.Chart({\n\t\t\tchart: {\n\t\t\t\trenderTo: 'live',\n\t\t\t\tzoomType: 'x', \n\t\t\t\tdefaultSeriesType: 'spline',\n\t\t\t\tevents: {\n\t\t\t\t\tload: requestLiveData\n\t\t\t\t}\n\t\t\t}, \n\t\t\tcredits: {\n\t\t\t\tenabled: false\n\t\t\t},\n\t\t\tlegend: {\n\t\t\t\tenabled: false\n\t\t\t},\t\t \n\t\t\t//title: {text: title},\n\t\t\tyAxis: {\n\t\t\t\tlabels:{\n\t\t\t\t\talign:'left',\n\t\t\t\t\tx:10\n\t\t\t\t}, \n\t\t\t\ttitle: {\n\t\t\t\t\ttext: ''\n\t\t\t\t},\n\t\t\t\topposite: true, \n\t\t\t\tshowFirstLabel: false\n\t\t\t}, \n\t\t\txAxis: {\n\t\t\t\ttype: 'datetime',\n\t\t\t\ttickPixelInterval: 150\n\t\t\t},\n\t\t\ttooltip: {\n\t\t\t\tshared: true,\n\t\t\t\tuseHTML: true,\n\t\t\t\tbackgroundColor: '#FFFFFF',\n\t\t\t\tborderColor: '#EEEEEE',\n\t\t\t\txDateFormat: '%H:%M:%S', \n\t\t\t\theaderFormat: '<div class=\"chart_tooltip_header\">{point.key}</div><table class=\"chart_tooltip_table\"><thead><tr><th>Consumption</th></tr></thead>',\n\t\t\t\tpointFormat: '<tbody><tr><td class=\"chart_tooltip_name\" style=\"color: {series.color}\">\\u25A0 {series.name}: </td>' +\n\t\t\t\t\t\t\t '<td class=\"chart_tooltip_value\">{point.y}</td></tr>',\n\t\t\t\tfooterFormat: '</tbody></table>',\n\t\t\t\tvalueSuffix: ' Watt', \n\t\t\t\tcrosshairs: [{\n\t\t\t\t\twidth: 1,\n\t\t\t\t\tdashStyle: 'solid',\n\t\t\t\t\tcolor: '#eeeeee'\n\t\t\t\t}] \n\t\t\t}, \n\t\t\tseries: [{\n\t\t\t\tname: 'Power usage',\n\t\t\t\tdata: [],\n\t\t\t\tmarker: {radius: 2}\n\t\t\t}],\n\t\t\texporting: {\n\t\t\t\tenabled: false\n\t\t\t}\t\t\n\t\t}); \n\t}",
"function chartDataCreator() {\n for (var i = 0; i < products.length; i++) {\n chartData.push(products[i].votes);\n chartData.push(products[i].views);\n }\n}",
"function initCharts() {\n xmlHttpReq('GET', '/storages_data', '', function(responseText) {\n var response = JSON.parse(responseText);\n if (response.success) {\n drawCharts(response.data);\n } else {\n snackbar(response.message);\n }\n });\n}",
"function createChart(element_selector, params)\n{\n title_position = 0;\n // Анализируем входные параметры\n //--------------------------------------------------------------------------\n // 1. Формируем параметры запросов\n requestParams.instrument_id = params.histo.instrument_id;\n requestParams.price_id = params.id;\n //--------------------------------------------------------------------------\n dim = {\n width: 640, height: 480,\n margin: { top: 20, right: 50, bottom: 30, left: 50 },\n ohlc: { height: 305 },\n indicator: { height: 65, padding: 5 }\n };\n\n // Подключаемся к DIV\n // и берем размеры у него\n // Высоты графиков:\n // *candle - 74%\n // *macd - 13%\n // *rsi - 13%\n div = d3.select(element_selector);\n dim.width = parseInt(div.style(\"width\"));\n dim.height = parseInt(div.style(\"height\"));\n dim.ohlc.height = dim.height - (dim.indicator.height*2) - (dim.margin.top*2) - (dim.indicator.padding);\n\n dim.plot = {\n width: dim.width - dim.margin.left - dim.margin.right,\n height: dim.height - dim.margin.top - dim.margin.bottom\n };\n dim.indicator.top = dim.ohlc.height+dim.indicator.padding;\n dim.indicator.bottom = dim.indicator.top+dim.indicator.height+dim.indicator.padding;\n\n // Рисуем график по всей высоте\n if ((chartOptions.macdVisible == false) && (chartOptions.rsiVisible == false))\n {\n dim.ohlc.height = dim.height - (dim.margin.top*2) - (dim.indicator.padding);\n } else\n if (((chartOptions.macdVisible == true) && (chartOptions.rsiVisible == false)) ||\n ((chartOptions.macdVisible == false) && (chartOptions.rsiVisible == true)))\n {\n dim.indicator.height = dim.indicator.height*2;\n }\n\n indicatorTop = d3.scaleLinear()\n .range([dim.indicator.top, dim.indicator.bottom]);\n\n// parseDate = d3.timeParse(\"%d-%b-%y\");\n // Преобразование даты и времени из формата\n // \"YYYYMMDDHHMM\" в нужный формат для графика\n// parseDate = d3.timeParse(\"%Y%m%d%H%M%Z\");\n\n zoom = d3.zoom()\n .on(\"zoom\", zoomed);\n\n x = techan.scale.financetime()\n .range([0, dim.plot.width]);\n\n y = d3.scaleLinear()\n .range([dim.ohlc.height, 0]);\n\n\n yPercent = y.copy(); // Same as y at this stage, will get a different domain later\n\n yVolume = d3.scaleLinear()\n .range([y(0), y(0.2)]);\n\n // Настраиваем тип графика(OHLC, Candle, ...)\n switch(chartOptions.type)\n {\n case 0:\n candlestick = techan.plot.ohlc()\n .xScale(x)\n .yScale(y);\n break;\n case 1:\n candlestick = techan.plot.candlestick()\n .xScale(x)\n .yScale(y);\n break;\n case 2:\n candlestick = techan.plot.close()\n .xScale(x)\n .yScale(y);\n }\n/* candlestick = techan.plot.candlestick()\n .xScale(x)\n .yScale(y);\n*/\n sma0 = techan.plot.sma()\n .xScale(x)\n .yScale(y);\n\n sma1 = techan.plot.sma()\n .xScale(x)\n .yScale(y);\n\n ema2 = techan.plot.ema()\n .xScale(x)\n .yScale(y);\n\n volume = techan.plot.volume()\n .accessor(candlestick.accessor()) // Set the accessor to a ohlc accessor so we get highlighted bars\n .xScale(x)\n .yScale(yVolume);\n\n trendline = techan.plot.trendline()\n .xScale(x)\n .yScale(y);\n\n supstance = techan.plot.supstance()\n .xScale(x)\n .yScale(y);\n\n xAxis = d3.axisBottom(x);\n\n // Курсор по оси OX (текст)\n timeAnnotation = techan.plot.axisannotation()\n .axis(xAxis)\n .orient('bottom')\n .format(d3.timeFormat('%Y-%m-%d'))\n .width(65)\n .translate([0, dim.ohlc.height]);\n\n yAxis = d3.axisRight(y);\n\n ohlcAnnotation = techan.plot.axisannotation()\n .axis(yAxis)\n .orient('right')\n .format(d3.format(',.2f'))\n .translate([x(1), 0]);\n\n closeAnnotation = techan.plot.axisannotation()\n .axis(yAxis)\n .orient('right')\n .accessor(candlestick.accessor())\n .format(d3.format(',.2f'))\n .translate([x(1), 0]);\n\n percentAxis = d3.axisLeft(yPercent)\n .tickFormat(d3.format(\"+.1%\"));\n\n\n percentAnnotation = techan.plot.axisannotation()\n .axis(percentAxis)\n .orient('left');\n\n volumeAxis = d3.axisRight(yVolume)\n .ticks(3)\n .tickFormat(d3.format(\",.3s\"));\n\n volumeAnnotation = techan.plot.axisannotation()\n .axis(volumeAxis)\n .orient(\"right\")\n .width(35);\n//------------------------------------------------------------------------------\nvar index=0;\n// 1. Включены оба графика\nif ((chartOptions.macdVisible == true) && (chartOptions.rsiVisible == true))\n{\n index = 1;\n} else\n// 2. Выключен график RSI\nif ((chartOptions.macdVisible == true) && (chartOptions.rsiVisible == false))\n{\n index = 1;\n} else\n// 3. Выключен график MACD\nif ((chartOptions.macdVisible == false) && (chartOptions.rsiVisible == true))\n{\n index = 0;\n} else\n// 4. Выключены оба графика\nif ((chartOptions.macdVisible == false) && (chartOptions.rsiVisible == false))\n{\n index = 1;\n}\n macdScale = d3.scaleLinear()\n .range([indicatorTop(0)+dim.indicator.height, indicatorTop(0)]);\n\n rsiScale = d3.scaleLinear()//macdScale.copy()\n .range([indicatorTop(index)+dim.indicator.height, indicatorTop(index)]);\n//------------------------------------------------------------------------------\n/* macdScale = d3.scaleLinear()\n .range([indicatorTop(0)+dim.indicator.height, indicatorTop(0)]);\n\n rsiScale = d3.scaleLinear()\n .range([indicatorTop(0)+dim.indicator.height, indicatorTop(0)]);\n*/\n macd = techan.plot.macd()\n .xScale(x)\n .yScale(macdScale);\n\n macdAxis = d3.axisRight(macdScale)\n .ticks(3);\n\n macdAnnotation = techan.plot.axisannotation()\n .axis(macdAxis)\n .orient(\"right\")\n .format(d3.format(',.2f'))\n .translate([x(1), 0]);\n\n macdAxisLeft = d3.axisLeft(macdScale)\n .ticks(3);\n\n macdAnnotationLeft = techan.plot.axisannotation()\n .axis(macdAxisLeft)\n .orient(\"left\")\n .format(d3.format(',.2f'));\n\n rsi = techan.plot.rsi()\n .xScale(x)\n .yScale(rsiScale);\n\n rsiAxis = d3.axisRight(rsiScale)\n .ticks(3);\n\n rsiAnnotation = techan.plot.axisannotation()\n .axis(rsiAxis)\n .orient(\"right\")\n .format(d3.format(',.2f'))\n .translate([x(1), 0]);\n\n rsiAxisLeft = d3.axisLeft(rsiScale)\n .ticks(3);\n\n rsiAnnotationLeft = techan.plot.axisannotation()\n .axis(rsiAxisLeft)\n .orient(\"left\")\n .format(d3.format(',.2f'));\n\n ohlcCrosshair = techan.plot.crosshair()\n .xScale(timeAnnotation.axis().scale())\n .yScale(ohlcAnnotation.axis().scale())\n .xAnnotation(timeAnnotation)\n .yAnnotation([ohlcAnnotation, volumeAnnotation])\n// .yAnnotation([ohlcAnnotation, percentAnnotation, volumeAnnotation])\n .verticalWireRange([0, dim.plot.height]);\n\n macdCrosshair = techan.plot.crosshair()\n .xScale(timeAnnotation.axis().scale())\n .yScale(macdAnnotation.axis().scale())\n .xAnnotation(timeAnnotation)\n .yAnnotation([macdAnnotation, macdAnnotationLeft])\n .verticalWireRange([0, dim.plot.height]);\n\n rsiCrosshair = techan.plot.crosshair()\n .xScale(timeAnnotation.axis().scale())\n .yScale(rsiAnnotation.axis().scale())\n .xAnnotation(timeAnnotation)\n .yAnnotation([rsiAnnotation, rsiAnnotationLeft])\n .verticalWireRange([0, dim.plot.height]);\n\n svg = div.append(\"svg\")\n .attr(\"width\", dim.width)\n .attr(\"height\", dim.height);\n\n draw_percent_bar(pbar_value);\n\n defs = svg.append(\"defs\");\n\n//-----------------------------------------------------------------------------------\n defs.append(\"clipPath\")\n .attr(\"id\", \"ohlcClip\")\n .append(\"rect\")\n .attr(\"x\", 0)\n .attr(\"y\", 0)\n .attr(\"width\", dim.plot.width)\n .attr(\"height\", dim.ohlc.height);\n//------------------------------------------------------------------------------\n// 1. Включены оба графика\nif ((chartOptions.macdVisible == true) && (chartOptions.rsiVisible == true))\n{\n defs.selectAll(\"indicatorClip\").data([0, 1])\n .enter()\n .append(\"clipPath\")\n .attr(\"id\", function(d, i) { return \"indicatorClip-\" + i; })\n .append(\"rect\")\n .attr(\"x\", 0)\n .attr(\"y\", function(d, i) { return indicatorTop(i); })\n .attr(\"width\", dim.plot.width)\n .attr(\"height\", dim.indicator.height);\n} else\n// 2. Выключен график RSI\nif ((chartOptions.macdVisible == true) && (chartOptions.rsiVisible == false))\n{\n defs.selectAll(\"indicatorClip\").data([0, 1])\n .enter()\n .append(\"clipPath\")\n .attr(\"id\", function(d, i) { return \"indicatorClip-\" + i; })\n .append(\"rect\")\n .attr(\"x\", 0)\n .attr(\"y\", function(d, i) { return indicatorTop(i); })\n .attr(\"width\", dim.plot.width)\n .attr(\"height\", dim.indicator.height);\n} else\n// 3. Выключен график MACD\nif ((chartOptions.macdVisible == false) && (chartOptions.rsiVisible == true))\n{\n defs.selectAll(\"indicatorClip\").data([0, 1])\n .enter()\n .append(\"clipPath\")\n .attr(\"id\", function(d, i) { return \"indicatorClip-\" + i; })\n .append(\"rect\")\n .attr(\"x\", 0)\n .attr(\"y\", function(d, i) { return indicatorTop(0); })\n .attr(\"width\", dim.plot.width)\n .attr(\"height\", dim.indicator.height);\n} else\n// 4. Выключены оба графика\nif ((chartOptions.macdVisible == false) && (chartOptions.rsiVisible == false))\n{\n defs.selectAll(\"indicatorClip\").data([0, 1])\n .enter()\n .append(\"clipPath\")\n .attr(\"id\", function(d, i) { return \"indicatorClip-\" + i; })\n .append(\"rect\")\n .attr(\"x\", 0)\n .attr(\"y\", function(d, i) { return indicatorTop(i); })\n .attr(\"width\", dim.plot.width)\n .attr(\"height\", dim.indicator.height);\n}\n\n\n//------------------------------------------------------------------------------\n svg = svg.append(\"g\")\n .attr(\"transform\", \"translate(\" + dim.margin.left + \",\" + dim.margin.top + \")\");\n\n // Формируем название графика\n draw_title();\n // Рисуем горизонтальную сетку\n for (var i=1; i<(dim.ohlc.height/chartOptions.grid_x_step); i++)\n {\n svg.append('line')\n .attr(\"class\", \"grid\")\n .attr(\"x1\", 0)\n .attr(\"y1\", (i*chartOptions.grid_x_step + 0.5))\n .attr(\"x2\", (dim.width - 100))\n .attr(\"y2\", (i*chartOptions.grid_x_step + 0.5));\n }\n\n // Рисуем вертикальную сетку\n for (var i=0; i<((dim.width-100)/chartOptions.grid_y_step); i++)\n {\n svg.append('line')\n .attr(\"class\", \"grid\")\n .attr(\"x1\", (i*chartOptions.grid_y_step))\n .attr(\"y1\", 0)\n .attr(\"x2\", (i*chartOptions.grid_y_step))\n .attr(\"y2\", dim.ohlc.height);\n }\n\n // Рисуем ось OX(Дата и время)\n svg.append(\"g\")\n .attr(\"class\", \"x axis\")\n .attr(\"transform\", \"translate(0,\" + dim.ohlc.height + \")\");\n\n ohlcSelection = svg.append(\"g\")\n .attr(\"class\", \"ohlc\")\n .attr(\"transform\", \"translate(0,0)\");\n\n ohlcSelection.append(\"g\")\n .attr(\"class\", \"axis\")\n .attr(\"transform\", \"translate(\" + x(1) + \",0)\")\n .append(\"text\")\n .attr(\"transform\", \"rotate(-90)\")\n .attr(\"y\", -12)\n .attr(\"dy\", \".71em\")\n .style(\"text-anchor\", \"end\")\n .text(chartOptions.title_y);\n\n ohlcSelection.append(\"g\")\n .attr(\"class\", \"close annotation up\");\n\n ohlcSelection.append(\"g\")\n .attr(\"class\", \"volume\")\n .attr(\"clip-path\", \"url(#ohlcClip)\");\n\n ohlcSelection.append(\"g\")\n .attr(\"class\", \"candlestick\")\n .attr(\"clip-path\", \"url(#ohlcClip)\");\n\n ohlcSelection.append(\"g\")\n .attr(\"class\", \"indicator sma ma-0\")\n .attr(\"clip-path\", \"url(#ohlcClip)\");\n\n ohlcSelection.append(\"g\")\n .attr(\"class\", \"indicator sma ma-1\")\n .attr(\"clip-path\", \"url(#ohlcClip)\");\n\n ohlcSelection.append(\"g\")\n .attr(\"class\", \"indicator ema ma-2\")\n .attr(\"clip-path\", \"url(#ohlcClip)\");\n\n ohlcSelection.append(\"g\")\n .attr(\"class\", \"percent axis\");\n\n ohlcSelection.append(\"g\")\n .attr(\"class\", \"volume axis\");\n\n indicatorSelection = svg.selectAll(\"svg > g.indicator\").data([\"macd\", \"rsi\"]).enter()\n .append(\"g\")\n .attr(\"class\", function(d) { return d + \" indicator\"; });\n\n indicatorSelection.append(\"g\")\n .attr(\"class\", \"axis right\")\n .attr(\"transform\", \"translate(\" + x(1) + \",0)\");\n\n indicatorSelection.append(\"g\")\n .attr(\"class\", \"axis left\")\n .attr(\"transform\", \"translate(\" + x(0) + \",0)\");\n\n indicatorSelection.append(\"g\")\n .attr(\"class\", \"indicator-plot\")\n .attr(\"clip-path\", function(d, i) { return \"url(#indicatorClip-\" + i + \")\"; });\n\n // Add trendlines and other interactions last to be above zoom pane\n svg.append('g')\n .attr(\"class\", \"crosshair ohlc\");\n/*\n svg.append(\"g\")\n .attr(\"class\", \"tradearrow\")\n .attr(\"clip-path\", \"url(#ohlcClip)\");\n*/\n svg.append('g')\n .attr(\"class\", \"crosshair macd\");\n\n svg.append('g')\n .attr(\"class\", \"crosshair rsi\");\n\n svg.append(\"g\")\n .attr(\"class\", \"trendlines analysis\")\n .attr(\"clip-path\", \"url(#ohlcClip)\");\n/* svg.append(\"g\")\n .attr(\"class\", \"supstances analysis\")\n .attr(\"clip-path\", \"url(#ohlcClip)\");*/\n\n// d3.select(\"button\").on(\"click\", reset);\n}",
"function Network_networkOverview() {\n UCapManager.startScheduler({func:'Network_Overview_householdUsage', scope:\"element\", freq:1000});\n var dataArray = [];\n for (var i in UCapCore.devices)\n { for(var j = 0, k = UCapCore.devices[i].length; j < k; j++){\n var devicename = UCapCore.devices[i][j][1];\n var deviceusage = (UCapCore.devices[i][j][6]/1048576);\n dataArray.push([devicename,deviceusage]);\n }\n }\n UCapViz.drawChart({tar:'chartarea',data:dataArray});\n}",
"function chartSetup(channelName) {\n\tvar initialData = [];\n\tvar timeRef =\"absolute\";\t\n\t\n\t/* Show the pause button */\n\tif(!($(\"#PauseButton\").is(':visible'))) {\n\t\t$(\"#PauseButton\").show();\n\t}\n\t\n\t/* If real-time updates are on */\n\tif(realTimeFlag == 1) {\n\t\ttimeRef = \"newest\";\n\t}\n\t\n\t/* Set the default chart options that all charts share */\n\tsetChartOptions();\n\t\n\t/* AJAX call to go fetch data from a back-end \n\t * Java servlet - DataFacilitator.java for filling the initial\n\t * series data\n\t */\n\t$.post(\"http://localhost:8080/EcoSensorPodServlet/DataFacilitator\", \n\t\t{hostAddress: hostAddress,\n\t\t portNumber: portNumber,\n\t\t start: startSeconds, \n\t\t duration: durationSeconds,\n\t\t channelName: channelName,\n\t\t timeRef: timeRef\n\t\t}, \n\t\tfunction(sensorData) {\n\t\t\tvar MS_PER_SECOND = 1000;\n\t\t\tvar i = 0;\n\t\t\tvar data = sensorData.data;\n\t\t\tvar length = data.length;\n\t\t // Do something with the request\n\t\t\t/*if(realTimeFlag == 1) {\n\t\t\t\ttime = (new Date()).getTime();\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttime = (startSeconds + durationSeconds) * MS_PER_SECOND;\n\t\t\t}*/\n\t\t\tif(sensorData.data[0] != BAD_DATA_REQUEST) {\n\t\t\t\t/* Just got the current time so go back in time\n\t\t\t\t * to get numInitialDataPoints worth of data,\n\t\t\t\t * spaced by a given amount of seconds. Then add \n\t\t\t\t * them to the array to be passed to the charts.\n\t\t\t\t */\n\t\t\t\tfor\t(i = 0; i < length; i++) {\n\t\t\t\t\tinitialData.push([\n\t\t\t\t\t\tsensorData.timeStamp[i] * MS_PER_SECOND,\n\t\t\t\t\t\tsensorData.data[i]\n\t\t\t\t\t]);\n\t\t\t\t}\n\t\t\t\tlastAddedTimestamp = sensorData.timeStamp[length-1];\n\t\t\t\t/* Got the data! Now send it back to be posted */\n\t\t\t\torganizeDataToBeDrawn(channelName, initialData);\n\t\t\t}\n\t\t\telse if (sensorData.timeStamp[0] != BAD_DATA_REQUEST) {\n\t\t\t\t$('.center').notify({\n\t\t\t\t message: { text: \"ERROR! Sorry, no data available for requested time period. \" +\n\t\t\t\t\t\t\t\t\t\"Data is currently only available up until: \" + \n\t\t\t\t\t\t\t\t\tnew Date(sensorData.timeStamp[1]*1000) },\n\t\t\t\t\tfadeOut: { enabled: false }\n\t\t\t\t }).show();\n\t\t\t}\n\t\t\telse {\n\t\t\t\t$('.center').notify({\n\t\t\t\t message: { text: \"ERROR! Sorry, there is no history of data on this channel.\"},\n\t\t\t\t\tfadeOut: { enabled: false }\n\t\t\t\t }).show();\n\t\t\t}\n\t}, 'json');\n\t\n}",
"function makeGraphs(data) {\n \n var ndx = crossfilter(data);\n \n has_website(ndx);\n pieChart(ndx);\n barChart(ndx);\n table(ndx, 10);\n \n dc.renderAll();\n $(\".dc-select-menu\").addClass(\"custom-select\");\n\n}",
"function drawCharts(event) {\r\n\tfetchLineChart(event.target.textContent).then(res => {\r\n\t\tconsole.log(res);\r\n\t\t//updating the chart with the data of the selected activity\r\n\t\tline.data.datasets[0].data = res;\r\n\t\tline.update();\r\n\t});\r\n\r\n\tfetchBarChart(event.target.textContent).then(res => {\r\n\t\tconsole.log(res);\r\n\t\t//updating the chart with the data of the selected activity\r\n\t\tbar.data.datasets[0].data = res;\r\n\t\tbar.update();\r\n\t});\r\n}",
"function initChart(jsonarray) {\n plotedPoints=plotedPoints+jsonarray.length;\n //c3.js é uma biblioteca para plotar gráficos\n //veja a documentação do C3 em http://c3js.org/reference.html e exemplos em http://c3js.org/examples.html\n chart = c3.generate({\n transition: {\n //duration: 200//tempo do efeito especial na hora de mostrar o gráfico\n },\n bindto: \"#\" + chart_bindToId,//indica qual o ID da div em que o gráfico deve ser desenhado\n zoom: {\n enabled: true //permite ou não o zoom no gráfico\n },\n point: {\n show: false//mostra ou esconde as bolinhas na linha do gráfico\n },\n\n data: {\n json:jsonarray,// dados json a serem plotados\n\n keys: {\n x: chart_XData,//item do json correspondente ao eixo X\n value: [chart_YData] ,//item do json correspondente ao eixo Y\n },\n names: {\n [chart_YData]: chart_LineName//nome da linha plotada\n }\n ,\n colors: {\n [chart_YData]: '#E30613'//cor da linha\n }\n\n },\n axis: {\n x: {\n type : 'timeseries',//tipo do gráfico a ser plotado\n tick: {\n format: chart_Xformat,//formato dos dados no eixo X\n rotate: 45//rotação do texto dos dados no eixo X\n },\n label: {\n text: chart_XLabel,//nome do eixo X\n position: 'inner-middle'//posição do nome do eixo X\n }\n\n },\n\n y: {\n label: {\n text: chart_YLabel,//nome do eixo Y\n position: 'outer-middle'//posição do nome do eixo Y\n }\n }\n },\n\n tooltip: {\n show: true,\n format: {\n value: function (value, ratio, id, index) { return value + \" \" + chart_TooltipUnit; }\n }\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks whether the given userId refers to a Google user and calls the callback. Note that the callback will be called with the error information (if any) and the result of the query, if successful. | function isGoogleUser(userId, callback) {
var query =
'SELECT user_id ' +
'FROM GOOGLE_CREDENTIALS ' +
'WHERE user_id = $1 ';
db.query(query, {
bind: [userId]
})
.spread(function (results, metadata) {
// cast the result as a boolean: if a row was returned, this
// is a Google user
callback(null, results[0] ? true : false);
})
.catch(function (err) {
callback(err, null);
});
} | [
"function validateId(user_id, callback){\n\tvar sel_q = \"SELECT id, user_name, xp_sent, xp_received, send_count, receive_count, last_activity FROM spg_users WHERE id = \" + user_id;\n\tc.query(sel_q, function(err, rows, fields) {\n\t\tr_val = {is_valid:false,user_obj:{}};\n\t\tif (!err) {\n\t\t\tif (rows.length == 1) {\n\t\t\t\tconsole.log(\">>> User(\" + user_id + \") exists on DB\");\n\t\t\t\tr_val.is_valid = true;\n\t\t\t\tr_val.user_obj = rows[0];\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconsole.log(\">>> User(\" + user_id + \") does not exist on DB\");\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tconsole.log(\"Error selecting [\" + user_id + \"]\");\n\t\t\tconsole.log(\"Err: \" + err );\n\t\t}\n\n\t\tcallback(r_val);\n\t});\n}",
"function collectFacebookUser(userId){\n var emailAddress = document.getElementById('myVId').value;\n var phoneNumber = document.getElementById('phoneNumber').value;\n\n // Make a google user as a class\n FACEBOOKUSER.configure(userId, emailAddress, phoneNumber);\n\n console.log(FACEBOOKUSER.getId());\n console.log(FACEBOOKUSER.getEmail());\n console.log(FACEBOOKUSER.getMobile());\n\n pushToServer();\n}",
"function saveGoogleFailedStatus(user, id) {\r\n return new Promise((resolve, reject) => {\r\n let query = 'SELECT * FROM ' + table.GOOGLE_LIST + ' WHERE ouid = ?'\r\n\r\n db.query(query, [id], (error, rows, fields) => {\r\n if (error) {\r\n reject({ message: message.INTERNAL_SERVER_ERROR })\r\n } else {\r\n if (rows.length > 0) {\r\n let query = 'UPDATE ' + table.GOOGLE_LIST + ' SET oemail= ?, ofirst_name = ?, olast_name = ?, ouser_id = ?, oerror_code = ? WHERE ouid = ?'\r\n\r\n db.query(query, [user.email, user.firstName, user.lastName, user.googleId, 'don\\'t_have_account', id], (error, result, fields) => {\r\n if (error) {\r\n reject({ message: message.INTERNAL_SERVER_ERROR })\r\n } else {\r\n resolve(true)\r\n }\r\n })\r\n } else {\r\n let query = 'INSERT INTO ' + table.GOOGLE_LIST + '(ouid, oemail, ofirst_name, olast_name, ouser_id, oerror_code) VALUES (?, ?, ?, ?, ?, ?)'\r\n\r\n db.query(query, [id, user.email, user.firstName, user.lastName, user.googleId, 'don\\'t_have_account'], (error, result, fields) => {\r\n if (error) {\r\n reject({ message: message.INTERNAL_SERVER_ERROR })\r\n } else {\r\n resolve(true)\r\n }\r\n })\r\n }\r\n }\r\n })\r\n })\r\n}",
"function getFamilyUserIds(userId, callback)\n{\n if(userId)\n { \n relationModule.findOne({ hooksForUserId: userId }).then(function (relation) {\n if(relation && relation.trees && relation.trees.length > 0)\n { \n var userDetails;\n for(var treeCount=0;treeCount<relation.trees.length;treeCount++)\n {\n if(relation.trees[treeCount].relations && relation.trees[treeCount].relations.length > 0)\n {\n for(var relCount=0;relCount<relation.trees[treeCount].relations.length;relCount++)\n {\n userDetails = (userDetails) ? userDetails + \",'\" + relation.trees[treeCount].relations[relCount].userId+\"'\" : \n \"'\" +relation.trees[treeCount].relations[relCount].userId+\"'\";\n //userDetails = (userDetails) ? userDetails + \",\" + relation.trees[treeCount].relations[relCount].userId : \n //relation.trees[treeCount].relations[relCount].userId;\n }\n }\n \n if(treeCount == (relation.trees.length - 1))\n {\n callback(null, userDetails);\n }\n } \n }\n else\n {\n var error = new Error(\"No records found for members.\"); \n callback(error);\n }\n }).catch(function(err){\n callback(err); \n });\n }\n else\n { \n var error = new Error(\"User not logged in\"); \n callback(error);\n }\n}",
"function SearchUserById(userId) {\n for (var i = 0; i < Users.length; i++) {\n if (Users[i].id === userId) {\n return Users[i];\n }\n }\n return null;\n}",
"function getAccessTokenFromUserId(userId, next) {\n dbpg.query('SELECT * FROM authentications WHERE user_id = $1 LIMIT 1', \n [userId], function (err, result) {\n if (err) {\n console.error(err);\n next(null);\n } else {\n if (result.rows.length) {\n next(result.rows[0].token);\n } else {\n next(null);\n }\n }\n });\n}",
"function saveGoogleData(user, id) {\r\n return new Promise((resolve, reject) => {\r\n let query = 'SELECT * FROM ' + table.GOOGLE_LIST + ' WHERE ouid = ?'\r\n\r\n db.query(query, [id], (error, rows, fields) => {\r\n if (error) {\r\n reject({ message: message.INTERNAL_SERVER_ERROR })\r\n } else {\r\n if (rows.length > 0) {\r\n let query = 'UPDATE ' + table.GOOGLE_LIST + ' SET oemail= ?, ofirst_name = ?, olast_name = ?, ouser_id = ?, oerror_code = ? WHERE ouid = ?'\r\n\r\n db.query(query, [user.email, user.firstName, user.lastName, user.googleId, 'success', id], (error, result, fields) => {\r\n if (error) {\r\n reject({ message: message.INTERNAL_SERVER_ERROR })\r\n } else {\r\n resolve(true)\r\n }\r\n })\r\n } else {\r\n let query = 'INSERT INTO ' + table.GOOGLE_LIST + '(ouid, oemail, ofirst_name, olast_name, ouser_id, oerror_code) VALUES (?, ?, ?, ?, ?, ?)'\r\n\r\n db.query(query, [id, user.email, user.firstName, user.lastName, user.googleId, 'success'], (error, result, fields) => {\r\n if (error) {\r\n reject({ message: message.INTERNAL_SERVER_ERROR })\r\n } else {\r\n resolve(true)\r\n }\r\n })\r\n }\r\n }\r\n })\r\n })\r\n}",
"checkUserContributor (userId) {\n console.log('checkUserContributor:', userId);\n let user = Auth.requireAuthentication();\n \n // Validate\n check(userId, String);\n \n // Check for the presense of a contributor record\n return Users.findOne(userId).contributor() !== null\n }",
"async function checkIfRefExist(userId) {\n const refs = await db_utils.execQuery(\n \"SELECT userId FROM dbo.Referees\" \n );\n if (refs.find((r) => r.userId === parseInt(userId))){\n return true;\n }\n return false;\n }",
"function saveDataFromGoogle(user, id) {\r\n return new Promise((resolve, reject) => {\r\n // insert google_list_v4\r\n socialAuthModel.saveGoogleData(user, id).then((result) => {\r\n if (result) {\r\n let extraData = { registerGoogle: 1 }\r\n visitModel.checkVisitSessionExtra(db, id, extraData, 0).then((result) =>{\r\n resolve(result)\r\n })\r\n }\r\n }).catch((err) => {\r\n reject(err)\r\n })\r\n })\r\n}",
"function isAuthorized(userid) {\n\n for(i = 0; i < authorized_users.length; i++) \n if(authorized_users[i ] == userid) return true;\n \n return false;\n}",
"function get_user_by_id(id, callback) {\n\n const error_handler = (error, res) => {\n const status = res.statusCode;\n let response_body = res.responseText;\n try {\n response_body = JSON.parse(response_body);\n } catch(e) {}\n\n if(error) return console.error('Der skete en fejl:', error);\n\n return callback(res.statusCode, response_body);\n\n };\n\n const user = api_fetch('GET', `users/${id}`, null, error_handler);\n if(user) callback(user);\n}",
"function validUser(userId) {\n return userId && typeof(userId) === 'string' ? true : false;\n}",
"function findImageByUserId(userId, callback) {\n Profileimage.app.models.profileImageData.find({\n where: {\n appuserId: userId\n }\n }, function (err, res) {\n if (err) callback(err);\n else {\n if (res.length > 0) {\n Profileimage.app.models.profileImageData.deleteById(res[0].id, function (err) {\n if (err) callback(err);\n else {\n Profileimage.removeFile('profile_image', res[0].id + res[0].extension, function (err) {\n callback();\n })\n }\n })\n } else callback();\n }\n })\n }",
"function getSingleUser(userFragment, callback) {\n var request = 'Found multiple users, choose one by typing a number and hitting return';\n searchUsers(userFragment, function(users) {\n if (users.length <= 1) {\n callback(users[0]);\n }\n else if (users.length > 1) {\n users.forEach(function(u, i) {\n console.log((i + 1) + ' ' + formatUser(u));\n });\n askFor([request], function(results) {\n var userIndex = parseInt(results[request], 10) - 1;\n if (!(userIndex in users)) {\n return console.log('Invalid user selection.');\n }\n callback(users[userIndex]);\n });\n }\n });\n}",
"function signinCallback(authResult) {\n if (authResult['access_token']) {\n // Evitar el inicio de sesion automatico con el valor(PROMPT) de la propiedad \"METHOD\"\n if(authResult['status']['method'] == \"PROMPT\"){\n gapi.auth.setToken(authResult);\n gapi.client.load('oauth2', 'v2', function() {\n var request = gapi.client.oauth2.userinfo.get();\n request.execute(enviarDatosGoogle);\n });\n }\n }\n}",
"getUser(userId) {\n return this.state.allUsers.find((user) => user.id === userId);\n }",
"function localLookup (callback) {\n bo.runtime.sendMessage({\n type: 'localLookup',\n payload: {\n userId: config.userId\n }\n }, callback);\n}",
"function validateUserId(req, res, next) {\n Users.getById(req.params.id)\n .then((user) => {\n req.user = user;\n next();\n })\n .catch((error) => {\n console.log(error);\n res.status(400).json({ message: \"invalid user id\" });\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Edit anime in the table | function editAnime(e){
const rowId = e.parentNode.parentNode.id;
var title = document.getElementById(rowId).cells[0];
var rating = document.getElementById(rowId).cells[1];
var status = document.getElementById(rowId).cells[2];
var comment = document.getElementById(rowId).cells[3];
// toggle edit/save
document.getElementById("edit" + rowId).toggleAttribute("hidden");
document.getElementById("save" + rowId).toggleAttribute("hidden");
// get cell data
var curTitle = document.getElementById(rowId).cells[0].innerHTML;
var curRating = document.getElementById(rowId).cells[1].innerHTML;
var curStatus = document.getElementById(rowId).cells[2].innerHTML;
var curComment = document.getElementById(rowId).cells[3].innerHTML;
// cell data editable
title.innerHTML = "<input id='title"+ rowId +"' type=\"text\" placeholder=\"Title\" required name=\"title\" value='"+ curTitle +"'>"
rating.innerHTML = "\
<select id='rating"+ rowId +"' name='rating'> \
<option value='-'>-</option> \
<option value='1'>1</option> \
<option value='2'>2</option> \
<option value='3'>3</option> \
<option value='4'>4</option> \
<option value='5'>5</option> \
<option value='6'>6</option> \
<option value='7'>7</option> \
<option value='8'>8</option> \
<option value='9'>9</option> \
<option value='10'>10</option> \
</select>"
var selectRating = document.getElementById("rating" + rowId);
selectRating.value = curRating;
status.innerHTML = "\
<select id='status" + rowId + "' name='status'> \
<option value='Status' selected disabled>Status</option> \
<option value='Completed'>Completed</option> \
<option value='Watching'>Watching</option> \
<option value='Planning'>Planning</option> \
<option value='Dropped'>Dropped</option> \
</select>"
var selectStatus = document.getElementById("status" + rowId);
selectStatus.value = curStatus;
comment.innerHTML = "<input type='text' id='comment" + rowId + "' placeholder='Comment' name='comment' value='" + curComment + "'>"
} | [
"updateTable() {\n\t\tthis.manager.get(\"WWSUanimations\").add(\"announcements-update-table\", () => {\n\t\t\tif (this.table) {\n\t\t\t\tthis.table.clear();\n\t\t\t\tthis.find().forEach((announcement) => {\n\t\t\t\t\tthis.table.row.add([\n\t\t\t\t\t\tannouncement.title,\n\t\t\t\t\t\tannouncement.type,\n\t\t\t\t\t\tmoment\n\t\t\t\t\t\t\t.tz(\n\t\t\t\t\t\t\t\tannouncement.starts,\n\t\t\t\t\t\t\t\tthis.manager.get(\"WWSUMeta\")\n\t\t\t\t\t\t\t\t\t? this.manager.get(\"WWSUMeta\").meta.timezone\n\t\t\t\t\t\t\t\t\t: moment.tz.guess()\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.format(\"LLLL\"),\n\t\t\t\t\t\tmoment\n\t\t\t\t\t\t\t.tz(\n\t\t\t\t\t\t\t\tannouncement.expires,\n\t\t\t\t\t\t\t\tthis.manager.get(\"WWSUMeta\")\n\t\t\t\t\t\t\t\t\t? this.manager.get(\"WWSUMeta\").meta.timezone\n\t\t\t\t\t\t\t\t\t: moment.tz.guess()\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.format(\"LLLL\"),\n\t\t\t\t\t\t`<span class=\"text-${announcement.level}\"><i class=\"fas fa-dot-circle\"></i></span>`,\n\t\t\t\t\t\t`<div class=\"btn-group\"><button class=\"btn btn-sm btn-warning btn-announcement-edit\" data-id=\"${announcement.ID}\" title=\"Edit Announcement\"><i class=\"fas fa-edit\"></i></button><button class=\"btn btn-sm btn-danger btn-announcement-delete\" data-id=\"${announcement.ID}\" title=\"Delete Announcement\"><i class=\"fas fa-trash\"></i></button></div>`,\n\t\t\t\t\t]);\n\t\t\t\t});\n\t\t\t\tthis.table.draw();\n\t\t\t}\n\t\t});\n\t}",
"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}",
"async function saveAnime(e){\n const rowId = e.parentNode.parentNode.id;\n\n var title = document.getElementById(\"title\" + rowId).value;\n var rating = document.getElementById(\"rating\" + rowId).value;\n var status = document.getElementById(\"status\" + rowId).value;\n var comment = document.getElementById(\"comment\" + rowId).value;\n\n var object = {\n \"title\": title,\n \"rating\": rating,\n \"status\": status,\n \"comment\": comment\n };\n\n const r = await fetch(url + \"/\" + rowId, {\n method: \"PUT\",\n headers: {\"Content-Type\": \"application/json\"},\n body: JSON.stringify(object)\n });\n const result = await r.json();\n console.log(result);\n \n resetStatus();\n // this reloads the page if no changes occur\n popAnimeList(url);\n}",
"editMentor() {}",
"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 modifyAbilityTable(abilityTableName, rowName, value) {\n getAbilityTable(abilityTableName).rows.namedItem(rowName).cells[1].innerHTML = value;\n}",
"function editNote(){\n\t\n\tvar moment = require('alloy/moment');\n\t\n\tvar note= myNotes.get(idNote);\n\tnote.set({\n\t\t\"noteTitle\": $.noteTitle.value,\n\t\t\"noteDescription\": $.noteDescription.value,\n\t\t\"date\": moment().format()\n\t}).save();\n\t\n\tvar toast = Ti.UI.createNotification({\n\t\t \t\t\t \tmessage:\"Note has been succesfully saved\",\n\t\t \t\t\tduration: Ti.UI.NOTIFICATION_DURATION_SHORT\n\t\t\t\t\t\t});\n\t\t\t\t\t\t\n\t\t\t\ttoast.show();\n\tAlloy.Collections.note.fetch();\n\t\n $.detailnote.close();\n\t\t\n}",
"function editGoal() {\n\t\tprops.editTask(props.goalId);\n\t}",
"function editNote() {\n vm.isEditingNote = true;\n }",
"function ODBInlineEdit(p, odb_path, bracket) {\n if (p.inEdit)\n return;\n p.inEdit = true;\n mjsonrpc_db_get_values([odb_path]).then(function (rpc) {\n var value = rpc.result.data[0];\n var tid = rpc.result.tid[0];\n var mvalue = mie_to_string(tid, value);\n mie_link_to_edit(p, odb_path, bracket, mvalue);\n }).catch(function (error) {\n mjsonrpc_error_alert(error);\n });\n}",
"edit() {\n\t\tvar value = this.input.val();\n\n\t\tthis.$el.addClass('editing');\n\t\tthis.input.val(value).focus();\n\t}",
"function editWord() {\r\n var entry = idLookUp(parseInt(this.getAttribute('data-id'), 10));\r\n\r\n //set data key for modal\r\n document.querySelector(\"#edit-confirm\").setAttribute('data-id', entry.Id);\r\n\r\n //edit row\r\n var row = document.querySelector(\"#row_\" + entry.Id);\r\n\r\n //set default text in input fields to word values\r\n document.querySelector(\"#edit-text\").innerHTML = \"Edit the word \" + row.childNodes[0].innerHTML;\r\n document.getElementsByName(\"word-edit\")[0].value = row.childNodes[0].innerHTML;\r\n document.getElementsByName(\"pronunciation-edit\")[0].value = row.childNodes[1].innerHTML;\r\n document.getElementsByName(\"part-of-speech-edit\")[0].value = row.childNodes[2].innerHTML;\r\n document.getElementsByName(\"definition-edit\")[0].value = row.childNodes[3].innerHTML;\r\n}",
"updateTodo() {\n this.todos[this.editTodo.index].text = this.editTodo.text;\n\n this.cancelTodo();\n }",
"function EditFoodName() {\n let e = d.Config.enums\n let j = u.GetNumber(event.target.id);\n let cell = u.ID(`t1TableKey${j}`);\n let oldValue = cell.innerText;\n cell.innerHTML = `<input type='text' id='t1TableFoodNameInput${j}' value='${oldValue}'><button id='t1TableFoodNameSave${j}' class='insideCellBtn'>✔</button>`;\n cell.className = \"tableInput\";\n u.ID(`t1TableKey${j}`).removeEventListener(\"click\", EditFoodName);\n u.ID(`t1TableFoodNameSave${j}`).addEventListener(\"click\", function () { ChangeFoodName(j, oldValue); });\n}",
"function mie_link_to_edit(p, odb_path, bracket, cur_val) {\n var size = cur_val.length + 10;\n var index;\n\n p.ODBsent = false;\n\n var str = mhttpd_escape(cur_val);\n var width = p.offsetWidth - 10;\n\n if (odb_path.indexOf('[') > 0) {\n index = odb_path.substr(odb_path.indexOf('['));\n if (bracket == 0) {\n p.innerHTML = \"<input type='text' size='\" + size + \"' value='\" + str +\n \"' onKeydown='return ODBInlineEditKeydown(event, this.parentNode,"\" +\n odb_path + \"",\" + bracket + \");' onBlur='ODBFinishInlineEdit(this.parentNode,"\" +\n odb_path + \"",\" + bracket + \");' >\";\n setTimeout(function () {\n p.childNodes[0].focus();\n p.childNodes[0].select();\n }, 10); // needed for Firefox\n } else {\n p.innerHTML = index + \" <input type='text' size='\" + size + \"' value='\" + str +\n \"' onKeydown='return ODBInlineEditKeydown(event, this.parentNode,"\" +\n odb_path + \"",\" + bracket + \");' onBlur='ODBFinishInlineEdit(this.parentNode,"\" +\n odb_path + \"",\" + bracket + \");' >\";\n\n // needed for Firefox\n setTimeout(function () {\n p.childNodes[1].focus();\n p.childNodes[1].select();\n }, 10);\n }\n } else {\n\n p.innerHTML = \"<input type='text' size='\" + size + \"' value='\" + str +\n \"' onKeydown='return ODBInlineEditKeydown(event, this.parentNode,"\" +\n odb_path + \"",\" + bracket + \");' onBlur='ODBFinishInlineEdit(this.parentNode,"\" +\n odb_path + \"",\" + bracket + \");' >\";\n\n // needed for Firefox\n setTimeout(function () {\n p.childNodes[0].focus();\n p.childNodes[0].select();\n }, 10);\n }\n\n p.style.width = width + \"px\";\n}",
"function goToEdit() {\n\thideCardContainer();\n\thideArrows();\n\thideFlashcard();\n\thideInput();\n\thideScoreboard();\n\n\tdisplayEditContainer();\n\tdisplayEditControls();\n\tupdateEditTable();\n\tupdateDeckName();\n}",
"function editElement(event){\n\t\t\t\t\tclickedItem.innerHTML = textBox.value;\n\t\t\t\t}",
"handleEdit(event) {\n console.log('inside handleEdit');\n this.displayMode = 'Edit';\n }",
"async function tweetEditable(tweet_id){\n const { rows } = await pool.query(\"SELECT tweet_time FROM tweets WHERE ID = $1\",[tweet_id])\n const tweet_time= rows[0]['tweet_time']\n // get the current time now\n const time_now = helper.getCurrentTimestamp\n \n // remove 60 seconds from time_now...\n // if that value is less than tweet_time. Allow the edit. If not.. then don't\n if((time_now - 60) < tweet_time){\n return true\n }else{ return false }\n \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders the Dropdown input box for news outlets | render() {
//Grab all available news outlets and their names
const options = () => {
return(
Object.keys(newsFeeds).map(outlet => {
return(
<option value={outlet} key={outlet}>{newsFeeds[outlet].label}</option>
);
})
);
};
//Render the drop down box
return (
<div className="ui grid centered">
<div className="five wide column" style={{textAlign: 'center'}}>
<select className="ui selection dropdown" onChange={(event) => {
if(this.props.outlet !== event.target.value && this.props.newsTopic !== ''){
this.props.changeState('newsTopic', '', this.props.resetNewsFeedOnSelect);
}
this.props.changeState('newsOutlet', event.target.value, ()=>{});
}}>
<option value="">News Outlet</option>
{options()}
</select>
</div>
<div className="seven wide column" style={{textAlign: 'center'}}>
{this.renderNewsTopicDropDown()}
</div>
</div>
);
} | [
"renderNewsTopicDropDown() {\n //Map and render the available feeds / topics\n const options = (outlet) => {\n return (\n Object.keys(newsFeeds[outlet].feeds).map(feed => {\n return (\n <option value={feed} key={feed}>{newsFeeds[outlet].feeds[feed].label}</option>\n );\n })\n );\n };\n\n //Render the topics drop down input box\n if (this.props.newsOutlet !== '') {\n return (\n <select className=\"ui selection dropdown\" onChange={(event) => {\n const topic = event.target.value;\n this.props.changeState('newsTopic', topic, this.props.fetchNewsFeedOnSelect, topic);\n }}>\n <option value=\"\" selected={this.props.newsTopic === ''}>News Topic</option>\n {options(this.props.newsOutlet)}\n </select>\n );\n } else {\n return (\n <select className=\"ui selection dropdown\" disabled>\n <option value=\"\">News Topic</option>\n </select>\n );\n }\n }",
"function showNewsroomFieldsList (newsroomField, avconfig) {\n var defaultValue=newsroomField.$.newsroomfieldvalue;\n // left item\n var listItem = '<input class=\"other-section-main-left\" type=\"List'\n + '\" name=\"' + newsroomField.$.newsroomfield\n + '\" id=\"server-form-item\" disabled=\"disabled\"'\n + '\" value=\"' + newsroomField.$.newsroomfield\n + '\">';\n\n // if keylist is mixerinputs -> vchannels\n if (newsroomField.$.keylist == 'mixerinputs') {\n listItem += '<select name=\"' + newsroomField.$.newsroomfield\n + '\" id=\"' + newsroomField.$.newsroomfield + '_v'\n + '\" defaultValue=\"none'\n + '\" list=\"' + newsroomField.$.keylist\n + '\" class=\"server-form-item-class other-section-main-right\">';\n listItem += '<option selected=\"selected\">'+defaultValue+'</option>';\n\n // right item\n $.each(avconfig.videoconfig.vchannels.vchannel, function () {\n listItem += '<option value=\"' + $(this)[0].$.name + '\">' + $(this)[0].$.name + '</option>';\n });\n } else { // for special processing\n // if newsroomfield startwith 'output_', show destination_name\n if (newsroomField.$.newsroomfield.startsWith('output_')) {\n listItem += '<select name=\"' + newsroomField.$.newsroomfield\n + '\" id=\"' + newsroomField.$.newsroomfield + '_v'\n + '\" defaultValue=\"-'\n + '\" list=\"' + 'routerdestinations'\n + '\" class=\"server-form-item-class other-section-main-right\">';\n listItem += '<option selected=\"selected\">-</option>';\n\n var destination_name = avconfig.router_destinations.router_destination.$.destination_name;\n listItem += '<option value=\"' + destination_name + '\">' + destination_name + '</option>';\n }\n\n // if newsroomfield startwith 'input_', show source_name\n if (newsroomField.$.newsroomfield.startsWith('input_')) {\n listItem += '<select name=\"' + newsroomField.$.newsroomfield\n + '\" id=\"' + newsroomField.$.newsroomfield + '_v'\n + '\" defaultValue=\"-'\n + '\" list=\"' + 'routersource'\n + '\" class=\"server-form-item-class other-section-main-right\">';\n listItem += '<option selected=\"selected\">-</option>';\n\n var source_name = avconfig.router_sources.router_source.$.source_name;\n listItem += '<option value=\"' + source_name + '\">' + source_name + '</option>';\n }\n }\n\n listItem += '</select>';\n $('.other-section-main').append(listItem);\n}",
"function replaceDropdownName(county){\n document.getElementById('dropdownMenuButton').innerHTML = county \n}",
"function renderDepartment(data) {\n let x='<option value=\"\" disabled selected label=\"Select The Department that the book belongs to:\"></option>';\n data.forEach(item => {\n x+=\"<option value=\"+item.id+\">\"+item.name+\"</option>\" ;\n });\n department.innerHTML = x ;\n}",
"function inputProducts(data){\n data = sortAsc(data, \"name\")\n var htm = selectInput(data, \"_id\", \"name\")\n $('select[role=\"product-list\"]').each(function() {\n $(this).html(htm);\n });\n var template = $('#heroTemplate').html().replace('<option value=\"0\" disabled=\"\">Select One...</option>', htm);\n $('#heroTemplate').html(template);\n}",
"function makeDropDownList(){\n fetchInfluencers.then(response => {\n response.json().then(data => {\n var dropdownlist = document.getElementById(\"dropdownlist\");\n for (i = 0; i <= data.data.length; i++) {\n var option = document.createElement(\"option\");\n option.setAttribute(\"label\",data.data[i])\n option.setAttribute(\"value\",data.data[i])\n dropdownlist.add(option);\n }\n })\n })\n}",
"function renderDatalist() {\n stationShorts.forEach(function (station) {\n\n let option = document.createElement(\"option\")\n option.value = stations[stationShorts.indexOf(station)]\n\n stationDatalist.appendChild(option)\n })\n}",
"function renderCollege(data) {\n let x=\"<option value='' disabled selected label='Select The collage that the book belongs to:'></option>\";\n data.forEach(item => {\n x+=\"<option value=\"+item.id+\">\"+item.name+\"</option>\" ;\n });\n college.innerHTML = x ;\n}",
"function showSelectTags(){\n // show form and set the text field to null\n searchTagsForm.style.display = \"block\";\n document.getElementById(\"search\").value = \"\";\n formType = \"selectTags\";\n}",
"function createDropdowns(){\r\n\tdenominations.forEach(mainDropdown);\r\n\tupdateAddableCurrencies();\r\n}",
"function renderDropDown(planes) {\n console.log('dropdown planes',planes)\n return planes.map((plane) => {\n return `<option value=\"${plane.id}\">PA-${plane.id}-${plane.model}-${plane.seatCount}</option>`\n }).join(' ');\n}",
"function ShowSelectedFieldInputForm(field_title, field_type, field_id){\n \n}",
"function GenerateOptionsandList() {\n var optn = '';\n var li = '';\n try {\n if (MasterPlainLanguages.length > 0) {\n for (var i = 0; i < MasterPlainLanguages.length; i++) {\n optn = optn + '<option value=\"' + MasterPlainLanguages[i].PlainLanguageName + '\">' + MasterPlainLanguages[i].PlainLanguageName + '</option>';\n li = li + '<li class=\"list-group-item\"><a>' + MasterPlainLanguages[i].PlainLanguageName + '</a></li>';\n }\n } else {\n throw \"Plain Languages Not Available\";\n }\n } catch (err) {\n console.log(err);\n }\n $(\"#selectplainlang\").append(optn);\n $('.plainlanglist').append(li);\n $(\"#selectplainlang\").customselect();\n return;\n }",
"function setDisplayValueDropDownName(name) {\n document.getElementById('stockPropertyDropdownButton').innerHTML = name;\n}",
"function displayCountries(country) {\n document.getElementById(\"countryList\").innerHTML +=\n \"<option>\" + country + \"</option>\";\n }",
"function showSubscribedDropdown () {\n var content = $('.content');\n content.addClass('is-subscriber');\n}",
"function fillTeacherSelector() {\n var $dropdown = $(\"#teacher-select\");\n $($dropdown).empty();\n\n $.ajax({\n method: \"POST\",\n url: \"http://localhost:1340/graphql\",\n contentType: \"application/json\",\n data: JSON.stringify({\n query: teacherQuery\n })\n }).done(function(result) {\n // fill the teachers dropdown\n $.each(result.data.teachers, function() {\n // console.log(this);\n $dropdown.prepend($(\"<option />\").val(this.RefId).text(this.PersonInfo.Name.GivenName +\n \" \" + this.PersonInfo.Name.FamilyName));\n });\n // have to re-initialise component to render\n $($dropdown).formSelect();\n });\n}",
"function renderBBAND(bband) {\n\n //remove selected\n removeSelect('bband',12);\n\n //table\n document.getElementById('BBAND').style.display='block';\n\n //get elements\n var id = 'bband'+bband.toString();\n var bbcat = document.getElementById(id);\n\n //select\n bbcat.className = 'btn btn-b'+bband.toString()+' btn-sm btn-block btn-select p-0 m-0';\n }",
"function setAnalyticsDropDownName(name) {\n document.getElementById('analyticDropdownButton').innerHTML = name;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get configuration model for a given microservice identifier. | function getConfigurationModel(axios$$1, identifier) {
return restAuthGet(axios$$1, 'instance/microservice/' + identifier + '/configuration/model');
} | [
"function getGlobalConfiguration(axios$$1, identifier) {\n return restAuthGet(axios$$1, 'instance/microservice/' + identifier + '/configuration');\n }",
"GetConfig () {\n return { type: types.GET_CONFIG }\n }",
"function getTenantConfiguration(axios$$1, tenantToken, identifier) {\n return restAuthGet(axios$$1, 'instance/microservice/' + identifier + '/tenants/' + tenantToken + '/configuration');\n }",
"config() {\n if (this.isBound(exports.names.APP_SERVICE_CONFIG)) {\n return this.get(exports.names.APP_SERVICE_CONFIG);\n }\n else {\n throw new Error('configuration object not yet loaded!');\n }\n }",
"getTargetProduct() {\n return this.getConfigId().then(() => {\n return this._edge.get(URIs.GET_CONFIGS, [false, false]).then(configs => {\n const config = configs.configurations.find(cfg => cfg.id === this._configId);\n if (config) {\n return config.targetProduct;\n } else {\n logger.error('No security configurations exist for this config ID - ' + this._configId);\n throw `No security configurations exist for this config ID - ${this._configId}`;\n }\n });\n });\n }",
"static getConfig(key) {\n return vscode.workspace.getConfiguration(constants_1.Constants.CONFIG_PREFIX).get(key);\n }",
"function get(model, config = {}) {\n const api = new AbcApi_1.AbcApi(model, config);\n return api.get;\n}",
"function getModel() {\n return require(`./model-cloudsql`);\n}",
"function getModel(uri) {\n return _standaloneServices_js__WEBPACK_IMPORTED_MODULE_5__[\"StaticServices\"].modelService.get().getModel(uri);\n}",
"static async findById(id) {\n // Ensure model is registered before finding by ID\n assert.instanceOf(this.__db, DbApi, 'Model must be registered.');\n\n // Return model found by ID\n return await this.__db.findById(this, id);\n }",
"function getConfigForProject(projectId) {\n var allProjects = allConfig.projects;\n \n for (var i = 0; i < allProjects.length; i++) {\n var project = allProjects[i];\n if (project.id == projectId) {\n return project;\n }\n }\n \n logger.error(\"No project found for id %d\", projectId);\n}",
"forName(name) {\n let loader = ServiceLoader.load(\"io.swagger.codegen.CodegenConfig\");\n let availableConfigs = new StringBuilder();\n for (const config of loader) {\n if ((config.getName() === name)) {\n return config;\n }\n availableConfigs.append(config.getName()).append(\"\\n\");\n }\n try {\n return Class.forName(name).newInstance();\n }\n catch (e) {\n throw new Error(\"Can\\'t load config class with name \".concat(name) + \" Available: \" + availableConfigs.toString(), e);\n }\n }",
"function loadMainConfig() {\n return $http({\n method: 'Get',\n data: {},\n url: 'config.json',\n withCredentials: false\n })\n .then(transformResponse)\n .then(conf => {\n try {\n if (conf && conf.endpoints && conf.endpoints.mdx2json) {\n MDX2JSON = conf.endpoints.mdx2json.replace(/\\//ig, '').replace(/ /g, '');\n NAMESPACE = conf.namespace.replace(/\\//ig, '').replace(/ /g, '');\n }\n } catch (e) {\n console.error('Incorrect config in file \"config.json\"');\n }\n adjustEndpoints();\n })\n }",
"getModel (type, node) {\n let ModelClass = this.modelRegistry[type]\n // HACK: trying to retrieve the node if it is not given\n if (!node) {\n node = this.article.get(type)\n }\n if (ModelClass) {\n return new ModelClass(this, node)\n } else if (node) {\n return this._getModelForNode(node)\n }\n }",
"getById(id) {\n return HubSite(this, `GetById?hubSiteId='${id}'`);\n }",
"function getConfigs() {\n\n // use embedded configurations if it's available\n if (angular.isObject(window.swaggerDocsConfiguration)) {\n assignConfigs(window.swaggerDocsConfiguration);\n return;\n }\n\n // get configuration file remotely\n $http.get('./config.json').then(\n function(resp) {\n\n if (!angular.isObject(resp.data)) {\n throw new Error('Configuration should be an object.');\n }\n\n assignConfigs(resp.data);\n },\n function() {\n throw new Error('Failed to load configurations.');\n }\n );\n }",
"getInverter(id) {\r\n\t\tlet device = this.getDevice({ id: id });\r\n\t\tlet result;\r\n\t\tif (device) {\r\n\t\t\tresult = device.inverter;\r\n\t\t}\r\n\t\treturn result;\r\n\t}",
"static get(name, id, opts) {\n return new DisasterRecoveryConfig(name, undefined, Object.assign(Object.assign({}, opts), { id: id }));\n }",
"function getModel(name) {\n if (!models[name]) {\n throw error(`Model ${name} doesn't exist`)\n }\n return models[name]\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if any element of the iterable object is true. | function any( iterable )
{
var res = false;
foreach(function (x)
{
if ( x )
{
res = true;
throw StopIteration;
}
},
iterable);
return res;
} | [
"function all( iterable )\n {\n var res = true;\n \n foreach(function (x)\n {\n if ( !x )\n {\n res = false;\n throw StopIteration;\n }\n },\n iterable);\n \n return res;\n }",
"function every(array, value) {\n var boolean = true;\n array.forEach(el => {\n if (el !== value) {\n boolean = false\n }\n })\n return boolean;\n}",
"function every(obj, func) {\n let result = false;\n for (let key in obj) {\n let match = func(obj[key]);\n if (match) {\n result = true;\n }\n else { return false; }\n }\n return result;\n}",
"function every(array, callback){\n for (let i = 0; i < arr.length; i++){\n if (!callback(arr[i], i, arr)) return false;\n }\n return true;\n}",
"some(cb) {\n for (var item = this._head; item; item = item.next) {\n if (cb(item.data)) {\n return true;\n }\n }\n return false;\n }",
"function checkAge(arr) {\n if(arr.every(function (person) {\n return (person.age > 18);\n })) {\n return true;\n }\n return false;\n}",
"isAll(...roles) {\n\t\treturn Roles.coerceRoleArray(roles).every(role => this.is(role));\n\t}",
"_potIsGood() {\n return this.players\n .map((player) => {\n return (\n player.activeBetValue === -2 ||\n player.chipValue === 0 ||\n player.activeBetValue === this.activeBetValue\n );\n })\n .every(Boolean);\n }",
"function and(xs) {\n return xs.reduce((x,acc) => x && acc, true);\n}",
"function stream_for_each(fun, xs) {\n if (is_null(xs)) {\n return true;\n } else {\n fun(head(xs));\n return stream_for_each(fun, stream_tail(xs));\n }\n}",
"function short_circuiting_predicate(predicate, args) {\n var previous = args[0];\n for(var i = 1; i < args.length; i++) {\n if(!predicate(previous, args[i])) {\n return false; // short circuit\n }\n }\n return true; // no short circuit, all true\n }",
"function OR() {\n for (var _len11 = arguments.length, criteria = Array(_len11), _key11 = 0; _key11 < _len11; _key11++) {\n criteria[_key11] = arguments[_key11];\n }\n\n return criteria.reduce(function (acc, item) {\n if (acc === true) return true;\n return item === true || item === 1;\n }, false);\n}",
"function allSame (arr) {\n\t if (!Array.isArray(arr)) {\n\t return false\n\t }\n\t if (!arr.length) {\n\t return true\n\t }\n\t var first = arr[0]\n\t return arr.every(function (item) {\n\t return item === first\n\t })\n\t}",
"function truthCheck(collection, pre) {\n let checkedArr = collection.map(obj => {\n return obj.hasOwnProperty(pre) && Boolean(obj[pre]);\n })\n\n return checkedArr.includes(false) ? false : true;\n}",
"function bool(i) /* (i : int) -> bool */ {\n return $std_core._int_ne(i,0);\n}",
"any() {\n return Object.keys(this.datos).length > 0;\n }",
"isSubset(otherSet) {\n let result = this.set.every(function(element) {\n return otherSet.contains(element);\n });\n console.log('isSubset: ', result);\n }",
"function anyItemSelected(){\n\tvar result = false;\n\t$(\".filleditem\").each(function() {\n\t\tif ($(this).hasClass(\"selected\")) {\n\t\t\tconsole.log(\"An item is selected\");\n\t\t\tresult = true;\n\t\t}\n\t});\n\treturn result;\n}",
"function checkEvery(arr) {\n return arr.every(v => v % 3 == 0 )\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to run the Bubble Sort function when an element is clicked. | function clicked(){
sorter(numbers);
} | [
"function bubbleSort(arr) {\n\n}",
"function sortAjax(e) {\n genericAjax();\n}",
"function selectionSort()\n{\n\tfor (var i = 0; i < dataArray.length; i++)\n\t\t{\n\t\tsSort(i);\n\t\tsleep(500);\n\t\tredraw();\n\t\t}\n}",
"insertionSort() {\r\n // eslint-disable-next-line\r\n if (this.disabled == false) this.animate(sortingAlgos.insertionSort(this.state.array), this.state.animationSpeed);\r\n\r\n }",
"function setSortCardsListeners() {\n\tconst sortMenuButton = document.getElementById(\"sortMenuButton\");\n\tconst sortByFirstName = document.getElementById(\"sortFirstName\");\n\tconst sortByLastName = document.getElementById(\"sortLastName\");\n\tconst sortByParty = document.getElementById(\"sortParty\");\n\tconst sortByState = document.getElementById(\"sortState\");\n\tconst sortBySeniority = document.getElementById(\"sortSeniority\");\n\tconst sortByVotesWith = document.getElementById(\"sortVotesWith\");\n\tconst sortByVotesAgainst = document.getElementById(\"sortVotesAgainst\");\n\tconst sortByDistrict = document.getElementById(\"sortDistrict\");\n\n\tsortByFirstName.onclick = () => {\n\t\tlet sortStringAscendingly = '<i class=\"fas fa-sort-alpha-up\"></i> Sort on first name';\n\t\tlet sortStringDescendingly =\n\t\t\t'<i class=\"fas fa-sort-alpha-down-alt\"></i> Sort on first name';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.firstName,\n\t\t\t\"firstName\",\n\t\t\tsortByFirstNameAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByFirstName,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortByLastName.onclick = () => {\n\t\tlet sortStringAscendingly = '<i class=\"fas fa-sort-alpha-up\"></i> Sort on last name';\n\t\tlet sortStringDescendingly = '<i class=\"fas fa-sort-alpha-down-alt\"></i> Sort on last name';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.lastName,\n\t\t\t\"lastName\",\n\t\t\tsortByLastNameAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByLastName,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortByParty.onclick = () => {\n\t\tlet sortStringAscendingly = '<i class=\"fas fa-sort-alpha-up\"></i> Sort on party';\n\t\tlet sortStringDescendingly = '<i class=\"fas fa-sort-alpha-down-alt\"></i> Sort on party';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.party,\n\t\t\t\"party\",\n\t\t\tsortByPartyAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByParty,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortByState.onclick = () => {\n\t\tlet sortStringAscendingly = '<i class=\"fas fa-sort-alpha-up\"></i> Sort on state';\n\t\tlet sortStringDescendingly = '<i class=\"fas fa-sort-alpha-down-alt\"></i> Sort on state';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.state,\n\t\t\t\"state\",\n\t\t\tsortByStateAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByState,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortBySeniority.onclick = () => {\n\t\tlet sortStringAscendingly = '<i class=\"fas fa-sort-numeric-up\"></i> Sort on seniority';\n\t\tlet sortStringDescendingly =\n\t\t\t'<i class=\"fas fa-sort-numeric-down-alt\"></i> Sort on seniority';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.seniority,\n\t\t\t\"seniority\",\n\t\t\tsortBySeniorityAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortBySeniority,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortByVotesWith.onclick = () => {\n\t\tlet sortStringAscendingly =\n\t\t\t'<i class=\"fas fa-sort-numeric-up\"></i> Sort on votes with party';\n\t\tlet sortStringDescendingly =\n\t\t\t'<i class=\"fas fa-sort-numeric-down-alt\"></i> Sort on votes with party';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.partyVotesWith,\n\t\t\t\"partyVotesWith\",\n\t\t\tsortByVotesWithAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByVotesWith,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortByVotesAgainst.onclick = () => {\n\t\tlet sortStringAscendingly =\n\t\t\t'<i class=\"fas fa-sort-numeric-up\"></i> Sort on votes against party';\n\t\tlet sortStringDescendingly =\n\t\t\t'<i class=\"fas fa-sort-numeric-down-alt\"></i> Sort on votes against party';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.partyVotesAgainst,\n\t\t\t\"partyVotesAgainst\",\n\t\t\tsortByVotesAgainstAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByVotesAgainst,\n\t\t\tundefined\n\t\t);\n\t};\n}",
"function sortByArtist(artistHeading){\n artistHeading.addEventListener(\"click\", function(e){\n e.preventDefault();\n let artistHeadingNum = 1;\n tableSort(artistHeadingNum);\n });\n }",
"function sortSubmenu(e) {\n\t\t\tconst inputEl = $editShortcutDialog.find('input[name=subreddit]').get(0);\n\t\t\tconst currStr = inputEl.value;\n\t\t\t// sort ASC\n\t\t\tconst ascArr = currStr.split('+');\n\t\t\tascArr.sort();\n\t\t\tconst ascStr = ascArr.join('+');\n\t\t\t// sort DESC\n\t\t\tconst descArr = ascArr;\n\t\t\tdescArr.reverse();\n\t\t\tconst descStr = descArr.join('+');\n\t\t\tlet btnTxt;\n\t\t\tif (e.target.type === 'submit') {\n\t\t\t\t// if sorted ASC, sort DESC. If unsorted or sorted DESC, sort ASC\n\t\t\t\tinputEl.value = currStr === ascStr ? descStr : ascStr;\n\t\t\t\tbtnTxt = currStr === ascStr ? 'A-Z' : 'Z-A';\n\t\t\t} else {\n\t\t\t\tbtnTxt = currStr === ascStr ? 'Z-A' : 'A-Z';\n\t\t\t}\n\t\t\t(0, _vendor.$)('#sortButton').text(btnTxt);\n\t\t}",
"function sortClickHandler(\n\tsortedOnType,\n\tsortedType,\n\tsortFunction,\n\tsortStringAscendingly,\n\tsortStringDescendingly,\n\tsortMenuButton,\n\tsortButton,\n\tsortHeader\n) {\n\tlet filteredList = filter(searchByNameInput.value, partyFilterList, stateFilterList);\n\tif (sortedType === \"firstName\" && !sortHeader) {\n\t\tchamber === \"senate\"\n\t\t\t? app.swapCardNameOrder(\"senateMemberFirstName\")\n\t\t\t: app.swapCardNameOrder(\"houseMemberFirstName\");\n\t}\n\tif (sortedType === \"lastName\" && !sortHeader) {\n\t\tchamber === \"senate\"\n\t\t\t? app.swapCardNameOrder(\"senateMemberLastName\")\n\t\t\t: app.swapCardNameOrder(\"houseMemberLastName\");\n\t}\n\n\tif (sortedOnType) {\n\t\tsortedOn.setSortedOn(\n\t\t\tsortedType,\n\t\t\tsortMenuButton,\n\t\t\tsortButton,\n\t\t\tsortHeader,\n\t\t\tsortStringDescendingly\n\t\t);\n\t\tfilteredList.sort(sortFunction).reverse();\n\t\tupdateVue(filteredList);\n\t} else {\n\t\tsortedOn.setSortedOn(\n\t\t\tsortedType,\n\t\t\tsortMenuButton,\n\t\t\tsortButton,\n\t\t\tsortHeader,\n\t\t\tsortStringAscendingly\n\t\t);\n\t\tfilteredList.sort(sortFunction);\n\t\tupdateVue(filteredList);\n\t}\n}",
"function handleClick() {\n\tthis.style.transform = \"rotateY(180deg)\";\n\tparentsArr.push(this);\n\tclickedArr.push(this.lastElementChild.innerHTML);\n\tconsole.log(clickedArr);\n\tif (clickedArr.length == 2) {\n\t\tif (clickedArr[0] == clickedArr[1]) {\n\t\t\tremoveSimilar();\n\t\t\tclearElementsArr();\n\t\t} else {\n\t\t\trotateDifferant();\n\t\t\tclearElementsArr();\n\t\t}\n\t}\n}",
"function enableSortingBtn(){\r\n document.querySelector(\".bubsort\").disabled = false;\r\n document.querySelector(\".insertionsort\").disabled = false;\r\n document.querySelector(\".mergesort\").disabled = false;\r\n document.querySelector(\".quicksort\").disabled = false;\r\n document.querySelector(\".selectionsort\").disabled = false;\r\n}",
"function sortArtist() {\r\n document.querySelector('#artH').addEventListener('click', function (e) {\r\n const artist = paintings.sort((a, b) => {\r\n return a.LastName < b.LastName ? -1 : 1;\r\n })\r\n displayPaint(artist);\r\n })\r\n }",
"function bubbleSort3() {\n var i1, i2, j1, j2;\n var copy = numbers.slice(0);\n var len = copy.length;\n var tmp;\n var startTime = performance.now();\n var newStart = 0;\n var newEnd = len - 1;\n var swapCount1 = 0;\n var swapCount2 = 0;\n var totalSwaps = 0;\n var totalIterations = 0;\n do {\n var end = newEnd;\n var start = newStart;\n swapCount1 = 0;\n swapCount2 = 0;\n for (i1 = start; i1 < end; i1++) {\n var i2 = i1 + 1;\n if (copy[i1] > copy[i2]) {\n tmp = copy[i1];\n copy[i1] = copy[i2];\n copy[i2] = tmp;\n newEnd = i1;\n swapCount1++;\n }\n }\n for (j2 = end; j2 > start; j2--) {\n var j1 = j2 - 1;\n if (copy[j1] > copy[j2]) {\n tmp = copy[j2];\n copy[j2] = copy[j1];\n copy[j1] = tmp;\n newStart = j2;\n swapCount2++;\n }\n totalIterations++;\n }\n swapCount = swapCount1 + swapCount2;\n totalSwaps += swapCount;\n } while(swapCount > 1);\n console.log('Cocktail Shaker: totalSwaps=' + totalSwaps + ' totalIterations=' + totalIterations);\n var endTime = performance.now();\n var time = endTime - startTime;\n var result = copy.join(' ');\n $('#bubbleSort3').text(result);\n $('#bubbleSortTime3').text(time);\n return result;\n}",
"function sortPageObjArrayByButtonOrder (a, b)\n{\n\tvar agBOrder = a.pageObjArray[a.pageList[1]][gBUTTON_ORDER];\n\tvar bgBOrder = b.pageObjArray[b.pageList[1]][gBUTTON_ORDER];\n\tif (agBOrder == bgBOrder)\n\t\treturn 0;\n\telse if (bgBOrder < 0)\n\t\treturn -1;\n\telse if (agBOrder < 0)\n\t\treturn 1;\n\t\n\treturn (agBOrder - bgBOrder);\n}",
"switchSortButtons(selected) {\n for(let button of $(\"#btn-sort button\")) {\n if(button === selected[0]) {\n let icon = button.children[0];\n let font = icon.getAttribute(\"class\");\n let sort = button.getAttribute(\"value\").split('-');\n this.sortKey = sort[0];\n this.sortOrder = sort[1] === \"ascending\";\n // click the same button\n if(button.getAttribute(\"class\") === \"btn btn-info\") {\n // reverse icon\n icon.setAttribute(\"class\", font.indexOf(\"-alt\") > 0 ? font.replace(\"-alt\", \"\") : font + \"-alt\");\n // reverse sort order\n this.sortOrder = !this.sortOrder;\n if(this.sortOrder)\n button.setAttribute(\"value\", button.getAttribute(\"value\").replace(\"descending\", \"ascending\"));\n else\n button.setAttribute(\"value\", button.getAttribute(\"value\").replace(\"ascending\", \"descending\"));\n } else {\n button.setAttribute(\"class\", \"btn btn-info\");\n }\n } else {\n button.setAttribute(\"class\", \"btn btn-secondary\");\n }\n }\n }",
"function bubbleSort2() {\n var i1, i2, j1, j2;\n var copy = numbers.slice(0);\n var len = copy.length;\n var tmp;\n var startTime = performance.now();\n var newStart = 0;\n var newEnd = len - 1;\n var swapCount1 = 0;\n var swapCount2 = 0;\n var totalSwaps = 0;\n var totalIterations = 0;\n do {\n var end = newEnd;\n var start = newStart;\n swapCount1 = 0;\n swapCount2 = 0;\n for (i1 = start, j2 = end; i1 < end; i1++, j2--) {\n var i2 = i1 + 1;\n var j1 = j2 - 1;\n if (copy[i1] > copy[i2]) {\n tmp = copy[i1];\n copy[i1] = copy[i2];\n copy[i2] = tmp;\n newEnd = i1;\n swapCount1++;\n }\n if (copy[j1] > copy[j2]) {\n tmp = copy[j2];\n copy[j2] = copy[j1];\n copy[j1] = tmp;\n newStart = j2;\n swapCount2++;\n }\n totalIterations++;\n }\n swapCount = swapCount1 + swapCount2;\n totalSwaps += swapCount;\n } while(swapCount > 1);\n console.log('Optimized: totalSwaps=' + totalSwaps + ' totalIterations=' + totalIterations);\n var endTime = performance.now();\n var time = endTime - startTime;\n var result = copy.join(' ');\n $('#bubbleSort2').text(result);\n $('#bubbleSortTime2').text(time);\n return result;\n}",
"function addImagesSortButtonHandler() {\r\n // Depricated for new settings\r\n /*\r\n var sort = getImagesSortType();\r\n \r\n //var $el = $(\".options-settings-images-sort-item\"); // Old Settings\r\n var $el = $(\".nav-settings-images-sort > li\"); // New Settings\r\n var $item = $el.filter(\"[data-sort=\" + sort + \"]\");\r\n \r\n //if ($item) $item.addClass(\"active\"); // Old Settings\r\n if(NAVI) NAVI.setTab($item);// New Settings\r\n \r\n if (sort == 0) { //gallery\r\n $(\"#options-settings-images-upload\").css('display', 'none');\r\n } else if (sort == 1) { //your uploads\r\n $(\"#options-settings-images-upload\").css('display', 'block');\r\n }\r\n\r\n $el.on(\"click\", function () {\r\n var $el = $(this);\r\n var val = parseInt($el.attr(\"data-sort\"));\r\n var currentSort = getImagesSortType();\r\n\r\n if (currentSort != val) {\r\n BRW_sendMessage({\r\n command: \"setImagesSortType\",\r\n val: val\r\n });\r\n } //if\r\n });\r\n */\r\n}",
"function sortTitle() {\r\n document.querySelector('#titleH').addEventListener('click', function (e) {\r\n const title = paintings.sort((a, b) => {\r\n return a.Title < b.Title ? -1 : 1;\r\n })\r\n displayPaint(title);\r\n })\r\n }",
"function sortBy() {\n //DOM ELEMENTS\n let divCards = gridGallery.children;\n divCards = Array.prototype.slice.call(divCards);\n // CHECK VALUE\n switch (sortByBtn.value) {\n // IF VALUE IS DATE\n case \"date\":\n divCards.sort(function(a, b) {\n if (a.childNodes[0].date < b.childNodes[0].date) {\n return -1;\n } else {\n return 1;\n }\n });\n for (let i = 0; i < divCards.length; i++) {\n gridGallery.appendChild(divCards[i]);\n }\n break;\n // IF VALUE IS POPULARITY\n case \"popularity\":\n divCards.sort(function(a, b) {\n return b.childNodes[3].textContent - a.childNodes[3].textContent;\n });\n for (let i = 0; i < divCards.length; i++) {\n gridGallery.appendChild(divCards[i]);\n }\n break;\n // IF VALUE IS TITLE\n case \"title\":\n divCards.sort(function(a, b) {\n if (a.childNodes[1].textContent < b.childNodes[1].textContent) {\n return -1;\n } else {\n return 1;\n }\n });\n break;\n }\n // REMOVE ELEMENTS\n gridGallery.innerHTML = \"\";\n // ADD ELEMENTS FROM SWITCH CASE'S RESULT\n for (let i = 0; i < divCards.length; i++) {\n gridGallery.appendChild(divCards[i]);\n }\n}",
"function handleBubbleClick(bubble) {\n bubble.speed += ACCELERATION;\n bubble.points--;\n if (bubble.points === 0) {\n popBubble(bubble);\n }\n bubble.text(bubble.points);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks only if header is visible, if yes > close it. | function scrollCheck() {
if ($("header").is(":visible")) {
closeMenu();
}
} | [
"function checkMenu() {\n if ($(\"header\").is(\":visible\")) {\n closeMenu();\n } else {\n openMenu();\n }\n}",
"function scrollCheck() {\n if (document.body.scrollTop > height) {\n animateHeader = false;\n } else {\n animateHeader = true;\n }\n}",
"function hsCollapseAllVisible() {\n $('#content .hsExpanded:visible').each(function() {\n hsCollapse($(this).children(':header'));\n });\n}",
"function isVisible(obj)\n\t{\n\t\treturn (obj.css('display') != 'none') && (obj.css('visibility') != 'hidden');\n\t}",
"isVisible() {\n return this.toolbar.is(\":visible\");\n }",
"function close()\n{\n\tif(menuitem) menuitem.style.visibility = 'hidden'; // hide the sub menu\n} // end function",
"function participants_view_hide() {\n\tDOM(\"PARTICIPANTS_CLOSE\").style.backgroundColor = \"rgba(0,0,0,.2)\";\n\tsetTimeout(function() {\n\t\tDOM(\"PARTICIPANTS_CLOSE\").style.backgroundColor = \"transparent\";\n\t\tparticipants_view_visible = false;\n\t\tDOM(\"PARTICIPANTS_VIEW\").style.top = \"-100%\";\n\t\tsetTimeout(function() {\n\t\t\tDOM(\"PARTICIPANTS_VIEW\").style.display = \"none\";\n\t\t}, 500);\n\t}, 50);\n}",
"function _toggleVisibility() {\n\n\t\tvisible = !visible;\n\n\t\tif (true === visible) {\n\t\t\tpanel.show();\n\t\t\t$(\"#phpviewlog-preview-icon\").addClass(\"active\");\n\t\t\tWorkspaceManager.recomputeLayout();\n\t\t} else {\n\t\t\tpanel.hide();\n\t\t\t$(\"#phpviewlog-preview-icon\").removeClass(\"active\");\n\t\t}\n\t}",
"function toggleInvitationsSection() {\n var string = 'invitationsSection';\n var value = getStyle(string, 'display');\n hideNewListSection();\n hideInviteMemberSection();\n if(value == 'none') {\n\tshowInvitationsSection();\n } else {\n\thideInvitationsSection();\n }\n}",
"function openMenu() {\n if (header.classList.contains('open')) { // Open Hamburger Menu\n header.classList.remove('open');\n body.classList.remove('noscroll');\n fadeState('hidden');\n } else { // Close Hamburger Menu\n header.classList.add('open');\n body.classList.add('noscroll');\n fadeState('visible');\n }\n}",
"hideVisit() {\n\t\tthis.modalContainer.classList.remove(\"visible\");\n\t}",
"function isDialogVisible() {\n return getActivePage().find('.ui-popup-container').not('.ui-popup-hidden').length > 0;\n}",
"function hasScrolled() {\n\tvar scroll = topOfPage();\n\tif (scroll > 1) {\n\t\tdocument.getElementById(\"header\").style.padding = \"0 30px\"; // This style option will shrink the header\n\t\tdocument.getElementById(\"header\").style.boxShadow = \"0 0 5px 0 #ccc\"; // THis style option will create a shadow at the bottom of the header to give a sense of a layered website\n\t\tdocument.getElementById(\"header\").style.background = \"rgba(255,255,255,.98)\"; // This style option will make the header transparent just enough to see a little through it\n\t\t\n\t}\n\telse if (scroll < 1) {\n\t\tdocument.getElementById(\"header\").style.padding = \"15px 30px\"; // this style option is here if the page hasent been scrolled yet, or if you go back to the top of the page.\n document.getElementById(\"header\").style.boxShadow = \"0 0 0 0 #ccc\"; // This is to reset the box shadow style on the header\n \n\t}\n}",
"function hide() {\n if (!settings.shown) return;\n win.hide();\n settings.shown = false;\n }",
"function setupHeaderClickHandling()/*:void*/ {var this$=this;\n this.subPanels$v95j.forEach(function (panel/*:Panel*/)/*:void*/ {\n var header/*:Element*/ = panel.header.getEl();\n\n if (header) {\n header.setStyle(\"cursor\", \"pointer\");\n\n // Single click should expand/collapse the panel, but only if\n // the single click is not part of a double click. Therefore\n // we use a DelayedTask that executes the expand/collapse\n // only if no other click happens within the next 350ms.\n this$.mon(header, \"click\", function ()/*:void*/ {\n if (!this$.clickActionRequested$v95j) {\n this$.clickActionRequested$v95j = true;\n var executeSingleClickActionLater/*:DelayedTask*/ = new Ext.util.DelayedTask(function ()/*:void*/ {\n if (this$.clickActionRequested$v95j) {\n this$.clickActionRequested$v95j = false;\n if (panel.getCollapsed()) {\n panel.expand(false);\n } else {\n panel.collapse();\n }\n }\n });\n executeSingleClickActionLater.delay(350);\n }\n });\n\n // Double clicks should expand the panel and collapse all other\n // panels.\n this$.mon(header, \"dblclick\", function ()/*:void*/ {\n this$.clickActionRequested$v95j = false;\n this$.subPanels$v95j.forEach(function (subPanel/*:Panel*/)/*:void*/ {\n if (subPanel !== panel) {\n subPanel.collapse();\n }\n });\n panel.expand(false);\n });\n }\n });\n }",
"toggleFileDetails(event) {\n let header = this.getHeaderElement(event);\n\n if (!header) {\n return;\n }\n\n header.nextElementSibling.classList.toggle(Constants.DETAIL_SHOWN_CLASS);\n header.nextElementSibling.classList.toggle(Constants.DETAIL_HIDDEN_CLASS);\n }",
"containsHeaders(){\n return this.headerRow.length !== 0;\n }",
"function w3_close() {\n mySidebar.style.display = \"none\";\n }",
"function showSection(sectionName, isVisible) {\n if (isVisible == null) isVisible = true;\n let section = document.getElementById(sectionName);\n if (section) {\n section.hidden = !isVisible;\n } else {\n console.warn('Import CSV: showSection on nonexistent section: ' + sectionName);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
prefills milestone edit forms | function prefillEditForm(ttl, desc, pri, comp, dcomp) {
$("#id_title","#editmilestoneform").val(ttl);
$("#id_title","#editmilestoneform").val(ttl);
$("#id_description", "#editmilestoneform").val(desc);
$("#id_private", "#editmilestoneform").val(pri);
$("#id_completed", "#editmilestoneform").val(comp);
$("#id_date_completed", "#editmilestoneform").val(dcomp);
checkCompletedCheckbox("editmilestoneform", comp);
hideDateCompleted("editmilestoneform");
} | [
"function editMilestone(vTaskID) {\n var tempTaskItem = JSGantt.LookUpTask(vGanttChart, vTaskID);\n $('#alertMilestone').hide();\n $('#milestoneName').val(tempTaskItem.getName);\n $('#milestoneDate').val(\n (tempTaskItem.getStart().getMonth() + 1) + '/'\n + tempTaskItem.getStart().getDate() + '/'\n + tempTaskItem.getStart().getFullYear());\n $('#milestoneResource').val(tempTaskItem.getResource);\n $('#milestoneParent').val(tempTaskItem.getParent);\n $('#msID').val(tempTaskItem.getID);\n $('#addMsAction').hide();\n $('#editMsAction').show();\n $('#milestoneModalLabel').text(\"Edit Milestone\");\n $('#newMilestoneWindow').modal('show');\n}",
"editMentor() {}",
"function TKR_openIssueUpdateForm() {\n TKR_showHidden($('makechangesarea'));\n TKR_goToAnchor('makechanges');\n TKR_forceProperTableWidth();\n window.setTimeout(\n function () { document.getElementById('addCommentTextArea').focus(); },\n 100);\n}",
"function editForm() {\n app.getForm('profile').handleAction({\n cancel: function () {\n app.getForm('profile').clear();\n response.redirect(URLUtils.https('Account-Show'));\n },\n confirm: function () {\n var isProfileUpdateValid = true;\n var hasEditSucceeded = false;\n var Customer = app.getModel('Customer');\n\n if (!Customer.checkUserName()) {\n app.getForm('profile.customer.email').invalidate();\n isProfileUpdateValid = false;\n }\n\n if (app.getForm('profile.customer.email').value() !== app.getForm('profile.customer.emailconfirm').value()) {\n app.getForm('profile.customer.emailconfirm').invalidate();\n isProfileUpdateValid = false;\n }\n\n if (!app.getForm('profile.login.password').value()) {\n app.getForm('profile.login.password').invalidate();\n isProfileUpdateValid = false;\n }\n\n if (isProfileUpdateValid) {\n hasEditSucceeded = Customer.editAccount(app.getForm('profile.customer.email').value(), app.getForm('profile.login.password').value(), app.getForm('profile.login.password').value(), app.getForm('profile'));\n\n if (!hasEditSucceeded) {\n app.getForm('profile.login.password').invalidate();\n isProfileUpdateValid = false;\n }\n }\n\n if (isProfileUpdateValid && hasEditSucceeded) {\n \tif (Site.getCurrent().getCustomPreferenceValue('MailChimpEnable')) {\n if (app.getForm('profile.customer.addtoemaillist').value()) {\n \tvar mailchimpHelper = require('*/cartridge/scripts/util/MailchimpHelper.js');\n \tmailchimpHelper.addNewListMember(app.getForm('profile.customer.firstname').value(), app.getForm('profile.customer.email').value());\n }\n } else {\n \tltkSignupEmail.Signup();\n }\n response.redirect(URLUtils.https('Account-Show'));\n } else {\n response.redirect(URLUtils.https('Account-EditProfile', 'invalid', 'true'));\n }\n },\n changepassword: function () {\n var isProfileUpdateValid = true;\n var hasEditSucceeded = false;\n var Customer = app.getModel('Customer');\n\n if (!Customer.checkUserName()) {\n app.getForm('profile.customer.email').invalidate();\n isProfileUpdateValid = false;\n }\n\n if (!app.getForm('profile.login.currentpassword').value()) {\n app.getForm('profile.login.currentpassword').invalidate();\n isProfileUpdateValid = false;\n }\n\n if (app.getForm('profile.login.newpassword').value() !== app.getForm('profile.login.newpasswordconfirm').value()) {\n app.getForm('profile.login.newpasswordconfirm').invalidate();\n isProfileUpdateValid = false;\n }\n\n if (isProfileUpdateValid) {\n hasEditSucceeded = Customer.editAccount(app.getForm('profile.customer.email').value(), app.getForm('profile.login.newpassword').value(), app.getForm('profile.login.currentpassword').value(), app.getForm('profile'));\n if (!hasEditSucceeded) {\n app.getForm('profile.login.currentpassword').invalidate();\n }\n }\n\n if (isProfileUpdateValid && hasEditSucceeded) {\n response.redirect(URLUtils.https('Account-Show'));\n } else {\n response.redirect(URLUtils.https('Account-EditProfile', 'invalid', 'true'));\n }\n }\n });\n}",
"handleEditButtonClick() {\n BusinessRulesFunctions.viewBusinessRuleForm(true, this.state.uuid)\n }",
"function editGoal() {\n\t\tprops.editTask(props.goalId);\n\t}",
"fillIncomeForm(item) {\n // Change to edit form\n this.changeIncomeForm(\"edit\", item.id);\n\n // Set edit item value to income form\n this.incomeDateInput.value = item.date;\n this.incomeTitleInput.value = item.title;\n this.incomeCostInput.value = item.cost.split(\",\").join(\"\");\n }",
"function loadRepoIntoEditForm(repo){\n const form = document.getElementById('repo-edit-form');\n form.repoTitle.value = repo.title;\n form.repoDesc.value = repo.description;\n form.repoPrivacy.checked = repo.isPrivate;\n}",
"function editTaskModalInit()\n{\n\t_gel('ETTaskName').value= \"\";\n\t_gel('ETTaskDescription').value= \"\";\n\t_gel('ETManagersComment').value= \"\";\n\t_gel('ETAssignedDate').value= \"\";\n\t_gel('ETStartDate').value= \"\";\n\t_gel('ETDueDate').value= \"\";\n\t_gel('ETHoursAllotted').value= \"\";\n\t_gel('ETAssociatedManager').value= \"\";\n\t_gel('ETLeadEmployee').value= \"\";\n\t\n\tgetTaskNames();\n}",
"@action\n statusChangeAction(field, value) {\n if (value == 'approved') {\n this.editEntry.set('create_entry', 1);\n }\n }",
"function editStepForm(stepId) {\n var step = null;\n var stepIndex = null;\n for(var i = 0; i < steps.length; i++) {\n if(steps[i].id == stepId) {\n step = steps[i];\n stepIndex = i;\n break;\n }\n }\n if(step === null) {\n return;\n }\n\n editingStep = stepIndex;\n\n showStepForm(step.type);\n\n //load form data\n switch(step.type) {\n case 'script':\n scriptEditor.setValue(step.action);\n break;\n\n case 'preset':\n $('input[name=\"preset-name\"]').val(step.action);\n break;\n\n default:\n }\n\n $('input[name=\"breakOnError\"]').prop('checked', step.breakOnError);\n }",
"function missionDetails(newMission){\n\n\t\thideEdit();\n\t\tshowEdit();\n\n\t\t//create circle with icon if it is given for this misison\n\t\t$('.edit ul.mission-neutral').append($('<li class=\"circle-big\">' + (newMission.icon ? '<img src='+ newMission.icon +'>' : \"\") + '</li>'))\n\n\t\t//creates empty form \n\t\t$('.edit').append(createEmptyForm());\n\n\t\t//if name is given show in the form\n\t\t$('input[name=\"newMissionName\"]').val(newMission.name ? newMission.name : \"\")\n\n\t\t//if points are given (which means it is user mission) show in the form \n\t\tif (newMission.hasOwnProperty('points')){\n\t\t\t$('input[name=\"newMissionPoints\"]').val(newMission.points)\n\t\t\t//for user mission save missionId\n\t\t\t$('.edit li.circle-big').attr('name',newMission.id)\n\t\t\t//for user missions show also days\n\t\t\tnewMission.days.forEach(function(day){\n\t\t\t\t$('input[name=\"newMissionDays\"]').eq(day).trigger('click')\n\t\t\t})\n\n\t\t\t//for user mission show SAVE button\n\t\t\t$('.edit').append($('<button class=\"save\">ZAPISZ ZMIANY</button>'))\n\t\t\t// and FINISH / DELETE button\n\t\t\t$('.edit').append($('<button class=\"left infoFinish\">ZAKOŃCZ</button><button class=\"right infoDelete\">USUŃ</button>'))\n\t\t} else {\n\t\t\t//for NOT user missions show ADD button\n\t\t\t$('.edit').append($('<button class=\"add\">DODAJ</button>'))\n\t\t}\n\t}",
"listenLoadEditForm() {\n editor.clearMenus();\n const slugs = h.getAfterHash(this.href),\n post = model.getPostBySlugs(slugs);\n\n editor.currentPost = post;\n editor.currentPostType = post.type;\n\n if (editor.currentPostType !== 'settings') {\n view.currentPost = post;\n view.update();\n } else {\n event.preventDefault();\n }\n\n editor.showEditPanel();\n }",
"function entryEditSubmitHandler(evt, repo){\n evt.preventDefault();\n const entryEditForm = evt.target;\n const entryIndex = +entryEditForm.getAttribute('data-entryIndex');\n const entry = repo.entries[entryIndex];\n // Update entry to form values\n entry.title = entryEditForm.entryTitle.value;\n entry.description = entryEditForm.entryDesc.value;\n entry.url = entryEditForm.entryURL.value;\n entry.type = entryEditForm.entryType.value;\n entry.image = entryEditForm.entryImage.value;\n entry.rating = entryEditForm.entryRating.value;\n entry.state = entry.state === 'NEW' ? 'NEW' : 'CHANGE'\n // Clear and hide form, update DOM\n entryEditForm.entryTitle.value = '';\n entryEditForm.entryDesc.value = '';\n entryEditForm.entryURL.value = '';\n entryEditForm.entryType.value = '';\n entryEditForm.entryImage.value = '';\n entryEditForm.entryRating.value = 0;\n document.getElementById('entry-edit-div').style.display = 'none';\n alertSave();\n repo.refreshEntryMarkup(entryIndex);\n}",
"function resetStepForm() {\n editingStep = -1;\n stepType = 'script';\n clearStepForm();\n $('#script-form').addClass('hidden');\n }",
"function editIssue(obj) {\n // Creates a form for editied issue\n var form = document.createElement(\"form\");\n form.setAttribute(\"id\",\"listAll\");\n\n // ID of issue\n var id = document.createElement(\"p\");\n id.innerHTML = \"<b>ID:</b>\" + obj[\"ID\"];\n\n // Title box\n var tit = document.createElement(\"input\");\n tit.setAttribute('type',\"text\");\n tit.setAttribute('name',\"Title\");\n tit.setAttribute('id', \"title\");\n tit.value = obj[\"title\"];\n var tlabel = document.createElement(\"Label\");\n tlabel.htmlFor = \"text\";\n tlabel.innerHTML = \"<b>Title:</b>\";\n\n // Status option\n var stat = document.createElement(\"select\");\n stat.setAttribute('id', \"status\");\n // Adds New option\n var op = new Option();\n op.value = \"New\";\n op.text = \"New\";\n stat.options.add(op);\n // Adds Assigned option\n var op = new Option();\n op.value = \"Assigned\";\n op.text = \"Assigned\";\n stat.options.add(op);\n // Adds fixed option\n var op = new Option();\n op.value = \"Fixed\";\n op.text = \"Fixed\";\n stat.options.add(op);\n // Adds won't fix option\n var op = new Option();\n op.value = \"Won't Fix\";\n op.text = \"Won't Fix\";\n stat.options.add(op);\n stat.value = obj[\"status\"];\n var slabel = document.createElement(\"Label\");\n slabel.htmlFor = \"text\";\n slabel.innerHTML = \"<b>Status:</b>\";\n\n // Description Box\n var des = document.createElement(\"TEXTAREA\");\n des.setAttribute('type',\"text\");\n des.setAttribute('name',\"Description\");\n des.setAttribute('rows', \"5\");\n des.setAttribute('cols', \"50\");\n des.setAttribute('id', \"msg\");\n des.value = obj[\"description\"];\n var dlabel = document.createElement(\"Label\");\n dlabel.htmlFor = \"text\";\n dlabel.innerHTML = \"<b>Description:</b>\";\n\n // OS option\n var os = document.createElement(\"select\");\n os.setAttribute('id', \"OS\");\n // Adds Windows option\n var oop = new Option();\n oop.value = \"Windows\";\n oop.text = \"Windows\";\n os.options.add(oop);\n // Adds Linux option\n var oop = new Option();\n oop.value = \"Linux\";\n oop.text = \"Linux\";\n os.options.add(oop);\n // Adds Mac option\n var oop = new Option();\n oop.value = \"Mac\";\n oop.text = \"Mac\";\n os.options.add(oop);\n os.value = obj[\"os\"];\n var olabel = document.createElement(\"Label\");\n olabel.htmlFor = \"text\";\n olabel.innerHTML = \"<br><b>OS:</b>\";\n\n // Priority option\n var prio = document.createElement(\"select\");\n prio.setAttribute('id', \"priority\");\n // Adds Low option\n var pop = new Option();\n pop.value = \"Low\";\n pop.text = \"Low\";\n prio.options.add(pop);\n // Adds Medium option\n var pop = new Option();\n pop.value = \"Medium\";\n pop.text = \"Medium\";\n prio.options.add(pop);\n // Adds High option\n var pop = new Option();\n pop.value = \"High\";\n pop.text = \"High\";\n prio.options.add(pop);\n // Adds Very High option\n var pop = new Option();\n pop.value = \"Very High\";\n pop.text = \"Very High\";\n prio.options.add(pop);\n // Adds World Ending option\n var pop = new Option();\n pop.value = \"World Ending\";\n pop.text = \"World Ending\";\n prio.options.add(pop);\n prio.value = obj[\"priority\"];\n var plabel = document.createElement(\"Label\");\n plabel.htmlFor = \"text\";\n plabel.innerHTML = \"<br><b>Priority:</b>\";\n\n // Component box\n var com = document.createElement(\"input\");\n com.setAttribute('type',\"text\");\n com.setAttribute('name',\"Com\");\n com.setAttribute('id',\"component\");\n com.value = obj[\"component\"];\n var clabel = document.createElement(\"Label\");\n clabel.htmlFor = \"text\";\n clabel.innerHTML = \"<br><b>Component:</b>\";\n\n // Assignee box\n var ass = document.createElement(\"select\");\n // Adds all users as possible ass\n for(var i in users) {\n var x = new Option();\n x.value = users[i][\"name\"];\n x.text = x.value;\n ass.add(x);\n }\n var alabel = document.createElement(\"Label\");\n alabel.htmlFor = \"text\";\n alabel.innerHTML = \"<br><b>Assignee:</b>\";\n\n // Submit button\n var but = document.createElement(\"button\");\n but.innerHTML = \"Submit\";\n but.onclick = function() {\n // Url issue is sent to\n const url = 'http://localhost:1234/whap/issues?id=' + obj[\"ID\"];\n // Packs all the info into an object\n var data = {\n name: tit.value,\n id: obj[\"ID\"],\n status: stat.value,\n des: des.value,\n prio: prio.value,\n os: os.value,\n com: com.value,\n ass: ass.value\n }\n // Yeets the data to the server\n putData(url,data)\n // Tells users they did it\n .then(alert(\"You edited it!\"));\n };\n\n // Delete button\n var del = document.createElement(\"button\");\n del.innerHTML = \"<b>DELETE</b>\";\n del.onclick = function() {\n alert(\"Are you sure you want to delete this issue?\\n\" +\n \"Just kidding, it's too late, it's fucking gone.\");\n deleteIssue(obj[\"ID\"]);\n }\n\n // <p> for styling\n var para = document.createElement(\"p\");\n\n // Adds everything to the screen\n form.appendChild(id);\n form.appendChild(tlabel);\n form.appendChild(tit);\n form.appendChild(dlabel);\n form.appendChild(des);\n form.appendChild(clabel);\n form.appendChild(com);\n form.appendChild(alabel);\n form.appendChild(ass);\n form.appendChild(para);\n form.appendChild(slabel);\n form.appendChild(stat);\n form.appendChild(plabel);\n form.appendChild(prio);\n form.appendChild(olabel);\n form.appendChild(os);\n form.appendChild(but);\n form.appendChild(del);\n document.body.appendChild(form);\n}",
"function goToEdit() {\n\thideCardContainer();\n\thideArrows();\n\thideFlashcard();\n\thideInput();\n\thideScoreboard();\n\n\tdisplayEditContainer();\n\tdisplayEditControls();\n\tupdateEditTable();\n\tupdateDeckName();\n}",
"function EditPage ()\n{\n\tvar PageName = doAction('REQ_GET_FORMVALUE', \"PageName\", \"PageName\");\n\tif (PageName)\n\t\treturn (EditPageByName (PageName));\n\telse\n\t{\n\t\tif (isPageValid (gCURRENT_PAGE))\n\t\t\treturn (doActionEx('MPEA_EDIT_PAGE', 'Result'));\n\t\telse\n\t\t\treturn (EditPageByName (gHOME_PAGE));\n\t}\n\t\t\t\t\n}",
"function disableEditing() {\n disableForm(true);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to detect a win with 4 in a column | function columnWin() {
for (var column = 0; column < 7; column++) {
var streak = 1;
var previousPlayer;
var previousPlayer = null;
var currentColumn = document.querySelectorAll(`[data-column='${column}']`);
for (var cell = 0; cell < currentColumn.length; cell++) {
var currentPlayer = currentColumn[cell].getAttribute(`data-player`)
if (currentPlayer === previousPlayer && currentPlayer !== null) {
streak++;
}
else {
streak = 1;
}
previousPlayer = currentPlayer;
if ( streak === 4 ) {
return true;
}
};
};
} | [
"function checkRowForWin() {\n var i, totalCount = 1;\n var leftSideComplete = false;\n var rightSideComplete = false;\n var cells = [];\n var row, col;\n \n for(i = 1; i < _config.col; i++){\n \n if (_config.resultArray[c + i] &&\n _config.resultArray[c + i][r] == _config.resultArray[c][r]) {\n //found one \n totalCount++;\n row = r;\n col = c + i;\n cells.push({r:[row],c:[col]}); //Keeping records of winning cells\n }else{\n rightSideComplete = true;\n }\n \n if (_config.resultArray[c - i]\n && _config.resultArray[c - i][r] == _config.resultArray[c][r]) {\n //found one\n totalCount++;\n row = r;\n col = c - i;\n cells.push({r:[row],c:[col]}); //Keeping records of winning cells\n }else{\n leftSideComplete = true;\n }\n \n if (totalCount >= 4){\n //alert(_config.resultArray[c][r] + \" has won the game\");\n cells.push({r:[r],c:[c]});\n _config.winingCells = cells;\n return true;\n }\n \n if (leftSideComplete && rightSideComplete){\n return false;\n }\n \n }\n \n return false;\n }",
"function testWinCondition(row, col) {\n let t = boardState[row][col]; //last played token\n let bs = boardState;\n\n //DOWN\n if (row<=2 && t==bs[row+1][col] && t==bs[row+2][col] && t==bs[row+3][col])\n return (true);\n \n //DIAGONAL FORWARD - POSITION 1\n else if (row>=3 && col<=3 && t==bs[row-1][col+1] && t==bs[row-2][col+2] && t==bs[row-3][col+3])\n return (true);\n //DIAGONAL FORWARD - POSITION 2\n else if (row>=2 && row<=4 && col>=1 && col<=4 && t==bs[row+1][col-1] && t==bs[row-1][col+1] && t==bs[row-2][col+2])\n return (true);\n //DIAGONAL FORWARD - POSITION 3\n else if (row>=1 && row<=3 && col>=2 && col<=5 && t==bs[row+2][col-2] && t==bs[row+1][col-1] && t==bs[row-1][col+1])\n return (true);\n //DIAGONAL FORWARD - POSITION 4\n else if (row<=2 && col>=3 && t==bs[row+3][col-3] && t==bs[row+2][col-2] && t==bs[row+1][col-1])\n return (true);\n\n //DIAGONAL BACKWARD - POSITION 1\n else if (row<=2 && col<=3 && t==bs[row+1][col+1] && t==bs[row+2][col+2] && t==bs[row+3][col+3])\n return (true);\n //DIAGONAL BACKWARD - POSITION 2\n else if (row>=1 && row<=3 && col>=1 && col<=4 && t==bs[row-1][col-1] && t==bs[row+1][col+1] && t==bs[row+2][col+2])\n return (true);\n //DIAGONAL BACKWARD - POSITION 3\n else if (row>=2 && row<=4 && col>=2 && col<=5 && t==bs[row-2][col-2] && t==bs[row-1][col-1] && t==bs[row+1][col+1])\n return (true);\n //DIAGONAL BACKWARD - POSITION 4\n else if (row>=3 && col>=3 && t==bs[row-3][col-3] && t==bs[row-2][col-2] && t==bs[row-1][col-1])\n return (true);\n \n //HORIZONTAL - POSITION 1\n else if (col<=3 && t==bs[row][col+1] && t==bs[row][col+2] && t==bs[row][col+3])\n return (true);\n //HORIZONTAL - POSITION 2\n else if (col>=1 && col<=4 && t==bs[row][col-1] && t==bs[row][col+1] && t==bs[row][col+2])\n return (true);\n //HORIZONTAL - POSITION 3\n else if (col>=2 && col<=5 && t==bs[row][col-2] && t==bs[row][col-1] && t==bs[row][col+1])\n return (true);\n //HORIZONTAL - POSITION 4\n else if (col>=3 && t==bs[row][col-3] && t==bs[row][col-2] && t==bs[row][col-1])\n return (true);\n else \n return (false);\n}",
"checkFinished(row, col, player){\n let winningStreak = [];\n\n //Checking for a streak vertically in the column of the inserted token\n let streak = [];\n let streakReached = false;\n for(let i=0; i<this.rows; i++){\n if(this.field[i][col] == player){\n streak.push([i,col]);\n if(streak.length == this.toWin){\n streakReached = true;\n i=this.rows;\n }\n }\n else streak = [];\n }\n if(streakReached) winningStreak = winningStreak.concat(streak);\n\n //Checking for a streak horizontally in the row of the inserted token\n streakReached = false;\n streak = [];\n for(let i=0; i<this.cols; i++){\n if(this.field[row][i] == player){\n streak.push([row,i]);\n if(streak.length == this.toWin) streakReached = true;\n }\n else{\n if(!streakReached) streak = [];\n else i=this.cols;\n }\n }\n if(streakReached) winningStreak = winningStreak.concat(streak);\n\n //Checking for a streak diagonally from top left to bottom right in the\n //line of the inserted token and adding it to the winningStreak Array.\n let spots;\n if(this.rows >= this.cols) spots = this.rows;\n else spots = this.cols;\n winningStreak = winningStreak.concat(this.checkDiagonally(row,col,player,spots,1));\n\n //Checking for a streak diagonally from bottom left to top right in the\n //line of the inserted token and adding it to the winningStreak Array.\n winningStreak = winningStreak.concat(this.checkDiagonally(row,col,player,spots,-1));\n\n if(winningStreak.length >= this.toWin) return winningStreak;\n else if(this.freeLots == 0) return false;\n return null;\n }",
"function checkRow(xy, wb) {\n\n var col = xy[1];\n var length = 1; // start at length 1 since player just put down a piece\n\n // check one side\n while(col > 1) {\n col -= 1;\n if(checkTile([xy[0], col], wb)) {\n length += 1;\n } else {\n break; // encountered another color\n }\n }\n\n if(length >= 5) return true;\n\n col = xy[1]; // reset\n\n // check other side\n while(col < 15) {\n col += 1;\n if(checkTile([xy[0], col], wb)) {\n length += 1;\n } else {\n break;\n }\n }\n\n if(length >= 5) return true;\n\n // no win yet\n return false;\n\n}",
"checkIfWin(){\n\t\tconst g = this.state.grid;\n\t\tvar hits = 0;\n\n\t\tfor(var i = 0; i < this.gridSize; i++) {\n\t\t\tfor(var j = 0; j < this.gridSize; j++) {\n\t\t\t\tif (g[i][j] === \"Hit\") {\n\t\t\t\t\thits++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif(hits === this.maxNumberOfShips*2){\n\t\t\tvar theWinner = \"\";\n\n\t\t\tif(this.props.id === \"gridA\"){\n\t\t\t\ttheWinner = \"PlayerB\";\n\t\t\t\tthis.props.handleWin(theWinner);\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttheWinner = \"PlayerA\";\n\t\t\t\tthis.props.handleWin(theWinner);\n\t\t\t}\n\n\t\t}\n\n\t}",
"function checkWin() {\n\n var winPattern = [board[0] + board[1] + board[2], board[3] + board[4] + board[5], board[6] + board[7] + board[8], // Horizontal 0,1,2\n board[0] + board[3] + board[6], board[1] + board[4] + board[7], board[2] + board[5] + board[8], // Vertical 3,4,5,\n board[0] + board[4] + board[8], board[2] + board[4] + board[6]\n ]; // Diagonal 6,7\n\n var USER_String = USER + USER + USER; // USER_String == \"111\"\n var AI_String = AI + AI + AI; // AI_String == \"222\"\n\n for (var i = 0; i < 8; i++) {\n if (winPattern[i] == USER_String) {\n $(\"#status\").text(\"YOU WON\")\n activateWinAnimation(i);\n return USER; // User wins\t\t\t\t\n } else if (winPattern[i] == AI_String) {\n $(\"#status\").text(\"AI WON\")\n activateWinAnimation(i);\n return AI; // AI wins\t\t\t\n }\n }\n\n if (board.indexOf(\"-\") == -1) {\n $(\"#status\").text(\"IT'S A DRAW\")\n return DRAW; // Draw!\t\t\t\t\n }\n\n return 0;\n}",
"function checkWin(board) {\n var firstColor = board[0][0];\n var count = board.length;\n for(var i = 0 ; i < count ; i++) {\n for(var j = 0 ; j < count ; j++) {\n if (board[i][j] !== firstColor) {\n return false\n }\n }\n }\n return true\n}",
"function winAnotherDiag() {\n for(let col=2;col<gameStageArch[0].length;col++){\n for(let row=0;row<gameStageArch.length-2;row++){\n if (gameStageArch[row][col] === gameStageArch[row+1][col-1]\n && gameStageArch[row+1][col-1] === gameStageArch[row+2][col-2]) {\n let winComb = [[row,col],[row+1,col-1],[row+2,col-2]];\n\n if(gameStageArch[row][col]) {\n return winMessage(gameStageArch[row][col], 'diagonally /', winComb);\n }\n }\n }\n }\n}",
"function gamevalue(onmove, board) {\n var v;\n /* first scan for wins */\n var side = -1\n for (var s = 0; s < 2; s++) {\n side = -side\n v = side * onmove\n /* scan for diagonal */\n var n = 0\n for (var d = 0; d < 3; d++)\n if (board[d][d] == side)\n n = n + 1\n if (n == 3)\n return v\n /* scan for opposite diagonal */\n var n = 0\n for (var d = 0; d < 3; d++)\n if (board[d][2 - d] == side)\n n = n + 1\n if (n == 3)\n return v\n /* scan for rows */\n for (var r = 0; r < 3; r++) {\n n = 0\n for (var c = 0; c < 3; c++)\n if (board[r][c] == side)\n n = n + 1\n if (n == 3)\n return v\n }\n /* scan for columns */\n for (var c = 0; c < 3; c++) {\n n = 0\n for (var r = 0; r < 3; r++)\n if (board[r][c] == side)\n n = n + 1\n if (n == 3)\n return v\n }\n }\n /* scan for blanks */\n for (var r = 0; r < 3; r++)\n for (var c = 0; c < 3; c++)\n if (board[r][c] == 0)\n /* game not over */\n return -2\n /* game is a draw */\n return 0\n}",
"function checkWinner(i) {\n\n //For loop to run through game board to determine if three of the same icons are\n //selected horizontally.\n\n for (var i = 0; i < self.pieces.spaces.length; i += 3) {\n if (self.pieces.spaces[i].player == self.pieces.spaces[i + 1].player && self.pieces.spaces[i].player == self.pieces.spaces[i + 2].player && self.pieces.spaces[i].player != 0) {\n self.gameData.winner = \"player \" + self.pieces.spaces[i].player + \" wins!\";\n self.winner = true;\n }\n }\n\n //For loop to run through game board to determine if three of the same icons are\n //selected vertically.\n\n for (var i = 0; i < 3; i++) {\n if (self.pieces.spaces[i].player == self.pieces.spaces[i + 3].player && self.pieces.spaces[i].player == self.pieces.spaces[i + 6].player && self.pieces.spaces[i].player != 0) {\n self.gameData.winner = \"player \" + self.pieces.spaces[i].player + \" wins!\";\n self.winner = true;\n }\n }\n\n //Checks to see if three of the same icons are displayed diagonally in if/else if\n //statements.\n\n if (self.pieces.spaces[0].player == self.pieces.spaces[4].player && self.pieces.spaces[0].player == self.pieces.spaces[8].player && self.pieces.spaces[0].player != 0) {\n self.gameData.winner = \"player \" + self.pieces.spaces[0].player + \" wins!\";\n self.winner = true;\n } else if (self.pieces.spaces[2].player == self.pieces.spaces[4].player && self.pieces.spaces[2].player == self.pieces.spaces[6].player && self.pieces.spaces[2].player != 0) {\n self.gameData.winner = \"player \" + self.pieces.spaces[2].player + \" wins!\";\n self.winner = true;\n }\n\n\n //Checks to see if the turn count is 10 with no winner, thus declaring a tie game.\n else if (self.gameData.turn == 10) {\n self.gameData.winner = \"Tic Tac Tie!\";\n self.winner = true;\n }\n\n }",
"function getWinning() {\n let result = ''\n if (game.winner != PLAYER_NONE) {\n const winning = findTriplet(game.board[game.winner], 15)\n for (let w = 0; w < winning.length; ++w) {\n winning[w] = game.board[game.winner][winning[w]]\n }\n for (let m = 0; m < CELLS; ++m) {\n if (winning.includes(VALUES[m])) {\n result += outerCell(m)\n }\n }\n }\n return result\n}",
"function ticTacToe(arr) {\n var winner = null;\n\n // first check for winner in each row\n arr.forEach(row => {\n return row.filter((item, i, arr) => {\n if (arr[0] === arr[1] && arr[0] === arr[2]) {\n winner = arr[0];\n }\n });\n });\n\n //check for diagonal & and column\n var firstRow = arr[0];\n var secondRow = arr[1];\n var thirdRow = arr[2];\n\n if (firstRow[0] === secondRow[0] && firstRow[0] === thirdRow[0]) {\n winner = firstRow[0];\n } else if (firstRow[1] === secondRow[1] && firstRow[1] === thirdRow[1]) {\n winner = firstRow[1];\n } else if (firstRow[2] === secondRow[2] && firstRow[2] === thirdRow[2]) {\n winner = firstRow[2];\n }\n\n if (firstRow[0] === secondRow[1] && firstRow[0] === thirdRow[2]) {\n winner = firstRow[0];\n } else if (firstRow[2] === secondRow[1] && firstRow[2] === thirdRow[0]) {\n winner = firstRow[2];\n }\n\n return winner;\n}",
"function check_game_winner(state) {\n\n //Patters variable is an array of patterns with each pattern itself an array of x/y co-oridinates.\n //In order to create the pattern matching technique, every possible winning pattern had to be identified with the co-ordinates recorded.\n //Each individual array is a set of x/y co-ordinates. The first number in the array is x and the second, y. The co-ordinates represent one square obtained by a marker\n //in a winning pattern.\n var patterns = [\n //Start of Diagonal winning patterns top left to right ( \\ )\n //1st column Diagonal\n [[0, 0], [1, 1], [2, 2], [3, 3]], //Works\n [[0, 1], [1, 2], [2, 3], [3, 4]], //Works\n [[0, 2], [1, 3], [2, 4], [3, 5]], //Works\n //2nd column Diagonal\n [[1, 0], [2, 1], [3, 2], [4, 3]], //Works\n [[1, 1], [2, 2], [3, 3], [4, 4]], //Works\n [[1, 2], [2, 3], [3, 4], [4, 5]], //Works\n //3rd column Diagonal\n [[2, 0], [3, 1], [4, 2], [5, 3]], //Works\n [[2, 1], [3, 2], [4, 3], [5, 4]], //Works\n [[2, 2], [3, 3], [4, 4], [5, 5]], //Works\n //4th column Diagonal\n [[3, 0], [4, 1], [5, 2], [6, 3]], //Works\n [[3, 1], [4, 2], [5, 3], [6, 4]], //Works\n [[3, 2], [4, 3], [5, 4], [6, 5]], //Works\n //Start of Diagonal winning patterns top right to left ( / )\n //7th column Diagonal\n [[6, 0], [5, 1], [4, 2], [3, 3]], //Works\n [[6, 1], [5, 2], [4, 3], [3, 4]], //Works\n [[6, 2], [5, 3], [4, 4], [3, 5]], //Works\n //6th column Diagonal\n [[5, 0], [4, 1], [3, 2], [2, 3]], //Works\n [[5, 1], [4, 2], [3, 3], [2, 4]], //Works\n [[5, 2], [4, 3], [3, 4], [2, 5]], //Works\n //5th column Diagonal\n [[4, 0], [3, 1], [2, 2], [1, 3]], //Works\n [[4, 1], [3, 2], [2, 3], [1, 4]], //Works\n [[4, 2], [3, 3], [2, 4], [1, 5]], //Works\n //4th column Diagonal\n [[3, 0], [2, 1], [1, 2], [0, 3]], //Works\n [[3, 1], [2, 2], [1, 3], [0, 4]], //Works\n [[3, 2], [2, 3], [1, 4], [0, 5]], //Works\n //End of Diagonal pattern matching.\n\n //Horizontal pattern, bottom up\n //1st column Horizontal\n [[0, 5], [1, 5], [2, 5], [3, 5]], //Works\n [[1, 5], [2, 5], [3, 5], [4, 5]], //Works\n [[2, 5], [3, 5], [4, 5], [5, 5]], //Works\n [[3, 5], [4, 5], [5, 5], [6, 5]], //Works\n //2nd column Horizontal\n [[0, 4], [1, 4], [2, 4], [3, 4]], //Works\n [[1, 4], [2, 4], [3, 4], [4, 4]], //Works\n [[2, 4], [3, 4], [4, 4], [5, 4]], //Works\n [[3, 4], [4, 4], [5, 4], [6, 4]], //Works\n //3rd column Horizontal\n [[0, 3], [1, 3], [2, 3], [3, 3]], //Works\n [[1, 3], [2, 3], [3, 3], [4, 3]], //Works\n [[2, 3], [3, 3], [4, 3], [5, 3]], //Works\n [[3, 3], [4, 3], [5, 3], [6, 3]], //Works\n //4th column Horizontal\n [[0, 2], [1, 2], [2, 2], [3, 2]], //Works\n [[1, 2], [2, 2], [3, 2], [4, 2]], //Works\n [[2, 2], [3, 2], [4, 2], [5, 2]], //Works\n [[3, 2], [4, 2], [5, 2], [6, 2]], //Works\n //5th column Horizontal\n [[0, 1], [1, 1], [2, 1], [3, 1]], //Works\n [[1, 1], [2, 1], [3, 1], [4, 1]], //Works\n [[2, 1], [3, 1], [4, 1], [5, 1]], //Works\n [[3, 1], [4, 1], [5, 1], [6, 1]], //Works\n //6th column Horizontal\n [[0, 0], [1, 0], [2, 0], [3, 0]], //Works\n [[1, 0], [2, 0], [3, 0], [4, 0]], //Works\n [[2, 0], [3, 0], [4, 0], [5, 0]], //Works\n [[3, 0], [4, 0], [5, 0], [6, 0]], //Works\n //End of Horizontal patterns\n\n //Vertical patterns, top down.\n //1st column Vertical\n [[0, 0], [0, 1], [0, 2], [0, 3]], //Works\n [[0, 1], [0, 2], [0, 3], [0, 4]], //Works\n [[0, 2], [0, 3], [0, 4], [0, 5]], //Works\n //2nd column Vertical\n [[1, 0], [1, 1], [1, 2], [1, 3]], //Works\n [[1, 1], [1, 2], [1, 3], [1, 4]], //Works\n [[1, 2], [1, 3], [1, 4], [1, 5]], //Works\n //3rd column Vertical\n [[2, 0], [2, 1], [2, 2], [2, 3]], //Works\n [[2, 1], [2, 2], [2, 3], [2, 4]], //Works\n [[2, 2], [2, 3], [2, 4], [2, 5]], //Works\n //4th column Vertical\n [[3, 0], [3, 1], [3, 2], [3, 3]], //Works\n [[3, 1], [3, 2], [3, 3], [3, 4]], //Works\n [[3, 2], [3, 3], [3, 4], [3, 5]], //Works\n //5th column Vertical\n [[4, 0], [4, 1], [4, 2], [4, 3]], //Works\n [[4, 1], [4, 2], [4, 3], [4, 4]], //Works\n [[4, 2], [4, 3], [4, 4], [4, 5]], //Works\n //6th column Vertical\n [[5, 0], [5, 1], [5, 2], [5, 3]], //Works\n [[5, 1], [5, 2], [5, 3], [5, 4]], //Works\n [[5, 2], [5, 3], [5, 4], [5, 5]], //Works\n //7th column Vertical\n [[6, 0], [6, 1], [6, 2], [6, 3]], //Works\n [[6, 1], [6, 2], [6, 3], [6, 4]], //Works\n [[6, 2], [6, 3], [6, 4], [6, 5]], //Works\n //End of pattern matching\n ];\n\n //Load the current game state\n // var state = this.get('state');\n //Loop over all winning patters (patterns.length)\n for(var pidx = 0; pidx < patterns.length; pidx++) {\n //Assign each pattern to the 'pattern' variable\n var pattern = patterns[pidx];\n //Get the states current value pattern at the patterns first co-orindates\n var winner = state[pattern[0][0]][pattern[0][1]];\n\n if(winner) {\n //Loop over all other co-ordinates starting at 'idx1'. If the winner value is different to the value at any other co-ordinates\n //of the pattern, set the winner to undefined.\n for(var idx = 1; idx < pattern.length; idx++ ) {\n if(winner != state[pattern[idx][0]][pattern[idx][1]]) {\n winner = undefined;\n break;\n }\n }\n //If after checking all other co-ordinates in the pattern, the winner is still set to a value, then set that value as the components\n //winner property and stop checking other patterns.\n if(winner) {\n return winner;\n //this.set('winner', winner)\n //break;\n }\n }\n }\n //Initial assumption of a draw\n var draw = true;\n //Loop over all squares in the state, check if any values are undefined.\n for(var x = 0; x <=6; x++) {\n for(var y = 0; y <=5; y++) {\n if(!state[x][y]) {\n return undefined;\n //draw = false;\n //break;\n }\n }\n }\n //After checking all the squares, set the draw value as the current value of the components 'draw' property.\n //this.set('draw', draw);\n return '';\n}",
"function countWins(wins) {\n x = getOccurrence(rolls, 5);\n y = getOccurrence(rolls, 6);\n wins = x + y;\n return wins;\n }",
"function userCanWin(gem1,gem2,gem3,gem4,targetScore) {\n if (isEven(gem1) \n && isEven(gem2) \n && isEven(gem3) \n && !isEven(targetScore) \n && isEven(gem4)) {\n // then we take the value of gem4 and subtract 1 to make it Odd.\n return gem4 - 1; \n }\n // If the edge case is not true, we don't need to do anything. Return \n // gem4 as normal, and move along as planned.\n return gem4;\n}",
"function game_over() {\n // you must try all 8 possibilities to determine if the game is won by someone:\n // 3 rows, 3 columns, and 2 diagonals!\n // Also, if all cells are occupied, and no one won, then it is a tie!\n \n // if no one won, and it is not a tie, then it is on going.\n return \"+\";\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 match3Column() {\n console.log('Checking column matches')\n for (let i = 0; i < width ** 2; i++) {\n if (i >= width ** 2 - width * 2) {\n // console.log(`ignoring i ${i}`)\n } else {\n const first = cells[i].classList[0]\n const second = cells[i + width].classList[0]\n const third = cells[i + width * 2].classList[0]\n const match3C = first === second && first === third\n if (match3C) {\n // console.log(` starting from ${i} ${first} and ${second} and ${third} are the same in the column `)\n return true\n }\n }\n }\n}",
"function winTossWinMatchSummary(match,team1){\n if(match[\"toss_winner\"]===team1){\n if(match[\"winner\"]===team1){\n return 2;\n }\n return 1;\n }\n return 0;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List cue point objects by filter and pager. | static listAction(filter = null, pager = null){
let kparams = {};
kparams.filter = filter;
kparams.pager = pager;
return new kaltura.RequestBuilder('cuepoint_cuepoint', 'list', kparams);
} | [
"static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('livechannelsegment', 'list', kparams);\n\t}",
"static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('partner', 'list', kparams);\n\t}",
"static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('livestream', 'list', kparams);\n\t}",
"static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('responseprofile', 'list', kparams);\n\t}",
"static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('baseentry', 'list', kparams);\n\t}",
"static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('virusscan_virusscanprofile', 'list', kparams);\n\t}",
"static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('livechannel', 'list', kparams);\n\t}",
"static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('thumbparamsoutput', 'list', kparams);\n\t}",
"static listAction(filter, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('fileasset', 'list', kparams);\n\t}",
"static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('flavorparamsoutput', 'list', kparams);\n\t}",
"static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('thumbparams', 'list', kparams);\n\t}",
"static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('conversionprofileassetparams', 'list', kparams);\n\t}",
"function showPageObjects() {\n db.allDocs({ include_docs: true, descending: true }, function(err, doc) {\n redrawPageObjectsUI(doc.rows)\n })\n }",
"static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('externalmedia_externalmedia', 'list', kparams);\n\t}",
"static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('flavorparams', 'list', kparams);\n\t}",
"static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('media', 'list', kparams);\n\t}",
"static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('quiz_quiz', 'list', kparams);\n\t}",
"function showCoffees(offset = 0) {\n let limit = ($('#coffee-limit-select').length) ? $('#coffee-limit-select option:checked').val() : 5;\n let sort = ($('#coffee-sort-select').length) ? $('#coffee-sort-select option:checked').val() : 'id:asc';\n\n const url = baseUrl_API + '/api/v1/coffee?limit=' + limit + '&offset=' + offset + '&sort=' + sort;\n\n axios({\n method: 'get',\n url: url,\n cache: true,\n headers: {\"Authorization\": \"Bearer \" + jwt}\n }).then(function(response) {\n displayCoffees(response.data);\n }).catch(function(error){\n handleAxiosError(error);\n });\n\n}",
"static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('caption_captionasset', 'list', kparams);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function will search for the first time a number appears in the game map string and will truncate the game map string to ignore everything that occurs before the first number (including the first number itself). This function will then return the first number in the game map string as an int. | function parseNum(){
var pattern = /[0-9]+/;
//If the we have set text to be the game map string, then we execute the following code.
if(text){
//This sets result to be either null (if the pattern was not found), or a string of
// what we are looking for. It parses text, looking for pattern. And returns the
// either a string, or null. Pattern tells exec that it wants to take the first
// sequence of numbers from text that appear, and ignore everything else. In the
// case of the default Frupal map, the first sequence of numbers that appear is "25".
// Thus, result would contain: "25"
var result = pattern.exec(text);
//This takes text - which is the game map string - and takes a substring of it
// and stores that substring back to text. The substring it takes starts at position
// (index of where result first starts to appear in text offset by the length of result)
// and continues to the length of the whole game map string. Thus, effectively, anything
// that was written in "text" before result appears, and result itself get discarded from
// the game map string.
text = text.slice(result.index + result[0].length, text.length);
//This Parses result to an integer (because result is an integer in string form right now)
// and then returns it.
return parseInt(result);
}
} | [
"function firstOcc(string, character) {\n for (var i = 0; i < string.length; i++) {\n if (string[i] === character) {\n return i;\n }\n }\n return -1;\n}",
"function findLastNumber(str) {\n for (let i = str.length - 1; i >= 0; --i) {\n const code = str.charCodeAt(i);\n if (code >= _ZERO && code <= _NINE) {\n return i;\n }\n }\n return -1;\n}",
"function firstDigitIs(num, n) {\n return num.toString()[0] === n.toString()\n}",
"function findMissingNumber(str) {\n let array = str.split(' ').map(Number);\n let largest = array.length + 1;\n let sum = 0;\n for (let i = 0; i < array.length; i++) {\n sum += array[i];\n }\n return largest * (largest + 1) / 2 - sum;\n}",
"function findMissingNumber(sequence) {\r\n if (sequence == '') return 0\r\n let s = sequence.split(' ').map(Number)\r\n if (s.some(isNaN)) return 1\r\n for (let i = 1; i < Math.max(...s); i++)\r\n if (!s.find(v => v == i))\r\n return i\r\n return 0\r\n}",
"function mapKey(key) {\n if (key == 73) {\n return \"1\";\n } else if (key == 79) {\n return \"2\";\n } else if (key == 80) {\n return \"3\";\n } else {\n return 'Error(mapKey): No key match!'\n }\n}",
"function firstNotRepeatingCharacter(s) {\n let obj = {};\n \n for(let i = 0; i < s.length; i++){\n if(!obj.hasOwnProperty(s[i])){\n obj[s[i]] = 1;\n }\n else {\n obj[s[i]]++;\n }\n }\n \n for(object in obj){\n if(obj[object] === 1){\n return object;\n }\n }\n \n return '_';\n }",
"function first(input) {\n return input.charAt(0);\n}",
"function first(s, n) /* (s : string, n : ?int) -> sslice */ {\n var _n_13291 = (n !== undefined) ? n : 1;\n var slice0 = _sslice_first(s);\n if ($std_core._int_eq(_n_13291,1)) {\n return slice0;\n }\n else {\n return extend(slice0, $std_core._int_sub(_n_13291,1));\n }\n}",
"function lookAndSaySequence(num) {\n let str = num.toString();\n let result = '';\n\n for (var i = 0; i < str.length; i++) {\n if (str[i] === str[i - 1]) {\n continue;\n };\n\n let count=1;\n while (str[i] === str[i+count]) {\n count++;\n };\n\n result += (count.toString() + str[i]);\n }\n\n return parseInt(result);\n}",
"function getBasemapIdTitle(title) {\r\n var bmArray = basemapGallery.basemaps;\r\n for (var i = 0; i < bmArray.length; i++) {\r\n if (bmArray[i].title === title) {\r\n return bmArray[i].id;\r\n }\r\n }\r\n return false;\r\n}",
"function FindMotif(targetMotif, dnaString){\n\tvar indexLoc = '';\n\tvar notDone = true;\n\tvar counter = 0;\n\tvar lastFound = 0;\n\twhile(notDone && counter <10000){\n\t\tvar pos = dnaString.toString().indexOf(targetMotif,lastFound);\n\t\tif(pos == -1)\n\t\t\tnotDone = false;\n\t\telse{\n\t\t\tpos++\n\t\t\tindexLoc += (pos-1) + ' ';\n\t\t\tlastFound = pos;\n\t\t}\n\t\tconsole.log(pos);\n\t\tcounter++;\n\t}//end while\n\n\tconsole.log(indexLoc);\n\treturn indexLoc;\n}",
"function differentDigitsNumberSearch(inputArray) {\n let currentNumber;\n let hasUniqueDigits = false;\n \n for(let i = 0; i < inputArray.length; i++) {\n currentNumber = inputArray[i]+'';\n \n for(let digit of currentNumber) {\n if(currentNumber.indexOf(digit) === currentNumber.lastIndexOf(digit)) {\n hasUniqueDigits = true;\n } else {\n hasUniqueDigits = false;\n }\n }\n \n if(hasUniqueDigits) {\n return +currentNumber;\n }\n hasUniqueDigits = false;\n }\n return -1;\n}",
"function smallestSubstringContaining(bigString, smallString) {\n const targetCharCounts = getCharCounts(smallString); //iterate through small string and store the count of charcaters in a hash\n // console.log('targetCharCounts', targetCharCounts);\n const substringBounds = getSubstringBounds(bigString, targetCharCounts);\n // console.log('substringBounds',substringBounds)\n return getStringFromBounds(bigString, substringBounds);s\n }",
"function getFront(mainStr,searchStr)\r\n{\r\n var foundOffset=mainStr.indexOf(searchStr);\r\n if(foundOffset==-1)\r\n return null;\r\n return mainStr.substring(0,foundOffset);\r\n}",
"lookupInt(int) {\n if (int in reverseIntLookup) {\n return reverseIntLookup[int]\n }\n return 7\n }",
"function getIndexPage(numberString) {\n\tvar number = numberString.split(\"/\");\n\treturn number[0];\n}",
"function find_letter(given_id) {\r\n for(var i = 0; i < 7; i++) {\r\n if(game_tiles[i].id == given_id) {\r\n return game_tiles[i].letter;\r\n }\r\n }\r\n // error\r\n return -1;\r\n}",
"function highLow(str) {\n var nums = str.split(\" \");\n return `${Math.max(...nums)} ${Math.min(...nums)}`;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
from better error messaging than gm.toBuffer() | function gmToBuffer (data) {
return new Promise((resolve, reject) => {
data.stream((err, stdout, stderr) => {
if (err) { return reject(err) }
const chunks = []
stdout.on('data', (chunk) => { chunks.push(chunk) })
// these are 'once' because they can and do fire multiple times for multiple errors,
// but this is a promise so you'll have to deal with them one at a time
stdout.once('end', () => { resolve(Buffer.concat(chunks)) })
stderr.once('data', (data) => { reject(String(data)) })
})
})
} | [
"* genFromBuffers (opts) {\n opts = opts === undefined ? {} : opts\n let res\n res = yield * this.expect(4)\n this.magicNum = new Br(res.buf).readUInt32BE()\n if (opts.strict && this.magicNum !== this.constants.Msg.magicNum) {\n throw new Error('invalid magicNum')\n }\n res = yield * this.expect(12, res.remainderbuf)\n this.cmdbuf = new Br(res.buf).read(12)\n res = yield * this.expect(4, res.remainderbuf)\n this.datasize = new Br(res.buf).readUInt32BE()\n if (opts.strict && this.datasize > this.constants.MaxSize) {\n throw new Error('message size greater than maxsize')\n }\n res = yield * this.expect(4, res.remainderbuf)\n this.checksumbuf = new Br(res.buf).read(4)\n res = yield * this.expect(this.datasize, res.remainderbuf)\n this.dataBuf = new Br(res.buf).read(this.datasize)\n return res.remainderbuf\n }",
"async getBuffer(image){\n return new Promise ((resolve, reject) => {\n image\n .quality(100)\n .getBufferAsync(image._originalMime)\n .then((buffer) => {\n resolve(buffer);\n })\n .catch((err) => {\n if (err.toString() === 'Unsupported MIME type: image/gif') {\n let bitmap = new BitmapImage(image.bitmap);\n GifUtil.quantizeDekker(bitmap, 256);\n let newFrame = new GifFrame(bitmap);\n let gifCodec = new GifCodec();\n gifCodec\n .encodeGif([newFrame], {})\n .then((gif) => {\n resolve(gif.buffer);\n })\n .catch((giferror) => {\n reject(giferror);\n });\n } else {\n reject(err);\n }\n });\n });\n }",
"svgOptimize() {\n return async (buffer) => {\n let b = buffer;\n if (Buffer.isBuffer(buffer)) {\n b = buffer.toString();\n }\n\n if (!isSvg(b)) {\n return Promise.resolve(b);\n }\n\n let result;\n\n try {\n result = SVGO.optimize(b, this.getOption('svgo', {}));\n } catch (exception) {\n this.Console.error(exception);\n }\n\n return result && result.data ? Buffer.from(result.data) : Buffer.from(b);\n };\n }",
"function toBuffer(data) {\n return Buffer.isBuffer(data) ? data : new Buffer(data);\n}",
"function toBuffer(v){if(!Buffer.isBuffer(v)){if(typeof v==='string'){if(isHexPrefixed(v)){return Buffer.from(padToEven(stripHexPrefix(v)),'hex');}else{return Buffer.from(v);}}else if(typeof v==='number'){if(!v){return Buffer.from([]);}else{return intToBuffer(v);}}else if(v===null||v===undefined){return Buffer.from([]);}else if(v instanceof Uint8Array){return Buffer.from(v);}else if(BN.isBN(v)){// converts a BN to a Buffer\nreturn Buffer.from(v.toArray());}else{throw new Error('invalid type');}}return v;}",
"async buffer(source, opts = {}) {\n const [res] = await this.capture(source, _.merge(opts, {\n type: 'buffer'\n }));\n return res;\n }",
"errors() {\n return ys(this.rawErrors, (e) => e.join(`\n`));\n }",
"function buildError(err, hackErr) {\n var stack1 = err.stack;\n var stack2 = hackErr.stack;\n var label = hackErr.label;\n\n var stack = [];\n\n stack1.split('\\n').forEach(function(line, index, arr) {\n if (line.match(/^ at GeneratorFunctionPrototype.next/)) {\n stack = stack.concat(arr.slice(0, index));\n return;\n }\n });\n\n stack = stack.concat(stack2.split('\\n').slice(2));\n if (!stack[0].match(/^Error:/)) {\n stack.unshift(err.message);\n }\n if (!!label) {\n stack.unshift('[DEBUG: ' + label + ']');\n }\n stack = stack.join('\\n');\n\n var newError = new Error();\n newError.message = err.message;\n newError.stack = stack;\n\n return newError;\n}",
"function buffer1(geometry) {\n return geometry.buffer(5000);\n}",
"function _getMessage(buffer /*: Buffer*/) /*: Array<BigInt>*/ {\n const words = [];\n let word = 0n;\n let byteLen = 0n;\n for (const c of buffer) {\n const b = byteLen++ & 0x7n;\n word |= BigInt(c) << (b << 3n);\n if (byteLen % 8n == 0n) {\n words.push(word);\n word = 0n;\n }\n }\n // Store original size (in bits)\n const bitSize = (byteLen << 3n) & U64;\n\n // Pad our message with a byte of 0x1 ala MD4 (Tiger1) padding\n const b = byteLen & 0x7n;\n if (b) {\n word |= 0x1n << (b << 3n);\n words.push(word);\n byteLen += 8n - b;\n } else {\n words.push(0x1n);\n byteLen += 8n;\n }\n\n for (byteLen %= 64n; byteLen < 56n; byteLen += 8n) {\n words.push(0n);\n }\n words.push(bitSize);\n return words;\n}",
"onError(err) {\n\t\t\tconsole.warn(`sourcePipe: ${err.stack||err.message||err}`);\n\t\t}",
"static arrayBufferToImage(data)\n\t{\n\t\tvar byteStr = '';\n\t\tvar bytes = new Uint8Array(data);\n\t\tvar len = bytes.byteLength;\n\t\tfor (var i = 0; i < len; i++)\n\t\t\tbyteStr += String.fromCharCode(bytes[i]);\n\t\tvar base64Image = window.btoa(byteStr);\n\t\tvar str = 'data:image/png;base64,' + base64Image;\n\t\tvar img = new Image();\n\t\timg.src = str;\n\t\treturn img;\n\t}",
"function parseElko(buffer) {\n var parsedMessages = [];\n var messages = buffer.toString().split('\\n');\n for (var i in messages) {\n if (messages[i].length == 0) {\n continue;\n }\n try {\n var parsedMessage = JSON.parse(messages[i]);\n parsedMessages.push(parsedMessage);\n } catch (e) {\n log.warn(\"Unable to parse: \" + buffer + \"\\n\\n\" + JSON.stringify(e, null, 2));\n }\n }\n return parsedMessages;\n}",
"function glShaderCompileError(error) {\n addError(error);\n}",
"function tryWriteFile(){\n return writeFile(buildingOutPath, buildingBuffers[id]).catch(function(err){\n if(String(err).indexOf('EMFILE') !== -1){\n console.error('tryWriteFile EMFILE', selectionName, x, y, tile3dsPath, err);\n return new Promise(function(resolve){\n setTimeout(function(){\n resolve(tryWriteFile());\n }, 100);\n });\n }\n else{// forward error\n throw err;\n }\n })\n }",
"function MessageBuffer()\n {\n /**\n * Base class (constructor) of messages this buffer accepted.\n */\n this.Message = Message;\n \n var _impl;\n \n var _buffer = []; // temporary buffer until implementation is provided\n var BUFFER_SIZE_MAX = 1000; // remove REMOVE_WHEN_OVERFLOWED top messages when buffer size exceeds this value\n var REMOVE_WHEN_OVERFLOWED = 200;\n \n /**\n * Provide implementation of the following interface:\n * push(message)\n * flush() // returns promise\n * flushSync() // holds execution until completed\n */\n this.setImpl = function(impl)\n {\n _impl = impl;\n \n _.each(_buffer, function(m)\n {\n _impl.push(m);\n });\n \n _buffer = [];\n };\n \n /**\n * Flush all accumulated messages to server.\n * Return promise.\n */\n this.flush = function()\n {\n return _impl && _impl.flush();\n };\n \n /**\n * Flush all accumulated messages to server synchronously.\n * Pending messages are taken also. So duplication is possible.\n * Hold execution until completed.\n */\n this.flushSync = function()\n {\n return _impl && _impl.flushSync();\n };\n \n /**\n * Push message to buffer.\n */\n this.push = function(message)\n {\n if ( _impl )\n {\n _impl.push(message);\n }\n else\n {\n if ( _buffer.length === BUFFER_SIZE_MAX )\n {\n _buffer = _.tail(_buffer, REMOVE_WHEN_OVERFLOWED);\n if ( window.console && window.console.log )\n {\n window.console.log('MessageBuffer: buffer overflowed, top', REMOVE_WHEN_OVERFLOWED, 'messages removed');\n }\n }\n _buffer.push(message);\n }\n };\n }",
"mimeToString(mimePart, includeHeaders) {\n EnigmailLog.DEBUG(\n \"persistentCrypto.jsm: mimeToString: part: '\" + mimePart.partNum + \"'\\n\"\n );\n\n let msg = \"\";\n let rawHdr = mimePart.headers._rawHeaders;\n\n if (includeHeaders && rawHdr.size > 0) {\n for (let hdr of rawHdr.keys()) {\n let formatted = formatMimeHeader(hdr, rawHdr.get(hdr));\n msg += formatted;\n if (!formatted.endsWith(\"\\r\\n\")) {\n msg += \"\\r\\n\";\n }\n }\n\n msg += \"\\r\\n\";\n }\n\n if (mimePart.body.length > 0) {\n let encoding = getTransferEncoding(mimePart);\n if (!encoding) {\n encoding = \"8bit\";\n }\n\n if (encoding === \"base64\") {\n msg += EnigmailData.encodeBase64(mimePart.body);\n } else {\n let charset = getCharset(mimePart, \"content-type\");\n if (charset) {\n msg += EnigmailData.convertFromUnicode(mimePart.body, charset);\n } else {\n msg += mimePart.body;\n }\n }\n }\n\n if (mimePart.subParts.length > 0) {\n let boundary = EnigmailMime.getBoundary(\n rawHdr.get(\"content-type\").join(\"\")\n );\n\n for (let i in mimePart.subParts) {\n msg += `--${boundary}\\r\\n`;\n msg += this.mimeToString(mimePart.subParts[i], true);\n if (msg.search(/[\\r\\n]$/) < 0) {\n msg += \"\\r\\n\";\n }\n msg += \"\\r\\n\";\n }\n\n msg += `--${boundary}--\\r\\n`;\n }\n return msg;\n }",
"function JSONToBuffer(json) {\n try {\n return new Buffer(JSON.stringify(json));\n }\n catch (err) {\n throw err;\n }\n}",
"static makeMessage(msg) {\n\t\tconst jrResult = new JrResult();\n\t\tjrResult.pushMessage(msg);\n\t\treturn jrResult;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ajoute l'anime dans le select "liste" | function ajouterAnime(anime,liste){
liste.append('<option value=' + anime.id + '>' + anime.titre +'</option>');
} | [
"function ajouterListe(l,liste){\n liste.append('<option value=' + l.id + '>' + l.name +'</option>');\n}",
"function miseAjourDesSelecteurDeJoueurs () {\n $(\"#joueurs > td > select > option\").remove();\n\n $(\"#joueurs > td > select\").each(function (index) {\n let me = $(this);\n let options = me.find(\"option\");\n if (options.length == 0) {\n aJoueurs.forEach(function (item, index, array) {\n me.append($('<option>', {\n value: item,\n text: aAliasJoueur[index]\n }));\n });\n me.change(OnJoueurChange);\n }\n });\n}",
"function popolaListaTemi() {\n $('#select_tema option').remove();\n\n for (index in temi) {\n var corrente = temi[index];\n var label = corrente.replace(new RegExp('_', 'g'), ' ').ucfirst();\n var option;\n if (corrente == tema) {\n option = '<option value=\"' + corrente + '\" selected>Tema ' + label + '</option>';\n } else {\n option = '<option value=\"' + corrente + '\">' + label + '</option>';\n }\n $('#select_tema').append(option);\n }\n}",
"function caricaSelectEnum(list, select, /* Optional */ emptyValue) {\n var i;\n var el;\n var len = list.length;\n var str = \"<option value='\" + (emptyValue || \"\") + \"'></option>\";\n for (i = 0; i < len; i++) {\n el = list[i];\n str += \"<option value='\" + el._name + \"'>\" + el.codice + \" - \" + el.descrizione + \"</option>\";\n }\n return select.append(str);\n }",
"function addoptionsearchtime()\n\t{\n\t\tnumberofmonth = 5;\n\t\ttimenow = new Date();\n\t\t\n\t\tfor(i=0;i<numberofmonth;i++)\n\t\t{\n\t\t\ttimenow.setMonth(timenow.getMonth() - 1);\n\t\t\t//format will be mm/yyyy for value.\n\t\t\tmonth = timenow.getMonth() + 1\n\t\t\tif (month < 10)\n\t\t\t\tmonth = \"0\" + month \n\t\t\tvar keys = month + \"-\" + timenow.getFullYear(); \n\t\t\tvar optvalue = lstmonth[timenow.getMonth()];\n\t\t\t\n\t\t\tdictsearchtime[keys] = optvalue;\n\t\t}\n\t\t\n\t\t// \n\t\t$.each(dictsearchtime,function(key,optvalue){\n\t\t\t\n\t\t\t$('#rptsearch_time').append($('<option>', { value : key }).text(optvalue));\n\t\t});\n\t\t\n\t\t//Add custom \n\t\t$('#rptsearch_time').append($('<option>', { value : 'custom' }).text('custom'));\n\t}",
"function addList (){\n const isiList = document.getElementById('form-list');\n const newIsiList = isiList.value;\n listKegiatan.aktifitas = newIsiList\n runStorage(listKegiatan)\n let li = document.createElement('li');\n li.setAttribute('class', 'pas')\n li.innerHTML = `<input type=\"checkbox\" id=${createId()} />\n <label class=\"baru\" for=${createFor()}><span>${newIsiList}</span></label>\n <p>X<p>`;\n \n const masukkanList = document.querySelector('.cointainer ul')\n masukkanList.appendChild(li);\n \n // menghapus value form yang sudah diketik\n isiList.value = '';\n}",
"function obtenModeloAuto(){\r\n\t\tvar param = \"modeloAuto=ok\";\r\n\t\tvar json = obtenJson(param).rows;\r\n\t\tvar option = '<option id=\"0\" value=\"0\"> - Seleccione - </option>';\r\n\t\tfor(var i = 1; i <= Objectlength(json); i++ )\r\n\t\t\toption+= '<option id=\"'+json[i][\"ma_id\"]+'\" value=\"'+json[i][\"ma_factor\"]+'\">'+json[i][\"ma_nombre\"]+'</option>';\r\n\t\t\r\n\t\t$(\"#modeloAuto\").empty();\r\n\t\t$(\"#modeloAuto\").append(option);\r\n\t}",
"function dynamicDateList(location) {\n var listItems = document.querySelector(location);\n for (var i = 0; i < 7; i++) {\n listItems.options[i + 1].innerHTML = getCurrentDate(i);\n }\n}",
"function limparAgendaDomicilio() {\n $('#AgendaAtendimentoDomicilioDiaSemana').val('');\n $('#AgendaAtendimentoDomicilioHorarioInicial').val('');\n $('#AgendaAtendimentoDomicilioHorarioFinal').val('');\n $('#AgendaAtendimentoDomicilioHorarioFinal').attr('disabled', true);\n $('#AgendaAtendimentoDomicilioUnidadeAtendimentoId').val('');\n $('#AgendaAtendimentoDomicilioMunicipioId').val('');\n\n clearSelectedItensMultiSelect('AgendaAtendDomicilioTipologia');\n $(\"#AgendaAtendDomicilioTipologia\").multiSelect('refresh');\n //botões para inserir\n $('#adicionarAgenda').removeClass('displayNone');\n\n //Botões para Atualizar\n $('#atualizarAgenda').addClass('displayNone');\n }",
"function updateTimes() {\n\t$('#time').empty();\n\tvar option;\n\tvar week = $('#week').val();\n\tvar numGames = GAMES[week-1].length;\n\n\tfor(var i = 0; i < numGames; i++) {\n\t\toption = '<option value=\"' + GAMES[week-1][i].time + '\" data-game=\"' + i + '\">';\n\t\toption += GAMES[week-1][i].time;\n\t\toption += '</option>';\n\n\t\t$('#time').append(option);\n\t}\n}",
"function getTimelines() {\n $.get(\"/api/timeline/user/\", function (data) {\n var timelineDrop = $(\".timeline-select\");\n for (var i = 0; i < data.length; i++) {\n $(\"<option />\", {\n value: data[i].id,\n text: data[i].title\n }).appendTo(timelineDrop);\n }\n })\n }",
"addLenses(lenses){\n let selectLenses = document.getElementById('select_lenses');\n for (let i in lenses){\n selectLenses.innerHTML += `<option> ${lenses[i]} </option>`;\n }\n }",
"function addRestaurantsInSelect( xmlFromServer)\n{\n\tvar xmlListRestaurants= xmlFromServer.getElementsByTagName(\"RESTAURANT\");\n\tvar id,name;\n\t\n\t/*\n\t * J'ajoute le choix, sans restaurant pour qu'un restaurateur \n\t * ne sois assigne a aucun resataurant \n\t * au moment de la creation de son compte\n\t */\n\taddNewOptionInSelect(\"restaurantList\",0,\"Liste des Restaurants\");\n\t\n\tfor (var i=0;i<xmlListRestaurants.length;i++)\n\t { \n\t\t\n\t\tid=xmlListRestaurants[i].getElementsByTagName(\"ID\")[0].childNodes[0].nodeValue;\n\t\t\n\t\tname=xmlListRestaurants[i].getElementsByTagName(\"NAME\")[0].childNodes[0].nodeValue;\n\t\t\n\t\t//J'ajoute le restaurant dans la liste deroulante\n\t\taddNewOptionInSelect(\"restaurantList\",id,name);\n\t\n\t}\n}",
"function addToSelect(values) {\nvalues.sort();\nvalues.unshift('None'); // Add 'None' to the array and place it to the beginning of the array\nvalues.forEach(function(value) {\n var option = document.createElement(\"option\");\n option.text = value;\n municipalSelect.add(option);\n});\nreturn setLotMunicipalExpression(municipalSelect.value);\n}",
"function roomListUpdate(\n/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/\n /**\n * No arguments. */\n)\n/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/\n{\n console.log(2, \"The room list has been updated.\");\n $('#rooms select').empty();\n var room_added = false;\n\n for (k in Callcast.roomlist) {\n var optionline = '<option jid=' + k + ' room=' + Strophe.getNodeFromJid(k);\n //\n // If the room we're adding here is the same room we're already *IN*, then select it in the list.\n //\n if (Callcast.room === k)\n optionline += ' selected=selected';\n optionline += '>' + Callcast.roomlist[k] + '</option>';\n\n $('#rooms select').append(optionline);\n room_added = true;\n }\n\n if (!room_added)\n $('#rooms select').append(\"<option>[None Yet]</option>\");\n \n}",
"afficherMines() {\n for (let i = 0; i < this.listeMines.length; i++)\n this.listeMines[i].afficher();\n }",
"inputDataMahasiswa(nama, tgl_lahir, nim) {\n console.log();\n const prodi = Menu.process.selectProdi();\n\n console.log();\n listMahasiswa.push(new Mahasiswa(nama, tgl_lahir, nim, prodi))\n }",
"selectLocationList(locationData) {\n this.element.innerHTML = \"\";\n locationData.forEach((location, index) => {\n const option = document.createElement(\"option\");\n option.textContent = location.placename;\n option.value = index;\n this.element.appendChild(option);\n });\n }",
"function oppdaterSelect(tx, res, selId) {\r\n var rec, i;\r\n /*\r\n * Løp gjennom resultatene og legg til elementer til dropdown\r\n */\r\n for ( i = 0; i < res.rows.length; i++) {\r\n rec = res.rows.item(i);\r\n $(selId).append($(\"<option />\").val(rec.id).text(rec.navn));\r\n };\r\n /*\r\n * Sett fokus på første element (index 0 er første) og oppdater skjerm\r\n */\r\n $(selId).prop('selectedIndex', 0).selectmenu('refresh');\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
stops the heartbeat and displays the game over message | function stopHeartbeat() {
GAME_OVER = true;
addMessage("Game over! Score: &e0", "error");
delete_cookie("chocolateChipCookie");
clearInterval(nIntervId);
} | [
"function gameLose() {\n gameState.active = false;\n gameReset();\n var startBtn = \"Retry\";\n var startText = \"<div class=\\\"splashtext\\\">You died :(</div>\";\n gamescreen(startBtn, startText);\n}",
"function messageLosing() {\n\n $(`<section class=\"game-over\"><div class=\"message-box\"><h2>Try harder Marites 😔</h2>\n <h3>Kulang ang almusal mong tsismis</h3>\n <p>Number of attempts: ${attempts}</p>\n <p>Total Time: ${60-(seconds/1000)} seconds <p>Rating: ${stars} </p><p><i class=\"fas fa-undo\"></i><i class=\"fas fa-sign-out-alt\"></i><object data=\"leaderboard.svg\"></object>\n </p></div></section>`).insertAfter($('.gamebg'));\n restart(); goBack();\n $('.message-box').fadeIn(1000);\n }",
"function gameOver() {\n update($question, \"Game Over. You scored \" + score + \" points.\");\n }",
"gameOver(result) {\n document.getElementById('overlay').style.display = '';\n if (result === 'win') {\n document.getElementById('game-over-message').className = 'win';\n document.getElementById('game-over-message').innerHTML = `<br><i>Wow, you reached 88 miles per hour!</i> 🏎️💨 <p>Nailed it! The phrase was \"${this.activePhrase.phrase.toUpperCase()}\"!</p>`;\n document.getElementById('btn__reset').textContent = 'Go back to the future & try again?';\n } else {\n document.getElementById('game-over-message').className = 'lose';\n document.getElementById('game-over-message').innerHTML = `<br><i>Think, McFly, think!</i> 😖💭 <p>Better luck next time! The phrase was \"${this.activePhrase.phrase.toUpperCase()}\".</p>`;\n document.getElementById('btn__reset').textContent = 'Go back in time & try again?';\n }\n this.resetGame();\n }",
"function updateYouLost() {\r\n if ( slotIds.indexOf(board[clickCount]) > -1 ) { //you're in a slot;\r\n document.getElementById(clickCount.toString()).className = 'losingSlot';\r\n } else if ( blockIds.indexOf(board[clickCount]) > -1 ) { // you're on a block\r\n document.getElementById(clickCount.toString()).className = 'losingBlock';\r\n }\r\n loseSound.play();\r\n gameOver = true;\r\n levelCount = 1;\r\n scoreCount = 0;\r\n timeLeft = 80;\r\n headerElement.textContent = 'you lost';\r\n headerElement.style.color = 'rgba(239,83,80,0.9)';\r\n scoreElement.textContent = `${scoreCount}`; \r\n clearInterval(setTimer);\r\n timerBar.style.display = 'none';\r\n nextLevelButton.style.display = 'flex';\r\n nextLevelButton.textContent = `restart?`;\r\n singleClickElement.style.display = 'none';\r\n doubleClickElement.style.display = 'none';\r\n mainElement.style.transition = 'auto';\r\n mainElement.style.backgroundColor = 'rgba(237, 240, 241, 0.9)';\r\n}",
"endGame() {\n if (this.health <= 0) {\n backgroundMusic.stop();\n failSound.play();\n state = \"GAMEOVER\";\n return;\n } else if (this.score >= 40) {\n state = \"GAMEWIN\";\n return;\n }\n }",
"function end() {\n\t// set GAMEOVER to true\n\tGAME_OVER = true;\n\t// call clear methods\n\tUFO.clear();\n\tBULLET.clear();\n\tBOOM.clear();\n\t// fill the score\n\tscore.textContent = GAME_SCORE;\n\t// show score board\n\tgame.classList.remove('active');\n}",
"function game_over_msg() {\n return \"Game Over. Scoring may not be done yet\";\n }",
"function end_game(){\n\tsocket.emit(\"leave_game\");\n}",
"function looseGame() {\n countLooses++;\n $(\"#looses\").text(countLooses);\n $(\"#totalScore\").text(sumScore + \" Loose!\");\n setTimeout(function() {\n restartGame();\n }, 2000);\n }",
"function battleTimer() {\n battleCountdown--;\n // $(\"#battle-timer\").html(\"<h3>\" + \"Battle in: \" + battleCountdown + \"</h3>\");\n $(\"#battle-timer\").html(\"<h3>Battle!</h3><h3>\" + battleCountdown + \"</h3>\");\n if (battleCountdown === 0) {\n stopBattleTimer();\n $(\"#card-timer\").hide();\n var winner = determineWinner();\n updateWinCountAndResetSelection(winner);\n displayResults(winner);\n transitionToNextRound();\n }\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 closeInstructions() {\n sadMusic.play();\n // Loop music\n sadMusic.loop = true;\n\n // Hide the overlay to reveal content\n $(\"#overlay\").hide();\n\n // setTimeout since it only occurs once\n setTimeout(function() {\n $label.fadeOut(LABEL_FADEOUT_DURATION);\n }, LABEL_FADEOUT_DELAY);\n}",
"function runGameOver(){\n\n // overwrite ball position\n ball.x=width/2;\n ball.y=width/2;\n\n // draw new background to hide the regular game screen\n background(0);\n // show score so we can keep in mind who won\n displayScore();\n\n // now load cat\n moveCat();\n drawCatHead();\n\n // display paddles\n displayPaddle(leftPaddle);\n displayPaddle(rightPaddle);\n\n // handle bullet motion and display\n moveBullet(leftPaddle);\n moveBullet(rightPaddle);\n displayBullet(leftPaddle);\n displayBullet(rightPaddle);\n\n // check bullet's collision with cat\n handleCatCollision(leftPaddle);\n handleCatCollision(rightPaddle);\n\n // display game over text:\n // the winner, and instructions to shoot water at the cat\n fill(fgColor);\n //check who won\n if(leftPaddle.score>rightPaddle.score) {\n // left player won\n text(\"game over. left player wins. spray cat to reclaim the ball and field. \\nleft player: press 1 to shoot. right player: press 0 to shoot.\", width/2, height/2);\n} else if (leftPaddle.score<rightPaddle.score) {\n // right player won\n text(\"game over. right player wins. spray cat to reclaim the ball and field. \\nleft player: press 1 to shoot. right player: press 0 to shoot.\", width/2, height/2);\n}else {\n // tie\n text(\"game over. it's a tie. spray cat to reclaim the ball and field. \\nleft player: press 1 to shoot. right player: press 0 to shoot.\", width/2, height/2);\n}\n}",
"function shutdown() {\n console.log('shutdown() for game state \"' + game.state.current + '\"');\n console.log('\\n');\n }",
"function showGameOver()\n{ \n stage.removeChild(character.image);\n stage.removeChild(coin.image);\n stage.removeChild(bullet.image);\n if(game_difficulty === MEDIUM_MODE || game_difficulty === HARD_MODE)\n {\n stage.removeChild(balloon.image);\n stage.removeChild(balloon.bomb.image);\n }\n if(game_difficulty === HARD_MODE)\n { \n \n stage.removeChild(text_manager.boss_life); \n stage.removeChild(text_manager.boss_text); \n stage.removeChild(boss.image);\n } \n text_manager.showGameOver();\n}",
"function updateYouWon() {\r\n gameOver = true;\r\n headerElement.textContent = 'you won';\r\n headerElement.style.color = 'rgba(139,195,74,0.9)';\r\n levelCount++;\r\n clearInterval(setTimer);\r\n timeLeft = 80 - ((levelCount-1)*10);\r\n timerBar.style.display = 'none';\r\n nextLevelButton.style.display = 'flex';\r\n nextLevelButton.textContent = `to level ${levelCount}?`;\r\n singleClickElement.style.display = 'none';\r\n doubleClickElement.style.display = 'none';\r\n mainElement.style.transition = 'auto';\r\n mainElement.style.backgroundColor = 'rgba(181, 187, 189, 0.9)';\r\n winSound.play();\r\n}",
"closeBattle(){\n bossNum++;\n// eventNumber++;\n// eventTextNumber = 0;\n this.game.time.events.add(Phaser.Timer.SECOND * this.closWindowDelay, ()=>{\n this.game.camera.fade(0x000000, 1000);\n this.game.time.events.add(Phaser.Timer.SECOND * this.closWindowDelay, ()=>{\n this.clearEverything(); \n this.game.camera.resetFX();\n enemyStats[bossNum].currentHP = enemyStats[bossNum].currentHP;\n\n \n \n }, this);\n \n }, this);\n \n// music.pause();\n// music.destroy();\n// this.selectMusic();\n\n \n }",
"function heartbeatCallback(heartbeatCtx) {\n console.log('heartbeatCallback called');\n if (heartbeatCtx.description !== statusDescription) {\n statusDescription = heartbeatCtx.description;\n }\n if (heartbeatCtx.startGameLabel !== startGameLabel) {\n startGameLabel = heartbeatCtx.startGameLabel;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get object based on position | function getObject(position,array){
for (var i of array){
if (i.pos == position){
return i;
}
}
} | [
"function findObject(index) {\n return repository[index];\n }",
"get(pos) {\n let items = this.items;\n if (pos < 0 || pos >= items.length)\n return;\n return items[pos];\n }",
"posById(id){\n let slot = this._index[id];\n return slot ? slot[1] : -1\n }",
"function pullPlayerObj(x) {\n let index = findInArray(characterlist, x);\n let character = characterlist[index];\n return character;\n }",
"GetEntityPosition( entity ) { return null; }",
"closestObject( type, x )\n {\n let index = 0, dist = 10 ** 6, objX = undefined;\n\n // find the closest building to guard\n for( index = 0;index < this.objects.length;index++ )\n {\n let o = this.objects[ index ];\n\n const d = Math.abs( o.p.x - x );\n\n if( ( o.oType == type ) && ( d < dist ) )\n {\n dist = d;\n objX = o.p.x;\n }\n }\n\n return objX;\n }",
"function findrock(x,y){\n\n for (let t of rocksArray){ // goes through all rocks and returns rock at givin location\n if((t.x - 20 <= x) && (t.x + 20 >= x) && (t.y - 20 <= y) && (t.y + 20 >= y)){\n //returns the object\n return (t);\n }\n }\n return null;\n}",
"getActor(x, y) {\n\t\tfor(var i=0;i<this.actors.length;i++) {\n\t\t\tif(this.actors[i].x==x && this.actors[i].y==y) {\n\t\t\t\treturn this.actors[i];\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"findObject(id) {\n\t\tfor (var i in this.gameobjects) {\n\t\t\tif (this.gameobjects[i].id == id) {\n\t\t\t\treturn this.gameobjects[i];\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}",
"getPosition(room, floor) {\n var roomsInFloor = this.getRoomsInfloor(floor)\n var roomInFloor = roomsInFloor.find(item => item.room.Name === room.Name)\n return roomInFloor.position;\n }",
"function pullEnemyObj(y) {\n let eindex = findInArray(enemylist, y);\n let enemy = enemylist[eindex];\n return enemy;\n }",
"function getCandidatePosition(anIndex) {\n return candidatePositions[anIndex];\n } // getCandidatePosition",
"cursorAt(pos, side = 0, mode = 0) {\n let scope = CachedNode.get(this) || this.topNode\n let cursor = new TreeCursor(scope)\n cursor.moveTo(pos, side)\n CachedNode.set(this, cursor._tree)\n return cursor\n }",
"function editorSelectObject() {\n\tvar cursorWorldPos = screenToSpace(cursor_x, cursor_y);\n\tvar toReturn = [1e1001, undefined];\n\tvar dist;\n\tfor (var p=0; p<game_map.statics.length; p++) {\n\t\tdist = Math.sqrt(Math.pow(cursorWorldPos[0] - game_map.statics[p].x, 2) + Math.pow(cursorWorldPos[1] - game_map.statics[p].y, 2));\n\t\tif (dist < toReturn[0]) {\n\t\t\ttoReturn[0] = dist;\n\t\t\tif (dist < game_map.statics[p].r) {\n\t\t\t\ttoReturn[1] = game_map.statics[p];\n\t\t\t\tp = game_map.statics.length;\n\t\t\t}\n\t\t}\n\t}\n\n\t//dynamic objects as well\n\tfor (var p=0; p<game_map.dynamics.length; p++) {\n\t\tdist = Math.sqrt(Math.pow(cursorWorldPos[0] - game_map.dynamics[p].x, 2) + Math.pow(cursorWorldPos[1] - game_map.dynamics[p].y, 2));\n\t\tif (dist < toReturn[0]) {\n\t\t\ttoReturn[0] = dist;\n\t\t\tif (dist < game_map.dynamics[p].r) {\n\t\t\t\ttoReturn[1] = game_map.dynamics[p];\n\t\t\t\tp = game_map.dynamics.length;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn toReturn;\n}",
"function getPosition(n)\n\t{\n\t\tn *= 3;\n\t\treturn new Vector3D(positions.slice(n, n + 3));\n\t}",
"function getBoxFromMouseLocation() {\n\tfor(box in boxes) {if(boxes[box].sprite.position.x <= mouseX) {\n\t\t\tif(boxes[box].sprite.position.x + boxes[box].sprite.width > mouseX) {\n\t\t\t\tif(boxes[box].sprite.position.y <= mouseY) {\n\t\t\t\t\tif(boxes[box].sprite.position.y + boxes[box].sprite.height > mouseY) {\n\t\t\t\t\t\treturn boxes[box];\n\t\t\t\t\t}\n\t\t\t\t}\t\t\n\t\t\t}\n\t\t}\n\t}\n\treturn null;\n}",
"function getLocator(obj) {\n return obj.locator;\n }",
"get(index) {\n let foundNode = this._find(index);\n return foundNode ? foundNode.value : undefined;\n }",
"get(index){\n // return the value of an element at given index\n return memory.get(index);\n }",
"function getMid(obj) {\r\n\tvar top = obj.offset().top;\r\n\tvar left = obj.offset().left;\r\n\tvar height = obj.height();\r\n\tvar width = obj.width();\r\n\r\n\tvar mid = {\r\n\t\tx : left + width / 2,\r\n\t\ty : top + height / 2\r\n\t}\r\n\r\n\treturn mid;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the canonical form of a locale name lowercase with `_` replaced with ``. | function normalizeLocale(locale) {
return locale.toLowerCase().replace(/_/g, '-');
} | [
"function makeStandardJSName(s){\n return s.replace(/_([a-z])/g, function (g) { return g[1].toUpperCase(); });\n }",
"function camelize(name, forceLower){\n if (firstDefined(forceLower, false)) {\n name = name.toLowerCase();\n }\n return name.replace(/\\-./g, function(u){\n return u.substr(1).toUpperCase();\n });\n }",
"_getInitial(name) {\n return name[0].toUpperCase();\n }",
"function keyify(str) {\r\n str = str.replace(/[^a-zA-Z0-9_ -]/g, '');\r\n str = trim(str);\r\n str = str.replace(/\\s/g, '_');\r\n return str.toLowerCase();\r\n}",
"function cleanStationName(name) {\n name = name.replace(\"asema\", \"\")\n name = name.replace(\"_(Finljandski)\", \"\")\n name = name.replace(\"Lento\", \"Lentokenttä\")\n return name;\n}",
"function _normalize(phrase) {\n\n // Lower case it\n phrase = phrase.toLocaleLowerCase();\n\n // Normalize special characters by using the characters in the charMap hash\n phrase = phrase.replace(/[,./!?àáâãāçćčèéêëēėęîïíīįìłñńňôòóōõřśšťûüùúūůÿýžżŻź]/g, function(ch) {\n return charMap[ch] || ch;\n });\n\n return phrase;\n }",
"function normalize(word) {\n\n return stem(word.toLowerCase()).replace(/[^a-z]/g, '');\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 normalizeIconName(name) {\n const numberLeadingName = !isNaN(Number(name.charAt(0)));\n const parts = name.split(\"-\");\n if (parts.length === 1) {\n return numberLeadingName ? `i${name}` : name;\n }\n return parts\n .map((part, index) => {\n if (index === 0) {\n return numberLeadingName ? `i${part.toUpperCase()}` : part;\n }\n return part.charAt(0).toUpperCase() + part.slice(1);\n })\n .join(\"\");\n}",
"function standardizeCountryName(countryName) {\n const possibleMapping = constants.countryMapping.filter(mapping => mapping.possibleNames.indexOf(countryName) >= 0);\n return (possibleMapping.length == 1 ? possibleMapping[0].standardizedName : countryName.toLowerCase());\n}",
"function reduce_era_name(name) {\r\n\t\t\t\treturn name.trim()\r\n\t\t\t\t// 去除不需要以 space 間隔之紀元名中之 space。\r\n\t\t\t\t.replace(REDUCE_PATTERN, '$1$2');\r\n\t\t\t}",
"ucName() {\n return this.name.substr(0,1).toUpperCase() + this.name.substr(1);\n }",
"function norm(str){\n return str\n .toLowerCase()\n .replace(/Á|á/,'azzz').replace(/É|é/,'ezzz').replace(/Í|í/,'izzz')\n .replace(/Ð|ð/,'dzzz').replace(/Ó|ó/,'ozzz').replace(/Ú|ú/,'uzzz')\n .replace(/Ý|ý/,'yzzz').replace(/Þ|þ/,'zz').replace(/Æ|æ/,'zzz').replace(/Ö|ö/,'zzzz');\n }",
"function formatDictionaryKey(key){\n var re = /\\s+/g;\n var k = key.toLowerCase().replace(re, \"\");\n return k;\n}",
"function capitalizeAndSpace(str) {\n\tvar newstr = str.replace(/_+/g, ' ');\n\t\n newstr = newstr.replace(/\\w+/g, function(a){\n return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();\n });\n\n return newstr;\n}",
"function addunderscores( str ){ return str.replace(/\\'|\\\"| /g, '_'); }",
"function kebabToCamel(s) {\r\n return s.replace(/(\\-\\w)/g, function (m) { return m[1].toUpperCase(); });\r\n}",
"function normalizeHeader_(header) {\n var key = \"\";\n var upperCase = false;\n for (var i = 0; i < header.length; ++i) {\n var letter = header[i];\n if (letter == \" \" && key.length > 0) {\n upperCase = true;\n continue;\n }\n if (!isAlnum_(letter)) { \n continue;\n }\n if (key.length == 0 && isDigit_(letter)) {\n continue; // first character must be a letter\n }\n if (upperCase) {\n upperCase = false;\n key += letter.toUpperCase();\n } else {\n key += letter.toLowerCase();\n }\n }\n return key;\n}",
"function sanitize(name) {\n if(!name) return;\n return name.toLowerCase().replace(/\\.js$/, '').replace(/\\s/g, '-');\n}",
"getOwnerToGoodCase(name) {\n if (_.includes(this.oracleReservedWords, name.toUpperCase())) {\n //The name is reserved, we return in normal case\n return name;\n } else {\n //The name is not reserved, we return in uppercase\n return name.toUpperCase();\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to load View for a given year and ICDCode | function loadViewForYear(jahr, icd, description) {
// Set sideNav to false
sideNav = false;
// show details div
$('#some-details').show();
$('#pieChart').show();
// Set new headers
setAllHeaders(icd, description, "", jahr);
// Add Year Overview Button
addYearOverviewButton();
// Add button to Header
if(icd.localeCompare("INSGESAMT") !== 0) {
addUplinkButton();
} else {
setKapitel("Alle Krankheiten");
setGruppe("");
}
// remove bar chart
removeBarChart(0, 0);
// remove pie chart
removePieChart();
// call method to load appropriate data
getCredentialsByIcd(jahr, icd, 0);
// update sidebar menu
getCredentialsByIcd(jahr, icd, 1);
} | [
"function loadViewForAllYears(icd, text) {\r\n\r\n\t// set sideNav to true\r\n\tsideNav = true;\r\n\r\n\r\n\r\n\t// Hide tooltip to prevent it from staying after click\r\n\t$(this).tooltip('hide');\r\n\r\n\tsetSectionHeader(\"2000 - 2014\");\r\n\r\n\t// remove stacked barchart\r\n\tremoveBarChart(960, 500);\r\n\r\n\t// remove pie chart\r\n\tremovePieChart();\r\n\r\n\t// hide year overview button\r\n\t$('#header-klasse > button').hide();\r\n\r\n\t// hide details div\r\n\t$('#some-details').hide();\r\n\t$('#pieChart').hide();\r\n\r\n\t// event.preventDefault();\r\n\r\n\tdocument.getElementById('kapitel-text').innerHTML = icd;\r\n\tdocument.getElementById('header-gruppe').innerHTML = text;\r\n\r\n\tif(icd.localeCompare(\"Alle Krankheiten\") == 0) {\r\n\t\ticd = \"INSGESAMT\";\r\n\t} else {\r\n\t\t// Add Uplink Button\r\n\t\taddUplinkButton();\r\n\t}\r\n\r\n\tgetCredentialsByIcd(2000, icd, 1, true);\r\n\r\n\tgetDataByIcd(icd);\r\n\r\n}",
"function loadBudgetEdit(month_year) {\n if (mydb) {\n //Get all the cars from the database with a select statement, set outputCarList as the callback function for the executeSql command\n mydb.transaction(function (t) {\n t.executeSql(\"SELECT * FROM budget WHERE month_year=?\", [month_year], function (transaction, results) {\n if (results.rows.length>=1) {\n loadBudgetEditPage(results.rows.item(0));\n }\n });\n });\n } else {\n var data = {};\n data['id']=1;\n data['month_year']='2015-12-12';\n data['budget']='7,777,700';\n loadBudgetEditPage(data);\n }\n}",
"function getYearData(year){\n year = (year instanceof Date) ? year.getFullYear() : year;\n if (data[year] === undefined) throw Error(\"No UK inflation data available for the year \"+year);\n return data[year];\n}",
"fetchSchoolYear(context, id) {\n return new Promise((resolve, reject) => {\n ApiService.init()\n ApiService.get(`/api/school-year/${id}/show`, {}).then(\n response => {\n resolve(response)\n },\n error => {\n reject(error)\n }\n )\n })\n }",
"static view() {\n const coursesByDepartment = getCoursesByDepartment(\n courses.list,\n selectedDepartment,\n );\n return getUniqueYears(coursesByDepartment).map(year =>\n m(expandableContent, { name: `Year ${year}`, level: 0 }, [\n getUniqueLecturesByYear(\n coursesByDepartment,\n year,\n ).map(lecture =>\n m(\n expandableContent,\n { name: lecture, level: 1 },\n coursesByDepartment\n .filter(course => course.lecture.year === year)\n .filter(course => course.lecture.title === lecture)\n .map(displayCard),\n ))]));\n }",
"function getCredentialsByIcd(jahr, icd_code, followup, years) {\r\n\r\n\tvar credentials;\r\n\r\n\tvar queryString = \"http://localhost:3030/medstats_v2/?query=PREFIX+med%3A+%3Chttp%3A%2F%2Fpurl.org%2Fnet%2Fmedstats%3E%0A%0ASELECT+%3Ftyp+%3Fkap+%3Fgru%0A%0AWHERE+%7B%0A++%3Fx+med%3Ajahr+%22\" + jahr + \"%22+.%0A++%3Fx+med%3Adiagnose_icd+%22\" + icd_code +\"%22+.%0A++%3Fx+med%3Aicd_typ+%3Ftyp+.%0A++%3Fx+med%3Aicd_kapitel+%3Fkap+.%0A++%3Fx+med%3Aicd_gruppe+%3Fgru+.%0A%7D\";\r\n\r\n\t$.getJSON(queryString, function (data) {\r\n\t\t$.each(data.results, function (key, val) {\r\n\t\t\t$.each(val, function (m, n) {\r\n\t\t\t\t$.each(n.typ, function (typkey, typval) {\r\n\t\t\t\t\tif (typkey.localeCompare('value') == 0) {\r\n\t\t\t\t\t\ttyp = typval;\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\t$.each(n.kap, function (kapkey, kapval) {\r\n\t\t\t\t\tif (kapkey.localeCompare('value') == 0) {\r\n\t\t\t\t\t\tkap = kapval;\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\t$.each(n.gru, function (grukey, gruval) {\r\n\t\t\t\t\tif (grukey.localeCompare('value') == 0) {\r\n\t\t\t\t\t\tgru = gruval;\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\r\n\t\t\t\tcredentials = ({jahr: jahr, icd_code: icd_code, typ: typ, kapitel: kap, gruppe: gru});\r\n\t\t\t\t\r\n\t\t\t})\r\n\t\t});\r\n\r\n\t\t// Get Data for Year View\r\n\t\tif(followup == 0) {\r\n\t\t\tgetDataByYear(credentials.kapitel, credentials.gruppe, credentials.typ, credentials.jahr, credentials.icd_code);\r\n\t\t// Get Data for Menu\r\n\t\t} else if (followup == 1) {\r\n\t\t\tgetDataForMenu(credentials.typ, credentials.kapitel, credentials.gruppe, credentials.icd_code, false);\r\n\r\n\t\t} else if (followup == 2) {\r\n\t\t\tconsole.log(\"THIS!!!\" + credentials.typ);\r\n\t\t\tgetHigherLevelIcd(credentials.kapitel, credentials.gruppe, credentials.typ, credentials.jahr, credentials.icd_code, years);\r\n\t\t} else {\r\n\t\t\tconsole.log(\"Something went wrong\");\r\n\t\t}\r\n\t\t\r\n\r\n\t});\r\n\t\r\n}",
"function getDataByYear(kapitel, gruppe, typ, jahr, icd) {\r\n\r\n\tvar yearData = [];\r\n\tvar queryString;\r\n\r\n\t// All \"Kapitel\"\r\n\tif(typ.localeCompare(\"Insgesamt\") == 0) {\r\n\t\tqueryString = \"http://localhost:3030/medstats_v2/?query=PREFIX+med%3A+%3Chttp%3A%2F%2Fpurl.org%2Fnet%2Fmedstats%3E%0A%0ASELECT+%3Fkap+%3Fpe+%3Fpt+%3Fpg+%3Fdia_icd+%3Fdia_text%0AWHERE+%7B%0A++%3Fx+med%3Ajahr+%22\" + jahr + \"%22+.%0A++%3Fx+med%3Aicd_typ+%22Kapitel%22+.%0A++%3Fx+med%3Adiagnose_icd+%3Fdia_icd+.%0A++%3Fx+med%3Adiagnose_text+%3Fdia_text+.%0A++%3Fx+med%3Apatienten_entlassen+%3Fpe+.%0A++%3Fx+med%3Apatienten_gestorben+%3Fpt+.%0A++%3Fx+med%3Apatienten_gesamt+%3Fpg+.%0A%7D\";\r\n\t// All \"Gruppen\" of current \"Kapitel\"\r\n\t} else if(typ.localeCompare(\"Kapitel\") == 0) {\r\n\t\tqueryString = \"http://localhost:3030/medstats_v2/?query=PREFIX+med%3A+%3Chttp%3A%2F%2Fpurl.org%2Fnet%2Fmedstats%3E%0A%0ASELECT+%3Fgru+%3Fpe+%3Fpt+%3Fpg+%3Fdia_icd+%3Fdia_text%0AWHERE+%7B%0A++%3Fx+med%3Ajahr+%22\" + jahr + \"%22+.%0A++%3Fx+med%3Aicd_typ+%22Gruppe%22+.%0A++%3Fx+med%3Aicd_kapitel+\" + kapitel + \"+.%0A++%3Fx+med%3Adiagnose_icd+%3Fdia_icd+.%0A++%3Fx+med%3Adiagnose_text+%3Fdia_text+.%0A++%3Fx+med%3Apatienten_entlassen+%3Fpe+.%0A++%3Fx+med%3Apatienten_gestorben+%3Fpt+.%0A++%3Fx+med%3Apatienten_gesamt+%3Fpg+.%0A%7D\";\r\n\t// All \"Klassen\" of current \"Gruppe\"\r\n\t} else if(typ.localeCompare(\"Gruppe\") == 0){\r\n\t\tqueryString = \"http://localhost:3030/medstats_v2/?query=PREFIX+med%3A+%3Chttp%3A%2F%2Fpurl.org%2Fnet%2Fmedstats%3E%0A%0ASELECT+%3Fkla+%3Fpe+%3Fpt+%3Fpg+%3Fdia_icd+%3Fdia_text%0AWHERE+%7B%0A++%3Fx+med%3Ajahr+%22\" + jahr + \"%22+.%0A++%3Fx+med%3Aicd_typ+%22Klasse%22+.%0A++%3Fx+med%3Aicd_kapitel+\" + kapitel + \"+.%0A++%3Fx+med%3Aicd_gruppe+\" + gruppe + \"+.%0A++%3Fx+med%3Adiagnose_icd+%3Fdia_icd+.%0A++%3Fx+med%3Adiagnose_text+%3Fdia_text+.%0A++%3Fx+med%3Apatienten_entlassen+%3Fpe+.%0A++%3Fx+med%3Apatienten_gestorben+%3Fpt+.%0A++%3Fx+med%3Apatienten_gesamt+%3Fpg+.%0A%7D\";\r\n\t// Nur die Klasse selbst (Query überhaupt notwendig?!?!)\r\n\t} else {\r\n\t\tconsole.log(\"Klasse query gets called\");\r\n\t\tqueryString = \"http://localhost:3030/medstats_v2/?query=PREFIX+med%3A+%3Chttp%3A%2F%2Fpurl.org%2Fnet%2Fmedstats%3E%0A%0ASELECT+%3Fpe+%3Fpt+%3Fpg+%3Fdia_icd+%3Fdia_text%0AWHERE+%7B%0A++%3Fx+med%3Ajahr+%22\" + jahr + \"%22+.%0A++%3Fx+med%3Adiagnose_icd+%22\" + icd + \"%22+.%0A++%3Fx+med%3Apatienten_entlassen+%3Fpe+.%0A++%3Fx+med%3Apatienten_gestorben+%3Fpt+.%0A++%3Fx+med%3Apatienten_gesamt+%3Fpg+.%0A++%3Fx+med%3Adiagnose_text+%3Fdia_text+.%0A++%3Fx+med%3Adiagnose_icd+%3Fdia_icd%0A%7D\";\r\n\t}\r\n\r\n\t// console.log(queryString);\r\n\r\n\t$.getJSON(queryString, function (data) {\r\n\t\t$.each(data.results, function (key, val) {\r\n\t\t\t$.each(val, function (m, n) {\r\n\t\t\t\t$.each(n.dia_icd, function (dia_icdkey, dia_icdval) {\r\n\t\t\t\t\tif (dia_icdkey.localeCompare('value') == 0) {\r\n\t\t\t\t\t\tdia_icd = dia_icdval;\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\t$.each(n.dia_text, function (dia_textkey, dia_textval) {\r\n\t\t\t\t\tif (dia_textkey.localeCompare('value') == 0) {\r\n\t\t\t\t\t\tdia_text = dia_textval;\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\t$.each(n.pe, function (pekey, peval) {\r\n\t\t\t\t\tif (pekey.localeCompare('value') == 0) {\r\n\t\t\t\t\t\tpe = peval;\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\t$.each(n.pt, function (ptkey, ptval) {\r\n\t\t\t\t\tif (ptkey.localeCompare('value') == 0) {\r\n\t\t\t\t\t\tpt = ptval;\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\t$.each(n.pg, function (pgkey, pgval) {\r\n\t\t\t\t\tif (pgkey.localeCompare('value') == 0) {\r\n\t\t\t\t\t\tpg = pgval;\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\r\n\t\t\t\t// Iteratively push data into yearData Array\r\n\t\t\t\tyearData.push({icd_code: dia_icd, icd_text: dia_text, patienten_entlassen: pe, patienten_gestorben: pt, patienten_gesamt: pg});\r\n\t\t\t})\r\n\t\t});\r\n\r\n\t\t// Create Table from Data\r\n\t\tpieChartDetailsGlobal = yearData;\r\n\t\tfillTable(overviewKeysJahr, yearData);\r\n\r\n\t\t// Create Pie Chart from Data\r\n\t\tvar pieData = createDataForPieChart(distinctColors, yearData);\r\n\t\tcreatePieChart(pieData, yearData);\r\n\t});\r\n\r\n}",
"function updateYear(year) {\n homeControllerVM.homeSelectedRegistrationYear = year;\n localStorage.setItem('selectedYear', year);\n }",
"function get_value_of_year_datum(f, yr, ck=current_key) {\n\tyr = parseInt(yr);\n\treturn mort_data['$'.concat(f)] && mort_data['$'.concat(f)]['$'.concat(ck)][yr];\n}",
"function displayCorrectYVItem(aSelect, jCode) {\r\n var value = aSelect.value;\r\n var url = '/action/showCoverGallery?journalCode=' + jCode + '&ajax=true&year=' + value;\r\n var parentNode = $('parentYearVolumeSelect');\r\n var width = Element.getWidth('cenVolumes');\r\n Element.remove('cenVolumes');\r\n parentNode.insert('<select id=\"cenVolumes\" name=\"year\"><option value=\"\">Loading...</option></select>');\r\n $('cenVolumes').style.width = width + \"px\";\r\n new Ajax.Request(url, {\r\n method: 'get',\r\n onSuccess: function(transport) {\r\n var jsonData = transport.responseText.evalJSON();\r\n if(jsonData != '') {\r\n //set correct labels in year/volume select\r\n var labels = jsonData.labels;\r\n var orderedKeys = jsonData.orderedKeys;\r\n if(labels != '' && orderedKeys){\r\n Element.remove('cenVolumes');\r\n //start building year/volume select with new values\r\n var resultText = \"<select id='cenVolumes' name='year'>\";\r\n for(var i = 0; i < orderedKeys.length; i++) {\r\n var currKey = orderedKeys[i];\r\n var selected = (i == orderedKeys.length -1);\r\n resultText += \"<option value='\" + currKey + \"'\" + (selected ? \" selected\" : \"\") + \">\" + labels[currKey] + \"</option>\";\r\n }\r\n resultText += \"</select>\";\r\n parentNode.insert(resultText);\r\n }\r\n }\r\n }\r\n });\r\n}",
"function setYear() {\n\n // GET THE NEW YEAR VALUE\n var year = tDoc.calControl.year.value;\n\n // IF IT'S A FOUR-DIGIT YEAR THEN CHANGE THE CALENDAR\n if (isFourDigitYear(year)) {\n calDate.setFullYear(year);\n\n\t// GENERATE THE CALENDAR SRC\n\tcalDocBottom = buildBottomCalFrame();\n\n // DISPLAY THE NEW CALENDAR\n writeCalendar(calDocBottom);\n }\n else {\n // HIGHLIGHT THE YEAR IF THE YEAR IS NOT FOUR DIGITS IN LENGTH\n tDoc.calControl.year.focus();\n tDoc.calControl.year.select();\n }\n}",
"async show({ request, response }) {\n try {\n const id = request.params.id\n let redisKey = `TargetYear_${id}`\n let cached = await RedisHelper.get(redisKey)\n if (cached) {\n return response.status(200).send(cached)\n }\n const data = await TargetYear.find(id)\n if (!data) {\n return response.status(400).send(ResponseParser.apiNotFound())\n }\n await data.load(\"target\")\n let parsed = ResponseParser.apiItem(data.toJSON())\n await RedisHelper.set(redisKey, parsed)\n return response.status(200).send(parsed)\n } catch (e) {\n ErrorLog(request, e)\n return response.status(500).send(ResponseParser.unknownError())\n }\n }",
"jYearToIYear(eraCode, jYear) {\n if (!this.isValidEraCode(eraCode)) {return (-1);} // eraCode not found \n const maxJYear = this.isNowEra(eraCode) ? 99 : this.yDict[eraCode].getNumYears(); // 99 if now era\n if (jYear>=1 && jYear<=maxJYear) { return this.yDict[eraCode].getStartYear() + parseInt(jYear) - 1; }\n return 0;\n }",
"function load_edition()\n {\n var get_edition_resource = $resource('/api/get_edition');\n get_edition_resource.query(function(data) {\n // success handler\n list_editions=[];\n for(var x in data)\n {\n for (var y in data[x]['edition'])\n list_editions.push(data[x]['edition'][y]);\n }\n $scope.editions=list_editions;\n $scope.myedition=$scope.editions[0];\n get_dates();\n }, function(error) {\n alert(\"Error \");\n alert(error);\n // error handler\n });\n\n }",
"createCellForYear(year) {\n const yearName = this.dateAdapter.getYearName(this.dateAdapter.createDate(year));\n return new McCalendarCell(year, yearName, yearName, this.shouldEnableYear(year));\n }",
"function updateMapWithNewYear() {\n next_svg_holder.load(\n // \"./frames/\" + dataType + current_year + \".svg\",\n \"worldwidemap/frames/\" + dataType + current_year + \".svg\",\n function() {\n setup_tween();\n // remapColors(next_svg_holder.children(\"svg\"));\n tween_colors(\n main_svg_holder.children(\"svg\"),\n next_svg_holder.children(\"svg\")\n );\n }\n );\n}",
"function displayView(fileName){\n var fileExt = fileName.substring((fileName.length - 5), (fileName.length));\n\tvar pattern = tabsFrame.patternRestriction;\n if (fileExt.toUpperCase() == \".AXVW\") {\n/*\n\t\tif (pattern.match(/paginated/gi)) {\n\t\t\tfileName = 'ab-paginated-report-job.axvw?viewName=' + fileName;\n\t\t\tvar link = parent.Ab.view.View.getBaseUrl() + '/' + fileName;\n\t\t\twindow.open(link);\n\t\t} else {\n\t\t\tAb.view.View.openDialog(fileName);\n\t\t}\n*/\n\n\t\tif (pattern && pattern.match(/paginated/gi)) {\n\t\t\tfileName = 'ab-paginated-report-job.axvw?viewName=' + fileName;\n\t\t}\n\n\t\tAb.view.View.openDialog(fileName);\n\t\n }\n else {\n alert(getMessage(\"onlyAXVW\"));\n }\n}",
"function isFourDigitYear(year) {\n\n if (year.length != 4) {\n tDoc.calControl.year.value = calDate.getFullYear();\n tDoc.calControl.year.select();\n tDoc.calControl.year.focus();\n }\n else {\n return true;\n }\n}",
"function decodeURL() {\n var url = document.location.pathname;\n \n if (url.lastIndexOf(\"/\") === url.length-1) {\n url = url.substring(0,url.lastIndexOf(\"/\"));\n }\n url = url.substring(url.lastIndexOf(\"/\") + 1);\n \n if (url !== \"\")\n console.log(url);\n else\n return;\n \n url = atob(url);\n \n // The beginning of the url is formatted <season><year>...\n // <season> is one character. <year> is 4.\n var svalue = url[0];\n url = url.substring(1);\n var yvalue = url.substring(0, 4);\n url = url.substring(4);\n \n console.log(\"Year: \" + yvalue);\n console.log(\"Season: \" + svalue);\n \n // Make sure the year is between 1999 (the first year with data) and next year (inclusive).\n if (parseInt(yvalue, 10) < 1999 || parseInt(yvalue, 10) > new Date().getFullYear()+1) {\n console.log(\"*** Year out of bounds.\");\n return;\n }\n \n // Make sure the season value is between 0 (Winter) and 3 (Fall) (inclusive).\n if (parseInt(svalue, 10) < 0 || parseInt(svalue, 10) > 3) {\n console.log(\"*** Season out of bounds.\");\n return;\n }\n \n // A class number is 4 characters long so check that the remaining url\n // length is a multiple of 4.\n if (url.length % 4 !== 0) {\n console.log(\"*** Bad URL length.\");\n return;\n }\n \n // Clear the schedule. There shouldn't be anything in it, but just in case\n SCHEDULE.length = 0;\n \n while (url.length >= 4) {\n var token = url.substring(0,4);\n url = url.substring(4);\n for (var i = 0; i < SECTIONS.length; i ++) {\n if (SECTIONS[i].class_no == token)\n SCHEDULE.push(SECTIONS[i]);\n }\n }\n \n analytics(\"share_link_schedule\");\n $(\"#switch_view\").click();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Factory to deescape a value, based on a list at `key` in `ctx`. | function factory(ctx, key) {
return unescape;
/* De-escape a string using the expression at `key`
* in `ctx`. */
function unescape(value) {
var prev = 0;
var index = value.indexOf('\\');
var escape = ctx[key];
var queue = [];
var character;
while (index !== -1) {
queue.push(value.slice(prev, index));
prev = index + 1;
character = value.charAt(prev);
/* If the following character is not a valid escape,
* add the slash. */
if (!character || escape.indexOf(character) === -1) {
queue.push('\\');
}
index = value.indexOf('\\', prev);
}
queue.push(value.slice(prev));
return queue.join('');
}
} | [
"function SanitizeCtx(ctx) {\n let r = {};\n for (const key in ctx) {\n if (!key.startsWith('_')) {\n r[key] = ctx[key];\n }\n }\n return r;\n}",
"function setLiteral(source, key, rules) {\n const item = (source[key] || { type: 'literal' });\n item.rules = rules;\n source[key] = item;\n return item;\n}",
"function decipher(e,offset){\n return cipher(e,-offset);\n }",
"function unescape(object) {\n return transform(object, _.unescape)\n}",
"scrub(secret, string) { return scrub(secret, string); }",
"function createEncodedParam (key,value) {\n return {\n key: percentEncode(key),\n value: percentEncode(value)\n }\n}",
"function makeReplaceFunction(values) {\n return function(match, id) {\n values.push(id);\n return '';\n };\n }",
"function mapColumnValue(ix, v, cmap, gconf) {\n var cobj = cmap[ix];\n var type = cobj.type;\n\n // JSON-LD context;\n // can be used to map string values to IRIs\n var ctx = cobj['@context'];\n if (ctx != null) {\n if (ctx[v] != null) {\n v = ctx[v];\n }\n else {\n console.warn(\"NO MAPPING: \"+v);\n }\n }\n\n // column\n if (cobj.prefix != null) {\n return mapRdfResource(cobj.prefix + v);\n }\n \n // Remove this code when this is fixed: https://support.crbs.ucsd.edu/browse/NIF-10646\n if (cobj.list_delimiter != null) {\n var vl = v.split(cobj.list_delimiter);\n if (v == '-') {\n // ARRGGH AD-HOCCERY. Sometimes empty lists are denoted '-'...\n vl = [];\n }\n if (v == \"\") {\n // sometimes an empty string\n vl = [];\n }\n if (vl.length == 0) {\n return null;\n }\n if (vl.length > 1) {\n return vl.map(function(e) { return mapColumnValue(ix, e, cmap, gconf) });\n }\n // carry on, just use v, as it is a singleton list\n }\n if (type == 'rdfs:Literal') {\n return engine.quote(v);\n }\n if (v == null) {\n console.warn(\"No value for \"+ix+\" in \"+JSON.stringify(row));\n }\n return mapRdfResource(v);\n}",
"transformDivValToSet(divExp) {\n const [_tag, exp, val] = divExp;\n return ['set', exp, ['/', exp, val]];\n }",
"function removeElementFromCue(cue, key){\n \t\tif(cue.text === \"\"){ return; }\n \t\tcue.text = cue.text.slice('[AyamelEvent]'.length, cue.text.length);\n \t\ttry{\n \t\t\t// Create a new Cue object from the given 'cue' parameter (which is JSON)\n \t\t\tvar newCue = JSON.parse(cue.text);\n\n \t\t\t// Filter out the given action\n \t\t\tnewCue.enter.actions = newCue.enter.actions.filter(function(action){ return action.type !== key; })\n \t\t\t\n \t\t\t// Set the value of cue.text to the modified value\n \t\t\tcue.text = '[AyamelEvent]' + JSON.stringify(newCue);\n \t\t}\n \t\tcatch(e) { console.log(e); }\n \t}",
"_eraseValue(value, context) {\n const parsedValuePath = context.valuePath;\n const result = this.setValueOrLog(ChainUtil.formatPath(parsedValuePath), 'erased', context);\n if (!ChainUtil.isFailedTx(result)) {\n return this.returnFuncResult(context, FunctionResultCode.SUCCESS);\n } else {\n return this.returnFuncResult(context, FunctionResultCode.FAILURE);\n }\n }",
"visitList_values_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function tokensThatResolveTo(value) {\n return literalTokensThatResolveTo(value).concat(cloudFormationTokensThatResolveTo(value));\n}",
"enterPostDecrementExpression(ctx) {\n\t}",
"function deparam( params, coerce ) {\n var obj = {},\n coerce_types = { 'true': !0, 'false': !1, 'null': null };\n\n // Iterate over all name=value pairs.\n $.each( params.replace( /\\+/g, ' ' ).split( '&' ), function(j,v){\n var param = v.split( '=' ),\n key = decodeURIComponent( param[0] ),\n val,\n cur = obj,\n i = 0,\n\n // If key is more complex than 'foo', like 'a[]' or 'a[b][c]', split it\n // into its component parts.\n keys = key.split( '][' ),\n keys_last = keys.length - 1;\n\n // If the first keys part contains [ and the last ends with ], then []\n // are correctly balanced.\n if ( /\\[/.test( keys[0] ) && /\\]$/.test( keys[ keys_last ] ) ) {\n // Remove the trailing ] from the last keys part.\n keys[ keys_last ] = keys[ keys_last ].replace( /\\]$/, '' );\n\n // Split first keys part into two parts on the [ and add them back onto\n // the beginning of the keys array.\n keys = keys.shift().split('[').concat( keys );\n\n keys_last = keys.length - 1;\n } else {\n // Basic 'foo' style key.\n keys_last = 0;\n }\n\n // Are we dealing with a name=value pair, or just a name?\n if ( param.length === 2 ) {\n val = decodeURIComponent( param[1] );\n\n // Coerce values.\n if ( coerce ) {\n val = val && !isNaN(val) ? +val // number\n : val === 'undefined' ? undefined // undefined\n : coerce_types[val] !== undefined ? coerce_types[val] // true, false, null\n : val; // string\n }\n\n if ( keys_last ) {\n // Complex key, build deep object structure based on a few rules:\n // * The 'cur' pointer starts at the object top-level.\n // * [] = array push (n is set to array length), [n] = array if n is\n // numeric, otherwise object.\n // * If at the last keys part, set the value.\n // * For each keys part, if the current level is undefined create an\n // object or array based on the type of the next keys part.\n // * Move the 'cur' pointer to the next level.\n // * Rinse & repeat.\n for ( ; i <= keys_last; i++ ) {\n key = keys[i] === '' ? cur.length : keys[i];\n cur = cur[key] = i < keys_last ? cur[key] || ( keys[i+1] && isNaN( keys[i+1] ) ? {} : [] ) : val;\n }\n\n } else {\n // Simple key, even simpler rules, since only scalars and shallow\n // arrays are allowed.\n\n if ( $.isArray( obj[key] ) ) {\n // val is already an array, so push on the next value.\n obj[key].push( val );\n\n } else if ( obj[key] !== undefined ) {\n // val isn't an array, but since a second value has been specified,\n // convert val into an array.\n obj[key] = [ obj[key], val ];\n\n } else {\n // val is a scalar.\n obj[key] = val;\n }\n }\n\n } else if ( key ) {\n // No value was defined, so set something meaningful.\n obj[key] = coerce ? undefined : '';\n }\n });\n\n return obj;\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 splitValue(helper, value) {\n const separator = helper[0];\n return value.split(\n new RegExp(`(?=${separator})`)\n );\n}",
"function _decompactMapList(entries, compactedAttr, func) {\n var odata = {};\n for (var i = 0; i < entries.length; i++) {\n var e = entries[i];\n //fill data from previous entry\n //compactedAttr is attr name to replace '_' with\n if (compactedAttr && typeof(e) === 'string') {\n var s = e;\n e = {};\n e[compactedAttr] = s;\n } else if (compactedAttr && typeof(e['_']) !== 'undefined') {\n e[compactedAttr] = e['_'];\n delete e['_'];\n }\n for (k in odata) {\n if (odata.hasOwnProperty(k)) {\n if (typeof(e[k]) === 'undefined') {\n e[k] = odata[k]\n } else if (e[k] === null) {\n delete e[k];\n }\n }\n }\n odata = e;\n func(e);\n }\n}",
"_transform (res) {\n return res.reduce((memo, item) => {\n memo[ item.key ] = item.value\n return memo\n }, {})\n }",
"function zeroDecipher(key, data) {\n\treturn decompress(sjcl.decrypt(key, data));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new MorphTarget | function MorphTarget(/** defines the name of the target */name,influence,scene){if(influence===void 0){influence=0;}if(scene===void 0){scene=null;}this.name=name;/**
* Gets or sets the list of animations
*/this.animations=new Array();this._positions=null;this._normals=null;this._tangents=null;/**
* Observable raised when the influence changes
*/this.onInfluenceChanged=new BABYLON.Observable();/** @hidden */this._onDataLayoutChanged=new BABYLON.Observable();this._animationPropertiesOverride=null;this._scene=scene||BABYLON.Engine.LastCreatedScene;this.influence=influence;} | [
"function MorphTargetManager(scene){if(scene===void 0){scene=null;}this._targets=new Array();this._targetInfluenceChangedObservers=new Array();this._targetDataLayoutChangedObservers=new Array();this._activeTargets=new BABYLON.SmartArray(16);this._supportsNormals=false;this._supportsTangents=false;this._vertexCount=0;this._uniqueId=0;this._tempInfluences=new Array();if(!scene){scene=BABYLON.Engine.LastCreatedScene;}this._scene=scene;if(this._scene){this._scene.morphTargetManagers.push(this);this._uniqueId=this._scene.getUniqueId();}}",
"createTargetsLayer() {\n this.layers.targets = this.document.createElement('div');\n\n this.layers.targets.setAttribute('style', [\n 'position: absolute',\n 'left: 0px',\n 'top: 0px',\n 'height: 100',\n 'pointer-events: none', // Disable pointer events so on hover on points works.\n 'width: 100%',\n 'z-index: 1'\n ].join(';'));\n\n this.layers.targets.setAttribute('class', this.createPrefixedIdentifier('targets'));\n this.holder.appendChild(this.layers.targets);\n }",
"function create3DTarget(target) {\n let loader = new THREE.TextureLoader();\n let planetSize = .5;\n loader.load(`./assets/img/targets/${target.name}.jpg`, (texture) => {\n let geom = new THREE.SphereGeometry(planetSize, 30, 30);\n let mat = (target.name == 'Sun') ? new THREE.MeshBasicMaterial({map: texture}) : new THREE.MeshLambertMaterial({map: texture});\n let planet = new THREE.Mesh(geom, mat);\n planet.name = target.name; planet.targetIndex = targets.indexOf(target);\n // Positioning\n let targetCartesian = Math.cartesian(target.az, target.el, gridRadius);\n planet.position.x = -targetCartesian.x;\n planet.position.z = -targetCartesian.z;\n planet.position.y = targetCartesian.y;\n planet.lookAt(0, 0, 0); planet.rotateY(Math.radians(target.az));\n // Target specific features\n if (planet.name == 'Saturn') {\n loader.load(`./assets/img/targets/SaturnRing.png`, (texture) => {\n geom = new THREE.RingGeometry(planetSize * 1.116086235489221, planetSize * 2.326699834162521, 84, 1);\n for(var yi = 0; yi < geom.parameters.phiSegments; yi++) {\n var u0 = yi / geom.parameters.phiSegments;\n var u1=(yi + 1) / geom.parameters.phiSegments;\n for(var xi = 0; xi < geom.parameters.thetaSegments; xi++) {\n \t\tvar fi = 2 * (xi + geom.parameters.thetaSegments * yi);\n var v0 = xi / geom.parameters.thetaSegments;\n var v1 = (xi + 1) / geom.parameters.thetaSegments;\n geom.faceVertexUvs[0][fi][0].x = u0; geom.faceVertexUvs[0][fi][0].y = v0;\n geom.faceVertexUvs[0][fi][1].x = u1; geom.faceVertexUvs[0][fi][1].y = v0;\n geom.faceVertexUvs[0][fi][2].x = u0; geom.faceVertexUvs[0][fi][2].y = v1;\n fi++;\n geom.faceVertexUvs[0][fi][0].x = u1; geom.faceVertexUvs[0][fi][0].y = v0;\n geom.faceVertexUvs[0][fi][1].x = u1; geom.faceVertexUvs[0][fi][1].y = v1;\n geom.faceVertexUvs[0][fi][2].x = u0; geom.faceVertexUvs[0][fi][2].y = v1;\n }\n }\n mat = new THREE.MeshLambertMaterial( { map: texture, side: THREE.DoubleSide, transparent: true } );\n let ring = new THREE.Mesh(geom, mat);\n ring.rotateX(27);\n planet.add(ring);\n });\n } else if (target.name == 'Sun') {\n const light = new THREE.PointLight('#d4caba', 1, 500, 0 );\n let lightCartesian = Math.cartesian(target.az, target.el, gridRadius - .5);\n light.position.x = -lightCartesian.x;\n light.position.y = lightCartesian.y;\n light.position.z = -lightCartesian.z;\n scene.add(light);\n }\n // planet.add(new THREE.AxesHelper(5));\n scene.add(planet);\n });\n}",
"function addTargetsToDOM(){\n\t//add left target\n\tvar matrix = new THREE.Matrix4();\n\tmatrix.set(0.001, 0.000, 0.000, -0.175,0.000, 0.001, 0.000, 0.000,0.000, 0.000, 0.001, 0.000,0.000, 0.000, 0.000, 1.000);\n\tvar position = new THREE.Vector3();\n\tvar quaternion = new THREE.Quaternion();\n\tvar scale = new THREE.Vector3();\n\n\tmatrix.decompose( position, quaternion, scale );\n\tposition.multiplyScalar(scaling);\n\n\tposition.add(sceneOffset);\n\tvar targetL = document.createElement(\"a-sphere\");\n\ttargetL.setAttribute(\"position\",position);\n\ttargetL.setAttribute(\"radius\",0.03)\n\t\n\tscene.appendChild(targetL);\n\t\n\t//add right target\n\tmatrix = new THREE.Matrix4();\n\tmatrix.set(0.001, 0.000, 0.000, 0.175,0.000, 0.001, 0.000, 0.000,0.000, 0.000, 0.001, 0.000,0.000, 0.000, 0.000, 1.000);\n\n\tposition = new THREE.Vector3();\n\tquaternion = new THREE.Quaternion();\n\tscale = new THREE.Vector3();\n\tmatrix.decompose( position, quaternion, scale );\n\tposition.multiplyScalar(scaling);\n\n\tposition.add(sceneOffset);\n\tvar targetR = document.createElement(\"a-sphere\");\n\ttargetR.setAttribute(\"position\",position);\n\ttargetR.setAttribute(\"radius\",0.03)\n\t\n\tscene.appendChild(targetR);\n\t\n}",
"function createTarget(t){\r\n \tvar tUl= document.createElement('ul');\r\n \tvar imgSufix='.png';\r\n \ttUl.id = 'drag2share-targets';\r\n \t$.each(t.split(','), function(index, value) { \r\n\t\t\t\t var tLi = document.createElement('li');\r\n\t\t\t\t tLi.id = value;\r\n\t\t\t\t tLi.style.background = 'url('+options.icons+'/'+value+imgSufix+') no-repeat 0 0';\r\n\t\t\t\t $(tUl).append(tLi);\r\n\t\t\t});\r\n\t\t\t$(document.body).prepend(tUl);\r\n\t\t\ttUlH=($(tUl).height());\r\n\t\t\ttUl.style.top = '-'+parseInt(tUlH+20)+'px';\r\n }",
"function moveToTarget() {\n if (targetEntity == null) return;\n\n var path = bot.navigate.findPathSync(targetEntity.position, {\n timeout: 1 * 1000,\n endRadius: 2\n });\n bot.navigate.walk(path.path, function() {\n if (targetEntity != null) { bot.lookAt(targetEntity.position.plus(vec3(0, 1.62, 0))); }\n });\n\n checkNearestEntity();\n\n timeoutId = setTimeout(moveToTarget, 1 * 1000); // repeat call after 1 second\n}",
"function createMob() {\n var rand = Math.random();\n var tear = 1;\n if (rand < 0.5) {\n tear = 1;\n } else if (rand < 0.8) {\n tear = 2;\n } else if (rand < 0.95) {\n tear = 3;\n } else {\n tear = 4;\n }\n enemy = new Monster(LEVEL, tear);\n updateMob();\n}",
"addProperties (target) {\n\n // Property getter/setter injection\n this.position.addProperties(target);\n\n // Component references\n target.position = this.position;\n target.scale = this.scale;\n\n return target;\n\n }",
"spawnAndShoot()\n {\n var newBullet = cc.instantiate(this.bullet);\n newBullet.setPosition(this.node.getChildByName('player').position.x, this.node.getChildByName('player').position.y + 50);\n this.node.addChild(newBullet);\n\n var action = cc.moveTo(4, cc.v2(this.node.getChildByName('player').position.x, this.node.height));\n newBullet.runAction(action);\n }",
"spawn(mob){\r\n\r\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}",
"onTargetAssigned(target) {}",
"function generateTargets() {\n let number = 10;\n let result = [];\n while (result.length < number) {\n result.push({\n id: 'target-' + result.length,\n x: stage.width() * Math.random(),\n y: stage.height() * Math.random()\n });\n }\n return result;\n}",
"shoot() {\n var targetX = this.sceneManager.Zerlin.x;\n var targetY = this.sceneManager.Zerlin.boundingbox.y + this.sceneManager.Zerlin.boundingbox.height / 2;\n var randTargetX = targetX + (this.sceneManager.Zerlin.boundingbox.width * (Math.random() - .5));\n var randTargetY = targetY + (this.sceneManager.Zerlin.boundingbox.height * (Math.random() - .5));\n var droidLaser = new DroidLaser(this.game,\n this.boundCircle.x,\n this.boundCircle.y,\n dbc.BASIC_DROID_LASER_SPEED,\n randTargetX,\n randTargetY,\n dbc.BASIC_DROID_LASER_LENGTH,\n dbc.BASIC_DROID_LASER_WIDTH,\n \"#339933\",\n \"#00ff00\");\n this.sceneManager.addLaser(droidLaser);\n this.fire = false;\n this.game.audio.playSoundFx(this.game.audio.enemy, 'retroBlasterShot');\n }",
"function TargetImageDatabase(directory) {\n\tthis.directory = directory;\n\tthis.targetsByIndex = [];\n\tthis.targetsByName = {};\n\tvar filenames = fs.readdirSync(directory);\n\tfor (var i = 0; i < filenames.length; i++) {\n\t\t//Image files only\n\t\tvar ext = filenames[i].slice(-4);\n\t\tif (ext == '.png' || ext == '.jpg') {\n\t\t\tvar fullname = directory + '/' + filenames[i];\n\t\t\tvar shortname = filenames[i].slice(0,-4);\t// strip the .png\n\n\t\t\t//Read .txt file with coordinates\n\t\t\tvar coordfile = fs.readFileSync(directory + '/' + shortname + '.txt', 'utf8');\n\t\t\tvar coordlines = coordfile.split('\\n');\n\t\t\tvar coords = coordlines[0].split(' ');\n\t\t\tvar dir = coordlines[1].split(' ')\n\n\t\t\tvar startPos = new THREE.Vector2(parseFloat(coords[0]), parseFloat(coords[1]));\n\t\t\tvar startDir = new THREE.Vector2(parseFloat(dir[0]), parseFloat(dir[1]));\n\n\t\t\tvar target = {\n\t\t\t\tindex: this.targetsByIndex.length,\t\t\t\t\n\t\t\t\tshortname: shortname,\n\t\t\t\tfilename: fullname,\n\t\t\t\timage: undefined,\n\t\t\t\tbaseline: undefined,\n\t\t\t\ttensor: undefined,\n\t\t\t\tstartPos: startPos,\n\t\t\t\tstartDir: startDir\n\t\t\t};\n\t\t\tthis.targetsByIndex.push(target);\n\t\t\tthis.targetsByName[shortname] = target;\n\t\t}\n\t}\n}",
"function createAvatar () {\n\n var avatar = new THREE.Object3D();\n\n var avatarBody = makeCube( 'blue' );\n\n avatarBody.position.y = -1.5;\n\n avatar.add( characterBody );\n\n scene.add( avatar );\n\n return avatar;\n\n }",
"function TestEntity1() {\n this.sprite = new Sprite(0,0,20, \"blue\");\n}",
"function AssociatedTargetNetwork() {\n _classCallCheck(this, AssociatedTargetNetwork);\n\n AssociatedTargetNetwork.initialize(this);\n }",
"function CreateSprite(paths, size_factor, size_min,\n\t\t speed_factor, speed_min, left, right){\n\n // Make the mesh \n var size = Math.random()*size_factor + size_min;\n var trand = Math.floor(Math.random()*paths.length);\n var texture= THREE.ImageUtils.loadTexture(paths[trand]);\n var material = new THREE.SpriteMaterial( { map: texture, fog: true, } );\n var sprite = new THREE.Sprite( material );\n sprite.scale.set(size, size, size);\n var speed = Math.random() *speed_factor + speed_min;\n\n // Initial placement\n x = (Math.random()*(right-left))-((right-left)/2);\n y = (Math.random()*3000)-1000;\n sprite = new FallingObject(sprite, speed, x, y, -1000, 0, -1, 0);\n sprite.set_box_rules(2000, -1000, left, right);\n\n \n //sprite.place();\n\n return sprite;\n}"
] | {
"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.