query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Removes a set of Bluemix credentials from the DB, and any references to them. | async function deleteBluemixCredentials(credentials) {
// reset scratch keys that have a copy of the credentials in them
await store.removeCredentialsFromScratchKeys(credentials);
// delete references to classifiers that rely on the credentials
await store.deleteClassifiersByCredentials(credentials);
// delete the credentials from the DB
await store.deleteBluemixCredentials(credentials.id);
} | [
"function deleteAuthCredentials() {\n setAuthCredentials(null)\n request.deleteAuthCredentials()\n saveRequest()\n }",
"async removeAllCredentials() {\n await this.execute(\n new command.Command(command.Name.REMOVE_ALL_CREDENTIALS).setParameter(\n 'authenticatorId',\n this.authenticatorId_\n )\n )\n }",
"resetCredentials() {\n Session.removeSession();\n Token.remove(this.resource);\n }",
"function deleteAuthentication() {\n var credentialsJSON = {};\n console.log(\"In delete Authentication\");\n db = new sqlite3.Database('encoder.db');\n db.all(\"SELECT value from SYSTEM_AUTHENTICATION where name = \\\"user\\\"\", function(err, rows) {\n if(err) {\n console.err(err);\n }\n credentialsJSON.user = rows[0].value;\n db.all(\"SELECT value from SYSTEM_AUTHENTICATION where name = \\\"user-pwd\\\"\", function(err, rows) {\n if(err) {\n console.err(err);\n }\n credentialsJSON.user_pwd = cryptoObject.createHash(rows[0].value);\n db.all(\"SELECT value from SYSTEM_AUTHENTICATION where name = \\\"admin\\\"\", function(err, rows) {\n if(err) {\n console.err(err);\n }\n credentialsJSON.admin = rows[0].value;\n db.all(\"SELECT value from SYSTEM_AUTHENTICATION where name = \\\"admin-pwd\\\"\", function(err, rows) {\n if(err) {\n console.err(err);\n }\n credentialsJSON.admin_pwd = cryptoObject.createHash(rows[0].value); \n db.exec(\"DROP TABLE SYSTEM_AUTHENTICATION\", function() {createAuthentication(credentialsJSON);});\n });\n });\n });\n });\n }",
"function revokeCredentials() {\n\tos.storage.login.clear(); // Clean bad storage\n\tos.delay(function(){chrome.runtime.reload()},300); // Reload client, triggering setup\n}",
"async function removeCredentialsFromStorage() {\n await AsyncStorage.removeItem('api/credentials');\n}",
"async removeAllAuths() {\n const authConfigs = await this.findAllAuthConfigs();\n const usernames = [...authConfigs.keys()];\n for (const username of usernames) {\n await this.removeAuth(username);\n }\n }",
"async clearSlackCredentials () {\n\t\tconst query = {\n\t\t\tteamIds: this.team.id\n\t\t};\n\t\tconst op = {\n\t\t\t$unset: {\n\t\t\t\t[`providerInfo.${this.team.id}.slack`]: true\n\t\t\t}\n\t\t};\n\t\tif (Commander.dryrun) {\n\t\t\tthis.log('\\t\\tWould have cleared all Slack credentials');\n\t\t}\n\t\telse {\n\t\t\tthis.log('\\t\\tClearing all Slack credentials');\n\t\t\tawait this.data.users.updateDirect(query, op);\n\t\t}\n\t\tthis.verbose(query);\n\t\tthis.verbose(op);\n\t}",
"async deleteAllPasswords(){\n const user = await AsyncStorage.getItem('loggedInUser');\n this.getPasswords().then((list) => {\n for (const password of list){\n db.collection('users').doc(user).collection('passwords').doc(password.passwordName).delete();\n }\n });\n }",
"function removeCredentials () {\n var storage = window.localStorage;\n storage.removeItem(\"username\");\n storage.removeItem(\"password\");\n closeMenu();\n checkCredentials();\n showNotice(\"Welcome\", \"#2980b9\");\n}",
"resetCredentials() {\n this.username = null;\n this.password = null;\n this.usesSso = null; // related to credentials to clear this too\n }",
"async clearCredentials () {\n\n\t\t// remove credentials for the given provider and team ID in the user object\n\t\tconst teamId = this.request.body.teamId.toLowerCase();\n\t\tconst provider = this.request.params.provider.toLowerCase();\n\t\tlet { host, subId } = this.request.body;\n\t\tlet userKey = `providerInfo.${provider}`;\n\t\tlet teamKey = `providerInfo.${teamId}.${provider}`;\n\t\tif (host) {\n\t\t\thost = host.toLowerCase().replace(/\\./g, '*');\n\t\t\tuserKey += `.hosts.${host}`;\n\t\t\tteamKey += `.hosts.${host}`;\n\t\t}\n\t\tif (subId) {\n\t\t\tuserKey += `.multiple.${subId}`;\n\t\t\tteamKey += `.multiple.${subId}`;\n\t\t}\n\n\t\tconst existingUserProviderInfo = this.user.getProviderInfo(provider);\n\t\tif (\n\t\t\t!host &&\n\t\t\texistingUserProviderInfo &&\n\t\t\texistingUserProviderInfo.hosts &&\n\t\t\tObject.keys(existingUserProviderInfo.hosts).length > 0\n\t\t) {\n\t\t\t// if we have enterprise hosts for this provider, don't stomp on them\n\t\t\tuserKey += '.accessToken';\n\t\t}\n\n\t\tconst existingTeamProviderInfo = this.user.getProviderInfo(provider, teamId);\n\t\tif (\n\t\t\t!host &&\n\t\t\texistingTeamProviderInfo &&\n\t\t\texistingTeamProviderInfo.hosts &&\n\t\t\tObject.keys(existingTeamProviderInfo.hosts).length > 0\n\t\t) {\n\t\t\t// if we have enterprise hosts for this provider, don't stomp on them\n\t\t\tteamKey += '.accessToken';\n\t\t}\n\n\t\tconst op = {\n\t\t\t$unset: {\n\t\t\t\t[userKey]: true,\n\t\t\t\t[teamKey]: true\n\t\t\t},\n\t\t\t$set: {\n\t\t\t\tmodifiedAt: Date.now()\n\t\t\t}\n\t\t};\n\n\t\t// this is really only for \"sharing model\" chat providers, which will provide a subId\n\t\tconst serviceAuth = this.api.services[`${provider}Auth`];\n\t\tif (\n\t\t\tserviceAuth &&\n\t\t\tsubId &&\n\t\t\texistingTeamProviderInfo &&\n\t\t\texistingTeamProviderInfo.multiple\n\t\t) {\n\t\t\tconst providerUserId = await serviceAuth.getUserId(existingTeamProviderInfo.multiple[subId]);\n\t\t\tif (providerUserId) {\n\t\t\t\tconst identity = `${provider}::${providerUserId}`;\n\t\t\t\tif ((this.user.get('providerIdentities') || []).find(id => id === identity)) {\n\t\t\t\t\top.$pull = { providerIdentities: identity };\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.transforms.userUpdate = await new ModelSaver({\n\t\t\trequest: this,\n\t\t\tcollection: this.data.users,\n\t\t\tid: this.user.id\n\t\t}).save(op);\n\t}",
"function deleteCred() {\n var scriptProperties = PropertiesService.getScriptProperties();\n scriptProperties.deleteAllProperties();\n}",
"delete_persisted_credentials() {\n sessionStorage.removeItem('morel-credentials');\n }",
"function cleanStore() {\n store.remove(SECURITY.ACCESS_TOKEN);\n store.remove(SECURITY.REFRESH_TOKEN);\n store.remove(SECURITY.ACCESS_TOKEN_TIMESTAMP);\n }",
"function resetAuth() {\n var userProperties = PropertiesService.getUserProperties();\n userProperties.deleteProperty('dscc.username');\n userProperties.deleteProperty('dscc.password');\n userProperties.deleteProperty('dscc.accessToken');\n}",
"function clearLocalStorageCredentials(){\r\n\t\r\n\t\r\n\t// Loop through all the UserFieldRememberListIDs Entries and Remove all approproiate Local Storage values\r\n\tfor (var i = 0; i < UserFieldRememberListIDs.length; i++) {\r\n\t\tvar LocalStorageTempValue = localStorage.getItem('RLF.' + UserFieldRememberListIDs[i]);\r\n\t\t// If LocalStorageTempValue is NOT Empty (Empty String or NULL)\r\n\t\tif(LocalStorageTempValue){\r\n\t\t\tlocalStorage.removeItem('RLF.' + UserFieldRememberListIDs[i]);\r\n\t }\r\n\t }\r\n\t\r\n}",
"deleteAll() {\n this.fb_inst.database().ref('/serverState/').remove();\n this.fb_inst.database().ref('/serverData/').remove();\n }",
"function removeCredentials(url) {\n\tfor (var i=0; i < pendingCredentials.length; i++) {\n\t\tvar currentItem = pendingCredentials[i];\n\t\tif (currentItem.url.href === url.href) {\n\t\t\tpendingCredentials.splice(i, 1);\n\t\t\tsetUIIcon();\n\t\t\tbreak;\n\t\t}\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert y to screen basis from gl basis | yToScreenBasis(y) {
//return y + this.canvas.centre[1]
return (y + this.canvas.centre[1]) / this.smallestScreenEdge() * this.params.sy
} | [
"yFromScreenBasis(y) {\n return y / this.params.sy * this.smallestScreenEdge() - this.canvas.centre[1]\n }",
"yToScreenBasis(y, z) {\n //return y + this.canvas.centre[1]\n return (y + this.canvas.centre[1]) / this.smallestScreenEdge() * z\n }",
"yFromScreenBasis(y, z) {\n return y / z * this.smallestScreenEdge() - this.canvas.centre[1]\n }",
"function screen2model(s_x, s_y) {\n var m_x, m_y;\n var canvas = document.getElementById(\"gl-canvas\");\n var w = canvas.width, h = canvas.height;\n \n m_x = (s_x/w) * 2 - 1;\n m_y = 1 - 2 * (s_y/h);\n \n return [m_x/scale, m_y/scale];\n}",
"function transformY(y){\n return H * (1-(y+1) / ROWS);\n}",
"function yToIm(y) {\n //var y_coefficient = (globals.ImMin - globals.ImMax) / globals.canvas.height;\n var y_coefficient = -(globals.ImMax - globals.ImMin) / globals.canvas.height\n return (y * y_coefficient) + globals.ImMax;\n}",
"function yLightyearsToScreen(y, layer) {\n return CANVAS_CENTER_Y + (y - OffsetY) / (LIGHTYEARS_PER_PIXEL_SCALE_1 * layerToScale(layer));\n}",
"screenToWorld(x, y) {\n if (y === undefined) {\n y = x.y;\n x = x.x;\n }\n\n let M = this.ctx.getTransform().invertSelf();\n\n let ret = {\n x: x * M.a + y * M.c + M.e,\n y: x * M.b + y * M.d + M.f,\n };\n\n return ret;\n }",
"function yScreenToLightyears(y, layer) {\n return OffsetY + (y - CANVAS_CENTER_Y) * LIGHTYEARS_PER_PIXEL_SCALE_1 * layerToScale(layer);\n}",
"function UmapY (y) {\n\treturn -y*AXISHEIGHT/(AXISYEND-AXISYSTART) + AXISORIGPOSY;\n}",
"function xPixelToGL(px) {\n\treturn (px / canvas_size) * 2 - 1;\n}",
"function camY(y) {\n return ty + (y - height/2) / zoom;\n }",
"worldToScreen(x, y) {\n if (y === undefined) {\n y = x.y;\n x = x.x;\n }\n\n let M = this.ctx.getTransform();\n\n let ret = {\n x: x * M.a + y * M.c + M.e,\n y: x * M.b + y * M.d + M.f,\n };\n\n return ret;\n }",
"modifyY(y) {\n return 800 - (y / this.scale);\n }",
"xToScreenBasis(x, z) {\n //return x + this.canvas.centre[0]\n return (x + this.canvas.centre[0]) / this.smallestScreenEdge() * z\n }",
"WorldToScreenY(y) {\n return Math.round((this.center.y - this.scale.py*y));\n }",
"function yToGraph(y){\r\n\treturn (sciMonk.Height/sciMonk.CanvasHeight*(y - (sciMonk.CanvasHeight/2))*-1)*0.5;\r\n}",
"ScreenToWorldY(y) {\n return -( y - this.center.y + 0.5) / this.scale.py;\n }",
"static _y2v(y) {\n\t\tif (y <= 0.0121) return y / 0.0121;\n\t\tlet v = 10;\n\t\twhile (true) {\n\t\t\tconst f = Munsell._v2y(v) * 100 - y * 100;\n\t\t\tconst fp = 3 * 0.0467 * (v * v) + 2 * 0.5602 * v - 0.1753;\n\t\t\tconst v1 = -f / fp + v;\n\t\t\tif (Math.abs(v1 - v) < 0.01) break;\n\t\t\tv = v1;\n\t\t}\n\t\treturn v;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
i = index, height = height of Element, color = background color of element | function visElement(i, height, color){
setTimeout(() => {
divs[i].style = "height:"+height+"%; background-color:"+color+"; width:"+width+"%;";
}, currentDelay);
} | [
"color(i) {\n return this.native.color(i);\n }",
"function displayColor(color)\n{\n\tfor(var i=0;i<squares.length;i++)\n\t{\n \t\tsquares[i].style.background=color;\n\t}\n}",
"function getColorAt(i){\n return colors[i].toRGB();\n}",
"function createColorElement({ index, color, listener } = {}) {\n const elementRow = Math.floor(index / 6);\n const elementColumn = index % 6;\n\n const elementOffsetX =\n kPickerOffsetX + kColorRectangleMarginX +\n elementColumn * (kColorRectangleMarginX + kColorRectangleWidth);\n\n const elementOffsetY =\n kPickerOffsetY + kColorRectangleMarginY + kHeaderHeight +\n elementRow * (kColorRectangleMarginY + kColorRectangleHeight);\n\n return new ClickableTextDraw(listener, {\n position: [ elementOffsetX + kColorRectangleWidth / 2, elementOffsetY ],\n text: '_',\n\n alignment: TextDraw.ALIGN_CENTER,\n letterSize: [ 0.0, 1.775 ],\n textSize: [ kColorRectangleWidth, kColorRectangleHeight ],\n selectable: true,\n\n boxColor: color,\n useBox: true,\n });\n}",
"function updateBox (rgba, i) {\n BDO.terms[i].boxElement.style.backgroundColor = rgba;\n //document.getElementById(boxId).style.backgroundColor = rgba;\n}",
"function highlightArrayItem(item_number, color) {\n $('#array_item_' + item_number).css({'background-color': color[1]});\n $('#array_item_container_' + item_number).css({'border': 'solid ' + color[0] + ' 2px'});\n}",
"function fill(val, i, color){\t\n\t\tvar height = scope.maxHeight * (val/scope.max);\n\t\tvar leftOffset = i*(scope.horizontalSpacing + scope.barWidth) + scope.padding;\n\t\tvar topOffset = scope.topMargin + (scope.maxHeight - height) + scope.padding;\n\t\t\n\t\tscope.ctx.fillStyle = color;\n\t\tscope.ctx.fillRect(leftOffset, topOffset, scope.barWidth, height);\n\t}",
"function getColorIndex(e) {\n\treturn e.target.children[0].dataset.index\n}",
"function uvColor (index) {\n if (index > 0 && index < 3 ) {\n green (index)\n }\n else if (index > 3 && index < 5 ) {\n yellow (index)\n }\n else if (index > 3 && index < 5 ) {\n yellow (index)\n }\n else if (index > 5 && index < 8 ) {\n orange (index)\n }\n else if (index > 8 && index < 11 ) {\n red (index)\n }\n else if (index > 11) {\n violet (index)\n }\n $(`#uvIndex2`).html(`\n <span> ${ index }</span>\n `) \n }",
"function colorCell (i, j, colorCode) {\n let x = i * 50;\n let y = j * 50;\n fill(colorCode[0], colorCode[1], colorCode[2]);\n stroke(0);\n rect(x, y, 50, 50);\n}",
"function getBgColorForRow(i) {\n if (i % 2 == 0) return '#ffffff'; // white for even rows\n else return '#e6e6fa' ; //'#e6f0fd'; // light blue for odd rows\n\n}",
"function getBackgroundColor(row, i){\n\tvar squareBackground;\n\tif( Math.floor(row%2)===0 ){\n\t\tsquareBackground = Math.floor(i%2)===0?\"black\":\"grey\";\n\t} else {\n\t\tsquareBackground = Math.floor(i%2)===0?\"grey\":\"black\";\n\t}\n\treturn squareBackground;\n}",
"function changeColors(color){\n for(var i =0; i<squares.length; i++){\n squares[i].style.backgroundColor = color;\n header.style.backgroundColor = color;\n }\n}",
"function highlightSorted(start) {\r\n for (var i = 0; i <= start; i++) {\r\n document.getElementById('bar' + i).style.backgroundColor = \"#ff93bb\"; //lightpink\r\n }\r\n}",
"drawnode(i, color) {\n let x = i % this.maze.width;\n let y = (i - x) / this.maze.width;\n this.cx.fillStyle = color;\n this.cx.fillRect(x * this.nodesize, y * this.nodesize, this.nodesize, this.nodesize);\n }",
"function forloop() {\n for (let i = 0; i > 7; index++) {\n console.log(color)\n // let index = colors[0];\n colors.forEach(element => console.log(i) ); \n }\n}",
"function winningColorToAllBlock(x){\r\n for(var i = 0 ; i < numberOfBlock ; i++)\r\n {\r\n block[i].style.backgroundColor = x;\r\n }\r\n}",
"colorIn(list) {\r\n list.forEach((item) => {\r\n item.div.style.backgroundColor = item.color;\r\n });\r\n }",
"function extractColor(text, i, color) {\n var matches = [],\n match;\n\t\t\n\ttext = text.slice(i);\n while ((match = text.match(/^\\x1b\\[([\\d;]*)m/))) {\n matches.push(match);\n text = text.slice(match[0].length);\n\t\ti += match[0].length;\n }\n \n if (!matches.length) {\n return null;\n }\n \n var tokens = matches.map(function(match){\n return match[1].split(\";\");\n });\n \n tokens = Array.prototype.concat.apply([], tokens);\n \n var span = color.copy();\n span.i = i;\n \n var code;\n \n for (i = 0; i < tokens.length; i++) {\n code = +tokens[i];\n if (code == 0) {\n span.reset();\n } else if (code == 1) {\n span.l = true;\n } else if (code == 5) {\n span.flash = true;\n } else if (code == 7) {\n var t = span.f;\n span.f = span.b;\n span.b = t;\n } else if (code < 40) {\n span.f = code - 30;\n } else if (code < 50) {\n span.b = code - 40;\n }\n }\n return span;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
decode_digit(cp) returns the numeric value of a basic code point (for use in representing integers) in the range 0 to base1, or base if cp is does not represent a value. | function decode_digit(cp) {
return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 : cp - 97 < 26 ? cp - 97 : base;
} | [
"function decode_digit(cp) {\n\t\treturn cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 : cp - 97 < 26 ? cp - 97 : base;\n\t}",
"function decode_digit(cp) {\r\n return cp - 48 < 10 ? cp - 22 : cp - 65 < 26 ? cp - 65 : cp - 97 < 26 ? cp - 97 : base;\r\n }",
"function parseDigits(cs, base, acc) /* (cs : list<char>, base : ?int, acc : ?int) -> maybe<int> */ { tailcall: while(1)\n{\n var base_18825 = (base !== undefined) ? base : 10;\n var acc_18829 = (acc !== undefined) ? acc : 0;\n if (cs == null) {\n return Just(acc_18829);\n }\n else {\n if (base_18825 >= 10) {\n var _x1 = '9';\n }\n else {\n var _x1 = _plus__4('0', String.fromCharCode(((base_18825 - 1)|0)));\n }\n var _x0 = ((cs.head >= '0') && (cs.head <= _x1));\n if (_x0) {\n var d = (_dash__2(cs.head, '0')).charCodeAt(0);\n }\n else {\n var _x2 = (base_18825 > 10 && (base_18825 <= 36 && ((cs.head >= 'a') && (cs.head <= _plus__4('a', String.fromCharCode(((base_18825 - 11)|0)))))));\n if (_x2) {\n var d = (((_dash__2(cs.head, 'a')).charCodeAt(0) + 10)|0);\n }\n else {\n var _x3 = (base_18825 > 10 && (base_18825 <= 36 && ((cs.head >= 'A') && (cs.head <= _plus__4('A', String.fromCharCode(((base_18825 - 11)|0)))))));\n if (_x3) {\n var d = (((_dash__2(cs.head, 'A')).charCodeAt(0) + 10)|0);\n }\n else {\n return Nothing;\n }\n }\n }\n {\n var _x0 = base_18825;\n var _x1 = (($std_core.intMultiply(base_18825,acc_18829) + d)|0);\n cs = cs.tail;\n base = _x0;\n acc = _x1;\n continue tailcall;\n }\n }\n}}",
"function prefixToBase(c){if(c===CP_b||c===CP_B){/* 0b/0B (binary) */return 2;}else if(c===CP_o||c===CP_O){/* 0o/0O (octal) */return 8;}else if(c===CP_t||c===CP_T){/* 0t/0T (decimal) */return 10;}else if(c===CP_x||c===CP_X){/* 0x/0X (hexadecimal) */return 16;}else{/* Not a meaningful character */return-1;}}",
"function toDigit(c) {\n var ccc = ord(c);\n if (cc0 <= ccc && ccc <= cc9)\n return ccc - cc0;\n throw new Error(\"Non-digit character: \" + c);\n }",
"function decToAltDigit(d, base) {\n if (base <= 10)\n return d;\n if (d < 10)\n return d;\n else {\n d = d - 10;\n return \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".charAt(d);\n }\n}",
"function ConvertBaseToDigit(sequenceBase) {\n switch (sequenceBase) {\n case 'A': return '0';\n case 'C': return '1';\n case 'G': return '2';\n case 'T':\n case 'U': return '3';\n }\n}",
"function prefixToBase(c) {\r\n if (c === CP_b || c === CP_B) {\r\n /* 0b/0B (binary) */\r\n return 2\r\n } else if (c === CP_o || c === CP_O) {\r\n /* 0o/0O (octal) */\r\n return 8\r\n } else if (c === CP_t || c === CP_T) {\r\n /* 0t/0T (decimal) */\r\n return 10\r\n } else if (c === CP_x || c === CP_X) {\r\n /* 0x/0X (hexadecimal) */\r\n return 16\r\n } else {\r\n /* Not a meaningful character */\r\n return -1\r\n }\r\n }",
"function baseNtoDec(num, base) {\n if (base != 1) {\n return parseInt(num, base);\n }\n return num.length;\n}",
"function prefixToBase(c) {\n\t\tif (c === CP_b || c === CP_B) {\n\t\t\t/* 0b/0B (binary) */\n\t\t\treturn 2;\n\t\t} else if (c === CP_o || c === CP_O) {\n\t\t\t/* 0o/0O (octal) */\n\t\t\treturn 8;\n\t\t} else if (c === CP_t || c === CP_T) {\n\t\t\t/* 0t/0T (decimal) */\n\t\t\treturn 10;\n\t\t} else if (c === CP_x || c === CP_X) {\n\t\t\t/* 0x/0X (hexadecimal) */\n\t\t\treturn 16;\n\t\t} else {\n\t\t\t/* Not a meaningful character */\n\t\t\treturn -1;\n\t\t}\n\t}",
"function prefixToBase(c) {\n\tif (c === CP_b || c === CP_B) {\n\t\t/* 0b/0B (binary) */\n\t\treturn 2;\n\t} else if (c === CP_o || c === CP_O) {\n\t\t/* 0o/0O (octal) */\n\t\treturn 8;\n\t} else if (c === CP_t || c === CP_T) {\n\t\t/* 0t/0T (decimal) */\n\t\treturn 10;\n\t} else if (c === CP_x || c === CP_X) {\n\t\t/* 0x/0X (hexadecimal) */\n\t\treturn 16;\n\t} else {\n\t\t/* Not a meaningful character */\n\t\treturn -1;\n\t}\n}",
"function prefixToBase(c) {\n if (c === CP_b || c === CP_B) {\n /* 0b/0B (binary) */\n return 2;\n } else if (c === CP_o || c === CP_O) {\n /* 0o/0O (octal) */\n return 8;\n } else if (c === CP_t || c === CP_T) {\n /* 0t/0T (decimal) */\n return 10;\n } else if (c === CP_x || c === CP_X) {\n /* 0x/0X (hexadecimal) */\n return 16;\n } else {\n /* Not a meaningful character */\n return -1;\n }\n }",
"function prefixToBase(c)\n{\n\tif (c === CP_b || c === CP_B) {\n\t\t/* 0b/0B (binary) */\n\t\treturn (2);\n\t} else if (c === CP_o || c === CP_O) {\n\t\t/* 0o/0O (octal) */\n\t\treturn (8);\n\t} else if (c === CP_t || c === CP_T) {\n\t\t/* 0t/0T (decimal) */\n\t\treturn (10);\n\t} else if (c === CP_x || c === CP_X) {\n\t\t/* 0x/0X (hexadecimal) */\n\t\treturn (16);\n\t} else {\n\t\t/* Not a meaningful character */\n\t\treturn (-1);\n\t}\n}",
"function hex_digit_decode_decimal(hex_digit_as_string){\n\tvar ascii = hex_digit_as_string.charCodeAt(0); \t\t\n\n\tif(ascii <= \"9\".charCodeAt(0)){\n\t\treturn ascii - 48 ;\t\t\t\t\t\t\t \t\n\t}\n\n\treturn ascii - \"a\".charCodeAt(0) + 10;\n}",
"function parseDigit(\n digitChar\n )\n{ \n var value = _getDigits()[digitChar];\n \n if (value == null)\n {\n return NaN;\n }\n else\n {\n return value;\n }\n}",
"function int2char(base) {\n\tif(base == 0) return 'A';\n\tif(base == 1) return 'C';\n\tif(base == 2) return 'G';\n\tif(base == 3) return 'U';\n\tthrow(\"There's something wrong in your int-base!\");\n}",
"_stateDecimalCharacterReferenceStart(cp) {\n if (isAsciiDigit(cp)) {\n this.state = State.DECIMAL_CHARACTER_REFERENCE;\n this._stateDecimalCharacterReference(cp);\n }\n else {\n this._err(error_codes_js_1$1.ERR.absenceOfDigitsInNumericCharacterReference);\n this._flushCodePointConsumedAsCharacterReference(unicode_js_1.CODE_POINTS.AMPERSAND);\n this._flushCodePointConsumedAsCharacterReference(unicode_js_1.CODE_POINTS.NUMBER_SIGN);\n this._reconsumeInState(this.returnState);\n }\n }",
"[DECIMAL_CHARACTER_REFERENCE_START_STATE](cp) {\n if (isAsciiDigit(cp)) {\n this._reconsumeInState(DECIMAL_CHARACTER_REFERENCE_STATE);\n } else {\n this._err(ERR.absenceOfDigitsInNumericCharacterReference);\n this._flushCodePointsConsumedAsCharacterReference();\n this._reconsumeInState(this.returnState);\n }\n }",
"[DECIMAL_CHARACTER_REFERENCE_START_STATE](cp) {\n if (isAsciiDigit(cp)) {\n this._reconsumeInState(DECIMAL_CHARACTER_REFERENCE_STATE);\n } else {\n this._err(ERR$1.absenceOfDigitsInNumericCharacterReference);\n this._flushCodePointsConsumedAsCharacterReference();\n this._reconsumeInState(this.returnState);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the Y component of the acceleration, as a floating point number. | function YAccelerometer_get_yValue()
{
if (this._cacheExpiration <= YAPI.GetTickCount()) {
if (this.load(YAPI.defaultCacheValidity) != YAPI_SUCCESS) {
return Y_YVALUE_INVALID;
}
}
return this._yValue;
} | [
"function getSpeedY() {\n\t\treturn this.speedY;\n\t}",
"function YMagnetometer_get_yValue()\n {\n if (this._cacheExpiration <= YAPI.GetTickCount()) {\n if (this.load(YAPI.defaultCacheValidity) != YAPI_SUCCESS) {\n return Y_YVALUE_INVALID;\n }\n }\n return this._yValue;\n }",
"get speed_y() {\n\t\treturn this.speed.y;\n\t}",
"get y(){\n\t\treturn Number(this.paddle.getAttribute(\"y\"));\n\t}",
"getVelocity() {\n return this.canTrackVelocity ? (\n // These casts could be avoided if parseFloat would be typed better\n velocityPerSecond(parseFloat(this.current) - parseFloat(this.prev), this.timeDelta)\n ) : 0;\n }",
"function getY() {\n return this.y;\n }",
"get y()\n\t{\n\t\tif (this._y != null)\n\t\t\treturn this._y;\n\n\t\t/*\n\t\tlet list = this.isInput ?\n\t\t\tthis.node.inputPlugs : this.node.outputPlugs;\n\n\t\treturn this.node.posSmooth.y\n\t\t\t+ this.node.height / 2\n\t\t\t+ (list.indexOf(this) + 1)\n\t\t\t* this.node.tree.theme.plugSpacing\n\t\t\t- (list.length + 1)\n\t\t\t* this.node.tree.theme.plugSpacing / 2;\n\t\t*/\n\n\t\treturn this.node.input.plugPositions()[this.isInput ? 'inputs'\n\t\t\t: 'outputs'].filter(o => o.plug === this)[0].y;\n\t}",
"function YGps_get_altitude()\n {\n var res; // double;\n if (this._cacheExpiration <= YAPI.GetTickCount()) {\n if (this.load(YAPI.defaultCacheValidity) != YAPI_SUCCESS) {\n return Y_ALTITUDE_INVALID;\n }\n }\n res = this._altitude;\n return res;\n }",
"function YSensor_get_currentValue()\n {\n var res; // float;\n if (this._cacheExpiration <= YAPI.GetTickCount()) {\n if (this.load(YAPI.defaultCacheValidity) != YAPI_SUCCESS) {\n return Y_CURRENTVALUE_INVALID;\n }\n }\n res = this._applyCalibration(this._currentRawValue);\n if (res == Y_CURRENTVALUE_INVALID) {\n res = this._currentValue;\n }\n res = res * this._iresol;\n return Math.round(res) / this._iresol;\n }",
"getVelocity() {\n // This could be isFloat(this.prev) && isFloat(this.current), but that would be wasteful\n return this.canTrackVelocity\n ? // These casts could be avoided if parseFloat would be typed better\n velocityPerSecond(parseFloat(this.current) -\n parseFloat(this.prev), this.timeDelta)\n : 0;\n }",
"deltaY() { return Math.sin(this.angle) * (this.speed); }",
"get y() {\n return this.__Internal__Dont__Modify__.position.y - (this.__Internal__Dont__Modify__.height / 2);\n }",
"function computeY (y) {\n const mag = me.magnification / 100\n return decimalRound((-y + me.element.el.offsetTop + (me.height / 2)) / mag, 2)\n }",
"function getY(){\n\t\treturn ((cursorY - prevCursorY));\n\t}",
"getY() {\n\t\treturn ( 800 - this.ty ) * 32 + terrain.getYOffset( game.tyoff );\n\t}",
"y_value(){\n let a = 0;\n let b = this.max_ammount;\n let c = 279;\n let d = 35;\n\n this.pos.y = (this.ammount - a) * ((d - c) / (b - a)) + c;\n }",
"get driftY() {\n return Utils.RTD(this.background.rotation.y);\n }",
"function YCarbonDioxide_get_currentValue()\n { if(YAPI.applyCalibration) {\n var res = YAPI.applyCalibration(this);\n if(res != Y_CURRENTVALUE_INVALID) {\n var resol = this.get_resolution();\n res = Math.round(res / resol) * resol;\n return res;\n }\n }\n var json_val = this._getAttr('currentValue');\n return (json_val == null ? Y_CURRENTVALUE_INVALID : Math.round(json_val/6553.6) / 10);\n }",
"get dragY() {\n return Utils.RTD(this.rotation.y);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
loop creating password until userchoice is matched in value to password.length | function generatePassword() {
password = '';
for ( i = 0; i < userchoice; i++) { //this will run until 'i' matches the length of userchoice
Char = choices[(Math.floor(Math.random() * choices.length))];
password += Char;
}
}//end of generatePassword() | [
"function generatePassword(){\n var passwordLength = document.getElementById(\"passLength\").value;\n if (passwordLength<8 || passwordLength>128){\n document.getElementById('mainDisplay').innerText = \"Please input password length between 8 and 128\";\n } else {\n getSelectedItems()\n finalPassword=tempPass\n for (i=tempPass.length; i<passwordLength; i++){\n finalPassword = finalPassword.concat(tempKeyPool.charAt(Math.floor(Math.random() * tempKeyPool.length)));\n }\n document.getElementById('mainDisplay').innerText = finalPassword;\n clearPassword()\n }\n}",
"function generatePassword() {\n // Gather inputs from password criteria form\n const length = lengthSlider.value;\n\n // Gather the password criteria\n const passwordCriteria = getCriteria();\n\n // Generate the password output\n let passwordOutput = \"\";\n if (passwordCriteria != null && passwordCriteria.length > 0) {\n for(var i = 0; i < length; i++) {\n let p = Math.floor(Math.random() * passwordCriteria.length);\n\n if (passwordCriteria[p] === \"0\") {\n passwordOutput = passwordOutput += getOptions(\"letters\");\n }\n\n if (passwordCriteria[p] === \"1\") {\n passwordOutput = passwordOutput += getOptions(\"letters\").toUpperCase();\n } \n\n if (passwordCriteria[p] === \"2\") {\n passwordOutput = passwordOutput += getOptions(\"numbers\");\n } \n\n if (passwordCriteria[p] === \"3\") {\n passwordOutput = passwordOutput += getOptions(\"characters\");\n } \n }\n }\n\n // Return the generated password\n return passwordOutput\n}",
"function makePassword(){\n createdPassword = \"\";\n for (i = 0; i < passwordLength; i++){\n if(hasLowercase === true){\n lowerPass();\n }\n if (hasUppercase === true){\n upperPass();\n }\n if(hasNumbers === true){\n numberPass();\n }\n if(hasSpecial === true){\n specialPass();\n }\n \n }\n}",
"function generatePassword() {\n\n \n\n\n // length of password should be equl to pass lenth promt input //\n\n console.log(length)\n\n\n for (let index = 0; index < passLength; index++) {\n var random = Math.floor(Math.random() * poolEl.length)\n console.log(index)\n\n password += poolEl[random]\n }\n console.log(password)\n\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n // but before we select random characters, we must first declare what opt components will be included in poolset, based on prompt\n\n // ???????????????????????????????????????????????????\n\n // publish password result to the html //\n\n // ?????????????????????????????????????????????????????\n }",
"function generatePassword(passLen, passVals, pReqs){\n var isValid = false;\n\n //Runs until a valid password is created\n while(isValid === false){\n var i = 0;\n var pword = \"\";\n var validCheck = [];\n var anyFalse = true;\n //creates password for length requested\n while(i < passLen){\n pword += passVals[Math.floor(Math.random() * (passVals.length))];\n i++;\n }\n\n //calling function to see if password matches all requirements\n validCheck = validation(pReqs, pword);\n\n //looping through returned value - if all requirements are met, will set anyFalse to true to signfy all values are true\n for(var check of validCheck){\n if(check !== true){\n anyFalse = false;\n } \n }\n\n //if all requeirments are met, anyfalse will remain true and set isValid to true, which ends loop\n if(anyFalse === true){\n isValid = true;\n }\n }\n var passwordText = document.querySelector('#password');\n passwordText.value = pword;\n}",
"function generatePassword() {\n const passwordLength = getPassswordLength();\n const userSelection = getUserCharSelection();\n\n let password = \"\";\n let passwordGeneratedChars = 0;\n\n while (passwordGeneratedChars != passwordLength) {\n let characterSelection = getRandomInt(4) + 1;\n\n if (characterSelection === 1 && userSelection.lowerCase === true) {\n password = password + lowerCase[getRandomInt(lowerCase.length)];\n passwordGeneratedChars++;\n } else if (characterSelection === 2 && userSelection.upperCase === true) {\n password = password + upperCase[getRandomInt(upperCase.length)];\n passwordGeneratedChars++;\n } else if (characterSelection === 3 && userSelection.numbers === true) {\n password = password + numbers[getRandomInt(numbers.length)];\n passwordGeneratedChars++;\n } else if (characterSelection === 4 && userSelection.specialChar === true) {\n password = password + specialChar[getRandomInt(specialChar.length)];\n passwordGeneratedChars++;\n }\n }\n return password;\n}",
"function generatePassword() {\n for (var i = 0; i < pwLength; i++)\n password = password + passwordPossibles.charAt(Math.floor(Math.random() * passwordPossibles.length));\n}",
"function randomizePassword() {\n for(var i = 0; i < charSelect; i++) {\n var randomIdx = Math.floor(Math.random() * passwordContainer.length);\n var randomChar = passwordContainer[randomIdx];\n finalPassword = randomChar + finalPassword;\n } \n }",
"function generatePassword() {\n //Resetting the criterias before new password generation\n\n isSpecialchar = false;\n isUppercasechar = false;\n isLowercasechar = false;\n isNumericChar = false;\n // get user inputs\n getPasswordcriteria();\n\n //selection set based on criterias\n var selectionSet = [];\n\n //user generated password based on selected criteria\n var userPassword = [];\n\n //add special char if user conform\n if (isSpecialchar === true) {\n let passwordChar =\n specialChar[Math.floor(Math.random() * (specialChar.length - 1))];\n userPassword.push(passwordChar);\n selectionSet = selectionSet.concat(specialChar);\n // console.log(\"selectionset is \" + selectionSet);\n }\n\n //add uppercase char if user conform\n if (isUppercasechar === true) {\n let passwordChar =\n upperCasechar[Math.floor(Math.random() * (upperCasechar.length - 1))];\n userPassword.push(passwordChar);\n selectionSet = selectionSet.concat(upperCasechar);\n //console.log(\"selectionset is \" + selectionSet);\n }\n\n //addlowercase char if user conform\n if (isLowercasechar === true) {\n let passwordChar =\n lowerCasechar[Math.floor(Math.random() * (lowerCasechar.length - 1))];\n userPassword.push(passwordChar);\n selectionSet = selectionSet.concat(lowerCasechar);\n //console.log(\"selectionset is \" + selectionSet);\n }\n\n //addnumeric char if user conform\n if (isNumericChar === true) {\n let passwordChar =\n numericChar[Math.floor(Math.random() * (numericChar.length - 1))];\n userPassword.push(passwordChar);\n selectionSet = selectionSet.concat(numericChar);\n //console.log(\"selectionset is \" + selectionSet);\n }\n\n //set no of more chars need to be added\n var remainingLength = passwordLength - userPassword.length;\n // console.log(\"Password Lenght user what selected is \" + passwordLength);\n // console.log(\"Current Password length is \" + userPassword.length);\n // console.log(\"Remaining length is \" + remainingLength);\n\n // fill the the remaining pwd lenght from Selection set\n for (var i = 0; i < remainingLength; i++) {\n let passwordChar =\n selectionSet[Math.floor(Math.random() * (selectionSet.length - 1))];\n userPassword.push(passwordChar);\n }\n // convert array into string without commas\n // console.log(\"Value of current password is \" + userPassword);\n // console.log(\"Value of password as string is \" + userPassword.join(\"\"));\n var userGeneratedpassword = userPassword.join(\"\");\n return userGeneratedpassword;\n}",
"function generatePassword() {\n var workingChars = criteriaFinder();\n var passwordLength = passwordLengthFinder();\n\n var tempPassword = createPasswordAttempt(workingChars, passwordLength);\n var passwordAccepted = false;\n while (passwordAccepted === false) {\n passwordAccepted = acceptablePassword(workingChars, tempPassword);\n if (passwordAccepted === false) {\n tempPassword = createPasswordAttempt(workingChars, passwordLength);\n }\n }\n return tempPassword;\n}",
"function generatePassword() {\n let verify = false;\n while (!verify) {\n let passLength = parseInt(prompt(\"Choose a password number between 8 and 128\"));\n //make statment for making sure there is a value\n if (!passLength) {\n alert(\"You need a value\");\n continue;\n } else if (passLength < 8 || passLength > 128) {\n passLength = parseInt(prompt(\"Password length must be between 8 and 128 characters long.\"));\n //this will happen once user puts in a correct number\n } else {\n confirmNumber = confirm(\"Do you want your password to contain numbers?\");\n confirmCharacter = confirm(\"Do you want your password to contain special characters?\");\n confirmUppercase = confirm(\"Do you want your password to contain Uppercase letters?\");\n confirmLowercase = confirm(\"Do you want your password to contain Lowercase letters?\");\n };\n //confirm that something will happen or error\n if (!confirmCharacter && !confirmLowercase && !confirmNumber && !confirmUppercase) {\n alert('At least one character type must be selected.');\n continue;\n }\n //verify its true to set pass\n verify = true;\n let newPass = '';\n let charset = '';\n //start if for statment for the password length\n //set combinations in else if statments\n //set charset for each else if statment\n //create for for loop for (var i = 0; i < passLength; ++i)\n //newPass += charset.charAt(Math.floor(Math.random() * charset.length));\nif(!confirmNumber && !confirmUppercase && ! confirmLowercase){\n charset = \"!@#$%^&*\"\n for (var i = 0; i < passLength; ++i) {\n newPass += charset.charAt(Math.floor(Math.random() * charset.length));\n }\n} else if (!confirmCharacter && !confirmUppercase && !confirmLowercase){\n charset = \"0123456789\"\n for (var i = 0; i < passLength; ++i) {\n newPass += charset.charAt(Math.floor(Math.random() * charset.length));\n }\n} else if (!confirmCharacter && !confirmNumber && !confirmLowercase){\n charset = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n for (var i = 0; i < passLength; ++i) {\n newPass += charset.charAt(Math.floor(Math.random() * charset.length));\n }\n} else if (!confirmCharacter && !confirmUppercase && !confirmNumber){\n charset = \"abcdefghijklmnopqrstuvwxyz\"\n for (var i = 0; i < passLength; ++i) {\n newPass += charset.charAt(Math.floor(Math.random() * charset.length));\n }\n}else if (!confirmCharacter && !confirmNumber){\n charset = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n for (var i = 0; i < passLength; ++i) {\n newPass += charset.charAt(Math.floor(Math.random() * charset.length));\n }\n}else if (!confirmUppercase && !confirmLowercase){\n charset = \"0123456789!@#$%^&*\"\n for (var i = 0; i < passLength; ++i) {\n newPass += charset.charAt(Math.floor(Math.random() * charset.length));\n }\n}else if (!confirmUppercase && !confirmNumber){\n charset = \"abcdefghijklmnopqrstuvwxyz!@#$%^&*\"\n for (var i = 0; i < passLength; ++i) {\n newPass += charset.charAt(Math.floor(Math.random() * charset.length));\n }\n}else if (!confirmLowercase && !confirmNumber){\n charset = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*\"\n for (var i = 0; i < passLength; ++i) {\n newPass += charset.charAt(Math.floor(Math.random() * charset.length));\n }\n} else {\n charset = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*\" \n for (var i = 0; i < passLength; ++i) {\n newPass += charset.charAt(Math.floor(Math.random() * charset.length));\n }\n}\n document.getElementById(\"password\").textContent = newPass;\n }\n}",
"function generatePassword() {\n //the variable prompts the user to choose the length of password and if it includes lower, upper, num/spec. characters\n var passwordLength = 0;\n while (!(passwordLength >= 8) || !(passwordLength <= 128)) {\n passwordLength = prompt(\n \"How long would you like for the password to be?, Must choose a length between 8-128 characters.\"\n );\n }\n\n var includeLower = confirm(\"Include lowercase letters?\");\n var includeUpper = confirm(\"Include uppercase letters?\");\n var includeNumber = confirm(\"Include numbers?\");\n var includeSpecial = confirm(\"Include special characters?\");\n console.log(\n passwordLength,\n includeLower,\n includeUpper,\n includeNumber,\n includeSpecial\n );\n // Get info from user to generate password.\n // Generate password based on criteria by concatinating the characterPool variable with the 4 options.\n var characterPool = [];\n if (includeUpper) {\n characterPool = characterPool.concat(UPPERCASE);\n }\n if (includeLower) {\n characterPool = characterPool.concat(LOWERCASE);\n }\n if (includeNumber) {\n characterPool = characterPool.concat(NUMBERS);\n }\n if (includeSpecial) {\n characterPool = characterPool.concat(SPECIAL);\n }\n console.log(characterPool);\n var password = \"\";\n for (var x = 0; x < passwordLength; x++) {\n console.log(x);\n randomChar = characterPool[rand(0, characterPool.length)];\n password = password + randomChar;\n }\n\n return password;\n}",
"function generatePassword(){\n for(i = 0; i < passLength; i++) {\n\n var randomCharacter = Math.floor(Math.random() * completeArray.length);\n password = password + completeArray[randomCharacter];\n }\n}",
"function pwLength() {\n while(charNum<8 || charNum>128) {\n charNum = prompt(\"Select a password length between 8 and 128 characters\");\n }\n}",
"function generatePassword() {\n var password = \"\"; // empty string to hold generated password \n var available = []; // An array placeholder for user generated amount of length\n\n // if statements concatenantes any of the confirms that return true\n if (confirmLower) {\n available = available.concat(lowercase);\n };\n\n if (confirmUpper) {\n available = available.concat(uppercase);\n };\n\n if (confirmNumeric) {\n available = available.concat(number);\n };\n\n if(confirmSymbol) {\n available = available.concat(symbol);\n };\n\n // Start random selection for passwordLength, based on selected options\n for (var i = 0; i < passwordLength; i++) {\n password += available[Math.floor(Math.random() * available.length)]; \n }; \n \n return password; // returns password onto the screen\n}",
"function generatePassword() {\n userInput();\n var output = characterOptions(passwordLength);\n return output;\n}",
"function generatePassword() {\n var concatArrays = upperCasedCharacters.concat(\n lowerCasedCharacters,\n specialCharacters,\n numericCharacters\n );\n\n var password = \"\";\n\n var passwordLength = prompt(\n \"Enter a length, between 8 - 128, for your password.\"\n );\n if (passwordLength <= 7) {\n prompt(\"Choice of password length is too short. Must be at least 8.\");\n return;\n } else if (passwordLength >= 129) {\n prompt(\"Choice of password length is too long. Must be a maximum of 128.\");\n return;\n }\n var lowerCase = confirm(\n \"If you would like to include lower-cased letters, click OK.\"\n );\n var upperCase = confirm(\n \"If you would like to include capitalized letters, click OK.\"\n );\n var numericChar = confirm(\"If you would like to include numbers, click OK.\");\n var specialChar = confirm(\n \"If you would like to include special characters, click OK.\"\n );\n // console.log(passwordLength);\n while (password.length < +passwordLength) {\n if (lowerCase === true) {\n var randomLowerChar =\n lowerCasedCharacters[\n Math.floor(Math.random() * lowerCasedCharacters.length)\n ];\n password += randomLowerChar;\n }\n if (upperCase === true) {\n var randomUpperChar =\n upperCasedCharacters[\n Math.floor(Math.random() * upperCasedCharacters.length)\n ];\n password += randomUpperChar;\n }\n if (numericChar === true) {\n var randomNumberChar =\n numericCharacters[Math.floor(Math.random() * numericCharacters.length)];\n password += randomNumberChar;\n }\n if (specialChar === true) {\n var randomSpecChar =\n specialCharacters[Math.floor(Math.random() * specialCharacters.length)];\n password += randomSpecChar;\n }\n }\n\n return password;\n}",
"function generateCriteria() {\n if (passCriteria[0]) {\n criteriaChars = lowercaseChars;\n console.log(criteriaChars);\n }\n if (passCriteria[1]) {\n criteriaChars = (criteriaChars + uppercaseChars);\n console.log(criteriaChars);\n }\n if (passCriteria[2]) {\n criteriaChars = (criteriaChars + numericChars);\n console.log(criteriaChars);\n }\n if (passCriteria[3]) {\n criteriaChars = (criteriaChars + specialChars);\n console.log(criteriaChars);\n }\n for (var i = 0; i < passLength; i++) {\n password = password + criteriaChars.charAt(Math.floor(Math.random() * criteriaChars.length));\n }\n console.log(password);\n // Use setTimeout function to allow viewport text area and alert show password close to same time \n document.getElementById(\"password\").value = password;\n setTimeout(function () {\n alert(\"Your password is: \" + password);\n }, 0);\n}",
"function createPassword(){\n for(i=0; i<passLength; i++){\n var array1 = charArray[randomIndex(charArray)];\n var randomChar = array1[randomIndex(array1)];\n newPassword += randomChar;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function sets the background color of the entire spreadsheet to white | function clearColors() {
var allRange = sheet.getRange('A:Z');
allRange.setBackground('#ffffff');
} | [
"function resetColor() {\n removeListeners();\n for(i=0; i < cells.length; i++) {\n cells[i].style.backgroundColor = \"white\";\n}}",
"function ApplyTopRowColor() {\n currentSpreadsheet.getRange('1:1').activate();\n currentSpreadsheet.getActiveRangeList().setBackground(titleRowColor); \n}",
"function cleanBgColor() {\r\n\t\tfor(var j=0; j<board.length; j++) {\r\n\t\t\tboard[j].style.backgroundColor = 'transparent';\r\n\t\t}\r\n\t}",
"function setwhite() {\n\tdocument.body.style.background= \"white\";\n\t\n}",
"function setNormalBackground(cell)\r\n {\r\n // light gray background-color with 15% opacity\r\n $(cell).css('background-color', 'rgba(30, 30, 30, 0.15)');\r\n }",
"function setWhite() {\r\n document.body.style.background = \"white\";\r\n}",
"function setCellColor(sheet, row, col, color)\n {\n var single_cell = sheet.getRange(row, col, 1, 1);\n single_cell.setBackgroundColor(color);\n }",
"function ChangeBackgroundColor(row) {\n row.style.backgroundColor = \"#9999ff\";\n}",
"function resetBackground (){\n viewer.setBackgroundColor(169,169,169, 255,255, 255);\n}",
"function setBoardBackgroundColor() {\n var num = getRowColNum('board');\n for (var row = 0; row < num.rowsNum; row++) {\n for (var col = 0; col < num.colsNum; col++) {\n setSquareBackgroundColor(row, col, getBoardSquareColor(row, col));\n }\n }\n }",
"function clearAll() {\n cells.forEach(cell => cell.style.backgroundColor = \"white\")\n}",
"function detBackgroundColor(cell) {\r\n var currentCell = SpreadsheetApp.getActiveSpreadsheet().getRange(cell);\r\n return currentCell.getBackground();\r\n}",
"function highlightBackground(cell)\r\n {\r\n // Gold background-color with 35% opacity\r\n $(cell).css('background-color', 'rgba(255, 215, 0, 0.35)');\r\n }",
"function unpaint() {\n var cells = document.getElementsByClassName('cell');\n for (var l = 0; l < cells.length; l++) {\n cells[l].style.removeProperty('background-color');\n }\n}",
"function setWhite(element){\n element.style.backgroundColor = \"white\";\n}",
"function setColors() {\n\t$('.worksheet-row').each(function (index) {\n\t\tvar rowColor = $(this).attr('colorid');\n\t\trowColor = (rowColor === '' ? '#FFFFFF' : rowColor);\n\t\tvar contrastColor = jQuery.Color(rowColor).contrastColor();\n\t\tvar contrastColor2 = (contrastColor == 'white' ? 'black' : 'white');\n\n\t\t$(this).css(\"background-color\", rowColor);\n\t\t$(this).find('.rownumberbadge').css({'background-color': contrastColor, 'color': contrastColor2});\n\t\t$(this).find('.buttonContainer').css({'border-color': contrastColor2});\n\t\t$(this).find('.checkButton, .skipButton').css({'background-color': contrastColor, 'color': contrastColor2});\n\t});\n}",
"function colorSheet(sheet) {\n if (!isBacklog(sheet))\n return;\n var startRow = 2;\n var endRow = sheet.getLastRow();\n\n for (var r = startRow; r <= endRow; r++) {\n colorRow(sheet, r);\n }\n}",
"function fillU(){\n var defaultColor = \"\";\n // Loop through all table to check which cells' background color is undefine and fill it in with color. \n for (var i =0; i < numRows; i++){\n for (var j =0; j < numCols; j++){\n defaultColor =document.getElementById(\"grid\").children[i].children[j].style.backgroundColor;\n if(defaultColor == \"\" ){\n document.getElementById(\"grid\").children[i].children[j].style.backgroundColor= colorSelected;\n }\n }\n }\n}",
"function greyBackground() {\n\t\tfor(i = 0; i <= 9; i++){ \n\t\t\tfor(j = 0; j <= 9; j++){ \n\t\t\t\tif(document.getElementById(\"\"+[i]+\",\" +[j] +\"\").style.backgroundColor != 'rgb(244, 67, 54)'\n\t\t\t\t&& document.getElementById(\"\"+[i]+\",\" +[j] +\"\").style.backgroundColor != 'rgb(219, 60, 48)'\t\t\n\t\t\t\t&& document.getElementById(\"\"+[i]+\",\" +[j] +\"\").style.backgroundColor != 'rgb(26, 26, 26)'){\n\t\t\t\t\tdocument.getElementById(\"\"+[i]+\",\" +[j] +\"\").style.backgroundColor = \"#f2f2f2\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
in case user clicked no for navigation action where a dialog was presented to make sure user wants to leave the page | abortPageNavigate() {
this.confirm_navigation_level = 2;
history.back();
setTimeout(function() {
this.confirm_navigation_level = 1;
}, 300);
} | [
"function onModalUnsavedOkayButtonClicked( modalInstance ) {\n modalInstance.close();\n isNavigationApprovedByUser = true;\n self.stopListening();\n $state.go( targetState );\n //isNavigationApprovedByUser = false;\n }",
"function ExitPage() {\n\t\talert('Are you sure you want navigate away from this App?');\n\t\tgetit()\n\t}",
"function confirmExit() {\r\n // 'view' and 'status' (which is the instrument status view) do not have editable data, so \r\n // do not prompt user\r\n if (!submitted && !quicklink && componentView != 'view' && componentView != 'status') {\r\n return \"Are you sure you want to leave this page without saving ?\";\r\n }\r\n // if user clicked on a quicklink thereby setting the quicklink flag, need to turn it back\r\n // off so it will not prevent the confirm exit dialog \r\n quicklink = false;\r\n}",
"checkAndCancel() {\n const currentPage = this.currentPage;\n const currentPageHasOverrides = currentPage.stopCancel || currentPage.preventDefault;\n if (this.stopNavigation) {\n return;\n }\n currentPage.pageOnCancel.emit();\n if (!currentPageHasOverrides) {\n this.onCancel.emit();\n }\n if (!this.stopCancel && !currentPageHasOverrides) {\n this.close();\n }\n }",
"function confirmNavigationIfDirtyWithoutEvent()\r\n{\r\n // If Any Frame's Data Has Changed Since Last Save - This is necessary because the beforeunload event is coming from the main window\r\n if (isAnyoneDirty())\r\n {\r\n return \"You are now leaving this page. If you continue, any unsaved data will be lost.\";\r\n }\r\n}",
"beforeRouteLeave (to, from, next) {\n // if user already confimed \"yes\" to leave the page\n if (this.isYesToLeave) {\n next() // leave model page and route to next page\n return\n }\n // else:\n // if there any edited and unsaved parameters for current model\n this.paramEditCount = this.paramViewUpdatedCount(this.digest)\n if (this.paramEditCount <= 0) {\n next() // no unsaved changes: leave model page and route to next page\n return\n }\n // else:\n // redirect to dialog to confirm \"discard all changes?\"\n this.showAllDiscardDlg = true\n this.pathToRouteLeave = to.path || '' // store path-to leave if user confirm \"yes\" to \"discard changes?\"\n next(false)\n }",
"preventNavigation() {\n return (\n this._dialogInstance &&\n this._dialogInstance.preventNavigation !== undefined &&\n this._dialogInstance.preventNavigation()\n );\n }",
"onLeave(e = {}) {\n if (this.isChanged()) {\n return e.returnValue = 'You haven\\'t posted your message. If you leave this page, your message will not be saved. Are you sure you want to leave?'\n }\n }",
"function onClosePage(event)\n\t{\n\t\tevent.preventDefault();\n\t\tevent.returnValue='';\n\t}",
"function onLeaveStepCallback(obj)\n {\n var step_num= obj.attr('rel'); // get the current step number\n return validateSteps(step_num); // return false to stay on step and true to continue navigation\n }",
"confirmCancel() {\n if (this.confirmingCancel) return\n\n this.confirmingCancel = true\n\n this.$buefy.dialog.confirm({\n message: this.trans('If you leave this page changes will not be saved.'),\n onConfirm: () => {\n this.confirmingCancel = false\n window.location.href = this.cancelUrl\n },\n onCancel: () => { this.confirmingCancel = false },\n cancelText: this.trans('buttons.stay_on_page'),\n confirmText: this.trans('buttons.leave_page'),\n })\n }",
"_onBeforeUnload(e) {\n // ensure we don't leave DURING edit mode\n if (!this.skipExitTrap && this.editMode) {\n return \"Are you sure you want to leave? Your work will not be saved!\";\n }\n }",
"dismissDialog() {\n if (!this.preventNavigation()) {\n hub.emit(new DialogChangedEvent({\n currentDialog: null\n }));\n }\n }",
"onYesDiscardChanges () {\n this.dispatchParamViewDeleteByModel(this.digest) // discard parameter view state and edit changes\n this.isYesToLeave = true\n this.$router.push(this.pathToRouteLeave)\n }",
"function modalWindowConfirmLeave(event) {\n var isConfirmed = confirm('Are you sure you want to leave?');\n if (isConfirmed === false) {\n event.preventDefault();\n alert('OK. You can stay!');\n } \n}",
"function onCancel(){\n\tView.getOpenerView().closeDialog();\t\t\n}",
"function onPageLeaving() {\n window.onbeforeunload = function () {\n return false;\n };\n}",
"goBackToDefaultView(event){\n\t\tevent.preventDefault();\n\t\tthis.setState({\n\t\t\tshowSingleInterviewer: false\n\t\t})\n\t}",
"function leaveUnsaved() {\n if ($('.save-actions .unsaved').is(':visible')) {\n return confirm(\"You have unsaved data. Leave?\");\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function to produce an XML tag. | function tag(name, attrs, selfclosing) {
var result = '<' + name;
if(attrs && attrs.length > 0) {
var i = 0;
var attrib;
while ((attrib = attrs[i]) !== undefined) {
result += ' ' + attrib[0] + '="' + this.esc(attrib[1]) + '"';
i++;
}
}
if(selfclosing) {
result += ' /';
}
result += '>';
return result;
} | [
"function openTag(tag,attr,raw){var s='<'+tag,key,val;if(attr){for(key in attr){val=attr[key];if(val!=null){s+=' '+key+'=\"'+val+'\"';}}}if(raw)s+=' '+raw;return s+'>';}// generate string for closing xml tag",
"function xml_tag(name, attrs, selfclosing) {\n var result = \"<\" + name;\n if (attrs && attrs.length > 0) {\n var i = 0;\n var attrib;\n while ((attrib = attrs[i]) !== undefined) {\n result += \" \" + attrib[0] + '=\"' + this.esc(attrib[1]) + '\"';\n i++;\n }\n }\n if (selfclosing) {\n result += \" /\";\n }\n result += \">\";\n return result;\n}",
"function xrxCreateTag( label, type, value )\n{\n if(type == \"\")\n {\n return( \"<\" + label + \">\" + value + \"</\" + label + \">\" );\n }\n else\n {\n return( \"<\" + label + \" \" + type + \">\" + value + \"</\" + label + \">\" );\n }\n}",
"function makeTag (tagName, strValue) {\n return \"<\"+tagName+\">\"+strValue+\"</\"+tagName+\">\"\n}",
"function openTag(tag, attr, raw) {\n var s = '<' + tag,\n key,\n val;\n\n if (attr) {\n for (key in attr) {\n val = attr[key];\n\n if (val != null) {\n s += ' ' + key + '=\"' + val + '\"';\n }\n }\n }\n\n if (raw) s += ' ' + raw;\n return s + '>';\n} // generate string for closing xml tag",
"function tag(name, content, attr) {\n if (typeof content === 'number') { content = content.toString(); }\n return '<' + name + (attr ? ' ' + attr : '') + '>' +\n (typeof content === 'string' ? (content + '</' + name + '>') : '');\n }",
"function createTag(tag, content) {\n return '<' + tag + '>' +\n content +\n '</' + tag + '>';\n}",
"function xrxCreateEscapedTag(label, type, value) \n{\n if (type == \"\") {\n return (\"<\" + label + \">\" + value + \"</\" + label + \">\");\n }\n else {\n return (\"<\" + label + \" \" + type + \">\" + value + \"</\" + label + \">\");\n }\n}",
"function tag$1(name, attrs, selfclosing) {\n var result = \"<\" + name;\n if (attrs && attrs.length > 0) {\n var i = 0;\n var attrib;\n while ((attrib = attrs[i]) !== undefined) {\n result += \" \" + attrib[0] + '=\"' + this.esc(attrib[1]) + '\"';\n i++;\n }\n }\n if (selfclosing) {\n result += \" /\";\n }\n result += \">\";\n return result;\n }",
"function html_tag(tag) {\n var out = \"<\" + tag;\n var contents = A.slice.call(arguments, 1);\n if (typeof contents[0] === \"object\") {\n var attrs = contents.shift();\n for (var a in attrs) {\n if (attrs.hasOwnProperty(a)) {\n var v = attrs[a];\n // true and false act as special values: when true, just output the\n // attribute name (without any value); when false, skip the attribute\n // altogether\n if (v !== false) {\n out += (v === true ? \" {0}\" : \" {0}=\\\"{1}\\\"\").fmt(a, v);\n }\n }\n }\n }\n out += \">\";\n var keep_open = typeof contents[contents.length - 1] === \"boolean\" ?\n contents.pop() : false;\n out += contents.join(\"\");\n if (!keep_open) {\n out += \"</{0}>\".fmt(tag);\n }\n return out;\n}",
"function versionTag() {\r\n return '<?xml version=\"' + version + '\" encoding=\"utf-8\"?>';\r\n}",
"get tag() {\n var tag = this.advance.val,\n selfClosing = !this.xml && exports.selfClosing.indexOf(tag) !== -1,\n buf = ['\"\\\\n<' + tag + this.attrs + (selfClosing ? '/>\"' : '>\"')]\n switch (this.peek.type) {\n case 'text':\n buf.push(this.text)\n break\n case 'conditionalComment':\n buf.push(this.conditionalComment)\n break;\n case 'comment':\n buf.push(this.comment)\n break\n case 'outputCode':\n buf.push(this.outputCode)\n break\n case 'escapeCode':\n buf.push(this.escapeCode)\n break\n case 'indent':\n buf.push(this.block)\n }\n if (!selfClosing) buf.push('\"</' + tag + '>\"')\n return buf.join(' + ')\n }",
"function buildXMLString()\r\n\t\t{\r\n\t\t\tif(d.p.elName.text != \"\")\r\n\t\t\t{\r\n\t\t\t\tif(d.topGP.attGp.bottomRow.attribList.items[0].text != \"None\")\r\n\t\t\t\t{\r\n\t\t\t\t\tvar params = \"\";\r\n\t\t\t\t\tfor(var i = 0;i < d.topGP.attGp.bottomRow.attribList.items.length;i++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tvar item = d.topGP.attGp.bottomRow.attribList.items[i]\r\n\t\t\t\t\t\tparams += \" \" + item.text + \"='\" + item.value + \"'\";\r\n\t\t\t\t\t}\r\n\t\t\t\t\tvar n = \"<\" + d.p.elName.text + params + \">\" + d.topGP.attGp2.dText.text + \"</\" + d.p.elName.text + \">\";\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tvar n = \"<\" + d.p.elName.text + \">\" + d.topGP.attGp2.dText.text + \"</\" + d.p.elName.text + \">\";\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if(d.elementGp.eText.text != \"\")\r\n\t\t\t{\r\n\t\t\t\tvar n = d.elementGp.eText.text;\r\n\t\t\t}\r\n\t\t\treturn n;\t\t\r\n\t\t}",
"function build_node(tag_name, val) {\n\t\t\tvar\n\t\t\ttag_name = tag_name.replace(/[^\\w\\-_]/g, '-').replace(/-{2,}/g, '-').replace(/^[^a-z]/, function($0) { return 'node-'+$0; }),\n\t\t\tpadder = new Array(depth + 2).join('\\t'),\n\t\t\tnode = '\\n'+padder+'<'+tag_name+'>\\n'+padder+'\\t';\n\t\t\tnode += typeof val != 'object' ? val : json_to_xml(val, null, depth + 1);\n\t\t\treturn node + '\\n'+padder+'</'+tag_name+'>\\n';\n\t\t}",
"function buildTagHTML(tag){\n return \"<span class=\\\"tag tagLink\\\">\"+tag+\"</span>\";\n}",
"function openTag(tag, attr, raw) {\n var s = '<' + tag, key, val;\n if (attr) {\n for (key in attr) {\n val = attr[key];\n if (val != null) {\n s += ' ' + key + '=\"' + val + '\"';\n }\n }\n }\n if (raw) s += ' ' + raw;\n return s + '>';\n }",
"emitStartTag(token) {\n let res = `<${token.tagName}`;\n for (const attr of token.attrs) {\n res += ` ${attr.name}=\"${escapeAttribute(attr.value)}\"`;\n }\n res += token.selfClosing ? '/>' : '>';\n this.push(res);\n }",
"function createLabel() {\n if (elLabel.ref || elLabel.defText) {\n xmlWriter.writeStartElement('label');\n if (elLabel.ref) {\n xmlWriter.writeAttributeString('ref',elLabel.ref);\n }\n if (elLabel.defText) {\n xmlWriter.writeString(elLabel.defText);\n }\n xmlWriter.writeEndElement(); //close Label tag;\n }\n }",
"function createLabel() {\n if (elLabel) {\n xmlWriter.writeStartElement('label');\n if (elLabel.ref) {\n xmlWriter.writeAttributeString('ref',elLabel.ref);\n }\n if (elLabel.defText) {\n xmlWriter.writeString(elLabel.defText);\n }\n xmlWriter.writeEndElement(); //close Label tag;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
filtering all the pets | function filterAllPets (){
filterType = "";
filterAgeMin = 0;
filterAgeMax = Number.MAX_VALUE;
loadTableWithFilters();
} | [
"getFilteredPets(props) {\n let settings = props ? props.settings : this.state.settings;\n let allPets = props ? props.pets.allPets : this.state.pets.allPets;\n let savedPets = props ? props.pets.savedPets : this.state.pets.savedPets;\n\n let savedPetIds = [];\n for (let savedPet of savedPets) {\n savedPetIds.push(savedPet.id);\n }\n\n let pets = [];\n for (let pet of allPets) {\n if (!savedPetIds.includes(pet.id) &&\n pet.type == settings.typePreference &&\n pet.age >= settings.ageRange.min &&\n pet.age <= settings.ageRange.max) {\n pets.push(pet);\n }\n }\n return pets;\n }",
"function filterPets(filter) {\n // OBTAIN data from server.\n const selectedPet = getUserPet(selectedPetId);\n filteredPets = petProfiles.filter((pet)=>{\n return pet.ownerUsername !== curUser.username\n && !pet.dislikedBy.includes(selectedPetId) && !pet.dislikes.includes(selectedPetId)\n && !selectedPet.likes.includes(pet._id) && !selectedPet.matchedIds.includes(pet._id)\n && !selectedPet.favouriteIds.includes(pet._id);\n });\n\n if (filter === 'Gender') {\n filteredPets = filteredPets.filter((pet) => {\n if (filterGender !== 'Any') {\n if (pet.gender === filterGender) {\n return pet\n }\n } else {\n return pet\n }\n })\n }\n\n if (filter === 'Species') {\n filteredPets = filteredPets.filter((pet) => {\n if (filterSpecies !== 'Any') {\n if (pet.species === filterSpecies) {\n return pet\n }\n } else {\n return pet\n }\n })\n }\n\n if (filter === 'Breed') {\n filteredPets = filteredPets.filter((pet) => {\n if (filterBreed !== 'Any') {\n if (pet.breed === filterBreed) {\n return pet\n }\n } else {\n return pet\n }\n })\n }\n}",
"function filterPets(){\r\n for(let i = 0; i < listings.length; i++){\r\n let l = listings[i].val;\r\n listings[i].visible = l.pets && listings[i].visible;\r\n }\r\n}",
"function filterAllPets()\n{\n filterAgeMin=0;\n filterAgeMax=Number.MAX_VALUE;\n filterType=\"\";\n loadTableWithFilters();\n}",
"function filterPets(pet){\n let lessThan5 = pet.age < 5;\n let hasS = pet.name[0] == \"S\" || pet.ownerName[0] == \"S\";\n return lessThan5 && hasS;\n}",
"function read_pets(filters) {\n\n let q = datastore.createQuery(PETS);\n\n // Add filters passed by the url\n for (var key in filters) {\n // Dynamically convert boolean values\n if (filters[key] == 'on') {\n filters[key] = true;\n }\n // if (filters[key] == 'false') {\n // filters[key] = false;\n // }\n\n q = q.filter(key, '=', filters[key])\n }\n \n return datastore.runQuery(q).then( (entities) => {\n return entities[0].map(fromDatastore);\n })\n\n}",
"function filterPokemons(){\n\t//Iterates through each pokemon div view and checks\n\t// its type classes against filter\n\t$(\".pokemon\").each(function(i, obj) {\n\t\tvar visibility = true;\n\t\tfor(k=0; k<filterCheckedTypes.length; k++){\n\t\t\tif($(this).children(\".\"+filterCheckedTypes[k]).length == 0){\n\t\t\t\tvisibility = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (visibility) {\n\t\t\t$(obj).show();\n\t\t} else {\n\t\t\t$(obj).hide();\n\t\t}\n\t});\n}",
"onFilterFull() {\n this.lots = this.lots.filter(lot => lot.vehicle);\n }",
"function getSpotsWithPetrology() {\n return _.filter(activeSpots, function (spot) {\n return _.has(spot.properties, 'pet');\n });\n }",
"function filterDogs() {\n const onlyDogs = allAnimals.filter(isDog);\n displayList(onlyDogs);\n}",
"getPetsByOwner(ownerId) {\r\n return this.pets.filter((pet) => {\r\n return pet.owner && pet.owner.id === ownerId;\r\n });\r\n }",
"filterList () {\n let pets = this.state.pets;\n let filterValue = this.state.filterValue;\n\n pets = pets.filter(function (pets) {\n return pets.name.toLowerCase().indexOf(filterValue) != -1;\n });\n this.setState({filteredPets: pets});\n }",
"function experienceFilters() {\n const filtered = pokemon.filter((pexp) => pexp.base_experience > \"100\");\n displaydata(filtered);\n}",
"filterByCategory(plates, categoryfilter) {\n let res = [];\n if (categoryfilter.indexOf('Other') !==-1) {\n plates.forEach((plate) => {\n var founded =false;\n for (var key in plate.category) {\n if (allFilters.indexOf(key) !==1 && !founded) {\n founded = true;\n }\n }\n if (!founded){\n res.push(plate);\n };\n })\n }\n // no more filters except 'Other' filter\n if (categoryfilter.length ===1 &&\n categoryfilter[0] === 'Other') return res;\n\n // Add on top of 'Other' filter if it exists\n plates.forEach((plate) => {\n categoryfilter.forEach((filter)=>{\n if (filter in plate.category) {\n res.push(plate)\n return;\n };\n })\n });\n return res = helpers.shuffle(res);;\n }",
"filterVessels ({ vessels, filter, key }) {\n return filter ? vessels.filter((vessel) => filter.includes(vessel[key])) : vessels\n }",
"function filterPokemon(arrayPokemones, paramFilter) {\n let arrFiltrado = []\n arrayPokemones.forEach(element => {\n if (element.type.includes(paramFilter)) {\n arrFiltrado.push(element)\n }\n })\n return arrFiltrado\n}",
"function filterCats() {\n const onlyCats = allAnimals.filter(isCat);\n displayList(onlyCats);\n}",
"filterByType (pokemon, type) {\n const filterType = [];\n for(let i= 0; i < pokemon.length; i++){\n for(let t=0; t < pokemon[i].type.length; t++){\n if (pokemon[i].type[t] === type){\n filterType.push(pokemon[i]);\n }\n }\n }\n\n return filterType;\n}",
"filteredCastles() {\n return this.castles.filter(\n (castle) => {\n let filterCastleResult = true\n if (this.form.filterName !== \"\") {\n filterCastleResult = castle.name.includes(this.form.filterName)\n }\n return filterCastleResult\n }\n )\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs a new RequestLaunchTemplateData. The information to include in the launch template. | function RequestLaunchTemplateData() {
_classCallCheck(this, RequestLaunchTemplateData);
RequestLaunchTemplateData.initialize(this);
} | [
"constructor() { \n \n RequestLaunchTemplateData.initialize(this);\n }",
"function ModifyLaunchTemplateRequest() {\n _classCallCheck(this, ModifyLaunchTemplateRequest);\n\n ModifyLaunchTemplateRequest.initialize(this);\n }",
"function ResponseLaunchTemplateData() {\n _classCallCheck(this, ResponseLaunchTemplateData);\n\n ResponseLaunchTemplateData.initialize(this);\n }",
"constructor() { \n \n ResponseLaunchTemplateData.initialize(this);\n }",
"function LaunchTemplatePlacementRequest() {\n _classCallCheck(this, LaunchTemplatePlacementRequest);\n\n LaunchTemplatePlacementRequest.initialize(this);\n }",
"function TemplateInstantiationRequest() {\n}",
"function cfnLaunchTemplateLaunchTemplateDataPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnLaunchTemplate_LaunchTemplateDataPropertyValidator(properties).assertSuccess();\n return {\n BlockDeviceMappings: cdk.listMapper(cfnLaunchTemplateBlockDeviceMappingPropertyToCloudFormation)(properties.blockDeviceMappings),\n CreditSpecification: cfnLaunchTemplateCreditSpecificationPropertyToCloudFormation(properties.creditSpecification),\n DisableApiTermination: cdk.booleanToCloudFormation(properties.disableApiTermination),\n EbsOptimized: cdk.booleanToCloudFormation(properties.ebsOptimized),\n ElasticGpuSpecifications: cdk.listMapper(cfnLaunchTemplateElasticGpuSpecificationPropertyToCloudFormation)(properties.elasticGpuSpecifications),\n IamInstanceProfile: cfnLaunchTemplateIamInstanceProfilePropertyToCloudFormation(properties.iamInstanceProfile),\n ImageId: cdk.stringToCloudFormation(properties.imageId),\n InstanceInitiatedShutdownBehavior: cdk.stringToCloudFormation(properties.instanceInitiatedShutdownBehavior),\n InstanceMarketOptions: cfnLaunchTemplateInstanceMarketOptionsPropertyToCloudFormation(properties.instanceMarketOptions),\n InstanceType: cdk.stringToCloudFormation(properties.instanceType),\n KernelId: cdk.stringToCloudFormation(properties.kernelId),\n KeyName: cdk.stringToCloudFormation(properties.keyName),\n Monitoring: cfnLaunchTemplateMonitoringPropertyToCloudFormation(properties.monitoring),\n NetworkInterfaces: cdk.listMapper(cfnLaunchTemplateNetworkInterfacePropertyToCloudFormation)(properties.networkInterfaces),\n Placement: cfnLaunchTemplatePlacementPropertyToCloudFormation(properties.placement),\n RamDiskId: cdk.stringToCloudFormation(properties.ramDiskId),\n SecurityGroupIds: cdk.listMapper(cdk.stringToCloudFormation)(properties.securityGroupIds),\n SecurityGroups: cdk.listMapper(cdk.stringToCloudFormation)(properties.securityGroups),\n TagSpecifications: cdk.listMapper(cfnLaunchTemplateTagSpecificationPropertyToCloudFormation)(properties.tagSpecifications),\n UserData: cdk.stringToCloudFormation(properties.userData),\n };\n}",
"function cfnLaunchTemplateLaunchTemplateDataPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnLaunchTemplate_LaunchTemplateDataPropertyValidator(properties).assertSuccess();\n return {\n BlockDeviceMappings: cdk.listMapper(cfnLaunchTemplateBlockDeviceMappingPropertyToCloudFormation)(properties.blockDeviceMappings),\n CapacityReservationSpecification: cfnLaunchTemplateCapacityReservationSpecificationPropertyToCloudFormation(properties.capacityReservationSpecification),\n CpuOptions: cfnLaunchTemplateCpuOptionsPropertyToCloudFormation(properties.cpuOptions),\n CreditSpecification: cfnLaunchTemplateCreditSpecificationPropertyToCloudFormation(properties.creditSpecification),\n DisableApiTermination: cdk.booleanToCloudFormation(properties.disableApiTermination),\n EbsOptimized: cdk.booleanToCloudFormation(properties.ebsOptimized),\n ElasticGpuSpecifications: cdk.listMapper(cfnLaunchTemplateElasticGpuSpecificationPropertyToCloudFormation)(properties.elasticGpuSpecifications),\n ElasticInferenceAccelerators: cdk.listMapper(cfnLaunchTemplateLaunchTemplateElasticInferenceAcceleratorPropertyToCloudFormation)(properties.elasticInferenceAccelerators),\n EnclaveOptions: cfnLaunchTemplateEnclaveOptionsPropertyToCloudFormation(properties.enclaveOptions),\n HibernationOptions: cfnLaunchTemplateHibernationOptionsPropertyToCloudFormation(properties.hibernationOptions),\n IamInstanceProfile: cfnLaunchTemplateIamInstanceProfilePropertyToCloudFormation(properties.iamInstanceProfile),\n ImageId: cdk.stringToCloudFormation(properties.imageId),\n InstanceInitiatedShutdownBehavior: cdk.stringToCloudFormation(properties.instanceInitiatedShutdownBehavior),\n InstanceMarketOptions: cfnLaunchTemplateInstanceMarketOptionsPropertyToCloudFormation(properties.instanceMarketOptions),\n InstanceType: cdk.stringToCloudFormation(properties.instanceType),\n KernelId: cdk.stringToCloudFormation(properties.kernelId),\n KeyName: cdk.stringToCloudFormation(properties.keyName),\n LicenseSpecifications: cdk.listMapper(cfnLaunchTemplateLicenseSpecificationPropertyToCloudFormation)(properties.licenseSpecifications),\n MetadataOptions: cfnLaunchTemplateMetadataOptionsPropertyToCloudFormation(properties.metadataOptions),\n Monitoring: cfnLaunchTemplateMonitoringPropertyToCloudFormation(properties.monitoring),\n NetworkInterfaces: cdk.listMapper(cfnLaunchTemplateNetworkInterfacePropertyToCloudFormation)(properties.networkInterfaces),\n Placement: cfnLaunchTemplatePlacementPropertyToCloudFormation(properties.placement),\n RamDiskId: cdk.stringToCloudFormation(properties.ramDiskId),\n SecurityGroupIds: cdk.listMapper(cdk.stringToCloudFormation)(properties.securityGroupIds),\n SecurityGroups: cdk.listMapper(cdk.stringToCloudFormation)(properties.securityGroups),\n TagSpecifications: cdk.listMapper(cfnLaunchTemplateTagSpecificationPropertyToCloudFormation)(properties.tagSpecifications),\n UserData: cdk.stringToCloudFormation(properties.userData),\n };\n}",
"function cfnLaunchTemplateLaunchTemplateDataPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnLaunchTemplate_LaunchTemplateDataPropertyValidator(properties).assertSuccess();\n return {\n BlockDeviceMappings: cdk.listMapper(cfnLaunchTemplateBlockDeviceMappingPropertyToCloudFormation)(properties.blockDeviceMappings),\n CapacityReservationSpecification: cfnLaunchTemplateCapacityReservationSpecificationPropertyToCloudFormation(properties.capacityReservationSpecification),\n CpuOptions: cfnLaunchTemplateCpuOptionsPropertyToCloudFormation(properties.cpuOptions),\n CreditSpecification: cfnLaunchTemplateCreditSpecificationPropertyToCloudFormation(properties.creditSpecification),\n DisableApiTermination: cdk.booleanToCloudFormation(properties.disableApiTermination),\n EbsOptimized: cdk.booleanToCloudFormation(properties.ebsOptimized),\n ElasticGpuSpecifications: cdk.listMapper(cfnLaunchTemplateElasticGpuSpecificationPropertyToCloudFormation)(properties.elasticGpuSpecifications),\n ElasticInferenceAccelerators: cdk.listMapper(cfnLaunchTemplateLaunchTemplateElasticInferenceAcceleratorPropertyToCloudFormation)(properties.elasticInferenceAccelerators),\n HibernationOptions: cfnLaunchTemplateHibernationOptionsPropertyToCloudFormation(properties.hibernationOptions),\n IamInstanceProfile: cfnLaunchTemplateIamInstanceProfilePropertyToCloudFormation(properties.iamInstanceProfile),\n ImageId: cdk.stringToCloudFormation(properties.imageId),\n InstanceInitiatedShutdownBehavior: cdk.stringToCloudFormation(properties.instanceInitiatedShutdownBehavior),\n InstanceMarketOptions: cfnLaunchTemplateInstanceMarketOptionsPropertyToCloudFormation(properties.instanceMarketOptions),\n InstanceType: cdk.stringToCloudFormation(properties.instanceType),\n KernelId: cdk.stringToCloudFormation(properties.kernelId),\n KeyName: cdk.stringToCloudFormation(properties.keyName),\n LicenseSpecifications: cdk.listMapper(cfnLaunchTemplateLicenseSpecificationPropertyToCloudFormation)(properties.licenseSpecifications),\n Monitoring: cfnLaunchTemplateMonitoringPropertyToCloudFormation(properties.monitoring),\n NetworkInterfaces: cdk.listMapper(cfnLaunchTemplateNetworkInterfacePropertyToCloudFormation)(properties.networkInterfaces),\n Placement: cfnLaunchTemplatePlacementPropertyToCloudFormation(properties.placement),\n RamDiskId: cdk.stringToCloudFormation(properties.ramDiskId),\n SecurityGroupIds: cdk.listMapper(cdk.stringToCloudFormation)(properties.securityGroupIds),\n SecurityGroups: cdk.listMapper(cdk.stringToCloudFormation)(properties.securityGroups),\n TagSpecifications: cdk.listMapper(cfnLaunchTemplateTagSpecificationPropertyToCloudFormation)(properties.tagSpecifications),\n UserData: cdk.stringToCloudFormation(properties.userData),\n };\n}",
"function Template(payload) {\n this._preparedPayload = Template.prepare(payload);\n }",
"function launchTemplateResourceLaunchTemplateDataPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n LaunchTemplateResource_LaunchTemplateDataPropertyValidator(properties).assertSuccess();\n return {\n BlockDeviceMappings: cdk.listMapper(launchTemplateResourceBlockDeviceMappingPropertyToCloudFormation)(properties.blockDeviceMappings),\n CreditSpecification: launchTemplateResourceCreditSpecificationPropertyToCloudFormation(properties.creditSpecification),\n DisableApiTermination: cdk.booleanToCloudFormation(properties.disableApiTermination),\n EbsOptimized: cdk.booleanToCloudFormation(properties.ebsOptimized),\n ElasticGpuSpecifications: cdk.listMapper(launchTemplateResourceElasticGpuSpecificationPropertyToCloudFormation)(properties.elasticGpuSpecifications),\n IamInstanceProfile: launchTemplateResourceIamInstanceProfilePropertyToCloudFormation(properties.iamInstanceProfile),\n ImageId: cdk.stringToCloudFormation(properties.imageId),\n InstanceInitiatedShutdownBehavior: cdk.stringToCloudFormation(properties.instanceInitiatedShutdownBehavior),\n InstanceMarketOptions: launchTemplateResourceInstanceMarketOptionsPropertyToCloudFormation(properties.instanceMarketOptions),\n InstanceType: cdk.stringToCloudFormation(properties.instanceType),\n KernelId: cdk.stringToCloudFormation(properties.kernelId),\n KeyName: cdk.stringToCloudFormation(properties.keyName),\n Monitoring: launchTemplateResourceMonitoringPropertyToCloudFormation(properties.monitoring),\n NetworkInterfaces: cdk.listMapper(launchTemplateResourceNetworkInterfacePropertyToCloudFormation)(properties.networkInterfaces),\n Placement: launchTemplateResourcePlacementPropertyToCloudFormation(properties.placement),\n RamDiskId: cdk.stringToCloudFormation(properties.ramDiskId),\n SecurityGroupIds: cdk.listMapper(cdk.stringToCloudFormation)(properties.securityGroupIds),\n SecurityGroups: cdk.listMapper(cdk.stringToCloudFormation)(properties.securityGroups),\n TagSpecifications: cdk.listMapper(launchTemplateResourceTagSpecificationPropertyToCloudFormation)(properties.tagSpecifications),\n UserData: cdk.stringToCloudFormation(properties.userData),\n };\n }",
"function eC2FleetResourceFleetLaunchTemplateSpecificationRequestPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n EC2FleetResource_FleetLaunchTemplateSpecificationRequestPropertyValidator(properties).assertSuccess();\n return {\n LaunchTemplateId: cdk.stringToCloudFormation(properties.launchTemplateId),\n LaunchTemplateName: cdk.stringToCloudFormation(properties.launchTemplateName),\n Version: cdk.stringToCloudFormation(properties.version),\n };\n }",
"function TemplateInfo() {\n\tthis.code = '';\n\tthis.type = '';\n\tthis.parent = '';\n\tthis.description = '';\n}",
"function LaunchTemplateVersion() {\n _classCallCheck(this, LaunchTemplateVersion);\n\n LaunchTemplateVersion.initialize(this);\n }",
"function createTemplate() {\n var newTemplate = new Object();\n for(var k in TemplatePreset) newTemplate[k]=TemplatePreset[k];\n return newTemplate;\n }",
"function generateLaunchConfig () {\n launchConfig.dataset_uuid = $window.dataSetUuid;\n launchConfig.tool_definition_uuid = toolService.selectedTool.uuid;\n launchConfig.file_relationships = generateFileStr();\n launchConfig.parameters = paramsService.paramsForm;\n if (paramsService.toolEditForm.display_name) {\n launchConfig.display_name = paramsService.toolEditForm.display_name;\n }\n }",
"function LaunchTemplateSpotMarketOptionsRequest() {\n _classCallCheck(this, LaunchTemplateSpotMarketOptionsRequest);\n\n LaunchTemplateSpotMarketOptionsRequest.initialize(this);\n }",
"templateData() {\n return {\n title: this.localTitle,\n content: this.localContent,\n interactive: !this.noninteractive,\n // Pass these props as is\n ...pick(this.$props, [\n 'boundary',\n 'boundaryPadding',\n 'container',\n 'customClass',\n 'delay',\n 'fallbackPlacement',\n 'id',\n 'noFade',\n 'offset',\n 'placement',\n 'target',\n 'target',\n 'triggers',\n 'variant',\n MODEL_PROP_NAME_ENABLED\n ])\n }\n }",
"function EmailTemplate( template, data ) {\n this.temp = openEmailTemplate( template );\n this.data = data;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
calls a method on a random peer, and retries on another peer if it times out | _request (method, ...args) {
let cb = args.pop()
while (!cb) cb = args.pop()
let peer = this.randomPeer()
args.push((err, res) => {
if (this.closed) return
if (err && err.timeout) {
// if request times out, disconnect peer and retry with another random peer
logdebug(`peer request "${method}" timed out, disconnecting`)
peer.disconnect(err)
this.emit('requestError', err)
return this._request(...arguments)
}
cb(err, res, peer)
})
peer[method](...args)
} | [
"_request (method, ...args) {\n let cb = args.pop()\n while (!cb) cb = args.pop()\n let peer = this.randomPeer()\n args.push((err, res) => {\n if (this.closed) return\n if (err && err.timeout) {\n // if request times out, disconnect peer and retry with another random peer\n debug(`peer request \"${method}\" timed out, disconnecting`)\n peer.disconnect(err)\n this.emit('requestError', err)\n return this._request(...arguments)\n }\n cb(err, res, peer)\n })\n peer[method](...args)\n }",
"_request (method, ...args) {\n var cb = args.pop()\n var peer = this.randomPeer()\n args.push((err, res) => {\n if (this.closed) return\n if (err && err.timeout) {\n // if request times out, disconnect peer and retry with another random peer\n debug(`peer request \"${method}\" timed out, disconnecting`)\n peer.disconnect(err)\n this.emit('requestError', err)\n return this._request(...arguments)\n }\n cb(err, res, peer)\n })\n peer[method](...args)\n }",
"async fail (sleepSeconds, additionalMsg) { // note: parent classe's fail is not async\n // Continue trying for polling client, don't cause crashes\n if (this.reqArgs.proxyClient && this.reqArgs.proxyClient.isPollingClient) {\n if (this.numTriesSoFar > 3) {\n this.reqArgs.proxyClient.circuit.degradeHealth();\n this.numTriesSoFar = 4;\n\n await new Promise((resolve, reject) => setTimeout(resolve, 1000)); // enforce 1 second wait to slow down\n }\n }\n\n // Check for the errors that occur randomly but aren't a big issue\n const randomErrors = [\n 'Error: socket hang up',\n 'Error: SOCKS connection failed. Host unreachable.',\n 'Error: SOCKS connection failed. Connection not allowed by ruleset',\n 'SSL routines:SSL23_GET_SERVER_HELLO',\n 'SSL routines:SSL3_GET_RECORD:wrong version number:',\n 'Error: SOCKS connection failed. General SOCKS server failure.',\n // 'Error: read ECONNRESET', (also happens but only deserves 10 second wait)\n ];\n\n const shadyErrors = [\n 'Error: unable to verify the first certificate',\n 'Error: self signed certificate',\n 'Error: self signed certificate in certificate chain',\n \"Error [ERR_TLS_CERT_ALTNAME_INVALID]: Hostname/IP does not match certificate's altnames\",\n 'SSL routines:SSL3_GET_RECORD:decryption failed or bad record mac',\n 'Error: unable to get local issuer certificate',\n ];\n\n let valueToSearchErroMessage = this.data; // was additionalMsg, COULD be unreliable...?\n let randomErrorsFound = randomErrors.filter(e => valueToSearchErroMessage.indexOf(e) != -1);\n let shadyErrorsFound = shadyErrors.filter(e => valueToSearchErroMessage.indexOf(e) != -1);\n\n // Check for some known annoying errors and possibly change circuit if under tor\n if (randomErrorsFound.length) {\n sleepSeconds = 60; // wait a full minute\n\n // Switch circuit if SOCKS CONNECTION FAILED is suffering hard\n if (this.numTriesSoFar > 5) {\n sleepSeconds = 180; // 3 minutes\n\n // Irritating today. Change circuit to stop this junk\n //if (randomErrorsFound[0].indexOf('Error: SOCKS connection failed. Host unreachable.') != -1) {\n // change circuit if possible\n if (this.reqArgs.proxyClient) {\n this.reqArgs.proxyClient.forceIPChangeImmediately().then();\n }\n //}\n } else {\n // If less than 5 tries... ensure only 0.1 try added for this connection and HURRY UP to try again\n if (randomErrorsFound[0] == 'Error: SOCKS connection failed. Host unreachable.') {\n sleepSeconds = 0.5;\n this.numTriesSoFar -= 0.9;\n\n // change circuit as well\n if (this.reqArgs.proxyClient) {\n this.reqArgs.proxyClient.forceIPChangeImmediately().then();\n }\n }\n }\n } else if (shadyErrorsFound.length) {\n INFO(`[D] ${this.constructor.name}.fail - Shady error encountered: ${shadyErrorsFound[0]}`);\n if (this.reqArgs.proxyClient) {\n this.reqArgs.proxyClient.forceIPChangeImmediately().then(); // try to switch circuits if available\n }\n }\n\n // Check for Tor's weird issue where it stops working after like 5000 requests or a few days... weird\n let isTorCircuit = this.reqArgs.proxyClient && this.reqArgs.proxyClient.circuit.isLocalTor;\n if (valueToSearchErroMessage.indexOf('Error: SOCKS connection failed. TTL expired.') != -1 && this.numTriesSoFar > 3 && isTorCircuit) {\n //if (this.numTriesSoFar > 7) {\n // This is a menace, we've already tried changing exit nodes. We have to restart tor.\n return this.reqArgs.proxyClient.manager.forceRestartTorImmediately().then(() => {\n return super.fail(sleepSeconds, `[!] TTL Expired error getting out of hand. Restarting tor`);\n });\n //}\n\n //return this.reqArgs.proxyClient.manager.forceRestartTorImmediately().then(() => {\n //return super.fail(sleepSeconds, `[!] Got TTL Expired error from IP:${exitIP} SO WE CHANGED IP.`);\n //});\n } else {\n return super.fail(sleepSeconds, additionalMsg);\n }\n }",
"retry() {}",
"_connectPeer (cb) {\n cb = cb || this._onConnection.bind(this)\n if (this.closed) return\n if (this.peers.length >= this._numPeers) return\n let getPeerArray = []\n if (!process.browser) {\n if (this._params.dnsSeeds && this._params.dnsSeeds.length > 0) {\n getPeerArray.push(this._connectDNSPeer.bind(this))\n }\n if (this._params.staticPeers && this._params.staticPeers.length > 0) {\n getPeerArray.push(this._connectStaticPeer.bind(this))\n }\n }\n if (this._connectWeb && this._exchange.peers.length > 0) {\n getPeerArray.push(this._exchange.getNewPeer.bind(this._exchange))\n }\n if (this._params.getNewPeer) {\n getPeerArray.push(this._params.getNewPeer.bind(this._params))\n }\n if (getPeerArray.length === 0) {\n this.connecting = false\n if (this.connectTimeout) {\n setTimeout(() => {\n this.connecting = true\n setImmediate(this.connect.bind(this))\n }, this.connectTimeout)\n }\n return this._onConnection(\n Error('No methods available to get new peers'))\n }\n let getPeer = utils.getRandom(getPeerArray)\n debug(`_connectPeer: getPeer = ${getPeer.name}`)\n getPeer(cb)\n }",
"function retry()\r\n{\r\n\tif(pusher == null)\r\n\t{\r\n\t\treturn;\r\n\t}\t\r\n\t\r\n\tvar connect = pusher.isConnect();\r\n\tif(connect)\r\n\t{\r\n\t\treturn;\r\n\t}\t\t\t\r\n\telse\r\n\t{\r\n\t\tprint_msg('push connect failed!');\r\n\t\tpusher.disconnect();\r\n\t\tprint_msg('push connect retry!');\r\n\t\tpusher.login();\r\n\t\tretry_count += 1;\r\n\t\t\r\n\t\tif(retry_count < retry_max)\r\n\t\t{\r\n\t\t\tsetTimeout(retry,1000*15);\r\n\t\t}\t\r\n\t\telse\r\n\t\t{\r\n\t\t\tretry_count = 0;\r\n\t\t}\t\r\n\t}\r\n}",
"sendRequestWithCallbackAndRetry(request, data = {}, callback, initialDelay = 1000, delayFalloff = 1.3) {\n let callbackWrapper = (res) => {\n if(!res.err) {\n callback(res);\n } else if(res.err === \"Socket Not Connected\") {\n setTimeout((() => {\n initialDelay = initialDelay * delayFalloff;\n this.sendRequestWithCallback2(request, data, callbackWrapper);\n }), initialDelay); \n } else if(res.err === \"Peer not found\") {\n callback(res); // Server could not find peer, \n } else {\n console.log(\"ERROR 12511: Unknown Error from socket...\")\n }\n }\n this.sendRequestWithCallback2(request, data, callbackWrapper);\n }",
"function call() {\n callBtn.disabled = true;\n hangupBtn.disabled = false;\n\n var servers = null;\n\n // Create the peer connections. Peer1 will be \"us\" and Peer2 will be the mocked peer.\n peer1 = new RTCPeerConnection(servers);\n peer2 = new RTCPeerConnection(servers);\n\n // Add a handler for when there are new ICE candidates\n peer1.onicecandidate = function (e) {\n addCandidate(peer2, e);\n };\n\n peer2.onicecandidate = function (e) {\n addCandidate(peer1, e);\n };\n\n // Add a callback for when we get the remote stream for the 2nd peer so we can see their video\n peer2.onaddstream = function (e) {\n remoteVid.srcObject = e.stream;\n };\n\n // Add our local stream to peer1\n peer1.addStream(localStream);\n\n // Create an offer to connect\n peer1.createOffer(offerConstraints)\n .then(function (desc) {\n // The APIs for setting descriptions are promise-based.\n // For brevity, we aren't adding callbacks.\n peer1.setLocalDescription(desc);\n peer2.setRemoteDescription(desc);\n peer2.createAnswer()\n .then(createAnswerSuccess);\n });\n}",
"_reconnect () {\n if (this._reconnecting === true) return\n this._reconnecting = true\n\n log('Trying to reconnect to remote endpoint')\n this._checkInternet((online) => {\n if (!online && !cst.PM2_DEBUG) {\n log('Internet down, retry in 2 seconds ..')\n this._reconnecting = false\n return setTimeout(this._reconnect.bind(this), process.env.NODE_ENV === 'test' ? 1 : 2000)\n }\n this.connect((err) => {\n if (err || !this.isConnected()) {\n log('Endpoint down, retry in 5 seconds ...')\n this._reconnecting = false\n return setTimeout(this._reconnect.bind(this), process.env.NODE_ENV === 'test' ? 1 : 5000)\n }\n\n log('Connection etablished with remote endpoint')\n this._reconnecting = false\n this._emptyQueue()\n })\n })\n }",
"async _retryConnect() {\n // eslint-disable-next-line\n while (true) {\n try {\n await wait(this._retryTimeoutMs);\n await this._attemptConnect();\n return;\n } catch (ex) {\n this.emit(\"error\", ex);\n }\n }\n }",
"pingParent() {\n const self = this;\n self.retries = 0;\n function error() {\n if (self.retries > 2) {\n self.kill();\n process.exit(1);\n }\n self.retries++;\n }\n setInterval(() => {\n try {\n let result = self.send({action: 'ping'});\n if (!result) {\n return error();\n }\n self.retries = 0;\n } catch (e) {\n error();\n }\n }, 500);\n }",
"_dialPeer (peer, callback) {\n // Attempt Paratii 0.0.1\n this.libp2p.dialProtocol(peer, PARATII001, (err, conn) => {\n if (err) {\n // Attempt Paratii 0.0.1\n this.libp2p.dialProtocol(peer, PARATII001, (err, conn) => {\n if (err) { return callback(err) }\n\n callback(null, conn, PARATII001)\n })\n\n return\n }\n\n callback(null, conn, PARATII001)\n })\n }",
"function testRetries(retries) {\n return function (done) {\n var randomSelector = require('../../src/lib/selectors/random');\n var connections;\n var attempts = 0;\n function failRequest(params, cb) {\n attempts++;\n process.nextTick(function () {\n cb(new Error('Unable to do that thing you wanted'));\n });\n }\n\n var trans = new Transport({\n hosts: _.map(new Array(retries + 1), function (val, i) {\n return 'localhost/' + i;\n }),\n maxRetries: retries,\n selector: function (_conns) {\n connections = _conns;\n return randomSelector(_conns);\n }\n });\n\n // trigger a select so that we can harvest the connection list\n trans.connectionPool.select(_.noop);\n _.each(connections, function (conn) {\n stub(conn, 'request', failRequest);\n });\n\n trans.request({}, function (err, resp, body) {\n attempts.should.eql(retries + 1);\n err.should.be.an.instanceOf(errors.ConnectionFault);\n should.not.exist(resp);\n should.not.exist(body);\n done();\n });\n };\n }",
"function testRetries(retries) {\n return function(done) {\n var randomSelector = require('../../../src/lib/selectors/random');\n var connections;\n var attempts = 0;\n function failRequest(params, cb) {\n attempts++;\n process.nextTick(function() {\n cb(new Error('Unable to do that thing you wanted'));\n });\n }\n\n var trans = new Transport({\n hosts: _.map(new Array(retries + 1), function(val, i) {\n return 'localhost/' + i;\n }),\n maxRetries: retries,\n selector: function(_conns) {\n connections = _conns;\n return randomSelector(_conns);\n },\n });\n\n // trigger a select so that we can harvest the connection list\n trans.connectionPool.select(_.noop);\n _.each(connections, function(conn) {\n stub(conn, 'request', failRequest);\n });\n\n trans.request({}, function(err, resp, body) {\n expect(attempts).to.eql(retries + 1);\n expect(err).to.be.a(errors.ConnectionFault);\n expect(resp).to.be(undefined);\n expect(body).to.be(undefined);\n trans.close();\n done();\n });\n };\n }",
"_dialPeer (peer, callback) {\n // Attempt Bitswap 1.1.0\n this.libp2p.dial(peer, BITSWAP110, (err, conn) => {\n if (err) {\n // Attempt Bitswap 1.0.0\n this.libp2p.dial(peer, BITSWAP100, (err, conn) => {\n if (err) { return callback(err) }\n\n callback(null, conn, BITSWAP100)\n })\n\n return\n }\n\n callback(null, conn, BITSWAP110)\n })\n }",
"_tryToCreatePeer (cbFn = _.noop) {\n const pcCreated = (this.pc) ? this.pc.iceConnectionState !== 'closed' : false\n if (!pcCreated) {\n return this._createPeerConnection(cbFn)\n }\n\n return cbFn && cbFn()\n }",
"function retryConnection() {\r\n setTimeout(reconnect.bind(this), this.retryDelay);\r\n }",
"_dialPeer (peer, callback) {\n // Attempt Bitswap 1.1.0\n this.libp2p.dialProtocol(peer, BITSWAP110, (err, conn) => {\n if (err) {\n // Attempt Bitswap 1.0.0\n this.libp2p.dialProtocol(peer, BITSWAP100, (err, conn) => {\n if (err) { return callback(err) }\n\n callback(null, conn, BITSWAP100)\n })\n\n return\n }\n\n callback(null, conn, BITSWAP110)\n })\n }",
"_gossip()\n\t{\n\t\t//\t...\n\t\tlet arrLivePeerUrls\t= this.m_oScuttle.getLivePeerUrls();\n\t\tlet arrDeadPeerUrls\t= this.m_oScuttle.getDeadPeerUrls();\n\t\tlet sLivePeerUrl\t= null;\n\t\tlet sDeadPeerUrl\t= null;\n\n\t\t//\n\t\t//\tFind a live peer to gossip to\n\t\t//\n\t\tif ( arrLivePeerUrls.length > 0 )\n\t\t{\n\t\t\tsLivePeerUrl\t= this._chooseRandom( arrLivePeerUrls );\n\t\t\tthis._gossipToPeer( sLivePeerUrl );\n\t\t}\n\n\t\t//\n\t\t//\tpossibly gossip to a dead peer\n\t\t//\n\t\tlet fProb = arrDeadPeerUrls.length / ( arrLivePeerUrls.length + 1 );\n\t\tif ( fProb > Math.random() )\n\t\t{\n\t\t\tsDeadPeerUrl\t= this._chooseRandom( arrDeadPeerUrls );\n\t\t\tthis._gossipToPeer( sDeadPeerUrl );\n\t\t}\n\n\t\t//\n\t\t//\tGossip to seed under certain conditions\n\t\t//\n\t\tif ( sLivePeerUrl && ! this.m_oSeeds[ sLivePeerUrl ] &&\n\t\t\tarrLivePeerUrls.length < this.m_oSeeds.length )\n\t\t{\n\t\t\tif ( Math.random() < ( this.m_oSeeds.length / this.m_oScuttle.getAllPeerUrls().length ) )\n\t\t\t{\n\t\t\t\tlet arrCertainPeerUrl\t= this._chooseRandom( Object.keys( this.m_oScuttle.m_oPeers ) );\n\t\t\t\tthis._gossipToPeer( arrCertainPeerUrl );\n\t\t\t}\n\t\t}\n\n\t\t//\n\t\t//\tCheck health of m_oScuttle.m_oPeers\n\t\t//\n\t\tfor ( let sPeerUrl in this.m_oScuttle.m_oPeers )\n\t\t{\n\t\t\tif ( sPeerUrl === this.m_oScuttle.m_sLocalUrl )\n\t\t\t{\n\t\t\t\t//\tignore checking for local peer\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t//_log.info( 'gossiper', 'will checkIfSuspect for peer %s', sPeerUrl );\n\t\t\tlet oPeer = this.m_oScuttle.m_oPeers[ sPeerUrl ];\n\t\t\tif ( oPeer )\n\t\t\t{\n\t\t\t\toPeer.checkIfSuspect();\n\t\t\t}\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
opens infoview window at the marker mentioned in Location object 'loc' uses the global variable 'infoWindow' | function openInfoView(loc) {
infoWindow.close(); //closes currently displayed infoView (if it is there).
//center the map at the marker for which infoView is displayed.
map.setCenter(new google.maps.LatLng(loc.lat, loc.lon));
var htmlStrings = [];
htmlStrings[0] = '<div>' + '<strong>' + loc.name + '</strong>' + '</div>';
htmlStrings[1] = '<p>' + loc.category + '</p>';
htmlStrings[2] = '<p>' + loc.address + '</p>';
htmlStrings[3] = '<p>' + 'Phone No. ' + loc.phone + '</p>';
var html = htmlStrings.join('');
infoWindow.setContent(html);//'html' has the infoView content
//sets the BOUNCE animation on marker
loc.marker.setAnimation(google.maps.Animation.BOUNCE);
//switch off the animation after 1second.
setTimeout(function() { loc.marker.setAnimation(null);},1000);
infoWindow.open(map, loc.marker);
} | [
"OpenInfoWindow(infoWindow, map, marker) {\n infoWindow.open(map, marker);\n }",
"openInfoWindow(location) {\n this.closeInfoWindow();\n this.state.infowindow.open(this.state.map, location.marker);\n this.state.infowindow.setContent(\"Looking Up . . . \");\n this.getWindowData(location);\n }",
"function showInfoWindow(marker)\n {\n google.maps.event.trigger(markers[marker], 'click');\n }",
"function set_info_window (info,marker,auto_open) {\n // pulls an element's html content\n if (info.charAt(0) == '#') {\n id = info.split('#')[1];\n info = document.getElementById(id).innerHTML;\n }\n \n var infowindow = new google.maps.InfoWindow({\n content: info\n });\n \n if (auto_open) {\n infowindow.open(marker.map, marker);\n }else{\n google.maps.event.addListener(marker, 'click', function() {\n infowindow.open(marker.map, marker);\n });\n };\n\n}",
"function openInfoWindow(brand_location_id){\n google.maps.event.trigger(markers[brand_location_id], 'click');\n}",
"function infoWindowAction() {\n infoWindow.open(map, locationObj.marker);\n\n //close infoWindow\n infoWindow.addListener('closeClick', function() {\n infoWindow.setContent(null);\n });\n\n // Animate marker.\n if(locationObj.marker.getAnimation() !== null) {\n locationObj.marker.setAnimation(null);\n } else {\n locationObj.marker.setAnimation(google.maps.Animation.BOUNCE);\n locationObj.marker.setIcon(visitedMarker);\n setTimeout(function() {\n locationObj.marker.setAnimation(null);\n }, 1400);\n }\n }",
"function openInfoWindow() {\n infoWindow.setContent(this.title);\n infoWindow.open(map, this);\n }",
"function showInfoWindow($markerModel){\n $scope.infoWindow.show = true;\n $scope.infoWindow.coords.latitude = $markerModel.latitude;\n $scope.infoWindow.coords.longitude = $markerModel.longitude;\n $scope.infoWindow.workout = $markerModel.workout;\n $scope.$apply();\n }",
"function createNewInfoWindow(coord, content){\n // information window is displayed at click position\n\tmapCollector.infowindow = new google.maps.InfoWindow({\n\t \tcontent: content,\n\t \tposition: coord\n\t});\n }",
"function openMarker() {\n if (openInfoWindow !== 0) {\n openInfoWindow.close();\n }\n infowindow.open(map, marker);\n openInfoWindow = infowindow;\n }",
"function ShowInfo(id){\n var desc=dataModel.locations[id].view.getDescription(id);\n // open new info window\n if(desc){\n // close infoo window if already open\n CloseInfo();\n infoWindow=new google.maps.InfoWindow({\n content: desc\n });\n infoWindow.open(mapElement, GetMarker(id));\n }\n}",
"function attachInfoWindow(marker, windowContents) {\n\tmarker.infoWindow = new google.maps.InfoWindow({\n\t\tcontent: windowContents\n\t});\n\tmarker.addListener('click', function() { \n\t\tdisplayInfoWindow(marker); \n\t});\n}",
"function showInfoWindow(marker) {\n map.setCenter(marker.getPosition());\n populateInfoWindow(marker, infoWindow);\n }",
"function createNewInfoWindow() {\n appVM.locationArray().forEach(function (locationItem) {\n // Create a new info window object for each marker object\n locationItem.marker.infowindow = new google.maps.InfoWindow({\n content: infoWindowContentString\n });\n });\n}",
"function showInfoWindow (){\n var marker = this;\n places.getDetails({placeId: marker.placeResult.place_id},\n function(place, status) {\n if (status !== google.maps.places.PlacesServiceStatus.OK) {\n return;\n }\n infoWindow.open(map, marker);\n buildIWContent(place);\n });\n}",
"function setMarkerInfo(info) {\n infoWindow.setContent(info);\n }",
"function showIdMarker(marker, locations) { \t\n\t\tvar latlgn = new google.maps.LatLng(locations[1], locations[2]);\n\t\tvar ifw = new google.maps.InfoWindow();\n\t\tifw = new google.maps.InfoWindow({\n\t\t\t content: (locations[4]).toString(),\n\t\t\t closeBoxURL: \"\",\n\t\t\t maxWidth: 160\n\t\t });\n\t\tifw.open(map, marker);\n }",
"function oneInfoWindowOnly(map, marker, infoWindow) {\n if (currentInfoWindow) currentInfoWindow.close();\n currentInfoWindow = infoWindow;\n infoWindow.open(map, marker);\n }",
"function createFTInfoWindow(map, marker, date, location, title, url) {\r\n var insertUrl = null;\r\n if (url != '') {\r\n insertUrl = \"<a href='\" + url + \"'>check it out</a>\";\r\n }\r\n else {\r\n insertUrl = \"\";\r\n }\r\n\r\n var contentString = '<div id=\"InfoWindow\" style=\"color:black;font-size:80%;\">' +\r\n '<div id=\"InfoWindowCaption\" style=\"font-weight:bold\">' +\r\n '<nobr>' + title + '</nobr></div>' +\r\n '<div id=\"InfoWindowContent\">' +\r\n '<nobr>' + location + '</nobr>' +\r\n '<br /><nobr>' + date + '</nobr>' +\r\n '<br /><nobr>' + insertUrl + '</nobr></div>' +\r\n '</div>';\r\n\r\n var infowindow = new google.maps.InfoWindow({\r\n content: contentString\r\n });\r\n\r\n\tgoogle.maps.event.addListener(infowindow, 'domready', function() {\r\n\t\tdocument.getElementById('InfoWindow').parentNode.style.overflow='';\r\n\t\tdocument.getElementById('InfoWindow').parentNode.parentNode.style.overflow='';\r\n });\r\n\r\n google.maps.event.addListener(marker, 'click', function() {\r\n \t\t//close previosly opened window if opened at all\r\n\t\tif(curr_infw) { curr_infw.close();} \r\n\t\t// save info about opened window \r\n\t\tcurr_infw = infowindow;\t\r\n infowindow.open(map, marker);\r\n });\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Entering animation for quotepanel | function fadeInQuotePane() {
$('#quote-panel').animateCSS('fadeInLeft', {
delay: 200
});
} | [
"_startAnimation() {\n // @breaking-change 8.0.0 Combine with _resetAnimation.\n this._panelAnimationState = 'enter';\n }",
"function animateIt() {\n \t\tsquare\n\t \t\t.show( \"slow\" )\n\t \t\t.addClass('box-spin box-animate')\n\t\t .animate({ left: \"+=200\" }, 500 )\n\t\t .css( \"background-color\", \"orange\")\n\t\t .toggle(\"explode\", {pieces: 16 }, 1000)\n\t// Don't forget to return our box to the original position, ready to go again.\n\t\t .animate({ left: \"-=200\" }, 100 )\n\n\n}",
"function animateIn() {\n\n chartRing.selectAll('.chart-ring')\n .style('opacity', 0)\n .transition()\n .duration(DURATION)\n .delay(function (d, i) {\n return (DELAY + (i * 100));\n })\n .style('opacity', 1);\n }",
"function animatePanelExpansion() {\n $(\"#ad-hoc-panel\").animate({\n \"width\": geometry.getPanelWidth() + 'px',\n \"height\": geometry.getPanelHeight() + 'px'\n }, parameters.panelSizeChangeDuration, onPanelExpanded)\n }",
"function animate() { }",
"function anim() {\n context.clearRect(170, 190, 150, 500);\n wtank1.draw(+slider1.value - 2);\n wtank2.draw(+slider2.value - 2);\n isanim = false;\n}",
"function slideInAnimation() {\n $('.make-account-box, .make-account-text').css({'transform': 'translateX(0%)'})\n }",
"function animateQuote1() {\n $('#ep-quote-1 .text-box').toggle( \"slide\", {\"direction\": \"left\", 'easing': 'easeInOutBack', 'duration': 1000});\n $('#ep-quote-1 .hot-air-balloon').toggle({\"direction\": \"down\"});\n mattsEP.hotAirBalloonDrift2();\n mattsEP.animatitonOn['quote1'] = true;\n }",
"function flingpiece_animate(flingPiece){\n\tflingpiece_activate(flingPiece);\n}",
"animateIn() {\n if (this.skipAnimations_) {\n return;\n }\n this.getRunners_().forEach((runner) => runner.start());\n }",
"animate() {\n\t\tconst step = this.runningTeleportation.steps[this.runningTeleportation.stepIndex];\n\t\tObject.assign(this.wrapper.style, step.webAnimation.stepStyles[1]);\n\t\tthis.runningTeleportation.player = this.wrapper.animate(step.webAnimation.stepStyles, {\n\t\t\tduration: step.webAnimation.animation.duration,\n\t\t\tdelay: step.webAnimation.animation.delay,\n\t\t\teasing: step.webAnimation.animation.easing\n\t\t});\n\t\tthis.runningTeleportation.player.addEventListener(\n\t\t\t'finish', this.onAnimateEnd.bind(this), false\n\t\t);\n\t}",
"pauseAnimation() {\n\t\tthis.Grid.pause();\n\t}",
"animateIn () {\n this.chartRing.selectAll('.chart-ring')\n .style('opacity', 0)\n .transition()\n .duration(DURATION)\n .delay((d, i) => {\n return i * 100\n })\n .style('opacity', 1)\n }",
"animateFireShard()\n {\n this.player.animations.play('fire_shard');\n }",
"animate(){\n this.x += this.delta(3.1416*2.0,10);\n }",
"function moveShark1(){\n // console.log('we movin')\n $shark1.animate({\n left: 800\n },{\n duration: 4000,\n step: handleSharkMove,\n done: $shark1.animate({\n left: Math.floor(Math.random() * 6) + 1\n },{\n duration: 2500,\n step: handleSharkMove,\n complete: moveShark1\n })\n })\n }",
"function animations() {\n\tarthur.srcX = arthur.currentFrame * arthur.width;\n\tif (arthur.goRight) {\n\t\tarthur.srcY = arthur.goRowRight * arthur.height;\n\t} else if (arthur.goLeft) {\n\t\tarthur.srcY = arthur.goRowLeft * arthur.height;\n\t} else if (arthur.duckRight) {\n\t\tarthur.srcY = arthur.duckRowRight * arthur.height;\n\t} else if (arthur.atkRight) {\n\t\tarthur.srcY = arthur.atkRowRight * arthur.height;\n\t} else if (arthur.jumpRight) {\n\t\tarthur.srcY = arthur.jumpRowRight * arthur.height;\n\t} else if (arthur.die) {\n\t\tarthur.srcY = arthur.dieRowRight * arthur.height;\n\t}\n}",
"function expand() {\n\t\tif(!sidePanelExpanded) {\n\t\t\tvar timer = setInterval(shift,1.4);\n\t\t\tvar t = 0;\n\t\t\tvar step = ballX * (1- (windowWidth-248)/(windowWidth-50));\n\t\t\tsidePanelExpanded = true; \n\t\t\tfunction shift() {\n\t\t\t\tif(t < 100) {\n\t\t\t\t\t$(\"#shadow\").css(\"right\", 10 + 2 * t + 'px');\n\t\t\t\t\t$(\"#sidePanel\").css(\"width\", 30 + 2 * t + 'px');\n\t\t\t\t\tif($(canvas).css(\"visibility\") == 'visible') {\n\t\t\t\t\t\twidth = canvas.width = (windowWidth-50) - 2 * t;\n\t\t\t\t\t\tballX-= step/100;\n\t\t\t\t\t\tholeX-= step/100;\n\n\t\t\t\t\t\tif(instruction1Displayed) {\n\t\t\t\t\t\t\t$(\"#instruction_1\").css(\"left\",width/2 - 50 - (step/100) + \"px\");\n\t\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\t\t$(\"#overlay\").css(\"left\",holeX+ \"px\");\n\t\t\t\t\t\tresetCanvas();\n\t\t\t\t\t}\n\t\t\t\t\tt++;\n\t\t\t\t} else {\n\t\t\t\t\tclearInterval(timer); \n\t\t\t\t}\n\t\t\t} \n\t\t}\n\t}",
"function transition() {\n $carousel.css({ left: ( positions[currentPosition] * -1 ) });\n // Wraparound logic\n // Should refresh staging area\n var wraparound = false;\n console.log(currentPosition);\n if (currentPosition == 1) {\n currentPostion += numItems;\n wraparound = true;\n } else if (currentPosition == positions.length - 3) {\n currentPosition -= numItems;\n wraparound = true;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the graph in which the nodeNumber is present for an error node | function getGraphForErrorNode(nodeNumber) {
return errorGraphMap.findIndex((graph) =>
graph.nodes().includes(`${nodeNumber}`)
);
} | [
"function getGraphForErrorNode(nodeNumber) {\n\t\t\t\treturn errorGraphMap.findIndex(function (graph) {\n\t\t\t\t\treturn graph.nodes().includes(\"\" + nodeNumber);\n\t\t\t\t})\n\t\t\t}",
"function getGraphForNode(nodeNumber) {\n return graphMap.findIndex((graph) =>\n graph.nodes().includes(`${nodeNumber}`)\n );\n }",
"function getGraphForNode(nodeNumber) {\n\t\t\t\treturn graphMap.findIndex(function (graph) {\n\t\t\t\t\treturn graph.nodes().includes(\"\" + nodeNumber);\n\t\t\t\t})\n\t\t\t}",
"function getGraphForNode(nodeNumber) {\n\t\t\treturn graphMap.findIndex(function (graph) {\n\t\t\t\treturn graph.nodes().includes(\"\" + nodeNumber);\n\t\t\t})\n\t\t}",
"function prepareErrorGraph() {\n const errorNodes = [];\n const errorEdges = [];\n nodes.forEach((n) => {\n if (errorPath.includes(n.index)) {\n errorNodes.push(n);\n }\n });\n edges.forEach((e) => {\n if (errorPath.includes(e.source) && errorPath.includes(e.target)) {\n errorEdges.push(e);\n }\n });\n if (errorNodes.length > graphSplitThreshold) {\n buildMultipleErrorGraphs(errorNodes, errorEdges);\n } else {\n const g = createGraph();\n setGraphNodes(g, errorNodes);\n setGraphEdges(g, errorEdges, false);\n errorGraphMap.push(g);\n }\n }",
"function prepareErrorGraph() {\n\t\t\t\tvar errorNodes = [],\n\t\t\t\t\terrorEdges = [];\n\t\t\t\tnodes.forEach(function (n) {\n\t\t\t\t\tif (errorPath.includes(n.index)) {\n\t\t\t\t\t\terrorNodes.push(n);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tedges.forEach(function (e) {\n\t\t\t\t\tif (errorPath.includes(e.source) && errorPath.includes(e.target)) {\n\t\t\t\t\t\terrorEdges.push(e);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (errorNodes.length > graphSplitThreshold) {\n\t\t\t\t\tbuildMultipleErrorGraphs(errorNodes, errorEdges);\n\t\t\t\t} else {\n\t\t\t\t\tvar g = createGraph();\n\t\t\t\t\tsetGraphNodes(g, errorNodes);\n\t\t\t\t\tsetGraphEdges(g, errorEdges, false);\n\t\t\t\t\terrorGraphMap.push(g);\n\t\t\t\t}\n\t\t\t}",
"function buildMultipleErrorGraphs(errorNodes, errorEdges) {\n errorNodes.sort(\n (firstNode, secondNode) => firstNode.index - secondNode.index\n );\n const requiredGraphs = Math.ceil(errorNodes.length / graphSplitThreshold);\n let firstGraphBuild = false;\n let nodesPerGraph = [];\n for (let i = 1; i <= requiredGraphs; i += 1) {\n if (!firstGraphBuild) {\n nodesPerGraph = errorNodes.slice(0, graphSplitThreshold);\n firstGraphBuild = true;\n } else if (nodes[graphSplitThreshold * i - 1] !== undefined) {\n nodesPerGraph = errorNodes.slice(\n graphSplitThreshold * (i - 1),\n graphSplitThreshold * i\n );\n } else {\n nodesPerGraph = errorNodes.slice(graphSplitThreshold * (i - 1));\n }\n const graph = createGraph();\n errorGraphMap.push(graph);\n setGraphNodes(graph, nodesPerGraph);\n const nodesIndices = [];\n nodesPerGraph.forEach((n) => {\n nodesIndices.push(n.index);\n });\n const graphEdges = errorEdges.filter(\n (e) =>\n nodesIndices.includes(e.source) && nodesIndices.includes(e.target)\n );\n setGraphEdges(graph, graphEdges, true);\n }\n buildCrossgraphEdges(errorEdges, true);\n }",
"function buildMultipleErrorGraphs(errorNodes, errorEdges) {\n\t\t\t\terrorNodes.sort(function (firstNode, secondNode) {\n\t\t\t\t\treturn firstNode.index - secondNode.index;\n\t\t\t\t})\n\t\t\t\tvar requiredGraphs = Math.ceil(errorNodes.length / graphSplitThreshold);\n\t\t\t\tvar firstGraphBuild = false;\n\t\t\t\tvar nodesPerGraph = [];\n\t\t\t\tfor (var i = 1; i <= requiredGraphs; i++) {\n\t\t\t\t\tif (!firstGraphBuild) {\n\t\t\t\t\t\tnodesPerGraph = errorNodes.slice(0, graphSplitThreshold);\n\t\t\t\t\t\tfirstGraphBuild = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (nodes[graphSplitThreshold * i - 1] !== undefined) {\n\t\t\t\t\t\t\tnodesPerGraph = errorNodes.slice(graphSplitThreshold * (i - 1), graphSplitThreshold * i);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tnodesPerGraph = errorNodes.slice(graphSplitThreshold * (i - 1));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tvar graph = createGraph();\n\t\t\t\t\terrorGraphMap.push(graph);\n\t\t\t\t\tsetGraphNodes(graph, nodesPerGraph);\n\t\t\t\t\tvar nodesIndices = []\n\t\t\t\t\tnodesPerGraph.forEach(function (n) {\n\t\t\t\t\t\tnodesIndices.push(n.index);\n\t\t\t\t\t});\n\t\t\t\t\tvar graphEdges = errorEdges.filter(function (e) {\n\t\t\t\t\t\tif (nodesIndices.includes(e.source) && nodesIndices.includes(e.target)) {\n\t\t\t\t\t\t\treturn e;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tsetGraphEdges(graph, graphEdges, true);\n\t\t\t\t}\n\t\t\t\tbuildCrossgraphEdges(errorEdges, true);\n\t\t\t}",
"getNodeValidationErrors(node: Object, visited: any[] = []): Object[] {\n const validationErrors = node.validationErrors ? [ ...node.validationErrors ] : [];\n \n // if this is a parallel, check the parent stage for errors\n const parent = pipelineStore.findParentStage(node);\n if (parent && pipelineStore.pipeline !== parent && parent.validationErrors) {\n validationErrors.push.apply(validationErrors, parent.validationErrors);\n }\n\n return validationErrors.length ? validationErrors : null;\n }",
"getNodeValidationErrors(node: Object, visited: any[] = []): Object[] {\n const validationErrors = node.validationErrors ? [...node.validationErrors] : [];\n\n // if this is a parallel, check the parent stage for errors\n const parent = pipelineStore.findParentStage(node);\n if (parent && pipelineStore.pipeline !== parent && parent.validationErrors) {\n validationErrors.push.apply(validationErrors, parent.validationErrors);\n }\n\n return validationErrors.length ? validationErrors : null;\n }",
"function getTreeMissingMatchingNodeDefError() {\n return Error(\"Could not find a matching node definition for the provided node data.\");\n}",
"function subgraph(n){\n subG = new Array;\n for (var i=0;i<nodes.length;i++){\n if (nodes[i].subgraph==n){\n subG.push(i);\n }\n }\n return subG;\n} // end of subgraph function",
"function getTreeMissingMatchingNodeDefError() {\n return Error(\"Could not find a matching node definition for the provided node data.\");\n }",
"function getTreeMissingMatchingNodeDefError() {\n return Error(`Could not find a matching node definition for the provided node data.`);\n}",
"function verifyGraph(graph) {\n const nodes = new Set(Object.keys(graph));\n for (const [node, edges] of Object.entries(graph)) {\n for (const edge of edges) {\n if (!nodes.has(edge)) {\n throw new Error(\n `Graph edge ${edge} of node ${node} not found in the graph`);\n }\n }\n }\n}",
"function getTreeMissingMatchingNodeDefError() {\n return Error(`Could not find a matching node definition for the provided node data.`);\n}",
"findUnvisitedNode(nodeSet) { \n for(let i = 0; i < nodeSet.length; i++) {\n let index = this.checkExist(nodeSet[i]);\n if(index !== null) { // it exists in the set\n if(this.nodes[index].visited === false) {\n return index;\n }\n }\n }\n return null;\n }",
"function getGraphError(res){\n\tvar ret='';\n\ttry{\n\t\tvar parsed=JSON.parse(res);\n\t}catch(error){\n\n\t}\n\tif(parsed){\n\t\tif(parsed.error){\n\t\t\tif(parsed.error.message){\n\t\t\t\tret=parsed.error.message;\n\t\t\t}\n\t\t}\n\t}\n\treturn ret;\n}",
"function identifySubgraphs()\n\t{\n\t\tsetStatusText(\"Identify Subgraphs...\");\n\t\tfor(var i=0;i< myAllNodes.length;i++ )\n\t\t{\n\t\t\tmyAllNodes[i].graphNumber=-1;\n\t\t}\n\t\t\n\t\tvar nodesToCheck = [];\n\t\tcountNodesInGraph = [];\n\t\tvar graphNumber = 1;\n\t\tfor(var i=0;i<myAllNodes.length;i++ )\n\t\t{\n\t\t\tvar n=myAllNodes[i];\n\t\t\tif( n.graphNumber < 1 )\n\t\t\t{\n\t\t\t\tnodesToCheck.push( n );\n\t\t\t\tcountNodesInGraph.push( 0 );\n\t\t\t\t\n\t\t\t\twhile( nodesToCheck.length > 0 )\n\t\t\t\t{\n\t\t\t\t\tcountNodesInGraph[ countNodesInGraph.length - 1 ]++;\n\t\t\t\t\t\n\t\t\t\t\tvar currNode = nodesToCheck.pop( );\n\t\t\t\t\tcurrNode.graphNumber = graphNumber;\n\t\t\t\t\t\n\t\t\t\t\tfor(var j=0;j<currNode.connectedNodes.length;j++ )\n\t\t\t\t\t{\n\t\t\t\t\t\tvar u=currNode.connectedNodes[j];\n\t\t\t\t\t\tif( u.graphNumber < 1 )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnodesToCheck.push( u );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgraphNumber++;\n\t\t\t}\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
view all Partys in database | static async viewAll() {
return Database.select(new Party().table);
} | [
"function viewAll() {\n connection.query(\"SELECT * FROM products\", function (err, results) {\n if (err) throw err;\n for (let i = 0; i < results.length; i++) {\n console.log(\"Item \" + results[i].item_id + \"| Dept Name: \" + results[i].department_name + \"| Product Name: \" + results[i].product_name + \"| Price: \" + results[i].price + \"| In Stock: \" + results[i].stock_quantity);\n }\n connection.end();\n });\n}",
"function viewEPAs(req, res) {\n db.serialize(function() { \n db.all(\"SELECT * FROM EPAs\", function(err, rows) {\n res.send(rows);\n });\n });\n}",
"function viewAllProducts() {\r\n connection.query(\"SELECT * FROM products\", (err, res) => {\r\n if (err) throw err;\r\n console.log(\"\\n======================FULL INVENTORY=======================\\n\");\r\n console.table(res);\r\n managerCommands();\r\n }) \r\n}",
"function viewAllProducts() {\n connection.query('SELECT * FROM products', function(error, res) {\n if (error) throw error;\n var table = new Table({\n head: ['item_Id', 'Product Name', 'Price Per', 'Stock Qty']\n });\n\n for (i = 0; i < res.length; i++) {\n table.push(\n [res[i].item_id, res[i].product_name, \"$\" + res[i].price, res[i].stock_quantity]\n );\n }\n console.log(table.toString());\n connection.end();\n });\n}",
"function viewTable() {\n db\n .showAll()\n .then((result) => {\n console.table(result);\n start();\n })\n}",
"function viewAllDepartments() {\n connection.query(\"SELECT * FROM department\", function (err, res) {\n console.table(res);\n if (err) throw err;\n startProgram();\n });\n}",
"function viewProducts() {\n\tvar query = \"SELECT * FROM products\";\n\tconnection.query(query, function(error, results) {\n\t\tif (error) throw error;\n\t\tconsoleTable(\"\\nAll Products For Sale\", results);\n\t\twelcome();\n\t});\n}",
"function viewProducts() {\n\tconnection.query('SELECT * FROM products', function(err,res) {\n\t\tif (err) throw err;\n\t\tfor (var i = 0; i < res.length; i++) {\n\t\t\tconsole.log(res[i].id + ' | ' + res[i].product_name + ' | ' + res[i].department_name + ' | ' + res[i].price + ' | ' + res[i].stock_quantity);\n\t\t}\n\t\tconsole.log('-------------------');\n\t\tdisplayOptions();\n\t});\n}",
"static getAll(req, res) {\n db.query('SELECT * FROM parties ORDER BY id ASC', (err, foundParties) => {\n // callback\n if (err) {\n return res.status(500).json({\n status: 500,\n error: err,\n });\n }\n return res.status(200).send({\n status: 200,\n data: foundParties.rows,\n });\n });\n }",
"function viewAllDepartments() {\n var query = 'SELECT * FROM department';\n connection.query(query, function(err, res) {\n if(err)throw err;\n console.table('All Departments:', res);\n options();\n })\n}",
"findAll() {\n return db.many(`\n SELECT *\n FROM parks p\n ORDER BY p.name\n `);\n }",
"function viewAllDept() {\n // query the database for all employees\n connection.query(\n \"SELECT employee.firstname, employee.lastname, department.departmentName FROM employee INNER JOIN jobrole ON employee.role_id = jobrole.id INNER JOIN department ON jobrole.department_id = department.id;\",\n function(err, results) {\n if (err) throw err;\n console.table(results);\n start();\n },\n );\n}",
"function viewDataAll(table) {\n console.log(\"view data all...\");\n db.transaction(function(transaction) {\n transaction.executeSql('SELECT * FROM '+table, [], function (tx, results) {\n var resLen = results.rows.length;\n console.log(\"table results=\"+JSON.stringify(results));\n for (i = 0; i < resLen; i++){\n console.log(\"id=\"+results.rows.item(i).id+\"-title=\"+results.rows.item(i).title+\"-desc=\"+results.rows.item(i).desc);\n $(\"#data-output\").append(\"<p>id=\"+results.rows.item(i).id+\" - title=\"+results.rows.item(i).title+\" - desc=\"+results.rows.item(i).desc)\n }\n }, null);\n });\n }",
"function viewAllEmployeesByDepartments() {\n connection.query(\"SELECT * FROM department;\", (err, res) => {\n if (err) throw err;\n console.table(res);\n startScreen();\n });\n}",
"function viewProducts() {\n\n \tconnection.query(\"SELECT * FROM `products`\", function (err, results, fields) {\n\n \t\tif (err) throw err;\n\t\t\n\t\tconsole.log(\"\");\n\t\tconsole.log(\" ID Product Name Quantity Price \".yellow);\n\t\tconsole.log(\"----------------------------------------------------------\");\n\t\t\n\t\t// loop through the results from the select query on the products table\n\t\tfor (var i = 0; i < results.length; i++) {\n\t\t\tconsole.log(formatTableData(results[i].item_id, results[i].product_name, results[i].stock_quantity, results[i].price));\n\t\t}\n\n\t\tconsole.log(\"----------------------------------------------------------\");\n\t\tconsole.log(\"\");\n\t\tmainMenuPrompt();\n\n\t});\n\n }",
"function viewAllDepartments() {\n db.query(\"SELECT * FROM department\", function (err, res) {\n if (err) throw err;\n console.table(res);\n employerOption();\n });\n}",
"list(req, res) {\n Evolution.findAll()\n .then((evolutions) => {\n res.status(200).json(evolutions);\n })\n .catch((error) => {\n res.status(500).json(error);\n });\n }",
"index(req, res) {\n let plants = Plant.all();\n console.log(plants);\n res.render('plantIndex', { plants: plants });\n }",
"function viewAllDepartments() {\n return connection.query(viewAllDepartmentsQuery);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Valida un numero de cedula ingresado | function validarCedula(inCedula)
{
var array = inCedula.split("") ;
var num = array.length;
var total;
var digito;
var mult;
var decena;
var end;
if(num == 10)
{
total = 0;
digito = (array[9]*1);
for( var i = 0; i<(num-1);i++)
{
mult = 0;
if((i%2) != 0)
{
total = total + (array[i]*1);
}
else
{
mult = array[i]*2;
if( mult > 9)
{
total = total + (mult - 9);
}
else
{
total = total + mult;
}
}
}
decena = total/10;
decena = Math.floor(decena);
decena = ( decena + 1 ) * 10;
end = ( decena - total ) ;
if((end == 10 && digito == 0)|| end == digito)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
} | [
"function validarNumero(){\r\n if(!(this.configurado===true)){\r\n\t this.displayErrorCfg();\r\n\t return false;\r\n\t} // if\r\n\telse{\r\n\t if(isNaN(this.valor)){\r\n\t if(this.displayAlert) alert('El campo debe ser numerico');\r\n\t\tif(this.displayFoco) this.setFoco();\r\n\t\treturn false;\r\n\t } // if\r\n\t else return true;\r\n\t} // else\r\n }",
"function validarNumero(e,punto,id){\n var valor=\"\";\n\t\n\ttecla_codigo = (document.all) ? e.keyCode : e.which;\n\tvalor=document.getElementById(id).value;\n\t\n\t\n\tif(tecla_codigo==8 || tecla_codigo==0)return true;\n\tif (punto==1)\n\t\tpatron =/[0-9\\-.]/;\n\telse\n\t\tpatron =/[0-9\\-]/;\n\t\n\t\t\n\t//validamos que no existan dos puntos o 2 -\n\ttecla_valor = String.fromCharCode(tecla_codigo);\n\t//46 es el valor de \".\"\n\tif (valor.split('.').length>1 && tecla_codigo==46)\t\t\n\t{\n\t\treturn false;\n\t}\n\telse if (valor.split('-').length>1 && tecla_codigo==45)\t\t\n\t{\n\t\t//45 es el valor de \"-\"\n\t\treturn false;\n\t}\n\t\n\t\n\treturn patron.test(tecla_valor);\n\n}",
"function validar_numero(dato){\n\n\treturn Number.isInteger(Number(dato));\n\n}",
"function validar(numIngresado) {\n const regex = /^(10|[1-9]{1})$/;\n return regex.test(numIngresado);\n}",
"function esCadenaConNumeroEntero(str) {\n// Devuelve: true si la cadena recibida es un numero entero o false en caso\n// contrario\n\n var expresionRegularNumeroEnteroPositivo = /^\\d{1,10}$/;\n var expresionRegularNumeroEnteroNegativo = /^-\\d{1,10}$/;\n var indiceDelCaracterGuion = 0;\n\n indiceDelCaracterGuion = str.indexOf(CARACTER_GUION);\n // Si es un numero entero positivo\n if(indiceDelCaracterGuion == ERROR)\n return(expresionRegularNumeroEnteroPositivo.test(str));\n else {\n // Si es un numero entero negativo\n if (indiceDelCaracterGuion == 0)\n return(expresionRegularNumeroEnteroNegativo.test(str));\n else\n return(false);\n }\n}",
"function validarCedula(){\n var cedula = document.formDoc.CedulaPaciente;\n if(cedula.value ==\"\" || cedula.value.indexOf(\" \") == 0 || (isNaN(cedula.value))){\n alert (\"Es necesario introducir un número de cedula\");\n document.getElementById(\"CedulaPaciente\").value = \"\";\n document.getElementById(\"CedulaPaciente\").focus();\n return false;\n } \n}",
"function ValidaMascaraNumTpr() {\n if (numtpr.value.length > 10) {\n numtpr.focus();\n EscreveAviso(\"Tamanho do número da Requisição é maior que 10 dígitos\");\n return false;\n }\n\n if (!IsNumber(parseFloat(numtpr.value))) {\n numtpr.focus();\n EscreveAviso(\"O valor informado não é um número\");\n return false;\n } \n LimpaAviso();\n return true;\n\n}",
"function valida_numeros_solos(id_campo){\n\tvar s_sn = $(\"#\"+id_campo).val();\n\tfor (i_sn=0;i_sn<s_sn.length;i_sn++){\n\t\t\n\t\t\tif(!isDigit(s_sn.charAt(i_sn))) {\n\t\t\t\treturn true;\n\t\t\t\ti_sn=s_sn.length;\n\t\t\t}\n\t}\n}",
"function esNumeroAfiliadoValido(str) {\n\n var expresionRegular = /^\\d{3,8}$/;\n\n // Si es un numero entero\n if (esCadenaConNumeroEntero(str))\n return(expresionRegular.test(str));\n else\n return(false);\n}",
"function validaMinimo(numero){ \n if (!/^([0-9])*$/.test(numero)||(numero === \"\")){\n alert(\"[ERROR] Stock minimo invalido\");\n document.getElementById(\"minimo\").value=\"0\"; \n document.getElementById(\"minimo\").focus();\n }\n }",
"function validar_campos_num (campo){\r\n\tvar swcampo= false;\r\n\tobtener_campo = recopilarinfotextbox(campo);\r\n\t//alert (obtener_campo);\r\n\tif(obtener_campo.length > 0){\r\n\t\tswcampo=/^\\d+\\.?\\d*$/.test(obtener_campo);\r\n\t\tif(swcampo == false){\r\n\t\t\t//alert(\"caracter invalido en \"+campo);\r\n\t\t\treemplazarinfotextbox(campo, \"\");\r\n\t\t}\r\n\t\tif(obtener_campo.length > 2){\r\n\t\t\tif(parseFloat(obtener_campo)==0.0){\r\n\t\t\t\talert(campo+\" no puede tener magnitud 0.0\");\r\n\t\t\t\treemplazarinfotextbox(campo, \"\");\r\n\t\r\n\t\t\t\tswcampo=false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n\treturn swcampo;\r\n}",
"function checkNum() {\n let message = '';\n let valid = true;\n\n if (phAux.tel_numero === '') {\n message = 'número não pode estar vazio!';\n valid = false;\n }\n else if (!(/^[0-9-]{10,12}$/).test(phAux.tel_numero)) {\n message = 'número inválido! DDDXXXXX-XXXX';\n valid = false;\n }\n\n setError({ ...error, numero: message });\n return valid;\n }",
"function validaDisponible(numero){ \n if (!/^([0-9])*$/.test(numero)||numero === \"\"){\n alert(\"[ERROR] Stock disponible invalido\");\n document.getElementById(\"disponible\").value= \"0\"; \n document.getElementById(\"disponible\").focus();\n }\n }",
"function validaNumeros(event) {\n if (event.charCode >= 48 && event.charCode <= 57) {\n return true;\n }\n return false;\n}",
"function validarNumerosLetras(campo){\n \n \n if(/^[a-zA-Z0-9]*$/.test(campo)){\n \n return \"ok\"\n \n }else{\n return \"bad\"\n }\n \n}",
"function fSoloNumerosRango(e, obj, ini, fin, cval, cpas) {\nvar objnum = eventoKey(e);\n//alert(cpas)\n//var cpas1=document.getElementById(\"txtordensuf\"+cpas)\n\nif(objnum == 9) {return false};\nif(objnum == 13 || objnum == 39){\n\tvar expr1 = /^\\d+$/; // Valida solo numero\n\t\n\tif (expr1.test(obj) && parseInt(fconvertir(obj)) >= ini && parseInt(fconvertir(obj)) <= fin ) {\t\t\n\t\t//pasarCajas(cval, cpas1);\n\t\tpasarCajas(cval, cpas);\n\t\treturn true;\n\t\t/*\n\t\tCondicion para compar la caja de texto si es numero y esta dentro del rango inicial y final.\n\t\ttest => es una funcion de la expresion regular que compara deacuerdo a la expresion.\n\t\t*/\n\t} else {\n\t\t//alert(\"Fuera de Rango\");\n\t\tcval.value = \"\";\n\t\tcval.className = \"cajainvalida\";\n\t\treturn false;\n\t}\n}\n\n//return (objnum==13 || (objnum>=48 && objnum<=57 ) )\n\n}",
"function validarCedula(cedula){\t\n\tcadena=/^[0-9]{10}$/;\n\tsumaprod=0;\n\tcoef='212121212';\n if(cadena.test(cedula)){\t\t\n\t\ti=0;\n\t\twhile(i<9){\t\t\t\t\n\t\t\tif(i==0){\n\t\t\t numruc=cedula.substr(0,1);\t\t\n\t\t\t numcoef=coef.substr(0,1);\t \t\t \n\t\t\t}\n\t\t\telse{\n\t\t\t numruc=cedula.substr(i,1);\t\t\n\t\t\t numcoef=coef.substr(i,1);\t \n\t\t\t}\t\t\n\t\t\tproduct=numruc*numcoef;\t\t\n\t\t\tif (product>=10){\t\t\t\n\t\t\t product1=String(product);\t \t\t\t\n\t\t\t num1=product1.substr(0,1);\t\t \n\t\t\t num2=product1.substr(1,1);\t\t\t\n\t\t\t product=Number(num1)+Number(num2);\t \n\t\t\t}\n\t\t\t sumaprod=sumaprod+product;\t\t\t\t \t\t \n\t\t\t i=i+1;\t\t\n\t\t}\t\t\n\t\tresid=sumaprod%10;\t\n\t\tif(resid==0)\n\t\t digverf=0;\n\t\telse\n\t\tdigverf=10-resid;\n\t\tdigverfced=cedula.substr(9,1);\n\t\tif(Number(digverfced)==Number(digverf)) {\n\t\t return 1;\t \n\t\t }\n\t\telse {\n\t\t return 0;\t \n\t\t} \n\t}\n\telse {\n\t return 0;\t \n\t }\n}",
"function validarTel(id){\n\n\tlet campo= document.getElementById(id);\n\tconst patron =/^\\d{8}$/;\n\n\t if (! patron.test(campo.value)) {\n\t \t\talert(\"En el campo Telefono solo se permiten numeros \");\n\t\t \tcampo.classList.add('input-error');\n\t \t\tcampo.classList.remove('input-success');\n\t\t\tcampo.value=\"\";\n\t\t \tcampo.focus();\n\t\treturn false;\n\n\t}\n\t\n}",
"function validaIncrementaExistencias(){\n\t\n\tvar cantidad =$('#cantidad').val();\n\tvar expReg = /^\\d*$/; \n\t\n\tif (cantidad==\"\"){\n\t\t\n\t\tdocument.getElementById(\"alertExistencias\").style.visibility=\"visible\";\n\t\t$(\"#alertExistencias\").text(\"Error. Inserte un valor.\");\n\t\t$(\"#cantidad\").focus();\n\t\t$(\"#cantidad\").select();\n\t}\n\telse{\n\t\t\n\t\tif ( !expReg.test(cantidad)) { \n\t\t\t\n\t\t\tdocument.getElementById(\"alertExistencias\").style.visibility=\"visible\";\n\t\t\t$(\"#alertExistencias\").text(\"Por favor. Inserte un valor correcto.\");\n\t\t\t$(\"#cantidad\").focus();\n\t\t\t$(\"#cantidad\").select();\n\t\t}\n\t\telse {\n\t\t\t\t\n\t\t\t\tprocesaIncrementaExistencias();\n\t\t}\t\n\t}\t\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loading all advertisements in user's cart | async function loadAdvertisements() {
let userId = sessionStorage.getItem("sessionUserId");
try {
let ads = await $.ajax({
url: "/api/users/" + userId + "/cartItems",
method: "get",
dataType: "json"
});
showAds(ads);
} catch (err) {
let elemMain = document.getElementById("main");
console.log(err);
elemMain.innerHTML =
"<h1> Página não está disponível</h1> <br>" +
"<h2> Por favor tente mais tarde</h2>";
}
} | [
"async function listAds(ctx) {\n ctx.loggedIn = sessionStorage.getItem('authToken') !== null;\n ctx.username = sessionStorage.getItem('username');\n try {\n let response = await requestor.get('appdata', 'ads', 'Kinvey');\n let ads = response.reverse();\n if (ads.length === 0) {\n ctx.noAds = true;\n }\n for (let ad of ads) {\n if (ad.publisher === sessionStorage.getItem('username')) {\n ad.isPublisher = true;\n }\n }\n ctx.ads = ads;\n ctx.loadPartials({\n header: './templates/common/header.hbs',\n footer: './templates/common/footer.hbs',\n ad: './templates/catalog/ad.hbs',\n adsCatalog: './templates/catalog/adsCatalog.hbs'\n }).then(function () {\n this.partial('./templates/catalog/adsPage.hbs')\n });\n ctx.redirect('#/listAds');\n } catch (err) {\n errorHandler.handleAjaxError(err);\n }\n }",
"function loadPurchasesGetAllAdmin() {\n var api = new APIConnect();\n api.fetchPurchasesGetAllAdmin(purchasesGetAllAdmin);\n}",
"function get_all_ads() {\n return all_ads;\n}",
"function getAdvertisers() {\n getAudiencesController().fetchAndOutputAdvertisers();\n}",
"async shopifyInitializations () {\n await this.initCart()\n await this.fetchAllCollections()\n }",
"function loadCartInformation() {\n // reserve cart\n // mmrCartService.cartList({\n // uid: $rootScope.$root.pinfo.uid,\n // type: 1,\n // city: $rootScope.$root.location.id\n // }).then(function(res) {\n // console.log(res);\n // }, function(err) {\n // console.log(err);\n // });\n }",
"function loadProducts() {\n sendRequest(\"/products/allProducts\", \"GET\", null, null, setProducts);\n}",
"function loadProducts(){\n productService.products().then(function(data){\n all_products = data;\n setOptions();\n setupListeners();\n })\n}",
"function preloadProducts() {\n var url;\n var callback;\n var params = {};\n if (shopCart.order > 0) {\n url = shopCart.apiURL + 'product/act:by_order';\n params.order = shopCart.order;\n callback = function (response) {\n var answer = JSON.parse(response);\n if (isset(answer.error)) {\n slackErrorDump(new Error(answer.error));\n }\n if (0 == answer.orderId) {\n // чистим куку!!\n setCookie(CART_COOKIE_NAME, 0, -1);\n }\n shopCart.order = parseInt(answer.orderId);\n setCookie(CART_COOKIE_NAME, shopCart.order, 30);\n setProductsList(answer.products);\n };\n } else {\n url = shopCart.apiURL + 'product';\n callback = function (response) {\n setProductsList(JSON.parse(response));\n };\n }\n $.get(url, params).then(callback);\n }",
"function getItemsFromShoppingCart() {\n $.getJSON(getPanierRequest, function (data) {\n items = data;\n nbProducts = items.length;\n }).done(function () {\n addItemsToHtmlShopping();\n });\n }",
"function handleDisplayingAllAd() {\n requester.get('appdata', 'adposts')\n .then(renderAllAds)\n .catch(handleError);\n\n function renderAllAds(data) {\n let context = {\n products: data,\n username: sessionHandler\n .getUsername()\n };\n requester.getTemplate('adPreview', 'products').then(function (data) {\n let template = Handlebars.compile(data);\n viewContainer.empty().append(template(context));\n $('.edit-btn').on('click', function (e) {\n let id = $(e.target).closest('.edit-btn').attr('data-id');\n populateFormToEditAd(id);\n });\n $('.delete-btn').on('click', function (e) {\n let id = $(e.target).closest('.delete-btn').attr('data-id');\n let name = $(e.target).closest('.delete-btn').attr('data-name');\n handleDeleteId(id, name);\n });\n $('.link-product-page').on('click', function (e) {\n let id = $(e.target).closest('.link-product-page').attr('data-id');\n handleShowAllInfoForAd(id);\n });\n });\n }\n }",
"function loadAdvert(advert) {\r\n $.ajax({\r\n method: \"GET\",\r\n url: `${baseUrl}appdata/${appKey}/offers/${advert._id}`,\r\n headers: system.getKinveyAuthHeaders()\r\n })\r\n .then(displayAdvert)\r\n .catch(system.displayError);\r\n\r\n }",
"function loadAllBagsToDOM() {\n templates.clearGearDiv();\n db.getAllBags()\n .then((data) => {\n templates.makeItemList(data);\n });\n}",
"static _LoadOrderedItemsFromSession(){\n if(Storage.Session.get.CheckoutList){\n let loadedList = JSON.parse(Storage.Session.get.CheckoutList);\n\n loadedList.forEach(orderedItem => {\n this.Add(Product.Instances[orderedItem.representedProduct], orderedItem.quantity);\n });\n }\n }",
"function loadProducts() {\n API.getProducts()\n .then(products => {\n setId(window.location.href.split(\"/\").pop());\n setProducts(products);\n getProduct();\n })\n .catch(err => console.log(err));\n }",
"getAds() {\n return models.Ad.findAll({ where: { accept_ad: false } });\n }",
"function loadCatalog() {\n postsService.listAllPosts()\n .then((allPosts) => {\n //console.log(allPosts);\n displayAllPosts(allPosts);\n }).catch(handleError);\n }",
"getBannerList () {\n let _this = this;\n wx.$http({\n url: api.GetCBanner,\n }).then(res => {\n _this.setData({\n bannerList: res\n })\n })\n }",
"async loadPlans() {\n const plansResponse = await fetch('/plans');\n const plans = (await plansResponse.json()).data;\n plans.forEach(plan => {\n let product = this.products[plan.product];\n if (product) {\n if (!product.plans) {\n product.plans = [];\n }\n product.plans.push(plan);\n }\n this.plans[plan.id] = plan;\n });\n const url = window.location.href;\n const prod_id = getParameterByName('id',url);\n this.plans = plans.filter(plan=> plan.product===prod_id)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the outerWidth and dragBarPos variables; used on initialization and window resize | function setOuterWidth() {
outerWidth = wrap.offsetWidth;
dragBarPos = calcDragBarPosFromCss() || Math.floor(outerWidth / 2) - 5;
} | [
"function setSplitterbarPosition() {\n var screenWidth = Math.floor($(window).width());\n\n if (screenWidth < ((minPanelWidth * 2) + parseInt(splitterWidth, 10))) {\n dragEnabled = false;\n var newLeftWidth = Math.floor($(window).width() - parseInt(splitterWidthEdges, 10));\n document.getElementById('splitterBar').style.width = splitterWidthEdges;\n document.getElementsByClassName('leftPanel')[0].setAttribute('style', 'width:' + newLeftWidth + 'px');\n }\n else {\n dragEnabled = true;\n var newLeftWidth = Math.floor(($(window).width() - parseInt(splitterWidth, 10)) / 2);\n document.getElementById('splitterBar').style.width = splitterWidth;\n document.getElementsByClassName('leftPanel')[0].setAttribute('style', 'width:' + newLeftWidth + 'px');\n }\n setSlitterbarWidth();\n }",
"function setGraphBarsWidth() {\n\t\t\t//the width is the result of dividing available space (100%) between the number of bars\n\t\t\t//init var for preventing bars to be wider than they should in case there are less bars than barsByScreen()\n\t\t\tvar barsTotal;\n\t\t\tif ( $absoluteSizeGraphBars.length < getBarsByScreen() ) {\n\t\t\t\tbarsTotal = getBarsByScreen();\n\t\t\t} else {\n\t\t\t\tbarsTotal = $absoluteSizeGraphBars.length;\n\t\t\t}\n\t\t\t//setting its width\n\t\t\t$relativeSizeGraphBars.css( 'width', 100 / barsTotal + '%' );\n\t\t\t$absoluteSizeGraphBars.css( 'width', 100 / barsTotal + '%' );\n\t\t}",
"function setBoxWidths() {\n var leftWidth = dragBarPos - 2,\n rightWidth = outerWidth - dragBarPos - 12;\n\n left.css('width', '' + toPercent(leftWidth) + '%');\n right.css('width', '' + toPercent(rightWidth) + '%');\n }",
"setDraggableArea() {\n let vh = this.track.displayHeight;\n\n if (this.version === undefined) {\n vh += this.bar.displayHeight;\n }\n\n this.verticalDraggableArea = {\n x: this.track.x - ((this.bar.displayWidth - this.track.displayWidth) / 2),\n y: this.track.y - (this.bar.displayHeight / 2),\n w: this.bar.displayWidth,\n h: vh,\n };\n\n this.horizontalDraggableArea = {\n x: this.track.x - (this.bar.displayWidth / 2),\n y: this.track.y - ((this.bar.displayHeight - this.track.displayHeight) / 2),\n w: this.track.displayWidth + this.bar.displayWidth,\n h: this.bar.displayHeight,\n };\n }",
"function setBarWidth() {\n // We do numBars*2 to create a bar width of space between each bar\n barWidth = Math.floor((2 * Math.PI * RADIUS) / (numBars * 2));\n barWidth = barWidth <= MIN_BAR_WIDTH ? MIN_BAR_WIDTH : barWidth;\n}",
"function setWindowScrollerWidth() {\n\t\t\t//getting the ratio for visible bars within the screen\n\t\t\twindowScrollRatio = $absoluteSizeGraphBars.length / getBarsByScreen();\n\t\t\t//preventing ratio to go under 1, so scrollWindow never goes above 100%\n\t\t\tif ( windowScrollRatio < 1 ) {\n\t\t\t\twindowScrollRatio = 1;\n\t\t\t}\n\t\t\t//setting the percent\n\t\t\t$scrollWindow.css( 'width', 100 / windowScrollRatio + '%' );\n\t\t}",
"setFixedBarsSizeAndPosition() {\n\t\tconst fixedBars = this.bars.filter(b=> b.bar.isFixed === true && window.getComputedStyle(b.bar.element).visibility !== 'hidden');\n\t\tconst win = {\n\t\t\ttitleBarEl: {offsetHeight: 0},\n\t\t\tdefaultBorderSize: 0,\n\t\t\t_currentTop: 0,\n\t\t\t_currentBottom: 0,\n\t\t\t_currentLeft: 0,\n\t\t\t_currentWidth: window.innerWidth,\n\t\t\t_currentHeight: window.innerHeight,\n\t\t};\n\t\tthis.setWindowBarsSizeAndPosition(fixedBars, win, this, false);\n\t}",
"function setGraphContainerWidth() {\n\t\t\t//getting the number of bars, divinding it by barsByScreen and multiplying the result by 100, we will get the percent scale of current screen size (#graphContainer's parent is same width as screen)\n\t\t\t//if happens that we get as a result less than 100%, we will force it to be at least 100% width of its parent\n\t\t\tgraphContainerWidth = ( $absoluteSizeGraphBars.length / getBarsByScreen() ) * 100;\n\t\t\tif ( graphContainerWidth < 100 ) {\n\t\t\t\tgraphContainerWidth = 100;\n\t\t\t}\n\t\t\t//setting the percent width\n\t\t\t$graphContainer.css( 'width', graphContainerWidth + '%' );\n\t\t}",
"function dragBarVarSetUp(e,addclass){\n \n var container = $(dragBar).parent().parent()[0];\n var rect = container.getBoundingClientRect();\n offset.x=rect.left;\n offset.y=rect.top+$(newtab.window).scrollTop();\n if(addclass){\n mousePosition.x = e.pageX || e.clientX;\n mousePosition.y = e.pageY || e.clientY;\n $(container).css(\"width\",$(container).width());\n \n $(container).css(\"left\",offset.x);\n $(container).css(\"top\",offset.y);\n $(dragBar).parent().parent().addClass(\"moving\");\n }\n}",
"function updateSideBarSize(){\r\n\r\n // sideBar.style.width = (window.innerWidth - mainCanvas.width - 20) + \"px\";\r\n // // 20px cus sometimes we have the scroll bar on right and that takes ~20px\r\n // sideBar.style.height = window.innerHeight + \"px\";\r\n }",
"_resize() {\n\t\tthis.graphOptions.width = window.innerWidth * 0.7;\n\t\tthis.graphOptions.height = window.innerWidth * 0.5;\n\t\tthis.notifyPath('graphOptions.width');\n\t\tthis.notifyPath('graphOptions.height');\n\t}",
"function setDimensions() {\n let max_radius = parseInt(radius_slider[\"slider\"].max, 10),\n max_height = parseInt(barHeight_slider[\"slider\"].max, 10),\n cWidth = (max_radius + max_height + 5) * 2;\n\n // The 20 is to verify that cWidth can satify first iteration of while loop\n // need to better handle this\n if (cWidth + 20 <= CANVAS_WIDTH) {\n while (cWidth <= CANVAS_WIDTH) {\n max_height += 5;\n max_radius += 5;\n cWidth = (max_radius + max_height + 5) * 2;\n }\n } else if (cWidth - 20 >= CANVAS_WIDTH) {\n while (cWidth >= CANVAS_WIDTH) {\n max_height -= 5;\n max_radius -= 5;\n\n cWidth = (max_radius + max_height + 5) * 2;\n }\n }\n\n // Update each Input Range\n updateRadiusSlider(max_radius);\n updateBarHeightSlider(max_height);\n updateNumBarSlider(max_radius);\n}",
"static resetScrollBarWidth() {\n scrollBarWidth = null;\n }",
"function setTimelineBarsWidth() {\n\t\t\t//the width is the result of dividing available space (100%) between the number of bars\n\t\t\t$timelineBars.css( 'width', 100 / $timelineBars.length + '%' );\n\t\t}",
"static resetScrollBarWidth() {\n scrollBarWidth = null;\n }",
"function setDragBarLeft() {\n dragBar.css('left', '' + toPercent(dragBarPos) + '%');\n }",
"onWindowResize() {\n this.recalculateScrollBar();\n this.recalculatePosition();\n this.recalculateScale();\n }",
"getAndSetDimensions() {\n\t\tthis.resetStyles();\n\t\tthis.width = this.$wrapper.outerWidth();\n\t\tthis.thumbWidth = this.width / this.visibles;\n\t\tthis.$wrapper.css('width', this.width + 'px');\n\t\tthis.$items.css('width', this.thumbWidth + 'px');\n\n\t\tthis.$ribbon.css({\n\t\t\twidth: this.ribbonWidth + 'px'\n\t\t});\n\t}",
"function createResizeBar(params) {\n console.log(\"createResizeBar() called\")\n\n /********************************************************************************\n * \n * Called by the createResizeBar() function to return an encapsulated\n * {resizeBar} JavaScript object.\n * \n * #create_resize_bar_constructor\n\t ********************************************************************************/\n function CreateResizeBar(params) {\n console.log(\"CreateResizeBar() constructor called\")\n const resizeBar = this;\n \n const sResizeBarId = getNextId();\n\n let sAlign = getVal(params,\"align\",\"left\");\n let sResizeClass;\n let sStyle = \"\";\n let resizeBarNd; // DOM node element of resize bar\n\n\n let parentContainer = getVal(params,\"parentContr\",{});\n \n // DOM node element of the parent container\n let parentContainerNode = getVal(params,\"parentContainerEl\",{});\n\n // #resize_bar_instance_array_defs\n let relatedItemsByIndex = []; \n \n // Note: Starting Pos is starting pos at the beginning of a resize bar drag!\n let nStartingLeft = -1,nStartingRight = -1,nStartingTop = -1,nStartingBottom = -1;\n\n let nResizeLeft = -1,nResizeRight = -1,nResizeTop = -1,nResizeBottom = -1;\n\n let nPendingResizeLeft = -1;\n let nPendingResizeRight = -1;\n let nPendingResizeTop = -1;\n let nPendingResizeBottom = -1;\n\n\n let bResizeBarPosAdjusted = false;\n\n // reference to pane objects on either side of resize bar:\n let previousPane = params.previousPane;\n let currentPane = params.currentPane;\n \n\n // initial values until overridden...\n let nMinPos = 0;\n let nMaxPos = window.innerWidth - orvRESIZE_BAR_THICKNESS;\n\n \n // #resize_prop_def\n // Define resize bar properties:\n Object.defineProperties(resizeBar, {\n //\n \"style\": {\n \"get\": function() { \n return sStyle;\n } // end of getter code!\n }, // end of overall 'style' property block!\n\n \"align\": {\n \"get\": function() { \n return sAlign;\n } // end of getter code!\n },\n\n \"id\": {\n \"get\": function() { \n return sResizeBarId;\n } // end of getter code!\n },\n\n\n // #########################################################################################\n // #resize_bar_edge_position_properties\n // #########################################################################################\n\n \"leftEdge\": {\n \"get\": function() { \n \n if (typeof parentContainerNode === \"undefined\") {\n return -1;\n } else if (nStartingLeft > -1) {\n return nStartingLeft;\n } else if (nStartingRight > -1) {\n return parentContainerNode.offsetWidth - nStartingRight - orvRESIZE_BAR_HALFTHICKNESS;\n } // end if / else if / else\n\n } // end of getter code!\n }, // end of overall 'leftEdge' property block!\n\n \"rightEdge\": {\n \"get\": function() { \n if (typeof parentContainerNode === \"undefined\") {\n return -1;\n } else if (nStartingRight > -1) {\n return parentContainerNode.offsetWidth - nStartingRight;\n // } else if (nStartingRight > -1) {\n\n } else {\n return nStartingLeft + orvRESIZE_BAR_THICKNESS;\n } // end if / else if / else\n\n } // end of getter code!\n },\n\n \"topEdge\": {\n \"get\": function() { \n if (typeof parentContainerNode === \"undefined\") {\n return -1;\n } else if (nStartingTop > -1) {\n return nStartingTop;\n } else if (nStartingBottom > -1) {\n return parentContainerNode.offsetHeight - nStartingBottom - orvRESIZE_BAR_HALFTHICKNESS;\n } else {\n return -1;\n }\n \n } // end of getter code!\n },// end of overall 'topEdge' property block!\n\n\n \"bottomEdge\": {\n \"get\": function() { \n if (typeof parentContainerNode === \"undefined\") {\n return -1;\n } else if (nStartingBottom > -1) {\n return parentContainerNode.offsetHeight - nStartingBottom\n } else if (nStartingTop > -1) {\n return nStartingTop + orvRESIZE_BAR_HALFTHICKNESS\n } else {\n return -1;\n }\n\n } // end of getter code!\n },// end of overall 'bottomEdge' property block!\n\n // #########################################################################################\n // #########################################################################################\n\n\n \"relatedItemsByIndex\": {\n \"get\": function() { \n return relatedItemsByIndex;\n } // end of getter code!\n }, \n\n\n \"resizeClass\": {\n \"get\": function() { \n return sResizeClass;\n } // end of getter code!\n }, \n\n \"currPos\": {\n \"get\": function() { \n return 0;\n } // end of getter code!\n },\n\n \"minPos\": {\n \"get\": function() { \n return nMinPos;\n } // end of getter code!\n }, \n\n \"maxPos\": {\n \"get\": function() { \n return nMaxPos;\n } // end of getter code!\n },\n\n // #resize_bar_starting_pos_property_defs\n\n // Note: Starting Pos is starting pos at the beginning of a resize bar drag!\n\n \"startingLeft\": {\n \"get\": function() { \n return nStartingLeft;\n } // end of getter code!\n },\n\n \"startingRight\": {\n \"get\": function() { \n return nStartingRight;\n } // end of getter code!\n },\n\n \n\n \"startingTop\": {\n \"get\": function() { \n return nStartingTop;\n } // end of getter code!\n },\n\n \"startingBottom\": {\n \"get\": function() { \n return nStartingBottom;\n } // end of getter code!\n },\n\n // #resize_bar_basic_pos_properties\n // -------------------------------------------\n \"top\": {\n \"get\": function() { \n return nResizeTop;\n } // end of getter code!\n },\n\n \"bottom\": {\n \"get\": function() { \n return nResizeBottom;\n } // end of getter code!\n },\n\n \"left\": {\n \"get\": function() { \n return nResizeLeft;\n } // end of getter code!\n }, \n\n \"right\": {\n \"get\": function() { \n return nResizeRight;\n } // end of getter code!\n },\n\n // -------------------------------------------\n\n \"extraPanesForCurrent\": {\n \"get\": function() { \n return extraPanesByPrevCurr[\"curr\"];\n } // end of getter code!\n },\n\n \"extraPanesForPrevious\": {\n \"get\": function() { \n return extraPanesByPrevCurr[\"prev\"];\n } // end of getter code!\n },\n\n \"previousPane\": {\n \"get\": function() { \n return previousPane;\n } // end of getter code!\n }, \n \n // the property: \"objType\" is set up elsewhere!\n \n\n \"currentPane\": {\n \"get\": function() { \n return currentPane;\n } // end of getter code!\n }\n \n }); // end of Object.defineProperties\n\n // if (sResizeBarId==='orvPaneEl5') debugger;\n\n if (sAlign=== \"left\" || sAlign=== \"right\") {\n console.log(\"detected need for vertical resize bar\")\n sResizeClass = \"orvPaneResizeToolbarVertical\"; \n const retVal = posStyle(previousPane, sAlign); \n sStyle = sStyle + retVal.style\n nResizeLeft = retVal.left;\n nResizeRight = retVal.right;\n nResizeTop = retVal.top;\n nResizeBottom = retVal.bottom;\n\n } // end if\n\n if (sAlign=== \"top\" || sAlign=== \"bottom\") {\n console.log(\"detected need for horizontal resize bar\")\n sResizeClass = \"orvPaneResizeToolbarHorizontal\";\n const retVal = posStyle(previousPane, sAlign);\n sStyle = sStyle + retVal.style\n\n nResizeLeft = retVal.left;\n nResizeRight = retVal.right;\n nResizeTop = retVal.top;\n nResizeBottom = retVal.bottom; \n \n } // end if\n\n nStartingLeft = nResizeLeft;\n nStartingRight = nResizeRight;\n nStartingTop = nResizeTop;\n nStartingBottom = nResizeBottom;\n\n nLastResizeLeft = nResizeLeft;\n nLastResizeRight = nResizeRight;\n nLastResizeTop = nResizeTop;\n nLastResizeBottom = nResizeBottom;\n\n console.log(\"sStyle = '\"+sStyle+\"'\")\n // debugger\n\n\n /********************************************************************************\n * \n * \n * #resize_bar_add_related_item_method\n\t ********************************************************************************/\n resizeBar.addRelatedItem = function(obj, sAdjustProperty, sPosRelatedToResizeBar) {\n console.log(\"resizeBar.addRelatedItem() method called...\")\n\n if (typeof sAdjustProperty === \"undefined\") {\n debugger\n } // end if\n\n if (typeof sPosRelatedToResizeBar === \"undefined\") {\n debugger\n } // end if\n\n const relatedItem = {};\n relatedItem.obj = obj;\n relatedItem.objType = obj.objType;\n relatedItem.adjustProperty = sAdjustProperty;\n relatedItem.posRelatedToResizeBar = sPosRelatedToResizeBar;\n relatedItemsByIndex.push(relatedItem);\n // relatedItemsByAlignment[sAdjustProperty].push(relatedItem);\n } // end of resizeBar.addRelatedItem() method\n\n\n\n \n\n /********************************************************************************\n * \n * \n * #resize_bar_view_innards\n\t ********************************************************************************/\n resizeBar.viewInnards = function(bNoDrilldown) {\n const fm1 = \"color:blue;\"\n const fm1b = \"color:blue;font-style:italic;\"\n const fm2 = \"color:red;font-weight:bold;\";\n const fm3 = \"background-color:#ffcc99;padding:4px;\";\n const fm4 = \"color:gray;\";\n\n nReportDepth = nReportDepth + 1;\n\n console.groupCollapsed(\"🔑%cid: %c'\"+resizeBar.id+\"'\",fm1,fm2)\n console.log(\"%cobjType: %c'\"+resizeBar.objType+\"'\",fm1,fm2)\n console.log(\"%calign: %c'\"+sAlign+\"'\",fm1,fm2)\n console.log(\"%cstartingLeft: %c\"+resizeBar.startingLeft+\" \",fm1,fm2)\n console.log(\"%cstartingRight: %c\"+resizeBar.startingRight+\" \",fm1,fm2)\n console.log(\"%cstartingTop: %c\"+resizeBar.startingTop+\" \",fm1,fm2)\n console.log(\"%cstartingBottom: %c\"+resizeBar.startingBottom+\" \",fm1,fm2)\n console.log(\"%cmaxPos: %c\"+resizeBar.maxPos+\" \",fm1,fm2)\n console.log(\"%cminPos: %c\"+resizeBar.minPos+\" \",fm1,fm2)\n console.log(\"%cresizeClass: %c'\"+resizeBar.resizeClass+\"'\",fm1,fm2)\n\n console.group(\"%cresize bar Edge values: ... over from top-left of the container...\",fm3)\n console.log(\"%cleftEdge: %c\"+resizeBar.leftEdge+\" \",fm1,fm2)\n\n if (resizeBar.id === 'orvPaneEl4') {\n // debugger\n } // end if\n\n console.log(\"%crightEdge: %c\"+resizeBar.rightEdge+\" \",fm1,fm2)\n console.log(\"%ctopEdge: %c\"+resizeBar.topEdge+\" \",fm1,fm2)\n console.log(\"%cbottomEdge: %c\"+resizeBar.bottomEdge+\" \",fm1,fm2)\n console.groupEnd(); // end of resize bar edge values\n\n let nMax2 = resizeBar.relatedItemsByIndex.length;\n\n if (nMax2 > 0) {\n console.group(\"%crelatedItemsByIndex...(\"+nMax2+\")\",fm3)\n \n for (let n=0;n<nMax2;n++) {\n const relatedItm = resizeBar.relatedItemsByIndex[n];\n const relatedItmObj = relatedItm.obj;\n console.group(\"[\"+n+\"] relatedItm id: '\"+relatedItmObj.id+\"'\")\n\n console.log(\"%cadjustProperty: %c'\"+relatedItm.adjustProperty+\"' \",fm1,fm2)\n console.log(\"%cposRelatedToResizeBar: %c'\"+relatedItm.posRelatedToResizeBar+\"' \",fm1,fm2)\n console.log(\"%cobjType: %c'\"+relatedItm.objType+\"' \",fm1,fm2)\n\n if (nReportDepth < 6) {\n relatedItmObj.viewInnards(true)\n } // end if\n\n console.groupEnd(); // end of relatedItm\n } // next n\n console.groupEnd(); // end of relatedItemsByIndex values\n } // end if\n\n\n\n if (typeof bNoDrilldown === \"undefined\") {\n\n if (nReportDepth < 6) {\n console.log(\"%ccurrentPane:\",fm1b)\n resizeBar.currentPane.viewInnards(true)\n console.log(\"%cpreviousPane:\",fm1b)\n resizeBar.previousPane.viewInnards(true)\n } // end if\n\n /*\n if (resizeBar.extraPanesForCurrent.length > 0) {\n console.group(\"extraPanesForCurrent(\"+resizeBar.extraPanesForCurrent.length+\" elements):\")\n let nMax = resizeBar.extraPanesForCurrent.length;\n for (let n=0;n<nMax;n++) {\n let paneWrapper = resizeBar.extraPanesForCurrent[n];\n paneWrapper.pane.viewInnards(true);\n } // next n\n console.groupEnd();\n } else {\n console.log(\"%cextraPanesForCurrent(0 elements):\",fm4)\n } // end if/else\n \n \n if (resizeBar.extraPanesForPrevious.length > 0) {\n console.group(\"extraPanesForPrevious(\"+resizeBar.extraPanesForPrevious.length+\" elements):\")\n let nMax = resizeBar.extraPanesForPrevious.length;\n for (let n=0;n<nMax;n++) {\n let paneWrapper = resizeBar.extraPanesForPrevious[n];\n paneWrapper.pane.viewInnards(true);\n } // next n\n console.groupEnd();\n } else {\n console.log(\"%cextraPanesForPrevious(0 elements):\",fm4)\n } // end if/else\n */\n } else {\n console.log(\"%ccurrentPane:\",fm1b)\n console.log(\" 🔑id: '\"+resizeBar.currentPane.id+\"'\")\n console.log(\"%cpreviousPane:\",fm1b)\n console.log(\" 🔑id: '\"+resizeBar.previousPane.id+\"'\")\n\n \n } // end if\n\n //console.log(\" =====================================================\")\n console.groupEnd();\n \n nReportDepth = nReportDepth - 1;\n\n } // end of resizeBar.viewInnards() method!\n\n\n\n /********************************************************************************\n * \n * called at the beginning of a Resize-bar drag.\n * \n * #resize_bar_set_start_pos\n\t ********************************************************************************/\n resizeBar.setStartPos = function() {\n console.log(\"resizeBar.setStartPos() method called\")\n nStartingLeft = nResizeLeft;\n nStartingRight = nResizeRight;\n nStartingTop = nResizeTop;\n nStartingBottom = nResizeBottom;\n\n nPendingResizeLeft = -1;\n nPendingResizeRight = -1;\n nPendingResizeTop = -1;\n nPendingResizeBottom = -1;\n\n } // end of resizeBar.setStartPos() method\n\n\n\n /********************************************************************************\n * \n * #resize_bar_apply_changes_method\n * \n * pending values are set in: resizeBar.setNewPos() method\n\t ********************************************************************************/\n resizeBar.applyChanges = function() {\n console.log(\"resizeBar.applyChanges() method called\")\n\n if (nPendingResizeLeft > -1) {\n nResizeLeft = nPendingResizeLeft;\n resizeBarNd.style.left = (nResizeLeft)+\"px\";\n nPendingResizeLeft = -1\n } // end if\n\n if (nPendingResizeRight > -1) {\n nResizeRight = nPendingResizeRight;\n resizeBarNd.style.right = (nResizeRight)+\"px\";\n nPendingResizeRight = -1;\n } // end if\n\n if (nPendingResizeBottom > -1) {\n nResizeBottom = nPendingResizeBottom;\n resizeBarNd.style.bottom = (nResizeBottom)+\"px\";\n nPendingResizeBottom = -1;\n } // end if\n\n if (nPendingResizeTop > -1) {\n nResizeTop = nPendingResizeTop;\n resizeBarNd.style.top = (nResizeTop)+\"px\";\n nPendingResizeTop = -1;\n } // end if\n\n \n } // end of resizeBar.applyChanges() method \n\n\n /********************************************************************************\n * \n * Called from: \n * \n * #resize_bar_set_pos_adjust_flag\n\t ********************************************************************************/\n resizeBar.setPosAdjustFlag = function(bNewValue) {\n bResizeBarPosAdjusted = bNewValue;\n } // end of resizeBar.setPosAdjustFlag() method\n\n\n\n\n /********************************************************************************\n * \n * Called from: resizeBarDragMove()\n * \n * #resize_bar_set_new_pos\n\t ********************************************************************************/\n resizeBar.setNewPos = function(nNewPos, sAlign) {\n console.log(\"resizeBar.setNewPos() called. nNewPos=\"+nNewPos+\" sAlign='\"+sAlign+\"'\")\n\n let returnInfo = {};\n returnInfo.obj = resizeBar;\n returnInfo.operation = \"setNewPos\";\n returnInfo.objType = \"resizeBar\";\n returnInfo.success = true; // assume success in this case\n returnInfo.errMsg = \"\";\n\n if (nNewPos < 0) {\n returnInfo.success = false; \n returnInfo.errMsg = \"nNewPos < 0 (\"+nNewPos+\")\";\n return returnInfo;\n } // end if\n\n if (sAlign === \"left\") { \n //nResizeLeft = nNewPos;\n nPendingResizeLeft = nNewPos;\n } // end if\n\n if (sAlign === \"right\") {\n // nResizeRight = nNewPos;\n nPendingResizeRight = nNewPos;\n } // end if\n\n if (sAlign === \"top\") {\n // nResizeTop = nNewPos;\n nPendingResizeTop = nNewPos;\n } // end if\n\n if (sAlign === \"bottom\") {\n // nResizeBottom = nNewPos;\n nPendingResizeBottom = nNewPos;\n } // end if\n\n // resizeBarNd.style[sAlign] = (nNewPos)+\"px\";\n return returnInfo; // success\n\n } // end of resizeBar.setNewPos() method\n\n\n\n /********************************************************************************\n * \n * \n * Search for: \"#resize_prop_def\"\n * \n * #resize_bar_add_another_pane\n\t ********************************************************************************/\n resizeBar.addAnotherPane = function(newPane, sPrevCurrent, matchupPane) {\n console.log(\"🧀🧀 resizeBar.addAnotherPane() method called 🧀🧀\")\n\n if (typeof extraPanesById[newPane.id] === \"undefined\") {\n const extraPaneContainer = {};\n\n extraPaneContainer.id = newPane.id;\n extraPaneContainer.pane = newPane;\n extraPaneContainer.prevCurrent = sPrevCurrent; // matched up with what pane... the previous or current\n extraPaneContainer.matchupPane = matchupPane;\n\n extraPanesById[newPane.id] = extraPaneContainer;\n extraPanesByIndex.push(extraPaneContainer);\n console.log(\"**** Extra pane was added. 🌴🌴🌴\")\n\n if (typeof extraPanesByPrevCurr[sPrevCurrent] === \"undefined\") {\n extraPanesByPrevCurr[sPrevCurrent] = [];\n } // end if\n\n let prevCurrLst = extraPanesByPrevCurr[sPrevCurrent];\n prevCurrLst.push(extraPaneContainer);\n console.log(\"**** Added to extraPanesByPrevCurr list for: '\"+sPrevCurrent+\"'. 🌴🌴🌴\")\n } // end if\n } // end of resizeBar.addAnotherPane() method\n\n\n /********************************************************************************\n * \n * Generates HTML markup needed to produce a resize bar on the web page.\n * \n * Called multiple times from: pane.genMarkup()\n * \n * #resize_bar_get_html_markup\n\t ********************************************************************************/\n resizeBar.getHtmlMarkup = function() {\n console.log(\"🤔🤔resizeBar.getHtmlMarkup() method called\")\n const s = [];\n\n s.push(\"<div class='\");\n s.push(sResizeClass);\n s.push(\"' \");\n\n s.push(\"id=\"+Q);\n s.push(sResizeBarId);\n s.push(Q);\n\n // temp:\n s.push(\" title=\"+Q);\n s.push(sResizeBarId);\n s.push(Q);\n\n s.push(\" style=\");\n s.push(Q);\n s.push(sStyle);\n s.push(Q);\n s.push(\">\"); // end of opening tag\n\n s.push(\"</div>\"); // closing tag\n\n return s.join(\"\");\n } // end of getHtmlMarkup method for resize bar\n\n\n /********************************************************************************\n * \n * called by: pns.showPanes()\n * \n * Let plain JavaScript resize bar object know about the \n * DOM element that it is working with!\n * \n * #resize_bar_set_dom_ref\n\t ********************************************************************************/\n resizeBar.setDomRef = function() {\n console.log(\"💈 resizeBar.setDomRef() method called. id: '\"+sResizeBarId+\"' 💈\")\n resizeBarNd = document.getElementById(sResizeBarId)\n } // end of setDomRef() method\n\n\n\n\n\n /********************************************************************************\n * called at the beginning of a resize bar drag...\n\t ********************************************************************************/ \n resizeBar.setStartPos = function() {\n console.log(\"called resizeBar.setStartPos() method\")\n } // end of resizeBar.setStartPos() method\n\n\n\n\n // global references to the resize bars are added to:\n resizeBarsByIndex.push(resizeBar);\n resizeBarsById[sResizeBarId] = resizeBar;\n\n // resize bar references for specific related panes\n previousPane.addResizeBarRef(resizeBar);\n currentPane.addResizeBarRef(resizeBar);\n\n } // end of function CreateResizeBar()\n\n\n const rb = new CreateResizeBar(params); // calls Constructor defined above.\n setupObjTypeProp(rb,\"resizeBar\");\n \n return rb;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ADICIONA MASCARA DE DATA | function mascaraData(data){
if(mascaraInteiro(data)==false){
event.returnValue = false;
}
return formataCampo(data, '00/00/0000', event);
} | [
"function MascaraData(data) {\n if (mascaraInteiro(data) == false) {\n event.returnValue = false;\n }\n return formataCampo(data, '00/00/0000', event);\n }",
"function MascaraData(data){\r\n if(mascaraInteiro(data)==false){\r\n event.returnValue = false;\r\n }\r\n return formataCampo(data, '00/00/0000', event);\r\n }",
"function MascaraData(data)\n{\t\n if(mascaraInteiro(data)==false)\n {\t\t\n event.returnValue = false;\t\n }\t\t\n return formataCampo(data, '00/00/0000', event);\n}",
"function mascaraData(data){\n if(mascaraInteiro(data)==false){\n event.returnValue = false;\n } \n return formataCampo(data, '00/00/0000', event);\n}",
"function MascaraData(data, event) {\n\n return formataCampo(data, '00/00/0000', event);\n}",
"function MascaraDataSQL(data){\n if(mascaraInteiro(data)==false){\n event.returnValue = false;\n } \n return formataCampo(data, '0000-00-00', event);\n}",
"montapesquisa(){\n var dados = [];\n dados.push(\n {name: \"pesq_top\", value: this.pesq_top},\n {name: \"pesq_pagina\", value: this.pesq_pagina},\n {name: \"ordena_por\", value: this.ordena},\n {name: \"class\", value: this.class},\n {name: \"only_headers\", value: this.only_headers},\n {name: \"nome_tabela\", value: this.tabela.id}\n );\n\n return dados;\n }",
"function mostrarDatos() {\n //Obtener los datos del dataset\n let penetracion = datos.penetracion;\n\n // calcular promedio de penetración anual\n penetracion = getPromedioAnualPais(penetracion);\n\n // dibujar garaficos\n dibujarChart(penetracion);\n} // fin mostrarDatos",
"function Data(dia, mes, ano) {\n this.dia = dia;\n this.mes = mes;\n this.ano = ano;\n // this.dia = dia;\n // this.mes = mes;\n // this.ano = ano;\n }",
"function loaddata()\n{\n\tvar active = dataBase.result;\n\tvar data = active.transaction(['almacen'], 'readonly');\n\tvar object = data.objectStore('almacen');\n\tvar elements = [];\n\tvar subindice = object.index('indicefecha');\n\t//ejecutamos un metodo de indexedDB y abre el almacen peaple y coloca el puntero en la posicion inicial que es 0\n\tsubindice.openCursor().onsuccess = function(e)\n\t{\n\t\t//asignamos el puntero\n\t\tvar result = e.target.result;\n\t\t//si cuando result es null \n\t\tif (result === null) \n\t\t{\n\t\t\treturn;\n\t\t}\n\t\telements.push(result.value);\n\t\tresult.continue();\n\t};\n\n\tdata.oncomplete = function()\n\t{\n\t\tdocument.getElementById(\"contenidoingreso\").innerHTML = \"\";\n\t\tdocument.getElementById(\"contenidoegreso\").innerHTML = \"\";\n\t\tvar subtotalingresos = 0;\n\t\tvar subtotalegresos = 0;\n\t\tvar num = 0, num2 = 0; \n\t\tfor (var key in elements)\n\t\t{\n\t\t\tconsole.log(elements[key].titulo);\n\t\t\tif (elements[key].titulo == \"Ingresos\") \n\t\t\t{\n\t\t\t\tdocument.getElementById(\"contenidoingreso\").innerHTML += \"<table border=1><th>fecha</th><th>producto</th><th>cantidad</th><tr><td>\"+elements[key].fecha+\"</td><td>\"+elements[key].producto+\"</td><td>\"+elements[key].cantidad+\"</td><tr><th colspan=3>observacion</th></tr><tr><td colspan=3>\"+elements[key].observacion+\"</td></tr></table><br>\";\n\t\t\t\tnum += parseFloat(elements[key].cantidad);\n\t\t\t\tconsole.log(num);\n\t\t\t\tsubtotalingresos = num.toFixed(2);\n\t\t\t}\n\t\t\telse if (elements[key].titulo == \"Compras\")\n\t\t\t{\n\t\t\t\tdocument.getElementById(\"contenidoegreso\").innerHTML += \"<table border=1><th>fecha</th><th>producto</th><th>cantidad</th><tr><td>\"+elements[key].fecha+\"</td><td>\"+elements[key].producto+\"</td><td>\"+elements[key].cantidad+\"</td><tr><th colspan=3>observacion</th></tr><tr><td colspan=3>\"+elements[key].observacion+\"</td></tr></table><br>\";\n\t\t\t\tnum2 += parseFloat(elements[key].cantidad);\n\t\t\t\tconsole.log(num2);\n\t\t\t\tsubtotalegresos = num2.toFixed(2);\n\t\t\t}\n\t\t}\n\t\tdocument.getElementById(\"subtotalingresos\").innerHTML = \"El total de todos los ingresos es $\" + subtotalingresos;\n\t\tdocument.getElementById(\"subtotalegresos\").innerHTML = \"El total de todos los egresos es $\" + subtotalegresos;\n\t}\n}",
"function datosADIC(){\n var adic = {};\n adic = {\n nombre: \"ADICIONALES\",\n alcance:\"Adicionales\",\n num_subprocesos: 0\n }\n return adic;\n}",
"function obtenerCasaMatriz(){\n cxcService.getCasaMatriz({}, {},0,serverConf.ERPCONTA_WS, function (response) {\n //exito\n console.info(\"emisionFactura: Casa matriz\",response.data);\n $scope.sucursalCasaMatriz = response.data;\n }, function (responseError) {\n //error\n });\n }",
"function set_absensi_array(data){\n absensi_siswa_arr=[];\n for(var i=0;i<getJumlah();i++){\n absensi_siswa_arr.push({\n status : data[i].charAt(0),\n id_kelas_siswa : getIdKelas(i),\n });\n }\n }",
"function metadeAmericano(inputIngrediente, valorG) {\n let ingredienteConvertido = todasConversoes(inputIngrediente, valorG)\n let gRestantes = [ingredienteConvertido[1], ingredienteConvertido[3], ingredienteConvertido[5]]\n let metadeAmericanoConvertida = metadeConvertidaAmericano(valorG)\n let gRestanteX = Math.round(gRestantes[0])//indice da metade do copo americano\n\n let comparacaoMetadesGramas = americanoComparaGramas(metadeAmericanoConvertida, gRestantes) //array com as metades e os true/false\n let indiceMetadeTrue = americanoPosicaoTrue(comparacaoMetadesGramas)\n\n if (indiceMetadeTrue === 0) { //0 pode ser false\n //mudar o valor para MeiaXicara\n $('[data-valor-metade-americano]').text(\"\")//numero\n $('[data-metade-americano]').text(\"Meio copo americano\")\n $(\"[data-linha-americano='mais']\").removeClass(\"esconder-metades\")\n $(\"[data-linha-americano='metades']\").removeClass(\"esconder-metades\")\n $(\"[data-linha-americano='inteiro']\").removeClass(\"esconder-inteiros\")\n $(\"[data-linha-americano='ou']\").removeClass(\"esconder-inteiros\")\n \n } else if (indiceMetadeTrue === 1) {\n //mudar o valor para UmTerço\n $('[data-valor-metade-americano]').text(\"\")//numero\n $('[data-metade-americano]').text(\"Um terço de copo americano\")\n $(\"[data-linha-americano='mais']\").removeClass(\"esconder-metades\")\n $(\"[data-linha-americano='metades']\").removeClass(\"esconder-metades\")\n $(\"[data-linha-americano='inteiro']\").removeClass(\"esconder-inteiros\")\n $(\"[data-linha-americano='ou']\").removeClass(\"esconder-inteiros\")\n \n } else if (indiceMetadeTrue === 2) {\n //mudar valor para UmQuarto\n $('[data-valor-metade-americano]').text(\"\")//numero\n $('[data-metade-americano]').text(\"Um quarto de copo americano\")\n $(\"[data-linha-americano='mais']\").removeClass(\"esconder-metades\")\n $(\"[data-linha-americano='metades']\").removeClass(\"esconder-metades\")\n $(\"[data-linha-americano='inteiro']\").removeClass(\"esconder-inteiros\")\n $(\"[data-linha-americano='ou']\").removeClass(\"esconder-inteiros\")\n \n } else if (indiceMetadeTrue === 3) {\n //mudar valor para TresQuartos\n $('[data-valor-metade-americano]').text(\"\")//numero\n $('[data-metade-americano]').text(\"Um terço de copo americano\")\n $(\"[data-linha-americano='mais']\").removeClass(\"esconder-metades\")\n $(\"[data-linha-americano='metades']\").removeClass(\"esconder-metades\")\n $(\"[data-linha-americano='inteiro']\").removeClass(\"esconder-inteiros\")\n $(\"[data-linha-americano='ou']\").removeClass(\"esconder-inteiros\")\n \n } else {\n if (gRestanteX == 0) {\n $(\"[data-linha-americano='mais']\").addClass(\"esconder-metades\")\n $(\"[data-linha-americano='metades']\").addClass(\"esconder-metades\")\n \n } else if ((gRestanteX != 0) && (ingredienteConvertido[0] == 0)) {\n //esconder as gramas quando não tiver valor inteiro\n $(\"[data-linha-americano='inteiro']\").addClass(\"esconder-inteiros\")\n $(\"[data-linha-americano='ou']\").addClass(\"esconder-inteiros\")\n $(\"[data-linha-americano='mais']\").addClass(\"esconder-metades\")\n $(\"[data-linha-americano='metades']\").addClass(\"esconder-metades\")\n }\n else{\n $('[data-valor-metade-americano]').text(gRestanteX)\n $('[data-metade-americano]').text(\"gramas\")\n $(\"[data-linha-americano='mais']\").removeClass(\"esconder-metades\")\n $(\"[data-linha-americano='metades']\").removeClass(\"esconder-metades\")\n $(\"[data-linha-americano='inteiro']\").removeClass(\"esconder-inteiros\")\n $(\"[data-linha-americano='ou']\").removeClass(\"esconder-inteiros\")\n \n //mostrar valores das gramas\n }\n } \n}",
"function cargarPromedio() {\n var prom = segundoParcial.empleados.reduce(function (anterior, actual) {\n return Number(anterior) + Number(actual.edad);\n }, 0) / segundoParcial.empleados.length;\n if (!isNaN(prom)) {\n $(\"#promedio\").val(prom + \" años\");\n }\n else {\n $(\"#promedio\").val(\"Sin datos\");\n }\n }",
"function setDatos() {\n vm.movimiento = {};\n vm.movimiento.total_costo = 0;\n vm.movimiento.total = 0;\n vm.movimiento.detalle = [];\n vm.detalle = {};\n vm.detalle.cantidad = 0;\n vm.detalle.precio_costo = 0;\n // vm.detalle.precio_venta = 0;\n }",
"function ControlloDataInserita(datadafiltrare,campo,dt,colore,sfondo) {\r\n\r\nvar gg; //variabile per i giorni\r\nvar mm; // variabile per i mesi\r\nvar yy; // variabile per l'anno\r\nvar dateNow = new Date(); // assegna la data corrente (presa dal pc locale)\r\nvar yearNow = dateNow.getFullYear(); //assegna l'anno corente\r\nvar indice=0; // variabile di servizio\r\n\r\nvar nrgiorni = new Array();\r\n\tnrgiorni[0]=29; // febbraio bisestile\r\n\tnrgiorni[1]=31; // gennaio\r\n\tnrgiorni[2]=28; // febbraio\r\n\tnrgiorni[3]=31; // marzo\r\n\tnrgiorni[4]=30;\t// aprile\r\n\tnrgiorni[5]=31; // maggio\r\n\tnrgiorni[6]=30; // giugno\r\n\tnrgiorni[7]=31; // luglio\r\n\tnrgiorni[8]=31; // agosto\r\n\tnrgiorni[9]=30; // settembre\r\n\tnrgiorni[10]=31; // ottobre\r\n\tnrgiorni[11]=30; // novembre\r\n\tnrgiorni[12]=31; // dicembre\r\n\r\nif (datadafiltrare==null || datadafiltrare==\"\") { //se il campo è vuoto esce dalla funzione\r\n document.getElementById(campo).style.color=colore;\r\n document.getElementById(campo).style.background=\"white\";\r\n return;\r\n}\r\n\r\nswitch (datadafiltrare.length) { //analizza il formato della data e prepara le variabili gg, mm, yy\r\n case is = 6: //formato data breve\r\n gg = datadafiltrare.slice(0,2);\r\n mm = datadafiltrare.slice(2,4);\r\n yy = datadafiltrare.slice(4,6);\r\n break; \r\n \r\n case is = 8: //formato data a 8 caratteri\r\n if (datadafiltrare.indexOf(\"/\") >= 0 || datadafiltrare.indexOf(\"-\")>=0) { //con separatori\r\n gg = datadafiltrare.slice(0,2);\r\n mm = datadafiltrare.slice(3,5);\r\n yy = datadafiltrare.slice(6,8);\r\n } else { //data a 8 cifre senza separatori\r\n gg = datadafiltrare.slice(0,2);\r\n mm = datadafiltrare.slice(2,4);\r\n yy = datadafiltrare.slice(4,8);\r\n }\r\n break;\r\n \r\n case is = 10: //formato data completa\r\n gg = datadafiltrare.slice(0,2);\r\n mm = datadafiltrare.slice(3,5);\r\n yy = datadafiltrare.slice(6,10);\r\n break;\r\n\r\n default: //negli altri formati inseriti la routine genera un errore\r\n alert(\"Attenzione! La data che hai inserito e' errata. Sono validi i seguenti formati: 'ggmmaa','gg/mm/aa','ggmmaaaa' e 'gg/mm/aaaa'\");\r\n document.getElementById(campo).focus();\r\n //datadafiltrare.focus();\r\n datadafiltrare=\"\";\r\n return datadafiltrare;\r\n}\r\n\r\n//controlla che i dati di riferimento al giorno, al mese e all'anno siano dati numerici \r\nif (isNaN(gg) || isNaN(mm) || isNaN(yy)) {\r\n\talert(\"Attenzione! La data che hai inserito e' errata.\");\r\n document.getElementById(campo).focus();\r\n //datadafiltrare.focus();\r\n datadafiltrare=\"\";\r\n return datadafiltrare;\r\n}\r\n\r\n//controlla che siano stati inseriti giusti tutti gli elementi che compongono la data\r\nif (Number(gg) <= 0 || Number(mm) <= 0 || Number(mm) > 12 || Number(yy) < 0) { \r\n alert(\"Attenzione! La data che hai inserito e' errata.\");\r\n document.getElementById(campo).focus();\r\n //datadafiltrare.focus();\r\n datadafiltrare=\"\";\r\n return datadafiltrare;\r\n}\r\n\r\n//porta l'anno a quattro cifre calcolando il cambio del millennio\r\nif (Number(yy) <= (Number(yearNow)-2000)) { \r\n yy = (Number(yy)+2000); \r\n } else if (Number(yy) < 100 && Number(yy) > (Number(yearNow)-2000)){\r\n yy = (Number(yy)+1900);\r\n }\r\n\r\n//controlla che l'anno non sia maggiore o uguale a quello corrente\r\n//(dt e dn significano data tesseramento e data di nascita)\r\nif (dt==\"dn\") {\r\n if (Number(yy) >= Number(yearNow)) { \r\n alert(\"Attenzione! L'anno che hai inserito e' errato!\");\r\n document.getElementById(campo).focus;\r\n //datadafiltrare.focus();\r\n datadafiltrare=\"\";\r\n return datadafiltrare;\r\n }\r\n}\r\n// controlla che l'anno inserito non sia bisestile e assegna il valore alla variabile indice\r\nif ((Number(yy) % 4) == 0 && Number(mm)==2) {\r\n\tindice=0;\r\n} else {\r\n\tindice=Number(mm);\r\n}\r\n\r\n// controlla che l'utente non abbia inserito un numero giorni del mese errato\r\nif (Number(gg) > nrgiorni[indice]) {\t\r\n\talert(\"Attenzione! La data che hai inserito e' errata.\");\r\n document.getElementById(campo).focus();\r\n //datadafiltrare.focus();\r\n datadafiltrare=\"\";\r\n return datadafiltrare;\r\n}\r\n// ricompone e stampa la data filtrata\r\ndatadafiltrare=gg+\"/\"+mm+\"/\"+yy;\r\ndocument.getElementById(campo).value=datadafiltrare;\r\ndocument.getElementById(campo).style.color=colore;\r\ndocument.getElementById(campo).style.background=\"white\";\r\nreturn;\r\n}",
"function alianzaMercado(){\n\t\tvar a = find(\"//tr[@class='rbg']\", XPFirst).parentNode;\n\n\t\t// Prepara la insercion de la nueva columna\n\t\tvar b = a.getElementsByTagName(\"TR\");\n\t\t// FIXME: Apaño para Firefox. FF mete nodos de tipo texto vacios\n\t\tb[0].childNodes[b[0].childNodes.length == 3 ? 1 : 0].setAttribute('colspan', '8');\n\t\tb[b.length - 1].childNodes[0].setAttribute(\"colspan\", \"8\");\n\n\t\t// Crea e inserta la columna\n\t\tvar columna = document.createElement(\"TD\");\n\t\tcolumna.innerHTML = T('ALIANZA');\n\t\tb[1].appendChild(columna);\n\n\t\t// Rellena la columna con los nombres de las alianzas\n\t\tfor(var i = 2; i < b.length - 1; i++){\n\t\t\tvar alianza = document.createElement(\"TD\");\n\t\t\t// FIXME: Apaño para Firefox. FF mete nodos de tipo texto vacios\n\t\t\tvar alianza_txt = b[i].childNodes[b[i].childNodes.length == 12 ? 8 : 4].getAttribute('title');\n\t\t\tif (alianza_txt != null) alianza.innerHTML = alianza_txt;\n\t\t\tb[i].appendChild(alianza);\n\t\t}\n\t}",
"function definirAlumnos(){\n var _carreraAlumno = \"\";\n // uso de la variable alumno \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
strips HTML from input, preserving BR tags | function stripHtml(input) {
if (typeof input === 'undefined') {
return '';
}
// note this is not a good way to do this with normal HTML, but works for GW2's item db
var stripped = input.replace(/<br>/ig, '\n');
stripped = stripped.replace(/(<([^>]+)>)/ig, '');
stripped = stripped.replace(/\n|\\n/g, '<br>');
return stripped;
} | [
"function strip(html)\n {\n html = html.replace(/<b>/g, \"\");\n html = html.replace(/<\\/b>/g, \"\");\n html = html.replace(/<(?:.|\\n)*?>/gm, \"\");\n return html;\n }",
"function baynote_removeHtml(raw) {\n\tif (!raw) return;\n\traw = raw.replace(/\\<[^>]*\\>/g, \"\");\n\traw = raw.replace(/\\<.*/, \"\");\n\traw = raw.replace(/\\ /g, \" \");\n\traw = raw.replace(/^\\s+/, \"\");\n\traw = raw.replace(/\\s+$/, \"\");\n\traw = raw.replace(/\\n/g, \" \");\n\treturn raw;\n}",
"function rm_empty_br(html_str) {\n\t// remove br next to opening tags\n\tlet edited_html_str = html_str.replaceAll(/(<p( [^>]*)*>)( |\\n)*<br[ \\/]*>( |\\n)*/g, \"$1\");\n\tedited_html_str = edited_html_str.replaceAll(/(<li( [^>]*)*>)( |\\n)*<br[ \\/]*>( |\\n)*/g, \"$1\");\n\tedited_html_str = edited_html_str.replaceAll(/(<th( [^>]*)*>)( |\\n)*<br[ \\/]*>( |\\n)*/g, \"$1\");\n\tedited_html_str = edited_html_str.replaceAll(/(<td( [^>]*)*>)( |\\n)*<br[ \\/]*>( |\\n)*/g, \"$1\");\n\tedited_html_str = edited_html_str.replaceAll(/(<h[0-9]+( [^>]*)*>)( |\\n)*<br[ \\/]*>( |\\n)*/g, \"$1\");\n\t// remove br next to closing tags\n\tedited_html_str = edited_html_str.replaceAll(/( |\\n)*<br[ \\/]*>( |\\n)*<\\/p>/g, \"</p>\");\n\tedited_html_str = edited_html_str.replaceAll(/( |\\n)*<br[ \\/]*>( |\\n)*<\\/li>/g, \"</li>\");\n\tedited_html_str = edited_html_str.replaceAll(/( |\\n)*<br[ \\/]*>( |\\n)*<\\/th>/g, \"</th>\");\n\tedited_html_str = edited_html_str.replaceAll(/( |\\n)*<br[ \\/]*>( |\\n)*<\\/td>/g, \"</td>\");\n\tedited_html_str = edited_html_str.replaceAll(/( |\\n)*<br[ \\/]*>( |\\n)*<\\/h([0-9]+)>/g, \"</h$3>\");\n\treturn edited_html_str;\n}",
"function strip_HTML(str) {\n var findHtml = /<(.|\\n)*?>/gi;\n return str.replace(findHtml,\"\");\n}",
"function normaliseContentEditableHTML(html, trim) {\n html = html.replace(initialBreaks, '$1\\n\\n')\n .replace(initialBreak, '$1\\n')\n .replace(wrappedBreaks, '\\n')\n .replace(openBreaks, '')\n .replace(breaks, '\\n')\n .replace(allTags, '')\n .replace(newlines, '<br>')\n\n if (trim) {\n html = html.replace(trimWhitespace, '')\n }\n\n return html\n}",
"function stripHTML(cadena)\r\n{\r\n\treturn cadena.replace(/<[^>]+>/g,'');\r\n}",
"function revoveHTMLAndStyleButNotBr(text) {\n\ttext = text.replace(/<style(.)*style>/gm, '');\n\ttext = text.replace(/\\n/g, ' ');\n\ttext = text.replace(/<br>|<\\/br>/gm, '\\n');\n\ttext = $('<div/>').html(text).text();\n\ttext = text.replace(/[ \\t\\r]{2,}/g, ' ');\n\ttext = text.replace(/\\n/gm, '</br>');\t\n\treturn text.trim();\n}",
"htmlToText(text) {\n text = text.replace(\"</br>\", \"\\n\");\n text = text.replace(\"<br>\", \"\\n\");\n text = text.replace(/<\\/?[^>]+>/ig, \" \"); // Remove all HTML-Tags!!!\n return text;\n }",
"function sanitizeHTML() {\r\n var bio = $(\"#bio\");\r\n bio.val(bio.val().replace(/<(.|\\n)*?>/g, \"\"));\r\n}",
"function stripHTML( html )\n{\n // Replace the tag\n var html = html.replace(/<.*?>/g, '');\n return html;\n}",
"function stripHTML(cadena)\r\n{\r\n\tvar cadena_temp = \"\";\r\n\tcadena_temp = cadena.replace(/<[^>]+>/g,'');\r\n\tcadena_temp = cadena_temp.replace(/\\[/g,'<');\r\n\tcadena_temp = cadena_temp.replace(/\\]/g,'>');\r\n\tcadena_temp = cadena_temp.replace(/<[^>]+>/g,'');\r\n\treturn cadena_temp;\r\n}",
"function clean_output(out) {\n //NOTE: make sure to use the g flag so it finds all (global) instances\n var brregex = /<br\\/>/g;\n var ret = out.replace(brregex,\"<br>\");\n return ret;\n}",
"function clean_up_html_to_show( t )\n{\n\tif ( t == \"\" || t == 'undefined' )\n\t{\n\t\treturn t;\n\t}\n\t\n\t//-------------------------------\n\t// Sort out BR tags\n\t//-------------------------------\n\t\n\tt = t.replace( /<br>/ig, \"<br />\");\n\t\n\t//-------------------------------\n\t// Remove empty <p> tags\n\t//-------------------------------\n\t\n\tt = t.replace( /<p>(\\s+?)?<\\/p>/ig, \"\");\n\t\n\t//-------------------------------\n\t// HR issues\n\t//-------------------------------\n\t\n\tt = t.replace( /<p><hr \\/><\\/p>/ig , \"<hr />\"); \n\tt = t.replace( /<p> <\\/p><hr \\/><p> <\\/p>/ig, \"<hr />\");\n\t\n\t//-------------------------------\n\t// Attempt to fix some formatting\n\t// issues....\n\t//-------------------------------\n\t\n\tt = t.replace( /<(p|div)([^&]*)>/ig , \"<br /><$1$2><br />\" );\n\tt = t.replace( /<\\/(p|div)([^&]*)>/ig , \"<br /></$1$2><br />\");\n\tt = t.replace( /<br \\/>(?!<\\/td)/ig , \"<br /><br />\" );\n\t\n\t//-------------------------------\n\t// And some table issues...\n\t//-------------------------------\n\t\n\tt = t.replace( /<\\/(td|tr|tbody|table)>/ig , \"</$1><br />\");\n\tt = t.replace( /<(tr|tbody|table(.+?)?)>/ig , \"<$1><br />\" );\n\tt = t.replace( /<(td(.+?)?)>/ig , \" <$1>\" );\n\t\n\t//-------------------------------\n\t// Newlines\n\t//-------------------------------\n\t\n\tt = t.replace( /<p> <\\/p>/ig , \"<br />\");\n\t\n\treturn t;\n}",
"function stripHtml(line) {\n\tvar ret = [];\n\n\t// Replace HTML with newlines in order to separate chunks of text withing diifferent tags.\n\tvar stripped = line.replace(reHtml, '\\n');\n\tif (stripped) {\n\t\t// Split by the newline, then push valid chunks into the return array\n\t\tvar split = stripped.split('\\n');\n\n\t\tfor (var i=0; i<split.length; i++) {\n\t\t\t// If the chunk is empty, drop it\n\t\t\tif (split[i].match(reEmpty))\n\t\t\t\tcontinue;\n\n\t\t\tif (split[i]) \n\t\t\t\tret.push(split[i]);\n\t\t}\n\t}\n\n\tif (ret.length > 0)\n\t\treturn ret;\n\n\treturn null;\n}",
"function fromHtml(html) {\n return html.replace(/<p> <\\/p>/ig, \"\\n\")\n .replace(/<p>/ig,\"\")\n .replace(/<\\/p>/ig, \"\\n\")\n .replace(/<br \\/>/ig, \"\\n\")\n .replace(/( |\\xa0|\\u2005)/ig, \" \")\n // CKEditor uses zero-width spaces as markers\n // and sometimes they leak out (on copy/paste?)\n .replace(/\\u200b+/ig, \" \")\n // fixup final </p>, which is is not a newline\n .replace(/\\n$/, \"\");\n }",
"function cleanHtml() {\n document.querySelectorAll('.clean').forEach(function(elm) {\n var newHtml = parseNode(elm).trim();\n elm.innerHTML = newHtml;\n elm.classList.remove('clean');\n });\n }",
"function escapeHTMLBr(value){\n\t// Replace with newline char \\n.\n\treplaceWith = '\\n';\n\t\n\tvar newText = value;\n\t\n\tfor(i = 0; i < newText.length; i++) {\n\t\tif(newText.indexOf(\"<br />\") > -1) {\n\t\t\tnewText=newText.replace(\"<br />\",replaceWith);\n\t\t}\n\t}\n\t\n\treturn newText;\n}",
"removeWhiteSpace() {\n const html = this.element.html().toString().trim();\n const count = (str) => {\n const re = />\\s+</g;\n return ((str || '').match(re) || []).length;\n };\n\n // Remove Whitepsace after tags\n if (count(html) > 0) {\n this.element.html(html.replace(/>\\s+</g, '><'));\n }\n }",
"_cleanHTML(html) {\n\n\t\tlet sanitized = html;\n\n\t\tsanitized = sanitized.replace(/-\\\\n/g, ' ');\n\t\tsanitized = sanitized.replace(/\\\\n|\\\\r\\\\n|\\\\r/g, '');\n\t\tsanitized = _s.clean(sanitized);\n\n\n\t\treturn sanitized;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Hook to get the current responsive mode (window size category). | function getResponsiveMode(currentWindow) {
var responsiveMode = ResponsiveMode.small;
if (currentWindow) {
try {
while (currentWindow.innerWidth > RESPONSIVE_MAX_CONSTRAINT[responsiveMode]) {
responsiveMode++;
}
}
catch (e) {
// Return a best effort result in cases where we're in the browser but it throws on getting innerWidth.
responsiveMode = getInitialResponsiveMode();
}
// Tracking last mode just gives us a better default in future renders,
// which avoids starting with the wrong value if we've measured once.
_lastMode = responsiveMode;
}
else {
if (_defaultMode !== undefined) {
responsiveMode = _defaultMode;
}
else {
throw new Error('Content was rendered in a server environment without providing a default responsive mode. ' +
'Call setResponsiveMode to define what the responsive mode is.');
}
}
return responsiveMode;
} | [
"function GetDisplayMode() {\n //DETERMINE WINDOW SIZE\n if ($(window).width() > 600 && ((CurrentDisplayMode == \"Mobile\") || (CurrentDisplayMode == \"\"))) { //ensure it doesnt run repeatedly on each similar call i.e. screen mode still on Desktop already (event bubbling)\n CurrentDisplayMode = \"Desktop\";\n }\n\n if ($(window).width() <= 600 && ((CurrentDisplayMode == \"Desktop\") || (CurrentDisplayMode == \"\"))) { //ensure it doesnt run repeatedly on each similar call i.e. screen mode still on Desktop already (event bubbling)\n CurrentDisplayMode = \"Mobile\";\n }\n }",
"function detectScreenSize(){\n\tif($.browser.mobile || isTablet){\n\t\tif (window.matchMedia(\"(orientation: landscape)\").matches) {\n\t\t\tmodeW = stageW;\n\t\t\tmodeH = stageH;\n\t\t\treturn false;\n\t\t}else{\n\t\t\tmodeW = portraitW;\n\t\t\tmodeH = portraitH;\n\t\t\treturn true;\n\t\t}\n\t}else{\n\t\tmodeW = stageW;\n\t\tmodeH = stageH;\n\t\treturn false;\n\t\t/*if($(window).width() <= 768){\n\t\t\treturn true;\t\n\t\t}else{\n\t\t\treturn false;\t\n\t\t}*/\n\t}\n}",
"function detectScreenSize() {\n if ($.browser.mobile || isTablet) {\n if (window.matchMedia(\"(orientation: landscape)\").matches) {\n modeW = stageW;\n modeH = stageH;\n return false;\n } else {\n modeW = portraitW;\n modeH = portraitH;\n return true;\n }\n } else {\n modeW = stageW;\n modeH = stageH;\n return false;\n /*if($(window).width() <= 768){\n\t\t\treturn true;\t\n\t\t}else{\n\t\t\treturn false;\t\n\t\t}*/\n }\n}",
"function detectScreenWidth() {\n if ($(window).width() < 768) {\n let zoom = 10;\n console.log('screen size is less than 768px');\n return zoom;\n } else {\n let zoom = 11;\n console.log('screen size is less than 768px');\n return zoom;\n };\n}",
"function isResponsiveMode() {\n return hasClass($body, RESPONSIVE);\n }",
"function getInitialSize() {\n if (winWidth >= 1200) {\n toggleContainer();\n }\n\n else if (winWidth < 768) {\n getSize();\n }\n}",
"function isResponsiveMode(){\n return hasClass($body, RESPONSIVE);\n }",
"function getScreenSize() {\n var width = getScreenWidth();\n var height = getScreenHeight();\n\n //Check for Mobile\n if (width < 800) {\n return \"Mobile\";\n }\n //Check for Desktop Normal\n if (width > 799) {\n return \"Desktop\";\n }\n}",
"getScreenScale() {\n return window.innerWidth / window.outerWidth;\n }",
"function getScreenDimensions() {\n var maxWidth = $(window).width();\n var maxHeight = $(window).height();\n if (maxWidth > 800) {\n if (!this.zoom) {\n this.width = 800;\n this.height = 350;\n } else {\n this.width = 1000;\n this.height = 500;\n }\n } else {\n this.height = maxHeight - 90;\n this.width = maxWidth;\n }\n}",
"function isResponsiveNeed() {\n var b = false;\n if (THEMEREX_menuResponsive > 0) {\n var a = window.innerWidth;\n if (a == undefined) {\n a = jQuery(window).width() + (jQuery(window).height() < jQuery(document).height() || jQuery(window).scrollTop() > 0 ? 16 : 0)\n }\n b = THEMEREX_menuResponsive > a\n }\n return b\n}",
"isResponsive() {\n return this._isResponsive\n }",
"function getResizeMode() {\n return internal.resizeMode;\n }",
"function the_device_width_test()\r\n {\t\r\n\t var w = window.innerWidth;\r\n\t var h = window.innerHeight;\r\n\t $('#windims').html(w+' x ' + h + '<br>');\r\n\t \r\n\t if(( $('#device_width_small').css('display') == 'none' )&&( $('#device_width_large_p').css('display') == 'none' ) ) \r\n\t { \r\n\t\t ////// The Media Queries say PORTRAIT! \r\n\t }\r\n\r\n\t if(w < h)\r\n\t {\r\n\t \t////// The Height/Width ratio says PORTRAIT! \r\n\t }\r\n\r\n\t if(w == h)\r\n\t {\r\n\t \t////// What are you using? It's weird and different an I don't like it.\r\n\t }\r\n }",
"function getViewPort() {\r\n var screen = '';\r\n if(window.innerWidth)\r\n {\r\n if (window.innerWidth > 1440) { screen = \"Extra wide\"; }\r\n else if (window.innerWidth > 1024) { screen = \"Desktop\"; }\r\n else if (window.innerWidth > 640) { screen = \"Tablet\"; }\r\n else { screen = \"Mobile\"; }\r\n }\r\n return screen;\r\n}",
"static get macFullscreenMode() {}",
"function getScreenSize(width){\n if(width >= 1200){\n return 'xlarge';\n } else if (width >= 992 && width <= 1199 ){\n return 'large';\n } else if (width >=768 && width <= 991){\n return 'medium';\n } else if (width >= 576 && width <= 767){\n return 'small';\n } else if (width <= 575){\n return 'xsmall'\n } else {\n return 'xlarge';\n }\n}",
"function getCurrentBreakpoint() {\n const width = $(document).width();\n return width < 576\n ? 'xs'\n : Object.keys(breakpoints)\n .filter((bp) => width >= breakpoints[bp])\n .reverse()[0];\n}",
"function determineCurrentScreenWidthBreakpoint () {\n\n const screenWidth = window.innerWidth\n\n let determinedBreakpoint\n\n screenWidthBreakpoints.forEach(breakpoint => {\n\n const { name, minWidth, maxWidth } = breakpoint\n\n if (screenWidth >= minWidth && screenWidth < maxWidth ) {\n\n determinedBreakpoint = breakpoint\n\n }\n\n })\n\n return determinedBreakpoint\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the function getPlayingStyle, return the team you think it has the best playing style. Run the code in the console to find out what's the secondTeam final playing style. /////////////////////// your code here | function getPlayingStyle(){
let firstTeam = [3,3,1,3];
let secondTeam = firstTeam;
firstTeam[0] = 4;
firstTeam[1] = 1;
firstTeam[2] = 4;
firstTeam[3] = 1;
return secondTeam;
} | [
"function chooseEnemyNPCPlayStyle() {\n let coinToss = random(100);\n if (coinToss > 50) {\n playStyle = \"aggro\"\n }\n else {\n playStyle = \"passive\"\n }\n}",
"function switchTeams() {\n // Determine the current team\n if(playerOne) {\n playerColour = \"#F07167\";\n playerName = \"One\";\n playerOne = false;\n }\n else {\n playerColour = \"#5386E4\";\n playerName = \"Two\";\n playerOne = true;\n }\n}",
"getCrossOverGames() {\n\t\tlet crossovergames = \"Will display crossover games\" + `${View.NEWLINE()}`\n\t\t// allGames will have multiple lists inside as there are more than one week of games\n\t\tfor (let eachWeek of this.allGames){\n\t\t\t// and get each games from each week\n\t\t\tfor (let teamGame of eachWeek){\n\t\t\t\t// as crossover is between Championship and Premiership, so we have to check\n\t\t\t\t// both home and away.\n\t\t\t\t// I also made a list called allPDRanks, allCDRanks so I can use includes\n\t\t\t\t// builtin function to find whether this list contains the rank we are\n\t\t\t\t// looking\n\t\t\t\tif ((this.allPDRanks.includes(teamGame[\"homeTeamRank\"]) &&\n\t\t\t\t\t\t\tthis.allCDRanks.includes(teamGame[\"awayTeamRank\"]))\n\t\t\t\t\t\t||\n\t\t\t\t\t\t(this.allCDRanks.includes(teamGame[\"homeTeamRank\"]) &&\n\t\t\t\t\t\t\t\t\tthis.allPDRanks.includes(teamGame[\"awayTeamRank\"]))){\n\t\t\t\t\t// again, change time to readable, understandable time format\n\t\t\t\t\tlet newDate = new Date(teamGame.dateTime).toDateString()\n\t\t\t\t\tcrossovergames += newDate + `${View.SPACE()}`\n\t\t\t\t\t// getting time like 7:35PM\n\t\t\t\t\t// was gonna use navigator.language instead of en-US but it comes up with korean\n\t\t\t\t\t// even thought default language is ENG\n\t\t\t\t\tlet newTime = new Date(teamGame.dateTime).toLocaleTimeString(\"en-US\", {hour: \"numeric\", minute: \"numeric\"})\n\n\t\t\t\t\tcrossovergames += newTime + `${View.SPACE()}`\n\n\t\t\t\t\tcrossovergames += \"Week:\" + teamGame.week\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ `${View.SPACE()}`\n\t\t\t\t\t\t\t\t\t\t\t\t\t// unlike other method, its comparing between Premiership and Championship\n\t\t\t\t\t\t\t\t\t\t\t\t\t// I decided to print out their rank so you can see clearly that those outputs are crossover games.\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ \"Team: rank:\" + teamGame.homeTeamRank + `${View.SPACE()}` + this.allTeams[teamGame.homeTeamRank - 1].name\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ `${View.SPACE()}`\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ \"vs\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ `${View.SPACE()}`\n\t\t\t\t\t\t\t\t\t\t\t\t\t// again, getting away teams rank and their team name.\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ \"rank:\" + teamGame.awayTeamRank + `${View.SPACE()}` + this.allTeams[teamGame.awayTeamRank - 1].name\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ `${View.SPACE()}`\n\t\t\t\t\t\t\t\t\t\t\t\t\t// getting hometeam's venue\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ \"At: \" + this.allTeams[teamGame.homeTeamRank -1].venue\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ `${View.SPACE()}`\n\t\t\t\t\t\t\t\t\t\t\t\t\t// getting hometeams' city\n\t\t\t\t\t\t\t\t\t\t\t\t\t+ this.allTeams[teamGame.homeTeamRank -1].city\n\t\t\t\t\t \t\t\t\t\t\t\t\t+ `${View.NEWLINE()}`\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn crossovergames\n\t}",
"getCrossOverGames () {\n let crossovergames = 'Will display crossover games' + `${View.NEWLINE()}`\n// allGames will have multiple lists inside as there are more than one week of games\n for (let eachWeek of this.allGames) {\n// and get each games from each week\n for (let teamGame of eachWeek) {\n// as crossover is between Championship and Premiership, so we have to check\n// both home and away.\n// I also made a list called allPDRanks, allCDRanks so I can use includes\n// builtin function to find whether this list contains the rank we are\n// looking\n if ((this.allPDRanks.includes(teamGame['homeTeamRank']) && this.allCDRanks.includes(teamGame['awayTeamRank'])) || (this.allCDRanks.includes(teamGame['homeTeamRank']) && this.allPDRanks.includes(teamGame['awayTeamRank']))) {\n// again, change time to readable, understandable time format\n let newDate = new Date(teamGame.dateTime).toDateString()\n crossovergames += newDate + `${View.SPACE()}`\n// getting time like 7:35PM\n// was gonna use navigator.language instead of en-US but it comes up with korean\n// even thought default language is ENG\n let newTime = new Date(teamGame.dateTime).toLocaleTimeString('en-US', {hour: 'numeric', minute: 'numeric'})\n\n crossovergames += newTime + `${View.SPACE()}`\n\n crossovergames += 'Week:' + teamGame.week + `${View.SPACE()}` + 'Team: rank:' + teamGame.homeTeamRank + `${View.SPACE()}` + this.allTeams[teamGame.homeTeamRank - 1].name + `${View.SPACE()}` + 'vs' + `${View.SPACE()}` + 'rank:' + teamGame.awayTeamRank + `${View.SPACE()}` + this.allTeams[teamGame.awayTeamRank - 1].name + `${View.SPACE()}` + 'At: ' + this.allTeams[teamGame.homeTeamRank - 1].venue + `${View.SPACE()}` + this.allTeams[teamGame.homeTeamRank - 1].city + `${View.NEWLINE()}`\n }\n }\n }\n return crossovergames\n }",
"function stylePicker(){ \n push();\n clear();\n background(0);\n pop();\n\n // add heading\n push();\n fill(120, 120, 120, 90);\n rect(0,0,width, height/6);\n textSize(40);\n fill(255, 90, 90);\n stroke(10,70,190);\n strokeWeight(5);\n text('Stage Two : Choose Visualization Style ', width/4+width/20, height/10);\n textSize(20);\n stroke(2);\n text('* ( Click on the play button to see the style ) ', width/7*6, height/8);\n pop();\n \n // button of each style\n push();\n fill(180,180,180,90);\n ellipse(width/4, height/2, width/8,width/8);\n ellipse(width/2, height/2, width/8,width/8);\n ellipse(width/4*3, height/2, width/8,width/8);\n pop();\n\n // set mouse-over effect\n mouseOverStyle();\n\n // set click-on effect for displaying style\n if(playing1 == true){\n generateStyle(1);\n button4.show();\n }\n if(playing2 == true){\n generateStyle(2);\n button4.show();\n }\n if(playing3 == true){\n generateStyle(3);\n button4.show();\n }\n\n // set click-on effect -- which means current selected style\n if(styleChosen1 == true){\n selectedStyle = 1;\n findStyle(width/4, 'Style 1');\n button5.show(); \n button6.hide(); \n button7.hide();\n }\n if(styleChosen2 == true){\n selectedStyle = 2;\n findStyle(width/2, 'Style 2');\n button6.show(); \n button5.hide(); \n button7.hide();\n }\n if(styleChosen3 == true){\n selectedStyle = 3;\n findStyle(width/4*3, 'Style 3');\n button7.show(); \n button5.hide(); \n button6.hide();\n }\n\n\n}",
"calculateSpreadWinner(homeScore, awayScore, homeAbbreviation, awayAbbreviation, favoredTeam, spread) {\n\n //corner case - checking if the game was a pick-em\n if (spread === 0) {\n if (homeScore > awayScore) {\n return homeAbbreviation;\n }\n if (awayScore > homeScore) {\n return awayAbbreviation;\n }\n return \"P\";\n }\n\n //if home team is favored\n if (favoredTeam === homeAbbreviation) {\n if (homeScore - awayScore > spread) {\n return homeAbbreviation;\n } else if (homeScore - awayScore < spread) {\n return awayAbbreviation;\n }\n return \"P\";\n }\n\n //if away team is favored\n else if (favoredTeam === awayAbbreviation) {\n if (awayScore - homeScore > spread) {\n return awayAbbreviation;\n } else if (awayScore - homeScore < spread) {\n return homeAbbreviation;\n }\n return \"P\";\n }\n\n //if neither favored\n else {\n if (homeScore - awayScore !== 0) {\n let highestScore = Math.max(homeScore, awayScore);\n if (homeScore === highestScore) {\n return homeAbbreviation;\n } else if (awayScore === highestScore) {\n return awayAbbreviation;\n }\n return \"P\";\n }\n }\n }",
"function getTeamColor(team) {\n switch(team.substring(0, 3)) {\n case 'BOS': return '#c60c30';\n case 'BSN': return '#002f5f';\n case 'CHC': return '#003279';\n case 'CHW': return '#c0c0c0';\n case 'CIN': return '#c6011f';\n case 'CLE':\n case 'CLV': return '#d30335';\n case 'DET': return '#001742';\n case 'HOU': return '#072854';\n case 'LAA': return '#b71234';\n case 'BRO':\n case 'LAD': return '#083c6b';\n case 'NYM': return '#002c77';\n case 'NYY': return '#1c2841';\n case 'PHA':\n case 'PHI': return '#ba0c2f';\n case 'PIT': return '#fdb829';\n case 'SFG':\n case 'NYG': return '#f2552c';\n case 'SLB':\n case 'SLM':\n case 'STL': return '#c41e3a';\n case 'TOR': return '#003da5';\n case 'WSH': return '#ba122b';\n default: return '#0000ff'; // blue as default\n }\n}",
"function setTeam(TeamName){\n \t\tswitch(TeamName)\n \t\t{\n \t\t\tcase \"Portland Trail Blazers\":\n \t\t\t\treturn {style:\"blazers\", logo:\"images/pl.png\"}; \n \t\t\tbreak;\n \t\t\tcase \"Los Angeles Clippers\":\n \t\t\t\treturn {style:\"clippers\", logo:\"images/clp.png\"}; \n \t\t\tbreak;\n \t\t\tcase \"Charlotte Hornets\":\n \t\t\t\treturn {style:\"hornets\", logo:\"images/cha.png\"}; \n \t\t\tbreak;\n \t\t\tcase \"Milwaukee Bucks\":\n \t\t\t\treturn {style:\"bucks\", logo:\"images/mil.png\"}; \n \t\t\tbreak;\n \t\t\tcase \"Miami Heat\":\n \t\t\t\treturn {style:\"heat\", logo:\"images/mh.png\"}; \n \t\t\tbreak;\n \t\t\tcase \"Brooklyn Nets\":\n \t\t\t\treturn {style:\"nets\", logo:\"images/bn.png\"}; \n \t\t\tbreak;\n \t\t\tcase \"New York Knicks\":\n \t\t\t\treturn {style:\"nicks\", logo:\"images/nyn.png\"}; \n \t\t\tbreak;\n \t\t\tcase \"Memphis Grizzlies\":\n \t\t\t\treturn {style:\"grizzlies\", logo:\"images/griz.png\"}; \n \t\t\tbreak;\n\t break;\n\t \t case \"Golden State Warriors\":\n\t \t return {style:\"Warriors\", logo:\"images/gs.png\"}; \n\t \tbreak;\n \t\t\tdefault: \n \t\t}\n\n \t}",
"constructor(mode,lang,Team1Name,Team1NbPlayers,Team2Name,Team2NbPlayers) { //Precise if the game is competitive, cooperative, solo..\n\t\tthis.mode=mode;\n\t\tthis.language=lang;\n\t\tthis.gameEnd=false\n\t\tthis.turn=\"master\";//master or player\n\t\t//this.setTeam(\"Black\",\"Trap\",0); //non playable teams to represent grey and black cards\n\t\t//this.setTeam(\"Grey\",\"Neutral\",0);\n\t\tthis.teams=new Array();\n\t\tthis.setTeam(\"Red\",Team2Name,Team2NbPlayers);//[Blue,Red]\n\t\tthis.setTeam(\"Blue\",Team1Name,Team1NbPlayers);\n\t\tthis.board=this.createBoard();\n\t\tthis.currentTeam=this.board.getFirstTeam(); //\"Blue\" or \"Red\"\n\t\tconsole.log(\"firsTeam=\"+this.currentTeam);\n\t\tthis.currentTeam=this.currentTeam==\"Blue\"?1:0;\n\t\t//this.currentTeam=1;\n\t\t//this.teams[this.board.getFirstTeam()==\"Blue\"?0:1].AddScore(-1);//First team has 1 more card\n\t}",
"function tournamentWinner(competitions, results) {\n // Write your code here.\n // Need a way to keep track of each team's score\n let highestScore = 0;\n let bestTeam = '';\n let teamScores = {};\n for (let i = 0; i < competitions.length; i ++) {\n // If results at i = 1 then competitions at i at 0 gets 3 points --> home team wins\n console.log('Results at i: ', results[i]);\n console.log('Competitions at i: ', competitions[i][0]);\n if (results[i] === 1) {\n // Need to see if team exists in object - if exists then add 3 if not then create new key\n if (!teamScores[competitions[i][0]]) {\n teamScores[competitions[i][0]] = 3;\n teamScores[competitions[i][1]] = 0;\n } else {\n teamScores[competitions[i][0]] += 3;\n }\n if (teamScores[competitions[i][0]] > highestScore) {\n highestScore = teamScores[competitions[i][0]];\n bestTeam = competitions[i][0];\n }\n }\n // If results at i = 0 then competitions at i at 1 gets 3 points --> away team wins\n if (results[i] === 0) {\n if (!teamScores[competitions[i][1]]) {\n teamScores[competitions[i][0]] = 0;\n teamScores[competitions[i][1]] = 3;\n } else {\n teamScores[competitions[i][1]] += 3;\n }\n if (teamScores[competitions[i][1]] > highestScore) {\n highestScore = teamScores[competitions[i][1]];\n bestTeam = competitions[i][1];\n }\n }\n }\n return bestTeam;\n}",
"whoHasHighestScore() {\n //See who has the highest score\n let highestScore = 0;\n let winner = \"\";\n for (var i = 0; i < 2; i++) {\n let playerScore = this.players[i].getScore();\n let teammateScore = this.players[this.getTeammateIndex(i)].getScore();\n let teamScore = playerScore + teammateScore;\n\n if (teamScore > highestScore) {\n highestScore = teamScore;\n winner = this.players[i].getShape();\n }\n }\n return winner;\n }",
"gameWinner() {\n if(window.player1.playerScore >= this.bestOfValue || window.player2.playerScore >= this.bestOfValue){\n this.gameOver();\n if(this.player === 'red'){\n return window.playerOneName;\n }else{\n return window.playerTwoName;\n }\n }else{\n return;\n }\n }",
"function get_team_color(team) {\n var color = \"green\";\n switch(team) {\n case \"broncos\":\n color = \"#FB4F14\";\n break;\n case \"seahawks\":\n color = \"#71D54A\";\n break;\n case \"chiefs\":\n color = \"#C60C30\";\n break;\n case \"pats\":\n color = \"#002244\";\n break;\n case \"niners\":\n color = \"#AA0000\";\n break;\n case \"panthers\":\n color = \"#0088CE\";\n break;\n case \"saints\":\n color = \"#B4A76C\";\n break;\n default:\n color = \"pink\";\n }\n return color;\n}",
"function getPlayerColor() {\r const gameBoard = document.querySelector('.board');\r var gameBoardClasses = gameBoard.className.split(' ');\r if (gameBoardClasses.includes('flipped')){\r playerColor = \"b\";\r }\r else{\r playerColor = \"w\";\r }\r return playerColor;\r}",
"getCanterburyGames (teamName) {\n// find the rank of the team we want, as I dont want to use magic number. futureproof\n for (let aTeam of this.allTeams) {\n if (aTeam['name'] === teamName) {\n var aRank = aTeam['rank']\n }\n }\n// again, fufure proofing print line, instead of fixed string with Canterbury\n let specificTeam = 'Will only display ' + teamName + ' team games' + `${View.NEWLINE()}`\n// allGames will have multiple lists inside as there are more than one week of games\n for (let eachWeek of this.allGames) {\n// and get each games from each week\n for (let specificTeamGame of eachWeek) {\n if (specificTeamGame['homeTeamRank'] === aRank || specificTeamGame['awayTeamRank'] === aRank) {\n// converting time into string, readable time format\n let newDate = new Date(specificTeamGame.dateTime).toDateString()\n specificTeam += newDate + `${View.SPACE()}`\n// getting time like 7:35PM\n// was gonna use navigator.language instead of en-US but it comes up with korean\n// even thought default language is ENG\n let newTime = new Date(specificTeamGame.dateTime).toLocaleTimeString('en-US', {hour: 'numeric', minute: 'numeric'})\n\n specificTeam += newTime + `${View.SPACE()}`\n\n specificTeam += 'Week:' + specificTeamGame.week + `${View.SPACE()}` + 'Team: ' + this.allTeams[specificTeamGame.homeTeamRank - 1].name + `${View.SPACE()}` + 'v' + `${View.SPACE()}` + this.allTeams[specificTeamGame.awayTeamRank - 1].name + `${View.SPACE()}` + 'At: ' + this.allTeams[specificTeamGame.homeTeamRank - 1].venue + `${View.SPACE()}` + this.allTeams[specificTeamGame.homeTeamRank - 1].city + `${View.NEWLINE()}`\n }\n }\n }\n return specificTeam\n }",
"function stylingChanges() { \n let selectorStart = document.getElementById(\"selector-start\");\n selectorStart.classList.remove(\"min-width\", \"selector-start-onload\");\n selectorStart.classList.add(\"absolute\");\n difficulty.classList.remove(\"cairo\", \"text-medium\", \"bg-green\");\n difficulty.classList.add(\"bg-black\");\n let playIcon = document.getElementById(\"play-icon\");\n playIcon.classList.remove(\"text-big\");\n playIcon.classList.add(\"score-bar-bg\");\n let outerContainer = document.getElementById(\"outer-container\");\n outerContainer.classList.remove(\"margin-top-big\");\n outerContainer.classList.add(\"margin-top-small\");\n let callToPlay = document.getElementById(\"call-to-play\");\n callToPlay.innerHTML = \"\";\n let scoreBar = document.getElementById(\"score-bar\");\n scoreBar.classList.add(\"score-bar-bg\");\n let play = document.getElementById(\"play\");\n play.classList.add(\"score-bar-bg\");\n let flagContianer = document.getElementById(\"flag-container\");\n flagContianer.classList.remove(\"invisible-text\");\n flagContianer.classList.add(\"text-red\");\n let bombsMotif = document.getElementsByClassName(\"bombs-motif\");\n for (item of bombsMotif) {\n item.classList.add(\"hide\");\n }\n}",
"function calculateWinner(gameId){\n let contents = loadGameFileContents(gameId);\n let [player1Time, player2Time] = calculateMoveTime(contents);\n let teams = contents.state.teams;\n let player1 = teams.filter(team => team.id == 0);\n let player2 = teams.filter(team => team.id == 1);\n console.log( player1[0].name + \" took \" + player1Time);\n console.log( player2[0].name + \" took \" + player2Time);\n if (player1Time > player2Time){\n console.log(\"Winner is \" + player2[0].name);\n console.log(\"Player ID is \" + player2[0].playerId)\n\n }\n else if (player2Time > player1Time){\n console.log(\"Winner is \" + player1[0].name);\n console.log(\"Player ID is \" + player1[0].playerId)\n }\n else {\n console.log(\"Wooooooow it's a draw?!?!?!\")\n }\n \n\n}",
"function getBlueTeam() {\n var blueTeam = room.getPlayerList().filter((player) => player.team == 2);\n return blueTeam;\n}",
"function checkTeam() {\n //wait until you'be been assigned to a team and the tiles have been loaded. \n if (!tagpro.players[tagpro.playerId] | !tagpro.tiles) {\n return setTimeout(checkTeam,0);\n }\n\n //if the team color you've been assigned to is different from your preference, switch team colored tiles\n teamId = tagpro.players[tagpro.playerId].team;\n if (teamId != colorId[teamColor]) {\n tagpro.switchedColors = true;\n switchTiles();\n\n }\n setTimeout(checkSwitchTeam, 5000);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
a value that indicate whether the current window context is a parent one | function useParentContextOrNot() {
return ((nt.useParentContext == 'auto') && (parent != this))
|| (nt.useParentContext == 'yes');
} | [
"function getIsParent() {\n // top level variables should not be exported for performance reasons (PERF_NOTES.md)\n return isParent;\n }",
"parentFrame() {\n return this.sameTargetParentFrame() || this.crossTargetParentFrame();\n }",
"get parentWindow() {\r\n return this._parentWindow;\r\n }",
"isTopLevelContext() {\n return this.#parentId === null;\n }",
"get windowParent() {\n\t\treturn this.nativeElement ? this.nativeElement.windowParent : undefined;\n\t}",
"isToplevel() {\n return this.enclosingEnvironment() === null;\n }",
"function isEocComingFromParent(context) {\n // To determine the direction we check callerId property which is set to the parent bot\n // by the BotFrameworkHttpClient on outgoing requests.\n return !!context.activity.callerId;\n}",
"function getIsParentExplicit() {\n\n var isExplicit = false;\n\n if (scope.parentControl) {\n\n var container = spFormBuilderService.isExplicitContainer(scope.parentControl);\n if (container && container !== false) {\n\n isExplicit = true;\n }\n }\n\n return isExplicit;\n }",
"function isPoEWindow() {\n return getPoEWindow() !== undefined;\n}",
"hasParent(){\n return this.getParent() != null;\n }",
"function getParentWindow()\r\n {\r\n \tif(typeof document.parentWindow == 'undefined') {\r\n \t\treturn document.defaultView;\r\n \t} else {\r\n \t\treturn document.parentWindow;\r\n \t}\r\n }",
"parentFrame() {\n return this._frameManager._frameTree.parentFrame(this._id) || null;\n }",
"function isIframe() {\r\n return IS_WEB && window.parent !== window;\r\n }",
"componentIsInParentScopeForManagerCurrentWp(type, parentName, name){\n server.call('verifyWorkPackageComponents.currentWpComponentIsInParentScope', type, parentName, name, 'miles',\n (function(error, result){\n return(error === null);\n })\n )\n }",
"get isTopLevel() {\n // XXX: This is absolutely not how you find out if the space is top level\n // but is safe for a managed usecase like we offer in the SDK.\n const parentEvents = this.room.currentState.getStateEvents(_event.EventType.SpaceParent);\n if (!parentEvents?.length) return true;\n return parentEvents.every(e => !e.getContent()?.['via']);\n }",
"sameTargetParentFrame() {\n return this.#sameTargetParentFrameInternal;\n }",
"isTopWindow() {\n return window.top === window.self;\n }",
"function isChildWindowOpen()\n{\n\tif (childWindows != null)\n\t{\n\t\tif (childWindows.closed)\n\t\t{\n\t\t\tchildWindows = null;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}",
"function isParentSameOrigin () {\n try {\n // May throw an exception if `window.opener` is on another origin\n return window.opener.location.origin === window.location.origin\n } catch (err) {\n return false\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If we're searching, update the filter results. (If we stop searching, we're going to end up in the onFolderDisplayMessagesLoaded notification. Mayhaps we should lose that vector and just use this one.) | onSearching(aFolderDisplay, aIsSearching) {
// we only care if we just started searching and we are active
if (!aIsSearching || !aFolderDisplay.active) {
return;
}
// - Update match status.
this.reflectFiltererResults(this.activeFilterer, aFolderDisplay);
} | [
"updateDisplayedMessages() {\n this.setState((prevState) => {\n let { storedMessages, filterText, displayedMessages, currentFolderID } = prevState;\n displayedMessages = storedMessages.filter((messageItem) => {\n if (messageItem.subject.toLowerCase().indexOf(filterText) === -1 &&\n messageItem.from.toLowerCase().indexOf(filterText) === -1)\n return false;\n if (messageItem.folderID !== currentFolderID)\n return false;\n return messageItem;\n });\n return {displayedMessages: displayedMessages};\n });\n }",
"function onFolderListDialogCallback(searchFolderURIs) {\n gSearchFolderURIs = searchFolderURIs;\n updateFoldersCount();\n updateOnlineSearchState(); // we may have changed the server type we are searching...\n}",
"function updateSearch()\n\t{\n\t\t// Start with fresh copy.\n\t\tvar filteredItems = items;\n\t\t\n\t\tif (filters.length)\n\t\t{\n\t\t\tfor (var i = 0; i < filters.length; i++)\n\t\t\t{\n\t\t\t\tvar filter = filters[i];\n\t\t\t\tfilteredItems = filterItem(filter, filteredItems);\n\t\t\t}\n\t\t}\n\t\t\n\t\t// If there's entry to search then search else skip it.\n\t\tif (searchEntry) convertString(searchEntry, filteredItems);\n\t\telse verifyManage(filteredItems);\n\t}",
"function updateList() {\n\n\tvar filter = search.text.toLowerCase();\n\n\telList.removeAll();\n\n\tfor(var i in allElements) {\n\n\t\tvar e = allElements[i];\n\t\tif(!filter || e.displayName.toLowerCase().indexOf(filter) !== -1) {\n\t\t\tvar item = elList.add(\"item\", stripExt(e.displayName));\n\t\t\tif(e instanceof Folder) {\n\t\t\t\titem.text += \" \\u00BB\";\n\t\t\t}\n\t\t\titem.file_object = e;\n\t\t}\n\n\t}\n\n}",
"function updateMessageSearch() {\n var criteria = $('#message-search').val();\n if (criteria.length < 2) {\n $('.message-list-entry').show();\n return;\n }\n criteria = criteria.toLowerCase();\n for (i=0; i<messageListData.length; i++) {\n entry = messageListData[i];\n if ((entry.subject.toLowerCase().indexOf(criteria) > -1) ||\n (entry.from.toLowerCase().indexOf(criteria) > -1)) {\n // Match\n $('#' + entry.id).show();\n } else {\n $('#' + entry.id).hide();\n }\n }\n}",
"reflectFiltererResults(aFilterer, aFolderDisplay) {\n let view = aFolderDisplay.view;\n let threadPane = document.getElementById(\"threadTree\");\n let qfb = document.getElementById(\"quick-filter-bar\");\n\n // bail early if the view is in the process of being created\n if (!view.dbView) {\n return;\n }\n\n // no filter active\n if (!view.search || !view.search.userTerms) {\n threadPane.removeAttribute(\"filterActive\");\n qfb.removeAttribute(\"filterActive\");\n } else if (view.searching) {\n // filter active, still searching\n // Do not set this immediately; wait a bit and then only set this if we\n // still are in this same state (and we are still the active tab...)\n setTimeout(function() {\n if (\n !view.searching ||\n QuickFilterBarMuxer.maybeActiveFilterer != aFilterer\n ) {\n return;\n }\n threadPane.setAttribute(\"filterActive\", \"searching\");\n qfb.setAttribute(\"filterActive\", \"searching\");\n }, 500);\n } else if (view.dbView.numMsgsInView) {\n // filter completed, results\n // some matches\n threadPane.setAttribute(\"filterActive\", \"matches\");\n qfb.setAttribute(\"filterActive\", \"matches\");\n } else {\n // filter completed, no results\n // no matches! :(\n threadPane.setAttribute(\"filterActive\", \"nomatches\");\n qfb.setAttribute(\"filterActive\", \"nomatches\");\n }\n }",
"onMessageCountsChanged(aFolderDisplay) {\n this._update(aFolderDisplay);\n }",
"onMessagesRemoved() {\n // result text is only for when we are not searching\n if (!this.view.searching) {\n this.updateStatusResultText();\n }\n this.__proto__.__proto__.onMessagesRemoved.call(this);\n }",
"function filterChanged() {\n\t\t\tthis.fireEvent(\"filterChanged\", \"FolderFilters\", this.suspendUpdate);\n\t\t}",
"function updateFilteredSearch(){\n \n if(typeof searchPnt != \"undefined\")\n findProviders(providerFS, searchPnt)\n }",
"function filterDirectory() {\n\tlogTrace('invoking filterDirectory()');\n\n\tif (filterRunning === true) {\n\n\t\tlogWarn('Filter already running.');\n\t\treturn [];\n\t}\n\tfilterRunning = true;\n\n\tconst currentItems = getItems();\n\n\tlet remainingItems = [];\n\tif (currentItems.length > 0) {\n\n\t\tremainingItems = filterItems(storedBlacklistedItems, currentItems);\n\t}\n\tfilterRunning = false;\n\n\tif (remainingItems.length < currentItems.length) {\n\n\t\tlogVerbose('Attempting to re-populate items.');\n\t\ttriggerScroll();\n\t}\n\n\treturn remainingItems;\n}",
"onSearchOrPrintersChanged_() {\n if (!this.nearbyPrinters) {\n return;\n }\n // Filter printers through |searchTerm|. If |searchTerm| is empty,\n // |filteredPrinters_| is just |nearbyPrinters|.\n const updatedPrinters = this.searchTerm ?\n this.nearbyPrinters.filter(\n item => matchesSearchTerm(item.printerInfo, this.searchTerm)) :\n this.nearbyPrinters.slice();\n\n updatedPrinters.sort(sortPrinters);\n\n this.updateList(\n 'filteredPrinters_', printer => printer.printerInfo.printerId,\n updatedPrinters);\n }",
"_onSearchTextChanged () {\n let searchedText = this.searchEntry.get_text().toLowerCase();\n\n if(searchedText === '') {\n this._getAllIMenuItems().forEach(function(mItem){\n mItem.actor.visible = true;\n });\n }\n else {\n this._getAllIMenuItems().forEach(function(mItem){\n let text = mItem.clipContents.toLowerCase();\n let isMatching = text.indexOf(searchedText) >= 0;\n mItem.actor.visible = isMatching\n });\n }\n }",
"function update_viewport_filter_now() {\n update_subject_status_is();\n update_visible_subject_icons();\n update_subject_list(); \n}",
"function syncSearch() {\n app.searchWidget.view = app.activeView;\n if (app.searchWidget.selectedResult) {\n app.searchWidget.search(app.searchWidget.selectedResult.name);\n app.activeView.popup.reposition();\n }\n }",
"function filterDirectory() {\n\tlogTrace('invoking filterDirectory()');\n\n\t// prevent filtering more than once at the same time\n\tif (filterRunning === true) {\n\n\t\tlogWarn('Filter already running.');\n\t\treturn [];\n\t}\n\tfilterRunning = true;\n\n\tconst currentItems = getItems();\n\n\tlet remainingItems = [];\n\tif (currentItems.length > 0) {\n\n\t\tremainingItems = filterItems(currentItems);\n\t}\n\tfilterRunning = false;\n\n\tif (remainingItems.length < currentItems.length) {\n\n\t\tif (currentItemType !== 'frontpage') {\n\n\t\t\tlogVerbose('Attempting to re-populate items.');\n\t\t\ttriggerScroll();\n\t\t}\n\t}\n\n\treturn remainingItems;\n}",
"onSearchTextChanged () {\n let searchedText = this.searchEntry.get_text().toLowerCase();\n\n if (searchedText === '') {\n this.getAllIMenuItems().forEach(function(mItem){\n mItem.actor.visible = true;\n });\n } else {\n this.getAllIMenuItems().forEach(function(mItem){\n let text = mItem.clipContents.toLowerCase();\n let isMatching = text.indexOf(searchedText) >= 0;\n mItem.actor.visible = isMatching\n });\n }\n }",
"function refreshMailList() {\n\t\treturn performSearch();\n\t}",
"_messageCountsChanged(aFolder) {\n if (aFolder == this.displayedFolder) {\n this.listener.onMessageCountsChanged();\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Client class proxying the incoming OData request to the upstream XSOData the incoming XSOData response to the downstream OData client and applying the added decorator types. Decorator classes are instantiated per request entity and subentity (in case of $batch requests). The tombstone filter decorator is always applied, so that tombstones of harddeleted entities never leak to the client. | function Client(destination) {
Object.defineProperties(this, {
"request": {
value: new WebRequest($.request, destination)
},
"destination": {
value: destination
},
"decoratorClasses": {
value: [TombstoneFilterDecorator]
}
});
} | [
"function TombstoneFilterDecorator(request, metadataClient) {\n\tif(!request) throw 'Missing required attribute request\\nat: ' + new Error().stack;\n\tif(!metadataClient) throw 'Missing required attribute metadataClient\\nat: ' + new Error().stack;\n\t\n\tvar traceTag = 'TombstoneFilterDecorator.init.' + request.id;\n\tPerformance.trace('Creating tombstone filter decorator ' + request.id, traceTag);\n\t\n\tDecorator.call(this, request, metadataClient, TombstoneFilterPreProcessor, null);\n\t\n\tPerformance.finishStep(traceTag);\n}",
"static decorateNodeRestClient(client, args) {\n if (!this.isActive(args)) {\n return client;\n }\n\n const perfActionId = args.__ow_headers[this.const.PERF_ACTION_ID] || args.__ow_headers[this.const.PERF_ACTION_ID.toLowerCase()];\n args.uri = '';\n\n const decorate = function (fn, method, url, parameters, callback) {\n args.method = method.toUpperCase();\n const cb = callback;\n callback = function (params) {\n cb(params);\n PerformanceMeasurement.endBackendRequest(args, currentRequestNumber, perfActionId);\n };\n\n const currentRequestNumber = args.backendRequestCount++;\n PerformanceMeasurement.startBackendRequest(args, currentRequestNumber, perfActionId, url);\n fn(url, parameters, callback);\n };\n\n const wrapper = function (fn, method) {\n return function (url, parameters, callback) {\n decorate(fn, method, url, parameters, callback);\n };\n };\n\n const methods = ['get', 'put', 'post', 'delete'];\n for (let i = 0, l = methods.length; i < l; i++) {\n const method = methods[i];\n client[method] = wrapper(client[method], method);\n }\n\n return client;\n }",
"decorate () {\n let [model, decorator_names] = parseParams(arguments);\n\n return decorate.call (this, model, decorator_names);\n }",
"_applyInterceptors() {\n this._getInterceptors().map(middleware => {\n this.client.applyInterceptorRequest(middleware);\n });\n }",
"_decorateRequest () {\n this.server.decorate('request', 'session', (request) => this._sessionDecoration(request), {\n apply: true // ensure the \"request.session\" decoration for each request\n })\n }",
"function ProxyRequestor(client) {\n this.client = client;\n}",
"clientSideStreaming(client, inputs, md, requestStartTime) {\n const call = client[this.protoInfo.methodName](md, (err, response) => {\n this.handleUnaryResponse(err, response, requestStartTime)\n })\n\n if (inputs && Array.isArray(inputs.stream)) {\n inputs.stream.forEach((data) => {\n call.write(data)\n })\n } else {\n call.write(inputs)\n }\n\n if (!this.interactive) {\n call.end()\n }\n\n return call\n }",
"function resourceDecorator(requestHeaders) {\n return function(rsc) {\n rsc.$post = function() {\n arguments.length = Math.max(4, arguments.length);\n arguments[3] = _.mergeLeft({headers: requestHeaders}, arguments[3] || {});\n return rsc.$request().$post.apply(undefined, arguments)\n .then(resourceDecorator(requestHeaders));\n };\n rsc.$get = function() {\n arguments.length = Math.max(3, arguments.length);\n arguments[2] = _.mergeLeft({headers: requestHeaders}, arguments[2] || {});\n return rsc.$request().$get.apply(undefined, arguments)\n .then(resourceDecorator(requestHeaders));\n };\n rsc.$put = function() {\n arguments.length = Math.max(4, arguments.length);\n arguments[3] = _.mergeLeft({headers: requestHeaders}, arguments[3] || {});\n return rsc.$request().$put.apply(undefined, arguments)\n .then(resourceDecorator(requestHeaders));\n };\n rsc.$delete = function() {\n arguments.length = Math.max(3, arguments.length);\n arguments[2] = _.mergeLeft({headers: requestHeaders}, arguments[2] || {});\n return rsc.$request().$delete.apply(undefined, arguments)\n .then(resourceDecorator(requestHeaders));\n };\n return rsc;\n };\n }",
"function OverriddenClientRequest(...args) {\n const { options, callback } = common.normalizeClientRequestArgs(...args)\n\n if (Object.keys(options).length === 0) {\n // As weird as it is, it's possible to call `http.request` without\n // options, and it makes a request to localhost or somesuch. We should\n // support it too, for parity. However it doesn't work today, and fixing\n // it seems low priority. Giving an explicit error is nicer than\n // crashing with a weird stack trace. `http[s].request()`, nock's other\n // client-facing entry point, makes a similar check.\n // https://github.com/nock/nock/pull/1386\n // https://github.com/nock/nock/pull/1440\n throw Error(\n 'Creating a ClientRequest with empty `options` is not supported in Nock'\n )\n }\n\n http.OutgoingMessage.call(this)\n\n // Filter the interceptors per request options.\n const interceptors = interceptorsFor(options)\n\n if (isOn() && interceptors) {\n debug('using', interceptors.length, 'interceptors')\n\n // Use filtered interceptors to intercept requests.\n // TODO: this shouldn't be a class anymore\n // the overrider explicitly overrides methods and attrs on the request so the `assign` below should be removed.\n const overrider = new InterceptedRequestRouter({\n req: this,\n options,\n interceptors,\n })\n Object.assign(this, overrider)\n\n if (callback) {\n this.once('response', callback)\n }\n } else {\n debug('falling back to original ClientRequest')\n\n // Fallback to original ClientRequest if nock is off or the net connection is enabled.\n if (isOff() || isEnabledForNetConnect(options)) {\n originalClientRequest.apply(this, arguments)\n } else {\n common.setImmediate(\n function () {\n const error = new NetConnectNotAllowedError(\n options.host,\n options.path\n )\n this.emit('error', error)\n }.bind(this)\n )\n }\n }\n }",
"async applyRequestInterceptors(domainObject, request) {\n const interceptors = this.#getInterceptorsForRequest(domainObject.identifier, request);\n\n if (interceptors.length === 0) {\n return request;\n }\n\n let modifiedRequest = { ...request };\n\n for (let interceptor of interceptors) {\n modifiedRequest = await interceptor.invoke(modifiedRequest);\n }\n\n return modifiedRequest;\n }",
"function getEntityDecorator() {\n const compositeDecorator = new CompositeDecorator([\n {\n strategy: (contentBlock, callback) => {\n contentBlock.findEntityRanges((meta) => meta.entity, callback);\n },\n component: Entity,\n },\n ]);\n return compositeDecorator;\n}",
"function load_decorators(server) {\n print_helper_1.print_verbose('* load_decorators');\n decorate_server(server);\n decorate_request(server);\n decorate_response(server);\n}",
"function decorateClientObj(clientObject, info) {\n var amtData;\n if (info.handshake.headers) {\n clientObject.userAgent = info.handshake.headers['user-agent'];\n }\n if (!clientObject.connectTime) clientObject.connectTime = Date.now();\n\n if (info.query) {\n amtData = info.query.id;\n if (!info.query.id) {\n console.log('no amt data!', clientObject.id);\n return;\n }\n amtData = atob(info.query.id);\n if ('object' === typeof amtData) {\n clientObject.WorkerId = amtData.id;\n clientObject.AssignmentId = amtData.a;\n clientObject.HITId = amtData.h;\n }\n else {\n clientObject.amtData = info.query.id;\n }\n }\n }",
"function PipeDecorator() { }",
"function typeDecoratorFactory(type) {\n let decorator = function (target, targetKey, parameterIndex) {\n let baseType = Object.getPrototypeOf(target).constructor;\n if (baseType != Object && getProperties(baseType.prototype).length > 0) {\n EntityType()(baseType.prototype);\n let children = Reflect.getOwnMetadata(EdmChildren, baseType) || [];\n if (children.indexOf(target.constructor) < 0) {\n children.unshift(target.constructor);\n }\n Reflect.defineMetadata(EdmChildren, children, baseType);\n }\n if (typeof parameterIndex == \"number\") {\n let parameterNames = utils_1.getFunctionParameters(target, targetKey);\n let existingParameters = Reflect.getOwnMetadata(EdmParameters, target, targetKey) || [];\n let paramName = parameterNames[parameterIndex];\n let param = existingParameters.filter(p => p.name == paramName)[0];\n if (param) {\n param.type = type;\n }\n else {\n existingParameters.push({\n name: paramName,\n type: type\n });\n }\n Reflect.defineMetadata(EdmParameters, existingParameters, target, targetKey);\n }\n else {\n if (typeof target == \"function\") {\n register(target);\n }\n let desc = Object.getOwnPropertyDescriptor(target, targetKey);\n if (targetKey != EdmType && ((desc && typeof desc.value != \"function\") || (!desc && typeof target[targetKey] != \"function\"))) {\n let properties = Reflect.getOwnMetadata(EdmProperties, target) || [];\n if (properties.indexOf(targetKey) < 0)\n properties.push(targetKey);\n Reflect.defineMetadata(EdmProperties, properties, target);\n }\n Reflect.defineMetadata(EdmType, type, target, targetKey);\n }\n };\n return function (...args) {\n if (arguments.length == 0)\n return decorator;\n else\n return decorator.apply(this, args);\n };\n}",
"function OverriddenClientRequest(options, cb) {\r\n if (http.OutgoingMessage) http.OutgoingMessage.call(this);\r\n\r\n // Filter the interceptors per request options.\r\n var interceptors = interceptorsFor(options);\r\n\r\n if (isOn() && interceptors) {\r\n debug('using', interceptors.length, 'interceptors');\r\n\r\n // Use filtered interceptors to intercept requests.\r\n var overrider = RequestOverrider(this, options, interceptors, remove, cb);\r\n for(var propName in overrider) {\r\n if (overrider.hasOwnProperty(propName)) {\r\n this[propName] = overrider[propName];\r\n }\r\n }\r\n } else {\r\n debug('falling back to original ClientRequest');\r\n\r\n // Fallback to original ClientRequest if nock is off or the net connection is enabled.\r\n if(isOff() || isEnabledForNetConnect(options)) {\r\n originalClientRequest.apply(this, arguments);\r\n } else {\r\n timers.setImmediate(function () {\r\n var error = new NetConnectNotAllowedError(options.host, options.path);\r\n this.emit('error', error);\r\n }.bind(this));\r\n }\r\n }\r\n }",
"function withInterceptorsFromDi() {\n // Note: the legacy interceptor function is provided here via an intermediate token\n // (`LEGACY_INTERCEPTOR_FN`), using a pattern which guarantees that if these providers are\n // included multiple times, all of the multi-provider entries will have the same instance of the\n // interceptor function. That way, the `HttpINterceptorHandler` will dedup them and legacy\n // interceptors will not run multiple times.\n return makeHttpFeature(HttpFeatureKind.LegacyInterceptors, [{\n provide: LEGACY_INTERCEPTOR_FN,\n useFactory: legacyInterceptorFnFactory\n }, {\n provide: HTTP_INTERCEPTOR_FNS,\n useExisting: LEGACY_INTERCEPTOR_FN,\n multi: true\n }]);\n}",
"function child(oriClient, req, clientName) {\n assert.object(oriClient, 'oriClient');\n assert.object(req, 'req');\n assert.object(req.tritonTraceSpan, 'req.tritonTraceSpan');\n\n return oriClient.child({\n beforeSync: function _addHeaders(opts, ctx) {\n var span;\n var spanCtx;\n var tags = {\n component: 'restifyclient',\n 'span.kind': 'request'\n };\n var tracer;\n\n spanCtx = req.tritonTraceSpan.context();\n tracer = req.tritonTraceSpan.tracer();\n\n if (clientName) {\n tags['client.name'] = clientName;\n }\n\n // outbound request means a new span\n span = tracer.startSpan('restify_request', {\n childOf: spanCtx,\n tags: tags\n });\n\n ctx.tritonSpan = span;\n\n // Add headers to our outbound request\n tracer.inject(span.context(), opentracing.FORMAT_TEXT_MAP, opts.headers);\n span.log({event: 'client-send-req'});\n }, afterSync: function _onResponse(r_err, r_req, r_res, ctx) {\n var span = ctx.tritonSpan;\n var tags = {\n error: r_err ? 'true' : undefined,\n };\n\n if (r_res) {\n tags['client.bytes_read'] = r_res.client.bytesRead;\n tags['client.bytes_dispatched'] = r_res.client._bytesDispatched;\n tags['http.headers'] = r_res.headers;\n tags['http.status_code'] = r_res.statusCode;\n }\n\n if (r_req) {\n tags['http.method'] = r_req.method;\n tags['http.url'] = r_req.path;\n tags['peer.addr'] = r_req.connection.remoteAddress;\n tags['peer.port'] = r_req.connection.remotePort;\n }\n\n span.log({event: 'client-recv-res'});\n span.addTags(tags);\n span.finish();\n }\n });\n\n // TODO what can go wrong?\n}",
"function legacyInterceptorFnFactory() {\n let chain = null;\n return (req, handler) => {\n if (chain === null) {\n const interceptors = (0,_angular_core__WEBPACK_IMPORTED_MODULE_4__.inject)(HTTP_INTERCEPTORS, {\n optional: true\n }) ?? [];\n // Note: interceptors are wrapped right-to-left so that final execution order is\n // left-to-right. That is, if `interceptors` is the array `[a, b, c]`, we want to\n // produce a chain that is conceptually `c(b(a(end)))`, which we build from the inside\n // out.\n chain = interceptors.reduceRight(adaptLegacyInterceptorToChain, interceptorChainEndFn);\n }\n return chain(req, handler);\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
to display admin block | function display_admin() {
show(admin);
hide(user);
} | [
"function _displayAdmin() {\n var adminView = new BST.Admin.AdminView();\n adminView.draw(document.body);\n }",
"function showAdmin(){\n addTemplate(\"admin\");\n userAdmin();\n}",
"function DisplayAdmin(callback){\n\tif($(\"#adminlist\").html()=='+'){\n\t\tClearAdmins(function(){\n\t\t\tcallback();\n\t\t});\n\t} else {\n\t\tListAdmins(function(){\n\t\t\tcallback();\n\t\t});\n\t}\n}",
"showBlockMenu() {\n this.blockTag.css(\"height\", \"100%\");\n this.blockTag.css(\"width\", \"100%\");\n this.blocklyDiv.css(\"width\", \"100%\");\n this.blockly.resize();\n this.blockly.setVisible(true);\n this.blockTag.removeClass(\"col-md-6\");\n Blockly.svgResize(this.blockly);\n }",
"showAdmin(id) {\n let adminSection = \"<h1>Admin</h1>\";\n adminSection += \"<ul>\";\n for (const info in this.state.businessInfo) {\n adminSection += \"<li>\";\n adminSection += info;\n adminSection += \": \";\n adminSection += this.state.businessInfo[info];\n adminSection += \"</li>\";\n }\n adminSection += \"</ul>\";\n document.getElementById(id).innerHTML = adminSection;\n }",
"function showAdminDashboard() {\n $.dashboard.setWidth('95%');\n $.dashboard.setHeight('93%');\n $.dashboard.setTop('5%');\n $.dashboard.setBottom('5%');\n $.dashboard.setRight('3%');\n $.dashboard.setLeft(20);\n $.dashboard.setOpacity('1.0');\n $.dashboard_container.setHeight(Ti.UI.FILL);\n $.dashboard_container.setWidth(Ti.UI.FILL);\n handlePageSelection({\n page : 'configurations'\n });\n}",
"function _navigateAdmin() {\n _displayAdmin();\n }",
"adminRender() {\n const formAdminStatus = octopus.toggleAdminValue();\n \n if (formAdminStatus) {\n this.editForm.style.display = 'block';\n const currentCub = octopus.getCurrentCubObj();\n this.nameInput.value = currentCub.name;\n this.urlInput.value = currentCub.imgSrc;\n this.clicksInput.value = currentCub.clickCount;\n }\n }",
"function editBlock() {\n $('.btn-save').show();\n $('.btn-edit').hide();\n $('.btn-image').hide();\n $('.btn-print').hide();\n $('#overEdit').css({'margin-left': '0em', 'margin-right': '0em'});\n $('.summernoteEdit').summernote({\n focus: true,\n toolbar: [\n // [groupName, [list of button]]\n ['style', ['bold', 'italic', 'underline', 'superscript', 'subscript', 'clear', 'color']],\n ['fontsize', ['fontsize']],\n ['insert', ['link','hr','picture']],\n ['misc', ['fullscreen','codeview',]],\n ],\n print: {\n 'stylesheetUrl': 'static/css/print.css'\n }\n });\n}",
"static loaded(block) {\n var il = new _fpa_admin.all.index_page(block)\n il.setup_shrinkable_blocks()\n il.handle_filter_selections();\n }",
"function reloadAdmin(req, res, template, block, next) {\n\n calipso.theme.renderItem(req, res, template, block, {},next);\n\n}",
"function reloadAdmin(req, res, template, block, next) {\n\n calipso.theme.renderItem(req, res, template, block, {}, next);\n\n}",
"function displayAdmins(e, data) {\n\t\t\n\t\tif(data){\n\t\t\tdataAdmins = data;\n\t\t}\n\n\t\tbtnShowAdmins.addClass('btn-active ');\n\t\tbtnShowEvents.removeClass('btn-active').addClass('btn-default');\n\n\t\tcpListTitle.text('Administrators manager');\n\n\t\tbtnAdd\n\t\t\t.attr('data-wdw', 'add-admin')\n\t\t\t.removeClass('action-display-create-event-wdw')\n\t\t\t.addClass('action-display-add-admin-wdw');\n\t\t\n\t\tcpList.empty();\n\n\t\tdataAdmins.forEach(function (user) {\n\n\t\t\tif(user.isAdmin){\n\t\t\t\tvar cpLayoutAdmin = tempAdmins.replace('{{ USERID }}', user.id);\n\t\t\t\tcpLayoutAdmin = cpLayoutAdmin.replace('{{ FIRST_NAME }}', user.firstName);\n\t\t\t\tcpLayoutAdmin = cpLayoutAdmin.replace('{{ LAST_NAME }}', user.lastName);\n\t\t\t\tcpList.append(cpLayoutAdmin);\t\t\t\t\n\t\t\t}\n\t\t});\n\t}",
"function admin(req, res){\n\thelper.renderAdminPage (req, res, database, {});\n}",
"showAddBlock() {\n this.set('_addBookmarkInProcess', true);\n }",
"function AdminEditBlock(id, block, useHttp) {\n return api(AdminEditBlockUrl, { id: id, block: block }, useHttp, true).sync();\n}",
"function showBlockSettings(block) {\r\n document.querySelector('.draggable_properties.block_single').classList.add('open');\r\n}",
"function menu(blockspec){\n var title = blockspec.name.replace(/\\W/g, '');\n var specs = blockspec.blocks;\n var help = blockspec.help !== undefined ? blockspec.help : '';\n return edit_menu(title, specs, help);\n}",
"function showAdminOnly() {\n if (!userIsAdmin) {\n return;\n }\n $('.admin-only').addClass('is-visible');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given 2 strings, a and b, return a string of the form short+long+short, with the shorter string on the outside and the longer string on the inside. The strings will not be the same length, but they may be empty (length 0). | function comboString(a, b){
if(a.length > b.length){
return b + a + b;
}
else{
return a + b + a;
}
} | [
"function shorter_reverse_longer(a, b){\n let long = a.length >= b.length ? a.split('').reverse().join('') : b.split('').reverse().join('');\n let short = a.length >= b.length ? b : a;\n return `${short}${long}${short}`;\n}",
"function solution(a, b) {\n return a.length > b.length ? `${b}${a}${b}` : `${a}${b}${a}`\n}",
"function comboString(a, b) {\n if(a.length > b.length) {\n return `${b}${a}${b}`;\n } else {\n return a + b + a;\n }\n}",
"function shortLongShort(str1, str2) {\n let string = '';\n if (str1.length < str2.length) {\n string += str1 + str2 + str1;\n } else {\n string += str2 + str1 + str2;\n }\n\n return string;\n}",
"function buildPalindrome(a, b) {\n // compare the first string char by char to the second string char by char\n\n // iterate through each char of first string\n // compare current char to each char of second string starting from the end\n // if there's a match attempt palindrome assembly\n // compare char right of cur char in first string to char left of cur char in second string\n // if matches are successful and we run out of char to compare log as palindrome\n\n\n // iterate through each char of first string\n // compare current char to each char of second string starting from the end\n // if there's a match attempt palindrome assembly\n // combine both strings from using matches as start/end points ex: ('dfebhbe' + 'xfd') ('ac' + 'ba' ) ('dfh' + 'fd')\n // compare characters starting from the center (if odd length skip middle) (dfebhbexfd)\n \n let short, long\n\n if (a.length > b.length ) {\n long = a;\n short = b;\n } else {\n long = b;\n short = a;\n }\n\n findFragment(short.reverse(), long, short.length);\n\n}",
"function shortLongShort(str1, str2) {\n // [short, long] = [str1, str2].sort((a, b) => a.length - b.length);\n // return short + long + short;\n\n return str1.length < str2.length ? str1 + str2 + str1 : str2 + str1 + str2;\n}",
"function shortLongShort(string1, string2) {\n var long = (string1.length > string2.length ? string1 : string2);\n var short = (string1.length < string2.length ? string1 : string2);\n\n console.log(short + long + short);\n}",
"function mergeStrings(a, b){\n return a.length < b.length ? a+b+a : b+a+b;\n}",
"function shorter_reverse_longer(a,b){\n if (a.length > b.length || a.length === b.length) {\n return b+a.split(\"\").reverse().join(\"\")+b\n }else{\n return a+b.split(\"\").reverse().join(\"\")+a\n }\n}",
"function mixString(a, b){\n let s = '';\n let i = 0;\n while(i<a.length && i<b.length){\n s = s + a.charAt(i) + b.charAt(i);\n i++;\n }\n return s + a.substring(i) + b.substring(i);\n }",
"function solve(a, b) {\n const getUnique = (s1, s2) => s1.split('').filter(i => !s2.split('').includes(i)).join('');\n return getUnique(a, b) + getUnique(b, a);\n}",
"function solution(a, b){\r\n if(a.split('').length < b.split('').length){\r\n return a+b+a\r\n }else{return b+a+b}\r\n }",
"function shortLongShort(wordOne, wordTwo) {\n let shortWord = ''\n let longWord = ''\n \n if (wordOne.length < wordTwo.length) {\n shortWord = wordOne;\n longWord = wordTwo;\n } else {\n shortWord = wordTwo;\n longWord = wordOne;\n }\n\n return shortWord + longWord + shortWord;\n}",
"function mixUp (a, b) {\n let firstCharsA = a.slice(0, 2)\n let firstCharsB = b.slice(0, 2)\n let newA = a.replace(firstCharsA, firstCharsB)\n let newB = b.replace(firstCharsB, firstCharsA)\n\n return newA + ' ' + newB\n}",
"function combine(str1,str2){\n if(str1.length === str2.length){\n str1 = str1.concat(str2);\n console.log(str1);\n }\n else if(str1.length > str2.length){\n nstr = str1.substring(str1.length - str2.length, str1.length);\n nstr = nstr.concat(str2);\n console.log(nstr);\n }\n else{\n nstr = str2.substring(str2.length - str1.length, str2.length);\n nstr = nstr.concat(str1);\n console.log(nstr);\n }\n}",
"function morganAndString(a, b) {\nvar ans='';\n a += 'z',b += 'z';\n for (;;) {\n if (a<b) {\n var charA=a.charAt(0);\n ans += charA;\n a=a.slice(1);\n }\n else {\n var charB=b.charAt(0);\n ans += charB;\n b=b.slice(1);\n }\n if (a=='z') {\n b=b.slice(0,-1)\n ans += b;\n break;\n }\n if (b=='z') {\n a=a.slice(0,-1)\n ans += a;\n break;\n }\n \n }\n return ans;\n\n}",
"function solve(a, b) {\n return (a + b).split(\"\").filter(c => !a.includes(c) || !b.includes(c)).join(\"\");\n}",
"function mergeAndReduceToString(a, b) {\r\n let result = \"\";\r\n for (let i = 0; i < Math.max(a.length, b.length); i++) {\r\n if (i in a)\r\n result += a[i];\r\n if (i in b)\r\n result += b[i];\r\n }\r\n return result;\r\n}",
"function combineToString(a, b) {\n return (String(a)+String(b));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the keyword with keywordId is placed correctly (return true if correct & false if the keyword is still in the bank or misplaced ) | isCorrectAnswer(keywordId) {
var keyword = document.querySelector(keywordId);
if (keyword.parentNode.id == "keywords") {
return false;
}
var keywordId = Number(keyword.id.substring(keyword.id.length - 1));
var currentDropAreaId = Number(keyword.parentNode.id.substring(keyword.parentNode.id.length - 1))
var correctDropAreaId = this.jsonData[keywordId].classification
if (currentDropAreaId == correctDropAreaId)
return true;
return false;
} | [
"function keywordExists(keyword) {\n var kw = keyword;\n if (kw != null) {\n try{\n kwIter = AdWordsApp.keywords().withCondition(\"Text = \\'\"+kw+\"\\'\").withCondition(\"Status = ENABLED\").get();\n var exists = kwIter.totalNumEntities() > 0 ? true : false;\n if(!exists){\n kwIter = AdWordsApp.keywords().withCondition(\"Text CONTAINS_IGNORE_CASE \\'\"+kw+\"\\'\").withCondition(\"Status = ENABLED\").get();\n var existsBroad = kwIter.totalNumEntities() > 0 ? true : false;\n if(existsBroad){\n while (kwIter.hasNext()) {\n var keyword = kwIter.next();\n keyword = normalizeKeyword(keyword.getText());\n kw = normalizeKeyword(kw);\n if(keyword == kw){\n exists = true;\n if(exists){\n return exists;\n }\n }\n }\n }\n }\n return exists;\n }\n catch(err){\n Logger.log(err.message)\n }\n }\n}",
"Is_Keyword(word) {\n return this.Keywords.includes(word);\n }",
"isValidAutocomplete(keyword) {\n return keyword.length >= 3;\n }",
"function check_make(keyword) {\n for (var i=0;i<hearst_response.content.make.length;i++) {\n if (keyword.text.toLowerCase().indexOf(hearst_response.content.make[i].name.toLowerCase())>-1) {\n keyword.text = hearst_response.content.make[i].name;\n return keyword;\n }\n }\n return null;\n }",
"function checkwords(){\n\n var comment_raw = $(this).val();\n var comment_stripped = comment_raw.replace(/[^\\w\\s]|_/g, \"\").replace(/\\n/g, \" \").replace(/\\s+/g, \" \");\n var words = [];\n words = comment_stripped.split(' ');\n //reset incorrect_words\n incorrect_words = [];\n\n $.each(words, function(index, item){\n var is_in_vocab = false;\n for (var i = 0; i < vocab.responseJSON.word.length; ++i){\n var thisWord = vocab.responseJSON.word[i].name;\n if(thisWord.toUpperCase()===this.toUpperCase()){\n is_in_vocab = true;\n break;\n }\n //when we are checking the last word in the vocab, if it doesn't match the word typed\n else if(i == (vocab.responseJSON.word.length - 1) && thisWord.toUpperCase()!=this.toUpperCase() && this.length > 0){\n incorrect_words.push(this);\n }\n }\n // show whether each number word in the comment is in the vocab\n //console.log(index+' = '+is_in_vocab);\n //console.log(incorrect_words);\n })\n }",
"function _canSearch (keyword) {\n return keyword.length > 2;\n }",
"function checkRequiredKeywords()\n{\n\n var ret = true;\n var tbl = ge(\"keywordTable\");\n\n if (tbl)\n {\n\n var arr = tbl.getElementsByTagName(\"input\");\n\n for (var i=0;i<arr.length;i++)\n {\n\n var kid = arr[i].getAttribute(\"keyword_id\");\n var req = arr[i].getAttribute(\"required\");\n\n if (kid && req && req==\"t\" && arr[i].value.length==\"0\")\n {\n\n ret = false;\n break;\n\n }\n\n }\n\n }\n\n return ret;\n\n}",
"function checkWordPositions() {\n\tfor(var i = 0; i < words.length; i++) {\n\t\tif(yPos[i] > height - 130) { //if it passed the middle of the city\n\t\t\taddCrater(i); //add a crater where it hit the city\n\t\t\tnewWord(i); //replace the word\n\t\t\tlives -= 1;\n\t\t}\n\t}\n}",
"function check_model(keyword) {\n\n var length=0;\n var word=null;\n for (var i=0;i<hearst_response.content.model.length;i++) { \n var reg = new RegExp(\"(^|\\\\s)\"+hearst_response.content.model[i].name+\"(\\\\s|$)\");\n if (reg.test(keyword.text)) {\n keyword.text=hearst_response.content.model[i].name;\n return keyword;\n } \n }\n return null;\n }",
"function hasKeyword(json, kw) {\n var ret = false;\n if (json.keywords) {\n json.keywords.forEach(function (w) {\n if (w === kw) {\n ret = true;\n }\n });\n }\n return ret;\n}",
"function invalidKeyword(keyword) {\r\n\treturn (KEYLINKS[keyword] && keyword !== OLD_KEYWORD);\r\n}",
"search(keyword) {\n if (this.dictionary[keyword.toLowerCase()]) return 'correctly';\n return 'incorrectly';\n }",
"function isRelevant(tweet) {\n const words = tweet.text.toLowerCase().split(' ');\n if (words.length < 5) return false;\n for (let i = 0; i < words.length; i++) {\n let word = trimHashtagsAndPunctuation(words[i]);\n if (keywords.has(word)) {\n console.log(words[i]);\n return true;\n }\n }\n return false;\n}",
"function resultMatchesKeyword(result, keyword) {\n keyword = keyword.toLowerCase();\n if (result.title &&\n result.title.en.toLowerCase().indexOf(keyword) >= 0)\n return true;\n else if (result.description &&\n result.description.en.toLowerCase().indexOf(keyword) >= 0)\n return true;\n else if (result.topicsHtml &&\n result.topicsHtml.replace(/\\<.*?\\>/g,'').toLowerCase().indexOf(keyword) >= 0)\n return true;\n return false;\n}",
"function keywordMatch(key, nested){\r\n var matches;\r\n var keywords = nested[\"keywords\"].split(\",\");\r\n\r\n\r\n for(var i = 0; i < keywords.length; i++){\r\n var kw = keywords[i].split(\" \");\r\n for(var j = 0; j < kw.length; j ++){\r\n if(key === kw[j] || calcSim(key, kw[j]) >= 0.7){\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n}",
"function checkEventKeyword(description, key) {\n console.log(description);\n if (!description) return false;\n var words = description.split(\" \");\n\n for (var i = 0; i < words.length; i++) {\n if (words[i] == key) {\n return true;\n }\n }\n\n return false;\n}",
"function checkForKeywords(item, keywordList) {\n var wordArr = [\"java\", \"swift\", \"javascript\", \"ibm\"];\n wordArr = keywordList;\n for (var i = 0; i < wordArr.length; i++) {\n var word = wordArr[i];\n if ((item.title.toLowerCase().indexOf(word) > -1) ||\n (item.body.toLowerCase().indexOf(word) > -1) ||\n (item.tags.indexOf(word) > -1)) {\n var newJson = {\n 'id': item.question_id,\n 'title': item.title,\n 'body': item.body,\n 'tags': item.tags,\n 'link':item.link,\n 'keyword': word\n };\n // console.log(newJson);\n return newJson;\n }\n }\n return null;\n}",
"filtrerParIDkw(obj, id) {\r\n if (obj.keywordId == id) {\r\n return true;\r\n }\r\n }",
"isNewWord(word) {\n for (let wordObj of this.dictionary) {\n if (wordObj.text === word) {\n return false;\n }\n }\n\n return true;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate report to JSON | generateFinalReport() {
const obj = {
environment: "Dev",
numberOfTestSuites: this._numberOfTestSuites,
totalTests: this._numberOfTests,
browsers: this.browsers,
testsState: [{
state: this.standardTestState('Passed'),
total: this._numberOfPassedTests
}, {
state: this.standardTestState('Failed'),
total: this._numberOfFailedTests
}, {
state: this.standardTestState('Skipped'),
total: this._numberOfSkippedTests
}],
testsPerBrowserPerState: this._testsCountPerBrowserPerState,
testsPerSuitePerState: this._testsCountPerSuitePerState,
testsWeatherState: this.weatherState,
totalDuration: this._totalDuration,
testsPerBrowser: this._testsPerBrowser
};
jsonfile.writeFile(this._finalReport, obj, {
spaces: 2
}, function(err) {
if (err !== null) {
console.error('Error saving JSON to file:', err)
}
console.info('Report generated successfully.');
});
} | [
"generateReport() {\n this.getData();\n reporter.write(this.options, this.data);\n }",
"buildReport () {\n let self = this;\n let totalIssues = 0;\n let reportFiles = [];\n\n Object.keys(self.fileReports).forEach((file) => {\n let fileReport = self.fileReports[file];\n let linesWithItems = Object.keys(fileReport.itemsByLine);\n\n let jsonReport = { file: file, issues_count: fileReport.uniqueIssues, issues: [] };\n\n if (linesWithItems.length === 0) {\n reportFiles.push(jsonReport);\n return;\n }\n\n totalIssues += fileReport.uniqueIssues;\n\n linesWithItems.forEach((lineNum) => {\n let lineContent = fileReport.contentArray[parseInt(lineNum, 10) - 1];\n\n fileReport.itemsByLine[lineNum].forEach((item) => {\n let lineIssueJson = {\n line: lineNum,\n content: lineContent,\n category: item.category,\n title: item.title,\n description: item.description\n };\n\n jsonReport.issues.push(lineIssueJson);\n });\n });\n\n reportFiles.push(jsonReport);\n });\n\n this.json.files = reportFiles;\n this.json.totalIssues = totalIssues;\n\n return { toString: () => JSON.stringify(this.json), totalIssues: totalIssues };\n }",
"static generateReport() {\n let data = [];\n console.info(\"Processing Json Report Files\");\n let files = fs.readdirSync(intermediateJsonFilesDirectory);\n for (let i in files) {\n let f = `${intermediateJsonFilesDirectory}/${files[i]}`;\n console.log(`Processing file ${f}`);\n try {\n let fileContent = fs.readFileSync(f, 'utf-8');\n data.push(JSON.parse(fileContent)[0]);\n }catch (err) {\n if (err) {\n console.error(`Failed to process file ${f}`);\n console.error(err);\n }\n }\n }\n\n console.info(\"Writing consolidated json file\");\n try {\n fs.writeFileSync('./e2e/reports/combinedJSON/cucumber_report.json', JSON.stringify(data));\n } catch (err) {\n if (err) {\n console.error(\"Failed to generate the consolidated json file.\");\n console.error(err);\n throw err;\n }\n }\n\n console.info(\"Generating Final HTML Report\");\n try {\n reporter.generate(cucumberReporterOptions);\n } catch (err) {\n if (err) {\n console.error(\"Failed to generate the final html report\");\n console.error(err);\n throw err;\n }\n }\n }",
"function generateAndSaveJsonFile() {\n jsonFormatter.log = (report) => {\n adjustAndSaveJsonFile(device.desiredCapabilities, report);\n };\n}",
"function writeJson(_FILENAME){\n if(global.debug){\n console.log(\"======= Generating Json File ========\");\n console.log(\"json.filename: \"+_FILENAME);\n console.log(reportObject);\n console.log(\"======= /Generating Json File ========\");\n };\n jsonReport.writeFile(_FILENAME,reportObject)\n}",
"function report(title,description,addtionalInfo) {\r\n\trefreshReports();\r\n\tvar jsonObj = {\r\n key: [getDateTime()],\r\n response: [\"Title of bug:\"+title+\" \\n Description:\"+description+\" \\n Addtional information:\"+addtionalInfo]\r\n };\r\n JsonArrayReports.push(jsonObj);\r\n var newFile = fsReports.writeFileSync(\"./Dictionary/Report_Log.json\",JSON.stringify(JsonArrayReports, null, \"\\t\"));\r\n}",
"function generateReport() {\n var itemTemplate = $('#step2-item-markup').html();\n if (isOwnEmpty(reportObject)) {\n alert(\"请添加周报内容,再生成报告!\");\n } else {\n var ndCompleted = $('.resulter').find('.completed'),\n ndPlan = $('.resulter').find('.plan'),\n node,\n ndRefrection = $('.resulter').find('.refrection');\n\n for (var p in reportObject) {\n console.log(p);\n switch (p) {\n case \"completed\":\n node = ndCompleted;\n break;\n case \"plan\":\n node = ndPlan;\n break;\n default:\n node = ndRefrection;\n }\n\n for (var index in reportObject[p][\"reports\"]) {\n record = reportObject[p][\"reports\"][index];\n node.append(replace(itemTemplate, {\n 'title' : record[\"title\"],\n 'type' : record[\"type\"],\n 'description' : record[\"description\"],\n 'progress' : record[\"progress\"]\n }));\n }\n }\n\n }\n console.log(reportObject);\n }",
"function saveReport(){\n var newReport = {\n build: model.config.Version,\n reportData:model.jsonReport,\n overallFR: 1.40,\n stableFR: 1.98,\n unstableFR: model.unstableFailureRate,\n config: model.config,\n instType: \"GEM5K\",\n startDate: \"11/02/2017\",\n endDate: \"11/08/2017\"\n };\n DashboardService\n .saveReport(newReport)\n .success(function (response) {\n })\n }",
"function generateReport(form){\n\t\tvar report = $(form).serializeArray();\n\t\tvar json = {};\n\t\t$.each(report, function(){\n\t\t\tjson[this.name] = this.value || '';\t\n\t\t});\n\t\treturn json;\n\t}",
"static createHTMLReport() {\n try {\n reporter.generate(cucumberReporteroptions); //invoke cucumber-html-reporter\n } catch (err) {\n if (err) {\n console.log('Failed to save cucumber test results to json file.');\n console.log(err);\n }\n }\n }",
"overwriteJsonReport() {\n outputJsonSync(this.jsonReportFile, this.customJsonReport, { overwrite: true, spaces: 2, EOL: '\\r\\n' });\n }",
"generateJSON()\n {\n const namesOfData = ['name', 'id', 'date', 'hour', 'rocket', 'success', 'place', 'description', 'startTime', 'endTime']\n const namesOfDataStep = ['name', 'startTime', 'description']\n\n const obj = {}\n\n for(const name of namesOfData)\n {\n let value = this.$webcast.querySelector(`[name=${name}]`).value\n if(/Time/.test(name))\n {\n value = Math.floor(parseFloat(value))\n }\n else if(name == 'success')\n {\n value = (value == '1')\n }\n obj[name] = value\n }\n obj[\"telemetry\"] = this.arrayTextAnalyzed\n const arraySteps = []\n for(let i = 0; i <= this.stepId - 1; i++)\n {\n const stepContainer = this.$stepSection.querySelector(`.webcast-step-${i}`)\n const objStep = {}\n for(const name of namesOfDataStep)\n {\n let value = stepContainer.querySelector(`[name=step-${i}-${name}]`).value\n if(/Time/.test(name))\n {\n value = Math.floor(parseFloat(value) - this.startTime)\n }\n objStep[name] = value\n }\n arraySteps.push(objStep)\n }\n obj[\"steps\"] = arraySteps\n const finalJSON = JSON.stringify(obj)\n this.$webcast.querySelector('.webcast-entries').style.display = 'none'\n this.$webcast.querySelector('.webcast-result').style.display = 'block'\n this.$webcast.querySelector('.webcast-result textarea').textContent = finalJSON\n let file = new File([finalJSON], this.$webcast.querySelector('[name=id]').value+'.json', {type: 'application/json'})\n saveAs(file)\n }",
"function saveReport(){\n var newReport = {\n build: model.config.Version,\n reportData:model.jsonReport,\n overallFR: model.failureRate,\n stableFR: model.stableFailureRate,\n unstableFR: model.unstableFailureRate,\n instType: $scope.selectedInst.instType,\n startDate: model.startDate,\n endDate: model.endDate,\n config: model.config\n };\n DashboardService\n .saveReport(newReport)\n .success(function (response) {\n })\n }",
"function generate_json(page){\n\tvar csv = \"used in,name,title,type,description,format,bareNumber\\n\\\nviews,Date,Date,date,the date in which the views occurred - in ISO8601 format YYYY-MM-DD,%y/%m/%d,\\n\\\nuser-contributions,Date,Date,date,the date in which the views occurred - in ISO8601 format YYYY-MM-DD,%y/%m/%d,\\n\\\nviews,Views,Total of visualizations received,integer,Total of visualizations the items in the GLAM have had within the specified time period. The loading of a page which contains the image is considered as a visualization of said image.,default,TRUE\\n\\\nuser-contributions,User,Username,string,The Wikimedia username of a user who has made contributions to the GLAM in question.,default,\\n\\\nuser-contributions,Count,Count of contributions,integer,Total count of contributions (creations, edits and deletions) made by the User to the items of the GLAM.,default,TRUE\\n\\\ncount,Count,Count of contributions,integer,Total count of contributions (creations, edits and deletions) made by the User to the items of the GLAM.,default,TRUE\\n\\\nusage,File,File name,string,Name of a Wikimedia Commons file.,default,\\n\\\nusage,Project,Wikimedia project,string,Wikimedia project in which the file has been used.,default,\\n\\\nusage,Page,Page title,string,Title of the page in the Project which uses the File.,default,\\n\";\n\tvar lines = csv.split(\"\\n\");\n\tvar headers = lines[0].split(\",\");\n\tvar json = \"\";\n\tjson += '{\\n\\t\"schema\":{\\n';\n\tjson += '\\t\\t\"fields\": [\\n';\n\n\tfor (var i = 1; i < lines.length; i++) {\n\t\tvar current = lines[i].split(\",\");\n\t\tif (page == current[0]) {\n\t\tjson += '\\t\\t\\t{\\n';\n\t\t\tfor (var j = 1; j < headers.length; j++) { // won't add empty information to the JSON\n\t\t\t\tif (current[j] != \"\") json += '\\t\\t\\t\\t\"' + headers[j] + '\": \"' +current[j] + '\",\\n';\n\t\t\t}\n\t\tjson = json.substring(0, json.length - 2) + \"\\n\"; // removes trailing comma\n\t\tjson += '\\t\\t\\t},\\n';\n\t\t}\n\t}\n\tjson = json.substring(0, json.length - 2) + \"\\n\"; // removes trailing comma\n\tjson += \"\\t\\t]\\n\\t}\\n}\";\n\n\treturn (json);\n}",
"function getSummaryReport() {\n var result;\n result = {\n table: {\n widths: ['*'],\n body: [\n [{\n text: 'DILAPIDATION SURVEY REPORT SUMMARY',\n style: 'tableHeader'\n }],\n [{\n text: getIt('surveyReportSummary'),\n style: 'tableText'\n }]\n ]\n }\n };\n return result;\n}",
"function generateReport(data, format) {\n\n let report = {};\n //set reportDate to the current date. will be changed if myEmma\n let reportDate = new Date().toDateString();\n let found = false;\n\n //if myemma\n if (format === \"MyEmma\") {\n report[\"name\"] = data[\"Campaign\"];\n report[\"service\"] = \"myEmma\";\n report[\"report\"] = data;\n\n //set reportDate to the date in the report, instead of the current date\n reportDate = new Date(data[\"Sent\"]).toDateString();\n\n //if pardot\n } else if (format === \"Pardot\") {\n console.log(data);\n report[\"name\"] = data[\"Email List Info\"][\"Name\"];\n report[\"service\"] = \"Pardot\";\n report[\"report\"] = data;\n\n } else {\n console.log(\"Email report format not recognised. Cannot be added to stored list of reports.\");\n return;\n }\n\n //check if there are other emails from this date\n\n emailReport.reports.forEach(dateGroup => {\n if (new Date(dateGroup[\"date\"]).toDateString() === reportDate) {\n dateGroup[\"emails\"].push(report);\n found = true;\n }\n });\n\n //if this is the first email for this date, create new entry\n if (!found) {\n let dateGroup = {};\n dateGroup[\"date\"] = reportDate;\n dateGroup[\"emails\"] = [report];\n emailReport.reports.push(dateGroup);\n }\n\n}",
"function outputJSON() {\n fileUtils.makeDirectory(\"data/json\");\n fileUtils.saveJsonFile(\"data/json/sample-summary-detailed.json\", detailedObj);\n fileUtils.saveJsonFile(\n \"data/json/sample-summary-concise.json\",\n conciseObj,\n 4\n );\n fileUtils.saveJsonFile(\"data/json/sample-summary-overall.json\", overallObj);\n}",
"static generateXMLReport(pathToJson, pathToXml) {\n const builder = new xml2js.Builder();\n const jsonReport = require(path.resolve(pathToJson));\n\n const xml = builder.buildObject(new JunitReport(jsonReport).build());\n\n fs.writeFile(path.resolve(pathToXml), xml, (err) => {\n if (err) {\n throw err\n }\n })\n }",
"function getReportData() {\n if($scope.selectedInst.startDate !== \"\"){\n reqData = {\n startDate: $scope.selectedInst.startDate,\n instType: $scope.selectedInst.instType\n };\n DashboardService.getReport(reqData)\n .success(function (response) {\n model.config = response.config;\n model.startDate = response.startDate;\n model.endDate = response.endDate;\n var jsonArr = response.reportData;\n model.failureRate =response.overallFR;\n model.stableFailureRate = response.stableFR;\n model.unstableFailureRate = response.unstableFR;\n for(i in jsonArr){\n jsonArr[i][\"errorDate\"] = new Date(jsonArr[i][\"errorDate\"]);\n jsonArr[i][\"lastReboot\"] = new Date(jsonArr[i][\"lastReboot\"]);\n }\n model.jsonReport = jsonArr;\n createLineGraph();\n createCrashCountPieChart();\n createCrashPerPieChart();\n gelHistoricalData();\n })\n }\n else {\n getDataFromInstrument();\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
|| FUNCTION: MediaClick || PARAMETERS: || RETURNS: || PURPOSE: Clicks straight through to your media URL || || | function MediaClick()
{
if( LoadInNewWindow ) {
URL = xMediaContent[iCurrentImage+1];
win=window.open(URL,"NewWindow","");
if (!win.opener)win.opener=self;
} else
document.location.href = xMediaContent[iCurrentImage+1];
} | [
"function onClick() {\n var $elem = $(this).closest('.w_medium'),\n self = wraith.lookup($elem),\n expanded = self.expanded();\n\n if (expanded) {\n // starting playback\n self.play($elem);\n\n // triggering custom event\n $elem.trigger('meduimPlaybackStarted', {\n elem: $elem,\n widget: self\n });\n } else {\n // closing last opened entry\n if (lastOpen) {\n lastOpen\n .expanded(false)\n .render();\n }\n\n // flipping full state and re-rendering widget\n $elem = self\n .expanded(!expanded)\n .render();\n\n // saving reference to last opened entry\n lastOpen = self;\n\n // triggering custom event\n $elem.trigger('mediumExpanded', {\n widget: self,\n mediaid: self.mediaid()\n });\n }\n\n return false;\n }",
"function click() {\n\tclickSound.play();\n}",
"function MediaClickWithInfo( AdditionalInfo )\r\n{\r\n if( LoadInNewWindow ) {\r\n URL = xMediaContent[iCurrentImage+1] + AdditionalInfo;\r\n win=window.open(URL,\"NewWindow\",\"\");\r\n if (!win.opener)win.opener=self;\r\n } else\r\n document.location.href = (xMediaContent[iCurrentImage+1] + AdditionalInfo);\r\n}",
"function handleMediaItemClick(mediaUrl, format) {\n setPreviewUrl(mediaUrl)\n setMediaFormat(format)\n setPreviewShow(true)\n }",
"function soundClick () {\n clickSound.play();\n}",
"function onMediaDoubleTapped(e){\n\t// Toggle the \"likeness\" of this media\n\tif (media.user_has_liked) {\n\t\tinstagram.unlikeMedia(media.id, function(e){\n\t\t\tTitanium.API.info(e);\n\t\t\t// Mark that we no longer like this media\n\t\t\tmedia.user_has_liked = false;\n\t\t\t// Change the background image for the button\n\t\t\t$.likesButton.backgroundImage = \"/icons/mediaDetail/likes-up.png\";\n\t\t}, function(e){\n\t\t\t// I should do something here to let the user know\n\t\t\tTitanium.API.info(e);\n\t\t});\n\t} else {\n\t\tinstagram.likeMedia(media.id, function(e){\n\t\t\tTitanium.API.info(e);\n\t\t\t// Mark that we now like this media\n\t\t\tmedia.user_has_liked = true;\n\t\t\t// Change the background image for the button\n\t\t\t$.likesButton.backgroundImage = \"/icons/mediaDetail/mediaDetail.png\";\n\t\t}, function(e){\n\t\t\t// I should do something here to let the user know\n\t\t\tTitanium.API.info(e);\n\t\t});\n\t}\n\t\n\t// Animate the like button\n\tanimation.flash($.likesButton);\n}",
"playMedia() {\n\t\tthis.context.vent.trigger(EVENT_PLAY, {\n\t\t\tinstance: this\n\t\t});\n\t}",
"function clickThumb() {}",
"function assMediasingleDoubleclick(mediaHolder) {\r\n mediaHolder.click(function (e) {\r\n var that = this;\r\n setTimeout(function () {\r\n var dblclick = parseInt($(that).data('double'), 10);\r\n if (dblclick > 0) {\r\n $(that).data('double', dblclick - 1);\r\n } else {\r\n mediasingleClick.call(that, e, mediaHolder);\r\n }\r\n }, 300);\r\n }).dblclick(function (e) {\r\n $(this).data('double', 2);\r\n mediadoubleClick.call(this, e, mediaHolder);\r\n });\r\n }",
"function mouseClick() {\n music.play();\n}",
"function seeVideo() {\n console.log(currentOrder.video)\n window.open(`media/${currentOrder.video}`).focus();\n }",
"function videoClicked(){\n\tplayORpause();\n}",
"mimicClick() {\n if (this.props.state.status === \"recording\") {\n this.mediaRecorder.stop();\n\n this.props.doFunction.playModel(\"Second\");\n this.setStartTime();\n return;\n }\n\n if (!playableActivities.includes(this.props.state.status)) {\n return;\n }\n\n this.setStartTime();\n this.props.doFunction.playModel(\"First\");\n }",
"function clickSound() {\n $('body').click(function() {\n click.play();\n })\n}",
"function tw_sliders_media_frame() {\n\t\t$('.media-menu a:nth-child(2)').trigger('click');\n\t\t$('.media-frame').addClass('tw-sliders-media-frame');\n\t}",
"click_InsideVideoPlayer(){\n this.videoPlayer.click();\n }",
"function openMediaLibrary(){\n\t\t\tvar style = ctrl.state && ctrl.state.style;\n\n\t\t\tlet imageUrl = style && style.background.image;\n\t\t\tqlikService.evalExpression(imageUrl).then(function(reply){\n\t\t\t\tMediaLibrary.show({\n\t\t\t\t\tscope: $scope,\n\t\t\t\t\tmediaUrl: reply,\n\t\t\t\t\tonConfirm: function(url){\n\t\t\t\t\t\tctrl.setBackgroundImageUrl(url);\n\t\t\t\t\t},\n\t\t\t\t\tonCancel: function(){\n\t\t\t\t\t\t// nothing to do...\n\t\t\t\t\t\tangular.noop();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t}",
"function addMedia() {\n window.location.href = 'add-media';\n}",
"showItem(mediaId)\n {\n let args = new helpers.args(ppixiv.plocation);\n LocalAPI.getArgsForId(mediaId, args);\n helpers.navigate(args);\n\n // Hide the hover thumbnail on click to get it out of the way.\n this.setHover(null);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the visible top position of an element If _noOwnScroll is true, method not include scrollTop of element itself. | _getVisibleTopPosition(_id, _noOwnScroll) {
return this._getVisibleLeftOrTop(_id, _noOwnScroll, 'offsetTop', 'scrollTop');
} | [
"get _visibleDocTop() {\r\n return window.pageYOffset - document.documentElement.scrollTop;\r\n }",
"function viewTop() {\r\n if (self.pageYOffset)\r\n return self.pageYOffset;\r\n\r\n if (document.body && document.body.scrollTop)\r\n return document.body.scrollTop;\r\n\r\n return 0;\r\n}",
"function top(elem) { return elem[0].getBoundingClientRect().top; }",
"function elementsOffsetFromTop(element) {\n var offset = 0;\n\n if (element.getBoundingClientRect) {\n offset = element.getBoundingClientRect().top;\n }\n\n return offset;\n }",
"function getElementYOffsetToDocumentTop(element) {\n return element.getBoundingClientRect().top + getPageYOffset();\n }",
"function topCoord(elem) {\n let y = elem.getBoundingClientRect().top + window.scrollY;\n return y;\n }",
"function distanceToTop(el) {\n return Math.floor(el.getBoundingClientRect().top);\n }",
"function calcOffsetTop(section){\r\n return document.querySelector(section).offsetTop;\r\n}",
"function top_of_element(elm_arg){\n\tvar element = document.getElementById(elm_arg); //replace elementId with your element's Id.\n\tvar rect = element.getBoundingClientRect();\n\tvar elementTop; //x and y\n\tvar scrollTop = document.documentElement.scrollTop?\n\t document.documentElement.scrollTop:document.body.scrollTop;\n\telementTop = rect.top+scrollTop;\n\treturn elementTop;\n}",
"function getElementHeightAboveTop(elem)\n {\n var docViewTop = $(window).scrollTop();\n var elemTop = $(elem).offset().top;\n return (docViewTop - elemTop);\n }",
"_getScrollPosition(object) {\n const {container} = this.refs;\n // give the header some breath room\n let top = -28;\n while (object && Number.isFinite(object.offsetTop) && object !== container) {\n top += object.offsetTop;\n object = object.parentNode;\n }\n return top;\n }",
"function updateTopPosition(el)\n{\n if(isSet(el))\n {\n el.style.top = getPageOffset() + \"px\";\n }\n}",
"function innerTop(elem) { return top(elem) - border(elem).top; }",
"function getTopPosition(props) {\n window[\"__checkBudget__\"]();\n if (props.top || props.top === 0) {\n return props.top;\n }\n else if (props.bottom) {\n return contentHeight - props.bottom - props.height;\n }\n else {\n return 0;\n }\n }",
"function scrolledVisibleView(elem) {\n var docViewTop = $(window).scrollTop(); //top of browser window\n var docViewBottom = docViewTop + $(window).height(); //bottom of browser window\n var elemTop = $(elem).offset().top; //top of element\n var elemBottom = elemTop + $(elem).height(); //bottom of element\n return ((elemBottom <= docViewBottom) || (elemTop >= docViewTop)); //return the value when element is outside browser window\n }",
"getVisiblePosition(_id, _noOwnScroll) {\n return [\n this._getVisibleLeftPosition(_id, _noOwnScroll),\n this._getVisibleTopPosition(_id, _noOwnScroll)\n ];\n }",
"function calcularTop(idObj, posFix)\n//<- v3.1.22b\n{\n var resultado, valor, totalview, addscroll, addheight, max;\n totalview = getViewHeight();\n if( totalview>0 ){\n // se sitúa en mitad de la vista\n valor = totalview/2;\n // v3.1.22b: si position:fixed, no se añade scroll\n // se desplaza el elemento sobre el top de la vista\n //alert('debug: calcular Top(0):posFix=<'+posFix+'>');\n if(posFix!=true)\n {\n // se comprueba si se ha scrolleado\n addscroll = getScrollFromTop();\n if( addscroll>0 )\n {\n // se añade desplazamiento con scroll desde el top\n valor = valor + addscroll;\n }\n }\n\n // se obtiene altura del objeto a mostrar\n addheight = getObjHeight(idObj);\n // cálculo para posición en pixels\n // se desplaza el objeto hacia arriba en la mitad de su altura\n if( addheight>0 )\n {\n valor = valor - (addheight/2);\n }\n resultado = valor;\n /* v3.1.22b: innecesario\n // para impedir que se vaya de la pantalla\n max = getMaxDocHeight();\n if( resultado > max )\n {\n resultado = max-(totalview*0.25);\n }\n */\n /*\n // cálculo para posición porcentual (NO SE USA)\n var diff = totalview - addheight;\n valor = ((diff*100)/totalview)/2;\n var rest = ((diff*100)/totalview)%2;\n // si hay parte decimal\n if(rest>0)\n {\n try\n {\n // Utilizar directamente round da una excepción\n // Se trunca a dos decimales y se redondea a un entero\n var entero = Math.round(Number(valor.toFixed(2)));\n valor = entero;\n }catch(e){\n }\n }\n resultado = valor;\n */\n }\n else\n resultado = 0;\n //alert('debug:calcular Top(2):resultado='+resultado+'+totalview='+totalview+'+addscroll='+addscroll+\n // '+addheight='+addheight);\n return resultado;\n}",
"function getAbsoluteTop(elem) {\n return elem.getBoundingClientRect().top;\n}",
"function xOffsetTop(e)\r\n{\r\n if (!(e=xGetElementById(e))) return 0;\r\n if (xDef(e.offsetTop)) return e.offsetTop;\r\n else return 0;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turns codeElement into "Pandaed" code element. | colorNode(codeElement) {
let lang = this.identifyLanguage(codeElement);
codeElement.classList && codeElement.classList.add('panda-code', 'panda-' + lang);
//optional 'ignore' language for ignoring code blocks.
if(lang !== 'ignore') {
//send to parser.
codeElement.innerHTML = this.parse(lang, codeElement.textContent);
}
} | [
"identifyLanguage(codeElement) {\n let regex = /(?:\\s|^)panda[_-](\\w+)(?:\\s|$)/;\n\n if (regex.test(codeElement.className)) {\n return regex.exec(codeElement.className)[1];\n }\n\n return 'default'\n }",
"code(elem) {\r\n window._codelem = elem;\r\n\r\n let buf = '';\r\n\r\n for (let elem2 of elem.childNodes) {\r\n if (elem2.nodeName === \"#text\") {\r\n buf += elem2.textContent + '\\n';\r\n }\r\n }\r\n\r\n var func, $scope = this.templateScope;\r\n\r\n buf = `\r\nfunc = function() {\r\n ${buf};\r\n}\r\n `;\r\n\r\n eval(buf);\r\n\r\n let id = \"\" + elem.getAttribute(\"id\");\r\n\r\n this.codefuncs[id] = func;\r\n }",
"code(elem) {\n window._codelem = elem;\n\n let buf = '';\n\n for (let elem2 of elem.childNodes) {\n if (elem2.nodeName === \"#text\") {\n buf += elem2.textContent + '\\n';\n }\n }\n\n var func, $scope = this.templateScope;\n\n buf = `\nfunc = function() {\n ${buf};\n}\n `;\n\n eval(buf);\n\n let id = \"\" + elem.getAttribute(\"id\");\n\n this.codefuncs[id] = func;\n }",
"getCodeElement(input) {\n return this.getElement(this.codeElements, input);\n }",
"inlineCode(h, node) {\n return Object.assign({}, node, {\n type: 'element',\n tagName: 'inlineCode',\n properties: {},\n children: [\n {\n type: 'text',\n value: node.value\n }\n ]\n })\n }",
"inlineCode(h, node) {\n return Object.assign({}, node, {\n type: 'element',\n tagName: 'inlineCode',\n properties: {},\n children: [{\n type: 'text',\n value: node.value\n }]\n });\n }",
"function createCode(data) {\n var code = document.createElement(\"CODE\");\n var t = document.createTextNode(data);\n code.appendChild(t);\n placeForData.appendChild(code);\n code.style.display = \"block\";\n}",
"function renderCode(originalRule) {\n return (...args) => {\n const [tokens, idx] = args;\n // Escape quotes and apostrophes so that they don't break the HTML.\n const codeblockContent = tokens[idx].content\n .replaceAll('\"', '"')\n .replaceAll(\"'\", \"'\");\n\n const originalHTMLContent = originalRule(...args);\n\n if (codeblockContent.length === 0) {\n return originalHTMLContent;\n }\n\n return `\n<lit-island\n import=\"/js/hydration-entrypoints/copy-code-button.js\"\n on:interaction=\"focusin,pointerenter,touchstart\">\n <copy-code-button>\n ${originalHTMLContent}\n </copy-code-button>\n</lit-island>\n`;\n };\n}",
"function patchMermaidCodeElementClass() {\r\n var elements = document.getElementsByClassName(\"language-mermaid\");\r\n for(var i=0; i < elements.length; i+=1) {\r\n var element = elements.item(i);\r\n if (element.tagName.toLowerCase() == \"code\") {\r\n element.className = \"mermaid\";\r\n }\r\n }\r\n}",
"function build_point_code( point ){\n\t\treturn \"(\"+point.data.original_code+\")\"+\" [\"+point.data.point_id+\"]\";\n\t}",
"code() {\n return getPieceCode(this.name());\n }",
"function appendToScript(code){\n var script = document.createElement('script');\n script.setAttribute('class', 'aceCode');\n try {\n script.appendChild(document.createTextNode(code));\n document.body.appendChild(script);\n } catch (e) {\n script.text = code;\n document.body.appendChild(script);\n }\n }",
"function WFS_AddHtmlCodeElementToDocument(field, xmlDoc, renderParent) {\r\n //modifying the rendering document\r\n var htmlCode = xmlDoc.createElement('HTMLCODE');\r\n htmlCode.setAttribute('renderedLabel', WFS_XmlEncode(field.renderedLabel));\r\n htmlCode.setAttribute('src', WFS_XmlEncode(field.htmlSrc));\r\n\r\n renderParent.appendChild(htmlCode);\r\n}",
"code({ node, inline, className, children, ...props }) {\n\t\t\tconst match = /language-(\\w+)/.exec(className || '');\n\t\t\treturn !inline && match ? (\n\t\t\t\t<SyntaxHighlighter style={atomDark} language={match[1]} PreTag='div' {...props}>\n\t\t\t\t\t{(children = String(children).replace(/\\n$/, ''))}\n\t\t\t\t</SyntaxHighlighter>\n\t\t\t) : (\n\t\t\t\t<code className={className} {...props}>\n\t\t\t\t\t{children}\n\t\t\t\t</code>\n\t\t\t);\n\t\t}",
"function convertCodeToInline(item) {\n item.type = 'inline'\n const codeBlockSixSpace = ' '\n item.content = codeBlockSixSpace + item.content\n item.children = [{\n type: 'text',\n content: item.content,\n level: 0\n }]\n }",
"function getTagForCode(code){\n var ret;\n var ar = [\n 'C++',\n 'Java',\n 'JavaScript',\n 'HTML',\n 'C#',\n 'CSS',\n 'PHP',\n 'Python',\n 'Scala',\n 'Ruby',\n 'Android',\n 'Windows',\n 'Linux'\n ];\n ret = ar[code];\n return ret;\n}",
"code(h, node) {\n const value = node.value ? detab(node.value + '\\n') : ''\n const {lang} = node\n const props = {}\n\n if (lang) {\n props.className = ['language-' + lang]\n }\n\n props.metastring = node.meta\n\n // To do: this handling seems not what users expect:\n // <https://github.com/mdx-js/mdx/issues/702>.\n const meta =\n node.meta &&\n node.meta.split(' ').reduce((acc, cur) => {\n if (cur.split('=').length > 1) {\n const t = cur.split('=')\n acc[t[0]] = t[1]\n return acc\n }\n\n acc[cur] = true\n return acc\n }, {})\n\n if (meta) {\n Object.keys(meta).forEach(key => {\n const isClassKey = key === 'class' || key === 'className'\n if (props.className && isClassKey) {\n props.className.push(meta[key])\n } else {\n props[key] = meta[key]\n }\n })\n }\n\n return h(node.position, 'pre', [\n h(node, 'code', props, [u('text', value)])\n ])\n }",
"function inlineCode(node) {\n\t var value = node.value;\n\t var ticks = repeat('`', streak(value, '`') + 1);\n\t var start = ticks;\n\t var end = ticks;\n\t\n\t if (value.charAt(0) === '`') {\n\t start += ' ';\n\t }\n\t\n\t if (value.charAt(value.length - 1) === '`') {\n\t end = ' ' + end;\n\t }\n\t\n\t return start + value + end;\n\t}",
"function primaryName(code) {\n // Continuation of name: remain.\n if (code === 45 /* `-` */ || id.cont(code)) {\n effects.consume(code)\n return primaryName\n }\n\n // End of name.\n if (\n code === 46 /* `.` */ ||\n code === 47 /* `/` */ ||\n code === 58 /* `:` */ ||\n code === 62 /* `>` */ ||\n code === 123 /* `{` */ ||\n markdownLineEndingOrSpace(code) ||\n esWhitespace(code)\n ) {\n effects.exit(tagNamePrimaryType)\n returnState = afterPrimaryName\n return optionalEsWhitespace(code)\n }\n\n crash(\n code,\n 'in name',\n 'a name character such as letters, digits, `$`, or `_`; whitespace before attributes; or the end of the tag' +\n (code === 64 /* `@` */\n ? ' (note: to create a link in MDX, use `[text](url)`)'\n : '')\n )\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the Host Bot tab is closed then all the tabs created by the modules running in that bot instance will be closed. | function CloseActiveModule(hostTabId) {
if(typeof(_ActiveModules) !== "undefined" && _ActiveModules != null) {
for (var key in _ActiveModules) {
if(typeof(_ActiveModules[key]) !== "undefined" && _ActiveModules[key] != null && _ActiveModules[key].HostTabId) {
if(_ActiveModules[key].HostTabId == hostTabId) {
CloseAllModuleTabs(key);
delete _ActiveModules[key];
}
}
}
}
} | [
"function closeAllTabs() {\n IDE.sessions.forEach(function (session) {\n IDE.closeSession(session);\n });\n }",
"function CloseAllModuleTabs() {\n\t\tif(typeof(_ActiveModules) !== \"undefined\" && _ActiveModules != null) {\n\t\t\tfor (var key in _ActiveModules) {\n\t\t\t\tif(typeof(_ActiveModules[key]) !== \"undefined\" && _ActiveModules[key] != null && _ActiveModules[key].ActiveTabs && _ActiveModules[key].ActiveTabs != null) {\n\t\t\t\t\tfor(var i = 0; i < _ActiveModules[key].ActiveTabs.length; i++) {\n\t\t\t\t\t\tchrome.tabs.remove(_ActiveModules[key].ActiveTabs[i]);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tdelete _ActiveModules[key];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"closeAll() {\n const tabs = this.slice();\n this._current = null;\n for (let tab of tabs) tab.close();\n }",
"function closeAllTabs() {\r\n\tutils.log(\"closeAllTabs\");\r\n\ttry {\r\n\t\tfor each (var tab in tabs) {\r\n\t\t\tif (tab != null && (tab.title == env.globals.managerTitle || tab.title == env.globals.playerTitle)) {\r\n\t\t\t\ttab.close();\r\n\t\t\t\tutils.log(\"close Tab: \"+tab.title);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tcatch(e){}\r\n}",
"function closeTabs() {\n tabs.closeMany(selectEvenOddTabs(), SINGLE_CLOSING_DELAY);\n scheduler.addFunc(function () {\n if (window.confirm('Start again?')) {\n main();\n }\n }, 0);\n }",
"closeAllTabs() {\n for (let i = this.boxes.webviews.length; i > 0; i--) {\n this.closeTab(i);\n }\n }",
"function closeTabs() {\n while (mc.tabmail.tabInfo.length > 1) {\n mc.tabmail.closeTab(1);\n }\n }",
"function hide_in_all_tabs()\n {\n for (const id_string in host_tab_ids)\n {\n browser.pageAction.hide(parseInt(id_string));\n }\n host_tab_ids = {};\n }",
"closeAllWorkspaceTabs() {\n this.workspaceElement.clear();\n }",
"_teardown() {\n for (var i = 0; i < this.tabInfo.length; i++) {\n let tab = this.tabInfo[i];\n let tabCloseFunc = tab.mode.closeTab || tab.mode.tabType.closeTab;\n tabCloseFunc.call(tab.mode.tabType, tab);\n }\n }",
"function closeLastOpenedTab() {\n browser.getAllWindowHandles().then(handles => {\n browser.switchTo().window(handles[handles.length - 1]); // switch driver execution to the last tab\n browser.close();\n browser.switchTo().window(handles[0]); // switch driver execution to the first tab\n });\n}",
"closeContent() {\n\t\tthis.ensureContentTabOpen(undefined);\n\t}",
"function openTabsCloseTabs() {\n tabs.openMany(URLS, SINGLE_OPENING_DELAY);\n scheduler.addFunc(closeTabs, CLOSING_PHASE_DELAY);\n }",
"cleanTabs() {\n // all free tabs now\n const freeTabs = Object.keys(this.tabs).filter(tabId => this.tabs[tabId].free);\n // close all free tabs left one\n freeTabs.slice(1).forEach(this.closeTab.bind(this));\n }",
"async shutdown() {\n winston.info(MODULE, 'start shutdown');\n await this.headless.close();\n await this.chrome.kill();\n this.webappServer.close();\n this.headless = null;\n this.chrome = null;\n this.webappServer = null;\n winston.info(MODULE, 'finished shutdown');\n }",
"function closeOtherNewTabs() {\n chrome.tabs.query({\n active: false,\n url: 'chrome://newtab/'\n }, function (tabs) {\n for (let tab of tabs) {\n chrome.tabs.remove(tab.id);\n }\n });\n}",
"function closeBlockedTabs() {\n console.debug('closing blocked tabs');\n console.debug('querying for blocked tabs');\n chrome.tabs.query({'url': blockedSiteURLs()}, function(blockedTabs) {\n console.debug('found ' + blockedTabs.length + ' tabs');\n for (i = 0; i < blockedTabs.length; i++) {\n console.debug('found a blocked tab ' + blockedTabs[i].url);\n chrome.tabs.remove(blockedTabs[i].id); \n }\n });\n}",
"function closeAllPosts(original)\n{\n var url=\"*://chan.sankakucomplex.com/post/show/*\";\n\n if (original)\n {\n url=\"https://cs.sankakucomplex.com/data/*\";\n }\n\n chrome.tabs.query({\n currentWindow:true,\n url:url\n },(tabs)=>{\n for (var x=0,l=tabs.length;x<l;x++)\n {\n chrome.tabs.remove(tabs[x].id);\n }\n });\n}",
"unload() {\n Management.emit(\"page-unload\", this);\n\n this.extension.views.delete(this);\n\n for (let obj of this.onClose) {\n obj.close();\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine whether the given properties match those of a `DefaultCacheBehaviorProperty` | function CfnDistribution_DefaultCacheBehaviorPropertyValidator(properties) {
if (!cdk.canInspect(properties)) {
return cdk.VALIDATION_SUCCESS;
}
const errors = new cdk.ValidationResults();
errors.collect(cdk.propertyValidator('allowedMethods', cdk.listValidator(cdk.validateString))(properties.allowedMethods));
errors.collect(cdk.propertyValidator('cachedMethods', cdk.listValidator(cdk.validateString))(properties.cachedMethods));
errors.collect(cdk.propertyValidator('compress', cdk.validateBoolean)(properties.compress));
errors.collect(cdk.propertyValidator('defaultTtl', cdk.validateNumber)(properties.defaultTtl));
errors.collect(cdk.propertyValidator('fieldLevelEncryptionId', cdk.validateString)(properties.fieldLevelEncryptionId));
errors.collect(cdk.propertyValidator('forwardedValues', cdk.requiredValidator)(properties.forwardedValues));
errors.collect(cdk.propertyValidator('forwardedValues', CfnDistribution_ForwardedValuesPropertyValidator)(properties.forwardedValues));
errors.collect(cdk.propertyValidator('lambdaFunctionAssociations', cdk.listValidator(CfnDistribution_LambdaFunctionAssociationPropertyValidator))(properties.lambdaFunctionAssociations));
errors.collect(cdk.propertyValidator('maxTtl', cdk.validateNumber)(properties.maxTtl));
errors.collect(cdk.propertyValidator('minTtl', cdk.validateNumber)(properties.minTtl));
errors.collect(cdk.propertyValidator('smoothStreaming', cdk.validateBoolean)(properties.smoothStreaming));
errors.collect(cdk.propertyValidator('targetOriginId', cdk.requiredValidator)(properties.targetOriginId));
errors.collect(cdk.propertyValidator('targetOriginId', cdk.validateString)(properties.targetOriginId));
errors.collect(cdk.propertyValidator('trustedSigners', cdk.listValidator(cdk.validateString))(properties.trustedSigners));
errors.collect(cdk.propertyValidator('viewerProtocolPolicy', cdk.requiredValidator)(properties.viewerProtocolPolicy));
errors.collect(cdk.propertyValidator('viewerProtocolPolicy', cdk.validateString)(properties.viewerProtocolPolicy));
return errors.wrap('supplied properties not correct for "DefaultCacheBehaviorProperty"');
} | [
"function CfnDistribution_CacheBehaviorPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('behavior', cdk.validateString)(properties.behavior));\n return errors.wrap('supplied properties not correct for \"CacheBehaviorProperty\"');\n}",
"function CfnDistribution_CacheBehaviorPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('allowedMethods', cdk.listValidator(cdk.validateString))(properties.allowedMethods));\n errors.collect(cdk.propertyValidator('cachedMethods', cdk.listValidator(cdk.validateString))(properties.cachedMethods));\n errors.collect(cdk.propertyValidator('compress', cdk.validateBoolean)(properties.compress));\n errors.collect(cdk.propertyValidator('defaultTtl', cdk.validateNumber)(properties.defaultTtl));\n errors.collect(cdk.propertyValidator('fieldLevelEncryptionId', cdk.validateString)(properties.fieldLevelEncryptionId));\n errors.collect(cdk.propertyValidator('forwardedValues', cdk.requiredValidator)(properties.forwardedValues));\n errors.collect(cdk.propertyValidator('forwardedValues', CfnDistribution_ForwardedValuesPropertyValidator)(properties.forwardedValues));\n errors.collect(cdk.propertyValidator('lambdaFunctionAssociations', cdk.listValidator(CfnDistribution_LambdaFunctionAssociationPropertyValidator))(properties.lambdaFunctionAssociations));\n errors.collect(cdk.propertyValidator('maxTtl', cdk.validateNumber)(properties.maxTtl));\n errors.collect(cdk.propertyValidator('minTtl', cdk.validateNumber)(properties.minTtl));\n errors.collect(cdk.propertyValidator('pathPattern', cdk.requiredValidator)(properties.pathPattern));\n errors.collect(cdk.propertyValidator('pathPattern', cdk.validateString)(properties.pathPattern));\n errors.collect(cdk.propertyValidator('smoothStreaming', cdk.validateBoolean)(properties.smoothStreaming));\n errors.collect(cdk.propertyValidator('targetOriginId', cdk.requiredValidator)(properties.targetOriginId));\n errors.collect(cdk.propertyValidator('targetOriginId', cdk.validateString)(properties.targetOriginId));\n errors.collect(cdk.propertyValidator('trustedSigners', cdk.listValidator(cdk.validateString))(properties.trustedSigners));\n errors.collect(cdk.propertyValidator('viewerProtocolPolicy', cdk.requiredValidator)(properties.viewerProtocolPolicy));\n errors.collect(cdk.propertyValidator('viewerProtocolPolicy', cdk.validateString)(properties.viewerProtocolPolicy));\n return errors.wrap('supplied properties not correct for \"CacheBehaviorProperty\"');\n}",
"function CfnDistribution_CacheBehaviorPerPathPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('behavior', cdk.validateString)(properties.behavior));\n errors.collect(cdk.propertyValidator('path', cdk.validateString)(properties.path));\n return errors.wrap('supplied properties not correct for \"CacheBehaviorPerPathProperty\"');\n}",
"IsProceduralPropertyCached() {}",
"function containsAllowedProps(properties) {\n if (properties === null || (typeof properties === 'undefined' ? 'undefined' : _typeof(properties)) !== 'object') {\n return false;\n }\n return Object.entries(properties).some(function (property) {\n var key = property[0];\n var value = property[1];\n if (typeof value === 'string') {\n return key === 'style' || key === 'src' || key === 'href';\n } else if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && key === 'attributes') {\n return 'class' in properties.attributes;\n }\n });\n}",
"function cfnDistributionDefaultCacheBehaviorPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnDistribution_DefaultCacheBehaviorPropertyValidator(properties).assertSuccess();\n return {\n AllowedMethods: cdk.listMapper(cdk.stringToCloudFormation)(properties.allowedMethods),\n CachedMethods: cdk.listMapper(cdk.stringToCloudFormation)(properties.cachedMethods),\n Compress: cdk.booleanToCloudFormation(properties.compress),\n DefaultTTL: cdk.numberToCloudFormation(properties.defaultTtl),\n FieldLevelEncryptionId: cdk.stringToCloudFormation(properties.fieldLevelEncryptionId),\n ForwardedValues: cfnDistributionForwardedValuesPropertyToCloudFormation(properties.forwardedValues),\n LambdaFunctionAssociations: cdk.listMapper(cfnDistributionLambdaFunctionAssociationPropertyToCloudFormation)(properties.lambdaFunctionAssociations),\n MaxTTL: cdk.numberToCloudFormation(properties.maxTtl),\n MinTTL: cdk.numberToCloudFormation(properties.minTtl),\n SmoothStreaming: cdk.booleanToCloudFormation(properties.smoothStreaming),\n TargetOriginId: cdk.stringToCloudFormation(properties.targetOriginId),\n TrustedSigners: cdk.listMapper(cdk.stringToCloudFormation)(properties.trustedSigners),\n ViewerProtocolPolicy: cdk.stringToCloudFormation(properties.viewerProtocolPolicy),\n };\n}",
"shouldUpdate(changedProperties) {\n changedProperties.forEach((oldValue, propName) => {\n console.log(`${propName} changed. oldValue: ${oldValue}`);\n });\n return changedProperties.has('prop1');\n }",
"function checkSameProps(properties, qParams, model) {\n var result = INCLUDE;\n\n _.each(properties, function(property) {\n if (_.has(qParams, property) && qParams[property] !== model.get(property)) {\n result = EXCLUDE;\n }\n });\n\n return result;\n }",
"function isCacheWrapper(value){return value&&value.hasOwnProperty(\"lastFetchTime\")&&value.hasOwnProperty(\"value\");}",
"function CfnDistribution_CacheSettingsPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('allowedHttpMethods', cdk.validateString)(properties.allowedHttpMethods));\n errors.collect(cdk.propertyValidator('cachedHttpMethods', cdk.validateString)(properties.cachedHttpMethods));\n errors.collect(cdk.propertyValidator('defaultTtl', cdk.validateNumber)(properties.defaultTtl));\n errors.collect(cdk.propertyValidator('forwardedCookies', CfnDistribution_CookieObjectPropertyValidator)(properties.forwardedCookies));\n errors.collect(cdk.propertyValidator('forwardedHeaders', CfnDistribution_HeaderObjectPropertyValidator)(properties.forwardedHeaders));\n errors.collect(cdk.propertyValidator('forwardedQueryStrings', CfnDistribution_QueryStringObjectPropertyValidator)(properties.forwardedQueryStrings));\n errors.collect(cdk.propertyValidator('maximumTtl', cdk.validateNumber)(properties.maximumTtl));\n errors.collect(cdk.propertyValidator('minimumTtl', cdk.validateNumber)(properties.minimumTtl));\n return errors.wrap('supplied properties not correct for \"CacheSettingsProperty\"');\n}",
"function test_props_all( prop, callback ) {\n var uc_prop = prop.charAt(0).toUpperCase() + prop.substr(1),\n \n // following spec is to expose vendor-specific style properties as:\n // elem.style.WebkitBorderRadius\n // and the following would be incorrect:\n // elem.style.webkitBorderRadius\n // Webkit and Mozilla are nice enough to ghost their properties in the lowercase\n // version but Opera does not.\n \n // see more here: http://github.com/Modernizr/Modernizr/issues/issue/21\n props = [\n prop,\n 'Webkit' + uc_prop,\n 'Moz' + uc_prop,\n 'O' + uc_prop,\n 'ms' + uc_prop,\n 'Khtml' + uc_prop\n ];\n\n return !!test_props( props, callback );\n }",
"function CfnResolver_CachingConfigPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('cachingKeys', cdk.listValidator(cdk.validateString))(properties.cachingKeys));\n errors.collect(cdk.propertyValidator('ttl', cdk.validateNumber)(properties.ttl));\n return errors.wrap('supplied properties not correct for \"CachingConfigProperty\"');\n}",
"function test_props_all( prop, callback ) {\n var uc_prop = prop.charAt(0).toUpperCase() + prop.substr(1),\n\n // following spec is to expose vendor-specific style properties as:\n // elem.style.WebkitBorderRadius\n // and the following would be incorrect:\n // elem.style.webkitBorderRadius\n // Webkit and Mozilla are nice enough to ghost their properties in the lowercase\n // version but Opera does not.\n\n // see more here: http://github.com/Modernizr/Modernizr/issues/issue/21\n props = [\n prop,\n 'Webkit' + uc_prop,\n 'Moz' + uc_prop,\n 'O' + uc_prop,\n 'ms' + uc_prop,\n 'Khtml' + uc_prop\n ];\n\n return !!test_props( props, callback );\n }",
"function test_props_all( prop, callback ) {\n var uc_prop = prop.charAt(0).toUpperCase() + prop.substr(1),\n \n // following spec is to expose vendor-specific style properties as:\n // elem.style.WebkitBorderRadius\n // and the following would be incorrect:\n // elem.style.webkitBorderRadius\n \n // Webkit ghosts their properties in lowercase but Opera & Moz do not.\n // Microsoft foregoes prefixes entirely <= IE8, but appears to \n // use a lowercase `ms` instead of the correct `Ms` in IE9\n \n // see more here: http://github.com/Modernizr/Modernizr/issues/issue/21\n props = [\n prop,\n 'Webkit' + uc_prop,\n 'Moz' + uc_prop,\n 'O' + uc_prop,\n 'ms' + uc_prop,\n 'Khtml' + uc_prop\n ];\n\n return !!test_props( props, callback );\n }",
"function isPropertyObserved(prop){\n return observedprops[prop] !== undefined;\n }",
"function supportsProperty(props) {\n for (var i in props) {\n if (p.guineapig.style[props[i]] !== undefined) { return true; }\n }\n return false;\n } // Thanks modernizr!",
"function nativeTestProps ( props, value ) {\n var i = props.length;\n // Start with the JS API: http://www.w3.org/TR/css3-conditional/#the-css-interface\n if ('CSS' in window && 'supports' in window.CSS) {\n // Try every prefixed variant of the property\n while (i--) {\n if (window.CSS.supports(domToCSS(props[i]), value)) {\n return true;\n }\n }\n return false;\n }\n // Otherwise fall back to at-rule (for Opera 12.x)\n else if ('CSSSupportsRule' in window) {\n // Build a condition string for every prefixed variant\n var conditionText = [];\n while (i--) {\n conditionText.push('(' + domToCSS(props[i]) + ':' + value + ')');\n }\n conditionText = conditionText.join(' or ');\n return injectElementWithStyles('@supports (' + conditionText + ') { #modernizr { position: absolute; } }', function( node ) {\n return getComputedStyle(node, null).position == 'absolute';\n });\n }\n return undefined;\n }",
"function matchTransitionProperty(subject, property) {\n if (property === \"all\") {\n return true;\n }\n var sub = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__removeVendorPrefix__[\"a\" /* default */])(subject);\n var prop = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__removeVendorPrefix__[\"a\" /* default */])(property);\n if (sub.length < prop.length) {\n return false;\n }\n else if (sub.length === prop.length) {\n return sub === prop;\n }\n return sub.substr(0, prop.length) === prop;\n}",
"isCached(provider, endpoint, params) {\n\t const uri = mergeQuery(endpoint, params);\n\t return (this._cache[provider] !== void 0 &&\n\t this._cache[provider][uri] !== void 0);\n\t }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create oEmbed of first tweet via ID | function generateEmbed(tweetId) {
$.getJSON('https://api.twitter.com/1/statuses/oembed.json?id=' + tweetId + '&callback=?', function(embed) {
html = embed.html;
$('#thetweetembed').html(html);
});
} | [
"function getOEmbed (tweet) {\r\n\r\n\t\t\t\t// oEmbed request params\r\n\t\t\t\tvar params = { \"id\": tweet.id_str, \"maxwidth\": MAX_WIDTH, \"hide_thread\": true, \"omit_script\": true};\r\n\t\t\t\t// request data\r\n\t\t\t\ttwitter.get(OEMBED_URL, params, function (err, data, resp) {\r\n\t\t\t\t\ttweet.oEmbed = data;\r\n\t\t\t\t\toEmbedTweets.push(tweet);\r\n\r\n\t\t\t\t\t// do we have oEmbed HTML for all Tweets?\r\n\t\t\t\t\tif (oEmbedTweets.length == tweets.length) {\r\n\t\t\t\t\t\tcallback (\"OK\", oEmbedTweets);\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t}",
"function createTweet(tweet_id){\n let container = document.createElement('div');\n container.setAttribute('data-tweetid', tweet_id);\n container.classList.add(\"h-justify-center-content\", \"h-align-center-content\", \"h-flex-row-reverse\", \"h-display-none\");\n \n twttr.widgets.createTweet(tweet_id, container, {conversation: 'none'});\n\n return container;\n}",
"function makeTweet(index, tweet, openedTweets) {\n var box = new Box();\n box.right = 320;\n box.height = 65;\n\n box.element().classList.add('tweet');\n\n // Make content.\n var photo = document.createElement('div');\n photo.className = 'photo';\n box.element().appendChild(photo);\n\n var text = document.createElement('div');\n text.className = 'text';\n var user = document.createElement('div');\n user.className = 'username';\n user.textContent = tweet.user;\n text.appendChild(user);\n var tweetText = document.createElement('span');\n tweetText.textContent = tweet.content;\n text.appendChild(tweetText);\n box.element().appendChild(text);\n\n if (tweet.type == 'audio') {\n box.element().classList.add('audio-tweet');\n \n var progress = document.createElement('div');\n progress.className = 'progress';\n box.element().appendChild(progress);\n\n var audioControls = document.createElement('div');\n audioControls.className = 'button';\n audioControls.textContent = 'PLAY AUDIO';\n box.element().appendChild(audioControls);\n\n openedTweets.makeInteractive(index, box, audioControls);\n }\n\n return box;\n}",
"function twitterEmbed() {\n //following converts html from Twitter embed into jquery to build on the fly so not hardcoded into html\n $(\"<a class=twitter-timeline href=https://twitter.com/jessimagallon?ref_src=twsrc%5Etfw>\").append(\"Tweets by jessimagallon\").append(\n $(\"<script async src=https://platform.twitter.com/widgets.js charset=utf-8>\")\n ).appendTo(\"#twitter-list\");\n}",
"function addTweetToPreview(tweet){\n var tweet_time = Date.parse(tweet.created_at)\n var isotime = ISOTime(tweet_time)\n var humantime = elapsedTime(tweet_time)\n var in_reply_to = (tweet.in_reply_to_status_id != null && tweet.in_reply_to_screen_name != null) ? \n ' <a href=\"http://twitter.com/'+tweet.in_reply_to_screen_name+'/status/'+tweet.in_reply_to_status_id+'\">in reply to '+tweet.in_reply_to_screen_name+'</a>' : ''\n var newTweet = new Element('li',{\n 'id' : 'status_'+tweet.id,\n 'class' : 'hentry status u-'+tweet.user.screen_name,\n 'style' : 'left:-100%',\n '_time' : tweet_time})\n var html = ''\n html += ' <div class=\"thumb vcard author\">'\n html += ' <a class=\"url\" href=\"http://twitter.com/'+tweet.user.screen_name+'\">'\n html += ' <img width=\"48\" height=\"48\" src=\"'+tweet.user.profile_image_url+'\" class=\"photo fn\" alt=\"'+tweet.user.name+'\"/>'\n html += ' </a>'\n html += ' </div>'\n html += ' <div class=\"status-body\">'\n html += ' <a class=\"author\" title=\"'+tweet.user.name+'\" href=\"http://twitter.com/'+tweet.user.screen_name+'\">'+tweet.user.screen_name+'</a>'\n html += ' <span class=\"entry-content\">'\n html += ' '+twitter_at_linkify(linkify(tweet.text))\n html += ' </span>'\n html += ' <span class=\"meta entry-meta\">'\n html += ' <a rel=\"bookmark\" class=\"entry-date\" href=\"http://twitter.com/'+tweet.user.screen_name+'/status/'+tweet.id+'\">'\n html += ' <span title=\"'+isotime+'\" class=\"published\">'+humantime+'</span></a> <span>from '+tweet.source+'</span>'+in_reply_to\n html += ' </span>'\n html += ' </div>'\n html += ' <div class=\"actions\">'\n html += ' <a class=\"del\" href=\"#\" id=\"del_'+tweet.id+'\" onclick=\"return removeTweet(this);\">x</a>'\n html += ' </div>'\n newTweet.set('html', html)\n //existing tweets in the quote preview\n var quote_tweets = $$('li')\n if(quote_tweets.length == 1){\n quote_tweets[0].style.display = 'none'\n var container = $('quote')\n newTweet.inject(container)\n } else {\n for(var i=0; i< quote_tweets.length; i++){\n if (tweetComesBefore(newTweet, quote_tweets[i])){\n newTweet.inject(quote_tweets[i],'before')\n quote_tweets[i].style.top = '-'+newTweet.offsetHeight+'px'\n quote_tweets[i].set('tween', {duration: 'short'})\n quote_tweets[i].tween('top', '0px')\n break\n }\n //last position\n if (i == quote_tweets.length-1){\n newTweet.inject(quote_tweets[i],'after')\n }\n }\n }\n updateForm()\n newTweet.set('tween', {duration: 'long'});\n newTweet.tween('left', '0%');\n}",
"async embedTweets(tweets){\n let embedTweets = [];\n for(let index = 0; index < tweets.length; index++){\n let embedTweetData = await this.client.get('statuses/oembed', {id: tweets[index].id_str});\n embedTweets.push(embedTweetData);\n }\n return embedTweets;\n }",
"function embedTweets() {\n\t\tvar tweets = replacementArea.querySelectorAll('.postcontent a[href*=\"twitter.com\"]');\n\n\t\ttweets = Array.prototype.filter.call(tweets, function isTweet(twitterURL) {\n\t\t\treturn twitterURL.href.match(RegExp('https?://(?:[\\\\w\\\\.]*\\\\.)?twitter.com/[\\\\w_]+/status(?:es)?/([\\\\d]+)'));\n\t\t});\n\t\ttweets = Array.prototype.filter.call(tweets, filterNwsAndSpoiler);\n\t\ttweets.forEach(function eachTweet(tweet) {\n\t\t\tvar tweetUrl = tweet.href;\n\t\t\tJSONP.get('https://publish.twitter.com/oembed?omit_script=true&url=' + escape(tweetUrl), {}, function getTworts(data) {\n\t\t\t\tvar div = document.createElement('div');\n\t\t\t\tdiv.classList.add('tweet');\n\t\t\t\ttweet.parentNode.insertBefore(div, tweet);\n\t\t\t\ttweet.parentNode.removeChild(tweet);\n\t\t\t\tdiv.appendChild(tweet);\n\t\t\t\tdiv.innerHTML = data.html;\n\t\t\t\tif (document.getElementById('theme-css').dataset.darkTheme === 'true') {\n\t\t\t\t\tdiv.querySelector('blockquote').dataset.theme = 'dark';\n\t\t\t\t}\n\t\t\t\tif (window.twttr) {\n\t\t\t\t\twindow.twttr.widgets.load(div);\n\t\t\t\t} else {\n\t\t\t\t\tmissedEmbeds.push(div);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}",
"function getEmbeddedTweetHTML(id, callback) {\n var oEmbedSearchURL = config.twitter.oEmbedURL + \"id=\" + id;\n request.get(oEmbedSearchURL, function(error, response, body) {\n if(error) {\n console.log(\"Error - Querying oEmbed Twitter API for id '\" + id + \"' -> \" + e.message);\n callback({});\n }\n\n if(response.statusCode !== 200) {\n console.log(\"Error - Invalid status code returned \", response.statusCode);\n callback({});\n }\n\n var jsonContent = JSON.parse(body);\n callback(jsonContent);\n });\n}",
"function makeTweetDiv (tweet) {\n var newDiv = '<div class=\"tweet\">' +\n '<p>' + tweet.tweet_id + '</p>' +\n '<p>' + tweet.datetime + '</p>' +\n '<p>' + tweet.author + '</p>' +\n '<p>' + tweet.content + '</p>' +\n '</div>';\n\t\n return newDiv;\n}",
"function translateOembedTweet(tweetJSON) {\n var userName = \"\";\n try {\n userName = tweetJSON.author_name;\n }\n catch (e){\n console.log(\"author_name missing in this Tweet.:\" + e.message);\n }\n\n var userLink = \"\";\n try {\n userLink = tweetJSON.author_url;\n }\n catch (e) {\n console.log(\"author_url missing in this Tweet.:\" + e.message);\n }\n\n var tweetLink = \"\";\n try {\n tweetLink = tweetJSON.url;\n }\n catch (e){\n console.log(\"url missing in this Tweet.:\" + e.message);\n }\n\n var tweetText = \"\";\n try {\n var tweetHtml = new DOMParser().parseFromString(tweetJSON.html, 'text/html');\n tweetText = tweetHtml.getElementsByTagName('p')[0].innerHTML;\n }\n catch (e){\n console.log(\"html missing in this Tweet.:\" + e.message);\n }\n\n var tweetTemplate = \"\\n\"\n + \"<div class=\\\"tweet\\\">\\n \"\n + \" <div class=\\\"tweet-body\\\">\"\n + \" <div class=\\\"user-info\\\"> \"\n + \" <span class=\\\"name\\\"> \"\n + \" <a href=\\\"\"\n + userLink\n + \" \\\"> \"\n + \"@\"\n + userName\n + \" </a>\"\n + \" </span> \"\n + \" </div>\\n\t\"\n + \" <div class=\\\"tweet-text\\\">\"\n + tweetText\n + \"\\n <a href=\\\"\"\n + tweetLink\n + \" \\\"> \"\n + \"[more]...\"\n + \" </a>\"\n + \" </div>\\n\t \"\n + \" </div>\\n\t\"\n + \"</div>\\n\";\n\n return tweetTemplate;\n }",
"function placeNewTweet(data) {\n\n if (data) {\n lastTweetId = data[0].id;\n\n var divs = tweetArea.find(\"div\");\n for (var i = 1; i < tweetSpots; i++) {\n $(divs[i]).html = $(divs[i - 1]).html();\n }\n\n $(divs[0]).html = data[0].text;\n }\n }",
"function makeTweet(name, id, content) {\n client.query('INSERT INTO Tweets(userid, content) VALUES ($1, $2)', [id, content], function(err, data) {\n var newTweet = {name: name, content: content};\n postTweet(newTweet);\n });\n }",
"async generate()\r\n {\r\n const { post } = await this.random(this.subreddit);\r\n return new EmbedBuilder()\r\n .setTitle(`r/${this.subreddit} | ${post.title}`)\r\n .setColor(0xFF4500)\r\n .setImage(post.post_hint === 'image'? post.url: null)\r\n .setDescription(post.post_hint !== 'image' && post.selftext.length <= 2000? this.client.util.elipisis(post.selftext.length): post.selftext)\r\n .setTimestamp(new Date(post.created_utc * 1000))\r\n .setFooter(`${this.client.util.formatNumber(post.ups)} upvotes`)\r\n .build();\r\n }",
"function storyID(id) {\n return \"reddit_story_\" + id;\n}",
"function publishNewTweet () {\n document.querySelector(\"form\").reset();\n document.querySelector(\".counter\").innerHTML = 140;\n $.getJSON(\"/tweets/\", function(data) {\n var $happy = createTweetElement(data.slice(-1)[0]);\n $('.freshtweets').prepend($happy);\n })\n }",
"function getTweetDataById(request, response) {\n var tweetDataId = request.swagger.params.tweetDataId.value;\n //const userId = request.swagger.params.userId.value;\n TweetData.findOne({tweetDataId: tweetDataId})\n .populate('author')\n .exec(function(err, tweetData) {\n if(err) {\n response.status(404).json();\n }\n if(!tweetData) {\n response.status(400).json()\n }\n var tweetContent = tweetData.content;\n response.status(200).json({tweetDataId: tweetData.tweetDataId, content: tweetContent,\n dateCreated: new Date().toDateString(tweetData.dateCreated),\n userId: tweetData.author.userId,\n author: tweetData.author.fullName})\n });\n}",
"function updateTweetMessage() {\n var url = URI(\"https://zen-audio-player.github.io\");\n\n var opts = {\n text: \"Listen to YouTube videos without the distracting visuals\",\n hashTags: \"ZenAudioPlayer\",\n url: url.toString()\n };\n\n var id = getCurrentVideoID();\n if (id) {\n url.setSearch(\"v\", id);\n opts.url = url.toString();\n opts.text = \"I'm listening to \" + plyrPlayer.plyr.embed.getVideoData().title;\n }\n\n twttr.widgets.createHashtagButton(\n \"ZenAudioPlayer\",\n document.getElementById(\"tweetButton\"),\n opts\n );\n}",
"function createTweetElement(tweet) {\n let $tweet = $('<article>').addClass(\"tweet\").attr({\"id\": tweet._id});\n let header = $('<header>');\n let content = $('<p>').addClass(\"tweetContent\").text(tweet.content.text);\n let footer = $('<footer>');\n let icons = $('<div>').addClass(\"icons\");\n header.append(\n $('<img>').attr(\"src\", tweet.user.avatars.small),\n $('<span>').addClass(\"userName\").text(tweet.user.name),\n $('<span>').addClass(\"handle\").text(tweet.user.handle)\n );\n icons.append(\n $('<i>').addClass(\"likeBtn\").addClass(\"fas fa-heart\"),\n $('<i>').addClass('fas fa-retweet'),\n $('<i>').addClass('fas fa-flag')\n );\n footer.append(\n $(`<span data-livestamp=\"${(tweet.created_at)/1000}\">`),\n $('<span>').addClass('likeCounter').text(`${tweet.likes} likes`),\n icons);\n $tweet.append(header, content, footer);\n return $tweet[0].outerHTML;\n}",
"function borrarTweet(id){\ntweets = tweets.filter(tweet=> tweet.id !== id )\ncrearHTML()\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function changeProv function loadDistsProv Obtain the list of districts for a specific province in the census as an XML file. Input: prov two character province code | function loadDistsProv(prov)
{
var censusId = document.distForm.censusId.value;
var censusYear = censusId.substring(2);
// get the district information file
HTTP.getXML("CensusGetDistricts.php?Census=" + censusId +
"&Province=" + prov,
gotDistFile,
noDistFile);
} | [
"function loadDistsProv(prov)\n{\n var censusSelect = document.distForm.Census;\n var census = censusSelect.value;\n var censusYear = census.substring(2);\n var xmlName;\n if (censusYear < \"1871\")\n { // pre-confederation\n xmlName = \"CensusGetDistricts.php?Census=\" + prov + censusYear;\n } // pre-confederation\n else\n { // post-confederation\n xmlName = \"CensusGetDistricts.php?Census=\" + census +\n \"&Province=\" + prov;\n } // post-confederation\n var tdNode = document.getElementById('DivisionCell');\n tdNode.innerHTML = '';\n\n // get the district information file \n HTTP.getXML(xmlName,\n gotDistFile,\n noDistFile);\n}",
"function changeProv()\n{\n var provSelect = this;\n var optIndex = provSelect.selectedIndex;\n if (optIndex < 1)\n return; // nothing to do\n var province = provSelect.value;\n var censusId = document.distForm.CensusYear.value;\n var censusYear = censusId.substring(2);\n if (censusYear < \"1867\")\n document.distForm.censusId.value = province + censusYear;\n else\n document.distForm.censusId.value = censusId;\n loadDistsProv(province); // limit the districts selection\n}",
"function loadXMLProvincias(xml)\n{\n\t var i=0; \n //alert(\"XML Root Tag Name: \" + xml.documentElement.tagName);\n var provinces = xml.getElementsByTagName(\"provincia\");\n \n for(i=0; i<provinces.length; i++)\n {\n //The order is >> list[i].tag(id)[0].child.value \n \t var province_id = provinces[i].getElementsByTagName(\"id\")[0].firstChild.nodeValue;\n \t var province_name = provinces[i].getElementsByTagName(\"nombre_provincia\")[0].firstChild.nodeValue;\n \t //Add option\n addOptionProvincias(province_id,province_name);\n }\n}",
"function changeDist(ev)\n{\n // identify the selected census\n var form = document.distForm;\n var censusSelect = form.CensusSel;\n var census = censusSelect.value;\n var censusYear = census.substring(2);\n\n // identify the selected district\n var distSelect = form.District;\n var optIndex = distSelect.selectedIndex;\n if (optIndex < 1)\n return; // no district selected\n var distId = distSelect.options[optIndex].value;\n var tdNode = document.getElementById('DivisionCell');\n tdNode.innerHTML = '';\n\n // identify the file containing subdistrict information for\n // the selected district\n var subFileName;\n var provSelect;\n var provId;\n\n if (censusYear > 1867)\n { // post-confederation, one census for all of Canada\n subFileName = \"CensusGetSubDists.php?Census=\" + census +\n \"&District=\" + distId;\n } // post-confederation, one census for all of Canada\n else\n { // pre-confederation, separate census for each colony\n provSelect = form.Province;\n optIndex = provSelect.selectedIndex;\n if (optIndex < 0)\n return; // no colony selected\n provId = provSelect.options[optIndex].value;\n subFileName = \"CensusGetSubDists.php?Census=\" +\n provId + censusYear +\n \"&District=\" + distId;\n } // pre-confederation, separate census for each colony\n // get the subdistrict information file\n //alert(\"ReqUpdatePages.js: changeDist: subFileName=\" + subFileName);\n HTTP.getXML(subFileName,\n gotSubDist,\n noSubDist);\n\n}",
"onChangeProvincies() {\n this.editedItem.selectDistrict = { code: \"default\", name: \"default\" };\n var selected = this.editedItem.selectProvince;\n var found = this.depProvinces.find(element => {\n if (element.code === selected.code) {\n return element;\n }\n return null;\n });\n if (!!found) {\n this.proDistricts = found.districts;\n }\n }",
"cambioProvincia() {\n for (var i = 0; i < this.provincias.length; i++) {\n if (this.provincias[i].nombre == this.provinciaSeleccionada)\n this.getLocalidades(this.provincias[i].idProvincia);\n }\n }",
"function loadProvince(event){\n\t\t\tselectProvince.html('<option value=\"\">Select Provinces...</option>');\n\t\t\tfor (i in provinces) {\n\t\t\t\tif ( provinces[i].provCode.indexOf(event.target.value) == 0 ) {\n\t\t\t\t\tselectProvince.append($('<option>', {\n\t\t\t\t\t value: provinces[i].provCode,\n\t\t\t\t\t text: provinces[i].provDesc\n\t\t\t\t\t}));\n\t\t\t\t}\n\t\t\t}\n\t\t}",
"function loadprovinces(country){\n\tvar req = new XMLHttpRequest();\n\treq.onreadystatechange = function(){\n\t\tif (req.readyState == 4 && req.status == 200){\n\t\t\tvar provArray = JSON.parse(req.responseText);\n\t\t\tvar provSelect = document.getElementById(\"custProv\");\n\t\t\tclearSelect(provSelect); //clear dropdown before loading\n\t\t\tfor (i=0; i<provArray.length; i++){\n\t\t\t\tvar prov = provArray[i];\n\t\t\t\tvar option = document.createElement(\"option\");\n\t\t\t\toption.text = prov.provName;\n\t\t\t\toption.value = prov.provCode;\n\t\t\t\tprovSelect.add(option); \n\t\t\t}\n\t\t}\n\t};\n\treq.open(\"GET\", \"http://localhost:8080/TravelExperts/rs/province/getprovincesfromcountry/\" + country);\n\treq.send();\n}",
"function select_prov(id, prov) {\n // hilangkan list kecamatan\n list_prov.style.display = \"none\";\n list_prov.innerHTML = \"\";\n // simpan id provinsi dalam value input id_prov untuk disimpan\n id_prov.value = id;\n // tampilkan nama provinsi dalam value input nm_prov agar tetap terlihat nama provinsi yang dipilih\n nm_prov.value = prov.trim();\n // aktifkan input kab/kota\n document.getElementById('nm_kab').disabled = false;\n document.getElementById('nm_kab').focus();\n }",
"function caricaProvince(value){\n //svuota il contenuto della select sia delle province che dei comuni\n document.getElementById(\"provincia\").innerHTML=\"\";\n document.getElementById(\"comune\").innerHTML=\"\";\n var option = document.createElement(\"option\");\n document.getElementById(\"provincia\").append(option);\n\n var xhttp= new XMLHttpRequest();\n xhttp.onreadystatechange = function() {\n if (this.readyState == 4 && this.status == 200) {\n var province=this.responseXML;\n var id_regione=getIdByNomeRegione(xmlRegioni, value);\n console.log(\"Id regione: \"+id_regione);\n //scorre tutte le province nell'xml delle province e seleziona solo quelle con id della regione uguale alla regione scelta\n //e mette tutti valori in degli option che verrano appesi alla select delle province\n for (var i = 0; i < 110; i++) {\n //console.log(province.getElementsByTagName(\"provincia\")[i].getElementsByTagName(\"campo\")[1].childNodes[0].nodeValue);\n if(province.getElementsByTagName(\"provincia\")[i].getElementsByTagName(\"campo\")[1].childNodes[0].nodeValue==id_regione){\n var nome = province.getElementsByTagName(\"provincia\")[i].getElementsByTagName(\"campo\")[3].childNodes[0].nodeValue;\n var option = document.createElement(\"option\");\n var valueAttr=document.createAttribute(\"value\");\n valueAttr.value=nome;\n option.setAttributeNode(valueAttr);\n option.innerHTML = nome;\n document.getElementById(\"provincia\").append(option);\n //memorizzazzione xml regioni per utilizzi successivi\n xmlProvince=province;\n }\n }\n }\n }\n xhttp.open(\"GET\", \"xml/province.xml\", true);\n xhttp.send();\n}",
"function listProvinces()\n\t{\n\t\tvar Provinces=Parse.Object.extend(\"Provinces\");\n\t\tvar query=new Parse.Query(Provinces);\n\t\t\n\t\tquery.find(\n\t\t{\n\t\t\tsuccess:function(province){\n\t\t\t\tconsole.log(INFO + 'Those Results has been given ' + province.length);\n\t\t\t\t\n\t\t\t\tvar $datalist=$('#province');\n\t\t\t\tfor(var i=0;i<province.length;i++)\n\t\t\t\t{\n\t\t\t\t\tvar prov=province[i];\n\t\t\t\t\tconsole.log(INFO + 'Provinces: ' + prov.get('name'));\n\t\t\t\t\t$datalist.append('<option value=\"'+prov.get('name')+'\"/>');\n\t\t\t\t}\n\t\t\t},\n\t\t\terror:function(province,error)\n\t\t\t{\n\t\t\t\tconsole.error(FAIL + 'Ops! Something was wrong. Reason: ' + error.message);\n\t\t\t}\n\t\t});\n\t}",
"function districtMap(county_select_key) {\n\n var county_string = county_select_key;\n\n $(\"#C2 #patient_district_of_residence\").empty() //delete all options under the select with id = \"district\n\n html_district = \"<option value=\" + \">--Select--</option>\" //make the default option blank\n\n district_for_county = liberia_counties[county_string];\n\n for (var district in district_for_county) {\n\n html_district += \"<option value=\" + district_for_county[district] + \">\" +district_for_county[district]+\"</option>\"\n }\n\n $(\"#C2 #patient_district_of_residence\").append(html_district);\n }",
"function loadProvinces(){\n // Provinces array here\n\tvar provArray=[\"Ontario\",\"Quebec\",\"British Columbia\",\"Alberta\",\n\t\"Manitoba\",\"Saskatchewan\",\"Acotia\",\"Brunswick\",\"Newfoundland\",\n\t\"Edward Island\",\"Northwest Territores\",\"Nunavut\",\"Yukon\"]\n\tvar output=\"<option value=''>-Select-</option>\";\n // forLoop\n\tfor(index=0;index<provArray.length;index++){\n\t\toutput+=\"<option value='\"+provArray[index]+\"'>\"+\n\t\tprovArray[index]+\"</option>\";\n\t}\n // document gets elements from html 'id'\n\tdocument.getElementById('cboProv').innerHTML=output;\n}",
"function setearProvinciaLocalidad(provincia,localidad){\n // Primero busca en la tabla de provincias alguno que coincida.\n for (i=0; i < $rootScope.provinces.length; i++){\n if (provincia == $rootScope.provinces[i][1]) {\n // Si lo encuentra lo setea.\n $rootScope.userRegistration.provinces= $rootScope.provinces[i];\n\n // Despues busca en la tabla de localidades cuales pertenecen a la provincia en cuestion.\n for (i=0; i< $rootScope.localidad.length ; i++){\n if ($rootScope.userRegistration.provinces[0] == $rootScope.localidad[i][1]) {\n if (localidad == $rootScope.localidad[i][2]) {\n $rootScope.userRegistration.locality= $rootScope.localidad[i][2];\n }\n }\n }\n }\n }\n }",
"function loadProvinces() {\n\tvar provinces = [];\n\tfor (var i = 0, len = provinceDataFiles.length; i < len; i++) {\n\t\tvar provinceShape = d3.json('geodata/' + provinceDataFiles[i]);\n\t\tprovinces.push(provinceShape);\n\t}\n\treturn provinces;\n}",
"function populateDistricts() {\n\n\tvar countyId = $('#select_filter_districts_by_county').val();\n\tvar searchDistrict = $(\"#id_input_search_district\").val();\n\n\trequest_url = DISTRICTS_URL;\n\trequest_params = ACTION_TYPE + \"=\" + ACTION_QUERY + \"&\" + SEARCH_KEY + \"=\"\n\t\t\t+ searchDistrict + \"&county=\" + countyId;\n\trequest_intent = INTENT_QUERY_DISTRICTS;\n\tsendPOSTHttpRequest(request_url, request_params, request_intent);\n}",
"function showProvince(response)\n{\n var rootNode=response.responseXML.documentElement;\n var province_list_=rootNode.getElementsByTagName('province_list_')[0].firstChild.data;\n var unis_list_=rootNode.getElementsByTagName('univ_list_')[0].firstChild.data;\n document.getElementById(\"popup-province\").innerHTML=province_list_;\n document.getElementById(\"popup-unis\").innerHTML=unis_list_;\n}",
"function prepareEventHandlersThree(){\r\n var provList = document.getElementById(\"selectProv\");\r\n var selectProv = document.getElementById(\"provList\");\r\n var selectProvHidden = document.getElementById(\"selectProvHidden\");\r\n\r\n provList.onchange = function() {\r\n var newDoc = provList.value;\r\n var listIndex = provList.selectedIndex;\r\n var option = document.createElement(\"option\");\r\n option.text = newDoc;\r\n selectProv.add(option);\r\n provList.remove(listIndex);\r\n selectProvHidden.remove(listIndex);\r\n }\r\n}",
"function changeCensus(ev)\n{\n let censusSelect = this;\n let censusOptions = this.options;\n let censusElt = document.distForm.censusId;\n let provSelect = document.distForm.Province;\n let distSelect = document.distForm.District;\n let censusId;\n\n if (this.selectedIndex > 0)\n { // option chosen\n let currCensusOpt = censusOptions[this.selectedIndex];\n let censusId = currCensusOpt.value;\n\n if (censusId.length > 0)\n { // non-empty option chosen\n censusElt.value = censusId;\n provSelect.options.length = 1; // clear the list\n let options = {};\n options.errorHandler = function() {alert('script getRecordJSON.php not found')};\n HTTP.get('/getRecordJSON.php?table=Censuses&id=' + censusId +\n '&lang=' + lang,\n gotCensus,\n options);\n } // non-empty option chosen\n } // census chosen\n else\n {\n provSelect.options.length = 1;\n distSelect.options.length = 1;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Invalidates (clears) the references collection. This should be called anytime the AST has been manipulated. | invalidateReferences() {
this._references = undefined;
} | [
"updateReferences() {\n for (let variable in this.referencedVariables) {\n this.referencedVariables[variable].referenced = 0;\n }\n this.currentVariables.forEach(d => this.setReferences(d.id));\n this.savedReferences.forEach(d => this.setReferences(d));\n for (let variable in this.referencedVariables) {\n if (this.referencedVariables[variable].referenced === 0) {\n delete this.referencedVariables[variable]\n }\n }\n }",
"clearRefs() {\n for(const [elem, refs] of this.doc.__refs.entries()) {\n for(const type of refs.keys()) {\n const ref = elem.getAttr(type)\n if(Array.isArray(ref)) {\n ref.includes(this) && elem.setAttr(type, ref.filter(item => item !== this))\n }\n else ref === this && elem.removeAttr(type)\n }\n }\n }",
"_deleteReferences() {\n delete this._factory;\n delete this._map;\n delete this._options;\n }",
"unsetReferences() {\n // Override in child classes\n }",
"invalidate() {\n this.isValidated = false;\n //clear out various lookups (they'll get regenerated on demand the next time they're requested)\n this.cache.clear();\n }",
"free(address) {\n if (address >= 0 && address < this.locations.length) {\n\n let value = this.locations[address];\n\n // Decrements the number of references to this object\n this.references[address]--;\n\n // This means the object is not stored anywhere\n // So all its references can also be freed\n if (this.references[address] == 0) {\n this.locations[address] = undefined;\n\n if (value != undefined) {\n value.address = undefined;\n\n // Recursively frees all its references\n let addresses = value.getReferences();\n for (let add of addresses) {\n this.free(add);\n }\n }\n\n // Mark this address as free\n this.freeAddresses.push(address);\n } else if (this.references[address] < 0) {\n console.log(\"hmm.....\")\n this.references[address] = 0;\n throw new Error();\n }\n }\n }",
"async _invalidations() {\n let schema = await this.schema();\n let pendingOps = [];\n let references = await this._findTouchedReferences();\n for (let { type, id } of references) {\n let key = `${type}/${id}`;\n if (!this._touched[key]) {\n this._touched[key] = true;\n pendingOps.push((async ()=> {\n let resource = await this.read(type, id);\n if (resource) {\n let sourceId = schema.types.get(type).dataSource.id;\n let nonce = 0;\n await this.add(type, id, resource, sourceId, nonce);\n }\n })());\n }\n }\n await Promise.all(pendingOps);\n }",
"end() {\n this._resolver\n .getDependencyGraph()\n .getWatcher()\n .removeListener('change', this._handleMultipleFileChanges);\n\n // Clean up all the cache data structures to deallocate memory.\n this._dependencies = new Set();\n this._shallowDependencies = new Map();\n this._modifiedFiles = new Set();\n this._dependencyPairs = new Map();\n this._modulesByName = new Map();\n }",
"findReferences() {\n this._references = new References();\n const excludedExpressions = new Set();\n const visitCallExpression = (e) => {\n for (const p of e.args) {\n this._references.expressions.add(p);\n }\n //add calls that were not excluded (from loop below)\n if (!excludedExpressions.has(e)) {\n this._references.expressions.add(e);\n }\n //if this call is part of a longer expression that includes a call higher up, find that higher one and remove it\n if (e.callee) {\n let node = e.callee;\n while (node) {\n //the primary goal for this loop. If we found a parent call expression, remove it from `references`\n if ((0, reflection_1.isCallExpression)(node)) {\n this.references.expressions.delete(node);\n excludedExpressions.add(node);\n //stop here. even if there are multiple calls in the chain, each child will find and remove its closest parent, so that reduces excess walking.\n break;\n //when we hit a variable expression, we're definitely at the leftmost expression so stop\n }\n else if ((0, reflection_1.isVariableExpression)(node)) {\n break;\n //if\n }\n else if ((0, reflection_1.isDottedGetExpression)(node) || (0, reflection_1.isIndexedGetExpression)(node)) {\n node = node.obj;\n }\n else {\n //some expression we don't understand. log it and quit the loop\n this.logger.info('Encountered unknown expression while calculating function expression chain', node);\n break;\n }\n }\n }\n };\n this.ast.walk((0, visitors_1.createVisitor)({\n AssignmentStatement: s => {\n this._references.assignmentStatements.push(s);\n this.references.expressions.add(s.value);\n },\n ClassStatement: s => {\n this._references.classStatements.push(s);\n },\n ClassFieldStatement: s => {\n if (s.initialValue) {\n this._references.expressions.add(s.initialValue);\n }\n },\n NamespaceStatement: s => {\n this._references.namespaceStatements.push(s);\n },\n FunctionStatement: s => {\n this._references.functionStatements.push(s);\n },\n ImportStatement: s => {\n this._references.importStatements.push(s);\n },\n LibraryStatement: s => {\n this._references.libraryStatements.push(s);\n },\n FunctionExpression: (expression, parent) => {\n if (!(0, reflection_1.isMethodStatement)(parent)) {\n this._references.functionExpressions.push(expression);\n }\n },\n NewExpression: e => {\n this._references.newExpressions.push(e);\n for (const p of e.call.args) {\n this._references.expressions.add(p);\n }\n },\n ExpressionStatement: s => {\n this._references.expressions.add(s.expression);\n },\n CallfuncExpression: e => {\n visitCallExpression(e);\n },\n CallExpression: e => {\n visitCallExpression(e);\n },\n AALiteralExpression: e => {\n this.addPropertyHints(e);\n this._references.expressions.add(e);\n for (const member of e.elements) {\n if ((0, reflection_1.isAAMemberExpression)(member)) {\n this._references.expressions.add(member.value);\n }\n }\n },\n BinaryExpression: (e, parent) => {\n //walk the chain of binary expressions and add each one to the list of expressions\n const expressions = [e];\n let expression;\n while ((expression = expressions.pop())) {\n if ((0, reflection_1.isBinaryExpression)(expression)) {\n expressions.push(expression.left, expression.right);\n }\n else {\n this._references.expressions.add(expression);\n }\n }\n },\n ArrayLiteralExpression: e => {\n for (const element of e.elements) {\n //keep everything except comments\n if (!(0, reflection_1.isCommentStatement)(element)) {\n this._references.expressions.add(element);\n }\n }\n },\n DottedGetExpression: e => {\n this.addPropertyHints(e.name);\n },\n DottedSetStatement: e => {\n this.addPropertyHints(e.name);\n },\n EnumStatement: e => {\n this._references.enumStatements.push(e);\n },\n ConstStatement: s => {\n this._references.constStatements.push(s);\n },\n UnaryExpression: e => {\n this._references.expressions.add(e);\n },\n IncrementStatement: e => {\n this._references.expressions.add(e);\n }\n }), {\n walkMode: visitors_1.WalkMode.visitAllRecursive\n });\n }",
"applyObjectFreeing(refs) {\n // write free object head\n let head = this.parser.documentHistory.createObjectLookupTable()[0];\n let last_freed_object_id = head.id;\n let freed_objs = refs.filter(r => r.free);\n freed_objs = freed_objs.sort((a, b) => {\n if (a.id < b.id)\n return -1;\n if (a.id > b.id)\n return 1;\n return 0;\n });\n let lastobj = undefined;\n for (let obj of freed_objs) {\n if (!lastobj) {\n // set first object as list header\n head.pointer = obj.id;\n }\n if (lastobj) {\n lastobj.pointer = obj.id;\n }\n lastobj = obj;\n }\n if (freed_objs.length > 0)\n freed_objs[freed_objs.length - 1].pointer = last_freed_object_id;\n refs.push(head);\n return refs;\n }",
"validateReferences() {\n this.dataobjectreferences.forEach(function(compoundReference) {\n // Split compound reference into individual references\n var individualReferences = compoundReference.split(',');\n individualReferences.forEach(function(reference) {\n this.validateReference(reference.trim());\n }.bind(this));\n }.bind(this));\n }",
"reset() {\n\t\tthis._changesInElement.clear();\n\t\tthis._elementSnapshots.clear();\n\t\tthis._changedMarkers.clear();\n\t\tthis._cachedChanges = null;\n\t}",
"removeReference() {\n this.m_referenceCount -= 1;\n if (this.m_referenceCount === 0) {\n this.destroy();\n }\n }",
"reset() {\n\t\tthis._changesInElement.clear();\n\t\tthis._elementSnapshots.clear();\n\t\tthis._changedMarkers.clear();\n\t\tthis._refreshedItems = new Set();\n\t\tthis._cachedChanges = null;\n\t}",
"clearBindings() {\n\t\tthis._modelToViewMapping = new WeakMap();\n\t\tthis._viewToModelMapping = new WeakMap();\n\t\tthis._markerNameToElements = new Map();\n\t\tthis._elementToMarkerNames = new Map();\n\t\tthis._unboundMarkerNames = new Set();\n\t\tthis._deferredBindingRemovals = new Map();\n\t}",
"function garbageCollect(){\n if(!Ext.enableGarbageCollector){\n clearInterval(El.collectorThread);\n } else {\n var eid,\n el,\n d;\n\n for(eid in El.cache){\n el = El.cache[eid];\n d = el.dom;\n // -------------------------------------------------------\n // Determining what is garbage:\n // -------------------------------------------------------\n // !d\n // dom node is null, definitely garbage\n // -------------------------------------------------------\n // !d.parentNode\n // no parentNode == direct orphan, definitely garbage\n // -------------------------------------------------------\n // !d.offsetParent && !document.getElementById(eid)\n // display none elements have no offsetParent so we will\n // also try to look it up by it's id. However, check\n // offsetParent first so we don't do unneeded lookups.\n // This enables collection of elements that are not orphans\n // directly, but somewhere up the line they have an orphan\n // parent.\n // -------------------------------------------------------\n if(!d || !d.parentNode || (!d.offsetParent && !DOC.getElementById(eid))){\n delete El.cache[eid];\n if(d && Ext.enableListenerCollection){\n Ext.EventManager.removeAll(d);\n }\n }\n }\n }\n}",
"function _garbageCollect( collection, previous, options ){\n\t var _byId = collection._byId,\n\t silent = options.silent;\n\t\n\t // Filter out removed models and remove them from the index...\n\t for( var i = 0; i < previous.length; i++ ){\n\t var model = previous[ i ];\n\t\n\t if( !_byId[ model.cid ] ){\n\t silent || trigger3( model, 'remove', model, collection, options );\n\t removeReference( collection, model );\n\t }\n\t }\n\t}",
"clearVisited() {\n for (const groupState of this.m_referenceMap.values()) {\n groupState.visited = false;\n }\n }",
"invalidate() {\n if (!this._valid) return;\n this._valid = false;\n this.invokeObservers('invalidate');\n this.observers = {};\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper to transform a JSX identifier into a normal reference. | function toReference(t, node, identifier) {
if (t.isIdentifier(node)) {
return node;
} else if (t.isJSXIdentifier(node)) {
return identifier ? t.identifier(node.name) : t.stringLiteral(node.name);
} else {
return node;
}
} | [
"function toReference(node) {\n var identifier = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n if (typeof node === \"string\") {\n return node.split(\".\").map(function (s) {\n return t.identifier(s);\n }).reduce(function (obj, prop) {\n return t.memberExpression(obj, prop);\n });\n }\n\n if (t.isJSXIdentifier(node)) {\n return identifier ? t.identifier(node.name) : t.stringLiteral(node.name);\n }\n\n if (t.isJSXMemberExpression(node)) {\n return t.memberExpression(toReference(node.object, true), toReference(node.property, true));\n }\n\n return node;\n }",
"function toReference(node) {\n var identifier = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];\n\n if (typeof node === \"string\") {\n return node.split(\".\").map(function (s) {\n return t.identifier(s);\n }).reduce(function (obj, prop) {\n return t.memberExpression(obj, prop);\n });\n }\n\n if (t.isJSXIdentifier(node)) {\n return identifier ? t.identifier(node.name) : t.stringLiteral(node.name);\n }\n\n if (t.isJSXMemberExpression(node)) {\n return t.memberExpression(toReference(node.object, true), toReference(node.property, true));\n }\n\n return node;\n}",
"function getQualifiedJSXName(object){if(object.type==='JSXIdentifier')return object.name;if(object.type==='JSXNamespacedName')return object.namespace.name+':'+object.name.name;if(object.type==='JSXMemberExpression')return getQualifiedJSXName(object.object)+'.'+getQualifiedJSXName(object.property);}// Parse next token as JSX identifier",
"function getQualifiedJSXName(object){if(object.type === 'JSXIdentifier')return object.name;if(object.type === 'JSXNamespacedName')return object.namespace.name + ':' + object.name.name;if(object.type === 'JSXMemberExpression')return getQualifiedJSXName(object.object) + '.' + getQualifiedJSXName(object.property);} // Parse next token as JSX identifier",
"function getQualifiedJSXName(object){if(object.type==='JSXIdentifier')return object.name;if(object.type==='JSXNamespacedName')return object.namespace.name+':'+object.name.name;if(object.type==='JSXMemberExpression')return getQualifiedJSXName(object.object)+'.'+getQualifiedJSXName(object.property);} // Parse next token as JSX identifier",
"function transformRef(ref) {\n const parts = ref.replace(/^#\\//, '').split('/');\n return `${parts[0]}[\"${parts.slice(1).join('\"][\"')}\"]`;\n}",
"function JSXIdentifier(node) {\n this.push(node.name);\n}",
"function resolveIdentifier(value) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvar reference = value || '';\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn reference.toString();\n\t\t\t\t\t\t\t\t\t\t\t\t}",
"function renderReference(ref) {\n return `{${ref.target.node.path}[${ref.displayName}]}`;\n}",
"function getQualifiedJSXName(object) {\n if (object.type === \"JSXIdentifier\") {\n return object.name;\n }\n\n if (object.type === \"JSXNamespacedName\") {\n return object.namespace.name + \":\" + object.name.name;\n }\n\n if (object.type === \"JSXMemberExpression\") {\n return getQualifiedJSXName(object.object) + \".\" + getQualifiedJSXName(object.property);\n }\n } // Parse next token as JSX identifier",
"function jsxParseIdentifier() {\n nextJSXTagToken();\n}",
"function JSXIdentifier(node) {\n\t this.push(node.name);\n\t}",
"function extractValueFromJSXElement(value) {\n return \"<\" + value.openingElement.name.name + \" />\";\n}",
"function removeIdentifierReferences(node, name) {\n const result = ts.transform(node, [context => root => ts.visitNode(root, function walk(current) {\n return ts.isIdentifier(current) && current.text === name ?\n ts.createIdentifier(current.text) :\n ts.visitEachChild(current, walk, context);\n })]);\n return result.transformed[0];\n }",
"function idFromReference(url) {\n var m = url.toString().match(SVG.regex.reference)\n \n if (m) return m[1]\n }",
"function render_id(identifier) {\n const items = identifier.split('/');\n return items[items.length - 1];\n}",
"function idFromReference(url) {\r\n\t var m = url.toString().match(SVG.regex.reference)\r\n\r\n\t if (m) return m[1]\r\n\t}",
"function strtoid(name) {\n return new js.Identifier(name);\n}",
"function idFromReference(url) {\n var m = (url || '').toString().match(SVG.regex.reference)\n\n if (m) return m[1]\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
endregion region Test Helpers Populate a metadataStore with Northwind service CSDL metadata | function northwindMetadataStoreSetup(metadataStore) {
if (!metadataStore.isEmpty()) return; // got it already
metadataStore.importMetadata(northwindMetadata);
metadataStore.addDataService(
new breeze.DataService({ serviceName: northwindService })
);
} | [
"function moduleMetadataStoreSetup() {\n breeze.config.initializeAdapterInstance(\"modelLibrary\", modelLibrary, true);\n if (!firstTime) return; // got metadata already\n\n firstTime = true;\n moduleMetadataStore = new MetadataStore();\n stop(); // going async for metadata ...\n Q.all([\n moduleMetadataStore.fetchMetadata(northwindService),\n moduleMetadataStore.fetchMetadata(todoService)\n ]).fail(handleFail).fin(start);\n }",
"function fillMetadataStore() {\n // namespace of the corresponding classes on the server\n var namespace = '';\n\n // Breeze Labs: breeze.metadata.helper.js\n // https://github.com/IdeaBlade/Breeze/blob/master/Breeze.Client/Scripts/Labs/breeze.metadata-helper.js\n // The helper reduces data entry by applying common conventions\n // and converting common abbreviations (e.g., 'type' -> 'dataType')\n var helper = new breeze.config.MetadataHelper(namespace, breeze.AutoGeneratedKeyType.Identity);\n\n // addType - make it easy to add the type to the store using the helper\n var addType = function (typeDef) {\n var entityType = helper.addTypeToStore(metadataStore, typeDef);\n addDefaultSelect(entityType);\n return entityType;\n };\n\n // create the entity metadata and add to the store\n addLearningPathType();\n addLearningItemType();\n\n // add 'defaultSelect' custom metadata that selects for all mapped data properties\n // could be used by SharePoint dataservice adapter to exclude unwanted property data\n // in query payload\n function addDefaultSelect(type) {\n var custom = type.custom;\n // bail out if defined by hand already\n if (custom && custom.defaultSelect != null) { return; }\n\n var select = [];\n type.dataProperties.forEach(function (prop) {\n if (!prop.isUnmapped) { select.push(prop.name); }\n });\n if (select.length) {\n if (!custom) { type.custom = custom = {}; }\n custom.defaultSelect = select.join(',');\n }\n return type;\n }\n\n // add the learning path type to the metadata store\n function addLearningPathType() {\n addType({\n name: 'LearningPath',\n defaultResourceName: 'getbytitle(\\'Learning Paths\\')/items',\n dataProperties: {\n Id: { type: breeze.DataType.Int32 },\n Title: { nullable: false },\n OData__Comments: {},\n Created: { type: breeze.DataType.DateTime },\n Modified: { type: breeze.DataType.DateTime }\n },\n navigationProperties: {\n LearningItems: {\n type: 'LearningItem',\n hasMany: true\n }\n }\n });\n }\n\n // add the learning item type to the metadata store\n function addLearningItemType() {\n addType({\n name: 'LearningItem',\n defaultResourceName: 'getbytitle(\\'Learning Items\\')/items',\n dataProperties: {\n Id: { type: breeze.DataType.Int32 },\n Title: { nullable: false },\n ItemType: { nullable: false },\n OData__Comments: {},\n Url: {\n nullable: false,\n validators: [breeze.Validator.url()]\n },\n LearningPathId: {\n type: breeze.DataType.Int32,\n nullable: false\n },\n Created: { type: breeze.DataType.DateTime },\n Modified: { type: breeze.DataType.DateTime }\n },\n navigationProperties: {\n LearningPath: 'LearningPath'\n }\n });\n }\n }",
"function createMetadataStore(serviceName) {\n\n var store = new breeze.MetadataStore();\n var defaultNamespace = 'Northwind.Models';\n var defaultKeyGen = breeze.AutoGeneratedKeyType.Identity;\n var helper = new breeze.config.MetaDataHelper(defaultNamespace, defaultKeyGen);\n\n helper.addDataService(store, serviceName);\n\n // Add types in alphabetical order ... because we can\n addCategoryType(store);\n\n return store;\n }",
"function moduleMetadataStoreSetup(callback) {\n if (!moduleMetadataStore.isEmpty()) { // got it already\n callback();\n return;\n }\n\n stop(); // going async for metadata ...\n moduleMetadataStore.fetchMetadata(northwindService)\n .then(callback)\n .fail(handleFail)\n .fin(start);\n }",
"function preFetchMetadataStore(dataService, metadataStore){\n if (typeof(dataService) === 'string' ){\n dataService = new breeze.DataService();\n }\n if (dataService instanceof breeze.DataService){\n if (!metadataStore) {\n metadataStore = new breeze.MetadataStore();\n }\n if (metadataStore.isEmpty()){\n var metadata = serverMetadata[dataService.serviceName];\n if (metadata){\n metadataStore.importMetadata(metadata);\n metadataStore.addDataService(dataService);\n } else {\n preFetchMetadataInBeforeHook(dataService, metadataStore);\n }\n }\n return metadataStore;\n } else {\n throw new Error('preFetchMetadataStore failed: \"dataService\" must be a string or a breeze.DataService.');\n }\n\n function preFetchMetadataInBeforeHook(){\n before(function(done){\n metadataStore.fetchMetadata(dataService)\n .then(function(data){\n metadataStore.addDataService(dataService, true);\n serverMetadata[dataService.serviceName] = JSON.stringify(data);\n done();\n }, done);\n });\n }\n }",
"function importNorthwindMetadata(metadataStore) {\n importMetadata(metadataStore, docCode.northwindMetadata, testFns.northwindServiceName );\n }",
"function importMetadata(metadataStore, metadata, dataService) {\n if (!metadata){\n throw new Error('testFns#importMetadata: no metadata to import');\n }\n if (!metadataStore){\n metadataStore = new breeze.MetadataStore();\n } else if (metadataStore instanceof breeze.EntityManager){\n // gave us an EM; get the store from there\n var em = metadataStore;\n metadataStore = em.metadataStore;\n dataService = em.dataService;\n }\n metadataStore.importMetadata(metadata);\n\n // optionally associate these metadata data with the dataService\n if (dataService) {\n if (typeof dataService === 'string'){ // given dataService name\n dataService = new breeze.DataService({ serviceName: dataService });\n }\n metadataStore.addDataService(dataService);\n }\n }",
"function populateMetadataStore(newEm, metadataSetupFn) {\n\n var metadataStore = newEm.options.metadataStore;\n\n // Check if the module metadataStore is empty\n if (!metadataStore.isEmpty()) {\n return breeze.Q(true); // ok ... it's been populated ... we're done.\n }\n\n // It's empty; get metadata\n var serviceName = newEm.options.serviceName;\n\n return metadataStore.fetchMetadata(serviceName)\n .then(function () {\n if (typeof metadataSetupFn === 'function') {\n metadataSetupFn(metadataStore);\n }\n })\n .fail(handleFail);\n }",
"function makeNorthwindConventionMetadataStore() {\n var metadataStore =\n new MetadataStore({ namingConvention: new NorthwindNamingConvention() });\n\n northwindMetadataStoreSetup(metadataStore);\n return metadataStore;\n }",
"function importNorthwindMetadata(metadataStore) {\n importMetadata(metadataStore, ash.northwindMetadata, ash.northwindServiceName );\n }",
"function createEmployeeMetadataStore(dataservice) {\n\n var dayScheduleEntityName = 'DaySchedule';\n var employeeEntityName = 'Employee';\n var attendanceDayEntityName = 'AttendanceDay';\n\n var metadataStore = createMetadataStore();\n\n addDataService(metadataStore, dataservice);\n\n setDefaultNamespace(testFns.northwindDtoNamespace);\n\n // Add types in alphabetical order ... because we can\n addAttendanceDayType(metadataStore);\n addDayScheduleType(metadataStore);\n addEmployeeType(metadataStore);\n\n return metadataStore;\n\n\n //#region Employee\n function addEmployeeType(store) {\n var et = {\n name: employeeEntityName,\n autoGeneratedKeyType: Identity,\n dataProperties: {\n id: { type: breeze.DataType.Int32 },\n },\n\n navigationProperties: {\n schedules: { entityTypeName: dayScheduleEntityName, hasMany: true },\n attendanceDays: { entityTypeName: attendanceDayEntityName, hasMany: true },\n }\n };\n\n return addTypeToStore(store, et);\n }\n\n //#endregion\n\n //#region DaySchedule\n function addDayScheduleType(store) {\n var et = {\n name: dayScheduleEntityName,\n autoGeneratedKeyType: Identity,\n dataProperties: {\n id: { type: breeze.DataType.Int32 },\n employeeId: { type: breeze.DataType.Int32 },\n },\n\n navigationProperties: {\n employee: employeeEntityName,\n }\n };\n\n return addTypeToStore(store, et);\n }\n\n //#endregion\n\n //#region AttendanceDay\n function addAttendanceDayType(store) {\n var et = {\n name: attendanceDayEntityName,\n autoGeneratedKeyType: Identity,\n dataProperties: {\n id: { type: breeze.DataType.Int32 },\n employeeId: { type: breeze.DataType.Int32 },\n },\n\n navigationProperties: {\n employee: employeeEntityName,\n }\n };\n\n return addTypeToStore(store, et);\n }\n\n //#endregion\n }",
"function importMetadata(metadataStore, metadata, dataService) {\n if (!metadata){\n throw new Error('ash#importMetadata: no metadata to import');\n }\n if (!metadataStore){\n metadataStore = new breeze.MetadataStore();\n } else if (metadataStore instanceof breeze.EntityManager){\n // gave us an EM; get the store from there\n var em = metadataStore;\n metadataStore = em.metadataStore;\n dataService = em.dataService;\n }\n metadataStore.importMetadata(metadata);\n\n // optionally associate these metadata data with the dataService\n if (dataService) {\n if (typeof dataService === 'string'){ // given dataService name\n dataService = new breeze.DataService({ serviceName: dataService });\n }\n metadataStore.addDataService(dataService);\n }\n }",
"function clientMetadataStore(txn) {\n return txn.store(DbClientMetadata.store);\n}",
"function getMetadataStore() {\n\n var metadataStore = metadata.createMetadataStore();\n\n // convenience method for registering model types with the store\n // these model types contain extensions to the type definitions from metadata.js\n var registerType = metadataStore.registerEntityTypeCtor.bind(metadataStore);\n\n registerType('User', UserModelService.model);\n\n return metadataStore;\n \n }",
"function makeCamelCaseConventionMetadataStore() {\n var metadataStore =\n new MetadataStore({ namingConvention: breeze.NamingConvention.camelCase });\n\n northwindMetadataStoreSetup(metadataStore);\n return metadataStore;\n }",
"function clientMetadataStore(txn) {\n return txn.store(DbClientMetadata.store);\n}",
"function MetadataProvider() {\n}",
"function clientMetadataStore(txn) {\n return getStore(txn, DbClientMetadata.store);\n}",
"_ensureMetadata() {\n let metadata = this.metadata;\n if (!metadata.has('language_info')) {\n metadata.set('language_info', { name: '' });\n }\n if (!metadata.has('kernelspec')) {\n metadata.set('kernelspec', { name: '', display_name: '' });\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
vertices of the rocket body | drawRocketBody() {
beginShape();
vertex(15, 10)
vertex(0, 10)
vertex(-15, 10)
vertex(-26, 10)
vertex(-40, 18)
vertex(-40, 0)
vertex(-40, -18)
vertex(-26, -10)
vertex(-15, -10)
vertex(0, -10)
vertex(15, -10)
vertex(30, 0)
endShape(CLOSE);
} | [
"function initVertices() {\n\tif (primitive == \"triangle\") {\n\t\tvertices = [\n\t\t\tvec2(-0.5, -0.5),\n\t\t\tvec2(0, 0.5),\n\t\t\tvec2(0.5, -0.5)\n\t\t];\n\t}\n\t// Compose square from 4 triangles\n\telse if (primitive == \"square\") {\n\t\tv1 = [\n\t\t\tvec2(-0.5, -0.5),\n\t\t\tvec2(0.5, -0.5),\n\t\t\tvec2(0.0, 0.0)\n\t\t];\n\t\tv2 = [\n\t\t\tvec2(-0.5, 0.5),\n\t\t\tvec2(0.5, 0.5),\n\t\t\tvec2(0.0, 0.0)\n\t\t];\n\t\tv3 = [\n\t\t\tvec2(-0.5, -0.5),\n\t\t\tvec2(-0.5, 0.5),\n\t\t\tvec2(0.0, 0.0)\n\t\t];\n\t\tv4 = [\n\t\t\tvec2(0.5, 0.5),\n\t\t\tvec2(0.5, -0.5),\n\t\t\tvec2(0.0, 0.0)\n\t\t];\n\n\t}\n\telse if (primitive == \"pentagon\") {\n\t\t\n\t\t\n\t\tv1 = [\n\t\t\tvec2(0.0, 0.0),\n\t\t\tvec2(0.0, 0.5),\n\t\t\tvec2(s1*0.5, c1*0.5)\n\t\t];\n\t\tv2 = [\n\t\t\tvec2(0.0, 0.0),\n\t\t\tvec2(s1*0.5, c1*0.5),\n\t\t\tvec2(s2*0.5, -c2*0.5)\n\t\t];\n\t\tv3 = [\n\t\t\tvec2(0.0, 0.0),\n\t\t\tvec2(s2*0.5, -c2*0.5),\n\t\t\tvec2(-s2*0.5, -c2*0.5)\n\t\t];\n\t\tv4 = [\n\t\t\tvec2(0.0, 0.0),\n\t\t\tvec2(-s2*0.5, -c2*0.5),\n\t\t\tvec2(-s1*0.5, c1*0.5)\n\t\t];\n\t\tv5 = [\n\t\t\tvec2(0.0, 0.0),\n\t\t\tvec2(-s1*0.5, c1*0.5),\n\t\t\tvec2(0.0, 0.5)\n\t\t];\n\t}\n}",
"addAsteroidVerts() {\n let width = this.physicsObj.shapes[0].width;\n let height = this.physicsObj.shapes[0].height;\n this.physicsObj.verts = [\n [-width / 2, -height / 2],\n [-width / 2, height / 2],\n [width / 2, height / 2],\n [width / 2, -height / 2],\n ];\n }",
"addAsteroidVerts() {\n this.physicsObj.verts = [];\n let radius = this.physicsObj.shapes[0].radius;\n for (let j=0; j < game.numAsteroidVerts; j++) {\n let angle = j*2*Math.PI / game.numAsteroidVerts;\n let xv = radius*Math.cos(angle) + game.rand()*radius*0.4;\n let yv = radius*Math.sin(angle) + game.rand()*radius*0.4;\n this.physicsObj.verts.push([xv, yv]);\n }\n }",
"edges(){\n if(this.pos.x < 0 || this.pos.x > width){\n this.vel.x *= -1;\n }\n if(this.pos.y < 0 || this.pos.y > height){\n this.vel.y *= -1;\n }\n }",
"generateCubeVertices() {\n /*\n 7- - -6\n /| /|\n 3- - -2 |\n | | | |\n | 4- -|-5\n |/ |/\n 0- - -1\n */\n\n this.vertices = [\n //back\n -1.0, -1.0, -1.0, //4\n 1.0, 1.0, -1.0, //6\n 1.0, -1.0, -1.0, //5\n\n 1.0, 1.0, -1.0, //6\n -1.0, -1.0, -1.0, //4\n -1.0, 1.0, -1.0, //7\n\n //front\n -1.0, -1.0, 1.0, //0\n 1.0, -1.0, 1.0, //1\n 1.0, 1.0, 1.0, //2\n\n 1.0, 1.0, 1.0, //2\n -1.0, 1.0, 1.0, //3\n -1.0, -1.0, 1.0, //0\n\n //left\n -1.0, 1.0, 1.0, //3\n -1.0, 1.0, -1.0, //7\n -1.0, -1.0, -1.0, //4\n\n -1.0, -1.0, -1.0, //4\n -1.0, -1.0, 1.0, //0\n -1.0, 1.0, 1.0, //3\n\n //right\n 1.0, 1.0, 1.0, //2\n 1.0, -1.0, -1.0, //5\n 1.0, 1.0, -1.0, //6\n\n 1.0, -1.0, -1.0, //5\n 1.0, 1.0, 1.0, //2\n 1.0, -1.0, 1.0, //1\n\n //bottom\n -1.0, -1.0, -1.0, //4\n 1.0, -1.0, -1.0, //5\n 1.0, -1.0, 1.0, //1\n\n 1.0, -1.0, 1.0, //1\n -1.0, -1.0, 1.0, //0\n -1.0, -1.0, -1.0, //4\n\n //top\n -1.0, 1.0, -1.0, //7\n 1.0, 1.0, 1.0, //2\n 1.0, 1.0, -1.0, //6\n\n 1.0, 1.0, 1.0, //2\n -1.0, 1.0, -1.0, //7\n -1.0, 1.0, 1.0 //3\n\n ];\n this.UVs = [\n //back\n 0.0, 0.0, //4\n 1.0, 1.0, //6\n 1.0, 0.0, //5\n\n 1.0, 1.0, //6\n 0.0, 0.0, //4\n 0.0, 1.0, //7\n\n //front\n 0.0, 0.0, //0\n 1.0, 0.0, //1\n 1.0, 1.0, //2\n\n 1.0, 1.0, //2\n 0.0, 1.0, //3\n 0.0, 0.0, //0\n\n //left\n 1.0, 0.0, //3\n 1.0, 1.0, //7\n 0.0, 1.0, //4\n\n 0.0, 1.0, //4\n 0.0, 0.0, //0\n 1.0, 0.0, //3\n\n //right\n 1.0, 0.0, //2\n 0.0, 1.0, //5\n 1.0, 1.0, //6\n\n 0.0, 1.0, //5\n 1.0, 0.0, //2\n 0.0, 0.0, //1\n\n //bottom\n 0.0, 1.0, //4\n 1.0, 1.0, //5\n 1.0, 0.0, //1\n\n 1.0, 0.0, //1\n 0.0, 0.0, //0\n 0.0, 1.0, //4\n\n //top\n 0.0, 1.0, //7\n 1.0, 0.0, //2\n 1.0, 1.0, //6\n\n 1.0, 0.0, //2\n 0.0, 1.0, //7\n 0.0, 0.0 //3\n ];\n this.normals = [\n //back\n 0.0, 0.0, -1.0,\n 0.0, 0.0, -1.0,\n 0.0, 0.0, -1.0,\n 0.0, 0.0, -1.0,\n 0.0, 0.0, -1.0,\n 0.0, 0.0, -1.0,\n\n //front\n 0.0, 0.0, 1.0,\n 0.0, 0.0, 1.0,\n 0.0, 0.0, 1.0,\n 0.0, 0.0, 1.0,\n 0.0, 0.0, 1.0,\n 0.0, 0.0, 1.0,\n\n //left\n -1.0, 0.0, 0.0,\n -1.0, 0.0, 0.0,\n -1.0, 0.0, 0.0,\n -1.0, 0.0, 0.0,\n -1.0, 0.0, 0.0,\n -1.0, 0.0, 0.0,\n\n //right\n 1.0, 0.0, 0.0,\n 1.0, 0.0, 0.0,\n 1.0, 0.0, 0.0,\n 1.0, 0.0, 0.0,\n 1.0, 0.0, 0.0,\n 1.0, 0.0, 0.0,\n\n //bottom\n 0.0, -1.0, 0.0,\n 0.0, -1.0, 0.0,\n 0.0, -1.0, 0.0,\n 0.0, -1.0, 0.0,\n 0.0, -1.0, 0.0,\n 0.0, -1.0, 0.0,\n\n //top\n 0.0, 1.0, 0.0,\n 0.0, 1.0, 0.0,\n 0.0, 1.0, 0.0,\n 0.0, 1.0, 0.0,\n 0.0, 1.0, 0.0,\n 0.0, 1.0, 0.0\n ];\n }",
"function getVertices() {\n var vertices = [];\n vertices.push(vec4(0.0, -0.5, 0.0, 1.0));\n vertices.push(vec4(0.0, 0.5, 0.0, 1.0));\n vertices.push(vec4(0.5, 0.0, 0.0, 1.0));\n vertices.push(vec4(0.75, 0.0, -0.75, 1.0));\n vertices.push(vec4(0.0, 0.0, -0.5, 1.0));\n vertices.push(vec4(-0.75, 0.0, -0.75, 1.0));\n vertices.push(vec4(-0.5, 0.0, 0.0, 1.0));\n vertices.push(vec4(-0.75, 0.0, 0.75, 1.0));\n vertices.push(vec4(0.0, 0.0, 0.5, 1.0));\n vertices.push(vec4(0.75, 0.0, 0.75, 1.0));\n return vertices;\n}",
"function getVertices(shape)\n {\n var vertices = [];\n\n //line contains x1,y1,x2,y2 in pos\n if(shape.shape === \"line\") \n {\n //simulate rect for collision response's sake\n var len = new G.Vector(shape.pos.x2-shape.pos.x1, shape.pos.y2-shape.pos.y1);\n //get normal of edge\n var axis = new G.Vector(-len.y, len.x).normalize(0.01);\n\n vertices = [shape.pos.x1, shape.pos.y1, shape.pos.x2, shape.pos.y2, shape.pos.x2+axis.x, shape.pos.y2+axis.y, shape.pos.x1+axis.x, shape.pos.y1+axis.y];\n }\n\n //polygon contains sequence in vertices array, relative to pos, e.g. [pos.x-x1,pos.y-y1,pos.x-x2,pos.y-y2]\n else if(shape.shape === \"polygon\") \n {\n for(var i = 0; i < shape.vertices.length-1; i += 2) vertices.push((shape.pos.x||0)+shape.vertices[i], (shape.pos.y||0)+shape.vertices[i+1]);\n if(_.isArr(reverseVertices))\n {\n var n = [], arr = vertices;\n for(var i = arr.length-1; i > 0; i -= 2)\n {\n n.push(arr[i-1], arr[i]);\n }\n vertices = n;\n }\n }\n\n //box contains pos -> x,y at center, width and height\n else if(shape.shape === \"rect\") \n {\n var hw = shape.width/2, hh = shape.height/2;\n //clockwise order from top left\n vertices = [shape.pos.x-hw, shape.pos.y-hh, shape.pos.x+hw, shape.pos.y-hh, shape.pos.x+hw, shape.pos.y+hh, shape.pos.x-hw, shape.pos.y+hh];\n }\n\n //if invalid shape\n else return console.trace(\"Shape does not contain vertices\");\n\n //convert to vectors\n var vecVertices = [];\n for(var i = 0; i < vertices.length; i+=2) vecVertices.push(new G.Vector(vertices[i], vertices[i+1]));\n\n //account for rotation\n if(shape.rotation !== 0)\n {\n for(var i = 0; i < vecVertices.length; i++)\n {\n vecVertices[i] = rotatePoint(vecVertices[i], shape.pos, shape.rotation);\n }\n }\n\n return vecVertices;\n }",
"function gen_vertices(){\n var limit = 2 * Math.PI;\n var theta = 0;\n var length = 0;\n let scp1 = 64;\n let scp2 = 6;\n var r = ((Math.abs(Math.cos(theta * scp1)) + (0.25 - (Math.cos((theta * scp1) + (Math.PI/2))) * 6))/(2 + (Math.abs(Math.cos((theta * scp2) + (Math.PI / 2)))) * 1.2));\n vertices.push(0.0, 0.0);\n\n for(theta; theta <= limit; theta = theta + 0.001) {\n let x = (((Math.abs(Math.cos(theta * scp1)) + (0.25 - (Math.cos((theta * scp1) + (Math.PI/2))) * 6))/(2 + (Math.abs(Math.cos((theta * scp2) + (Math.PI / 2)))) * 1.2))) * Math.cos(theta);\n vertices.push(x / 10);\n let y = (((Math.abs(Math.cos(theta * scp1)) + (0.25 - (Math.cos((theta * scp1) + (Math.PI/2))) * 6))/(2 + (Math.abs(Math.cos((theta * scp2) + (Math.PI / 2)))) * 1.2))) * Math.sin(theta)\n vertices.push(y / 10);\n length = length + 1;\n }\n\n return length+1;\n}",
"GetBlendShapeFrameVertices() {}",
"calculateVertices() {\n if (this._transformID === this.transform._worldID) {\n return;\n }\n this._transformID = this.transform._worldID;\n var wt = this.transform.worldTransform;\n // reveal(wt)\n var a = wt.a;\n var b = wt.b;\n var c = wt.c;\n var d = wt.d;\n var tx = wt.tx;\n var ty = wt.ty;\n var data = this.geometry.points; // batch.vertexDataOriginal;\n var vertexData = this.vertexData;\n var count = 0;\n for (var i = 0; i < data.length; i += 2) {\n var x = data[i];\n var y = data[i + 1];\n vertexData[count++] = (a * x) + (c * y) + tx;\n vertexData[count++] = (d * y) + (b * x) + ty;\n }\n }",
"createPyramidVertices() {\n let vertices = new Float32Array([\n /*0*/ -1, 0, 1, /*1*/ 1, 0, 1, /*2*/ 1, 0, -1, /*3*/ -1, 0, -1,\n /*4*/ 0, 2, 0\n ]);\n return vertices;\n }",
"getVertices() {\n\t\treturn this.vertices;\n\t}",
"function getVertices() {\n // Determine outer edges of circle\n board = circle.getBounds();\n // Set vertices for four ajacent triangles\n // at circle center and edges\n vertex = {\n // center\n cx: circle.x,\n cy: circle.y,\n // top\n tx: circle.x,\n ty: board.top,\n // right\n rx: board.right,\n ry: circle.y,\n // left\n lx: board.left,\n ly: circle.y,\n // bottom\n bx: circle.x,\n by: board.bottom\n }\n}",
"generateVertices() {\n //wait, if I have all the points in the vertices array, then all I have to do is loop over the same exact shape pushing the faces to the face array\n //wait again, I could even try reserving the old face data since the shape is the same, like going from\n //one to adding four total to adding four per shape in there already\n return [\n new THREE.Vector3(this.x, this.y, this.z),//0\n new THREE.Vector3(this.x + this.height, this.y, this.z),//1\n new THREE.Vector3(this.x + this.height / 2, this.y + this.height, (this.z - this.height / 2)),//2\n new THREE.Vector3(this.x, this.y, (this.z - this.height)),//3\n new THREE.Vector3(this.x + this.height, this.y, (this.z - this.height))//4\n ];\n\n /*\n 2\n / \\\n 3-|--4\n /| |/\n 0----1\n */\n }",
"vertexWithXY () {}",
"function drawBody() {\n fill(bodyColor);\n stroke(bodyColor);\n strokeWeight(3);\n\n // collect the points\n let leftSide = [];\n let rightSide = [];\n for ( var i = 0; i < points.length; i++) {\n var f = points[i].getFixtureList();\n var t = f.m_body.getTransform();\n var s = f.getShape();\n var v, p;\n\n v = s.m_vertices[0];\n p = mulVec2(t, v);\n leftSide.push(p);\n\n v = s.m_vertices[3];\n p = mulVec2(t, v);\n leftSide.push(p);\n\n \n v = s.m_vertices[1];\n p = mulVec2(t, v);\n rightSide.push(p);\n\n v = s.m_vertices[2];\n p = mulVec2(t, v);\n rightSide.push(p);\n }\n\n // draw the body\n if ( leftSide.length > 0 ) {\n beginShape();\n\n for ( var i = 0; i < leftSide.length; i++ ) {\n var p = toScreen(leftSide[i]);\n vertex(p.x, p.y);\n }\n for ( var i = rightSide.length - 1; i >= 0; i-- ) {\n var p = toScreen(rightSide[i]);\n vertex(p.x, p.y);\n }\n\n var p = toScreen(leftSide[0]);\n vertex(p.x, p.y);\n\n endShape();\n }\n\n}",
"function WireFrameCube(gl, color) {\n function defineVertices(gl) {\n // define the vertices of the cube\n var vertices = [\n // X, Y, Z R, G, B U, V,\n // bottom\n -0.5, 0.5, -0.5, /* V0 / 0 */ 1.0, 0.0, 0.0, 0.0, 1.0,\n -0.5, -0.5, -0.5, /* V1 / 1 */ 1.0, 0.0, 0.0, 1.0, 1.0,\n 0.5, -0.5, -0.5, /* V2 / 2 */ 1.0, 0.0, 0.0, 1.0, 0.0,\n 0.5, 0.5, -0.5, /* V3 / 3 */ 1.0, 0.0, 0.0, 0.0, 0.0,\n\n // top\n 0.5, 0.5, 0.5, /* V4 / 4 */ 0.0, 1.0, 0.0, 0.0, 1.0,\n -0.5, 0.5, 0.5, /* V5 / 5 */ 0.0, 1.0, 0.0, 1.0, 1.0,\n -0.5, -0.5, 0.5, /* V6 / 6 */ 0.0, 1.0, 0.0, 1.0, 0.0,\n 0.5, -0.5, 0.5, /* V7 / 7 */ 0.0, 1.0, 0.0, 0.0, 0.0,\n\n // front\n -0.5, -0.5, -0.5, /* V1 / 8 */ 0.0, 0.0, 1.0, 0.0, 1.0,\n 0.5, -0.5, -0.5, /* V2 / 9 */ 0.0, 0.0, 1.0, 1.0, 1.0,\n 0.5, -0.5, 0.5, /* V7 / 10 */ 0.0, 0.0, 1.0, 1.0, 0.0,\n -0.5, -0.5, 0.5, /* V6 / 11 */ 0.0, 0.0, 1.0, 0.0, 0.0,\n\n // back\n -0.5, 0.5, -0.5, /* V0 / 12 */ 1.0, 1.0, 0.0, 0.0, 1.0,\n 0.5, 0.5, -0.5, /* V3 / 13 */ 1.0, 1.0, 0.0, 1.0, 1.0,\n 0.5, 0.5, 0.5, /* V4 / 14 */ 1.0, 1.0, 0.0, 1.0, 0.0,\n -0.5, 0.5, 0.5, /* V5 / 15 */ 1.0, 1.0, 0.0, 0.0, 0.0,\n\n // left\n -0.5, 0.5, -0.5, /* V0 / 16 */ 1.0, 0.0, 1.0, 0.0, 1.0,\n -0.5, -0.5, -0.5, /* V1 / 17 */ 1.0, 0.0, 1.0, 1.0, 1.0,\n -0.5, -0.5, 0.5, /* V6 / 18 */ 1.0, 0.0, 1.0, 1.0, 0.0,\n -0.5, 0.5, 0.5, /* V5 / 19 */ 1.0, 0.0, 1.0, 0.0, 0.0,\n\n // right\n 0.5, -0.5, -0.5, /* V2 / 20 */ 0.0, 1.0, 1.0, 0.0, 1.0,\n 0.5, 0.5, -0.5, /* V3 / 21 */ 0.0, 1.0, 1.0, 1.0, 1.0,\n 0.5, 0.5, 0.5, /* V4 / 22 */ 0.0, 1.0, 1.0, 1.0, 0.0,\n 0.5, -0.5, 0.5, /* V7 / 23 */ 0.0, 1.0, 1.0, 0.0, 0.0,\n ];\n\n var buffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);\n return buffer;\n }\n\n\n function defineEdges(gl) {\n // define the edges for the cube, there are 12 edges in a cube\n var vertexIndices = [\n // bottom\n 2, 1, 0,\n 0, 3, 2,\n\n // top\n 4, 5, 6,\n 6, 7, 4,\n\n // front\n 8, 9, 10,\n 10, 11, 8,\n\n // back\n 14, 13, 12,\n 12, 15, 14,\n\n // left\n 16, 17, 18,\n 18, 19, 16,\n\n // right\n 20, 21, 22,\n 22, 23, 20,\n ];\n var buffer = gl.createBuffer();\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(vertexIndices), gl.STATIC_DRAW);\n return buffer;\n }\n\n return {\n bufferVertices: defineVertices(gl),\n bufferEdges: defineEdges(gl),\n color: color,\n\n draw: function(gl, aVertexPositionId, aVertexColorId, aVertexTexCoordId) {\n gl.bindBuffer(gl.ARRAY_BUFFER, this.bufferVertices);\n gl.vertexAttribPointer(aVertexPositionId, 3, gl.FLOAT, false, 8 * Float32Array.BYTES_PER_ELEMENT, 0);\n gl.enableVertexAttribArray(aVertexPositionId);\n\n gl.vertexAttribPointer(aVertexColorId, 3, gl.FLOAT, false, 8 * Float32Array.BYTES_PER_ELEMENT, 3 * Float32Array.BYTES_PER_ELEMENT);\n gl.enableVertexAttribArray(aVertexColorId);\n\n gl.vertexAttribPointer(aVertexTexCoordId, 2, gl.FLOAT, false, 8 * Float32Array.BYTES_PER_ELEMENT, 6 * Float32Array.BYTES_PER_ELEMENT);\n gl.enableVertexAttribArray(aVertexTexCoordId);\n\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.bufferEdges);\n gl.drawElements(gl.TRIANGLES, 36 /* Anzahl Indices */ , gl.UNSIGNED_SHORT, 0);\n }\n }\n}",
"computeVerticesUVs() {\n // geometry vertices and UVs\n this.attributes.vertexPosition.array = [];\n this.attributes.textureCoord.array = [];\n\n const vertices = this.attributes.vertexPosition.array;\n const uvs = this.attributes.textureCoord.array;\n\n for(let y = 0; y < this.definition.height; y++) {\n const v = y / this.definition.height;\n\n for(let x = 0; x < this.definition.width; x++) {\n const u = x / this.definition.width;\n\n // uvs and vertices\n // our uvs are ranging from 0 to 1, our vertices range from -1 to 1\n\n // first triangle\n uvs.push(u);\n uvs.push(v);\n uvs.push(0);\n\n vertices.push((u - 0.5) * 2);\n vertices.push((v - 0.5) * 2);\n vertices.push(0);\n\n uvs.push(u + (1 / this.definition.width));\n uvs.push(v);\n uvs.push(0);\n\n vertices.push(((u + (1 / this.definition.width)) - 0.5) * 2);\n vertices.push((v - 0.5) * 2);\n vertices.push(0);\n\n uvs.push(u);\n uvs.push(v + (1 / this.definition.height));\n uvs.push(0);\n\n vertices.push((u - 0.5) * 2);\n vertices.push(((v + (1 / this.definition.height)) - 0.5) * 2);\n vertices.push(0);\n\n // second triangle\n uvs.push(u);\n uvs.push(v + (1 / this.definition.height));\n uvs.push(0);\n\n vertices.push((u - 0.5) * 2);\n vertices.push(((v + (1 / this.definition.height)) - 0.5) * 2);\n vertices.push(0);\n\n uvs.push(u + (1 / this.definition.width));\n uvs.push(v);\n uvs.push(0);\n\n vertices.push(((u + (1 / this.definition.width)) - 0.5) * 2);\n vertices.push((v - 0.5) * 2);\n vertices.push(0);\n\n uvs.push(u + (1 / this.definition.width));\n uvs.push(v + (1 / this.definition.height));\n uvs.push(0);\n\n vertices.push(((u + (1 / this.definition.width)) - 0.5) * 2);\n vertices.push(((v + (1 / this.definition.height)) - 0.5) * 2);\n vertices.push(0);\n }\n }\n }",
"function CuboidGeometry(engine, width, height, depth) {\n var _this;\n\n if (width === void 0) {\n width = 1;\n }\n\n if (height === void 0) {\n height = 1;\n }\n\n if (depth === void 0) {\n depth = 1;\n }\n\n _this = _ShapeGeometry.call(this, engine) || this;\n var halfWidth = width / 2;\n var halfHeight = height / 2;\n var halfDepth = depth / 2; // prettier-ignore\n\n var vertices = new Float32Array([// up\n -halfWidth, halfHeight, -halfDepth, 0, 1, 0, 0, 0, halfWidth, halfHeight, -halfDepth, 0, 1, 0, 1, 0, halfWidth, halfHeight, halfDepth, 0, 1, 0, 1, 1, -halfWidth, halfHeight, halfDepth, 0, 1, 0, 0, 1, // down\n -halfWidth, -halfHeight, -halfDepth, 0, -1, 0, 0, 1, halfWidth, -halfHeight, -halfDepth, 0, -1, 0, 1, 1, halfWidth, -halfHeight, halfDepth, 0, -1, 0, 1, 0, -halfWidth, -halfHeight, halfDepth, 0, -1, 0, 0, 0, // left\n -halfWidth, halfHeight, -halfDepth, -1, 0, 0, 0, 0, -halfWidth, halfHeight, halfDepth, -1, 0, 0, 1, 0, -halfWidth, -halfHeight, halfDepth, -1, 0, 0, 1, 1, -halfWidth, -halfHeight, -halfDepth, -1, 0, 0, 0, 1, // right\n halfWidth, halfHeight, -halfDepth, 1, 0, 0, 1, 0, halfWidth, halfHeight, halfDepth, 1, 0, 0, 0, 0, halfWidth, -halfHeight, halfDepth, 1, 0, 0, 0, 1, halfWidth, -halfHeight, -halfDepth, 1, 0, 0, 1, 1, // fornt\n -halfWidth, halfHeight, halfDepth, 0, 0, 1, 0, 0, halfWidth, halfHeight, halfDepth, 0, 0, 1, 1, 0, halfWidth, -halfHeight, halfDepth, 0, 0, 1, 1, 1, -halfWidth, -halfHeight, halfDepth, 0, 0, 1, 0, 1, // back\n -halfWidth, halfHeight, -halfDepth, 0, 0, -1, 1, 0, halfWidth, halfHeight, -halfDepth, 0, 0, -1, 0, 0, halfWidth, -halfHeight, -halfDepth, 0, 0, -1, 0, 1, -halfWidth, -halfHeight, -halfDepth, 0, 0, -1, 1, 1]); // prettier-ignore\n\n var indices = new Uint16Array([// up\n 0, 2, 1, 2, 0, 3, // donw\n 4, 6, 7, 6, 4, 5, // left\n 8, 10, 9, 10, 8, 11, // right\n 12, 14, 15, 14, 12, 13, // fornt\n 16, 18, 17, 18, 16, 19, // back\n 20, 22, 23, 22, 20, 21]);\n\n _this._initialize(engine, vertices, indices);\n\n return _this;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stop black boxing the specified source. | function unBlackBox(sourceClient) {
dumpn("Un-black boxing source: " + sourceClient.actor);
return rdpRequest(sourceClient, sourceClient.unblackBox);
} | [
"function stopSource() {\n\tds.source.stop({\n\t\t\t\"id\": sourceDetails.id\n\t\t}, function(err, response) {\n\t\t\tif (err) \n\t\t\t\tconsole.log(err);\n\t\t\telse\n\t\t\t{\n\t\t\t\tconsole.log(\"Source stopped.\");\n\t\t\t\tdeleteSource();\n\t\t\t}\n\t\t});\n}",
"removeSource(source) {\n const sourceIdx = this._sources.findIndex((s) => s === source);\n if (sourceIdx > -1) {\n arrayRemoveAt(this._sources, sourceIdx);\n source.dispose();\n }\n }",
"stop() {\n this.target = null;\n }",
"function stop() {\n source.stop(0);\n source.disconnect(0);\n playing = false;\n }",
"cancel() {\n this.cancelSource();\n }",
"function stop() {\n if (playingSource) {\n playingSource.stop();\n playingSource = null;\n }\n}",
"stop () {\n this._watching = false;\n this._source.removeListener(this._onData);\n }",
"stop() {\n this.noiseSource_.stop();\n this.speechSource_.stop();\n this.attackSlider_.disable();\n this.releaseSlider_.disable();\n this.thresholdSlider_.disable();\n this.playing = false;\n }",
"onSourceDisposed(sender, args) {\n this.source = null;\n }",
"_stopSpectrumAnalyzer () {\n this._canvasContext.clearRect(0, 0, this._canvas.width, this._canvas.height)\n window.cancelAnimationFrame(this._animationId)\n }",
"async stop() {\n await this.blockSource.stop();\n this.running = false;\n }",
"resetBlackout() {\r\n this.blackout = false;\r\n }",
"function stopAudio() {\n if (sa.nodes.sourceNode.buffer) {\n sa.nodes.sourceNode.stop();\n sa.paused = true;\n }\n }",
"stopScanning() {\n this.isScanning = false;\n this._log(\"debug\", \"stop scanning\");\n noble.stopScanning();\n }",
"stop() {\n\t\tthis.playground.erase();\n\t}",
"function blackBox(sourceClient) {\n dumpn(\"Black boxing source: \" + sourceClient.actor);\n return rdpRequest(sourceClient, sourceClient.blackBox);\n}",
"function stopSound() {\n if (source) {\n source.noteOff(0);\n }\n}",
"stopTrafficSampling() {\n\t\tthis.dispatch();\n\t}",
"function removeBreakpointsInSource(cx, source) {\n return async ({\n dispatch,\n getState,\n client\n }) => {\n const breakpoints = (0, _selectors.getBreakpointsForSource)(getState(), source.id);\n\n for (const breakpoint of breakpoints) {\n dispatch((0, _modify.removeBreakpoint)(cx, breakpoint));\n }\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine whether the argument can be converted to Tensor. Tensors, primitives, arrays, and TypedArrays all qualify; anything else does not. | function canTensorify(obj) {
return obj == null || isPrimitive(obj) || Array.isArray(obj) ||
(typeof obj === 'object' && (obj instanceof tf.Tensor)) ||
tf.util.isTypedArray(obj);
} | [
"function canTensorify(obj) {\n return obj == null || isPrimitive(obj) || Array.isArray(obj) || typeof obj === 'object' && obj instanceof tf.Tensor || tf.util.isTypedArray(obj);\n}",
"function canTensorify(obj) {\n return obj == null || isPrimitive(obj) || Array.isArray(obj) ||\n (typeof obj === 'object' && (obj instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__.Tensor)) ||\n _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__.util.isTypedArray(obj);\n}",
"function canTensorify(obj) {\n return obj == null || isPrimitive(obj) || Array.isArray(obj) ||\n (typeof obj === 'object' && (obj instanceof _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__[\"Tensor\"])) ||\n _tensorflow_tfjs_core__WEBPACK_IMPORTED_MODULE_0__[\"util\"].isTypedArray(obj);\n}",
"function isDataTensor(x) {\n return x instanceof tfjs_core_1.Tensor;\n}",
"isConvertibleTo(targetType) {\n //everything can be dynamic, so as long as a type is provided, this is true\n return !!targetType;\n }",
"function isValidTensorName(name) {\n return name.match(tensorNameRegex) ? true : false;\n}",
"function isValidTensorName(name) {\n return !!name.match(tensorNameRegex);\n}",
"function isValidTensorName(name) {\n return !!name.match(tensorNameRegex);\n}",
"static isTypeArgumentedNode(node) {\r\n switch (node.getKind()) {\r\n case typescript_1.SyntaxKind.CallExpression:\r\n case typescript_1.SyntaxKind.NewExpression:\r\n case typescript_1.SyntaxKind.ImportType:\r\n return true;\r\n default:\r\n return false;\r\n }\r\n }",
"function can_visualize() {\n return inputObject.network_archeticture.length > 0 && inputObject.dataset.length > 0\n && (inputObject.horizontal.length > 0 || inputObject.vertical.length > 0)\n && inputObject.depth.length > 0 && inputObject.width.length > 0;\n}",
"function opValid(opNode) {\n // Function library nodes are generally for internal use.\n if (opNode.name.search(graph_1.FUNCTION_LIBRARY_NODE_PREFIX) == 0) {\n return true;\n }\n // Nodes that lack op types should be ignored.\n if (!opNode.op) {\n return true;\n }\n // If assigned a device that is not TPU-related assume op is valid.\n if (opNode.device && isNotTpuOp(opNode.device)) {\n return true;\n }\n // If assigned to the TPU_SYSTEM device, assume op is valid.\n if (opNode.device && opNode.device.search('TPU_SYSTEM') != -1) {\n return true;\n }\n return op.WHITELIST.indexOf(opNode.op) != -1;\n }",
"function assertFeedCompatibility(key, val) {\n // Check dtype compatibility.\n if (key.dtype == null || key.dtype === val.dtype) {\n // a. If types match, return val tensor as is.\n return val;\n }\n try {\n // b. Attempt to convert to expected type.\n return tfjs_core_1.cast(val, key.dtype);\n }\n catch (err) {\n // c. If conversion fails, return helpful error.\n throw new errors_1.ValueError(\"The dtype of the feed (\" + val.dtype + \") can not be cast to the dtype \" +\n (\"of the key '\" + key.name + \"' (\" + key.dtype + \").\"));\n }\n}",
"function canConvert (input) {\n return (\n input != null && (\n typeof input === 'string' ||\n input.nodeType && (\n input.nodeType === 1 || input.nodeType === 9 || input.nodeType === 11\n )\n )\n )\n}",
"TargetTypeIsAllowed(dataType) {\n\t\tconst allowedDataTypes = ['List', 'Relation'];\n\t\tif(allowedDataTypes.indexOf(dataType) > -1){\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}",
"function supports32BitWebGL() {\n return tf.ENV.getBool('WEBGL_RENDER_FLOAT32_CAPABLE') && tf.ENV.getBool('WEBGL_RENDER_FLOAT32_ENABLED');\n}",
"function checkTransposeSuccessful(tData)\n{\n var correctType = Array.isArray(tData.contents);\n var checkRes = false;\n\n if (correctType === true && tData.contents.length > 0)\n {\n checkRes = true;\n }\n\n return checkRes;\n}",
"function internal_isDatasetCore(input) {\n return typeof input === \"object\" && input !== null && typeof input.size === \"number\" && typeof input.add === \"function\" && typeof input.delete === \"function\" && typeof input.has === \"function\" && typeof input.match === \"function\" && Array.from(input).length === input.size;\n}",
"function _checkIsUint8ClampedImageData () {\n\n if (typeof Uint8ClampedArray === \"undefined\")\n {\n return false;\n }\n\n var elem = document.createElement('canvas');\n var ctx = elem.getContext('2d');\n\n if (!ctx)\n {\n return false;\n }\n\n var image = ctx.createImageData(1, 1);\n\n return image.data instanceof Uint8ClampedArray;\n\n }",
"warnOnIncompatibleInputShape(inputShape) {\n if (this.batchInputShape == null) {\n return;\n }\n else if (inputShape.length !== this.batchInputShape.length) {\n console.warn(`The rank of the input tensor provided (shape: ` +\n `${JSON.stringify(inputShape)}) does not match that of the ` +\n `batchInputShape (${JSON.stringify(this.batchInputShape)}) ` +\n `of the layer ${this.name}`);\n }\n else {\n let dimMismatch = false;\n this.batchInputShape.forEach((dimension, i) => {\n if (dimension != null && inputShape[i] != null &&\n inputShape[i] !== dimension) {\n dimMismatch = true;\n }\n });\n if (dimMismatch) {\n console.warn(`The shape of the input tensor ` +\n `(${JSON.stringify(inputShape)}) does not ` +\n `match the expectation of layer ${this.name}: ` +\n `${JSON.stringify(this.batchInputShape)}`);\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
compute the coordinates of the errorbar objects | function errorCoords(d, xa, ya) {
var out = {
x: xa.c2p(d.x),
y: ya.c2p(d.y)
};
// calculate the error bar size and hat and shoe locations
if(d.yh !== undefined) {
out.yh = ya.c2p(d.yh);
out.ys = ya.c2p(d.ys);
// if the shoes go off-scale (ie log scale, error bars past zero)
// clip the bar and hide the shoes
if(!isNumeric(out.ys)) {
out.noYS = true;
out.ys = ya.c2p(d.ys, true);
}
}
if(d.xh !== undefined) {
out.xh = xa.c2p(d.xh);
out.xs = xa.c2p(d.xs);
if(!isNumeric(out.xs)) {
out.noXS = true;
out.xs = xa.c2p(d.xs, true);
}
}
return out;
} | [
"function errorCoords(d, xa, ya) {\n\t var out = {\n\t x: xa.c2p(d.x),\n\t y: ya.c2p(d.y)\n\t };\n\n\t // calculate the error bar size and hat and shoe locations\n\t if(d.yh !== undefined) {\n\t out.yh = ya.c2p(d.yh);\n\t out.ys = ya.c2p(d.ys);\n\n\t // if the shoes go off-scale (ie log scale, error bars past zero)\n\t // clip the bar and hide the shoes\n\t if(!isNumeric(out.ys)) {\n\t out.noYS = true;\n\t out.ys = ya.c2p(d.ys, true);\n\t }\n\t }\n\n\t if(d.xh !== undefined) {\n\t out.xh = xa.c2p(d.xh);\n\t out.xs = xa.c2p(d.xs);\n\n\t if(!isNumeric(out.xs)) {\n\t out.noXS = true;\n\t out.xs = xa.c2p(d.xs, true);\n\t }\n\t }\n\n\t return out;\n\t}",
"function errorCoords(d, xa, ya) {\n var out = {\n x: xa.c2p(d.x),\n y: ya.c2p(d.y)\n };\n\n // calculate the error bar size and hat and shoe locations\n if (d.yh !== undefined) {\n out.yh = ya.c2p(d.yh);\n out.ys = ya.c2p(d.ys);\n\n // if the shoes go off-scale (ie log scale, error bars past zero)\n // clip the bar and hide the shoes\n if (!isNumeric(out.ys)) {\n out.noYS = true;\n out.ys = ya.c2p(d.ys, true);\n }\n }\n\n if (d.xh !== undefined) {\n out.xh = xa.c2p(d.xh);\n out.xs = xa.c2p(d.xs);\n\n if (!isNumeric(out.xs)) {\n out.noXS = true;\n out.xs = xa.c2p(d.xs, true);\n }\n }\n\n return out;\n }",
"function updateErrorGraph() {\n propErrV = {\n x: ['proportion of total error'],\n y: [Math.pow(errorFromVelocity()/totalError(),2)],\n text: ['x_v error'],\n textposition: 'auto',\n hoverinfo: 'none',\n type: 'bar',\n marker: {color: 'rgb(0, 153, 51)'}\n };\n\n propErrTheta = {\n x: ['proportion of total error'],\n y: [Math.pow(errorFromAngle()/totalError(),2)],\n text: ['x_angle error'],\n textposition: 'auto',\n hoverinfo: 'none',\n type: 'bar',\n marker: {color: 'rgb(51, 204, 204)'}\n };\n}",
"function errorCoords(d, xa, ya) {\n var out = {\n x: xa.c2p(d.x),\n y: ya.c2p(d.y)\n };\n\n // calculate the error bar size and hat and shoe locations\n if(d.yh !== undefined) {\n out.yh = ya.c2p(d.yh);\n out.ys = ya.c2p(d.ys);\n\n // if the shoes go off-scale (ie log scale, error bars past zero)\n // clip the bar and hide the shoes\n if(!isNumeric(out.ys)) {\n out.noYS = true;\n out.ys = ya.c2p(d.ys, true);\n }\n }\n\n if(d.xh !== undefined) {\n out.xh = xa.c2p(d.xh);\n out.xs = xa.c2p(d.xs);\n\n if(!isNumeric(out.xs)) {\n out.noXS = true;\n out.xs = xa.c2p(d.xs, true);\n }\n }\n\n return out;\n}",
"function updateErrorGraph() {\n propErrX = {\n x: ['proportion of total error'],\n y: [Math.pow(errorFromX()/totalError(), 2)],\n text: ['y_x error'],\n textposition: 'auto',\n hoverinfo: 'none',\n type: 'bar',\n marker: {color: 'rgb(0, 0, 225)'}\n };\n\n propErrSlope = {\n x: ['proportion of total error'],\n y: [Math.pow(errorFromSlope()/totalError(),2)],\n text: ['y_m error'],\n textposition: 'auto',\n hoverinfo: 'none',\n type: 'bar',\n marker: {color: 'rgb(255, 0, 0)'}\n };\n}",
"function updateErrorGraph() {\n propErrX = {\n x: ['proportion of total error'],\n y: [Math.pow(errorFromX()/totalError(), 2)],\n text: ['y_x error'],\n textposition: 'auto',\n hoverinfo: 'none',\n type: 'bar',\n marker: {color: 'rgb(0, 0, 225)'}\n };\n\n propErrM = {\n x: ['proportion of total error'],\n y: [Math.pow(errorFromM()/totalError(), 2)],\n text: ['y_m error'],\n textposition: 'auto',\n hoverinfo: 'none',\n type: 'bar',\n marker: {color: 'rgb(51, 204, 204)'}\n };\n\n propErrB = {\n x: ['proportion of total error'],\n y: [errorFromB()/totalError()],\n text: ['y_b error'],\n textposition: 'auto',\n hoverinfo: 'none',\n type: 'bar',\n marker: {color: 'rgb(255, 0, 0)'}\n };\n}",
"function computeObjectErrorStats(xs,ys,spdDiff,angDiff){\r\n\t\t// Compute average error in direction\r\n \txErr = [];\r\n yErr = [];\r\n angs = [];\r\n xDiff = xs.average();\r\n \tyDiff = ys.average();\r\n \ttimeDiff = ts.average();\r\n for(i=0;i<xs.length;i++){\r\n\t xErr.push(Math.abs(xDiff - xs[i]));\r\n yErr.push(Math.abs(yDiff - ys[i]));\r\n ang = 270 - (Math.atan2(ys[i],xs[i]) * 180 / Math.PI);\r\n if(ang >= 360){\r\n \tang = ang - 360;\r\n }\r\n else if(ang < 0){\r\n ang = ang + 360;\r\n }\r\n \tangs.push(ang);\r\n \t}\r\n angAvg = angs.average();\r\n angDiffs = [];\r\n for(var i=0;i<angs.length;i++){\r\n \tang = Math.abs(angs[i] - angAvg);\r\n\t \tif(ang >= 360){\r\n ang = ang - 360;\r\n \t}\r\n \telse if(ang < 0){\r\n ang = ang + 360;\r\n }\r\n \tangDiffs.push(ang);\r\n }\r\n \tang = Math.round(angDiffs.average());\r\n if(ang > angDiff && ang < 45){\r\n angDiff = ang;\r\n }\r\n\r\n\t\t// Compute Motion Vector\r\n newDir = 270 - Math.round(Math.atan2(yDiff,xDiff) * 180 / Math.PI);\r\n if(newDir >= 360){\r\n newDir = newDir - 360;\r\n }\r\n else if(newDir < 0){\r\n newDir = newDir + 360;\r\n }\r\n newSpeed = -1 * Math.round((Math.sqrt((xDiff * xDiff) + (yDiff * yDiff))/ timeDiff) * 1.94384);\r\n\t\tif(newSpeed > 100){\r\n\t\t\tnewSpeed = 100;\r\n\t\t}\r\n for(var i=0;i<tempSpeeds.length;i++){\r\n tempSpeeds[i] = newSpeed;\r\n tempDirs[i] = newDir;\r\n }\r\n\r\n \t// Compute average error in speed\r\n xStd = xErr.average();\r\n yStd = yErr.average();\r\n newSpd = Math.round((Math.sqrt((xStd * xStd) + (yStd * yStd))/ (-1 * timeDiff)) * 1.94384);\r\n if(newSpd > spdDiff && newSpd < newSpeed){\r\n\t spdDiff = newSpd;\r\n }\r\n \tnewDir = Math.round(Math.atan2(yStd,xStd) * 180 / Math.PI);\r\n for(var i=0;i<tempSpd.length;i++){\r\n tempSpd[i] = spdDiff;\r\n tempDir[i] = angDiff;\r\n \t}\r\n\t}",
"function getCoords() {\n var chartLayout = chart1.getChartLayoutInterface();\n var chartBounds = chartLayout.getChartAreaBoundingBox();\n return {\n x: {\n min: chartLayout.getHAxisValue(chartBounds.left),\n max: chartLayout.getHAxisValue(chartBounds.width + chartBounds.left)\n },\n y: {\n min: chartLayout.getVAxisValue(chartBounds.top),\n max: chartLayout.getVAxisValue(chartBounds.height + chartBounds.top)\n }\n };\n }",
"function showErrorBars()\n{\n// hide all errorBars\n ErrorBarG.selectAll(\".errorBar\")\n .classed(\"selected\", false)\n .style(\"display\", \"none\")\n\n var domainMag = YL.domain()\n var height = PlotHeight-30\n var magXFactor = height/(domainMag[1]-domainMag[0])\n\n// for selected points, select errorbars > UncertGT, scale them\n var points = SymbolG.selectAll(\".Points.trimmed.selected\")[0]\n var errorBars = ErrorBarG.selectAll(\".errorBar\")[0]\n for (k = 0; k < points.length; k++)\n {\n var point = points[k]\n var errorBar = errorBars[point.getAttribute(\"dataLoc\")]\n var uncert = point.getAttribute(\"uncert\")\n var opacity = point.getAttribute(\"opacity\")\n if(uncert>UncertGT)\n {\n errorBar.setAttribute(\"transform\", \"translate(\"+XscaleJulian(point.getAttribute(\"xValTop\"))+\" \"+YL(point.getAttribute(\"yVal\"))+\")\")\n errorBar.setAttribute(\"y1\", -uncert*magXFactor)\n errorBar.setAttribute(\"y2\", uncert*magXFactor)\n errorBar.setAttribute(\"class\", \"errorBar selected\")\n }\n\n var opacity = point.getAttribute(\"opacity\")\n // if(opacity)\n errorBar.setAttribute(\"opacity\", opacity)\n }\n\n// show selected error bars\n ErrorBarG.selectAll(\".errorBar.selected\")\n .style(\"display\", \"block\")\n}",
"function CanvasErrorBar() {\n var X = function (d) { return d; };\n var Y = function (d) { return d; };\n var style = STYLES[\"default\"];\n var radius = 2.5;\n\n function render(context, x, y, error, vertical) {\n context.lineWidth = style[\"stroke_width\"];\n context.strokeStyle = style[\"stroke\"];\n\n x = X(x);\n y = Y(y);\n\n context.beginPath();\n context.arc(x, y, radius, 0, 2 * Math.PI);\n context.stroke();\n\n\n context.beginPath();\n if(vertical){\n error = Y(y + error) - Y(y);\n\n context.moveTo(x, y - radius);\n context.lineTo(x, y - radius + error);\n\n context.moveTo(x - radius, y - radius + error);\n context.lineTo(x + radius, y - radius + error);\n\n context.moveTo(x, y + radius);\n context.lineTo(x, y + radius - error);\n\n context.moveTo(x - radius, y + radius - error);\n context.lineTo(x + radius, y + radius - error);\n\n } else {\n error = X(x + error) - X(x);\n\n context.moveTo(x - radius, y);\n context.lineTo(x - radius + error, y);\n\n context.moveTo(x - radius + error, y - radius);\n context.lineTo(x - radius + error, y + radius);\n\n context.moveTo(x + radius, y);\n context.lineTo(x + radius - error, y);\n\n context.moveTo(x + radius - error, y - radius);\n context.lineTo(x + radius - error, y + radius);\n }\n\n context.stroke();\n\n }\n\n render.x = function (value) {\n if (!arguments.length) return X;\n X = value;\n return render;\n };\n\n render.y = function (value) {\n if (!arguments.length) return Y;\n Y = value;\n return render;\n };\n\n render.style = function (value) {\n if (!arguments.length) return style;\n style = value;\n return render;\n };\n\n return render;\n}",
"getVerticalBarsXPos() {\n return [this.minXpos, this.lowQuartXpos, this.medianXpos, this.uppQuartXpos, this.maxXpos];\n }",
"function barplotFaults(tabinput, colName, x, y, plotwidth, plotheight, barfrac, offset, fillclr, sliderSelectBar, linetokeep) {\n\n\n // Table column data matching\n col = tabinput.columns.indexOf(colName);\n col2 = tabinput.columns.indexOf(\"latitude\");\n col3 = tabinput.columns.indexOf(\"longitude\");\n col4 = tabinput.columns.indexOf(\"mag\");\n col5 = tabinput.columns.indexOf(\"depthError\");\n\n\n // Map zoom parameters for graph filetering\n // console.log(mapViewCoords)\n var mapLatSW = mapViewCoords._southWest.lat;\n var mapLongSW = mapViewCoords._southWest.lng;\n var mapLatNE = mapViewCoords._northEast.lat;\n var mapLongNE = mapViewCoords._northEast.lng;\n\n\n // Other initializiations\n var yzero = y;\n var colwidth = plotwidth / faultlinedata.length;\n var barwidth = colwidth * barfrac;\n // var totalN = tabinput.getRowCount();\n var totalN = faultlinedata.length;\n\n\n\n // draw the zero axis labels on the base-----------------------------------\n stroke(150);\n strokeWeight(0.5);\n line(x, yzero+plotheight, x + plotwidth, yzero+plotheight)\n\n\n\n // get the minimum and maximum values for scales --------------------------\n let miny1 = 3000000;\n let maxy1 = -300000;\n\n for (var i = 0; i < (totalN); i++) {\n if (faultlinedata[i].distance <= miny1) {\n miny1 = faultlinedata[i].distance;\n }\n if (faultlinedata[i].distance >= maxy1) {\n maxy1 = faultlinedata[i].distance;\n }\n }\n\n\n\n // loop through all the data points----------------------------------------\n for (let i = 0; i < totalN; i++) {\n\n\n // var place = tabinput.getString(i, 0) // grab the data\n var value = faultlinedata[i].distance;\n\n // var lgndval = tabinput.getString(i, 2)\n var thisBari = ceil(map(sliderSelectBar, 0, slidermax, 0, totalN - 1));\n\n\n // get the lat and long from the table\n var latval = tabinput.getNum(i, col2)\n var longval = tabinput.getNum(i, col3)\n var latval2 = faultlinedata[i].latitude;\n var longval2 = faultlinedata[i].longitude;\n\n\n // determine if selection is highlighted then change bar color\n if (mapLatSW <= latval && mapLongSW <= longval && mapLatNE >= latval && mapLongNE >= longval) {\n fillclr = fillclr1;\n console.log(\"Highlighted selection\")\n }\n else {\n fillclr = fillclr2;\n }\n\n var fillclrkeep = fillclr;\n\n\n\n // Create color for selected bar using slider value-----------------------\n if ((thisBari) == i) {\n\n // change map icon line position and content\n linetokeep.setLatLngs([{ lat: latval, lng: longval }, { lat: latval2, lng: longval2 }]);\n\n // add text value to the selected bar\n stroke(0);\n fill(0);\n textSize(10)\n strokeWeight(0.3)\n textAlign(CENTER)\n text(round(value * 10) / 10 + \"km\", x + offset * barwidth, y + 16 + plotheight );\n\n // Change colors for the highlighted bar\n fill('red');\n stroke('red');\n\n }\n\n // draw the bar on the barchart--------------------------------------------------\n rect(x + offset * barwidth, yzero+plotheight, barwidth, -(map(value, 0, maxy1,0, plotheight)));\n\n // reset the colors for the rest of the bars\n fill(fillclrkeep);\n stroke(fillclrkeep);\n\n\n x += colwidth // shift rightward to next col\n }\n\n}",
"getXoffset() {\n return labelWidth + this.getFullwidth() + barHeight * 2 + 19\n }",
"function caluclateXYOffsets(chrtLoc) {\r\n var xOffset, yOffset, offsets;\r\n offsets = {};\r\n offsets.x = ((chrtLoc.xmax - chrtLoc.xmin) / 2 ) + chrtLoc.xmin;\r\n offsets.y = ((chrtLoc.ymax - chrtLoc.ymin) ) + chrtLoc.ymin;\r\n if (chartCircumfrence > 1) {\r\n offsets.y = ((chrtLoc.ymax - chrtLoc.ymin) / 2) + chrtLoc.ymin;\r\n }\r\n console.log('xOffset ' + xOffset);\r\n console.log('yOffset ' + yOffset);\r\n return offsets;\r\n }",
"checkPosition() {\n\t\tlet parentBounds = { top: 0, left: 0, width: 0, height: 0 };\n\t\tif (this.paletteDock.getBounds) {\n\t\t\tparentBounds = this.paletteDock.getChartBoundsOffset();\n\t\t}\n\t\t// Get the xyz values in px\n\t\tconst transformValue = this.style.transform.split(/\\w+\\(|\\);?/);\n\t\t// Parse out the integer values from the style\n\t\tconst coordinates = transformValue[1].split(/,\\s?/g).map(function (val) {\n\t\t\treturn parseInt(val);\n\t\t});\n\t\t// Apply the offsets normally produced by the mouse pointer. Nneeded to satisfy setTransformPosition\n\t\tcoordinates[0] += parentBounds.left + this.dragStrip.clientWidth * 0.5;\n\t\tcoordinates[1] += parentBounds.top + this.dragStrip.clientHeight * 0.5;\n\n\t\tthis.setTransformPosition(coordinates[0], coordinates[1]);\n\t}",
"function ploterrors(errors){\n\n // console.log('Plot errors');\n\n // console.log(errors);\n\n scaleX2.domain(d3.extent(errors, function(d){return d.i}));\n scaleY2.domain(d3.extent(errors, function(d){return d.error}));\n\n let errordots = svg2.selectAll('errordots')\n .data(errors);\n\n errordots\n .enter()\n .append('circle')\n .style('fill', 'none')\n .attr('cx',0)\n .attr('cy',height/2)\n .merge(errordots) \n .transition()\n .duration(200)\n .attr('class', 'circle')\n .attr('cx',d=>scaleX2(d.i))\n .attr('cy',d=>scaleY2(d.error))\n .attr('r', 1)\n .style('fill', '#F92A82')\n .style('fill-opacity', 0.5);\n \n\n errordots.exit().remove();\n\n\n let errorsline = svg2.append('path')\n .data([errors])\n .attr('class', 'line')\n .attr('d', errorline)\n .style('fill', 'none')\n .style('stroke', 'pink')\n .style('stroke-width', '2px');\n\n xAxis2.scale(scaleX2).ticks(5);\n yAxis2.scale(scaleY2).ticks(5).tickFormat(d3.format(1));\n\n xAxisGroup2.call(xAxis2);\n yAxisGroup2.call(yAxis2); \n}",
"function updateTrace1() {\n trace1 = {\n x: [x],\n y: [m*x],\n error_y: {\n type: 'constant',\n value: totalError()\n },\n error_x: {\n type: 'constant',\n value: xError\n },\n type: 'scatter',\n showlegend: false\n };\n}",
"function compute_ex_position(data) {\r\n let data_coords = data.map(d=>[get_coord(d, 'x'), get_coord(d, 'y')]);\r\n\r\n let total_x = 0, total_y = 0;\r\n for(var i in data_coords) {\r\n total_x += data_coords[i][0];\r\n total_y += data_coords[i][1];\r\n }\r\n\r\n let pos = [total_x/data_coords.length,\r\n total_y/data_coords.length];\r\n\r\n return pos;\r\n}",
"function err_in_cbar(csa){\n var m = csa.m;\n var n = csa.n;\n var stat = csa.stat;\n var cbar = csa.cbar;\n var j;\n var e, emax, cost;\n var pi = new Float64Array(1+m);\n eval_pi(csa, pi);\n emax = 0.0;\n for (j = 1; j <= n; j++)\n { if (stat[j] == GLP_NS) continue;\n cost = eval_cost(csa, pi, j);\n e = Math.abs(cost - cbar[j]) / (1.0 + Math.abs(cost));\n if (emax < e) emax = e;\n }\n return emax;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Toggle visibility of modal about us on main page | function toggleAboutUsModal(){
document.getElementById("about-us").classList.toggle("is-active");
} | [
"function toggleAbout() {\n openModal('about');\n }",
"function toggle() {\n setModal(!modal);\n }",
"function toggle() {\n setModal(!modal);\n }",
"aboutToggle(state) {\n state.aboutShow = !state.aboutShow;\n }",
"function aboutUs() {\n let modal = document.getElementById(\"about-us-modal\");\n// Get the button that opens the modal\n let btn = document.getElementById(\"about-us\");\n// Get the <span> element that closes the modal\n let span = document.getElementsByClassName(\"close\")[0];\n// When the user clicks on the button, open the modal\n btn.onclick = function () {\n modal.style.display = \"block\";\n modal.classList.add(\"mystyle\");\n }\n// When the user clicks on <span> (x), close the modal\n span.onclick = function () {\n modal.style.display = \"none\";\n }\n// When the user clicks anywhere outside of the modal, close it\n window.onclick = function (event) {\n if (event.target === modal) {\n modal.style.display = \"none\";\n }\n }\n}",
"function closeAbout(e) {\n document.getElementById(\"aboutModal\").style.display = \"none\"; \n}",
"function showAboutMe() {\n const content = document.getElementById(\"about-me-content\");\n if (content.style.display === \"none\") {\n content.style.display = \"block\";\n } else {\n content.style.display = \"none\";\n }\n}",
"function toggleAbout() {\n if (aboutBox.style.display == \"block\") {\n aboutBox.style.display = \"none\";\n }\n else {\n aboutBox.style.display = \"block\";\n }\n}",
"function OpenAbout() {\r\n\t\t\t\t\r\n\t\t$(\"li.about-open\").on('click', function() {\t\t\t\t\r\n\t\t\t$.fn.fullpage.setAllowScrolling(false);\r\n\t\t\t$(\".about-open\").toggleClass(\"hidden\");\r\n\t\t\t$(\".about-close\").toggleClass(\"hidden\");\r\n\t\t\t$(\"#about-us\").toggleClass(\"is-active\");\r\n\t\t});\r\n\t\t\r\n\t\t$(\"li.about-close\").on('click', function() {\t\t\t\t\r\n\t\t\t$.fn.fullpage.setAllowScrolling(true);\r\n\t\t\t$(\".about-open\").toggleClass(\"hidden\");\r\n\t\t\t$(\".about-close\").toggleClass(\"hidden\");\r\n\t\t\t$(\"#about-us\").toggleClass(\"is-active\");\r\n\t\t\t$('#about-us').animate({scrollTop : 0},300);\r\n\t\t});\t\t\t\r\n\t\t\t\r\n\t}",
"function expandInfo() {\n if(aboutContent.style.display === \"block\"){\n aboutContent.style.display = \"none\";\n }\n else{\n aboutContent.style.display = \"block\";\n }\n}",
"function togglePaymentInfo(on = false) {\n if(on)\n $('#payment_info').modal('show');\n else\n $('#payment_info').modal('hide');\n}",
"function showAbout() {\n $('#modal-container').html(about_wpaudit_template())\n $('#modal-container').modal()\n}",
"function aboutUs() {\n\tif (aboutUsStatus == false) {\n\n\t\tlet openAboutUsSection = document.querySelector('.aboutus');\n\t\topenAboutUsSection.style.height = \"500px\"; //opens the paragraph\n\n\t\topenAboutUsSection.style.borderBottom = \"solid 1px lightgrey\";\n\n\t\tlet openAboutUsParaf = document.querySelector('#aboutUsParaf');\n\t\topenAboutUsParaf.style.visibility = \"visible\";\n\t\topenAboutUsParaf.style.opacity = 1;\n\t\topenAboutUsParaf.style.transitionDelay = \"all 3s ease-in-out\";\n\t\topenAboutUsParaf.style.transition = \"all 3.5s ease-in-out\";\n\t\topenAboutUsParaf.style.display = \"block\";\n\n\n\t\taboutUsStatus = true;\n\t}else {\n\t\tlet openAboutUsSection = document.querySelector('.aboutus');\n\n\n\t\topenAboutUsSection.style.height = \"62px\";//closes the paragraph\n\t\topenAboutUsSection.style.borderBottom = \"solid 1px lightgrey\";\n\n\t\tlet openAboutUsParaf = document.querySelector('#aboutUsParaf');\n\t\topenAboutUsParaf.style.visibility = \"hidden\";\n\t\topenAboutUsParaf.style.opacity = 0;\n\t\topenAboutUsParaf.style.transition = \"all 1s ease-in-out\";\n\n\n\n aboutUsStatus = false;\n\n\t}\n}",
"function toggleJoinNowButtonOnAboutUSPage() {\n var loggedIn = !!getStorageItem(storageKeys.email);;\n if (loggedIn) {\n $(joinNowButtonAboutUSPageSelector).hide();\n return;\n }\n $(joinNowButtonAboutUSPageSelector).show();\n}",
"function openInfoModal() {\n document.getElementById('info-modal').style.display = 'block';\n}",
"function aboutMe(){\n\thideEverything();\n\t$aboutMe.show();\n}",
"function CloseAbout(){\n\n document.getElementById('about').style.display = 'none';\n\n}",
"function toggleDetails() {\n ToggleComponent('user.detailView').toggle();\n }",
"function togglePlayerInfoModal() {\n\t\tplayerModal.classList.add(\"hide\");\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a function generateColors which can generate any number of hexa or rgb colors. | function generateColors(type, num) {
let output = [];
if (type === 'hexa') {
for (let i = 0; i < num; i++) {
let a;
let r = Math.floor(Math.random() * 255).toString(16);
let g = Math.floor(Math.random() * 255).toString(16);
let b = Math.floor(Math.random() * 255).toString(16);
a = `#${r}${g}${b}`;
output.push(a);
}
} else if (type === 'rgb') {
for (let i = 0; i < num; i++) {
let a;
let r = Math.floor(Math.random() * 255);
let g = Math.floor(Math.random() * 255);
let b = Math.floor(Math.random() * 255);
a = `rgb(${r},${g},${b})`;
output.push(a);
}
} else {
console.log('Provide type hexa/rgb and number');
}
return output;
} | [
"function generateColors(hexa,number){\n const letters = '0123456789ABCDEF';\n let hexaNumber = '#'\n let retorno = []\n let anyt;\n for (let i = 0; i < number; i++){\n if(hexa == 'hexa'){\n for (let i = 0; i < 6; i++){\n anyt = hexaNumber + letters[Math.floor(Math.random() * 16)]} \n }\n retorno.push(anyt)\n }\n return retorno\n}",
"function generateColors(numColors){\r\n arr = [];\r\n for(var i = 0; i < numColors; i++){\r\n arr.push(singleColor());\r\n }\r\n return arr;\r\n}",
"function generateColors(\n n,\n startingHue = Math.floor(Math.random() * 360)\n) {\n return new Array(n)\n .fill('')\n .map((_, index) => {\n var hue = (startingHue + (Math.floor(360 / n) * index)) % 360;\n return `hsl(${hue}, 100%, 75%)`\n });\n}",
"function _generateColor() {\n\t\treturn [_getHexValue(),_getHexValue(),_getHexValue()];\n\t}",
"function generateColor(num){\n var colorsArr = [];\n for (var i = 0; i < num; i ++){\n colorsArr.push(pickColor());\n }\n return colorsArr;\n}",
"function generatedColor(num) {\r\n var coloring = []\r\n // fill the array with colors\r\n for (var i = 0; i < num; i++) {\r\n coloring.push(generatingColors());\r\n }\r\n return coloring\r\n}",
"function getColors(n) {\n var colors = [];\n for (var i=0; i<n; i++) {\n str = \"rgb(\" + getRandomInt(0, 256) + \", \" + getRandomInt(0, 256) + \", \" + getRandomInt(0, 256) + \")\";\n colors.push(str);\n }\n return colors;\n}",
"function rgbColorGenerator()\r\n{ \r\n return `rgb(${~~(Math.random() * 256)},${~~(Math.random() * 256)},${~~(Math.random() * 256)})`;\r\n}",
"function colorGenerator() {\n\tlet colorArray = [];\n\n\tfor (let i = 0; i < difficulty * 2.5; i++) {\n\t\tlet hue = Math.ceil(Math.floor(Math.random() * 360) / 20) * 20;\n\t\twhile (colorArray.includes(`hsl(${hue},100%,50%)`)) {\n\t\t\thue = Math.ceil(Math.floor(Math.random() * 360) / 20) * 20;\n\t\t}\n\t\tcolorArray.push(`hsl(${hue},100%,50%)`);\n\t}\n\treturn colorArray;\n}",
"function genColor() {\n var ret = []; // via http://stackoverflow.com/a/15804183\n\n if (next_color < 16777215) {\n ret.push(next_color & 0xff); // R\n\n ret.push((next_color & 0xff00) >> 8); // G\n\n ret.push((next_color & 0xff0000) >> 16); // B\n\n next_color += 10; // This is exaggerated for this example and would ordinarily be 1.\n } //if\n\n\n return 'rgb(' + ret.join(',') + ')';\n } //function genColor",
"function generateRandomColors(num) {\n //Make an array with num random rgb string\n var rgbArray=[];\n for (var i=0; i < num; i++) {\n //Gets rgb string from randomColor() and adds it to end of rgbArray\n rgbArray.push(randomColor());\n }\n //Returns rbgArray, containing num rgb strings\n return rgbArray;\n}",
"function create5colorsFromInitial() {\n console.log(\"Creating New Color From initial\");\n\n // Make array or something of 5 colors from initial HEX\n\n}",
"function getColors(n)\n{\n\tvar colors = [];\n\tfor(var i = 0; i < n; i++)\n\t{\n\t\tr = getRandom(255);\n\t\tg = getRandom(255);\n\t\tb = getRandom(255);\n\t\tcolors[i] = \"rgb(\" + r + \", \" + g + \", \" + b + \")\";\n\t}\n\n\treturn colors;\n}",
"function rgbColorGenerator() {\n let rgb = 'rgb(';\n for ( let i=0; i<2; i++ ) {\n rgb += Math.floor(Math.random() * 256);\n rgb += ',';\n }\n rgb += Math.floor(Math.random() * 256);\n rgb += ')';\n\n return rgb;\n }",
"function arrayOfHexaColors() {\n let output = [];\n let arglength = arguments.length;\n if (arglength > 0) {\n let input = arguments;\n for (let i = 0; i < arglength; i++) {\n output.push(arguments[i].toString(16));\n }\n }\n return output;\n}",
"function randomColorGenerator(num)\r\n{\r\n var arr=[];\r\n for(i=0; i< num; i++)\r\n {\r\n arr.push(randomColors());\r\n }\r\n return arr;\r\n}",
"function generateRandomColors(num){\n var arr = [];\n for (i = 0; i < num; i++) {\n arr.push(randomColor()); \n }\n return arr; \n}",
"function generateNewColor(num){\n\tcolors=[]\n\t// generate random rgb colors\n\tfor (i = 0; i < num; i++){\n\t\tr=Math.floor(Math.random()*256)\n\t\tg=Math.floor(Math.random()*256)\n\t\tb=Math.floor(Math.random()*256) \n\t\t//combine colours into a string \n\t\tc = \"rgb(\" + r + \", \" + g + \", \"+ b + \")\"\n\n\t\tcolors.push(c)\n\t}\n\tif (num === 3){\n\t\tfor(j=0; j<3; j++){\n\t\t\tcolors.push(\"#232323\")\n\t\t}\n\t}\n\treturn colors\n}",
"function randomhexaGenerator() {\n var letters = '0123456789abcdef';\n var color = '#';\n for (var i = 0; i < 6; i++) {\n color += letters[Math.floor(Math.random() * 16)]; // same like i+=1; i=1+i;\n //color =color + (letters[Math.floor(Math.random() * 16)]);\n }\n return color;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
calling choicesL(choices) function to run here | function choicesL(choices) {
let result = ''; //providing string to display result
for (let i = 0; i < choices.length; i++) { //looping over choice values
result += `<p class="userChoice" data-answer= "${choices[i]}">${choices[i]}</p>`; //setting data vaule and displaying them onto the page
}
return result; //returning result to display this function in questionL ()
} | [
"showChoices() {\n\t\tthis.undumSystem.writeChoices(this.choiceStringArray);\n\t}",
"function updateChoices() {\n currType = parseInt(Math.random() * 3);\n // currType = PRONUNCIATION;\n if (currType == MULTIPLE_CHOICE) {\n multipleChoice();\n } else if (currType == FILL_IN_THE_BLANK) {\n fillInTheBlank();\n } else if (currType == PRONUNCIATION) {\n pronunciation();\n }\n}",
"addChoices(...choices) {\n if (choices.length > 0 && this.autocomplete) {\n throw new RangeError(\"Autocomplete and choices are mutually exclusive to each other.\");\n }\n choicesPredicate.parse(choices);\n if (this.choices === void 0) {\n Reflect.set(this, \"choices\", []);\n }\n validateChoicesLength(choices.length, this.choices);\n for (const { name, name_localizations, value } of choices) {\n if (this.type === import_v1017.ApplicationCommandOptionType.String) {\n stringPredicate.parse(value);\n } else {\n numberPredicate.parse(value);\n }\n this.choices.push({\n name,\n name_localizations,\n value\n });\n }\n return this;\n }",
"function menuChoices() {\n inquirer\n .prompt(menu)\n .then( ({select_choice}) => {\n switch(select_choice) {\n case 'View All Departments':\n viewAllDept();\n menuChoices();\n break;\n case 'View All Roles':\n viewAllRoles();\n menuChoices();\n break;\n case 'View All Employees':\n console.log('View All Employees');\n viewAllEmp();\n menuChoices();\n break;\n case 'Add A Department':\n inqDepAdd();\n menuChoices();\n break;\n case 'Add A Role':\n console.log('Add A Role');\n break;\n case 'Add An Employee':\n console.log('Add An Employee');\n break;\n case 'Update Employee Role':\n console.log('Update Employee Role');\n }\n })\n}",
"function multiple_choice_prompt(prompt, choices, cb) {\n let form = document.createElement('form');\n form.appendChild(document.createElement('div')).innerHTML = prompt;\n let select = form.appendChild(document.createElement('select'));\n for (let choice of choices) {\n select.appendChild(document.createElement('option')).textContent = choice;\n }\n form.appendChild(make_ok((e) => {\n e.preventDefault();\n cb(select.selectedIndex);\n dismiss_overlay_message('mc_prompt');\n return false;\n }));\n display_overlay_message(form, 'mc_prompt');\n select.focus();\n}",
"showChoices() {\n\t\tconsole.log(\"No known way to display current choices: \"+this.choiceStringArray);\n\t}",
"setupChoices() {\n\n\t\tthis.CHOICES_INPUTS = [];\n\t\tthis.CHOICES_OUTPUTS = [];\n\n\t\tif (this.inputCount > 0) {\n\t\t\tfor(var key = 0; key < this.inputCount; key++) {\n\t\t\t\tif (this.getInput(key).status != 'None') {\n\t\t\t\t\tthis.CHOICES_INPUTS.push( { id: key, label: this.getInput(key).label } );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (this.outputCount > 0) {\n\t\t\tfor(var key = 0; key < this.outputCount; key++) {\n\t\t\t\tif (this.getOutput(key).status != 'None') {\n\t\t\t\t\tthis.CHOICES_OUTPUTS.push( { id: key, label: this.getOutput(key).label } );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"choose({\n question = `Choose one of the following:`,\n choices,\n prompt,\n exit,\n timeout,\n onMatch,\n onError = text => `_Sorry, but \\`${text}\\` is not a valid response. Please try again._`,\n }) {\n let keys;\n if (Array.isArray(choices)) {\n // Change from 0-indexed to 1-indexed. It makes the choices look prettier.\n keys = choices.map((c, i) => i + 1);\n choices = [null].concat(choices);\n }\n else {\n keys = Object.keys(choices);\n }\n\n const ask = () => this.ask({\n question: context => [\n this._fnOrValue(question, context),\n '',\n ...keys.map(k => `[*${k}*] ${choices[k]}`),\n ],\n prompt,\n exit,\n timeout,\n onResponse: (text, data) => {\n const match = keys.find(k => String(k).toLowerCase() === text.toLowerCase());\n if (match) {\n return onMatch(match, data);\n }\n return this.say(this._fnOrValue(onError, text, data)).then(ask);\n },\n });\n\n return ask();\n }",
"function loadChoices(){\n\t\tfor(i=0;i<questions[questionNumber].a.length; i++){\n\t\t\t$(\"#choices_list\").append(\"<li class='choice'>\"+questions[questionNumber].a[i]);\t\n\t\t}\n\t}",
"function addChoices() {\n // show container for inputs\n $input.removeClass('hidden');\n\n // disable property of radio buttons to not be checked\n $radios.prop('checked', false);\n\n /* iterates through choices object and populates choices */\n var c = $choices(); // calls choices function to store in variable\n for (var index in c) {\n $label[index].innerHTML = c[index];\n $radios[index].value = c[index];\n }\n }",
"setupChoices() {\n\n\t\tthis.CHOICES_INPUTS = [];\n\t\tthis.CHOICES_OUTPUTS = [];\n\t\tthis.CHOICES_SERIALS = [];\n\n\t\tif (this.inputCount > 0) {\n\t\t\tfor(var key = 0; key < this.inputCount; key++) {\n\t\t\t\tif (this.getInput(key).status != 'None') {\n\t\t\t\t\tthis.CHOICES_INPUTS.push( { id: key, label: this.getInput(key).label } );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (this.outputCount > 0) {\n\t\t\tfor(var key = 0; key < (this.outputCount + this.monitoringCount); key++) {\n\t\t\t\tif (this.getOutput(key).status != 'None') {\n\t\t\t\t\tthis.CHOICES_OUTPUTS.push( { id: key, label: this.getOutput(key).label } );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (this.serialCount > 0) {\n\t\t\tfor(var key = 0; key < this.serialCount; key++) {\n\t\t\t\tif (this.getSerial(key).status != 'None') {\n\t\t\t\t\tthis.CHOICES_SERIALS.push( { id: key, label: this.getSerial(key).label } );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"function execForMatchingChoice(facetChoices, name, func) {\n\t facetChoices.filter(matchesName(name)).forEach(func);\n\t }",
"choice(choices, choiceText, pgs1, pgs2 = null, pgs3 = null){\n //parameter validation; \n if (choices >= 2 && pgs2 == null){ return; }\n if (choices == 3 && pgs3 == null){ return; }\n if (choices > 3) { return; }\n \n }",
"function displayChatChoices() {\n sendChatMessage(\"a) \"+displayChoices[0]);\n sendChatMessage(\"b) \"+displayChoices[1]);\n sendChatMessage(\"c) \"+displayChoices[2]);\n sendChatMessage(\"d) \"+displayChoices[3]);\n sendChatMessage(\"e) \"+displayChoices[4]);\n sendChatMessage(\"---------------------------------------------------\");\n}",
"function updatechoices(result, choices) {\n if (result.length) {\n if (choices.length > result[0].length) return;\n if (choices.length < result[0].length) result.length = 0;\n }\n result.push(choices);\n}",
"function displayChoices() {\n\n //displays onto the HTML\n $(\".name1\").text(rand.choices[0]);\n $(\".name2\").text(rand.choices[1]);\n $(\".name3\").text(rand.choices[2]);\n $(\".name4\").text(rand.choices[3]);\n\n }",
"function choicesGenerator(choices) {\n\n var possibleAnswers = '';\n\n for (i = 0; i < choices.length; i++) {\n possibleAnswers += `<p class= \"choice\" data-answer=\"${choices[i]}\">${choices[i]}</p>`;\n }\n\n return possibleAnswers;\n\n}",
"static list(choices, text, speak, options) {\n const opt = Object.assign({\n includeNumbers: true\n }, options);\n // Format list of choices\n let connector = '';\n let txt = (text || '');\n txt += '\\n\\n ';\n ChoiceFactory.toChoices(choices).forEach((choice, index) => {\n const title = choice.action && choice.action.title ? choice.action.title : choice.value;\n txt += `${connector}${opt.includeNumbers ? (index + 1).toString() + '. ' : '- '}${title}`;\n connector = '\\n ';\n });\n // Return activity with choices as a numbered list.\n return botbuilder_1.MessageFactory.text(txt, speak, botbuilder_1.InputHints.ExpectingInput);\n }",
"setupCheckedChoices() {\n if (!this.opt.default || !_.isArray(this.opt.default)) {\n this.opt.default = this.opt.choices.realChoices.map((c) => c.value)\n }\n\n if (!this.opt.choices) {\n this.throwParamError('choices');\n }\n\n // TODO: validate this.opt.default args are a subset of the this.opt.choices\n // TODO: fill in missing gaps, when this.opt.default has non contigus \"checked\"\n\n this.checkedChoices = [];\n this.separatorOffset = 0;\n this.disabledOffset = 0;\n this.opt.choices.forEach((choice, i) => {\n const isSeperator = choice.type === 'separator';\n if (isSeperator) {\n this.separatorOffset++;\n return;\n }\n const isDisabled = Boolean(choice.disabled);\n if (isDisabled) {\n this.disabledOffset++;\n return;\n }\n const choiceIsDefaultChecked = this.opt.default.indexOf(choice.value) >= 0;\n if (choiceIsDefaultChecked) {\n const c = { choice, i, realI: i - (this.separatorOffset + this.disabledOffset) };\n c.choice.checked = true;\n this.checkedChoices.push(c);\n }\n });\n this.checkedChoices.sort((a, b) => a.i - b.i);\n this.anchorStart = this.realIndexOfChecked(_.first(this.checkedChoices));\n this.anchorEnd = this.realIndexOfChecked(_.last(this.checkedChoices));\n\n this.opt.default = null;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Looks for matching glob patterns or stdin | async function findFiles(globPatterns, options) {
const globPats = globPatterns.filter((filename) => filename !== STDIN);
const stdin = globPats.length < globPatterns.length ? [STDIN] : [];
const globResults = globPats.length ? await (0, glob_1.globP)(globPats, options) : [];
const cwd = options.cwd || process.cwd();
return stdin.concat(globResults.map((filename) => path.resolve(cwd, filename)));
} | [
"let exactMatch;\n for (let pattern in globMap) {\n if (this.isGlobMatch(filePath, pattern, pipeline)) {\n exactMatch = globMap[pattern];\n break;\n }\n }",
"async function findFiles(globPatterns, options) {\n const globPats = globPatterns.filter((filename) => filename !== STDIN);\n const stdin = globPats.length < globPatterns.length ? [STDIN] : [];\n const globResults = globPats.length ? await globP(globPats, options) : [];\n const cwd = options.cwd || process.cwd();\n return stdin.concat(globResults.map((filename) => path.resolve(cwd, filename)));\n}",
"function glob(/* patterns... */) {\n return glob.pattern.apply(null, arguments);\n }",
"glob(pattern=\"*\", opts={})\n {\n return new Promise((resolve,reject) =>\n {\n glob(this._string+\"/\"+pattern,opts, (err,results) => {\n if (err) return reject(err);\n resolve(results);\n })\n });\n }",
"function findPattern(files,regex){\n var emitter = new EventEmitter();\n files.forEach(function(file){\n fs.readFile(file,'utf8', function(err,content){\n \tif(err)\n \t\treturn emitter.emit('error',err); //return is very important here\n\n \temitter.emit('fileread',file);\n \tvar match = null;\n \tif(match = content.match(regex)){\n \t\tmatch.forEach(function(elem){\n \t\t\temitter.emit('found',file,elem);\n \t\t});\n \t}\n });\n });\n return emitter;\n\n}",
"function isGlob (text) { // 2358\n return text.indexOf('*') > -1; // 2359\n } // 2360",
"function isGlob(text) {\n\t return text.indexOf('*') > -1;\n\t }",
"function isGlob (text) {\n return text.indexOf('*') > -1;\n }",
"expandGlobPatterns(context, argv) {\n const nextArgv = [];\n this.debug('Expanding glob patterns');\n argv.forEach((arg) => {\n if (arg.charAt(0) !== '-' && is_glob_1.default(arg)) {\n const paths = fast_glob_1.default\n .sync(arg, {\n cwd: String(context.cwd),\n onlyDirectories: false,\n onlyFiles: false,\n })\n .map((path) => new common_1.Path(path).path());\n this.debug(' %s %s %s', arg, chalk_1.default.gray('->'), paths.length > 0 ? paths.join(', ') : chalk_1.default.gray(this.tool.msg('app:noMatch')));\n nextArgv.push(...paths);\n }\n else {\n nextArgv.push(arg);\n }\n });\n return nextArgv;\n }",
"function isGlob (text) {\n\t return text.indexOf('*') > -1;\n\t }",
"function simple_glob(glob) {\n if (Array.isArray(glob)) {\n return [].concat.apply([], glob.map(simple_glob));\n }\n if (glob && glob.match(/[*?]/)) {\n var dir = path.dirname(glob);\n try {\n var entries = fs.readdirSync(dir);\n } catch (ex) {}\n if (entries) {\n var pattern = \"^\" + path.basename(glob).replace(/[.+^$[\\]\\\\(){}]/g, \"\\\\$&\").replace(/\\*/g, \"[^/\\\\\\\\]*\").replace(/\\?/g, \"[^/\\\\\\\\]\") + \"$\";\n var mod = process.platform === \"win32\" ? \"i\" : \"\";\n var rx = new RegExp(pattern, mod);\n var results = entries.filter(function (name) {\n return rx.test(name);\n }).map(function (name) {\n return path.join(dir, name);\n });\n if (results.length) return results;\n }\n }\n return [glob];\n }",
"function findPattern(filePaths, regex) {\n const emitter = new EventMitter()\n filePaths.forEach(function(filePath) {\n // Events should be emitted later\n process.nextTick(() => emitter.emit('attempt', filePath))\n require('fs').readFile(\n require('path').resolve(filePath), 'utf8', function _(err, content) {\n if(err) {\n return emitter.emit('error', err)\n }\n emitter.emit('fileread', filePath)\n let match \n if(match = content.match(regex)) {\n match.forEach(function _(elem) {\n emitter.emit('found', filePath, elem)\n })\n }\n })\n })\n return emitter;\n}",
"function getGlobMatches(pattern, options = {}) {\n return new Promise((resolve, reject) => {\n glob(pattern, options, (err, matches) => {\n /* istanbul ignore next */\n if (err) {\n reject(err);\n }\n\n resolve(matches);\n });\n });\n}",
"function grepFileFn ( filename, pattern_str ) {\n return new PromiseObj( function ( resolve_fn, catch_fn ) {\n var\n line_read_obj = new LineReader( filename, {skipEmptyLines:true }),\n pattern_rx = new RegExp( pattern_str ),\n match_list = []\n ;\n\n line_read_obj.on( 'error', catch_fn );\n line_read_obj.on( 'line', function ( line_str ) {\n if ( line_str.match( pattern_rx ) ) {\n match_list.push( line_str );\n }\n });\n line_read_obj.on( 'end', function () {\n resolve_fn( match_list );\n });\n });\n}",
"globP(pattern, options) {\r\n return new Promise((resolve, reject) => {\r\n glob_1.default(pattern, options, (err, files) => {\r\n if (err) {\r\n reject(err);\r\n }\r\n else {\r\n resolve(files);\r\n }\r\n });\r\n });\r\n }",
"globP(pattern, options) {\n return new Promise((resolve, reject) => {\n glob(pattern, options, (err, files) => {\n if (err) {\n reject(err);\n }\n else {\n resolve(files);\n }\n });\n });\n }",
"function globMatch(file, globs) {\n for (let i = 0; i < globs.length; i += 1) {\n if (minimatch(file, globs[i])) {\n return true;\n }\n }\n return false;\n}",
"function find(pattern, location, opts, cb) {\n // Match the color code for background orange.\n var matchRegexp = new RegExp(/[\\u001b]\\[30;43m/g);\n var newFileRegexp = new RegExp(/^[\\u001b]\\[1;32m/);\n\n // Copy args\n var args = [].concat(opts._args);\n\n // Counter for number of files with matches\n var fileCount = 0;\n\n // Execute globs\n glob(location, {mark: true, dot: true}, function (error, files) {\n if (error) return cb(error);\n\n // Filter out all directories and .git .hg\n files = _.filter(files, function (file) {\n return !common.endsWith(file, '/') && !common.startsWith(file, '.git/') && !common.startsWith(file, '.hg/');\n });\n\n if (files.length === 0) return console.error('No files found.');\n\n // Spawn the ack process\n var child = spawn('xargs', [ackCmd].concat(args).concat(pattern));\n\n child.stdin.setEncoding = 'utf-8';\n child.stdin.write(files.join('\\n'));\n child.stdin.end();\n\n var stopIn = -1;\n var stopped = false;\n\n child.stdout.pipe(split())\n .on('data', function(line) {\n if (stopped) return;\n\n line = line.trim();\n if (line.length === 0) {\n return;\n }\n\n if (stopIn === 0) {\n stopped = true;\n child.kill('SIGHUP');\n\n return cb([\n 'Stopped because of max-result-limit at ',\n opts._resultsCount,\n ' match(es) in ',\n fileCount,\n ' file(s).\\n'\n ].join(''));\n }\n\n\n // Count all occurrences of the match in the line\n var matchesCount = line.match(matchRegexp);\n opts._resultsCount += matchesCount ? matchesCount.length : 0;\n\n if (line.match(newFileRegexp)) ++fileCount;\n\n // Output\n opts._readable.push(line + '\\n');\n\n // Decrement stopIn after output.\n if (stopIn > 0) return stopIn--;\n\n // If we are over the maximum stop the process and exit.\n if (stopIn === -1\n && opts.maxResults\n && opts._resultsCount >= opts.maxResults) {\n stopIn = opts.context;\n }\n })\n .on('end', function() {\n cb(null, fileCount);\n });\n\n child.stderr.pipe(process.stderr);\n });\n}",
"function grepMain() {\r\n\r\n\tlet argLen = process.argv.length;\r\n\r\n\t// The first element will be process.execPath\r\n\t// The second element will be the path to the JavaScript file being executed\r\n\t// The remaining elements will be any additional command line arguments\r\n\tif(argLen <= 2) {\r\n\t\tconsole.log(\"Usage: grep [-icR] [pattern] [file]\");\r\n\t\treturn;\r\n\t} else if (argLen > 5) {\r\n\t\tconsole.log(\"Wrong number of arguments, Usage: grep [-icR] [pattern] [file]\");\r\n\t\treturn;\r\n\t}\r\n\r\n\tvar argPromise = new Promise(function(resolve, reject) {\r\n\t\t\r\n\t\tlet options = '';\r\n\r\n\t\tprocess.argv.forEach((val, index) => {\r\n\r\n\t\t //console.log(`${index}: ${val}`);\r\n\r\n\t\t if(argLen === 4) {\r\n\r\n\t\t \tif(index === 2)\r\n\t\t \t\tpattern = val;\r\n\t\t \telse\r\n\t\t \t\tfileLoc = val;\r\n\r\n\t\t } else if (argLen === 5) {\r\n\r\n\t\t \tif(index === 2)\r\n\t\t \t\toptions = val;\r\n\t\t \telse if(index === 3)\r\n\t\t \t\tpattern = val;\r\n\t\t \telse\r\n\t\t \t\tfileLoc = val;\r\n\r\n\t\t }\r\n\r\n\t\t if (index === argLen-1) {\r\n\t\t \targObj = {\r\n\t\t\t\t'options': options,\r\n\t\t\t\t'pattern': pattern,\r\n\t\t\t\t'fileLoc': fileLoc\r\n\t\t \t}\r\n\r\n\t\t \tresolve(argObj);\r\n\t\t }\r\n\r\n\t\t});\r\n\r\n\t});\r\n\r\n\targPromise.then(function(argObj) {\r\n\r\n\t\t// Print promise object\r\n\t\t//console.log(argObj);\r\n\r\n\t\tlet options = argObj.options;\r\n\t\tlet pattern = argObj.pattern;\r\n\t\tlet fileLoc = argObj.fileLoc;\r\n\r\n\t\tif (options.indexOf('r') > 0) {\r\n\r\n\t\t\trecursive(fileLoc, function (err, files) {\r\n\r\n\t\t\t\tif(err){\r\n\t\t\t\t\tconsole.log('Error: not able to find directory');\r\n\t\t\t\t\tprocess.exit(1);\r\n\t\t\t\t};\r\n\r\n\t\t\t\t// `files` is an array of file paths\r\n\t\t\t\t//console.log(files);\r\n\r\n\t\t\t\t(async function loop() {\r\n\t\t\t\t\tfor (let i = 0; i < files.length; i++) {\r\n\t\t\t\t\t\tawait new Promise(resolve => setTimeout(resolve, Math.random() * 1000));\r\n\t\t\t\t\t\tprint(files[i]);\r\n\t\t\t\t\t}\r\n\t\t\t\t})();\r\n\r\n\t\t\t});\r\n\r\n\t\t} else {\r\n\t\t\tprint(fileLoc);\r\n\t\t}\r\n\r\n\t\tfunction print(fileLoc) {\r\n\r\n\t\t\tconst fileStream = fs.createReadStream(fileLoc);\r\n\r\n\t\t\tfileStream.on('error', function(err) {\r\n\t\t\t\tif(err) {\r\n\t\t\t\t\tconsole.log('Invalid argument: ' + err);\r\n\t\t\t\t\tprocess.exit(1);\r\n\t\t\t\t}\r\n\t\t\t});\r\n\r\n\t\t\tconst rd = readline.createInterface({\r\n\t\t\t input: fileStream,\r\n\t\t\t output: process.stdout,\r\n\t\t\t terminal: false\r\n\t\t\t});\r\n\r\n\t\t\tlet countOfMatchedLines = 0;\r\n\r\n\t\t\trd.on('line', function(line) {\r\n\r\n\t\t\t\tif(options != '') {\r\n\r\n\t\t\t\t\tlet flgOpt = '';\r\n\r\n\t\t\t\t\tif (options[0] != \"-\") {\r\n\t\t\t\t\t\tconsole.log('Invalid options!');\r\n\t\t\t\t\t\tprocess.exit(1);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif(options.indexOf('i') > 0) {\r\n\r\n\t\t\t\t\t\tflgOpt = 'i';\r\n\r\n\t\t\t\t\t\tlet lowerLine = line.toLowerCase();\r\n\t\t\t\t\t\tlet lowerPattern = pattern.toLowerCase();\r\n\r\n\t\t\t\t\t\tif(lowerLine.includes(lowerPattern)){\r\n\r\n\t\t\t\t\t\t\tif(options.indexOf('r') > 0) {\r\n\r\n\t\t\t\t\t\t\t\tif(options.indexOf('c') <= 0) {\r\n\t\t\t\t\t\t\t\t\tconsole.log(fileLoc + ': ' + line + '\\n');\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t} else if(options.indexOf('c') <= 0) {\r\n\r\n\t\t\t\t\t\t\t\tconsole.log(line);\r\n\r\n\t\t\t\t\t\t\t} \r\n\r\n\t\t\t\t\t\t}\t\t\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif(options.indexOf('c') > 0) {\r\n\r\n\t\t\t\t\t\tif(flgOpt=='i') {\r\n\t\t\t\t\t\t\tline = line.toLowerCase();\r\n\t\t\t\t\t\t\tpattern = pattern.toLowerCase();\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tif(line.includes(pattern)){\r\n\t\t\t\t\t\t\tcountOfMatchedLines++;\r\n\t\t\t\t\t\t}\t\t\t\t\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif(options.indexOf('r') > 0 && flgOpt != 'i' && options.indexOf('c') <= 0) {\r\n\r\n\t\t\t\t\t\tif(line.includes(pattern)){\r\n\t\t\t\t\t\t\tconsole.log(fileLoc + ': ' + line + '\\n');\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t} else {\r\n\r\n\t\t\t\t\tif(line.includes(pattern)){\r\n\t\t\t\t\t\tconsole.log(line);\r\n\t\t\t\t\t}\t\r\n\r\n\t\t\t\t}\r\n\r\n\t\t\t});\r\n\r\n\t\t\trd.on('close', function(line) {\r\n\r\n\t\t\t\tif(countOfMatchedLines>0) {\r\n\t\t\t\t\t\r\n\t\t\t\t\tif(options.indexOf('r') > 0) {\r\n\t\t\t\t\t\tconsole.log(fileLoc +': ' + countOfMatchedLines);\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tconsole.log(countOfMatchedLines);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t}\r\n\r\n\t\t\t});\r\n\r\n\t\t}\r\n\t\t\r\n\t});\r\n\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
! createStringFromCodePointArray.js Version 1.0.0 | function createStringFromCodePointArray(codePoints) {
// quicker than using `String.fromCodePoint.apply(String, codePoints)`
// (and 32766 was the amount limit of argument for a function call).
var i = 0, l = codePoints.length, code, s = "";
for (; i < l; i += 1) {
code = codePoints[i];
//if (0xD800 <= code && code <= 0xDFFF) s += String.fromCharCode(0xFFFD); else
if (code <= 0xFFFF) s += String.fromCharCode(code);
else if (code <= 0x10FFFF) { // surrogate pair
code -= 0x10000;
s += String.fromCharCode(0xD800 + ((code >>> 10) & 0x3FF), 0xDC00 + (code & 0x3FF));
} else throw new Error("Invalid code point " + code);
}
return s;
} | [
"function fromCodePoints(arr = []) {\n return arr.map(n => String.fromCodePoint(n)).join('');\n }",
"generateCodePointArray() {\n let index = 0;\n this.codePoints = [];\n while (index < this.str.length) {\n const num = JSUtils.toCodePoint(this.str, index);\n index += ((num > 0xFFFF) ? 2 : 1);\n this.codePoints.push(num);\n }\n }",
"function _array2str(chararray) \n{ return String.fromCharCode.apply(null, chararray);\n}",
"function fromCodePoint(code) {\n if (code <= 0xffff) return String.fromCharCode(code);\n code -= 0x10000;\n return String.fromCharCode((code >> 10) + 0xd800, (code & 1023) + 0xdc00);\n} /// The first character that takes up two positions in a JavaScript",
"function Utf8ArrayToStr(array) {\n var out, i, len, c;\n var char2, char3;\n\n out = \"\";\n len = array.length;\n i = 0;\n while (i < len) {\n c = array[i++];\n switch (c >> 4) {\n case 0:\n case 1:\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n case 7:\n // 0xxxxxxx\n out += String.fromCharCode(c);\n break;\n case 12:\n case 13:\n // 110x xxxx 10xx xxxx\n char2 = array[i++];\n out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));\n break;\n case 14:\n // 1110 xxxx 10xx xxxx 10xx xxxx\n char2 = array[i++];\n char3 = array[i++];\n out += String.fromCharCode(((c & 0x0F) << 12) |\n ((char2 & 0x3F) << 6) |\n ((char3 & 0x3F) << 0));\n break;\n }\n }\n return out;\n}",
"function _kn_stringFromCharCode() // codes ...\n{\n return _kn_stringFromCharCodes(arguments);\n}",
"function\nXATS2JS_string_vt2t\n (cs)\n{\ncs.pop(); // remove the last '0'\nlet res = // from array to string\nString.fromCharCode.apply(null, cs);\nreturn res; // XATS2JS_string_vt2t\n}",
"function codepointSequenceToString(seq) {\n return String.fromCharCode.apply(String, seq);\n}",
"function encodeCodePointInUtf8Array(code, utf8Codes, i, l) { // XXX rename vars XXX rename function s/Array/CodeArray/ ?\n // XXX do documentation\n\n // errors :\n // reserved code point (if > U+D800 & < U+DFFF)\n // invalid code point (if > U+10FFFF)\n // no space on buffer\n // no left space on buffer\n\n var b = 0, c = 0, d = 0, error = \"\";\n if (i >= l) { return {writeLength: 0, error: \"no space on buffer\"}; }\n if (code <= 0x7F) {\n utf8Codes[i] = code;\n return {writeLength: 1, error: \"\"};\n } else if (code <= 0x7FF) {\n // a = (0x1E << (6 - 1)) | (code & (0x3F >> 1));\n b = 0x80 | (code & 0x3F); code >>>= 6;\n utf8Codes[i++] = 0xC0 | (code & 0x1F);\n if (i >= l) { return {writeLength: 1, error: \"no left space on buffer\"}; }\n utf8Codes[i] = b;\n return {writeLength: 2, error: \"\"};\n } else if (code <= 0xFFFF) {\n if (0xD800 <= code && code <= 0xDFFF) error = \"reserved code point\";\n // a = (0x1E << (6 - 2)) | (code & (0x3F >> 2));\n c = 0x80 | (code & 0x3F); code >>>= 6;\n b = 0x80 | (code & 0x3F); code >>>= 6;\n utf8Codes[i++] = 0xE0 | (code & 0xF);\n if (i >= l) { return {writeLength: 1, error: \"no left space on buffer\"}; } // conflicts with \"reserved code point\" error ?\n utf8Codes[i++] = b;\n if (i >= l) { return {writeLength: 2, error: \"no left space on buffer\"}; } // conflicts with \"reserved code point\" error ?\n utf8Codes[i] = c;\n return {writeLength: 3, error: error};\n } else if (code <= 0x10FFFF) {\n // a = (0x1E << (6 - 3)) | (code & (0x3F >> 3));\n d = 0x80 | (code & 0x3F); code >>>= 6;\n c = 0x80 | (code & 0x3F); code >>>= 6;\n b = 0x80 | (code & 0x3F); code >>>= 6;\n utf8Codes[i++] = 0xF0 | (code & 0x7);\n if (i >= l) { return {writeLength: 1, error: \"no left space on buffer\"}; }\n utf8Codes[i++] = b;\n if (i >= l) { return {writeLength: 2, error: \"no left space on buffer\"}; }\n utf8Codes[i++] = c;\n if (i >= l) { return {writeLength: 3, error: \"no left space on buffer\"}; }\n utf8Codes[i] = d;\n } else {\n return {writeLength: 0, error: \"invalid code point\"};\n }\n }",
"function createUtf8CodeArrayFromString(text) {\n // XXX do documentation\n var i = 0, l = text.length, utf16Codes = new Array(l);\n for (; i < l; i += 1) utf16Codes[i] = text.charCodeAt(i);\n return createUtf8CodeArrayFromUtf16CodeArray(utf16Codes, 0, utf16Codes.length);\n }",
"function caml_string_of_array (a) { return new MlString(4,a,a.length); }",
"function stringToCodepoints(str) {\n var result =[];\n for (var i = 0; i < str.length; i++) {\n var c = str.charCodeAt(i);\n result.push((c >= 55296 && c <= 56319) ? ((c - 55296) * 1024) + (str.charCodeAt(++ i) - 56320) + 65536: c);\n }\n //saxonPrint(\"to-codepoints \" + result.join());\n return result;\n }",
"function decodeCodePointFromUtf8CodeArray(array, i, l) {\n // decodeCodePointFromUtf8CodeArray(bytes, 0, bytes.length) -> {result, length, error, warnings, requiredLength, expectedLength}\n // decodeCodePointFromUtf8CodeArray([0xc3, 0xa9, 0x61, 0x62], 0, 4) -> {.: 233, .: 2, .: \"\", .: \"\", .: 0, .: 2}\n\n // Unpacks the first UTF-8 encoding in array and returns the rune and its\n // width in bytes.\n\n // errors:\n // invalid start byte\n // invalid continuation byte\n // invalid code point\n // unexpected empty data\n // unexpected end of data\n // warnings:\n // overlong encoding\n // reserved code point\n\n // Return value:\n // {\n // result: 0xFFFD, // the resulting codepoint (default is runeError)\n // length: 0, // nb of utf8code read/used\n // error: \"\", // error code\n // warnings: \"\", // comma seperated warning codes\n // requiredLength: 0, // additional nb of utf8code required to possibly fix the error\n // expectedLength: 0, // the length of the expected code point size\n // };\n\n // \"reserved code point\" warning never happens at the same time as with \"overlong encoding\"\n\n // Benchmark shows that the speed is equal with old decodeUtf8XxxLikeChrome using decodeXxxAlgorithm.\n // XXX benchmark with return [runeError, 0, error, 1, 1]\n // XXX benchmark with decodeCodePointFromUtf8CodeArray.Result = makeStruct(\"result,length,error,warnings,requiredLength,expectedLength\");\n\n var code = 0,\n a = 0, c = 0,\n warnings = \"\",\n runeError = 0xFFFD;\n\n if (i >= l) { return {result: runeError|0, length: 0, error: \"unexpected empty data\", warnings: warnings, requiredLength: 1, expectedLength: 1}; }\n code = array[i];\n\n if (code <= 0x7F) { return {result: code|0, length: 1, error: \"\", warnings: warnings, requiredLength: 0, expectedLength: 1}; } // one byte required\n if ((0xE0 & code) === 0xC0) { // two bytes required\n if (code < 0xC2) { warnings = \"overlong encoding\"; }\n a = code;\n if (i + 1 >= l) { return {result: runeError|0, length: 1, error: \"unexpected end of data\", warnings: warnings, requiredLength: 1, expectedLength: 2}; }\n code = array[i + 1];\n if ((0xC0 & code) != 0x80) { return {result: runeError|0, length: 2, error: \"invalid continuation byte\", warnings: warnings, requiredLength: 0, expectedLength: 2}; }\n return {result: ((a << 6) | (code & 0x3F)) & 0x7FF, length: 2, error: \"\", warnings: warnings, requiredLength: 0, expectedLength: 2};\n }\n if ((0xF0 & code) === 0xE0) { // three bytes required\n a = code;\n if (i + 1 >= l) { return {result: runeError|0, length: 1, error: \"unexpected end of data\", warnings: warnings, requiredLength: 2, expectedLength: 3}; }\n code = array[i + 1];\n if ((0xC0 & code) != 0x80) { return {result: runeError|0, length: 2, error: \"invalid continuation byte\", warnings: warnings, requiredLength: 0, expectedLength: 3}; }\n if ((c = a) === 0xE0 && code <= 0x9F) { warnings = \"overlong encoding\"; }\n a = (c << 6) | (code & 0x3F);\n if (i + 2 >= l) { return {result: runeError|0, length: 2, error: \"unexpected end of data\", warnings: warnings, requiredLength: 1, expectedLength: 3}; }\n code = array[i + 2];\n if ((0xC0 & code) != 0x80) { return {result: runeError|0, length: 3, error: \"invalid continuation byte\", warnings: warnings, requiredLength: 0, expectedLength: 3}; }\n if (0xD800 <= (c = ((a << 6) | (code & 0x3F)) & 0xFFFF) && c <= 0xDFFF) { warnings = (warnings ? \",\" : \"\") + \"reserved code point\"; }\n return {result: c|0, length: 3, error: \"\", warnings: warnings, requiredLength: 0, expectedLength: 3};\n }\n if ((0xF8 & code) === 0xF0) { // four bytes required\n if (code >= 0xF5) { return {result: runeError|0, length: 1, error: \"invalid start byte\", warnings: warnings, requiredLength: 0, expectedLength: 4}; }\n a = code;\n if (i + 1 >= l) { return {result: runeError|0, length: 1, error: \"unexpected end of data\", warnings: warnings, requiredLength: 3, expectedLength: 4}; }\n code = array[i + 1];\n if ((0xC0 & code) != 0x80) { return {result: runeError|0, length: 2, error: \"invalid continuation byte\", warnings: warnings, requiredLength: 0, expectedLength: 4}; }\n if ((c = a) === 0xF0 && code <= 0x8F) { warnings = \"overlong encoding\"; }\n a = (c << 6) | (code & 0x3F);\n if (i + 2 >= l) { return {result: runeError|0, length: 2, error: \"unexpected end of data\", warnings: warnings, requiredLength: 2, expectedLength: 4}; }\n code = array[i + 2];\n if ((0xC0 & code) != 0x80) { return {result: runeError|0, length: 3, error: \"invalid continuation byte\", warnings: warnings, requiredLength: 0, expectedLength: 4}; }\n a = (a << 6) | (code & 0x3F);\n if (i + 3 >= l) { return {result: runeError|0, length: 3, error: \"unexpected end of data\", warnings: warnings, requiredLength: 1, expectedLength: 4}; }\n code = array[i + 3];\n if ((0xC0 & code) != 0x80) { return {result: runeError|0, length: 4, error: \"invalid continuation byte\", warnings: warnings, requiredLength: 0, expectedLength: 4}; }\n if ((c = ((a << 6) | (code & 0x3F)) & 0x1FFFFF) > 0x10FFFF) { return {result: runeError|0, length: 4, error: \"invalid code point\", warnings: warnings, requiredLength: 0, expectedLength: 4}; }\n return {result: c|0, length: 4, error: \"\", warnings: warnings, requiredLength: 0, expectedLength: 4};\n }\n return {result: runeError|0, length: 1, error: \"invalid start byte\", warnings: warnings, requiredLength: 0, expectedLength: 1};\n }",
"function writeString(array){\n try { return char.apply(null, array) } catch (e) {}\n\n var string = '',\n cycles = array.length % 8,\n index = 0;\n\n while (cycles--) {\n string += indices[array[index++]];\n }\n\n cycles = array.length >> 3;\n\n while (cycles--) {\n string +=\n indices[array[index]] +\n indices[array[index+1]] +\n indices[array[index+2]] +\n indices[array[index+3]] +\n indices[array[index+4]] +\n indices[array[index+5]] +\n indices[array[index+6]] +\n indices[array[index+7]];\n index += 8;\n }\n\n return string;\n }",
"function getStandardCharacters (charCodes) {\n var charArray = [];\n for (var i = charCodes[0]; i <= charCodes[1]; i++) {\n charArray.push(String.fromCharCode(i));\n }\n return charArray;\n}",
"function getExpandedCharCodes(input){var output=[];var length=input.length;for(var i=0;i<length;i++){var charCode=input.charCodeAt(i);// handle utf8\nif(charCode<0x80){output.push(charCode);}else if(charCode<0x800){output.push(charCode>>6|192);output.push(charCode&63|128);}else if(charCode<0x10000){output.push(charCode>>12|224);output.push(charCode>>6&63|128);output.push(charCode&63|128);}else if(charCode<0x20000){output.push(charCode>>18|240);output.push(charCode>>12&63|128);output.push(charCode>>6&63|128);output.push(charCode&63|128);}else{ts.Debug.assert(false,\"Unexpected code point\");}}return output;}",
"function caml_string_of_array (a) { return new MlBytes(4,a,a.length); }",
"function UniArrayToString(arr) {\n var ix, val, newarr;\n var len = arr.length;\n if (len == 0)\n return '';\n for (ix=0; ix<len; ix++) {\n if (arr[ix] >= 0x10000) \n break;\n }\n if (ix == len) {\n return String.fromCharCode.apply(this, arr);\n }\n newarr = Array(len);\n for (ix=0; ix<len; ix++) {\n val = arr[ix];\n if (val < 0x10000) {\n newarr[ix] = String.fromCharCode(val);\n }\n else {\n val -= 0x10000;\n newarr[ix] = String.fromCharCode(0xD800 + (val >> 10), 0xDC00 + (val & 0x3FF));\n }\n }\n return newarr.join('');\n}",
"function charMap(code) {\r\n if(code==32) { return [\" \",'0 0 0 0']; } // space\r\n\r\n if(code==65 || code=='A') { return [\"𝐴\",'0 0 0 0']; } // A\r\n if(code==66 || code=='B') { return [\"𝐵\",'0 .17em 0 0']; }\r\n if(code==67 || code=='C') { return [\"𝐶\",'0 .1em 0 0']; }// C\r\n if(code==68 || code=='D') { return [\"𝐷\",'0 .1em 0 0']; }\r\n if(code==69 || code=='E') { return [\"𝐸\",'0 .12em 0 0']; }// E\r\n if(code==70 || code=='F') { return [\"𝐹\",'0 .14em 0 0']; }\r\n if(code==71 || code=='G') { return [\"𝐺\",'0 .12em 0 0']; }// G\r\n if(code==72 || code=='H') { return [\"𝐻\",'0 .13em 0 0']; }\r\n if(code==73 || code=='I') { return [\"𝐼\",'0 .13em 0 0']; }// I\r\n if(code==74 || code=='J') { return [\"𝐽\",'0 .15em 0 0']; } // J\r\n if(code==75 || code=='K') { return [\"𝐾\",'0 .15em 0 0']; }\r\n if(code==76 || code=='L') { return [\"𝐿\",'0 .08em 0 0']; }// L\r\n if(code==77 || code=='M') { return [\"𝑀\",'0 .13em 0 0']; }\r\n if(code==78 || code=='N') { return [\"𝑁\",'0 .13em 0 0']; }// N\r\n if(code==79 || code=='O') { return [\"𝑂\",'0 .11em 0 0']; }\r\n if(code==80 || code=='P') { return [\"𝑃\",'0 .1em 0 0']; }// P\r\n if(code==81 || code=='Q') { return [\"𝑄\",'0 .09em 0 0']; }\r\n if(code==82 || code=='R') { return [\"𝑅\",'0 .03em 0 0']; }// R\r\n if(code==83 || code=='S') { return [\"𝑆\",'0 .11em 0 0']; }\r\n if(code==84 || code=='T') { return [\"𝑇\",'0 .14em 0 0']; } // T\r\n if(code==85 || code=='U') { return [\"𝑈\",'0 .16em 0 0']; }\r\n if(code==86 || code=='V') { return [\"𝑉\",'0 .16em 0 0']; }// V\r\n if(code==87 || code=='W') { return [\"𝑊\",'0 .16em 0 0']; }\r\n if(code==88 || code=='X') { return [\"𝑋\",'0 .16em 0 0']; }// X\r\n if(code==89 || code=='Y') { return [\"𝑌\",'0 .17em 0 0']; }\r\n if(code==90 || code=='Z') { return [\"𝑍\",'0 .17em 0 0']; }// Z\r\n\r\n if(code==97 || code=='a') { return [\"𝑎\",'0 .08em 0 0']; } // a\r\n if(code==98 || code=='b') { return [\"𝑏\",'0 .1em 0 0']; }\r\n if(code==99 || code=='c') { return [\"𝑐\",'0 .12em 0 0']; }\r\n if(code==100 || code=='d') { return [\"𝑑\",'0 .1em 0 0']; }\r\n if(code==101 || code=='e') { return [\"𝑒\",'0 .1em 0 0']; }\r\n if(code==102 || code=='f') { return [\"𝑓\",'0 .15em 0 .13em']; }\r\n if(code==103 || code=='g') { return [\"𝑔\",'0 .1em 0 .03em']; } \r\n if(code==104 || code=='h') { return [\"ℎ\",'0 .05em 0 0']; }\r\n if(code==105 || code=='i') { return [\"𝑖\",'0 .1em 0 0']; }\r\n if(code==106 || code=='j') { return [\"𝑗\",'0 .09em 0 .07em']; } // j\r\n if(code==107 || code=='k') { return [\"𝑘\",'0 .1em 0 0']; }\r\n if(code==108 || code=='l') { return [\"𝑙\",'0 .15em 0 0']; }\r\n if(code==109 || code=='m') { return [\"𝑚\",'0 .05em 0 0']; } // m\r\n if(code==110 || code=='n') { return [\"𝑛\",'0 .05em 0 0']; }\r\n if(code==111 || code=='o') { return [\"𝑜\",'0 .08em 0 0']; }\r\n if(code==112 || code=='p') { return [\"𝑝\",'0 .1em 0 .07em']; }\r\n if(code==113 || code=='q') { return [\"𝑞\",'0 .12em 0 0']; }\r\n if(code==114 || code=='r') { return [\"𝑟\",'0 .11em 0 0']; }\r\n if(code==115 || code=='s') { return [\"𝑠\",'0 .11em 0 0']; }\r\n if(code==116 || code=='t') { return [\"𝑡\",'0 .15em 0 0']; } // t\r\n if(code==117 || code=='u') { return [\"𝑢\",'0 .08em 0 0']; }\r\n if(code==118 || code=='v') { return [\"𝑣\",'0 .12em 0 0']; }\r\n if(code==119 || code=='w') { return [\"𝑤\",'0 .1em 0 0']; }\r\n if(code==120 || code=='x') { return [\"𝑥\",'0 .05em 0 0']; }\r\n if(code==121 || code=='y') { return [\"𝑦\",'0 .06em 0 0']; }\r\n if(code==122 || code=='z') { return [\"𝑧\",'0 .07em 0 0']; }\r\n\r\n if(code==60 || code=='<') { return [\"<\",'0 .2em']; } // <\r\n if(code==62 || code=='>') { return [\">\",'0 .2em']; } // >\r\n\r\n if(code==42 || code=='*') { return [\"∗\",'0 .2em']; } // *\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
default config for a close button | get closeButton() {
return {
command: "cancel",
icon: "close",
label: "Cancel",
type: "rich-text-editor-button",
};
} | [
"handleClose() {\n this.showConfirm = false;\n }",
"function closeSettings() {\n\n $settingsElement.classed(showClass, false);\n $settingsButton.classed(activeClass, false);\n }",
"function settingsCancel(ev) {\r\n closeSettings();\r\n}",
"function settingsClosed(event)\r\n{\r\n\tif (event.closeAction == event.Action.commit) \r\n\t{\r\n\t\tloadTheme();\r\n\t\tcurrentFeed = 0;\r\n\t\tgetNews();\r\n\t}\r\n}",
"_close() {\n this.close();\n this.opts.onClose && this.opts.onClose();\n }",
"function setCloseBtn() {\n\n\t\t\t\t_$parent.find('#close-btn').on('click',function() {\n\n\t\t\t\t\t_$parent.animate({\n\t\t\t\t\t\topacity : 0,\n\t\t\t\t\t\ttop : parseInt(_$parent.css('top')) + 50 + 'px'\n\t\t\t\t\t},100, function() {\n\t\t\t\t\t\t_$parent.add($('#onigiri-style')).remove();\n\t\t\t\t\t});\n\t\t\t\t});\n\n\t\t\t\treturn false;\n\t\t\t}",
"close() {\n\t\tif (this.options.closedLabel) {\n\t\t\tthis.$ctaContent.text(this.options.closedLabel);\n\t\t\tthis.$el.attr('title', this.options.closedLabel);\n\t\t}\n\n\t\tthis.$el.removeClass(this.options.activeClass);\n\t\tthis.active = false;\n\t}",
"close() {\n\n\t\t\tthis.displayConfirm = false;\n\t\t}",
"function handleClose() {\n setInfoBar(false);\n setButtonActive(\"\");\n }",
"_onCloseButtonTap() {\n this.fireDataEvent(\"close\", this);\n }",
"function btn_settings_close() {\n var o = {};\n\n settings.chattz = ge(\"settings_chattz\").selectedIndex;\n settings.distunit = ge(\"settings_distunit\").selectedIndex;\n settings.logtz = ge(\"settings_logtz\").selectedIndex;\n settings.dateform = ge(\"settings_dateform\").selectedIndex;\n hide_overlay();\n o.cmd = \"settings\";\n o.settings = settings;\n ws_send_message(o);\n}",
"function settingsClosed(event)\r\n{\r\n\tif (event.closeAction == event.Action.commit) \r\n\t{\r\n\t\tcurrentProject = 0;\r\n\t\tgetProjects();\r\n\t}\r\n}",
"_onCloseClick(e) {\n this.hide();\n }",
"function closeConfigWindow()\n{\n\t//Determine if any backup rounds have been defined\n\tif (config.getConfig()['rounds'].length > 0)\n\t{\n\t\t//Open the list of rounds\n\t\tloadPage(mainWindow, 'rounds');\n\t}\n\telse\n\t{\n\t\t//Quit the application\n\t\tmainWindow.close();\n\t}\n}",
"function optionPopUpClose(){\n//\thighLightId();\n\tif ($('#StatTerminal').is(':checked')){\n\t\tglobalTerminal = 'yes';\n\t}else{\n\t\tglobalTerminal = 'no';\n\t}\t\n\n\tif ($('#StatSwitch').is(':checked')){\n\t\tglobalSwitch = 'yes'\n\t}else{\n\t\tglobalSwitch = 'no'\n\t}\n\t//console.log(globalSwitch+\" globalSwitch\");\n\t$( \"#StatisticOption\" ).dialog('close');\n\tchangeComponents();\n}",
"close() {\n this.sendAction('close');\n }",
"function close(){\n\t\tresizePopin();\n\t\toptions.hide(domElement);\n\t}",
"function close() {\n settings.container.hide();\n settings.container.empty();\n\n $('#overlay').remove();\n\n if (typeof onClose === 'function') { onClose(); }\n}",
"close() {\n this._qs(\"#close-popup\").addEventListener(\"click\", () => {\n this.exitDock();\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method submits the request to delete a research area to server. It first checks to see that there are no pending changes that need to be persisted, and submits only if so. If there are pending changes then it will simply ask the user to either save or abandon the changes. | function deleteResearchArea(liId) {
if (raChanges.moreChangeData()) {
if (confirm('You must save (or abandon) all outstanding changes before attempting a delete. Do you want to save changes to Research Area Hierarchy?')) {
save();
}
$j("#researcharea").empty();
raChanges = new RaChanges();
nextRaChangeProcessIdx = 0;
cutNode = null;
deletedNodes = "";
newNodes = ";";
icur = 1;
loadFirstLevel();
$j("#listcontent00").show();
return false;
}
else {
var researchAreaCode = getResearchAreaCode($j(liId));
// alert("RAcode is " + researchAreaCode);
$j("#headermsg").html("");
$j.ajax({
url: getResearchAreaAjaxCall(),
type: 'POST',
dataType: 'html',
data: 'researchAreaCode='
+ researchAreaCode
+ '&addRA=D',
cache: false,
async: false,
timeout: 1000,
error: function () {
alert('This research area cannot be deleted (perhaps due to archival reasons), but you could try deactivating it.');
},
success: function (xml) {
$j(xml).find('h3').each(function () {
retmsg = $j(this).text();
});
if (retmsg == 'Success') {
// alert("removing node now");
$j(liId).remove();
cutNode = null;
$j('<span id="msg"/>').css("color", "black").html("Research area deleted successfully").appendTo($j("#headermsg"));
$j('<br/>').appendTo($j("#headermsg"));
} else {
$j('<span id="msg"/>').css("color", "red").html("Research area could not be deleted.<br/>" + retmsg).appendTo($j("#headermsg"))
$j('<br/>').appendTo($j("#headermsg"));
alert('This research area cannot be deleted (perhaps due to archival reasons), but you could try deactivating it.');
}
}
}); // end ajax
return false;
}
} | [
"function capacityDelete()\r\n{\r\n\tvar htmlAreaObj = _getWorkAreaDefaultObj();\r\n \tvar objAjax = htmlAreaObj.getHTMLAjax();\r\n var objHTMLData = htmlAreaObj.getHTMLDataObj();\r\n \tif(objAjax)\r\n \t{\r\n \t\t// Check for valid record to execute process.\r\n\t \tif(!isValidRecord(true))\r\n\t\t{\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t// Changes have been done, prompt the User\r\n\t\t// to decide whether the User will Save or\r\n\t\t// continue with the deletion.\r\n\t\tif(objHTMLData!=null && objHTMLData.isDataModified())\r\n {\r\n var htmlErrors = objAjax.error();\r\n htmlErrors.addError(\"confirmInfo\", szMsg_Changes, false);\r\n\t \t\tmessagingDiv(htmlErrors, \"saveWorkArea()\", \"_capDelete()\");\r\n\t \t\treturn;\r\n }\r\n // No changes simply Delete\r\n else\r\n {\r\n \t_capDelete();\r\n }\t\t\r\n \t}\r\n}",
"function remove_selected_from_db() {\n // initialze data string\n var data = \"type=delete\";\n\n // append data string with relevant info\n var elements = document.getElementsByClassName('mark_delete');\n for (var i = 0; i < elements.length; i++) {\n data += \"&del_docs[]\" + \"=\"+ elements[i].value;\n }\n\n // send the request to the server\n var req = new Request(\"update.php\", { post: data });\n req.whenDone = function () {\n get_contents(\"docs\");\n new Request(\n \"side.php\",\n { get: \"part=docs\" },\n document.getElementById(\"side_docs\")\n ).execute();\n };\n req.execute();\n\n // close down action\n console.log(\"DELETE statement sent\");\n document.getElementById('form_del').innerHTML = \"\";\n unselectAllRows();\n modalOff();\n}",
"function deleteObservation() {\n const deleteObservationURL = \"/api/delete-observation/\" + document.getElementById(\"deleteObservationId\").value;\n\n const deleteRequestObject = {\n method:'DELETE'\n }\n\n fetch(deleteObservationURL, deleteRequestObject)\n .then(() => {location.reload()})\n}",
"deleteOrg(orgId){\n if(window.confirm('Are you sure?')){\n fetch('/organizations/'+orgId, {\n method:'DELETE',\n headers: {'Accept':'application/json','Content-Type':'application/json'}\n })\n }\n this.refreshOrgs();\n }",
"function deleteStoreIssue()\n{\n var issueId = dijit.byId(\"StoresIssue.No\").getValue();\n dojo.publish(\"/saving\", [{message: \"<b>Deleting...: \", type: \"info\", duration: 5000}]);\n\n dojo.xhrGet(\n {\n url: \"servlets/storeIssueManager?operationType=delete&issueId=\" + issueId,\n load: function(response)\n {\n dojo.publish(\"/saved\", [{message: \"<b>...Deleted\", type: \"info\", duration: 10000}]);\n nextStoreIssue();\n dijit.byId(\"StoresIssue.DeleteDialog\").hide();\n },\n error: function(response)\n {\n if (response.status == 0)\n {\n sessionEnded();\n return;\n }\n\n dojo.publish(\"/saved\", [{message: \"<b>...Failed\", type: \"error\", duration: 5000}]);\n }\n });\n}",
"function cancelform() {\n\n if (mode=='add') {\n removeLastFeature();\n }\n editedFeature=null;\n onsaved(null,'cancelled');\n}",
"_handleRequestWorkflowRunDelete(options)\n {\n Radio.channel('rodan').request(RODAN_EVENTS.REQUEST__MODAL_SHOW_IMPORTANT, {title: 'Deleting Workflow Run', content: 'Please wait...'});\n options.workflowrun.destroy({success: (model) => Radio.channel('rodan').trigger(RODAN_EVENTS.EVENT__WORKFLOWRUN_DELETED, {workflowrun: model})});\n }",
"function deleteStaffTake() {\n //request to delete the staff take form\n}",
"function performClearRepositoryRequest() {\n //Perform DELETE request\n $http.delete(\"/deviceDescriptions\").then(() => {\n //Clear device descriptions list\n $scope.deviceDescriptionsList = [];\n //Show success alert\n Swal.fire({\n title: 'Success',\n text: 'The repository was successfully cleared.',\n icon: 'success',\n timer: ALERT_TIMEOUT\n });\n }, handleRequestFailure);\n }",
"function HTL_removeIssues() {\n let selectedLocalIDs = [];\n for (let i = 0; i < issueRefs.length; i++) {\n issueRef = issueRefs[i]['project_name']+':'+issueRefs[i]['id'];\n let checkbox = document.getElementById('cb_' + issueRef);\n if (checkbox && checkbox.checked) {\n selectedLocalIDs.push(issueRef);\n }\n }\n\n if (selectedLocalIDs.length > 0) {\n if (!confirm('Remove all selected issues?')) {\n return;\n }\n let selectedLocalIDString = selectedLocalIDs.join(',');\n $('bulk_remove_local_ids').value = selectedLocalIDString;\n $('bulk_remove_value').value = 'true';\n setCurrentColSpec();\n\n let form = $('bulkremoveissues');\n form.submit();\n } else {\n alert('Please select some issues to remove');\n }\n}",
"function mission_delete(){\n var mission_id = encodeURIComponent(document.getElementById('mission_delete_name').value);\n\n //Sends delete request to PHP to process.\n request = new XMLHttpRequest();\n if (!request) {\n throw 'HttpRequest object not created.';\n }\n url = 'http://web.engr.oregonstate.edu/~olsoeric/CS340/mission_data.php?req=delete_mission&id=' + mission_id;\n request.open('GET', url, true);\n request.send();\n request.onreadystatechange = function () {\n if (this.readyState === 4) {\n mission_delete_stage();\n clear_detail();\n }\n }\n}",
"function remove() {\n if ($window.confirm('Are you sure you want to delete?')) {\n vm.submission.$remove($state.go('contests.list'));\n }\n }",
"deleteAction(id){\n \t\tlet apiKey = this.props.apiKey;\n \t\tlet api = \"https://api.jotform.com/submission/\"+id+\"?apiKey=\"+apiKey;\n \t\tfetch(api, {method: 'delete'})\n \t\t.then(function(response){\n\t \treturn response.json();\n\t })\n\t .then(function(data){\n\t \t// if done successfully, routing FORMS LAYOUT\n\t \tif(data.responseCode==200){\n\t \t\tAlert.alert(\"Success\",\"Submission deleted successfully.\");\n\t \t}\n\t \telse\n\t \t\tAlert.alert(\"Error\",\"Error happened while delete operation.\")\n\t });\n \t}",
"afterSubmit(){\n $H.removeForms()\n $H.resetCreateBlocks()\n Project.showList()\n Project.reload()\n }",
"function submit_delete_list()\n{\n // If a request is currently active, do NOT stop it.\n // Let it finish so there are no errors in the database.\n if (request)\n {\n return false;\n }\n \n if ($(\"success_monitor\").innerHTML != \"\")\n {\n $(\"success_monitor\").innerHTML = \"\";\n }\n \n request = new XMLHttpRequest();\n let url = \"deletewords.php\";\n \n let words_to_delete = JSON.stringify(selected_list);\n \n request.open(\"POST\", url, true);\n request.setRequestHeader('Content-type',\n 'application/x-www-form-urlencoded');\n request.onload = function()\n {\n let success_notice = document.createElement('p');\n // word(s) successfully deleted\n if (request.responseText == 1)\n {\n success_notice.classList.add(\"success\");\n \n success_notice.innerHTML = \"Successfully deleted: \";\n \n for (let i = 0; i < selected_list.length; i++)\n {\n let word = selected_list[i].split(\"_\", 1);\n \n if (i == (selected_list.length - 1))\n {\n success_notice.innerHTML += word + \".\";\n }\n else\n {\n success_notice.innerHTML += word + \", \";\n } \n }\n }\n // error deleting word(s)\n else\n {\n success_notice.classList.add(\"fail\");\n \n if (selected_list.length > 1)\n {\n success_notice.innerHTML = \"Failed to delete all words\";\n }\n else\n {\n success_notice.innerHTML = \"Failed to delete word\";\n }\n }\n $(\"success_monitor\").appendChild(success_notice);\n \n reset_delete_grid();\n\n // revert to null so other request may be made\n request = null;\n }\n request.send(\"words_to_delete=\" + words_to_delete);\n \n return false;\n}",
"function deleteArea(){\n loadArea(true, \"Eliminando archivo\", true);\n fetch(direccion + `doc/${fileCheck.value}`,{\n method: 'DELETE'\n }).then(function(res){\n return res.json();\n }).then(function(myRes){\n pdfToolsCnt.style.opacity = \"\";\n pdfToolsCnt.style.zIndex = \"\";\n loadArea(false, \"\",true);\n })\n}",
"function deleteExperiment(idExp, cbSuccess, cbError){\n\t\tvar xhttp = new XMLHttpRequest();\n\t\txhttp.onreadystatechange = function(){\n\t\t\tcallbackAJAX(xhttp, cbSuccess, cbError);\n\t\t\t};\n\t\t\n\t\txhttp.open('POST', aponeURL+\"/service/experiment/delete\", true);\n\t\txhttp. setRequestHeader(\"Content-Type\", \"text/plain\");\n\t\txhttp.send(idExp); \n\t}",
"function deactivateResearchArea(id) {\n if (raChanges.moreChangeData()) {\n if (confirm('You must save (or abandon) all outstanding changes before attempting a deactivation. Do you want to save changes to Research Area Hierarchy?')) {\n save();\n }\n\n $j(\"#researcharea\").empty();\n raChanges = new RaChanges();\n nextRaChangeProcessIdx = 0;\n cutNode = null;\n deletedNodes = \"\";\n newNodes = \";\";\n icur = 1;\n\n loadFirstLevel();\n $j(\"#listcontent00\").show();\n return false;\n }\n else {\n var researchAreaCode = getResearchAreaCode($j(\"#\" + id));\n // alert(\"RAcode is \" + researchAreaCode);\n var retValue = false;\n // alert(\"retvalue before ajax\" + retValue);\n $j(\"#headermsg\").html(\"\");\n $j.ajax({\n url: getResearchAreaAjaxCall(),\n type: 'POST',\n dataType: 'html',\n data: 'researchAreaCode='\n + researchAreaCode\n + '&addRA=I',\n cache: false,\n async: false,\n timeout: 1000,\n error: function () {\n alert('This research area cannot be deactivated because it (or one of its descendants) is being currently referenced.');\n retValue = false;\n },\n success: function (xml) {\n $j(xml).find('h3').each(function () {\n retmsg = $j(this).text();\n });\n if (retmsg == 'Success') {\n $j('<span id=\"msg\"/>').css(\"color\", \"black\").html(\"Research area deactivated successfully\").appendTo($j(\"#headermsg\"));\n $j('<br/>').appendTo($j(\"#headermsg\"));\n\n $j('input[id^=checkActive]', 'li#' + id).each(function () {\n $j(this).attr('checked', false);\n });\n $j('input[id^=activeflag]', 'li#' + id).val('false');\n\n retValue = true;\n } else {\n alert('This research area cannot be deactivated because it (or one of its descendants) is being currently referenced.');\n $j('<span id=\"msg\"/>').css(\"color\", \"red\").html(\"Research area could not be deactivated.<br/>\" + retmsg).appendTo($j(\"#headermsg\"))\n $j('<br/>').appendTo($j(\"#headermsg\"));\n retValue = false;\n }\n }\n }); // end ajax\n // alert(\"retvalue before returning\" + retValue);\n return retValue;\n }\n}",
"deleteGapAnalysis() {\n this._get(\n \"deleteGapAnalysis?user=\" +\n this.state.owner +\n \"&project=\" +\n this.state.project\n ).then((response) => {\n console.log(response);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
removes the file from the import route dialogue | function handleImportRouteRemove(e) {
//if the file is removed from the view, we do NOT remove the waypoints from the list, etc.
//just remove the erorr message if visible
showImportRouteError(false);
} | [
"function cancelImport() {\n var thisImportDialog = this;\n thisImportDialog.hide();\n gOverlay.hide();\n}",
"unassignFile(file) {\n delete this.files[file.srcPath.toLowerCase()];\n delete this.pkgMap[file.pkgPath.toLowerCase()];\n return file;\n }",
"function handleImportRouteSelection() {\n\t\t\tvar file;\n\t\t\tvar fileInput = $$('#gpxUploadFiles input[type=\"file\"]')[0];\n\t\t\tif (fileInput && fileInput.files && fileInput.files.length > 0) {\n\t\t\t\tfile = fileInput.files[0];\n\t\t\t} else if (fileInput && fileInput.value) {\n\t\t\t\t//IE doesn't know x.files\n\t\t\t\tfile = fileInput.value;\n\t\t\t}\n\n\t\t\tif (file) {\n\t\t\t\ttheInterface.emit('ui:uploadRoute', file);\n\t\t\t}\n\t\t}",
"function remove_design_file(){\n console.log('removing existing design file');\n $('.file_to_remove').parents('.design_file_row').fadeOut('300');\n event.preventDefault();\n }",
"function removeExposeMeFileFrom(project) {\n file = path.resolve(project,filename);\n if(fs.existsSync(file))\n fs.unlinkSync(file);\n}",
"function limpiarImportarModelo(){\n //aqui el codigo\n document.getElementById(\"inputfile\").value=\"\";\n\t\t\t}",
"onDeleteFile() {\r\n const file = this.state.selected;\r\n\r\n if (file == 'main.js') return;\r\n\r\n const script = Object.assign({}, this.state.script);\r\n\r\n delete script[this.state.selected];\r\n\r\n this.setState({ script, selected: '' });\r\n }",
"stop() {\n this.contentMap.forEach((val, filePath) => {\n if (!this.overrides.has(filePath)) {\n fs.unlinkSync(this.getAbsPath(filePath));\n }\n });\n }",
"detruire () {\n if (this.nom) { fs.unlinkSync(this.path) }\n }",
"onremove() {\n this.chosenFile = null;\n this.uploadProgress = null;\n }",
"function deleteFile() {\r\n\t\t// sent to the server.\r\n\t\tlocation.href = \"index.html\";\r\n\t}",
"async interactivelyRemoveImport () {\n const { importsList } = this.ui;\n const requester = this.view.getWindow();\n const sels = importsList.selections;\n if (!sels || !sels.length) return;\n const really = await this.world().confirm([\n 'Really remove these imports?\\n', {},\n arr.pluck(sels, 'local').join('\\n'), { fontWeight: 'normal', fontSize: 16 }],\n { requester });\n if (!really) return;\n const error = await this.editor.withContextDo(async (ctx) => {\n let m, origSource;\n try {\n m = ctx.selectedModule;\n origSource = await m.source();\n await m.removeImports(sels);\n return false;\n } catch (e) {\n origSource && await m.changeSource(origSource);\n return e;\n }\n }, { sels });\n importsList.selection = null;\n if (error) requester.showError(error);\n this.refreshInterface();\n }",
"function _discardVideo() {\n var filepath = file.split(\"/\");\n var fileEnd = filepath[6];\n var fileString = fileEnd.toString();\n var myFolder = fileSystemModule.knownFolders.temp();\n myFile = myFolder.getFile(fileString);\n if (myFile) {\n myFile.remove();\n } else {\n console.error(\"Couldn't remove \" + fileString + \" because the file does not exist.\");\n }\n}",
"_removeFile(name) {\n let index = this.indexOf(name)\n\n if (index !== -1) {\n this._files.splice(index, 1)\n\n if (this.options.load) {\n this._list.splice(index, 1)\n }\n }\n }",
"function _discardVideo() {\n var filepath = path.split(\"/\");\n file = filepath[6];\n fileString = file.toString();\n myFolder = fileSystemModule.knownFolders.temp();\n myFile = myFolder.getFile(fileString);\n myFile.remove();\n}",
"function deleteFileHandler(event){\r\n\t\tremoveFile(event.data);\r\n\t\tredrawUploadField();\r\n\t}",
"function finalize(){\n process.send(['import-finalizing', 'null']);// mainWindow.webContents.send('import-finalizing');\n\n let final = fs.openSync(stagePath, 'r+');\n fs.fsyncSync(final);\n fs.closeSync(final);\n\n let processed = path.join(process.cwd(), 'data', 'processed.csv');\n\n fs.rename(stagePath, processed, function (err) {\n if (err){\n console.log(err);\n process.send(['import-failed', 'finalize']); //mainWindow.webContents.send('import-failed', 'finalize');\n } else {\n if (isUpd) {\n if (keepDL) {\n fs.unlink(extract, function (err) {\n if (err) {\n console.log(err);\n process.send(['notify', ['Unable to remove extracted file', 'danger']]); //mainWindow.webContents.send('notify', ['Unable to remove downloaded file', 'danger']);\n }\n process.send(['import-success', timestamp]);// mainWindow.webContents.send('import-success', timestamp);\n });\n } else {\n fs.unlink(filePath, function (err) {\n if (err) {\n console.log(err);\n process.send(['notify', ['Unable to remove downloaded file', 'danger']]); //mainWindow.webContents.send('notify', ['Unable to remove downloaded file', 'danger']);\n }\n fs.unlink(extract, function (err) {\n if (err) {\n console.log(err);\n process.send(['notify', ['Unable to remove extracted file', 'danger']]); //mainWindow.webContents.send('notify', ['Unable to remove downloaded file', 'danger']);\n }\n process.send(['import-success', timestamp]);// mainWindow.webContents.send('import-success', timestamp);\n });\n });\n }\n } else {\n // Last updated time will be the opened file's modified time if manually imported\n let tstamp = new Date().toString();\n if (ext === '.gz') {\n fs.unlink(extract, function (err) {\n if (err) {\n console.log(err);\n process.send(['notify', ['Unable to remove extracted file', 'danger']]); //mainWindow.webContents.send('notify', ['Unable to remove downloaded file', 'danger']);\n }\n fs.stat(filePath, function (err, data) {\n tstamp = data.mtime;\n process.send(['import-success', tstamp]);// mainWindow.webContents.send('import-success', tstamp);\n });\n });\n } else {\n fs.stat(filePath, function (err, data) {\n tstamp = data.mtime;\n process.send(['import-success', tstamp]);// mainWindow.webContents.send('import-success', tstamp);\n });\n }\n }\n }\n });\n}",
"static unloadTextFile (fileName)\n {\n Engine.resourceMap.unloadAsset(fileName);\n }",
"function _deleteUploadFile(event){\n //Get the index of the clicked file in the array of file to upload\n var fileIndex = _getFileIndex(event.target.parentNode.childNodes[0].innerHTML);\n //Delete the file from the array\n filesToUpload.splice(fileIndex, 1);\n //Delete the file from the list of files to be uploaded in the app \n event.target.parentNode.parentNode.remove();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the values of the countries | function calculate_values_of_countries(wc_selection, club_selecton) {
var data_plot1 = [];
var data_plot2 = [];
// Als 1 van de 2 een land is, dan loopt ie over de desbetreffende loop maar 1 keer, zoals gewenst
var world_cup_countries = make_selection_of_world_cup_countries(wc_selection);
var club_countries = make_selection_of_club_countries(club_selecton);
for (var i = 0; i < club_countries.length; i ++)
{
data_plot1.push(which_players_in_country(club_countries[i], wc_selection, club_selecton)[0].length);
}
for (var i = 0; i < world_cup_countries.length; i ++)
{
data_plot2.push(which_players_in_country(world_cup_countries[i], wc_selection, club_selecton)[1].length);
}
return [data_plot1, data_plot2];
} | [
"function getCountryValues() {\n // Retrive selected county on dropdown menu\n const countrySelected = countryDropdownMenu.value;\n console.log(countrySelected);\n\n // Retrive the data for country selected\n const selectedCountryInformation = data.filter(\n (entry) => entry.Country === countrySelected\n );\n console.log(selectedCountryInformation);\n\n // Feeding an array for the years of interest to get an objet with two arrays\n // Each array is key:value equivalet to \"year of interest\":\"values of interest defined in country_happiness_keys\"\n const dataArrayByYears = [\"2019\", \"2020\"].map((year) => {\n const yearData = selectedCountryInformation.find(\n (entry) => entry.Year === year\n );\n\n return [year, countryHappinessKeys.map((key) => yearData[key])];\n });\n return Object.fromEntries(dataArrayByYears);\n }",
"function getCountries() {\n var countryChoices = [\n {\n \"abbr\":\"\",\n \"name\":\"(not applicable)\"\n },\n {\n \"abbr\":\"AF\",\n \"name\":\"Afghanistan\"\n },\n {\n \"abbr\":\"AX\",\n \"name\":\"Akrotiri\"\n },\n {\n \"abbr\":\"AL\",\n \"name\":\"Albania\"\n },\n {\n \"abbr\":\"AG\",\n \"name\":\"Algeria\"\n },\n {\n \"abbr\":\"AQ\",\n \"name\":\"American Samoa\"\n },\n {\n \"abbr\":\"AN\",\n \"name\":\"Andorra\"\n },\n {\n \"abbr\":\"AO\",\n \"name\":\"Angola\"\n },\n {\n \"abbr\":\"AV\",\n \"name\":\"Anguilla\"\n },\n {\n \"abbr\":\"AY\",\n \"name\":\"Antarctica \"\n },\n {\n \"abbr\":\"AC\",\n \"name\":\"Antigua and Barbuda\"\n },\n {\n \"abbr\":\"AR\",\n \"name\":\"Argentina\"\n },\n {\n \"abbr\":\"AM\",\n \"name\":\"Armenia\"\n },\n {\n \"abbr\":\"AA\",\n \"name\":\"Aruba\"\n },\n {\n \"abbr\":\"AT\",\n \"name\":\"Ashmore and Cartier Islands\"\n },\n {\n \"abbr\":\"AS\",\n \"name\":\"Australia\"\n },\n {\n \"abbr\":\"AU\",\n \"name\":\"Austria\"\n },\n {\n \"abbr\":\"AJ\",\n \"name\":\"Azerbaijan\"\n },\n {\n \"abbr\":\"BF\",\n \"name\":\"Bahamas\"\n },\n {\n \"abbr\":\"BA\",\n \"name\":\"Bahrain\"\n },\n {\n \"abbr\":\"FQ\",\n \"name\":\"Baker Island \"\n },\n {\n \"abbr\":\"BG\",\n \"name\":\"Bangladesh\"\n },\n {\n \"abbr\":\"BB\",\n \"name\":\"Barbados \"\n },\n {\n \"abbr\":\"BO\",\n \"name\":\"Belarus\"\n },\n {\n \"abbr\":\"BE\",\n \"name\":\"Belgium\"\n },\n {\n \"abbr\":\"BH\",\n \"name\":\"Belize\"\n },\n {\n \"abbr\":\"BN\",\n \"name\":\"Benin\"\n },\n {\n \"abbr\":\"BD\",\n \"name\":\"Bermuda\"\n },\n {\n \"abbr\":\"BT\",\n \"name\":\"Bhutan\"\n },\n {\n \"abbr\":\"BL\",\n \"name\":\"Bolivia\"\n },\n {\n \"abbr\":\"BK\",\n \"name\":\"Bosnia-Herzegovina\"\n },\n {\n \"abbr\":\"BC\",\n \"name\":\"Botswana\"\n },\n {\n \"abbr\":\"BV\",\n \"name\":\"Bouvet Island\"\n },\n {\n \"abbr\":\"BR\",\n \"name\":\"Brazil\"\n },\n {\n \"abbr\":\"IO\",\n \"name\":\"British Indian Ocean Territory\"\n },\n {\n \"abbr\":\"VI\",\n \"name\":\"British Virgin Islands\"\n },\n {\n \"abbr\":\"BX\",\n \"name\":\"Brunei\"\n },\n {\n \"abbr\":\"BU\",\n \"name\":\"Bulgaria\"\n },\n {\n \"abbr\":\"UV\",\n \"name\":\"Burkina Faso\"\n },\n {\n \"abbr\":\"BM\",\n \"name\":\"Burma\"\n },\n {\n \"abbr\":\"BY\",\n \"name\":\"Burundi\"\n },\n {\n \"abbr\":\"CB\",\n \"name\":\"Cambodia\"\n },\n {\n \"abbr\":\"CM\",\n \"name\":\"Cameroon\"\n },\n {\n \"abbr\":\"CA\",\n \"name\":\"Canada \"\n },\n {\n \"abbr\":\"CV\",\n \"name\":\"Cape Verde\"\n },\n {\n \"abbr\":\"CJ\",\n \"name\":\"Cayman Islands\"\n },\n {\n \"abbr\":\"CT\",\n \"name\":\"Central African Republic\"\n },\n {\n \"abbr\":\"CD\",\n \"name\":\"Chad\"\n },\n {\n \"abbr\":\"CI\",\n \"name\":\"Chile\"\n },\n {\n \"abbr\":\"CH\",\n \"name\":\"China \"\n },\n {\n \"abbr\":\"KT\",\n \"name\":\"Christmas Island\"\n },\n {\n \"abbr\":\"IP\",\n \"name\":\"Clipperton Island\"\n },\n {\n \"abbr\":\"CK\",\n \"name\":\"Cocos (Keeling) Islands\"\n },\n {\n \"abbr\":\"CO\",\n \"name\":\"Colombia\"\n },\n {\n \"abbr\":\"CN\",\n \"name\":\"Comoros \"\n },\n {\n \"abbr\":\"CF\",\n \"name\":\"Congo (Brazzaville)\"\n },\n {\n \"abbr\":\"CG\",\n \"name\":\"Congo (Kinshasa)\"\n },\n {\n \"abbr\":\"CW\",\n \"name\":\"Cook Islands\"\n },\n {\n \"abbr\":\"CR\",\n \"name\":\"Coral Sea Islands\"\n },\n {\n \"abbr\":\"CS\",\n \"name\":\"Costa Rica\"\n },\n {\n \"abbr\":\"IV\",\n \"name\":\"Cote D'Ivoire (Ivory Coast)\"\n },\n {\n \"abbr\":\"HR\",\n \"name\":\"Croatia\"\n },\n {\n \"abbr\":\"CU\",\n \"name\":\"Cuba\"\n },\n {\n \"abbr\":\"UC\",\n \"name\":\"Curacao\"\n },\n {\n \"abbr\":\"CY\",\n \"name\":\"Cyprus\"\n },\n {\n \"abbr\":\"EZ\",\n \"name\":\"Czech Republic\"\n },\n {\n \"abbr\":\"DA\",\n \"name\":\"Denmark\"\n },\n {\n \"abbr\":\"DX\",\n \"name\":\"Dhekelia\"\n },\n {\n \"abbr\":\"DJ\",\n \"name\":\"Djibouti\"\n },\n {\n \"abbr\":\"DO\",\n \"name\":\"Dominica\"\n },\n {\n \"abbr\":\"DR\",\n \"name\":\"Dominican Republic\"\n },\n {\n \"abbr\":\"TT\",\n \"name\":\"East Timor \"\n },\n {\n \"abbr\":\"EC\",\n \"name\":\"Ecuador\"\n },\n {\n \"abbr\":\"EG\",\n \"name\":\"Egypt\"\n },\n {\n \"abbr\":\"ES\",\n \"name\":\"El Salvador\"\n },\n {\n \"abbr\":\"EK\",\n \"name\":\"Equatorial Guinea\"\n },\n {\n \"abbr\":\"ER\",\n \"name\":\"Eritrea\"\n },\n {\n \"abbr\":\"EN\",\n \"name\":\"Estonia\"\n },\n {\n \"abbr\":\"ET\",\n \"name\":\"Ethiopia\"\n },\n {\n \"abbr\":\"FK\",\n \"name\":\"Falkland Islands (Islas Malvinas)\"\n },\n {\n \"abbr\":\"FO\",\n \"name\":\"Faroe Islands\"\n },\n {\n \"abbr\":\"FM\",\n \"name\":\"Federated States of Micronesia\"\n },\n {\n \"abbr\":\"FJ\",\n \"name\":\"Fiji\"\n },\n {\n \"abbr\":\"FI\",\n \"name\":\"Finland\"\n },\n {\n \"abbr\":\"FR\",\n \"name\":\"France\"\n },\n {\n \"abbr\":\"FP\",\n \"name\":\"French Polynesia\"\n },\n {\n \"abbr\":\"FS\",\n \"name\":\"French Southern and Antarctic Lands\"\n },\n {\n \"abbr\":\"GB\",\n \"name\":\"Gabon\"\n },\n {\n \"abbr\":\"GA\",\n \"name\":\"The Gambia\"\n },\n {\n \"abbr\":\"GG\",\n \"name\":\"Georgia\"\n },\n {\n \"abbr\":\"GM\",\n \"name\":\"Germany\"\n },\n {\n \"abbr\":\"GH\",\n \"name\":\"Ghana\"\n },\n {\n \"abbr\":\"GI\",\n \"name\":\"Gibraltar\"\n },\n {\n \"abbr\":\"GR\",\n \"name\":\"Greece\"\n },\n {\n \"abbr\":\"GL\",\n \"name\":\"Greenland\"\n },\n {\n \"abbr\":\"GJ\",\n \"name\":\"Grenada\"\n },\n {\n \"abbr\":\"GQ\",\n \"name\":\"Guam\"\n },\n {\n \"abbr\":\"GT\",\n \"name\":\"Guatemala\"\n },\n {\n \"abbr\":\"GK\",\n \"name\":\"Guernsey\"\n },\n {\n \"abbr\":\"GV\",\n \"name\":\"Guinea\"\n },\n {\n \"abbr\":\"PU\",\n \"name\":\"Guinea-Bissau\"\n },\n {\n \"abbr\":\"GY\",\n \"name\":\"Guyana\"\n },\n {\n \"abbr\":\"HA\",\n \"name\":\"Haiti\"\n },\n {\n \"abbr\":\"HM\",\n \"name\":\"Heard Island and McDonald Islands\"\n },\n {\n \"abbr\":\"VT\",\n \"name\":\"Holy See\"\n },\n {\n \"abbr\":\"HO\",\n \"name\":\"Honduras\"\n },\n {\n \"abbr\":\"HK\",\n \"name\":\"Hong Kong\"\n },\n {\n \"abbr\":\"HQ\",\n \"name\":\"Howland Island \"\n },\n {\n \"abbr\":\"HU\",\n \"name\":\"Hungary\"\n },\n {\n \"abbr\":\"IC\",\n \"name\":\"Iceland\"\n },\n {\n \"abbr\":\"IN\",\n \"name\":\"India\"\n },\n {\n \"abbr\":\"ID\",\n \"name\":\"Indonesia\"\n },\n {\n \"abbr\":\"IR\",\n \"name\":\"Iran\"\n },\n {\n \"abbr\":\"IZ\",\n \"name\":\"Iraq\"\n },\n {\n \"abbr\":\"EI\",\n \"name\":\"Ireland\"\n },\n {\n \"abbr\":\"IS\",\n \"name\":\"Israel\"\n },\n {\n \"abbr\":\"IT\",\n \"name\":\"Italy\"\n },\n {\n \"abbr\":\"JM\",\n \"name\":\"Jamaica\"\n },\n {\n \"abbr\":\"JN\",\n \"name\":\"Jan Mayen\"\n },\n {\n \"abbr\":\"JA\",\n \"name\":\"Japan\"\n },\n {\n \"abbr\":\"DQ\",\n \"name\":\"Jarvis Island\"\n },\n {\n \"abbr\":\"JE\",\n \"name\":\"Jersey\"\n },\n {\n \"abbr\":\"JQ\",\n \"name\":\"Johnston Atoll\"\n },\n {\n \"abbr\":\"JO\",\n \"name\":\"Jordan\"\n },\n {\n \"abbr\":\"KZ\",\n \"name\":\"Kazakhstan\"\n },\n {\n \"abbr\":\"KE\",\n \"name\":\"Kenya\"\n },\n {\n \"abbr\":\"KQ\",\n \"name\":\"Kingman Reef\"\n },\n {\n \"abbr\":\"KR\",\n \"name\":\"Kiribati\"\n },\n {\n \"abbr\":\"KN\",\n \"name\":\"Korea, North\"\n },\n {\n \"abbr\":\"KS\",\n \"name\":\"Korea, South\"\n },\n {\n \"abbr\":\"KV\",\n \"name\":\"Kosovo\"\n },\n {\n \"abbr\":\"KU\",\n \"name\":\"Kuwait\"\n },\n {\n \"abbr\":\"KG\",\n \"name\":\"Kyrgyzstan\"\n },\n {\n \"abbr\":\"LA\",\n \"name\":\"Laos\"\n },\n {\n \"abbr\":\"LG\",\n \"name\":\"Latvia\"\n },\n {\n \"abbr\":\"LE\",\n \"name\":\"Lebanon\"\n },\n {\n \"abbr\":\"LT\",\n \"name\":\"Lesotho\"\n },\n {\n \"abbr\":\"LI\",\n \"name\":\"Liberia\"\n },\n {\n \"abbr\":\"LY\",\n \"name\":\"Libya\"\n },\n {\n \"abbr\":\"LS\",\n \"name\":\"Liechtenstein\"\n },\n {\n \"abbr\":\"LH\",\n \"name\":\"Lithuania\"\n },\n {\n \"abbr\":\"LU\",\n \"name\":\"Luxembourg \"\n },\n {\n \"abbr\":\"MC\",\n \"name\":\"Macau\"\n },\n {\n \"abbr\":\"MK\",\n \"name\":\"Macedonia\"\n },\n {\n \"abbr\":\"MA\",\n \"name\":\"Madagascar\"\n },\n {\n \"abbr\":\"MI\",\n \"name\":\"Malawi\"\n },\n {\n \"abbr\":\"MY\",\n \"name\":\"Malaysia\"\n },\n {\n \"abbr\":\"MV\",\n \"name\":\"Maldives\"\n },\n {\n \"abbr\":\"ML\",\n \"name\":\"Mali\"\n },\n {\n \"abbr\":\"MT\",\n \"name\":\"Malta\"\n },\n {\n \"abbr\":\"IM\",\n \"name\":\"Man, Isle of\"\n },\n {\n \"abbr\":\"RM\",\n \"name\":\"Marshall Islands\"\n },\n {\n \"abbr\":\"MR\",\n \"name\":\"Mauritania\"\n },\n {\n \"abbr\":\"MP\",\n \"name\":\"Mauritius\"\n },\n {\n \"abbr\":\"MX\",\n \"name\":\"Mexico\"\n },\n {\n \"abbr\":\"MQ\",\n \"name\":\"Midway Islands\"\n },\n {\n \"abbr\":\"MD\",\n \"name\":\"Moldova\"\n },\n {\n \"abbr\":\"MN\",\n \"name\":\"Monaco\"\n },\n {\n \"abbr\":\"MG\",\n \"name\":\"Mongolia \"\n },\n {\n \"abbr\":\"MJ\",\n \"name\":\"Montenegro\"\n },\n {\n \"abbr\":\"MH\",\n \"name\":\"Montserrat\"\n },\n {\n \"abbr\":\"MO\",\n \"name\":\"Morocco\"\n },\n {\n \"abbr\":\"MZ\",\n \"name\":\"Mozambique\"\n },\n {\n \"abbr\":\"WA\",\n \"name\":\"Namibia\"\n },\n {\n \"abbr\":\"NR\",\n \"name\":\"Nauru\"\n },\n {\n \"abbr\":\"BQ\",\n \"name\":\"Navassa Island\"\n },\n {\n \"abbr\":\"NP\",\n \"name\":\"Nepal\"\n },\n {\n \"abbr\":\"NL\",\n \"name\":\"Netherlands\"\n },\n {\n \"abbr\":\"NC\",\n \"name\":\"New Caledonia\"\n },\n {\n \"abbr\":\"NZ\",\n \"name\":\"New Zealand\"\n },\n {\n \"abbr\":\"NU\",\n \"name\":\"Nicaragua\"\n },\n {\n \"abbr\":\"NG\",\n \"name\":\"Niger\"\n },\n {\n \"abbr\":\"NI\",\n \"name\":\"Nigeria\"\n },\n {\n \"abbr\":\"NE\",\n \"name\":\"Niue \"\n },\n {\n \"abbr\":\"NF\",\n \"name\":\"Norfolk Island\"\n },\n {\n \"abbr\":\"CQ\",\n \"name\":\"Northern Mariana Islands\"\n },\n {\n \"abbr\":\"NO\",\n \"name\":\"Norway\"\n },\n {\n \"abbr\":\"MU\",\n \"name\":\"Oman\"\n },\n {\n \"abbr\":\"PK\",\n \"name\":\"Pakistan\"\n },\n {\n \"abbr\":\"PS\",\n \"name\":\"Palau\"\n },\n {\n \"abbr\":\"LQ\",\n \"name\":\"Palmyra Atoll\"\n },\n {\n \"abbr\":\"PM\",\n \"name\":\"Panama \"\n },\n {\n \"abbr\":\"PP\",\n \"name\":\"Papua-New Guinea\"\n },\n {\n \"abbr\":\"PF\",\n \"name\":\"Paracel Islands\"\n },\n {\n \"abbr\":\"PA\",\n \"name\":\"Paraguay\"\n },\n {\n \"abbr\":\"PE\",\n \"name\":\"Peru\"\n },\n {\n \"abbr\":\"RP\",\n \"name\":\"Philippines\"\n },\n {\n \"abbr\":\"PC\",\n \"name\":\"Pitcairn Islands\"\n },\n {\n \"abbr\":\"PL\",\n \"name\":\"Poland\"\n },\n {\n \"abbr\":\"PO\",\n \"name\":\"Portugal \"\n },\n {\n \"abbr\":\"RQ\",\n \"name\":\"Puerto Rico\"\n },\n {\n \"abbr\":\"QA\",\n \"name\":\"Qatar\"\n },\n {\n \"abbr\":\"RO\",\n \"name\":\"Romania\"\n },\n {\n \"abbr\":\"RS\",\n \"name\":\"Russia\"\n },\n {\n \"abbr\":\"RW\",\n \"name\":\"Rwanda\"\n },\n {\n \"abbr\":\"TB\",\n \"name\":\"Saint Barthelemy\"\n },\n {\n \"abbr\":\"RN\",\n \"name\":\"Saint Martin\"\n },\n {\n \"abbr\":\"WS\",\n \"name\":\"Samoa\"\n },\n {\n \"abbr\":\"SM\",\n \"name\":\"San Marino\"\n },\n {\n \"abbr\":\"TP\",\n \"name\":\"Sao Tome and Principe\"\n },\n {\n \"abbr\":\"SA\",\n \"name\":\"Saudi Arabia\"\n },\n {\n \"abbr\":\"SG\",\n \"name\":\"Senegal\"\n },\n {\n \"abbr\":\"RI\",\n \"name\":\"Serbia\"\n },\n {\n \"abbr\":\"SE\",\n \"name\":\"Seychelles \"\n },\n {\n \"abbr\":\"SL\",\n \"name\":\"Sierra Leone\"\n },\n {\n \"abbr\":\"SN\",\n \"name\":\"Singapore\"\n },\n {\n \"abbr\":\"NN\",\n \"name\":\"Sint Maarten\"\n },\n {\n \"abbr\":\"LO\",\n \"name\":\"Slovakia\"\n },\n {\n \"abbr\":\"SI\",\n \"name\":\"Slovenia\"\n },\n {\n \"abbr\":\"BP\",\n \"name\":\"Solomon Islands\"\n },\n {\n \"abbr\":\"SO\",\n \"name\":\"Somalia\"\n },\n {\n \"abbr\":\"SF\",\n \"name\":\"South Africa\"\n },\n {\n \"abbr\":\"SX\",\n \"name\":\"South Georgia and The S Sandwich Islands\"\n },\n {\n \"abbr\":\"OD\",\n \"name\":\"South Sudan\"\n },\n {\n \"abbr\":\"SP\",\n \"name\":\"Spain\"\n },\n {\n \"abbr\":\"PG\",\n \"name\":\"Spratly Islands \"\n },\n {\n \"abbr\":\"CE\",\n \"name\":\"Sri Lanka\"\n },\n {\n \"abbr\":\"SH\",\n \"name\":\"St. Helena\"\n },\n {\n \"abbr\":\"SC\",\n \"name\":\"St. Kitts and Nevis\"\n },\n {\n \"abbr\":\"ST\",\n \"name\":\"St. Lucia Island\"\n },\n {\n \"abbr\":\"SB\",\n \"name\":\"St. Pierre and Miquelon\"\n },\n {\n \"abbr\":\"VC\",\n \"name\":\"St. Vincent and Grenadines\"\n },\n {\n \"abbr\":\"SU\",\n \"name\":\"Sudan\"\n },\n {\n \"abbr\":\"NS\",\n \"name\":\"Suriname\"\n },\n {\n \"abbr\":\"SV\",\n \"name\":\"Svalbard\"\n },\n {\n \"abbr\":\"WZ\",\n \"name\":\"Swaziland\"\n },\n {\n \"abbr\":\"SW\",\n \"name\":\"Sweden \"\n },\n {\n \"abbr\":\"SZ\",\n \"name\":\"Switzerland\"\n },\n {\n \"abbr\":\"SY\",\n \"name\":\"Syria\"\n },\n {\n \"abbr\":\"TW\",\n \"name\":\"Taiwan\"\n },\n {\n \"abbr\":\"TI\",\n \"name\":\"Tajikistan\"\n },\n {\n \"abbr\":\"TZ\",\n \"name\":\"Tanzania\"\n },\n {\n \"abbr\":\"TH\",\n \"name\":\"Thailand\"\n },\n {\n \"abbr\":\"TO\",\n \"name\":\"Togo\"\n },\n {\n \"abbr\":\"TL\",\n \"name\":\"Tokelau \"\n },\n {\n \"abbr\":\"TN\",\n \"name\":\"Tonga\"\n },\n {\n \"abbr\":\"TD\",\n \"name\":\"Trinidad and Tobago\"\n },\n {\n \"abbr\":\"TS\",\n \"name\":\"Tunisia\"\n },\n {\n \"abbr\":\"TU\",\n \"name\":\"Turkey\"\n },\n {\n \"abbr\":\"TX\",\n \"name\":\"Turkmenistan\"\n },\n {\n \"abbr\":\"TK\",\n \"name\":\"Turks and Caicos Islands\"\n },\n {\n \"abbr\":\"TV\",\n \"name\":\"Tuvalu\"\n },\n {\n \"abbr\":\"UG\",\n \"name\":\"Uganda\"\n },\n {\n \"abbr\":\"UP\",\n \"name\":\"Ukraine\"\n },\n {\n \"abbr\":\"AE\",\n \"name\":\"United Arab Emirates\"\n },\n {\n \"abbr\":\"UK\",\n \"name\":\"United Kingdom\"\n },\n {\n \"abbr\":\"UY\",\n \"name\":\"Uruguay\"\n },\n {\n \"abbr\":\"UZ\",\n \"name\":\"Uzbekistan\"\n },\n {\n \"abbr\":\"NH\",\n \"name\":\"Vanuatu\"\n },\n {\n \"abbr\":\"VE\",\n \"name\":\"Venezuela\"\n },\n {\n \"abbr\":\"VM\",\n \"name\":\"Vietnam\"\n },\n {\n \"abbr\":\"VQ\",\n \"name\":\"Virgin Islands\"\n },\n {\n \"abbr\":\"WQ\",\n \"name\":\"Wake Island\"\n },\n {\n \"abbr\":\"WF\",\n \"name\":\"Wallis and Futuna\"\n },\n {\n \"abbr\":\"WI\",\n \"name\":\"Western Sahara\"\n },\n {\n \"abbr\":\"YM\",\n \"name\":\"Yemen (Aden)\"\n },\n {\n \"abbr\":\"ZA\",\n \"name\":\"Zambia\"\n },\n {\n \"abbr\":\"ZI\",\n \"name\":\"Zimbabwe\"\n },\n {\n \"abbr\":\"OC\",\n \"name\":\"Other Countries\"\n }\n ];\n return countryChoices;\n}",
"getCountries() {\n for (let i = 2; i < this.originData.length; i++) {\n this.countries.push(this.originData[i][1]);\n }\n }",
"function initCountry() {\n //reference points for countries\n var countriesLL = [\n [\"Canada\", 65, -95 ],\n [\"Mexico\", 19, -102.4],\n [\"China\", 35, 103],\n [\"Japan\", 35, 136],\n [\"UK\", 54, -2],\n [\"United Kingdom\", 54, -2],\n [\"Germany\", 51.6, 10],\n [\"Brazil\", -10.7, -53],\n [\"Netherlands\", 52.2, 4.5],\n [\"HK\", 22.3, 114.2],\n [\"Korea\", 37.6, 127],\n [\"Saudi\", 24, 45],\n [\"Saudi Arabia\", 24, 45],\n [\"France\", 47, 2],\n [\"India\", 21, 78],\n [\"US\", 38.9, -90.01],\n [\"United States\", 38.9, -90.01],\n [\"Korea, Rep.\", 37.6, 127],\n\n [\"South Asia\", 21, 78],\n [\"Sub-Saharan Africa\", -30, 25],\n [\"Russian Federation\", 60, 90],\n [\"North America\", 38.9, -90.01],\n\n [\"Hong Kong, China\", 35, 103],\n\n [\"Canada\", 65, -95 ],\n [\"Mexico\", 19, -102.4],\n [\"China\", 35, 103],\n [\"Japan\", 35, 136],\n [\"UK\", 54, -2],\n [\"Germany\", 51.6, 10],\n [\"Brazil\", -10.7, -53],\n [\"Netherlands\", 52.2, 4.5],\n [\"HK\", 22.3, 114.2],\n [\"Korea\", 37.6, 127],\n [\"Saudi\", 24, 45],\n [\"France\", 47, 2],\n [\"India\", 21, 78],\n [\"US\", 38.9, -90.01],\n [\"Russia\", 60, 90],\n [\"Vietnam\", 21, 105.9],\n [\"Australia\", -35.3, 149.1],\n [\"Malaysia\", 3.13, 101.8],\n [\"Switzerland\", 46.8, 8.4],\n [\"Thailand\", 13.75, 100.49],\n [\"Singapore\", 1.3, 103.8],\n [\"Thailand\", 13.8, 100.5],\n [\"Indonesia\", 6.18, 106.8],\n [\"Qatar\", 25.3, 51.5]\n \n ];\n \n countries = {};\n \n for (var i = 0; i < countriesLL.length; i++) {\n var key = countriesLL[i][0];\n var lat = countriesLL[i][1];\n var lon = countriesLL[i][2];\n //countryLL[key] = [lat, lon];\n var data = calculatePoint(lat, lon);\n countries[key] = data;\n };\n \n return countries;\n}",
"getCountries() {\n for (let i = 2; i < this.originData.length; i++) {\n this.countries.push(this.originData[i][1]);\n }\n }",
"getPerCountryData(ordersWithCountries) {\n return ordersWithCountries.reduce((accumulator, currentObject) => {\n const countryCode = currentObject['country_code'];\n\n if (!accumulator.countries) accumulator.countries = [];\n\n if (!accumulator.countries.find(item => item.country_code === countryCode)) {\n const countryObjectTemplate = {\n \"country\": currentObject['country'],\n \"country_code\": countryCode,\n \"sales\": 0,\n \"sales_percentage\": 0,\n \"orders\": 0,\n \"average_order_value\": 0\n };\n accumulator.countries.push(countryObjectTemplate)\n }\n\n const countryIndexInAccumulator = accumulator.countries.findIndex(item => item.country_code === countryCode);\n accumulator.countries[countryIndexInAccumulator].sales += currentObject.total_sales;\n accumulator.countries[countryIndexInAccumulator].orders++;\n\n return accumulator;\n }, {});\n }",
"function loadCountry(country) {\n var ret = [];\n\n for (var key in countryIndices[country]) {\n if(!isNaN(parseInt(key))) {\n var val = parseFloat(countryIndices[country][key]);\n if(isNaN(val)) {\n val = 0;\n }\n ret.push({'year':parseInt(key),'value':val});\n }\n }\n\n return ret;\n }",
"function findCountryData(country) {\n var countryData = [];\n\n for (let i = 2; i < country.cells.length; i++) {\n var cellData = country.cells[i].innerHTML;\n countryData.push(parseFloat(cellData));\n }\n return countryData;\n}",
"distance(country) {\n return this.variables.map((variable, index) => country.variables[index] - variable)\n }",
"function availableCountry() {\n let countries = [];\n Object.values(tdata).forEach(value => {\n let country = value.country.toUpperCase();\n if(countries.indexOf(country) !== -1) {\n\n }\n else {\n countries.push(country);\n }\n });\n return countries;\n}",
"function totalAsianPopulation(){\n let asianCountries = getAsianCountries();\n return asianCountries.reduce((acc, country)=>{\n return acc + country.population;\n }, 0)\n}",
"getGlobalDataperCountry(country) {\n return this.http.get(this.globalDataUrl, { responseType: 'text' }).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])(result => {\n var jsonresult = JSON.parse(result);\n this.updateCovidDataGlobalPerCountry(jsonresult, country);\n }));\n }",
"function totalPopulation(){\n return data.reduce((acc, country)=>{\n return acc + country.population;\n }, 0)\n}",
"countryCollectsVat() {\n return this.collectsVat(this.form.country);\n }",
"function calculate_colors(country)\n {\n index_country = all_countries.indexOf(country);\n color_1 = all_colors[index_country][2];\n color_2 = all_colors[index_country][3];\n return [color_1, color_2];\n }",
"static async getCountries() {\n let countries = [];\n try {\n countries = await salaryData.distinct(\"Country\");\n return countries;\n } catch (e) {\n console.error(`Unable to get countries, ${e}`);\n return countries;\n }\n }",
"function getLifeExpOfSelectedCountry(filtered_dataset){\r\n\t\t\t\tvar life_exp = ''\r\n\t\t\t\tfiltered_dataset.map((data,i)=>{\r\n\t\t\t\t\tif(data.Country == currentCountry.Country){\r\n\t\t\t\t\t\tlife_exp = Math.round(data.LifeExp,2)\r\n\t\t\t\t\t\treturn\r\n\t\t\t\t\t}\r\n\t\t\t\t})\r\n\t\t\t\treturn life_exp\r\n\t\t\t}",
"function getTotalTaxes(country){\n\n return this.tax * this.middleSalary * this.vacancies;\n}",
"function getCountries() {\n weatherService.getCountryList().then(resolver, rejector);\n //if success\n function resolver(response) {\n vm.countries = response.data;\n geteCountryForecast();\n }\n\n //if reject\n function rejector(response) {\n console.log(response);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
adapted from Sucrase ( Polyfill for the nullish coalescing operator (`??`), when used in situations where at least one of the values is the result of an async operation. Note that the RHS is wrapped in a function so that if it's a computed value, that evaluation won't happen unless the LHS evaluates to a nullish value, to mimic the operator's shortcircuiting behavior. Adapted from Sucrase ( | async function _asyncNullishCoalesce(lhs, rhsFn) {
return _nullishCoalesce._nullishCoalesce(lhs, rhsFn);
} | [
"function orElseAsyncForMaybe(input, recoverer) {\n if (Maybe_1.isNotNullAndUndefined(input)) {\n return Promise.resolve(input);\n }\n var fallback = recoverer();\n // If this is async function, this always return Promise, but not.\n // We should check to clarify the error case if user call this function from plain js\n // and they mistake to use this.\n assert_1.assertIsPromise(fallback, ErrorMessage_1.ERR_MSG_RECOVERER_MUST_RETURN_PROMISE);\n return fallback;\n}",
"async function _asyncOptionalChain(ops) {\n let lastAccessLHS = undefined;\n let value = ops[0];\n let i = 1;\n while (i < ops.length) {\n const op = ops[i] ;\n const fn = ops[i + 1] ;\n i += 2;\n // by checking for loose equality to `null`, we catch both `null` and `undefined`\n if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) {\n // really we're meaning to return `undefined` as an actual value here, but it saves bytes not to write it\n return;\n }\n if (op === 'access' || op === 'optionalAccess') {\n lastAccessLHS = value;\n value = await fn(value);\n } else if (op === 'call' || op === 'optionalCall') {\n value = await fn((...args) => (value ).call(lastAccessLHS, ...args));\n lastAccessLHS = undefined;\n }\n }\n return value;\n}",
"function _nullishCoalesce(lhs, rhsFn) {\n // by checking for loose equality to `null`, we catch both `null` and `undefined`\n return lhs != null ? lhs : rhsFn();\n}",
"function _nullishCoalesce(lhs, rhsFn) {\n\t // by checking for loose equality to `null`, we catch both `null` and `undefined`\n\t return lhs != null ? lhs : rhsFn();\n\t}",
"shortcircuit () {\n return null\n }",
"function orElseForMaybe(input, recoverer) {\n if (input !== undefined && input !== null) {\n return input;\n }\n var fallback = recoverer();\n return fallback;\n}",
"unwrapOrElse(fn) {\n if (this.isOk()) {\n return this.value\n }\n return fn(this.error)\n }",
"function coalesce( ...args )\n{\n for( var i = 0; i < args.length; i++ )\n {\n var arg = args[i];\n\n if( !is_null_or_undef( arg ) )\n {\n return arg;\n }\n }\n}",
"coalesce(default_value, value) {\n return value === undefined ? default_value : value;\n }",
"function orForNullable(a, b) {\n if (a !== null) {\n return a;\n }\n return b;\n}",
"function fallback(...args) {\n for (let i = 0; i < args.length; i += 1) {\n if (args[i] != null) { return args[i] }\n }\n return null\n}",
"function andThenAsyncForNullable(input, transformer) {\n if (Nullable_1.isNull(input)) {\n return Promise.resolve(input);\n }\n var result = transformer(input);\n // If this is async function, this always return Promise, but not.\n // We should check to clarify the error case if user call this function from plain js\n // and they mistake to use this.\n assert_1.assertIsPromise(result, ErrorMessage_1.ERR_MSG_TRANSFORMER_MUST_RETURN_PROMISE);\n return result;\n}",
"function strict_or(x, z) { return x !== undefined ? x : z }",
"function or_undefined(val, alternate) {\n return typeof val == 'undefined' ? alternate : val\n}",
"getOrElse(fallback) {\n if (!this._isEmpty)\n return this.value;\n else\n return fallback;\n }",
"function withDefault(fallback) {\n return value => {\n if (value === undefined)\n return fallback;\n return value;\n };\n}",
"function unwrapOrElseAsyncFromResult(input, recoverer) {\n if (Result_1.isOk(input)) {\n var value = unwrap_1.unwrapFromResult(input);\n return Promise.resolve(value);\n }\n var error = unwrap_1.unwrapErrFromResult(input);\n var defaultValue = recoverer(error);\n // If this is async function, this always return Promise, but not.\n // We should check to clarify the error case if user call this function from plain js\n // and they mistake to use this.\n assert_1.assertIsPromise(defaultValue, ErrorMessage_1.ERR_MSG_RECOVERER_MUST_RETURN_PROMISE);\n return defaultValue;\n}",
"function resultOrZero(x, f = (v) => v, zero=0) {\n\tif (!x) {\n\t\treturn zero;\n\t}\n\n\treturn f(x);\n}",
"async fetch_or_call(thing) {\n\t\tif (thing.constructor !== String) {\n\t\t\tvar ret = await thing();\n\t\t\treturn ret;\n\t\t}\n\t\tvar ret = this.url_cache[thing];\n\t\tif (!ret) {\n\t\t\tret = this.fetch_stuff(thing);\n\t\t\tret = ret.then(json => JSON.parse(json));\n\t\t\tthis.url_cache[thing] = ret;\n\t\t}\n\t\treturn ret;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an EightBit with the current value, e.g. EightBit(255). | toEightBit() {
const value = typeof this.value === 'string' ? parseInt(this.value, 16) : null;
return new EightBit(value);
} | [
"toEightBit() {\n const value = typeof this.value === \"string\" ? parseInt(this.value, 16) : null;\n return new EightBit(value);\n }",
"toEightBit() {\n const t = typeof this.value == \"string\" ? parseInt(this.value, 16) : null;\n return new Os(t);\n }",
"function highnibble(x)\n{\n return (x & 0xf0) >> 4;\n}",
"byte() {\n return this.int8();\n }",
"function u8(val) {\n return val & 0xFF;\n}",
"_bit() {\n const value = this._memoryValue();\n const result = this._accumulator & value;\n\n this._status = setOrReset(this._status, value, this._OVERFLOW);\n this._status = setOrReset(this._status, value, this._NEGATIVE);\n this._setOrResetZero(result);\n }",
"function getValueBit(val) {\n const prop = Object.keys(ValuesBit).find(prop => {\n return prop === val;\n });\n return ValuesBit[prop];\n}",
"getHighBitsUnsigned() {\n return this.high >>> 0;\n }",
"function Bit() {\n\t\t// TODO: Decide whether to keep this class...?\n\t}",
"function isEight(num) {\n if (num === 8) {\n return true;\n }\n}",
"function getBit() {\n\t \treturn _sensor.bit;\n\t }",
"function getBit(bit, value) {\n return (value >> bit) & 0b1;\n}",
"function getBitIndex(bitIndex) {\n return bitIndex % 8;\n}",
"function BIT() {\n return this.choice(this.stringf('0'), this.stringf('1'));\n}",
"asSByte() {\n if ((value & 0x80) == 0x80) {\n return ((~value + 1) & 0xFF);\n } else {\n return value;\n }\n }",
"function getBit (id, b) { return (id[~~(b / 8)] & (1 << (7 - (b % 8)))) === 0 ? 0 : 1 }",
"function uint8(name, { transform = value => value } = {}) {\n\treturn uint(name, { size: 1, transform });\n}",
"_byte(val, index) {\n return ((val >> (8 * index)) & 0xFF);\n }",
"function tinf_getbit(d){/* check if tag is empty */if(!d.bitcount--){/* load next tag */d.tag=d.source[d.sourceIndex++];d.bitcount=7;}/* shift bit out of tag */var bit=d.tag&1;d.tag>>>=1;return bit;}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PART 5 Define a function with the identifier "splitToArray" Parameters: "word" (string) Definition: Returns the given parameter string split by individual character into an array Return type: (string array) Example: "MAD" > ["M", "A", "D"] | function splitToArray(word) {
let wordCharacters = [];
for (let i = 0; i < word.length; i++) {
wordCharacters[i] = word[i];
}
return wordCharacters;
} | [
"function sentenceToArray(string){\n return string.split(\" \"); \n}",
"function arrayNow(str) {\n ans = str.split(\" \");\n return ans;\n}",
"function string_to_array(x){\n return x.split(\" \");\n}",
"function arrayWord(word) {\n var arrayWord = [];\n for (i = 0; i < word.length; i++) {\n arrayWord.push(word[i]);\n }\n return arrayWord;\n }",
"function splitWordIntoArray() {\n\tfor (var i = 0, j = 0; i < wordChoice.length; i++) {\n\t\tarrayLetters[j] = wordChoice.charAt(i);\n\t\tj++\n\t\tif (wordChoice.charAt(i) != \" \") {\n\t\t\tarrayLetters[j] = false;\n\t\t} else {\n\t\t\tarrayLetters[j] = true;\n\t\t}\n\t\tj++\n\t}\n}",
"function split_char(string){\n for(i=0;i<string.length;i++){\n arr[i]=string[i]\n }\n console.log(arr)\n}",
"create_alphabet_array() {\n var alphabet = \"abcdefghijklmnopqrstuvwxyz\";\n var alpha_array = alphabet.split(\"\");\n return alpha_array\n }",
"function arrOfWords(str){\n var arr = str.split(\" \");\n return arr;\n}",
"function makeLetterArray(wordArray) {\n letterArray = wordArray.split(\"\");\n}",
"words (inputString) {\n let wordArray = inputString.split(' ');\n return wordArray;\n }",
"function wordIntoArray() {\n for (var i = 0; i < word.length; i++) {\n wordArray[i] = word.charAt(i);\n }\n}",
"function toSplit(phrase){\n\tvar cut = phrase.split(\" \");\n\treturn cut;\n}",
"function textToArray(text) {\n var textSplit = text.split(\" \");\n console.log(textSplit);\n return textSplit;\n}",
"splitWord() {\n let wordArray = this.string.split(\"\");\n var myArray = [];\n for (var i = 0; i < wordArray.length; i += 4) {\n myArray.push(wordArray.slice(i, i + 4));\n }\n // console.log(myArray)\n return this.eachWordDecimal(myArray);\n // return myArray;\n }",
"function wordToCharArray (word) {\n let charArray = [];\n for (var i = 0; i < word.length; i++) {\n charArray.push (word[i]);\n }\n return charArray;\n}",
"function convertStringOfWordsToArrayOfStrings (secretMessage){\n\treturn secretMessage.split(\" \");\n}",
"function splitInput(words) {\n return words.split(\" \");\n}",
"function buildAlphabetArray() {\n var alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n var alphabetArray = alphabet.split('');\n \n return alphabetArray;\n}",
"function split(string, delimiter){\n // Words by splitting a string with a predetermined delimiter\n var res = [];\n while(string.indexOf(delimiter) != -1){\n // Pushes first word to array, then slices the current word out of array\n var position = string.indexOf(delimiter);\n res.push(string.slice(0, position));\n string = string.slice(position + delimiter.length, string.length);\n }\n res.push(string); // Pushes last word to array. \n return res;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The spec says "An editing host is a node that is either an Element with a contenteditable attribute set to the true state, or a Document whose designMode is enabled." Because Safari returns "true" for the contentEditable property of an element that actually inherits its editability from its parent, we use a different definition: "An editing host is a node that is either an Element whose isContentEditable property returns true but whose parent node is not an element or whose isContentEditable property returns false, or a Document whose designMode is enabled." | function isEditingHost(node) {
return node
&& ((node.nodeType == 9 && node.designMode == "on")
|| (isEditableElement(node) && !isEditableElement(node.parentNode)));
} | [
"function isEditingHost(node) {\n return node\n && isHtmlElement(node)\n && (node.contentEditable == \"true\"\n || (node.parentNode\n && node.parentNode.nodeType == Node.DOCUMENT_NODE\n && node.parentNode.designMode == \"on\"));\n}",
"function isEditingHost(node) {\n\t\treturn node && node.nodeType == $_.Node.ELEMENT_NODE && (node.contentEditable == \"true\" || (node.parentNode && node.parentNode.nodeType == $_.Node.DOCUMENT_NODE && node.parentNode.designMode == \"on\"));\n\t}",
"function isEditingHost(node) {\n var parent;\n return node && node.nodeType == 1 &&\n (( (parent = node.parentNode) && parent.nodeType == 9 && parent.designMode == \"on\") ||\n (isEditableElement(node) && !isEditableElement(node.parentNode)));\n }",
"function isEditable(node) {\n\t\t// This is slightly a lie, because we're excluding non-HTML elements with\n\t\t// contentEditable attributes.\n\t\treturn node && !isEditingHost(node) && (node.nodeType != $_.Node.ELEMENT_NODE || node.contentEditable != \"false\" || jQuery(node).hasClass('aloha-table-wrapper')) && (isEditingHost(node.parentNode) || isEditable(node.parentNode));\n\t}",
"function isInEditable(node) {\n while (node.nodeName != \"HTML\") {\n if (node.getAttribute && node.getAttribute(\"contenteditable\")) {\n return true;\n }\n node = node.parentNode;\n }\n return false;\n}",
"function supportContentEditable() {\n var div = document.createElement('div');\n return (typeof(div.contentEditable) != 'undefined' && !/(iPhone|iPod|iPad|Android|Mobi)/i.test(navigator.userAgent));\n }",
"function isEditable(node) {\n return node\n && !isEditingHost(node)\n && (node.nodeType != Node.ELEMENT_NODE || node.contentEditable != \"false\")\n && (isEditingHost(node.parentNode) || isEditable(node.parentNode))\n && (isHtmlElement(node)\n || (node.nodeType == Node.ELEMENT_NODE && node.namespaceURI == \"http://www.w3.org/2000/svg\" && node.localName == \"svg\")\n || (node.nodeType == Node.ELEMENT_NODE && node.namespaceURI == \"http://www.w3.org/1998/Math/MathML\" && node.localName == \"math\")\n || (node.nodeType != Node.ELEMENT_NODE && isHtmlElement(node.parentNode)));\n}",
"isActiveElementEditable() {\n return document.activeElement && (document.activeElement.isContentEditable\n || ['INPUT', 'TEXTAREA', 'SELECT'].indexOf(document.activeElement.tagName) !== -1);\n }",
"function isContentEditableDiv (element) {\n return (element.nodeName === 'DIV' && element.contentEditable === 'true')\n }",
"function isInActiveContentEditable(node) {\n while (node) {\n if ( node.getAttribute && \n node.getAttribute(\"contenteditable\") && \n node.getAttribute(\"contenteditable\").toUpperCase() === \"TRUE\" ) {\n return true;\n }\n node = node.parentNode;\n }\n return false;\n}",
"function ed_isEditable(node) {\n return ed_kind(node) !== null;\n }",
"function getContentEditable(node) {\n const element = getElement(node);\n return element && (element.closest('[contenteditable=\"\"]') || element.closest('[contenteditable=\"true\"]'));\n}",
"getEditable() {\n return this.getAttribute('contenteditable');\n }",
"function isEditable(element) {\n return element && !element.disabled &&\n (element.localName === 'textarea' || element.localName === 'select' ||\n element.isContentEditable ||\n element.matches('div.CodeMirror-scroll,div.ace_content') ||\n (element.localName === 'input' &&\n /^(?!button|checkbox|file|hidden|image|radio|reset|submit)/i.test(\n element.type)));\n}",
"function isEditable(target) {\n\tif (target.getAttribute(\"contentEditable\") == \"true\")\n\t\treturn true;\n\tvar focusableInputs = [\"input\", \"textarea\", \"select\", \"button\"];\n\treturn focusableInputs.indexOf(target.tagName.toLowerCase()) >= 0;\n}",
"function Fev_IsElementEditable(objElement)\n{\n if (objElement && (objElement != null))\n {\n if (objElement.readOnly)\n {\n return false;\n }\n if ((!objElement.isContentEditable) && (typeof(objElement.isContentEditable) != 'undefined'))\n {\n return false;\n }\n return true;\n }\n return false;\n}",
"get isEditable() {\n return this.view && this.view.editable;\n }",
"function isEditable(node, options) {\n return node &&\n ((options && !options.applyToEditableOnly)\n || (((isEditableElement(node) || (node.nodeType != 1 && isEditableElement(node.parentNode)))\n && !isEditingHost(node) ) ));\n }",
"get isEditable() {\r\n // since plugins are applied after creating the view\r\n // `editable` is always `true` for one tick.\r\n // that’s why we also have to check for `options.editable`\r\n return this.options.editable\r\n && this.view\r\n && this.view.editable;\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
open new page and calls parseTree for provided path and href | async function callParser({ href, name, currPath }) {
const newPage = await browser.newPage();
await parseTree({
url: href,
currPath: path.join(currPath, name),
page: newPage,
});
await newPage.close();
} | [
"async function parseTree({ url, currPath, page }) {\n console.log(`creating/recreating path: ${currPath}`);\n await page.goto(url);\n resolveFolder(currPath);\n await page.waitForSelector(\".Box-row\");\n const itemRows = await page.$$(\".Box-row\");\n const folders = [];\n // potential parallel spot\n for (let i = 0; i < itemRows.length; i++) {\n const currRow = itemRows[i];\n const toSkip = await page.evaluate((ele) => {\n return ele.innerText === \". .\";\n }, currRow);\n if (toSkip) {\n continue;\n }\n const { isFolder, name, href } = await getRowData({ page, currRow });\n if (isFolder) {\n folders.push({ name, href });\n } else {\n toDownload.push({ name, href, currPath });\n }\n }\n const folderVisiter_p = [];\n for (let i = 0; i < folders.length; i++) {\n const { href, name } = folders[i];\n const parseFolder_p = callParser({ href, name, currPath });\n folderVisiter_p.push(parseFolder_p);\n }\n await Promise.all(folderVisiter_p);\n}",
"function loadPage(href) {\n\t// open a link to the href and send request to load it\n\tvar xmlhttp = new XMLHttpRequest();\n\tvar trimmedHref = href.replace(new RegExp(\" \", 'g'), \"\");\n\txmlhttp.open('GET', trimmedHref + '.html', true);\n\txmlhttp.send();\n\t\n\tprojInfo.setAttribute('data-oldContents', projInfo.innerHTML);\n\tpageHeader.setAttribute('data-oldContents', pageHeader.innerText);\n\tpageHeader.innerText += \" > \" + href.replace(/\\w\\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});\n\n\t// return the response\n\txmlhttp.addEventListener('load', function() {\n\t\tprojInfo.innerHTML = \"<div>\" + xmlhttp.responseText + \"</div>\";\n\t\tvar projMediaPanel = document.querySelector(\".projMedia\");\n\t\tprojMediaPanel.innerHTML = \"<p id='escape'>Return to project listing</p>\" + projMediaPanel.innerHTML;\n\t\tdocument.querySelector('#escape').addEventListener(\"click\", closeProjectViewer);\n\t\t\n\t\tGalleria.loadTheme('galleria/themes/classic/galleria.classic.min.js');\n\t\tdocument.querySelector('.galleria').style.height = document.querySelector('.galleria').clientWidth + \"px\";\n\t\tGalleria.run('.galleria');\n\t});\n}",
"function loadPage(path){\r\n return fetchPath(path).then(parseHtml)\r\n}",
"function page_new(parent_page, new_page) {\n new_page['__utf8_check__'] = decodeURIComponent('%C3%96');\n $GLOBAL.request.post(\"page/\" + parent_page.id, {\n data: $GLOBAL.json.stringify(new_page),\n timeout: 2000,\n headers: {\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\"\n },\n handleAs: \"json\"\n }).then(function(data) {\n console.log(\"page created.\");\n console.log(data);\n var new_id = $GLOBAL.pageTree.jstree(\"create_node\", parent_page.id, data, \"last\");\n $GLOBAL.pageTree.jstree(\"deselect_all\", true);\n $GLOBAL.pageTree.jstree(\"select_node\", new_id);\n });\n}",
"function refreshOpenPage() {\n updatePageChildNodes(current_page);\n updatePageParentNodes(current_page);\n\n if (!(Object.keys(editor.openStories).includes(current_story))) {\n current_page = null;\n $('#page-body').empty();\n page_pane_child = document.createElement('p');\n page_pane_child.setAttribute('id', 'page-pane-child')\n $('#page-body')[0].appendChild(page_pane_child);\n return;\n } else if (!(Object.keys(editor.getStoryState(current_story)['page_nodes']).includes(current_page))) {\n $('#page-body').empty();\n page_pane_child = document.createElement('p');\n page_pane_child.setAttribute('id', 'page-pane-child')\n $('#page-body')[0].appendChild(page_pane_child);\n return;\n }\n\n $('#page-body').empty();\n\n page_data = editor.getPageData(current_story, current_page);\n body_text = page_data['page_body_text'];\n child_dic = page_data['page_children'];\n\n page_pane_child = document.createElement('p');\n page_pane_child.innerHTML = body_text;\n page_pane_child.setAttribute('id', 'page-pane-child')\n $('#page-body')[0].appendChild(page_pane_child);\n\n Object.values(child_dic).forEach(child => {\n child_link = document.createElement('p');\n child_link.innerHTML = child['link_text'];\n child_link.setAttribute('class', 'link_text');\n $('#page-body')[0].appendChild(child_link);\n });\n \n}",
"function treeOpenPath(path) {\n if (path.length) {\n var thisseg = unescape(path.shift());\n $(\"#__tree_div\").jstree(\"open_node\", $(\"#__tree_div a:containsexactly('\\xA0\" + thisseg + \"') :parent\"), \n function () { treeOpenPath(path); });\n }\n}",
"async newPage() {}",
"function loadPage(path) {\n\tloadPageDetails(path, null, true, false)\n}",
"function su_openPageForNode(nodeID, nodeType)\n{\n\t//console.log(\"Opening page for \" + nodeID + \" of type \" + nodeType);\n\t\n\t// by default everyone gets nodeinfo.html\n\twindow.open('nodeinfo.html?id='+nodeID);\n}",
"function goto(path) {\n\n\t\t\tif (path.length) {\n\t\t\t\tvar rendered = '';\n\n\t\t\t\t// if hash has search in it\n\n\t\t\t\tif (filemanager.hasClass('searching')) {\n\t\t\t\t\trender(searchData(response, path));\n\t\t\t\t}\n\t\t\t\t// if hash is some path\n\t\t\t\telse {\n\t\t\t\t\trendered = searchByPath(path);\n\t\t\t\t\tcurrentPath = path;\n\t\t\t\t\tbreadcrumbsUrls = generateBreadcrumbs(path);\n\t\t\t\t\trender(rendered);\n\t\t\t\t}\n\t\t\t}\n\t\t}",
"_openTillSelectedPage(selectedRoute) {\n\n var navList = this.navList;\n\n var path = pathToLeafNode(navList, selectedRoute);\n\n path.forEach(function (node) {\n node.opened = true;\n });\n\n this.set('navList', []);\n this.async(function () {\n this.set('navList', navList);\n });\n }",
"function create_new_page( path, params, k, err ) {\n\n if (!$.perc_fakes.page_service.create_page) {\n $.perc_pathmanager.get_folder_path(path, function(fp){\n createPage(fp, params, k, err);\n }, err);\n }\n else {\n if (false)\n err(I18N.message(\"perc.ui.page.manager@Create New Page Error\"));\n else\n k('16777215-101-733');\n }\n }",
"async function main() {\n browser = await puppeteer.launch({\n headless: true,\n // headless: false,\n });\n const [page] = await browser.pages();\n const splitLink = url.split(\"/\");\n const userInfo = {\n username: splitLink[3],\n repoTitle: splitLink[4],\n branch: splitLink[6] || \"master\",\n };\n console.log(\n \"---------------------------- creating folder's tree structure & parsing links ----------------------------\"\n );\n await parseTree({ url, page, currPath: destPath });\n await browser.close();\n console.log(\n \"---------------------------- downloading files ----------------------------\"\n );\n // browser = await puppeteer.launch({\n // headless: false,\n // defaultViewport: false,\n // });\n await downloaderCaller(userInfo);\n // await browser.close();\n}",
"function treeAdminArea_load_page(url, cb) {\n var unhandle = $GLOBAL.on($GLOBAL.registry.byId('leftCol'), \"Unload\", function(evt) {\n unhandle.remove();\n if(typeof window[\"ontree_unload\"] != \"undefined\") {\n ontree_unload();\n }\n });\n\n var handle = $GLOBAL.on($GLOBAL.registry.byId('leftCol'), \"Load\", function(evt) {\n handle.remove();\n cb();\n });\n\n $GLOBAL.registry.byId('leftCol').set('href', url);\n}",
"function bindBrowseTreeClick() {\n $('.js-browse__item-title').click(function () {\n var $this = $(this),\n $thisItem = $this.closest('.js-browse__item'),\n uri = $thisItem.attr('data-url'),\n baseURL = Florence.babbageBaseUrl,\n isDataVis = localStorage.getItem('userType') == 'DATA_VISUALISATION';\n\n if (uri) {\n var newURL = baseURL + uri;\n\n treeNodeSelect(newURL);\n\n // Data vis browsing doesn't update iframe\n if (isDataVis) {\n return false\n }\n\n // Update iframe location which will send change event for iframe to update too\n document.getElementById('iframe').contentWindow.location.href = newURL;\n $('.browser-location').val(newURL);\n\n } else {\n\n // Set all directories above it in the tree to be active when a directory clicked\n selectParentDirectories($this);\n }\n\n // Open active branches in browse tree\n openBrowseBranch($this);\n });\n}",
"function NavigateTo(id) {\n try {\n // var node_id=-1;\n var node_id = \"00000000-0000-0000-0000-000000000000\";\n //try to find node in the tree\n\n if (nodes_a[id] != null)\n node_id = nodes_a[id]._id;\n\n //if it exist open it and all it's parent nodes\n if (node_id != \"00000000-0000-0000-0000-000000000000\") {\n if (node_id != 0) {\n var par = findParentById(node_id);\n\n var nodesArray = [];\n var array_length = 1;\n nodesArray[0] = par;\n\n //add parent nodes to array\n while (par != nodes[0]) {\n par = nodes_a[par.pid];\n nodesArray[array_length] = par;\n array_length++;\n }\n\n //do o function for all items from array\n for (var i = array_length - 1; i >= 0; i--)\n if (nodesArray[i]._io == false)\n o(getNodeId(nodesArray[i]));\n }\n inProgress = false;\n s(node_id);\n var eElem = document.getElementById('node' + node_id);\n eElem.scrollIntoView(true);\n }\n\n //if not, open path.xml and iterate throgh parents of current child\n else {\n var xml = new ActiveXObject(\"MSXML2.DOMDocument.3.0\");\n xml.validateOnParse = false;\n xml.async = false;\n\n var path = mainPath + id + \"/path.xml\"\n xml.load(path);\n if (xml.parseError.errorcode == null) {\n var root = xml.documentElement;\n var oNodeList = root.childNodes;\n var nodesArray = [];\n var array_length = 0;\n\n for (var i = 1; i < oNodeList.length; i++) {\n //\t parent_node_id = -1;\n parent_node_id = \"00000000-0000-0000-0000-000000000000\";\n var child = oNodeList[i].getAttribute(\"id\");\n if (nodes_a[child])\n parent_node_id = nodes_a[child].id;\n nodesArray[array_length] = child;\n array_length++;\n if (parent_node_id != \"00000000-0000-0000-0000-000000000000\")\n break;\n }\n // when parent in the tree is found open all parent's children until we reach necessary node\n for (var i = array_length - 1; i >= 0; i--) {\n o(nodes_a[nodesArray[i]]._id);\n }\n var open_id = nodes_a[id]._id;\n inProgress = false;\n s(open_id);\n var eElem = document.getElementById('node' + open_id);\n eElem.scrollIntoView(true);\n }\n }\n }\n catch (e) {\n inProgress = false;\n alert(\"SSMA: Object is not accessible.\");\n }\n}",
"function openTree(element, path) {\n // Cache key for cached json data\n var cacheKey = options.cacheStore ? options.cacheStore + ':' + path : null;\n\n // Store json in cache\n function store(data) {\n if (cacheKey) {\n $.storage.set(cacheKey, data);\n }\n }\n\n // Data loaded via ajax (callback) or from the cache\n function dataLoaded(data) {\n var ul = $('<ul/>');\n $.each(data, function(i, child) { ul.append(createChild(child)); });\n if (path == options.root) {\n element.empty();\n }\n element.children('ul').remove();\n element.append(ul);\n }\n\n // Data updated via ajax (callback)\n function dataUpdated(data) {\n store(data);\n\n var exists = {}, list = [];\n $.each(data, function(i, child) {\n exists[child[3]] = child;\n });\n $('> ul > li', element).each(function() {\n var li = $(this), name = li.data('name');\n if (!exists[name]) {\n li.remove();\n } else {\n delete exists[name];\n }\n list.push($(this));\n });\n $.each(exists, function(name, child) {\n var inserted = false;\n $.each(list, function(i, other) {\n if (name < other.data('name')) {\n inserted = true;\n other.before(createChild(child));\n return false;\n }\n });\n if (!inserted) {\n element.children('ul').append(createChild(child));\n }\n });\n }\n\n // Update this element with some delay\n function update() {\n setTimeout(function() {\n options.ajax(path, dataUpdated, function() {\n if (cacheKey) {\n $.storage.remove(cacheKey);\n }\n });\n }, options.delay);\n }\n\n // If children exist, show them and update this element\n if (element.children('ul').length !== 0) {\n element.children('ul').show();\n update();\n } else {\n // Try to load from cache\n var data = cacheKey ? $.storage.get(cacheKey) : null;\n if (data) {\n dataLoaded(data);\n update();\n }\n // Load data via ajax and add busy indicator\n else {\n element.addClass('wait');\n options.ajax(path, function(data) {\n element.removeClass('wait');\n dataLoaded(data);\n store(data);\n }, function() {\n element.removeClass('wait');\n });\n }\n }\n }",
"function _newPageHandler(currentStatus, oldStatus, newContainer, newRawHtml) {\n // console.log('New page is ready.');\n //make it visible immediately after being loaded\n newContainer.style.visibility = 'visible';\n //update newPage object\n var pathArray = window.location.pathname.split('/'); // /pathname1/pathname2/ -> split -> array[\"\", \"pathname1\", \"pathname2\", \"\"]\n newPage.pathname = pathArray[pathArray.length - 2];\n newPage.containerEl = newContainer;\n newPage.class = newContainer.classList.item(1);\n newPage.object = _getPageObject(newPage.class);\n }",
"function parser_page(navInfo, $timeinterval){\n\n\trequest(navInfo['page']['currentPage'], function (error, response, html) {\n\t if (!error && response.statusCode == 200) {\n\t\t// parsing the html page with cheerio\n\t\tlet $ = cheerio.load(html);\n\t\t\n\t\tlet articles = $(navInfo['page']['path_liste_articles']);\n\t\t//let nextPage = $(navInfo['page']['path_url_next_page']);\n\t\t\n\t\tarticles.each(function(index, element){\n\t\t\tlet navInfoArticle = copyArray(navInfo);\n\t\t\tnavInfoArticle['page']['currentPage'] = 'https:' + $(element).attr('href');\n\t\t\tsetTimeout(function(){parser_article(navInfoArticle)}, $timeinterval*index);\n\t\t});\n/*\n\t\tif(typeof nextPage != 'undefined' && nextPage.attr('href') != 'undefined'){\n\t\t\tconsole.log('[DEBUG] Next page find: ' + 'https:' + nextPage.attr('href'));\n\t\t\tlet navInfoNextPage = copyArray(navInfo);\n\t\t\tnavInfoNextPage['page']['currentPage'] = 'https:' + nextPage.attr('href');\n\t\t\tparser_page(navInfoNextPage, $timeinterval);\n\t\t}\n*/\n\t }\n\t});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calling play on the element will emit playing even if the stream is stalled. If the stream is stalled, emit a waiting event. | function onPlaying() {
if (element && isStalled() && element.playbackRate === 0) {
const event = document.createEvent('Event');
event.initEvent('waiting', true, false);
element.dispatchEvent(event);
}
} | [
"function onPlaying() {\n if (element && isStalled() && element.playbackRate === 0) {\n var _event = document.createEvent('Event');\n _event.initEvent('waiting', true, false);\n element.dispatchEvent(_event);\n }\n }",
"play() {\n // Force asynchronous event firing for IE e.g.\n qx.event.Timer.once(\n function () {\n this._media.play();\n },\n this,\n 0\n );\n }",
"play() {\n this._parentPlay();\n this._markPlaying();\n this._markCurrentTimePlaying();\n }",
"play() {\n\t\tthis.trigger('play', this);\n\t}",
"__delayPlay__ () {\n let media = this.$media[0];\n\n media.paused && media.play(); \n this.__events__.emit('play');\n }",
"play() {\n this._super();\n this.getNodeFrom('audioSource').onended = () => this.stop();\n this._trackPlayPosition();\n }",
"play() {\n this._source.play();\n }",
"play() {\n this._source.play();\n }",
"play() {}",
"play() {\r\n // console.log('play:', this.name)\r\n if (this.isVideo() && this._element) {\r\n this._element.play()\r\n }\r\n }",
"play() {\n if (this._playingState === 'play') {\n return;\n }\n\n this._playByIndex(this.index);\n this._playingState = 'play';\n }",
"play() {\n const HAVE_NOTHING = 0;\n if (this.videoElement.readyState === HAVE_NOTHING) {\n this.videoElement.addEventListener('loadeddata', this.videoElement.play, { once: true });\n } else {\n this.videoElement.play();\n }\n }",
"playOnce(){\n\t\tthis.songElem.loop = false;\n\t\tthis.songElem.play();\n\t}",
"play() {\n this.svg.init();\n if (this.state != State.PLAYING) {\n this.state = State.PLAYING;\n if (this.progress != 1) {\n this.dispatchEvent(EventType.RESUME);\n this.startTime = goog.now() - (this.duration * this.progress);\n } else {\n this.dispatchEvent(EventType.BEGIN);\n this.progress = 0;\n this.startTime = goog.now();\n }\n this.dispatchEvent(EventType.PLAY);\n this.animation();\n }\n }",
"play() {\n if (this.status !== 'PLAY') {\n this.editor.focus();\n this.emit('play');\n this.playChanges();\n }\n }",
"play() {\n this.audioElement.play();\n }",
"play() {\n return __awaiter(this, void 0, void 0, function* () {\n if (!this.paused) {\n yield this._bufferPromise;\n if (!this.paused) {\n return;\n }\n throw new Error('The play() request was interrupted by a call to pause().');\n }\n this._audioNode = this._audioContext.createBufferSource();\n this._audioNode.loop = this.loop;\n this._audioNode.addEventListener('ended', () => {\n if (this._audioNode && this._audioNode.loop) {\n return;\n }\n this.dispatchEvent('ended');\n });\n const buffer = yield this._bufferPromise;\n if (this.paused) {\n throw new Error('The play() request was interrupted by a call to pause().');\n }\n this._audioNode.buffer = buffer;\n this._audioNode.connect(this._gainNode);\n this._audioNode.start();\n if (this._audioElement.srcObject) {\n return this._audioElement.play();\n }\n });\n }",
"playVideo() {\n this.element.load();\n\n var playPromise = this.element.play();\n if (playPromise !== undefined) {\n playPromise.then(() => {\n this._setDebug(\"Video stream is playing.\");\n }).catch(() => {\n if (this.onplayvideorequired !== null) {\n this.onplayvideorequired();\n } else {\n this._setDebug(\"Video play failed and no onplayvideorequired was bound.\");\n }\n });\n }\n }",
"playMedia() {\n\t\tthis.context.vent.trigger(EVENT_PLAY, {\n\t\t\tinstance: this\n\t\t});\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
depositProfit You have deposited a specific amount of dollars into your bank account. Each year your balance increases at the same growth rate. Find out how long it would take for your balance to pass a specific threshold with the assumption that you don't make any additional deposits. Example For deposit = 100, rate = 20 and threshold = 170, the output should be depositProfit(deposit, rate, threshold) = 3. Each year the amount of money on your account increases by 20%. It means that throughout the years your balance would be: year 0: 100; year 1: 120; year 2: 144; year 3: 172,8. Thus, it will take 3 years for your balance to pass the threshold, which is the answer. | function depositProfit(deposit, rate, threshold) {
var yr = 0;
while(deposit < threshold){
deposit += deposit * (rate/100);
yr ++;
}
return yr;
} | [
"function depositProfit(deposit, rate, threshold) {\n let yearsToMature = 0\n let rateOfReturn = rate / 100\n while (deposit < threshold) {\n deposit += (deposit * rateOfReturn)\n yearsToMature++\n }\n return yearsToMature\n}",
"function depositProfit(deposit, rate, threshold) {\n let years = 0;\n while (deposit < threshold) {\n deposit += deposit * rate / 100;\n years++;\n }\n return years;\n}",
"function depositProfit(deposit, rate, threshold) {\n let year = 0;\n let account = deposit;\n\n while (threshold > account) {\n account += account * (rate / 100);\n year++;\n }\n return year;\n}",
"function depositProfit(deposit, rate, threshold) {\n let years = 0;\n while (deposit < threshold) {\n years++;\n deposit = deposit * (rate / 100) + deposit;\n }\n return years;\n}",
"function depositProfit(deposit, rate, threshold) {\n // write code here.\n let years = 0;\n let total = deposit;\n \n while(threshold > total) {\n let convertToPercentage = (rate/100);\n let interest = total * convertToPercentage;\n total += interest;\n years++;\n }\n return years;\n}",
"function depositProfit(deposit, rate, threshold){\n let count = 0;\n while(deposit < threshold){\n deposit = deposit * (rate / 100 + 1);\n count++;\n }\n return count;\n}",
"function find_Profit(x, a, b) {\n sp = a * x;\n cp = x * b + 100\n profit = sp - cp;\n return profit;\n}",
"function calcProfit (income, expenses){\n\n\t\t\t//calculation of proft based on income and expenses\n\t\t\tvar mula = (income - expenses);\n\t\t\treturn mula;\n\n\t\t}",
"function depositProfit(deposit, rate, threshold) {\n let i = 1;\n let summe = deposit + deposit * rate/100;\n while (summe <= threshold){\n i = i + 1;\n summe = summe + summe * rate/100;\n // console.log(i);\n // console.log(summe);\n }\n return i;\n}",
"function calculateDeposit(arr){\n let balance = arr[0];\n let interestRate = arr[1];\n let frequencyInMonths = arr[2];\n let timeInYears = arr[3];\n let compoundFrequency = 12 * 1.0 / frequencyInMonths;\n\n let result = balance * Math.pow(1 + (interestRate / 100) / compoundFrequency,\n compoundFrequency * timeInYears);\n\n return result.toFixed(2);\n}",
"function retire(bal, intR, nPer, mDep){\n\t\tvar retirement =bal;\n\t\tfor(var year=1;year<=nYears;year++){\n\t\tretirement*=(1+intRate/100);\n\t\tretirement+=(mDeposit*12);\n\t\tretirement=retirement.toFixed(2);\n\t\t}\n\treturn retirement;\n\t}",
"function profits(quant, pay, sell){//This will determine how many tickets the user needs to sell to make a profit.\n var ticketSalesNeeded = quant * pay / sell + 1;//Equation for finding the number of tickets the user will need to sell to start making a profit.\n return ticketSalesNeeded;//The return value of ticket sales needed to display.\n}",
"function getPaye(grossPay) {\n gp = grossPay; // assign gross pay value to function variable\n paye = 0; // initialise PAYE value\n fl = 235000; // first limit\n sl = 335000; // second limit\n tl = 410000; // third limit\n vl = 10000000; // fourth limit\n m1 = 10000; // maximum tax payable first bracket\n m2 = 25000; // maximum tax payable second bracket\n\n // first tax bracket\n if (gp <= 235000)\n {\n paye = 0;\n }\n \n // second tax bracket\n else if ((gp > fl) && (gp < sl)) {\n // calculating first increment\n inc = gp - fl;\n // calculating paye of second bracket\n paye = 0.1 * inc;\n\n // ensuring maximum pay is 10000shs\n if (paye > m1)\n {\n paye = m1;\n }\n } \n\n // third tax bracket\n else if ((gp > sl) && (gp < tl)) {\n // calculating second increment\n inc2 = gp - sl;\n // calculating paye of third bracket\n paye = (0.2 * inc2) + m1;\n\n // ensuring maximum pay is 25000shs\n if (paye > m2)\n {\n paye = m2;\n }\n }\n\n //final tax bracket\n else \n {\n // calculating third increment\n inc3 = gp - tl;\n // calculating paye of third bracket\n paye = (0.3 * inc3) + m2;\n\n // for those earning above 10 million\n if (gp > vl)\n {\n // calculating final increment\n inc4 = gp - vl;\n paye += (0.1 * inc4) ;\n }\n }\n // output for Paye to be paid\n console.log(\"Yo Paye is \" + paye + \"shs\");\n return paye;\n}",
"function calculatedownPayment(cost){\n if(cost < 50000){\n console.log( 0.05 * cost);\n }else if(cost > 50000 && cost < 100000){\n console.log(\"your Down Payment is \" + 2500 + 0.10 * cost - 50000);\n }else if(cost > 100000 && cost < 200000){\n console.log(\"your Down Payment is \" + 7500 + 0.15 * cost - 100000);\n }else{\n console.log(5000 + 0.10 * cost - 200000);\n }\n}",
"function expensesPercentage(income,expense){\n return (expense/income)*100;\n}",
"function paye() {\n var grossPay = 1000000\n var perc = 30 / 100\n var tax = grossPay * perc\n var netPay = grossPay - tax\n console.log(netPay)\n}",
"function profitableGamble(prob, prize, pay) \r\n{\r\n if((prob*prize) > pay)\r\n {\r\n return true;\r\n }\r\n else{\r\n return false;\r\n }\r\n}",
"function calcBenefitRate(age, group, years) {\n if (years < 30) {\n if (group === \"group1\") {\n if (age >= 67) {\n return 2.5\n }\n var otherAges = {\n 66:2.35,\n 65:2.2,\n 64:2.05,\n 63:1.9,\n 62:1.75,\n 61:1.60,\n 60:1.45,\n }\n if (age in otherAges) {\n return otherAges[age]\n } else {\n return 0;\n }\n }\n else if (group === \"group2\") {\n if (age >=62) {\n return 2.5\n }\n var otherAges = {\n 61:2.35,\n 60:2.2,\n 59:2.05,\n 58:1.9,\n 57:1.75,\n 56:1.60,\n 55:1.45,\n };\n if (age in otherAges) {\n return otherAges[age]\n } else {\n return 0;\n }\n }\n else if (group === \"group4\") {\n if (age >=57) {\n return 2.5\n }\n var otherAges = {\n 56:2.35,\n 55:2.2,\n 54:2.05,\n 53:1.9,\n 52:1.75,\n 51:1.60,\n 50:1.45,\n };\n if (age in otherAges) {\n return otherAges[age]\n } else {\n return 0;\n }\n } else {\n return 0;\n }\n }\n else if (years >= 30) {\n if (group === \"group1\") {\n if (age >=67) {\n return 2.5\n }\n var otherAges = {\n 66:2.375,\n 65:2.25,\n 64:2.125,\n 63:2.0,\n 62:1.875,\n 61:1.75,\n 60:1.625,\n };\n if (age in otherAges) {\n return otherAges[age]\n } else {\n return 0;\n }\n }\n else if (group === \"group2\") {\n if (age >=62) {\n return 2.5\n }\n var otherAges = {\n 61:2.375,\n 60:2.25,\n 59:2.125,\n 58:2.0,\n 57:1.875,\n 56:1.75,\n 55:1.625\n };\n if (age in otherAges) {\n return otherAges[age]\n } else {\n return 0;\n }\n }\n else if (group === \"group4\") {\n if (age >=57) {\n return 2.5\n }\n var otherAges = {\n 56:2.375,\n 55:2.25,\n 54:2.125,\n 53:2.0,\n 52:1.875,\n 51:1.75,\n 50:1.625\n };\n if (age in otherAges) {\n return otherAges[age]\n } else {\n return 0;\n }\n } else {\n return 0;\n }\n } else {\n return 0;\n }\n}",
"function getCashflow(monthly_profit, monthly_expenses){\n\n var cash_flow = monthly_profit - monthly_expenses;\n\n // cash_flow = cash_flow.toPrecision(4);\n\n return cash_flow;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets all of the edges of a rectangle that are outside of the given bounds. If there are no out of bounds edges it returns an empty array. | function _getOutOfBoundsEdges(rect, boundingRect) {
var outOfBounds = new Array();
if (rect.top < boundingRect.top) {
outOfBounds.push(RectangleEdge.top);
}
if (rect.bottom > boundingRect.bottom) {
outOfBounds.push(RectangleEdge.bottom);
}
if (rect.left < boundingRect.left) {
outOfBounds.push(RectangleEdge.left);
}
if (rect.right > boundingRect.right) {
outOfBounds.push(RectangleEdge.right);
}
return outOfBounds;
} | [
"function _getOutOfBoundsEdges(rect, boundingRect) {\n var outOfBounds = new Array();\n if (rect.top < boundingRect.top) {\n outOfBounds.push(RectangleEdge.top);\n }\n if (rect.bottom > boundingRect.bottom) {\n outOfBounds.push(RectangleEdge.bottom);\n }\n if (rect.left < boundingRect.left) {\n outOfBounds.push(RectangleEdge.left);\n }\n if (rect.right > boundingRect.right) {\n outOfBounds.push(RectangleEdge.right);\n }\n return outOfBounds;\n }",
"function GetFigureOutsideRect(pRect,Iterator)\n{}",
"getBounds(){\r\n let r = null;\r\n for (let i = 0; i < nodes.length; i++) {\r\n let n = nodes[i];\r\n b = n.getBounds();\r\n if (r === null) r = b;\r\n else r.push(b);\r\n }\r\n for (let i = 0; i < edges.length; i++) r.push(e.getBounds());\r\n return r === null\r\n ? document.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\")\r\n : r;\r\n }",
"getCollidingTilesBoundsFromBounds(bounds) {\n return this.getCollidingTilesIndexesFromBounds(bounds)\n .map(({ row, col }) => this.getTileBoundsFromIndex(row, col));\n }",
"RetrieveInBounds(bounds)\n\t{\n\t\tlet list = [];\n\t\t\n\t\tif(!this.Bounds.IsOverlapping(bounds))\n\t\t\treturn null;\n\t\tfor(let item of this.Items)\n\t\t{\n\t\t\tif(item[0].IsOverlapping(bounds))\n\t\t\t\tlist.push(item);\n\t\t}\n\t\t\n\t\tif(this.Children != null)\n\t\t{\n\t\t\tfor(let child of this.Children)\n\t\t\t{\n\t\t\t\tlet temp = child.RetrieveInBounds(bounds);\n\t\t\t\t//TODO: we need to filter out duplicates that may occur due to storing the same\n\t\t\t\t//item in multiple children when it overlaps boundaries\n\t\t\t\tif(temp != null)\n\t\t\t\t\tlist = list.concat(temp);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn list.length > 0 ? list : null;\n\t}",
"function findBounds (rects) {\n var width = 0\n var height = 0\n for (var i = 0; i < rects.length; i++) {\n var rect = rects[i]\n var right = rect.x + rect.width\n var bottom = rect.y + rect.height\n if (right > width) {\n width = right\n }\n if (bottom > height) {\n height = bottom\n }\n }\n return { width: width, height: height }\n}",
"outsideBounds(s, bounds, extra) {\n\n let x = bounds.x,\n y = bounds.y,\n width = bounds.width,\n height = bounds.height;\n\n //The `collision` object is used to store which\n //side of the containing rectangle the sprite hits\n let collision = new Set();\n\n //Left\n if (s.x < x - s.width) {\n collision.add(\"left\");\n }\n //Top\n if (s.y < y - s.height) {\n collision.add(\"top\");\n }\n //Right\n if (s.x > width + s.width) {\n collision.add(\"right\");\n }\n //Bottom\n if (s.y > height + s.height) {\n collision.add(\"bottom\");\n }\n\n //If there were no collisions, set `collision` to `undefined`\n if (collision.size === 0) collision = undefined;\n\n //The `extra` function runs if there was a collision\n //and `extra` has been defined\n if (collision && extra) extra(collision);\n\n //Return the `collision` object\n return collision;\n }",
"getCollidingTilesIndexesFromBounds(bounds) {\n // Indexes of the for corner of the bounds\n const boundsIndexes = bounds.map(b => this.getTileIndexesFromPos(b));\n\n let allTiles = [];\n\n for (let r = boundsIndexes[3].row; r <= boundsIndexes[0].row; r += 1) {\n for (let c = boundsIndexes[3].col; c <= boundsIndexes[2].col; c += 1) {\n allTiles.push({ row: r, col: c });\n }\n }\n return allTiles\n .filter(t => this.tileMap.logicalMap[t.row][t.col] === 1);\n }",
"function getAllArtboardBounds() {\n var rect, bounds;\n for (var i=0, n=doc.artboards.length; i<n; i++) {\n rect = doc.artboards[i].artboardRect;\n if (i === 0) {\n bounds = rect;\n } else {\n bounds = [\n Math.min(rect[0], bounds[0]), Math.max(rect[1], bounds[1]),\n Math.max(rect[2], bounds[2]), Math.min(rect[3], bounds[3])];\n }\n }\n return bounds;\n}",
"outsideBounds(s, bounds, extra) {\n let x = bounds.x, y = bounds.y, width = bounds.width, height = bounds.height;\n //The `collision` object is used to store which\n //side of the containing rectangle the sprite hits\n let collision = new Set();\n //Left\n if (s.x < x - s.width) {\n collision.add(\"left\");\n }\n //Top\n if (s.y < y - s.height) {\n collision.add(\"top\");\n }\n //Right\n if (s.x > width + s.width) {\n collision.add(\"right\");\n }\n //Bottom\n if (s.y > height + s.height) {\n collision.add(\"bottom\");\n }\n //If there were no collisions, set `collision` to `undefined`\n if (collision.size === 0)\n collision = undefined;\n //The `extra` function runs if there was a collision\n //and `extra` has been defined\n if (collision && extra)\n extra(collision);\n //Return the `collision` object\n return collision;\n }",
"function isOutsideBounds(x, y) {\n return (\n (x < MIN_BOARD || x > MAX_BOARD) ||\n (y < MIN_BOARD || y > MAX_BOARD)\n )\n}",
"getAllEdges() {\n let edges = [];\n for (let i = 0; i < this.size; i++) {\n for (let j = 0; j < this.size; j++) {\n const neighbours = [\n [i + 1, j],\n [i, j + 1],\n ]\n neighbours.map(([p, q]) => {\n if (p < 0 || p >= this.size || q < 0 || q >= this.size) return;\n if (!this.getEdge(i, j, p, q)) return;\n edges.push([i, j, p, q]);\n })\n }\n }\n return edges;\n }",
"findBoundaries(evenOrOdd, src){\n //boundaries in the order: T, L, R, B\n let boundaries=Array(4).fill(false);\n //top boundary\n if(0<=src && src<=4){\n //top boundary set\n boundaries[0]=true;\n }\n //left boundary\n if(src%5===0){\n //left boundary set\n boundaries[1]=true;\n }\n //right boundary\n if(src%5===4)\n {\n //right boundary set\n boundaries[2]=true;\n }\n //bottom boundary\n if(20<=src && src<=24)\n {\n //bottom boundary set\n boundaries[3]=true;\n }\n return boundaries;\n }",
"function outOfBounds(x, y){\n return x < 0 || y < 0 || x > 7 || y > 7;\n}",
"function findOuterEdges() {\n var edges = []\n var faces = geometry.faces\n for (var firstI = 0; firstI < faces.length; firstI++) {\n var firstFace = faces[firstI]\n firstFace.eachEdge(function(vertIndexA, vertIndexB, other) {\n var isEdge = true\n for (var secondI = 0; secondI < faces.length; secondI++) {\n if (firstI == secondI) continue\n var secondFace = faces[secondI]\n if (secondFace.contains(vertIndexA) && secondFace.contains(vertIndexB)) return\n }\n edges.push([vertIndexA, vertIndexB, other])\n })\n }\n return edges\n}",
"function getNorthEast(bounds) {\n if (bounds) {\n if (bounds.length === 4) {\n return [bounds[2], bounds[3]];\n }\n else if (bounds.length === 6) {\n return [bounds[3], bounds[4]];\n }\n }\n return null;\n }",
"hitsEdges() {\n return (\n this.coordinates.x - this.radius <= 0 ||\n this.coordinates.x + this.radius >= width ||\n this.coordinates.y - this.radius <= 0 ||\n this.coordinates.y + this.radius >= height\n );\n }",
"function getInnerCellsInRect(contextApi, xAxis, yAxis) {\n var e_1, _a, e_2, _b;\n var spaceInside = [];\n try {\n for (var yAxis_1 = __values(yAxis), yAxis_1_1 = yAxis_1.next(); !yAxis_1_1.done; yAxis_1_1 = yAxis_1.next()) {\n var vCell = yAxis_1_1.value;\n try {\n for (var xAxis_1 = (e_2 = void 0, __values(xAxis)), xAxis_1_1 = xAxis_1.next(); !xAxis_1_1.done; xAxis_1_1 = xAxis_1.next()) {\n var hCell = xAxis_1_1.value;\n var vhContext = contextApi.findRowInCache(vCell.rowIdent).cells[hCell.colIndex];\n if (vhContext) {\n spaceInside.push({ rowIdent: vCell.rowIdent, colIndex: hCell.colIndex });\n }\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (xAxis_1_1 && !xAxis_1_1.done && (_b = xAxis_1.return)) _b.call(xAxis_1);\n }\n finally { if (e_2) throw e_2.error; }\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (yAxis_1_1 && !yAxis_1_1.done && (_a = yAxis_1.return)) _a.call(yAxis_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n return spaceInside;\n }",
"function GetRectArray(topLeftInd, bottomRightInd) {\n let rectArray = [];\n let iterator = 0;\n for (let x = topLeftInd.x; x < bottomRightInd.x + 1; x++) {\n for (let y = topLeftInd.y; y < bottomRightInd.y + 1; y++) {\n rectArray[iterator] = new Index(x, y);\n iterator++;\n }\n }\n return rectArray;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decimal character reference start state | [DECIMAL_CHARACTER_REFERENCE_START_STATE](cp) {
if (isAsciiDigit(cp)) {
this._reconsumeInState(DECIMAL_CHARACTER_REFERENCE_STATE);
} else {
this._err(ERR.absenceOfDigitsInNumericCharacterReference);
this._flushCodePointsConsumedAsCharacterReference();
this._reconsumeInState(this.returnState);
}
} | [
"_stateDecimalCharacterReferenceStart(cp) {\n if (isAsciiDigit(cp)) {\n this.state = State.DECIMAL_CHARACTER_REFERENCE;\n this._stateDecimalCharacterReference(cp);\n }\n else {\n this._err(error_codes_js_1$1.ERR.absenceOfDigitsInNumericCharacterReference);\n this._flushCodePointConsumedAsCharacterReference(unicode_js_1.CODE_POINTS.AMPERSAND);\n this._flushCodePointConsumedAsCharacterReference(unicode_js_1.CODE_POINTS.NUMBER_SIGN);\n this._reconsumeInState(this.returnState);\n }\n }",
"_stateHexademicalCharacterReferenceStart(cp) {\n if (isAsciiHexDigit(cp)) {\n this.state = State.HEXADEMICAL_CHARACTER_REFERENCE;\n this._stateHexademicalCharacterReference(cp);\n }\n else {\n this._err(ERR.absenceOfDigitsInNumericCharacterReference);\n this._flushCodePointConsumedAsCharacterReference(CODE_POINTS.AMPERSAND);\n this._flushCodePointConsumedAsCharacterReference(CODE_POINTS.NUMBER_SIGN);\n this._unconsume(2);\n this.state = this.returnState;\n }\n }",
"_stateHexademicalCharacterReferenceStart(cp) {\n if (isAsciiHexDigit(cp)) {\n this.state = State.HEXADEMICAL_CHARACTER_REFERENCE;\n this._stateHexademicalCharacterReference(cp);\n }\n else {\n this._err(error_codes_js_1.ERR.absenceOfDigitsInNumericCharacterReference);\n this._flushCodePointConsumedAsCharacterReference(unicode_js_1.CODE_POINTS.AMPERSAND);\n this._flushCodePointConsumedAsCharacterReference(unicode_js_1.CODE_POINTS.NUMBER_SIGN);\n this._unconsume(2);\n this.state = this.returnState;\n }\n }",
"[DECIMAL_CHARACTER_REFERENCE_START_STATE](cp) {\n if (isAsciiDigit(cp)) {\n this._reconsumeInState(DECIMAL_CHARACTER_REFERENCE_STATE)\n } else {\n this._err(errorCodes.absenceOfDigitsInNumericCharacterReference)\n this._flushCodePointsConsumedAsCharacterReference()\n this._reconsumeInState(this.returnState)\n }\n }",
"[DECIMAL_CHARACTER_REFERENCE_START_STATE](cp) {\n if (isAsciiDigit(cp)) {\n this._reconsumeInState(DECIMAL_CHARACTER_REFERENCE_STATE);\n } else {\n this._err(ERR$1.absenceOfDigitsInNumericCharacterReference);\n this._flushCodePointsConsumedAsCharacterReference();\n this._reconsumeInState(this.returnState);\n }\n }",
"[NUMERIC_CHARACTER_REFERENCE_STATE](cp) {\n this.charRefCode = 0;\n\n if (cp === $$1.LATIN_SMALL_X || cp === $$1.LATIN_CAPITAL_X) {\n this.tempBuff.push(cp);\n this.state = HEXADEMICAL_CHARACTER_REFERENCE_START_STATE;\n } else {\n this._reconsumeInState(DECIMAL_CHARACTER_REFERENCE_START_STATE);\n }\n }",
"[NUMERIC_CHARACTER_REFERENCE_STATE](cp) {\n this.charRefCode = 0\n\n if (cp === $$1.LATIN_SMALL_X || cp === $$1.LATIN_CAPITAL_X) {\n this.tempBuff.push(cp)\n this.state = HEXADEMICAL_CHARACTER_REFERENCE_START_STATE\n } else {\n this._reconsumeInState(DECIMAL_CHARACTER_REFERENCE_START_STATE)\n }\n }",
"[HEXADEMICAL_CHARACTER_REFERENCE_START_STATE](cp) {\n if (isAsciiHexDigit(cp)) {\n this._reconsumeInState(HEXADEMICAL_CHARACTER_REFERENCE_STATE);\n } else {\n this._err(ERR.absenceOfDigitsInNumericCharacterReference);\n\n this._flushCodePointsConsumedAsCharacterReference();\n\n this._reconsumeInState(this.returnState);\n }\n }",
"[HEXADEMICAL_CHARACTER_REFERENCE_START_STATE](cp) {\n if (isAsciiHexDigit(cp)) {\n this._reconsumeInState(HEXADEMICAL_CHARACTER_REFERENCE_STATE);\n } else {\n this._err(ERR.absenceOfDigitsInNumericCharacterReference);\n this._flushCodePointsConsumedAsCharacterReference();\n this._reconsumeInState(this.returnState);\n }\n }",
"_stateDecimalCharacterReference(cp) {\n if (isAsciiDigit(cp)) {\n this.charRefCode = this.charRefCode * 10 + cp - 0x30;\n }\n else if (cp === CODE_POINTS.SEMICOLON) {\n this.state = State.NUMERIC_CHARACTER_REFERENCE_END;\n }\n else {\n this._err(ERR.missingSemicolonAfterCharacterReference);\n this.state = State.NUMERIC_CHARACTER_REFERENCE_END;\n this._stateNumericCharacterReferenceEnd(cp);\n }\n }",
"[NUMERIC_CHARACTER_REFERENCE_STATE](cp) {\n this.charRefCode = 0;\n\n if (cp === $.LATIN_SMALL_X || cp === $.LATIN_CAPITAL_X) {\n this.tempBuff.push(cp);\n this.state = HEXADEMICAL_CHARACTER_REFERENCE_START_STATE;\n } else {\n this._reconsumeInState(DECIMAL_CHARACTER_REFERENCE_START_STATE);\n }\n }",
"[HEXADEMICAL_CHARACTER_REFERENCE_START_STATE](cp) {\n if (isAsciiHexDigit(cp)) {\n this._reconsumeInState(HEXADEMICAL_CHARACTER_REFERENCE_STATE)\n } else {\n this._err(errorCodes.absenceOfDigitsInNumericCharacterReference)\n this._flushCodePointsConsumedAsCharacterReference()\n this._reconsumeInState(this.returnState)\n }\n }",
"_stateNumericCharacterReference(cp) {\n this.charRefCode = 0;\n if (cp === unicode_js_1.CODE_POINTS.LATIN_SMALL_X || cp === unicode_js_1.CODE_POINTS.LATIN_CAPITAL_X) {\n this.state = State.HEXADEMICAL_CHARACTER_REFERENCE_START;\n }\n // Inlined decimal character reference start state\n else if (isAsciiDigit(cp)) {\n this.state = State.DECIMAL_CHARACTER_REFERENCE;\n this._stateDecimalCharacterReference(cp);\n }\n else {\n this._err(error_codes_js_1.ERR.absenceOfDigitsInNumericCharacterReference);\n this._flushCodePointConsumedAsCharacterReference(unicode_js_1.CODE_POINTS.AMPERSAND);\n this._flushCodePointConsumedAsCharacterReference(unicode_js_1.CODE_POINTS.NUMBER_SIGN);\n this._reconsumeInState(this.returnState, cp);\n }\n }",
"_stateNumericCharacterReference(cp) {\n this.charRefCode = 0;\n if (cp === CODE_POINTS.LATIN_SMALL_X || cp === CODE_POINTS.LATIN_CAPITAL_X) {\n this.state = State.HEXADEMICAL_CHARACTER_REFERENCE_START;\n }\n // Inlined decimal character reference start state\n else if (isAsciiDigit(cp)) {\n this.state = State.DECIMAL_CHARACTER_REFERENCE;\n this._stateDecimalCharacterReference(cp);\n }\n else {\n this._err(ERR.absenceOfDigitsInNumericCharacterReference);\n this._flushCodePointConsumedAsCharacterReference(CODE_POINTS.AMPERSAND);\n this._flushCodePointConsumedAsCharacterReference(CODE_POINTS.NUMBER_SIGN);\n this._reconsumeInState(this.returnState, cp);\n }\n }",
"[NUMERIC_CHARACTER_REFERENCE_STATE](cp) {\n this.charRefCode = 0;\n\n if (cp === $$5.LATIN_SMALL_X || cp === $$5.LATIN_CAPITAL_X) {\n this.tempBuff.push(cp);\n this.state = HEXADEMICAL_CHARACTER_REFERENCE_START_STATE;\n } else {\n this._reconsumeInState(DECIMAL_CHARACTER_REFERENCE_START_STATE);\n }\n }",
"[DECIMAL_CHARACTER_REFERENCE_STATE](cp) {\n if (isAsciiDigit(cp)) {\n this.charRefCode = this.charRefCode * 10 + cp - 0x30;\n } else if (cp === $.SEMICOLON) {\n this.state = NUMERIC_CHARACTER_REFERENCE_END_STATE;\n } else {\n this._err(ERR.missingSemicolonAfterCharacterReference);\n this._reconsumeInState(NUMERIC_CHARACTER_REFERENCE_END_STATE);\n }\n }",
"[DECIMAL_CHARACTER_REFERENCE_STATE](cp) {\n if (isAsciiDigit(cp)) {\n this.charRefCode = this.charRefCode * 10 + cp - 0x30;\n } else if (cp === $$1.SEMICOLON) {\n this.state = NUMERIC_CHARACTER_REFERENCE_END_STATE;\n } else {\n this._err(errorCodes.missingSemicolonAfterCharacterReference);\n this._reconsumeInState(NUMERIC_CHARACTER_REFERENCE_END_STATE);\n }\n }",
"[NUMERIC_CHARACTER_REFERENCE_STATE](cp) {\n this.charRefCode = 0;\n\n if (cp === $.LATIN_SMALL_X || cp === $.LATIN_CAPITAL_X) {\n this.tempBuff.push(cp);\n this.state = HEXADEMICAL_CHARACTER_REFERENCE_START_STATE;\n } else {\n this._reconsumeInState(DECIMAL_CHARACTER_REFERENCE_START_STATE);\n }\n }",
"_stateHexademicalCharacterReference(cp) {\n if (isAsciiUpperHexDigit(cp)) {\n this.charRefCode = this.charRefCode * 16 + cp - 0x37;\n }\n else if (isAsciiLowerHexDigit(cp)) {\n this.charRefCode = this.charRefCode * 16 + cp - 0x57;\n }\n else if (isAsciiDigit(cp)) {\n this.charRefCode = this.charRefCode * 16 + cp - 0x30;\n }\n else if (cp === CODE_POINTS.SEMICOLON) {\n this.state = State.NUMERIC_CHARACTER_REFERENCE_END;\n }\n else {\n this._err(ERR.missingSemicolonAfterCharacterReference);\n this.state = State.NUMERIC_CHARACTER_REFERENCE_END;\n this._stateNumericCharacterReferenceEnd(cp);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Counts and tracks the number of external scripts currently being loaded, and when they are all loaded, calls the 'scriptsLoadFun'. This can also be used to set the scriptsLoadFun, by just passing a function in. It can also take multiple function calls. | function scriptLoad( inc ) {
if ( typeof inc === 'number' ) {
scriptsLoading += inc;
if ( scriptsLoading === 0 && scriptsLoadFun ) {
scriptsLoadFun();
scriptsLoadFun = null;
}
// store the fun to call it later
} else if ( inc instanceof Function ) {
scriptsLoadFuns.push( inc );
} else {
console.log( inc );
throw new Error( "unknown parameter given " + inc );
}
} | [
"function CountLoadedScript()\r\n\t{\r\n\t\t--tNbScriptToLoad;\r\n\t\t\r\n\t\tif( _callBackPercent )\r\n\t\t{\r\n\t\t\t_callBackPercent( (((tNbScriptToLoadTotal-tNbScriptToLoad)/tNbScriptToLoadTotal)*100).toFixed(1) );\r\n\t\t}\r\n\t\tif( tNbScriptToLoad != 0)\r\n\t\t\treturn;\r\n\t\t\r\n\t\t_callBackWhenDone();\r\n\t}",
"function callback() {\n scriptCounter.push(url)\n // Finished loading all scripts.\n if (scriptCounter.length === scripts.length)\n scriptsLoaded()\n }",
"function reloadOnLoadScripts() {\n\n\tfor (var i = 0; i < onLoadScripts.length; i++) {\n\t\tonLoadScripts[i]();\n\t}\n}",
"function loadScripts()\n\t{\n\t\tif (scriptList.length > 0)\n\t\t{\n\t\t\tvar file = scriptList.shift();\n\n\t\t\t// Inject the script elements\n\t\t\tajaxHandles.push(fw.injectScript(that.path + file, loadScripts, loadFailed));\n\t\t}\n\t\telse\n\t\t\tdoneLoading();\n\t}",
"function loadScripts( scriptList, lastCb )\n {\n var completionCount = 0;\n\n scriptList.forEach( function( scriptItem, ix ) {\n\n //https://developer.mozilla.org/en-US/docs/Web/HTTP/\n // Basics_of_HTTP/MIME_types#JavaScript_types\n type = scriptItem.type || 'text/javascript';\n var scrip = document.createElement('script');\n scrip.onload = function() {\n completionCount++;\n //ccc( completionCount + ' loaded ' + scriptItem.src );\n scriptItem.cb && scriptItem.cb( loadedItem );\n checkCompletion();\n }\n document.head.appendChild( scrip );\n //https://medium.com/@vschroeder/javascript-how-to-execute-code-from-an-\n //asynchronously-loaded-script-although-when-it-is-not-bebcbd6da5ea\n scrip.src = scriptItem.src;\n });\n return; //rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr\n\n function checkCompletion()\n {\n if( completionCount === scriptList.length ) {\n lastCb && lastCb();\n }\n }\n }",
"function loadScripts(){\r\n\t\t$showLoadingDiv();\r\n\t\tif (scriptIndex<scriptToLoad.length){\t\r\n\t\t\t$.getScript(scriptToLoad[scriptIndex], loadScripts);\t\r\n\t\t\tscriptIndex++\r\n\t\t}else{\r\n\t\t$loadGameFiles();\r\n\t\t}\r\n\t}",
"function ScriptLoadHandler(params) {\n\n var scr = scripts[scripts_counter];\n\n // Advance the scripts_counter\n\n scripts_counter++;\n\n // Load the next script in the chain\n\n scr = scripts[scripts_counter];\n\n // If there is a next script to load, create the script tag, otherwise\n // call the PreMain() function.\n\n if (scr) {\n\n CreateScriptTag(scr.name, scr.src)\n \n } else {\n\n // This is the last script in the page, call main()\n main();\n }\n }",
"function load_script_assets(script_list, callbackFcn) {\r\n\r\n\tvar loaded = 0;\r\n\tfor (var i = 0; i < script_list.length ; i++) {\r\n\t\t// Should we check the cache? I'm only calling this function once, so I don't see the point.\r\n\r\n\t\tvar assetName = script_list[i];\r\n\r\n\t\t// our asset is a Javascript file, and we\r\n\t\t// need to:\r\n\t\t//\r\n\t\t// 1) Use document.createElement to create\r\n\t\t// a new script tag.\r\n\r\n \tvar script_elem = document.createElement('script');\r\n\r\n\t\t// 2) Set the type attribute on this element\r\n\t\t// to 'text/javascript'.\r\n\r\n \tscript_elem.type = 'text/javascript';\r\n\r\n\t\t// 3) We'll need to set an event listener to\r\n\t\t// call onLoadedCallback just like we do\r\n\t\t// for images. Luckily, the same '.onload'\r\n // we use for images will also work here.\r\n\r\n\t\tscript_elem.name = assetName;\r\n\r\n script_elem.onload = function () {\r\n\r\n\t\t\t\r\n\t\t\t\r\n\t\t\tloaded++;\r\n\t\t\t//console.log(this.name + \" loaded\");\r\n\t\t\tif(loaded >=script_list.length) {\r\n\t\t\t\tcallbackFcn(script_elem); // why pass script_elem?\r\n\t\t\t}\r\n \t//onLoadedCallback(script_elem, loadBatch);\t//what?\r\n };\r\n\r\n\t\t// 4) Set the src attribute on this element\r\n\t\t\t// to the filename.\r\n\r\n script_elem.src = script_list[i]; // Does this trigger the loading like for images?\r\n\r\n\t\t// 5) Use document.getElementsByTagName to\r\n\t\t\t// grab a LIST of the elements in the\r\n\t\t\t// document named 'head'.\r\n\r\n var list_of_elems = document.getElementsByTagName('head');\r\n\r\n\t\t\t// 6) Use the appendChild method of the first\r\n\t\t\t// element of that list to append the\r\n\t\t\t// script element you created.\r\n\r\n list_of_elems[0].appendChild(script_elem);\r\n\r\n\t}\r\n\r\n\t\r\n\r\n}",
"function Init(_ScriptName, func, waittime) {\n var FailSafe = 0; //Failsafe so that doesnt get stuck in a forever loop\n var Error = false;\n while (AddScript(_ScriptName) != true) { //If the scripts havent loaded then continue to wait\n\n if (FailSafe > 10000) { //break if it takes to long\n Error = true;\n console.error(\"Failed to load dynamic scripts\");\n break;\n }\n FailSafe += 1;\n console.log(FailSafe); //It shouldnt take it long to make the scripts so I print the Failsafe count for debuging purposes\n }\n if (Error === false) {\n setTimeout(function() { StartFunctions(func) }, waittime); //After waiting a set amount of time go to functions to start functions in loaded scripts\n }\n\n}",
"async function onScriptsLoaded(recur){\n var pending = false\n scripts = Array.from(this.window.document.getElementsByTagName('script'))\n //promise array which resolves only on all scripts are loaded\n promiseArray = scripts.map(script => {\n return new Promise(function(resolve, reject){\n if(script.isLoaded == undefined){\n pending = true\n let data = {script,resolved: true}\n script.onload = () => {resolve(data);script.isLoaded = true}\n }else{\n let data = {script,resolved: true}\n resolve(data);\n }\n })\n })\n let result = await Promise.all(promiseArray);\n if(pending && recur) {\n await this.onScriptsLoaded(pending && recur)\n }\n return result;\n }",
"function incrementLoadCount() {\n loadCount++;\n if (loadCount === scriptsToLoadLength && scriptsToLoadLength !== 0) {\n window.initGcdm();\n deferred.resolve();\n }\n }",
"loadAllScripts() {\n\t\tthis._scripts.forEach( function( scriptPlugin ) {\n\t\t\tif ( false === scriptPlugin._ranInline ) {\n\t\t\t\tscriptPlugin.theScript();\n\t\t\t}\n\t\t\tscriptPlugin.createScript();\n\t\t});\n\t}",
"function loadScripts(urls, callback) {\n\n let scriptsToComplete = 0;\n function maybeCallback() {\n scriptsToComplete -= 1;\n if (scriptsToComplete < 1 && typeof callback === 'function') {\n callback();\n }\n }\n\n if (Array.isArray(urls) && urls.length === 0) {\n maybeCallback();\n return;\n }\n\n // Prevents a lot of bad input in one check (after handling an empty url array above): prevents it if url is missing,\n // null, an empty or only-spaces string, or an array where none of the items contain characters other than spaces\n if (((urls || \"\") + \"\").replace(/,/g, '').trim() === \"\") {\n console.error(\"Aborting: malformed 'urls' argument (all empty): \" + JSON.stringify(urls));\n return;\n }\n\n if (typeof urls === \"string\") {\n urls = [urls];\n }\n\n // Trim each url, and remove the duplicates and empty items\n urls = urls.map(url => (url || \"\").trim());\n urls = urls.filter( (url, index) =>\n url !== \"\" &&\n urls.indexOf(url) === index\n );\n\n scriptsToComplete = urls.length;\n\n\n try {\n urls.forEach(url => {\n try {\n const script = document.createElement(\"script\");\n script.type = \"text/javascript\";\n\n if (script.readyState) { //IE\n script.onreadystatechange = () => {\n if (script.readyState == \"loaded\" || script.readyState == \"complete\") {\n script.onreadystatechange = null;\n maybeCallback();\n }\n };\n } else { //Others\n script.onload = maybeCallback;\n }\n\n script.src = url;\n document.getElementsByTagName(\"head\")[0].appendChild(script);\n\n } catch (e) {\n throw Error(\"Error occurred while trying to load script from url [ \" + url + \" ]: \" + e.message);\n }\n });\n\n } catch (e) {\n console.error(\"Aborted - \" + e.message);\n }\n}",
"function increment_scripts()\n {\n\n if((++Gov.scripts_loaded[url])>=Gov.scripts_total[url]) setTimeout(function() { Gov.parse_contact_tables(doc,url,resolve,reject,temp_div,dept_name); }, 100);\n }",
"function getFileUploadScripts(callback){\n if(ux.preload.fileUploadScripts !== true){\n load('scripts/external/jquery-ui-widget.js', 'scripts/external/jquery.iframe-transport.js')\n .then('scripts/external/jquery.fileupload.js')\n .thenRun(function(){\n \n // Log that the scripts are loaded so they won't be called again\n ux.preload.fileUploadScripts = true;\n dlog('UPLOAD: Requesting fileUpload scripts...');\n\n // Run whatever callback script you define...\n callback();\n\n });\n } else {\n dlog('UPLOAD: Skipping fileUpload scripts. Scripts already loaded!');\n callback();\n }\n }",
"function checkAllLoaded() {\n if (nike.ScriptLoader.scriptsToInclude.length == 0) {\n // Reset script include loaded start flag\n nike.ScriptLoader.scriptIncludeLoadStart = false;\n\n // Fire event indicating scripts are loaded\n nike.dispatchEvent(nike.EVENT_REQUESTED_SCRIPTS_LOADED);\n return true;\n }\n return false;\n }",
"function allLoaded() {\n\t\t\t\t// hope.execute() does its own error handling\n\t\t\t\tfor (var i = 0, script; i < scriptCount; i++) {\n\t\t\t\t\tscript = results[i];\n\t\t\t\t\thope.execute(script, \"hope.loadScripts()\", \"\"+urls[i]);\n\t\t\t\t}\n\t\t\t\tcompletelyDone();\n\t\t\t}",
"loadJS () {\n let count = this.urls.length;\n let writeScript = function (src) {\n let script = document.createElement(\"script\");\n\n script.async = true;\n script.src = src;\n\n script.onload = function () {\n this.onTagInjected();\n }.bind(this);\n\n document.querySelector(\"head\").appendChild(script);\n }.bind(this);\n\n for(let i = 0; i < count; i++) {\n writeScript(this.urls[i]);\n }\n }",
"function include(scripts, callback)\n{\n var list = scripts;\n var loaded = 0;\n if (typeof scripts == \"string\") return;\n var fnLoaded = function(script)\n {\n if (script.target.src)\n console.log(include.config.indent + \"LOADED CODE:\" + script.target.src);\n else\n console.log(include.config.indent + \"LOADED CODE:\" + script.target.href);\n loaded++;\n if (loaded == list.length && callback) callback();\n }\n var fnLoadError = function(oError)\n {\n console.log(include.config.indent + \"The script \" + oError.target.src + \" is not accessible.\");\n if (!include.config.strict)\n {\n loaded++;\n if (loaded == list.length && callback) callback(); \n }\n }\n\n var head = document.getElementsByTagName('head')[0];\n for(index in scripts)\n {\n var url = scripts[index];\n \n if (!url) continue; \n\n for (var key in include.config.paths) \n {\n if (include.config.paths.hasOwnProperty(key)) \n {\n var path = include.config.paths[key];\n url = url.replace(\"{\"+key+\"}\",path);\n }\n }\n\n\n if (url.indexOf(\".css\") != -1)\n {\n var script = document.createElement('link');\n script.type = 'text/css';\n script.rel = 'stylesheet'; \n script.async = true;\n script.href = url; \n }\n else\n {\n // Adding the script tag to the head as suggested before\n var script = document.createElement('script');\n script.type = 'text/javascript';\n script.async = true;\n if (url.indexOf(\".js\") == -1) url += \".js\";\n if (!include.config.devmode)\n script.src = \"./production.php?js=\" + url;\n else\n script.src = url;\n } \n // Then bind the event to the callback function.\n // There are several events for cross browser compatibility.\n script.onreadystatechange = fnLoaded;\n script.onload = fnLoaded;\n script.onerror = fnLoadError;\n\n if (include.config.verbose)\n {\n if (url.indexOf(\".css\") != -1)\n console.log(include.config.indent + \"loading CSS:\" + script.href);\n else\n console.log(include.config.indent + \"loading CODE:\" + script.src);\n }\n\n // Fire the loading\n head.appendChild(script);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Configuration of the current Truffle project. | async function currentConfig() {
let config = Config.default();
config.resolver = new Resolver(config);
config.artifactor = new Artifactor();
config.paths = await contractPaths(config);
config.base_path = config.contracts_directory;
return config;
} | [
"function config() {\n global.config.build.rootDirectory = path.join('../EquiTrack/assets/frontend/', global.config.appName);\n global.config.build.templateDirectory = path.join('../EquiTrack/templates/frontend/', global.config.appName);\n global.config.build.bundledDirectory = '.';\n indexPath = path.join(global.config.build.rootDirectory, 'index.html');\n bowerPath = path.join(global.config.build.rootDirectory, 'bower.json');\n templatePath = global.config.build.templateDirectory;\n}",
"@computed get config() {\n\n\t\treturn {\n\t\t\tgamePath: this.gamePath,\n\t\t\trealismPreset: this.realismPreset\n\t\t}\n\t}",
"static configureProject(project) {\n const\n {config} = project,\n {toolchains, android} = project.rootProject || project\n \n if (toolchains.length === 0) {\n if (!android && config.toolchainExcludeHost !== true) {\n toolchains.push(Toolchain.host)\n }\n \n Object\n .entries(config.toolchains || {})\n .map(([name, toolchainConfig]) => {\n // If name has exactly three parts then its a triplet\n if (name.split(_).length === 3) {\n const tripletStr = toolchainConfig\n \n const\n toolchainFileOrObject = config.toolchains[tripletStr],\n [processor, system, abi] = _.split(tripletStr, \"-\")\n \n toolchains.push(new Toolchain(\n new Triplet(\n Object.keys(System).find(it => it.toLowerCase() === system),\n Object.keys(Architecture).find(it => it.toLowerCase() === processor),\n Object.keys(ABI).find(it => it.toLowerCase() === abi)\n ),\n toolchainFileOrObject\n ))\n }\n // Otherwise, its just the name\n else {\n let {system, arch, abi, file, name} = toolchainConfig,\n triplet = new Triplet(\n findSystem(system),\n findArch(arch),\n findABI(abi)\n )\n \n if (file) {\n const dir = getValue(() => project.rootProject.projectDir, project.projectDir).toString()\n if (!Path.isAbsolute(file)) {\n file = Path.join(dir, file)\n }\n }\n \n log.info(`Toolchain (${name}) file ${file}`)\n Assert.ok(exists(file), `Toolchain (${name}) file ${file} does not exist`)\n \n toolchains.push(new Toolchain(\n triplet,\n {\n file,\n name: name || triplet.toString(),\n ...toolchainConfig\n }\n ))\n }\n })\n \n }\n \n \n Object.assign(project, {\n buildTypes: toolchains.map(toolchain =>\n new BuildType(project, toolchain)\n )\n })\n }",
"function configure() {\n lightjs.info('taks: configures and copy root files');\n\n const generalConfig = projectConfig.general;\n const templatePath = 'src/template/root';\n if (generalConfig.useMITLicense) {\n shjs.cp(path.join(templatePath, swProjectConst.LICENSE_MD), projectPath);\n lightjs.replacement('{{PROJECT.YEAR}}', new Date().getFullYear(), [path.join(projectPath, swProjectConst.LICENSE_MD)]);\n }\n shjs.cp(path.join(templatePath, swProjectConst.DOT_EDITORCONFIG), projectPath);\n shjs.cp(path.join(templatePath, '.gitattributes'), projectPath);\n shjs.cp(swProjectConst.SWAAPLATE_JSON, projectPath);\n\n if (generalConfig.useDocker) {\n shjs.cp(path.join(templatePath, swProjectConst.DOCKER, swProjectConst.DOCKERFILE), path.join(projectPath, swProjectConst.DOCKERFILE));\n shjs.cp(path.join(templatePath, swProjectConst.DOCKER, swProjectConst.DOCKER_COMPOSE_YML), path.join(projectPath, swProjectConst.DOCKER_COMPOSE_YML));\n shjs.cp(path.join(templatePath, swProjectConst.DOCKER, swProjectConst.README_MD), path.join(projectPath, 'README_docker.md'));\n shjs.cp(path.join(templatePath, swProjectConst.DOCKER, 'default.env'), path.join(projectPath, 'default.env'));\n shjs.cp(path.join(templatePath, swProjectConst.DOCKER, 'default.env'), path.join(projectPath, '.env'));\n lightjs.replacement('{{PROJECT.TITLE}}', generalConfig.name, [path.join(projectPath, swProjectConst.DOCKER_COMPOSE_YML)]);\n const contributors = projectConfig.frontend.packageJson.contributors;\n const name = contributors[0].name ? contributors[0].name : '';\n const email = contributors[0].name ? contributors[0].email : '';\n lightjs.replacement('{{PROJECT.AUTHOR}}', name, [path.join(projectPath, swProjectConst.DOCKERFILE)]);\n lightjs.replacement('{{PROJECT.FIRSTCONTRIBUTORSMAIL}}', email, [path.join(projectPath, swProjectConst.DOCKERFILE)]);\n }\n}",
"function FabricConfig() {}",
"async initialize() {\n this.configWriter.guardForExistingConfig();\n this.patchProxies();\n const selectedPreset = await this.selectPreset();\n let configFileName;\n if (selectedPreset) {\n configFileName = await this.initiatePreset(this.configWriter, selectedPreset);\n }\n else {\n configFileName = await this.initiateCustom(this.configWriter);\n }\n await this.gitignoreWriter.addStrykerTempFolder();\n this.out(`Done configuring stryker. Please review \"${configFileName}\", you might need to configure transpilers or your test runner correctly.`);\n this.out(\"Let's kill some mutants with this command: `stryker run`\");\n }",
"function OktaConfigurationStrategy() {\n\n}",
"configure() {\n let taskerConfig = this.app.config.tasker\n const profile = getWorkerProfile(taskerConfig)\n taskerConfig = configureExchangesAndQueues(profile, taskerConfig)\n\n this.app.tasker = new Client(this.app, rabbit, taskerConfig.exchangeName)\n TaskerUtils.registerTasks(profile, this.app, rabbit)\n\n this.app.workerCount = 0\n this.app.api.tasks = this.app.api.tasks || {}\n }",
"async function getTruffleConfig(opts) {\n let file = await findUp('truffle-config.js', opts);\n if (!file) file = await findUp('truffle.js', opts);\n return file;\n}",
"function config() {\n\tgameTitle = \"A Blink Game\";\n\tgameAuthor = \"BloomEngine\";\n\tmetaContent = \"{About|about} {Hints|hints}\"; //goes at menu at bottom\n\tinventorySystem = 0; //If you don't want an inventory system in your game, set inventorySystem = 0;\n\t\n\twaitSystem = 0; //If you want a \"wait\" button to allow time to pass, set waitSystem = 1; If the wait system is off, it can be activated on a specific node by writing wait=1; Alternatively, if the wait system is turned on, it can be deactivated on a specific node by writing wait=0;\n\t\n\tdebugMode = 1;\n\t\n}",
"configure() {\n\n }",
"async init() {\n App.web3 = new Web3(web3.givenProvider);\n App.networkId = await web3.eth.net.getId();\n App.contract = await ProjectSubmission.deployed();\n }",
"function Conf() {\n this.transformerDir = path.resolve(\n __dirname,\n '../../src/site/stages/build/process-cms-exports/transformers',\n );\n // The cache dir where the build stores files\n this.cacheDir = path.resolve(__dirname, `../../.cache/localhost/`);\n // The directory for the nodes that the tome sync created in the tar file\n this.cmsExportDir = path.join(this.cacheDir, 'cms-export-content');\n // The open API schema of Drupal\n this.cmsExportSchema = path.join(this.cmsExportDir, '/meta/schema.json');\n // GraphQL variables\n // The graphQL file created by the graphQL query\n this.graphqlFile = path.join(this.cacheDir, '/drupal/pages.json');\n // Where to store the nodes from the transformed file\n this.nodeFileDir = path.join(this.cacheDir, '/drupal/nodes');\n // Transformer variables\n // The graphQL file created by the transformer output schemas\n this.transformedFile = path.join(\n this.cacheDir,\n '/drupal/pagesTransformed.json',\n );\n // Where to store the nodes from the transformed file\n this.nodeTransformedFileDir = path.join(\n this.cacheDir,\n '/drupal/nodesTransformed',\n );\n}",
"setConfig() {\n\t\tthis.config = config.get();\n\t}",
"function config() {\n\n // The input file format\n\tCONFIG.FileFormat = 'XML';\n\n /*\n * The XPath expression to select the nodes/records\n * to be evaluated by transform().\n */\n CONFIG.RecordPath = '/orderFulfillmentRequest/orderFulfillment';\n}",
"async init() {\n //using web3.js therefore Web3.givenProvider\n App.web3 = new Web3(Web3.givenProvider || \"ws://localhost:8546\");\n App.networkId = await this.web3.eth.net.getId();\n App.contract = await ProjectSubmission.deployed();\n \n }",
"setup() {\n const projectPaths = AtomUtils.getProjectPaths();\n const projectConfigUrls = AtomUtils.getProjectConfigUrls(projectPaths);\n const projectSettings = Config.loadProjectSettings(projectConfigUrls);\n const configKeys = Object.keys(this.config);\n const userSettings = Config.loadUserSettings(configKeys);\n const options = Object.assign({}, userSettings, projectSettings);\n let babelConfigs = null;\n let webpackConfigs = null;\n\n if (!options.user.disableBabelRc) {\n babelConfigs = AtomUtils.getBabelRc(projectPaths);\n }\n\n if (!options.user.disableWebpack) {\n webpackConfigs = AtomUtils.getWebpackConfigs(projectPaths);\n }\n\n const userOverrides = options.user.pathOverrides;\n const aliases = Utils.extractAllAliases(\n userOverrides,\n babelConfigs,\n projectConfigUrls,\n webpackConfigs\n );\n\n if (userSettings.user.enableDebug) {\n Logger.enable();\n } else {\n Logger.disable();\n }\n\n this.initialized = true;\n this.options = options;\n this.aliases = aliases;\n\n Logger.report({\n options,\n aliases\n });\n\n this.subscribeToChanges(configKeys, projectConfigUrls, babelConfigs, webpackConfigs);\n }",
"function Config() {\n}",
"config(options) {\n Config.set(options);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is a function for repositoriesWorkspaceRepoSlugPullrequestsPullRequestIdPut / Mutates the specified pull request. This can be used to change the pull request&39;s branches or description. Only open pull requests can be mutated. | repositoriesWorkspaceRepoSlugPullrequestsPullRequestIdPut(
incomingOptions,
cb
) {
const Bitbucket = require('./dist');
let defaultClient = Bitbucket.ApiClient.instance;
// Configure API key authorization: api_key
let api_key = defaultClient.authentications['api_key'];
api_key.apiKey = incomingOptions.apiKey;
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
api_key.apiKeyPrefix = incomingOptions.apiKeyPrefix || 'Token';
// Configure HTTP basic authorization: basic
let basic = defaultClient.authentications['basic'];
basic.username = 'YOUR USERNAME';
basic.password = 'YOUR PASSWORD';
// Configure OAuth2 access token for authorization: oauth2
let oauth2 = defaultClient.authentications['oauth2'];
oauth2.accessToken = incomingOptions.accessToken;
let apiInstance = new Bitbucket.PullrequestsApi(); // String | This can either be the workspace ID (slug) or the workspace UUID surrounded by curly-braces, for example: `{workspace UUID}`. // String | This can either be the repository slug or the UUID of the repository, surrounded by curly-braces, for example: `{repository UUID}`. // Number | The id of the pull request.
/*let workspace = "workspace_example";*/ /*let repoSlug = "repoSlug_example";*/ /*let pullRequestId = 56;*/ let opts = {
body: new Bitbucket.Pullrequest(), // Pullrequest | The pull request that is to be updated.
};
if (incomingOptions.opts)
Object.keys(incomingOptions.opts).forEach(
(key) =>
incomingOptions.opts[key] === undefined &&
delete incomingOptions.opts[key]
);
else delete incomingOptions.opts;
incomingOptions.opts = Object.assign(opts, incomingOptions.opts);
apiInstance.repositoriesWorkspaceRepoSlugPullrequestsPullRequestIdPut(
incomingOptions.workspace,
incomingOptions.repoSlug,
incomingOptions.pullRequestId,
incomingOptions.opts,
(error, data, response) => {
if (error) {
cb(error, null, response);
} else {
cb(null, data, response);
}
}
);
} | [
"async updatePullRequestComment(owner, repo, commentId, body, pullRequestId) {\n this.authenticate();\n const response = await this.unwrap(this.client.pullrequests.updateComment({\n pull_request_id: `${pullRequestId}`,\n comment_id: `${commentId}`,\n repo_slug: repo,\n workspace: owner,\n _body: { type: 'pullrequest_comment', content: { raw: body, markup: 'markdown' } },\n }));\n const comment = response.data;\n return {\n user: { id: `${comment.user.id}`, login: comment.user.username, url: comment.user.website },\n id: comment.id,\n url: comment.links.html.href,\n body: comment.content.markup,\n createdAt: comment.created_on,\n updatedAt: comment.updated_on,\n };\n }",
"async updatePullRequestComment(owner, repo, commentId, body, pullRequestId) {\n const { data } = await this.unwrap(this.client.MergeRequests.updateComment(`${owner}/${repo}`, pullRequestId, body, commentId));\n return {\n user: { id: `${data.author.id}`, login: data.author.username, url: data.author.web_url },\n id: data.id,\n url: `${this.host}/projects/${owner}/${repo}/merge_requests/${pullRequestId}/notes`,\n body: data.body,\n createdAt: data.created_at.toString(),\n updatedAt: data.updated_at.toString(),\n };\n }",
"async uploadPullRequest(params) {\n try {\n return await this.github.openPullRequest(params);\n } catch (e) {\n const message = e.errors && e.errors[0] && e.errors[0].message;\n if (/A pull request already exists/.exec(message)) {\n return await this.github.updatePullRequest(params);\n }\n throw e;\n }\n }",
"handlePullRequestEditSubmit(editPullRequestObject) {\n var status = 'merged'; \n var changes = editPullRequestObject; \n var usernameParameter = this.props.params.targetUser; \n var pullIdParameter = this.props.params.pullId; \n axios.put(`/${usernameParameter}/${pullIdParameter}/update-pull`, {\n status: status,\n changes: changes\n })\n .then((result) => {\n this.setState({ pullRequestObject: {} }); \n browserHistory.push(`/User/${usernameParameter}`); \n })\n .catch((error) => {\n console.log(error); \n }); \n }",
"function edit_repo(owner, repo, description_edit)\r\n{ \r\n \r\n var options = {\r\n url: urlRoot + \"/repos/\" + owner + \"/\" + repo,\r\n method: 'PATCH',\r\n headers: {\r\n \"User-Agent\": \"EnableIssues\",\r\n \"content-type\": \"application/json\",\r\n \"Authorization\": token\r\n },\r\n json: {\r\n \"name\":repo,\r\n \"description\":description_edit,\r\n \"private\": false, \r\n\t\t\t\t\"has_issues\": false\r\n\t\t\t\t}\r\n };\r\n\r\n request(options, function (error, response, body)\r\n {\r\n console.log( body );\r\n });\r\n}",
"repositoriesWorkspaceRepoSlugPullrequestsPullRequestIdPatchGet(\n incomingOptions,\n cb\n ) {\n const Bitbucket = require('./dist');\n let defaultClient = Bitbucket.ApiClient.instance;\n // Configure API key authorization: api_key\n let api_key = defaultClient.authentications['api_key'];\n api_key.apiKey = incomingOptions.apiKey;\n // Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n api_key.apiKeyPrefix = incomingOptions.apiKeyPrefix || 'Token';\n // Configure HTTP basic authorization: basic\n let basic = defaultClient.authentications['basic'];\n basic.username = 'YOUR USERNAME';\n basic.password = 'YOUR PASSWORD';\n // Configure OAuth2 access token for authorization: oauth2\n let oauth2 = defaultClient.authentications['oauth2'];\n oauth2.accessToken = incomingOptions.accessToken;\n\n let apiInstance = new Bitbucket.PullrequestsApi(); // String | // String | This can either be the workspace ID (slug) or the workspace UUID surrounded by curly-braces, for example: `{workspace UUID}`. // String | This can either be the repository slug or the UUID of the repository, surrounded by curly-braces, for example: `{repository UUID}`.\n /*let pullRequestId = \"pullRequestId_example\";*/ /*let workspace = \"workspace_example\";*/ /*let repoSlug = \"repoSlug_example\";*/ apiInstance.repositoriesWorkspaceRepoSlugPullrequestsPullRequestIdPatchGet(\n incomingOptions.pullRequestId,\n incomingOptions.workspace,\n incomingOptions.repoSlug,\n (error, data, response) => {\n if (error) {\n cb(error, null, response);\n } else {\n cb(null, data, response);\n }\n }\n );\n }",
"function updateIssue(issueID, done, uuid, text_val, date_val, prio_val){\n // get project id in order to compuse URL\n var projectID = localStorage.getItem(\"projectID\");\n var urlData = \"http://zhaw-weng-api.herokuapp.com/api/project/\" + projectID + \"/issues/\"+issueID;\n\n var postData = JSON.stringify({\n \"client_id\": uuid,\n \"done\": done,\n \"title\": text_val+\"###\"+prio_val,\n \"due_date\": date_val\n });\n\n $.ajax({\n type: \"PUT\",\n url: urlData,\n data: postData,\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n async: true,\n success: function(data) {\n //\n },\n failure: function(errMsg) {\n alert(\"Error while updating issue with backend\");\n }\n });\n\n}",
"function editRepo(owner,repo)\r\n{\r\nvar options = {\r\n\t\turl: urlRoot + '/repos/' + owner + \"/\" + repo,\r\n\t\tmethod: 'PATCH',\r\n\t\theaders: {\r\n\t\t\t\"User-Agent\": \"EnableIssues\",\r\n\t\t\t\"content-type\": \"application/json\",\r\n\t\t\t\"Authorization\": token\r\n\t\t},\r\n\t\tjson: {\r\n \t\t\t \"name\": repo,\r\n \t\t \t \"description\": \"This is scyadav demo HW1 repository\",\r\n \t\t \t \"homepage\": \"https://github.com\",\r\n \t\t \"private\": true,\r\n\t\t\t \"has_wiki\": true\r\n \t\t }\r\n\t};\r\n\r\n\t// Send a http request to url and specify a callback that will be called upon its return.\r\n\trequest(options, function (error, response, body) \r\n\t{\r\n\t\tvar obj = body;\r\n\t\tconsole.log( obj );\r\n\t\tfor( var i = 0; i < obj.length; i++ )\r\n\t\t{\r\n\t\t\tvar name = obj[i].name;\r\n\t\t\tconsole.log( name );\r\n\t\t}\r\n\t});\r\n\t\r\n}",
"handlePullRequestEdit(event) {\n event.preventDefault(); \n var pullRequestObject = this.state.pullRequestObject; \n var usernameParameter = pullRequestObject.sendingUser; \n var recipeParameter = pullRequestObject.sentRootVersion;\n var branchParameter = pullRequestObject.sentBranch;\n var versionParameter = pullRequestObject.sentVersion; \n var pullIdParameter = pullRequestObject._id; \n var targetUserParameter = pullRequestObject.targetUser; \n\n browserHistory.push(`/EditPull/${targetUserParameter}/${pullIdParameter}/${usernameParameter}/${recipeParameter}/${branchParameter}/${versionParameter}`);\n }",
"handlePullRequestResponse(event) {\n event.preventDefault(); \n var response = event.target.id; \n if (response === 'approve') {\n var status = 'merged'; \n } else if (response === 'deny') {\n var status = 'closed'; \n }\n var pullRequestObject = this.state.pullRequestObject; \n var usernameParameter = pullRequestObject.targetUser; \n var pullIdParameter = pullRequestObject._id; \n axios.put(`/${usernameParameter}/${pullIdParameter}/update-pull`, {\n status: status\n })\n .then((result) => {\n this.setState({ pullRequestObject: {} }); \n browserHistory.push(`/User/${usernameParameter}`); \n })\n .catch((error) => {\n console.log(error); \n }); \n }",
"pushChangesToForkAndCreatePullRequest(targetBranch, proposedForkBranchName, title, body) {\n return __awaiter(this, void 0, void 0, function* () {\n const repoSlug = `${this.git.remoteParams.owner}/${this.git.remoteParams.repo}`;\n const { fork, branchName } = yield this._pushHeadToFork(proposedForkBranchName, true);\n const { data } = yield this.git.github.pulls.create(Object.assign(Object.assign({}, this.git.remoteParams), { head: `${fork.owner}:${branchName}`, base: targetBranch, body,\n title }));\n // Add labels to the newly created PR if provided in the configuration.\n if (this.config.releasePrLabels !== undefined) {\n yield this.git.github.issues.addLabels(Object.assign(Object.assign({}, this.git.remoteParams), { issue_number: data.number, labels: this.config.releasePrLabels }));\n }\n info(green(` ✓ Created pull request #${data.number} in ${repoSlug}.`));\n return {\n id: data.number,\n url: data.html_url,\n fork,\n forkBranch: branchName,\n };\n });\n }",
"async updatePullRequestComment(owner, repo, commentId, body) {\n const response = await this.client.issues.updateComment({\n owner,\n repo,\n comment_id: commentId,\n body,\n });\n const comment = response.data;\n return {\n user: { id: comment.user.id.toString(), login: comment.user.login, url: comment.user.url },\n id: comment.id,\n url: comment.url,\n body: comment.body,\n createdAt: comment.created_at,\n updatedAt: comment.updated_at,\n };\n }",
"repositoriesWorkspaceRepoSlugPullrequestsPullRequestIdApprovePost(\n incomingOptions,\n cb\n ) {\n const Bitbucket = require('./dist');\n let defaultClient = Bitbucket.ApiClient.instance;\n // Configure API key authorization: api_key\n let api_key = defaultClient.authentications['api_key'];\n api_key.apiKey = incomingOptions.apiKey;\n // Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n api_key.apiKeyPrefix = incomingOptions.apiKeyPrefix || 'Token';\n // Configure HTTP basic authorization: basic\n let basic = defaultClient.authentications['basic'];\n basic.username = 'YOUR USERNAME';\n basic.password = 'YOUR PASSWORD';\n // Configure OAuth2 access token for authorization: oauth2\n let oauth2 = defaultClient.authentications['oauth2'];\n oauth2.accessToken = incomingOptions.accessToken;\n\n let apiInstance = new Bitbucket.PullrequestsApi(); // String | // String | This can either be the workspace ID (slug) or the workspace UUID surrounded by curly-braces, for example: `{workspace UUID}`. // String | This can either be the repository slug or the UUID of the repository, surrounded by curly-braces, for example: `{repository UUID}`.\n /*let pullRequestId = \"pullRequestId_example\";*/ /*let workspace = \"workspace_example\";*/ /*let repoSlug = \"repoSlug_example\";*/ apiInstance.repositoriesWorkspaceRepoSlugPullrequestsPullRequestIdApprovePost(\n incomingOptions.pullRequestId,\n incomingOptions.workspace,\n incomingOptions.repoSlug,\n (error, data, response) => {\n if (error) {\n cb(error, null, response);\n } else {\n cb(null, data, response);\n }\n }\n );\n }",
"pushChangesToForkAndCreatePullRequest(targetBranch, proposedForkBranchName, title, body) {\n return tslib.__awaiter(this, void 0, void 0, function* () {\n const repoSlug = `${this.git.remoteParams.owner}/${this.git.remoteParams.repo}`;\n const { fork, branchName } = yield this._pushHeadToFork(proposedForkBranchName, true);\n const { data } = yield this.git.github.pulls.create(Object.assign(Object.assign({}, this.git.remoteParams), { head: `${fork.owner}:${branchName}`, base: targetBranch, body,\n title }));\n // Add labels to the newly created PR if provided in the configuration.\n if (this.config.releasePrLabels !== undefined) {\n yield this.git.github.issues.addLabels(Object.assign(Object.assign({}, this.git.remoteParams), { issue_number: data.number, labels: this.config.releasePrLabels }));\n }\n info(green(` ✓ Created pull request #${data.number} in ${repoSlug}.`));\n return {\n id: data.number,\n url: data.html_url,\n fork,\n forkBranch: branchName,\n };\n });\n }",
"async function update_status_of_all_pull_requests(context, args) {\n var FETCH_LIMIT = 30\n\n var state = args.state\n var message = args.message\n\n const logger = context.log\n const log_prefix = context.log_prefix || \"\"\n\n var github_cli = context.github\n\n //fetch PRs\n var prs = await list_prs(context, {\n base : args.base,\n limit : FETCH_LIMIT\n });\n\n\n //Update status for each PR\n prs.forEach( async pr => {\n\n logger.info(`${log_prefix} Creating status ${state} for pr ${pr.number}:${pr.head.sha}`)\n var resp = await github_cli.repos.createStatus(\n context.repo({\n state: state,\n description: message,\n sha: pr.head.sha,\n context: process.env.DISPLAY_NAME\n })\n );\n console.log(github_cli.repos)\n console.log(JSON.stringify(resp, null, 2))\n logger.info(`${log_prefix} Created status ${state} for pr ${pr.number}:${pr.head.sha}`);\n })\n}",
"static async putToGithubAPI(url, data){\n let result;\n try\n { \n console.log(\"making a PUT request to github API to make branch protection changes\") \n result = await axios.put(url, data, {\n headers: githubAPIObject.HeaderPreview\n });\n // console.log(result.status)\n }catch(error){\n // console.log(error)\n console.log(Object.keys(error), error.message);\n console.log(\"failed to make put request to github to update branch protection\")\n }\n return result;\n }",
"function updateIssue(issueNumber, oldLabel, newLabel, blocked, issueTitle) {\n var ISSUE_ENDPOINT = '/issues/' + ownerName + '/' + repositoryName + '/update/' +issueNumber;\n var data = {\n issueTitle: issueTitle,\n oldLabel: oldLabel,\n newLabel: newLabel,\n blocked: blocked\n }\n\n var request = $.ajax({\n url: ISSUE_ENDPOINT,\n type: \"POST\",\n data: data,\n success: function(msg) {\n console.log(msg);\n },\n error: function(error) {\n console.log('Error: ' + JSON.parse(error));\n }\n });\n}",
"async addReviewerToPullRequest(info) {\n this.bitbucketAuth()\n let reviewers = await this.userLookup(info.team, info.individual)\n await bb.repositories.updatePullRequest({\n username: config.bit.username,\n repo_slug: info.repo,\n pull_request_id: info.pr_id,\n _body: {\n title: info.title,\n reviewers: [{ uuid: reviewers.uuid }],\n },\n })\n }",
"repositoriesWorkspaceRepoSlugPullrequestsPullRequestIdMergePost(\n incomingOptions,\n cb\n ) {\n const Bitbucket = require('./dist');\n let defaultClient = Bitbucket.ApiClient.instance;\n // Configure API key authorization: api_key\n let api_key = defaultClient.authentications['api_key'];\n api_key.apiKey = incomingOptions.apiKey;\n // Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n api_key.apiKeyPrefix = incomingOptions.apiKeyPrefix || 'Token';\n // Configure HTTP basic authorization: basic\n let basic = defaultClient.authentications['basic'];\n basic.username = 'YOUR USERNAME';\n basic.password = 'YOUR PASSWORD';\n // Configure OAuth2 access token for authorization: oauth2\n let oauth2 = defaultClient.authentications['oauth2'];\n oauth2.accessToken = incomingOptions.accessToken;\n\n let apiInstance = new Bitbucket.PullrequestsApi(); // String | // String | This can either be the workspace ID (slug) or the workspace UUID surrounded by curly-braces, for example: `{workspace UUID}`. // String | This can either be the repository slug or the UUID of the repository, surrounded by curly-braces, for example: `{repository UUID}`.\n /*let pullRequestId = \"pullRequestId_example\";*/ /*let workspace = \"workspace_example\";*/ /*let repoSlug = \"repoSlug_example\";*/ let opts = {\n body: new Bitbucket.PullrequestMergeParameters(), // PullrequestMergeParameters |\n };\n\n if (incomingOptions.opts)\n Object.keys(incomingOptions.opts).forEach(\n (key) =>\n incomingOptions.opts[key] === undefined &&\n delete incomingOptions.opts[key]\n );\n else delete incomingOptions.opts;\n incomingOptions.opts = Object.assign(opts, incomingOptions.opts);\n\n apiInstance.repositoriesWorkspaceRepoSlugPullrequestsPullRequestIdMergePost(\n incomingOptions.pullRequestId,\n incomingOptions.workspace,\n incomingOptions.repoSlug,\n incomingOptions.opts,\n (error, data, response) => {\n if (error) {\n cb(error, null, response);\n } else {\n cb(null, data, response);\n }\n }\n );\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the speed of the snai. Adds a random speed boost for a bit more variety. | setRandomSpeed() {
const rand = Math.random();
this.speed = rand > .5
? 1 + (rand / 2) // divide by two just so they don't get too far ahead
: 1;
} | [
"function setSpeed() {}",
"function setSpeed(\r\n speed_)\r\n {\r\n speed = speed_;\r\n }",
"set speedUS(speed) {\r\n this.speed = speed * 1.6;\r\n }",
"setSpeed() {\n var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;\n\n if (!this._lottie) {\n return;\n }\n\n this._lottie.setSpeed(value);\n }",
"setSpeed(speed) {\n this.speed = speed;\n }",
"setSpeed() {\n return Math.floor(Math.random() * 250) + 120;\n }",
"set SpeedUS(newSpeed){\n this.speed = newSpeed * 1.6\n }",
"setSimulationSpeed(speed) {\n this.speed = speed;\n }",
"function setSpeed(){\r\n speed = Math.random() * 4;\r\n}",
"setSpeed(value) {\n\t\tthis.moveSpeed = value;\n\t\tthis.speed = Math.round((6.66666666667 * GAME_SPEED) / this.moveSpeed);\n\t}",
"set speedMultiplier(value) {}",
"function setSpeed(asteroid, speed) {\n\tif (speed > 50000) {\n\t\tasteroid.className += ' speed-high';\n\t} else if (speed > 25000) {\n\t\tasteroid.className += ' speed-medium';\n\t} else {\n\t\tasteroid.className += ' speed-low';\n\t}\n\treturn asteroid;\n}",
"increaseSpeed() {\n\n this.speed = Math.max(this.speed - Snake.SPEED_INCREMENT, Snake.MAX_SPEED);\n\n }",
"setSpeed(speed) {\r\n this.lottieAnimation.setSpeed(speed);\r\n }",
"function setFastMovement() {\r\n setSpeed(stateConstants.SPEED.FAST);\r\n}",
"function setSpeed(speed_data){\r\n\tif(speed_data == 0)\r\n\t\tset_speed = 40;\r\n\telse if(speed_data == 1)\r\n\t\tset_speed = 25;\r\n\telse\r\n\t\tset_speed = 15;\r\n}",
"function setSlowMovement() {\r\n setSpeed(stateConstants.SPEED.SLOW);\r\n}",
"function setSpeed(speed){\n for (m in motors){\n ms.setMotorSpeed(motors[m], speed);\n }\n //currentSpeed = speed;\n console.log(\"Speed set to\" + speed);\n }",
"function setSpeed(speed) {\n\tif (song) {song.speed = speed;}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function to apply the sorting parameter by simply modifying the currentBrands object only the brands are needed because the products are displayed and rendered from this object only | function sort(typeOfSort, brands) {
if(typeOfSort=='price-asc'){
Object.keys(brands).forEach((brand, i) => {
brands[brand].sort(price_asc);
});}
else if (typeOfSort=='price-desc'){
Object.keys(brands).forEach((brand, i) => {
brands[brand].sort(price_desc);
});}
else if (typeOfSort=='date-asc'){
Object.keys(brands).forEach((brand, i) => {
brands[brand].sort(date_asc);
});}
else if (typeOfSort=='date-desc'){
Object.keys(brands).forEach((brand, i) => {
brands[brand].sort(date_desc);
});}
return brands;
} | [
"sortListByAvailability(){\n let productList = this.state.productList;\n productList.sort((a,b)=>{\n this.setState({\n sortPriceOrder:0,\n sortQuantityOrder:0\n });\n if(this.state.sortAvailabilityOrder === 1){\n this.setState({sortAvailabilityOrder:-1});\n return a.available - b.available;\n }\n else{\n this.setState({sortAvailabilityOrder:1});\n return b.available - a.available;\n }\n })\n }",
"function orderBy(sort_category)\n{\n //console.log('button was clicked!')\n let results = [];\n if(sort_category === 'name')\n {\n results = products.sort(function(a, b)\n {\n let title1 = a.title.toUpperCase();\n let title2 = b.title.toUpperCase();\n if(title1 < title2)\n {\n return -1;\n }\n if(title1 > title2)\n {\n return 1;\n }\n return 0;\n })\n }\n else if(sort_category === 'price-l')\n {\n results = products.sort(function(a, b)\n {\n return a.price - b.price;\n });\n }\n else//sort_category === price-h\n {\n results = products.sort(function(a, b)\n {\n return b.price - a.price;\n });\n}\n //console.log('rendering newly sorted products list...')\n renderList(results);\n}",
"sortProducts(sortingType = this.props.sorting) {\n if (sortingType === 'price_ascending') {\n return this.loadProductsBasedOnQuery().sort((a, b) => {\n return b.price - a.price;\n });\n } else {\n return this.loadProductsBasedOnQuery().sort((a, b) => {\n return a.price - b.price;\n });\n }\n }",
"function sortAllOfTheProductsAscendantlyBasedOnTheNewPrices() {\n\n}",
"function SortAssetModels() {\n brandId = $(\"#assetBrands option:selected\").val();\n typeId = $(\"#assetTypes option:selected\").val();\n //Updating the asset Model Dropdown\n if (brandId == \"\") {\n //Update Asset Model dropdown\n if (typeId == \"\") {\n $('.NormalModelSelectRow').each(function () {\n $(this).show();\n });\n }\n else {\n $('.NormalModelSelectRow').each(function (value) {\n var rowTypeId = $(this).attr(\"data-typeId\");\n if (rowTypeId == typeId) {\n $(this).show();\n }\n else {\n $(this).hide();\n }\n });\n }\n $('.assetModelsDropDown').trigger(\"chosen:updated\");\n }\n else {\n //If the Brand is selected, and the type isn't selected, show models with the brand\n if (typeId == \"\") {\n $('.NormalModelSelectRow').each(function () {\n var rowBrandId = $(this).attr(\"data-brandId\");\n if (rowBrandId == brandId) {\n $(this).show();\n }\n else {\n $(this).hide();\n }\n });\n $('.assetModelsDropDown').trigger(\"chosen:updated\");\n }\n else {\n //If both are selected, then show the models that apply to both\n $('.NormalModelSelectRow').each(function () {\n var rowBrandId = $(this).attr(\"data-brandId\");\n var rowTypeId = $(this).attr(\"data-typeId\");\n if (rowBrandId == brandId) {\n if (rowTypeId == typeId) {\n $(this).show();\n }\n else {\n $(this).hide();\n }\n }\n else {\n $(this).hide();\n }\n });\n $('.assetModelsDropDown').trigger(\"chosen:updated\");\n }\n }\n}",
"onSortSelection(e) {\n var sortBy = e.target.innerHTML;\n this.setState({sortBy});\n // sort products array\n var products = this.state.products;\n var toggleComparison = 1; // 1 for don't toggle, -1 for toggle\n if (sortBy === 'Featured') {\n var param = 'ordinal';\n } else if (sortBy === 'Name') {\n var param = 'name';\n } else if (sortBy === 'Price - low to high') {\n var param = 'defaultPriceInCents';\n } else if (sortBy === 'Price - high to low') {\n var param = 'defaultPriceInCents';\n toggleComparison = -1;\n } else if (sortBy === 'Newest') {\n var param = 'createdAt';\n toggleComparison = -1;\n };\n products.sort((a, b) => {\n if (a[param] < b[param]) {\n return -1 * toggleComparison; // toggle, if activated, just reverses the sign\n } else if (a[param] > b[param]) {\n return 1 * toggleComparison;\n }\n return 0;\n });\n this.setState({products});\n }",
"function sortByPrice() {\n\n if (document.getElementById('sort').value = 'price-high') {\n var priceFilter = products.sort(function(a,b) {\n return b.saleprice - a.saleprice;\n })\n } else if (document.getElementById('sort').value = 'price-low') {\n var priceFilter = products.sort(function(a,b) {\n return a.saleprice - b.saleprice;\n })\n } else {\n return 0;\n }\n\n renderProducts(priceFilter);\n}",
"function sortByPrice() { // i stole this from the module and idk\r\n window.books.sort((book1, book2) => {\r\n if (book1.price > book2.price) {\r\n return 1;\r\n } else if (book1.price < book2.price) {\r\n return -1;\r\n } else {\r\n return 0;\r\n }\r\n })\r\n render();\r\n}",
"function sorting() {\n let option = document.querySelector('.sort select').value;\n if (option === 'cheap') {\n sortedProducts.sort((a, b) => a.price - b.price);\n } else if (option === 'expensive') {\n sortedProducts.sort((a, b) => b.price - a.price);\n } else if (option === 'name') {\n sortedProducts.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));\n } else if (option === 'novalue') {\n console.log('Hi');\n console.log(products);\n\n sortedProducts = products;\n }\n renderProducts(sortedProducts);\n}",
"function sortByPrice() {\n // 1. Get list of Books & sort, save the sorted books array inside the library.\n myLibrary.books = myLibrary.sortByPrice();\n // 2. Display the result on the page. \n displayResult(myLibrary);\n }",
"function sortMarketListings(elem, isPrice, isDate, isName) {\n var list = getListFromContainer(elem);\n if (list == null) {\n console.log('Invalid parameter, could not find a list matching elem.');\n return;\n }\n\n // Change sort order (asc/desc).\n var nextSort = isPrice ? 1 : (isDate ? 2 : 3);\n var asc = true;\n\n // (Re)set the asc/desc arrows.\n const arrow_down = '🡻';\n const arrow_up = '🡹';\n\n $('.market_listing_table_header > span', elem).each(function() {\n if ($(this).hasClass('market_listing_edit_buttons'))\n return;\n\n if ($(this).text().includes(arrow_up))\n asc = false;\n\n $(this).text($(this).text().replace(' ' + arrow_down, '').replace(' ' + arrow_up, ''));\n })\n\n var market_listing_selector;\n if (isPrice) {\n market_listing_selector = $('.market_listing_table_header', elem).children().eq(1);\n } else if (isDate) {\n market_listing_selector = $('.market_listing_table_header', elem).children().eq(2);\n } else if (isName) {\n market_listing_selector = $('.market_listing_table_header', elem).children().eq(3);\n }\n market_listing_selector.text(market_listing_selector.text() + ' ' + (asc ? arrow_up : arrow_down));\n\n if (list.sort == null)\n return;\n\n if (isName) {\n list.sort('', {\n order: asc ? \"asc\" : \"desc\",\n sortFunction: function(a, b) {\n if (a.values().market_listing_game_name.toLowerCase()\n .localeCompare(b.values().market_listing_game_name.toLowerCase()) ==\n 0) {\n return a.values().market_listing_item_name_link.toLowerCase()\n .localeCompare(b.values().market_listing_item_name_link.toLowerCase());\n }\n return a.values().market_listing_game_name.toLowerCase()\n .localeCompare(b.values().market_listing_game_name.toLowerCase());\n }\n });\n } else if (isDate) {\n var currentMonth = DateTime.local().month;\n\n list.sort('market_listing_listed_date', {\n order: asc ? \"asc\" : \"desc\",\n sortFunction: function(a, b) {\n var firstDate = DateTime.fromString((a.values().market_listing_listed_date).trim(), 'd MMM');\n var secondDate = DateTime.fromString((b.values().market_listing_listed_date).trim(), 'd MMM');\n\n if (firstDate == null || secondDate == null) {\n return 0;\n }\n\n if (firstDate.month > currentMonth)\n firstDate = firstDate.plus({ years: -1});\n if (secondDate.month > currentMonth)\n secondDate = secondDate.plus({ years: -1});\n\n if (firstDate > secondDate)\n return 1;\n if (firstDate === secondDate)\n return 0;\n return -1;\n }\n })\n } else if (isPrice) {\n list.sort('market_listing_price', {\n order: asc ? \"asc\" : \"desc\",\n sortFunction: function(a, b) {\n var listingPriceA = $(a.values().market_listing_price).text();\n listingPriceA = listingPriceA.substr(0, listingPriceA.indexOf('('));\n listingPriceA = listingPriceA.replace('--', '00');\n\n var listingPriceB = $(b.values().market_listing_price).text();\n listingPriceB = listingPriceB.substr(0, listingPriceB.indexOf('('));\n listingPriceB = listingPriceB.replace('--', '00');\n\n var firstPrice = parseInt(replaceNonNumbers(listingPriceA));\n var secondPrice = parseInt(replaceNonNumbers(listingPriceB));\n\n return firstPrice - secondPrice;\n }\n })\n }\n }",
"sortListByQuantity(){\n let productList = this.state.productList;\n productList.sort((a,b)=> {\n this.setState({\n sortPriceOrder:0,\n sortAvailabilityOrder:0\n });\n if(this.state.sortQuantityOrder === 1){\n this.setState({sortQuantityOrder:-1});\n return a.quantity - b.quantity;\n }\n else{\n this.setState({sortQuantityOrder:1});\n return b.quantity - a.quantity;\n }\n })\n }",
"_sortGridItems() {\n \tlet element = $(\"#shuffle-sort option:selected\")[0],\n \t\treverse = element.getAttribute(\"data-reverse\") || false,\n options = { \n by: function(element) {\n \t\tlet res = element.getAttribute(\"data-sortby\");\n \t\treturn $.isNumeric(res) ? parseFloat(res) : res;\n }, \n reverse: reverse \n };\n \tthis.shuffle.sort(options);\n }",
"sortProductsByCategory(productSortCriteria){\n this.clearSearch();\n this.setState({productSortCriteria});\n }",
"function sortByHigh() {\n setWishlist(\n [...wishlist].sort((a, b) => {\n return Number(b.product.price) - Number(a.product.price);\n })\n );\n }",
"function sortByLow() {\n setWishlist(\n [...wishlist].sort((a, b) => {\n return Number(a.product.price) - Number(b.product.price);\n })\n );\n }",
"function setComparator() {\n // If the first three letters are \"asc\", sort in ascending order\n // and remove the prefix.\n if (by.substring(0,3) == 'asc') {\n var i = by.substring(3);\n comp = function(a, b) { return a[i] - b[i]; };\n } else {\n // Otherwise sort in descending order.\n comp = function(a, b) { return b[by] - a[by]; };\n }\n\n // Reset link styles and format the selected sort option.\n $('a.sel').attr('href', '#').removeClass('sel');\n $('a.by' + by).removeAttr('href').addClass('sel');\n }",
"_reSortGoods(){\n for (let i = 0; i < this._goods.length; i++){\n let j, element = this._goods[i];\n for (j = i - 1; 0 <= j; j--) {\n if (this._goods[j].getLowestCost() > element.getLowestCost()) break;\n this._goods[j + 1] = this._goods[j];\n }\n this._goods[j + 1] = element;\n }\n }",
"function sortRenderOrder() {\n \n var sortBy = function(field, reverse, primer){\n var key = primer ? function(x) {return primer(x[field])} : function(x) {return x[field]};\n reverse = [-1, 1][+!!reverse];\n return function (a, b) {\n\treturn a = key(a), b = key(b), reverse * ((a > b) - (b > a));\n } \n }\n \n gadgetRenderOrder.sort(sortBy(\"tabPos\", true, parseInt));\n gadgetRenderOrder.sort(sortBy(\"paneId\", true, parseInt));\n gadgetRenderOrder.sort(sortBy(\"parentColumnId\", true, parseInt));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
afficher la page Scene | RenderDeviceScenePage(){
// Clear view
this._DeviceConteneur.innerHTML = ""
// Clear Menu Button
this.ClearMenuButton()
// Add Back button in settings menu
NanoXAddMenuButtonSettings("Back", "Back", IconModule.Back(), this.RenderDeviceStartPage.bind(this))
// Conteneur
let Conteneur = NanoXBuild.DivFlexColumn("Conteneur", null, "width: 100%;")
// Titre
Conteneur.appendChild(NanoXBuild.DivText("Scenes", null, "Titre", null))
// Add all scenes
if (this._DeviceConfig != null){
if (this._DeviceConfig.Scenes.length != 0){
let SceneCount = 0
this._DeviceConfig.Scenes.forEach(Scene => {
Conteneur.appendChild(this.RenderButtonAction(Scene.Name, this.ClickOnScene.bind(this, Scene.Name, Scene.Sequence), this.ClickOnTreeDotsScene.bind(this, Scene, SceneCount)))
SceneCount ++
});
} else {
Conteneur.appendChild(NanoXBuild.DivText("No scene defined", null, "Text", ""))
}
}else {
// Add texte Get Config
Conteneur.appendChild(NanoXBuild.DivText("No configuration get from device", null, "Texte", "margin: 1rem;"))
}
// Div Button
let DivButton = NanoXBuild.DivFlexRowSpaceAround(null, "Largeur", "margin-top: 3rem;")
Conteneur.appendChild(DivButton)
// Button Add Scene
if (this._DeviceConfig != null){
DivButton.appendChild(NanoXBuild.Button("Add Scene", this.ClickOnAddScene.bind(this), "addscene", "Button Text WidthButton1", null))
}
// Button Back
DivButton.appendChild(NanoXBuild.Button("Back", this.RenderDeviceStartPage.bind(this), "Back", "Button Text WidthButton1", null))
// add conteneur to divapp
this._DeviceConteneur.appendChild(Conteneur)
// Espace vide
this._DeviceConteneur.appendChild(NanoXBuild.Div(null, null, "height: 2rem;"))
} | [
"loadScene() { }",
"function Scene() {}",
"displayScene() {\n // entry point for graph rendering\n var transformations = [];\n var materials = [];\n var textures = [];\n this.visitNode(this.components[this.root], transformations, materials, textures, false,0);\n\n }",
"function LoadChapter(){\n SceneManagement.SceneManager.LoadScene(\"chapters\");\n// Application.LoadLevel(name);\n}",
"displayScene() {\n this.processNode(this.idRoot);\n }",
"displayScene() {\n\n //Process all component nodes\n this.processNode(this.idRoot, null, null, 1, 1);\n }",
"scene (store, routerProps, routeState, page) {\n const { route } = routeState\n const { page: { combined } } = route\n const scene = page.content(combined, route.pass || {}, routerProps)\n const handlers = page.handlers(routerProps)\n const style = page.style(routerProps)\n\n return (\n <Navigation.Card\n {...routerProps}\n key={routeState.key}\n style={style}\n panHandlers={handlers}\n renderScene={() => scene}\n />\n )\n }",
"initializeScene(){}",
"function AppScene() {}",
"setupScene() {\n this.scene = new Scene();\n }",
"function displayNewScene() {\n\t\n\t//first Start of Page\n\tif (!particleSystem) {\n\t\tupdateArticleDiv(startText);\n\t\tinitParticles();\n\t\tupdateSkyBoxColor(bgColor);\n\t\tfadeIn(cssObject, true);\n\t\tfillScene();\n\t\treturn;\n\t}\n\n\t\n\t\n\tif (lastBgColor != bgColor) {\n\t\tchangeBgColor();\n\t}\n\t\n\tconsole.log(\"cssObject \" + cssObject);\n\t\n\t\n\tfadeOutIn(cssObject);\n\t\n\tfillScene();\n\t\n}",
"displayScene() {\n this.scene.pushMatrix()\n this.processNode(this.nodes[this.idRoot], this.nodes[this.idRoot].material, this.nodes[this.idRoot].texture, this.nodes[this.idRoot].animation)\n this.scene.popMatrix()\n }",
"ClickOnAddScene(){\n // Load add Scene Config\n this._Scene.RenderAddModScene(this._DeviceConteneur, this._DeviceConfig.Electrovannes)\n }",
"displayScene() {\n // entry point for graph rendering\n //TODO: Render loop starting at root of graph\n //console.log(this.nodes)\n this.components[this.idRoot].display();\n }",
"getStaticScene() {\n\n\t}",
"function init(){\n setPage(nodes[0].page);\n}",
"set AfterSceneLoad(value) {}",
"function setCurrentScene() {\n currentScene = scenes[sceneId];\n currentScene.showName();\n currentScene.showImage();\n currentSceneNode = story[currentScene.id].find(currentSceneNode => currentSceneNode.id === nodeId);\n actions = currentSceneNode.actions;\n}",
"function SceneLoader() {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ajoute le event handler de mouseover sur un polylineForHover. Le event handler gere l'apparition du polyline et de l'infoWindowItineraire. | function ajouterPolylineForHoverMouseoverEventHandler(polylineForHover, indice, description_depart, description_arrivee, idPaire, distance, vitesseMed, tempsParcours, carte)
{
//attribution de propriétés au polylineForHover, permet de changer les infos présentée dans l'infoWindowItineraire ailleurs dans le code suite à une mise a jour des données
polylineForHover.idPaire = idPaire;
polylineForHover.description_depart = description_depart;
polylineForHover.description_arrivee = description_arrivee;
polylineForHover.vitesseMed = vitesseMed;
polylineForHover.tempsParcours = tempsParcours;
var eventHandler = google.maps.event.addListener(polylineForHover, 'mouseover', function(event)
{
if ((polylineForHover.getMap() === carteReseau && checkboxElementArray[indice].querySelector("input").checked) || polylineForHover.getMap() !== carteReseau)
{
//si le tempsParcours = 0, c'est que le backend n'a renvoyé aucune donnée de temps pour cette paire
if (tempsParcours === 0 || tempsParcours === 'ND')
{
//les temps de parcours et la vitesse med sont indisponibles
tempsParcours = "ND";
vitesseMed = "ND";
}
//Afficher l'infoWindowItineraire à l'endroit du curseur de souris
polylineForHover.infoWindowContent = '<div id="infoWindowItineraire"><div class="infoWindow_titre">idPaire: ' + polylineForHover.idPaire + '</div><span class="infoWindow_desc">' + polylineForHover.description_depart + '<img src="../../images/fleche.png" class="imgFlecheInfoWindow">' + polylineForHover.description_arrivee + '</span>' + '<div class="infoWindow_desc">Distance: ' + distance + '</div><div class="infoWindow_desc">Vitesse médiane: ' + polylineForHover.vitesseMed + '</div><div class="infoWindow_desc">Temps parcours: ' + polylineForHover.tempsParcours + '</div>';
infoWindowItineraire.setContent(polylineForHover.infoWindowContent);
infoWindowItineraire.setPosition(event.latLng);
infoWindowItineraire.open(carte);
polylineForHover.setOptions(
{
//Rendre le polyline visible
strokeOpacity: 0.6,
});
polylineForHover.setMap(carte);//Sert a réafficher le polyline avec les nouvelles options
//dans le cas de la carteReseau, gérer le checkbox correspondant à l'itinéraire
if (carte === carteReseau)
{
//Rendre le checkbox correpondant au polyline en caractere gras
document.querySelectorAll('.checkboxDiv')[indice].style.fontWeight = "bold";
}
}
});
return eventHandler;
} | [
"function onPolylineMouseOver(e) {\n\tvar tooltipContent = \"\";\n\tthis.setOptions(onPolylineHoverColorOptions);\n\tif (this.linkColor != \"undefined\") {\n\t\tthis.icons[0].icon.fillColor = this.linkColor;\n\t}\n\ttooltipContent = \"<span>\" + this.linkName + \"</span><hr>number of records: \" + this.numberOfRecords;\n\ttooltipContent += \"<br>approx. median travel-time: \" + this.medianTtString;\n\ttooltipContent += \"<br>approx. median speed (mph): \" + this.medianSpeedMph;\n\ttooltipContent += \"<br>median record timestamp: \" + moment(this.medianTtDatetime).format(\"M-DD-YY h:mm:ss a\");\n\ttooltipContent += \"<br>segment length: \" + this.linkLength + \" meters (\" + (this.linkLength * 3.2808).toFixed(2) + \" ft)\";\n\ttooltipContent += \"<br>segment ID \" + this.sid;\n\ttooltipContent += \"<br>segment points: \" + this.lid0 + \" to \" + this.lid1;\n\tlinkToolTip.setContent(tooltipContent);\n\t//here e is the overlay object and whenever we hover over the overlay we can get the coords to use with our infobox tooltip\n\tlinkToolTip.setPosition(e.latLng);\n\tlinkToolTip.open(map);\n}",
"function ajouterPolylineForHoverMouseoutEventHandler(polylineForHover, carte, indice, persistent)\n {\n //le paramètre persistent est facultatif et false par défaut (lorsque true, il permet d'afficher les polylineForHover de manière permanente lors de la consultation des itinéraires prédéfinis)\n if (persistent === undefined)\n {\n persistent = false;\n }\n //Mouseout = rend le polyline invisible\n var eventHandler = google.maps.event.addListener(polylineForHover, 'mouseout', function()\n {\n //si le polylineForHover n'est pas persistent\n if (!persistent)\n {\n polylineForHover.setOptions(\n {\n //Rendre le polyline à nouveau invisible \n strokeOpacity: 0\n });\n polylineForHover.setMap(carte);//Sert a réafficher le polyline avec les nouvelles options\n }\n \n //dans le cas de la carteReseau, gérer le checkbox correspondant à l'itinéraire\n if (carte === carteReseau)\n {\n //Rendre le checkbox correpondant au polyline sans caractere gras\n document.querySelectorAll('.checkboxDiv')[indice].style.fontWeight = \"\";\n }\n\n //Fermer l'infoWindowItineraire\n infoWindowItineraire.close();\n });\n return eventHandler;\n }",
"function onTranscomPolylineMouseOver(e) {\n\tvar tooltipContent = \"\";\n\tthis.setOptions(onPolylineHoverColorOptions);\n\tif (this.icons != null) {\n\t\tthis.icons[0].icon.scale = 3;\n\t}\n\ttooltipContent = \"<span><b>\" + this.linkName + \"</b></span><hr>\";\n\ttooltipContent += \"<br>segment ID: \" + this.id;\n\ttooltipContent += \"<br>number of records: \" + this.VehiclesInSample;\n\ttooltipContent += \"<br>new matches in sample period: \" + this.NewMatchesInSamplePeriod;\n\ttooltipContent += \"<br>link readers status: \" + this.readersStatus;\n\ttooltipContent += \"<br>link status: \" + this.SystemStatus;\n\ttooltipContent += \"<br>approx. travel-time: \" + this.currTtSec + \" seconds\";\n\ttooltipContent += \"<br>approx. speed: \" + this.speedMph + \"(MPH)\";\n\ttooltipContent += \"<br>record timestamp: \" + this.recordTimeStamp;\n\ttooltipContent += \"<br>segment length: \" + this.linkLength + \" meters (\" + (this.linkLength * 3.2808).toFixed(2) + \" ft)\";\n\ttooltipContent += \"<br>confidence level: \" + this.ConfidenceLevel;\n\ttooltipContent += \"<br>Synthetic Link: \" + this.FromSyntheticSegment;\n\n\tlinkToolTip.setContent(tooltipContent);\n\t//here e is the overlay object and whenever we hover over the overlay we can get the coords to use with our infobox tooltip\n\tlinkToolTip.setPosition(e.latLng);\n\tlinkToolTip.open(map);\n}",
"function addMouseOverToLayer(layer) {\n var marker = window[layer];\n\n marker.on('mouseover', function(e){\n var marker = e.target;\n var markerPos = marker.getLatLng();\n jscallback.registerWaypoint(layer, markerPos.lat, markerPos.lng);\n });\n marker.on('mouseout', function(e){\n var marker = e.target;\n var markerPos = marker.getLatLng();\n jscallback.deregisterWaypoint(layer, markerPos.lat, markerPos.lng);\n });\n}",
"function addMouseoverOaEvent(map) {\n map.data.addListener('mouseover', function(e) {\n let feat = e.feature\n map.data.revertStyle();\n\n // Apply hovering style.\n if (feat[\"state_clicked\"] !== undefined && feat[\"state_clicked\"] === \"on\") {\n map.data.overrideStyle(feat, style_hover_clicked);\n } else {\n map.data.overrideStyle(feat, style_hover);\n }\n\n feat[\"state\"] = \"hover\";\n\n let key = feat.getProperty(\"geo_code\");\n let value = \"undenfined\"\n\n // Update the value indicator in the continuous legend. No defined action for the categorical legend.\n if (SELECTED_DATASET !== \"none\" && SELECTED_COLUMN !== \"blank\") {\n let feat_dataset = feat.getProperty(SELECTED_DATASET)\n key = feat_dataset['OA'];\n value = feat_dataset[SELECTED_COLUMN].toLocaleString();\n\n let dom = SCALES_MAP.get(SELECTED_DATASET).get(SELECTED_COLUMN).domain()\n\n if (typeof(dom[0]) === \"string\") {\n // Maybe highlight OAs of the same category.\n } else {\n let legend_body = document.getElementById(\"legend\");\n legend_body.innerHTML = \"\"\n\n let min_div = document.createElement(\"div\")\n min_div.id = \"census-min\"\n min_div.classList.add(\"legend_text\")\n min_div.textContent = \"min\"\n legend_body.appendChild(min_div)\n\n let color_key_div = document.createElement(\"div\")\n color_key_div.classList.add(\"color-key\")\n const span = document.createElement(\"span\")\n span.id = \"data-caret\"\n span.classList.add(\"legend_text\")\n span.textContent = \"◆\"\n color_key_div.appendChild(span)\n legend_body.appendChild(color_key_div)\n\n let max_div = document.createElement(\"div\")\n max_div.id = \"census-max\"\n max_div.classList.add(\"legend_text\")\n max_div.textContent = \"max\"\n legend_body.appendChild(max_div)\n\n // Update continuous legend's min and max with the new selected column\n let min_value = (dom[0]).toFixed(3)\n let max_value = (dom[dom.length - 1]).toFixed(3)\n\n document.getElementById('census-min').textContent = min_value;\n document.getElementById('census-max').textContent = max_value;\n let percent = (feat_dataset[SELECTED_COLUMN] - min_value) / (max_value - min_value) * 100;\n document.getElementById('data-caret').style.paddingLeft = percent + '%';\n }\n }\n\n document.getElementById('data-label').textContent = key;\n document.getElementById('data-value').textContent = value;\n });\n}",
"static polygonLiHoverHandler(client, hov) {\n return (event) => {\n let polygonCollection = client.polygonCollection;\n const id = event.target.getAttribute('data-id');\n const className = polygonCollection.getClassFromId(id);\n polygonCollection.changePolygonStyle(id, hov ?\n polygonCollection.polygonHoverStyle : polygonCollection.styles[className]);\n };\n }",
"function onPolylineMouseClick(e) {\n\t//this is the actual polyline object\n\tshowChart(this);\n}",
"function showTooltip_onMouseOver(){\n//----------------------------------------------------------------------------------------------------------------------------\t\n\n\n this.dispalyTooltips = function(toolz){ //args(tooplips array)\n // request mousemove events\n $(\"#graph\").mousemove(function (e) {\n\t\t var onMouseOver_file = new onMouseOver();//uses other module in this very file\n onMouseOver_file.handleMouseMoveAction(e, toolz); //args(mouse event, tooplips array)\n });\n\n } \n}",
"setCursorStyleOnHover() {\n this.mapRef.on('mouseenter', 'points', (e) => {\n this.mapRef.getCanvas().style.cursor = 'pointer';\n const eventIds = e.features.map(feature =>\n feature.properties.id)\n .reverse();\n store.commit('eventHovered', eventIds);\n });\n\n this.mapRef.on('mouseleave', 'points', (e) => {\n this.mapRef.getCanvas().style.cursor = '';\n });\n }",
"function mouseOverGraphic(ev) {\n map.setMapCursor(\"crosshair\");\n}",
"addTooltipEvent() {\n this.tooltips.forEach((tooltip) => {\n tooltip.addEventListener(\"mouseover\", this.onMouseOver);\n });\n }",
"function mapHoverHandler(eventObject) {\n console.log('event object', eventObject);\n cosnole.log('mouse lat/lng', evenObject.latlng)\n //update mouse coordinates HTML element with event latlng\n \n document.getElementById(\"mouseCoordinatesBox\").innerHTML=\"newtext\";\n \n \n}",
"onMouseOver(event) {\n // cria a tooltip box e coloca em uma propriedade\n this.criarTolltipBox(event.currentTarget);\n event.currentTarget.addEventListener(\"mouseleave\", this.onMouseLeave);\n event.currentTarget.addEventListener(\"mousemove\", this.onMouseMove);\n }",
"function mouseoverTrainLine() {\n var lineID = d3.select(this).attr(\"id\");\n\n var circleID = lineID.replace(\"line\", \"circle\");\n var circle = d3.select(\"#\" + circleID);\n\n if ((popupOpen && circleID != currentCircleID) || editting)\n return;\n\n console.log(\"MOUSE OVER LINE\");\n d3.select(this).style(\"cursor\", \"pointer\");\n\n currentCircleID = circleID;\n currentCircle = circle;\n\n currentCircle\n .transition().duration(200)\n .style(\"cursor\", \"pointer\")\n .attr(\"r\", trainCircleFocusedR * (1 / currentScale));\n\n defineChangesFromLine(circleID);\n\n popupOpen = true;\n\n updatePopupCircleSize(currentCircle);\n updatePopupCircleContent();\n}",
"function onPolylineMouseOut(e) {\n\tthis.setOptions(defaultPolylineColorOptions);\n\tif (this.icons != null) {\n\t\tthis.icons[0].icon.scale = 2;\n\t}\n\tlinkToolTip.close();\n}",
"addTooltipsEvent() {\n this.tooltips.forEach((item) => {\n item.addEventListener('mouseover', this.onMouseOver);\n });\n }",
"function markerMouseoverCallback(event) {\n document.getElementById(\"bottom-left-coordinates-lat\").innerHTML = $.i18n('coordinates-hover-container-latitude') + \": \" + parseFloat(event.feature.getProperty(\"Latitud\").toFixed(4)) + \"°\";\n document.getElementById(\"bottom-left-coordinates-lng\").innerHTML = $.i18n('coordinates-hover-container-longitude') + \": \" + parseFloat(event.feature.getProperty(\"Longitud\").toFixed(4)) + \"°\";\n fadeInElements([\"map-bottom-left-container\"], 350);\n}",
"handleHoverInEvent (e) {\n console.log('handleHoverInEvent')\n this.highlight()\n this.emit('hoverin')\n dispatchWindowEvent('annotationHoverIn', this)\n }",
"function polyMouseover (event, path) {\n\tpath.setOptions({\n\t\tstrokeOpacity: 1.0,\n \tstrokeWeight: 4\n\t});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes and prepares to introduce the game, and initializes the uow audio element | function init()
{
canvas = document.getElementById('canvas');
context2D = canvas.getContext('2d');
uow.getAudio().then(function(a)
{
audio=a;
dojo.publish('/org/hark/prefs/request');
introduceGame();
});
} | [
"function audioSetUp() {\n bgOST = new Howl({\n src: ['static/sounds/OST/FastDrawing.mp3'],\n autoplay: false,\n loop: true,\n volume: 0.5\n });\n\n}",
"function setupAudio() {\n audioEating = loadSound('assets/sounds/eating.wav');\n audioHurt = loadSound('assets/sounds/hurt.wav');\n audioTeleport = loadSound('assets/sounds/teleport.wav');\n audioCanTeleport = loadSound('assets/sounds/canTeleport.wav');\n audioGameOver = loadSound('assets/sounds/gameOver.wav');\n audioEaten = loadSound('assets/sounds/die.wav');\n}",
"init () {\n this.setSource();\n this.setup();\n this.addSound();\n }",
"initSound() {\n this.enemyDyingSound = this.level.game.add.audio('enemy_dying');\n this.playerHitSound = this.level.game.add.audio('player_hit');\n this.itemCollectSound = this.level.game.add.audio('item_collect');\n this.itemDropoffSound = this.level.game.add.audio('item_dropoff');\n this.advanceLevelSound = this.level.game.add.audio('advance_level');\n this.playerDyingSound = this.level.game.add.audio('player_dying');\n this.music = this.level.game.add.audio('music');\n this.music.volume = .4;\n }",
"function audioSetup()\n{\n if( script.audioTrack && !audioComponent )\n { \n audioComponent = script.getSceneObject().createComponent(\"Component.AudioComponent\");\n audioComponent.audioTrack = script.audioTrack;\n }\n else\n {\n print( \"Soundboard: \" + script.getSceneObject().name + \" - Audio resource not set. Please add in the Inspector\")\n }\n}",
"function initializeAudio() {\n\n\t\t// generate audio player with randomly selected audio clip\n\t\t$('#random_song').html('<audio controls><source src=\"audio/' + series[random] + '.mp3\" type=\"audio/mpeg\">Unfortunately, it appears that your browser does not support the audio playback element.</audio>');\n\n\t} // end audio initialization function",
"function audioSetup()\n{\n if(script.followAudio && !audioComponentFollow)\n { \n audioComponentFollow = script.getSceneObject().createComponent(\"Component.AudioComponent\");\n audioComponentFollow.audioTrack = script.followAudio;\n } \n \n if(script.arriveAudio && !audioComponentArrive)\n { \n audioComponentArrive = script.getSceneObject().createComponent(\"Component.AudioComponent\");\n audioComponentArrive.audioTrack = script.arriveAudio;\n } \n\n if(script.pathDrawAudio && !audioComponentPathDraw)\n { \n audioComponentPathDraw = script.getSceneObject().createComponent(\"Component.AudioComponent\");\n audioComponentPathDraw.audioTrack = script.pathDrawAudio;\n } \n}",
"function audioSetup() {\n if (script.tapAnimAudio && !audioComponentTap) {\n audioComponentTap = script.getSceneObject().createComponent(\"Component.AudioComponent\");\n audioComponentTap.audioTrack = script.tapAnimAudio;\n }\n}",
"function initGameMusic(){\n musicTheme = new THREE.AudioListener();\n scene.add( musicTheme );\n\n var sound = new THREE.Audio( musicTheme );\n // global audio source\n if (gameState.scene=='start') {\n var audloader = new THREE.AudioLoader();\n audloader.load( 'libs/sounds/MainThemeV2.m4a', function(buffer){\n sound.setBuffer( buffer );\n sound.setLoop( true );\n sound.setVolume( 1 );\n sound.play();\n });\n } else if (gameState.scene=='bossState'){\n var audloader1 = new THREE.AudioLoader();\n audloader1.load( 'libs/sounds/BossThemeV1.m4a', function(buffer){\n sound.setBuffer( buffer );\n sound.setLoop( true );\n sound.setVolume( 1 );\n sound.play();\n });\n } else if (gameState.scene=='main'){\n var audloader2 = new THREE.AudioLoader();\n audloader2.load( 'libs/sounds/MainThemeV2.m4a', function(buffer){\n sound.setBuffer( buffer );\n sound.setLoop( true );\n sound.setVolume( 1 );\n sound.play();\n });\n }\n }",
"static initialize() {\n if (Audio.sounds == null) {\n Audio.sounds = {};\n Audio.sounds[Sounds.PLOP] = new howler_1.Howl({\n // mp3 is public domain, downloaded from\n // http://soundbible.com/2067-Blop.html\n src: [\"sounds/Blop-Mark_DiAngelo-79054334.mp3\"],\n volume: 0.1,\n });\n }\n }",
"function init () {\n window.AudioContext = window.AudioContext || window.webkitAudioContext;\n context = new AudioContext();\n\n bufferLoader = new BufferLoader(\n context, \n [\n \"https://whitebrandon.github.io/audio/sounds/correct_letter.wav\",\n \"https://whitebrandon.github.io/audio/sounds/wrong_letter.wav\",\n \"https://whitebrandon.github.io/audio/sounds/game_lost.wav\",\n \"https://whitebrandon.github.io/audio/sounds/game_won.wav\",\n \"https://whitebrandon.github.io/audio/sounds/keypress.wav\",\n ], \n finishedLoading\n );\n \n bufferLoader.load()\n }",
"function initiateAudioSprite() {\n audioSprite = new Audio();\n audioSprite.src = PIECE.AUDIO_SPRITE_URL;\n\n // Tell mute.js what audio sprite file will be played\n sr.setPlayingAudio(audioSprite);\n}",
"makeAudio() {\n sfx.absorb = this.sound.add('absorb');\n sfx.bullet = this.sound.add('bullet');\n sfx.extend = this.sound.add('extend');\n sfx.gameover = this.sound.add('gameover');\n sfx.levelup = this.sound.add('levelup');\n sfx.laser = this.sound.add('laser');\n sfx.lose = this.sound.add('lose');\n sfx.move = this.sound.add('move');\n sfx.ready = this.sound.add('ready');\n }",
"function setUpGame() {\n createDivGrid();\n var bgAudioTag = new Audio('./media/background.mp3');\n bgAudioTag.loop = true;\n bgAudioTag.volume = .15;\n bgAudioTag.play();\n}",
"_initAudioComponents() {}",
"function init() {\n //Shorthand state\n s = app.state;\n sa = app.state.audio;\n\n //Initialize audio context and nodes\n createAudioContext();\n\n //Set the volume\n sa.nodes.gainNode.gain.value = s.e.DEFAULT_VOLUME;\n\n //Play the first song\n playNewAudio(s.e.DEFAULT_SONG);\n }",
"constructor(selector= '.audioPlayer', audio=[]){\n //ref where player Elm is on page\n this.playerElm = document.querySelector(selector); \n //list of songs\n this.audio=audio;\n //song playing\n this.currentAudio=null;\n //creates HTML elements for audio player\n this.createPlayerElement();\n this.audioContext=null;\n }",
"function audioInit() {\n $( 'audio' ).audioPlayer();\n}",
"createAudio() {\n this.audios = {};\n this.audios.running = this.sound.add('running', { loop: true });\n this.audios.harvest = this.sound.add('harvest', {volume: 0.5});\n this.audios.dig = this.sound.add('dig', {volume: 0.4});\n this.audios.sell = this.sound.add('sell', {volume: 0.5});\n this.audios.ocean = this.sound.add('ocean_waves', { loop: true });\n \n this.audios.questionSFX = this.sound.add('question_sfx', {volume: 0.7});\n this.audios.surprisedSFX = this.sound.add('surprised_sfx', {volume: 0.3});\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get specific plugin details API | function getSpecificPluginDetails(plugin_id) {
developer.Api('/plugins/' + plugin_id + '.json', 'GET', [], [], function (e) {
logResponse(e, developer);
});
} | [
"function getAllPluginDetails() {\n developer.Api('/plugins.json', 'GET', [], [], function (e) {\n logResponse(e, developer);\n });\n}",
"getpluginWithID(req, res) {\n plugin.findById(req.params.pluginId, (err, plugin) => {\n if (err) {\n res.send(err);\n }\n res.json(plugin);\n });\n }",
"getPluginLicenseInfo() {\n return axios.get(Craft.getActionUrl('app/get-plugin-license-info'))\n }",
"function requestPluginsData() {\n chrome.send('requestPluginsData');\n chrome.send('getShowDetails');\n}",
"function fetchPluginApiReference(plugin) {\n return axios\n .get(`https://pub.dartlang.org/documentation/${plugin}/latest/index.json`)\n .then(response => {\n if (response.headers['content-type'] === 'application/json') {\n return response.data.map(entity => ({\n ...entity,\n plugin,\n }));\n }\n\n return null;\n });\n}",
"getPlugin(name) {\n const guildData = this.knub.getGuildData(this.guildId);\n return guildData.loadedPlugins.get(name);\n }",
"getPluginById(pluginId) {\n return this.room._plugins[pluginId];\n }",
"function processInfo(id, sendResponse) {\n let plugin = library[\"plugins\"][id]\n let infopath = plugin.info\n let url = chrome.runtime.getURL(\"library/info/\"+plugin.namespace+\".\"+infopath)\n fetch(url)\n .then(response => response.text())\n .then(data => {\n sendResponse({status: 1, data: sanitizeResponse(data)})\n })\n}",
"function fetchPluginApiReference(plugin, version = 'latest') {\n return axios\n .get(`https://pub.dev/documentation/${plugin}/${version}/index.json`, {\n maxRedirects: 0,\n })\n .then(response => {\n if (response.headers['content-type'] === 'application/json') {\n return response.data.map(entity => ({\n ...entity,\n version,\n plugin,\n }));\n }\n\n return null;\n })\n .catch(() => {\n return null;\n });\n}",
"function getPlugin() {\n var plugin = fs.readFileSync('./plugin.json', 'utf8');\n return JSON.parse(plugin, 'utf8');\n}",
"function getPluginsAndUser(cb) {\n $.getJSON('cli', function (data, success, xhr) {\n if (xhr.status != 200 || !data) return cb(new Error('got status code:' + xhr.status + '; response:' + xhr.responseText));\n return cb(null, data);\n })\n .error(function (xhr) {\n return new Error('error: status code:' + xhr.status + ' status text:' + xhr.statusText + ' response text:' + xhr.responseText);\n }); \n }",
"function getPlugin(name) {\n\t\treturn plugins[name];\n\t}",
"function getPluginSettings(name, type){\n return XNAT.spawner.resolve(name + '/' + type);\n }",
"getPluginLicenseInfo() {\n return new Promise((resolve, reject) => {\n Craft.sendApiRequest('GET', 'cms-licenses', {\n params: {\n include: 'plugins',\n },\n })\n .then(function(response) {\n _axios.post(Craft.getActionUrl('app/get-plugin-license-info'), {\n pluginLicenses: response.license.pluginLicenses || [],\n }, {\n headers: {\n 'X-CSRF-Token': Craft.csrfTokenValue,\n }\n })\n .then((response) => {\n resolve(response)\n })\n .catch((error) => {\n if (axios.isCancel(error)) {\n // request cancelled\n } else {\n reject(error)\n }\n })\n })\n })\n }",
"getDatavisualPlugins(params) {\n return axios({\n method: 'get',\n url: 'v1/mindinsight/datavisual/plugins',\n params: params,\n });\n }",
"getPluginData(name) {\r\n const data = this._plugins\r\n .map(p => (Array.isArray(p.data) ? p.data : [p.data]))\r\n .reduce((acc, arr) => [...acc, ...arr], []);\r\n return name ? data.filter((d) => d.name === name) : data;\r\n }",
"function getPlugin(id) {\n return plugins[id] || null;\n}",
"getPlugin(name) {\n return (this.#plugins.get(name)) || null;\n }",
"plugin(plugin) {\n for (let inst of this.plugins) if (inst.spec == plugin) return inst.value;\n\n return null;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks for script updates. | function updateCheck()
{
var scriptNum = 27776;
//Only check for update if using Greasemonkey and no check has been made in the last day.
if( !MS_getValue('checked_update') )
{
MS_setValue( 'checked_update', true, 24*3600 );
GM_xmlhttpRequest(
{
method: 'GET',
url: 'http://userscripts.org/scripts/source/'+scriptNum+'.meta.js?'+new Date().getTime(),
headers: { 'Cache-Control': 'no-cache' },
onload: function(response)
{
var localVersion = parseInt( GM_getValue( 'local_version', 0 ) );
var remoteVersion = parseInt( /@uso:version\s*([0-9]+?)\s*$/m.exec(response.responseText)[1] );
if( !localVersion || remoteVersion <= localVersion )
GM_setValue( 'local_version', remoteVersion );
else if( confirm( 'There is an update available for the Greasemonkey script "'+/@name\s*(.*?)\s*$/m.exec(response.responseText)[1]+'".\nWould you like to go to the install page now?' ) )
{
GM_openInTab( 'http://userscripts.org/scripts/show/'+scriptNum );
GM_setValue( 'local_version', remoteVersion );
}
},
});
}
} | [
"function scriptUpdateCheck() {\r\n\tif (Date.now() - scriptLastCheck >= 86400000) { // 86400000 == 1 day\r\n\t\t// At least a day has passed since the last check. Sends a request to check for a new script version\r\n\t\tGM_setValue(\"scriptLastCheck\", Date.now().toString());\r\n\t\tscriptCheckVersion();\r\n\t}\r\n\telse {\r\n\t\t// If a new version was previously detected the notice will be shown to the user\r\n\t\t// This is to prevent that the notice will only be shown once a day (when an update check is scheduled)\r\n\t\tif (scriptLastRemoteVersion > scriptVersion) {\r\n\t\t\tscriptShowUpdateMessage(true, scriptLastRemoteVersion);\r\n\t\t}\r\n\t}\r\n}",
"function checkUpdates() {\n\tGitCUpdate.files([ 'package.json' ], (err, results)=> {\n\t\tif (err) return;\n\t\tresults.forEach(file=> {\n\t\t\tlet c = file.contents.toString();\n\t\t\tif (c[0] === \"{\") {\n\t\t\t\tlet data = JSON.parse(c);\n\t\t\t\t\n\t\t\t\tlet msg = (data.version > pJson.version)? \"Доступно обновление! -> github.com/xTCry/VCoin \\t[\"+(data.version +\"/\"+ pJson.version)+\"]\":\n\t\t\t\t\t\t\t// (data.version != pJson.version)? \"Версии различаются! Проверить -> github.com/xTCry/VCoin \\t[\"+(data.version +\"/\"+ pJson.version)+\"]\":\n\t\t\t\t\t\t\tfalse;\n\t\t\t\tif(msg) {\n\t\t\t\t\tif(onUpdatesCB) onUpdatesCB(msg);\n\t\t\t\t\telse con(msg, \"white\", \"Red\");\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t});\n}",
"function CheckForUpdate() {\r\n // create and format actual date\r\n var today = new Date();\r\n var tagesdatum = FormatDate(today);\r\n\r\n // if not searched for a new version of the script today\r\n if (GM_getValue(\"LastUpdateCheck\",\"\") != tagesdatum) {\r\n // load the script page on userscripts.org\r\n GM_xmlhttpRequest({\r\n method: 'GET', \r\n url: THISSCRIPTINSTALL_URL, \r\n onload: function(responseDetails) {\r\n var content = responseDetails.responseText;\r\n \r\n // find the script version\r\n var scriptversion = content.split(\"<b>Version:</b>\")[1];\r\n var scriptfullversion = trimString(scriptversion.split(\"</p\")[0]);\r\n scriptversion = trimString(scriptversion.split(\"</p\")[0]).split(\" \")[0];\r\n \r\n // if there is a new version of the script\r\n if (scriptversion != THISSCRIPTVERSION) {\r\n // build the message\r\n var alerttext = \"Es gibt eine neue Version des Skriptes '\" + THISSCRIPTNAME + \"':\\n\\n\" + scriptfullversion + \"\\n\\nDie neue Version kann Fehlerbehebungen und/oder neue Funktionen beinhalten.\\nHier gibt es weitere Infos über die neue Version:\\n\\n\" + THISSCRIPTINSTALL_URL + \"\\n\\nEine Aktualisierung ist empfehlenswert und kann direkt anschließend durchgeführt werden.\\n\\nHinweis: Die überprüfung auf neue Versionen wird nur einmal pro Tag durchgeführt.\"\r\n\r\n // display the message\r\n alert(alerttext);\r\n // load the page with the new script for installation\r\n window.location.href = THISSCRIPTSOURCE_URL;\r\n }\r\n }\r\n });\r\n\r\n // memorize the new date\r\n GM_setValue(\"LastUpdateCheck\", tagesdatum)\r\n }\r\n}",
"function checkForUpdate()\r\n\t\t\t{\r\n\t\t\t\tappUpdater.checkNow();\r\n\t\t\t}",
"function manuallyCheckForUpdate() {\r\n\tcheckForUpdate(true);\r\n} //End manual update check",
"function checkForUpdates() {\n logger.success('Ionic Deploy: Checking for updates');\n $ionicDeploy.check().then(function(hasUpdate) {\n logger.success('Ionic Deploy: Update available: ' + hasUpdate);\n vm.hasUpdate = hasUpdate;\n }, function(err) {\n logger.error('Ionic Deploy: Unable to check for updates', err);\n });\n }",
"function checkUpdate() {\n\tif(file_date(serviceIniFile) > serviceIniFileDate)\n\t\texit(0);\n}",
"function checkUpdate () {\n var pkg = require(\"./package.json\");\n require(\"update-notifier\")({\n packageName: pkg.name,\n packageVersion: pkg.version\n }).notify();\n}",
"function cn_ubb_enhanceUpdateCheck() {\n\tif (typeof GM_xmlhttpRequest != 'function') {\n\t\treturn;\n\t}\n\tvar version = GM_getValue('version', '');\n\tvar lastChecked = GM_getValue('update.last', 0);\n\tvar now = parseInt(new Date() / 1000, 10);\n\t// Check every 1 days.\n\tvar interval = 60 * 60 * 24 * 1;\n\tif (lastChecked - now < -interval) {\n\t\t// Whatever happens to this request, remember that we tried.\n\t\tGM_setValue('update.last', now);\n\t\tGM_xmlhttpRequest({\n\t\t\tmethod: 'GET',\n\t\t\turl: 'http://shutterfreak.net/xtra/greasemonkey/cn_ubb_enhance/cn_ubb_enhance.user.js',\n\t\t\tonload: function (responseDetails) {\n\t\t\t\tif (responseDetails.status == 200) {\n\t\t\t\t\tvar newversion = responseDetails.responseText.match(/\\$Id.+\\$/)[0];\n\t\t\t\t\tif (newversion == version) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tvar doUpdate = window.confirm('A new version of cn_ubb_enhance is available.\\nCurrent version: '+version+'\\nNew version: '+newversion+'\\nShall we update?');\n\t\t\t\t\tif (doUpdate) {\n\t\t\t\t\t\twindow.open('http://shutterfreak.net/xtra/greasemonkey/cn_ubb_enhance/cn_ubb_enhance.user.js', 'dreditor');\n\t\t\t\t\t\t// Let's just assume that we DID update. ;)\n\t\t\t\t\t\tGM_setValue('version', newversion);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}",
"function updateScript() {\r\n try {\r\n if (!GM_getValue) {\r\n return;\r\n }\r\n GM_xmlhttpRequest({\r\n method: 'GET',\r\n url: SCRIPT.url + '?source', // don't increase the 'installed' count; just for checking\r\n onload: function(result) {\r\n if (result.status != 200) {\r\n return;\r\n }\r\n if (!result.responseText.match(/build:\\s+'(\\d+)/)) return;\r\n var theOtherBuild = parseInt(RegExp.$1);\r\n var runningBuild = parseInt(SCRIPT.build);\r\n var theOtherVersion = result.responseText.match(/@version\\s+([\\d.]+)/)? RegExp.$1 : '';\r\n if (theOtherBuild < runningBuild) {\r\n if (window.confirm('You have a beta version (build ' + runningBuild + ') \r\n\r\ninstalled.\\n\\nDo you want to DOWNGRADE to the most recent official release (version ' + \r\n\r\ntheOtherVersion + ')?\\n')) {\r\n //clearSettings();\r\n window.location.href = SCRIPT.url;\r\n }\r\n return;\r\n } else if (theOtherBuild > runningBuild ||\r\n theOtherVersion != SCRIPT.version) {\r\n if (window.confirm('Version ' + theOtherVersion + ' is available!\\n\\n' + 'Do you want \r\n\r\nto upgrade?' + '\\n')) {\r\n //clearSettings();\r\n window.location.href = SCRIPT.url;\r\n }\r\n } else {\r\n alert('You already have the latest version.');\r\n return;\r\n }\r\n }\r\n });\r\n } catch (ex) {\r\n addToLog('warning Icon', ex);\r\n } \r\n}",
"function updateScript() {\r\n try {\r\n if (!GM_getValue) return;\r\n GM_xmlhttpRequest({\r\n method: 'GET',\r\n url: SCRIPT.url + '?source', // don't increase the 'installed' count; just for checking\r\n onload: function(result) {\r\n if (result.status != 200) return;\r\n if (!result.responseText.match(/@version\\s+([\\d.]+)/)) return;\r\n var theOtherVersion = RegExp.$1;\r\n if (theOtherVersion == SCRIPT.version) {\r\n alert('you have the latest version' + ' (v ' + SCRIPT.version + ') !');\r\n return;\r\n } else if (theOtherVersion < SCRIPT.version) {\r\n alert('Beta version' + ' (v ' + SCRIPT.version + ') installed ?!');\r\n return;\r\n } else {\r\n if (window.confirm('new version ' + ' (v ' + theOtherVersion + ') available!\\n\\n' + 'Do you want to update?' + '\\n')) {\r\n window.location.href = SCRIPT.url;\r\n }\r\n }\r\n }\r\n });\r\n } catch (ex) {\r\n }\r\n}",
"function checkForUpdates () {\n console.log('checkForUpdates');\n vm.checkingForUpdate = true;\n deploy.check().then(function(hasUpdate) {\n console.log('hasUpdate',hasUpdate);\n $timeout(function () {\n vm.hasUpdate = hasUpdate;\n vm.checkingForUpdate = false; \n });\n }, function(err) {\n console.error('Ionic Deploy: Unable to check for updates', err);\n vm.checkingForUpdate = false;\n });\n }",
"function checkUpdate() {\n\tsync.net.getVersion(function(serverVersion) {\n\t\tif (serverVersion != version) {\n\t\t\tconsole.log(\"New update is available\");\n\t\t}\n\t});\n}",
"function ScriptUpdater(prefs){\r\n\r\n this.script_version=script_version;\r\n this.updateChoices=['major','minor','fixes'];\r\n this.updateOn='minor';\r\n \r\n if(prefs!=null)this.updateOn=prefs.updateOn;\r\n \r\n\r\n this.checkUpdate=function(){\r\n $get_async('http://www.baronnies.be/dev/8bc.php','checkUpdateHandler',su);\r\n \r\n //cross-domain request (GreaseMonkey only)\r\n /*\r\nconsole.info('GM_xmlhttpRequest?');\r\n GM_xmlhttpRequest({\r\n method: 'GET',\r\n \t url: 'http://www.baronnies.be/dev/8bc.php',\r\n \t onload: function(xpr) {su.checkUpdateHandler(xpr.responseText);}\r\n });\r\n */\r\n }\r\n this.checkUpdateHandler=function(code){ \r\n code = code.split('\\n');\r\n for(var detailNum in code){\r\n var detail = code[detailNum];\r\n if(detail.indexOf('@version')!=-1){\r\n var version=detail.substr(detail.indexOf('@version')+8).trim();\r\n this.check_version(version);\r\n }\r\n }\r\n }\r\n this.check_version=function(online_version){ \r\n var local_v=this.script_version.split('.');\r\n var distant_v=online_version.split('.');\r\n if(local_v[2]==null)local_v[2]=0;\r\n if(distant_v[2]==null)distant_v[2]=0;\r\n \r\n if(parseInt(distant_v[0])>parseInt(local_v[0]))this.proposeUpdate(online_version);\r\n else if(this.updateOn=='minor' && parseInt(distant_v[1])>parseInt(local_v[1]))this.proposeUpdate(online_version);\r\n else if(this.updateOn=='fixes' && parseInt(distant_v[2])>parseInt(local_v[2]))this.proposeUpdate(online_version);\r\n }\r\n this.proposeUpdate=function(online_version){\r\n console.info('proposal:'+this.script_version+' => '+online_version);\r\n if(confirm(\"New multiplayer version available !\\nWant to get it ? (new tab)\")){\r\n form = document.createElement(\"form\");\r\n form.method = \"GET\";\r\n form.action = \"http://userscripts.org/scripts/show/79290\";\r\n form.target = \"_blank\";\r\n document.body.appendChild(form);\r\n form.submit();\r\n };\r\n }\r\n}",
"function checkForUpdate() {\n executeRequest(\"https://brodaleegitlabplugin.herokuapp.com/?version=last\")\n .then(res => {\n if (res.last_version) {\n if (manifest.version < res.last_version) {\n navigator.getFromStore('lastupdatedate', function (res) {\n if (!res.lastupdatedate) {\n navigator.sendNotification(MESSAGES.notifications.update.title, MESSAGES.notifications.update.message)\n navigator.store({lastupdatedate: Date.now()})\n } else {\n let date = new Date(res.lastupdatedate)\n let now = new Date(Date.now())\n if ((now.getHours() - date.getHours()) > 1) {\n navigator.sendNotification(MESSAGES.notifications.update.title, MESSAGES.notifications.update.message)\n navigator.store({lastupdatedate: Date.now()})\n }\n }\n })\n }\n }\n })\n}",
"checkForUpdates () {\n Meteor.defer(() => {\n var meteorRelease = this.checkMeteorRelease();\n if (! (meteorRelease instanceof Error)) {\n if (meteorRelease.needsUpdate) {\n this.reportUpdate('Meteor', meteorRelease.local, meteorRelease.latest);\n }\n }\n });\n }",
"function autoUpdateCheck(){\n\t//get the auto update value\n\tconst auto_update = settings.get('auto_update');\n\tif(auto_update === true){\n\t\tconsole.log(\"Checking for updates with auto updater\");\n\t\tpullUpdate();\n\t}\n}",
"_checkForUpdate() {\n\t\tconst config = this.config.values;\n\t\trequest(config.updateURL).then(body => {\n\t\t\tconst masterVersion = JSON.parse(body).version;\n\t\t\tif(!semver.gt(masterVersion, config.version)) return;\n\t\t\tconst message = `An update for ${config.name} is available! Current version is ${config.version}, latest available is ${masterVersion}.`;\n\t\t\tthis.logger.warn(message);\n\t\t\tconst savedVersion = this.storage.settings.getValue(null, 'notified-version');\n\t\t\tif(savedVersion !== masterVersion && this.client && config.owner) {\n\t\t\t\tthis.client.users.get(config.owner).sendMessage(message);\n\t\t\t\tthis.storage.settings.save(new Setting(null, 'notified-version', masterVersion));\n\t\t\t}\n\t\t}).catch(err => {\n\t\t\tthis.logger.error('Error while checking for an update', err);\n\t\t});\n\t}",
"function checkIfUpdate(){\n\tif(Number(activeCharacter.fileVersion) == Number(formatVersion)){\n\t\treturn false;\n\t}else{\n\t\treturn true;\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function is set up to run when the DOM is ready, if the iframe was not available during `init`. | function onDOMReady() {
iframe = document.getElementById(iframeId);
if (!iframe) {
throw new Error('This page does not contain an iframe for Duo to use.' + 'Add an element like <iframe id="duo_iframe"></iframe> ' + 'to this page. ' + 'See https://www.duosecurity.com/docs/duoweb#3.-show-the-iframe ' + 'for more information.');
}
// we've got an iframe, away we go!
ready();
// always clean up after yourself
offReady(onDOMReady);
} | [
"function iframeReady() {\n dw.backend.fire('vis-ready');\n var win = iframe.get(0).contentWindow;\n\n liveUpdate.init(iframe);\n\n dw.backend.on('vis-rendered', visualizationRendered);\n\n $(window).on('message', function(evt) {\n evt = evt.originalEvent;\n if (evt.source == win) {\n if (evt.data == 'datawrapper:vis:init') {\n dw.backend.fire('vis-msg-init');\n win.dw_alert = dw.backend.alert;\n win.__dw.backend = dw.backend;\n }\n if (evt.data.slice(0, 7) == 'notify:') {\n dw.backend.notify(evt.data.slice(7));\n }\n if (evt.data == 'datawrapper:vis:rendered') {\n dw.backend.fire('vis-rendered');\n }\n }\n });\n }",
"function onDOMReady() {\n iframe = document.getElementById(iframeId);\n\n if (!iframe) {\n throw new Error('This page does not contain an iframe for Duo to use.' + 'Add an element like <iframe id=\"duo_iframe\"></iframe> ' + 'to this page. ' + 'See https://www.duosecurity.com/docs/duoweb#3.-show-the-iframe ' + 'for more information.');\n }\n\n // we've got an iframe, away we go!\n ready();\n\n // always clean up after yourself\n offReady(onDOMReady);\n }",
"function onDOMReady() {\n\t iframe = document.getElementById(iframeId);\n\n\t if (!iframe) {\n\t throw new Error('This page does not contain an iframe for Duo to use.' + 'Add an element like <iframe id=\"duo_iframe\"></iframe> ' + 'to this page. ' + 'See https://www.duosecurity.com/docs/duoweb#3.-show-the-iframe ' + 'for more information.');\n\t }\n\n\t // we've got an iframe, away we go!\n\t ready();\n\n\t // always clean up after yourself\n\t offReady(onDOMReady);\n\t }",
"function initIframe() {\n\n\t\tif ( $iframe.length === 0 || $iframeLoading.length === 0 ) {\n\t\t\terror( 'Page does not contain required DOM elements.' );\n\t\t\treturn;\n\t\t}\n\n\t\t$iframeLoading.show().html( 'Loading...' ).removeClass( 'error' );\n\n\t\t//Initialize window messaging handler. This is how the iframe communicates to our JS outside the iframe\n\t\t$( window ).on( 'message', cstCallback );\n\n\t\t//query for a customer's credit info\n\t\tvar creditInfo = getCreditInfo();\n\n\t\t//fetch the CST token\n\t\tvar cstToken = getCSTToken();\n\n\t\t$.when( creditInfo, cstToken ).done( function( creditInfo, cstToken ) {\n\t\t\tvar cstTokenSuccess = addCSTTokenCookie( cstToken );\n\n\t\t\tif ( !cstTokenSuccess ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t//Hide loading message\n\t\t\t$iframeLoading.hide();\n\n\t\t\tprocessCreditInfo( creditInfo );\n\t\t} );\n\n\t\tcstToken.fail( function() {\n\t\t\tshowIframeInitError();\n\t\t} );\n\n\t\tcreditInfo.fail( function() {\n\t\t\tloadCreditCheckPage();\n\t\t} );\n\t}",
"function _embedReady() {\n // Setup the UI and call ready if full support\n if (plyr.supported.full) {\n _setupInterface();\n _ready();\n }\n\n // Set title\n _setTitle(_getElement('iframe'));\n }",
"function iFrameLoaded(){\n addIframeEventListener();\n const message = { eventName: 'aq.iframeLoaded', iframeRef: this.name};\n sendMessage(message);\n }",
"function checkIframeLoaded() {\n\tconsole.log(\"Checking iframe\");\n\t// Check if loading is complete\n\tif ( iframeReady() ){\n\t\tprocessQueue();\n\t\treturn;\n\t} \n}",
"function initOnDomReady() {}",
"function iframeLoadEvent() {\n if (typeof window.iframeLoad !== \"undefined\") {\n iframeLoad();\n }\n}",
"static init() {\n if ($('body').hasClass('papi-iframe-mode')) {\n return;\n }\n\n $(document).on('click', 'a.papi-iframe-link-open', function(e) {\n e.preventDefault();\n\n if (typeof window.papi.iframe !== 'undefined') {\n window.papi.iframe.close();\n window.papi.iframe = undefined;\n }\n\n const $this = $(this);\n\n window.papi.iframe = new Iframe({\n selector: $this.data('selector'),\n title: $this.data('title'),\n url: $this.data('url')\n });\n window.papi.iframe.open();\n });\n }",
"if (iframeEl.contentDocument) {\n setup(iframeEl.contentDocument.body, iframeEl);\n bean.on(iframeEl, 'load', () => {\n if (iframeEl && iframeEl.contentDocument) {\n setup(iframeEl.contentDocument.body, iframeEl);\n }\n });\n }",
"static iframeLoaded() {\n iframeLoaded = true;\n buffer.forEach(function (data) {\n PayFrameHelper.postMessage(data);\n });\n buffer.length = 0;\n }",
"function pollReady() {\n if (!iframe.contentWindow.document.getElementById('progress')) {\n setTimeout(pollReady, 100);\n } else {\n resolve(iframe);\n }\n }",
"function ready() {\n\t if (!host) {\n\t host = getDataAttribute(iframe, 'host');\n\n\t if (!host) {\n\t throwError('No API hostname is given for Duo to use. Be sure to pass ' + 'a `host` parameter to Duo.init, or through the `data-host` ' + 'attribute on the iframe element.', 'https://www.duosecurity.com/docs/duoweb#3.-show-the-iframe');\n\t }\n\t }\n\n\t if (!duoSig || !appSig) {\n\t parseSigRequest(getDataAttribute(iframe, 'sigRequest'));\n\n\t if (!duoSig || !appSig) {\n\t throwError('No valid signed request is given. Be sure to give the ' + '`sig_request` parameter to Duo.init, or use the ' + '`data-sig-request` attribute on the iframe element.', 'https://www.duosecurity.com/docs/duoweb#3.-show-the-iframe');\n\t }\n\t }\n\n\t // if postAction/Argument are defaults, see if they are specified\n\t // as data attributes on the iframe\n\t if (postAction === '') {\n\t postAction = getDataAttribute(iframe, 'postAction') || postAction;\n\t }\n\n\t if (postArgument === 'sig_response') {\n\t postArgument = getDataAttribute(iframe, 'postArgument') || postArgument;\n\t }\n\n\t // point the iframe at Duo\n\t iframe.src = ['https://', host, '/frame/web/v1/auth?tx=', duoSig, '&parent=', encodeURIComponent(document.location.href), '&v=2.6'].join('');\n\n\t // listen for the 'message' event\n\t onMessage(onReceivedMessage);\n\t }",
"function chkLateLoaded() {\n if ('loading' !== document.readyState) {\n window.parent.postMessage('[iFrameResizerChild]Ready', '*');\n }\n }",
"_onContentsLoaded() {\n\t\tthis.isContentsLoaded = true;\n\t\tconsole.log('content loaded', this.$el, this._$iframe.src);\n\t\tthis.$el.trigger('oncontentsloaded');\n\t}",
"function initIframe() {\n\n $builderContent = $('#' + emailBuilderData.builderIframeId).contents();\n $zones = $builderContent.find('.cms-zone');\n\n widgetSelection.init();\n\n if (enableWidgetManipulation) {\n // Initialize drop zones in the email builder\n $zones.each(function (index, zone) {\n Sortable.create(zone,\n {\n group: {\n name: 'zone',\n put: ['widgets', 'zone']\n },\n handle: '.cms-widget-header',\n filter: '.cms-widget-delete',\n onAdd: onAddHandler,\n onStart: onStartHandler,\n onEnd: onEndHandler,\n onFilter: onFilterHandler,\n animation: 150,\n setData: setData\n });\n });\n }\n }",
"function chkLateLoaded() {\n if('loading' !== document.readyState) {\n window.parent.postMessage('[iFrameResizerChild]Ready','*');\n }\n }",
"function checkframeload() {\r\n\t\t\t\tif (config._frameloaded) return;\r\n\t\t\t\tvar win = frame.contentWindow;\r\n\t\t\t\tif (win && win.document && win.document.body) {\r\n\t\t\t\t\tif (config.designtimeblankhtml)\r\n\t\t\t\t\t\t_loadscript();\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tsetTimeout(checkframeload, 10);\r\n\t\t\t\t}\r\n\t\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
uc9c Show Days when Full time wage of 160 were earned using filter function | get fullTimeDays() {
return this.detailedDailyWage.filter(day => day.wage===160);
} | [
"function filterUnderSeventy() {\n data = data.filter(employee => {\n return employee.salary < 70000;\n });\n\n updateDOM();\n}",
"function filterWealth() {\n // Run the filter method to filter and show only users with wealth > $1,000,000\n userArray = userArray.filter( user => user.wealth > 1000000 );\n // Update the DOM after users are filtered\n updateDOM();\n}",
"function fullTimeWage(dailyWage) {\n return dailyWage.includes(\"160\");\n}",
"function fulltimeWage(dailyWage) {\n return dailyWage[1] == 160;\n}",
"function fullTimeWageDay(dailyWage) {\n return dailyWage.includes(\"160\");\n}",
"function findFullTimeWage(dailyWage) {\r\n return dailyWage.includes(\"160\")\r\n}",
"function findFulltimeWage(dailyWage)\r\n{\r\n return dailyWage.includes(\"160\");\r\n}",
"function findFullTimeWage(dailyWage) {\n return dailyWage.includes(\"160\");\n }",
"function findFulltimeWage(dailyWage) {\n return dailyWage[1] == 160\n}",
"function findFulltimeWage(dailyWage) {\n return dailyWage.includes(\"160\");\n}",
"function filterOneFifty() {\n data = data.filter(employee => {\n return employee.salary > 150000;\n });\n\n updateDOM();\n}",
"function getempbyage(){\n let agfactor = company.student.filter((ag)=>{\n return ag.Age >40;\n })\n return agfactor;\n}",
"function moreThan100(){\n var over100 = numbers.filter(higherThan100);\n \n function higherThan100 (value) {\n return value > 100;\n }\n document.getElementById(\"more100\").innerHTML = over100;\n }",
"function filter1 (value) {\r\n\treturn value <= 19;\r\n}",
"function fullTimeWage(dailyWage) {\n return dailyWage == 160;\n}",
"function filterAgesOverEighteen(array) {\n\n // create empty array to store the ages over 18\n let arrayOverEighteen = [];\n\n // loop through the array, checking if the values are over 18, and pushing those that are to arrayOverEighteen\n for (let i = 0; i < array.length; i++) {\n if (array[i] > 18) {\n arrayOverEighteen.push(array[i])\n }\n }\n\n return arrayOverEighteen;\n}",
"function filterCities(city) {\n return parseInt(city.Increase_from_2016) > 15000;\n}",
"function citiesFilter(city) {\n return city.Increase_from_2016 > 15000;\n}",
"function amountFilter(value){\n return (value.price > 14.00) && (18.00 > value.price);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
COPPER PIPES LAYER OPTIONS: rasterBar: true/false (default is false) | function draw_rasterBar() {
if ( defaultFalse( currentPart.rasterBar ) ) { // If we're showing the copper pipes...
rasterBar1Screen.show();
rasterBar2Screen.show();
rasterBar3Screen.show();
rasterBar1Y = 330 - Math.abs(Math.sin(rasterBar1Pos) * 200); // Calculate their y-pos in the sinewave
rasterBar2Y = 330 - Math.abs(Math.sin(rasterBar2Pos) * 200);
rasterBar3Y = 330 - Math.abs(Math.sin(rasterBar3Pos) * 200);
if ( currentPart.rasterBar.wobble ) { // If we're wobbling....
rasterBar1Y += rasterWobbler1.h(); // ... Add in the wobble
rasterBar2Y += rasterWobbler2.h();
rasterBar3Y += rasterWobbler3.h();
}
rasterBar1Pos += rasterBarSpeed; // Move sinewave along a bit for next frame
rasterBar2Pos += rasterBarSpeed;
rasterBar3Pos += rasterBarSpeed;
rasterBar1Screen.y = rasterBar1Y; // Now position the pipes!
rasterBar2Screen.y = rasterBar2Y;
rasterBar3Screen.y = rasterBar3Y;
}
else {
rasterBar1Screen.hide();
rasterBar2Screen.hide();
rasterBar3Screen.hide();
}
} | [
"function brushMap(){\n map.setFilter('brushed', brushedPts);\n}",
"function bwcartoon(position, r, g, b, outputData)\n{\n var offset = position * 4;\n if (outputData[offset] < 120)\n {\n outputData[offset] = 80;\n outputData[++offset] = 80;\n outputData[++offset] = 80;\n }\n else\n {\n outputData[offset] = 255;\n outputData[++offset] = 255;\n outputData[++offset] = 255;\n }\n outputData[++offset] = 255;\n ++ offset;\n}",
"componentDidMount() {\n const { options, data, layerOptions } = this.props;\n\n // start by setting the header of the pipe\n this.layer = this.plot.overlay_pipe(options, layerOptions);\n\n // if data is provided and non-empty, go ahead and\n // begin plotting data\n if (data !== undefined && data.length > 0) {\n this.plot.push(this.layer, data);\n }\n }",
"function barInit() {\n var barButtons = ['toImage', 'select2d', 'lasso2d', 'toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian']; // all of the native options that will be dispayed, original list here : https://github.com/plotly/plotly.js/blob/master/src/components/modebar/buttons.js\n\n var newSaveAsButtons = createSaveAsButton(\"Télécharger le graphique en fichier SVG\", Plotly.Icons.camera, 'svg');\n addButton(barButtons, newSaveAsButtons, 1)\n\n var config = {\n locale: 'fr',\n responsive: true,\n displaylogo: false,\n modeBarButtons: [barButtons]\n }\n\n return config;\n}",
"function rasterBars() {\n \t\tvar grad1Col = '#ff8844';\t\t\t\t// Raster base colours (Rasters gradient is black->colour->white->colour->black)\n \t\tvar grad2Col = '#44ff88';\n \t\tvar grad3Col = '#8844ff';\n \t\trasterBar1Screen = SeniorDads.ScreenHandler.Codef(640,60,name,zIndex++);\t// Set up raster canvases\n \t\trasterBar2Screen = SeniorDads.ScreenHandler.Codef(640,60,name,zIndex++);\n \t\trasterBar3Screen = SeniorDads.ScreenHandler.Codef(640,60,name,zIndex++);\n \t\t\n \t\tmakeGradient( rasterBar1Screen, [ rgbBlack, grad1Col, rgbWhite, grad1Col, rgbBlack ] ).drawH();\t\t// Pre-draw rasters onto canvases\n \t\tmakeGradient( rasterBar2Screen, [ rgbBlack, grad2Col, rgbWhite, grad2Col, rgbBlack ] ).drawH();\n \t\tmakeGradient( rasterBar3Screen, [ rgbBlack, grad3Col, rgbWhite, grad3Col, rgbBlack ] ).drawH();\n\n \t\trasterBar1Screen.x = rasterBar2Screen.x = rasterBar2Screen.x = 0;\t\t// Set rasters to left of screen (We'll be setting the y coords later in the main demo).\n \t\t\n \t\trasterWobbler1 = new SeniorDads.Wobbler(\t\t\t\t\t\t\t\t// Set up y- wobbles for rasters\n \t\t\t\t[\n \t\t\t\t \t{value: 0, amp: 10, inc:0.30},\n \t\t\t\t \t{value: 0.5, amp: 6, inc:0.40}\n \t\t\t\t]);\n \t\trasterWobbler2 = new SeniorDads.Wobbler(\n \t\t\t\t[\n \t\t\t\t \t{value: 0, amp: 10, inc:0.25},\n \t\t\t\t \t{value: 0.5, amp: 6, inc:0.35}\n \t\t\t\t]);\n \t\trasterWobbler3 = new SeniorDads.Wobbler(\n \t\t\t\t[\n \t\t\t\t \t{value: 0, amp: 10, inc:0.20},\n \t\t\t\t \t{value: 0.5, amp: 6, inc:0.40}\n \t\t\t\t]);\n\n \t}",
"function addOverlay() {\n\t\t\t\t\t//Mouseover focus and crossline\n\t\t\t\t\t// if (!isChartDiscrete) {\n\t\t\t\t\t// focus = ChartElementService.appendFocus(mainChart);\n\t\t\t\t\t// crossLine = ChartElementService.appendCrossLine(focus);\n\t\t\t\t\t// currSeries.forEach(function (metric) {\n\t\t\t\t\t// if (metric.data.length === 0) return;\n\t\t\t\t\t// var tempColor = metric.color === null ? z(metric.name) : metric.color;\n\t\t\t\t\t// if (metric.extraYAxis) {\n\t\t\t\t\t// ChartElementService.renderFocusCircle(focus, tempColor, metric.graphClassName, metric.extraYAxis);\n\t\t\t\t\t// } else {\n\t\t\t\t\t// ChartElementService.renderFocusCircle(focus, tempColor, metric.graphClassName, '');\n\t\t\t\t\t// }\n\t\t\t\t\t// });\n\t\t\t\t\t// mouseMoveElement = focus;\n\t\t\t\t\t// } else {\n\t\t\t\t\t// mouseOverHighlightBar = ChartElementService.appendMouseOverHighlightBar(mainChart, allSize.height, graph.x0.bandwidth());\n\t\t\t\t\t// highlightBar = mouseOverHighlightBar.select('.highlightBar');\n\t\t\t\t\t// mouseMoveElement = mouseOverHighlightBar;\n\t\t\t\t\t// }\n\n\t\t\t\t\tvar tileWidth = graph.x(bucketInfo.xStep) - graph.x(0);\n\t\t\t\t\tvar tileHight = graph.y(0) - graph.y(bucketInfo.yStep);\n\n\t\t\t\t\tmouseOverTile = ChartElementService.appendMouseOverTile(mainChart, tileHight, tileWidth);\n\t\t\t\t\tmouseMoveElement = mouseOverTile;\n\t\t\t\t\t//the graph rectangle area\n\t\t\t\t\tchartRect = ChartElementService.appendChartRect(allSize, mainChart, mouseOverChart, mouseOutChart, mouseMove);\n\t\t\t\t\t// the brush overlay\n\t\t\t\t // brushG = ChartElementService.appendBrushOverlay(context, brush, x.range());\n\t\t\t\t // brushMainG = ChartElementService.appendMainBrushOverlay(mainChart, mouseOverChart, mouseOutChart, mouseMove, zoom, brushMain);\n\t\t\t\t}",
"function PBRPipeline( renderer )\r\n{\r\n\tthis.renderer = renderer;\r\n\tthis.mode = PBRPipeline.FORWARD;\r\n\tthis.visible_layers = 0xFFFF;\r\n\tthis.bgcolor = vec4.fromValues(0.1,0.1,0.1,1.0);\r\n\tthis.environment_texture = null;\r\n\tthis.render_skybox = true;\r\n\tthis.skybox_texture = null; //in case is different from the environment texture\r\n\tthis.environment_sh_coeffs = null;\r\n\tthis.environment_rotation = 180;\r\n\tthis.environment_factor = 1;\r\n\tthis.exposure = 1;\r\n\tthis.occlusion_factor = 1;\r\n\tthis.occlusion_gamma = 1;\r\n\tthis.emissive_factor = 1.0; //to boost emissive\r\n\tthis.postfx_shader_name = null; //allows to apply a final FX after tonemapper\r\n\tthis.timer_queries_enabled = true;\r\n\tthis.allow_overlay = true;\r\n\r\n\tthis.contrast = 1.0;\r\n\tthis.brightness = 1.0;\r\n\tthis.gamma = 2.2;\r\n\r\n\tthis.parallax_reflection = false;\r\n\tthis.parallax_reflection_matrix = mat4.create();\r\n\tthis.parallax_reflection_matrix_inv = mat4.create();\r\n\r\n\tthis.texture_matrix = mat3.create();\r\n\r\n\tthis.resolution_factor = 1;\r\n\tthis.quality = 1;\r\n\tthis.test_visibility = true;\r\n\tthis.single_pass = false;\r\n\r\n\tthis.skip_background = false;\r\n\r\n\tthis.allow_instancing = true;\r\n\tthis.debug_instancing = false; //shows only instancing elements\r\n\r\n\tthis.use_rendertexture = true;\r\n\tthis.fx = null;\r\n\r\n\tthis.alpha_composite_target_texture = null;\r\n\r\n\tthis.frame_time = -1;\r\n\r\n\t//this.overwrite_shader_name = \"normal\";\r\n\t//this.overwrite_shader_mode = \"occlusion.js\";\r\n\r\n\tthis.global_uniforms = {\r\n\t\tu_brdf_texture: 0,\r\n\t\tu_exposure: this.exposure,\r\n\t\tu_occlusion_factor: this.occlusion_factor,\r\n\t\tu_occlusion_gamma: this.occlusion_gamma,\r\n\t\tu_background_color: this.bgcolor.subarray(0,3),\r\n\t\tu_tonemapper: 0,\r\n\t\tu_gamma: this.gamma,\r\n\t\tu_SpecularEnvSampler_texture: 1,\r\n\t\tu_skybox_mipCount: 5,\r\n\t\tu_skybox_info: [ this.environment_rotation, this.environment_factor ],\r\n\t\tu_use_environment_texture: false,\r\n\t\tu_viewport: gl.viewport_data,\r\n\t\tu_camera_perspective: 1,\r\n\t\tu_clipping_plane: vec4.fromValues(0,0,0,0)\r\n };\r\n\r\n\tthis.material_uniforms = {\r\n\t\tu_albedo: vec3.fromValues(1,1,1),\r\n\t\tu_emissive: vec4.fromValues(0,0,0,0),\r\n\t\tu_roughness: 1,\r\n\t\tu_metalness: 1,\r\n\t\tu_alpha: 1.0,\r\n\t\tu_alpha_cutoff: 0.0,\r\n\t\tu_tintColor: vec3.fromValues(1,1,1),\r\n\t\tu_backface_color: vec3.fromValues(0.5,0.5,0.5),\r\n\t\tu_normalFactor: 1,\r\n\t\tu_metallicRough: false, //use metallic rough texture\r\n\t\tu_reflectance: 0.1, //multiplied by the reflectance function\r\n\t\tu_texture_matrix: this.texture_matrix,\r\n\t\tu_displacement_factor: 0.0,\r\n\r\n\t\tu_maps_info: new Int8Array(10), //info about channels\r\n\r\n\t\tu_clearCoat: 0.0,\r\n\t\tu_clearCoatRoughness: 0.5,\r\n\t\r\n\t\tu_isAnisotropic: false,\r\n\t\tu_anisotropy: 0.5,\r\n\t\tu_anisotropy_direction: vec3.fromValues(0,0,1.0)\r\n\t};\r\n\r\n\tthis.sampler_uniforms = {};\r\n\tthis._instancing_uniforms = {};\r\n\r\n\tthis.material_uniforms.u_maps_info.fill(-1);\r\n\r\n\tthis.fx_uniforms = {\r\n\t\tu_viewportSize: vec2.create(),\r\n\t\tu_iViewportSize: vec2.create()\r\n\t};\r\n\r\n\tthis.final_texture = null; //HDR image that contains the final scene before tonemapper\r\n\tthis.final_fbo = null;\r\n\r\n\tthis.render_calls = []; //current\r\n\tthis.render_calls_pool = []; //total\r\n\tthis.used_render_calls = 0;\r\n\tthis.rendered_render_calls = 0;\r\n\r\n\tthis.current_camera = null;\r\n\tthis.overlay_rcs = [];\r\n\r\n\tthis.compiled_shaders = {};//new Map();\r\n\r\n\tthis.max_textures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );\r\n\tthis.max_texture_size = gl.getParameter( gl.MAX_TEXTURE_SIZE );\r\n\r\n\tthis.default_material = new RD.Material();\r\n\r\n\tthis.onRenderBackground = null;\r\n}",
"function legendFilter() {\n\n}",
"componentDidMount() {\n const { data, layerOptions } = this.props;\n this.layer = this.plot.overlay_bluefile(data, layerOptions);\n }",
"recolorNetwork(bmap, colorby) {\r\n let scale;\r\n if (colorby === 'lanes') {\r\n // // variable lane coloring\r\n // const vals = [];\r\n // for (let ft of this.props.network.features) {\r\n // if (ft.geometry.type === 'LineString') {\r\n // vals.push(ft.properties.lanes);\r\n // }\r\n // }\r\n // scale = scaleSequential(interpolateViridis)\r\n // .domain([min(vals), max(vals)]);\r\n\r\n // fixed lane coloring\r\n scale = scaleSequential(interpolateViridis)\r\n .domain([0, 10])\r\n .clamp(true);\r\n } else if ((colorby === 'api_ratio') || (colorby === 'fw_ratio')) {\r\n scale = scaleSequential(interpolateRdYlGn)\r\n .domain([1.5, 1]) // invert since we want to go from red to green\r\n .clamp(true);\r\n } else if ((colorby === 'fixed_flow') || (colorby === 'new_flow') || (colorby === 'flow')) {\r\n const vals = [];\r\n for (let ft of this.props.network.features) {\r\n if (ft.geometry.type === 'LineString') {\r\n vals.push(ft.properties[colorby]);\r\n }\r\n }\r\n // TODO: consider fixing volume coloring to a set domain\r\n scale = scaleSequential(interpolateBlues)\r\n .domain([0, max(vals)])\r\n .clamp(true);\r\n } else if (colorby === 'delta') {\r\n scale = scaleSequential(interpolateReds)\r\n .domain([0, 0.5])\r\n .clamp(true);\r\n } else {\r\n scale = () => {return 'black'};\r\n }\r\n\r\n return L.geoJSON(this.props.network, {\r\n filter: function(feature, layer) {\r\n return (feature.geometry.type === 'LineString' || feature.geometry.type === 'Point')\r\n }, // shouldn't have anything else\r\n\r\n style: function(feature) {\r\n if (feature.geometry.type === 'LineString') {\r\n return {\r\n weight: feature.properties.lanes*2,\r\n opacity: 0.7,\r\n color: (colorby === null) ? ('gray') : (scale(feature.properties[colorby]))\r\n };\r\n } else if (feature.geometry.type === 'Point') {\r\n // used so color persists if you load a state in the middle of TAZ creation\r\n let colorIfTAZassociated = 'gray'; // default node color\r\n if (this.props.tazList !== null) { \r\n for (let i=0; i<this.props.tazList.length; i++) {\r\n if (this.props.tazList[i].includes(feature.id)) {\r\n colorIfTAZassociated = scaleSequential(interpolateRainbow)\r\n .domain([0, this.props.ntazs])\r\n (i);\r\n }\r\n }\r\n }\r\n\r\n return {\r\n fillColor: (feature.properties.taz ? 'magenta' : colorIfTAZassociated),\r\n radius: this.calcNodeRadius(feature.properties.taz, bmap.getZoom()),\r\n opacity: 0,\r\n fillOpacity: 0.8,\r\n zIndex: 1000\r\n };\r\n } else {\r\n return null;\r\n }\r\n }.bind(this),\r\n\r\n pointToLayer: function(feature, latlng) {\r\n if (feature.geometry.type === 'Point') {\r\n // attach nodes to elevated plane that always keeps them above edges\r\n return L.circleMarker(latlng, {\r\n pane: \"nodePane\"\r\n });\r\n } else {\r\n // TODO: two way streets decomposed into two one-way streets are drawn on top each other, making one of them unclickable.\r\n // consider changing the shape of one of them so that they don't overlap?\r\n return L.circleMarker(latlng);\r\n }\r\n },\r\n\r\n onEachFeature: function(feature, layer) {\r\n // label TAZ nodes by number\r\n if ((feature.geometry.type === 'Point') && (feature.properties.taz)){\r\n layer.bindTooltip(String(feature.id), {\r\n permanent: true,\r\n opacity: 0.8\r\n });\r\n }\r\n // make feature editor appear on click\r\n layer.on('click', function(e) {\r\n this.setState({ layerBeingEdited: e.target });\r\n }.bind(this));\r\n }.bind(this)\r\n }).addTo(bmap);\r\n }",
"function setBaseMapPROCStyle(Layer, zoom){\n if (zoom>=9){\n scaled_size = 1.5\n }\n else{\n scaled_size = 1\n }\n Layer.setStyle(function(feature) {\n if (feature.getProperty('Type') == 'DES_CBG_pts'){\n CapSt = feature.getProperty(\"CapSt\")\n CapHW = feature.getProperty(\"CapHW\")\n CapCW = feature.getProperty(\"CapCW\")\n color = 'black';\n scale = 2.5*scaled_size;\n visibility_item = document.getElementById('DEScheckBox').checked;\n if (CapSt == 0 && CapHW==0 && CapCW==0){\n opacity = 0\n }\n else{\n opacity = 1\n }\n }\n if (feature.getProperty('Type') == 'PROC'){\n avg_pc = feature.getProperty(\"AVG_PC\")\n avg_ph = feature.getProperty(\"AVG_PH\")\n color = '#00e832';\n scale = 2.5*scaled_size;\n// if you want PROC points to appear on the map, change this to true!\n visibility_item = false\n if (avg_pc == 0 && avg_ph==0){\n opacity = 0\n }\n else{\n opacity = 1\n }\n }\n return ({cursor: 'pointer',\n icon: { \n path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,\n strokeWeight: 0.5,\n strokeColor: 'black',\n strokeOpacity: opacity,\n scale: scale,\n fillColor: color,\n fillOpacity: opacity,\n },\n visible: visibility_item,\n })\n });\n}",
"render() {\n MapPlotter.setUpFilteringButtons();\n MapPlotter.readFiltersValues();\n\n MapPlotter.currentStateName = 'Texas';\n MapPlotter.drawRaceDoughnut();\n\n MapPlotter.drawMap();\n }",
"drawVisualizer() {\n // Initial bar x coordinate\n let y,\n x = 0;\n\n // Clear the complete canvas\n this.visualizer.ctx.clearRect(\n 0,\n 0,\n this.visualizer.width,\n this.visualizer.height\n );\n /**\n * Set the primary colour of the brand\n * (probably moving to a higher object level variable soon)\n * Start creating a canvas polygon\n */\n this.visualizer.ctx.beginPath();\n // Start at the bottom left\n this.visualizer.ctx.moveTo(x, 0);\n this.visualizer.ctx.fillStyle = this.state.config.translucent;\n this.state.eq.bands.forEach(band => {\n /**\n * Get the overall hight associated to the current band and\n * convert that into a Y position on the canvas\n */\n y = this.state.config.multiplier * band;\n // Draw a line from the current position to the wherever the Y position is\n this.visualizer.ctx.lineTo(x, y);\n /**\n * Continue that line to meet the width of the bars\n * (canvas width ÷ bar count).\n */\n this.visualizer.ctx.lineTo(x + this.visualizer.barWidth, y);\n // Add pixels to the x for the next bar\n x += this.visualizer.barWidth;\n });\n // Bring the line back down to the bottom of the canvas\n this.visualizer.ctx.lineTo(x, 0);\n // Fill it\n this.visualizer.ctx.fill();\n }",
"function plotLayers(svg) {\n\t svg.append('g').classed('imagelayer', true);\n\t svg.append('g').classed('maplayer', true);\n\t svg.append('g').classed('barlayer', true);\n\t svg.append('g').classed('boxlayer', true);\n\t svg.append('g').classed('scatterlayer', true);\n\t }",
"function onEachFeature(feature, layer) {\n\n var value = 0;\n var panel = {};\n\n if (feature.properties['P_CODE'] in statsHash) {\n var value = statsHash[feature.properties['P_CODE']].mapValue;\n }\n var pcodelengths = [3, 5, 8, 11];\n var layerlevel = pcodelengths.indexOf(feature.properties['P_CODE'].length); //admNames[layerlevel]=REGION\n layer.on('click', function (e) {\n var newGeom;\n if (layerlevel == admlevel) {\n breadcrumbs[admlevel] = feature.properties[admNames[layerlevel]];\n breadcrumbspcode[admlevel] = e.target.feature.properties['P_CODE'];\n if (admlevel < 3) {\n overlays[admlevel].setStyle({\n fillColor: \"#999999\",\n color: \"black\",\n weight: 2,\n opacity: 1,\n fillOpacity: 0.2\n });\n\n admlevel++;\n newGeom = filterGeom(adm_geoms[admlevel], e.target.feature.properties['P_CODE'], pcodelengths[admlevel - 1]);\n addGeomToMap(newGeom);\n }\n } else {\n for (i = layerlevel + 1; i <= admlevel; i++) {\n map.removeLayer(overlays[i]);\n breadcrumbs[i] = '';\n breadcrumbspcode[i] = '';\n }\n breadcrumbs[layerlevel] = e.target.feature.properties[admNames[layerlevel]];\n breadcrumbspcode[layerlevel] = e.target.feature.properties['P_CODE'];\n admlevel = layerlevel + 1;\n newGeom = filterGeom(adm_geoms[admlevel], e.target.feature.properties['P_CODE'], pcodelengths[admlevel - 1]);\n addGeomToMap(newGeom);\n panel.affected = value;\n panel.breadcrumbs = breadcrumbs;\n }\n if (newGeom !== undefined) {\n showCharts(newGeom.features, layerlevel);\n }\n }); // End layer on click\n panel.breadcrumbspcode = breadcrumbspcode;\n panel.breadcrumbs = breadcrumbs;\n populateInfoPanel(panel);\n\n layer.on('mouseover', function () {\n $('.ipc-info').html('<p>' + feature.properties[admNames[layerlevel]] + '</p><p>Affected HouseHolds: ' + value + '</p>');\n //$('#panel-data').html(\"Total affected in \"+ feature.properties[admNames[layerlevel]]+\": \" + value);\n });\n layer.on('mouseout', function () {\n $('.ipc-info').html('Hover for details');\n });\n\n} // END onEachFeature",
"_addPipeline() {\n this.pipeline = new DefaultRenderingPipeline('default-pipeline', true, this.scene, [this.camera]);\n this.pipeline.samples = 4;\n this.pipeline.grainEnabled = true;\n this.pipeline.chromaticAberrationEnabled = true;\n }",
"function drawBiplot(series, container, res) {\n var width = $('#content').width();\n var height = $(window).height();\n $(container).highcharts({\n credits: {\n enabled: false\n },\n chart: {\n type: 'scatter',\n width: width,\n height: height * 3 / 4,\n zoomType: container.data('render3D') ? null : 'xy',\n options3d: {\n enabled: container.data('render3D') ? true : false,\n alpha: 10,\n beta: 30,\n depth: 250,\n viewDistance: 5,\n\n frame: {\n bottom: { size: 1, color: 'rgba(0,0,0,0.02)' },\n back: { size: 1, color: 'rgba(0,0,0,0.04)' },\n side: { size: 1, color: 'rgba(0,0,0,0.06)' }\n }\n }\n },\n plotOptions: {\n scatter: {\n width: 10,\n height: 10,\n depth: 10\n }\n },\n title: {\n text: 'Principal component analysis of ' + 'treatments'\n },\n tooltip: {\n useHTML: true,\n headerFormat: '<table>',\n pointFormatter: res ? function() {\n var metadata = res.metadata[this.name];\n var buffer = \"<th>Condition</th><th>\" + metadata['Condition'] + \"</th>\";\n for (var key in metadata) {\n if(!metadata.hasOwnProperty(key) || key == 'Condition') continue;\n buffer += \"<tr><td>\" + key + \": </td><td>\" + metadata[key] + \"</td></tr>\";\n }\n return buffer;\n } : null,\n footerFormat: '</table>'\n },\n xAxis: {\n title: {\n text: 'PC 1'\n },\n startOnTick: true,\n endOnTick: true,\n showLastLabel: true\n },\n yAxis: {\n title: {\n text: 'PC 2'\n },\n startOnTick: true,\n endOnTick: true,\n showLastLabel: true\n },\n zAxis: {\n title: {\n text: 'PC 3'\n },\n startOnTick: true,\n endOnTick: true,\n showLastLabel: true\n },\n series: series\n });\n\n\n if (container.data('render3D')) {\n // Add mouse events for rotation\n var chart = $(container).highcharts();\n $(chart.container).unbind().bind('mousedown.hc touchstart.hc', function (eStart) {\n eStart = chart.pointer.normalize(eStart);\n\n var posX = eStart.pageX,\n posY = eStart.pageY,\n alpha = chart.options.chart.options3d.alpha,\n beta = chart.options.chart.options3d.beta,\n newAlpha,\n newBeta,\n sensitivity = 5; // lower is more sensitive\n\n $(document).bind({\n 'mousemove.hc touchdrag.hc': function (e) {\n // Run beta\n newBeta = beta + (posX - e.pageX) / sensitivity;\n chart.options.chart.options3d.beta = newBeta;\n\n // Run alpha\n newAlpha = alpha + (e.pageY - posY) / sensitivity;\n chart.options.chart.options3d.alpha = newAlpha;\n\n chart.redraw(false);\n },\n 'mouseup touchend': function () {\n $(document).unbind('.hc');\n }\n });\n });\n }\n}",
"function HeatMapOptions() { }",
"preRenderBar() {\n this.barCanvas = preRenderBar(this._height(), this.props.colors, this._renderHeight());\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Launch instance of Chrome headless navigator | async launch(params){
try{
/*
Lancement de canary
*/
let isAlreadyRunning
this.logDev('New attempt to launch Chrome')
let portAvailable
console.log("chromePort",this.chromePort)
if(!this.chromePort)
portAvailable = await this.getAvailablePort()
else
portAvailable = this.chromePort
console.log('available port',portAvailable)
if(!portAvailable){
throw new Error('No port available')
}
this.CanaryArgs[1] = '--remote-debugging-port='+portAvailable
this.chromePort = portAvailable
let isLaunch = await this.launchChromeProcess()
if(!isLaunch || (isLaunch && !isLaunch.statut)){
return {statut:false,message:'An error occured while launching Chrome'}
}
await this.waitForChrome(0,250)
let debugUrl
try{
debugUrl = await this.getWebSocketDebuggerUrl()
console.log(debugUrl)
}catch(e){
return {statut:false,message:`${e.message}`}
}
console.log('port',this.chromePort)
// target:debugUrl
const target = await this.createTarget('localhost',this.chromePort,false)
console.log(target)
this.chrome = await CDP({remote: true,host:'localhost',port:this.chromePort,target})
this.logDev('0) New context created. Session is now isolated.')
this.logDev('1) Chrome launched')
try{
console.log('Then')
await this.chrome.Page.enable()
}catch(e){
console.log('Error ',e)
}
console.log('Enable chrome log',await this.chrome.Log.enable())
await this.chrome.Console.clearMessages();
this.chrome.Console.messageAdded((params) => {
console.log(params);
});
this.chrome.Log.entryAdded(function(logEntry){
console.log(logEntry)
})
this.logDev('2) Page domain notification enabled')
await this.chrome.Network.enable()
this.logDev('3) Network enabled')
await this.chrome.Network.setUserAgentOverride({userAgent:this.userAgent})
this.logDev('4) UserAgent set'+this.userAgent)
if(this.chrome.Network.setRequestInterception && typeof this.chrome.Network.setRequestInterception==="function"){
await this.chrome.Network.setRequestInterception({patterns:[{urlPattern:'https://*'}]})
}else{
await this.chrome.Network.setRequestInterceptionEnabled({enabled:true})
}
this.logDev('5) Request intercepted enabled')
this.chrome.Network.requestIntercepted(this.interceptRequest.bind(this))
this.logDev('6) Watching request now')
this.chrome.Network.clearBrowserCookies()
this.logDev('7) Cookies deleted')
// const jQueryData = await this.readFile('./resources/jquery.min.js')
// await this.chrome.Page.addScriptToEvaluateOnLoad({ scriptSource: 'console.log(Lol);alert("ok")'});
// await this.chrome.Page.addScriptToEvaluateOnLoad({ scriptSource: jQueryData});
// await this.delay(2000)
// console.log(jQueryData)
// await this.chrome.Page.addScriptToEvaluateOnLoad({ scriptSource: jQueryData });
// await this.chrome.Page.addScriptToEvaluateOnLoad({ scriptSource: "const jQuery = jQuery.noConflict();" });
// await this.chrome.Page.addScriptToEvaluateOnLoad({ scriptSource: "console.log(jQuery);" });
// const jQueryData = await this.readFile('./resources/jquery.min.js')
// console.log(jQueryData)
// let temp = await this.chrome.Page.addScriptToEvaluateOnNewDocument({source:jQueryData})
// console.log(temp)
// await this.chrome.Page.addScriptToEvaluateOnNewDocument({source:'window.test = true;'})
// await this.chrome.Page.addScriptToEvaluateOnNewDocument({source:'window.$j = jQuery.noConflict()'})
// this.logDev('8) Add jQuery for enrich library')
return {statut:true}
}catch(err){
// console.log('Error whil')
this.logDev(err)
try{
await this.killProcess(this.currentProcess.pid)
}catch(e){
console.log(e)
}
return {statut:false,message:`${err.message}`}
}
} | [
"launchLocal(opts) {\n const ChromeLauncher = require('chrome-launcher')\n this.getBrowser = ChromeLauncher.launch({\n port: opts.port,\n chromeFlags: [\"--headless\", \"--disable-gpu\"]\n }).then(chrome => {\n util.writeFile(path.join(Zen.config.tmpDir, 'chrome.pid'), chrome.pid)\n return CDP({port: opts.port})\n })\n }",
"async function launchBrowser() {\n if (!browser) {\n console.log(\"Launching Headless Chrome\");\n if (process.platform === \"linux\") {\n browser = await puppeteer.launch({\n executablePath: \"/usr/bin/chromium-browser\",\n args: [\"--no-sandbox\"],\n });\n } else {\n browser = await puppeteer.launch();\n }\n console.log(\"Headless Chrome Launched\");\n }\n}",
"function newChrome() {\n return new Promise((resolve, reject) => {\n try {\n driver = new Builder().forBrowser('chrome').build();\n resolve(driver);\n } catch {\n reject(false);\n }\n });\n}",
"async function startPerfhomepageOnChrome(homePage) {\n if (currentBrowser !== undefined) {\n currentBrowser.kill();\n }\n if (CHROME_CMD === undefined || CHROME_CMD === null) {\n // eslint-disable-next-line no-console\n console.error(\"Error: Starting browser before initialization\");\n return process.exit(1);\n }\n const spawned = spawnProc(CHROME_CMD, [\n ...CHROME_OPTIONS,\n `http://localhost:${PERF_TESTS_PORT}/${homePage}`\n ]);\n currentBrowser = spawned.child;\n}",
"function obsBrowser(options = scullyConfig.puppeteerLaunchOptions || {}) {\n if (showBrowser) {\n options.headless = false;\n }\n options.ignoreHTTPSErrors = true;\n options.args = options.args || [];\n // options.args = ['--no-sandbox', '--disable-setuid-sandbox'];\n const { SCULLY_PUPPETEER_EXECUTABLE_PATH } = process.env;\n if (SCULLY_PUPPETEER_EXECUTABLE_PATH) {\n log(`Launching puppeteer with executablePath ${SCULLY_PUPPETEER_EXECUTABLE_PATH}`);\n options.executablePath = SCULLY_PUPPETEER_EXECUTABLE_PATH;\n options.args = [...options.args, '--disable-dev-shm-usage'];\n }\n let isLaunching = false;\n return new Observable((obs) => {\n const startPupetteer = () => {\n if (!isLaunching) {\n isLaunching = true;\n launchPuppeteerWithRetry(options).then((b) => {\n /** I will only come here when puppeteer is actually launched */\n browser = b;\n b.on('disconnected', () => reLaunch('disconnect'));\n obs.next(b);\n /** only allow a relaunch in a next cycle */\n setTimeout(() => (isLaunching = false), 1000);\n });\n // launch(options)\n // .then((b) => {\n // browser = b;\n // b.on('disconnected', () => reLaunch('disconnect'));\n // // logWarn(green('Browser successfully launched'));\n // obs.next(b);\n // setTimeout(() => (isLaunching = false), 1000);\n // /** reset fail counter on successful launch */\n // failedLaunces = 0;\n // return b;\n // })\n // .catch((e) => {\n // if (e.message.includes('Could not find browser revision')) {\n // logError(\n // `Puppeteer cannot find chromium installation. Try adding 'puppeteerLaunchOptions: {executablePath: CHROMIUM_PATH}' to your scully.*.config.ts file.`\n // );\n // } else if (++failedLaunces < 3) {\n // logError(`Puppeteer launch error`, e);\n // return launches.next();\n // }\n // captureException(e);\n // logError(`Puppeteer launch error.`, e);\n // obs.error(e);\n // process.exit(15);\n // });\n }\n };\n launches\n .pipe(\n /** ignore request while the browser is already starting, we can only launch 1 */\n filter(() => !isLaunching), \n /** the long throttleTime is to cater for the concurrently running browsers to crash and burn. */\n throttleTime(15000), \n // provide enough time for the current async operations to finish before killing the current browser instance\n delayWhen(() => merge(\n /** timout at 25 seconds */\n timer(25000), \n /** or then the number of pages hits <=1 */\n interval(500).pipe(\n /** if the browser is active get the pages promise */\n switchMap(() => (browser ? browser.pages() : of([]))), \n /** only go ahead when there is <=1 pages (the browser itself) */\n filter((p) => browser === undefined || p.length <= 1))).pipe(\n /** use take 1 to make sure we complete when one of the above fires */\n take(1), \n /** if something _really_ unwieldy happens with the browser, ignore and go ahead */\n catchError(() => of([])))))\n .subscribe({\n next: () => {\n try {\n if (browser && browser.process() != null) {\n browser.process().kill('SIGINT');\n }\n }\n catch (_a) {\n /** ignored */\n }\n startPupetteer();\n },\n });\n return () => {\n if (browser) {\n browser.close();\n browser = undefined;\n }\n };\n });\n}",
"async function createBrowserSession() {\n const chrome = {\n capabilities: {\n browserName: 'chrome'\n },\n logLevel: 'silent',\n };\n // Create a new chrome web driver\n browser = await remote(chrome);\n}",
"async init () {\n if (this.options.launchChrome) {\n // Launch a new Chrome instance and update the instance port\n this.chromeInstance = await _launchChrome({\n headless: this.options.headless,\n disableGPU: this.options.disableGPU,\n noSandbox: this.options.chrome.noSandbox,\n port: this.options.chrome.port,\n userDataDir: this.options.chrome.userDataDir,\n launchAttempts: this.options.chrome.launchAttempts,\n handleSIGINT: this.options.chrome.handleSIGINT\n })\n this.port = this.chromeInstance.port\n }\n\n await _attachCdpToChrome.call(this, this.host, this.port, this.options.chrome.remote)\n }",
"async launchBrowser() {\n const { headless } = this.options\n try {\n // load script content from `script` folder\n this.scriptContent = await genScriptContent()\n // Launch the browser\n this.browser = await puppeteer.launch({ headless, devtools: !headless })\n return Promise.resolve({code: 0, msg: 'browser has been launch'});\n } catch (err) {\n console.log(err);\n return Promise.reject({code: 1, msg: 'browser launch error'});\n }\n }",
"function openChrome() {\r\n robot.moveMouseSmooth(59,704);\r\n setTimeout(function() {\r\n robot.mouseClick();\r\n robot.typeString(\"chrome\");\r\n robot.keyTap(\"enter\");\r\n \r\n setTimeout(openTabs,2000);\r\n },2000);\r\n}",
"function openMyPage() {\n console.log(\"injecting\");\n browser.tabs.create({\n \"url\": \"/sony-tv.html\"\n });\n}",
"function launchChromeAndRunLighthouse(url, flags = {}, config = null) {\n\treturn chromeLauncher.launch().then(chrome => {\n\t\tflags.port = chrome.port;\n\t\treturn lighthouse(url, flags, config).then(results => chrome.kill().then(() => results));\n\t});\n}",
"function openBrowser() {\n\t\tcreateService();\n\t\tvar spawn = require('child_process').spawnSync;\n\t\tspawn(GLOBAL.browser, ['http://localhost:8080']);\n\t}",
"function startChrome(port){\n\tport.postMessage({ text: \"start chrome\" });\n}",
"async function launchChromeAndRunLighthouse(url, opts, config = null) {\n\t\treturn chromeLauncher.launch({chromeFlags: opts.chromeFlags}).then(chrome => {\n\t\t\topts.port = chrome.port;\n\t\t\treturn lighthouse(url, opts, config).then(results => {\n\t \t\treturn chrome.kill().then(() => results)\n\t\t\t});\n\t\t});\n\t}",
"function launchChromeAndRunLighthouse(url, opts, config = null) {\n return chromeLauncher.launch({chromeFlags: opts.chromeFlags}).then((chrome) => {\n opts.port = chrome.port;\n return lighthouse(url, opts, config).then((results) => {\n return chrome.kill().then(() => results.lhr);\n });\n });\n}",
"spawn(uri, args, opts, callback) {\n opts = Object.assign({}, opts) // copy\n\n if (false === Array.isArray(opts.chromeFlags)) {\n opts.chromeFlags = [ opts.chromeFlags ].filter(isString)\n }\n\n if (true === opts.app) {\n let hasAppFlag = false\n for (const flag of opts.chromeFlags) {\n if (flag.startsWith('--app')) {\n hasAppFlag = true\n break\n }\n }\n\n if (false === hasAppFlag) {\n // use a bit of JavaScript as an intermediate to clean up\n // the launched chrome frame before redirecting to the URI\n const bootscript = this.constructor.bootscript(uri, opts)\n opts.chromeFlags.push('--app=' + bootscript)\n }\n } else {\n opts.startingUrl = uri\n }\n\n if (opts.headless) {\n // istanbul ignore next\n if (false === opts.chromeFlags.includes('--headless')) {\n opts.chromeFlags.push('--headless')\n }\n }\n\n // launch and return the spawned child process to the caller\n return errback(chrome.launch(opts), onbrowser)\n\n function onbrowser(err, browser) {\n // istanbul ignore next\n if (err) { return callback(err) }\n\n // return `browser.process` to the `spawn()` caller that came\n // from `chrome.launch()`\n process.nextTick(callback, null, browser.process)\n\n // call `browser.kill()` when the browser process\n // closes so the 'chrome-launcher' module can clean up\n // the 'SIGTERM' event handler and remove the browser\n // instance from its internal memory\n browser.process.once('close', onclose)\n function onclose() {\n // silent killer, ignore err\n errback(browser.kill(), (err) => {\n void err\n })\n }\n }\n }",
"function testChrome() {\n var toolbox = findElement.ID(controller.window.document, \"navigator-toolbox\");\n var tabs = findElement.ID(controller.window.document, \"tabbrowser-tabs\");\n\n let screenshot = controller.screenshot(controller.window, \"screen2\", false,\n [tabs]);\n check_screenshot(screenshot, \"screen2\", false);\n}",
"function start( next, isHeadless, options ) {\n function seleniumStarted() {\n console.log( 'seleniumrc webdriver ready on ' + options.host + ':' + options.port );\n started = true;\n starting = false;\n if ( typeof next === 'function' ) {\n return next();\n }\n }\n\n if ( started ) {\n return next(console.log('already started'));\n }\n\n if ( isHeadless ) {\n selOptions.push ( '-role');\n selOptions.push ( 'hub');\n }\n\n // selOptions.push ( '-host' );\n // selOptions.push ( options.host );\n //\n // selOptions.push ( '-port' );\n // selOptions.push ( options.port );\n\n if ( options.timeout) {\n selOptions.push( '-timeout' );\n selOptions.push( options.timeout );\n }\n\n if ( options.maxSession) {\n selOptions.push( '-maxSession' );\n selOptions.push( options.maxSession );\n }\n\n // if (options.firefoxProfile) {\n // selOptions.push('-Dwebdriver.firefox.profile=' + options.firefoxProfile);\n // console.log( 'Using Firefox profile ' + options.firefoxProfile);\n // }\n\n var spawnOptions = options['cwd'] ? {cwd: options['cwd']} : undefined;\n seleniumServerProcess = spawn( 'java', selOptions, spawnOptions );\n // selenium webdriver has a port prober in it which could be factored in.\n seleniumServerProcess.on('uncaughtException', function(err) {\n if(err.errno === 'EADDRINUSE' ){\n console.log ('PORT already IN USE, assume selenium running');\n next();\n } else {\n console.trace(err);\n process.exit(1);\n }\n });\n\n seleniumServerProcess.stderr.setEncoding('utf8');\n // parse procee output until server is actually ready, otherwise next task will break\n seleniumServerProcess.stderr.on('data', function(data) {\n var errMsg;\n data = data.trim();\n if ( isHeadless ) {\n // check for grid started, which is outputted to standard error\n if ( data.indexOf( 'Selenium Grid hub is up and running' ) > -1 ) {\n// console.log ('selenium hub ready');\n return startPhantom(next, options);\n } else if ( data.indexOf ('Address already in use') > -1 ) {\n // throw error if already started\n errMsg = 'FATAL ERROR starting selenium: ' + data + ' maybe try killall -9 java';\n throw errMsg;\n }\n } else if ( data.indexOf( 'Selenium Server is up and running' ) > -1 ) {\n // seems selenium 2.43.1 now outputs logs to standard error too so listening to standard out is redundant?\n seleniumStarted();\n } else if ( !started && data.indexOf( 'Selenium Server is up and running') > -1 ) {\n // as of 2.471 this nice clear message appears\n seleniumStarted();\n } else if ( data &&\n // throw error if something unexpected happens\n data.indexOf('org.openqa.grid.selenium.GridLauncher main') === -1 &&\n data.indexOf('Setting system property') === -1 &&\n data.indexOf('INFO') === -1 &&\n data.indexOf('WARNING') === -1 &&\n data.indexOf('Picked up') === -1 &&\n data.indexOf('Xmx3500m') === -1 &&\n !started\n ) {\n errMsg = 'FATAL ERROR starting selenium: ' + data+ ' is java runtime installed?';\n throw errMsg;\n } else if ( options.displaySeleniumLog ) {\n console.log(data);\n }\n });\n seleniumServerProcess.stdout.setEncoding('utf8');\n // seems selenium 2.43.1 now outputs logs to standard error too so this is now redundant\n // will leave for now. Tested on mac and ubuntu\n seleniumServerProcess.stdout.on('data', function( msg ) {\n console.log('STDOUT' , msg);\n // monitor process output for ready message, most recent version gives a nice clear message on standard error\n // but have left java trigger for support for older seleniums as can select in config\n if ( !started && ( msg.indexOf( 'Started Selenium Standalone' ) > -1 )) {\n seleniumStarted();\n }\n });\n\n}",
"function launchChromeAndRunLighthouse(url, flags = {}, config = null) {\n return chromeLauncher.launch(flags).then(chrome => {\n flags.port = chrome.port;\n return lighthouse(url, flags, config)\n .then(results => chrome.kill().then(() => results));\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add bold and italic text settings to all parent items | function labelTextSettingsFormatter(label, dataItem) {
if (dataItem.numChildren()) {
label.fontWeight('bold').fontStyle('italic');
}
} | [
"onItalicFontButtonClick() {\n let previousFontWeight = this.get('value.options.captionFontStyle');\n this.set('value.options.captionFontStyle', previousFontWeight !== 'italic' ? 'italic' : 'normal');\n }",
"onItalicFontButtonClick() {\n let previousFontWeight = this.get('_options.captionFontStyle');\n this.set('_options.captionFontStyle', previousFontWeight !== 'italic' ? 'italic' : 'normal');\n }",
"withTextFontWeight(fontWeight){return this.extend({fontWeight,font:\"\"});}",
"toggleItalic() {\n if (this.owner.editorModule) {\n this.owner.editorModule.toggleItalic();\n }\n }",
"setModeToText() {\n this.hideBlockMenu();\n this.showTextMenu();\n // Update the text model from the blocks\n }",
"setBold (bold=true) {\n let levels = Object.keys(LEVELS);\n for (let severity of levels) {\n if (severity === 'level') continue;\n this.levels[severity].bold = bold;\n }\n }",
"onBoldFontButtonClick() {\n let previousFontWeight = this.get('_options.captionFontWeight');\n this.set('_options.captionFontWeight', previousFontWeight !== 'bold' ? 'bold' : 'normal');\n }",
"function updateText(args, prop, item) {\n var option = {};\n var label = item.type === \"text\" ? item.textBlock : item.labels[0];\n var selectedObject = diagram._selectedObject;\n switch (prop) {\n case \"fontColor\":\n selectedObject.labelFontColor = option.fontColor = args.style.backgroundColor;\n break;\n case \"bold\":\n option.bold = selectedObject.bold = label ? !label.bold : !selectedObject.bold;\n selectedObject.boldBackgroundColor = option.bold ? \"#28B1BF\" : \"#F9F9F9\";\n selectedObject.boldFontColor = option.bold ? \"#FFFFFF\" : \"#7F7F7F\";\n break;\n case \"italic\":\n option.italic = selectedObject.italic = label ? !label.italic : !selectedObject.italic;\n selectedObject.boldBackgroundColor = option.italic ? ko.observable(\"#28B1BF\") : ko.observable(\"#F9F9F9\");\n selectedObject.boldFontColor = option.italic ? ko.observable(\"#FFFFFF\") : ko.observable(\"#7F7F7F\");\n break;\n case \"fontSize\":\n option.fontSize = Number(args.text.trim());\n break;\n case \"fontStyle\":\n option.fontFamily = args.text;\n break;\n case \"left\":\n case \"right\":\n case \"center\":\n {\n\n selectedObject.textLeftAlign = selectedObject.textRightAlign = selectedObject.textCenterAlign = false;\n selectedObject.textLeftAlignFontColor = selectedObject.textRightAlignFontColor = selectedObject.textCenterAlignFontColor = \"#7F7F7F\";\n selectedObject.textLeftAlignBackgroundColor = selectedObject.textRightAlignBackgroundColor = selectedObject.textCenterAlignBackgroundColor = \"#F9F9F9\";\n if (!(item.isSwimlane || item.isLane)) {\n option.horizontalAlignment = prop;\n option.textAlign = prop;\n if (prop == \"left\") {\n selectedObject.textLeftAlign = true;\n selectedObject.textLeftAlignFontColor = \"#FFFFFF\";\n selectedObject.textLeftAlignBackgroundColor = \"#28B1BF\";\n option.offset = ej.datavisualization.Diagram.Point(0, 0.5);\n }\n else if (prop == \"right\") {\n selectedObject.textRightAlign = true;\n selectedObject.textRightAlignFontColor = \"#FFFFFF\";\n selectedObject.textRightAlignBackgroundColor = \"#28B1BF\";\n option.offset = ej.datavisualization.Diagram.Point(1, 0.5);\n }\n else {\n selectedObject.textCenterAlign = true;\n selectedObject.textCenterAlignFontColor = \"#FFFFFF\";\n selectedObject.textCenterAlignBackgroundColor = \"#28B1BF\";\n option.offset = ej.datavisualization.Diagram.Point(0.5, 0.5);\n }\n }\n }\n break;\n\n }\n if (Object.keys(option).length > 0) {\n /* update the label properties at runtime using diagram client side API method \"updateLabel\". */\n if (item.type === \"text\") {\n /* if node type is \"text\", then will update the textblock or else will update the node's labels property. */\n diagram.updateLabel(item.name, item.textBlock, option);\n }\n else {\n for (var i = 0; i < item.labels.length; i++) {\n diagram.updateLabel(item.name, item.labels[i], option);\n }\n }\n /* binding the selected object to visualize the connector appearance in the property panel. */\n ko.applyBindings(diagram._selectedObject);\n }\n}",
"get italicButton() {\n return {\n ...super.italicButton,\n label: this.t.italicButton,\n };\n }",
"function italics(){\n bread.style.fontStyle = 'italic';\n bread.style.color = 'cornflowerblue'; \n}",
"formatBold() {\r\n\t\t\t\ttextInserter.handleEmphasis(codemirror, \"**\");\r\n\t\t\t}",
"function changeTextStyle() {\n document.getElementById(\"domStyle1\").getElementsByTagName('p')[0].style.fontStyle = \"italic\";\n document.getElementById(\"domStyle1\").getElementsByTagName('p')[0].style.textTransform = \"uppercase\";\n}",
"function styleItalic() {\n\t\tif (activeEl != undefined) {\n\t\t\t// if selected element actually has text to add style to\n\t\t\tif (activeEl.innerText != '') {\n\t\t\t\tif (activeEl.css(\"font-style\") == \"italic\") {\n\t\t\t\t\tactiveEl.css(\"font-style\", \"normal\");\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tactiveEl.css(\"font-style\", \"italic\");\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\t}",
"toggleBold() {\n if (this.owner.editorModule) {\n this.owner.editorModule.toggleBold();\n }\n }",
"function TextOptionItem() { OptionItem.apply(this, arguments); }",
"function makeItalic(elem){\n //CODE\n }",
"function styleBold() {\n\t\tif (activeEl != undefined) {\n\t\t\t// if selected element actually has text to add style to\n\t\t\tif (activeEl.innerText != '') {\n\t\t\t\tif (activeEl.css(\"font-weight\") == \"bold\") {\n\t\t\t\t\tactiveEl.css(\"font-weight\", \"normal\");\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tactiveEl.css(\"font-weight\", \"bold\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"function change(selector) {\n var ar = document.querySelectorAll(selector);\n for (var i = 0; i < ar.length; i++) {\n ar[i].style.fontStyle = \"italic\";\n ar[i].style.fontWeight = \"bold\";\n ar[i].style.textDecoration = \"underline\"\n }\n}",
"function setPageFontStyle(contianer) {\r\n Cufon.now();\r\n Cufon.replace(contianer + ' .text', {textShadow:'rgba(50 ,50 ,50 , 0.3) 1px 1px, rgba(60 ,60 ,60 , 0.2) 2px 2px, rgba(60 ,60 ,60 , 0.1) 4px 4px'});\r\n Cufon.replace(contianer + ' .textNoShadow');\r\n Cufon.replace(contianer + ' .menuItem',\r\n {\r\n hover:{\r\n textShadow:'5px 5px rgba(60,23,97, .3),-5px -5px rgba(60,23,97, .3),-5px 5px rgba(60,23,97, .3),5px -5px rgba(60,23,97, .3)',\r\n color:'#ffff00'\r\n }\r\n }\r\n );\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test whether specified constraint id is NOT a stay constraint id. | function isNotStayConstraint(cid) {
return (cid.substr(-3) != '#sc');
} | [
"function isStayConstraint(cid) {\n return (cid.substr(-3) == '#sc');\n }",
"function check_compound_constraint(constraint_id){\n\n var reverse_constraint_lookup = \n env['reverse_constraint_lookup'];\n var compound_constraint_lookup = \n env['compound_constraint_lookup'];\n\n var compound_constraint_id = \n reverse_constraint_lookup[constraint_id];\n\n var compound_constraint = \n compound_constraint_lookup[compound_constraint_id]; \n\n var result = compound_constraint(constraint_id);\n \n return result;\n }",
"function nonLitNodeConstraint (idx) {\n let c = shapeExpr.shapeExprs[idx];\n return c.type !== \"NodeConstraint\"\n || (\"nodeKind\" in c && c.nodeKind === \"literal\")\n || \"datatype\" in c\n || \"values\" in c\n ? false\n : true;\n }",
"function gml_Script_scrNotTrigger(_inst, _other, argument0) {\n return argument0 != 32775 && argument0 != 32776;\n}",
"function isUnusedID(doc, id)\n{\n if (EditObj.idCache[id] || doc.getElementById(id))\n return false;\n return true;\n}",
"function checkForConstraints() {\n if (constraint && constraint < totalTime) {\n return false;\n }\n\n return true;\n}",
"function isThislessTypeParameter(node) {\n return !node.constraint || isThislessType(node.constraint);\n }",
"function isThislessTypeParameter(node) {\n return !node.constraint || isThislessType(node.constraint);\n }",
"checkDependency(id) {\n if (id === this.id) return true;\n for (let i = 0; i < this.SubCircuit.length; i++) { if (this.SubCircuit[i].id === id) return true; }\n\n for (let i = 0; i < this.SubCircuit.length; i++) { if (scopeList[this.SubCircuit[i].id].checkDependency(id)) return true; }\n\n return false;\n }",
"function addUnenforcedConstraints( ccset, vv ) {\n // check stay constraint explicitly, since vv doesn't know about it\n var sid= stayId( vv );\n if (this.sgraph.selected[sid] === null) {\n ccset[sid]= this.sgraph.lookupNode( sid );\n }\n // other constraints\n vv.constraints.forEach( function( cc ) {\n if (this.sgraph.selected[cc] === null) {\n ccset[cc]= cc;\n }\n }, this );\n return ccset;\n}",
"get nonRepeatedConstraints() {\n return this.constraints.filter(cons => {\n return !cons.isUniqueType || !this.primaryKeyConstraints.find(pkCons => pkCons.involvesColumns(cons.columns));\n });\n }",
"isNotCurrentlyBeingEdited(candidate) {\n return current_edit_id !== candidate.id;\n }",
"isAdjacent(id) {\n if(this.getAdjacent(id) == -1)\n return false;\n\n return true;\n }",
"function not(b){ return !b; }",
"function hasBlockUnder(id) {\n\tfor(x=0; x<blocks.length; ++x) {\n\t\tif(x != id) {\n\t\t\tif(blocks[x].y == blocks[id].y + yMove && \n\t\t\t blocks[x].x == blocks[id].x) {\n\t\t\t\treturn true\n\t\t\t} else {\n\t\t\t\talert(\"Illegal Move: Cannot release block over empty space\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n}",
"function preventTransition(current, newState, diff) {\n if (!current) return false;\n\n return newState.state == current.state && Object.keys(diff.all).length == 0;\n }",
"function checkId(id) {\n if (id != restrictedChatId) {\n return false;\n }\n return true;\n}",
"function isSubstitutionPrevented(node){return noSubstitution&&node.id&&noSubstitution[node.id];}",
"function isThislessTypeParameter(node){var constraint=ts.getEffectiveConstraintOfTypeParameter(node);return!constraint||isThislessType(constraint);}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Hidden Bar Menu Config | function hiddenBarMenuConfig() {
var menuWrap = $('.hidden-bar .side-menu');
// hidding submenu
menuWrap.find('.dropdown').children('ul').hide();
// toggling child ul
menuWrap.find('li.dropdown > a').each(function () {
$(this).on('click', function (e) {
e.preventDefault();
$(this).parent('li.dropdown').children('ul').slideToggle();
// adding class to item container
$(this).parent().toggleClass('open');
return false;
});
});
} | [
"function hiddenBarMenuConfig() {\n\t\tvar menuWrap = $('.main-nav-box .navigation > li.dropdown > ul');\n\t\t// hidding submenu \n\t\tmenuWrap.find('.dropdown').children('ul').hide();\n\t\t// toggling child ul\n\t\tmenuWrap.find('li.dropdown > a').each(function () {\n\t\t\t$(this).on('click', function (e) {\n\t\t\t\te.preventDefault();\n\t\t\t\t$(this).parent('li.dropdown').children('ul').slideToggle();\n\t\n\t\t\t\t// adding class to item container\n\t\t\t\t$(this).parent().toggleClass('open');\n\t\n\t\t\t\treturn false;\n\t\n\t\t\t});\n\t\t});\n\t}",
"function hiddenBarMenuConfig() {\n var menuWrap = $(\".hidden-bar .side-menu\");\n\n // hidding submenu\n\n menuWrap.find(\".dropdown\").children(\"ul\").hide();\n\n // toggling child ul\n\n menuWrap.find(\"li.dropdown > a\").each(function () {\n $(this).on(\"click\", function (e) {\n e.preventDefault();\n\n $(this).parent(\"li.dropdown\").children(\"ul\").slideToggle();\n\n // adding class to item container\n\n $(this).parent().toggleClass(\"open\");\n\n return false;\n });\n });\n }",
"function hiddenBarMenuConfig() {\n\t\tvar menuWrap = $('.hidden-bar .side-menu');\n\t\t// appending expander button\n\t\tmenuWrap.find('.dropdown').children('a').append(function () {\n\t\t\treturn '<button type=\"button\" class=\"btn expander\"><i class=\"icon fa fa-bars\"></i></button>';\n\t\t});\n\t\t// hidding submenu \n\t\tmenuWrap.find('.dropdown').children('ul').hide();\n\t\t// toggling child ul\n\t\tmenuWrap.find('.btn.expander').each(function () {\n\t\t\t$(this).on('click', function () {\n\t\t\t\t$(this).parent() // return parent of .btn.expander (a) \n\t\t\t\t\t.parent() // return parent of a (li)\n\t\t\t\t\t\t.children('ul').slideToggle();\n\t\n\t\t\t\t// adding class to expander container\n\t\t\t\t$(this).parent().toggleClass('current');\n\t\t\t\t// toggling arrow of expander\n\t\t\t\t$(this).find('i').toggleClass('fa-minus fa-bars');\n\t\n\t\t\t\treturn false;\n\t\n\t\t\t});\n\t\t});\n\t}",
"function hiddenBarMenuConfig() {\n\t\tvar menuWrap = $('.hidden-bar .side-menu');\n\t\t// appending expander button\n\t\tmenuWrap.find('.dropdown').children('a').append(function () {\n\t\t\treturn '<button type=\"button\" class=\"btn expander\"><i class=\"fa fa-angle-down\"></i></button>';\n\t\t});\n\t\t// hidding submenu \n\t\tmenuWrap.find('.dropdown').children('ul').hide();\n\t\t// toggling child ul\n\t\tmenuWrap.find('.btn.expander').each(function () {\n\t\t\t$(this).on('click', function () {\n\t\t\t\t$(this).parent() // return parent of .btn.expander (a) \n\t\t\t\t\t.parent() // return parent of a (li)\n\t\t\t\t\t\t.children('ul').slideToggle();\n\t\n\t\t\t\t// adding class to expander container\n\t\t\t\t$(this).parent().toggleClass('current');\n\t\t\t\t// toggling arrow of expander\n\t\t\t\t$(this).find('i').toggleClass('');\n\t\n\t\t\t\treturn false;\n\t\n\t\t\t});\n\t\t});\n\t}",
"function hiddenBarMenuConfig() {\n\t\tvar menuWrap = $('.hidden-bar .side-menu');\n\t\t// appending expander button\n\t\tmenuWrap.find('.dropdown').children('a').append(function () {\n\t\t\treturn '<button type=\"button\" class=\"btn expander\"><i class=\"icon fa fa-angle-right\"></i></button>';\n\t\t});\n\t\t// hidding submenu\n\t\tmenuWrap.find('.dropdown').children('ul').hide();\n\t\t// toggling child ul\n\t\tmenuWrap.find('.btn.expander').each(function () {\n\t\t\t$(this).on('click', function () {\n\t\t\t\t$(this).parent() // return parent of .btn.expander (a)\n\t\t\t\t\t.parent() // return parent of a (li)\n\t\t\t\t\t\t.children('ul').slideToggle();\n\n\t\t\t\t// adding class to expander container\n\t\t\t\t$(this).parent().toggleClass('current');\n\t\t\t\t// toggling arrow of expander\n\t\t\t\t$(this).find('i').toggleClass('fa-angle-right fa-angle-down');\n\n\t\t\t\treturn false;\n\n\t\t\t});\n\t\t});\n\t}",
"function hiddenBarMenuConfig() {\r\n var menuWrap = $('.hidden-bar .side-menu');\r\n // appending expander button\r\n menuWrap.find('.dropdown').children('a').append(function() {\r\n return '<button type=\"button\" class=\"btn expander\"><i class=\"icon fa fa-angle-down\"></i></button>';\r\n });\r\n // hidding submenu \r\n menuWrap.find('.dropdown').children('ul').hide();\r\n // toggling child ul\r\n menuWrap.find('.btn.expander').each(function() {\r\n $(this).on('click', function() {\r\n $(this).parent() // return parent of .btn.expander (a) \r\n .parent() // return parent of a (li)\r\n .children('ul').slideToggle();\r\n\r\n // adding class to expander container\r\n $(this).parent().toggleClass('current');\r\n // toggling arrow of expander\r\n $(this).find('i').toggleClass('fa-angle-up fa-angle-down');\r\n\r\n return false;\r\n\r\n });\r\n });\r\n }",
"function hideMobileBar(){\n\t\t\t$(menu).show(0);\n\t\t\t$(showHideButton).hide(0);\n\t\t}",
"function showBarMenu() {\n E.showMenu({\n '': {\n 'title': 'Bar',\n 'back': showMainMenu\n },\n 'Enable while locked': {\n value: config.bar.enabledLocked,\n onchange: value => {\n config.bar.enableLocked = value;\n saveSettings();\n }\n },\n 'Enable while unlocked': {\n value: config.bar.enabledUnlocked,\n onchange: value => {\n config.bar.enabledUnlocked = value;\n saveSettings();\n }\n },\n 'Mode': {\n value: BAR_MODE_OPTIONS.map(item => item.val).indexOf(config.bar.type),\n format: value => BAR_MODE_OPTIONS[value].name,\n onchange: value => {\n config.bar.type = BAR_MODE_OPTIONS[value].val;\n saveSettings();\n },\n min: 0,\n max: BAR_MODE_OPTIONS.length - 1,\n wrap: true\n },\n 'Day progress': () => {\n E.showMenu({\n '': {\n 'title': 'Day progress',\n 'back': showBarMenu\n },\n 'Color': {\n value: COLOR_OPTIONS.map(item => colorString(item.val)).indexOf(colorString(config.bar.dayProgress.color)),\n format: value => COLOR_OPTIONS[value].name,\n min: 0,\n max: COLOR_OPTIONS.length - 1,\n wrap: false,\n onchange: value => {\n config.bar.dayProgress.color = COLOR_OPTIONS[value].val;\n saveSettings();\n }\n },\n 'Start hour': {\n value: Math.floor(config.bar.dayProgress.start / 100),\n format: hourToString,\n min: 0,\n max: 23,\n wrap: true,\n onchange: hour => {\n minute = config.bar.dayProgress.start % 100;\n config.bar.dayProgress.start = (100 * hour) + minute;\n saveSettings();\n }\n },\n 'Start minute': {\n value: config.bar.dayProgress.start % 100,\n min: 0,\n max: 59,\n wrap: true,\n onchange: minute => {\n hour = Math.floor(config.bar.dayProgress.start / 100);\n config.bar.dayProgress.start = (100 * hour) + minute;\n saveSettings();\n }\n },\n 'End hour': {\n value: Math.floor(config.bar.dayProgress.end / 100),\n format: hourToString,\n min: 0,\n max: 23,\n wrap: true,\n onchange: hour => {\n minute = config.bar.dayProgress.end % 100;\n config.bar.dayProgress.end = (100 * hour) + minute;\n saveSettings();\n }\n },\n 'End minute': {\n value: config.bar.dayProgress.end % 100,\n min: 0,\n max: 59,\n wrap: true,\n onchange: minute => {\n hour = Math.floor(config.bar.dayProgress.end / 100);\n config.bar.dayProgress.end = (100 * hour) + minute;\n saveSettings();\n }\n },\n 'Reset hour': {\n value: Math.floor(config.bar.dayProgress.reset / 100),\n format: hourToString,\n min: 0,\n max: 23,\n wrap: true,\n onchange: hour => {\n minute = config.bar.dayProgress.reset % 100;\n config.bar.dayProgress.reset = (100 * hour) + minute;\n saveSettings();\n }\n },\n 'Reset minute': {\n value: config.bar.dayProgress.reset % 100,\n min: 0,\n max: 59,\n wrap: true,\n onchange: minute => {\n hour = Math.floor(config.bar.dayProgress.reset / 100);\n config.bar.dayProgress.reset = (100 * hour) + minute;\n saveSettings();\n }\n }\n });\n },\n 'Calendar bar': () => {\n E.showMenu({\n '': {\n 'title': 'Calendar bar',\n 'back': showBarMenu\n },\n 'Look ahead duration': {\n value: config.bar.calendar.duration,\n format: value => {\n let hours = value / 3600;\n let minutes = (value % 3600) / 60;\n let seconds = value % 60;\n\n let result = (hours == 0) ? '' : `${hours} hr`;\n if (minutes != 0) {\n if (result == '') result = `${minutes} min`;\n else result += `, ${minutes} min`;\n }\n if (seconds != 0) {\n if (result == '') result = `${seconds} sec`;\n else result += `, ${seconds} sec`;\n }\n return result;\n },\n onchange: value => {\n config.bar.calendar.duration = value;\n saveSettings();\n },\n min: 900,\n max: 86400,\n step: 900\n },\n 'Pipe color': {\n value: COLOR_OPTIONS.map(color => colorString(color.val)).indexOf(colorString(config.bar.calendar.pipeColor)),\n format: value => COLOR_OPTIONS[value].name,\n onchange: value => {\n config.bar.calendar.pipeColor = COLOR_OPTIONS[value].val;\n saveSettings();\n },\n min: 0,\n max: COLOR_OPTIONS.length - 1,\n wrap: true\n },\n 'Default color': {\n value: COLOR_OPTIONS.map(color => colorString(color.val)).indexOf(colorString(config.bar.calendar.defaultColor)),\n format: value => COLOR_OPTIONS[value].name,\n onchange: value => {\n config.bar.calendar.defaultColor = COLOR_OPTIONS[value].val;\n saveSettings();\n },\n min: 0,\n max: COLOR_OPTIONS.length - 1,\n wrap: true\n }\n });\n }\n });\n }",
"function hideMenu() {\n\t\tmenu.Hide();\n\t\ttileTouchController.enableInput();\n\t\tcameraMovement.enableInput();\n\t}",
"HideMenus() {\n this.HideMenuSubs();\n this.HideMenusAuds();\n }",
"function show_menu(visible) {\n var setit = visible ? \"octo-off-screen\" : \"octo-on-screen\";\n PUBNUB.$(\"octo-group\").className = setit;\n PUBNUB.$(\"numbers-group\").className = setit;\n PUBNUB.$(\"labels-group\").className = setit;\n}",
"function hideMenu(){\n menu.classList.add('menu_closed');\n showScrollBar();\n }",
"function TaskbarMenu(){}",
"function showMobileBar(){\n\t\t\t$(menu).hide(0);\n\t\t\t$(showHideButton).show(0).click(function(){\n\t\t\t\tif($(menu).css(\"display\") == \"none\")\n\t\t\t\t\t$(menu).slideDown(settings.showSpeed);\n\t\t\t\telse\n\t\t\t\t\t$(menu).slideUp(settings.hideSpeed).find(\".dropdown, .megamenu\").hide(settings.hideSpeed);\n\t\t\t});\n\t\t}",
"checkMenu() {\n const { buttons } = this.elements.settings;\n const visible = !is.empty(buttons) && Object.values(buttons).some(button => !button.hidden);\n\n toggleHidden(this.elements.settings.menu, !visible);\n }",
"function showMobileBar(){\n\t\t\t$(menu).hide(0);\n\t\t\t$(showHideButton).show(0).click(function(e){\n\t\t\t\te.preventDefault();\n\t\t\t\tif($(menu).css(\"display\") == \"none\")\n\t\t\t\t\t$(menu).slideDown(settings.showSpeed);\n\t\t\t\telse\n\t\t\t\t\t$(menu).slideUp(settings.hideSpeed).find(\".dropdown, .megamenu\").hide(settings.hideSpeed);\n\t\t\t});\n\t\t}",
"function hideShowMenu() {\r\n \r\n if (isActive) {\r\n this.innerHTML = iconArray[0];\r\n document.getElementById(\"menu-options\").style.display = \"none\";\r\n isActive = false;\r\n }\r\n else {\r\n this.innerHTML = iconArray[1];\r\n document.getElementById(\"menu-options\").style.display = \"block\";\r\n isActive = true;\r\n }\r\n}",
"checkMenu() {\n const {\n buttons\n } = this.elements.settings;\n const visible = !is.empty(buttons) && Object.values(buttons).some(button => !button.hidden);\n toggleHidden(this.elements.settings.menu, !visible);\n }",
"checkMenu() {\n const {\n buttons\n } = this.elements.menu.settings;\n const visible = !is.empty(buttons) && Object.values(buttons).some(button => !button.hidden);\n toggleHidden(this.elements.menu.settings.menu, !visible);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates secondary character bodies | function spawnSecondaryCharacters(x, y, elementId) {
var boxSd = new b2BoxDef();
boxSd.density = 0.1;
boxSd.friction = 0.0; //1.0 or 1.4
boxSd.restitution = 0.1; // 0.4
boxSd.extents.Set(20, 20); // 20 30
boxSd.userData = document.getElementById(elementId);
var boxBd = new b2BodyDef();
boxBd.AddShape(boxSd);
boxBd.preventRotation = true;
boxBd.position.Set(x,y);
var playerBody = game.world.CreateBody(boxBd);
return playerBody;
} | [
"function createWorld() \n{\n //gravity vector x, y - 10 m/s2 - thats earth!!\n\tvar gravity = new b2Vec2(0, -9.8);//create a new gravity\n\n\tworld = new b2World(gravity , true );//create a new world\n\t//setup debug draw\n\tvar debugDraw = new b2DebugDraw();\n\tdebugDraw.SetSprite(document.getElementById(\"canvas\").getContext(\"2d\"));\n\tdebugDraw.SetDrawScale(scale);\n\tdebugDraw.SetFillAlpha(0.5);\n\tdebugDraw.SetLineThickness(1.0);\n\tdebugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);\n\n\tworld.SetDebugDraw(debugDraw);\n\n\t//createground(world);\n\tground = createBox(world, 7.33, 0.2, 7.3 , 0.2, 1.0, {type : b2Body.b2_staticBody}),\n createBox(world,13, 0.2, 0.2 , 5, 1.0, {type : b2Body.b2_staticBody});\n\n var a = createBox(world, 9.8, 3, 2.8, 0.125, 1); \n var b = createBox(world, 9.8, 1.4, 0.25, 1, 1, {type : b2Body.b2_staticBody});\n var c = createBox(world, 12.5, 1.4, 0.125 , 0.5 , 2);\n var d = createBox(world, 7.1, 1.4, 0.125, 0.5 ,1);\n\n addjoint1(a,b);\n addjoint2(a,c);\n addjoint3(a,d);\n addjoint4(c,d);\n\n\n\treturn world;\n}",
"function Body(ent) {\n\tthis.entity = ent;\n\tvar debugName = function() { return ent.name + \".body\"; };\n\t// Body stats\n\tthis.muscleTone = new Stat(0);\n\tthis.muscleTone.debug = function() { return debugName() + \".muscleTone\"; }\n\tthis.bodyMass = new Stat(0);\n\tthis.bodyMass.debug = function() { return debugName() + \".bodyMass\"; }\n\tthis.height = new Stat(175); // cm\n\tthis.height.debug = function() { return debugName() + \".height\"; }\n\t// TODO: fix?\n\tthis.weigth = new Stat(65); // kg\n\tthis.weigth.debug = function() { return debugName() + \".weigth\"; }\n\t\n\tthis.femininity = new Stat(0);\n\tthis.femininity.debug = function() { return debugName() + \".femininity\"; }\n\t\n\t// BODYPARTS\n\t// Head\n\tthis.head = new Head();\n\t\n\t// Torso\n\tthis.torso = new BodyPart();\n\tthis.torso.hipSize = new Stat(1); // TODO: Default\n\tthis.torso.hipSize.debug = function() { return debugName() + \".hipSize\"; }\n\t// Add slots for wings, tails and such\n\tthis.backSlots = new Array();\n\t\n\t// Genetalia\n\tthis.gen = new Genitalia(this);\n\tthis.cock = new Array();\n\tthis.balls = new Balls();\n\t\n\tthis.vagina = new Array();\n\tthis.ass = new Butt();\n\t\n\tthis.breasts = new Array();\n\tthis.breasts.push(new Breasts());\n\t\n\t// Arms and legs\n\tthis.arms = new BodyPart();\n\tthis.arms.count = 2;\n\tthis.legs = new BodyPart();\n\tthis.legs.count = 2;\n}",
"function createBody() {\n var bodyObj = new THREE.Object3D();\n\n var bodyDimen = [ [0, 0],\n [paramsMikey.bodyWidth*1.5/5, 1],\n [paramsMikey.bodyWidth*4/5, paramsMikey.bodyHeight/5],\n [paramsMikey.bodyWidth, paramsMikey.bodyHeight/2],\n [paramsMikey.bodyWidth*3/5, paramsMikey.bodyHeight*9/10],\n [paramsMikey.bodyWidth*1/5, paramsMikey.bodyHeight-1],\n [0, paramsMikey.bodyHeight]]; //body dimension\n\n var bodyCurve = new THREE.CatmullRomCurve3( makeVertices(bodyDimen) );\n var bodyGeom = new THREE.LatheGeometry( bodyCurve.getPoints(20) );\n\n bodyMesh = new THREE.Mesh (bodyGeom, bodyMaterials.bodyMat);\n\n bodyMesh.add(createHorn(1));\n bodyMesh.add(createHorn(-1));\n bodyMesh.add(createEye());\n bodyMesh.add(createLimb(1, \"leg\"));\n bodyMesh.add(createLimb(-1, \"leg\"));\n bodyMesh.add(createLimb(1, \"arm\"));\n bodyMesh.add(createLimb(-1, \"arm\"));\n bodyMesh.add(createSmile());\n\n bodyObj.add(bodyMesh);\n return bodyObj;\n }",
"function createBody(bbody) {\n let bodyMaterial = new THREE.MeshPhongMaterial({shininess: 100});\n bodyMaterial.color.setRGB(31 / 255, 86 / 255, 169 / 255);\n bodyMaterial.specular.setRGB(0.5, 0.5, 0.5);\n bodyMaterial.ambient.copy(bodyMaterial.color);\n\n let glassMaterial = new THREE.MeshPhongMaterial({\n color: 0x0,\n specular: 0xFFFFFF,\n shininess: 100,\n opacity: 0.3,\n transparent: true\n });\n glassMaterial.ambient.copy(glassMaterial.color);\n\n let crossbarMaterial = new THREE.MeshPhongMaterial({color: 0x808080, specular: 0xFFFFFF, shininess: 400});\n crossbarMaterial.ambient.copy(crossbarMaterial.color);\n\n // body\n sphere = new THREE.Mesh(\n new THREE.SphereGeometry(104 / 2, 32, 16, 0, Math.PI * 2, Math.PI / 2, Math.PI), bodyMaterial);\n sphere.position.x = 0;\n sphere.position.y = 160;\n sphere.position.z = 0;\n bbody.add(sphere);\n\n // cap for top of hemisphere\n cylinder = new THREE.Mesh(\n new THREE.CylinderGeometry(104 / 2, 104 / 2, 0, 32), bodyMaterial);\n cylinder.position.x = 0;\n cylinder.position.y = 160;\n cylinder.position.z = 0;\n bbody.add(cylinder);\n\n cylinder = new THREE.Mesh(\n new THREE.CylinderGeometry(12 / 2, 12 / 2, 390 - 100, 32), bodyMaterial);\n cylinder.position.x = 0;\n cylinder.position.y = 160 + 390 / 2 - 100;\n cylinder.position.z = 0;\n bbody.add(cylinder);\n\n // glass stem\n sphere = new THREE.Mesh(\n new THREE.SphereGeometry(116 / 2, 32, 16), glassMaterial);\n sphere.position.x = 0;\n sphere.position.y = 160;\n sphere.position.z = 0;\n bbody.add(sphere);\n\n cylinder = new THREE.Mesh(\n new THREE.CylinderGeometry(24 / 2, 24 / 2, 390, 32), glassMaterial);\n cylinder.position.x = 0;\n cylinder.position.y = 160 + 390 / 2;\n cylinder.position.z = 0;\n bbody.add(cylinder);\n\n // crossbar\n cylinder = new THREE.Mesh(\n new THREE.CylinderGeometry(5, 5, 200, 32), crossbarMaterial);\n cylinder.position.set(0, 360, 0);\n cylinder.rotation.x = 90 * Math.PI / 180.0;\n bbody.add(cylinder);\n}",
"function placeUniversLines(allStr : String[], main : Main, sentence : GameObject[], table : GameObject[], allTexts : Array, blackOrWhite : boolean){\n\t// CREATE object\n\tfor(var i=0 ; i < allStr.length ; i++){\n\t\tDebug.Log(\"zDEFAULT: \" + main.getZDEFAULT() + \"zSTEP: \" + main.getZSTEP());\n//\t\tDebug.Log(\"palceUniversLine, z = \"+ (main.getZDEFAULT() + i*main.getZSTEP()));\n\t\ttablePos[i] = Vector3(Random.Range(xMin, xMax), Random.Range(yMin, yMax), main.getZDEFAULT() + i*main.getZSTEP()); // random starting position\n\t\ttableSpeed[i] = Random.Range(speedMin, speedMax);// compute random speed\n\t\t\n\t\t//create the sentences\n\t\tsentence = textFunctions.CreateText(allStr[i], i , tablePos[i], table, i, size, 0, blackOrWhite); \n\t\tallTexts.push(sentence);\n\t\t\n\t\t//we choose a radius\n\t/*\tvar radius : float = textFunctions.ComputeRandomRadius(sentence);\n\t\ttableRadius[i] = Vector3(radius,0,0);\n\t\t\n\t\t//we place the letters\n\t\t\n\t\tif (i%3 == 1) \n\t\t\ttextFunctions.PlaceVortexText(sentence, Vector3(tablePos[i].x, tablePos[i].y - tableRadius[i].x, tablePos[i].z));\n\t\telse if (i%3 == 2) \n\t\t\ttextFunctions.PlaceCircleText(sentence , radius , Random.Range(0,360), tablePos[i]);\n\t\telse \n\t\t\ttextFunctions.PlaceSinusoideText(sentence, Vector3(tablePos[i].x, tablePos[i].y - tableRadius[i].x, tablePos[i].z), tableAmp[i]/2, tablePer[i]);\n\t\t*/\n\t\ttextFunctions.placeTextLine(tablePos[i], sentence);\n\t}\n}",
"function buildUfoBody(){\n // UFO Body top half\n ctx.beginPath();\n ctx.ellipse(xBase, yBase, 100, 30, 0, Math.PI, 0);\n ctx.fillStyle = 'rgb(0, 0, 0)'\n ctx.fill();\n\n // UFO Body bottom half\n ctx.beginPath();\n ctx.ellipse(xBase, yBase + 2, 100, 10, 0, 0, Math.PI);\n ctx.fillStyle = 'rgb(0, 0, 0)'\n ctx.fill();\n\n // UFO Base\n ctx.beginPath();\n ctx.ellipse(xBase, yBase + 14, 50, 12, 0, 0, Math.PI);\n ctx.fillStyle = 'rgb(0, 0, 0)'\n ctx.fill();\n\n // UFO Cabin\n ctx.beginPath();\n ctx.ellipse(xBase, yBase - 20, 40, 50, 0, Math.PI, 0);\n ctx.fillStyle = 'rgb(0, 0, 0)'\n ctx.lineWidth = 3.0\n ctx.stroke();\n}",
"createBody()\n {\n const materialsBody = faceTexture('torch/side-on', 'torch/side-on', 'torch/top-on', 'torch/back')\n\n const body = new THREE.Mesh(\n new THREE.BoxBufferGeometry(0.6, 2.8, 0.6),\n materialsBody\n )\n body.position.y = 1.2\n if(this.onWall)\n {\n body.rotation.x = Math.PI*0.25\n body.position.y = 1\n body.position.z = 0.8\n }\n this.threeObject.add(body)\n burningSoundManager(this, true)\n\n return body\n }",
"function setupBody() {\n // start at the ground\n var last = ground;\n\n var bodyOffset = -offsetY + bodyYOffset;\n\n for ( var i = 0; i < SEGMENTS; i++ ) {\n var anchor, db;\n var def = bodySegmentDef;\n\n if ( i == SEGMENTS - 1 ) {\n def.density = 0.5;\n }\n\n db = world.createDynamicBody(Vec2(bodyXOffset, bodyOffset + (i * step) ));\n db.createFixture(shape, bodySegmentDef);\n\n // put the anchor right between the two segments we are joining, attached to the last object\n var anchor = Vec2(bodyXOffset, bodyOffset + (i * step) - step/2);\n world.createJoint(pl.RevoluteJoint(bodyJointDef, last, db, anchor));\n \n last = db;\n \n points.push(db);\n }\n\n // the head is the last element in the array\n head = points[SEGMENTS-1];\n \n // pick a vaguely random segment to join arms to\n torso = points[SEGMENTS-random([2, 3])];\n}",
"function createBox2DBody() {\n // BODY\n var bodyDef = new box2d.b2BodyDef();\n bodyDef.type = box2d.b2Body.b2_dynamicBody;\n bodyDef.angle = 0;\n bodyDef.angularDamping = 0.2;\n bodyDef.position.Set( 1000/SCALE, 1470/SCALE); //canvas.height / 2 / SCALE;\n bodyDef.userData = \"body name\";\n var body = world.CreateBody(bodyDef);\n \n // FIXTURES\n var fixDef = new box2d.b2FixtureDef();\n fixDef.density = 100.;\n fixDef.friction = 0.6;\n fixDef.restitution = 0.0;\n fixDef.shape = new box2d.b2PolygonShape;\n fixDef.shape.SetAsBox((70 / 2 / SCALE), (136 / 2 / SCALE));\n fixDef.filter.categoryBits = CAT.SHIP;\n fixDef.filter.maskBits = CAT.GROUND | CAT.SOLDIER_FOOT_SENSOR;\n fixDef.userData = \"fixture name\";\n body.CreateFixture(fixDef);\n \n return body;\n }",
"function createBody() {\n\tvar a = Math.floor(Math.random() * robotBodyList.length);\n\tvar newBody = robotBodyList[a];\n\tvar defenseBoost = Math.floor(Math.random() * 5);\n\tnewBody.defense += defenseBoost;\n\tvar speedBoost = Math.floor(Math.random() * 5);\n\tnewBody.speed += speedBoost;\n\tnewBody.powerConsumption += (defenseBoost + speedBoost);\n\treturn newBody;\n}",
"function generateWorld() {\n\t\t/**\n\t\t * Initialize the arrays with 0\n\t\t */\n\t\tfor (var j = 0; j <= 14; j++) {\n\t\t\tfor (var i = 0; i <= 18; i++) {\n\t\t\t\tbrick_array[i][j] = 0;\n\t\t\t\tentity_array[i][j] = 0;\n\t\t\t\tgoody_array[i][j] = 0;\n\t\t\t}\n\t\t};\n\t\t\n\t\tfor(var j = 0; j <=14; j++) {\n\t\t\tfor(var i = 0; i <=18; i++) {\n\t\t\t\t\n\t\t\t\tif(generateWall(i, j)) { \n\t\t\t\t Crafty.e(\"2D, DOM, wall\")\n\t\t\t\t .attr({ x: i * 32, y: j * 32, z: 3 })\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(generateBricks(i, j)) {\n\t\t\t\t\tentity_array[i][j] = Crafty.e(\"2D, DOM, brick, solid, explodable\")\n\t\t\t\t\t\t.attr({ x: i * 32, y: j * 32, z: 3 })\n\t\t\t\t\t\t.bind('explode', function() {\n\t\t\t\t\t\t\tCrafty.e(\"SetBurningBrick\")\n\t\t\t\t\t\t\t\t.setBurningBrick(this.x, this.y);\n this.destroy();\n })\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t/**\n\t\t * Print the values of the array to the console \n\t\t */\n\n\t\t//console.log(string);\n\t}",
"function penguin(x, y, scale, feetColor, mainBodyColor, innerBodyColor) {\n stroke(feetColor);\n fill(feetColor);\n rect(x - (scale * 0.25), y + (scale * 0.45), scale * 0.2, scale * 0.075, scale * 0.025); //left foot (150, 290, 40, 15, 5)\n rect(x + (scale * 0.05), y + (scale * 0.45), scale * 0.2, scale * 0.075, scale * 0.025); //right foot (210, 290, 40, 15, 5)\n stroke(mainBodyColor);\n fill(mainBodyColor);\n ellipse(x, y, scale * 0.75, scale); //main body (200, 200, 150, 200)\n stroke(innerBodyColor);\n fill(innerBodyColor);\n ellipse(x, y + (scale * 0.125), scale * 0.575); //inner body (200, 225, 115)\n ellipse(x - (scale * 0.1), y - (scale * 0.325), scale * 0.1, scale * 0.15); //eyes (180, 135, 20, 30)\n ellipse(x + (scale * 0.1), y - (scale * 0.325), scale * 0.1, scale * 0.15); //eyes (220, 135, 20, 30)\n stroke(mainBodyColor);\n fill(mainBodyColor);\n ellipse(x - (scale * 0.085), y - (scale * 0.3), scale * 0.05, scale * 0.075); //pupil (183, 140, 10, 15)\n ellipse(x + (scale * 0.085), y - (scale * 0.3), scale * 0.05, scale * 0.075); //pupil (217, 140, 10, 15)\n stroke(mainBodyColor);\n fill(feetColor);\n triangle(x - (scale * 0.1), y - (scale * 0.175), x, y - (scale * 0.125), x + (scale * 0.1), y - (scale * 0.175)); //beak (180, 165; 200, 175; 220, 165)\n}",
"createBody() {\n var precision = 30; // Number of radial segments\n var bodyRadius = this.bodyWidth * 0.5;\n\n // Creates the base cylinder\n var bodyGeometry = new THREE.CylinderGeometry(bodyRadius, bodyRadius, this.bodyHeight, precision)\n var body = new THREE.Mesh(bodyGeometry, this.materialBody);\n\n // Positions the body over the axis\n body.translateX((-(bodyRadius)) - (this.legHeight * 0.125 / 2));\n body.translateY(-(this.bodyHeight / 2) + (this.headRadius / 2) + (0.25 * this.legHeight));\n\n body.castShadow = true;\n this.body = body;\n body.add(this.createHead());\n\n return body;\n }",
"function draw_bodies() {\n clear_canvas();\n for(var i=0; i < bodies.length; i++) {\n draw_body(bodies[i]);\n }\n\tif (draw_barycenters) {\n\t\tdraw_all_barycenters();\n\t}\n}",
"function createFrame(){\n\n\t\tlet type = b2Body.b2_staticBody;\n let div = (ch2 / 15 + 5) * Math.sqrt(2) * 6;\n\t\t// Remover\n\t\t//let removerb1 = manager.createBody(type, canvas.width * 0.05, canvas.height /2 , canvas.height, 10, 90);\n\t\t//removerb1.SetUserData({tag: TAG_REMOVERB});\n\t\t//let removerb2 = manager.createBody(type, canvas.width * 0.95, canvas.height /2 , canvas.height, 10, 90);\n\t\t//removerb2.SetUserData({tag: TAG_REMOVERB});\n\n\t\t//let remover3 = manager.createBody(type, canvas.width /2 , canvas.height * 0.15, canvas.width * 0.9 -radiusball * 3.75, 10, 0);\n\t\t//remover3.SetUserData({tag: TAG_REMOVER});\n\t\t//let remover4 = manager.createBody(type, canvas.width /2 , canvas.height * 0.85, canvas.width * 0.9 -radiusball * 3.75, 10, 0);\n\t\t//remover4.SetUserData({tag: TAG_REMOVER});\n\n\t\t//let remover5 = manager.createBody(type, canvas.width /2 , canvas.height * 0.15, canvas.width * 0.9 -radiusball * 3.75, 10, 0);\n\t\t//let remover5 = manager.createCircle(type, canvas.width * 25 / 100, canvas.height * 50 / 100, CirImga, radiusball / 2, 0, null, null, null);\n\t\t//remover5.SetUserData({tag: TAG_REMOVERC});\n\n\n\n\t//\tlet remover5 = manager.createBody(type, canvas.width /2 - div, ch2 *3/4 -10, ch2 /4, 10, 45);\n\t//\tremover5.SetUserData({tag: TAG_REMOVER});\n\t//\tlet remover6 = manager.createBody(type, canvas.width /2 + div, ch2 *3/4 -10, ch2 /4, 10, 45);\n\t//\tremover6.SetUserData({tag: TAG_REMOVER});\n\n\t\t//manager.createBody(type, 100, 240, 220, 5, +15);\n\t\t//manager.createBody(type, 30, 200, 70, 5, +45);\n\t\t//manager.createBody(type, 380, 240, 220, 5, -15);\n\t\t//manager.createBody(type, 450, 200, 70, 5, -45);\n\t}",
"function drawBody() {\n fill(bodyColor);\n stroke(bodyColor);\n strokeWeight(3);\n\n // collect the points\n let leftSide = [];\n let rightSide = [];\n for ( var i = 0; i < points.length; i++) {\n var f = points[i].getFixtureList();\n var t = f.m_body.getTransform();\n var s = f.getShape();\n var v, p;\n\n v = s.m_vertices[0];\n p = mulVec2(t, v);\n leftSide.push(p);\n\n v = s.m_vertices[3];\n p = mulVec2(t, v);\n leftSide.push(p);\n\n \n v = s.m_vertices[1];\n p = mulVec2(t, v);\n rightSide.push(p);\n\n v = s.m_vertices[2];\n p = mulVec2(t, v);\n rightSide.push(p);\n }\n\n // draw the body\n if ( leftSide.length > 0 ) {\n beginShape();\n\n for ( var i = 0; i < leftSide.length; i++ ) {\n var p = toScreen(leftSide[i]);\n vertex(p.x, p.y);\n }\n for ( var i = rightSide.length - 1; i >= 0; i-- ) {\n var p = toScreen(rightSide[i]);\n vertex(p.x, p.y);\n }\n\n var p = toScreen(leftSide[0]);\n vertex(p.x, p.y);\n\n endShape();\n }\n\n}",
"function setupWorld() {\n\tworld = new b2World(new b2Vec2(0, gravity), false); //gravity in Y direction\n\tif (visualize) {\n\t\tif (stage === undefined) {\n\t\t\tstage = new Stage(\"c\");\n\t\t}\n\t\tendVis();\n\t\tvar bg = new Bitmap(new BitmapData(\"static/images/wallpaper.png\"));\n\t\tbg.scaleX = bg.scaleY = scale;\n\t\tstage.addChild(bg);\n\t}\n\n\t//ground\n\tcreateBox(width = centerX,\n\t\theight = 0.1,\n\t\tx = centerX,\n\t\ty = fullY - 0.1,\n\t\tangle = 0,\n\t\ttype = b2Body.b2_staticBody,\n\t\tdensity = 10,\n\t\tfriction = 1,\n\t\trestitution = 0,\n\t\tuserData = \"box\",\n\t\timg = \"static/images/ground.png\"\n\t);\n\n\t//table\n\tcreateBox(0.1, 0.4, centerX - 1, fullY - 0.4 - 0.2, 0, b2Body.b2_staticBody, table_density, table_friction, table_restitution, \"left_leg\", \"static/images/table_leg.png\");\n\tcreateBox(0.1, 0.4, centerX + 1, fullY - 0.4 - 0.2, 0, b2Body.b2_staticBody, table_density, table_friction, table_restitution, \"right_leg\", \"static/images/table_leg.png\");\n\tcreateBox(1.5, 0.1, centerX, fullY - 0.1 - 0.80 - 0.18, 0, b2Body.b2_staticBody, table_density, table_friction, table_restitution, \"table\", \"static/images/table_top.png\");\n\tsettle(100);\n}",
"function createBox2DBody() {\n // Box2D physics body\n var bodyDef = new box2d.b2BodyDef();\n bodyDef.type = box2d.b2Body.b2_dynamicBody;\n bodyDef.angle = 0;\n bodyDef.angularDamping = 0.2;\n bodyDef.position.Set( 3182/SCALE, 2236/SCALE); // World coordinates\n bodyDef.userData = \"Ship\";\n var body = world.CreateBody(bodyDef);\n /*\n var fixDef = new box2d.b2FixtureDef();\n fixDef.density = 100.;\n fixDef.friction = 0.6;\n fixDef.restitution = 0.0;\n fixDef.shape = new box2d.b2PolygonShape;\n fixDef.shape.SetAsBox((70 / 2 / SCALE), (54 / 2 / SCALE));\n fixDef.filter.categoryBits = CAT.SHIP;\n fixDef.filter.maskBits = CAT.GROUND | CAT.SOLDIER_FOOT_SENSOR;\n fixDef.userData = \"Ship\";\n body.CreateFixture(fixDef);\n */\n //Main ship body\n var Vec2 = box2d.b2Vec2;\n var fixDef = new box2d.b2FixtureDef();\n fixDef.density = 100.;\n fixDef.friction = 0.6;\n fixDef.restitution = 0.0;\n fixDef.shape = new box2d.b2PolygonShape;\n var vertices = [\n new Vec2(0,-68/ SCALE),\n new Vec2(30/SCALE,-27/SCALE),\n new Vec2(18/SCALE, 37/SCALE),\n new Vec2(-18/SCALE, 37/SCALE),\n new Vec2(-30/SCALE,-27/SCALE)\n ];\n fixDef.shape.SetAsArray(vertices, 5);\n fixDef.filter.categoryBits = CAT.SHIP;\n fixDef.filter.maskBits = CAT.GROUND | CAT.SOLDIER_FOOT_SENSOR | CAT.STATION;\n fixDef.userData = \"Ship\";\n body.CreateFixture(fixDef);\n \n //Right engine\n fixDef.shape = new box2d.b2PolygonShape;\n var vertices = [\n new Vec2(22/SCALE, 18/SCALE),\n new Vec2(30/SCALE, 10/SCALE),\n new Vec2(33/SCALE, 67/SCALE),\n new Vec2(12/SCALE, 67/SCALE)\n ];\n fixDef.shape.SetAsArray(vertices, 4);\n body.CreateFixture(fixDef);\n \n //Left engine\n fixDef.shape = new box2d.b2PolygonShape;\n var vertices = [\n new Vec2(-12/SCALE, 67/SCALE),\n new Vec2(-33/SCALE, 67/SCALE),\n new Vec2(-30/SCALE, 10/SCALE),\n new Vec2(-22/SCALE, 18/SCALE)\n ];\n fixDef.shape.SetAsArray(vertices, 4);\n body.CreateFixture(fixDef);\n \n return body;\n }",
"function createFishBody() {\n gPush();\n {\n setColor(vec4(0.4, 0, 0, 1.0));\n gScale(1, 1, 3);\n gTranslate(0, 0, -0.66);\n gRotate(180, 0, 1, 0);\n drawCone();\n }\n gPop();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For the filed that represent major, it has datamajor contains major id, take it an set text to element with major id | function setMajorNameInstadeOfId() {
$("*[data-major]").each(function () {
var id = $(this).data("major");
$(this).text(majorsMap[id]);
})
} | [
"updateMajor() {\n const major = this.productMajorAttribute.name;\n const minor = this.productMinorAttribute.name;\n /* only if there are minors */\n if (minor) {\n Vue.set(this.selectedAttributes, minor, this.productAttributeItems[this.selectedAttributes[major]][0]);\n }\n }",
"function setInfo(id, value)\n{\n if (!value) {\n hideNode(id);\n return;\n }\n\n var node = document.getElementById(id+\"-text\");\n\n if (node.namespaceURI == XULNS && node.localName == \"label\" ||\n (node.namespaceURI == XULNS && node.localName == \"textbox\")) {\n node.setAttribute(\"value\",value);\n\n } else if (node.namespaceURI == XULNS && node.localName == \"description\") {\n node.textContent = value;\n }\n}",
"function fillMe(identifier, val) {\n var $field = $('fieldset[data-reference-identifier=\"'+ identifier +'\"]').find('input.string, select')\n if ($field.val() && $field.val().match(/[^\\s]/)) return\n return $field.val(val)\n }",
"function updateLabelForAttribute() {\r\n var model = getDeviceModel();\r\n var speciesLabelElem = document.getElementById('species_label');\r\n var beamApertureLabelElem = document.getElementById('beamAperture_label');\r\n \r\n if (model === 'FINSHAW') {\r\n //set for to finshaw id\r\n setForAttribute(speciesLabelElem, 'finshaw_species');\r\n setForAttribute(beamApertureLabelElem, 'beamAperture_inFinshaw');\r\n \r\n } else {//if otherwise, keep for with echlon5.\r\n //set for to echlon5 id\r\n setForAttribute(speciesLabelElem, 'echlon5_species');\r\n setForAttribute(beamApertureLabelElem, 'beamAperture_inEchlon5');\r\n \r\n } \r\n}",
"updateMajor(id, major){\n return UserDB.findOne({_id: id})\n .updateOne({$set:{Major: major}})\n }",
"function setNessusIDData(idData, nodeInfo){\n var div = $('#nessusinfo');\n div.html('<hr><p>');\n if(nodeInfo){\n if(nodeInfo.type == 'hole')\n div.append(\"Security Hole\"+ '<br><br>');\n else\n div.append(\"Security Note\"+ '<br><br>');\n div.append(\"Group: \" + nodeInfo.group + '<br>');\n div.append(\"Address: \" + nodeInfo.ip + '<br>');\n div.append(\"Port: \" + nodeInfo.group + '<br><br>');\n div.append(\"Nessus ID: \" + nodeInfo.id + '<br>');\n }\n div.append(\"Title: \" + idData.title + '<br>');\n if(idData.family && idData.family !== \"\")\n div.append(\"Family: \" + idData.family + '<br>');\n div.append('<br>');\n if(idData.synopsis && idData.synopsis !== \"\")\n div.append(\"Synopsis: \" + idData.synopsis + '<br><br>');\n if(idData.description && idData.description !== \"\")\n div.append(\"Description: \" + idData.description + '<br><br>');\n if(idData.updateInfo && idData.updateInfo !== \"\")\n div.append(\"UpdateInfo: \" + idData.updateInfo + '<br><br>');\n if(idData.solution && idData.solution !== \"\")\n div.append(\"Solution: \" + idData.solution);\n /* //TODO deal with these later.\n div.append(\"bugtraqList: \" + idData.bugtraqList);\n div.append(\"cveList: \" + idData.cveList);\n div.append(\"otherInfoList: \" + idData.otherInfoList);\n */\n div.append('</p>');\n\n /*\n var enter = div.selectAll('.nessusinfosection')\n .data(iddata, function(d) { return d.key; })\n .enter();\n\n $.each(enter[0], function(i, v) { \n var key = v.__data__.key;\n var text = v.__data__.text;\n d3.select('#nessus_'+key).select('p').html(text);\n });\n */\n}",
"function selectToText(shortName, idStr) {\n $(\"div[id^='select_\"+shortName+\"']\").each(function() {\n var cont = $(this);\n if(cont.attr('id').endsWith(\"_\"+idStr) && !cont.attr('id').endsWith(\"ZZ\")) {\n // remove the short name and \"select_\" from the string we're parsing\n var divStr = cont.attr('id').replace(\"select_\", \"\").replace(shortName + \"_\", \"\");\n // remove the idstr to receive the name of this element\n var regex = new RegExp(\"\\_\"+idStr+\"$\", \"g\");\n var name = divStr.replace(regex, \"\");\n var id = $(\"#\"+shortName+\"_\"+name+\"_id_\"+idStr).val();\n var term = $(\"#\"+shortName+\"_\"+name+\"_id_\"+idStr+ \" option:selected\").text();\n var vocabtype = $(\"#\"+shortName+\"_\"+name+\"_vocabtype_\"+idStr).val();\n var minlength = $(\"#\"+shortName+\"_\"+name+\"_minlength_\"+idStr).val();\n\n var additionalStyle = \"\";\n var postText = \"\";\n if (vocabtype == \"name_component\") {\n additionalStyle = \"name-component-type\";\n postText = \" :\";\n }\n\n cont.html(\"<input type=\\\"hidden\\\" id=\\\"\"+shortName+\"_\"+name+\"_id_\"+idStr+\"\\\" \" +\n \"name=\\\"\"+shortName+\"_\"+name+\"_id_\"+idStr+\"\\\" value=\\\"\"+id+\"\\\"/>\" +\n \"<input type=\\\"hidden\\\" id=\\\"\"+shortName+\"_\"+name+\"_term_\"+idStr+\"\\\" \" +\n \"name=\\\"\"+shortName+\"_\"+name+\"_term_\"+idStr+\"\\\" value=\\\"\"+term+\"\\\"/>\" +\n \"<input type=\\\"hidden\\\" id=\\\"\"+shortName+\"_\"+name+\"_vocabtype_\"+idStr+\"\\\" \" +\n \"name=\\\"\"+shortName+\"_\"+name+\"_vocabtype_\"+idStr+\"\\\" value=\\\"\"+vocabtype+\"\\\"/>\" +\n \"<input type=\\\"hidden\\\" id=\\\"\"+shortName+\"_\"+name+\"_minlength_\"+idStr+\"\\\" \" +\n \"name=\\\"\"+shortName+\"_\"+name+\"_minlength_\"+idStr+\"\\\" value=\\\"\"+minlength+\"\\\"/>\" +\n \"<p class=\\\"form-control-static \"+additionalStyle+\"\\\">\"+term+postText+\"</p>\");\n\n }\n });\n}",
"function getUpdateStringByIdAndKind(id,kind){\n \tvar data = \"\";\n \tfor(var i=0; i< $j('#'+id+' > li').size(); i++){\n\t\tdata += \"&elementString=\"+$j('#'+id+' > li:nth-child('+(i+1)+')').attr('id')+\",\"+kind+\",\"+$j('#'+id+' >li:nth-child('+(i+1)+')').attr('name')+\"|\";\n\t\t$j('#'+id+' > li:nth-child('+(i+1)+') input').each(function(j){\n\t\t\t\n\t\t\tif(this.id.indexOf('t')== -1){\n\t\t\t\t//not include the input of title kind\n\t\t\t\tdata+= this.id+\":\"+this.name+\":\"+this.value+\",\";\n\t\t\t}\n\t\t});\n\t\t$j('#'+id+' > li:nth-child('+(i+1)+') select').each(function(j){\n\t\t\tdata+= this.id+\":\"+this.name+\":\"+this.value+\",\";\n\t\t});\n\t}\n\t//alert(data);\n\treturn data;\n}",
"function update300sElecsMajor() {\n 'use strict';\n\n numBCBMajor = $('#300sElecsMajor input:checkbox:checked').length;\n var numProjects = 2;\n if ($('#BCB430checkMajor').prop('checked')) {\n numBCBMajor += 1;\n numProjects = 0;\n }\n\n var tmp = active300s.concat(active400s,\n projectCourses.slice(0, numProjects));\n\n // Manually add active 3rd year courses required by specialist\n if (CSC373.status === 'active' || CSC373.status === 'overridden') {\n tmp.push('CSC373');\n extraMajor += 0.5;\n }\n\n if (CSC369.status === 'active' || CSC369.status === 'overridden') {\n tmp.push('CSC369');\n extraMajor += 0.5;\n }\n\n for (var i = 1; i <= 6; i++) {\n if (i <= tmp.length) {\n $('#3xx' + i + 'Major').attr('value', tmp[i - 1]);\n } else {\n $('#3xx' + i + 'Major').attr('value', '');\n }\n }\n\n\n elec300sTotalMajor = tmp.length + numBCBMajor;\n\n// for (var i = 1; i <= 3; i++) {\n// if ($('#MAT' + i + 'Major').prop('value').substr(0, 3) === 'MAT') {\n// elec300sTotalMajor += 1;\n// }\n// }\n\n elec300sTotalMajor /= 2;\n}",
"function updateData(text, field) {\n var node = myDiagram.selection.first();\n // maxSelectionCount = 1, so there can only be one Part in this collection\n var data = node.data;\n if (node instanceof go.Node && data !== null) {\n var model = myDiagram.model;\n model.startTransaction(\"modified \" + field);\n model.setDataProperty(data, field, text);\n // if (field === \"name\") {\n // } else if (field === \"title\") {\n // model.setDataProperty(data, \"title\", text);\n // } else if (field === \"comments\") {\n // model.setDataProperty(data, \"comments\", text);\n // }\n model.commitTransaction(\"modified \" + field);\n }\n }",
"function updateData(text, field) {\n var node = myDiagram.selection.first();\n // maxSelectionCount = 1, so there can only be one Part in this collection\n var data = node.data;\n if (node instanceof go.Node && data !== null) {\n var model = myDiagram.model;\n model.startTransaction(\"modified \" + field);\n if (field === \"name\") {\n model.setDataProperty(data, \"name\", text);\n } else if (field === \"title\") {\n model.setDataProperty(data, \"title\", text);\n } else if (field === \"comments\") {\n model.setDataProperty(data, \"comments\", text);\n }\n model.commitTransaction(\"modified \" + field);\n }\n }",
"setMajor(major) {\n this.major = major\n }",
"function setAnnotationValues(compNo, lT, rT) {\n document.getElementById(\"anComp\" + compNo + \"LT\").textContent = lT;\n document.getElementById(\"anComp\" + compNo + \"RT\").textContent = rT;\n // TODO\n document.getElementById(\"aComp\" + compNo + \"LT\").textContent = lT;\n document.getElementById(\"aComp\" + compNo + \"RT\").textContent = rT;\n}",
"function fillLabTechs(object, id) {\n\tvar elements = document.getElementById(id);\n\tvar techs = object.lab_techs;\n\tvar newInnerHTML = \"\"\n\n\tfor(var i=0; i < techs.length; i++) {\n\t\tnewInnerHTML += \"<option tech_id=\" + techs[i].tech_id + \">\" + techs[i].name + \"</option>\";\n\t}\n\telements.innerHTML = newInnerHTML;\n}",
"setElementsText(type, value) {\n this.getElementsByQuery(`[data-type=${type}]`)\n .forEach(element => element.textContent = value);\n }",
"function textToSelect(shortName, idStr) {\n $(\"#\"+shortName+\"_datapart_\" + idStr + \" div[id^='select_\"+shortName+\"']\").each(function() {\n var cont = $(this);\n if(cont.attr('id').endsWith(\"_\"+idStr) && !cont.attr('id').endsWith(\"ZZ\")) {\n // remove the short name and \"select_\" from the string we're parsing\n var divStr = cont.attr('id').replace(\"select_\", \"\").replace(shortName + \"_\", \"\");\n // remove the idstr to receive the name of this element\n var regex = new RegExp(\"\\_\"+idStr+\"$\", \"g\");\n var name = divStr.replace(regex, \"\");\n var id = $(\"#\"+shortName+\"_\"+name+\"_id_\"+idStr).val();\n var term = $(\"#\"+shortName+\"_\"+name+\"_term_\"+idStr).val();\n var vocabtype = $(\"#\"+shortName+\"_\"+name+\"_vocabtype_\"+idStr).val();\n var minlength = $(\"#\"+shortName+\"_\"+name+\"_minlength_\"+idStr).val();\n var placeholder = \"Select\";\n if ($(\"#\"+shortName+\"_\"+name+\"_placeholder_\"+idStr).exists()) {\n placeholder = $(\"#\"+shortName+\"_\"+name+\"_placeholder_\"+idStr).val();\n }\n var options = \"\";\n if ($(\"#\"+shortName+\"_\"+name+\"_defaultOptions_\"+idStr).exists()) {\n options = $(\"#\"+shortName+\"_\"+name+\"_defaultOptions_\"+idStr).val();\n }\n\n cont.html(\"<select id='\"+shortName+\"_\"+name+\"_id_\"+idStr+\"' name='\"+shortName+\"_\"+name+\"_id_\"+idStr+\"' class='form-control' data-placeholder='\"+placeholder+\"'>\"+\n \"<option></option>\"+\n \"<option value=\\\"\"+id+\"\\\" selected>\"+term+\"</option>\"+ options +\n \"</select>\"+\n \"<input type=\\\"hidden\\\" id=\\\"\"+shortName+\"_\"+name+\"_vocabtype_\"+idStr+\"\\\" \" +\n \"name=\\\"\"+shortName+\"_\"+name+\"_vocabtype_\"+idStr+\"\\\" value=\\\"\"+vocabtype+\"\\\"/>\" +\n \"<input type=\\\"hidden\\\" id=\\\"\"+shortName+\"_\"+name+\"_minlength_\"+idStr+\"\\\" \" +\n \"name=\\\"\"+shortName+\"_\"+name+\"_minlength_\"+idStr+\"\\\" value=\\\"\"+minlength+\"\\\"/>\");\n\n if (name == \"citation\")\n scm_source_select_replace($(\"#\"+shortName+\"_\"+name+\"_id_\"+idStr), \"_\"+idStr);\n else if (shortName == \"sameAs\" && name == \"baseuri\") {\n //The following block handles the specific case of Same As External Resource association form\n var loadPromise = loadVocabSelectOptions($(\"#\"+shortName+\"_\"+name+\"_id_\"+idStr), \"external_sameas_domain\", \"Base URI\", true);\n loadPromise.then(function(result){\n var currentURI = $(\"#\"+shortName+\"_uri_\"+idStr).val();\n if (currentURI) {\n var found = false;\n $(\"#\"+shortName+\"_\"+name+\"_id_\"+idStr+\" option\").each(function(index,op){\n if( found || (!op.hasAttribute(\"value\") || !op.value)) {\n return;\n }\n var uriComponents = op.value.split(/{id}/);\n if(currentURI.indexOf(uriComponents[0]) == 0) {\n var currOption = op.value;\n var currId = currentURI.replace(uriComponents[0],\"\");\n if(!!uriComponents[1]) {\n if(currentURI.indexOf(uriComponents[1]) != -1) {\n currId = currId.replace(/uriComponents[1]$/,\"\");\n }\n }\n found = true;\n $(\"#sameAs_baseuri_id_\"+idStr).val(currOption);\n $(\"#sameAs_baseuri_id_\"+idStr).trigger(\"change\");\n $(\"#sameAs_uriid_\"+idStr).val(currId);\n $(\"#sameAs_uri_\"+idStr).val(currOption.replace(/{id}/,currId));\n }\n });\n }\n $(\"#\"+shortName+\"_uri_\"+idStr).prop(\"readonly\", true);\n });\n // If dealing with subject, function, or occupation term, query Concept Vocab system\n } else if (shortName == 'activity' || shortName == 'subject' || shortName =='occupation') {\n conceptVocabSelectReplace($(\"#\"+shortName+\"_\"+name+\"_id_\"+idStr), \"_\"+idStr, vocabtype, minlength);\n } else\n vocab_select_replace($(\"#\"+shortName+\"_\"+name+\"_id_\"+idStr), \"_\"+idStr, vocabtype, minlength);\n\n }\n });\n}",
"function get_major(major){\n\tvar parsedMajor = major.trim()\n\tif(parsedMajor.indexOf('/') !==-1){\n\t\tparsedMajor = (parsedMajor.slice(0, parsedMajor.indexOf('/')))\n\t}\n\telse if(parsedMajor.indexOf('-') !==-1){\n\t\tparsedMajor = (parsedMajor.slice(0, parsedMajor.indexOf('-')))\n\t}\n\telse if(parsedMajor.indexOf('>') !==-1){\n\t\tparsedMajor = (parsedMajor.slice(0, parsedMajor.indexOf('>')))\n\t}\n\n//\tconsole.log(parsedMajor)\n\treturn major_data[parsedMajor.toUpperCase()];\n}",
"function copySelectedTextToXMLDataIsland(fieldSelected , xmlGrid , dispFieldName){\r\n\r\nvar dispText=fieldSelected [fieldSelected.selectedIndex].text;\r\nif(isStringCodeValue(fieldSelected.value)) {\r\n xmlGrid.recordset(dispFieldName).value=dispText;\r\n} else {\r\n dispText='';\r\n xmlGrid.recordset(dispFieldName).value=dispText;\r\n}\r\nreturn dispText;\r\n}",
"function createMajorList () {\n var getForm = tagName(\"form\");\n var getDepartmentsId = idTag(\"departments\");\n var createSelectTag = makeTag(\"Select\");\n createSelectTag.setAttribute(\"id\", \"selectMajor\");\n for (var i = 0, l = departmentMajors.length; i < l; i++) {\n var createOptionTag = makeTag(\"option\");\n var optionInArray = departmentMajors[i];\n createOptionTag.setAttribute(\"value\", optionInArray);\n createOptionTag.innerHTML = optionInArray; \n createSelectTag.appendChild(createOptionTag);\n }\n getDepartmentsId.appendChild(createSelectTag);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Import module Description: Includes a raw wiki page as javascript | function importScript(page, lang) {
var url = '/index.php?title='
+ encodeURIComponent(page.replace(' ','_'))
+ '&action=raw&ctype=text/javascript&dontcountme=s';
if (lang) url = 'http://' + lang + '.wikipedia.org/w/' + url;
var s = document.createElement('script');
s.src = url;
s.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(s);
} | [
"function import_wiki() {\n\tif (!woas.config.permit_edits) {\n\t\talert(woas.i18n.READ_ONLY);\n\t\treturn false;\n\t}\n\twoas.import_wiki();\n\twoas.refresh_menu_area();\n}",
"function importScript( page ) {\n var url = wgScriptPath + '/index.php?title='\n + escape( page.replace( ' ', '_' ) )\n + '&action=raw&ctype=text/javascript&dontcountme=s';\n var scriptElem = document.createElement( 'script' );\n scriptElem.setAttribute( 'src' , url );\n scriptElem.setAttribute( 'type' , 'text/javascript' );\n document.getElementsByTagName( 'head' )[0].appendChild( scriptElem );\n }",
"function loadPageContent(page){\n\n}",
"function load() {\n \n //writes all the html for the page\n htmlWriter();\n }",
"function loadWikiContent(title,container){ \n var target = $jq('#'+container);\n // JSONP via the Mediawiki API\n // $jq.getJSON(\"http://wiki.wormbase.org/api.php?action=query&prop=revisions&titles=Updating_The_Development_Server&rvprop=content&format=json&callback=?\",\n\n // XML (formatted) via the Mediawiki API\n // $jq.getJSON(\"http://wiki.wormbase.org/api.php?action=query&prop=revisions&titles=Updating_The_Development_Server&rvprop=content&format=xmlfm&callback=?\",\n\n // HTML via the Mediawiki API\n // $jq.getJSON(\"http://wiki.wormbase.org/api.php?action=parse&page=Updating_The_Development_Server&callback=?\",\n\n // JSONP directly\n //$jq.getJSON(\"http://wiki.wormbase.org/index.php/Updating_The_Development_Server?callback=?\",\n \n // HTML via YQL via the Mediawiki API, selecting the content we want by xpath. \n $jq.getJSON(\"http://query.yahooapis.com/v1/public/yql?\"\n\t\t+\"q=select%20*%20from%20html%20where%20url%3D%22\"\n\t\t+\"http%3A%2F%2Fwiki.wormbase.org%2Findex.php%2F\"\n\t\t+title\n\t\t+\"%22%20and%20xpath%3D%22%2F%2Fdiv%5B%40id%3D'globalWrapper'%5D%22&callback=?\",\n\t\tfunction(data){\t\t\t\n\t\t if(data.results[0]){\n\t\t\t// var data = filterData(data.results[0]);\n\t\t\tvar data = data.results[0];\n\t\t\t$jq(target).html(data).focus().effect(\"highlight\",{},1000);\n\t\t\talert(data);\n\t\t\treturn false;\n\t\t } else {\n\t\t\t// Couldn't fetch or no content?\n \n\t\t\tvar errormsg = '<p>Error: unable to fetch content from the wiki.</p>';\n\t\t\t$jq(target).\n\t\t\t html(errormsg).\n\t\t\t focus().\n\t\t\t effect('highlight',{color:'#c00'},1000);\n\t\t }\n\t\t}\n\t\t)\n\t}",
"function loadMainContent(){\n //obtain the name of the markdown file\n var mdFile = getMDFilenameFromHash();\n //convert the markdown file contents into HTML and store them in #mainContent\n fileMDtoHTML(\"#mainContent\", mdFile); \n}",
"function importArticle( ) { \n const base = window.location.origin + mw.config.get( \"wgLoadScript\" );\n const defaults = Object.freeze( { \n debug : mw.config.get( \"debug\" ),\n lang : mw.config.get( \"wgUserLanguage\" ),\n mode : \"articles\",\n skin : mw.config.get( \"skin\" )\n } );\n const loaded = { };\n const state = { done: false };\n const modules = Array.from( Array.isArray( arguments[ 0 ] ) ? \n arguments[ 0 ] : arguments );\n const result = [ ];\n const length = modules.length;\n \n return new Promise( function( resolve, reject ) {\n mw.hook( \"dev.url\" ).add( function( WikiaURL ) {\n Array.from( modules ).forEach( function( module, index ) { \n const done = state.done = ( index === length - 1 );\n const options = Object.assign( { }, defaults, module );\n const type = module.type;\n options.articles = options.article || options.articles;\n delete options.article;\n \n if ( !options.articles || !options.articles.length ) return;\n if ( Array.isArray( options.articles ) ) {\n options.articles = options.articles.join( \"|\" );\n }\n \n if ( mw.config.get( \"wgContentReviewExtEnabled\" ) ) {\n if ( /MediaWiki:/.test( module.articles ) ) {\n if ( mw.config.get( \"wgContentReviewTestModeEnabled\" ) ) {\n options.current = mw.config.get( \"wgScriptsTimestamp\" );\n } else {\n options.reviewed = mw.config.get( \"wgReviewedScriptsTimestamp\" );\n }\n }\n }\n \n const importMethod = ( /scripts?/.test( type ) ? importScriptURL : ( /styles?/.test( type ) ?\n importStylesheetURL : null\n ) );\n \n if ( importMethod === null ) return;\n options.only = options.type.endsWith( \"s\" ) ? options.type : \n options.type + \"s\";\n delete options.type;\n \n const url = new WikiaURL( base, options );\n if ( loaded[ String( url ) ] ) return;\n loaded[ String( url ) ] = true;\n result.push( importMethod( url ) );\n if ( done ) Promise.all( result ).then( resolve );\n } );\n } );\n } );\n }",
"function LoadSource(topic) {\r\n oDiv = document.getElementById('Wiki')\r\n oDiv.innerHTML = $(\"#Source\").load(\"/wiki/index.php?title=\" + topic + \" #mw-content-text\");\r\n DisplayTab(5);\r\n return;\r\n}",
"_parseHTML() {\n const contents = fs.readFileSync(this.filepath, 'utf-8');\n this.code = htmlLoader(contents);\n }",
"content() {\n // querystring text=\n let textRequest = poc2go.include.text();\n if (textRequest) { return textRequest; }\n\n // querystring md=\n return this.text(poc2go.render.filepath())\n .then(txt => this.inserts(txt))\n .then(txt => this.renderCodeBlocks(txt))\n .then(txt => this.styles(txt))\n .then(txt => this.scripts(txt))\n .then(txt => this.includes(txt));\n }",
"function loadBlog() {\n var result = webix.ajax().sync().get('BLOG.md');\n var text = result.responseText;\n var blog = text.split(/^[#]/gm);\n//console.log(blog);\n $$('blog1').setHTML(marked('#'+(blog[1]||'')));\n $$('blog2').setHTML(marked('#'+(blog[2]||'')));\n $$('blog3').setHTML(marked('#'+(blog[3]||'')));\n\n}",
"function htmlPage() {\r\n return gulp\r\n .src([paths.html.input, \"!src/slim/0.include/**\", \"!src/slim/1.template/**\"], { since: gulp.lastRun(htmlPage) })\r\n .pipe(\r\n slim({\r\n pretty: true,\r\n options: \"encoding='utf-8'\",\r\n require: \"slim/include\", // 呼叫include plug-in\r\n format: \"xhtml\",\r\n options: 'include_dirs=[\"./src/slim/0.include/\"]'\r\n })\r\n )\r\n .pipe(gulp.dest(paths.html.output))\r\n .pipe(browserSync.stream());\r\n}",
"LoadContent(){ }",
"async function getPage(url) {\n let { title, icon, cover, html } = await NotionPageToHtml.convert(url);\n const path = `./src/articles/${title.replace(/ /g, '-')}.ejs`;\n html = html.replace('<head>', '<head><% include /_head.ejs %>');\n html = html.replace('<body>', '<body><% include /_page-fade-in-animation.ejs %><% include /_nav.ejs %><main style=\"overflow: hidden;\" class=\"container\">');\n html = html.replace('</body>', '</main><% include /_footer.ejs %><% include /_scripts.ejs %></body>', '</body>');\n html = html.replace('margin: 2em auto;', '');\n html = html.replace('max-width: 900px;', '');\n html = html.replace('class=\"page-title\"', 'class=\"page-title\" style=\"margin-top: calc(var(--indent) * 3)\"');\n await fs.writeFile(path, html);\n}",
"function Page(name) {\n this.name = name\n this.title = name;\n this.hasOwnTitle = false;\n //this.tiddlyIO = new TiddlyIO();\n //this.converter = new Showdown.converter();\n this.text = '';\n \n this.creole = new Parse.Simple.Creole( {\n forIE: document.all,\n interwiki: {\n Wikipedia: 'http://web.archive.org/web/20091116200910/http://en.wikipedia.org//wiki/'\n },\n linkFormat: '?page='\n } );\n \n this.path = \"data/\" + this.name + \".txt\";\n}",
"function buildWebPage(result){\n document.getElementById('article').innerHTML = result.description;\n document.getElementById('article-title').innerHTML = result.title;\n}",
"function loadExternalFile() {\n var script = document.createElement('script');\n script.src = 'https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.19/marked.js';\n document.getElementsByTagName('head')[0].appendChild(script);\n }",
"function loadMD(file, tag){\n var url = baseLocation+file;\n // load article content.\n $.ajax({\n url: url,\n type: 'GET',\n dataType: 'text',\n success: function(text) {\n // insert html converted markdown into content div.\n //console.log(\"Loading file: \"+url);\n $(tag).html(converter.makeHtml(text));\n }\n});\n}",
"function templateContent() {\n const html = read(appHTML).toString();\n const doc = cheerio(html);\n doc.find('body')\n .append(`<script data-dll='true' src='/${entryName}.dll.js'></script>`);\n\n return doc.toString();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this method is used to validate and send the professor registration request, throws error message otherwise | function professorRegister(user) {
vm.profError = "";
vm.profnoMatch = "";
vm.profMessage = "";
vm.profSuccess = false;
checkValidation(user);
if(vm.profError.length === 0){
user.role = 'professor';
if ($scope.professorForm.$valid) {
userService
.findUserByUsername(user.username)
.then(function (usr) {
if (usr)
vm.profMessage = "Username Taken";
else
requestProfessorRegistration(user);
});
}
else {
$scope.professorForm.submitted = true;
vm.profError = "Missing fields!"
}
}
} | [
"function professorRegister(user) {\n vm.error = \"\";\n vm.profNoMatch = \"\";\n vm.profMessage = \"\";\n vm.profSuccess = false;\n checkValidation(user);\n if (vm.error.length === 0) {\n if ($scope.professorForm.$valid) {\n user.role = 'professor';\n userService\n .findUserByUsername(user.username)\n .then(function (usr) {\n if (usr)\n vm.profMessage = \"Username Taken\";\n else\n requestProfessorRegistration(user);\n });\n }\n else {\n $scope.professorForm.submitted = true;\n vm.profError = \"Missing fields!\"\n }\n }\n vm.profError = vm.error, vm.error = \"\";\n }",
"function validateRegistration() {\n if (errorInField(\"firstName\", /^[a-zA-Z\\-]+$/, \"First name must contain only letters or dashes.\") ||\n errorInField(\"lastName\", /^[a-zA-Z\\-]+$/, \"Last name must contain only letters or dashes.\") ||\n errorInField(\"phoneNumber\", /^\\(\\d\\d\\d\\)\\d\\d\\d\\-\\d\\d\\d\\d$/, \"Phone number must be in format (XXX)XXX-XXXX\") ||\n errorInField(\"email\", /^(?=.*[@])(?=.*[\\.]).+$/, \"Email must contain an @ symbol and at least one '.'\") ||\n errorInField(\"loginName\", /^[a-zA-Z0-9]{6,}$/, \"Login name must only contain letters or numbers and be at \" +\n \"least 6 characters long.\") ||\n errorInField(\"password\", /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).+$/, \"Password must contain at least one lower \" +\n \"case letter, at least one upper case letter, and at least one number.\")) {\n return false;\n }\n\n else if (!stringsMatch(\"password\", \"passwordConfirmation\")) {\n window.alert(\"Your passwords don't match!\");\n return false;\n }\n\n else if (!document.getElementById(\"tenant\").checked && !document.getElementById(\"owner\").checked) {\n window.alert(\"Please select if you wish to be a property owner or a tenant.\");\n return false;\n }\n\n return true;\n}",
"function requestProfessorRegistration(user) {\n if (user.password === user.verifyPassword) {\n userService\n .requestProfessorRegistration(user)\n .then(function (usr) {\n if (usr !== 0) {\n vm.error = null;\n vm.noMatch = null;\n vm.message = null;\n vm.profSuccess = true;\n }\n });\n }\n else {\n vm.profNoMatch = \"Passwords don't match\";\n }\n }",
"function validateUserRegistrationForm() {\n\tconsole.log(`# validating recipient registration...`);\n}",
"function eduSigValidate() {\n\tvar email = document.forms[\"educatorSignUp\"][\"email\"].value;\n\tvar pass = document.forms[\"educatorSignUp\"][\"password\"].value;\n\tvar class_id = document.forms[\"educatorSignUp\"][\"class_ID\"].value;\n\tvar first = document.forms[\"educatorSignUp\"][\"firstName\"].value;\n\tvar last = document.forms[\"educatorSignUp\"][\"lastName\"].value;\n\tvar school = document.forms[\"educatorSignUp\"][\"school\"].value;\n\tvar zip = document.forms[\"educatorSignUp\"][\"zip\"].value;\n\t\n\tif(email == null || email== \"\"){\n\t\talert(\"Email cannot be blank!\");\n\t}else if (pass == null || pass ==\"\"){\n\t\talert(\"Password cannot be blank!\");\n\t}else if (class_id == null || class_id ==\"\"){\n\t\talert(\"You must enter at least one class to continue!\");\n\t}else if (first == null || first ==\"\"){\n\t\talert(\"Name cannot be blank!\");\n\t}else if (last == null || last ==\"\"){\n\t\talert(\"Name cannot be blank!\");\n\t}else if (school == null || school ==\"\"){\n\t\talert(\"School name cannot be blank!\");\n\t}else if (zip == null || zip ==\"\"){\n\t\talert(\"Zip cannot be blank!\");\n\t}\n}",
"function PromoterValidation() {\n\n \n\n var bool = true;\n var Lo_Obj = [\"ddlOwner\", \"ddlPromPrefer\", \"txtPromFName\", \"txtPromMName\", \"txtPromLName\", \"ddlPromNominee\", \"txtPromNomineeName\", \"txtPromDBO\", \"ddlGender\",\n \"txtPromCAddres\", \"ddlPromCState\", \"ddlPromCCity\", \"txtPromCPIN\", \"txtPromPAddress\", \"ddlPromPState\", \"ddlPromPCity\", \"txtPromPPIN\",\n \"txtPromPhone\", \"txtPromCell\", \"txtPromPan\", \"txtPromAdhar\", \"txtPromQualification\", \"txtPromEmail\"];\n var Ls_Msg = [\"Company Owner\", \"Preference\", \"First Name\", \"Middele Name\", \"Last Name\", \"Nominee Type\", \"Nominee Name\", \"Date of Birth\", \"Gender\",\n \"Current Address\", \"Current state\", \"Current city\", \"Current pin\", \"Permanent Address\", \"Permanent State\", \"Permanent City\", \"Permanent PIN\",\n \"Landline Number\", \"Mobile Number\", \"PAN Number\", \"Adhar Number\", \"Qualification\", \"Email\"];\n\n if (!CheckMandatory(Lo_Obj, Ls_Msg)) {\n return false;\n }\n return bool;\n}",
"function submitRegistration() {\n\tregistrationForm.setValidation();\n}",
"function validateRegistration(){\n\t\n\t//check to see if the user left the name field blank\n\tif (document.getElementById(\"r_name\").value == null || document.getElementById(\"r_name\").value == \"\"){\n\t\t\n\t\t//finding the error element to insert a warning message to screen\n\t\tdocument.getElementById(\"nameerror\").innerHTML= \"*name not filled in\";\n\t\t\n\t\t//changes to the fields properties to highlight the incorrect field\n\t\tformAtt(\"r_name\");\n\t\t\n\t\t//telling the event handler not to execute the onSubmit command\n return false;\n }\n\t\n\t//check to see if the user left the surname field blank\n\tif (document.getElementById(\"r_surname\").value == null || document.getElementById(\"r_surname\").value == \"\"){\n\t\t\n\t\t//finding the error element to insert a warning message to screen\n\t\tdocument.getElementById(\"snameerror\").innerHTML= \"*surname not filled in\";\n\t\t\n\t\t//changes to the fields properties to highlight the incorrect field\n\t\tformAtt(\"r_surname\");\n\t\t\n\t\t//telling the event handler not to execute the onSubmit command\n return false;\n }\n\t\n\t//check to see if the user left username field blank\n\tif (document.getElementById(\"r_username\").value == null || document.getElementById(\"r_username\").value == \"\"){\n\t\t\n\t\t//finding the error element to insert a warning message to screen\n\t\tdocument.getElementById(\"usernameerror\").innerHTML= \"*username not filled in\";\n\t\t\n\t\t//changes to the fields properties to highlight the incorrect field\n\t\tformAtt(\"r_username\");\n\t\t\n\t\t//telling the event handler not to execute the onSubmit command\n return false;\n }\n\t\n\t//check to make sure username is at least 6 characters long\n\tif (document.getElementById(\"r_username\").value.length < 4){\n\t\t\n\t\t//finding the error element to insert a warning message to screen\n\t\tdocument.getElementById(\"usernameerror\").innerHTML= \"*username must be at least 5 characters long\";\n\t\t\n\t\t//changes to the fields properties to highlight the incorrect field\n\t\tformAtt(\"r_username\");\n\t\t\n\t\t//telling the event handler not to execute the onSubmit command\n return false;\t\n\t}\n\t\n\t\n\t//check to see if the password was left empty\n\tif (document.getElementById(\"r_password\").value == null || document.getElementById(\"r_password\").value == \"\"){\n\t\t\n\t\t//finding the error element to insert a warning message to screen\n\t\tdocument.getElementById(\"passworderror\").innerHTML= \"*password not filled in\";\n\t\t\n\t\t//changes to the fields properties to highlight the incorrect field\n\t\tformAtt(\"r_password\");\n\t\t\n\t\t//telling the event handler not to execute the onSubmit command\n return false;\n }\n\t\n\t//check to see if the password is at least 6 characters long\n\tif (document.getElementById(\"r_password\").value.length < 5){\n\t\t\n\t\t//finding the error element to insert a warning message to screen\n\t\tdocument.getElementById(\"passworderror\").innerHTML= \"*password must be at least 6 characters long\";\n\t\t\n\t\t//changes to the fields properties to highlight the incorrect field\n\t\tformAtt(\"r_password\");\n\t\t\n\t\t//telling the event handler not to execute the onSubmit command\n return false;\t\n\t}\n\t\n\t\n\t/*\n\t//i tried to call a function that would check to see if there was a number in the password and return a false value if it didn't\n\tif (document.getElementById(\"r_password\").value.length >= 6 && passNum(document.getElementById(\"r_password\")) == false){\n\t\t\n\t\talert(\"Password must contain at least 1 number!\");\n\t\t\n\t\tformAtt(\"r_password\");\n\t\t\n\t\treturn false;\n\n\t}\n\t*/\n\t\n\t//checks to make sure that the password confirmation is not empty\n\tif (document.getElementById(\"c_password\").value == null || document.getElementById(\"c_password\").value == \"\"){\n\t\t\n\t\t//finding the error element to insert a warning message to screen\n\t\tdocument.getElementById(\"c_passworderror\").innerHTML= \"*confirm password not filled in\";\n\t\t\n\t\t//changes to the fields properties to highlight the incorrect field\n\t\tformAtt(\"c_password\");\n\t\t\n\t\t//telling the event handler not to execute the onSubmit command\n return false;\n }\n\t\n\t//checks to see if the password and confirmed password entries are the same \n\tif(!(document.getElementById(\"r_password\").value === document.getElementById(\"c_password\").value)){\n\t\t\n\t\t//finding the error element to insert a warning message to screen\n\t\tdocument.getElementById(\"c_passworderror\").innerHTML= \"*passwords do not match\";\n\t\t\n\t\t//changes to the fields properties to highlight the incorrect field\n\t\tformAtt(\"r_password\");\n\t\tformAtt(\"c_password\");\n\t\t\n\t\t//telling the event handler not to execute the onSubmit command\n return false;\n\t}\n\t\n\t//checks to see if the email field is empty\n\tif (document.getElementById(\"r_email\").value == null || document.getElementById(\"r_email\").value == \"\"){\n\t\t\n\t\t//finding the error element to insert a warning message to screen\n\t\tdocument.getElementById(\"emailerror\").innerHTML= \"*email not filled in\";\n\t\t\n\t\t//changes to the fields properties to highlight the incorrect field\n\t\tformAtt(\"r_email\");\n\t\t\n\t\t//telling the event handler not to execute the onSubmit command\n return false;\n }\n\t\n\t\n\t//check to see if the email is valid by checking if there is input first\n\t//taking care of the client side check if the input is valid/ php will take care of checking if email already in the database\n\tif (document.getElementById(\"r_email\").value != \"\" || document.getElementById(\"r_email\").value != \"\"){\n\t\t\n\t\t//assigning a variable to email value entered by user\n\t\tvar a = document.getElementById(\"r_email\").value;\n\t\t\n\t\t//assigning a variable to the index of the @ character if found, assigns -1 if not found\n\t\tatPos = a.indexOf(\"@\");\n\t\n\t\t//if the @ sign is not found\n\t\tif (atPos == -1){\n\t\t\t\n\t\t//finding the error element to insert a warning message to screen\n\t\tdocument.getElementById(\"emailerror\").innerHTML= \"*invalid email\";\n\t\t\n\t\t//changes made to fields properties to highlight the incorrect field\n\t\tformAtt(\"r_email\");\t\n\n\t\t//telling the event handler not to execute the onSubmit command\n\t\treturn false;\t\n\t\t}\n\t}\n\t//if the users submission returns no false checks, then tell the even handler to execute the onSubmit command\n\treturn true;\n}",
"function parSigValidate() {\n\tvar email = document.forms[\"parentSignUp\"][\"email\"].value;\n\tvar pass = document.forms[\"parentSignUp\"][\"password\"].value;\n\tvar first = document.forms[\"parentSignUp\"][\"firstName\"].value;\n\tvar last = document.forms[\"parentSignUp\"][\"lastName\"].value;\n\tvar phone = document.forms[\"parentSignUp\"][\"phone_num\"].value;\n\tvar consent = document.forms[\"parentSignUp\"][\"parental_consent\"].value;\n\tif(email == null || email== \"\"){\n\t\talert(\"Email cannot be blank!\");\n\t}else if (pass == null || pass ==\"\"){\n\t\talert(\"Password cannot be blank!\");\n\t}else if (firstName == null || firstName == \"\"){\n\t\talert(\"Your first name cannot be blank!\");\n\t}else if (lastName == null || lastName == \"\"){\n\t\talert(\"Your last name cannot be blank!\");\n\t}else if (parental_consent == null || parental_consent == \"\"){\n\t\talert(\"You must give parental consent to continue with signup!\");\n\t}\n}",
"function sendRegister() {\n let name = document.getElementById('nameFieldReg').value;\n let email = document.getElementById('emailFieldReg').value;\n let password = document.getElementById('passwordFieldReg').value;\n\n if (!name) {\n showErrorMsg(\"Name missing\");\n } else if (!validateEmail(email)) {\n showErrorMsg(\"Email invalid\");\n } else if (!password) {\n showErrorMsg(\"Password missing\");\n } else {\n clearErrorMsg();\n sendData({\n cmd: \"reg\",\n nam: name,\n ema: email,\n psw: password\n }, receiveRegister);\n }\n}",
"validateRegistrationBody(req, res) { // register body param validation\n\t\treq.checkBody('employee_number', 'Invalid employeenumber').notEmpty().withMessage(\"employeenumber can not be empty\");\n\t\treq.checkBody('first_name', 'Invalid firstname').notEmpty().withMessage(\"firstname can not be empty\");\n\t\treq.checkBody('last_name', 'Invalid lastname').notEmpty().withMessage(\"lastname can not be empty\");\n\t\treq.checkBody('email', 'Invalid email').notEmpty().withMessage(\"email can not be empty\");\n\t\treq.checkBody('nic_no', 'Invalid nicno').notEmpty().withMessage(\"nicno can not be empty\");\n\t\treq.checkBody('dob', 'Invalid dob').notEmpty().withMessage(\"dob can not be empty\");\n\t\treq.checkBody('nationality', '').notEmpty().withMessage(\" can not be empty\");\n\t\treq.checkBody('marital_status', '').notEmpty().withMessage(\" can not be empty\");\n\t\treq.checkBody('position', '').notEmpty().withMessage(\" can not be empty\");\n\t\treq.checkBody('joinDate', 'Invalid joinDate').notEmpty().withMessage(\"joinDate can not be empty\");\n\t\treq.checkBody('telephone_number', '').notEmpty().withMessage(\" can not be empty\");\n\t\treq.checkBody('mobile_number', '').notEmpty().withMessage(\" can not be empty\");\n\t\treq.checkBody('permanent_address', '').notEmpty().withMessage(\" can not be empty\");\n\t\treq.checkBody('current_address', '');\n\t\treq.checkBody('emergency_contact_name', '').notEmpty().withMessage(\"can not be empty\");\n\t\treq.checkBody('emergency_contact_number', '').notEmpty().withMessage(\"can not be empty\");\n\t\treq.checkBody('emergency_contact_relationship', '').notEmpty().withMessage(\"can not be empty\");\n\t\t// req.checkBody('bank_name', '').notEmpty().withMessage(\"can not be empty\");\n\t\t// req.checkBody('account_holder', '').notEmpty().withMessage(\"can not be empty\");\n\t\t// req.checkBody('account_no', '').notEmpty().withMessage(\"can not be empty\");\n\t\t// req.checkBody('branch', '').notEmpty().withMessage(\"can not be empty\");\n\t\t// req.checkBody('type_of_account', '').notEmpty().withMessage(\"can not be empty\");\n\t\treq.checkBody('isCreateAccount', '').notEmpty().withMessage(\"can not be empty\");\n\t}",
"function submitInput() {\r\n var emailCorrect = validateEmail();\r\n if (validateMandatoryFields()) {\r\n if (emailCorrect){\r\n createResume();\r\n }\r\n }\r\n}",
"function validateSignupInfo (signupInfo) {\n /*NEED TO CONFIRM THAT THE ENTRIES ARE VALID\n CERTAIN TYPE OF PASSWORD,\n VADID AND NEW EMAIL,\n VALID AND NEW USERNAME*/\n}",
"function registerValidate(registerForm){\n\n var validationVerified=true;\n var errorMessage=\"\";\n var okayMessage=\"click OK to process registration\";\n\n if (registerForm.firstname.value==\"\")\n {\n errorMessage+=\"Firstname not filled!\\n\";\n validationVerified=false;\n }\n if(registerForm.lastname.value==\"\")\n {\n errorMessage+=\"Lastname not filled!\\n\";\n validationVerified=false;\n }\n if (registerForm.email.value==\"\")\n {\n errorMessage+=\"Email not filled!\\n\";\n validationVerified=false;\n }\n if (registerForm.voter_id.value==\"\")\n {\n errorMessage+=\"Voter Id not filled!\\n\";\n validationVerified=false;\n }\n if(registerForm.password.value==\"\")\n {\n errorMessage+=\"Password not provided!\\n\";\n validationVerified=false;\n }\n if(registerForm.ConfirmPassword.value==\"\")\n {\n errorMessage+=\"Confirm password not filled!\\n\";\n validationVerified=false;\n }\n if(registerForm.ConfirmPassword.value!=registerForm.password.value)\n {\n errorMessage+=\"Confirm password and password do not match!\\n\";\n validationVerified=false;\n }\n if (!isValidEmail(registerForm.email.value)) {\n errorMessage+=\"Invalid email address provided!\\n\";\n validationVerified=false;\n }\n if (!isValidVoterId(registerForm.voter_id.value)) {\n errorMessage+=\"Invalid Voter Id provided!\\n\";\n validationVerified=false;\n }\n if(!validationVerified)\n {\n alert(errorMessage);\n }\n if(validationVerified)\n {\n alert(okayMessage);\n }\n return validationVerified;\n}",
"static userSignUpValidation(req, res, next) {\n const schema = Joi.object().keys({\n email: Joi.string().email().required(),\n first_name: Joi.string().trim().regex(/^([a-zA-Z]+\\s)*[a-zA-Z]+$/, 'Name format').min(3).required(),\n last_name: Joi.string().trim().regex(/^([a-zA-Z]+\\s)*[a-zA-Z]+$/, 'Name format').min(3).required(),\n password: Joi.string().min(6).max(50).required(),\n phoneNumber: Joi.number().required(),\n address: Joi.string().trim().min(2).max(50).required(),\n });\n validator(req, res, schema, next);\n }",
"function registerValidate(registerForm){\n\nvar validationVerified=true;\nvar errorMessage=\"\";\n\nif (registerForm.fname.value==\"\")\n{\nerrorMessage+=\"Nombre no rellenado!\\n\";\nvalidationVerified=false;\n}\nif(registerForm.lname.value==\"\")\n{\nerrorMessage+=\"Apellido no rellenado!\\n\";\nvalidationVerified=false;\n}\nif (registerForm.login.value==\"\")\n{\nerrorMessage+=\"Correo electrónico no rellenado!\\n\";\nvalidationVerified=false;\n}\nif(registerForm.password.value==\"\")\n{\nerrorMessage+=\"Contraseña no proporcionada!\\n\";\nvalidationVerified=false;\n}\nif(registerForm.cpassword.value==\"\")\n{\nerrorMessage+=\"Confirmar contraseña no rellenada!\\n\";\nvalidationVerified=false;\n}\nif(registerForm.cpassword.value!=registerForm.password.value)\n{\nerrorMessage+=\"Las contraseñas no coinciden!\\n\";\nvalidationVerified=false;\n}\nif (!isValidEmail(registerForm.login.value)) {\nerrorMessage+=\"Dirección de correo electrónico no válida!\\n\";\nvalidationVerified=false;\n}\nif(registerForm.question.selectedIndex==0)\n{\nerrorMessage+=\"Pregunta no seleccionada!\\n\";\nvalidationVerified=false;\n}\nif(registerForm.answer.value==\"\")\n{\nerrorMessage+=\"Respuesta no rellenada!\\n\";\nvalidationVerified=false;\n}\nif(!validationVerified)\n{\nalert(errorMessage);\n}\nreturn validationVerified;\n}",
"function validateRegister() {\n \n var x = document.forms[\"registerForm\"][\"reg_F_Name\"].value;\n if (x == \"\") {\n alert(\"First name must be filled out\");\n return false;\n }\n\n var x = document.forms[\"registerForm\"][\"reg_L_Name\"].value;\n if (x == \"\") {\n alert(\"Last name must be filled out\");\n return false;\n }\n \n var x = document.forms[\"registerForm\"][\"reg_email\"].value;\n if (x == \"\") {\n alert(\"The Email field cannot be left blank.\");\n return false;\n }\n \n var x = document.forms[\"registerForm\"][\"reg_username\"].value;\n if (x == \"\") {\n alert(\"The Message field cannot be left blank.\");\n return false;\n }\n \n var x = document.forms[\"registerForm\"][\"reg_password\"].value;\n if (x == \"\") {\n alert(\"The Message field cannot be left blank.\");\n return false;\n }\n \n document.register_modal.submit();\n}",
"function handleSubmitForm(e) {\n e.preventDefault();\n var self = $(this);\n if (self.validate().form()) {\n // Retrieve widget and form options\n var widgetOptions = JSON.parse(self.parent().parent(\".percRegistration\").attr(\"data\"));\n var options = self.data(\"options\");\n \n var registerObj = {\n email: self.find(\"#perc-registration-email-field\").val(),\n password: self.find(\"#perc-registration-password-field\").val(),\n confirmationRequired:\"perc-registration-cform\" === self.attr(\"name\"),\n confirmationPage: window.location.href\n };\n \n //registraionPageUrl:options.verReq\n $.PercMembershipService.register(registerObj, function(status, data) {\n data = $.PercServiceUtils.toJSON(data);\n // Retrieve where the user came from (URL param) and Confirmation page\n var urlstring = $.deparam.querystring();\n var redirectURL = \"\";\n if (\"undefined\" !== typeof (urlstring.registrationRedirect)){\n redirectURL = urlstring.registrationRedirect;\n }\n var confirmation_page = self.find(\"#perc-confirmation-page\").val();\n \n if (status === $.PercServiceUtils.STATUS_SUCCESS) {\n // Check for registration service REST service result and redirect\n if (data.status.toUpperCase() === $.PercServiceUtils.STATUS_SUCCESS.toUpperCase()) {\n if(!options.verReq) {\n // If successful registration, store the ID session in a cookie\n $.cookie('perc_membership_session_id', data.sessionId, { \"path\": \"/\", \"expires\": \"null\" });\n \n // If there is no confirmation page redirect to registrationRedirect (after\n // removing the corresponding URL parameter)\n if ('' === confirmation_page) {\n // Confirmation page and registrationRedirect are not defined, \n // redirect to Home\n if ('' === redirectURL) {\n redirectURL = widgetOptions.homePageLink;\n }\n else {\n delete urlstring.registrationRedirect;\n }\n \n var params = $.param.querystring('', urlstring);\n if (1 < params.length) {\n window.location = redirectURL + params;\n }\n else {\n window.location = redirectURL;\n }\n }\n // Redirect to the confirmation page and pass all the current URL parameters\n else {\n var params = '';\n if ($.param.querystring()) {\n params = '?' + $.param.querystring(); \n }\n window.location = confirmation_page + params;\n }\n }\n else\n {\n $(\".perc-registration-mode\").hide();\n $(\".perc-reg-confirmation-message\").html(\"<div>Thank you for registering with us.</div><div>Please check your email and confirm your registration to activate your account.</div>\");\n $(\".perc-reg-confirmation-mode\").show();\n }\n }\n else {\n // If the registration wasn't succesful show the error message inline and remain in the same page.\n \t$(\".perc-reg-error-message\").show().html(data.message);\n }\n }\n else {\n // If there was an error with the AJAX registration request\n \t$(\".perc-reg-error-message\").show().html(\"There was an unexpected error.\");\n }\n });\n }\n return false;\n }",
"function registerUser() {\n if(!firstName || !lastName || !username || !password || !email || !ssn) { //check if all required fields are filled\n setErrormsg(\"Please fill in all required fields\")\n return\n }\n\n let data = ({\n role: 2,\n firstName: firstName,\n lastName: lastName,\n username: username,\n password: password,\n email: email,\n ssn: ssn,\n update: updateExisting\n })\n\n fetch('/user/register', {\n method: 'POST', \n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(data)\n }).then(response => {\n console.log(response)\n if(response.status === 201) { // user is registered \n window.location = \"/\" \n }\n else if(response.status === 200) { // ok request\n response.json().then(result => setErrormsg(result.statusMessage))\n } \n else if(response.status === 400) { // bad request\n setErrormsg(response.statusText)\n }\n else if(response.status === 500) { // internal error\n setErrormsg(response.statusText)\n } \n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the status of all related fields based on the dependency and also the count of disabled fields | updateFieldsStatus () {
let service = dependencyService
service.updateFieldsStatus(this.formParameters)
} | [
"function correctStatusOfrelatedField(element) {\n var $related_field = $(element).closest('form').find('input[name=\"' + $(element).data('related-field') + '\"]').first();\n if (!$related_field) return;\n $related_field.prop('disabled', element.value == '1');\n $related_field.prop('required', element.value != '1');\n if (element.value == '1') $related_field.val('');\n}",
"function updateCountOfEffectiveSelectedProjects() {\n var cnt = 0;\n\n for (var i = 0; i < $scope.projectsData.length; i++) {\n const aLeadOrg = $scope.projectsData[i];\n for (var k = 0; k < aLeadOrg.projects.length; k++) {\n const project = aLeadOrg.projects[k];\n if (project.effectiveToggled) {\n cnt++;\n }\n }\n }\n\n $scope.effectiveSelectedProjectsCount = cnt;\n }",
"_updateEnabledFlag() {\n let newEnabled = this.isEnabled();\n if (this.__enabled !== newEnabled) {\n if (newEnabled) {\n this._setEnabledFlag();\n } else {\n this._unsetEnabledFlag();\n }\n\n let children = this._children.get();\n if (children) {\n let m = children.length;\n if (m > 0) {\n for (let i = 0; i < m; i++) {\n children[i]._updateEnabledFlag();\n }\n }\n }\n\n // Run this after all _children because we'd like to see (de)activating a branch as an 'atomic' operation.\n if (newEnabled) {\n this.emit('enabled');\n } else {\n this.emit('disabled');\n }\n }\n }",
"function _Field_enforceDependency(e){\n\tvar lstExcludeFields = _param(arguments[0], \",\");\n\tvar lstFieldsChecked = \",\";\n\tvar lstFieldsRequired = \",\";\n\t// loop through all the dependency and run each one\n\tfor( var i=0; i < this._queue.dependencies.length; i++ ){\n\t\tvar s = eval(this._queue.dependencies[i]);\n\t\t// keep a unique list of field checked\n\t\tif( lstFieldsChecked.indexOf(\",\" + s.field + \",\") == -1 ) lstFieldsChecked += s.field + \",\";\n\t\t// keep a unique list of fields that now should be required\n\t\tif( s.result && lstFieldsRequired.indexOf(\",\" + s.field + \",\") == -1 ) lstFieldsRequired += s.field + \",\";\n\t}\n\t// create an array of the field checked\n\taryFieldsChecked = lstFieldsChecked.split(\",\");\n\t// loop through the array skipping the first and last elements\n\tfor( var j=1; j < aryFieldsChecked.length-1; j++ ){\n\t\t// determine if the field is required\n\t\tvar result = (lstFieldsRequired.indexOf(\",\" + aryFieldsChecked[j] + \",\") > -1);\n\t\t// update it's status\n\t\tthis.qForm[aryFieldsChecked[j]].required = result;\n\t\t// now go check the dependencies for the field whose required status was changed\n\t\t// if the dependency rules for the field have already been run, then don't run\n\t\t// them again\n\t\tif( lstExcludeFields.indexOf(\",\" + aryFieldsChecked[j] + \",\") == -1 ) setTimeout(this.qForm._pointer + \".\" + aryFieldsChecked[j] + \".enforceDependency('\" + lstExcludeFields + this.name + \",')\", 1);\n\t}\n}",
"validateAllDirty () {\n for (let fieldID of Object.keys(this.fields)) {\n let field = this.fields[fieldID]\n\n if (field.dirty) {\n field.validate()\n }\n }\n }",
"function UpdateFieldStatus(field_name, fld_value, data_dict) {\n //console.log(\"========= UpdateFieldStatus =========\");\n //console.log(\" field_name\", field_name);\n //console.log(\" fld_value\", fld_value);\n //console.log(\" data_dict\", data_dict);\n //console.log(\" data_dict.secret_exam\", data_dict.secret_exam);\n //console.log(\" data_dict.ceex_secret_exam\", data_dict.ceex_secret_exam);\n\n const field_arr = field_name.split(\"_\");\n const prefix_str = field_arr[0];\n\n // field_name = \"se_status\", \"sr_status\", \"pe_status\", \"ce_status\", \"note_status\"\n let className = \"diamond_3_4\"; // diamond_3_4 is blank img\n let title_text = null, filter_value = null;\n if (prefix_str === \"note\"){\n // dont show note icon when user has no permit_read_note\n className = \"note_\" + ( (permit_dict.permit_read_note && fld_value && fld_value !== \"0\") ?\n (fld_value.length === 3) ? fld_value : \"0_1\" : \"0_0\" )\n\n } else {\n // only show status when weight > 0\n\n // TODO enable this next year. It is turned off because empty scores were submitted\n //const grade_has_value = get_grade_has_value(field_name, data_dict, true);\n\n // PR2-23-05-29 TODO grade_with_exam_rows returns ceex_secret_exam, grade_rows returns secret_exam\n const is_secret_exam = (data_dict.secret_exam || data_dict.ceex_secret_exam);\n const hide_secret_exam = false; // (is_secret_exam && field_name === \"ce_status\" && !permit_dict.requsr_role_admin )\n\n const subj_has_weight = ( [\"se_status\", \"sr_status\"].includes(field_name) && data_dict.weight_se > 0 ||\n [\"pe_status\", \"ce_status\"].includes(field_name) && data_dict.weight_ce > 0 );\n const show_status = (subj_has_weight && !hide_secret_exam);\n\n if (!show_status){\n if (is_secret_exam && !permit_dict.requsr_role_admin){\n title_text = [\n loc.This_is_designated_exam,\n loc.approve_err_list.Dont_haveto_approve_secretexam\n ].join(\"\\n\");\n };\n } else {\n const field_auth1by_id = prefix_str + \"_auth1by_id\";\n const field_auth2by_id = prefix_str + \"_auth2by_id\";\n const field_auth3by_id = prefix_str + \"_auth3by_id\";\n const field_auth4by_id = prefix_str + \"_auth4by_id\";\n const field_published_id = prefix_str + \"_published_id\";\n const field_blocked = prefix_str + \"_blocked\";\n const field_status = prefix_str + \"_status\";\n\n const auth1by_id = (data_dict[field_auth1by_id]) ? data_dict[field_auth1by_id] : null;\n const auth2by_id = (data_dict[field_auth2by_id]) ? data_dict[field_auth2by_id] : null;\n const auth3by_id = (data_dict[field_auth3by_id]) ? data_dict[field_auth3by_id] : null;\n const auth4by_id = (data_dict[field_auth4by_id]) ? data_dict[field_auth4by_id] : null;\n const published_id = (data_dict[field_published_id]) ? data_dict[field_published_id] : null;\n const is_blocked = (data_dict[field_blocked]) ? data_dict[field_blocked] : null;\n\n // - auth3 does not have to sign when secret exam (aangewezen examen)\n // - auth3 also does not have to sign when exemption (vrijstelling) PR2023-02-02\n\n // PR2023-02-07 debug: this is not correct value: !data_dict.examperiod === 4, must be: data_dict.examperiod !== 4\n const auth3_must_sign = (!data_dict.secret_exam && data_dict.examperiod !== 4);\n\n // - auth4 does not have to sign when secret exam (aangewezen examen) or when se-grade\n // - auth4 does not have to sign when se-grade\n // - auth4 also does not have to sign when exemption (vrijstelling) PR2023-02-02\n\n // PR2023-02-07 debug: this is not correct value: !data_dict.examperiod === 4, must be: data_dict.examperiod !== 4\n const auth4_must_sign = (!data_dict.secret_exam && data_dict.examperiod !== 4\n && [\"pe_status\", \"ce_status\"].includes(field_name));\n\n //console.log(\" auth3_must_sign\", auth3_must_sign);\n //console.log(\" auth4_must_sign\", auth4_must_sign);\n\n className = f_get_status_auth_iconclass(published_id, is_blocked, auth1by_id, auth2by_id, auth3_must_sign, auth3by_id, auth4_must_sign, auth4by_id);\n filter_value = className;\n\n let formatted_publ_modat = \"\";\n if (published_id){\n const field_publ_modat = prefix_str + \"_publ_modat\" // subj_publ_modat\n const publ_modat = (data_dict[field_publ_modat]) ? data_dict[field_publ_modat] : null;\n const modified_dateJS = parse_dateJS_from_dateISO(publ_modat);\n formatted_publ_modat = format_datetime_from_datetimeJS(loc, modified_dateJS);\n };\n if (is_blocked) {\n if (published_id){\n title_text = loc.unlocked_11 + \"\\n\" + loc.unlocked_12 + formatted_publ_modat + \"\\n\" + loc.unlocked_13;\n } else {\n title_text = loc.unlocked_01 + \"\\n\" + loc.unlocked_02 + \"\\n\" + loc.unlocked_03;\n };\n } else if (published_id){\n title_text = loc.Submitted_at + \" \" + formatted_publ_modat\n\n } else if(auth1by_id || auth2by_id || auth3by_id || auth4by_id){\n title_text = (data_dict.secret_exam) ? loc.Designated_exam + \"\\n\" : \"\";\n title_text += loc.Approved_by + \": \";\n for (let i = 1; i < 5; i++) {\n const auth_id = (i === 1) ? auth1by_id :\n (i === 2) ? auth2by_id :\n (i === 3) ? auth3by_id :\n (i === 4) ? auth4by_id : null;\n const prefix_auth = prefix_str + \"_auth\" + i;\n if(auth_id){\n const function_str = (i === 1) ? loc.Chairperson :\n (i === 2) ? loc.Secretary :\n (i === 3) ? loc.Examiner :\n (i === 4) ? loc.Corrector : \"\";\n const field_usr = prefix_auth + \"by_usr\";\n const auth_usr = (data_dict[field_usr]) ? data_dict[field_usr] : \"-\";\n\n // PR2023-05-11 Sentry debug: TypeError function_str is undefined\n // solved by adding ' if (function_str) {', not tested yet\n if (function_str) {\n title_text += \"\\n\" + function_str.toLowerCase() + \": \" + auth_usr;\n };\n };\n };\n };\n };\n };\n return [className, title_text, filter_value]\n }",
"function _doUpdateDependencies(acFields, acDeps, acValues, container, containerACFields,\n objectId, valueId, updatedFields, relatedObjectName) {\n //if field has a related field\n objectId = \"\" + objectId;\n updatedFields.push(objectId);\n // find dependant fields in current container\n var allDependentFieldsInfo = acDeps[objectId];\n var acFieldsKey;\n for (key in allDependentFieldsInfo) {\n if (key === 'length' || !allDependentFieldsInfo.hasOwnProperty(key)) {continue;};\n // loop through all ac-fields in current container\n // to find ones to be updated\n for (key1 in containerACFields) {\n if (key1 === 'length' || !containerACFields.hasOwnProperty(key1)) {continue;};\n // get key for acFields array. It holds input,\n // \"wrapped\" with ac functionality\n acFieldsKey = containerACFields[key1];\n // if there's no acField by this key - skip\n var acField = acFields[acFieldsKey];\n if (!acField) {continue;};\n\n if (acField.oid == key && $.inArray(\"\" + acField.oid, updatedFields) == -1) {\n if (!allDependentFieldsInfo[key]) {continue};\n var deps = allDependentFieldsInfo[key][valueId];\n // if something is wrong with dependencies or there are no values\n // set empty data source for particular field\n if (!deps || !deps.length) {\n _updateDataSource(container, acField.element, acField.propertyName, [],\n _autocompleteData[\"Values\"], key, relatedObjectName);\n } else {\n var values = [];\n //get field values by ids\n deps.forEach(function (element) {\n if (acValues[key][\"Values\"][element]) {\n values.push(acValues[key][\"Values\"][element]);\n }\n });\n var valueSetId = _updateDataSource(container, acField.element, acField.propertyName, values,\n _autocompleteData[\"Values\"], key, relatedObjectName);\n }\n // if we set the only value to subfield -\n // update dependant values\n if(valueSetId){\n // recursively update subfields\n _doUpdateDependencies(acFields, acDeps, acValues, container, containerACFields,\n key, valueSetId, updatedFields, relatedObjectName)\n }\n }\n }\n }\n }",
"function job_count_update() {\n $('#job_count_form input').prop('disabled', false);\n if ($('#addr_radio_strat_once_per').is(':checked')) {\n $('#job_count_form input').val('');\n $('#job_count_form input').prop('disabled', true);\n }\n }",
"function updateDependencies (value)\n {\n $.each (dependencyList[value.getFieldID()], function (i, field)\n {\n if (field.updateDependencies (value))\n {\n if (totalTabs > 1)\n {\n if (currentTab === tabHolder[field.getFieldData ().tabID])\n field.showParent ();\n }\n else\n field.showParent ();\n }\n else\n field.hideParent ();\n\n field.updateDependenciesLocal (value);\n });\n }",
"function _updateDependencies(acFields, acData, container, containerACFields, objectId, value, relatedObjectName) {\n if (!acData) {\n return\n }\n var acValues = acData[\"Values\"];\n var acDeps = acData[\"Dependencies\"];\n if (!acValues || !acDeps) {\n return\n }\n var updatedFields = [];\n var valueId = _getPropertyIdByName(acValues, objectId, value);\n if(!valueId && relatedObjectName){\n valueId = _getValueIDByObjectName(relatedObjectName ,value);\n }\n // main logic comes there. And available for recursion\n _doUpdateDependencies(acFields, acDeps, acValues, container,\n containerACFields, objectId, valueId, updatedFields, relatedObjectName);\n }",
"function updateModules(){\n\t\tvar isWanted = this.checked || this.hasClass('activeChoice') || this.hasClass('dependency');\n\t\tvar action = isWanted ? addDependency : removeDependency;\n\t\tvar modules = getData(this)[isWanted ? 'requires' : 'provides'];\n\t\tfor (var i = 0; i < modules.length; i++) if (modules[i]) action(modules[i]);\n\t}",
"function toggleFields(){\r\n $(\".countable\").each(function() {\r\n\r\n // Use regex to get the id number for that row. Match returns an array of values, so\r\n // use [0] to look just at the first item it returns.\r\n id_number = $(this).attr('id').match(/[\\d]{1,2}/)[0];\r\n\r\n // get the type, 'cou' or 'adl'\r\n type = $(this).attr('id').substring(3,6);\r\n\r\n id_prefix = \"#id_\" + type + \"-\" + id_number;\r\n\r\n // toggle fields with same id and type\r\n if ($(this).val() !== \"Y\") {\r\n $(id_prefix + \"-min_grade_required\").hide();\r\n $(id_prefix + \"-pass_fail_accepted\").hide();\r\n $(id_prefix + \"-min_grade_required\").val(\"\"); \r\n $(id_prefix + \"-pass_fail_accepted\").val(\"\");\r\n } else {\r\n $(id_prefix + \"-min_grade_required\").show();\r\n $(id_prefix + \"-pass_fail_accepted\").show(); \r\n }\r\n });\r\n } // end toggleFields",
"updateDependentRecordIds(oldValue, value) {\n this.dependentStoreConfigs && this.dependentStoreConfigs.forEach(configs => {\n configs.forEach(config => {\n const dependentStore = config.dependentStore,\n cache = dependentStore.relationCache[config.relationName],\n localRecords = cache && cache[oldValue] && cache[oldValue].slice();\n localRecords && localRecords.forEach(localRecord => {\n // First update cache\n dependentStore.cacheRelatedRecord(localRecord, value, config.relationName, oldValue); // Then update & announce, otherwise relations wont be up to date in listeners\n\n localRecord.set(config.fieldName, value, false, true);\n });\n });\n });\n }",
"function updateControls() {\n var gotNow = nowGroup.getLayers().length > 0;\n var gotToday = todayGroup.getLayers().length > 0;\n $('#now').prop('disabled', !gotNow);\n $('#now').prop('checked', gotNow);\n $('#today').prop('disabled', !gotToday);\n $('#today').prop('checked', !gotNow && gotToday);\n $('#other').prop('checked', !gotNow && !gotToday);\n}",
"canStatusBeChanged() {\n if(this.isLocked()){\n if(this.dependsOn && this.dependsOn.isLocked()){\n return false;\n } \n return true;\n }\n return false;\n }",
"function addPossibleFieldsValidation(mandatoryObj,formWrapperId){\n\tvar possibleDependency = mandatoryObj.possibleDependencies;\n\tvar fieldName = mandatoryObj.name;\n\t$(formWrapperId+\" [name = '\"+fieldName+\"']\").on(\"change\",function(){\n\t\tvar formValue = $(this).val();\n\t\t$.each(possibleDependency,function(index,value){\n\t\t\tif(formValue == value.fieldValue){\n\t\t\t\tvar explodeField = value.fieldValidate.split(\",\");\n\t\t\t\t$.each(explodeField,function(fIndex){\n\t\t\t\t\tvar addMandatory = $(formWrapperId+\" [name = '\"+explodeField[fIndex]+\"'],[data-name = '\"+explodeField[fIndex]+\"']\");\n\t\t\t\t\tvar setEmptyFields = \"set_empty_\"+explodeField[fIndex];\n\t\t\t\t\tif(addMandatory.attr(\"data-validate\") != undefined){\n\t\t\t\t\t\taddMandatory.attr(\"data-validate\",\"required,\"+$(addMandatory).attr(\"data-validate\"));\t\n\t\t\t\t\t}else{\n\t\t\t\t\t\taddMandatory.attr(\"data-validate\",\"required\");\n\t\t\t\t\t}\n\t\t\t\t\taddMandatory.attr(\"isDependent\",true);\n\t\t\t\t\taddMandatory.parents(\".form-row\").find(\"label\").attr(\"isDependent\",true).addClass(\"label-bold\");\n\t\t\t\t\tif(setEmptyFields != undefined){\n\t\t\t\t\t\tif($(formWrapperId+\" :input[name = '\"+explodeField[fIndex]+\"']\").data(\"type\") == \"select-one\"){\n\t\t\t\t\t\t\t$(formWrapperId+\" :input[name = '\"+explodeField[fIndex]+\"']\").siblings(\".dropdown-toggle\").removeAttr(\"disabled\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$(formWrapperId+\" :input[name = '\"+explodeField[fIndex]+\"'],[data-name = '\"+explodeField[fIndex]+\"']\").removeAttr(\"disabled\");\n\t\t\t\t\t\t$(formWrapperId+\" [name = '\"+explodeField[fIndex]+\"'],[data-name = '\"+explodeField[fIndex]+\"']\").parents(selector_p_r_5).removeClass(\"element-clear\");\n\t\t\t\t\t\t$(formWrapperId+\" [name = '\"+setEmptyFields+\"'],[data-name = '\"+setEmptyFields+\"']\").attr(\"checked\",false);\n\t\t\t\t\t\t$(formWrapperId+\" [name = '\"+setEmptyFields+\"'],[data-name = '\"+setEmptyFields+\"']\").parents(\".checkbox\").show();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t});\n}",
"function updateValidationVar() {\n var primaryNum = 0, secondaryNum = 0;\n angular.forEach(vm.existingDiseases, function (disease) {\n if (disease.rank === 'Primary') {\n primaryNum++;\n } else if (disease.rank === 'Secondary') {\n secondaryNum++;\n }\n });\n\n if (primaryNum === 0) {\n vm.showPrimaryRequired = true;\n vm.showPrimaryOnlyOne = false;\n } else if (primaryNum === 1) {\n vm.showPrimaryRequired = false;\n vm.showPrimaryOnlyOne = false;\n } else {\n vm.showPrimaryRequired = false;\n vm.showPrimaryOnlyOne = true;\n }\n\n if (secondaryNum <= 1) {\n vm.showSecondaryOnlyOne = false;\n } else {\n vm.showSecondaryOnlyOne = true;\n }\n }",
"refreshValidationState() {\n this.errors = {}\n\n for (const field of this.fields) {\n field.refreshValidationState()\n }\n }",
"function statusSetter (ref, module, status){\n var classes = Object.keys(ref[module]);\n console.log(classes);\n for (var i = 0; i < classes.length; i++){\n if (classes[i] !== status){\n ref[module][classes[i]] = false;\n } else {\n ref[module][classes[i]] = true;\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
First player submits their turn, consisting of canvas data, sentence data, and recaptcha response. | function submitFirstTurn(e) {
var img = state.canvas.toDataURL("image/png");
var email = $("email").value.trim();
var sentence = $("sentenceInput").value.trim();
// Validates sentence content.
if (!validateSentence(sentence)) {
return;
}
// Separates emails by commas or by spaces. (Would be nice to allow a mix.)
if (email.match(/,/)) {
email = email.split(/\s*,\s*/);
} else {
email = email.split(/\s+/);
}
// Validates email input.
for (var i = 0; i < email.length; i++) {
if (!email[i].match(/.+@.+\..+/) || email[i].length == 0) {
$("status").innerText = "Please enter valid email addresses.";
return;
}
}
// Verifying the Recaptcha.
var recaptchaChallenge = Recaptcha.get_challenge();
var recaptchaResponse = Recaptcha.get_response();
// Sending pic, sentence, email, & Recaptcha data to server.
sendRequest("/cgi-bin/game.rb", "POST",
"cmd=create&data=" + encodeURIComponent(img) +
"&sentence=" + encodeURIComponent(sentence) +
"&email=" + encodeURIComponent($("email").value) +
"&challenge=" + encodeURIComponent(recaptchaChallenge) +
"&response=" + encodeURIComponent(recaptchaResponse),
function(response) {
var parsedResponse = JSON.parse(response);
$("status").innerText = parsedResponse.message;
if (!parsedResponse.success) {
Recaptcha.reload();
} else {
Recaptcha.destroy();
}
});
} | [
"function submit() {\n displayResponse();\n if(currentTime !== 0) {\n startChallenge();\n }\n }",
"load_next_challenge() {\r\n this.success(\"Good JOB! You solved the question\", \"green\");\r\n if (this.challenges.has_next_challenge()) {\r\n const challenge = this.challenges.next();\r\n this.display_challenge_description();\r\n } else {\r\n this.handle_win();\r\n }\r\n }",
"function submitForm() {\r\n const { username, number, category, difficulty } = getFormData();\r\n if (!username) {\r\n alert(\"Enter a username first!\");\r\n return;\r\n }\r\n playerName = username;\r\n let url = buildURL(number, category, difficulty);\r\n getQuestions(url);\r\n changeScene(userRegPage, questionPage);\r\n}",
"initializeKeySubmit() {\n this.public.activeSeat = this.findNextPlayer(this.public.dealerSeat);\n this.lastPlayerToAct = this.findPreviousPlayer(this.public.activeSeat);\n\n const { activeSeat, playersInHandCount } = this.public;\n\n switch (this.public.phase) {\n case PHASE_MENTAL_SHUFFLE:\n logger.debug('assignning mental cards and changing the phase to key submit preflop');\n this.public.phase = PHASE_KEY_SUBMIT_PREFLOP;\n let currentPlayer = activeSeat;\n for (let i = 0; i < playersInHandCount; i += 1) {\n // Assign the mental cards\n if (this.public.gameMode === GAME_MODE_PLO) {\n this.seats[currentPlayer].public.mentalCards = this.mentalDeck.drawCards(4);\n } else {\n this.seats[currentPlayer].public.mentalCards = this.mentalDeck.drawCards(2);\n }\n logger.debug(`sending mental card ${this.seats[currentPlayer].public.mentalCards} to ${this.seats[currentPlayer].public.name}:${this.seats[currentPlayer].socket}`);\n this.playerSocketEmitter(\n this.seats[currentPlayer].socket,\n 'dealingMentalCards',\n this.seats[currentPlayer].public.mentalCards,\n ); // Tell the player which cards were drawn for him\n currentPlayer = this.findNextPlayer(currentPlayer);\n }\n break;\n case PHASE_PREFLOP: // Draw flop\n this.public.phase = PHASE_KEY_SUBMIT_FLOP;\n this.mentalDeck.communityCards = this.mentalDeck.communityCards.concat(\n this.mentalDeck.drawCards(3),\n );\n break;\n case PHASE_FLOP: // Draw turn\n this.public.phase = PHASE_KEY_SUBMIT_TURN;\n this.mentalDeck.communityCards = this.mentalDeck.communityCards.concat(\n this.mentalDeck.drawCards(1),\n );\n break;\n case PHASE_TURN: // Draw river\n this.public.phase = PHASE_KEY_SUBMIT_RIVER;\n this.mentalDeck.communityCards = this.mentalDeck.communityCards.concat(\n this.mentalDeck.drawCards(1),\n );\n break;\n case PHASE_RIVER:\n this.public.phase = PHASE_KEY_SUBMIT_SHOWDOWN;\n break;\n // no default\n }\n logger.debug(`init key submit ${this.seats[activeSeat].public.name}`);\n this.emitEvent('mental-deck-data', {\n dealt: this.mentalDeck.dealt,\n communityCards: this.mentalDeck.communityCards,\n });\n this.emitEvent('table-data', this.public); // Publish the drawn community cards indexes\n this.timeActivePlayer();\n\n\n // Tell all players to submit keys\n let currentPlayer = activeSeat;\n for (let i = 0; i < this.public.playersInHandCount; i += 1) {\n this.playerSocketEmitter(\n this.seats[currentPlayer].socket,\n 'submitKeys',\n this.getKeysToSubmit(currentPlayer),\n );\n currentPlayer = this.findNextPlayer(currentPlayer);\n }\n }",
"function begin_play(){\n\tif (game_started()){\n\t\talert(\"The game has already started\");\n\t\treturn;\n\t}\n\n\tif(document.getElementById(\"player1_id\").value==\"\"||document.getElementById(\"player2_id\").value==\"\") {\n\t\talert(\"Two player game, both the fields are mandatory.\");\n\t\treturn;\n\t}\n\tstarted = true;\n\tvar p1 = document.getElementById(\"player1_id\").value;\n\tvar p2 = document.getElementById(\"player2_id\").value;\n\tdocument.getElementById(\"player1_id\").value.disabled = true;\n\tdocument.getElementById(\"player2_id\").value.disabled = true;\n\tdocument.getElementById(\"player1_id\").value = `${p1} ${\"(X)\"}`;\n\tdocument.getElementById(\"player2_id\").value = `${p2} ${\"(O)\"}`;\n\tif (turn == 1) {\n\t\tdocument.getElementById(\"turn_info\").innerText = \"Turn for: X\";\n\t} else {\n\t\tdocument.getElementById(\"turn_info\").innerText = \"Turn for: O\";\n\t}\n\tdocument.getElementsByClassName(\"btn btn-primary\")[0].disabled = true;\n\tdocument.getElementsByClassName(\"btn btn-primary\")[2].disabled = false;\n}",
"function recaptchaSubmitHandler(token) {\n _grecaptchaResponse = token;\n\n if (_attemptedCaptchaSubmission && _submitFormHandler) {\n _submitFormHandler();\n }\n}",
"function postProject(recaptchaChallengeField, recaptchaResponseField) {\r\n $('#recaptchaChallengeField').val(recaptchaChallengeField);\r\n $('#recaptchaResponseField').val(recaptchaResponseField);\r\n $('#projectForm').submit();\r\n}",
"function handleCAPTCHA() \n{\n captchaSolved = true;\n}",
"function startChallenge() {\n clearTimer();\n currentTime = CHALLENGE_TIME;\n toggleChallengeControls();\n updateChallengeText();\n timerID = setInterval(updateChallengeTimer, SECOND);\n }",
"function checkLogin() {\n if (grecaptcha.getResponse().length == 0) {\n //reCaptcha not verified\n document.getElementById(\"message\").style.color = \"red\";\n document.getElementById(\"message\").innerHTML = \"do the reCaptcha !!!\";\n } else {\n console.log(\"try to check\");\n var entUsername = \"48414c4c4f\";\n var entPw = \"25477765663132264c436947542a5139\";\n\n var newU = CryptoJS.AES.encrypt(document.getElementById(\"inputText\").value, \"Super Secret Key\");\n var newP = CryptoJS.AES.encrypt(document.getElementById(\"inputPw\").value, \"Super Secret Key\");\n var decryptedU = CryptoJS.AES.decrypt(newU, \"Super Secret Key\");\n var decryptedP = CryptoJS.AES.decrypt(newP, \"Super Secret Key\");\n\n if (a) {\n if (entUsername == decryptedU && entPw == decryptedP) {\n document.getElementById(\"message\").style.color = \"green\";\n document.getElementById(\"message\").innerHTML = \"Success\";\n } else {\n grecaptcha.reset();\n document.getElementById(\"submitButton\").disabled = true;\n document.getElementById(\"submitButton\").style.visibility = \"hidden\";\n\n document.getElementById(\"message\").style.color = \"red\";\n document.getElementById(\"message\").innerHTML = \"Try again / try:\" + tries;\n a = false;\n setTimeout(function () {\n a = true;\n tries++;\n }, 5000);\n }\n } else {\n document.getElementById(\"message\").style.color = \"red\";\n document.getElementById(\"message\").innerHTML = \"Try harder !!\";\n }\n }\n}",
"function make_production_trial(relationship,person1,person2,correct_label,labels,block) {\n var trial = {type:'sidebyside-canvas-button-response',\n stimulus:function (c) {build_greeting_canvas(c,person1,person2,'_______')}, // the label will always be blank\n canvas_size: [500,625],\n prompt: \"<p>Choose a word to finish the greeting.</p>\",\n //show two labelled buttons and have the participant select\n timeline: [{choices: labels,\n //randomise the left-right order of the labels and note that randomisation in data\n on_start: function(trial) {\n trial.data = {block:'learning', \n block_number: block,\n type:'production',\n button_choices:labels,\n correct_answer:correct_label,\n relationship: relationship}},\n //figure out which label they selected, and add that to data\n on_finish: function(data) {\n var button_number = data.response\n var button_pressed = data.button_choices[button_number]\n data.button_selected = button_pressed\n data.greeter = person1\n data.greetee = person2\n data.label = \"?\"\n if(button_pressed === correct_label){data.correct = true;} \n else {data.correct = false;}\n save_kinship_data(data)}},\n // now provide feedback on participant response\n {stimulus:function(c) {\n // find out if the last trial was answered correctly and rebuild the stim with feedback set to True\n var last_trial_correct = jsPsych.data.get().last(1).values()[0].correct\n build_greeting_canvas(c,person1,person2,correct_label + '!',true,last_trial_correct)},\n canvas_size: [500,1500],\n choices:labels,\n button_html:'<button style=\"visibility: hidden;\" class=\"jspsych-btn\">%choice%</button>',\n trial_duration: 3000,\n prompt:function(){\n var last_trial_correct = jsPsych.data.get().last(1).values()[0].correct\n var mistake = jsPsych.data.get().last(1).values()[0].button_selected\n // if correct, print correct. if incorrect, show them the correct response\n if(last_trial_correct){return \"<p><br>Correct! <b>\" + correct_label + \"</b> is the right greeting.\"} \n else {return \"<p><br>Incorrect! You chose <b>\"+ mistake + \"</b>, but the correct greeting is <b>\" + correct_label + \"</b>.\"}},\n }\n ]}\n return trial}",
"function submitPic() {\n var img = state.canvas.toDataURL(\"image/png\");\n var params = getUrlParams();\n var url = \"cmd=pic&data=\" + encodeURIComponent(img) + \"&gameid=\" + params.gameid + \"&turn=\" + params.turn;\n \n sendRequest(\n \t\"/cgi-bin/game.rb\", \"POST\", url,\n \tfunction(response) {\n \t var parsedResponse = JSON.parse(response);\n \t\t $(\"status\").innerText = parsedResponse.message;\n \t});\n}",
"function create_captcha(){var options={};if(Recaptcha.focus_on_load){options['callback']=Recaptcha.focus_response_field;}\nsetTimeout(function(){Recaptcha.create(\"6LezHAAAAAAAADqVjseQ3ctG3ocfQs2Elo1FTa_a\",\"captcha\",options)},0);}",
"function onCaptcha (options, response, body) {\n const recaptchaVer = detectRecaptchaVersion(body);\n const isRecaptchaVer2 = recaptchaVer === 'ver2';\n const callback = options.callback;\n // UDF that has the responsibility of returning control back to cloudscraper\n const handler = options.onCaptcha;\n // The form data to send back to Cloudflare\n const payload = { /* r|s, g-re-captcha-response */ };\n\n let cause;\n let match;\n\n match = body.match(/<form(?: [^<>]*)? id=[\"']?challenge-form['\"]?(?: [^<>]*)?>([\\S\\s]*?)<\\/form>/);\n if (!match) {\n cause = 'Challenge form extraction failed';\n return callback(new ParserError(cause, options, response));\n }\n\n const form = match[1];\n\n let siteKey;\n let rayId; // only for ver 2\n\n if (isRecaptchaVer2) {\n match = body.match(/\\sdata-ray=[\"']?([^\\s\"'<>&]+)/);\n if (!match) {\n cause = 'Unable to find cloudflare ray id';\n return callback(new ParserError(cause, options, response));\n }\n rayId = match[1];\n }\n\n match = body.match(/\\sdata-sitekey=[\"']?([^\\s\"'<>&]+)/);\n if (match) {\n siteKey = match[1];\n } else {\n const keys = [];\n const re = /\\/recaptcha\\/api2?\\/(?:fallback|anchor|bframe)\\?(?:[^\\s<>]+&(?:amp;)?)?[Kk]=[\"']?([^\\s\"'<>&]+)/g;\n\n while ((match = re.exec(body)) !== null) {\n // Prioritize the explicit fallback siteKey over other matches\n if (match[0].indexOf('fallback') !== -1) {\n keys.unshift(match[1]);\n if (!debugging) break;\n } else {\n keys.push(match[1]);\n }\n }\n\n siteKey = keys[0];\n\n if (!siteKey) {\n cause = 'Unable to find the reCAPTCHA site key';\n return callback(new ParserError(cause, options, response));\n }\n\n if (debugging) {\n console.warn('Failed to find data-sitekey, using a fallback:', keys);\n }\n }\n\n // Everything that is needed to solve the reCAPTCHA\n response.captcha = {\n siteKey,\n uri: response.request.uri,\n form: payload,\n version: recaptchaVer\n };\n\n if (isRecaptchaVer2) {\n response.rayId = rayId;\n\n match = body.match(/id=\"challenge-form\" action=\"(.+?)\" method=\"(.+?)\"/);\n if (!match) {\n cause = 'Challenge form action and method extraction failed';\n return callback(new ParserError(cause, options, response));\n }\n response.captcha.formMethod = match[2];\n match = match[1].match(/\\/(.*)/);\n response.captcha.formActionUri = match[0];\n payload.id = rayId;\n }\n\n Object.defineProperty(response.captcha, 'url', {\n configurable: true,\n enumerable: false,\n get: deprecate(function () {\n return response.request.uri.href;\n }, 'captcha.url is deprecated. Please use captcha.uri instead.')\n });\n\n // Adding formData\n match = form.match(/<input(?: [^<>]*)? name=[^<>]+>/g);\n if (!match) {\n cause = 'Challenge form is missing inputs';\n return callback(new ParserError(cause, options, response));\n }\n\n const inputs = match;\n // Only adding inputs that have both a name and value defined\n for (let name, value, i = 0; i < inputs.length; i++) {\n name = inputs[i].match(/name=[\"']?([^\\s\"'<>]*)/);\n if (name) {\n value = inputs[i].match(/value=[\"']?([^\\s\"'<>]*)/);\n if (value) {\n payload[name[1]] = value[1];\n }\n }\n }\n\n // Sanity check\n if (!payload.s && !payload.r) {\n cause = 'Challenge form is missing secret input';\n return callback(new ParserError(cause, options, response));\n }\n\n if (debugging) {\n console.warn('Captcha:', response.captcha);\n }\n\n // The callback used to green light form submission\n const submit = function (error) {\n if (error) {\n // Pass an user defined error back to the original request call\n return callback(new CaptchaError(error, options, response));\n }\n\n onSubmitCaptcha(options, response);\n };\n\n // This seems like an okay-ish API (fewer arguments to the handler)\n response.captcha.submit = submit;\n\n // We're handing control over to the user now.\n const thenable = handler(options, response, body);\n // Handle the case where the user returns a promise\n if (thenable && typeof thenable.then === 'function') {\n // eslint-disable-next-line promise/catch-or-return\n thenable.then(submit, function (error) {\n if (!error) {\n // The user broke their promise with a falsy error\n submit(new Error('Falsy error'));\n } else {\n submit(error);\n }\n });\n }\n}",
"function goToNextChallenge() {\n //Add the current challenge to the answered challenges collection\n var answeredChallenges = Session.get(\"answeredChallenges\");\n answeredChallenges.push(Session.get(\"currentChallengeId\"));\n Session.set(\"answeredChallenges\", answeredChallenges);\n\n //Clear the current challenge ID\n Session.set(\"currentChallengeId\", null); \n\n //Clear the answer text box\n $('#answerTextBox').val(\"\");\n\n //Set the game state to answering\n Session.set(\"gameState\", \"answering\");\n\n //The next time the view wants the current challenge, the next challenge will be loaded \n }",
"function onCaptchaLoad(data) {\n // we should have checks based on what kind of captcha it is:\n // if data[\"captcha\"][\"type\"] == \"text\" blah blah\n // but for now, lets be lazy\n document.getElementById(\"question\").innerText = data[\"captcha\"][\"display_data\"];\n window.captchaID = data[\"id\"];\n // TODO: store captchaID expiry (so that at submit we can check client side, before sending, just to avoid messy request handling less often)\n\n // hide the spinner\n document.getElementById(\"captchaspinner\").style.display = \"none\";\n // make them able to answer!\n document.getElementById(\"captchaloaded\").style.display = \"block\";\n}",
"function clickSubmit() {\n stopDraw();\n readCanvasImage();\n hideResultPlots();\n showPrediction();\n}",
"function submitScore() {\n var scoreInfo = getScoreInfo();\n if (scoreInfo) {\n var xhttp = new XMLHttpRequest();\n\n xhttp.onreadystatechange = function() {\n if (xhttp.readyState === 4 && xhttp.status === 200) {\n //CLEAR MENU & ALERT IT WAS SUCCESSFUL. -> play again button\n getScoreboard();\n //ddSuccessNotification();\n // TODO: add submission confirmation to scoreboard.\n } else if (xhttp.readyState === 4 && xhttp.status !== 200) {\n //addErrorNotification(); // TODO: add error notification to scoreboard.\n //TODO: change error handling\n }\n };\n\n xhttp.open(\n \"POST\",\n \"https://cyber-space.liammahoney.me/score\",\n true\n );\n xhttp.send(JSON.stringify(scoreInfo));\n }\n }",
"function postAction() {\n $(\"#winModal\").modal('hide')\n result.playerposttokens = player.tokens\n result.playerpostpoints = player.points\n result.computerposttokens = com.tokens\n result.computerpostpoints = com.points\n result.responseTime = t2-t1\n startRound()\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set temperatures to offline status | function set_temperatures_offline(){
log_temperatures("Set temperatures offline");
$.each(temperatures, function(i, item) {
if ( item.type=="text" ){
log_temperatures("Set temperatures offline - text");
$("#"+item.id).text("--");
}
if ( item.type=="color" ){
log_temperatures("Set temperatures offline - color");
$("#"+item.id).css( item.style, "#CECECE" );
}
if( item.type=="value %" ){
log_temperatures("Set temperatures offline - value %");
$("#"+item.id).css( item.style, '0%' );
}
if( item.type=="value 100-%" ){
log_temperatures("Set temperatures offline - value 100-%");
$("#"+item.id).css( item.style, '100%' );
}
if ( item.type=="create" ){
log_temperatures("Set temperatures offline - create");
if (!isset (() => item.min)) var min=-30;
else var min=item.min;
if (!isset (() => item.max)) var max=90;
else var max=item.max;
if (!isset (() => item.styleX)) var styleX="style1";
else var styleX=item.styleX;
temperature_update(min, item.id, styleX, min, max);
$("#"+item.id+"-text").text("--°C");
}
});
} | [
"function setTemperature() {\n citiesService.getWeatherDataByCityId(city._id).then(\n function(data) {\n vm.currentTemperature = data.main.temp;\n city.temperature = vm.currentTemperature;\n },\n function(error) {\n console.log(\"Error!\");\n });\n\n }",
"function updateTemperature() {\n $('#current-thermostat-temp').text(thermostat.temperature);\n $('#current-thermostat-temp').attr('class', thermostat.energyUsage());\n }",
"static async updateTemp() { \n\t\tlet weatherData = await Weather.getWeather();\n document.querySelector(\".wind-dir\").innerHTML = `${weatherData[0].wind_deg} <sup>o</sup>`;\n document.querySelector(\".wind-speed\").innerText = `${weatherData[0].wind_speed} km/h`;\n\t\tlet forecasts = Array.from(forecastContents);\n\t\tforecasts.forEach(item => {\n\t\t\tlet temp = Math.round(weatherData[forecasts.indexOf(item)].temp.day);\n\t\t\titem.querySelector(\".degree-num\").innerText = `${temp}`;\t\t\n\t\t})\n\t}",
"function upTemp() {\n // little comment to check PR analysis\n let currTemp = initTemp;\n if (currTemp >= 30 || currTemp < 0) {\n alert('Reached the limit');\n return\n }\n else {\n if (currTemp > 15) {\n setTemperatureColor('hot');\n setInitTemp(currTemp + 1);\n } else {\n setInitTemp(currTemp + 1);\n }\n }\n }",
"function updateTemperature() {\n temperature.text(vm.config.temperature);\n }",
"function setOfflineState() {\n if (getCurrentState() === \"online\") {\n clickStatStopBtn();\n }\n}",
"setSettings(temperature) {\n if (temperature < 40) {\n this.fillColor = this.temperatureLowColor;\n } else if (temperature >= 40 && temperature < 80) {\n this.fillColor = this.temperatureMediumColor;\n } else {\n this.fillColor = this.temperatureHighColor;\n }\n this.range.end = this.calculateUnitsZone(temperature);\n }",
"function updateStyling(temperature) {\n let tempRange = \"\";\n\n if (temperature <= 15) {\n tempRange = \"cold\";\n } else if (temperature > 15 && temperature < 25) {\n tempRange = \"fair\";\n } else if (temperature >= 25 < 35) {\n tempRange = \"warm\";\n } else {\n tempRange = \"hot\";\n }\n\n document.body.setAttribute(\"data-temp-range\", tempRange);\n }",
"function downTemp() {\n let currTemp = initTemp;\n if (currTemp > 30 || currTemp <= 0) {\n alert(undeclaredVariable);\n return\n } else {\n if (currTemp < 15) {\n setTemperatureColor('cold');\n setInitTemp(currTemp - 1);\n } else {\n setInitTemp(currTemp - 1);\n }\n }\n }",
"function updateTemps(units) {\n\t\t$('#current .temp').html(Math.round(currentTemp[units]));\n\t\t$forecastDivs.each(function(index) {\n\t\t\t$(this).find('.high').html(forecast[index][units].high);\n\t\t\t$(this).find('.low').html(forecast[index][units].low);\n\t\t});\n\t}",
"function set_inside_temperature(room, data)\n{\n var is_old = is_date_old(data.e);\n var temperature = parseFloat(data.t);\n current_room_temperatures[room] = temperature;\n\n // Set temperature rounded to 1 decimal place and with '*C' after it\n $('div#' + room + ' p.temperature')\n .html(temperature.toFixed(1) + '℃');\n\n // Set the colour of the room\n $('div#' + room + ', div.' + room)\n .css('background-color', generate_room_colour(temperature, is_old));\n\n // Set emoji\n set_image('div#' + room + ' img#' + room + '_emoji',\n get_image($('div#' + room).css('background-color'), is_old));\n\n // Set the average house temperature\n set_current_average();\n}",
"function setTemperature(){\n readline.question(`Set fridge temperature level to: `, (templevel) => {\n client.setTemperatureLevel({templevel:templevel}, function(err, response){\n console.log(`Response: ${response.message}`);\n });\n })\n}",
"function DecTemp() {\n\tif (actualMode) {\n\t\tconfiguration_modified = true;\n \tshowDataToSend();\n\t\tTemperature--;\n \tupdateTextWithJQuery(\"hvac_temp_id\", Temperature); \n }\n} // End Of DecTemp()",
"function updateTempIndoor(cb) {\n current.board.temp.getCurrentTemp(function(err, temp) {\n if (!err) {\n current.status.temp_indoor = temp;\n } else log.error(\"error reading Temp indoor: \" + err);\n cb();\n });\n }",
"function _set() {\n app.updateTargetTemperature(function(err, temp) {\n app.log('CONTROL updated temp', err, { number: temp.number, current: temp.currentTemperature, target: temp.targetTemperature });\n })\n}",
"function updateTempUnit(unit){\n\t\t\tModel.updateTempSetting(unit); // updates temp unit in model\n Header.tempSetting = unit;\n\t\t\tView.toggleTemp(Model.get('tempSetting')); // update view with temp unit \n\t\t}",
"function updateTemperature() {\n const diff = randBetween(-0.6, 1.8)\n if (meta.rising) {\n fakeData.value += diff\n if (fakeData.value >= meta.max) {\n meta.rising = false\n }\n } else {\n fakeData.value -= diff\n if (fakeData.value <= meta.min) {\n meta.rising = true\n }\n }\n}",
"function sendWaterState() {\n Promise.all([\n isScheduleOn('water'),\n isBoostOn('water')\n ]).then(function(results){\n var status = (results[0] || results[1]) ? '1' : '0';\n if (status !== currentWaterState) {\n mqtt.publish('hvac/boiler/water/control/set', status, {retain: true});\n currentWaterState = status;\n }\n });\n }",
"function hotOrNot (temp) {\n\tif (temp > 75) {\n\t\t$('.temperature').html('Hot!');\n\t} else {\n\t\t$('.temperature').html('Not hot!');\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
STICKERS FUNCTIONS check if an object is included on the favorites (array of objects) array.include() doesn't work to check this object, because facorites was stored and the array of objects only stores object references | function isFavorite(item){
for(var i=0; i< favorites.length; i++){
if(favorites[i].id === item.id) return true;
}
return false;
} | [
"isFavoritedBy(user){\n for (let favStory of user.favorites){\n if (favStory.storyId === this.storyId) return true;\n }\n return false;\n }",
"function favorited(favorites, recipe_id){\n for (var i=0; i<favorites.length; i++){\n if (favorites[i].recipe_id == recipe_id){\n return true;\n }\n }\n return false;\n }",
"isFavorite(story) {\n for (let i = 0; i < this.favorites.length; i++) {\n if (this.favorites[i].storyId === story.storyId) {\n return true\n }\n }\n return false\n }",
"static isFavorite(inFavStories, inStoryId) {\n\n // inFavStories is an array of story objects. We need to check whether \n // inStoryId is a storyId for one of the favorite stories.\n\n const foundStory = inFavStories.some(currStory =>\n currStory.storyId === inStoryId\n )\n\n return foundStory;\n\n }",
"function checkForFavorites() {\n // grab the favorited story's IDs\n let favoriteIds = currentUser.favorites.map(function(obj) {\n return obj.storyId;\n })\n \n // loop through the stories on the page, check to see if their Id's are one of our favorite story IDs,\n // if so, make their star's yellow\n for (let story of storyList.stories) {\n if (favoriteIds.includes(story.storyId)) {\n $(`#${story.storyId}`).children().eq(0).addClass('hasBeenFavorited')\n }\n }\n }",
"function checkIfFavorite(story)\n{\n if(currentUser){\n if(currentUser.favorites.length !==0)\n {\n let faves=new Set(currentUser.favorites.map(s=>s.storyId))\n return(faves.has(story.storyId))\n }\n}\nreturn\n}",
"function isFavorite(data) {\r\n const findFavorite = favorites.find((fav) => {\r\n return fav.show.id === data.show.id;\r\n });\r\n // si retorna undefine el elemento no es favorito = false\r\n\r\n if (findFavorite === undefined) {\r\n return false;\r\n\r\n // si lo encuentra retorna true\r\n } else {\r\n return true;\r\n }\r\n}",
"function isAlreadyFavorite(id){\n var match = favs.filter(function(fav){return id === fav.id});\n //if already exists the obj will already be in the favs array therefore match.length > 0\n return match.length > 0\n}",
"function checkFavorite(story) {\n return currentUser.favorites.some(function(storyItem){\n return storyItem.storyId === story.storyId;\n })\n}",
"function isShowFav(item) {\r\n const favoriteFound = favoritesList.find((favorite) => {\r\n return favorite.id === item.id;\r\n });\r\n if (favoriteFound === undefined) {\r\n return false;\r\n } else {\r\n return true;\r\n }\r\n}",
"function checkFavorites() {\n let resultList = document.querySelectorAll('.js-main-show-container');\n\n for (let result of resultList) {\n let favObject = favShows.findIndex(\n (show) => parseInt(result.id) === show.id\n );\n\n if (favObject >= 0) {\n result.classList.add('added-to-favs');\n }\n }\n}",
"function areFavoritesInCachedWeatherData()\n{\n var allfound = true;\n var weatherdata = getCachedWeatherdata();\n \n if (!weatherdata)\n return false;\n\n $.each(app.favorites, function(i, favorite) {\n var found = false;\n \n $.each(weatherdata.forecasts, function(i, forecast) {\n if (forecast.forecast[0].geoid==favorite.id)\n found = true;\n });\n \n if (!found) {\n allfound = false;\n return false;\n }\n });\n \n return allfound;\n}",
"function isInFavorites(shows) {\n let favorites = JSON.parse(localStorage.getItem(\"favorites\")).map(\n item => item.id\n );\n let result = shows.map(item => {\n if (favorites.includes(item.id)) {\n item.favorite = true;\n } else {\n item.favorite = false;\n }\n return item;\n });\n return result;\n}",
"checkFavorited() {\n for(let i = 0; i < this.state.favorites.length; i++)\n {\n if (this.state.favorites[i].id === this.state.selected)\n {\n return true\n }\n }\n return false\n }",
"userHasFav(favArtworkId) {\r\n if (welcomePage.authUser.favorites && welcomePage.authUser.favorites.includes(favArtworkId)) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }",
"function checkFavsArr(favs, rposts) {\n rposts.forEach(function(post, index) {\n if (favs[post.id] === true) {\n rposts[index].favorited = true;\n }\n });\n return rposts\n}",
"function inFavList(symbol){\n\n // Import favoties list from the local storage\n var favorites = localStorage.getItem(\"favorites\");\n favorites = JSON.parse(favorites);\n\n // Check if the symbol is in the list\n if (favorites !== null && favorites !== []){ \n const index = favorites.indexOf(symbol)\n if(index > -1) {\n return true;\n }\n }\n return false;\n \n }",
"alreadyFavorited(checkId) {\n //returns -1 if checkId is not in this users favorite stories\n const isFavorited = this.getFavoriteIds().findIndex(id => (\n //if this story Id is the same as the one passed in, return true\n id === checkId\n ));\n //if the storyId inputted is not already favored, return false\n if (isFavorited === -1) {\n return false;\n }\n //otherwise, return true\n return true;\n }",
"function isPageFavourite(data) {\n // Ineffectient . Need To Refactor and make Array an map\n var count = 0;\n if (favouriteList.isEmpty()) {\n return false;\n }\n for (count; count < favouriteList.length; count++) {\n if (favouriteList[count].id === data.id) {\n return true;\n }\n }\n return false;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a promise which resolves to the download MessagePort. | function _getDownloadServer()
{
// If we already have a download port, return it.
if(_downloadPort != null)
return _downloadPort;
_downloadPort = new Promise((accept, reject) => {
// Send request-download-channel to window to ask the user script to send us the
// GM.xmlHttpRequest message port. If this is handled and we can expect a response,
// the event will be cancelled.
let e = new Event("request-download-channel", { cancelable: true });
if(window.dispatchEvent(e))
{
reject("GM.xmlHttpRequest isn't available");
return;
}
// The MessagePort will be returned as a message posted to the window.
let receiveMessagePort = (e) => {
if(e.data.cmd != "download-setup")
return;
window.removeEventListener("message", receiveMessagePort);
_downloadPort = e.ports[0];
accept(e.ports[0]);
};
window.addEventListener("message", receiveMessagePort);
});
return _downloadPort;
} | [
"close() {\n return new Promise((resolve, reject) => {\n if (!this._port || this._port.isOpen === false) {\n resolve();\n return;\n }\n this._port.close((error) => {\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n });\n });\n }",
"function wait_for_reply(t, port) {\n return new Promise(function(resolve) {\n var resolved = false;\n port.onmessage = t.step_func(function(event) {\n assert_false(resolved);\n resolved = true;\n resolve(event.data);\n });\n });\n }",
"get bufferPromise() {\n return this._downloadPromise;\n }",
"_sendAsync(msg, port, address) {\n return new Promise((resolve, reject) => {\n this.socket.send(msg, port, address, (err, bytes) => {\n if (err) {\n reject(err)\n }\n else {\n resolve(bytes)\n } \n })\n })\n }",
"function requestPort() {\n\n return new Promise((resolve, reject) => {\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n rl.question(fonts.question('Enter a port you will forward messages to'), (answer) => {\n\n rl.close();\n\n if (answer !== '') {\n resolve(answer);\n } else {\n reject('port empty');\n }\n\n });\n\n });\n}",
"buildModemInterface() {\n return new Promise((resolve, reject) => {\n this.log(`starting modem interface on port ${this.uri} @ ${this.baud_rate}`);\n let serial_port = new SerialPort(this.uri, {\n baudRate: this.baud_rate\n });\n serial_port.on('open', () => {\n resolve(serial_port);\n });\n serial_port.on('error', (err) => {\n reject(err);\n });\n serial_port.on('data', (data) => {\n // buffer the received data\n this.response_buffer += data.toString();\n // check if the response code exists in our buffered data\n this.response_codes.forEach((code) => {\n if (this.response_buffer.toUpperCase().indexOf(code) > -1) {\n this.handleModemResponse({\n data: this.response_buffer.replace(code, '').trim(), \n code: code\n });\n this.response_buffer = '';\n }\n })\n });\n return serial_port;\n });\n }",
"open() {\n return new Promise((resolve, reject) => {\n if (!this._port) {\n this._port = new SerialPort(this._path, this._options);\n }\n if (this._port.isOpen === true) {\n resolve();\n return;\n }\n\n this._port.once('open', () => {\n this.emit('serial-open');\n });\n this._port.once('close', () => {\n this.emit('serial-close');\n });\n this._port.on('data', (buf) => {\n this._handleReceivedData(buf);\n });\n\n this._port.open((error) => {\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n });\n\n });\n }",
"function Download()\n{\n this._deferSucceeded = Promise.defer();\n}",
"async getPort() {\n const port = this.getRandomPort();\n\n return await this.testPort(port).catch(() => {\n return this.getPort();\n });\n }",
"async function getMessageFromServiceWorker() {\n return new Promise(resolve => {\n function listener(event) {\n navigator.serviceWorker.removeEventListener('message', listener);\n resolve(event.data);\n }\n\n navigator.serviceWorker.addEventListener('message', listener);\n });\n}",
"function portRead( port, num ) {\n\n return new Promise( function( resolve ){\n let result = [];\n\n function ondata( data ) {\n result.push( ...data );\n //console.log('portread ', data, result );\n if( result.length >= num ) {\n\n port.removeListener('data', ondata );\n resolve( result );\n }\n }\n\n port.on( 'data', ondata );\n });\n\n}",
"waitForDisconnection() {\n console.log('[3] bleTransport: waitForDisconnection()');\n \n //return Promise.resolve(); //TODO\n\n /* TODO */\n this._debug('Waiting for target device to disconnect.');\n const TIMEOUT_MS = 10000;\n\n return new Promise((resolve, reject) => {\n const connectedDevice = this._getConnectedDevice(this._transportParameters.targetAddress);\n if (!connectedDevice) {\n this._debug('Already disconnected from target device.');\n return resolve();\n }\n\n let timeout;\n const disconnectionHandler = device => {\n this._debug('### device.instanceId, connectedDevice.instanceId =', device.instanceId, connectedDevice.instanceId);\n if (device.instanceId === connectedDevice.instanceId) {\n clearTimeout(timeout);\n this._debug('Received disconnection event for target device.');\n this._adapter.removeListener('deviceDisconnected', disconnectionHandler);\n resolve();\n }\n };\n\n timeout = setTimeout(() => {\n this._adapter.removeListener('deviceDisconnected', disconnectionHandler);\n reject(createError(ErrorCode.DISCONNECTION_TIMEOUT,\n 'Timed out when waiting for target device to disconnect.'));\n }, TIMEOUT_MS);\n\n this._adapter.on('deviceDisconnected', disconnectionHandler);\n });\n /* */\n }",
"open() {\n if (this.port && this.port.isOpen) {\n return Promise.resolve();\n }\n\n return new Promise((res, rej) => {\n debug('Opening serial port.');\n\n this.port.open(err => {\n if (err) {\n return rej(err);\n }\n\n debug('Initializing SLIP decoder.');\n // Start listening for data, and pipe it all through a SLIP decoder.\n // This code will listen to events from the SLIP decoder instead\n // of from the serial port itself.\n this.slipDecoder = new slip.Decoder({\n onMessage: this.onData.bind(this),\n });\n\n this.port.on('data', this.onRawData.bind(this));\n\n return res();\n });\n });\n }",
"readWait() {\n if (!this.used) {\n throw new Error(`tcp${this.id} is not started`);\n }\n return new Promise((resolve, reject) => {\n this._addReadObserver(resolve);\n });\n }",
"async stop() {\n return new Promise(async (resolve, reject) => {\n // Don't do anything if not listening\n if (!this.isListening)\n return resolve();\n\n this.isListening = false; // This flag is used to stop after handling a message\n this.stopPromise = { resolve, reject };\n this._log(this.levels.debug, 'stop', 'Stop initiated. Unsubscribing from request channel.');\n\n // Unsubscribe from request channel to stop receiving requests\n try {\n await this.subscriber.unsubscribe(this.requestChannel);\n }\n catch (error) {\n this._log(this.levels.warning, 'stop', 'Failed to unsubscribe from request channel. Trying to continue with shutdown.');\n }\n\n if (this.isWorking) {\n this._log(this.levels.info, 'stop', 'Waiting for current task to finish.');\n return;\n }\n\n this._shutdown();\n });\n }",
"download () {\n const context = this\n\n this.showInfo(this.$t('download.preparingDownload'), { timeout: 0 })\n this.buildContent().then((content) => {\n // The way to force a native browser download of a string is by\n // creating a hidden anchor and setting its href as a data text\n const link = document.createElement('a')\n link.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(content)\n\n // Check if it has reached the max length\n if (link.href.length > 2097152) {\n this.showError(this.$t('download.fileTooBigToBeDownloaded'), { timeout: 2000 })\n } else {\n // Set the filename\n const timestamp = new Date().getTime()\n const format = context.lodash.find(context.downloadFormats, (df) => { return df.value === context.downloadFormat })\n // If the file has the default name, add a unique timestamp\n if (this.downloadFileName === this.defaultDownloadName) {\n link.download = `${context.downloadFileName}_${timestamp}.${format.ext}`\n } else {\n link.download = `${context.downloadFileName}.${format.ext}`\n }\n\n // Fire the download by triggering a click on the hidden anchor\n document.body.appendChild(link)\n link.click()\n link.remove()\n this.showSuccess(this.$t('download.fileReady'), { timeout: 2000 })\n this.closeDownload()\n }\n }).catch(error => {\n console.error(error)\n this.showError(this.$t('download.errorPreparingFile'), { timeout: 2000 })\n })\n }",
"async requestExternalPort(username) {\n return new Promise((resolve) => {\n const requestTimeout = setTimeout(() => {\n logger_1.Logger.internal.warn(\"Parent process did not respond to port allocation request within 5 seconds - assigning random port.\");\n resolve(undefined);\n }, 5000);\n // setup callback\n const callback = (port) => {\n clearTimeout(requestTimeout);\n resolve(port);\n this.portRequestCallback.delete(username);\n };\n this.portRequestCallback.set(username, callback);\n // send port request\n this.sendMessage(\"portRequest\" /* PORT_REQUEST */, { username });\n });\n }",
"function downloadFile() {\n return selectTableInfo().then((lastVersionFileLink) => {\n\n const file = fs.createWriteStream(fileName);\n const request = http.get(lastVersionFileLink, function (response) {\n response.pipe(file);\n });\n });\n}",
"close() {\n return this.flashAddress(0, 0)\n .then((result) => this.flashFinish(false))\n .then((result) => this._port.close((err) => {\n log.info(\"Closing port...\");\n this.portIsOpen = false;\n }));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set CSS transition time | function setTransitionTime(time) {
time = time || '0';
$this.css('-webkit-transition-duration', time + 'ms');
} | [
"function setTransitionTime (timeMs){\n _screenElement.container.css({'transition-duration': timeMs + 'ms'});\n }",
"addTransitionTimeToCSS(){\n\t\tdocument.getElementById(this._elementID).style.transition = 'filter '+this._transitionTime+'s';\n\t}",
"function setAnimTiming() {\n var time = options.animTime,\n transitionDuration = 'webkitTransitionDuration';\n\n if (!time) {\n options.animTime = parseFloat(win.getComputedStyle($smartBanner)[transitionDuration]);\n }\n style($smartBanner, transitionDuration, time + 's');\n style($placeholder, transitionDuration, time + 's');\n }",
"function setTransitionDuration(sec) {\n\n _reel1.style.webkitTransitionDuration = sec + \"s\";\n _reel1.style.transitionDuration = sec + \"s\";\n _reel2.style.webkitTransitionDuration = sec + \"s\";\n _reel2.style.transitionDuration = sec + \"s\";\n _reel3.style.webkitTransitionDuration = sec + \"s\";\n _reel3.style.transitionDuration = sec + \"s\";\n\n}",
"function addTransitionDelay(node, delay) {\n\tnode.style.transitionDelay = delay + 's';\n\tnode.style.WebkitTransitionDelay = delay + 's';\n}",
"function transition(element, time) {\n return time && time > 0 ? element.transition().duration(time) : element\n }",
"function setCssTransitionDuration(){\n if( +(config.transitionDuration) !== _transitionDuration ){\n var vendors = ['-webkit-', '-moz-', '-o-', '-ms-', ''],\n time1 = (config.transitionDuration/1000),\n time2 = time1/2;\n $('.modal-container, .content', $element).attr('style', vendors.join('transition-duration: '+time1+'s;'));\n $('.loader-container', $element).attr('style', vendors.join('transition-duration: '+time2+'s;'));\n }\n }",
"constructor(transitionTime) {\n this.transitionTime = transitionTime;\n }",
"setTransDuration($el) {\n\t\t$el[0].style.WebkitTransition = `${this.transitions[this.transitionType].property} ${this.settings.transTime}s ${this.transitions[this.transitionType].easing}`;\n\t\t$el[0].style.MozTransition = `${this.transitions[this.transitionType].property} ${this.settings.transTime}s ${this.transitions[this.transitionType].easing}`;\n\t}",
"function transTimer(){\n transitionTime--;\n $(\"#countDown\").text(transitionTime);\n }",
"function transitionCSS(element, transProperty, transDuration, transFunction, style) {\n element.style.transitionProperty = transProperty;\n element.style.transitionDuration = transDuration;\n element.style.transitionTimingFunction = transFunction;\n if (style) {\n setTimeout(function () {\n applyStyle(element, style);\n }, 50);\n }\n }",
"function setTransition(){\n\t\t\n\t\t//add css tansition\n\t\tif(g_options.tiles_enable_transition == true)\n\t\t\tg_objParent.addClass(\"ug-tiles-transit\");\n\t\t\n\t}",
"function resetDelay(delay) {\n delay.style.transitionDelay = '0s'\n}",
"function configureTransition(t, delay, ease) {\n t.delay(delay).ease(ease);\n}",
"function setTransitionDuration(els, value) {\n els.forEach(function (el) {\n if (el) {\n el.style.transitionDuration = value + \"ms\";\n }\n });\n }",
"static set smoothDeltaTime(value) {}",
"function setTransitionDuration(els, value) {\n els.forEach(function (el) {\n if (el) {\n el.style.transitionDuration = value + \"ms\";\n }\n });\n }",
"function delayTransitionInComplete() { \n\t\t//setTimeout(transitionInComplete, 0);\n\t\ttransitionInComplete();\n\t}",
"function setUpCSSTransitions(duration) {\n var cell = this;\n util.setTransitionDurationSeconds(cell.element, cell.durationRatio * duration);\n util.setTransitionDelaySeconds(cell.element, cell.delayRatio * duration);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
setMinPermintaan set the minPermintaan variable with value from text input | function setMinPermintaan () {
minPermintaan = document.getElementById('newMinPermintaan').value;
} | [
"function setMinPersediaan(params) {\n minPersediaan = document.getElementById('newMinPersediaan').value;\n }",
"function _setMinutos( min )\r\r\r\n{\r\r\r\n\tif( this.validaInt( min, \"Tempo.setMinutos( int ) - Número inválido.\" ) )\r\r\r\n\t\tthis._minutos = min;\r\r\r\n}",
"set min(value){Helper.UpdateInputAttribute(this,\"min\",value)}",
"function setXMin(xmin) {\n document.getElementById(\"xMinInput\").value=xmin;\n}",
"get min() {\n return (this.startInput$.value || {}).min || null;\n }",
"function setMaxPermintaan() {\n maxPermintaan = document.getElementById('newMaxPermintaan').value;\n }",
"function setMinData() {\n res = 'min = ' + ss.min(data)\n $('.minData').text(res)\n }",
"function setMaxPersediaan() {\n maxPermintaan = document.getElementById('newMaxPersediaan').value;\n }",
"set min(value) {\n if (!diceUtils.isNumeric(value)) {\n throw new TypeError('min must be a number');\n }\n\n this[minSymbol] = parseFloat(value);\n }",
"function setMinimumAmount(min_amount) {\n min_rent_amount = min_amount;\n //-console.log(min_amount);\n}",
"function filterByMinCal(event) {\n setFilterMinCal(parseInt(event.target.value));\n }",
"function setMinDateTime(){\n let currentDate = new Date();\n let day = currentDate.getDate();\n let month = currentDate.getMonth() + 1;\n let year = currentDate.getFullYear();\n day = (day < 10) ? ('0' + day) : day;\n month = (month < 10) ? ('0' + month) : month;\n let min = year + '-' + month + '-' + day + 'T00:00'; // format za datum vreme\n \n $(\".datum-vreme-polje\").attr('min', min);\n }",
"get minNumber() {\n const min = parseFloat(this.min);\n if (!this.min || isNaN(min)) {\n return 0;\n }\n return min;\n }",
"function getMin(){\n if ((document.getElementById(\"userMin\").value)===\"\"){\n return 1;\n }\n else {\n return Number(document.getElementById(\"userMin\").value);\n}\n}",
"setMin(minIn) {\n // paper-single-range-slider needs a safety check that the min value we are going to set is\n // not larger than the max value which is already set\n if(this.max < minIn) this.max = minIn;\n\n this.min = minIn;\n this._prevUpdateValues = [this.min, this.max];\n\n // update the selected value if it is now outside of the lower bound,\n // or just update the position of the overlay divs for the min/max knobs\n if(this.valueMin < this.min) this._setValuesNoTrans(this.min,null,'setMin');\n\n return;\n }",
"set min(value){Helper.UpdateInputAttribute(this,\"minlength\",value)}",
"get lMin() { return Core.LocalizeNumber(this.min) || \"\"; }",
"function setMinCustomDie(){\r\n minCustomDie = inMinCustomDie.value;\r\n}",
"setMin() {\n this.min = this.lows.reduce((carry, low) => {\n return Math.min(carry, low);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
It generates hexadecimal sequence from a dataurl with Base64 encoded data | function hexFromDataurl(dataurl,W,H,sd){W=Math.floor(Math.abs(W)),H=Math.floor(Math.abs(H)),sd=Math.floor(Math.abs(sd));var slf=window,sd_3=sd>99999999999999?(99999999999999).toString(3):sd.toString(3),sdL=sd_3.length,buffer='',i=0,v='',L=0,seq='';v=window.atob(dataurl.replace(/data\:[^/]+\/[^/]+\;base64\,/,'')).replace(/\s/g,'');L=v.length;while(i<L){buffer=(+v.codePointAt(i)).toString(16)[sd_3[i%sdL]];seq+=i>0?(i%W>0?'':'\n'):'';seq+=!buffer?0:buffer;i+=1;i=i>(W*H-1)?L:i;}return seq;} | [
"function base64url(data) {\n return Buffer.from(JSON.stringify(data))\n .toString(\"base64\")\n .replace(/=/g, \"\")\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\");\n}",
"function fromBase64Url(data) {\n var input = data.padRight(data.length + (4 - data.length % 4) % 4, '=')\n .replace(/\\-/g, '+')\n .replace(/_/g, '/');\n\n return toArrayBuffer(atob(input));\n}",
"function Base64ExtractPNG(data_url)\n{\n return data_url.substring(DATA_URL_HEADER_OFFSET);\n}",
"static base64UrlEncode(data) {\n var encoded = Buffer.from(data).toString('base64');\n return encoded.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n }",
"function utoa(data) {\n return btoa(unescape(encodeURIComponent(data)));\n}",
"function b64urltohex(s) {\r\n\t\tvar ret = \"\"\r\n\t\tvar i;\r\n\t\tvar k = 0; // b64 state, 0-3\r\n\t\tvar slop;\r\n\t\tfor (i = 0; i < s.length; ++i) {\r\n\t\t\tv = b64mapurl.indexOf(s.charAt(i));\r\n\t\t\tif (v < 0)\r\n\t\t\t\tcontinue;\r\n\t\t\tif (k == 0) {\r\n\t\t\t\tret += int2char(v >> 2);\r\n\t\t\t\tslop = v & 3;\r\n\t\t\t\tk = 1;\r\n\t\t\t} else if (k == 1) {\r\n\t\t\t\tret += int2char((slop << 2) | (v >> 4));\r\n\t\t\t\tslop = v & 0xf;\r\n\t\t\t\tk = 2;\r\n\t\t\t} else if (k == 2) {\r\n\t\t\t\tret += int2char(slop);\r\n\t\t\t\tret += int2char(v >> 2);\r\n\t\t\t\tslop = v & 3;\r\n\t\t\t\tk = 3;\r\n\t\t\t} else {\r\n\t\t\t\tret += int2char((slop << 2) | (v >> 4));\r\n\t\t\t\tret += int2char(v & 0xf);\r\n\t\t\t\tk = 0;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (k == 1)\r\n\t\t\tret += int2char(slop << 2);\r\n\t\treturn ret;\r\n\t}",
"function convertBase64UrlToBlob(urlData) {\n\n var bytes = window.atob(urlData.split(',')[1]); //remove the head of the url, and decode into bytes.\n\n var ab = new ArrayBuffer(bytes.length);\n var ia = new Uint8Array(ab);\n for (var i = 0; i < bytes.length; i++) {\n ia[i] = bytes.charCodeAt(i);\n }\n\n return new Blob([ab], {type: 'image/png'});\n }",
"function generateKey(_url, _data) {\n var key = _data ? (_url + _data) : _url;\n key = obfuscateKeys && window.btoa ? window.btoa(key) : key;\n return key;\n }",
"function Base64x(){}",
"function dataUrlToBase64(u) {\n\n if(!u) {\n throw Error('the data url must be supplied to convert to base64');\n }\n\n if(0!= u.indexOf('data:')) {\n throw Error('the data url was unable to be converted to base64 because it does not look like a data url');\n }\n\n var commaI = u.indexOf(',');\n\n if(-1==commaI) {\n throw Error('expecting comma in data url to preceed the base64 data');\n }\n\n if(!_.indexOf(u.substring(5,commaI).split(';'),'base64')) {\n throw Error('expecting base64 to appear in the data url');\n }\n\n return u.substring(commaI+1);\n }",
"getEncodedString(){let length=this.__data.length;for(;isFinite(this.__length)&&this.__data.length<this.__length;)this.__data.push(0);let raw=String.fromCharCode(...this.__data);return this.__data.length=length,tchmi_base64encode(raw)}",
"function prepareBASE64(value) {\n\n\tvar index = 0;\n\tvar output = '';\n\tvar length = value.length;\n\n\twhile (index < length) {\n\t\tvar max = index + 68;\n\t\tif (max > length)\n\t\t\tmax = length;\n\t\toutput += value.substring(index, max) + CRLF;\n\t\tindex = max;\n\t}\n\n\treturn output;\n}",
"async function getHexDataImage(url) {\n\tlet hexDataStr;\n\ttry {\n\t\tawait updateStatus(\"getting blob of image at \" + url);\n\t\tlet b = await getRemoteBlob(url); // fetches img blob\n\n\t\tawait updateStatus(\"getting buffer of image blob\");\n\t\tlet arrayBuffer = await b.arrayBuffer(); // get ArrayBuffer from blob;\n\t\tawait updateStatus(\"converting buffer into string\");\n\t\thexDataStr = String(await buf2hex(arrayBuffer)); // converts hex data of arrayBuffer to string\n\t} catch (e) {\n\t\tconsole.error(e);\n\t\thexDataStr = \"useAlt\";\n\t}\n\tconsole.debug(hexDataStr);\n\treturn hexDataStr;\n}",
"async function getHexDataImage(url) {\n\tlet hexDataStr;\n\ttry {\n\t\tlet b = await getRemoteBlob(url); // fetches img blob\n\t\t// if (pictNum == 1) {\n\t\t// \tpicture1Blob = b;\n\t\t// }\n\t\t// else if (pictNum == 2) {\n\t\t// \tpicture2Blob = b;\n\t\t// }\n\t\t// else if (pictNum == 3) {\n\t\t// \tpicture3Blob = b;\n\t\t// }\n\t\t// else if (pictNum == 4) {\n\t\t// \tpicture4Blob = b;\n\t\t// }\n\n\t\tlet arrayBuffer = await b.arrayBuffer(); // get ArrayBuffer from blob;\n\t\thexDataStr = String(buf2hex(arrayBuffer)); // converts hex data of arrayBuffer to string\n\t} catch (e) {\n\t\tconsole.error(e);\n\t\thexDataStr = \"useAlt\";\n\t}\n\tconsole.debug(hexDataStr);\n\treturn hexDataStr;\n}",
"function task1(str) {\n let bytes = new Buffer(str, 'hex');\n\n return bytes.toString('base64');\n}",
"function base64ToUrl(s) {\n return s.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/\\=+$/, '');\n }",
"function getBase64Data(url) {\n\tvar defer = q.defer();\n\n\trequest({url, encoding: 'base64'}, (err, res, body) => {\n\t\tif (err) {\n\t\t\tdefer.reject(err);\n\t\t}\n\n\t\tdefer.resolve(body);\n\t});\n\n\treturn defer.promise;\n}",
"function url_safe_uuid() {\n\t \treturn urlencodeBase64(btoa(uuid_fn()));\n\t }",
"function extractDataUriData(str) {\n var matches = str.match(parseDataUriRe);\n return base64DecodeUnicode(matches[2]);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ajax call find all movie | function findAllMovie(){
$("#allMovies").click(function(){
url="../MovieCalender/index.php?route=CustomerCalender/showAllMovies";
$.get(url,function(data,status){
data = JSON.parse(data);
console.log(data);
createList(data);
})
})
} | [
"function loadMovies() {\n $.ajax({\n \turl: movieUrl\n }).done(function(response){\n console.log(response);\n \t\t insertContent(response.results);\n \t }).fail(function(error) {\n console.log(error);\n })\n }",
"function get_movies() {\n\t$.ajax({\n\t\ttype: 'GET',\n\t\turl: apiUrl,\n\t\tresponseType: 'application/json',\n\t\tdataType: 'json',\n\t\theaders: {\"Authorization\" : id_token},\n\t\tsuccess: function(data) {\n\t\t\tset_movies(JSON.parse(data.body));\n\t\t\tdraw_movie_table(movies);\n\t\t},\n\t\terror: function(data) {\n\t\t\tconsole.log(\"failed to download movie data\");\n\t\t\t$(\"#c_logonform\").dialog(\"open\");\n\t\t\tconsole.log(data);\n\t\t}\n\t});\n}",
"function movieSearch(searchString) {\n var settings = {\n \"url\": \"https://api.themoviedb.org/3/search/movie?query=\" + encodeURIComponent(searchString) + \"&api_key=\" + user.apiKey,\n // \"url\": \"https://sleepy-dusk-13496.herokuapp.com/api/movies\",\n \"method\": \"GET\"\n };\n $.ajax(settings).done(function(response) {\n console.log(response);\n $('.topTwentyBox').html('');\n response.results.forEach(function(movie) {\n var newMovie = new MovieDetails(movie);\n newMovie.addToList();\n });\n });\n}",
"function loadMovies() {\n $.ajax({\n url: movieUrl\n }).done(function (ans) {\n //console.log(ans); //ładuje jsona do konsoli\n ans.forEach(function (el) {\n var tytlE = el.title;\n //console.log(tytlE); // wypisuje w kons. tytuł\n var desctiptioN = el.description;\n //console.log(desctiptioN); // wypisuje w kons. opis\n var idMovie = el.id; // pobieram id filmu - żeby go zapisać jako atrybut data-id>> do wskazywania np. w usuwaniu\n var screenings = el.screenings;\n console.log(screenings);\n\n\n insertContent(tytlE, desctiptioN, idMovie, screenings);\n\n\n })\n }).fail(function (error) {\n console.log(error)\n })\n }",
"function search(title) {\n\n $.ajax({\n type: 'GET',\n url: 'http://www.omdbapi.com/?t=' + title,\n dataType: 'JSON',\n success: function (response) {\n console.log(\"Finish searching for \" + title);\n console.log(\"This is the response \" + response);\n\n $('#movietitle').text(response['Title']);\n $('#movieyear').text(response['Year']);\n $('#movieposter').attr(\"src\", response['Poster']);\n }\n })\n }",
"function getActionMovies(){\n var url = \"https://api.themoviedb.org/3/discover/movie?api_key=19f84e11932abbc79e6d83f82d6d1045&with_genres=28\";\n fetchMovies(url, '#action-movies', 'backdrop_path');\n}",
"function get_movie_info_OMDB(film) {\r\n var url = \"http://www.omdbapi.com/?t=\" + film[\"name\"];\r\n $.ajax({\r\n \"type\": \"GET\",\r\n \"dataType\": \"JSON\",\r\n \"url\": url,\r\n \"success\": function(result) {\r\n display_movie_info(result);\r\n },\r\n \"error\": function(error) {\r\n console.log(error.responseText);\r\n }\r\n });\r\n}",
"function getMovieListFromSearch(name){\n requesting = true;\n $.ajax({\n type : 'POST',\n url : '/api/ps',\n dataType : 'json',\n data : {\n q: name\n },\n success : function(data){\n $(\"#movie_name_results\").html('');\n if($(\"#movie_name\").val().length <=2){\n $(\"#movie_name_results\").stop().animate({opacity: '0.0'},300); \n requesting = false;\n return;\n }\n $(\"#movie_name_results\").css({'display':'block'});\n $(\"#movie_name_results\").stop().animate({opacity: '1.0'},400);\n \n // Iterate through each result and append to list. Maintain information\n // on movie name, if, and year.\n for(var i = 0; i < data.length; i++){\n var item = \"\";\n item = '<li id=\"'+data[i]['id']+'\" rel=\"'+data[i]['title']+'\">'+data[i]['title']\n if(data[i]['year'] != \"-1\"){\n item = item + ' ('+data[i]['year']+')'\n }\n item = item + '</li>';\n $(\"#movie_name_results\").append(item);\n if(i > 200){i = data.length;}\n loadListeners();\n }\n requesting = false;\n },\n error : function(XMLHttpRequest, textStatus, errorThrown){\n requesting = false;\n }\n });\n\n}",
"function loadMovies() {\n\n $.ajax({\n url: config.moviesFile,\n cache: false,\n success: function (data) {\n var movieList = data.split(/[\\r\\n]+/g);\n printList(movieList);\n printCount(movieList.length);\n },\n dataType: 'text'\n });\n }",
"function discoverMovies(callback) {\n $.ajax({\n url: api.root + \"/discover/movie\",\n data: {\n api_key: api.token\n },\n success: function(response) {\n model.browseItems = response.results;\n callback(response);\n //console.log(response);\n }\n });\n}",
"function vGetMovies(eltSelect) {\n // Get Movie ID from the select element\n var strMovieID = eltSelect.value;\n // construct query string to pass the author ID to the server\n var strQueryString = \"function=GetMovies&movieID=\" + strMovieID;\n var strQueryStringCast = \"function=GetCast&movieID=\" + strMovieID;\n var strQueryStringDirect = \"function=GetDirector&movieID=\" + strMovieID;\n var strQueryStringProduce = \"function=GetProducer&movieID=\" + strMovieID;\n var strQueryLocation = \"function=GetLocation&movieID=\" + strMovieID;\n // set up ajax and send request\n var strURL = \"Ajax.php\";\n vDoAjax(strURL, strQueryString, vDisplayMovieInfo);\n vDoAjax(strURL, strQueryStringCast, vDisplayCast);\n vDoAjax(strURL, strQueryStringDirect, vDisplayDirect);\n vDoAjax(strURL, strQueryStringProduce, vDisplayProducer);\n vDoAjax(strURL, strQueryLocation, vDisplayLocation);\n}",
"function movieBtnClick(id) {\n $.get(\"http://localhost:59180/api/Reviewer/\" + id),\n function (resp) {\n console.log(resp);\n allPeople(resp);\n }\n }",
"function getVideoList() {\n // AJAX calling to DB to get videos\n request('GET', '/index', null).done(function(response) {\n console.log(response);\n // Getting each video and appeding them to index\n $.each(response, function(index, video) {\n appendTube(video);\n })\n })\n}",
"function MoviesAdvancedSearch() {\n var title = $(\"#Title\").val();\n var actors = $(\"#Actors\").val();\n var year = $(\"#Year\").val();\n ToAjax('AdvancedSearch', 'Movies', MovieListToHtml, { \"Title\": title, \"Actors\": actors, \"YearRelease\": year });\n}",
"function discoverMovies(callback) {\n $.ajax({\n url: api.root + \"/discover/movie\",\n data: {\n api_key: api.token\n },\n success: function(response) {\n model.browseItems = response.results;\n callback(response);\n }\n });\n}",
"function movieSearch() {\n\t\n\t//Clears results container\n\t$(\"#results\").empty();\n\t\n\t//Hides initial warnings and buttons\n\t$(\"#showAll\").hide();\n\t$(\"#notfound\").hide();\n\t\n\t//Ajax loader is showed\n\t$(\"#loader\").show();\n\t\n\t//Stores user query\n\tvar query = $(\"input:first\").val();\n\t\n\t//API query is sent, response size is limited to 10 elements by 'page_limit' property.\n\t//searchCallback function manages the JSON response object.\n\t$.ajax({\n\t url: moviesSearchUrl + '&q=' + encodeURI(query) + '&page_limit=10',\n\t dataType: \"jsonp\",\n\t success: searchCallback\n\t});\n\t\n}",
"function getMovies() {\n var queryURL = \"https://api.nytimes.com/svc/movies/v2/reviews/search.json?critics-pick=Y&opening-date=2019-01-01;2020-09-01&api-key=xUVU76OUVbXKD94Ig4mUUmlvQJGAyTSQ\";\n\n $.ajax({\n url: queryURL,\n method: \"GET\"\n }).then(function (response) {\n let results = response.results;\n for (let i = 0; i < results.length; i++) {\n let newMovie = {\n title: results[i].display_title,\n description: results[i].summary_short,\n url: results[i].link.url,\n headline: results[i].headline,\n byline: results[i].byline,\n image_url: results[i].multimedia.src\n };\n moviesArray.push(newMovie);\n }\n console.log(\"Movies:\", moviesArray);\n });\n }",
"function discoverMovies(data, callback) {\n // DONE \n $.ajax({\n url: api.root + \"/discover/movie\",\n data: data,\n success: function(response) {\n model.browseItems = response.results;\n callback(response);\n },\n fail: function() {\n console.log(\"discover failed\");\n }\n });\n}",
"function addMovieTv(name, category){\r\n //analizzo se è un film o una serie tv e cambio le variabili\r\n if (category == \"movie\") {\r\n var url = \"https://api.themoviedb.org/3/search/movie\";\r\n }\r\n\r\n else {\r\n var url = \"https://api.themoviedb.org/3/search/tv\";\r\n }\r\n\r\n //chiamata AJAX\r\n $.ajax(\r\n {\r\n url: url,\r\n method: \"GET\",\r\n data: {\r\n api_key: \"65ed57e84173ef501a3f48cc27087d06\",\r\n language: \"it-IT\",\r\n query: name,\r\n },\r\n success: function (data) {\r\n var results = data.results;\r\n\r\n //avvio funzione print ad ogni risultato della chiamata ajax\r\n for (var i = 0; i < results.length; i++){\r\n // var genre = printGenre(category, results[i].genre_ids);\r\n\r\n printData(\r\n results[i].poster_path,\r\n results[i].title || results[i].name, //FILM: \"title\" - SERIE TV: \"name\"\r\n results[i].original_title || results[i].original_name, //FILM: \"original_title\" - SERIE TV: \"original_name\"\r\n results[i].original_language,\r\n results[i].vote_average,\r\n results[i].overview,\r\n );\r\n }\r\n\r\n //stampo il numero di film/serie della ricerca\r\n if (category == \"movie\"){\r\n $(\"#movie-number\").text(results.length);\r\n }\r\n\r\n else {\r\n $(\"#tv-number\").text(results.length)\r\n }\r\n },\r\n error: function () {\r\n alert(\"E' avvenuto un errore. \");\r\n }\r\n }\r\n );\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getting element to numbeer | function gettingElementToNum(elementId){
var element=document.getElementById(elementId).innerText;
elementNum=parseFloat(element);
return elementNum;
} | [
"function getImageNumber(element) {\n\t\tvar number = null;\n\t\tif (!imageNumberMap.has(element)) {\n\t\t\tvar numberElement = element.querySelector('.image-number')\n\t\t\tif (numberElement && numberElement.dataset.number) {\n\t\t\t\tnumber = parseInt(numberElement.dataset.number, 10);\n\t\t\t}\n\t\t} else {\n\t\t\tnumber = imageNumberMap.get(element);\n\t\t}\n\t\treturn number;\n\t}",
"function getNum(selector)\n{\n\treturn parseInt(getFloat(selector));\n}",
"getNum() {\n return this.num\n }",
"function getNumber(num){\n const number = document.getElementById(\"num\"+num);\n const parsed = parseInt(number.innerText);\n return parsed\n}",
"function incEltNbr(id){\n elt = document.getElementById(id);\n endNbr = Number(document.getElementById(id).innerHTML);\n incNbrRec(0,endNbr,elt);\n}",
"function get_num_id(element){\n return parseInt( element.prop(\"id\").match(/\\d+/g) );\n}",
"function numberClicked(event) {\n\tvar type = event.target.innerHTML; // the clicked element\n\tconsole.log(type);\n\tappendNumToHead(type);\n}",
"function resultNum() {\n\tvar _len = $('.list').find('.piece').find('i').length,\n\t\t_footNum = $('.result').find('.piece').find('i'),\n\t\t_i = 0,\n\t\t_resultNum = 0\n\tfor(; _i < _len; _i++) {\n\t\tvar _txt = $('.list').find('.piece').eq(_i).find('i').text()\t\n\t\t_resultNum += +(_txt)\t\n\t}\n\t_footNum.text(_resultNum)\n}",
"function getNumTotalItemEl() {\n\tvar numTotalItemEl;\n\n\t// Get the hidden numTotalItems textbox to update it\n\t// prefix added by jsf when rendering\n\treturn getEl('gbForm:numTotalItems');\n}",
"function getNums (identifier) {\n myList = document.getElementsByClassName(identifier);\n myNumArray = Array();\n for (var i = 0; i < myList.length; i++) {\n myNumArray[i] = Number(myList[i].innerHTML);\n }\n return myNumArray;\n}",
"counterList() {\n Array.from(costsBox.children).forEach((list, index) => {\n list.querySelector('#number').innerHTML = index + 1;\n });\n }",
"function NumTools() {}",
"function getCounter(element) {\n return element.parentNode.getElementsByClassName(\"counter\")[0];\n}",
"function getDisplay(btn) {\n var number = \"\";\n var children = btn.getElementsByTagName(\"span\");\n for (var i=0; i < children.length; i++) {\n number += children[i].innerHTML;\n }\n return parseInt(number);\n}",
"get element() {\n return this.isPercussion ? PercussionMapper.getElementAndVariation(this)[0] : -1;\n }",
"visitNumber(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"toNumber() {\r\n let returnValue = 0;\r\n for (let i = this._trits.length - 1; i >= 0; i--) {\r\n returnValue = returnValue * 3 + this._trits[i];\r\n }\r\n return returnValue;\r\n }",
"function getTileNumber (tile) {\n\t\treturn String($(tile).find(\".tile_number\").data(\"number\"))\n\t}",
"function getPostNumberElement(post) {\r\n\tvar list = getElementsByClassName('reflink', 'span', post);\r\n\tif(list.length > 0) return list[0];\r\n\telse return null;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Construct a tonelist, then invoke the callback | function MakeToneList( a_tone_list_name, a_completion_function )
{
g_toneList = new ToneList();
g_toneList.init( a_tone_list_name, a_completion_function );
} | [
"function playTone(btn,len){ \n o.frequency.value = freqMap[btn]\n g.gain.setTargetAtTime(volume,context.currentTime + 0.05,0.025)\n tonePlaying = true\n setTimeout(function(){\n stopTone()\n },len)\n}",
"function createTone(){\n // create FFT\n fft = new Tone.FFT(fft_dim);\n\n // set main Buffer callback function\n Tone.Buffer.on('load', loadPlayButton);\n\n // button\n play_button = document.createElement(\"INPUT\");\n play_button.setAttribute(\"type\", \"button\");\n play_button.value = \"Play\";\n play_button.disabled = true;\n // document.querySelector(\"#controls\").appendChild(play_button);\n\n // player\n player = new Tone.Player({\n \t'url':'../media/hellfire.mp3'\n });\n player.fan(fft).toMaster();\n player.autostart = false;\n}",
"function startTone( i ) {\n if ( oscList[ i ] !== null ) {\n return;\n }\n\n oscList[ i ] = audioContext.createOscillator();\n lpfList[ i ] = audioContext.createBiquadFilter();\n gainList[ i ] = audioContext.createGain();\n\n oscList[ i ].connect( lpfList[ i ] );\n lpfList[ i ].connect( gainList[ i ] );\n gainList[ i ].connect( compressor );\n\n oscList[ i ].type = 'square';\n oscList[ i ].frequency.value = freqList[ i ];\n\n lpfList[ i ].type = 'highshelf';\n lpfList[ i ].frequency.setValueAtTime( 1000, audioContext.currentTime );\n lpfList[ i ].gain.setValueAtTime( -10, audioContext.currentTime );\n lpfList[ i ].gain.linearRampToValueAtTime( -10, audioContext.currentTime + 0.15 );\n lpfList[ i ].gain.linearRampToValueAtTime( -30, audioContext.currentTime + 0.4 );\n\n gainList[ i ].gain.setValueAtTime( 0, audioContext.currentTime );\n gainList[ i ].gain.linearRampToValueAtTime( 0.4, audioContext.currentTime + 0.15 );\n gainList[ i ].gain.linearRampToValueAtTime( 0.3, audioContext.currentTime + 0.4 );\n\n oscList[ i ].start();\n}",
"function completedBeep()\n{\nconsole.log(completedTone);\ncompletedTone.play();\n// completedTone.onplay=function(){\n// console.log('tone is playing'); // these commented commands check whether the audio is working or not\n// }\n}",
"makeSynthSeq(tone, notesArr) {\n let pattern = new Tone.Sequence( (time, note) => {\n this.tone.triggerAttackRelease(note, \"4n\", time)\n }, notesArr, \"4n\").start()\n\n pattern.loop = false\n}",
"static fromArray(array) {\n return new ToneAudioBuffer().fromArray(array);\n }",
"function startTone(btn){\n if(!tonePlaying){\n o.frequency.value = freqMap[btn]\n g.gain.setTargetAtTime(volume,context.currentTime + 0.05,0.025)\n tonePlaying = true\n }\n}",
"function tone(freq, duration, sampleRate) {\n duration = sampleRate * duration;\n\n var curve = [];\n for (var i=0; i < duration; i++) {\n curve.push(Math.sin((2 * Math.PI) * freq * (i / sampleRate)));\n }\n\n return curve;\n}",
"function startTone(btn){\n if(!tonePlaying){\n o.frequency.value = freqMap[btn];\n g.gain.setTargetAtTime(volume,context.currentTime + 0.05,0.025);\n tonePlaying = true;\n }\n}",
"initPitchCounting() {\n this.initListener();\n this.frequencyData = new Float32Array(\n this.analyser.frequencyBinCount);\n this.audioContext.resume();\n}",
"function AudioTrackList() { }",
"function playTone(btn, len) {\n o.frequency.value = freqMap[btn];\n g.gain.setTargetAtTime(volume, context.currentTime + 0.05, 0.025);\n tonePlaying = true;\n setTimeout(function() {\n stopTone();\n }, len);\n //document.getElementById(\"btn\"+btn).play();\n var myAudio = new Audio('btn'+btn.toString()+'.wav');\n myAudio.play();\n}",
"static fromArray(array) {\n return (new ToneAudioBuffer()).fromArray(array);\n }",
"function play_scramble(scramble_type) {\n //scramble_type : 1 (minor), 2 (major)\n\n \n //Create audio context if it hasn't been made already (some browsers will prevent the audio context from being created before user input)\n if(!aud_ctx) {\n init();\n }\n \n //Always use 783.99 Hz as the tonic (as in Chubb et al, 2013)\n let f_I = 783.99;\n \n //Generate stimulus based on task type\n var seq;\n var freqs;\n var scramble;\n\n //Create the tone scramble waveform / PCM data\n seq = gen_seq(scramble_type);\n freqs = seq_2_freqs(seq, f_I);\n scramble = freqs_2_wave(freqs);\n \n //Initialize the audio buffer for playback\n let frame_count = scramble.length;\n let arr_buf = aud_ctx.createBuffer(channels, frame_count, aud_ctx.sampleRate);\n\n //Fill the buffer with the tone scramble waveform\n for (let channel = 0; channel < channels; channel++) {\n //This gives us the actual array that contains the data\n let now_buffering = arr_buf.getChannelData(channel);\n for (let k = 0; k < frame_count; k++) {\n now_buffering[k] = scramble[k];\n }\n }\n\n //Get an AudioBufferSourceNode; this is the AudioNode to use when we want to play an AudioBuffer\n source = aud_ctx.createBufferSource();\n source.buffer = arr_buf; //Set the buffer in the AudioBufferSourceNode\n source.connect(aud_ctx.destination); //Connect the AudioBufferSourceNode to the destination so we can hear the sound\n source.start(); //Start the source playing\n\n //Print a message to the console when the sound is done playing\n /*source.onended = () => {\n console.log('Sound finished.');\n }*/\n \n //Playback initiated, return an object with all the scramble parameters\n var trial_obj = new Object();\n trial_obj.seq = seq;\n trial_obj.freqs = freqs;\n trial_obj.f_I = f_I;\n return trial_obj;\n}",
"function createSounds(arr){\n\tsounds.length=0; // clears old sounds \n\t$toneLoc = document.getElementsByClassName('tonekeys'); // can this really be this easy?\n\tarr.forEach(function (soundNum,index){\n\t\tsounds.push(masterSoundList[soundNum]); // have to make masterList first\n\t\t// have to figure out how to get the specific node number in the class 'tonekeys' and set it's background \n\t\t// to the dullColors[] unless it's the one selected.\t\t\n\t\tif (index === previous){\n\t\t\t$toneLoc[soundNum].style.backgroundColor = brightColors[index];\n\t\t} else {\n\t\t\t$toneLoc[soundNum].style.backgroundColor = dullColors[index];\n\t\t}\n\t})\n\n}",
"function PulsatingTone(buffer, minPause, maxPause, minVol, maxVol, minDur, maxDur, minDetune, maxDetune, pitchArray, startWithPause, completionCallback) {\n\t//alert(this);\n\tthis.buffer = buffer;\n\tthis.minPause = minPause;\n\tthis.maxPause = maxPause;\n\tthis.minVol = minVol;\n\tthis.maxVol = maxVol;\n\tthis.minDur = minDur;\n\tthis.maxDur = maxDur;\n\tthis.outputNode;\n\tthis.isPlaying = false;\n\tthis.minDetune = minDetune;\n\tthis.maxDetune = maxDetune;\n\tthis.pitchArray = pitchArray;\n\tthis.startWithPause = startWithPause;\n\tthis.completionCallback = completionCallback;\n\t\n\t\n\t\n\t\n\t//this.volCurve = [[0.0, 0.0], [0.5, 1.0], [1.0, 0.0]];\n\t//this.detuneCurve = [[0.0, 0.0], [0.4, 0.0], [0.5, 1.0], [0.6, 0.0], [1.0, 0.0]];\n\t//minStages, maxStages, minValue, maxValue\n\tthis.volCurve = generateRandomCurve(3, 7, 0., 1.);\n\t//console.log('volume curve: ' + this.volCurve);\n\tthis.volCurve[0] = [0.0, 0.0];\n\tthis.volCurve[this.volCurve.length-1] = [1.0, 0.0];\n\t//console.log('volume curve: ' + this.volCurve);\n\tthis.detuneCurve = generateRandomCurve(2, 6, 0., 1.);\n\t//console.log('detune curve: ' + this.detuneCurve);\n\tthis.durationCurve = generateRandomCurve(2, 4, 0., 1.);\n\tthis.pauseCurve = generateRandomCurve(2, 7, 0., 1.);\n\t\n\t\n\t\n\tthis.dur = Math.random() * (this.maxDur - this.minDur) + this.minDur;\n\tif (this.dur > this.buffer.duration) {\n\t\tthis.dur = this.buffer.duration;\n\t\tthis.startTime = 0;\n\t} else {\n\t\tthis.startTime = Math.random() * (this.buffer.duration - this.dur);\n\t}\n\t\n\t// private variables\n\tvar timerID;\n\t// Douglas Crockford told me to do this: http://www.crockford.com/javascript/private.html\n\t// It's a convention that allows private member functions to access the object\n\t// due to an error in the ECMAScript Language Specification\n\tvar that = this;\n\t\n\tvar startTimeInContext;\n\t\n\tfunction generateRandomCurve(minStages, maxStages, minValue, maxValue) {\n\t\tvar newCurve = [[0.0, Math.random() * (maxValue - minValue) + minValue], \n\t\t [1.0, Math.random() * (maxValue - minValue) + minValue]];\n\t\tvar numberOfStages = Math.floor(Math.random() * (1 + maxStages - minStages)) + minStages;\n\t\tfor (var i = 1; i < numberOfStages; i++) {\n\t\t\t//console.log('i ' + i + ' is less than numberOfStages ' + numberOfStages);\n\t\t\tvar newX = Math.random();\n\t\t\tvar newY = Math.random() * (maxValue - minValue) + minValue;\n\t\t\tnewCurve.push([newX, newY]);\n\t\t}\n\t\treturn newCurve.sort();\n\t}\n\t\n\tfunction playBuffer(bufferIndex, volume, pitch, startTime, dur) {\n\t\t//somewhere in here we should probably error check to make sure an outputNode with an audioContext is connected\n\t\tvar newNow = that.outputNode.context.currentTime + 0.1;\n\t\tvar audioBufferSource = that.outputNode.context.createBufferSource();\n\t\taudioBufferSource.buffer = bufferIndex;\n\t\taudioBufferSource.playbackRate.value = pitch;\n\t\taudioBufferGain = that.outputNode.context.createGain();\n\t\t//audioBufferGain.gain.value = volume;\n\t\t//audioBufferGain.gain.setValueAtTime(0., newNow);\n\t\t//audioBufferGain.gain.setValueAtTime(0., that.outputNode.context.currentTime);\n\t\taudioBufferSource.connect(audioBufferGain);\n\t\taudioBufferGain.connect(that.outputNode);\n\t\ttry {\n\t\t\t//audioBufferSource.start(newNow, that.startTime, that.dur);\n\t\t\t\n\t\t\t//alert(that.outputNode.context.currentTime);\n\t\t\t//audioBufferGain.gain.linearRampToValueAtTime(volume, newNow + 0.05);\n\t\t\t\n\t\t\taudioBufferGain.gain.linearRampToValueAtTime(0.0, newNow);\n\t\t\taudioBufferGain.gain.linearRampToValueAtTime(volume, newNow + 0.05);\n\t\t\taudioBufferGain.gain.linearRampToValueAtTime(volume, newNow + dur - 0.05);\n\t\t\taudioBufferGain.gain.linearRampToValueAtTime(0.0, newNow + dur);\n\t\t\t\n\t\t\taudioBufferSource.start(newNow, startTime, dur);\n\t\t} catch(e) {\n\t\t\talert(e);\n\t\t}\t\t\n\t}\n\t\n\t// making this a private member function\n\tfunction tickDownIntermittentSound() {\n\t\t//calculate how far we are into overall tone\n\t\tvar percentDone = (that.outputNode.context.currentTime - startTimeInContext) / that.duration;\n\t\t//console.log('this far through: ' + percentDone);\n\t\tvar interpolatedVolume = interpolate(percentDone, that.volCurve);\n\t\t//console.log('interpolated volume: ' + interpolatedVolume);\n\t\tvar volume = ((that.maxVol - that.minVol) * Math.random() + that.minVol) * interpolatedVolume;\n\t\tvar pitchIndex = Math.floor(Math.random() * that.pitchArray.length); \n\t\tvar pitch = pitchClassToMultiplier(that.pitchArray[pitchIndex][0], that.pitchArray[pitchIndex][1]);\n\t\tvar interpolatedDetune = interpolate(percentDone, that.detuneCurve);\n\t\tvar randomDetune = Math.random() * (that.maxDetune - that.minDetune) + that.minDetune; \n\t\tvar detuneAmount = (interpolatedDetune * (randomDetune - 1.0)) + 1.0;\n\t\tpitch *= detuneAmount;\n\t\tvar dur = Math.random() * interpolate(percentDone, that.durationCurve) * (that.maxDur - that.minDur) + that.minDur;\n\t\tvar startTime = Math.random() * (that.buffer.duration - dur * pitch);\n\t\tplayBuffer(that.buffer, volume, pitch, startTime, dur);\n\t\t//var bufferDur = that.buffer.duration;\n\t\t// not anymore, now I'm specifying this, right?\n\t\tvar bufferDur = dur;\n\t\t//console.log('startTimeInContext: ' + startTimeInContext + '; elapsed time: ' + that.outputNode.context.currentTime);\n\t\tif (that.outputNode.context.currentTime < (startTimeInContext + that.duration)) {\n\t\t\tvar pauseDur = (that.maxPause - that.minPause) * interpolate(percentDone, that.pauseCurve) + that.minPause;\n\t\t\t//console.log('pauseDur: ' + pauseDur);\n\t\t\ttimerID = window.setTimeout(tickDownIntermittentSound, (pauseDur + bufferDur/pitch) * 1000.);\n\t\t} else {\n\t\t\ttimerID = window.setTimeout(finishedPlaying, (bufferDur/pitch) * 1000.);\n\t\t}\n\t\tthat.numberOfReps--;\n\t}\n\t\n\tfunction finishedPlaying() {\n\t\t//alert(that);\n\t\tthat.isPlaying = false;\n\t\t//console.log(\"this is how we know an intermittent sound is done, right?\");\n\t\tif (that.completionCallback) {\n\t\t\tthat.completionCallback();\n\t\t}\n\t}\n\t\n\tfunction pitchClassToMultiplier(octave, interval) {\n\t\tvar multiplier = Math.pow(2., (12. * octave + interval) / 12.);\n\t\treturn multiplier;\n\t}\n\t\n\tfunction interpolate(value, curve) {\n\t\t//remember, expecting curve to be an array of breakpoints (i.e., two-element arrays)\n\t\t//we should clip it on the ends...\n\t\t//console.log('value: ' + value + '; curve: ' + curve + '; curve.length: ' + curve.length);\n\t\tvar interpolatedValue;\n\t\tif (value < curve[0][0]) {\n\t\t\tinterpolatedValue = curve[0][1];\n\t\t} else if (value > curve[curve.length - 1][0]) {\n\t\t\tinterpolatedValue = curve[curve.length - 1][1];\n\t\t} else {\n\t\t\tfor (var i = 0; i < curve.length; i++) {\n\t\t\t\tif (value < curve[i][0]) {\n\t\t\t\t\t//console.log('value ' + value + ' is less than curve[i][0] ' + curve[i][0]);\n\t\t\t\t\t//console.log('value - curve[i-1][0] is ' + (value - curve[i-1][0]));\n\t\t\t\t\t//console.log('curve[i][0] - curve[i-1][0] is ' + (curve[i][0] - curve[i-1][0]));\n\t\t\t\t\tvar percentageThroughStage = (value - curve[i-1][0]) / (curve[i][0] - curve[i-1][0]);\n\t\t\t\t\t//console.log('percentage through stage: ' + percentageThroughStage);\n\t\t\t\t\tinterpolatedValue = (percentageThroughStage * (curve[i][1] - curve[i-1][1])) + curve[i-1][1];\n\t\t\t\t\t//console.log('interpolated value: ' + interpolatedValue);\n\t\t\t\t\treturn interpolatedValue;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn interpolatedValue;\n\t}\n\t\n\tthis.play = function(duration) {\n\t\tstartTimeInContext = this.outputNode.context.currentTime;\n\t\tconsole.log('startTimeInContext: ' + startTimeInContext);\n\t\tthis.duration = duration;\n\t\tthis.isPlaying = true;\n\t\tthis.numberOfReps = Math.floor(((this.maxReps - this.minReps) + 1) * Math.random() + this.minReps);\n\t\tif (this.startWithPause) {\n\t\t\tvar pauseDur = (that.maxPause - that.minPause) * Math.random() + that.minPause;\n\t\t\ttimerID = window.setTimeout(tickDownIntermittentSound, pauseDur * 1000.);\n\t\t} else {\n\t\t\ttickDownIntermittentSound();\n\t\t}\n\t}\n\t\n\tthis.stop = function() {\n\t\tif (this.isPlaying) {\n\t\t\twindow.clearTimeout(timerID);\n\t\t\tthis.isPlaying = false;\n\t\t\tfinishedPlaying();\n\t\t}\n\t}\n\t\n\tthis.connect = function(nodeToConnectTo) {\n\t\ttry {\n\t\t\tif (nodeToConnectTo.destination) {\n\t\t\t\tthis.outputNode = nodeToConnectTo.destination;\n\t\t\t} else {\n\t\t\t\tthis.outputNode = nodeToConnectTo;\n\t\t\t}\n\t\t} catch(e) {\n\t\t\talert(\"It seems you have not specified a valid node.\");\n\t\t}\n\t}\n\t\n\tthis.estimateDuration = function() {\n\t\tvar midiPitchArray = [];\n\t\tfor (var i = 0; i < this.pitchArray.length; i++) {\n\t\t\tvar midiPitch = this.pitchArray[i][0] * 12;\n\t\t\tmidiPitch += this.pitchArray[i][1];\n\t\t\tmidiPitchArray.push(midiPitch);\n\t\t}\n\t\tvar averagePitch = 0;\n\t\tfor (var i = 0; i < midiPitchArray.length; i++) {\n\t\t\taveragePitch += midiPitchArray[i];\n\t\t}\n\t\taveragePitch = averagePitch / midiPitchArray.length;\n\t\taveragePitch = pitchClassToMultiplier(0, averagePitch);\n\t\tvar averageDur = ((this.minDur + this.maxDur) / 2.0) / averagePitch;\n\t\tvar averageReps = (this.minReps + this.maxReps) / 2.0; \n\t\tvar averagePause = (this.minPause + this.maxPause) / 2.0;\n\t\tvar estimate = averageDur * (averageReps + 1.0) + averagePause * averageReps;\n\t\tif (this.startWithPause) {\n\t\t\testimate += averagePause;\n\t\t}\n\t\treturn estimate;\n\t}\n}",
"function startTone( frequency )\r\n{\r\n var now = audioContext.currentTime;\r\n \r\n oscillator.frequency.setValueAtTime(frequency, now);\r\n \r\n // Ramp up the gain so we can hear the sound.\r\n // We can ramp smoothly to the desired value.\r\n // First we should cancel any previous scheduled events that might interfere.\r\n amp.gain.cancelScheduledValues(now);\r\n // Anchor beginning of ramp at current value.\r\n amp.gain.setValueAtTime(amp.gain.value, now);\r\n amp.gain.linearRampToValueAtTime(0.5, audioContext.currentTime + 0.1);\r\n\r\n /* function forCanvas(stream) {\r\n source = oscillator;\r\n }\r\n\r\n forCanvas();*/\r\n \r\n writeMessageToID( \"soundStatus\", \"<p>Play tone at frequency = \" + frequency + \"</p>\");\r\n}",
"function playRandomNote() {\r\n playSound(newFreq);\r\n}",
"function playAudio() { \n tone.play(); \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
LDAP login which will checks for all kind of external connector | function ldapLogin(req, next) {
return new Promise(function (resolve, reject) {
let username = cf.parseString(req.body.username);
let password = req.body.password;
let subdomains = req.subdomains;
subdomain = licenseService.getSubdomain(subdomains);
sqlQuery = `select tenant_directory.*, tenant.id as tenant_id, tenant.tenant_uid as tenant_uid, tenant.subdomain from tenant_directory, tenant where tenant_directory.tenant_uid=tenant.tenant_uid and tenant.subdomain = $1 and tenant_directory.directory_type = $2 and tenant_directory.status=1 `;
req.gamma.query(sqlQuery, [subdomain, 'external'])
.then(directories => {
if (directories.length) {
let directoryIndex = 1;
async.forEachSeries(directories, function (directory, callback) {
let url = `${directory.metadata.protocol}://${directory.metadata.hostname}:${directory.metadata.port}`;
// Filtering by users and groups prepend group and user DN to baseDN
let ldapBaseDn = directory.metadata.baseDn;
if (directory.metadata.groupDn !== '' && directory.metadata.userDn !== '') {
ldapBaseDn = `${directory.metadata.userDn},${directory.metadata.groupDn},${ldapBaseDn}`;
} else if (directory.metadata.groupDn !== '') {
ldapBaseDn = `${directory.metadata.groupDn},${ldapBaseDn}`;
} else if (directory.metadata.userDn !== '') {
ldapBaseDn = `${directory.metadata.userDn},${ldapBaseDn}`;
}
var options = {
url: url + '/' + new Date().getTime(),
bindDN: directory.metadata.readerUsername,
bindCredentials: cf.decryptStringWithAES(directory.metadata.readerPassword),
searchBase: ldapBaseDn,
tlsOptions: {
rejectUnauthorized: false,
ecdhCurve: 'secp384r1'
},
timeout: 10000,
connectTimeout: 10000,
searchFilter: `(&(objectClass=${directory.metadata.userSchema.ldapUserObjectclass})${directory.metadata.userSchema.ldapUserFilter}(mail={{username}}))`,
searchAttributes: ['cn', 'givenName', 'sn', 'uid', 'objectClass', 'creatorsname', 'createtimestamp', 'modifiersname', 'structuralObjectClass', 'entryUUID', 'modifytimestamp', 'mail', 'objectGUID', 'objectSid', 'subschemaSubentry', 'hasSubordinates', 'member', 'groupOfNames', '+']
};
var auth = new ldapAuth(options);
auth.once('error', function (err) {
auth.close();
if (parseInt(directoryIndex) >= directories.length) {
directoryIndex += 1;
log.error('LDAP connection reject error : ', JSON.stringify(err) + ' for conection details :' + JSON.stringify(_.omit(options, ['bindCredentials', 'searchAttributes', 'timeout', 'connectTimeout', 'tlsOptions'])), {
'tenantUid': directory.tenant_uid,
'userId': directory.id
});
reject(err);
} else {
directoryIndex += 1;
log.error('LDAP connection callback error : ', JSON.stringify(err) + ' for connection details :' + JSON.stringify(_.omit(options, ['bindCredentials', 'searchAttributes', 'timeout', 'connectTimeout', 'tlsOptions'])), {
'tenantUid': directory.tenant_uid,
'userId': directory.id
});
return callback();
}
});
// Register a LDAP client connection "connectTimeout" handler
// The ldap connection attempt has been timed out...
auth.once('connectTimeout', function (err) {
auth.close();
if (parseInt(directoryIndex) >= directories.length) {
directoryIndex += 1;
log.error('LDAP connection timeout reject error : ', JSON.stringify(err) + ' for connection details :' + JSON.stringify(_.omit(options, ['bindCredentials', 'searchAttributes', 'timeout', 'connectTimeout', 'tlsOptions'])), {
'tenantUid': directory.tenant_uid,
'userId': directory.id
});
reject(err);
} else {
directoryIndex += 1;
log.error('LDAP connection timeout callback error : ', JSON.stringify(err) + ' for connection details :' + JSON.stringify(_.omit(options, ['bindCredentials', 'searchAttributes', 'timeout', 'connectTimeout', 'tlsOptions'])));
return callback();
}
});
auth.authenticate(username, password, function (err, ldapUser) {
auth.close();
if (ldapUser) {
// get external user details if available
externalUserDetails(username, subdomain, next, directory.id)
.then(existingUser => {
let ldapFirstName = ldapUser[directory.metadata.userSchema.ldapUserFirstname]; //ldapUser.givenName;
let ldapLastName = ldapUser[directory.metadata.userSchema.ldapUserLastname]; //ldapUser.sn;
let ldapEmail = ldapUser.mail;
let ldapDirectoryId = directory.id;
let ldapExternalId = '';
if (ldapUser.hasOwnProperty('objectGUID')) {
ldapExternalId = formatGUID(ldapUser.objectGUID);
} else if (ldapUser.hasOwnProperty('entryUUID')) {
ldapExternalId = ldapUser.entryUUID;
}
// if already exist direct login
if (existingUser.length) {
if (existingUser[0].user_status === 1 || existingUser[0].user_status === '1') {
let updateUserObject = {
ldapFirstName: ldapFirstName,
ldapLastName: ldapLastName,
externalId: existingUser[0].external_id,
ldapEmail: ldapEmail
};
updateUserData(updateUserObject, next);
userLogin(subdomains, existingUser, next);
} else {
return next(new errors.Unauthorized("Inactive User", 1002));
}
} else {
// check user limit with license
licenseService.checkUserLimit(directory.tenant_uid, directory.tenant_id, next)
.then(() => {
// insert new record in users for new external user
insertExternalUserDetails(directory.tenant_id, username, ldapFirstName, ldapLastName, ldapDirectoryId, ldapExternalId, next)
.then(function () {
// get entered user details for login
externalUserDetails(username, subdomain, next)
.then(newUser => {
if (newUser.length) {
// login external user
userLogin(subdomains, newUser, next);
} else {
return next(null, false, new errors.Unauthorized(null, 1001));
}
});
});
})
.catch(licenseError => {
// return any licensing error like limit exceded
log.error(licenseError.message, {
'tenantUid': directory.tenant_uid,
'userId': directory.id
});
next(licenseError);
});
}
});
} else {
if (parseInt(directoryIndex) >= directories.length) {
directoryIndex += 1;
log.info('LDAP reject error : ', JSON.stringify(err) + ' for conection details :' + JSON.stringify(_.omit(options, ['bindCredentials', 'searchAttributes', 'timeout', 'connectTimeout', 'tlsOptions'])), {
'tenantUid': directory.tenant_uid,
'userId': directory.id
});
reject(err);
} else {
directoryIndex += 1;
log.info('LDAP callback error : ', JSON.stringify(err) + ' for conection details :' + JSON.stringify(_.omit(options, ['bindCredentials', 'searchAttributes', 'timeout', 'connectTimeout', 'tlsOptions'])), {
'tenantUid': directory.tenant_uid,
'userId': directory.id
});
return callback();
}
}
});
},
function (err) {
if (err) {
reject();
}
reject();
});
} else {
return next(null, false, new errors.Unauthorized(null, 1001));
}
});
});
} | [
"function ldaplogin(username, password, next) {\n ldapclient.bind('uid=' + username + \",ou=people,dc=EECS,dc=Berkeley,dc=EDU\", password, function(err, result) {\n next(err, result);\n ldapclient.unbind(next);\n });\n}",
"function auth(dn, password, callback)\n{\n client = ldap.createClient({url: 'ldap://reaper.up.ac.za:'});\n client.bind(dn, password, function (err){\n client.unbind();\n callback(err === null, err);\n });\n}",
"function setupLogin() {\n\tvar athena = window.database.getObject(\"user\", \"athena\");\n\tvar url = document.location.href;\n\t\n\tif (document.location.protocol == 'https:' && athena != null) {\n\t\turl = \"http://picker.mit.edu\";\n\t\t$('#httpsStatus').html('logged in as ' + athena +\n\t\t\t' • <a href=\"' + url + '\">LOGOUT</a>');\n\t} else {\n\t\turl = \"https://picker.mit.edu:444\";\n\t\t$('#httpsStatus').html('<a href=\"' + url + '\">LOGIN</a>');\n\t}\n\n setupCookiesAndMiniTimegrid();\n}",
"function handleEmbeddedLogin() {\n\n function onEmbeddedLoginSuccess(transport) { \t\n // Login returns userInfo.\n Object.extend(userInfo, transport.responseJSON); \n options.onSuccess(new WL.Response(transport, options.invocationContext)); \n }\n\n function onEmbeddedLoginFailure(transport) {\n options.onFailure(new WL.FailResponse(transport, options.invocationContext)); \n }\n \n new Ajax.WLRequest(REQ_PATH_LOGIN, {\n method : 'get',\n parameters: {realm: realm},\n onSuccess : onEmbeddedLoginSuccess,\n onFailure : onEmbeddedLoginFailure\n });\n }",
"authenticate_ldap(dn, pw) {\n return new Promise((resolve, reject) => {\n let _client = ldapjs.createClient({\n \"url\": this._ldap_uri\n });\n\n _client.bind(dn, pw, (error, response) => {\n if (error) {\n reject(error);\n }\n if (response) {\n console.log(response);\n }\n resolve();\n });\n });\n }",
"function authenticate(layer, credential, callback) {\n\tvar password = process.env[format('LDAP_LAYER_%s_PASSWORD', layer.toUpperCase())];\n\tif ( password && credential === password )\n\t\tcallback(null, password)\n\telse\n\t\tcallback(new ldap.InvalidCredentialsError(\"Invalid login for layer \" + layer));\n}",
"authenticateUser() {\n const { username, password } = this.getProperties([\n 'username',\n 'password'\n ]);\n\n get(this, 'session')\n .authenticate('authenticator:custom-ldap', username, password)\n .catch(({ responseText = 'Bad Credentials' }) =>\n setProperties(this, { errorMessage: responseText }));\n }",
"function unix_getlogin() { unix_ll(\"unix_getlogin\", arguments); }",
"function EnsureDataSourceLogin(connectionName)\n{\n\tvar connRec = new Object();\n\tconnRec = MMDB.getConnection(connectionName);\n\tvar bTest = MMDB.testConnection(connRec, false);\n\n\tif (!bTest && connRec)\n\t{\n\t\tvar bCancelled = false;\n\t\twhile (!bTest && !bCancelled)\n\t\t{\n\t\t\tvar username = connRec.username;\n\t\t\tvar password = connRec.password;\n\t\t\tvar retVal = dwscripts.callCommand(\"Connection_cf_login.htm\", new Array(connectionName, username,password));\n\t\t\tif (retVal && retVal.length)\n\t\t\t{\n\t\t\t\tconnRec.username = retVal[0];\n\t\t\t\tconnRec.password = retVal[1];\n\t\t\t\tMMDB.setConnection(connRec);\n\t\t\t\tbTest = MMDB.testConnection(connRec, false);\n\t\t\t}\n\t\t\telse\n\t\t\t\tbCancelled = true;\n\t\t}\n\t}\n\n\treturn bTest;\n}",
"function wrappedLogin(params, next) {\n\tparams.logger.debug('Signing in for auto discovery');\n\tvar requestOptions = _.defaults(params.options.login, {\n\t\tjar: request.jar()\n\t});\n\trequest(requestOptions, function loggedIn(err, response, body) {\n\t\tparams.options.handleResponse(err, body, function handleLoginResponse(err, result) {\n\t\t\tif (err) {\n\t\t\t\tparams.logger.error('Login failed. Please double check your credentials.');\n\t\t\t\tnext(err);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tparams.options.jar = requestOptions.jar;\n\t\t\t\tnext();\n\t\t\t}\n\t\t});\n\t});\n}",
"function loginTola() {\n let parms = readConfig()\n LoginPage.open(parms.baseurl)\n if (parms.auth === 'mcsso') {\n LoginPage.username = parms.username\n LoginPage.password = parms.password\n LoginPage.login.click()\n } else if (parms.auth === 'django') {\n LoginPage.dUsername = parms.username\n LoginPage.dPassword = parms.password\n LoginPage.dLogin.click()\n } else if (parms.auth === 'google') {\n // Might bypass the login screen if google auth previously used\n // by the current browser profile...\n LoginPage.googleplus.click()\n // ...but if not, we're also ready to login manually\n if (LoginPage.title != 'Dashboard | TolaActivity') {\n LoginPage.gUsername = parms.username + '@mercycorps.org'\n LoginPage.gPassword = parms.password\n }\n }\n}",
"function checklogin () {\n\t//TODO make a boolean checking if you have an active session on the server.\n}",
"function get_ldap_mysql (cb) {\n connection.query('select * from '+config.mysql.name+'.auth_sources', function(err, rows, fields) {\n if (err) throw err;\n cb (rows, fields);\n });\n}",
"function LoginAdapter() {\n }",
"function wisdmLogin(params,callback) {\n\t\n\t/*This is used temporarily for demo purposes*/\n\t/*if (Wisdm.queryParameter('login_as_magland')=='temporary') {\n\t\tWisdm.setCurrentUser({user:'magland',password:'temporary'},function(tmp2) {\n\t\t\tif (tmp2.success==\"true\") {\n\t\t\t\tvar ret0={success:true,user:'magland'};\n\t\t\t\tif (callback) callback(ret0);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tjAlert('Incorrect user name or password.');\n\t\t\t\tif (callback) callback({success:false});\n\t\t\t}\n\t\t});\n\t\treturn;\n\t}*/\n\t////////////////////////////////////////////\n\t\n\tvar user0=Wisdm.queryParameter('user','');\n\tvar user_domain0=Wisdm.queryParameter('user_domain','');\n\tvar pass0=Wisdm.queryParameter('password','');\n\tif (!('manual' in params)) params.manual=true;\n\tif (params.password) pass0=params.password;\n\tif (params.user) user0=params.user;\n\tif (params.user_domain) user0=params.user_domain;\n\t\n\tif ((user0!=='')&&(pass0!=='')) {\n\t\tWisdm.setCurrentUser({user:user0,user_domain:user_domain0,password:pass0},function(tmp2) {\n\t\t\tif (tmp2.success==\"true\") {\n\t\t\t\tWisdm.setCookie('wisdmLogin-user',user0);\n\t\t\t\tvar ret0={success:true,user:user0,user_domain:user_domain0};\n\t\t\t\tif (callback) callback(ret0);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tparams.password='';\n\t\t\t\twisdmLogin(params,callback);\n\t\t\t}\n\t\t});\n\t\treturn;\n\t}\n\t\n\tvar manual_login=function(mlparams) {\n\t\t//pass0=Wisdm.getCookie('wisdmLogin-pass');\n\t\tif (mlparams.selectuser) {\n\t\t\tWisdm.getAllUsers({},function(ret_users) {\n\t\t\t\tvar users0=ret_users.users||[];\n\t\t\t\tif (!users0) {\n\t\t\t\t\tmanual_login({});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tselect_user({users:users0},function(user1) {\n\t\t\t\t\tmanual_login({user:user1});\n\t\t\t\t});\t\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif ('user' in mlparams) user0=mlparams.user;\n\t\tif (user0==='') user0=Wisdm.getCookie('wisdmLogin-user');\n\t\tif (user0=='magland') pass0=pass0||localStorage.magland_password||'';\n\t\tjLogin(\"Please log in:\",user0,pass0,\"WISDM login\",function(tmp) {\n\t\t\tif (mlparams.user1) user0=mlparams.user1;\n\t\t\tif (tmp!==null) {\n\t\t\t\tWisdm.setCurrentUser({user:tmp[0],password:tmp[1]},function(tmp2) {\n\t\t\t\t\tif (tmp2.success==\"true\") {\n\t\t\t\t\t\t\n\t\t\t\t\t\tif ((tmp[0]==tmp[1])&&(tmp[0]!='demo')) { //user and password are the same\n\t\t\t\t\t\t\tfunction prompt_new_password(str) {\n\t\t\t\t\t\t\t\tjPassword((str||'')+'Please select a stronger password for '+tmp[0],'','Stronger password required',function(newpass1) {\n\t\t\t\t\t\t\t\t\tif (!newpass1) return;\n\t\t\t\t\t\t\t\t\tjPassword('Please confirm new password for '+tmp[0]+':','','Stronger password required',function(newpass2) {\n\t\t\t\t\t\t\t\t\t\tif (newpass2!=newpass1) {\n\t\t\t\t\t\t\t\t\t\t\tprompt_new_password('Passwords do not match.\\n ');\n\t\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\t\tWisdm.setUserPassword({user:tmp[0],password:newpass1,old_password:tmp[1]},function(tmp8) {\n\t\t\t\t\t\t\t\t\t\t\t\tif (tmp8.success=='true') {\n\t\t\t\t\t\t\t\t\t\t\t\t\tjAlert('Password successfully changed for '+tmp[0]);\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t//prompt_new_password();\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tWisdm.setCookie('wisdmLogin-user',tmp[0]);\n\t\t\t\t\t\t//Wisdm.setCookie('wisdmLogin-pass',tmp[1]);\n\t\t\t\t\t\tvar ret0={success:true,user:tmp[0]};\n\t\t\t\t\t\tif (callback) callback(ret0);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tjAlert('Incorrect user name or password. Please contact Jeremy if you forgot your login information.');\n\t\t\t\t\t\tif (callback) callback({success:false});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (callback) callback({success:false});\n\t\t\t}\n\t\t});\n\t}\n \n\t\n\tif (params.manual) manual_login(params);\n\telse {\n\t\tif (callback) callback({success:false});\n\t}\n\t\n}",
"initLogin() {\n this.send({\n id: 10000,\n magic: '0x1234',\n method: 'global.login',\n params: {\n clientType: '',\n ipAddr: '(null)',\n loginType: 'Direct',\n password: '',\n userName: this.dahua_username,\n },\n session: 0,\n });\n }",
"function checkLogin()\n{\n\treturn goThroughRequiredInputs(\"login\");\n}",
"function LocalLogin() {\n }",
"Open() {\n\t\t\t\t\t\tvar OPEN = this.Open.bind(this), KILL = this.Destroy.bind(this);\n\t\t\t\t\t\tthis.Client = LDAPjs.createClient(this.options);\n\t\t\t\t\t\t// -------------------------------------------------------------------\n\t\t\t\t\t\tnew ELOGR(this.Client, cfgLDAP.port, 'LDAP', {\n\t\t\t\t\t\t\tconnect: \t{ kind:'msg', msg:'initialized', clr:'magenta' \t\t\t\t},\n\t\t\t\t\t\t\tidle: \t\t{ kind:'msg', msg:'idle', \t\t func:KILL\t\t\t\t\t},\n\t\t\t\t\t\t\tclose: \t\t{ kind:'msg', msg:'unbinded', \t func:OPEN, \tclr:'grey' \t},\n\t\t\t\t\t\t\tdestroy: \t{ kind:'msg', msg:'destroyed', \t func:OPEN \t\t\t\t\t},\n\t\t\t\t\t\t\terror: \t\t{ kind:'err' },\n\t\t\t\t\t\t});\n\t\t\t\t\t\t// -------------------------------------------------------------------\n\t\t\t\t\t\tthis.Bind(cfgLDAP.admin, cfgLDAP.passwd, function (err) {\n\t\t\t\t\t\t\tvar proc = { true: 'Error', false: 'Server' },\n\t\t\t\t\t\t\t\targs = (!!err ? [err.message] : ['Binded', 'magenta']),\n\t\t\t\t\t\t\t\tlogr = [cfgLDAP.port, 'LDAP'].concat(args),\n\t\t\t\t\t\t\t\tfunc = proc[!!err]; LG[func].apply(this, logr);\n\t\t\t\t\t\t\t// console.log(LDAP)\n\t\t\t\t\t\t});\n\t\t\t\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wrapper around `QueryBuilder.getCost()`. This must exist because the cost returned `QueryBuilder.getCost()` and therein the Hedera Network doesn't work for any acocuntns that have been deleted. In that case we want the minimum cost to be ~25 Tinybar as this seems to succeed most of the time. | getCost(client) {
const _super = Object.create(null, {
getCost: { get: () => super.getCost }
});
return __awaiter(this, void 0, void 0, function* () {
// deleted accounts return a COST_ANSWER of zero which triggers `INSUFFICIENT_TX_FEE`
// if you set that as the query payment; 25 tinybar seems to be enough to get
// `ACCOUNT_DELETED` back instead.
const min = Hbar_1.Hbar.fromTinybar(25);
const cost = yield _super.getCost.call(this, client);
return cost.isGreaterThan(min) ? cost : min;
});
} | [
"getCost(client) {\n const _super = Object.create(null, {\n getCost: { get: () => super.getCost }\n });\n return __awaiter(this, void 0, void 0, function* () {\n // deleted tokens return a COST_ANSWER of zero which triggers `INSUFFICIENT_TX_FEE`\n // if you set that as the query payment; 25 tinybar seems to be enough to get\n // `TOKEN_DELETED` back instead.\n const min = Hbar_1.Hbar.fromTinybar(25);\n const cost = yield _super.getCost.call(this, client);\n return cost.isGreaterThan(min) ? cost : min;\n });\n }",
"getCost(client) {\n const _super = Object.create(null, {\n getCost: { get: () => super.getCost }\n });\n return __awaiter(this, void 0, void 0, function* () {\n // deleted contracts return a COST_ANSWER of zero which triggers `INSUFFICIENT_TX_FEE`\n // if you set that as the query payment; 25 tinybar seems to be the minimum to get\n // `CONTRACT_DELETED` back instead.\n const min = Hbar_1.Hbar.fromTinybar(25);\n const cost = yield _super.getCost.call(this, client);\n return cost.isGreaterThan(min) ? cost : min;\n });\n }",
"getRefreshCost() {\n // If we have a free refersh, just assume all the quest are completed\n const notComplete = this.freeRefresh() ? 0 : this.incompleteQuests().length;\n const cost = Math.floor((250000 * Math.LOG10E * Math.log(Math.pow(notComplete, 4) + 1)) / 1000) * 1000;\n return new Amount(Math.max(0, Math.min(1e6, cost)), GameConstants.Currency.money);\n }",
"get cost() {\n return objective(this)\n }",
"static goldQuestMin (level, tower, guildTreasure, runes) {\n return Math.min(10000000, 1 * (1 + _clamp(guildTreasure, 0, 200) / 100 + _clamp(tower, 0, 100) / 100) * this.goldBase(level) / 11) * (1 + _clamp(runes, 0, 50) / 100);\n }",
"function costPlusQuote() {\n if (distanceInMiles >= 100) {\n quote = (wageExpense + fuelExpense) * margins[3];\n return quote\n } else if (distanceInMiles >= 500) {\n quote = (wageExpense + fuelExpense) * margins[2];\n return quote\n } else if (distanceInMiles >= 1000) {\n quote = (wageExpense + fuelExpense) * margins[1];\n return quote\n } else {\n quote = (wageExpense + fuelExpense) * margins[0];\n return quote\n }\n }",
"function leastExpensive(items) {\n var current2 = groceries[0].cost;\n for(var i = 0; i < groceries.length; i++){\n if(groceries[i].cost < current2) {\n current2 = groceries[i].cost;\n }\n }\n return current2;\n}",
"get totalCost() {\n\t\treturn this.__totalCost;\n\t}",
"get totalCost () {\n\t\treturn this._totalCost;\n\t}",
"getFCost(){\n return this.gCost + this.hCost;\n }",
"static getCost (item) { return item }",
"computeEnergyCapacity(creepActor) {\n const creep = creepActor.object('creep');\n const deposit = (\n Game.spawns[this.params.depositId] ||\n Game.creeps[this.params.depositId] ||\n Game.getObjectById(this.params.depositId)\n );\n let storeSpace = 0;\n if (deposit.energyCapacity) {\n storeSpace = deposit.energyCapacity - deposit.energy;\n }\n else if (deposit.carryCapacity) {\n storeSpace = deposit.carryCapacity - _.sum(deposit.carry);\n }\n else if (deposit.storeCapacity) {\n storeSpace = deposit.storeCapacity - _.sum(deposit.store);\n }\n else {\n logger.warning('Unable to get store capacity from deposit: ' + deposit.id || deposit.name);\n }\n\n return Math.min(storeSpace, creep.carryCapacity);\n }",
"function mostExpensive(items) {\n var current = groceries[0].cost;\n for(var i = 0; i < groceries.length; i++){\n if(groceries[i].cost > current) {\n current = groceries[i].cost;\n }\n }\n return current;\n}",
"function getCost(calculationStats) {\n\t\treturn calculationStats;\n\t}",
"minimizeCost(){\n\t\tvar minCost = Infinity;\n\t\tvar ret = 0;\n\t\tfor(let node of this.notEvaluated){\n\t\t\tvar cost = this.goToCost[node] + level.costToGoal[node];\n\t\t\tif(cost <= minCost){\n\t\t\t\tminCost = cost;\n\t\t\t\tret = node;\n\t\t\t}\n\t\t}\n\t\treturn ret;\n\t}",
"FCost()\n {\n return (this.gCost + this.hCost);\n }",
"get mercenaryCost() {\n let cost = Math.round((1.24 ** this.workers) * 75) - 50;\n if (cost > 25000){\n cost = 25000;\n }\n if (this.m_use > 0){\n cost *= 1.1 ** this.m_use;\n }\n cost *= traitVal('brute', 0, '-');\n if (game.global.race['inflation']){\n cost *= 1 + (game.global.race.inflation / 500);\n }\n cost *= traitVal('high_pop', 1, '=');\n return Math.round(cost);\n }",
"setGCost(cost){\n this.gCost = cost;\n }",
"resourceBaseCost (index) {\n return this.force.resourceBaseCost(index)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new reminder If date is far enough in the future, schedules a notification | async createReminder(reminder, date, time, img, coordinates, notificationsStatus) {
const localNotification = {
title: "Hello", body: "You have scheduled a reminder for " + date, ios: { sound: true }, android: {
sound: true, //icon (optional) (string) — URL of icon to display in notification drawer.
//color (optional) (string) — color of the notification icon in notification drawer.
priority: "high", sticky: false, vibrate: true
}
};
let notificationID = null;
if (time - new Date().getTime() > 3600000 && notificationsStatus) {
const when = time - 3600000;
notificationID = await Notifications.scheduleLocalNotificationAsync(localNotification, { time: when }); //schedules a notification two hours before reminder
}
let bourne_identity = this.generateID();
let obj = {
id: bourne_identity,
reminder: reminder,
date: date,
dateMilliseconds: time,
locked: true,
img: img,
imgHint: false,
mapHint: false,
attempts: 0,
notification: notificationID,
location: coordinates
}
return await Storage.setReminder(obj);
} | [
"function createReminder() {\n\n var today = new Date();\n var alertDate = new Date();\n alertDate.setDate(today.getDate()+7);\n alertDate.setHours(12);\n alertDate.setMinutes(30);\n alertDate.setSeconds(0);\n alertDate = new Date(alertDate);\n\n $cordovaLocalNotification.schedule({\n id: 2,\n firstAt: alertDate,\n message: \"We haven't seen you in a while. Help make a daily siyum in Mishna/Tehillim!\",\n title: \"Siyum Daily Reminder\",\n badge: 1,\n autoCancel: false,\n sound: 'res://platform_default'\n });\n }",
"addReminder() {\n this.event.recurrence.push({});\n }",
"function addReminder(myDate, myDesc, myId, myNotes, myPeriod, myEnabled){\r\nvar reminderDate=myDate.split(\"-\");\r\nmyDate = reminderDate[0]+\"-\"+((reminderDate[1]*1)-1)+\"-\"+reminderDate[2];\r\nreminders.push(new Reminder(myDate,myDesc,myId, myNotes, myPeriod, myEnabled));\r\n}",
"function addReminder(eventId, minutesBefore){\r\n // Logger.log(\"addReminder start\");\r\n var event = CalendarApp.getCalendarById(CALENDAR_ID).getEventById(eventId);\r\n event.addPopupReminder(minutesBefore);\r\n // Logger.log(\"addReminder end\");\r\n}",
"function trigger_diary_entry_reminder() {\n if (!store.get('reminders')) return;\n create_diary_entry_window();\n setTimeout(trigger_diary_entry_reminder, 24 * 60 * 60 * 1000); //Run again in 24 hours.\n}",
"function sendBooikngAppointmentReminder(callback) {\n return cron.job(\"0 */15 * * * *\", callback);\n //return cron.job(\"* * 23 * * *\", callback);\n}",
"createReminder(reminder) {\n reminder.schedule = new Schedule(reminder);\n this.state.settings.reminders.push(reminder);\n this.handleRemindersUpdate();\n\n //save the settings\n ipcRenderer.send('save-data', this.state.settings);\n }",
"function ifReminderIsToday(reminderWasSet, reminderTime, reminderDate, reminderRecurrence, snoozedToTime) {\r\n return new Promise((resolve, reject) => {\r\n // Get today's date and determine time, day of the week (and if it's a weekend/weekday), date, month\r\n const today = new Date();\r\n today.setUTCHours(today.getHours() + 3);\r\n const todaysDateYear = today.getFullYear();\r\n const todaysDateMonth = today.getMonth() + 1; // 0-11 >> 1-12\r\n const todaysDateDate = today.getDate();\r\n const dayOfWeek = today.getDay(); // 0-6, Sun=0\r\n //const currentTime = today.getTime(); // ms - at first I wanted to display only those todays' reminders that were\r\n // in future, that is between currentTime and todayEnds, ms\r\n\r\n const todayBeganMS = today.setHours(0, 0, 0, 0);\r\n const todayEnds = todayBeganMS + 86400000 - 1; // ms in 1 day\r\n\r\n // Working with reminder's time data\r\n if (snoozedToTime) {\r\n reminderTime = snoozedToTime;\r\n }\r\n\r\n // Parse reminderTime and transform it into ms\r\n const reminderTimeHours = reminderTime.split(\":\")[0];\r\n const reminderTimeMinutes = reminderTime.split(\":\")[1];\r\n const reminderTimeMS = new Date().setHours(reminderTimeHours, reminderTimeMinutes, 0, 0);\r\n\r\n // To get day of the week and date reminder was set (for \"Weekly\" recurrence cases) we need _id field\r\n const reminderWasSetDay = reminderWasSet.getDay();\r\n const reminderWasSetDate = reminderWasSet.getDate();\r\n\r\n // Parse reminderDate to separate year, month and date\r\n let reminderDateYear = \"\";\r\n let reminderDateMonth = \"\";\r\n let reminderDateDay = \"\";\r\n if (reminderDate) {\r\n reminderDateYear = reminderDate.split(\"-\")[0];\r\n reminderDateMonth = reminderDate.split(\"-\")[1];\r\n reminderDateDay = reminderDate.split(\"-\")[2];\r\n }\r\n\r\n // Main check-tree\r\n // If it's a one-time reminder, check yyyy-mm-dd and then hh:mm\r\n if (!reminderRecurrence) {\r\n if (reminderDateYear == todaysDateYear &&\r\n reminderDateMonth == todaysDateMonth &&\r\n reminderDateDay == todaysDateDate) {\r\n console.log(\"It's today! (ifReminderIsToday)\");\r\n resolve(reminderTimeMS > todayBeganMS && reminderTimeMS < todayEnds);\r\n } else {\r\n console.log(\"It's NOT today! (ifReminderIsToday)\");\r\n resolve(false);\r\n }\r\n\r\n // If it's a recurrent reminder\r\n } else {\r\n switch (reminderRecurrence) {\r\n // Daily - check if reminder's time hasn't passed today\r\n case \"Daily\":\r\n if (reminderTimeMS > todayBeganMS && reminderTimeMS < todayEnds) {\r\n console.log(\"It's today! (ifReminderIsToday)\");\r\n resolve(true);\r\n };\r\n\r\n // Weekly - check if the day reminder was set === today's day and then check the time\r\n case \"Weekly\":\r\n if (reminderWasSetDay === dayOfWeek) {\r\n resolve(reminderTimeMS > todayBeganMS && reminderTimeMS < todayEnds);\r\n } else {\r\n resolve(false);\r\n }\r\n\r\n // Monthly - check if the date reminder was set === today's day and then check the time\r\n case \"Monthly\":\r\n if (reminderWasSetDate === todaysDateDate) {\r\n resolve(reminderTimeMS > todayBeganMS && reminderTimeMS < todayEnds);\r\n } else {\r\n resolve(false);\r\n }\r\n\r\n // Weekends - check if today is a weekend and then check the time\r\n case \"Weekends\":\r\n if (dayOfWeek === 6 || dayOfWeek === 0) {\r\n resolve(reminderTimeMS > todayBeganMS && reminderTimeMS < todayEnds);\r\n } else {\r\n resolve(false);\r\n }\r\n\r\n // Weekdays - check if today is a week day and then check the time\r\n case \"Weekdays\":\r\n if (dayOfWeek > 0 && dayOfWeek < 6) {\r\n resolve(reminderTimeMS > todayBeganMS && reminderTimeMS < todayEnds);\r\n } else {\r\n resolve(false);\r\n }\r\n\r\n // \"Mondays\"\r\n case \"Mondays\":\r\n if (dayOfWeek === 1) {\r\n resolve(reminderTimeMS > todayBeganMS && reminderTimeMS < todayEnds);\r\n } else {\r\n resolve(false);\r\n }\r\n\r\n // \"Tuesdays\"\r\n case \"Tuesdays\":\r\n if (dayOfWeek === 2) {\r\n resolve(reminderTimeMS > todayBeganMS && reminderTimeMS < todayEnds);\r\n } else {\r\n resolve(false);\r\n }\r\n\r\n // \"Wednesdays\"\r\n case \"Wednesdays\":\r\n if (dayOfWeek === 3) {\r\n resolve(reminderTimeMS > todayBeganMS && reminderTimeMS < todayEnds);\r\n } else {\r\n resolve(false);\r\n }\r\n\r\n // \"Thursdays\"\r\n case \"Thursdays\":\r\n if (dayOfWeek === 4) {\r\n resolve(reminderTimeMS > todayBeganMS && reminderTimeMS < todayEnds);\r\n } else {\r\n resolve(false);\r\n }\r\n\r\n // \"Fridays\"\r\n case \"Fridays\":\r\n if (dayOfWeek === 5) {\r\n resolve(reminderTimeMS > todayBeganMS && reminderTimeMS < todayEnds);\r\n } else {\r\n resolve(false);\r\n }\r\n\r\n // \"Saturdays\"\r\n case \"Saturdays\":\r\n if (dayOfWeek === 6) {\r\n resolve(reminderTimeMS > todayBeganMS && reminderTimeMS < todayEnds);\r\n } else {\r\n resolve(false);\r\n }\r\n\r\n // \"Sundays\"\r\n case \"Sundays\":\r\n if (dayOfWeek === 0) {\r\n resolve(reminderTimeMS > todayBeganMS && reminderTimeMS < todayEnds);\r\n } else {\r\n resolve(false);\r\n }\r\n\r\n // \"Mondays, Tuesdays\"\r\n case \"Mondays, Tuesdays\":\r\n if (dayOfWeek === 1 || dayOfWeek === 2) {\r\n resolve(reminderTimeMS > todayBeganMS && reminderTimeMS < todayEnds);\r\n } else {\r\n resolve(false);\r\n }\r\n\r\n // \"Mondays, Wednesdays\"\r\n case \"Mondays, Wednesdays\":\r\n if (dayOfWeek === 1 || dayOfWeek === 3) {\r\n resolve(reminderTimeMS > todayBeganMS && reminderTimeMS < todayEnds);\r\n } else {\r\n resolve(false);\r\n }\r\n\r\n // \"Mondays, Fridays\"\r\n case \"Mondays, Fridays\":\r\n if (dayOfWeek === 1 || dayOfWeek === 5) {\r\n resolve(reminderTimeMS > todayBeganMS && reminderTimeMS < todayEnds);\r\n } else {\r\n resolve(false);\r\n }\r\n\r\n // \"Tuesdays, Thursdays\"\r\n case \"Mondays, Thursdays\":\r\n if (dayOfWeek === 2 || dayOfWeek === 4) {\r\n resolve(reminderTimeMS > todayBeganMS && reminderTimeMS < todayEnds);\r\n } else {\r\n resolve(false);\r\n }\r\n\r\n // \"Wednesdays, Fridays\"\r\n case \"Wednesdays, Fridays\":\r\n if (dayOfWeek === 3 || dayOfWeek === 5) {\r\n resolve(reminderTimeMS > todayBeganMS && reminderTimeMS < todayEnds);\r\n } else {\r\n resolve(false);\r\n }\r\n\r\n // \"Mondays, Tuesdays, Wednesdays\"\r\n case \"Mondays, Tuesdays, Wednesdays\":\r\n if (dayOfWeek === 1 || dayOfWeek === 2 || dayOfWeek === 3) {\r\n resolve(reminderTimeMS > todayBeganMS && reminderTimeMS < todayEnds);\r\n } else {\r\n resolve(false);\r\n }\r\n\r\n // \"Mondays, Tuesdays, Wednesdays, Thursdays\"\r\n case \"Mondays, Tuesdays, Wednesdays, Thursdays\":\r\n if (dayOfWeek === 1 || dayOfWeek === 2 || dayOfWeek === 3 || dayOfWeek === 4) {\r\n resolve(reminderTimeMS > todayBeganMS && reminderTimeMS < todayEnds);\r\n } else {\r\n resolve(false);\r\n }\r\n\r\n // \"Mondays, Wednesdays, Fridays\"\r\n case \"Mondays, Wednesdays, Fridays\":\r\n if (dayOfWeek === 1 || dayOfWeek === 3 || dayOfWeek === 5) {\r\n resolve(reminderTimeMS > todayBeganMS && reminderTimeMS < todayEnds);\r\n } else {\r\n resolve(false);\r\n }\r\n }\r\n }\r\n });\r\n}",
"function setupDailyReminderPing() {\n const pingRule = new schedule.RecurrenceRule();\n pingRule.dayOfWeek = [0, new schedule.Range(1, 6)];\n pingRule.hour = 10;\n pingRule.minute = 0;\n\n schedule.scheduleJob(pingRule, function() {\n helpers.publishMessage(\n 'Have you added your daily goals for today? ' +\n 'If not, use /addgoal to do it!');\n });\n}",
"function startReminder(Discord, client, message) {\n\n console.log(\"Starting due date reminder.\")\n const command = client.commands.get('dueReminder');\n\n if (command) {\n command.execute(client, message, \"\", Discord);\n console.log(\"Due date reminder is scheduled.\")\n }\n}",
"static add(reminder){\n\t\tlet kparams = {};\n\t\tkparams.reminder = reminder;\n\t\treturn new kaltura.RequestBuilder('reminder', 'add', kparams);\n\t}",
"function eventReminder(){\n\n //create variable that stores tomorrow's date for comparison against upcoming events\n var upcomingCheck = new Date();\n upcomingCheck = moment(upcomingCheck).add(1, 'days');\n upcomingCheck = (moment(upcomingCheck).format(\"DD-MM-YYYY\"));\n\n emailParams.user_name = userPreferences.userName;\n emailParams.user_email = userPreferences.userEmail;\n\n for(i=0; i<events.length;i++){\n if(events[i].eventDay === upcomingCheck && events[i].reminderSent === false){\n emailParams.upcoming_event = events[i].event;\n emailParams.message = \"You've got an event tomorrow: \";\n\n sendEmail(emailParams, templateUpcomingEvent);\n //flag event as having the reminder sent to prevent duplicate emails\n events[i].reminderSent = true;\n localStorage.setItem(\"events\", JSON.stringify(events));\n }\n }\n}",
"function addReminder( id, reminder) {\n gapi.client.load('calendar', 'v3', function() { \n var request = gapi.client.calendar.events.patch({\n 'calendarId': 'primary',\n 'eventId': id,\n\t 'resource': reminder\n });\n request.execute(function(resp) {\n console.log(resp);\n\t if (resp.id){\n\t \t console.log(\"Reminder was successfully added to: \" + resp.summary);\n\t }\n\t else{\n\t \tconsole.log(\"Reminder fail. An error occurred with: \" + resp.summary)\n\t }\n \n });\n });\n }",
"function setReminder(event_id){\n console.log(\"Reminder set for event: \", event_id)\n test_event_reminders.push({event_id: event_id})\n}",
"async function sendReminder(package) {\n const msPerDay = 86400000;\n const days = 3;\n\n let now = new Date().getTime();\n let then = new Date(package.creationDate).getTime();\n let creationDelta = now - then;\n \n if(creationDelta >= msPerDay*days) {\n let store = await storeIdToStore(package.storeId);\n console.log(`Sending reminder to: ` + package.customerEmail + ` (${Math.floor(creationDelta / msPerDay)} days has passed)`);\n await sendEmail(package.customerEmail, package.customerName, \"Reminder: no time slot booked\", `Hello ${package.customerName},\n you have not yet chosen a time slot for your package from ${store.name} with the id: ${package.id}.\n You can use the following link to choose a time slot: ${config.base_host_address}/package?guid=${package.guid}`, await reminderHTML(package));\n /* Increment package.remindersSent in database */\n await dbRun(db, \"UPDATE package SET remindersSent=1 WHERE id=?\", [package.id]);\n } else {\n return;\n }\n}",
"schedule () {\n\t\t// stagger each worker's schedule to occur at a random time every hour\n\t\tconst randomMinutes = Math.floor(Math.random() * 60);\n\t\tconst randomSeconds = Math.floor(Math.random() * 60);\n\t\tthis.api.log(`Triggering review reminders for execution at :${randomMinutes}m:${randomSeconds}s for every hour`);\n\t\tthis.job = Scheduler.scheduleJob(`${randomSeconds} ${randomMinutes} * * * 1-5`, this.remind.bind(this));\n\t}",
"function createReminder(id, idreminder, type, name, description, date, active) {\n // type = 1 => onetime reminder\n // type = 0 => repeating reminder\n\n const reminder = document.createElement(\"li\");\n reminder.setAttribute(\"class\", \"w3-bar\");\n\n const editIcon = document.createElement(\"i\");\n editIcon.setAttribute(\n \"class\",\n \"fa fa-edit w3-bar-item w3-button w3-xlarge w3-right\"\n );\n editIcon.style.backgroundColor = \"#ebebeb\";\n editIcon.addEventListener(\"click\", function () {\n let dateToEdit = type ? date : \"\";\n openReminderModal(idreminder, name, description, dateToEdit);\n });\n reminder.appendChild(editIcon);\n\n const img = document.createElement(\"img\");\n img.setAttribute(\"class\", \"w3-bar-item w3-circle w3-hide-small\");\n img.style.width = \"85px\";\n if (type) {\n //onetime reminder\n img.setAttribute(\"src\", \"../clock.png\");\n } else {\n //repeating reminder\n img.setAttribute(\"src\", \"../repeat.png\");\n }\n reminder.appendChild(img);\n\n const textDiv = document.createElement(\"div\");\n textDiv.setAttribute(\"class\", \"text w3-bar-item\");\n\n const titleSpan = document.createElement(\"span\");\n titleSpan.setAttribute(\"class\", \"name w3-large\");\n titleSpan.textContent = name;\n textDiv.appendChild(titleSpan);\n\n const br = document.createElement(\"br\");\n textDiv.appendChild(br);\n\n const descriptionSpan = document.createElement(\"span\");\n descriptionSpan.setAttribute(\"class\", \"description\");\n descriptionSpan.textContent = description;\n textDiv.appendChild(descriptionSpan);\n\n reminder.appendChild(textDiv);\n\n const dateSpan = document.createElement(\"span\");\n dateSpan.setAttribute(\"class\", \"time w3-bar-item w3-right w3-large\");\n if (type) {\n // one time\n dateSpan.classList.add(\"onetime\");\n dateSpan.setAttribute(\"data-date\", new Date(date));\n } else {\n // repeating\n dateSpan.classList.add(\"repeating\");\n dateSpan.dataset.timestamps = date;\n }\n reminder.appendChild(dateSpan);\n\n // repeating\n if (!type) {\n const slider = document.createElement(\"label\");\n slider.setAttribute(\"class\", \"switch\");\n\n const sliderInput = document.createElement(\"input\");\n sliderInput.setAttribute(\"type\", \"checkbox\");\n if (active) {\n sliderInput.setAttribute(\"checked\", \"checked\");\n } else {\n dateSpan.classList.remove(\"repeating\");\n dateSpan.textContent = \"\";\n }\n slider.appendChild(sliderInput);\n\n const sliderSpan = document.createElement(\"span\");\n sliderSpan.setAttribute(\"class\", \"slider round\");\n slider.appendChild(sliderSpan);\n\n reminder.appendChild(slider);\n\n sliderInput.addEventListener(\"click\", function () {\n let data = {\n idrepeating: id,\n };\n if (sliderInput.checked) {\n //enable repeating\n if (!dateSpan.classList.contains(\"repeating\")) {\n dateSpan.classList.add(\"repeating\");\n data.active = 1;\n }\n } else {\n //disable repeating\n if (dateSpan.classList.contains(\"repeating\")) {\n dateSpan.classList.remove(\"repeating\");\n dateSpan.textContent = \"\";\n data.active = 0;\n }\n }\n sendHttpRequest(\n \"PUT\",\n \"http://localhost:3000/auth/changeReminderActivity\",\n data\n );\n });\n }\n\n return reminder;\n}",
"function scheduleNotifier() {\n //first notification for late submitters at 1230hrs\n onTime({\n log: true,\n cycle: ['weekday 12:30:00'],\n }, function (ot) {\n standUpService.notifyBeforePostingStandup();\n ot.done();\n\n });\n\n //second notification for later submitters at 1430hrs\n onTime({\n log: true,\n cycle: ['weekday 14:30:00'],\n }, function (ot) {\n standUpService.notifyBeforePostingStandup();\n ot.done();\n\n });\n}",
"function createNotification(reminder) {\n const notification = new electron.Notification({ title: \"Cue\", body: \"Hello\" });\n // Open a new window when the notification is clicked\n\n notification.on(\"click\", getClickHandler(reminder));\n notification.show();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
populating domain faculty down button dynamically using the values fetched from database | function populate_faculty_dropdown_by_query()
{
let select = document.getElementById("Select Faculty");
let arr= Get("api/buttonsdynamically/get/faculty");
if(select===null)
alert("empty object retrieved from DOM parse");
if( select.length>1) {
//alert("faculty already exist in under the domain button, no need to again add them");
return "";
}
for (let i = 0; i < arr.length; i++) {
let option = document.createElement("OPTION"), txt = document.createTextNode(arr[i]);
option.appendChild(txt);
option.setAttribute("value", arr[i]);
select.insertBefore(option, select.lastChild);
}
} | [
"function setFacultad(ui) {\r\n nameFac = ui.item.label; // nombre de la facultad\r\n idfac = ui.item.id; // id de la facultad \r\n}",
"function displayReps(apiResponse){\n $(\"#candidateListId\").empty();\n var offices = apiResponse.offices;\n for (var officeIndex=0; officeIndex<offices.length; officeIndex++){\n var office = offices[officeIndex];\n var newDiv = $(\"<div></div>\");\n var dropDownId = officeName2Id(office.name);\n var dropDownContent = $(\"<ul class='dropdowncontent'></ul>\");\n dropDownContent.attr(\"id\",dropDownId);\n\n var dropDownHead = $(\"<button class='dropdownbutton btn' data-show=0></button>\");\n dropDownHead.text(office.name);\n dropDownHead.attr(\"data-activates\", dropDownId);\n\n for (officialIndex = 0; officialIndex<office.officialIndices.length; officialIndex++){\n var officialObj = apiResponse.officials[office.officialIndices[officialIndex]];\n var official = $(\"<li>\");\n var link = $(\"<a href='#' target='iframe_a' class='repLink'></a>\");\n $(link).text(officialObj.name);\n $(official).append(link);\n $(dropDownContent).append(official);\n }\n $(dropDownContent).hide();\n $(newDiv).append(dropDownHead);\n $(newDiv).append(dropDownContent);\n $(\"#candidateListId\").append(newDiv);\n }\n}",
"function setFields(){\n // remove current selection\n var feedback = document.getElementById('feedback');\n while(feedback.firstChild){\n feedback.removeChild(feedback.firstChild);\n }\n // now create items for current selection\n for (var i = 0; i < MAX_CHOICES; i++){\n if(selection[i]){\n var span = document.createElement('span');\n span.className = 'fb';\n span.name = 'fb-'+selection[i];\n var emo = getLabel(selection[i]);\n // var strength = getNumber(selection[i]);\n span.appendChild(document.createTextNode(emo)); // + \"/4 \"));\n\n var remBut = document.createElement('a');\n remBut.href = 'javacript::void();';\n \tremBut.innerHTML = ' ⊗ ';\n remBut.name = 'fb-'+selection[i];\n \tremBut.addEventListener('click', function(ev){\n var circle = this.name.substring(3);\n deselect(circle);\n \t});\n span.appendChild(remBut);\n\n span.style.border = \"4px solid \" + getColor(selection[i]);\n feedback.appendChild(span);\n }\n }\n}",
"buildDropDown(deptNames, facultycount, facultyAdjustedCount) {\n let univtext = {};\n for (let dept in deptNames) {\n if (!deptNames.hasOwnProperty(dept)) {\n continue;\n }\n let p = '<div class=\"table\"><table class=\"table table-sm table-striped\"><thead><th></th><td><small><em>'\n + '<abbr title=\"Click on an author\\'s name to go to their home page.\">Faculty</abbr></em></small></td>'\n + '<td align=\"right\"><small><em> <abbr title=\"Total number of publications (click for DBLP entry).\">\\# Pubs</abbr>'\n + ' </em></small></td><td align=\"right\"><small><em><abbr title=\"Count divided by number of co-authors\">Adj. \\#</abbr></em>'\n + '</small></td></thead><tbody>';\n /* Build a dict of just faculty from this department for sorting purposes. */\n let fc = {};\n for (let name of deptNames[dept]) {\n fc[name] = facultycount[name];\n }\n let keys = Object.keys(fc);\n keys.sort((a, b) => {\n if (fc[b] === fc[a]) {\n return this.compareNames(a, b);\n /*\t\t let fb = Math.round(10.0 * facultyAdjustedCount[b]) / 10.0;\n let fa = Math.round(10.0 * facultyAdjustedCount[a]) / 10.0;\n if (fb === fa) {\n return this.compareNames(a, b);\n }\n return fb - fa; */\n }\n else {\n return fc[b] - fc[a];\n }\n });\n for (let name of keys) {\n let homePage = encodeURI(this.homepages[name]);\n let dblpName = this.dblpAuthors[name]; // this.translateNameToDBLP(name);\n p += \"<tr><td> </td><td><small>\"\n + '<a title=\"Click for author\\'s home page.\" target=\"_blank\" href=\"'\n + homePage\n + '\" '\n + 'onclick=\"trackOutboundLink(\\''\n + homePage\n + '\\', true); return false;\"'\n + '>'\n + name\n + '</a> ';\n if (this.note.hasOwnProperty(name)) {\n const url = CSRankings.noteMap[this.note[name]];\n const href = '<a href=\"' + url + '\">';\n p += '<span class=\"note\" title=\"Note\">[' + href + this.note[name] + '</a>' + ']</span> ';\n }\n if (this.acmfellow.hasOwnProperty(name)) {\n p += '<span title=\"ACM Fellow\"><img alt=\"ACM Fellow\" src=\"' +\n this.acmfellowImage + '\"></span> ';\n }\n if (this.turing.hasOwnProperty(name)) {\n p += '<span title=\"Turing Award\"><img alt=\"Turing Award\" src=\"' +\n this.turingImage + '\"></span> ';\n }\n p += '<span class=\"areaname\">' + this.areaString(name).toLowerCase() + '</span> ';\n // p += '<font style=\"font-variant:small-caps\" size=\"-1\">' + this.areaString(name).toLowerCase() + '</em></font> ';\n p += '<a title=\"Click for author\\'s home page.\" target=\"_blank\" href=\"'\n + homePage\n + '\" '\n + 'onclick=\"trackOutboundLink(\\''\n + homePage\n + '\\', true); return false;\"'\n + '>'\n + '<img alt=\\\"Home page\\\" src=\\\"' + this.homepageImage + '\\\"></a> ';\n if (this.scholarInfo.hasOwnProperty(name)) {\n if (this.scholarInfo[name] != \"NOSCHOLARPAGE\") {\n let url = 'https://scholar.google.com/citations?user='\n + this.scholarInfo[name]\n + '&hl=en&oi=ao';\n p += '<a title=\"Click for author\\'s Google Scholar page.\" target=\"_blank\" href=\"' + url + '\" '\n + 'onclick=\"trackOutboundLink(\\''\n + url\n + '\\', true); return false;\"'\n + '>'\n + '<img alt=\"Google Scholar\" src=\"https://csrankings.org/scholar-favicon.ico\" height=\"10\" width=\"10\">'\n + '</a> ';\n }\n }\n p += '<a title=\"Click for author\\'s DBLP entry.\" target=\"_blank\" href=\"'\n + dblpName\n + '\" '\n + 'onclick=\"trackOutboundLink(\\''\n + dblpName\n + '\\', true); return false;\"'\n + '>'\n + '<img alt=\"DBLP\" src=\"https://csrankings.org/dblp.png\">'\n + '</a>';\n p += \"<span onclick='csr.toggleChart(\\\"\" + escape(name) + \"\\\");' title=\\\"Click for author's publication profile.\\\" class=\\\"hovertip\\\" id=\\\"\" + escape(name) + \"-chartwidget\\\">\"\n + \"<span class='piechart'>\" + this.PieChart + \"</span></span>\"\n + '</small>'\n + '</td><td align=\"right\"><small>'\n + '<a title=\"Click for author\\'s DBLP entry.\" target=\"_blank\" href=\"'\n + dblpName\n + '\" '\n + 'onclick=\"trackOutboundLink(\\''\n + dblpName\n + '\\', true); return false;\"'\n + '>'\n + fc[name]\n + '</a>'\n + \"</small></td>\"\n + '<td align=\"right\"><small>'\n + (Math.round(10.0 * facultyAdjustedCount[name]) / 10.0).toFixed(1)\n + \"</small></td></tr>\"\n + \"<tr><td colspan=\\\"4\\\">\"\n + '<div style=\"display:none;\" id=\"' + escape(name) + \"-chart\" + '\">'\n + '</div>'\n + \"</td></tr>\";\n }\n p += \"</tbody></table></div>\";\n univtext[dept] = p;\n }\n return univtext;\n }",
"function createFacultyMaster() {\n\n $(\"#dashboardOrderListId\").text(\"\").append('<label><a href=\"javascript:displayAdmissionModule()\">Admission</a></label>>> <label><a href=\"javascript:admissionMasterTabs()\">Admission Masters</a></label> >><label>Faculty Master</label>');\n createFormWithoutDisplayingFY(\"dashboardBodyMainDiv\", \"innerDiv\", \"Faculty Master\", \"fieldGroup\", \"successMessage\");\n\n getTwoColumnInRow(\"fieldGroup\", \"Row0\", \"Row0Col1\", \"Row0Col2\");\n getTwoColumnRowDropdownWithLable(\"Row0\", \"DDO\", \"required\", \"Row0Col1\", \"ddo\", \"\");\n getTwoColumnRowDropdownWithLable(\"Row0\", \"Location\", \"required\", \"Row0Col2\", \"location\", \"\");\n\n getLoggedInDDOInDropDown(\"ddo\", \"\");\n getLoggedInLocationInDropDown(\"location\", \"\");\n\n getTwoColumnInRow(\"fieldGroup\", \"Row1\", \"Row1Col1\", \"Row1Col2\");\n getSingleColumnRowInputTextboxWithLable(\"Row1\", \"Faculty Code\", \"required\", \"Row1Col1\", \"facultyCode\", \"\");\n getSingleColumnRowInputTextboxWithLable(\"Row1\", \"Faculty Name\", \"required\", \"Row1Col2\", \"facultyName\", \"\");\n\n getSaveResetUpdateBackButton(\"fieldGroup\", \"saveOrUpdateRowId\", \"Save\", \"saveUpdateBtnId\", \"saveFaculty()\", \"Reset\", \"resetBackBtnId\", \"createFacultyMaster('fieldGroup')\");\n\n restictSpaceInTheBegining();\n viewFacultyList(\"viewFacultyList\");\n\n}",
"function addNewButtonDisplay() {\r\n $('#addNewPatientId').click(function() {\r\n resetPatientReg();\r\n getPatientRegistrationForm();\r\n });\r\n}//to display add new button in demographic display end",
"function periodSelected()\n{\n var periodName = $( '#selectedPeriodId :selected' ).text();\n\n $( '#currentPeriod' ).html( periodName );\n \n dhis2.de.setAttributesMarkup();\n \n if ( dhis2.de.inputSelected() )\n { \t\n showLoader();\n\n if ( dhis2.de.dataEntryFormIsLoaded )\n {\n loadDataValues();\n }\n else\n {\n dhis2.de.loadForm();\n }\n }\n else\n {\n dhis2.de.clearEntryForm();\n }\n}",
"function createCVItineraryButton() {\r\n\tif(checkViewFields([\"text598\",\"text3381\",\"text3321\",\"text3341\",\"text4581\",\"text4541\",\"text4681\",\"text4627\",\"text4589\",\"text4543\",\"text4683\",\"text4629\",\"text4591\",\"text4545\",\"text4685\",\"text4631\",\"text4593\",\"text4547\",\"text4687\",\"text4633\",\"text4595\",\"text4549\",\"text4689\",\"text4635\",\"text4597\",\"text4551\",\"text4691\",\"text4637\",\"text4599\",\"text4553\",\"text4693\",\"text4639\",\"text4601\",\"text4555\",\"text4695\",\"text4641\",\"text4603\",\"text4557\",\"text4697\",\"text4643\",\"text4605\",\"text4559\"])){\r\n\r\n\t/*Dropdown menu from here https://www.w3schools.com/howto/howto_js_dropdown.asp*/\r\n\t//Create our HTML to inject.\r\n\tvar bereaButton = document.createElement(\"div\");\r\n\tbereaButton.style = \"float:right\";\r\n\tbereaButton.id = \"bereaButton\";\r\n\tbereaButton.innerHTML = \"<div class='BereaDropdown'>\"+\r\n\t\t\"<input ID='Berea_Menu_Button' value='Berea Visits' class='BereaBlue bigbutton new' type='button' onclick='return false;'>\"+\r\n\t \"<div id='BereaMenu' class='BereaDropdown-content'>\"+\r\n\t\t//\"<a href='#' ID='AM_No_Lunch' onclick='return false;'>AM Session</a>\"+\r\n\t\t//\"<a href='#' ID='AM_With_Lunch' onclick='return false;'>AM Session (Lunch)</a>\"+\r\n\t\t//\"<a href='#' ID='PM_Session' onclick='return false;'>PM Session</a>\"+\r\n\t\t//\"<a href='#' ID='Midday_Session' onclick='return false;'>Midday Session</a>\"+\r\n\t\t\"<a href='#' ID='Clear_Session'onclick='return false;' >Clear Sessions</a>\"+\r\n\t \"</div></div>\";\r\n\tvar buttonRow = document.getElementsByClassName('triggerBtnsTop');\r\n\tbuttonRow[0].appendChild(bereaButton);\r\n\t//Set even listeners \"click\" for the buttons above.\r\n\tdocument.getElementById(\"Berea_Menu_Button\").addEventListener(\"click\",showCVItineraryMenu);\r\n\t//document.getElementById(\"AM_No_Lunch\").addEventListener(\"click\",function(){creatCVItinerary(1);});\r\n\t//document.getElementById(\"AM_With_Lunch\").addEventListener(\"click\",function(){creatCVItinerary(2);});\r\n\t//document.getElementById(\"PM_Session\").addEventListener(\"click\",function(){creatCVItinerary(3);});\r\n\t//document.getElementById(\"Midday_Session\").addEventListener(\"click\",function(){creatCVItinerary(4);});\r\n\tdocument.getElementById(\"Clear_Session\").addEventListener(\"click\",clearCVItinerary);\r\n\t\r\n\r\n\t/*Just as a side note incase I ever need to insert a script code \r\n\thttps://www.danielcrabtree.com/blog/25/gotchas-with-dynamically-adding-script-tags-to-html*/\r\n\t} else{\r\n\t\trecheckViewFields();\r\n\t}\r\n\t\r\n}",
"function ifAdminDisplay(){\n database.getUserInfo(currentUser.uid).then((dbUser) => {\n let divFormGroupName = document.getElementById('divFormGroup');\n //console.log(dbUser.data().accessLevel);\n if (dbUser.data().accessLevel >= 2){\n let accessLevelSelector = element_builder('select', {class:'form-control', id:'accessLevelSelect'});\n let helpText = element_builder('small', {class: 'form-text text-muted' });\n divFormGroupName.appendChild(helpText);\n helpText.innerHTML = 'Please select the type of administration privileges wanted for this user';\n for (let i = 0; i < 4; i++){\n let optionsAccessLevels = element_builder('option');\n divFormGroupName.appendChild(accessLevelSelector);\n accessLevelSelector.appendChild(optionsAccessLevels);\n \n if (i == 0){\n optionsAccessLevels.innerHTML = 'User';\n optionsAccessLevels.setAttribute('value', '0');\n }\n if (i == 1){\n optionsAccessLevels.innerHTML = 'Group Coordinator';\n optionsAccessLevels.setAttribute('value', '1');\n }\n if (i == 2){\n optionsAccessLevels.innerHTML = 'Region Manager';\n optionsAccessLevels.setAttribute('value', '2');\n }\n if (i == 3){\n optionsAccessLevels.innerHTML = 'Global Manager';\n optionsAccessLevels.setAttribute('value', '3');\n }\n \n }\n }\n \n });\n \n\n}",
"function initializeFieldStaff(){\n //get drop down menu \n var fieldStaffSelect = document.getElementById('FieldStaffSelect');\n \n }",
"function attdeptFunction() {\n // select dropdown and get value\n attdept = attdept_dropdown.property('value');\n buildDepts(attdept);\n}",
"function makeProjectTab(x){\n\n \n // display each record from manager table to the user\n \n var result=`<input type='button' class='filter' value='${x}' onclick=\"setProject(this)\"> </input>`;\n\n document.getElementById('menu').innerHTML+=`${result}`;\n\n }",
"function publications_domainesCreateSelectionField(sNext){\n //our code\n var sCode = \"\";\n\n //create the block\n sCode += \"<div id=\\\"\" + sNext + \"\\\" class=\\\"\" + HEIMDALL_LAY_QUERY_Filter +\"\\\">\" + \"\\r\\n\";\n \n sCode += \"\\t\" + \"<button id=\\\"BTN_DEL_\" + sNext + \"\\\" class=\\\"BTN_ heim_Inline_Block\\\" type=\\\"button\\\" onclick=\\\"deleteSelectionField('\" + sNext + \"')\\\">-</button>\" + \"\\r\\n\";\n sCode += \"\\t\" + \"<select id=\\\"COMBO_Column_\" + sNext + \"\\\" onkeyup=\\\"publicationsKeySearch(event)\\\">\" + \"\\r\\n\";\n sCode += \"\\t\" + \"\\t\" +\"<option value=\\\"sNom\\\">Nom</option>\" + \"\\r\\n\";\n sCode += \"\\t\" + \"\\t\" +\"<option value=\\\"sDescription\\\">Description</option>\" + \"\\r\\n\";\n sCode += \"\\t\" + \"</select>\" + \"\\r\\n\";\n sCode += \"\\t\" + \"<select id=\\\"COMBO_COND_\" + sNext + \"\\\" onkeyup=\\\"publicationsKeySearch(event)\\\">\" + \"\\r\\n\";\n sCode += \"\\t\" + \"\\t\" +\"<option value=\\\"\" + HEIMDALL_QUERY_METHOD_LIKE_StartsWith + \"\\\">Commence Par</option>\" + \"\\r\\n\";\n sCode += \"\\t\" + \"\\t\" +\"<option value=\\\"\" + HEIMDALL_QUERY_METHOD_LIKE_EndsWith +\"\\\">Termine Par</option>\" + \"\\r\\n\";\n sCode += \"\\t\" + \"\\t\" +\"<option value=\\\"\" + HEIMDALL_QUERY_METHOD_LIKE_Contains +\"\\\">Contient</option>\" + \"\\r\\n\";\n sCode += \"\\t\" + \"</select>\" + \"\\r\\n\";\n sCode += \"\\t\" + '<input id=\"SAI_Value_' + sNext + '\" class=\"SAI_\" type=\"text\" name=\"SAI_search_Query\" value=\"\" onkeyup=\"publications_domaines_KeySearch(event)\"/>';\n \n sCode += \"</div>\";\n\n return sCode;\n}",
"click_form_RaceDropdownButton(){\n this.form_RaceDropdownButton.click();\n }",
"function handleClickByFaculty(name) {\n\n let el = gResearch.byFaculty.find(v => v.facultyName === name);\n $('#modal').html(` <div class=\"modal-background\"></div>\n <div class=\"modal-card\">\n <header class=\"modal-card-head\">\n <p class=\"modal-card-title\">${el.facultyName}</p>\n <button class=\"delete\" aria-label=\"close\" onclick=\"$('#modal').toggleClass('is-active')\"></button>\n </header>\n <section class=\"modal-card-body\">\n <div class=\"content\">\n <div class=\"content\">\n <ul>\n ${el.citations.map(value => `<li>${value}</li>`).join('')}\n </ul>\n </div>\n </div>\n </section>\n\n </div>`)\n $(`#modal`).toggleClass(\"is-active\")\n}",
"function change__show_relevant_dept_list() {\n\n\t\t// The faculty dropdown and it's changed-to value\n\t\tvar faculty_field = $( '#ubc_press_onboarding_faculty' );\n\t\tvar faculty_value = faculty_field.val();\n\n\t\t// Fetch all department list dropdowns\n\t\tvar all_department_rows = $( '.ubc_press_dept_list' );\n\n\t\t// The dept list for the chosen faculty\n\t\tvar chosen_dept_list = $( '#ubc_press_onboarding_' + faculty_value + '_department' );\n\t\tvar row_of_chosen_dept_list = chosen_dept_list.parents( '.ubc_press_dept_list' );\n\n\t\t// hide all of them, when complete, fade relevant one in\n\t\t// setTimeout used to make the animation look a little nicer\n\t\tall_department_rows.slideUp( 50, function() {\n\t\t\twindow.setTimeout( function(){\n\t\t\t\t// Fade in the relevant faculty list\n\t\t\t\trow_of_chosen_dept_list.slideDown( 100 );\n\t\t\t}, 200 );\n\t\t} );\n\n\t}",
"static create_records() {\n //\n //Get the $name of the selected entity using the id as tname meaning table name\n let $tname = document.querySelector('[selected=true]').id;\n //\n //Open an empty brand new window\n let $win = window.open(\"page_create.php\");\n //\n $win.onload = () => {\n //\n //Get the $body element of $win (window).\n let $body = $win.document.querySelector('form');\n //\n //looping through all the columns to create a label inputs\n for (let $cname in databases[page_graph.dbname].entities[$tname].columns) {\n\n //\n //Get the named column\n let $column = databases[page_graph.dbname].entities[$tname].columns[$cname];\n //\n //Append all the column as lables appended to the body of the new window \n $column.display($body);\n };\n };\n\n }",
"function existingDataSetButton() { \n var dataSetList = getDataSetList(); \n \n var image = \"<h2>Existing DataSets</h2>\"; \n for (var i = 0; i < dataSetList.length; i++) { \n image += '<input type=\"radio\" name=\"id\" value=\"' + dataSetList[i].id + '\"/>'; \n image += dataSetList[i].name + \"<br>\"; \n } \n \n var operations = \"\"; \n \n operations = '<input type=\"radio\" name=\"methodname\" value=\"clustering\" onclick=\"onClusterClick()\"/>' + \n ' Clustering <br>'; \n \n dojo.byId(\"wizardDataSets\").innerHTML = image; \n dojo.byId(\"operations\").innerHTML = operations; \n \n dijit.byId('wizardDialog').show(); \n}",
"function loadExistingDocuments() {\n //for each document associated to a specific faculty\n $(\"#existing-documents\").html(\"<option onclick='getDocInfo();'>Existing Documents</option>\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
var output = getProperty(obj, 'key'); console.log(output); // > 'value' | function getProperty(obj, key) {
var result = undefined;
for (var key1 in obj){
if (obj[key1] === obj[key]){
result = obj[key1];
}
}
return result;
} | [
"function getProperty(obj, key) {\n for (k in obj){\n if (k == key){\n return obj[key];\n }\n }\n}",
"function getPropertyValue (obj, name){\n return obj[name]\n}",
"function getValue(object, key){\n var returnKey = object[key]; \n return returnKey; \n}",
"function prop(name, obj) {\r\n return obj[name]\r\n}",
"function get(object, prop) {\n var propVal = null;\n if (object.hasOwnProperty(prop)) {\n propVal = object[prop];\n }\n else if (typeof object[\"get\"] == \"function\") {\n propVal = object.get(prop);\n }\n return propVal;\n }",
"function getValue(object, key) {\n return object[key];\n}",
"function grabKey(obj, key) {\n return obj[key];\n}",
"getPropertyValue(key) {\n return this[3\n /* properties */\n ][key] || '';\n }",
"function getValue(object,prop){\nif(!(object&&object[prop])){\nreturn null;\n}\nreturn _.isFunction(object[prop])?object[prop]():object[prop];\n}",
"function getObjectValue(obj, key) {\n if (isMap(obj)) {\n return obj.get(key);\n }\n else {\n return obj[key];\n }\n}",
"getPropertyValue(object, key, opId) {\n if (object instanceof Table) {\n return object.byId(key)\n } else if (object instanceof Text) {\n return object.get(key)\n } else {\n return object[CONFLICTS][key][opId]\n }\n }",
"function get(object, key) {\n return object[key];\n}",
"function accessAProperty(object, key) {\n\t// create a result variable,\n\tlet result;\n\t// assign it to an expression that accesses the property in the object located at the key\n\tresult = object[key];\n\t// return the result variable\n\treturn result;\n}",
"function searchGet(key, obj)\n{\n obj || (obj=this);\n\n var value;\n var Key=key.charAt(0).toUpperCase() + key.substring(1);\n var accessor;\n\n if((accessor=(\"get\" + Key)) in obj)\n {\n var fn=obj[accessor];\n\n value=fn.call(obj);\n }\n // else if((\"is\" + Key) in obj)\n // {\n // value=obj.isKey();\n // }\n // else if((\"_\" + key) in obj)\n // {\n // value=obj[\"_\" + key];\n // }\n // else if((\"_is\" + Key) in obj)\n // {\n // value=obj[\"_is\" + key];\n // }\n // else// if((key in obj))\n // {\n // value=obj[key];\n // }\n else {\n value=ivarGet(key, obj);\n }\n\n return value;\n}",
"function grabKey(obj, str) {\n console.log(obj[str])\n return obj[str]\n}",
"function getValue(object, key) {\n return (object.hasOwnProperty(key) ? object[key] : 'No such pairing')\n}",
"function get(obj, prop, defaultValue) {\n\t return (hasOwn(obj, prop) ? obj[prop] : defaultValue)\n\t}",
"function get(obj, key) {\n\t\ttry {\n\t\t\treturn obj[key];\n\t\t} catch (e) {\n\t\t\treturn false;\n\t\t}\n\t}",
"function get(object, key) {\n //Loop through the object\n //if you find that key return value\n //else return undefined\n for(let banana in object) {\n return object[key];\n}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
/ Updates the vertical scroll bar thumb based on height of window or level height | function UpdateVerticalScrollVisual()
{
var levelHeightPercentage = +(_canvas.height/_heightInputBox.value).toFixed(2);
if(levelHeightPercentage <= .99)
{
if(!_verticalScrollVisible)
{
_verticalScroll.style.display = "inline-block";
_verticalScrollVisible = true;
}
var proposedHeight = levelHeightPercentage*_verticalScroll.clientHeight;
if(proposedHeight >= _minThumbHeight)
{
_verticalThumb.style.height = proposedHeight;
}
else
{
_verticalThumb.style.height = _minThumbHeight;
}
}
else
{
if(_verticalScrollVisible)
{
//hide scroll bar when level height is the same or less than canvas height
_verticalScroll.style.display = "none";
_verticalScrollVisible = false;
}
}
} | [
"function setScrollbar(){\n\t\t\tvar $appendEl=o.scrollAppendTo||$root;\n\t\t\t$scrollBar=$('<div />', {\"class\":\"horizontal-slider\"}).appendTo($appendEl);\n\t\t\t$handle=$('<div />', {\"class\":\"horizontal-handle hover\"}).appendTo($scrollBar);\n\t\t\trefreshScrollbar();\n\t\t}",
"function sizeScrollbar() {\n var remainder = scrollContent.width() - scrollPane.width();\n var proportion = remainder / scrollContent.width();\n var handleSize = scrollPane.width() - (proportion * scrollPane.width());\n scrollbar.find(\".ui-slider-handle\").css({\n width: handleSize,\n \"margin-left\": -handleSize / 2\n });\n handleHelper.width(\"\").width(scrollbar.width() - handleSize);\n }",
"function sizeScrollbar(){\n\t\tvar remainder = scrollContent.width() - scrollPane.width();\n\t\tvar proportion = remainder / scrollContent.width();\n\t\tvar handleSize = scrollPane.width() - (proportion * scrollPane.width());\n\t\tscrollbar.find('.ui-slider-handle').css({\n\t\t\twidth: handleSize,\n\t\t\t'margin-left': -handleSize/2\n\t\t});\n\t\thandleHelper.width('').width( scrollbar.width() - handleSize);\n\t}",
"doUpdateScrollbars_() {\n this.scrollbarUpdate_ = 0;\n\n const content = this.content_;\n\n // Adjust scroll-height to account for possible header-bar.\n const adjustedScrollHeight = content.scrollHeight - content.offsetTop;\n\n if (adjustedScrollHeight <= content.clientHeight) {\n this.scrollbar_.hidden = true;\n return;\n } else {\n this.scrollbar_.hidden = false;\n }\n\n const thumbTop = content.offsetTop +\n content.scrollTop / adjustedScrollHeight * content.clientHeight;\n const thumbHeight =\n content.clientHeight / adjustedScrollHeight * this.clientHeight;\n\n this.scrollbar_.style.top = thumbTop + 'px';\n this.scrollbar_.style.height = thumbHeight + 'px';\n this.firePageLayoutEvent_();\n }",
"function sizeScrollbar(){\n\t\tvar remainder = scrollContent.width() - scrollPane.width();\n\t\tvar proportion = remainder / scrollContent.width();\n\t\tvar handleSize = scrollPane.width() - (proportion * scrollPane.width());\n\t\tscrollbar.find('.ui-slider-handle').css({\n\t\t\twidth: handleSize,\n\t\t\t'margin-left': -handleSize / 2\n\t\t});\n\t\thandleHelper.width('').width(scrollbar.width() - handleSize);\n\t}",
"function verticalThumb(scroller) {\n assert_equals(scroller.scrollTop, 0, \"verticalThumb() requires scroller to have scrollTop of 0\");\n const TRACK_WIDTH = calculateScrollbarThickness();\n const BUTTON_WIDTH = calculateScrollbarButtonWidth();\n\n if (scroller === document.documentElement || typeof(scroller) == 'undefined') {\n // HTML element is special, since scrollbars are not part of its client rect\n // and page scale doesn't affect the scrollbars. Use window properties instead.\n let x = window.innerWidth - TRACK_WIDTH / 2;\n let y = BUTTON_WIDTH + 6;\n return {x: x, y: y};\n }\n const scrollerRect = scroller.getBoundingClientRect();\n const thumbPoint = { x : scrollerRect.right - TRACK_WIDTH / 2,\n y : scrollerRect.top + BUTTON_WIDTH + 2 };\n return cssClientToCssVisual(thumbPoint);\n}",
"function sizeScrollbar() {\n\n\t\t\t\t\tlet remainder = $scrollContent.width() - $scrollPane.width();\n\t\t\t\t\tif (remainder < 0) {\n\t\t\t\t\t\tremainder = 0;\n\t\t\t\t\t}\n\t\t\t\t\tlet proportion = remainder / $scrollContent.width();\n\t\t\t\t\tlet handleSize = $scrollPane.width() - (proportion * $scrollPane.width());\n\t\t\t\t\t$scrollbar.parent().find('.ui-slider-handle').css({\n\t\t\t\t\t\twidth: handleSize,\n\t\t\t\t\t\t'margin-left': -handleSize / 2\n\t\t\t\t\t});\n\t\t\t\t\thandleHelper.width('').width($scrollbar.width() - handleSize);\n\t\t\t\t}",
"function sizeScrollbar() {\n var remainder = $scrollContent.width() - $scrollPane.width();\n var proportion = remainder / $scrollContent.width();\n var handleSize = $scrollPane.width() - (proportion * $scrollPane.width());\n $scrollbar.find(\".ui-slider-handle\").css({\n width: handleSize,\n \"margin-left\": -handleSize / 2\n });\n handleHelper.width(\"\").width($scrollbar.width() - handleSize);\n }",
"function sizeScrollbar() {\n var remainder = scrollContent.width() - scrollPane.width();\n var proportion = remainder / scrollContent.width();\n var handleSize = scrollPane.width() - ( proportion * scrollPane.width() );\n scrollbar.find( \".ui-slider-handle\" ).css({\n width: handleSize,\n \"margin-left\": -handleSize / 2\n });\n handleHelper.width( \"\" ).width( scrollbar.width() - handleSize );\n }",
"function sizeScrollbar() {\n var remainder = scrollContent.width() - scrollPane.width();\n var proportion = remainder / scrollContent.width();\n if (proportion <= 0)\n scrollbar.hide();\n else {\n var handleSize = scrollPane.width() - proportion*scrollPane.width();\n scrollbar.find(\".ui-slider-handle\").css({\n width: handleSize,\n \"margin-left\": -handleSize / 2\n });\n handleHelper.width(\"\").width(scrollbar.width() - handleSize);\n }\n }",
"function sizeScrollbar() {\n var remainder = scrollContent.width() - scrollPane.width();\n var proportion = remainder / scrollContent.width();\n var handleSize = scrollPane.width() - ( proportion * scrollPane.width() );\n scrollbar.find( \".ui-slider-handle\" ).css({\n width: handleSize,\n \"margin-left\": -handleSize / 2\n });\n handleHelper.width( \"\" ).width( scrollbar.width() - handleSize );\n }",
"_addScrollBar() {\n const canvas = this.getCanvas();\n\n canvas.add(this._horizontalScroll);\n canvas.add(this._verticalScroll);\n\n if (this.scrollBarTid) {\n clearTimeout(this.scrollBarTid);\n }\n\n this.scrollBarTid = setTimeout(() => {\n canvas.remove(this._horizontalScroll);\n canvas.remove(this._verticalScroll);\n }, 3000);\n }",
"_verticalScrollbarHandler() {\n const scrollViewer = this,\n verticalScrollBar = scrollViewer.$.verticalScrollBar,\n value = verticalScrollBar.value;\n\n if (scrollViewer.disabled) {\n return;\n }\n\n if (verticalScrollBar.max === value) {\n if (!scrollViewer._bottomReached) {\n scrollViewer.$.fireEvent('scrollBottomReached');\n delete scrollViewer._topReached;\n scrollViewer._bottomReached = true;\n }\n\n return;\n }\n\n if (verticalScrollBar.min === value) {\n if (!scrollViewer._topReached) {\n scrollViewer.$.fireEvent('scrollTopReached');\n delete scrollViewer._bottomReached;\n scrollViewer._topReached = true;\n }\n return;\n }\n\n delete scrollViewer._topReached;\n delete scrollViewer._bottomReached;\n }",
"updateVerScrollBarMaximum() {\n var paneSize = this._paneClipper.getInnerSize();\n if (!paneSize) {\n // will be called on the next resize event again\n return;\n }\n\n var tableModel = this.getTable().getTableModel();\n var rowCount = tableModel.getRowCount();\n\n if (this.getTable().getKeepFirstVisibleRowComplete()) {\n rowCount += 1;\n }\n\n var rowHeight = this.getTable().getRowHeight();\n var scrollSize = rowCount * rowHeight;\n var scrollBar = this.__verScrollBar;\n\n if (paneSize.height < scrollSize) {\n var max = Math.max(0, scrollSize - paneSize.height);\n\n scrollBar.setMaximum(max);\n scrollBar.setKnobFactor(paneSize.height / scrollSize);\n\n var pos = scrollBar.getPosition();\n scrollBar.setPosition(Math.min(pos, max));\n } else {\n scrollBar.setMaximum(0);\n scrollBar.setKnobFactor(1);\n scrollBar.setPosition(0);\n }\n }",
"function UpdateScrollThumbs()\n{\n UpdateVerticalScrollVisual();\n UpdateHorizontalScrollVisual();\n}",
"function AppleVerticalScrollbar(scrollbar)\n{\n\t/* Objects */\n\tthis.scrollarea = null;\n\tthis.scrollbar = scrollbar;\n\t\n\t/* public properties */\n\t// These are read-write. Set them as needed.\n\tthis.minThumbSize = 28;\n\tthis.padding = -1;\n\t\n\t// These are read-only. Use the setter functions to set them.\n\tthis.autohide = true;\n\tthis.hidden = true;\n\tthis.size = 19; // width\n\tthis.trackStartPath = \"AppleClasses/Images/scroll_track_vtop.png\";\n\tthis.trackStartLength = 18; // height\n\tthis.trackMiddlePath = \"AppleClasses/Images/scroll_track_vmid.png\";\n\tthis.trackEndPath = \"AppleClasses/Images/scroll_track_vbottom.png\";\n\tthis.trackEndLength = 18; // height\n\tthis.thumbStartPath = \"AppleClasses/Images/scroll_thumb_vtop.png\";\n\tthis.thumbStartLength = 9; // height\n\tthis.thumbMiddlePath = \"AppleClasses/Images/scroll_thumb_vmid.png\";\n\tthis.thumbEndPath = \"AppleClasses/Images/scroll_thumb_vbottom.png\";\n\tthis.thumbEndLength = 9; // height\n\n\t/* Internal objects */\n\tthis._track = null;\n\tthis._thumb = null;\n\t\n\t/* Dimensions */\n\t// these only need to be set during refresh()\n\tthis._trackOffset = 0;\n\tthis._trackLength = 0;\n\tthis._numScrollablePixels = 0;\n\tthis._thumbLength = 0;\n\tthis._repeatType = \"repeat-y\";\n\t\n\t// these change as the content is scrolled\n\tthis._thumbStart = this.padding;\n\t\n\t// For JavaScript event handlers\n\tvar _self = this;\n\t\n\tthis._captureEventHandler = function(event) { _self._captureEvent(event); };\n\tthis._mousedownThumbHandler = function(event) { _self._mousedownThumb(event); };\n\tthis._mousemoveThumbHandler = function(event) { _self._mousemoveThumb(event); };\n\tthis._mouseupThumbHandler = function(event) { _self._mouseupThumb(event); };\n\tthis._mousedownTrackHandler = function(event) { _self._mousedownTrack(event); };\n\tthis._mousemoveTrackHandler = function(event) { _self._mousemoveTrack(event); };\n\tthis._mouseoverTrackHandler = function(event) { _self._mouseoverTrack(event); };\n\tthis._mouseoutTrackHandler = function(event) { _self._mouseoutTrack(event); };\n\tthis._mouseupTrackHandler = function(event) { _self._mouseupTrack(event); };\n\t\n\tthis._init();\n}",
"static VerticalScrollbar() {}",
"_verticalScrollbarHandler(event) {\n const that = this;\n const value = event.detail.value;\n event.stopPropagation();\n\n if (that.isVirtualized) {\n that._recycle();\n }\n else {\n that.$.itemsContainer.scrollTop = value;\n }\n\n that._updateTopVisibleIndex();\n\n if (event.context.max === event.context.value) {\n that.$.fireEvent('scrollBottomReached');\n return;\n }\n\n if (event.context.min === event.context.value) {\n that.$.fireEvent('scrollTopReached');\n }\n }",
"_setSliderHeight() {\n // If fullscreen, do nothing\n if (!this.$el.hasClass('fullscreen')) {\n if (this.options.indicators) {\n // Add height if indicators are present\n this.$el.css('height', (this.options.height + 40) + 'px');\n }\n else {\n this.$el.css('height', this.options.height + 'px');\n }\n this.$slider.css('height', this.options.height + 'px');\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.