query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
change_color takes a path ID and a color (hex value) and changes that path's fill color. | function change_color(id, color) {
try {
var element = document.getElementById(id); // Can be a <g> element (with children), or a single <path> element.
element.style.fill = color;
fill_children(element, color); // Fill the child elements.
}
catch (e) {
console.log("Error: " + e + "; id: " + id);
};
} | [
"function changeColor(id, color) {\n\t// haal path dmv id en zet die naar kleur\n document.getElementById(id).style.fill = color;\n\n}",
"function svgColorHandler(svgId, color) {\n document.getElementById(svgId).getSVGDocument().getElementsByTagName(\"g\")[0].style.fill = color;\n }",
"function setColor(id, color) {\n\tdocument.getElementById(id).style.color = color;\n}",
"function changeColor(cord)\n{\n // set fillStyle to Blue\n context2D.fillStyle = \"Blue\";\n // fill clicked cell \n context2D.fillRect(cord[0] * canvas.width / 8, cord[1] * canvas.height / 8, canvas.width / 8, canvas.height / 8);\n}",
"function colorChange(selectObj, dataname) {\n var idx = selectObj.selectedIndex;\n var color = selectObj.options[idx].value;\n\n d3.select(\"#\" + dataname)\n .attr(\"style\", \"stroke: \" + color)}",
"updateColor (color) {\n this._sendMessage([0x56].concat(color).concat(0xAA))\n }",
"function svgcolor(el, color) {\n\n var fill = $(el).attr('fill');\n var stroke = $(el).attr('stroke');\n\n var isFill, isStroke;\n if (!fill && !stroke) {\n isFill = true;\n } else {\n if (fill && fill !== 'none') {\n isFill = true;\n }\n\n if (stroke && stroke !== 'none') {\n isStroke = true;\n }\n }\n\n if (isStroke) {\n $(el).attr('stroke', data.options.colorify || stroke);\n }\n\n if (isFill) {\n $(el).attr('fill', data.options.colorify || fill);\n }\n }",
"function changeColor(port) {\n myDiagram.startTransaction(\"colorPort\");\n var data = port.data;\n myDiagram.model.setDataProperty(data, \"portColor\", go.Brush.randomColor());\n myDiagram.commitTransaction(\"colorPort\");\n }",
"set strokeColor(color) {\n var hex = STYLE_UTIL.getHexColor(color);\n if (hex) {\n var stroke = SLD.stroke(this._symbolizer);\n stroke.setColor(STYLE_UTIL._filterFactory.literal(hex));\n } else {\n throw new Error(\"Can't determine hex color from strokeColor '\" + color + \"'.\")\n }\n }",
"changeColor() {\n this.currentColor = this.intersectingColor;\n }",
"function changeForegroundColor(eid, color) {\n if(document.getElementById && (elem=document.getElementById(eid)))\n elem.style.color=color;\n}",
"function changeColor(bottle, color) {\n bottle.attr('style', 'background-color: ' + color);\n }",
"function clickColor(event) {\n const target = event.target;\n selectedColor = target.style.fill;\n}",
"function changeColor(color) {\n gMeme.currText.color = color\n}",
"function cycleDrawColour() {\n Data.Edit.Node.style.stroke = cycleColour(Data.Edit.Node.style.stroke);\n hasEdits(true);\n}",
"function setColour() {\r\n vertices.selectAll(\"circle\")\r\n .style(\"fill\", function (v) {\r\n\r\n // If not connected to any other vertex, set colour to grey\r\n if (!v.degree)\r\n return customColours[2];\r\n\r\n // If general graph, set colour to red\r\n if (selectedAlgorithm == 3)\r\n return customColours[1];\r\n\r\n // If left-hand vertex, set colour to red and if right-hand vertex, set colour to blue\r\n if (v.parity)\r\n return customColours[v.parity % 2];\r\n\r\n // If non-bipartite graph, use one of the standard colours\r\n else\r\n return standardColours(v.id);\r\n\r\n });\r\n}",
"function setDrawingColor(event) {\n sketchController.color = this.value;\n}",
"function set_swatch_colour(new_colour) {\n chrome.storage.sync.set({\n 'daysago_swatch': new_colour\n }, function() {\n start_colour = new_colour;\n trigger_draw_grid();\n });\n}",
"function setBackgroundColor(id, hexColor) {\n document.getElementById(id).style.backgroundColor = hexColor;\n}",
"function setAllNodeEdgesColor(edgesDataSet, nodeId, newColor) {\n var theseEdges = edgesDataSet.get({\n filter: function(item) {\n return (item.to == nodeId || item.from == nodeId);\n }});\n for (var i = theseEdges.length - 1; i >= 0; i--) {\n setColor(edgesDataSet, theseEdges[i], newColor);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
new version: store by prefix add unique id to a subscription list | saveClient(client, uniqueid, prefix)
{
// console.log('saving client', uniqueid, prefix );
if( !this.ids.hasOwnProperty(prefix) )
{
this.ids[prefix] = new Set();
}
this.ids[prefix].add(uniqueid);
this.sockets.set(uniqueid, client);
} | [
"function addIdPrefix(component, prefix) {\n if (component.attr(\"id\") != undefined) {\n component.attr(\"id\", prefix + component.attr(\"id\"));\n }\n component.find('*').each(function () {\n if (jQuery(this).attr(\"id\") != undefined) {\n jQuery(this).attr(\"id\", prefix + jQuery(this).attr(\"id\"))\n }\n });\n return component;\n}",
"function storePrefixedInputStorageItem(prefix,input_element) {\n var item_data = getInputData(input_element);\n localStorage.setItem(prefix + item_data.id, JSON.stringify(item_data));\n }",
"function subscribe(id) {\n weavy.api.follow(\"item\", id).then(function () {\n updateSubscribers(id);\n });\n }",
"function renewSubscriptions() {\n udpPort.send({\n address: '/batchsubscribe',\n args: [\n // First defines the local endpoint that the X32 will send this subscription data to.\n { type: 's', value: '/chMutes' },\n { type: 's', value: '/mix/on' },\n { type: 'i', value: 0 },\n { type: 'i', value: 63 },\n { type: 'i', value: 10 }\n ]\n });\n udpPort.send({\n address: '/batchsubscribe',\n args: [\n // First defines the local endpoint that the X32 will send this subscription data to.\n { type: 's', value: '/chFaders' },\n { type: 's', value: '/mix/fader' },\n { type: 'i', value: 0 },\n { type: 'i', value: 63 },\n { type: 'i', value: 10 }\n ]\n });\n}",
"function setListId(string) {\n var new_id_prefix = 'list_id_';\n var new_id = new_id_prefix.concat(string);\n var element = document.getElementsByClassName('shopping_list')[0];\n element.id=new_id;\n}",
"addPrefixes(prefixes, done) {\n // Ignore prefixes if not supported by the serialization\n if (!this._prefixIRIs) return done && done(); // Write all new prefixes\n\n let hasPrefixes = false;\n\n for (let prefix in prefixes) {\n let iri = prefixes[prefix];\n if (typeof iri !== 'string') iri = iri.value;\n hasPrefixes = true; // Finish a possible pending quad\n\n if (this._subject !== null) {\n this._write(this._inDefaultGraph ? '.\\n' : '\\n}\\n');\n\n this._subject = null, this._graph = '';\n } // Store and write the prefix\n\n\n this._prefixIRIs[iri] = prefix += ':';\n\n this._write(`@prefix ${prefix} <${iri}>.\\n`);\n } // Recreate the prefix matcher\n\n\n if (hasPrefixes) {\n let IRIlist = '',\n prefixList = '';\n\n for (const prefixIRI in this._prefixIRIs) {\n IRIlist += IRIlist ? `|${prefixIRI}` : prefixIRI;\n prefixList += (prefixList ? '|' : '') + this._prefixIRIs[prefixIRI];\n }\n\n IRIlist = IRIlist.replace(/[\\]\\/\\(\\)\\*\\+\\?\\.\\\\\\$]/g, '\\\\$&');\n this._prefixRegex = new RegExp(`^(?:${prefixList})[^\\/]*$|` + `^(${IRIlist})([a-zA-Z][\\\\-_a-zA-Z0-9]*)$`);\n } // End a prefix block with a newline\n\n\n this._write(hasPrefixes ? '\\n' : '', done);\n }",
"function addSongToPlaylist( mixtape, change )\r\n{\r\n\r\n var idx = mixtape.playlists.findIndex((el) => el.id === change.playlistId)\r\n if ( idx === -1 )\r\n {\r\n console.log( \"Playlist with id '\"+change.playlistId+\"' does not exists\");\r\n return;\r\n }\r\n\r\n mixtape.playlists[idx].song_ids.push(change.songId);\r\n\r\n}",
"function getPrefixFromConf(prefix) {\n\n var values = Object.keys(prefixList).map(function(key) {\n return prefixList[key];\n });\n\n var position = valuePosition(prefix,values);\n var newPrefix = \"\";\n var keys = Object.keys(prefixList);\n\n if (position >= 0 && position < keys.length) {\n newPrefix = keys[position];\n }\n\n return newPrefix;\n}",
"function addPlaylist( mixtape, change )\r\n{\r\n \r\n var newId = mixtape.playlists[mixtape.playlists.length-1].id;\r\n newId++;\r\n newId = newId.toString();\r\n var newPlaylist = {\r\n id : newId,\r\n user_id : change.playlist.user_id,\r\n song_ids: change.playlist.song_ids\r\n }\r\n mixtape.playlists.push(newPlaylist);\r\n \r\n}",
"function getPrefixesList() {\n return prefixList;\n}",
"setPrefix(prefix, uri) {\n if (prefix.slice(0, 7) === 'default') return // Try to weed these out\n if (prefix.slice(0, 2) === 'ns') return // From others inferior algos\n if (!prefix || !uri) return // empty strings not suitable\n\n // remove any existing prefix targeting this uri\n // for (let existingPrefix in this.namespaces) {\n // if (this.namespaces[existingPrefix] == uri)\n // delete this.namespaces[existingPrefix];\n // }\n\n // remove any existing mapping for this prefix\n for (let existingNs in this.prefixes) {\n if (this.prefixes[existingNs] == prefix)\n delete this.prefixes[existingNs];\n }\n\n this.prefixes[uri] = prefix\n this.namespaces[prefix] = uri\n }",
"stateValuesSubscribe (path) {\n // prevent duplicates\n if (contains(path, this.subscriptions)) return\n // subscribe\n this.subscriptions.push(path)\n this.stateValuesSendSubscriptions()\n }",
"function TKR_updateUsedPrefixes(textField) {\n if (textField.oldPrefix != undefined) {\n DeleteArrayElement(TKR_usedPrefixes[textField.oldPrefix], textField);\n }\n\n var prefix = textField.value.split('-')[0].toLowerCase();\n if (TKR_usedPrefixes[prefix] == undefined) {\n TKR_usedPrefixes[prefix] = [textField];\n }\n else {\n TKR_usedPrefixes[prefix].push(textField);\n }\n textField.oldPrefix = prefix;\n}",
"function updateSubscribers(id) {\n var $subscribers = $(\"[data-entity=item][data-id='\" + id + \"'] .subscribers\");\n if (!$subscribers.length) {\n return;\n }\n\n $.ajax({\n url: weavy.url.resolve(\"/items/\" + id + \"/subscribers\"),\n method: \"GET\",\n contentType: \"application/json\"\n }).then(function (html) {\n $subscribers.replaceWith(html);\n });\n }",
"addSub(name) {\n let newSubredditList = this.props.subreddits;\n newSubredditList.push(name);\n this.props.callbackFromParent(newSubredditList);\n }",
"async addNotification(subscriptionId, notification) {\n const exists = await this.db.notifications.get(notification.id);\n if (exists) {\n return false;\n }\n try {\n // sw.js duplicates this logic, so if you change it here, change it there too\n await this.db.notifications.add({\n ...notification,\n subscriptionId,\n // New marker (used for bubble indicator); cannot be boolean; Dexie index limitation\n new: 1,\n }); // FIXME consider put() for double tab\n await this.db.subscriptions.update(subscriptionId, {\n last: notification.id,\n });\n } catch (e) {\n console.error(`[SubscriptionManager] Error adding notification`, e);\n }\n return true;\n }",
"function idToChannel() {\n updateConfig()\n setTimeout(() => {\n AddChannel()\n }, 1000);\n }",
"function push_DASH_nsp(nsp) {\n let GS__38 = Array.prototype.slice.call(arguments, 1);\n let info = getIndex(GS__38, 0);\n return _STAR_ns_DASH_cache_STAR_.unshift(hash_DASH_map(\"id\", nsp, \"meta\", info));\n}",
"add(state, { layer, corpuUid }) {\n const index = state.lists[corpuUid].length\n Vue.set(state.lists[corpuUid], index, layer)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
isHostExists checks if hostname exists or not via hostname lookup | function isHostExists(hostname) {
return __awaiter(this, void 0, void 0, function () {
var rd, s, p;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
rd = redis_1.getRedis();
s = hostname.split(".")[0];
p = util_1.promisify(rd.sismember).bind(rd);
return [4 /*yield*/, p("domains", s)];
case 1: return [2 /*return*/, (_a.sent()) == 1];
}
});
});
} | [
"function procExists(host) {\n return typeof getProc(host) != 'undefined'\n}",
"function checkCookieHost(cookie, host)\n{\n var domainPrefix = \".\";\n if (cookie.host.slice(0, domainPrefix.length) == domainPrefix) {\n if (cookie.host.substring(1) != host) {\n if (host.slice(-cookie.host.length) != cookie.host) {\n return false;\n }\n }\n }\n else {\n if (host != cookie.host) {\n if (0 == host.length) {\n return true;\n }\n return false;\n }\n }\n return true;\n}",
"function resolveHost(domain)\r\n{\r\n var hostString = \"www\";\r\n \r\n if(domain == \"lexis\" || domain == \"nexis\") \r\n hostString = \"w3\"; \r\n \r\n return hostString;\r\n}",
"function FindProxyForURL(url, host) {\n try {\n expectEq(\"127.0.0.1\", myIpAddress());\n expectEq(\"\", myIpAddressEx());\n\n expectEq(null, dnsResolve(\"not-found\"));\n expectEq(\"\", dnsResolveEx(\"not-found\"));\n\n expectEq(false, isResolvable(\"not-found\"));\n expectEq(false, isResolvableEx(\"not-found\"));\n\n return \"PROXY success:80\";\n } catch(e) {\n alert(e);\n return \"PROXY failed:80\";\n }\n}",
"function updateHosts(ip, host) {\n if (!hosts[ip] || hosts[ip].indexOf('*') != 0 && host != getHost(ip)) {\n\thosts[ip] = host;\n\tsaveHosts();\n\tconsole.log('Added host', ip + ':', host);\n }\n}",
"function checkConnection(){\n\tdns.lookup('google.com',function(err) {\n\t\n \tif (err && err.code == \"ENOTFOUND\") {\n \t connected = 0;\n \t}\n\t\telse{\n\t\t\t\tconnected = 1;\n\t\t}\n\t});\n}",
"function isLocalhost(){\n return window.location.origin.includes(\"localhost:8088\");\n}",
"_getHostname() {\r\n let host = this._os.hostname() || '';\r\n if (host.indexOf('.') < 0) { // ignore if not FQDN\r\n host = '[127.0.0.1]';\r\n }\r\n else if (host.match(/^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/)) { // IP mut be enclosed in []\r\n host = `[${host}]`;\r\n }\r\n return host;\r\n }",
"function register_proxy (uri, succeed, fail)\n{\n var options = url.parse(url.resolve(base, uri));\n \n test_host(options.hostname, \n function () {\n // local host so use local thing\n var thing = registry[options.href];\n \n if (thing)\n succeed(thing.thing);\n else // not yet created\n {\n console.log('waiting for ' + uri + ' to be created');\n record_handler(uri, succeed);\n }\n },\n function () {\n // remote host so find proxy\n console.log(options.hostname + \" is remote\");\n launch_proxy(options, succeed, fail);\n },\n function () {\n // unknown host name\n fail(\"server couldn't determine IP address for \" + options.hostname);\n });\n}",
"function is_remote_url(url) {\n\tvar parsed = require('url').parse(url);\n\tif(parsed.hostname === REMOTE_HOST) {\n\t\treturn true;\n\t}\n\treturn false;\n}",
"vaidateProtocol(host){\n let protocols = ['https://', 'http://'];\n if (protocols.map(protocol => host.includes(protocol)).includes(true)) return host\n throw new Error('Host String must include http:// or https://')\n }",
"function loadHosts() {\n if (noLoadHosts) return;\n\n noLoadHosts = true; // Debounce\n var file = __dirname + \"/\" + hostsFile;\n fs.exists(file, function(exists) {\n\tif (!exists) return;\n\n\thosts = {};\n\tfs.readFile(file, function(err, data) {\n\t _.each(data.toString().split(/[\\n\\r]+/), function(line) {\n\t\tline = line.replace(/\\s*\\#.*$/, '');\n\t\tif (line.match(/^\\s*$/)) return;\n\n\t\tvar parts = line.split(/\\s+/);\n\t\tif (parts && parts.length == 2) {\n\t\t hosts[parts[0]] = parts[1];\n\t\t}\n\t });\n\t if (_.keys(hosts).length > 0) {\n\t\tnoLoadHosts = false;\n\t\tconsole.log('Loaded ' + _.keys(hosts).length + ' hosts from ' + file);\n\t }\n\t});\n });\n}",
"function urlExists(url) {\n\t\tvar http = new XMLHttpRequest();\n\t\thttp.open('HEAD', url);\n\t\thttp.send();\n\t\tif (http.status !== 404) {\n\t\t\timgsNumber++;\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}",
"function isIPConnected(socket) {\n // Check if this sockets ip address is already exists in the clientSockets array\n for (i = 0; i < clientSockets.length; i++) {\n // socket.handshake.address returns the IP address\n if (socket.handshake.address === clientSockets[i].handshake.address) {\n return true;\n }\n }\n return false;\n} // End isIPConnected()",
"function checkAliasExistSync(alias){\n return new Promise(resolve => {\n db.checkAliasId(alias,function(error,data){\n if(error){\n resolve(false);\n }\n if(data){ \n if(data.message=='FOUND'){\n resolve(true);\n }else{\n resolve(false);\n }\n }\n });\n });\n}",
"function isHostKey(key){\n Room.forEach(function(element){\n if(element[\"hostKey\"] === key){\n return \"host\";\n }\n else if(element[\"guestKey\"]===key){\n return \"guest\";\n }\n \n })\n return null;\n}",
"get dedicatedHostsSupported() {\n return this.getBooleanAttribute('dedicated_hosts_supported');\n }",
"function checkInFile(url,cb){\n fs.readFile(__dirname+'/dns-cache.txt', function (err, data) { \n\n //file not found handling\n if(err !== null && err.code === \"ENOENT\"){\n process.nextTick(function(){return cb(false)}); \n }\n\n //other errors\n else if(err !== null && err.code !== \"ENOENT\"){\n console.log(err); \n }\n\n else if(data.toString('utf-8').match(url)){ \n //find the url and return the number next to it.\n process.nextTick(function(){return cb(1)});\n }\n else{\n dnsLookUp(url,function(address){ \n var fullAddress = url+\" \"+address; //send url + ip \n process.nextTick(function(){return cb(fullAddress)});\n fs.appendFile(__dirname+'/dns-cache.txt', fullAddress+\"\\n\", function(err){\n if (err !== null){\n console.log(err);\n }\n\n });\n });\n }\n });\n}",
"async function isUsernameAvailable(username) {\n const url = `https://passport.twitch.tv/usernames/${username}?users_service=true`;\n const response = await axios.head(url);\n\n return response.status === 204;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copies over missing rates when available. | function supplementMissingRates( rates ) {
if (rates.specific_std == null) {
if ((rates.specific_type == 'Mobile' && rates.mobi_min_std != null)
|| (rates.specific_type == 'Landline' && rates.land_min_std == null && rates.mobi_min_std != null)) {
rates.specific_std = rates.mobi_min_std;
rates.specific_add5 = rates.mobi_min_add5;
rates.specific_add10 = rates.mobi_min_add10;
rates.specific_gf1 = rates.mobi_min_gf1;
rates.specific_gf2 = rates.mobi_min_gf2;
} else if ((rates.specific_type == 'Landline' && rates.land_min_std != null)
|| (rates.specific_type == 'Mobile' && rates.mobi_min_std == null && rates.land_min_std != null)) {
rates.specific_std = rates.land_min_std;
rates.specific_add5 = rates.land_min_add5;
rates.specific_add10 = rates.land_min_add10;
rates.specific_gf1 = rates.land_min_gf1;
rates.specific_gf2 = rates.land_min_gf2;
}
}
// Overwrite any missing rates.
if (rates.mobi_min_std == null && rates.land_min_std != null) {
rates.mobi_min_std = rates.land_min_std;
rates.mobi_max_std = rates.land_max_std;
rates.mobi_min_add5 = rates.land_min_add5;
rates.mobi_max_add5 = rates.land_max_add5;
rates.mobi_min_add10 = rates.land_min_add10;
rates.mobi_max_add10 = rates.land_max_add10;
rates.mobi_min_gf1 = rates.land_min_gf1;
rates.mobi_max_gf1 = rates.land_max_gf1;
rates.mobi_min_gf2 = rates.land_min_gf2;
rates.mobi_max_gf2 = rates.land_max_gf2;
} else if (rates.land_min_std == null && rates.mobi_min_std != null) {
rates.land_min_std = rates.mobi_min_std;
rates.land_max_std = rates.mobi_max_std;
rates.land_min_add5 = rates.mobi_min_add5;
rates.land_max_add5 = rates.mobi_max_add5;
rates.land_min_add10 = rates.mobi_min_add10;
rates.land_max_add10 = rates.mobi_max_add10;
rates.land_min_gf1 = rates.mobi_min_gf1;
rates.land_max_gf1 = rates.mobi_max_gf1;
rates.land_min_gf2 = rates.mobi_min_gf2;
rates.land_max_gf2 = rates.mobi_max_gf2;
}
return rates;
} | [
"fillBucket(sortedWishList){\n let bucketAmount = this.bucketTotal\n let paidWishes = []\n for(var i = 0; i < sortedWishList.length; i++){\n bucketAmount -= sortedWishList[i].wishExpense\n paidWishes.push(sortedWishList[i])\n if(bucketAmount == 0){\n console.log(\"Bucket was emptied.\")\n break\n }\n }\n for(var j = 0; j < paidWishes.length; j++){\n console.log(paidWishes[j].doneeName + \"'s wish has been paid.\")\n }\n this.bucketTotal = bucketAmount\n }",
"static async getAllRates() {\n return new Promise((resolve, reject) => {\n oxr.latest(function() {\n // You can now use `oxr.rates`, `oxr.base` and `oxr.timestamp`\n let data = {\n rates: oxr.rates,\n base: oxr.base,\n timestamp: oxr.timestamp\n };\n return resolve(data);\n });\n });\n }",
"copyKeepFactors() {\n const { keepFactor, round } = this;\n\n const prevRound = round - 1;\n\n this.continuingAndWinners.forEach((c) => {\n keepFactor[round][c] = keepFactor[prevRound][c];\n });\n }",
"ifConversionRatesAvailable() {\n return !!(\n this.initialCurrencyConversionData?.rates &&\n Object.keys(this.initialCurrencyConversionData.rates).length !== 0\n );\n }",
"burnCards(){\n //Draw a card\n const firstCard = this.drawCard();\n\n //Save the first card\n this.burnedCards.firstCard = firstCard;\n\n //If the card is 10, J, Q, K, A, draw 10 more cards. \n const val = firstCard.actualVal > 0 ? firstCard.actualVal : 10;\n\n //Draw X number of cards where X is the value of the first card\n //Save them to the burned cards array\n for(let i = 1; i <= val; i++){\n this.burnedCards.burnCards.push(this.drawCard());\n }\n }",
"function addAllCurrencies(){\r\n\tfor(k = 0; k < denominations.length; k += 1){\r\n\t\tif(usedCurrencies.includes(\"\"+k)){continue;}\r\n\t\taddCurrency(\"\"+k);\r\n\t}\r\n}",
"function fillBucket() {\n \n // Old method - kept for bug checking\n //for (var i=1;i<=numOfAvailableFeeders;i++) {\n // availableFeeders.push(i);\n //}\n\n for (var i=0; i <= currentStage.feederArrangement.length; i++) {\n if (currentStage.feederArrangement[i] == true) {\n availableFeeders.push(i+1);\n }\n }\n numOfAvailableFeeders = availableFeeders.length;\n }",
"async refreshWallets() {\n const gapLimit = 1; //after 20 empty addresse we drop out\n\n //Deposit\n for (let i = 0, consecutivelyEmpty = 0; consecutivelyEmpty < gapLimit; i++) {\n let wallet = await this.refreshWallet({derive: `m/44'/1'/0'/0/${i}`})\n if (!wallet.used) {\n consecutivelyEmpty++;\n }\n }\n //Change\n for (let i = 0, consecutivelyEmpty = 0; consecutivelyEmpty < gapLimit; i++) {\n let wallet = await this.refreshWallet({derive: `m/44'/1'/0'/1/${i}`})\n if (!wallet.used) {\n consecutivelyEmpty++;\n }\n }\n }",
"function creditAllConsumedItems() {\n var currData;\n\n for (var item in consumedItems) {\n if (consumedItems[item]) {\n currData = getPurchaseData(item);\n creditConsumedItem(item, currData.token, currData.receipt, currData.origin);\n }\n }\n}",
"getData(base, date) {\n this.currencies = [];\n \n fetch(`https://api.exchangeratesapi.io/${date}?base=${base}`)\n .then(response => response.json())\n .then(json => {\n // console.log(json);\n for (const currency in json.rates) {\n this.currencies.push(new Currency(currency));\n }\n\n // Loop through currencies and set 'buy' to 5% less than conversion.\n // Loop through currencies and set 'sell' to 5% more than conversion.\n \n this.currencies.forEach(currency => {\n currency.buy = (json.rates[currency.name] * 0.95).toFixed(4);\n currency.sell = (json.rates[currency.name] * 1.05).toFixed(4);\n });\n\n // If page is being loaded for first time, table mounts.\n // Otherwise table updates with new base of alphabet order.\n \n if (this.table.mounted === false) {\n this.table.mount(container, this.currencies);\n } else {\n this.table.updateHTML(this.currencies, this.base);\n }\n });\n }",
"function getRate(i) {\n // console.log(hotelsArr[i][\"room-rates\"][\"room-rate\"]);\n let tempRateArr = hotelsArr[i][\"room-rates\"][\"room-rate\"];\n let rateArr = new Array();\n\n if(Array.isArray(tempRateArr)) {\n for(let d=0; d < 2; d++){\n // console.log(tempRateArr[d][\"rate-breakdown\"]);\n let tempBreakdown = tempRateArr[d][\"rate-breakdown\"][\"common:rate\"][\"common:pricing-elements\"][\"common:pricing-element\"];\n tempBreakdown.forEach(function(item) {\n rateArr.push(item);\n });\n }\n } else {\n rateArr.push(tempRateArr[\"rate-breakdown\"][\"common:rate\"][\"common:pricing-elements\"][\"common:pricing-element\"]);\n }\n\n let cost = 0;\n\n rateArr.forEach(function (item) {\n cost += item[\"common:amount\"];\n });\n\n return cost.toFixed(2);\n}",
"function copyAll(){\n\t//Load the req list\n\tchrome.storage.local.get('haloreq', function(values){\n\t\thaveList = \"haloreq\" in values ? values['haloreq'] : {};\n\t\t//New list rather than dict to be passed to the copy function\n\t\tfullList = [];\n\t\t//Only if there is a subcategory (Basically making sure it was already parsed)\n\t\tif (Object.keys(haveList).length >= 1){\n\t\t\t//For each subcategory\n\t\t\tfor (key in haveList){\n\t\t\t\t//Push a header like \"Armor -----------\" tab separated for easy spreadsheet pasting!\n\t\t\t\tfullList.push((key in prettyNames ? prettyNames[key] : key) + \"\\t-------------------\\n\");\n\t\t\t\t//For each req in that subcategory\n\t\t\t\tfor (var i = 0; i < haveList[key].length; i++){\n\t\t\t\t\t//Push it to the list as \"id name\"\n\t\t\t\t\tfullList.push(haveList[key][i][0] + \"\\t\" + haveList[key][i][1] + \"\\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t\t//Copy the entire list to the clipboard\n\t\t\tcopy(fullList);\n\t\t}else{\n\t\t\t//List was empty, most likely didn't scan first\n\t\t\tchrome.notifications.create({'type':'basic','iconUrl':'icon-48.png','title':'Sorry!','message':'No requisitions found. Try parsing again.'});\n\t\t}\n\t});\n\t\n}",
"function _createCopySchedules(data) {\r\n var info = JSON.parse(data);\r\n $(\"body\").css(\"cursor\", \"default\");\r\n copyConflictSchedules = info[\"schedules\"];\r\n\r\n // Display conflicts if any and remove them from list of schedules to be\r\n // rendered if user does not want to add them.\r\n var availabilities = info['availability'];\r\n if (Object.getOwnPropertyNames(availabilities).length > 0) {\r\n _copyConflicts(availabilities);\r\n } else {\r\n renderCopiedSchedules()\r\n }\r\n\r\n // Update cost display to reflect any cost changes\r\n if (info[\"cost_delta\"]) {\r\n updateHoursAndCost(info[\"cost_delta\"]);\r\n reRenderAllCostsHours();\r\n }\r\n }",
"CHANGE_PRICES(state) {\n // use a forEach() because it's an array\n // otherwise if it was an object you'd for(x in y)\n state.stocks.forEach(stock => {\n // doesn't make sense for the volatility to vary between a large range,\n // so it should only be a growth or shrinkage of the original price\n const min = 0.85\n const max = 1.15\n // the tried and true rand * (max - min) + min range calculation\n stock.pps = Math.round(stock.pps * (Math.random() * (max - min) + min))\n })\n }",
"function swapCurrencies() {\r\n const temp = currencyOneSymbol.value;\r\n currencyOneSymbol.value = currencyTwoSymbol.value;\r\n currencyTwoSymbol.value = temp;\r\n updateRate();\r\n}",
"_adjustQPs(superData) {\n const superDataRef = superData;\n\n if ('page' in superDataRef) {\n delete superDataRef.page;\n }\n\n if ('size' in superDataRef) {\n delete superDataRef.size;\n }\n\n if ('rating' in superDataRef) {\n set(superDataRef, 'rating__eq', superDataRef.rating);\n delete superDataRef.rating;\n }\n\n if ('fields' in superDataRef && !isEmpty(superDataRef.fields)) {\n set(superDataRef, 'fields', superDataRef.fields.join(','));\n }\n\n return superDataRef;\n }",
"function getInitialPrices(){\n\n\t$.getJSON(\"https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD,EUR,GBP,JPY,KRW,INR,ETH,LTC\", function(data) {\n\t // Collect the data in the BTCPRICES variable\n\t Object.assign(BTCPRICES, data);\n\t // Update the prices to the website\n\t updatePrices();\n\t updateTables();\n\t // Update the autocomplete options\n\t updateAutocomplete();\n\t // Do an inital conversion for the default value in the left box\n\t calculateConversion(\"right\");\n\t updateSummary();\n\t updateTime();\n\t // Get all the other coins\n\t getCoins();\n\t\t});\n}",
"copy() {\n if (this.era) return new $625ad1e1f4c43bc1$export$ca871e8dbb80966f(this.calendar, this.era, this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);\n else return new $625ad1e1f4c43bc1$export$ca871e8dbb80966f(this.calendar, this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);\n }",
"function init() {\n utilsService.addDropdownOptions('from-currency', availableCurrencies);\n document.getElementById('amount').value = defaultAmount;\n getRates(selectedBase);\n}",
"function mergeWallets(wallet1, wallet2) {\n let mergedWallet = copyWallet(wallet1)\n for (let bill in wallet2) {\n if (wallet2[bill] != 0) {\n mergedWallet[bill] = wallet2[bill]\n }\n }\n return mergedWallet\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unrolls given node until total number of nodes reach the given limit | function unrollNodeUptoLimit(node, limit) {
if (limit < 0) {
return limit;
}
// Current node is not a repeated node, unroll its children
if (!node.repeat || !node.repeat.count) {
return unrollChildrenUptoLimit(node, limit);
}
// Curent node is a repeated node.
// Make clones of it, unroll its children and append the clones to the parent.
// If Current node is a group, then append its children to the parent instead
for (let i = 0; i < node.repeat.count; i++) {
if (limit <= 0) {
break;
}
const clone = node.clone(true);
clone.repeat.value = i+1;
limit = unrollChildrenUptoLimit(clone, limit);
if (clone.isGroup) {
while (clone.children.length > 0) {
clone.firstChild.repeat = clone.repeat;
node.parent.insertBefore(clone.firstChild, node);
}
} else {
node.parent.insertBefore(clone, node);
}
}
node.parent.removeChild(node);
return limit;
} | [
"function unrollChildrenUptoLimit(node, limit) {\n\tif (!node.isGroup) {\n\t\tlimit--;\n\t}\n\tif (node.children) {\n\t\t// Make a copy of the children before unrolling as more might get added during unrolling\n\t\tvar nodeChildren = node.children.slice();\n\t\tfor (var i = 0; i < nodeChildren.length; i++) {\n\t\t\tif (limit > 0) {\n\t\t\t\tlimit = unrollNodeUptoLimit(nodeChildren[i], limit);\n\t\t\t} else {\n\t\t\t\tnode.removeChild(nodeChildren[i]);\n\t\t\t}\n\t\t}\n\t}\n\treturn limit;\n}",
"setupLoop(n) {\n const loopTo = this.kToLast2(n);\n if(loopTo === null){\n return loopTo;\n }\n let current = loopTo;\n while(current && current.next){\n current = current.next;\n }\n if(current === loopTo){\n return null;\n }\n current.next = loopTo;\n return this;\n\n }",
"cutTail () {\n // while we have duplicated node targets, remove not targeted node from chain one by one\n while ( this.hasDuplicatedTargets() ) {\n this.nodes = this.nodes.filter( node => {\n return ~this.targets.indexOf( node.index )\n });\n this.refreshTargets();\n }\n }",
"function looperRecursive(n){\n if (n < 0) {\n return console.log(\"finished\");\n } else {\n console.log(n--);\n looperRecursive(n);\n }\n}",
"function nodesReach(x, i) {\n if (x instanceof go.Link) {\n x.toNode.highlight = i;\n nodesReach(x.toNode, i + 1);\n } else {\n x.findNodesOutOf().each(function (node) {\n if (node.highlight === 0 || node.highlight > i) {\n node.highlight = i;\n nodesReach(node, i + 1);\n }\n });\n }\n}",
"function dfsIterative(outfile, source_URL_Index, limit, fake_internet, fake_names)\r\n{\t\r\n\t//************the starting spot*************\t\r\n\tvar current_node = fake_internet[source_URL_Index];\r\n\tvar collection_object = new Graph_collection(outfile, current_node.URL,\"DFS\", []);\r\n\tcurrent_node.parent = -1; // source node parent is not in the array\r\n\tcollection_object.graph_Node_Container.push(current_node); //now the souce node is at index 0\r\n\t\r\n\twhile(collection_object.graph_Node_Container.length < limit)\r\n\t{\r\n\t\tvar next_node = dfs_get_next_node(collection_object, fake_internet, fake_names); // helper funciton with random choice and error handling\r\n\t\tif(next_node != 0) // catches a complete search if somehow there are less nodes than the limit \r\n\t\t{\r\n\t\t\tcollection_object.graph_Node_Container.push(next_node);\r\n\t\t\t//console.log(\"*\");\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\t\r\n\treturn collection_object;\r\n}",
"function restrictFriendsFromTo(start, end) {\n const timeoutInterval = 5000;\n setTimeout(() => {\n if (start < end) {\n restrictFriendAtIndex(start);\n restrictFriendsFromTo(start + 1, end)\n }\n }, timeoutInterval);\n}",
"function limit(binaryFunction, limit){\n\tvar round = 0;\n\treturn function (first, second){\n\t\tif (round < limit){\n\t\t\tround += 1;\n\t\t\treturn binaryFunction(first, second);\n\t\t};\n\t}\n\treturn undefined;\n}",
"function fiveMultiples(arr,start)\r\n{\r\n \r\n if((start*5)<=100) // creating multiples of 5 till '100'\r\n {\r\n \r\n arr.push(start*5);\r\n \r\n return fiveMultiples(arr,start+1); //recursive loop to keep creating multiples of 5 \r\n }\r\n\r\n else\r\n {\r\n return arr;\r\n }\r\n \r\n}",
"function RollingMin(WindowSize)// generator\r\n{\r\n var DequeIndex=[],DequeValue=[],CurrentIndex=0,T=WindowSize;\r\n function atEveryStepDo(CurrentValue)\r\n {\r\n if ( DequeIndex.length!==0 && DequeIndex[0] <= CurrentIndex - T ) \r\n {\r\n DequeIndex.shift();\r\n DequeValue.shift();\r\n }\r\n //Head is too old, it is leaving the window\r\n \r\n while ( DequeValue.length!==0 && DequeValue[DequeValue.length-1] > CurrentValue )\r\n {\r\n DequeIndex.pop();\r\n DequeValue.pop();\r\n }\r\n //remove elements that have no chance to become minimum in the window\r\n \r\n DequeIndex.push(CurrentIndex); \r\n DequeValue.push(CurrentValue); \r\n CurrentIndex++;\r\n return DequeValue[0] //Head value is minimum in the current window\r\n }\r\n atEveryStepDo.setWindowSize=function(WindowSize){T=WindowSize};\r\n atEveryStepDo.reset=function(){DequeIndex.splice(0,DequeIndex.length);DequeValue.splice(0,DequeValue.length);CurrentIndex=0;};\r\n return atEveryStepDo;\r\n}",
"function addLimiterToLoopNodes(limiterParentNode, limiterStartParentNode, limiterEndParentNode, limiterStartElement, limiterEndElement, limitedRegionCapacity, checkPreviousIteration, thresholdDelay) {\n if (checkPreviousIteration === undefined) {\n checkPreviousIteration = false;\n }\n if (thresholdDelay === undefined) {\n thresholdDelay = false;\n }\n // Sanity check that limiterElement's block parent == node\n if (isComponentOrFunctionNode(limiterStartParentNode) || isComponentOrFunctionNode(limiterEndParentNode))\n return;\n if (!limiterStartParentNode.hasOwnProperty(\"limiter_start_objects\")) {\n limiterStartParentNode[\"limiter_start_objects\"] = [];\n limiterStartParentNode[\"limiter_start_objects_map_by_startpoint\"] = {};\n }\n if (!limiterEndParentNode.hasOwnProperty(\"limiter_end_objects\")) {\n limiterEndParentNode[\"limiter_end_objects\"] = {};\n }\n // doesLimiterExist finds a limiter that starts and ends at the exact same places, and updates the capacity to the lower between two options\n // Returns true if a duplicate limiter is found/updated\n if (doesLimiterExist(limiterStartParentNode, limiterEndParentNode, limiterStartElement, limiterEndElement, limitedRegionCapacity))\n return;\n let limiterStartObject = {};\n let limiterEndObject = {};\n limiterStartObject[\"is_limiter_start\"] = true;\n limiterStartObject['id'] = limiterStartElement.id;\n limiterEndObject[\"is_limiter_start\"] = false;\n limiterEndObject['id'] = limiterEndElement.id;\n limiterStartObject[\"limiter_parent_id\"] = limiterParentNode.id;\n limiterEndObject[\"limiter_parent_id\"] = limiterParentNode.id;\n limiterStartObject[\"check_prev_iter\"] = checkPreviousIteration;\n limiterEndObject[\"check_prev_iter\"] = checkPreviousIteration;\n limiterStartObject[\"threshold_delay\"] = thresholdDelay;\n limiterEndObject[\"threshold_delay\"] = thresholdDelay;\n // Limiter start needs to know the ID of the limiter end, to gather endpoint encounter data \n limiterStartObject[\"limiter_end_node_id\"] = limiterEndParentNode.id;\n limiterStartObject[\"limiter_end_id\"] = limiterEndElement.id; // To find the correct element in the limiter_end_objects hash\n // Limiter end needs to know the ID of the limiter start, to see if there is a new start encounter it needs to address\n limiterEndObject[\"limiter_start_node_id\"] = limiterStartParentNode.id;\n limiterEndObject[\"limiter_start_id\"] = limiterStartElement.id; // To find the correct element in the limiter_end_objects hash\n limiterStartObject[\"partition_start\"] = limiterStartElement.start;\n limiterEndObject[\"partition_start\"] = limiterEndElement.start;\n limiterStartObject[\"limited_region_capacity\"] = limitedRegionCapacity;\n limiterStartObject[\"limited_region_num_threads\"] = 0; // Initialize to zero, every encounter of the limited region start should increment this\n // Not sure if this is necessary:\n // I don't love this name\n limiterStartObject[\"partition_start_encounters\"] = [];\n limiterEndObject[\"partition_start_encounters\"] = [];\n if (limiterStartParentNode.id == limiterEndParentNode.id) {\n // Limiter is within the same node\n // Can calculate its latency\n limiterStartObject[\"latency\"] = parseInt(limiterEndElement.start) - parseInt(limiterStartElement.start);\n }\n else {\n limiterStartObject[\"latency\"] = parseInt(limiterStartParentNode.latency) - parseInt(limiterStartElement.start);\n }\n if (limiterStartObject.latency < 0)\n limiterStartObject.latency = 0;\n limiterStartParentNode.limiter_start_objects.push(limiterStartObject);\n if (!limiterStartParentNode.limiter_start_objects_map_by_startpoint.hasOwnProperty(limiterStartElement.start))\n limiterStartParentNode.limiter_start_objects_map_by_startpoint[limiterStartElement.start] = [];\n limiterStartParentNode.limiter_start_objects_map_by_startpoint[limiterStartElement.start].push(limiterStartObject);\n limiterEndParentNode.limiter_end_objects[limiterEndElement.id] = limiterEndObject;\n // Sort limiter objects by partition_start value\n sortArray(limiterStartParentNode.limiter_start_objects, \"partition_start\");\n}",
"function looptoNumber (limit) {\n for (var i = 0; i<limit; i++) {\n console.log(i);\n }\n}",
"throttle (n) {\n return throttle(n, this)\n }",
"function SkipQueue(base, maxLevel) {\r\n this.base = base;\r\n this.maxLevel = maxLevel;\r\n this.levelUpOdds = 1 / this.base;\r\n\r\n this.level = this.maxLevel;\r\n this.next = [];\r\n this.size = 0; \r\n this.prevs = [];\r\n}",
"function postProcessLimiters(node) {\n if (isComponentOrFunctionNode(node))\n return;\n // Do the first if statement for both starts/ends\n let allObjects = [];\n if (node.hasOwnProperty(\"limiter_start_objects\"))\n allObjects = allObjects.concat(node.limiter_start_objects);\n if (node.hasOwnProperty(\"limiter_end_objects\")) {\n let limiter_end_objects_values = Object.keys(node.limiter_end_objects).map(function (key) {\n return node.limiter_end_objects[key];\n });\n allObjects = allObjects.concat(limiter_end_objects_values);\n }\n if (allObjects.length > 0) {\n let implicitLimiterDetails = [];\n sortArray(allObjects, \"partition_start\");\n if (parseInt(allObjects[0].partition_start) != 0) {\n implicitLimiterDetails.push(createImplicitLimiterDetailNode(0, allObjects[0].partition_start));\n }\n for (let i = 0; i < allObjects.length; i++) {\n // Create implicit limiters between stallable points of the block\n if (i == allObjects.length - 1) {\n if (allObjects[i].partition_start != node.latency)\n // Don't create something that spans the whole block - why not? avoid duplicates? I'll add a duplicate checker to addLimiterToNode\n // Don't create a probe (start end at the same point)\n implicitLimiterDetails.push(createImplicitLimiterDetailNode(allObjects[i].partition_start, node.latency));\n //createImplicitLimiter(node, node, node.limiter_start_objects[i].partition_start, node.latency);\n }\n else {\n if (allObjects[i].partition_start != allObjects[i + 1].partition_start)\n implicitLimiterDetails.push(createImplicitLimiterDetailNode(allObjects[i].partition_start, allObjects[i + 1].partition_start));\n //createImplicitLimiter(node, node, node.limiter_start_objects[i].partition_start, node.limiter_start_objects[i+1].partition_start);\n }\n }\n // Actually add the limiters\n for (let i = 0; i < implicitLimiterDetails.length; i++) {\n let implicitLimiterStart = implicitLimiterDetails[i].start;\n let implicitLimiterEnd = implicitLimiterDetails[i].end;\n //if (node.interleaving > 1) createImplicitLimiter(node, node, parseInt(implicitLimiterStart), parseInt(implicitLimiterEnd), -1, true);\n //else \n createImplicitLimiter(node, node, parseInt(implicitLimiterStart), parseInt(implicitLimiterEnd));\n }\n }\n // if (node.hasOwnProperty(\"limiter_start_objects\")) {\n // let implicitLimiterDetails = [];\n // let nodeLimiterStartObjectLength = node.limiter_start_objects.length;\n // if (parseInt(node.limiter_start_objects[0].partition_start) != 0) {\n // implicitLimiterDetails.push(createImplicitLimiterDetailNode(0, node.limiter_start_objects[0].partition_start));\n // } \n // for (let i = 0; i < nodeLimiterStartObjectLength; i++) {\n // // Create implicit limiters between stallable points of the block\n // if (i == node.limiter_start_objects.length - 1 ) {\n // if (parseInt(node.limiter_start_objects[i].partition_start) != 0 && node.limiter_start_objects[i].partition_start != node.latency)\n // // Don't create something that spans the whole block - why not?\n // // Don't create a probe (start end at the same point)\n // implicitLimiterDetails.push(createImplicitLimiterDetailNode(node.limiter_start_objects[i].partition_start, node.latency ));\n // //createImplicitLimiter(node, node, node.limiter_start_objects[i].partition_start, node.latency);\n // } else {\n // if (node.limiter_start_objects[i].partition_start != node.limiter_start_objects[i+1].partition_start) \n // implicitLimiterDetails.push(createImplicitLimiterDetailNode(node.limiter_start_objects[i].partition_start, node.limiter_start_objects[i+1].partition_start )); \n // //createImplicitLimiter(node, node, node.limiter_start_objects[i].partition_start, node.limiter_start_objects[i+1].partition_start);\n // }\n // } \n // // Actually add the limiters\n // for (let i = 0; i < implicitLimiterDetails.length; i++) {\n // let implicitLimiterStart = implicitLimiterDetails[i].start;\n // let implicitLimiterEnd = implicitLimiterDetails[i].end;\n // createImplicitLimiter(node, node, parseInt(implicitLimiterStart), parseInt(implicitLimiterEnd));\n // } \n // }\n // Find the closest start point before each end point, within the same node\n if (node.hasOwnProperty(\"limiter_end_objects\")) {\n let limiter_end_objects_values = Object.keys(node.limiter_end_objects).map(function (key) {\n return node.limiter_end_objects[key];\n });\n limiter_end_objects_values.forEach(function (endObject) {\n let lastStartPoint = 0;\n let lastStartLimiterID = \"\";\n if (node.hasOwnProperty(\"limiter_start_objects\")) {\n for (let i = 0; i < node.limiter_start_objects.length; i++) {\n if (parseInt(node.limiter_start_objects[i].partition_start) > parseInt(endObject.partition_start) && i > 0) {\n lastStartPoint = node.limiter_start_objects[i - 1].partition_start;\n lastStartLimiterID = node.limiter_start_objects[i - 1].id;\n break; // Found the last start point\n }\n // If a stall point is equal to the end point, then it should use it\n if (parseInt(node.limiter_start_objects[i].partition_start) == parseInt(endObject.partition_start)) {\n lastStartPoint = node.limiter_start_objects[i].partition_start;\n lastStartLimiterID = node.limiter_start_objects[i].id;\n break; // Found the last start point\n }\n }\n }\n let distanceFromLastStartPoint = parseInt(endObject.partition_start) - parseInt(lastStartPoint);\n endObject[\"distance_from_last_start_point\"] = distanceFromLastStartPoint;\n endObject[\"last_start_point\"] = lastStartPoint; //lastStartLimiterID; // If this value is empty, use the node's start point\n });\n }\n}",
"function drop(xs, n) /* forall<a> (xs : list<a>, n : int) -> list<a> */ { tailcall: while(1)\n{\n if ($std_core._int_le(n,0)) {\n return xs;\n }\n else {\n if (xs == null) {\n return Nil;\n }\n else {\n {\n // tail call\n var _x17 = $std_core._int_sub(n,1);\n xs = xs.tail;\n n = _x17;\n continue tailcall;\n }\n }\n }\n}}",
"function fiveMultiple(arr,start,end)\r\n{\r\n if (start > end)\r\n {\r\n return arr; // if the array is done looping from 1 to 10, return the array\r\n }\r\n if((inputtable[start]*5)<=51) // set of multiples between 1 and 51\r\n {\r\n arr.push(inputtable[start]*5); // add the multiple of 5 into the array\r\n return fiveMultiple(arr,start+1,end); // recursion to loop again\r\n }\r\n else\r\n {\r\n return arr; // redundant check\r\n } \r\n}",
"function eulerProblem1(limit) {\n let sum = 0;\n let multiples = [];\n for (let i = 1; i < limit; i++) {\n if (i%3 === 0 || i%5 === 0) {\n multiples.push(i); // add the multiple to the array list\n sum += i;\n }\n }\n multiples.unshift(sum); // add solution to position 0\n return multiples;\n}",
"function rotateConnections(node) {\n\tvar timeout = 5;\n\twhile (node.connections.substring(0, 2) != \"01\" && timeout > 0) {\n\t\ttimeout -= 1;\n\t\tnode.connections = node.connections[3] + node.connections.substring(0, 3);\n\t\t//for auto-solving\n\t\tnode.rotation -= Math.PI / 2;\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a grapheme cluster end _after_ (not equal to) `pos`, if / possible. Moves across surrogate pairs, extending characters, / characters joined with zerowidth joiners, and flag emoji. | function nextClusterBreak(str, pos) {
if (pos == str.length)
return pos;
// If pos is in the middle of a surrogate pair, move to its start
if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1)))
pos--;
let prev = codePointAt(str, pos);
pos += codePointSize(prev);
while (pos < str.length) {
let next = codePointAt(str, pos);
if (prev == ZWJ || next == ZWJ || isExtendingChar(next)) {
pos += codePointSize(next);
prev = next;
}
else if (isRegionalIndicator(next)) {
let countBefore = 0, i = pos - 2;
while (i >= 0 && isRegionalIndicator(codePointAt(str, i))) {
countBefore++;
i -= 2;
}
if (countBefore % 2 == 0)
break;
else
pos += 2;
}
else {
break;
}
}
return pos;
} | [
"static getLastCharactersToPos(writer, pos) {\r\n const writerLength = writer.getLength();\r\n const charCount = writerLength - pos;\r\n const chars = new Array(charCount);\r\n writer.iterateLastChars((char, i) => {\r\n const insertPos = i - pos;\r\n if (insertPos < 0)\r\n return true; // exit iterating\r\n chars[insertPos] = char;\r\n return undefined;\r\n });\r\n return chars.join(\"\");\r\n }",
"textAfterPos(pos) {\n var _a, _b;\n let sim = (_a = this.options) === null || _a === void 0 ? void 0 : _a.simulateBreak;\n if (pos == sim && ((_b = this.options) === null || _b === void 0 ? void 0 : _b.simulateDoubleBreak))\n return \"\";\n return this.state.sliceDoc(pos, Math.min(pos + 100, sim != null && sim > pos ? sim : 1e9, this.state.doc.lineAt(pos).to));\n }",
"wordAt(pos) {\n let { text, from, length } = this.doc.lineAt(pos)\n let cat = this.charCategorizer(pos)\n let start = pos - from,\n end = pos - from\n while (start > 0) {\n let prev = findClusterBreak(text, start, false)\n if (cat(text.slice(prev, start)) != dist_CharCategory.Word) break\n start = prev\n }\n while (end < length) {\n let next = findClusterBreak(text, end)\n if (cat(text.slice(end, next)) != dist_CharCategory.Word) break\n end = next\n }\n return start == end\n ? null\n : EditorSelection.range(start + from, end + from)\n }",
"getChar(pos) {\n return this.document.getText(new vscode.Range(pos, pos.translate(0, 1)));\n }",
"function chessPosition( posText ) {\r\n\t// A position in a chess game - used in conjunction with a move history\r\n\t// and therefore not requiring flags for castling, en-passant, 50 move\r\n\t// position is 8 strings of 8 chars:\r\n\t// KQRBNP for white pieces, kqrbnp for black, other for blank\r\n\t// If argument is a chess position (not text) it is cloned\r\n\tout = new Object\r\n\tif ( !posText ) posText = defaultPosition\r\n\tout.toMove = 0\r\n\tfor (var j=0; j<8; j++) {\r\n\t var posRow = posText[ j ]\r\n\t for (var i=0; i<posRow.length; i++) {\r\n\t\tvar c = posRow.charAt( i )\r\n\t\tif ( \"PpBbNnRrKkQq\".indexOf( c ) > -1 ) {\r\n\t\t out[ [ i , j ] ] = c\r\n\t }\t} }\r\n\t// See if there's any info beyond board rows...\r\n\tif ( posText.length > 8 ) {\r\n\t\t// Look for indicator of whose move it is\r\n\t\t// Actually - if last line mentions black and not white,\r\n\t\t//\tmake it black's turn, otherwise leave it as white's.\r\n\t\tif (\t( posText[ -1 ].toLowerCase().indexOf( 'black' ) > -1 ) &&\r\n\t\t\t( posText[ -1 ].toLowerCase().indexOf( 'white' ) == -1 ) )\r\n\t\t\t\tout.toMove = 1\r\n\t\t}\r\n\treturn out\r\n\t}",
"childAfter(pos) {\n return this.enterChild(1, pos, 2 /* Side.After */)\n }",
"buildHighlightPosition (position, linenum, text) {\n var remainingCharacters = position;\n let lines = text.split(\"\\n\");\n\n // Iterate until we get to the position of the character we need, and then build\n // a relative vscode.Position.\n for (var i = 0; i < lines.length; i++) {\n let charactersInLine = lines[i].length + 1; // +1 for the newline.\n\n if (remainingCharacters - charactersInLine < 0) {\n return new vscode.Position(linenum - 1, remainingCharacters);\n }\n\n remainingCharacters = remainingCharacters - charactersInLine;\n }\n\n // If we get here, there's probaly a buffer mismatch.\n return undefined;\n }",
"function index_after_formatting(position) {\n\t var start = position === 0 ? 0 : position - 1;\n\t var command_len = $.terminal.length(command);\n\t for (var i = start; i < command_len - 1; ++i) {\n\t var substr = $.terminal.substring(command, 0, i);\n\t var next_substr = $.terminal.substring(command, 0, i + 1);\n\t var formatted_substr = formatting(substr);\n\t var formatted_next = formatting(next_substr);\n\t var substr_len = length(formatted_substr);\n\t var next_len = length(formatted_next);\n\t var test_diff = Math.abs(next_len - substr_len);\n\t if (test_diff > 1) {\n\t return i;\n\t }\n\t }\n\t }",
"newFacePos(oldFace, pos) {\n let row = pos[0];\n let col = pos[1];\n switch (oldFace) {\n case \"front\":\n return pos.map(co=> Util.wrap(co) );\n case \"left\":\n if(col < 0 || col > 2) {\n return [row, Util.wrap(col)];\n } else if (row < 0) {\n return [col, 0];\n } else if (row > 2) {\n return [-col + 2, 0]\n }\n else {\n return pos;\n }\n case \"right\":\n if(col < 0 || col > 2) {\n return [row, Util.wrap(col)];\n } else if (row < 0) {\n return [-col + 2, 2]\n } else if (row > 2) {\n return [col, 2]\n }\n else {\n return pos;\n }\n case \"back\":\n if(col < 0 || col > 2) {\n return [row, Util.wrap(col)];\n } else if (row < 0) {\n return [0, -col + 2]\n } else if (row > 2) {\n return [2, -col + 2]\n }\n else {\n return pos;\n }\n case \"top\":\n if(col < 0) {\n return [0, row];\n } else if (col > 2) {\n return [0, -row +2]\n }\n else if (row < 0) {\n return [0, -col + 2]\n } else if (row > 2) {\n return [0, col]\n }\n else {\n return pos;\n }\n case \"bottom\":\n if(col < 0) {\n return [2, -row +2];\n } else if (col > 2) {\n return [2, row]\n }\n else if (row < 0) {\n return [2, col]\n } else if (row > 2) {\n return [2, -col + 2]\n }\n else {\n return pos;\n }\n default:\n throw \"invalid face\";\n\n }\n }",
"mapPos(pos, assoc = -1, mode = MapMode.Simple) {\n let posA = 0, posB = 0;\n for (let i = 0; i < this.sections.length;) {\n let len = this.sections[i++], ins = this.sections[i++], endA = posA + len;\n if (ins < 0) {\n if (endA > pos)\n return posB + (pos - posA);\n posB += len;\n }\n else {\n if (mode != MapMode.Simple && endA >= pos &&\n (mode == MapMode.TrackDel && posA < pos && endA > pos ||\n mode == MapMode.TrackBefore && posA < pos ||\n mode == MapMode.TrackAfter && endA > pos))\n return -1;\n if (endA > pos || endA == pos && assoc < 0 && !len)\n return pos == posA || assoc < 0 ? posB : posB + ins;\n posB += ins;\n }\n posA = endA;\n }\n if (pos > posA)\n throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`);\n return posB;\n }",
"function deleteCharAtPos() {\n if (column < promptText.length) {\n promptText =\n promptText.substring(0, column) +\n promptText.substring(column + 1);\n restoreText = promptText;\n return true;\n } else return false;\n }",
"function getThumbnailStripBegPos(pos)\r\n{\r\n\tvar pnlimgcnt = visible_thumbnail_images-1;\r\n var pnlcnt = Math.ceil(objCase.pages.length / pnlimgcnt);\r\n beg = 0;\r\n for(var j=0; j<=pnlcnt; j++)\r\n\t{\r\n \tend = beg+pnlimgcnt;\r\n \tif(pos>=beg && pos<=end)\r\n \t\tbreak;\r\n \t\r\n \tbeg +=(pnlimgcnt+1); \t\t\r\n\t}\r\n \r\n return beg;\r\n}",
"function getCharAtPosInDiv(editableDiv, pos) {\n\t// var text = getClearTextFromDiv(editableDiv);\n\tvar text = editableDiv.textContent;\n\treturn text.charAt(pos);\n}",
"function buildCharMapIndex() {\n // Unicode Blocks\n let basicLatin = []; // Block: 00..7E; Subset: 20..7E\n let latin1 = []; // Block: 80..FF; Subset: A0..FF\n let latinExtendedA = []; // Block: 100..17F; Subset: 152..153\n let generalPunctuation = []; // Block: 2000..206F; Subset: 2018..2022\n let currencySymbols = []; // Block: 20A0..20CF; Subset: 20AC..20AC\n let privateUseArea = []; // Block: E000..F8FF; Subset: E700..E70C\n let specials = []; // Block: FFF0..FFFF; Subset: FFFD..FFFD\n for (let k of Object.keys(charMap).sort((a,b) => a-b)) {\n let v = charMap[k];\n if (v.start === null) {\n continue;\n }\n if (0x20 <= k && k <= 0x7E) {\n basicLatin[k-0x20] = v;\n } else if (0xA0 <= k && k <= 0xFF) {\n latin1[k-0xA0] = v;\n } else if (0x152 <= k && k <= 0x153) {\n latinExtendedA[k-0x152] = v;\n } else if (0x2018 <= k && k <= 0x2022) {\n generalPunctuation[k-0x2018] = v;\n } else if (0x20AC <= k && k <= 0x20AC) {\n currencySymbols[k-0x20AC] = v;\n } else if (0xE700 <= k && k <= 0xE70C) {\n privateUseArea[k-0xE700] = v;\n } else if (0xFFFD <= k && k <= 0xFFFD) {\n specials[k-0xFFFD] = v;\n }\n }\n let puaIndexStr = privateUseArea.length<1 ? '' : `\n\n// Index to Unicode Private Use Area block glyph patterns (UI sprites)\nconst PRIVATE_USE_AREA: [u16; ${privateUseArea.length}] = [\n ${privateUseArea.map(v => v.start + \", // \" + v.name).join(\"\\n \")}\n];`;\n let puaMatchStr = privateUseArea.length<1 ? '' : `\n 0xE700..=0xE70C => PRIVATE_USE_AREA[(c as usize) - 0xE700] as usize,`;\n let indexStr = `\n/// Return offset into DATA[] for start of pattern depicting glyph for character c\npub fn get_glyph_pattern_offset(c: char) -> usize {\n match c as u32 {\n 0x20..=0x7E => BASIC_LATIN[(c as usize) - 0x20] as usize,\n 0xA0..=0xFF => LATIN_1[(c as usize) - 0xA0] as usize,\n 0x152..=0x153 => LATIN_EXTENDED_A[(c as usize) - 0x152] as usize,\n 0x2018..=0x2022 => GENERAL_PUNCTUATION[(c as usize) - 0x2018] as usize,\n 0x20AC..=0x20AC => CURRENCY_SYMBOLS[(c as usize) - 0x20AC] as usize,${puaMatchStr}\n _ => SPECIALS[(0xFFFD as usize) - 0xFFFD] as usize,\n }\n}\n\n// Index to Unicode Basic Latin block glyph patterns\nconst BASIC_LATIN: [u16; ${basicLatin.length}] = [\n ${basicLatin.map(v => v.start + \", // '\" + v.chr + \"'\").join(\"\\n \")}\n];\n\n// Index to Unicode Latin 1 block glyph patterns\nconst LATIN_1: [u16; ${latin1.length}] = [\n ${latin1.map(v => v.start + \", // '\" + v.chr + \"'\").join(\"\\n \")}\n];\n\n// Index to Unicode Latin Extended A block glyph patterns\nconst LATIN_EXTENDED_A: [u16; ${latinExtendedA.length}] = [\n ${latinExtendedA.map(v => v.start + \", // '\" + v.chr + \"'\").join(\"\\n \")}\n];\n\n// Index to General Punctuation block glyph patterns\nconst GENERAL_PUNCTUATION: [u16; ${generalPunctuation.length}] = [\n ${generalPunctuation.map(v => v.start + \", // '\" + v.chr + \"'\").join(\"\\n \")}\n];\n\n// Index to Unicode Currency Symbols block glyph patterns\nconst CURRENCY_SYMBOLS: [u16; ${currencySymbols.length}] = [\n ${currencySymbols.map(v => v.start + \", // '\" + v.chr +\"'\").join(\"\\n \")}\n];${puaIndexStr}\n\n// Index to Unicode Specials block glyph patterns\nconst SPECIALS: [u16; ${specials.length}] = [\n ${specials.map(v => v.start + \", // '\" + v.chr + \"'\").join(\"\\n \")}\n];\n`;\n return indexStr.trim();\n}",
"findIndex(pos, end, side = end * Far, startAt = 0) {\n if (pos <= 0)\n return startAt;\n let arr = end < 0 ? this.to : this.from;\n for (let lo = startAt, hi = arr.length;;) {\n if (lo == hi)\n return lo;\n let mid = (lo + hi) >> 1;\n let diff = arr[mid] - pos || (end < 0 ? this.value[mid].startSide : this.value[mid].endSide) - side;\n if (mid == lo)\n return diff >= 0 ? lo : hi;\n if (diff >= 0)\n hi = mid;\n else\n lo = mid + 1;\n }\n }",
"findClusterBreak(start, forward) {\n if (start < 0 || start > this.length)\n throw new RangeError(\"Invalid position given to Line.findClusterBreak\");\n let contextStart, context;\n if (this.content == \"string\") {\n contextStart = this.from;\n context = this.content;\n }\n else {\n contextStart = Math.max(0, start - 256);\n context = this.slice(contextStart, Math.min(this.length, contextStart + 512));\n }\n return (forward ? nextClusterBreak : prevClusterBreak)(context, start - contextStart) + contextStart;\n }",
"function countPreviousSpaces(str, pos) {\r\n var spaces = 0;\r\n // check the characters before the pos one at a time, break when a nonspace char is found\r\n while(pos > spaces && /\\s/.test(str.charAt(pos-1-spaces) ) ){\r\n spaces++; // if space, increment spaces count\r\n }\r\n return spaces; // return spaces\r\n}",
"findClusterBreak(start, forward) {\n if (start < 0 || start > this.length)\n throw new RangeError(\"Invalid position given to Line.findClusterBreak\");\n let contextStart, context;\n if (this.content == \"string\") {\n contextStart = this.from;\n context = this.content;\n }\n else {\n contextStart = Math.max(0, start - 256);\n context = this.slice(contextStart, Math.min(this.length, contextStart + 512));\n }\n return (forward ? nextClusterBreak : prevClusterBreak)(context, start - contextStart) + contextStart;\n }",
"function findMarker(buf, pos) {\n for (var i = pos; i < buf.length; i++) {\n if (0xff === buf[i ] &&\n 0xe1 === buf[i+1]) {\n return i;\n }\n }\n return -1;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Amount of program data placed in each load Transaction Minimum number of signatures required to load a program not including retries Can be used to calculate transaction fees | static getMinNumSignatures(dataLength) {
return 2 * ( // Every transaction requires two signatures (payer + program)
Math.ceil(dataLength / Loader.chunkSize) + 1 + // Add one for Create transaction
1) // Add one for Finalize transaction
;
} | [
"getBakeProgress() {\n const pendingInputs = this.inputNums.length + this.loadingOutputs + this.inputs.length;\n let bakingInputs = 0;\n\n for (let i = 0; i < this.chefWorkers.length; i++) {\n if (this.chefWorkers[i].active) {\n bakingInputs++;\n }\n }\n\n const total = this.totalOutputs;\n const bakedInputs = total - pendingInputs - bakingInputs;\n\n return {\n total: total,\n pending: pendingInputs,\n baking: bakingInputs,\n baked: bakedInputs\n };\n }",
"function calculateTaskCompletionRate(data) \n{\n completion_details = {\n average : 0,\n longest : 0,\n shortest : Infinity\n };\n\n return completion_details\n}",
"function calculateSprintsRequired() {\n var feUnits = 0;\n var csUnits = 0;\n var ssUnits = 0;\n\n for(var i = 0; i < current_employees.length; i++) {\n console.log(current_employees[i].skill);\n switch(current_employees[i].skill) {\n case \"FrontEnd\":\n feUnits += current_employees[i].units;\n break;\n case \"ServerSide\":\n ssUnits += current_employees[i].units;\n break;\n case \"ClientSide\":\n csUnits += current_employees[i].units;\n break;\n }\n }\n\n var feSprints = Math.ceil(active_project.frontReq / feUnits);\n var csSprints = Math.ceil(active_project.clientReq / csUnits);\n var ssSprints = Math.ceil(active_project.serverReq / ssUnits);\n console.log(\"FE: \" + feUnits + \" / \" + feSprints + \" \\n\" +\n \"CS: \" + csUnits + \" / \" + csSprints + \" \\n\" +\n \"SS: \" + ssUnits + \" / \" + ssSprints + \" \\n\"\n );\n return Math.max(feSprints, csSprints, ssSprints);\n}",
"requestedSalaryIsLessThanMin(application) {\n return application.posted_salary_min && \n application.requested_salary && \n application.posted_salary_min > application.requested_salary;\n }",
"async function checkSystemFee() {\n const invokeFunctionResponse = await rpcClient.invokeScript(\n u.HexString.fromHex(vars.tx.script),\n [\n {\n account: inputs.fromAccount.scriptHash,\n scopes: tx.WitnessScope.CalledByEntry,\n },\n ]\n );\n if (invokeFunctionResponse.state !== \"HALT\") {\n throw new Error(\n `Transfer script errored out: ${invokeFunctionResponse.exception}`\n );\n }\n const requiredSystemFee = u.BigInteger.fromNumber(\n invokeFunctionResponse.gasconsumed\n );\n if (inputs.systemFee && inputs.systemFee >= requiredSystemFee) {\n vars.tx.systemFee = u.BigInteger.fromNumber(inputs.systemFee);\n console.log(\n ` i Node indicates ${requiredSystemFee} systemFee but using user provided value of ${inputs.systemFee}`\n );\n } else {\n vars.tx.systemFee = requiredSystemFee;\n }\n console.log(\n `\\u001b[32m ✓ SystemFee set: ${vars.tx.systemFee.toDecimal(8)}\\u001b[0m`\n );\n}",
"async function checkNetworkFee() {\n const feePerByteInvokeResponse = await rpcClient.invokeFunction(\n CONST.NATIVE_CONTRACT_HASH.PolicyContract,\n \"getFeePerByte\"\n );\n\n if (feePerByteInvokeResponse.state !== \"HALT\") {\n if (inputs.networkFee === 0) {\n throw new Error(\"Unable to retrieve data to calculate network fee.\");\n } else {\n console.log(\n \"\\u001b[31m ✗ Unable to get information to calculate network fee. Using user provided value.\\u001b[0m\"\n );\n vars.tx.networkFee = u.BigInteger.fromNumber(inputs.networkFee);\n }\n }\n const feePerByte = u.BigInteger.fromNumber(\n feePerByteInvokeResponse.stack[0].value\n );\n // Account for witness size\n const transactionByteSize = vars.tx.serialize().length / 2 + 109;\n // Hardcoded. Running a witness is always the same cost for the basic account.\n const witnessProcessingFee = u.BigInteger.fromNumber(1000390);\n const networkFeeEstimate = feePerByte\n .mul(transactionByteSize)\n .add(witnessProcessingFee);\n if (inputs.networkFee && inputs.networkFee >= networkFeeEstimate.toNumber()) {\n vars.tx.networkFee = u.BigInteger.fromNumber(inputs.networkFee);\n console.log(\n ` i Node indicates ${networkFeeEstimate.toDecimal(\n 8\n )} networkFee but using user provided value of ${inputs.networkFee}`\n );\n } else {\n vars.tx.networkFee = networkFeeEstimate;\n }\n console.log(\n `\\u001b[32m ✓ Network Fee set: ${vars.tx.networkFee.toDecimal(\n 8\n )} \\u001b[0m`\n );\n}",
"function last_chunk_size(lastreq) {\n let tot = 0;\n for (let tt = 0; tt < lastreq.trace.length; tt++) {\n tot = tot + lastreq.trace[tt].b[0];\n }\n return tot;\n }",
"async totalClaimable(){\n try {\n let claimable = await this._contract.claimAmount({\n user: this._accountId\n })\n return utils.format.formatNearAmount(claimable)\n } catch (error) {\n console.log(error)\n return 0 \n }\n }",
"minAmount() {\n if (this.props.marketPairData.minimum) {\n return this.props.marketPairData.minimum;\n } else return 0;\n }",
"function sumAllInstallments(){\n\tvar instlCount=$(\"#feeInstallments\").val();\n\tfor ( var i = 0; i < instlCount; i++) {\n\t\tvar instlSum=0;\n\t\tfor ( var headCount = 0; headCount < feeHeadCount; headCount++) {\n\t\t\tvar amt= jQuery.trim($(\"#feeHeads_\"+headCount+\"_installments_\"+i+\"_amount\").val());\n\t\n\t\t\tif(!isNaN(amt) && amt.length!=0) {\n\t\t\t\tinstlSum += parseInt(amt);\n\t\t\t}\n }\n\t\t$(\"#inst_col_\"+i+\"_total\").html(instlSum);\n\t}\n\tbindAdminInstallmentDueDatePicker();\n\tvalidateInstallmentsFee();\n}",
"function sumLinePerSubtab(type,lineExc)\r\n{\r\n var count = nlapiGetLineItemCount('custpage_svb_dist_details');\r\n var arrAllocWtAllLines = [];\r\n var arrAllocAmtAllLines = []\r\n \r\n for(var i=1; count && i<=count; i++)\r\n {\r\n var intLineNo = nlapiGetLineItemValue('custpage_svb_dist_details','custpage_svb_details_line_number',i);\r\n var intTab = nlapiGetLineItemValue('custpage_svb_dist_details','custpage_svb_details_sublisttype',i);\r\n var fAllocWt = nlapiGetLineItemValue('custpage_svb_dist_details','custpage_svb_details_allocation_weight',i);\r\n fAllocWt = Math.round((parseFloat(fAllocWt)/100) * 100000)/100000;\r\n var fAllocAmt = nlapiGetLineItemValue('custpage_svb_dist_details','custpage_svb_details_amount_fx',i);\r\n var fTotalLineAmt = nlapiGetLineItemValue('custpage_svb_dist_details','custpage_svb_details_line_amount',i);\r\n \r\n //array for allocation weight\r\n if (arrAllocWtAllLines[intTab + '-' + intLineNo + '-' + fTotalLineAmt] == null || arrAllocWtAllLines[intTab + '-' + intLineNo + '-' + fTotalLineAmt] == undefined) \r\n {\r\n arrAllocWtAllLines[intTab + '-' + intLineNo + '-' + fTotalLineAmt] = [];\r\n }\r\n arrAllocWtAllLines[intTab + '-' + intLineNo + '-' + fTotalLineAmt].push(fAllocWt);\r\n \r\n //array for allocation amount\r\n if (arrAllocAmtAllLines[intTab + '-' + intLineNo + '-' + fTotalLineAmt] == null || arrAllocAmtAllLines[intTab + '-' + intLineNo + '-' + fTotalLineAmt] == undefined) \r\n {\r\n arrAllocAmtAllLines[intTab + '-' + intLineNo + '-' + fTotalLineAmt] = [];\r\n arrAllocAmtAllLines[intTab + '-' + intLineNo + '-' + fTotalLineAmt].push(0.00);\r\n }\r\n arrAllocAmtAllLines[intTab + '-' + intLineNo + '-' + fTotalLineAmt].push(fAllocAmt); \r\n }\r\n \r\n return [arrAllocAmtAllLines,arrAllocWtAllLines];\r\n}",
"proofOfWork(difficulty,pendingTransactions) {\n //TODO\n let nonce = 0\n let prevHash = this.chain.length !== 0 ? this.chain[this.chain.length - 1].hash : '0';\n let hash = this.getHash(prevHash,pendingTransactions,nonce).toString()\n while (hash.substring(0, difficulty) !== Array(difficulty + 1).join('0')) {\n nonce++;\n hash = this.getHash(prevHash,pendingTransactions,nonce);\n }\n return nonce;\n }",
"function countSuitsBlazerMwfPlus() {\n\t\t\tinstantObj.noOfSuitsBlazerMWF = instantObj.noOfSuitsBlazerMWF + 1;\n\t\t\tcountTotalBill();\n\t\t}",
"function getLeastCoins(n) {\n const coins = [25, 10, 5, 1];\n let res = [];\n\n let remain = n;\n for ( let c = 0; c < coins.length; c++) {\n let quotient = Math.floor(remain / coins[c]);\n remain = remain - quotient * coins[c];\n\n res.push(quotient);\n }\n\n let count = 0;\n for (let i = 0; i < 4; i++) {\n count += res[i];\n }\n\n console.log(res);\n return count;\n}",
"getOrderMinAmount() {\n const { amount, presets } = this.getTier() || {};\n if (isNil(amount) && isNil(presets)) return 0;\n return min(isNil(amount) ? presets : [...(presets || []), amount]);\n }",
"getFreeSlotCount() {\n try {\n const result = this.parkingManager.getAvailabilityCount();\n if(result > 0) {\n console.log(`${result} slots available`);\n } else {\n console.log('Sorry, parking lot is full ');\n }\n } catch (e) {\n throw new Exception(errorMessage.PROCESSING_ERROR, e);\n }\n }",
"function getTotalSupply(callback) {\n\tvar supply = new BigNumber(0);\n\tvar options = {method: \"GET\", hostname: \"etherchain.org\", port: 443, path: \"/api/supply\"};\n\tvar req = https.request(options, function(res) {\n\t\tres.setEncoding('utf8');\n\t\tres.on('data', (data) => {\n\t\t\ttry {\n\t\t\t\tvar obj = JSON.parse(data);\n\t\t\t\tif (!obj.data || !obj.data[0] || !obj.data[0].supply) {\n\t\t\t\t\tconsole.log(\"invalid response from etherchain:\", obj);\n\t\t\t\t\tthrow new Error(\"etherchain API response doesn't contain supply\");\n\t\t\t\t}\n\t\t\t\tsupply = new BigNumber(web3.toWei(obj.data[0].supply, \"ether\"));\n\t\t\t} catch (err) {\n\t\t\t\treturn callback(err);\n\t\t\t}\n\t\t\tcallback(null, supply);\n\t\t});\n\t});\n\treq.on('error', () => {\n\t\tcallback(null, supply);\n\t});\n\treq.end();\n}",
"function getSimulationSize() {\n return Math.floor(MAX_SIZE / sizePerElection);\n } // getSimulationSize",
"function validateBillThreshold(type) {// BeforeSubmit function on vendor bill\n\tvar currentContext = nlapiGetContext(); \n\t// If the context is \"User Interface\" or \"CSV Import\".\n\tnlapiLogExecution('DEBUG', 'type '+type, 'currentContext '+currentContext.getExecutionContext());\n\tif (type == 'create' || type == 'edit') {// Validating when the record is created. \n\t\tvar createdFrom = nlapiGetFieldValue('custbody_spk_poid');\n\t\tvar vbSubs = nlapiGetFieldValue('subsidiary');\n\t\tif (createdFrom) {// If created from a purchase order.\n\t\t\t/****** Loading PO record and fetching required fields ******/\n\t\t\tvar poRec = nlapiLoadRecord('purchaseorder',createdFrom);\n\t\t\tvar poAmount = poRec.getFieldValue('total');\n\t\t\tvar poStatus = poRec.getFieldValue('status');\n\t\t\tvar currentVBAmount = parseFloat(nlapiGetFieldValue('usertotal'));\n\t\t\tnlapiLogExecution('DEBUG', 'poAmount is'+poAmount, 'poStatus'+poStatus);\n\t\t\tvar thresholdAmount = parseFloat(poAmount)+ parseFloat(poAmount/10); // Calculating the threshold amount.\n\t\t\tvar totalBillAmount = 0;\t\t\t\n\t\t\t// Creating dynamic saved search for finding other Bills for the same Purchase Order\n\t\t\tvar filter = new Array();\n\t\t\tvar column = new Array();\n\t\t\tfilter[0] = new nlobjSearchFilter('createdfrom', null, 'is', createdFrom);\n\t\t\tfilter[1] = new nlobjSearchFilter('mainline', null, 'is', 'T');\n\t\t\tif(type == 'edit') {\n\t\t\t\tfilter[2] = new nlobjSearchFilter('internalid', null, 'noneof', nlapiGetRecordId());\n\t\t\t}\n\t\t\tcolumn[0] = new nlobjSearchColumn('fxamount');\n\t\t\tvar records = nlapiSearchRecord('vendorbill', null, filter, column);\n\t\t\tif (records) {\n\t\t\t\tfor (var i = 0; i < records.length; i++) {\n\t\t\t\t\tvar vbValue = parseFloat(records[i].getValue('fxamount'));\n\t\t\t\t\ttotalBillAmount = parseFloat(totalBillAmount) + parseFloat(vbValue);\n\t\t\t\t\tnlapiLogExecution('DEBUG', 'totalBillAmount '+totalBillAmount, 'vbValue '+vbValue+ ' i '+i);\n\t\t\t\t}\n\t\t\t\tnlapiLogExecution('DEBUG', 'thresholdAmount '+thresholdAmount, 'Final Bill amnt is '+totalBillAmount+ ' currentVBAmount '+currentVBAmount);\n\t\t\t\ttotalBillAmount = parseFloat(totalBillAmount+currentVBAmount);\n\t\t\t\t// Comparing the Bill Amount and PO Amount.\t\t\t\t \n\t\t\t\tif (parseFloat(totalBillAmount) > parseFloat(thresholdAmount)) {\n\t\t\t\t\tthrow nlapiCreateError('User Defined', 'The Bill Total Amount is exceeding the 10% threshold of the PO Amount; so cannot save the Bill. Please reduce the amount to within %10 range in order to save the bill. And raise another PO for the additional Amount.');\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif(parseFloat(currentVBAmount) > parseFloat(thresholdAmount)) {\n\t\t\t\t\tthrow nlapiCreateError('User Defined', 'The Bill Total Amount is exceeding the 10% threshold of the PO Amount; so cannot save the Bill. Please reduce the amount to within %10 range in order to save the bill. And raise another PO for the additional Amount.');\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}",
"function noOfTransactions() {\n document.getElementById(\"transactions\").textContent = newBlock.transactions.length;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
todo the limts that i am giving are hard coded SHITTT console.log( let result = snail([ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25] ]); // ); sol = [ 1, 2, 3, 4, 5, 10, 15, 20, 25, 24, 23, 22, 21, 16, 11, 6, 7, 8, 9, 14, 19, 18, 17, 12, 13 ]; log(result); log(JSON.stringify(result) === JSON.stringify(sol)); for this case the fault lies in center estimation to determine if this is last cell: keep list of all cells we have looped over in memory if current cell was in memory then previous cell must be the last ?? | function snail(grid) {
if (grid.length == 1) {
return grid[0][0] ? [grid[0][0]] : [];
}
let snail = [];
let l = grid.length;
let [startR, startC] = [0, 0];
let [r, c] = [0, 0];
while (grid[r][c] !== null) {
snail.push(grid[r][c]);
let i;
// right
// we dont want to push the first value since it coinsides with the previous serial
i = c + 1;
for (i; i < l - startC; i++) {
if (grid[r][i] == null) {
// complete
return snail;
}
log("lol");
snail.push(grid[r][i]);
grid[r][i] = null;
}
c = i - 1;
// down
i = r + 1;
for (i; i < l - startR; i++) {
if (grid[i][c] == null) {
return snail;
}
log("lol");
snail.push(grid[i][c]);
grid[i][c] = null;
}
r = i - 1;
// left
// we dont want to push the first value since it coinsides with the previous serial
i = c - 1;
for (i; i > -1 + startC; i--) {
if (grid[r][i] == null) {
// complete {
return snail;
}
snail.push(grid[r][i]);
grid[r][i] = null;
}
c = i + 1; // to turn -1 to 0;
// up
i = r - 1;
log({ i, startR, c });
for (i; i > startR; i--) {
if (grid[i][c] == null) {
// complete
log("lolUP");
return snail;
}
if (i === startR && c == startC) {
continue;
}
snail.push(grid[i][c]);
grid[i][c] = null;
}
log("sadjsa");
log(snail);
r = i + 1;
[startR, startC] = [startR + 1, startC + 1];
[r, c] = [startR, startC];
}
return snail;
} | [
"function gameOfLifeBestSolution(board) {\n const boardAsLivingCellsOnly = []\n board.forEach((row, rowIndex) => {\n row.forEach((cell, columnIndex) => {\n if (cell === 1) {\n boardAsLivingCellsOnly.push([rowIndex, columnIndex])\n }\n })\n })\n const nextLiveCells = []\n const nowDeadButPotentiallyAliveCells = []\n boardAsLivingCellsOnly.forEach((livingCell) => {\n const liveCellX = livingCell[0]\n const liveCellY = livingCell[1]\n const neighborCells = [[liveCellX - 1 , liveCellY - 1], [liveCellX - 1, liveCellY], [liveCellX - 1, liveCellY + 1], [liveCellX, liveCellY - 1], [liveCellX, liveCellY + 1], [liveCellX + 1, liveCellY - 1], [liveCellX + 1, liveCellY], [liveCellX + 1, liveCellY + 1]]\n\n let liveNeighborCellCount = 0\n neighborCells.forEach((neighborCell) => {\n if (boardAsLivingCellsOnly.find(liveCell => neighborCell[0] === liveCell[0] && neighborCell[1] === liveCell[1])) {\n liveNeighborCellCount += 1\n } else {\n nowDeadButPotentiallyAliveCells.push(neighborCell)\n }\n })\n if (liveNeighborCellCount === 2 || liveNeighborCellCount === 3) {\n nextLiveCells.push(livingCell)\n }\n })\n\n nowDeadButPotentiallyAliveCells.forEach((nowDeadCell) => {\n const nowDeadCellX = nowDeadCell[0]\n const nowDeadCellY = nowDeadCell[1]\n const neighborCells = [[nowDeadCellX - 1 , nowDeadCellY - 1], [nowDeadCellX - 1, nowDeadCellY], [nowDeadCellX - 1, nowDeadCellY + 1], [nowDeadCellX, nowDeadCellY - 1], [nowDeadCellX, nowDeadCellY + 1], [nowDeadCellX + 1, nowDeadCellY - 1], [nowDeadCellX + 1, nowDeadCellY], [nowDeadCellX + 1, nowDeadCellY + 1]]\n let liveNeighborCellCount = 0\n neighborCells.forEach((neighborCell) => {\n if (boardAsLivingCellsOnly.find(liveCell => neighborCell[0] === liveCell[0] && neighborCell[1] === liveCell[1])) {\n liveNeighborCellCount += 1\n }\n })\n if (liveNeighborCellCount === 3) {\n nextLiveCells.push(nowDeadCell)\n }\n })\n\n // need to dedup\n const xyHash = {}\n const dedupedNextLiveCells = []\n nextLiveCells.forEach((cell) => {\n if (!Array.isArray(xyHash[cell[0]])) {\n xyHash[cell[0]] = [cell[1]]\n dedupedNextLiveCells.push(cell)\n } else {\n const oldValueArray = xyHash[cell[0]]\n if (!oldValueArray.includes(cell[1])) {\n const newValueArray = oldValueArray.push(cell[1])\n xyHash[cell[0]] = newValueArray\n dedupedNextLiveCells.push(cell)\n }\n }\n })\n\n return dedupedNextLiveCells\n}",
"function knapsnak(p, wt, m, n) {\n var table = new Array(n + 1);\n var i, w;\n\n for (i = 0; i <= n; i++) {\n table[i] = new Array(m + 1);\n for (w = 0; w <= m; w++) {\n if (i == 0 || w == 0) {\n table[i][w] = 0;\n } else if (wt[i] <= w) {\n // this formula use for fill the table\n table[i][w] = max(p[i] + table[i - 1][w - wt[i]], table[i - 1][w]);\n } else {\n table[i][w] = table[i - 1][w];\n }\n }\n }\n\n var x = n;\n var y = m;\n document.write(\"<br>\");\n // this code is use to chake which element we tack in form of o-1\n while (x >= 0 && y >= 0) {\n if (table[x][y] == table[x - 1][y]) {\n document.write(x + \"=0 <br>\");\n x--;\n } else {\n document.write(x + \"=1 <br>\");\n x--;\n y = y - wt[x];\n }\n }\n}",
"function getNeighbors(cell) {\n let neighbors = [];\n\n // A cells neighbors is all vertically, horizontally, and\n // diagonally adjacent cells. To find all neighbors we need to\n // iterate the 3x3 area surrounding the target cell. We can\n // accomplish this by starting our iteration one cell less than\n // the target cell, and end one cell beyond.\n let y = cell.getY() - 1\n let yBoundary = cell.getY() + 1\n\n while (y <= yBoundary) {\n\n // If the starting cell is out of bounds then we need to\n // determine which boundary is being violated. We will treat this\n // as an infinite space so the cell will switch to evaluating\n // the cell on the opposite end of the board.\n\n // If we are within the accepted boundaries then use the position.\n let yPosition = 0\n\n if (y >= 0 && y < config.cellsPerColumn) {\n yPosition = y;\n } else {\n\n // If we are negative then we have stretched beyond the top boundary.\n // Update the position to be at the bottom boundary. Otherwise, we\n // have stretched beyond the bottom boundary so update the position\n // to be at the top boundary.\n if (y < 0) {\n yPosition = config.cellsPerColumn - 1;\n }\n }\n\n let x = cell.getX() - 1\n let xBoundary = cell.getX() + 1\n\n while (x <= xBoundary) {\n\n // Similar to the y boundary, we need to determine if a\n // boundary is being violated, and respond accordingly.\n let xPosition = 0\n\n if (x >= 0 && x < config.cellsPerRow) {\n xPosition = x;\n } else {\n if (x < 0) {\n xPosition = config.cellsPerRow - 1;\n }\n }\n\n // Determine the index of the neighboring cell.\n const cellPosition = new Map()\n .set(Cell.ATTR_POSITION_Y, yPosition)\n .set(Cell.ATTR_POSITION_X, xPosition)\n const neighborIndex = calculateCellIndex(cellPosition)\n\n // Verify this cell is not the same as the target cell.\n // If it's not the same cell then add it to the array of\n // neighboring cells.\n let neighboringCell = cells[neighborIndex];\n\n if (neighboringCell !== cell) {\n neighbors.push(neighboringCell);\n }\n\n // Increment x position\n x++\n }\n\n // Increment y position\n y++\n }\n\n return neighbors;\n }",
"function snail(column, day, night) {\n let result = 0;\n let i = 0;\n\n while (result < column) {\n result = result + day;\n if (result < column) {\n result = result - night;\n }\n i++;\n }\n return i;\n}",
"getNeighbors(col, row){\n var res = [];\n //left border\n if(col > 0){\n this.agentController.ocean.lattice[col-1][row].forEach( (agent) =>{\n res.push(agent);\n });\n }\n //right border\n if(col < (100/ocean.latticeSize)-1){\n this.agentController.ocean.lattice[col+1][row].forEach( (agent) =>{\n res.push(agent);\n });\n }\n //upper border\n if(row > 0){\n this.agentController.ocean.lattice[col][row-1].forEach( (agent) => {\n res.push(agent);\n });\n }\n //lower border\n if(row < (100/ocean.latticeSize)-1){\n this.agentController.ocean.lattice[col][row+1].forEach( (agent) =>{\n res.push(agent);\n });\n }\n //upper left corner\n if(row > 0 && col > 0){\n this.agentController.ocean.lattice[col-1][row-1].forEach( (agent) => {\n res.push(agent);\n });\n }\n //upper right corner\n if(row > 0 && col < (100/ocean.latticeSize)-1){\n this.agentController.ocean.lattice[col+1][row-1].forEach( (agent) => {\n res.push(agent);\n });\n }\n //lower left corner\n if(row < (100/ocean.latticeSize)-1 && col > 0){\n this.agentController.ocean.lattice[col-1][row+1].forEach( (agent) => {\n res.push(agent);\n });\n }\n //lower right corner\n if(row < (100/ocean.latticeSize)-1 && col < (100/ocean.latticeSize)-1){\n this.agentController.ocean.lattice[col+1][row+1].forEach( (agent) => {\n res.push(agent);\n });\n }\n //own cell\n this.agentController.ocean.lattice[col][row].forEach( (agent) => {\n res.push(agent);\n });\n return res;\n }",
"function solveall(N) {\n for (var i = 2; i < N; i++) \n for (var j = i; j < N; j++) \n for (var k = j; k < N; k++) \n for (var l = 2; l < N; l++) \n for (var m = 2; m < N; m++) \n for (var n = 2; n < N; n++) {\n if (i == j && l > m) continue;\n if (j == k && m > n) continue;\n var p = solveangles([i,j,k,l,m,n]);\n if (p) {\n console.log(i,j,k,l,m,n);\n }\n }\n }",
"function minesweeper(matrix = []) {\n\n let mm = [];\n for (let i = 0; i < matrix.length; i++) {\n mm.push([])\n }\n\n for (let i = 0; i < matrix.length; i++) {\n for (let j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j]) {\n mm[i][j] = 1;\n\n } else {\n // 00\n if (i == 0 && j == 0) {\n mm[i][j] = (matrix[i][j + 1]) + (matrix[i + 1][j]);\n\n }\n // 01\n else if (i == 0 && j > 0 && j !== matrix[i].length - 1) {\n mm[i][j] = (matrix[i][j - 1]) + (matrix[i][j + 1]) + (matrix[i + 1][j])\n }\n //02\n else if (i == 0 && j == matrix[i].length - 1) {\n mm[i][j] = (matrix[i][j - 1]) + (matrix[i + 1][j]);\n\n }\n\n // 20\n else if (i == matrix.length - 1 && j == 0) {\n mm[i][j] = (matrix[i - 1][j]) + (matrix[i][j + 1]);\n\n }\n\n // 21\n else if (i == matrix.length - 1 && j > 0 && j !== matrix[i].length - 1) {\n mm[i][j] = (matrix[i][j - 1]) + (matrix[i][j + 1]) + (matrix[i - 1][j])\n\n }\n // 22\n else if (i == matrix.length - 1 && j == matrix[i].length - 1) {\n mm[i][j] = (matrix[i][j - 1]) + (matrix[i - 1][j])\n\n }\n // 10\n else if (i > 0 && i !== matrix.length - 1 && j == 0) {\n mm[i][j] = (matrix[i - 1][j]) + (matrix[i + 1][j]) + (matrix[i][j + 1])\n\n }\n // 12\n else if (i > 0 && i !== matrix.length - 1 && j == matrix[i].length - 1) {\n mm[i][j] = (matrix[i - 1][j]) + (matrix[i + 1][j]) + (matrix[i][j - 1])\n } else {\n mm[i][j] = (matrix[i][j + 1]) + (matrix[i][j - 1]) + (matrix[i + 1][j]) + (matrix[i - 1][j])\n }\n mm[i][j] = mm[i][j] == 0 ? 1 : mm[i][j];\n\n\n }\n\n\n }\n\n }\n return mm;\n}",
"function nextCellAvailable() {\n\t\t\t\tvar cellAvailable = true;\n\t\t\t\tvar newSnakeCellX = newSnakeCell().x;\n\t\t\t\tvar newSnakeCellY = newSnakeCell().y;\n\n\t\t\t\t/* Check if there is no border on X-axis. */\n\t\t\t\tif (Math.floor(newSnakeCellX / ($scope.options.cellWidth + $scope.options.cellMargin)) === $scope.maxAvailabeCells.x || newSnakeCellX < 0) {\n\t\t\t\t\treturn cellAvailable = false;\n\t\t\t\t}\n\n\t\t\t\t/* Check if there is no border on Y-axis. */\n\t\t\t\tif (Math.floor(newSnakeCellY / ($scope.options.cellHeight + $scope.options.cellMargin)) === $scope.maxAvailabeCells.y || newSnakeCellY < 0) {\n\t\t\t\t\treturn cellAvailable = false;\n\t\t\t\t}\n\n\t\t\t\t/* Walking thru all snake's cells. If next cell is busy by existing one it means that snake hits its own tail. */\n\t\t\t\tangular.forEach($scope.snake, function (cell) {\n\t\t\t\t\tif (cell.x === newSnakeCellX && cell.y === newSnakeCellY) {\n\t\t\t\t\t\treturn cellAvailable = false;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\treturn cellAvailable;\n\t\t\t}",
"function createNeighbors() {\n\tfor(var i = 0; i < cells.length; i++) {\n\t\tfor(var j = 0; j < cells[i].length; j++) {\n\t\t\tif(j == cells[i].length - 1)\n\t\t\t\tcells[i][j].neighbors.push(-1);\n\t\t\telse\n\t\t\t\tcells[i][j].neighbors.push(cells[i][j+1]);\n\t\t\t\n\t\t\tif(i == cells.length - 1)\n\t\t\t\tcells[i][j].neighbors.push(-1);\n\t\t\telse\n\t\t\t\tcells[i][j].neighbors.push(cells[i+1][j]);\n\t\t\t\t\n\t\t\tif(j == 0)\n\t\t\t\tcells[i][j].neighbors.push(-1);\n\t\t\telse\n\t\t\t\tcells[i][j].neighbors.push(cells[i][j-1]);\n\t\t\t\t\n\t\t\tif(i == 0)\n\t\t\t\tcells[i][j].neighbors.push(-1);\n\t\t\telse\n\t\t\t\tcells[i][j].neighbors.push(cells[i-1][j]);\n\t\t}\n\t}\n}",
"function checkGrid(grid) {\n var oldSpace = [];\n grid.forEach(function(ary) {\n ary.forEach(function(box) {\n\n //var banned = document.getElementById(box.id-1); //do not allow\n var north = document.getElementById(box.id-20);\n var northEast = document.getElementById(box.id-19);\n var northWest = document.getElementById(box.id-21);\n var east = document.getElementById(parseInt(box.id)+1);\n var west = document.getElementById(box.id-1);\n var south = document.getElementById(parseInt(box.id)+20);\n var southEast = document.getElementById(parseInt(box.id)+21);\n var southWest = document.getElementById(parseInt(box.id)+19);\n var boxConnect = 0;\n\n // if((box.id % 20 === 0 && box.checked === true) && banned.checked === true) {\n // console.log(box.id + \" \" + banned.id);\n // }\n if((box.checked === true && box.id > 19) && north.checked === true) {\n //console.log(\"North: \" + box.id + \" \" + north.id);\n boxConnect++;\n }\n if((box.checked === true && box.id > 19) && northEast.checked === true) {\n //console.log(\"Northeast: \" + box.id + \" \" + northEast.id);\n boxConnect+=2;\n }\n if((box.checked === true && box.id % 20 !== 0) && (box.id > 19 && northWest.checked === true)) {\n //console.log(\"Northwest: \" + box.id + \" \" + northWest.id);\n boxConnect+=2;\n }\n if((box.checked === true && (parseInt(box.id)+1)%20 !== 0) && east.checked === true) {\n //console.log(\"East: \" + box.id + \" \" + east.id);\n boxConnect++;\n }\n if(box.checked === true && west.checked === true && (box.id-1)%20 !== 19) {\n //console.log(\"West: \" + box.id + \" \" + west.id);\n boxConnect++;\n }\n if((box.checked === true && box.id < 380) && south.checked === true) {\n //console.log(\"South: \" + box.id + \" \" + south.id);\n boxConnect++;\n }\n if(box.checked === true && (box.id < 380) && southEast.checked === true) {\n //console.log(\"Southeast: \" + box.id + \" \" + southEast.id);\n boxConnect+=2;\n }\n if((box.checked === true && box.id < 380) && southWest.checked === true) {\n //console.log(\"Southwest: \" + box.id + \" \" + southWest.id);\n boxConnect+=2;\n }\n\n function ridSingles() {\n if(boxConnect < 2) {\n box.checked = false;\n }\n }\n\n //1.store old box.id in array\n //2.uncheck old position during random space move\n //3.check new position after random space move with new box.id\n // *******THIS IS THE PROBLEM*******\n function moveBoxes() {\n var spaces = [1, -1, 19, 20, 21, -19, -20, -21];\n var randNewSpace = Math.floor(Math.random()*spaces.length);\n if(box.checked === true && box.id < 400 || box.id > 0){\n box.id = parseInt(box.id)+ parseInt(spaces[randNewSpace]);\n //console.log(parseInt(box.id) + parseInt(spaces[randNewSpace]));\n box.id = parseInt(box.id);\n }\n else if(box.checked === true && box.id > 400 || box.id < 0){\n box.checked = false;\n }\n }\n\n setInterval(function() {\n ridSingles();\n moveBoxes();\n }, 1000);\n });\n //console.log(ary);\n });\n\n}",
"function mauriceWins(mSnails, sSnails) {\r\n\tlet acc = 0;\r\n\tif (mSnails[0] > sSnails[2]){\r\n\t\tacc++\r\n\t}\r\n\tif (mSnails[1] > sSnails[0]){\r\n\t\tacc++\r\n\t}\r\n\tif (mSnails[2] > sSnails[1]){\r\n\t\tacc++\r\n\t}\r\n\t\tif(acc >= 2){\r\n\t\treturn true\r\n\t}\r\n\telse{\r\n\treturn false}\r\n}",
"static neighbours(q, r) {\n return [[q + 1, r], [q, r + 1], [q - 1, r], [q, r - 1], [q + 1, r - 1], [q - 1, r + 1]];\n }",
"function create_cell_list( maze ) {\n\t\tlet result = {\n\t\t\tx_max:Math.floor(maze[0].length /2),\n\t\t\ty_max:Math.floor(maze.length/2),\n\t\t\tdata:[],\n\t\t\t/*\n\t\t\t * Determines if a position of a sprite, which is\n\t\t\t * given by the x,y pair of input parameters is valid.\n\t\t\t * A position is valid if it either positions a sprite\n\t\t\t * entirely in a cell, or if the sprite is positioned \n\t\t\t * in more than one cell, then those cells should not\n\t\t\t * have a border between them according to the cell\n\t\t\t * data. It is assumed that the width and height of\n\t\t\t * the cell is the same as the width and height of\n\t\t\t * the sprite, namely 64.\n\t\t\t *\n\t\t\t * Deterimining is a position is valid works as\n\t\t\t * follows:\n\t\t\t *\n\t\t\t * 1. Find the cell where the x,y position is\n\t\t\t * located:\n\t\t\t * \tcell_x = x div 64\n\t\t\t * \tcell_y = y div 64\n\t\t\t * \tcell = data[ cell_y * x_max + cell_x ]\n\t\t\t * 2. Check if either the x position is at the left hand\n\t\t\t * side of the cell or if it is not that the cell has\n\t\t\t * no right border.\n\t\t\t * x_pos = x mod 64\n\t\t\t * if x_pos != 0:\n\t\t\t * \t!cell.right\n\t\t\t * 3. Check if either y position is at the top of the\n\t\t\t * cell or, if it is not, that the cell has no\n\t\t\t * bottom border.\n\t\t\t * y_pos = y mod 64\n\t\t\t * if y_pos != 0:\n\t\t\t * \t!cell.bottom\n\t\t\t * 4. Return true if both checks (2 and 3 ) pass, and\n\t\t\t * false if at least one of them fails.\n\t\t\t *\n\t\t\t * @param x The x position of the top left corner of the \n\t\t\t * sprite on the screen.\n\t\t\t * @param y The y position of the top left corner of the\n\t\t\t * sprite on the screen.\n\t\t\t *\n\t\t\t * @return True if the position of the sprite is valid \n\t\t\t * according to the above rules, and False, if \n\t\t\t * the position is not valid.\n\t\t\t */ \n\t\t\tis_valid_position:function(x,y) {\n\t\t\t\tlet result = ( x>=0 ) && (y>=0);\n\t\t\t\tif( result ){\n\t\t\t\t\tlet cell_x = Math.floor( x/64);\n\t\t\t\t\tlet cell_y = Math.floor( y/64);\n\t\t\t\t\tlet cur_cell = this.data[ cell_y*this.x_max + cell_x];\n\t\t\t\t\n\t\t\t\t\tlet x_pos = x%64;\n\t\t\t\t\tif( x_pos != 0 ) {\n\t\t\t\t\t\tresult = !cur_cell.right;\n\t\t\t\t\t}\n\t\t\t\t\tif( result ){\n\t\t\t\t\t\tlet y_pos = y%64;\n\t\t\t\t\t\tif( y_pos != 0 ){\n\t\t\t\t\t\t\tresult = !cur_cell.bottom;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn result;\n\t\t\t}\n\t\t};\n\n\t\tfor( j=0; j<result.y_max; j++ ) {\n\t\t\tfor( i=0; i<result.x_max; i++ ){\n\t\t\t\tresult.data.push( init_cell(create_cell(), i, j, maze) );\n\t\t\t};\n\t\t};\n\t\treturn result;\n\t}",
"findNeighbours(){\n \t// Array of all free directions. Starts with all directions\n\tvar freeDirections = [0,1,2,3,4,5,6,7];\n\t// First, define the eight neighbouring locations\n\tvar neighN = this.pos.copy().add(createVector(0,-1));\n\tvar neighS = this.pos.copy().add(createVector(0, 1));\n\tvar neighE = this.pos.copy().add(createVector( 1,0));\n\tvar neighW = this.pos.copy().add(createVector(-1,0));\n\tvar neighNE = this.pos.copy().add(createVector(1, -1));\n\tvar neighSE = this.pos.copy().add(createVector(1, 1));\n\tvar neighNW = this.pos.copy().add(createVector(-1,-1));\n\tvar neighSW = this.pos.copy().add(createVector(-1,1));\n\t\n\t// Make a dictionary, for translating direction-number into location\n\tvar directionDict ={};\n\tdirectionDict[0] = neighN;\n\tdirectionDict[1] = neighS;\n\tdirectionDict[2] = neighE;\n\tdirectionDict[3] = neighW;\n\tdirectionDict[4] = neighNE;\n\tdirectionDict[5] = neighSE;\n\tdirectionDict[6] = neighNW;\n\tdirectionDict[7] = neighSW;\n\t\n\t// Check if the directions are in the occuPos dictionary\n\t// And remove it from the \"freeDirections\" vector if it is\n\tif (occuPos.hasKey(posToDictKey(neighN.x,neighN.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 0){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\tif (occuPos.hasKey(posToDictKey(neighS.x,neighS.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 1){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighE.x,neighE.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 2){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighW.x,neighW.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 3){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighNE.x,neighNE.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 4){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighSE.x,neighSE.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 5){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighNW.x,neighNW.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 6){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (occuPos.hasKey(posToDictKey(neighSW.x,neighSW.y))){\n\t\tfor (var j = freeDirections.length; j >= 0; j--){\n\t\t\tif (freeDirections[j] == 7){\n\t\t\t\tfreeDirections.splice(j,1);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t// Return the vector of free directions and the dictionary for translating the vector \n\treturn [freeDirections,directionDict];\n }",
"function computeHoldingCells() {\n holdingData.forEach(h => {\n const id = holdingId(h);\n const hData = data.filter(d => d.origin === id || d.dest === id);\n let prevDir = false;\n\n h.cells = [];\n\n hData.forEach(m => {\n const incoming = m.dest === id;\n\n // If it's an incoming movement, always need a new cell to store its stay length.\n if (incoming) {\n const cell = { stayLength: m.stayLength };\n h.cells.push(cell);\n m.destCell = cell;\n } else if (incoming === prevDir) {\n // If not, create a new cell if the previous one is also an outgoing.\n const cell = {};\n h.cells.push(cell);\n m.originCell = cell;\n } else {\n // Outgoing using the previous cell\n m.originCell = _.last(h.cells);\n }\n\n prevDir = incoming;\n });\n });\n\n // Mark initial cell\n data[0].originCell.start = true;\n }",
"function dynamicProgramming(coins, sum) {\n if (coins.length < 1) return 0\n const table = [...Array(sum + 1)].map(e => Array(coins.length + 1).fill(0))\n // when sum is 0, there's 1 way to fulfil it. simply by doing nothing\n for (let i = 0; i < table[0].length; i++) {\n table[0][i] = 1\n }\n for (let i = 1; i < table.length; i++) {\n for (let j = 1; j < table[i].length; j++) {\n table[i][j] = table[i][j-1]\n if (i - coins[j-1] >= 0) {\n table[i][j] += table[i-coins[j-1]][j]\n }\n }\n }\n console.log(table)\n return table[table.length-1][table[0].length-1]\n}",
"calculateTravelCost(previous, next) {\n if (next.row !== previous.row && next.col !== previous.col) {\n return 14;\n }\n return 10;\n }",
"function getAdjacentCells(cell){\n\tvar cellCopy;\n\tif(cell.location.row+1 < mazeSize ){ // down\n\t\tcellCopy = new Cell(maze[cell.location.row+1][cell.location.col].location.row, maze[cell.location.row+1][cell.location.col].location.col,maze[cell.location.row+1][cell.location.col].id);\n\t\tcell.adjacentCells.push(cellCopy);\n\t}\n\tif(cell.location.row-1 > -1){ // up\n\t\tcellCopy = new Cell(maze[cell.location.row-1][cell.location.col].location.row, maze[cell.location.row-1][cell.location.col].location.col,maze[cell.location.row-1][cell.location.col].id);\n\t\tcell.adjacentCells.push(cellCopy);\n\t}\n\tif(cell.location.col+1 < mazeSize){ // right \n\t\tcellCopy = new Cell(maze[cell.location.row][cell.location.col+1].location.row, maze[cell.location.row][cell.location.col+1].location.col,maze[cell.location.row][cell.location.col+1].id);\n\t\tcell.adjacentCells.push(cellCopy);\n\t}\n\tif(cell.location.col-1 > -1){ // left\n\t\tcellCopy = new Cell(maze[cell.location.row][cell.location.col-1].location.row, maze[cell.location.row][cell.location.col-1].location.col,maze[cell.location.row][cell.location.col-1].id);\n\t\tcell.adjacentCells.push(cellCopy);\n\t}\n}",
"function infectedGrid(currentBoard, row, column, currentPlayer) {\n\tvar opponent;\n\tif(currentPlayer == 1) {\n\t\topponent = 2;\n\t} \n\telse {\n\t\topponent = 1;\n\t}\n\n\tvar infectedGridList = [];\n\tif(row > 0 && row < length - 1 && column > 0 && column < length - 1) {\n\t\tif(currentBoard[row+1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row+1][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row+1][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t}\n\tif(row > 0 && row < length - 1 && column == 0) {\n\t\tif(currentBoard[row+1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row+1][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t}\n\tif(row > 0 && row < length - 1 && column == length - 1) {\n\t\tif(currentBoard[row-1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row+1][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row+1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t}\n\tif(row == 0 && column > 0 && column < length - 1) {\n\t\tif(currentBoard[row+1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row+1][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row+1][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row+1, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\n\t}\n\tif(row == length - 1 && column > 0 && column < length - 1) {\n\t\tif(currentBoard[row][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column+1] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column+1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row-1][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row-1, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t\tif(currentBoard[row][column-1] == opponent) {\n\t\t\tvar infectedGrid = {x:row, y:column-1};\n\t\t\tinfectedGridList.push(infectedGrid);\n\t\t}\n\t}\n\treturn infectedGridList;\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Open cash payment modal | openCashPayment() {
scope.get(this).$broadcast('show-modal', 'cash-payment');
} | [
"function onBuyClicked() {\n createPaymentRequest()\n .show()\n .then(function (response) {\n // Dismiss payment dialog.\n response.complete(\"success\");\n // handlePaymentResponse(response);\n $(\"#checkout\").css(\"display\", \"none\");\n $(\"#completeOrd\").css(\"display\", \"block\");\n $('#placeOrder').css(\"display\", \"inline\");\n })\n .catch(function (err) {\n console.log(\"show() error! \" + err.name + \" error: \" + err.message);\n });\n}",
"function openCashSummaryForEditAmount() {\n\t/* Show History Funds without select a type Option */\n\t$(\"#historyFundingSources\").show();\n\tremoveChitErrorBorder();\n\t$(\"#editCashSummaryTotal\").hide();\n\t$(\"#cashPaymnetInfoMessage\").hide();\n\taddOrRemoveBorderBottom();\n}",
"function addFundsModal(btn){\n var selectedAmount = $(btn).attr('data-id');\n $('#add-funds-modal').modal('close');\n $('#confirm-add-funds-modal').modal('open');\n $('.add-funds-amount').html(\"US$ \" + selectedAmount);\n var available_cash = $('#cash-available-invisible').html().replace(/,/g, \"\");\n var new_total_cash = parseFloat(available_cash) + parseFloat(selectedAmount.replace(/,/g, \"\"));\n $('#new-cash-available').html(formatter.format(new_total_cash));\n $('#confirm-add-funds-input').val(selectedAmount);\n}",
"clickPayBillsButton () {\n this.payBillsButton.click(); \n }",
"function openAssessmentPlanModal () {\n\t'use strict';\n\t$('#topicDialogBackground').css('display', 'block');\n\t$('#assessment-plan').css('display', 'block');\n}",
"function showInstructions()\n{\n $(\"#instructions_modal\").modal();\n}",
"function activate_utility_filters_modal_view(){\n \n jQuery('.end-button-comparacard.button-plus').click( function(){ \n \n // variables de modal y contenedor de comparacion\n var modal_filtro = jQuery('#modal-results-filters');\n var content_carousel = jQuery('.section--compare.container--compare-cards.container--comparacards--view');\n \n // se muestra el modal y se oculta el comparador\n modal_filtro.css({ \"visibility\":\"visible\", \"marginTop\":\"50px\", \"opacity\":\"1\" });\n modal_filtro.show();\n content_carousel.hide(); \n\n \n });\n\n }",
"_order_accepted(event) {\n const order = event.detail;\n if (order.pcode == this.pcode)\n return;\n\n this.$.modal.modal_text = `Do you want to ${order.is_bid ? 'sell' : 'buy'} for ${order.price}?`\n this.$.modal.on_close_callback = (accepted) => {\n if (!accepted)\n return;\n\n this.$.trader_state.accept_order(order);\n };\n this.$.modal.show();\n }",
"function paypalPrompt(booking) {\n\tsidepane.clear();\n\tsidepane.appendHeader(\"PAYMENT\");\n\tsidepane.append(view.payment(booking));\n\t// render paypal button\n\tpaypal.Button.render({\n\t env: 'sandbox', // sandbox | production\n\t style: {\n\t label: 'pay',\n\t tagline: false,\n\t size: 'medium', // small | medium | large | responsive\n\t shape: 'rect', // pill | rect\n\t color: 'blue' // gold | blue | silver | black\n\t },\n\t client: {\n\t sandbox: document.head.querySelector(\"[name~=paypal-sandbox-key][content]\").content,\n\t production: document.head.querySelector(\"[name~=paypal-production-key][content]\").content\n\t },\n\t payment: function(data, actions) {\n\t return actions.payment.create({\n\t payment: {\n\t transactions: [\n\t {\n\t amount: { total: '0.01', currency: 'AUD' }\n\t }\n\t ]\n\t }\n\t });\n\t },\n\t onAuthorize: function(data, actions) {\n\t return actions.payment.execute().then(function() {\n\t \tvar headers = new Headers();\n\t \theaders.append(\"Content-Type\", \"application/json\");\n\t \tvar request = new Request('/api/bookings/pay');\n\t \t\n\t \tfetch(request)\n\t\t\t\t.then(res => {\n\t\t\t\t\tif (res.status == 200) {\n\t\t\t\t\t\treturn callback(true);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\treturn callback(false);\n\t\t\t\t\t}\n\t\t\t\t});\n\t \t\n\t\t \tsidepane.clear();\n\t\t \tsidepane.appendHeader(\"PAYMENT\");\n\t\t \tsidepane.append(view.paymentConfirmation(true));\n\t\t \t\n\t });\n\t },\n\t onError: function(err) {\n\t \tsidepane.clear();\n\t \tsidepane.appendHeader(\"PAYMENT\");\n\t \tsidepane.append(view.paymentConfirmation(false));\n\t }\n\t}, '#paypal-button-container');\n\tsidepane.open();\n}",
"function openBuyStore(storeID){\n\t// Get the stores cost\n\tvar storeCost = $(\"#ps_name_\"+storeID).data(\"value\");\n\n\t$( \"#buyPartStore\" ).data('storeID', storeID);\n\t$( \"#bps_cost\" ).text(storeCost);\n\t$( \"#buyPartStore\" ).dialog( \"open\" );\n}",
"function changeSkinCarte(){\n $('#modalSkinCarton').modal('open');\n}",
"openStripeModal() {\n this.setState({\n open: true,\n });\n }",
"function ModConfirm_PartexCheck_Open() {\n console.log(\" ----- ModConfirm_PartexCheck_Open ----\")\n\n // --- create mod_dict\n mod_dict = {mode: \"remove_partex\"};\n\n const data_dict = mod_MEX_dict.partex_dict[mod_MEX_dict.sel_partex_pk];\n const partex_name = (data_dict) ? data_dict.name : \"-\";\n\n const msg_html = [\"<p class=\\\"p-2\\\">\", loc.All_partex_willbe_removed, \"<br>\",\n loc.except_for_selected_exam, \" '\", partex_name, \"'.\",\n \"</p><p class=\\\"p-2\\\">\", loc.Do_you_want_to_continue, \"</p>\"].join(\"\")\n el_confirm_msg_container.innerHTML = msg_html;\n\n el_confirm_header.innerText = loc.Remove_partial_exams;\n el_confirm_loader.classList.add(cls_hide);\n el_confirm_msg_container.classList.remove(\"border_bg_invalid\", \"border_bg_valid\");\n el_confirm_btn_save.innerText = loc.Yes_remove;\n add_or_remove_class(el_confirm_btn_save, \"btn-outline-secondary\", true, \"btn-primary\")\n\n el_confirm_btn_cancel.innerText = loc.No_cancel;\n\n// set focus to cancel button\n setTimeout(function (){\n el_confirm_btn_cancel.focus();\n }, 500);\n\n// show modal\n $(\"#id_mod_confirm\").modal({backdrop: true});\n\n }",
"function uiPagePurchaseSuccess() {\n updateModalVisilibity(\n ['shop-success'], ['shop-tshirt', 'shop-checkout']);\n}",
"clickPayByCheckLink() {\n this.lnkPayByCheck.click();\n }",
"function openImportPubKeyModal() {\n $uibModal.open({\n templateUrl: '/components/profile/importPubKeyModal.html',\n backdrop: true,\n windowClass: 'modal',\n controller: 'ImportPubKeyModalController as modal'\n }).result.finally(function() {\n ctrl.updatePubKeys();\n });\n }",
"function openModal() {\n\t\t\t//Create timestamp object\n\t\t\tconst timestamp = { session_id: new Date().getTime() };\n\t\t\tconsole.log(timestamp);\n\n\t\t\t//Get and/or set page variation\n\t\t\tlet imgId = '';\n\t\t\tif($cookies.imgValue !== undefined) {\n\t\t\t\timgId = $cookies.imgValue;\n\t\t\t} else {\n\t\t\t\timgId = Math.floor(Math.random() * 2).toString();\n\t\t\t\t$cookies.imgValue = imgId;\n\t\t\t}\n\n\t\t\t//Modify modal instance\n\t\t\tconst modalInstance = $uibModal.open({\n\t\t\t\tappendTo: angular.element(document).find('aside'),\n\t\t\t\tanimation: true,\n\t\t\t\tariaLabelledBy: 'modal-title',\n\t\t\t\tariaDescribedBy: 'modal-body',\n\t\t\t\ttemplateUrl: 'myModalContent',\n\t\t\t\tcontroller: 'ModalController',\n\t\t\t\tcontrollerAs: 'ctrl',\n\t\t\t\tresolve: {\n\t\t\t\t\timgId:function() {\n\t\t\t \treturn imgId;\n\t\t\t }\n\t\t\t\t},\n\n\t\t });\n\n\t\t\t//Display modal data to browser console\n\t\t modalInstance.result.then(function(data) {\n\t\t \tconsole.log(data);\n\t\t }, function() {});\n\t\t}",
"function changeEmail() {\n $('#modalEmail').modal('open');\n}",
"function win() {\n modal.style.display = \"block\";\n}",
"function display_form(){\r\n $('#staticBackdrop').modal('show');\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Event handler for the Chroma Key field | handleChangeChroma(event){
this.setState({chromaColour: event.target.value})
} | [
"function ChromaKey(video, buffer, output, color, variance, blur_radius) {\n this.video = video;\n this.buffer_canvas = buffer;\n this.buffer = buffer.getContext('2d');\n this.output_canvas = output;\n this.output = output.getContext('2d');\n this.color = color;\n this.variance = variance;\n this.blur_radius = blur_radius;\n \n var me = this;\n \n video.chroma_key = this;\n video.addEventListener('play', function() {me.start()}, false);\n video.addEventListener('ended', function() {me.stop()}, false);\n video.addEventListener('pause', function() {me.stop()}, false);\n video.addEventListener('abort', function() {me.stop()}, false);\n video.addEventListener('error', function() {me.stop()}, false);\n}",
"function handleKey (){\n var keyObj = event;\n handleInput(keyObj);\n}",
"function on_change_key_config()\n{\n\tkey_config = key_config_presets[key_config_menu.selectedIndex];\n}",
"function selectKey(e) {\n old_delta = delta\n delta = Number(e.target.id.split('-')[1]) // for 'key-n', extract n\n pitch = rootPitch + delta;\n [pitchName, frequency] = pitchMap.get(pitch)\n const black = [1, 3, 6, 8, 10].includes(old_delta)\n if (old_delta !== delta) {\n document.getElementById(`key-${old_delta}`).style.fill = black ? 'black' : 'white'\n document.getElementById(`key-${delta}`).style.fill = '#7aeb7a'\n }\n}",
"function handleKeys( event ) {\n var key = event.keyCode;\n console.log(key);\n switch (key) {\n case 119: // w\n camera.position.z += 0.1;\n break;\n case 115: // s\n camera.position.z -= 0.1;\n break;\n case 97: // a\n camera.position.x += 0.1;\n break;\n case 100: // d\n camera.position.x -= 0.1;\n break;\n case 113: // q\n camera.position.y += 0.1;\n break;\n case 101: // e\n camera.position.y -= 0.1;\n break;\n\n case 105: // i\n camera.rotateZ(0.05);\n break;\n case 107: // k\n camera.rotateZ(-0.05);\n break;\n case 106: // j\n camera.rotateY(0.05);\n break;\n case 108: // l\n camera.rotateY(-0.05);\n break;\n case 117: //u\n camera.rotateX(0.05);\n break;\n case 111: // o\n camera.rotateX(-0.05);\n break;\n }\n console.log( camera.position, camera.rotation);\n}",
"keyControl() {\n\n if (keyIsDown(this.activateKey)) {\n this.bossManipulation = true;\n } else {\n this.bossManipulation = false;\n }\n }",
"function fogKey(event)\n{\n if(event.keyCode == \"32\")\n {\n fog = !fog;\n }//end if fog\n}",
"function getKey(e){\r\n\tif (e == null) { // ie\r\n\t\tkeycode = event.keyCode;\r\n\t} else { // mozilla\r\n\t\tkeycode = e.which;\r\n\t}\r\n\tkey = String.fromCharCode(keycode).toLowerCase();\r\n\t\r\n\tif(key == 'x'){ hideLightbox(); }\r\n}",
"function keyPressed() {\r\n if (key == '5') sortMode = null;\r\n if (key == '6') sortMode = gd.HUE;\r\n if (key == '7') sortMode = gd.SATURATION;\r\n if (key == '8') sortMode = gd.BRIGHTNESS;\r\n if (key == '9') sortMode = gd.GRAYSCALE;\r\n}",
"function input_character_keys(key_array_index, event_type, character_key_index, key_code) {\r\n\tkey_array[key_array_index].addEventListener(event_type, function(event) {\r\n\t\tif (event_type == \"keydown\" && document.getElementById(\"mirrored_textarea\") != document.activeElement) {\r\n\t\t\tif (event.key === \" \" || event.key === \"Enter\" || event.key === \"Spacebar\") {\r\n\t\t\t\ttoggle_button(event.target);\r\n\t\t\t\tevent.preventDefault();\r\n\t\t\t\tedit_textarea(character_key_index);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tevent.preventDefault();\r\n\t\t\tedit_textarea(character_key_index);\r\n\t\t}\r\n\t});\r\n\r\n\tdocument.addEventListener(\"keydown\", function(event) {\r\n\t\tif (event.defaultPrevented) {\r\n\t\t\treturn; // Do nothing if event already handled\r\n\t\t}\r\n\t\tif (event.code == key_code && modifier_key_pressed == false) {\r\n\t\t\ttoggle_button(event.target);\r\n\t\t\tkey_button_array[key_array_index].classList.add(\"focus\");\r\n\t\t\tsetTimeout(function () {key_button_array[key_array_index].classList.remove(\"focus\");}, 250);\r\n\t\t\tedit_textarea(character_key_index);\r\n\t\t\tevent.preventDefault();\r\n\t\t}\r\n\t});\r\n}",
"function handleKeyDown(event){\r\n\r\n\t// left arrow -> rotate around teapot left\r\n if (event.keyCode == 37){\r\n quatRotation(-0.05, originUp);\r\n vec3.transformQuat(eyePt, originEyePt, globalQuat);\r\n\t\tvec3.normalize(viewDir, eyePt);\r\n\t\tvec3.scale(viewDir, viewDir, -1);\r\n }\r\n\t// right arrow -> rotate around teapot right\r\n else if (event.keyCode == 39){\r\n quatRotation(0.05, originUp);\r\n vec3.transformQuat(eyePt, originEyePt, globalQuat);\r\n\t\tvec3.normalize(viewDir, eyePt);\r\n\t\tvec3.scale(viewDir, viewDir, -1);\r\n }\r\n\t// A -> rotate teapot right\r\n\telse if (event.keyCode == 65){\r\n\t\tmodelRotation += 0.05;\r\n\t}\r\n\t// D -> rotate teapot left\r\n\telse if (event.keyCode == 68){\r\n\t\tmodelRotation -= 0.05;\r\n\t}\r\n}",
"function keyPressed () {\nif (keyCode === 32) {\nretro = !retro;\n}\n}",
"function keyPressed() {\n if (keyCode == 32) {\n if (strokeToggle) {\n stroke(0);\n } else {\n noStroke();\n }\n strokeToggle = !strokeToggle;\n }\n if (keyCode == LEFT_ARROW) {\n circleSize = circleSize - 10;\n }\n if (keyCode == RIGHT_ARROW) {\n circleSize = circleSize + 10;\n }\n if (keyCode == UP_ARROW) {\n toggle++;\n toggle = toggle % 3;\n }\n if (keyCode == DOWN_ARROW) {\n toggle++;\n toggle = toggle % 3;\n }\n}",
"function keyPressed() {\n switch (key) {\n case 'C':\n drawCos = !drawCos;\n break;\n case 'S':\n drawSin = !drawSin;\n break;\n case 'T':\n drawTan = !drawTan;\n break;\n }\n}",
"function draw2Dkeyboard()\n{\n imageMode(CORNER);\n image(keyboard, width/2 - 2.0*PPCM, height/2 - 1.0*PPCM, 4.0*PPCM, 3.0*PPCM);\n \n textFont(\"Arial\", 0.35*PPCM);\n textStyle(BOLD);\n fill(0);\n noStroke();\n text(\"S\" , width/2 - 1.32*PPCM, height/2 + 0.63*PPCM);\n textFont(\"Arial\", 0.25*PPCM);\n textStyle(NORMAL);\n text(\"Q\" , width/2 - 1.74*PPCM, height/2 + 0.10*PPCM);\n text(\"W\" , width/2 - 1.32*PPCM, height/2 + 0.10*PPCM);\n text(\"E\" , width/2 - 0.89*PPCM, height/2 + 0.10*PPCM);\n text(\"A\" , width/2 - 1.74*PPCM, height/2 + 0.60*PPCM);\n text(\"D\" , width/2 - 0.89*PPCM, height/2 + 0.60*PPCM);\n text(\"Z\" , width/2 - 1.74*PPCM, height/2 + 1.08*PPCM);\n text(\"X\" , width/2 - 1.32*PPCM, height/2 + 1.08*PPCM);\n text(\"C\" , width/2 - 0.89*PPCM, height/2 + 1.08*PPCM);\n \n textFont(\"Arial\", 0.35*PPCM);\n textStyle(BOLD);\n fill(0);\n noStroke();\n text(\"G\" , width/2 + 0.0*PPCM, height/2 + 0.63*PPCM);\n textFont(\"Arial\", 0.25*PPCM);\n textStyle(NORMAL);\n text(\"R\" , width/2 - 0.42*PPCM, height/2 + 0.10*PPCM);\n text(\"T\" , width/2 - 0*PPCM, height/2 + 0.10*PPCM);\n text(\"Y\" , width/2 + 0.42*PPCM, height/2 + 0.10*PPCM);\n text(\"H\" , width/2 + 0.42*PPCM, height/2 + 0.60*PPCM);\n text(\"F\" , width/2 - 0.44*PPCM, height/2 + 0.60*PPCM);\n text(\"V\" , width/2 - 0.42*PPCM, height/2 + 1.08*PPCM);\n text(\"B\" , width/2 - 0*PPCM, height/2 + 1.08*PPCM);\n text(\"N\" , width/2 + 0.42*PPCM, height/2 + 1.08*PPCM);\n \n textFont(\"Arial\", 0.35*PPCM);\n textStyle(BOLD);\n fill(0);\n noStroke();\n text(\"K\" , width/2 + 1.30*PPCM, height/2 + 0.63*PPCM);\n textFont(\"Arial\", 0.25*PPCM);\n textStyle(NORMAL);\n text(\"U\" , width/2 + 0.88*PPCM, height/2 + 0.10*PPCM);\n text(\"I\" , width/2 + 1.30*PPCM, height/2 + 0.10*PPCM);\n text(\"O\" , width/2 + 1.72*PPCM, height/2 + 0.10*PPCM);\n text(\"J\" , width/2 + 0.88*PPCM, height/2 + 0.60*PPCM);\n text(\"P\" , width/2 + 1.72*PPCM, height/2 + 0.60*PPCM);\n text(\"M\" , width/2 + 0.88*PPCM, height/2 + 1.08*PPCM);\n text(\"L\" , width/2 + 1.72*PPCM, height/2 + 1.08*PPCM);\n}",
"function tm_keystroke() {\n\n tm_keystrokes++;\n tm_calculate();\n}",
"function keyEvent() {\n for (const key of keyboard) {\n key.addEventListener(\"click\", keyboardClick);\n }\n}",
"function C101_KinbakuClub_Fight_KeyDown() {\n\tFightKeyDown();\n}",
"function keyTyped() {\n mode = key;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
endregion LocalStoragespecific code. ////////////////// ////////////////// region Stats tracking. Collect initial references for each Stat. | function τSST_get_stat_references() {
nodes.focus = $('#stats-panel div[class="stat-container focus"]');
nodes.focus_pct = nodes.focus.find('div[class="percentage"]');
for (var stat in all_stats) {
nodes[stat] = $('#stats-panel div[class="stat-container ' + stat + '"]');
nodes[stat + '_pct'] = nodes[stat].find('span[class="pc"]');
}
} | [
"resetStats() {\n\t\tthis.gameDataList = [];\n\t\tthis.curGameData = null;\n\t}",
"resetStats_() {\n this.mediaBytesTransferred = 0;\n this.mediaRequests = 0;\n this.mediaTransferDuration = 0;\n this.mediaSecondsLoaded = 0;\n }",
"function copy_base_stats() {\n\tvar ret = {};\n\n\t// Should be fine as base_stats doesn't have anything fancy in.\n\tfor (var attr in base_stats) {\n\t\tret[attr] = base_stats[attr];\n\t}\n\t\n\treturn ret;\n}",
"function computeStats(){\n return {\n pages: computePageCounts(),\n referrers: computeRefererCounts(),\n activeUsers: getActiveUsers()\n };\n}",
"function setPopulationStat(){\n if (Generation != faunaStat.length)\n alert(\"ERROR: multiple use of setPopulationStat per Generation! Generation = \"+Generation +\" faunaStat = \"+faunaStat.toSource())\n // get data of surviving population\n var bugStat = new Array();\n var alive = 0;\n for (i=0;i<BUGIMAGES.length;i++){ // initialization\n var bStat = new Object();\n bStat[\"starter\"]=0;\n bStat[\"survivor\"]=0;\n bugStat.push(bStat);\n }\n for (i=0;i<fauna.length;i++){\n bugStat[fauna[i][\"type\"]][\"starter\"]++;\n if (fauna[i][\"alive\"]){\n bugStat[fauna[i][\"type\"]][\"survivor\"]++;\n alive++;\n }\n }\n faunaStat.push(bugStat.slice(0));\n\n //alert(\"faunaStat: \" + faunaStat.toSource());\n //alert(\"bugStat: \" + bugStat.toSource());\n\n return alive;\n}",
"function fillStatPointsArray(){\n stat_points_per_level.push(0);\n for(var i=1;i<185;i++){\n stat_points_per_level.push(stat_points_per_level[i-1]+calcStatGain(i+1));\n }\n}",
"function init(){\n var storedScores = JSON.parse(localStorage.getItem(\"scoreArray\"));\n var storedInitials = JSON.parse(localStorage.getItem(\"arrayInitials\"))\n\n if (storedScores !== null){\n scoreArray = storedScores;\n }\n\n if (storedInitials !== null){\n arrayInitials = storedInitials;\n }\n logScore()\n}",
"function resetLoadedCounter() {\n\t\t_loadedCounter = 0;\n\t}",
"function getCacheStatuses() {\n\tgetCacheCount();\n\tgetCacheAvailableCount();\n\tgetCacheDownCount();\n\tgetCacheStates();\n}",
"function calculate_starting_bonuses(stats) {\n\tvar weap_1_stat = weapon_stats[document.getElementById(\"starting_weapon_1\").value];\n\tstats[weap_1_stat] += 1;\n\t\n\tvar weap_2_stat = weapon_stats[document.getElementById(\"starting_weapon_2\").value];\n\tstats[weap_2_stat] += 1;\n\n\tvar spirit_stat = spirit_stats[document.getElementById(\"starting_guardian_spirit\").value];\n\tstats[spirit_stat] += 1;\n}",
"function doReferenceTotals() {\n if (verboseLogging) console.log(selectedCountry + 'All Countries: ' + startYear + '-' + endYear);\n\n httpGetAsync('freqs?start=' + startYear + '&end=' + endYear, function (response) {\n countryFreq = JSON.parse(response);\n var maxCorporaSize = countryFreq['max corpora size'];\n\n mergedData = mergeCountryFreq(countryFreq['countries'], maxCorporaSize, countryData, true);\n\n updateGUI();\n });\n}",
"compressStats() {\n if (this.totalMins > 0) {\n this.history.push({\n date: this.sessionStartDateTime,\n distractionCount: this.distractionList.length,\n timeSpent: this.totalMins,\n });\n localStorage.setItem('statsHistory', JSON.stringify(this.history));\n }\n\n const event = new CustomEvent('reset-timer', {\n });\n this.dispatchEvent(event);\n }",
"function calculate_levels(stats) {\n\tvar total_levels = 1;\n\tfor (var stat in base_stats) {\n\t\tvar s_levels = levels(stat);\n\t\tstats[stat] += s_levels;\n\t\ttotal_levels += s_levels;\n\t}\n\tstats[\"level\"] = total_levels;\n}",
"function reportStats() {\n const now = Date.now();\n console.log(`STATS Tweets: ${totalTweets}\\tErrors: ${totalErrors}\\tUptime: ${Math.round((now - startStatus)/1000)}s`);\n}",
"gameInit() {\n\t\tthis.curGameData = new gameData.GameData(this.genome.length);\n\t\tthis.playHist = [];\n\t\tfor (let i = 0; i < this.hist.length; i++) {\n\t\t\tthis.playHist.push(this.hist[i]);\n\t\t}\n\t}",
"function loadCounters() {\n \n // set up timer for reading the script\n game.time.events.repeat(1000, 30, (() => {\n scriptIterator.readNextScript();\n }), this);\n\n createTimer(0, 1000, true);\n createLiveTimer();\n}",
"function IntegerTracker(){\n\tthis.integers=[];\n\tthis.mode={count:0,int:0};\n\t// this.integers={};\n}",
"function updateArrays() {\n var storedHighScore = JSON.parse(localStorage.getItem(\"highScore\"));\n\n if (storedHighScore !== null) {\n highScore = storedHighScore;\n }\n\n var storedInitials = JSON.parse(localStorage.getItem(\"initials\"));\n\n if (storedInitials !== null) {\n initials = storedInitials;\n }\n}",
"function resetPlayerStats() {\n localStorage.streak1 = 0;\n localStorage.streak2 = 0;\n localStorage.currentPlayer = 2;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method _jsTabControl_drawTab() This function draws an individual tab onto a jsDocument. Parameters: tab (jsTab) the tab to draw. objOwnerTD (jsTab) the cell to draw onto. Returns: nothing. | function _jsTabControl_drawTab(tab, objOwnerTD) {
//begin table
var objTable = document.createElement("table");
with (objTable) {
setAttribute("border", "0");
setAttribute("cellspacing", "0");
setAttribute("cellpadding", "0");
}
//begin row
var objTR = document.createElement("tr");
objTable.appendChild(objTR);
//begin first cell
var objTD = document.createElement("td");
var objIMG = document.createElement("img");
with (objIMG) {
setAttribute("src", IMG_TAB_OFF[0].filename);
setAttribute("height", IMG_TAB_OFF[0].height);
setAttribute("width", IMG_TAB_OFF[0].width);
setAttribute("id", "tab" + tab.id + "left");
}
objTD.appendChild(objIMG);
objTR.appendChild(objTD);
//begin middle cell
objTD = document.createElement("td");
with (objTD) {
setAttribute("id", "tab" + tab.id + "text");
setAttribute("class", "tabText");
setAttribute("width", this.tabWidth - IMG_TAB_OFF[2].width - IMG_TAB_OFF[0].width);
}
//create link
var objA = document.createElement("a");
with (objA) {
setAttribute("class", "tabLink");
setAttribute("href", "javascript:clickTab(" +tab.id + ")");
innerHTML = tab.text;
}
objTD.appendChild(objA);
objTR.appendChild(objTD);
//begin last cell
objTD = document.createElement("td");
objIMG = document.createElement("img");
with (objIMG) {
setAttribute("src", IMG_TAB_OFF[2].filename);
setAttribute("height", IMG_TAB_OFF[2].height);
setAttribute("width", IMG_TAB_OFF[2].width);
setAttribute("id", "tab" + tab.id + "right");
}
objTD.appendChild(objIMG);
objTR.appendChild(objTD);
//add it all to the layer
objOwnerTD.appendChild(objTable);
} | [
"function _jsTabControl_draw() {\n\n\t//calculate tabsperstrip\n\tthis.tabsPerStrip = parseInt((window.innerWidth - IMG_BTN_MORE.width - IMG_BTN_LESS.width) / this.tabWidth);\n\n\t//calculate number of strips needed\n\tvar numStrips = Math.ceil(this.tabs.length / this.tabsPerStrip);\n\t\n\t//draw each strip\n\tfor (i=0; i < numStrips; i++)\n\t\tthis.createStrip(0 + (this.tabsPerStrip * i), this.tabsPerStrip + (this.tabsPerStrip * i));\n\n}",
"function addObjectTab(wnd, node, data, tab)\n{\n if (!node.parentNode)\n return;\n\n // Click event handler\n tab.setAttribute(\"href\", data.location);\n tab.setAttribute(\"class\", policy.objtabClass);\n tab.addEventListener(\"click\", generateClickHandler(wnd, data), false);\n\n // Insert tab into the document\n if (node.nextSibling)\n node.parentNode.insertBefore(tab, node.nextSibling);\n else\n node.parentNode.appendChild(tab);\n}",
"function updateHistoryTab(tab) {\n if (_historyObj && !isNaN(tab) && tab !== null) {\n _historyObj.tab = tab;\n } else {\n if (_historyObj) {\n delete _historyObj['tab'];\n }\n }\n } //****************************************************************",
"function _jsTabControl_turnTabOn(tabID) {\n\tdocument.getElementById('tab' + tabID + 'text').style.backgroundImage = \"url(\" + IMG_TAB_ON[1].filename + \")\";\n\tdocument.images['tab' + tabID + 'left'].src = IMG_TAB_ON[0].filename;\n\tdocument.images['tab' + tabID + 'right'].src = IMG_TAB_ON[2].filename;\t\t\n}",
"saveFocus(aTab) {\n aTab._focusedElement = aTab.folderDisplay.focusedPane;\n }",
"function changeTabTitle(obj, htmlId, dim, tab, edit, eventid) {\r\n\r\n\r\n var gridId = getGridIdOfHtmlId(htmlId);\r\n var gridObj = CurFuncObj.allGrids[gridId];\r\n var iO = getIndObjOfHtmlId(htmlId);\r\n\r\n var curtab = gridObj.dimSelectTabs[dim];\r\n\r\n gridObj.dimSelectTabs[dim] = tab;\r\n\r\n if (gridObj.dimHasTitles[dim])\r\n gridObj.dimTitles[dim][tab] = obj.innerHTML;\r\n else\r\n assert(0, \"updating tab that has no titles!\");\r\n\r\n // Redraw the grid only when the focus is lost (onblur) OR if the user\r\n // clicked on an un-selected tab. Otherwise, the tab currently being \r\n // edited lose focus\r\n //\r\n if ((eventid == 2) || (curtab != tab))\r\n drawGrid(gridObj, iO, htmlId, edit); // redraw grid\r\n}",
"function WebappTabActor(connection, browser)\n{\n BrowserTabActor.call(this, connection, browser);\n}",
"function TabDom(h, b) {\n this.head = h;\n this.body = b;\n }",
"function useTab(props) {\n var {\n isDisabled,\n isFocusable\n } = props,\n htmlProps = _objectWithoutPropertiesLoose(props, [\"isDisabled\", \"isFocusable\"]);\n\n var {\n setSelectedIndex,\n isManual,\n id,\n setFocusedIndex,\n enabledDomContext,\n domContext,\n selectedIndex\n } = useTabsContext();\n var ref = (0, _react.useRef)(null);\n /**\n * Think of `useDescendant` as the function that registers tab node\n * to the `enabledDomContext`, and returns it's index.\n *\n * Tab is registered if it's enabled or focusable\n */\n\n var enabledIndex = (0, _descendant.useDescendant)({\n disabled: Boolean(isDisabled),\n focusable: Boolean(isFocusable),\n context: enabledDomContext,\n element: ref.current\n });\n /**\n * Registers all tabs (whether disabled or not)\n */\n\n var index = (0, _descendant.useDescendant)({\n context: domContext,\n element: ref.current\n });\n var isSelected = index === selectedIndex;\n\n var onClick = () => {\n setFocusedIndex(enabledIndex);\n setSelectedIndex(index);\n };\n\n var onFocus = () => {\n var isDisabledButFocusable = isDisabled && isFocusable;\n var shouldSelect = !isManual && !isDisabledButFocusable;\n\n if (shouldSelect) {\n setSelectedIndex(index);\n }\n };\n\n var clickable = (0, _clickable.useClickable)(_extends({}, htmlProps, {\n ref: (0, _utils.mergeRefs)(ref, props.ref),\n isDisabled,\n isFocusable,\n onClick: (0, _utils.callAllHandlers)(props.onClick, onClick)\n }));\n var type = \"button\";\n return _extends({}, clickable, {\n id: makeTabId(id, index),\n role: \"tab\",\n tabIndex: isSelected ? 0 : -1,\n type,\n \"aria-selected\": isSelected ? true : undefined,\n \"aria-controls\": makeTabPanelId(id, index),\n onFocus: (0, _utils.callAllHandlers)(props.onFocus, onFocus)\n });\n}",
"function floatTab(tab, on) {\n if (on) {\n tab.node.classList.add(FLOATING_CLASS);\n }\n else {\n tab.node.classList.remove(FLOATING_CLASS);\n }\n }",
"function geoLingTabNode (tab) {\n this.value = tab;\n this.prev = null;\n}",
"function createTab(battingTeam, bowlingTeam) {\n // Batting info table\n let tabContent = `\n <table class=\"table\" border=\"1\">\n <tr class=\"table-secondary\">\n <th>Batter</th>\n <th>R</th>\n <th>B</th>\n <th>4/6</th>\n </tr>`;\n battingTeam.players.forEach((player) => {\n tabContent += `\n <tr id=\"${player.name}-bat\">\n <td>${player.name}</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n </tr>`;\n });\n\n // Bowling info table\n tabContent += `</table>\n <br>\n <table class=\"table\" border=\"1\">\n <tr class=\"table-secondary\">\n <th>Bowler</th>\n <th>O</th>\n <th>R</th>\n <th>W</th>\n </tr>`;\n bowlingTeam.players.forEach((player) => {\n tabContent += `\n <tr id=\"${player.name}-bowl\">\n <td>${player.name}</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n </tr>`;\n });\n\n // Scorecard summary\n tabContent += `</table>\n <p class=\"alert alert-warning p-1 text-center fw-bolder\">Total: \n <span id=\"${battingTeam.id}-total\" class=\"text-primary\">0</span>\n / <span id=\"${battingTeam.id}-wickets\" class=\"text-danger\">0</span>\n Overs: <span id=\"${battingTeam.id}-overs\" class=\"text-success\">0.0</span> (${match.totalOvers})\n </p>`;\n\n return tabContent;\n}",
"function mouseOverTab(i){\n\tvar n=i.substring(i.length-1,i.length);\n\tvar tab_body_display=document.getElementById(\"tab_body\"+n).style.display;\n\tif(tab_body_display==\"none\"){\n\t\tdocument.getElementById(i).style.borderBottomColor=\"white\";\n\t}\n}",
"function useTabIndicator() {\n var context = useTabsContext();\n var {\n selectedIndex,\n orientation,\n domContext\n } = context;\n var isHorizontal = orientation === \"horizontal\";\n var isVertical = orientation === \"vertical\"; // Get the clientRect of the selected tab\n\n var [rect, setRect] = (0, _react.useState)(() => {\n if (isHorizontal) return {\n left: 0,\n width: 0\n };\n if (isVertical) return {\n top: 0,\n height: 0\n };\n });\n var [hasMeasured, setHasMeasured] = (0, _react.useState)(false); // Update the selected tab rect when the selectedIndex changes\n\n (0, _hooks.useSafeLayoutEffect)(() => {\n var _tab$element;\n\n if ((0, _utils.isUndefined)(selectedIndex)) return;\n var tab = domContext.descendants[selectedIndex];\n var tabRect = tab == null ? void 0 : (_tab$element = tab.element) == null ? void 0 : _tab$element.getBoundingClientRect(); // Horizontal Tab: Calculate width and left distance\n\n if (isHorizontal && tabRect) {\n var {\n left,\n width\n } = tabRect;\n setRect({\n left,\n width\n });\n } // Vertical Tab: Calculate height and top distance\n\n\n if (isVertical && tabRect) {\n var {\n top,\n height\n } = tabRect;\n setRect({\n top,\n height\n });\n } // Prevent unwanted transition from 0 to measured rect\n // by setting the measured state in the next tick\n\n\n var frameId = requestAnimationFrame(() => {\n setHasMeasured(true);\n });\n return () => {\n cancelAnimationFrame(frameId);\n };\n }, [selectedIndex, isHorizontal, isVertical, domContext.descendants]);\n return _extends({\n position: \"absolute\",\n transition: hasMeasured ? \"all 200ms cubic-bezier(0, 0, 0.2, 1)\" : \"none\"\n }, rect);\n}",
"function tabrandomizer(){\r\n\tif ( randomtab == 1)\r\n\t{\r\n\ttab1();\r\n\t}\r\n\tif ( randomtab == 2)\r\n\t{\r\n\ttab2();\r\n\t}\r\n\tif ( randomtab == 3)\r\n\t{\r\n\ttab3();\r\n\t}\r\n}",
"function displayUserTab() {\n\n}",
"function i2uiSetTabFillerHeight(id)\r\n{\r\n var filler_obj = document.getElementById(id+\"_filler\");\r\n var tab_table_obj = document.getElementById(id);\r\n if (filler_obj != null && tab_table_obj != null)\r\n {\r\n var container_table_obj = tab_table_obj.parentNode;\r\n while (container_table_obj != null)\r\n {\r\n if (container_table_obj.tagName == 'TABLE')\r\n {\r\n break;\r\n }\r\n container_table_obj = container_table_obj.parentNode;\r\n }\r\n if (container_table_obj != null &&\r\n tab_table_obj != null)\r\n {\r\n //i2uitrace(1,\"container height=\"+container_table_obj.offsetHeight);\r\n //i2uitrace(1,\"tab height=\"+tab_table_obj.offsetHeight);\r\n filler_obj.style.height = container_table_obj.offsetHeight -\r\n tab_table_obj.offsetHeight;\r\n }\r\n }\r\n}",
"function updateTab(container, param)\n\t{\n\t\tvar selectHis = $.data(container, 'tabs').selectHis;\n\t\tvar pp = param.tab; // the tab panel\n\t\tvar oldUrl = pp.panel('options').url;\n\t\tpp.panel($.extend({},\n\t\tparam.options, {\n\t\t\ticonCls: (param.options.icon ? param.options.icon : undefined)\n\t\t}));\n\t\tvar opts = pp.panel('options'); // get the tab panel options\n\t\tvar tab = opts.tab;\n\t\tvar s_title = tab.find('span.tabs-title');\n\t\tvar s_icon = tab.find('span.tabs-icon');\n\t\ts_title.html(opts.title);\n\t\ts_icon.attr('class', 'tabs-icon');\n\t\ttab.find('a.tabs-close').remove();\n\t\tif (opts.closable)\n\t\t{\n\t\t\ts_title.addClass('tabs-closable');\n\t\t\t$('<a href=\"javascript:void(0)\" class=\"tabs-close\"></a>').appendTo(tab);\n\t\t} else\n\t\t{\n\t\t\ts_title.removeClass('tabs-closable');\n\t\t}\n\t\tif (opts.iconCls)\n\t\t{\n\t\t\ts_title.addClass('tabs-with-icon');\n\t\t\ts_icon.addClass(opts.iconCls);\n\t\t} else\n\t\t{\n\t\t\ts_title.removeClass('tabs-with-icon');\n\t\t}\n\t\tif (oldUrl != opts.url)\n\t\t{\n\t\t\tfor (var i = 0; i < selectHis.length; i++)\n\t\t\t{\n\t\t\t\tif (selectHis[i] == oldUrl)\n\t\t\t\t{\n\t\t\t\t\tselectHis[i] = opts.url;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttab.find('span.tabs-p-tool').remove();\n\t\tif (opts.tools)\n\t\t{\n\t\t\tvar p_tool = $('<span class=\"tabs-p-tool\"></span>').insertAfter(tab.find('a.tabs-inner'));\n\t\t\tif ($.isArray(opts.tools))\n\t\t\t{\n\t\t\t\tfor (var i = 0; i < opts.tools.length; i++)\n\t\t\t\t{\n\t\t\t\t\tvar t = $('<a href=\"javascript:void(0)\"></a>').appendTo(p_tool);\n\t\t\t\t\tt.addClass(opts.tools[i].iconCls);\n\t\t\t\t\tif (opts.tools[i].handler)\n\t\t\t\t\t{\n\t\t\t\t\t\tt.bind('click', {\n\t\t\t\t\t\t\thandler: opts.tools[i].handler\n\t\t\t\t\t\t},\n\t\t\t\t\t\tfunction (e)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif ($(this).parents('li').hasClass('tabs-disabled'))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\te.data.handler.call(this);\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else\n\t\t\t{\n\t\t\t\t$(opts.tools).children().appendTo(p_tool);\n\t\t\t}\n\t\t\tvar pr = p_tool.children().length * 12;\n\t\t\tif (opts.closable)\n\t\t\t{\n\t\t\t\tpr += 8;\n\t\t\t} else\n\t\t\t{\n\t\t\t\tpr -= 3;\n\t\t\t\tp_tool.css('right', '5px');\n\t\t\t}\n\t\t\ts_title.css('padding-right', pr + 'px');\n\t\t} //\t\tsetProperties(container);\n\t\t//\t\tsetScrollers(container);\n\t\tsetSize(container);\n\t\t$.data(container, 'tabs').options.onUpdate.call(container, opts.url, getTabIndex(container, pp));\n\t}",
"function _jsTabControl_turnTabOff(tabID) {\t\n\tdocument.getElementById('tab' + tabID + 'text').style.backgroundImage = \"url(\" + IMG_TAB_OFF[1].filename + \")\";\n\tdocument.images['tab' + tabID + 'left'].src = IMG_TAB_OFF[0].filename;\n\tdocument.images['tab' + tabID + 'right'].src = IMG_TAB_OFF[2].filename;\t\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function takes in a DOM object which represents a puzzle tile as parameter and returns in boolean whether that particular puzzle tile is ready to be moved. The only puzzle tiles that can be moved are the tiles adjacent to the empty tile. | function isMovable(tile) {
var currentX = tile.style.left;
var currentY = tile.style.top;
if (currentX == emptyX && Math.abs(parseInt(currentY) - parseInt(emptyY)) == SIZE ||
currentY == emptyY && Math.abs(parseInt(currentX) - parseInt(emptyX)) == SIZE){
return true;
} else {
return false;
}
} | [
"isValidMoveNew(row, column) {\n if (!isInBoundaries(row, column)) {\n return false;\n }\n if (!this.tileSet.hasTileAt(row, column)) {\n return false;\n }\n var dx = [1, 0, -1, 0];\n var dy = [0, 1, 0, -1];\n let thisTile = this.tileSet.getTileAt(row, column);\n for (var i = 0; i < 4; ++i) {\n // if the given cell's i'th neighbour has the same color as this\n // cell, then this move is valid\n var neighbourTile = this.tileSet.getTileAt(row + dx[i], column + dy[i]);\n if (thisTile.equalTo(neighbourTile)) {\n return true;\n }\n }\n // if we have not found any neighbours with the same color, then the\n // move is not valid\n return false;\n }",
"function is_next_to_blank(tile) {\n var isAdjacent = false;\n if (is_below_blank(tile) || is_above_blank(tile) || is_to_the_left_of_blank(tile) || is_to_the_right_of_blank(tile))\n {\n isAdjacent = true;\n }\n return isAdjacent;\n}",
"canMove(tile) {\r\n if (abs(tile.mapX - this.mapX) <= this.info.movement &&\r\n abs(tile.mapY - this.mapY) <= this.info.movement) {\r\n if (tile.unit) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n return false;\r\n }",
"function isValidMovePawn(fromRow, fromCol, toRow, toCol, tmpDir)\r\n\t{\r\n\t\tif (((toRow - fromRow)/Math.abs(toRow - fromRow)) != tmpDir)\r\n\t\t{\r\n\t\t\t//errMsg = \"Pawns cannot move backwards, only forward.\";\r\n\t\t\terrMsg = document.getElementById('#alert_err_move_pawn_id').innerHTML;\r\n\t\t\t\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\t/* standard move */\r\n\t\tif ((tmpDir * (toRow - fromRow) == 1) && (toCol == fromCol) && (board[toRow][toCol] == 0))\r\n\t\t\treturn true;\r\n\t\t/* first move double jump - white */\r\n\t\tif ((tmpDir == 1) && (fromRow == 1) && (toRow == 3) && (toCol == fromCol) && (board[2][toCol] == 0) && (board[3][toCol] == 0))\r\n\t\t\treturn true;\r\n\t\t/* first move double jump - black */\r\n\t\tif ((tmpDir == -1) && (fromRow == 6) && (toRow == 4) && (toCol == fromCol) && (board[5][toCol] == 0) && (board[4][toCol] == 0))\r\n\t\t\treturn true;\r\n\t\t/* standard eating */\r\n\t\telse if ((tmpDir * (toRow - fromRow) == 1) && (Math.abs(toCol - fromCol) == 1) && (board[toRow][toCol] != 0))\r\n\t\t\treturn true;\r\n\t\t/* en passant - white */\r\n\t\telse if ((tmpDir == 1) && (fromRow == 4) && (toRow == 5) && (board[4][toCol] == (PAWN | BLACK)))\r\n\t\t{\r\n\t\t\t/* can only move en passant if last move is the one where the white pawn moved up two */\r\n\t\t\tif ((chessHistory[numMoves][TOROW] == 4) && (chessHistory[numMoves][FROMROW] == 6) && (chessHistory[numMoves][TOCOL] == toCol))\r\n\t\t\t\treturn true;\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t//errMsg = \"Pawns can only move en passant immediately after an opponent played his pawn.\";\r\n\t\t\t\terrMsg = document.getElementById('#alert_err_move_passant_id').innerHTML;\r\n\t\t\t\t\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\t\t/* en passant - black */\r\n\t\telse if ((tmpDir == -1) && (fromRow == 3) && (toRow == 2) && (board[3][toCol] == PAWN))\r\n\t\t{\r\n\t\t\t/* can only move en passant if last move is the one where the black pawn moved up two */\r\n\t\t\tif ((chessHistory[numMoves][TOROW] == 3) && (chessHistory[numMoves][FROMROW] == 1) && (chessHistory[numMoves][TOCOL] == toCol))\r\n\t\t\t\treturn true;\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t//errMsg = \"Pawns can only move en passant immediately after an opponent played his pawn.\";\r\n\t\t\t\terrMsg = document.getElementById('#alert_err_move_passant_id').innerHTML;\r\n\t\t\t\t\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t//errMsg = \"Pawns cannot move like that.\";\r\n\t\t\terrMsg = document.getElementById('#alert_err_move_pawn_id').innerHTML;\r\n\t\t\t\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}",
"function getMoveable() {\n let re = []\n $('.tile').each((index, element) => {\n if (element.id != \"tileEmpty\") {\n isMoveable(element) ? re.push(element) : null;\n }\n });\n return re;\n}",
"function checkSolution() {\r\n if (tileMap.empty.position !== 3) {\r\n return false;\r\n }\r\n\r\n for (var key in tileMap) {\r\n if (key == 1 || key == 9) {\r\n continue;\r\n }\r\n\r\n var prevKey = key == 4 ? 'empty' : key == 'empty' ? 2 : key - 1;\r\n if (tileMap[key].position < tileMap[prevKey].position) {\r\n return false;\r\n }\r\n }\r\n\r\n // Clear history if solved\r\n history = [];\r\n return true;\r\n }",
"movePiece(p_index, t_index) {\n // Pull variables out of loop to expand scope\n let piece = null;\n let o_tile = null;\n let t_tile = null;\n\n // Look for old and new tiles by index\n for (let line of this.board) {\n for (let tile of line) {\n if (tile.index === p_index) {\n // Grap piece and old tile\n piece = tile.piece;\n o_tile = tile;\n }\n if (tile.index === t_index) {\n // Grab target tile\n t_tile = tile;\n }\n }\n }\n\n // Only move piece if old tile has one to move and move id valid\n // Make sure you can't take out your own pieces\n if (o_tile.piece && t_tile.valid) {\n if (o_tile.piece.color === this.turn) {\n if (t_tile.piece) {\n if (o_tile.piece.color !== t_tile.piece.color) {\n o_tile.piece = null;\n t_tile.piece = piece;\n this.turn = this.turn === 'black' ? 'white' : 'black'; \n }\n } else { \n o_tile.piece = null;\n t_tile.piece = piece;\n this.turn = this.turn === 'black' ? 'white' : 'black'; \n }\n }\n }\n\n // Reset all valid tags\n for (let line of this.board) {\n for (let tile of line) {\n tile.valid = false;\n }\n }\n }",
"hasReachedDestination() {\r\n\t\tvar destinationTiles = this.levelGrid.getDestination();\r\n\t\tfor (var i = 0; i < destinationTiles.length; i++) {\r\n\t\t\tvar destinationRow = destinationTiles[i].row;\r\n\t\t\tvar destinationColumn = destinationTiles[i].column;\r\n\t\t\tif ( this.currentTileRow === destinationRow\r\n\t\t\t\t && this.currentTileColumn === destinationColumn ) {\r\n\t\t\t\tthis.speed = 0;\r\n\t\t\t\treturn true;\r\n\t\t\t} \t\t\r\n\t\t}\r\n\t\treturn false;\r\n\t}",
"function canPass(xTile, yTile) {\n\tif (xTile < 0 || yTile < 0 || xTile >= gridWidth || yTile >= gridHeight) return false;\n\treturn !grid[xTile + yTile * gridWidth].blocks;\n}",
"function tileIsDone(_fb_tile_id) {\n var tile_instance = fb.child(fb_collage_id).child('Tile').child(_fb_tile_id);\n tile_instance.once('value', function(snap) {\n var tile = snap.val(); // dictionary\n console.log(tile);\n if (tile.filled) { // if tile is filled\n return true;\n } else {\n return false;\n }\n })\n}",
"function dropPiece(evt, availableTiles, startx, starty)\n{\n var correct = 0; //variable that decides if the piece was placed in the correct spot\n for(var i = 0; i < availableTiles.length;i++)\n {\n if(intersect(availableTiles[i]))\n {\n correct = 1;\n evt.currentTarget.x = availableTiles[i].x;\n evt.currentTarget.y = availableTiles[i].y;\n var x = evt.currentTarget.gridx;\n var y = evt.currentTarget.gridy;\n var tilex = availableTiles[i].gridx;\n var tiley = availableTiles[i].gridy;\n grid[x][y].placedPiece = \"\"; //since the piece has been moved the starting square is free now\n if(grid[tilex][tiley].placedPiece != \"\")\n {\n stage.removeChild(grid[tilex][tiley].placedPiece); //removes the piece that was on that square from the board\n }\n grid[tilex][tiley].placedPiece = evt.currentTarget; //updates the grid to show that there's a piece on the board at that location\n evt.currentTarget.gridx = tilex;\n evt.currentTarget.gridy = tiley;\n\n break;\n }\n }\n cleanBoard(availableTiles); // cleans the board of all pieces\n\n if(correct == 0) // if the piece was not placed in the correct place, then return it to it's original square.\n {\n evt.currentTarget.x = grid[startx][starty].x;\n evt.currentTarget.y = grid[startx][starty].y;\n }\n else { //if the piece was moved then a turn was made and swap turns and update info\n var startSquare = starty*8+x;\n var endSquare = evt.currentTarget.gridy*8+evt.currentTarget.gridx;\n\n moveMade(startSquare, endSquare); //updates the internal logic of the game\n }\n\n parseFen(fenstr); //refreshes the board\n stage.update();\n}",
"function moveElement(playingArea, element) {\n\n //Initialization of the different elements used to modify html document\n var puzzleArea = document.getElementById(\"puzzlearea\");\n var puzzlePieces = puzzleArea.getElementsByTagName(\"div\");\n\n //Conditions that check the directions in which the puzzle piece can be moved\n if(playingArea[element - 1][0] == 16){\n \n return movePieceUp(playingArea, element, puzzlePieces);\n }\n else if(playingArea[element - 1][1] == 16){\n \n return movePieceRight(playingArea, element, puzzlePieces);\n }\n else if(playingArea[element - 1][2] == 16){\n \n return movePieceDown(playingArea, element, puzzlePieces);\n }\n else if(playingArea[element - 1][3] == 16){\n\n return movePieceLeft(playingArea, element, puzzlePieces);\n }\n}",
"function validTile(x, y) {\n if (x > (xmax - 1) || (x < 0)) {\n return false;\n }\n\n if (y > (ymax - 1) || (y < 0)) {\n return false;\n }\n return true;\n}",
"function checkAdjacentTiles(cx, cy, wordTreeNode, tileLetter, strWorkString, wordLen)\n{\n var x,y;\n\n // Append the new tile letter to the currently built word\n strWorkString = strWorkString + tileLetter;\n\n // Now check all adjacent tiles, including diagonals\n for (x = cx - 1; x <= cx + 1; x++) {\n for (y = cy - 1; y <= cy + 1; y++) {\n // Make sure to stay within board boundaries\n if ((x >= 0) && (x < boardTiles.length) && (y >= 0) && (y < boardTiles[x].length)) {\n // Don't use tiles which are currently occupied\n if (boardTileUsed[x][y] == 0) {\n // Feed in :\n // * offset from current working tile (x,y)\n // * child node by-letter of of the current radix/trie word tree\n // * current word length\n // * current working string\n if (wordTreeNode[ tileLetter ])\n checkBoardTile(x, y, wordTreeNode[ tileLetter ], wordLen, strWorkString);\n }\n }\n }\n }\n}",
"static removeCheck(sRow, sCol, pRow, pCol, board, turn) {\n const takenSpot = board[sRow][sCol];\n console.log(board[pRow][pCol]);\n board[sRow][sCol] = board[pRow][pCol];\n board[pRow][pCol] = null;\n const checkColor = turn === 'white' ? 'black' : 'white';\n for (let i = 0; i < 8; i++) {\n for (let j = 0; j < 8; j++) {\n // getting enemy pieces\n const atkr = board[i][j];\n console.log(atkr);\n if (atkr && atkr !== 'enpassant' && atkr.color !== checkColor) {\n const movesArr = atkr.movement(i, j, board);\n\n // checking if our king is in their movelist\n for (let k = 0, n = movesArr.length; k < n; k++) {\n const atkd = board[movesArr[k][0]][movesArr[k][1]];\n\n if (atkd && atkd instanceof King && atkd.color === checkColor) {\n console.log('still in check');\n board[pRow][pCol] = board[sRow][sCol];\n board[sRow][sCol] = takenSpot;\n return false;\n }\n }\n }\n }\n }\n board[pRow][pCol] = board[sRow][sCol];\n board[sRow][sCol] = takenSpot;\n return true;\n }",
"function isValidMoveQueen(fromRow, fromCol, toRow, toCol)\r\n\t{\r\n\t\tif (isValidMoveRook(fromRow, fromCol, toRow, toCol) || isValidMoveBishop(fromRow, fromCol, toRow, toCol))\r\n\t\t\treturn true;\r\n\r\n\t\tif (errMsg.search(\"jump\") == -1)\r\n\t\t\t//errMsg = \"Queens cannot move like that.\";\r\n\t\t\terrMsg = document.getElementById('#alert_err_move_queen_id').innerHTML;\r\n\t\telse\r\n\t\t\t//errMsg = \"Queens cannot jump over other pieces.\";\r\n\t\t\terrMsg = document.getElementById('#alert_err_move_queen_jump_id').innerHTML;\r\n\r\n\t\treturn false;\r\n\t}",
"function checkAllLegalMoves(oldPosition, faction, isFirstTurn){\n let oldPositionDiv = document.getElementById(oldPosition)\n let splitPosition = oldPosition.split(\"\")\n let letter = splitPosition[0]\n let number = splitPosition[1]\n\n //black goes up; black is 0 and K\n //kings and queens should have access to both sides' move options trees\n if (faction === \"black\" || oldPositionDiv.innerText === \"K\" || oldPositionDiv.innerText === \"Q\"){ \n //increments and decrements letter of new position (\"B\" becomes \"C\" and \"A\")\n let columnA = String.fromCharCode(letter.charCodeAt(0) + 1)\n let columnB = String.fromCharCode(letter.charCodeAt(0) - 1)\n let row = checkAboveRow(number)\n // below lines concatenate new column with row\n let newPositionA = columnA.concat(checkAboveRow(number)).toString()\n let newPositionB = columnB.concat(checkAboveRow(number)).toString()\n \n if (validColumn(columnA) && validRow(row)) {\n let moveDivA = document.getElementById(newPositionA)\n //if potential space to move in is empty, push it into validMoves Array\n if (moveDivA.innerText === \"\" && isFirstTurn){\n validMovesArray.push(newPositionA)\n }\n //else, if potential space to move in is occupied by opposite team\n //check if that's a possible attack opening\n if (moveDivA.innerText === \"1\"){\n //get rid of determinedirection???\n \n let direction = determineBlackDirection(oldPosition, newPositionA)\n blackAttack(newPositionA, direction)\n }\n } \n if (validColumn(columnB) && validRow(row)) {\n let moveDivB = document.getElementById(newPositionB)\n //if potential space to move in is empty, push it into validMoves Array\n if (moveDivB.innerText === \"\" && isFirstTurn){\n validMovesArray.push(newPositionB)\n }\n //else, if potential space to move in is occupied by opposite team\n //check if that's a possible attack opening\n if (moveDivB.innerText === \"1\"){ \n let direction = determineBlackDirection(oldPosition, newPositionB)\n blackAttack(newPositionB, direction)\n } \n }\n }\n //white goes down; white is 1 and Q\n //kings and queens should have access to both sides' moves options trees\n if (faction === \"white\" || oldPositionDiv.innerText === \"K\" || oldPositionDiv.innerText === \"Q\" ) {\n //increments and decrements letter of new position (\"B\" becomes \"C\" and \"A\")\n let columnA = String.fromCharCode(letter.charCodeAt(0) + 1)\n let columnB = String.fromCharCode(letter.charCodeAt(0) - 1)\n let row = checkBelowRow(number)\n // below lines concatenate new column with row\n let newPositionA = columnA.concat(checkBelowRow(number)).toString()\n let newPositionB = columnB.concat(checkBelowRow(number)).toString()\n\n //below two lines concatenate new columns with below row\n if (validColumn(columnA) && validRow(row)) {\n let moveDivA = document.getElementById(newPositionA)\n //if potential space to move in is empty, push it into validMoves Array\n if (moveDivA.innerText === \"\" && isFirstTurn){\n validMovesArray.push(newPositionA)\n }\n //else, if potential space to move in is occupied by opposite team\n //check if that's a possible attack opening\n if (moveDivA.innerText === \"0\"){\n let direction = determineWhiteDirection(oldPosition, newPositionA)\n whiteAttack(newPositionA, direction)\n }\n } \n if (validColumn(columnB) && validRow(row)) {\n let moveDivB = document.getElementById(newPositionB)\n //if potential space to move in is empty, push it into validMoves Array\n if (moveDivB.innerText === \"\" && isFirstTurn){\n validMovesArray.push(newPositionB)\n }\n //else, if potential space to move in is occupied by opposite team\n //check if that's a possible attack opening\n if (moveDivB.innerText === \"0\"){\n let direction = determineWhiteDirection(oldPosition, newPositionB)\n whiteAttack(newPositionB, direction)\n }\n } \n }\n }",
"function enableTileIfPresent([iRow, iCol]) {\n if (\n iRow < 0 ||\n iRow >= gridSize ||\n iCol < 0 ||\n iCol >= gridSize ||\n tiles[iRow][iCol].taken\n ) return false;\n else {\n document.getElementById(`tileR${iRow}C${iCol}`).disabled = false;\n return true;\n }\n}",
"function isValidMoveBishop(fromRow, fromCol, toRow, toCol)\r\n\t{\r\n\t\tif (Math.abs(toRow - fromRow) == Math.abs(toCol - fromCol))\r\n\t\t{\r\n\t\t\tif (toRow > fromRow)\r\n\t\t\t{\r\n\t\t\t\tif (toCol > fromCol)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (i = 1; i < (toRow - fromRow); i++)\r\n\t\t\t\t\t\tif (board[fromRow + i][fromCol + i] != 0)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t//errMsg = \"Bishops cannot jump over other pieces.\";\r\n\t\t\t\t\t\t\terrMsg = document.getElementById('#alert_err_move_bishop_jump_id').innerHTML;\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (i = 1; i < (toRow - fromRow); i++)\r\n\t\t\t\t\t\tif (board[fromRow + i][fromCol - i] != 0)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t//errMsg = \"Bishops cannot jump over other pieces.\";\r\n\t\t\t\t\t\t\terrMsg = document.getElementById('#alert_err_move_bishop_jump_id').innerHTML;\r\n\t\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif (toCol > fromCol)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (i = 1; i < (fromRow - toRow); i++)\r\n\t\t\t\t\t\tif (board[fromRow - i][fromCol + i] != 0)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t//errMsg = \"Bishops cannot jump over other pieces.\";\r\n\t\t\t\t\t\t\terrMsg = document.getElementById('#alert_err_move_bishop_jump_id').innerHTML;\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (i = 1; i < (fromRow - toRow); i++)\r\n\t\t\t\t\t\tif (board[fromRow - i][fromCol - i] != 0)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t//errMsg = \"Bishops cannot jump over other pieces.\";\r\n\t\t\t\t\t\t\terrMsg = document.getElementById('#alert_err_move_bishop_jump_id').innerHTML;\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t//errMsg = \"Bishops cannot move like that.\";\r\n\t\t\terrMsg = document.getElementById('#alert_err_move_bishop_id').innerHTML;\r\n\t\t\t\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes a new instance of `XMLComment` `text` comment text | constructor(parent, text) {
super(parent);
if (text == null) {
throw new Error("Missing comment text. " + this.debugInfo());
}
this.name = "#comment";
this.type = NodeType.Comment;
this.value = this.stringify.comment(text);
} | [
"function createTextElement(text) {\n return new VirtualElement(0 /* Text */, text, emptyObject, emptyArray);\n }",
"function extractCommentText(text) {\n\t\n\tvar lines = text.split(\"\\n\")\n\n\tvar start = /^\\/\\*+/,\n\t\t\tlineStart = /^[ \\t]*\\*[ ]?/,\n\t\t\tend = /\\*+\\//;\n\n\tfor (var i = 0; i < lines.length; i++) {\n\t\t\n\t\tif (i === 0) {\n\t\t\tlines[0] = lines[0].replace(start, \"\");\n\t\t}\n\t\t\n\t\tif (i === lines.length - 1) {\n\t\t\tlines[i] = lines[i].replace(end, \"\");\n\t\t\tlines[i] = lines[i].replace(lineStart, \"\");\n\t\t} else {\n\t\t\tlines[i] = lines[i].replace(lineStart, \"\");\n\t\t}\n\t\t\n\t}\n\t\n\treturn lines.join(\"\\n\");\n}",
"function createCommentElement(comment) {\n const commentElement = document.createElement('li');\n commentElement.className = 'comment';\n\n const textElement = document.createElement('span');\n textElement.innerText = comment.text;\n\n commentElement.appendChild(textElement);\n return commentElement;\n}",
"function initComments() {\n const $comments = $('.comment-item');\n $comments.each((ind, comment) => {\n const $comment = $(comment);\n initComment($comment);\n });\n }",
"function Text(attrs) {\n var dflt = {\n content: \"\",\n fill: \"black\",\n font: \"12pt Helvetica\",\n height: 12\n };\n attrs = mergeWithDefault(attrs, dflt);\n Drawable.call(this, attrs);\n\t//constructor code \n this.content=attrs.content;\n this.fill = attrs.fill; \n this.font = attrs.font;\n this.height = attrs.height;\n this.left = attrs.left;\n}",
"function onCommentChange(event) {\n setCommentText(event.target.value);\n }",
"tokenizeComment(offset) {\n const start = offset;\n common_1.matcher.commentGreedy.lastIndex = offset;\n const match = common_1.matcher.commentGreedy.exec(this.cssText);\n if (match == null) {\n offset = this.cssText.length;\n }\n else {\n offset = common_1.matcher.commentGreedy.lastIndex;\n }\n return new token_1.Token(token_1.Token.type.comment, start, offset);\n }",
"createText(){\n let text = Text.createText(this.activeColor);\n this.canvas.add(text);\n this.notifyCanvasChange(text.id, \"added\");\n }",
"comments(node, { value: text, type }) {\n return type === 'comment2' && bannerRegex.test(text)\n }",
"function changeComments(text) {\n var editor = ace.edit(\"editor\");\n var pos = editor.getSession().getDocument().indexToPosition(0, 0);\n editor.getSession().getDocument().insert(pos, text);\n}",
"function construct(){\n if( typeof( commentIdOrData ) == \"object\" ){\n data = commentIdOrData;\n } else {\n data[\"commentId\"] = commentIdOrData;\n }\n\n var $comment = $( \"#comment-\" + data[\"commentId\"] );\n \n var retrievedHTML = false; \n var html = '';\n\n if( $comment.length ){\n html = $comment.get();\n retrievedHTML = true;\n }\n\n if( !retrievedHTML ){\n html = generateHTML();\n if(html){ \n retrievedHTML = true;\n }\n } \n\n $.when(\n ajaxGetThread(\n {\n c: $this.getData( \"commentId\" ), \n single: true\n },\n {\n dataFilter: function( d, t ){\n d = JSON.parse( d );\n data = WPTCComment.convertDataForClient( d[0] );\n return JSON.stringify( data );\n }\n }, retrievedHTML )\n ).done( function( htmlR ){\n \n /**\n * If html code hasn't been generated yet, create it using\n * data from ajax call.\n */\n if( !html ){\n data[\"defaults\"] = false;\n properties[\"remote\"] = true;\n data = htmlR;\n html = generateHTML(); \n }\n\n if( data[\"defaults\"] ){\n data = WPTCComment.readDataFromHTML( html ); \n }\n\n // Attach generated html code to DOM\n if( $comment.length == 0 ){ \n $dom[\"list\"] = $( html ).appendTo( wptcO.wptcCommentsStorage );\n } else { \n $dom[\"list\"] = $comment;\n }\n\n $dom[\"dropzone\"] = $( wptcO.wptcDropzone.generateHTML( $this ) ).appendTo( wptcO.wptcCommentsStorageDropzone ); \n \n $dom[\"list\"].data( \"wptcCommentObject\", $this );\n $dom[\"dropzone\"].data( \"wptcCommentObject\", $this );\n \n $this.draggabify().droppabify();\n\n //Bind expand/collapse links \n $dom[\"list\"].find( \"a.tc-show-more\" ).live( \"click\", function(){ $this.expandSubthread()} );\n $dom[\"list\"].find( \"a.tc-show-less\" ).live( \"click\", function(){ $this.collapseSubthread()} );\n\n //If there was any callback passed, call it.\n if( callback ){\n callback( $this, $dom[\"list\"] );\n } \n }); \n }",
"convertDocCommentToParagraph() {\n let result = this.props.text;\n // Strip \"<summary>\", \"</summary>\"\n result = result.replace(/<summary>/g, '');\n result = result.replace(/<\\/summary>/g, '');\n // Strip \"<para>\", \"</para>\"\n result = result.replace(/<para>/g, '');\n result = result.replace(/<\\/para>/g, '');\n // Strip \"///\"\n result = result.replace(/\\/\\/\\//g, '');\n // Strip extra consecutive spaces\n result = result.replace(/[ \\t]+/g, ' ');\n // Delete whitespace from blank lines\n result = result.replace(/\\n\\s+\\n/g, '\\n\\n');\n // Delete single newlines (leaving multi-newline paragraph breaks).\n // (Credit: Tim Pietzcker - http://stackoverflow.com/a/18012521/12484 )\n result = result.replace(/(^|[^\\n])\\n(?!\\n)/g, \"$1\");\n // Clean up remaining leading whitespace on each line\n result = result.replace(/\\n[ \\t]+/g, '\\n');\n result = result.trim();\n this.props.setText(result);\n }",
"function setTextContent(node, value) {\n if (predicates_1.isCommentNode(node)) {\n node.data = value;\n }\n else if (predicates_1.isTextNode(node)) {\n node.value = value;\n }\n else {\n const tn = modification_1.constructors.text(value);\n tn.parentNode = node;\n node.childNodes = [tn];\n }\n}",
"function addCommentElement(postElement, id, text, author) {\n\tvar comment = document.createElement('div');\n\tcomment.classList.add('comment-' + id);\n\tcomment.innerHTML = '<span class=\"username\"></span><span class=\"comment\"></span>';\n\tcomment.getElementsByClassName('comment')[0].innerText = text;\n\tcomment.getElementsByClassName('username')[0].innerText = author;\n\n\tvar commentsContainer = postElement.getElementsByClassName('comments-container')[0];\n\tcommentsContainer.appendChild(comment);\n}",
"function makeTextNode(token) {\n var node = makeObj(baseTextNode);\n node.text = token;\n return node;\n }",
"function Comment(github, item, data) {\n this.github = github;\n this.item = item;\n this.data = data;\n }",
"function DocEdit_initialize(text, priorNodeSegment, weight, relativeNode, optionFlags)\n{\n //public\n this.text = text;\n\n if (priorNodeSegment && dw.nodeExists(priorNodeSegment.node))\n {\n this.priorNodeSegment = priorNodeSegment;\n this.priorNode = priorNodeSegment.node || false;\n this.matchRangeMin = priorNodeSegment.matchRangeMin || 0;\n this.matchRangeMax = priorNodeSegment.matchRangeMax || 0;\n\n if (this.matchRangeMin == this.matchRangeMax)\n {\n // If we are here, we were given a priorNodeSegment which, though non-null and\n\t // in existance, is in fact bogus. Therefore, act like we were given no\n\t // priorNodeSegment at all (i.e., given a null for that param). It is dangerous\n\t // to use priorNodeSegment without clearing it here because we apparently have\n\t // data with bad integrety at this point.\n\t \n alert(\"ERROR: bad node segment offsets\");\n\t priorNodeSegment = null;\n }\n }\n \n if (!priorNodeSegment)\n {\n this.priorNode = false;\n this.matchRangeMin = -1;\n this.matchRangeMax = -1;\n }\n\n this.weight = weight || \"\"; //aboveHTML[+nn], belowHTML[+nn],\n //beforeSelection, afterSelection, replaceSelection,\n //beforeNode, afterNode, replaceNode,\n //nodeAttribute[+attribname]\n this.node = relativeNode || null; //optional: only used with \"...Node\" weights\n \n this.dontMerge = (optionFlags & docEdits.QUEUE_DONT_MERGE);\n\n this.dontPreprocessText = (optionFlags & docEdits.QUEUE_DONT_PREPROCESS_TEXT);\n this.dontFormatForMerge = (optionFlags & docEdits.QUEUE_DONT_FORMAT_FOR_MERGE);\n\n this.defaultWeight = 99;\n this.version = 5.0;\n\n //private\n this.insertPos = null;\n this.replacePos = null;\n this.bDontMergeTop = false;\n this.bDontMergeBottom = false;\n\n\n this.weightType = \"\"; //weight *might* have a preword, like aboveHTML or nodeAttribute\n this.weightNum = null; //weight *might* include a number (set below)\n this.weightInfo = \"\"; //weight *might* have extra info, like an attribute name (set below)\n\n //Initialize weight, weightNum, and weightInfo properties\n //Determine correct weight type, and assign extra weight properties\n if (this.weight)\n {\n //if weight is just number, change to aboveHTML+number\n if (this.weight == String(parseInt(this.weight))) //if just number (old style)\n {\n this.weightNum = parseInt(this.weight); //convert if number\n this.weightType = \"aboveHTML\";\n this.weight = this.weightType + \"+\" + this.weight; //default is aboveHTML\n }\n //if extra weight info (someWeight+someData), extract data\n else if (this.weight.indexOf(\"+\") > 0)\n {\n var data = this.weight.substring(this.weight.indexOf(\"+\")+1);\n this.weightType = this.weight.substring(0,this.weight.indexOf(\"+\"));\n\n //if weight is ??+number, extract the number\n if (data == String(parseInt(data)))\n {\n this.weightNum = parseInt(data); //convert if number\n\n //if weight is ??+??, save data as info\n }\n else\n {\n this.weightInfo = data;\n }\n }\n //if weight is aboveHTML or belowHTML, add default weight number\n else if (this.weight == \"aboveHTML\" || this.weight == \"belowHTML\")\n {\n this.weightType = this.weight;\n this.weight += \"+\"+String(this.defaultWeight);\n this.weightNum = this.defaultWeight;\n }\n //for backward compatibility,convert \"afterDocument\" to \"belowHTML\"\n else if (this.weight == \"afterDocument\")\n {\n this.weightType = \"belowHTML\";\n this.weight = this.weightType + \"+\" + String(this.defaultWeight);\n this.weightNum = this.defaultWeight;\n }\n }\n else //default if no weight given\n {\n this.weight = \"aboveHTML+\"+String(this.defaultWeight);\n this.weightType = \"aboveHTML\";\n this.weightNum = this.defaultWeight;\n }\n\n // Only merge above and below the HTML tag. Merging within\n // the body can cause problems with translators.\n if (this.weightType != \"aboveHTML\" && this.weightType != \"belowHTML\")\n {\n this.preventMerge = true;\n }\n\n}",
"function Comment(id, user, body, date, post, parent){\n this.id = id; // id of user\n this.post = post; // date of root post\n //this.user = user;\n this.body = body;\n this.date = date.getTime();\n this.parent = parent; // date of previous comment, 0 if parent is root post\n this.more = 0;\n this.less = 0;\n this.score = 0;\n}",
"function GenerateNewText() {\n // Add property to the object\n this.sentences =\n [\n \"Do it.\",\n \"Just do it.\",\n \"Don't let your dreams be dreams.\",\n \"Yesterday you said tomorrow.\",\n \"So just do it.\",\n \"Make your dreams come true.\",\n \"Just do it.\",\n \"Some people dream of success.\",\n \"While you're gonna wake up and work hard at it.\",\n \"Nothing is impossible.\",\n \"You should get to the point.\",\n \"Where anyone else would quit.\",\n \"And you're not going to stop there.\",\n \"No.\",\n \"what are you waiting for?\",\n \"Do it.\",\n \"Just do it.\",\n \"Yes you can.\",\n \"Just do it.\",\n \"If you're tired of starting over.\",\n \"Stop giving up.\"\n ];\n}",
"function createComment(user, comment) {\n return {\n user: user,\n comment: comment\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cut via the keyboard | function KeyCut(evt)
{
var nKeyCode;
nKeyCode = GetKeyCode(evt);
switch (nKeyCode)
{
case 13: //enter
Cut();
break;
default:
//do nothing
break;
}
} | [
"handleCopyCut(event) {\n event.stopPropagation();\n let activeNode = this.getActiveNode();\n if(!activeNode) return;\n\n // If nothing is selected, say \"nothing selected\" for cut\n // or copy the clipboard to the text of the active node\n if(this.selectedNodes.size === 0) {\n if(event.type == 'cut') {\n this.say(\"Nothing selected\");\n return;\n } else if(event.type == 'copy') {\n this.clipboard = this.cm.getRange(activeNode.from, activeNode.to);\n }\n // Otherwise copy the contents of selection to the buffer, first-to-last\n } else {\n let sel = [...this.selectedNodes].sort((a, b) => poscmp(a.from, b.from));\n this.clipboard = sel.reduce((s,n) => s + this.cm.getRange(n.from, n.to)+\" \",\"\");\n }\n\n this.say((event.type == 'cut'? 'cut ' : 'copied ') + this.clipboard);\n this.buffer.value = this.clipboard;\n this.buffer.select();\n try {\n document.execCommand && document.execCommand(event.type);\n } catch (e) {\n console.error(\"execCommand doesn't work in this browser :(\", e);\n }\n // if we cut selected nodes, clear them\n if (event.type == 'cut') { this.deleteSelectedNodes(); } // delete all those nodes if we're cutting\n else { activeNode.el.focus(); } // just restore the focus if we're copying\n }",
"function copyOrCut(notebook, cut) {\n if (!notebook.model || !notebook.activeCell) {\n return;\n }\n const state = getState(notebook);\n const clipboard = Clipboard.getInstance();\n notebook.mode = 'command';\n clipboard.clear();\n const data = notebook.widgets\n .filter(cell => notebook.isSelectedOrActive(cell))\n .map(cell => cell.model.toJSON())\n .map(cellJSON => {\n if (cellJSON.metadata.deletable !== undefined) {\n delete cellJSON.metadata.deletable;\n }\n return cellJSON;\n });\n clipboard.setData(JUPYTER_CELL_MIME, data);\n if (cut) {\n deleteCells(notebook);\n }\n else {\n notebook.deselectAll();\n }\n handleState(notebook, state);\n }",
"function KeyPaste(evt)\r\n{\r\n var nKeyCode;\r\n nKeyCode = GetKeyCode(evt);\r\n switch (nKeyCode)\r\n {\r\n case 13: //enter\r\n Paste();\r\n break;\r\n default:\r\n //do nothing\r\n break;\r\n }\r\n}",
"function moveCaret(win, charCount) {\n var sel, range;\n if (win.getSelection) {\n sel = win.getSelection();\n if (sel.rangeCount > 0) {\n var textNode = sel.focusNode;\n var newOffset = sel.focusOffset + charCount;\n sel.collapse(textNode, Math.min(textNode.length, newOffset));\n }\n } else if ( (sel = win.document.selection) ) {\n if (sel.type != \"Control\") {\n range = sel.createRange();\n range.move(\"character\", charCount);\n range.select();\n }\n }\n}",
"handleBoardKeyPress(e) {\n if (!this.state.helpModalOpen && !this.state.winModalOpen) {\n if (49 <= e.charCode && e.charCode <= 57) {\n this.handleNumberRowClick((e.charCode - 48).toString());\n // undo\n } else if (e.key === \"r\") {\n this.handleUndoClick();\n // redo\n } else if (e.key === \"t\") {\n this.handleRedoClick();\n // erase/delete\n } else if (e.key === \"y\") {\n this.handleEraseClick();\n // notes\n } else if (e.key === \"u\") {\n this.handleNotesClick();\n }\n }\n }",
"function delete_function() {\r\n\tvar delete_end_char = textarea_element.selectionEnd;\r\n\tif (delete_end_char < textarea_element.value.length && delete_end_char == textarea_element.selectionStart) {\r\n\t\tdelete_end_char++;\r\n\t}\r\n\ttextarea_element.setRangeText(\"\", textarea_element.selectionStart, delete_end_char, \"end\");\r\n\ttextarea_element.focus();\r\n\tscroll_to_cursor();\r\n\tupdate_printable_table(); \r\n}",
"keyControl() {\n\n if (keyIsDown(this.activateKey)) {\n this.bossManipulation = true;\n } else {\n this.bossManipulation = false;\n }\n }",
"function strikeThrough() {\n document.execCommand('strikeThrough', false, '');\n browser.storage.local.set({\n key: txtArea.innerHTML\n });\n}",
"function keyDownZoom(e){\n deleteDefault(e);\n spaceKey(e);\n rightArrowKey(e);\n leftArrowKey(e);\n}",
"function move_cursor_right_to_100_and_back() \n{\n\ttry{\n\t\tvar sel = E._frame.selection;\n\t\tvar r = sel.createRange();\n\t\tr.moveEnd(\"character\", -100);\n\t\tr.moveStart(\"character\", -100);\n\t\tr.collapse(false);\n\t\tr.select();\n\t} catch(e){}\n}",
"function pfKeyRun() {\n if (pfq.length && ide.wins[0].promptType && !blk) {\n const { text, cmd } = pfq.shift();\n const w = D.ide.focusedWin;\n if (text) w.insert(text);\n else w.execCommand(cmd);\n }\n if (pfq.length) pfqtid = setTimeout(pfKeyRun, D.prf.floating() ? 100 : 20);\n else pfqtid = 0;\n }",
"function keyReleased() { \r\n if (key != ' ') {\r\n ship.setDir(0);\r\n }\r\n}",
"function add_character_move_cursor(input_string) {\r\n\ttextarea_element.setRangeText(input_string, textarea_element.selectionStart, textarea_element.selectionEnd, \"end\");\r\n\t//textarea_element.focus();\r\n\tscroll_to_cursor();\r\n\tupdate_printable_table();\r\n}",
"function keyPressed() {\n changeSnakeDir(keyCode);\n}",
"function selectKnCell(e){\n\tvar knCell = keynapse.currentKnCell;\n\tstopKeynapse();\n\n\tif(knCell.type == 'text'){\n\t\t$(knCell).focus();\t\t\n\t} else {\n\t\t$(knCell).focus();\n\t\t$(knCell).trigger(\"click\");\n\t}\n}",
"function DEL () {\n\t\tscreenDown.innerHTML = screenDown.innerHTML.slice(0,-1);\n\t\tsetNbsp();\n\t}",
"function remove(keyCode) {\n var state = getState();\n if (keyCode === DELETE_KEYCODE && state.selection.start === state.selection.end &&\n\tstate.value.charAt(state.selection.start) === ',') {\n state.selection.start ++;\n state.selection.end ++;\n }\n removeExtraStuff(state);\n if (state.selection.start !== state.selection.end) {\n state.value = clearRange(state.value, state.selection.start, state.selection.end);\n } else if (keyCode === BACKSPACE_KEYCODE) {\n state.value = clearRange(state.value, state.selection.start - 1, state.selection.start);\n } else if (keyCode === DELETE_KEYCODE) {\n state.value = clearRange(state.value, state.selection.start, state.selection.start + 1);\n }\n var moveRight = state.selection.start === state.selection.end && keyCode === DELETE_KEYCODE;\n addExtraStuff(state, moveRight);\n setState(state);\n }",
"static async ctrlClick(selector) {\n return JQueryAction.click(selector, {ctrlKey: true});\n }",
"clip() {\n var seen = 0, toClip = this.events - this.maxEvents\n for (let i = 0;; i++) {\n let cur = this.items[i]\n if (cur.selection) {\n if (seen < toClip) {\n ++seen\n } else {\n this.items.splice(0, i, new Item(null, this.events[toClip - 1]))\n this.events = this.maxEvents\n return\n }\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Exit a parse tree produced by Java9ParserexceptionTypeList. | exitExceptionTypeList(ctx) {
} | [
"exitExceptionType(ctx) {\n\t}",
"visitExit_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"exitTryExpression(ctx) {\n\t}",
"exitElementValueList(ctx) {\n\t}",
"enterExceptionTypeList(ctx) {\n\t}",
"visitExceptions_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitException_declaration(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"exitTypeModifierList(ctx) {\n\t}",
"exitMultiVariableDeclaration(ctx) {\n\t}",
"exitStatementWithoutTrailingSubstatement(ctx) {\n\t}",
"exitTypeArgumentList(ctx) {\n\t}",
"exitOrdinaryCompilation(ctx) {\n\t}",
"exitElementValuePairList(ctx) {\n\t}",
"exitSingleTypeImportDeclaration(ctx) {\n\t}",
"exitEnumEntry(ctx) {\n\t}",
"exitBlockLevelExpression(ctx) {\n\t}",
"exitElvisExpression(ctx) {\n\t}",
"exitVariableDeclaratorList(ctx) {\n\t}",
"visitException_handler(ctx) {\n\t return this.visitChildren(ctx);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is a synthetic lifecycle hook which gets inserted into `TView.preOrderHooks` to simulate `ngOnChanges`. The hook reads the `NgSimpleChangesStore` data from the component instance and if changes are found it invokes `ngOnChanges` on the component instance. | function rememberChangeHistoryAndInvokeOnChangesHook() {
const simpleChangesStore = getSimpleChangesStore(this);
const current = simpleChangesStore === null || simpleChangesStore === void 0 ? void 0 : simpleChangesStore.current;
if (current) {
const previous = simpleChangesStore.previous;
if (previous === EMPTY_OBJ) {
simpleChangesStore.previous = current;
}
else {
// New changes are copied to the previous store, so that we don't lose history for inputs
// which were not changed this time
for (let key in current) {
previous[key] = current[key];
}
}
simpleChangesStore.current = null;
this.ngOnChanges(current);
}
} | [
"static emitChanges() {\n changedStores.forEach(store => store.emitChange());\n changedStores.clear();\n }",
"track() {\n const snapShot = () => {\n return JSON.stringify(this.fields.reduce((obj, key) => {\n obj[key] = this.ctx[key];\n return obj;\n }, {}))\n }\n\n const changeListener = () => {\n this.hasFieldChanges = this.oldState !== snapShot();\n }\n\n this.oldState = snapShot();\n changeListener();\n observe(this.ctx, changeListener);\n }",
"function handleModelChange(newValue, oldValue) {\n\t\t\t// If we try to call render right away, two things will go wrong:\n\t\t\t// first, we won't give the ngValue directive time to pipe the\n\t\t\t// correct value into ngModle; and second, it will force an\n\t\t\t// undesirable repaint of the browser. As such, we'll perform the\n\t\t\t// Uniform synchronization at a later point in the $digest.\n\t\t\tscope.$evalAsync(synchronizeUniform);\n\t\t}",
"function HandleChangeHook(rootComponent, payloadPath) {\n this.rootComponent = rootComponent;\n this.payloadPath = payloadPath;\n}",
"changed() {\n ++this.revision_;\n this.dispatchEvent(EventType.CHANGE);\n }",
"handleInnerCollectionChanges(collection, changes) {\n // guard against source expressions that have observable side-effects that could\n // cause an infinite loop- eg a value converter that mutates the source array.\n if (this.ignoreMutation) {\n return;\n }\n this.ignoreMutation = true;\n let newItems = this.sourceExpression.evaluate(this.scope, this.lookupFunctions);\n this.observerLocator.taskQueue.queueMicroTask(() => this.ignoreMutation = false);\n\n // collection change?\n if (newItems === this.items) {\n return;\n }\n this.items = newItems;\n this.itemsChanged();\n }",
"_setOnChange() {\n let self = this;\n this.onChange = function() {\n self.value = self.innerGetValue(); // Update inner value\n if (self._onChangeCB) self._onChangeCB.call(self); // call user defined callback\n };\n this.innerMapOnChange(); // Map the event that will trigger onChange\n }",
"onChangeStorage(changes, type) {\n if (type === 'local' && State.windowFocused) return\n\n if (changes.settings) {\n Store.dispatch('updateSettings', changes.settings.newValue)\n Store.dispatch('reloadOptPermissions')\n }\n if (changes.styles) Store.dispatch('applyStyles', changes.styles.newValue)\n if (changes.containers) {\n Store.dispatch('updateContainers', changes.containers.newValue)\n }\n }",
"handleNoChangeEvent() {\n \n }",
"hydrateOnUpdate() {\n return true;\n }",
"haveChanges() {\n return this.code !== this.codeFromTableau;\n }",
"context(newValue, oldValue) {\n // Emit context information for external paging/filtering/sorting handling\n if (!looseEqual(newValue, oldValue)) {\n this.$emit(EVENT_NAME_CONTEXT_CHANGED, newValue)\n }\n }",
"_checkIfDirty(){\n if (this._isDirty === true){\n this._isDirty = false;\n this._refresh();\n }\n }",
"observe() {\n if(this.observer) {\n this.unobserve();\n }\n this.observer = jsonPatchObserve(this.didDocument);\n }",
"onModelChange(value) {\n this.newValue = value\n }",
"modelChanged() {\n }",
"function handleModifiedEvent(event) {\n setModified(true);\n}",
"function addRecordsChangedListeners(datastore) {\n\n var rcTargetCb = rcCbBuilder(targetTable, templateTable, renderTarget, renderTemplate);\n var rcPingCb = rcCbBuilder(pingTable, targetTable, renderPing, renderTarget);\n var rcTemplateCb = rcCbBuilder(templateTable, templateTable, renderTemplate, renderTemplate);\n\n datastore.recordsChanged.addListener(rcTargetCb);\n datastore.recordsChanged.addListener(rcPingCb);\n datastore.recordsChanged.addListener(rcTemplateCb);\n }",
"_onAppliedUpdate(view, metadata) {\n if (view && _.isFunction(view.afterApplyUpdate)) {\n view.afterApplyUpdate(metadata);\n }\n }",
"_onApplyingUpdate(view, metadata) {\n if (view && _.isFunction(view.beforeApplyUpdate)) {\n view.beforeApplyUpdate(metadata);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clean log entries (keep only the ones generated less than one minute ago) | processEntries() {
let previousMinute = new Date();
// One minute ago.
previousMinute = previousMinute.setMinutes(previousMinute.getMinutes() - 1);
// Keep only "new" log entries (less than 1 minute)
this.logEntries = reduce(this.logEntries, (list, entry) => {
if (entry >= previousMinute) {
list.push(entry);
}
return list;
}
, {});
} | [
"function cleanLog() {\n\tredis.zremrangebyscore('modLog', 0, Date.now() - 1000*60*60*24*7,\n\t\tfunction (err) {\n\t\t\tif (err)\n\t\t\t\twinston.error('Error cleaning up moderation log:', err);\n\t\t}\n\t);\n}",
"#removeExpiredTimestamps(key) {\n const timestampsArray = this.#apiCallTimeStamps[key]\n const now = Date.now()\n const oneMinuteAgo = now - 1000\n let index = 0\n while (index < timestampsArray.length && timestampsArray[index] <= oneMinuteAgo) {\n index += 1\n }\n\n timestampsArray.splice(0, index)\n }",
"function cleanLog() {\n cleanFolder(join(submitFolder, \"Logs\"));\n}",
"static cleanUpOldGames() {\n let expiredTime = new Date(Date.now());\n expiredTime.setHours(expiredTime.getHours() - 6);\n let date = expiredTime.toLocaleDateString('en-US');\n let time = expiredTime.toLocaleTimeString('en-US');\n let fullExpiredTime = new Date(`${date} ${time}`);\n let gameList = Game.loadGames();\n\n gameList = gameList.filter((g) => {\n // only return Games that have a CreatedOn greater than the expiredTime meaning they were made after that time\n return new Date(g.CreatedOn) > fullExpiredTime;\n });\n\n let gameJSON = JSON.stringify(gameList);\n\n fs.writeFileSync('./data/currentGames.json', gameJSON);\n }",
"function purgeMessages(room) {\n var oldestTimestampAllowed = new Date().getTime() - room.max_message_age;\n models.Message.remove({ roomId: room._id, timestamp: { $lt: oldestTimestampAllowed }},\n function(err) {\n if(err) console.error('Error trimming documents for room ' + room.name + ':', err);\n });\n }",
"flushHistory() {\n const currDate = new Date();\n for (let i = 0; i < this.history.length; i += 1) {\n const diff = (currDate - new Date(this.history[i].date));\n if (diff / (1000 * 3600 * 24 * 365) > 1) {\n this.history.splice(i, 1);\n }\n }\n localStorage.setItem('statsHistory', JSON.stringify(this.history));\n }",
"static cleaner() {\n console.log(\n \"STORE: Bucket cleaner started, cleaning every\",\n this.cleaningInterval,\n \"ms\"\n );\n\n const clean = () => {\n timeOut = setTimeout(clean, this.cleaningInterval);\n\n console.log(\"STORE: cleaning bucket\");\n\n const timeago = 3600000 * this.expiresAfter;\n const dateInTimePast = Date.now() - timeago;\n //Linear lookup for all keys.\n for (const key of Object.keys(this.bucket)) {\n // Copy of key in bucket to avoid data mismanagement while unshifting\n // main bucket\n const copy = this.bucket[key];\n for (let i = 0; i < copy.length; i++) {\n if (copy[i].time < dateInTimePast) this.bucket[key].unshift();\n // break when condition is not met,\n // since data is by default sorted in time order\n else break;\n }\n }\n };\n\n let timeOut = setTimeout(clean, this.cleaningInterval);\n }",
"function maintainLogSize() {\n while ($scope.logs.length > MAX_LOG_SIZE) {\n $scope.logs.shift();\n }\n }",
"clearLogs() {\n Instabug.clearLogs();\n }",
"function τSST_clear_logs() {\n for (var item in localStorage) {\n if (item.startsWith(storage_key_prefix + 'stat_logs_') ||\n item.startsWith(storage_key_prefix + \"stats_\")) {\n console.log('τSST_clear_logs(): Removing localStorage item: ' + item);\n localStorage.removeItem(item);\n }\n }\n\n // Also clear internal data that affects logging.\n stats = {};\n stat_logs = {};\n nodes.stats_collection.text(\"\");\n\n is_storage_initialized = false;\n }",
"function deleteDateInfoAll(timestamp)\n{\n\tdeleteDateInfo(timestamp, true, true, true, true);\n}",
"function removeOldNotifications() {\n // Only set up Cron Job when not in Test mode.\n if (!Meteor.isTest && !Meteor.isAppTest) {\n const frequency = 'every hour';\n SyncedCron.add({\n name: 'Checks for notifications that are older than a week and removes them from db',\n schedule(parser) {\n return parser.text(frequency); // Parser is a later.js parse object.\n },\n job() {\n console.log('Running job: removeOldNotifications');\n const date = new Date(Date.now() - (8 * 24 * 60 * 60 * 1000));\n Notifications.remove({ timestamp: { $lt: date } });\n },\n });\n console.log(`Starting cron job to remove old notifications ${frequency}`);\n SyncedCron.start();\n }\n}",
"function filterSessions(){\n var now = Date.now();\n for(let key of sessions.keys()){\n time = sessions.get(key);\n if(MAX_LOGIN_TIME + time < now){\n console.log(key + \"'s session expired\");\n sessions.delete(key);\n }\n }\n}",
"function removeDeadUsers() {\n users = users.filter(function(user) {\n return Math.round((Date.now()-user.time)) < 20000;});\n console.log(\"Removed dead users\");\n}",
"cleanUp() {\n state.getAllStates((err, states) => {\n if (err) return console.log('CLEANUP FAILED: ', err.message);\n\n if (states.length) {\n _.each(states, s => {\n const timeSince = moment\n .duration(moment().diff(s.updatedAt))\n .asMinutes();\n\n if (timeSince > 30) {\n state.deleteChat(s.chatId, err => {\n if (err) return console.log('CLEANUP FAILED', err.message);\n console.log('CLEANUP: ', s.chatId);\n });\n }\n });\n } else {\n console.log('NOTHING TO CLEANUP');\n }\n });\n }",
"function removeVisitedThreeDaysOld() {\n const currentTime = new Date().getTime();\n const refUserVisited = database.ref('users/' + firebase.currentUser.uid + \"/visited\");\n refUserVisited\n .orderByChild(\"dateVisited\").endAt(currentTime - 259200000).once(\"value\", function (snap) {\n snap.forEach(function (child) {\n refUserVisited.child(child.key).remove();\n })\n })\n }",
"visitMv_log_purge_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function pruneUtts(utts) {\n if (Object.keys(utts).length < 10) return utts\n\n const slicedKeys = Object.keys(utts).sort((a, b) => {\n const aTime = parseInt(utts[a][0].timestamp, 10)\n const bTime = parseInt(utts[b][0].timestamp, 10)\n if (aTime < bTime) {\n return 1\n } else if (bTime < aTime) {\n return -1\n } else {\n return 0\n }\n }).slice(0, 7)\n\n const newUtts = {}\n for (const key of slicedKeys)\n newUtts[key] = utts[key]\n\n return newUtts\n}",
"function formatWatchdog(alert) {\n\n return getTimestampString((new Date()).toISOString()) + ' ' +\n '[' + getTimestampString(alert.startsAt) + '] ' + \n '(' + alert.status + ') ' +\n alert.alertname;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
isPointInRect checks if a point, 'pt', is in, a rectangle with cooridinates 'rpt', with size 'rsz' (point,point,point) | function isPointInRect(pt,rpt, rsz){
//logic that checks a point is in a rectangle
if(!(pt.x < rpt.x || pt.y < rpt.y
|| pt.x > rpt.x + rsz.x || pt.y > rpt.y + rsz.y)){
//alert();
return true;
}else
return false;
} | [
"function isRectTouching(pt1,sz1,pt2,sz2){\n\t//check if all 4 of the corners of rect1 are in this\n\treturn isPointInRect(pt1,pt2,sz2)//topleft\n\t\t|| isPointInRect(new point(pt1.x +sz1.x,pt1.y),pt2,sz2)//top right\n\t\t|| isPointInRect(new point(pt1.x +sz1.x,pt1.y + sz1.y),pt2,sz2)//bot right\n\t\t|| isPointInRect(new point(pt1.x,pt1.y + sz1.y),pt2,sz2);//bot left\n\n}",
"function checkInsideBoundingBox(bound, pt)\n{\n\tif (pt.x < bound.lower_bound.x || pt.x > bound.higher_bound.x) {\n\t\treturn false;\n\t}\n\tif (pt.y < bound.lower_bound.y || pt.y > bound.higher_bound.y) {\n\t\treturn false;\n\t}\n\tif (pt.z < bound.lower_bound.z || pt.z > bound.higher_bound.z) {\n\t\treturn false;\n\t} \n\treturn true;\n}",
"function inBounds(p) {\n // check bounds of display\n if((p[0]-2*bcr) <= width * 0.1 || //left\n (p[0]+2*bcr) >= width - (width * 0.1) || //right\n (p[1]-2*bcr) <= height * 0.1 ||\n (p[1]+2*bcr) >= height - (height * 0.1)) {\n return false;\n }\n return true;\n}",
"function isInBounds(point) {\n\t\tif (point >= bounds.sw && point <= bounds.nw) {\n\t\t\tconsole.log(\"point in bounds\");\n\t\t}\n\t}",
"function insideAnyPolygon(point, vs) { \r\n if(typeof vs == 'string'){\r\n\t vs = JSON.parse(vs);\t \r\n }\r\n if(typeof point == 'string'){\r\n\t point = JSON.parse(point);\t \r\n }\r\n var isInside = false; \r\n var isArray = Array.isArray(vs);\r\n var lengthArray = 0;\r\n if(isArray){\r\n \tlengthArray = vs.length;\r\n } \r\n for (var dim = 0; dim < lengthArray; dim++) {\r\n\t \tconsole.log(\"polygon dimension: \"+dim)\r\n\t \t//console.log(vs[dim])\r\n\t \tisInside = isInside || inside(point, vs[dim]);\r\n\t \tconsole.log(\"Point is inside polygon: \"+isInside) \r\n\t \tif(isInside) return isInside;\r\n } \r\n return isInside;\r\n}",
"function pointIsInCanvas(x, y, w, h) {\n return x >= 0 && x <= w && y >= 0 && y <= h;\n}",
"function includes(b, p) {\n return p.x >= b.x && p.x <= b.x + b.width && p.y >= b.y && p.y <= b.y + b.height;\n}",
"function isRectLayer(layer) {\n\tvar method = layer._method;\n\treturn (method === $.fn.drawRect || method === $.fn.drawEllipse || method === $.fn.drawImage);\n}",
"function isMouseInRect(rect, mousePosX, mousePosY) {\r\n // x-boundary\r\n const xStart = rect.xStart;\r\n const xEnd = rect.xStart + rect.width;\r\n // y-boundary\r\n const yStart = rect.yStart;\r\n const yEnd = rect.yStart + rect.height;\r\n\r\n // is inside\r\n if (mousePosX >= xStart &&\r\n mousePosX <= xEnd &&\r\n mousePosY >= yStart &&\r\n mousePosY <= yEnd) {\r\n return true;\r\n }\r\n\r\n // is not inside\r\n return false;\r\n}",
"function isInside(rw, rh, rx, ry, x, y)\n{\n return x <= rx+rw && x >= rx && y <= ry+rh && y >= ry // Get Click Inside a Bush\n}",
"intersectsPoint(a, b) {\n if (!b) {\n var x2 = a.x;\n var y2 = a.y;\n } else {\n var x2 = a;\n var y2 = b;\n }\n const x = this.x;\n const y = this.y;\n const w = this.width;\n const h = this.height;\n return x2 >= x && x2 <= x + w && y2 >= y && y2 <= y + h;\n }",
"function check_point(p) {\n if (p.x < 0 || p.x > 9) {\n return false;\n } else if (p.y < 0 || p.y > 9) {\n return false;\n } else if (spielfeld[p.y][p.x]) {\n //console.log(\"point already in use:\", p);\n return false;\n } else {\n //console.log(\"point ok:\", p);\n return true;\n }\n}",
"contains(x, y) {\r\n return inside([x, y], this.polygon);\r\n }",
"function getRect(points) {\n var minX, minY, maxX, maxY;\n \n for (var ii = points.length; ii--; ) {\n var xy = points[ii];\n \n // update the min x and min y\n minX = (typeof minX === 'undefined') || xy.x < minX ? xy.x : minX;\n minY = (typeof minY === 'undefined') || xy.y < minY ? xy.y : minY;\n \n // update the max x and max y\n maxX = (typeof maxX === 'undefined') || xy.x > maxX ? xy.x : maxX;\n maxY = (typeof maxY === 'undefined') || xy.y > maxY ? xy.y : maxY;\n } // for\n \n return xyRectTools.init(minX, minY, maxY, maxY); \n }",
"function perturbedRect(x, y, width, height, X_PERTURB, Y_PERTURB){\n\n\tvar topLeft = {x:(x + s.random(width*X_PERTURB) - (width*X_PERTURB*.5)), \n\t y:(y + s.random(height*Y_PERTURB) - (height*Y_PERTURB*.5))};\n\tvar topRight = {x:(x + width + s.random(width*X_PERTURB) - (width*X_PERTURB*.5)), \n\t y:(y + s.random(height*Y_PERTURB) - (height*Y_PERTURB*.5))};\n\tvar bottomRight = {x:(x + width + s.random(width*X_PERTURB) - (width*X_PERTURB*.5)),\n\t y:(y + height + s.random(height*Y_PERTURB) - (height*Y_PERTURB*.5))};\n\tvar bottomLeft = {x:(x + s.random(width*X_PERTURB) - (width*X_PERTURB*.5)),\n\t y:(y + height + s.random(height*Y_PERTURB) - (height*Y_PERTURB*.5))};\n\n\ts.line(topLeft.x, topLeft.y, topRight.x, topRight.y);\n\ts.line(topRight.x, topRight.y, bottomRight.x, bottomRight.y);\n\ts.line(bottomRight.x, bottomRight.y, bottomLeft.x, bottomLeft.y);\n\ts.line(bottomLeft.x, bottomLeft.y, topLeft.x, topLeft.y);\n}",
"function isOnButton(x, y, btn) {\n var inXBounds = (x >= btn.rect[0]) && (x <= btn.rect[0] + btn.rect[2]);\n var inYBounds = (y >= btn.rect[1]) && (y <= btn.rect[1] + btn.rect[3]);\n return inXBounds && inYBounds;\n}",
"function isPointInView(p) {\n for (var i = 0; i < view_plane_normals.length; i++)\n if (dot([p.x-camera_location.x, \n\t\t\t\t\t p.y-camera_location.y, \n\t\t\t\t\t\t p.z-camera_location.z], \n\t\t\t\t\t\t view_plane_normals[i]) < -0.001)\n return false\n return true\n}",
"contains(x, y) {\r\n if (!this.isEnabled()) return false;\r\n if (x < this.at().x || x > (this.at().x + this.width())) return false;\r\n if (y < this.at().y || y > (this.at().y + this.height())) return false;\r\n return true;\r\n }",
"function point_in_object_list (objs, pt, margin) {\n var found_objs = []\n var obj = objs\n\n for (var i in objs) {\n\tvar o = objs[i]\n\tif (o.pt_in_object(pt, margin)) {\n\t found_objs.push(o)\n\t}\n }\n\n if (found_objs.length > 0)\n\treturn found_objs\n else\n\treturn null\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
new TemplateSet( name_String, options_Object ) | constructor ( name, options = {} ) {
if (name === undefined) throw new Error('Pass a name to TemplateSet')
// The name of the template set to use.
// This will be used as the directory in `base_path` to read the template from
this.base_name = name
// The base path where the named template sets live
// `{ base_path: '/path/to/dir/housing/template/dirs' }`
this.base_path = _.defaultTo( options.base_path, path.join(__dirname, '..', 'template') )
// The path to output rendered templates to
// `{ output_path: '/path/to/write/files/generated' }`
this.output_path = _.defaultTo( options.output_path, path.join(__dirname, '..', 'tmp') )
// Vars to render templates with`
// `{ name: 'a name', description: 'Sample Description' }`
this.properties = _.defaultTo( options.properties, {} )
debug('using properties', this.properties)
// Replace existing files
// `{ replace: true }`
this.replace = !!options.replace
// Options to pass to directly to handlebars
// `{ handlebar_options: { strict: false } }`
this.handlebar_options = {strict: true, noEscape: true}
//this.files = Walk.dir(this.path).catch(error => this.error = error)
} | [
"_setTemplate () {\n if (this._options.templatePath) {\n this._template = this._options.templatePath\n return\n }\n const generationTemplates = templates[this._options.generation]\n if (!generationTemplates) {\n throw new Error(`Generation not supported: ${generationTemplates}`)\n }\n this._template = generationTemplates[this._options.semicolons ? 'semicolons' : 'default']\n }",
"function setTemplate() {\n return {\n species: \"\",\n nickname: \"\",\n gender: \"\",\n ability: \"\",\n evs: statTemplate(0),\n ivs: statTemplate(31),\n nature: \"\",\n item: \"\",\n moves: [],\n other: {},\n };\n}",
"getTemplate(tname) {\n let template = this.templates[tname]\n if (!template) {\n template = new Template(this, tname);\n this.templates[tname] = template;\n }\n return template;\n }",
"function setupTemplateList() {\n // load the templates, then load the accounts\n // working around missing accounts ui functionality at the moment\n __acctsServiceCall = EmailApp.Util.callService(\"palm://com.palm.service.accounts/listAccountTemplates\", {\n capability: \"MAIL\"\n }, function (resp) {\n\n if (!resp.results.length) {\n console.log(\"### oh my. We don't have any templates\");\n return;\n }\n that.templateList = resp.results;\n resp.results.forEach(function (elem) {\n if (!that.accountTemplates[elem.templateId]) {\n that.accountTemplates[elem.templateId] = elem;\n }\n });\n __acctsServiceCall = undefined;\n // now load the accounts\n refresh();\n });\n }",
"constructor() {\n if (TemplateHolder._instance) {\n return TemplateHolder._instance;\n }\n TemplateHolder._instance = this;\n \n this._parts = {};\n }",
"static generate_settings() {\n // Initialise variables\n var html_content = {}\n var html_heading = {}\n\n // Setup content and heading variables\n for (var item of this.settings_json[\"categories\"]) {\n html_content[item] = \"\"\n\n html_heading[item] = this.html_settings_heading\n .replace(/{{item}}/g, item)\n }\n\n // Loop through setttings JSON and create HTML file\n for (var item of this.settings_json[\"settings\"]) {\n\n var category = item[\"category\"]\n\n // Select correct template based on advanced setting or not\n var temp_out\n if (item[\"advanced\"]) {\n temp_out = this.html_settings_advanced\n } else {\n temp_out = this.html_settings\n }\n\n // Replace variables\n temp_out = temp_out\n .replace(/{{title}}/g, item[\"title\"])\n .replace(/{{id}}/g, item[\"id\"])\n .replace(/{{unit}}/g, item[\"unit\"])\n .replace(/{{help}}/g, item[\"help\"])\n\n // Update main string\n html_content[category] = html_content[category].concat(temp_out)\n }\n\n var temp_html = \"\"\n for (item of this.settings_json[\"categories\"]) {\n temp_html = temp_html\n .concat(html_heading[item])\n .concat(html_content[item])\n }\n\n // Update HMTL on page\n document.querySelector(\"#settings_template_div\").innerHTML = temp_html\n }",
"function addTemplate(name, fn) {\n templates[name] = fn;\n}",
"constructor(directory, sqlTemplateRoot, options={}) {\n const sqlFilePath = [directory, sqlTemplateRoot].join(path.sep),\n sqlTemplateFiles = klawSync(sqlFilePath),\n templateLoader = new nunjucks.FileSystemLoader(sqlFilePath),\n envOpts = options.environment || {\n autoescape: false,\n throwOnUndefined: true,\n watch: true,\n tags: {\n commentStart: '/*',\n commentEnd: '*/'\n }\n }\n this.directory = directory\n this.sqlTemplateRoot = sqlTemplateRoot\n\n Object.defineProperty(this, 'env', {\n writable: false,\n enumerable: false,\n value: new nunjucks.Environment(templateLoader, envOpts)\n })\n\n Object.entries(filters).forEach(kv => {\n this.env.addFilter(kv[0], kv[1])\n })\n this.env.addFilter()\n\n var templates = sqlTemplateFiles.map(this.setupTemplateObject.bind(this))\n .filter(template => !!template.ext)\n\n templates.forEach(template => this.setupTemplateNamespaces(template))\n try {\n var self = this\n Object.defineProperty(this, 'loadCSV', {\n enumerable: true,\n writable: false,\n value: function (context) {\n return self.env.renderString(loadCSV, context)\n }\n })\n } catch (err) {\n console.error(err)\n }\n }",
"function workOrderTemplateNamesCallback(response) {\n // If the response is good, add clear then populate the templates drop-down list.\n}",
"getTemplate(name) {\n return this.templates.find(template => template.name === name);\n }",
"function FileTemplateAdder() {\n\tvar tempOptions = {\n\t\t'{{Jpeg}}': '.JPG',\n\t\t'{{Trans}}': 'Needs trans',\n\t\t'{{Imagequality}}': 'Poor quality'\n\t};\n if (wgUserGroups.indexOf(\"sysop\") != -1) {\n tempOptions['{{SDS}}'] = \"SDS\";\n }\n\tvar tempOptStr = '';\n\tfor(i in tempOptions) {\n\t\ttempOptStr += '<option value=\"' + i + '\" style=\"text-align:center;\">' + tempOptions[i] + '</option>';\n\t}\n \tvar html = '<p style=\"text-align:center;\" class=\"TemplateAdder\"><select id=\"FileTemplateAdder\">' + tempOptStr + '</select> <a class=\"wikia-button\" style=\"margin:0 1em; cursor:pointer;\" id=\"templateSubmit\">Add template</a>';\n\t$('#filetoc').append(html);\n\t$('#templateSubmit').click(function(event) {\n\t\tthis.innerHTML = '<img src=\"https://images.wikia.nocookie.net/dev/images/8/82/Facebook_throbber.gif\" style=\"vertical-align: baseline;\" border=\"0\" />';\n\t\t$.getJSON(\"/api.php\", {action: \"query\", prop: \"info\", titles: wgPageName, intoken: \"edit\", format: \"json\", indexpageids: 1}, function(json) {\n\t\t\tvar pageIdentification = json.query.pageids[0];\n\t\t\tvar pageToken = json.query.pages[pageIdentification].edittoken;\n\t\t\t$.post(\"/api.php\", {action: \"edit\", title: wgPageName, token: pageToken, bot: true, prependtext: $('#FileTemplateAdder').val() + \"\\n\"}, function (result) {$(\".TemplateAdder\").remove();});\n\t\t});\n\t});\n}",
"useTemplateLoader(templateLoader: TemplateLoader): void {\n this.templateLoader = templateLoader;\n }",
"constructor(templateFolder) {\n this.templateFolder = templateFolder;\n this.logger = new logger_1.Logger('template.manager:', config.logLevel);\n this.templates = this.loadTemplates();\n }",
"function loadTemplates(){\n for(let name of templates.toLoad) loadTemplate(name);\n}",
"function template_edit()\n{\n}",
"getV3TemplatesGitlabCiYmlsName(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.TemplatesApi()\n/*let name = \"name_example\";*/ // String | The name of the template\napiInstance.getV3TemplatesGitlabCiYmlsName(incomingOptions.name, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"static fromJSON(template, templateParsingOptions) {\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_assertions_TemplateParsingOptions(templateParsingOptions);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, this.fromJSON);\n }\n throw error;\n }\n return new Template(template, templateParsingOptions);\n }",
"function createGenresSelect(container, genres) {\n for (var i = 0; i < genres.length; i++) {\n var option = $(\".template option\").clone();\n option.val(genres[i][\"id\"]).text(genres[i][\"name\"])\n container.append(option);\n }\n}",
"function makeHtml(options) {\n options = options || {};\n\n var parts, fnCounter, propId, props;\n\n // Tagged function can be called multiple times, need to generate unique\n // IDs and track unique values per full use (until html.done is called).\n function reset() {\n parts = [];\n fnCounter = 0;\n propId = props = undefined;\n }\n reset();\n\n // The html() function used for the tagged template string. Call\n // html.done() to get the final string result.\n function html(strings, ...values) {\n strings.forEach(function(str, i) {\n // If there is no following value, at the end, just return;\n if (i >= values.length) {\n parts.push(str);\n return;\n }\n\n var value = values[i];\n if (!options.toStringAll &&\n typeof value !== 'string' &&\n !(value instanceof EscapedValue)) {\n // Check for propName=\" as the end of the previous string, if so, it\n // is a name to a property to be set/called later with the value.\n var match = propRegExp.exec(str);\n // data-prop should go the string path, since that is a defined HTML\n // API that maps to element.dataset.prop.\n if (match && match[1].indexOf('data-') !== 0) {\n if (propId === undefined) {\n propId = (idCounter++);\n }\n\n var propValueId = 'id' + (fnCounter++);\n\n if (!props) {\n props = {};\n }\n\n var propName = match[1];\n // Convert a-prop-name to aPropName\n if (propName.indexOf('-') !== -1) {\n propName = propName.split('-').map(function(part, partIndex) {\n return partIndex === 0 ?\n part : part.charAt(0).toUpperCase() + part.substring(1);\n }).join('');\n }\n\n props[propValueId] = {\n value: value,\n propName: propName\n };\n\n value = propValueId;\n\n // Swap out the attribute name to be specific to this html() use,\n // to make query selection faster and targeted.\n str = str.substring(0, match.index) + ' data-htemplateprop' +\n propId + '=\"';\n }\n }\n\n parts.push(str);\n\n if (value instanceof EscapedValue) {\n value = value.escapedValue;\n } else {\n if (typeof value !== 'string') {\n value = String(value);\n }\n value = esc(value);\n }\n parts.push(value);\n });\n }\n\n // Generates the final response by concatenating the previous html`` calls\n // into the final result.\n html.done = function() {\n var text = parts.join('');\n\n if (propId !== undefined) {\n // Process the text to replace multiple data-htemplateprop attributes\n // with one that groups the values. Otherwise the browser will just keep\n // the first value.\n text = groupProps(propId, text);\n }\n\n var result = {\n text: text\n };\n\n if (propId !== undefined) {\n result.propId = propId;\n result.props = props;\n }\n\n reset();\n\n return result;\n };\n\n return html;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find a valid program address Valid program addresses must fall off the ed25519 curve. This function iterates a nonce until it finds one that when combined with the seeds results in a valid program address. | static async findProgramAddress(seeds, programId) {
let nonce = 255;
let address;
while (nonce != 0) {
try {
const seedsWithNonce = seeds.concat(Buffer.from([nonce]));
address = await this.createProgramAddress(seedsWithNonce, programId);
} catch (err) {
if (err instanceof TypeError) {
throw err;
}
nonce--;
continue;
}
return [address, nonce];
}
throw new Error(`Unable to find a viable program address nonce`);
} | [
"static async createProgramAddress(seeds, programId) {\n let buffer = Buffer.alloc(0);\n seeds.forEach(function (seed) {\n if (seed.length > MAX_SEED_LENGTH) {\n throw new TypeError(`Max seed length exceeded`);\n }\n\n buffer = Buffer.concat([buffer, toBuffer(seed)]);\n });\n buffer = Buffer.concat([buffer, programId.toBuffer(), Buffer.from('ProgramDerivedAddress')]);\n let hash = await sha256$1(new Uint8Array(buffer));\n let publicKeyBytes = new bn$1(hash, 16).toArray(undefined, 32);\n\n if (is_on_curve(publicKeyBytes)) {\n throw new Error(`Invalid seeds, address must fall off the curve`);\n }\n\n return new PublicKey(publicKeyBytes);\n }",
"async function genSegWitAddr() {\n\n\tconst mnemonics = mnemonic.generateMnemonic(); //generates string\n const seed = await bip39.mnemonicToSeed(mnemonics);\n const root = hdkey.fromMasterSeed(seed);\n\n\tconst masterPrivateKey = root.privateKey.toString('hex');\n\tconst masterPublicKey = root.publicKey.toString('hex');\n\n\tconst addrnode = root.derive(\"m/44'/0'/0'/0/0\");\n\tconsole.log(addrnode._publicKey);\n\n\tconst step1 = addrnode._publicKey;//Get your public key\n\tconst step2 = createHash('sha256').update(step1).digest(); //Perform SHA-256 hashing on the public key\n\tconst step3 = createHash('rmd160').update(step2).digest(); //Perform RIPEMD-160 hashing on the result of SHA-256\n\n\tvar step4 = Buffer.allocUnsafe(21);//Add version byte in front of RIPEMD-160 hash (0x00 for mainnet, 0x6f for testnet)\n\tstep4.writeUInt8(0x00, 0);\n\tstep3.copy(step4, 1); //step4 now holds the extended RIPMD-160 result\n\n\tconst step9 = bs58check.encode(step4);\n\tconsole.log('Base58Check: ' + step9);\n\treturn step9;\n\t\n}",
"walletIsValid(address) {\n return DigiByte.Address.isValid(address);\n }",
"function inputForAddress (address, allInputs) {\n try {\n const addressUTXO = utxoForAddress(address)\n for (let i = 0; i < allInputs.length; i++) {\n const input = allInputs[i]\n const txId = Buffer.from(input.hash).reverse().toString('hex')\n if (txId === addressUTXO.tx_hash) return i\n }\n throw new Error(`No inputs for address ${address}`)\n } catch (err) {\n console.log(`Error in paymentTxForAddress(): ${err}`)\n throw err\n }\n}",
"function isAddress(string) {\n try {\n bitcoin.Address.fromBase58Check(string)\n } catch (e) {\n return false\n }\n\n return true\n}",
"async function getAddresses() {\n\n const lines = fs.readFileSync(0).toString().trim().split(\"\\n\")\n\n if (lines.length == 0) {\n console.log(\"No lines to process from stdin.\")\n system.exit(1)\n }\n\n var addresses = []\n for (var i = 0; i < lines.length; i++) {\n const address = lines[i].trim()\n\n // Make sure that all addresses we read from stdin are checksumed.\n if (web3.utils.checkAddressChecksum(address) !== true) {\n console.log(\"Invalid checksumed address: \" + address)\n system.exit(1)\n }\n\n addresses.push(address)\n }\n\n return addresses\n}",
"function generateNewAddress(){\n \n server.accounts()\n .accountId(source.publicKey())\n .call()\n .then(({ sequence }) => {\n const account = new StellarSdk.Account(source.publicKey(), sequence)\n const transaction = new StellarSdk.TransactionBuilder(account, {\n fee: StellarSdk.BASE_FEE\n })\n .addOperation(StellarSdk.Operation.createAccount({\n destination: destination.publicKey(),\n startingBalance: '2'\n }))\n .setTimeout(30)\n .build()\n transaction.sign(StellarSdk.Keypair.fromSecret(source.secret()))\n return server.submitTransaction(transaction)\n })\n .then(results => {\n console.log('Transaction', results._links.transaction.href)\n console.log('New Keypair', destination.publicKey(), destination.secret())\n })\n\n }",
"getPublicAddress(fioAddress, chainCode, tokenCode) {\n const publicAddressLookUp = new queries.GetPublicAddress(fioAddress, chainCode, tokenCode);\n return publicAddressLookUp.execute(this.publicKey);\n }",
"function GetHash160FromAddr(addr){\n const addrd = Address.fromString(addr);\n var script = bitcore.Script.buildPublicKeyHashOut(addrd).toString()\n script = script.split(\"0x\").pop();//Remove all text before 0x prefix of hash160\n script = script.replace(\" OP_EQUALVERIFY OP_CHECKSIG\",\"\");//Remove opcodes from output\n return script;\n}",
"inDiscoveryAddresses(peer) {\n let str = JSON.stringify(peer);\n for(let i=0; i<this.discoveryAddresses_.length; i++) {\n if(JSON.stringify(this.discoveryAddresses_[i]) == str) {\n return true;\n }\n }\n \n return false;\n }",
"static async createWithSeed(fromPublicKey, seed, programId) {\n const buffer = Buffer.concat([fromPublicKey.toBuffer(), Buffer.from(seed), programId.toBuffer()]);\n const hash = await sha256$1(new Uint8Array(buffer));\n return new PublicKey(Buffer.from(hash, 'hex'));\n }",
"query(protocolMask, serviceMask, maxAddresses = 1000) {\n // XXX inefficient linear scan\n const now = Date.now();\n const addresses = [];\n for (const peerAddressState of this._store.values()) {\n // Never return banned or failed addresses.\n if (peerAddressState.state === PeerAddressState.BANNED\n || peerAddressState.state === PeerAddressState.FAILED) {\n continue;\n }\n\n // Never return seed peers.\n const address = peerAddressState.peerAddress;\n if (address.isSeed()) {\n continue;\n }\n\n // Only return addresses matching the protocol mask.\n if ((address.protocol & protocolMask) === 0) {\n continue;\n }\n\n // Only return addresses matching the service mask.\n if ((address.services & serviceMask) === 0) {\n continue;\n }\n\n // Update timestamp for connected peers.\n if (peerAddressState.state === PeerAddressState.CONNECTED) {\n address.timestamp = now;\n // Also update timestamp for RTC connections\n if (peerAddressState.bestRoute) {\n peerAddressState.bestRoute.timestamp = now;\n }\n }\n\n // Never return addresses that are too old.\n if (this._exceedsAge(address)) {\n continue;\n }\n\n // Return this address.\n addresses.push(address);\n\n // Stop if we have collected maxAddresses.\n if (addresses.length >= maxAddresses) {\n break;\n }\n }\n return addresses;\n }",
"function hasAddressVal(addressTable) {\n for(var i = 0; i < 4; i++) {\n if(!addressTable[i]) {\n ui.alert(\"You must select a location before I can get your values.\");\n return false;\n } \n }\n return true;\n}",
"async function main(to, from) {\n\n const list = await listunspent();\n\n const addresses = new Set();\n const utxosSortedByAddress = list.reduce( (accumulator, utxo) => {\n const address = utxo.address;\n addresses.add(address);\n if (!accumulator[address]) {\n accumulator[address] = [];\n }\n accumulator[address].push(utxo);\n return accumulator;\n }, {});\n\n const addressArray = Array.from(addresses);\n\n if (addressArray.length === 0) {\n console.log('No UTXOs found with 10 or more confirmations.');\n process.exit(0);\n }\n\n let sendFrom = from ? from : '';\n if (!from || !to) {\n const response = await inquirer.prompt([\n {\n type: 'list',\n name: 'sendFrom',\n message: `Select an address to migrate:`,\n choices: addressArray,\n default: addressArray[0]\n },\n ]);\n sendFrom = response.sendFrom;\n }\n const utxoArray = utxosSortedByAddress[sendFrom];\n\n let sendTo = to ? to : '';\n if (!from || !to) {\n const response = await inquirer.prompt([\n {\n name: 'sendTo',\n message: `Enter address to send to:`\n },\n ]);\n sendTo = response.sendTo;\n if (!sendTo) {\n console.log('Send To address cannot be blank.');\n process.exit(0);\n }\n }\n\n if (!from || !to) {\n const { confirm } = await inquirer.prompt([\n {\n type: 'list',\n name: 'confirm',\n message: `Migrate ${utxoArray.length} UTXOs from ${sendFrom} to ${sendTo}?`,\n choices: ['Continue', 'Cancel']\n },\n ]);\n if (confirm === 'Cancel') {\n console.log('Aborted by user.');\n process.exit(0);\n }\n }\n\n utxoArray.forEach( async (utxo) => {\n const amount = Math.round(utxo.amount * 100000000);\n const minUtxoSize = argv.minUtxoSize ? argv.minUtxoSize : 100000000;\n if (amount > minUtxoSize) {\n const fee = 10000;\n const sendAmount = (amount - fee) / 100000000;\n const send = {};\n send[sendTo] = sendAmount;\n console.log(`Creating txn to send ${sendAmount} from ${sendFrom} to ${sendTo}`);\n let rawTxn = await createrawtransaction([utxo], send).catch((err) => {\n console.log('createrawtransaction Error.', err);\n console.log('Error creating raw transaction with utxo:', utxo);\n process.exit(0);\n });\n const signedTxn = await signrawtransaction(rawTxn).catch((err) => {\n console.log('signrawtransaction',err);\n console.log('Error signing raw transaction:', rawTxn);\n process.exit(0);\n });\n const txid = await sendrawtransaction(signedTxn.hex).catch((err) => {\n console.log('sendrawtransaction', err);\n console.log('Error sending signed transaction hex:', signedTxn);\n process.exit(0);\n });\n console.log(`Sent ${utxo.amount} to ${sendTo}. txid: ${txid}`);\n }\n });\n\n}",
"function krnVerifyInstructions(program)\n{\n var splitProgram = program.split(\" \"); \n \n for( var index = 0; index < splitProgram.length; index++)\n {\n var opCode = _InstructionSet.get(splitProgram[index]);\n \n if(splitProgram[index] === '00')\n {\n break;\n }\n \n if(opCode)\n {\n index += opCode.argCount;\n }\n else \n {\n return null;\n }\n }\n \n return splitProgram;\n}",
"getVendorAddress(address) {\n //\n }",
"getBlocksByAddress() {\n this.app.get('/stars/address::address', async (req, res) => {\n const { address } = req.params;\n // ensure address is valid\n if (checkAddress(address)) {\n try {\n // search through blockchain, add any blocks with matching address to total.\n const chainData = await this.chain.getFormattedData();\n const blocks = chainData.reduce((total, block) =>\n (block && block.body && block.body.address === address) \n ? [...total, block]\n : total,\n []\n );\n // blocks with address were found\n if (blocks.length > 0) {\n const decodedBlocks = blocks.map(block => decryptStarStory(block));\n return res.json(decodedBlocks);\n }\n throw new Error('No blocks found');\n } catch (error) {\n // no blocks were found\n return res.json({\n status: false,\n message: `Error: Blockchain doesn't have any blocks with address of ${address}.`\n });\n }\n }\n // address is junk or missing\n return res.json(INVALID_REQUEST);\n });\n }",
"function findFirstExternalIPv4NetworkAddress() {\n return findNetworkAddress(netAddress => !netAddress.internal && netAddress.family === 'IPv4');\n}",
"static isValidXAddress(address) {\n return addressCodec.isValidXAddress(address);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Added by Dharmveer for EPC File upload on 10/09/2008 | function uploadEPCFile(astrFilePath, aobjFileData) {
var lstrData;
lstrData = "";
try {
objFSO = new ActiveXObject("Scripting.FileSystemObject");
if (objFSO.FileExists(astrFilePath)) {
lstrData = objFSO.OpenTextFile(astrFilePath, 1,false,-2).ReadAll();
} else {
//showError("FE0901",FE0901);
return false;
}
aobjFileData.value = lstrData;
}
catch(e){
//Consume JS error or show to alert as per requirement
//showError("FE0904",FE0904);
return false;
}
return true;
} | [
"function of_electric_file(adbnetgrid,as_colfilelsh,as_write,as_compressed,as_colfilename,as_where, type)\r\n{\r\n\tif (type == undefined || type == null) {\r\n \t\ttype = 'blob'\r\n \t\tas_compressed = '0'\r\n \t}\r\n \tif (type == 'ftp') {\r\n \t\ttype = 'blob'\r\n \t\tas_compressed = '0'\r\n \t}\r\n\t var f = \"dialogHeight: 80px; dialogWidth:350px; status:no\";\r\n\t var url\r\n\t var editcontrol\r\n\t var colfilelsh\r\n if (as_where=='dbnetgrid')\r\n {\r\n editcontrol=adbnetgrid.editControl\r\n }else \r\n {\r\n editcontrol=adbnetgrid\r\n } \r\n\t if (as_write>\"0\")\r\n\t {\r\n\t\t colfilelsh=editcontrol.inputControl(as_colfilelsh.toUpperCase()).value\r\n if (as_write=='1')\r\n {\r\n\t var data = adbnetgrid.selectData(\"select trim(substr(to_char(systimestamp,'yyyymmddhh24missff'),1,17)) as id from dual\") \r\n\t\t\t colfilelsh=data.id\r\n\t }\r\n var params = 'colfilelsh='+colfilelsh+'&write='+as_write+'&compressed='+as_compressed+'&filelsh='+as_colfilelsh+'&filename='+ as_colfilename+'&type='+type;\r\n\r\n\t var obj=window.showModalDialog(sgccPath+'/app/bfile/uploadFile.htm',params,'dialogHeight:180px;help=no;status=no')\r\n\r\n\t if(obj != null && obj != \"\")\r\n\t {\r\n if (as_colfilename.length>0) {\r\n \t editcontrol.inputControl(as_colfilename.toUpperCase()).value= obj\r\n }\r\n\t editcontrol.inputControl(as_colfilelsh.toUpperCase()).value= colfilelsh\r\n\t if(as_where=='dbnetgrid') \r\n\t {\r\n\t editcontrol.apply() \r\n\t }else{\r\n\t editcontrol.applyChanges()\r\n\t }\t\r\n\t\t } \r\n } else if (as_write==\"0\")\r\n { \r\n var pk='';\r\n \t if (as_where=='dbnetgrid')\r\n \t {\r\n } \r\n else \r\n pk=editcontrol.inputControl(as_colfilelsh.toUpperCase()).value\r\n\t window.open(sgccPath+\"/file/attach.do?pk=\"+pk,'_parent','toolbars=no,top=100,left=100,dialogHide=yes')\r\n }\r\n \r\n}",
"function FileUpload(file, options) {\n var fileCreationOptions, getServerFile, key, minParts, _i, _len, _ref;\n this.file = file;\n if (options == null) {\n options = {};\n }\n this._onUploadProgress = __bind(this._onUploadProgress, this);\n options = $.extend({\n folder: \"/\"\n }, options);\n _ref = [\"folder\", \"partSize\", \"fileCreationPool\", \"workerPool\", \"uploadPool\", \"api\", \"projectID\", \"minimumPartSize\", \"maximumPartSize\", \"maximumFileSize\", \"maximumNumParts\", \"emptyLastPartAllowed\"];\n for (_i = 0, _len = _ref.length; _i < _len; _i++) {\n key = _ref[_i];\n if (options[key] == null) {\n throw new Error(\"Required parameter \" + key + \" is not specified\");\n }\n this[key] = options[key];\n }\n this.partSize = Math.max(Math.ceil(this.file.size / options.maximumNumParts), this.partSize, this.minimumPartSize);\n if (this.partSize < this.minimumPartSize) {\n throw new Error(\"Part size is less than the minimum allowed! (\" + this.partSize + \" vs. \" + this.minimumPartSize + \")\");\n } else if (this.partSize > this.maximumPartSize) {\n throw new Error(\"Part size is more than the maximum allowed! (\" + this.partSize + \" vs. \" + this.maximumPartSize + \")\");\n }\n if (this.file.size > this.maximumFileSize) {\n throw new Error(\"File size for '\" + this.file.name + \"' is too large! (\" + this.file.size + \" vs. \" + this.maximumFileSize + \")\");\n }\n this._uploadProgress = $.Deferred();\n this._checksumProgress = $.Deferred();\n this._closingProgress = $.Deferred();\n this._uploadCalls = {};\n this._uploadsDone = 0;\n this._bytesUploaded = 0;\n this._bytesResumed = 0;\n this._aborted = false;\n this._closing = false;\n this._closed = false;\n minParts = this.emptyLastPartAllowed ? 1 : 0;\n this.numParts = Math.max(minParts, Math.ceil(this.file.size / this.partSize));\n if (this.numParts > this.maximumNumParts) {\n throw new Error(\"Too many parts for '\" + this.file.name + \"'! (\" + this.numParts + \" vs. \" + this.maximumNumParts + \")\");\n }\n this.uploadStartedAt = null;\n this._checksumQueue = [];\n this._uploadQueue = [];\n this._parts = [];\n this._partUploadProgress = [];\n this._uploadPoolClientID = this.uploadPool.acquireClientID(\"file_upload_\");\n this._workerPoolClientID = this.workerPool.acquireClientID(\"file_worker_\");\n this.isDirectory = false;\n fileCreationOptions = {\n folder: this.folder,\n tags: options.tags,\n properties: options.properties\n };\n this.fileCreationStatus = $.Deferred();\n getServerFile = (function(_this) {\n return function() {\n return _this.fileCreationPool.acquire().done(function(createFileToken) {\n return FileUpload.prototype.findOrCreateFile(file, _this.api, _this.partSize, _this.projectID, fileCreationOptions).done(function(data) {\n var existingParts, i, part, start, _j, _ref1, _ref2, _ref3;\n existingParts = (_ref1 = data.parts) != null ? _ref1 : {};\n _this.fileID = data.fileID;\n for (i = _j = 0, _ref2 = _this.numParts; 0 <= _ref2 ? _j < _ref2 : _j > _ref2; i = 0 <= _ref2 ? ++_j : --_j) {\n start = _this.partSize * i;\n part = {\n index: i + 1,\n start: start,\n stop: Math.min(_this.file.size, start + _this.partSize)\n };\n _this._parts.push(part);\n if (((_ref3 = existingParts[i + 1]) != null ? _ref3.state : void 0) === \"complete\") {\n _this._uploadsDone += 1;\n _this._bytesResumed += part.stop - part.start;\n } else {\n _this._checksumQueue.push(part);\n }\n }\n _this._onUploadProgress();\n return _this.fileCreationStatus.resolve(_this.fileID);\n }).fail(function(error) {\n return _this.fileCreationStatus.reject(error);\n }).always(function() {\n return _this.fileCreationPool.release(createFileToken);\n });\n });\n };\n })(this);\n if (this.file.size < 1 * MB) {\n this.readBytes(0, 10).done(getServerFile).fail((function(_this) {\n return function() {\n var errorObject;\n _this.isDirectory = true;\n errorObject = {\n error: {\n type: \"InvalidType\",\n message: \"File is a directory and cannot be uploaded\"\n }\n };\n _this.fileCreationStatus.reject(errorObject);\n _this._uploadProgress.reject(errorObject);\n _this._checksumProgress.reject(errorObject);\n return _this._closingProgress.reject(errorObject);\n };\n })(this));\n } else {\n getServerFile();\n }\n }",
"upload(e){\n if(e.target.files.length) this.handleFile(e.target.files[0])\n }",
"function katalogSV () {\n //add image\n var files =new Array();\n $(\"input:file\").each(function() {\n files.push($(this).get(0).files[0]); \n });\n \n // Create a formdata object and add the files\n var filesAdd = new FormData();\n $.each(files, function(key, value){\n filesAdd.append(key, value);\n });\n\n if($('#k_photoTB').val()=='')//upload\n katalogDb('');\n else// ga upload\n katalogUp(filesAdd);\n }",
"function addUpload(maxUploads, fileFieldName, descFieldName)\r\n{\r\n\tnameFile = fileFieldName;\r\n\tif (typeof descFiledName!=\"undefined\")\r\n nameDesc = descFieldName;\r\n\r\n currentUploads++;\r\n\tif (currentUploads>maxUploads) return;\r\n\tif (currentUploads==maxUploads)\r\n\t document.getElementById('addupload').style.visibility='hidden';\r\n\r\n // First, clone the hidden attachment section\r\n\tvar newFields = document.getElementById('attachment').cloneNode(true);\r\n\tnewFields.id = '';\r\n\t// Make the new attachments section visible\r\n\tnewFields.style.display = 'block';\r\n\r\n\t// loop through tags in the new Attachment section and set ID and NAME properties\r\n\tvar newField = newFields.childNodes;\r\n\tfor (var i=0;i<newField.length;i++)\r\n\t{\r\n\t\tif (newField[i].name==nameFile)\r\n\t\t{\r\n\t\t newField[i].id=nameFile+currentUploads;\r\n\t\t newField[i].name=nameFile+currentUploads;\r\n\t\t}\r\n\r\n\t\tif (newField[i].name==nameDesc)\r\n\t\t{\r\n\t\t newField[i].id=nameDesc+currentUploads;\r\n newField[i].name=nameDesc+currentUploads;\r\n\t\t}\r\n\r\n\t\tif (newField[i].id=='dropcap')\r\n\t\t{\r\n\t\t\tnewField[i].id='dropcap'+currentUploads;\r\n\t\t\tnewField[i].childNodes[0].data=currentUploads;\r\n\t\t}\r\n\t}\r\n\r\n\t// Insert our new Attachment section into the Attachments Div on the form...\r\n\tvar insertHere = document.getElementById('attachmentmarker');\r\n\tinsertHere.parentNode.insertBefore(newFields,insertHere);\r\n}",
"function uploadProg() {\r\n\r\n // The fileUpload input box (hidden) declared in grid_main.html\r\n // is used to select the file. We just click the 'chose file' button\r\n // contained in that input element. When we automatically click the \r\n // input element below, we execute uploadFileContents() routine.\r\n //\r\n var upelem = document.getElementById('fileUpload');\r\n upelem.click();\r\n}",
"function upload() {\n\n isCanceled = false;\n indexNumbers = [];\n space = undefined;\n progress = 0;\n let path = $('#file-chooser').val();\n if (validatePath(path) & validateKey.call($('#space-key')) & validateTitle.call($('#space-title'))) {\n space = {\n name: $('#space-title').val(),\n key: $('#space-key').val()\n };\n setUploadMessage(i18n.PREPARING_FOR_UPLOAD, \"generic\");\n createDialog();\n if (AJS.$('#radioButtonUpdate').prop(\"checked\")) {\n\n } else if (AJS.$('#radioButtonClone').prop(\"checked\")) {\n specif = specIFLoader(URL.createObjectURL($('#file-chooser').prop('files')[0]), i18n, cloneToOldSpace, error);\n } else {\n specif = specIFLoader(URL.createObjectURL($('#file-chooser').prop('files')[0]), i18n, deleteOldSpace, error);\n }\n\n }\n }",
"preUpload(e){\n e.target.closest('.text').querySelector('input[type=\"file\"]').click()\n }",
"function prepareFilesToUploadFromDataTransferItemList(dataItems) {\n var files = [];\n if (dataItems && dataItems.length > 0) {\n for (var i = 0; i < dataItems.length; i++) {\n if (dataItems[i].kind == \"file\") {\n var f = dataItems[i].getAsFile();\n Wicket.Log.info(\"... file[\" + i + \"].name = \" + f.name);\n files.push(f);\n }\n }\n }\n return files;\n }",
"function uploadFile() {\n\t\t$.ajax({\n\t\t\turl : \"/api/brailleapplication/uploadFile\",\n\t\t\ttype : \"POST\",\n\t\t\tdata : new FormData($(\"#upload-file-form\")[0]),\n\t\t\tenctype : 'multipart/form-data',\n\t\t\tprocessData : false,\n\t\t\tcontentType : false,\n\t\t\tcache : false,\n\t\t\tsuccess : function() {\n\t\t\t\tpreviewFile();\n\t\t\t},\n\t\t\terror : function() {\n\t\t\t}\n\t\t});\n\t} // function uploadFile ",
"function setupUploadChain (selector) {\n if ($.type(selector) === \"string\") {\n\n // CHECK IF UPLOADS ALREADY EXIST:\n // It is possible to arrive at this point in execution after the user has submitted a\n // form containing errors that also already contains transcripts uploaded to input\n // fields that will be hidden by default. The following blocks of code resolve this\n // situation by showing such fields, as well as their nearest neighbors.\n var $inputs = $(selector + \" input[type='file']\");\n $inputs.each(function () {\n var $thisInput = $(this);\n var $nextDiv = $thisInput.nextAll(\"div[id]\").first();\n if($nextDiv.length > 0) {\n $thisInput.addClass(\"gf-value-entered\");\n var $parentOfInput = $thisInput.parents(selector).first();\n $parentOfInput.removeClass(\"gf-hidden\");\n var $parentNextSblngs = $parentOfInput.nextAll(selector).first();\n $parentNextSblngs.removeClass(\"gf-hidden\");\n }\n });\n $(\".gform_body\").on(\"change\", selector + \" input[type='file']\", function () {\n var $thisInput = $(this);\n if($thisInput.prop(\"files\") != null && $thisInput.prop(\"files\").length > 0) {\n var valuePassed = true;\n var $parentOfInput = $thisInput.parents(selector).first();\n var $parentNextSblngs = $parentOfInput.nextAll(selector);\n var $parentPrevSblngs = $parentOfInput.prevAll(selector);\n if($parentNextSblngs.length != 0 || $parentPrevSblngs.length != 0) {\n var originalFileName = $thisInput.prop(\"files\").item(0).name;\n $parentPrevSblngs.each(function () {\n if(valuePassed) {\n var $thisSblng = $(this);\n var $thisSblngInput = $thisSblng.find(\"input[type='file']\").first();\n if($thisSblngInput.prop(\"files\") != null && \n \t\t$thisSblngInput.prop(\"files\").length > 0) {\n var thisFileName = $thisSblngInput.prop(\"files\").item(0).name;\n valuePassed = originalFileName != thisFileName;\n }\n }\n });\n $parentNextSblngs.each(function () {\n if(valuePassed) {\n var $thisSblng = $(this);\n var $thisSblngInput = $thisSblng.find(\"input[type='file']\").first();\n if($thisSblngInput.prop(\"files\") != null &&\n \t\t$thisSblngInput.prop(\"files\").length > 0) {\n var thisFileName = $thisSblngInput.prop(\"files\").item(0).name;\n valuePassed = originalFileName != thisFileName;\n }\n }\n });\n }\n if(valuePassed) { \n $thisInput.addClass(\"gf-value-entered\");\n $parentNextSblngs.first().removeClass(\"gf-hidden\");\n }\n else\n {\n alert(\"A file with the same name has already been uploaded; please choose \"\n \t+ \"a different file.\");\n $thisInput.get(0).value = \"\";\n }\n }\n else {\n $thisChild.removeClass(\"gf-value-entered\");\n }\n });\n }\n }",
"function iFrameUpload(fieldId, fieldTypeId, contentTypeId, resultdata)\n{\n\tvar field = {id:fieldId, fieldtypeid:fieldTypeId, contenttypeid:contentTypeId};\n\tvar data = jQuery.parseJSON(resultdata);\n\t\n\t// test for error\n\tif(data['error'] == '')\n\t{\n\t\tif(fieldTypeId == 18) // Image Gallery\n\t\t{\n\t\t\taddImageGalleryRow(fieldId, data);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsetPreview(field, data);\n\t\t}\t\n\t}\n\telse\n\t{\n\t\talert(data['error']);\n\t}\t\n\t\n\tjQuery.unblockUI();\n}",
"function updateFileData(data) {\n if (data.field === 'name') {\n data.newObj.path = uploadPath + data.newObj.name + data.file.extension;\n dbSrvc.update(fileCollection, data);\n renameFileToSystem(data.file.path, data.newObj.path);\n } else {\n dbSrvc.update(fileCollection, data);\n }\n }",
"onFileUploadSubmit(e){\n\t\te.preventDefault();\n\t\tconst self = this,\n\t\t\t files = document.getElementById('olyauth.file').files;\n\n\t\t//Users.User.uploadProfileImage({email:this.state.user.email,files})\n\t\t//\t.then(user=>{\n\t\t//\t\tl(this.state.user,user);\n\t\t//\t\tthis.setState({user});\n\t\t//\t\tthis.toggleProfileUpload();\n\t\t//\t});\n\t}",
"_handleFile(req, files, callback) {\r\n /**\r\n * Create a writable stream using concat-stream that will\r\n * concatenate all the buffers written to it and pass the\r\n * complete buffer to a callback function\r\n */\r\n const fileManipulate = concat((imageData) => {\r\n /**\r\n * read the image buffer with Jimp\r\n * it return a promise\r\n */\r\n Jimp.read(imageData)\r\n .then((image) => {\r\n // precess the Jimp image buffer\r\n this.processImage(image, callback);\r\n })\r\n .catch(callback);\r\n });\r\n\r\n // write the uploaded file buffer to the fileManipulate stream\r\n files.stream.pipe(fileManipulate);\r\n }",
"function fileUploadAction() {\n\tif($(\"form\").childElementCount === 1)\n\t\t$(\"input[type=file]\").submit();\n}",
"function gotFile(filetmp) {\n console.log(\"gotfile\"+filetmp);\n var reader = new FileReader();\n reader.error = function(evt) {\n alert(\"read error q\");\n console.log(\"ERRORRR \"+JSON.stringify(evt));\n };\n reader.onloadend = function(evt) {\n imageData = evt.target.result;\n uploadPictures();\n };\n // alert(\"reading now\");\n reader.readAsDataURL(filetmp);\n }",
"function uploadFiles() {\n if ($('#queue').find('.fileName').length !== 0) {\n $(this).modal();\n showSpinner('upload-spin');\n\n //upload files via uploadify object\n if (uploadGUID !== -1) {\n $('#file_upload').uploadify('upload', '*');\n }\nconsole.log(\"done uploading files\");\n }\n}",
"_uploadFile(upload, file) {\n const formData = new FormData();\n\n // Copy the keys from our upload instructions into the form data\n for (const key in upload.fields) {\n formData.append(key, upload.fields[key]);\n }\n\n // AWS ignores all fields in the request after the file field, so all other\n // fields must appear before the file.\n formData.append('file', file);\n\n // Now we can upload the file\n fetch(upload.url, {\n method: 'post',\n body: formData\n }).then((response) => {\n if (response.ok) {\n this._finalizeFileUpload(upload, file);\n } else {\n this.options.onError(new AssetUploaderError(\"There was an error uploading the file. Please try again.\"));\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Play Video by time | function playVideoOnTime(videodata) {
$.each(getVideos, function(key, value) {
// See if any video should be played now
if ((value.startSeconds > 1)) {
//console.log('Video ID :' + value.videoId + ' at : ' + value.startSeconds);
domYouTubeContainer.tubeplayer("play", {
id: value.videoId,
time: value.startSeconds
});
}
});
} | [
"function playActorVideo(actor, time) {\n //playVideo(id, time - startTime of video)\n\n}",
"function videoSeekTo(time) {\n player.seekTo(time);\n}",
"play(startTime, endTime) {\n let { remote, fullScreen, playing } = this.props\n let { vc } = this\n log(`play startTime=${startTime}, endTime=${endTime}, playing=${playing}`)\n\n if (playing) { \n log('play - stop before restarting play')\n this.stop() \n }\n\n if (!isNaN(startTime)) {\n vc.currentTime = startTime\n }\n\n if (fullScreen) this.requestFullScreen()\n\n this.endTime = endTime\n\n let { playbackRate } = remote\n vc.playbackRate = playbackRate || 1.0\n\n this.startupdater()\n remote.playing = true\n //console.log('play!!!')\n this.vc.play()\n }",
"updateVideoTime(videoPlayer, time) {\n videoPlayer.currentTime = time;\n \n }",
"play() {\n // rewind when user clicks play on ended scene\n this.goToStartIfEnded();\n this.disablePlayButtonUntilPlaybackStarts();\n this.waitForCanPlayAll().then(() => {\n this.videoElements.forEach(e => e.play());\n });\n }",
"function updatevideostatus(){\n \n \n if(video.paused)\n {\n \n video.play();\n }\n else{\n video.pause();\n }\n\n \n }",
"function playPause() {\n if (video.paused) {\n // Play video\n video.play();\n } else {\n // Pause video\n video.pause();\n }\n}",
"static tryPlayVideo(videoElement){return __awaiter$1(this,void 0,void 0,function*(){if(videoElement===null||videoElement===void 0?void 0:videoElement.ended){console.error('Trying to play video that has ended.');return false;}if(BrowserCodeReader$1.isVideoPlaying(videoElement)){console.warn('Trying to play video that is already playing.');return true;}try{yield videoElement.play();return true;}catch(error){console.warn('It was not possible to play the video.',error);return false;}});}",
"function videoPlay($wrapper) {\n var $iframe = $wrapper.find('.js-videoIframe');\n var src = $iframe.data('src');\n // hide poster\n $wrapper.addClass('videoWrapperActive');\n // add iframe src in, starting the video\n $iframe.attr('src', src);\n }",
"static isVideoPlaying(video){return video.currentTime>0&&!video.paused&&video.readyState>2;}",
"function play(){\n next();\n timeout_id = setTimeout(\"play()\",1000/persec)\n}",
"function videoStartedPlaying() {\n timeStarted = new Date().getTime()/1000;\n alertMsg();\n}",
"function playSelectedVideo(selectedObj) {\n var source = \"../videos/\" + selectedObj.options[selectedObj.selectedIndex].value;\n video.src = source;\n video.load();\n}",
"function getVideoTime() {\n return player.getCurrentTime();\n}",
"function play_video_on_hover()\n{\n $(\".topfive .frame\").hover(function()\n {\n // get Frame Id\n var id = $(this).attr(\"id\");\n \n $(\".topfive .frame#\"+id+\" img\").hide();\n\n // Video Container\n var video = $(\".topfive .frame#\"+id+\" video.bgvideo\");\n\n // show Background Video\n video.css(\"display\", \"inline-block\");\n\n // Load Video\n /*\n var video_name = $(\".topfive .frame#\"+id+\" video\").attr(\"id\");\n var vid = document.getElementById(video_name);\n if (vid)\n {\n vid.pause();\n vid.load();\n vid.play();\n }\n */\n }, function() {\n // hide Background Video\n $(\"video.bgvideo\").hide();\n $(\".topfive .frame img\").show();\n });\n}",
"_showFirstFrame() {\n if (!this._video.isPlaying) {\n this._video.getVideoElement().currentTime = 0;\n }\n }",
"function loadVideo() {\n\t\tvar d = new Date();\n\t\tvar lastYear = d.getFullYear() - 1;\n\t\tvar month = d.getMonth() +1;\n\t\tvar day = d.getDate();\n\t\tvar myKey = \"AIzaSyAr0fnc8B-t96isVPUByudWNPFDKJIugoc\";\n\t\tvar request = 'https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=10&order=viewCount&publishedAfter='+lastYear+'-'+month+'-'+day+'T00%3A00%3A00Z&q=teaser|trailer -india|game&type=video&videoCaption=any&relevanceLanguage=en&videoCategoryId=24&videoEmbeddable=true&key=' + myKey;\n\t\t$.ajax({\n\t\t\turl: request,\n\t\t\tsuccess: function (data) {\n\t\t\t\tvar id = data.items[0].id.videoId;\n\n\t\t\t\tdata.items.forEach(buildArray);\n\n\t\t\t\tplayVideo();\n\n\t\t\t}\n\t\t});\n\t}",
"function video_click(e) {\n\t//console.log(e);\n\t//console.log(this);\n\tif (this.paused == true) {\n\t\tthis.play();\n\t} else {\n\t\tthis.pause();\n\t}\n}",
"function play_stop() {\n if(playing) {\n //video[v_index].play();\n video[v_index].loop();\n } else\n video[v_index].pause();\n\n playing = !playing;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine whether the given properties match those of a `ListenerTimeoutProperty` | function CfnVirtualNode_ListenerTimeoutPropertyValidator(properties) {
if (!cdk.canInspect(properties)) {
return cdk.VALIDATION_SUCCESS;
}
const errors = new cdk.ValidationResults();
if (typeof properties !== 'object') {
errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));
}
errors.collect(cdk.propertyValidator('grpc', CfnVirtualNode_GrpcTimeoutPropertyValidator)(properties.grpc));
errors.collect(cdk.propertyValidator('http', CfnVirtualNode_HttpTimeoutPropertyValidator)(properties.http));
errors.collect(cdk.propertyValidator('http2', CfnVirtualNode_HttpTimeoutPropertyValidator)(properties.http2));
errors.collect(cdk.propertyValidator('tcp', CfnVirtualNode_TcpTimeoutPropertyValidator)(properties.tcp));
return errors.wrap('supplied properties not correct for "ListenerTimeoutProperty"');
} | [
"function CfnVirtualNode_GrpcTimeoutPropertyValidator(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('idle', CfnVirtualNode_DurationPropertyValidator)(properties.idle));\n errors.collect(cdk.propertyValidator('perRequest', CfnVirtualNode_DurationPropertyValidator)(properties.perRequest));\n return errors.wrap('supplied properties not correct for \"GrpcTimeoutProperty\"');\n}",
"function CfnRoute_GrpcTimeoutPropertyValidator(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('idle', CfnRoute_DurationPropertyValidator)(properties.idle));\n errors.collect(cdk.propertyValidator('perRequest', CfnRoute_DurationPropertyValidator)(properties.perRequest));\n return errors.wrap('supplied properties not correct for \"GrpcTimeoutProperty\"');\n}",
"function CfnRoute_TcpTimeoutPropertyValidator(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('idle', CfnRoute_DurationPropertyValidator)(properties.idle));\n return errors.wrap('supplied properties not correct for \"TcpTimeoutProperty\"');\n}",
"function CfnVirtualNode_HttpTimeoutPropertyValidator(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('idle', CfnVirtualNode_DurationPropertyValidator)(properties.idle));\n errors.collect(cdk.propertyValidator('perRequest', CfnVirtualNode_DurationPropertyValidator)(properties.perRequest));\n return errors.wrap('supplied properties not correct for \"HttpTimeoutProperty\"');\n}",
"function CfnVirtualNode_TcpTimeoutPropertyValidator(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('idle', CfnVirtualNode_DurationPropertyValidator)(properties.idle));\n return errors.wrap('supplied properties not correct for \"TcpTimeoutProperty\"');\n}",
"function CfnRoute_HttpTimeoutPropertyValidator(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('idle', CfnRoute_DurationPropertyValidator)(properties.idle));\n errors.collect(cdk.propertyValidator('perRequest', CfnRoute_DurationPropertyValidator)(properties.perRequest));\n return errors.wrap('supplied properties not correct for \"HttpTimeoutProperty\"');\n}",
"function CfnVirtualNode_ListenerTlsPropertyValidator(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('certificate', cdk.requiredValidator)(properties.certificate));\n errors.collect(cdk.propertyValidator('certificate', CfnVirtualNode_ListenerTlsCertificatePropertyValidator)(properties.certificate));\n errors.collect(cdk.propertyValidator('mode', cdk.requiredValidator)(properties.mode));\n errors.collect(cdk.propertyValidator('mode', cdk.validateString)(properties.mode));\n errors.collect(cdk.propertyValidator('validation', CfnVirtualNode_ListenerTlsValidationContextPropertyValidator)(properties.validation));\n return errors.wrap('supplied properties not correct for \"ListenerTlsProperty\"');\n}",
"function CfnVirtualNode_ListenerPropertyValidator(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('connectionPool', CfnVirtualNode_VirtualNodeConnectionPoolPropertyValidator)(properties.connectionPool));\n errors.collect(cdk.propertyValidator('healthCheck', CfnVirtualNode_HealthCheckPropertyValidator)(properties.healthCheck));\n errors.collect(cdk.propertyValidator('outlierDetection', CfnVirtualNode_OutlierDetectionPropertyValidator)(properties.outlierDetection));\n errors.collect(cdk.propertyValidator('portMapping', cdk.requiredValidator)(properties.portMapping));\n errors.collect(cdk.propertyValidator('portMapping', CfnVirtualNode_PortMappingPropertyValidator)(properties.portMapping));\n errors.collect(cdk.propertyValidator('tls', CfnVirtualNode_ListenerTlsPropertyValidator)(properties.tls));\n errors.collect(cdk.propertyValidator('timeout', CfnVirtualNode_ListenerTimeoutPropertyValidator)(properties.timeout));\n return errors.wrap('supplied properties not correct for \"ListenerProperty\"');\n}",
"function CfnVirtualGateway_VirtualGatewayListenerTlsPropertyValidator(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('certificate', cdk.requiredValidator)(properties.certificate));\n errors.collect(cdk.propertyValidator('certificate', CfnVirtualGateway_VirtualGatewayListenerTlsCertificatePropertyValidator)(properties.certificate));\n errors.collect(cdk.propertyValidator('mode', cdk.requiredValidator)(properties.mode));\n errors.collect(cdk.propertyValidator('mode', cdk.validateString)(properties.mode));\n errors.collect(cdk.propertyValidator('validation', CfnVirtualGateway_VirtualGatewayListenerTlsValidationContextPropertyValidator)(properties.validation));\n return errors.wrap('supplied properties not correct for \"VirtualGatewayListenerTlsProperty\"');\n}",
"function CfnVirtualNode_ListenerTlsValidationContextPropertyValidator(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('subjectAlternativeNames', CfnVirtualNode_SubjectAlternativeNamesPropertyValidator)(properties.subjectAlternativeNames));\n errors.collect(cdk.propertyValidator('trust', cdk.requiredValidator)(properties.trust));\n errors.collect(cdk.propertyValidator('trust', CfnVirtualNode_ListenerTlsValidationContextTrustPropertyValidator)(properties.trust));\n return errors.wrap('supplied properties not correct for \"ListenerTlsValidationContextProperty\"');\n}",
"function CfnVirtualNode_ListenerTlsCertificatePropertyValidator(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('acm', CfnVirtualNode_ListenerTlsAcmCertificatePropertyValidator)(properties.acm));\n errors.collect(cdk.propertyValidator('file', CfnVirtualNode_ListenerTlsFileCertificatePropertyValidator)(properties.file));\n errors.collect(cdk.propertyValidator('sds', CfnVirtualNode_ListenerTlsSdsCertificatePropertyValidator)(properties.sds));\n return errors.wrap('supplied properties not correct for \"ListenerTlsCertificateProperty\"');\n}",
"function cfnVirtualNodeListenerTimeoutPropertyToCloudFormation(properties) {\n if (!cdk.canInspect(properties)) {\n return properties;\n }\n CfnVirtualNode_ListenerTimeoutPropertyValidator(properties).assertSuccess();\n return {\n GRPC: cfnVirtualNodeGrpcTimeoutPropertyToCloudFormation(properties.grpc),\n HTTP: cfnVirtualNodeHttpTimeoutPropertyToCloudFormation(properties.http),\n HTTP2: cfnVirtualNodeHttpTimeoutPropertyToCloudFormation(properties.http2),\n TCP: cfnVirtualNodeTcpTimeoutPropertyToCloudFormation(properties.tcp),\n };\n}",
"function CfnVirtualNode_DurationPropertyValidator(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('unit', cdk.requiredValidator)(properties.unit));\n errors.collect(cdk.propertyValidator('unit', cdk.validateString)(properties.unit));\n errors.collect(cdk.propertyValidator('value', cdk.requiredValidator)(properties.value));\n errors.collect(cdk.propertyValidator('value', cdk.validateNumber)(properties.value));\n return errors.wrap('supplied properties not correct for \"DurationProperty\"');\n}",
"function CfnVirtualRouter_VirtualRouterListenerPropertyValidator(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('portMapping', cdk.requiredValidator)(properties.portMapping));\n errors.collect(cdk.propertyValidator('portMapping', CfnVirtualRouter_PortMappingPropertyValidator)(properties.portMapping));\n return errors.wrap('supplied properties not correct for \"VirtualRouterListenerProperty\"');\n}",
"function CfnVirtualNode_ListenerTlsValidationContextTrustPropertyValidator(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('file', CfnVirtualNode_TlsValidationContextFileTrustPropertyValidator)(properties.file));\n errors.collect(cdk.propertyValidator('sds', CfnVirtualNode_TlsValidationContextSdsTrustPropertyValidator)(properties.sds));\n return errors.wrap('supplied properties not correct for \"ListenerTlsValidationContextTrustProperty\"');\n}",
"function CfnVirtualGateway_VirtualGatewayListenerPropertyValidator(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('connectionPool', CfnVirtualGateway_VirtualGatewayConnectionPoolPropertyValidator)(properties.connectionPool));\n errors.collect(cdk.propertyValidator('healthCheck', CfnVirtualGateway_VirtualGatewayHealthCheckPolicyPropertyValidator)(properties.healthCheck));\n errors.collect(cdk.propertyValidator('portMapping', cdk.requiredValidator)(properties.portMapping));\n errors.collect(cdk.propertyValidator('portMapping', CfnVirtualGateway_VirtualGatewayPortMappingPropertyValidator)(properties.portMapping));\n errors.collect(cdk.propertyValidator('tls', CfnVirtualGateway_VirtualGatewayListenerTlsPropertyValidator)(properties.tls));\n return errors.wrap('supplied properties not correct for \"VirtualGatewayListenerProperty\"');\n}",
"function CfnRoute_GrpcRetryPolicyPropertyValidator(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('grpcRetryEvents', cdk.listValidator(cdk.validateString))(properties.grpcRetryEvents));\n errors.collect(cdk.propertyValidator('httpRetryEvents', cdk.listValidator(cdk.validateString))(properties.httpRetryEvents));\n errors.collect(cdk.propertyValidator('maxRetries', cdk.requiredValidator)(properties.maxRetries));\n errors.collect(cdk.propertyValidator('maxRetries', cdk.validateNumber)(properties.maxRetries));\n errors.collect(cdk.propertyValidator('perRetryTimeout', cdk.requiredValidator)(properties.perRetryTimeout));\n errors.collect(cdk.propertyValidator('perRetryTimeout', CfnRoute_DurationPropertyValidator)(properties.perRetryTimeout));\n errors.collect(cdk.propertyValidator('tcpRetryEvents', cdk.listValidator(cdk.validateString))(properties.tcpRetryEvents));\n return errors.wrap('supplied properties not correct for \"GrpcRetryPolicyProperty\"');\n}",
"function CfnBucket_ReplicationTimePropertyValidator(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('status', cdk.requiredValidator)(properties.status));\n errors.collect(cdk.propertyValidator('status', cdk.validateString)(properties.status));\n errors.collect(cdk.propertyValidator('time', cdk.requiredValidator)(properties.time));\n errors.collect(cdk.propertyValidator('time', CfnBucket_ReplicationTimeValuePropertyValidator)(properties.time));\n return errors.wrap('supplied properties not correct for \"ReplicationTimeProperty\"');\n}",
"function CfnVirtualGateway_VirtualGatewayListenerTlsValidationContextPropertyValidator(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('subjectAlternativeNames', CfnVirtualGateway_SubjectAlternativeNamesPropertyValidator)(properties.subjectAlternativeNames));\n errors.collect(cdk.propertyValidator('trust', cdk.requiredValidator)(properties.trust));\n errors.collect(cdk.propertyValidator('trust', CfnVirtualGateway_VirtualGatewayListenerTlsValidationContextTrustPropertyValidator)(properties.trust));\n return errors.wrap('supplied properties not correct for \"VirtualGatewayListenerTlsValidationContextProperty\"');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a checkbox input at the position (x,y) within this interactive. | checkBox(x, y, label, value) {
return this.appendChild(new CheckBox(x, y, label, value));
} | [
"function addInputCheckbox(switchLabel, coin) {\n let inptSwtch = $(\"<input>\").attr(\"type\", \"checkbox\");\n addEventToSwitch(inptSwtch, coin);\n inptSwtch.appendTo(switchLabel);\n }",
"render() {\n return (\n <Checkbox\n className=\"bookmark bookmark-toggle\"\n onChange={this.onChange}\n inputRef={(ref) => { this.input = ref; }}\n />\n );\n }",
"function createCheckBox(createElement, enableRipple = false, options = {}) {\n let wrapper = createElement('div', { className: 'e-checkbox-wrapper e-css' });\n if (options.cssClass) {\n Object(_syncfusion_ej2_base__WEBPACK_IMPORTED_MODULE_0__[\"addClass\"])([wrapper], options.cssClass.split(' '));\n }\n if (options.enableRtl) {\n wrapper.classList.add('e-rtl');\n }\n if (enableRipple) {\n let rippleSpan = createElement('span', { className: 'e-ripple-container' });\n Object(_syncfusion_ej2_base__WEBPACK_IMPORTED_MODULE_0__[\"rippleEffect\"])(rippleSpan, { isCenterRipple: true, duration: 400 });\n wrapper.appendChild(rippleSpan);\n }\n let frameSpan = createElement('span', { className: 'e-frame e-icons' });\n if (options.checked) {\n frameSpan.classList.add('e-check');\n }\n wrapper.appendChild(frameSpan);\n if (options.label) {\n let labelSpan = createElement('span', { className: 'e-label', innerHTML: options.label });\n wrapper.appendChild(labelSpan);\n }\n return wrapper;\n}",
"function newCheckbox() {\n\tvar checkbox = $(document.createElement(\"INPUT\"));\n\tcheckbox.attr(\"type\", \"checkbox\")\n\tcheckbox.bind(\"change\", function() {\n\t\tcheckbox.parent().toggleClass(\"checked\");\n\t});\n\treturn checkbox;\n}",
"createCheckboxes() {\n const checkboxes = [];\n for (const option in this.props.const.option) {\n checkboxes.push(\n <Checkbox\n key={this.props.const.option[option]}\n name={this.props.const.option[option]}\n activeCheckbox={this.state.activeCheckbox}\n onclick={this.checkboxSelection.bind(this)}\n />\n );\n }\n return checkboxes;\n }",
"function Checkbox(label, v) {\r\n if (Array.isArray(v)) {\r\n return bind.Checkbox(label, v);\r\n }\r\n else {\r\n const ref_v = [v()];\r\n const ret = bind.Checkbox(label, ref_v);\r\n v(ref_v[0]);\r\n return ret;\r\n }\r\n }",
"function MouseButtonToggleInput(button) {\n this.button = button;\n}",
"function checkboxTemplate(name, value, label){\n var $tpl=\"<li>\";\n $tpl+=\"<input type='checkbox' name='\"+name+\"' value='\"+value+\"' />\";\n $tpl+=label;\n $tpl+=\"</li>\";\n return $tpl;\n }",
"render() {\n const checkboxes = this.props.form.value.contents.map(content => {\n const childPath = this.props.form.path + \".\" + content.value\n content.checked = get(childPath, \"toggle\")\n\n return <div key={childPath}>\n <input\n type=\"checkbox\"\n className=\"k-checkbox\"\n id={childPath}\n defaultChecked={content.checked}\n onClick={(event) => this.props.updateState(childPath, event.target.checked)} />\n <label className=\"k-checkbox-label\" htmlFor={childPath}>{content.text}</label>\n </div>\n })\n\n return <div className=\"k-form-field\">\n <LabelTooltip form={this.props.form} />\n {checkboxes}\n </div>\n }",
"interactive(x, y, options = {}) {\n let obj = new Interactive(this.id, options);\n // TODO: standardize this\n obj.root.setAttribute('x', x.toString());\n obj.root.setAttribute('y', y.toString());\n return obj;\n }",
"function BinaryBox(x, y, size, isClickable) {\n this.size = size;\n this.isClickable = isClickable;\n\n\n if (size == BoxSize.LARGE) {\n LargeTextBox.call(this, x, y, size, size, \"0\", isClickable);\n \n } else {\n TextBox.call(this, x, y, size, size, \"0\", undefined, isClickable);\n }\n }",
"static getCheckboxForRow(selected, checkboxHandler, cellType) {\n const CellComponent = `${cellType}`;\n return (\n <CellComponent key='meta-check' className='run-table-container'>\n <div>\n <input type='checkbox' checked={selected} onChange={checkboxHandler} />\n </div>\n </CellComponent>\n );\n }",
"function makeCoordInput(text, edit) {\n var layout = new android.widget.LinearLayout(ctx);\n layout.addView(text);\n layout.addView(edit);\n return layout;\n}",
"function positionCheckboxes() {\n\t\t\teach(allItems, function(item) {\n\t\t\t\tvar checkbox = item.checkbox,\n\t\t\t\t\talignAttr = legendGroup.alignAttr;\n\t\t\t\tif (checkbox) {\n\t\t\t\t\tcss(checkbox, {\n\t\t\t\t\t\tleft: (alignAttr.translateX + item.legendItemWidth + checkbox.x - 40) +PX,\n\t\t\t\t\t\ttop: (alignAttr.translateY + checkbox.y - 11) + PX\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t}",
"function createCheck(label) {\r\n if (label.childElementCount > 0) {\r\n label.removeChild(label.childNodes[1]);\r\n }\r\n var node = document.createElement(\"I\")\r\n node.className = \"fas fa-check-circle\";\r\n node.style = \"color:green\";\r\n label.appendChild(node);\r\n}",
"_handleCheckboxContainerClick(e) {\n const checkbox = dom(e.target).querySelector('input');\n if (!checkbox) { return; }\n checkbox.click();\n }",
"function handlecheckBox() {\n // This will give us the selected Box (parent node, to delete the whole canvasBox) (\"count-xx\")\n var selectedBox = this.parentNode.id;\n\n // Now see if you need to add/or remove selectedBox to imageSelected array\n if (this.checked === true) {\n // If it's checked, then add to imageSelected\n imageSelected.push(selectedBox);\n } else {\n // If not selected, then remove ID from imageSelected\n var boxIndex = imageSelected.indexOf(selectedBox);\n imageSelected.splice(boxIndex, 1);\n }\n}",
"function demoNumberPicker( layoutBounds ) {\n\n const enabledProperty = new BooleanProperty( true );\n\n const numberPicker = new NumberPicker( new Property( 0 ), new Property( new Range( -10, 10 ) ), {\n font: new PhetFont( 40 ),\n enabledProperty: enabledProperty\n } );\n\n const enabledCheckbox = new Checkbox( new Text( 'enabled', { font: new PhetFont( 20 ) } ), enabledProperty );\n\n return new VBox( {\n spacing: 40,\n children: [ numberPicker, enabledCheckbox ],\n center: layoutBounds.center\n } );\n}",
"function create_question() { \n var questionCell = Jupyter.notebook.get_selected_cell();\n addGroup(questionCell)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
hide dialogs and clear models | function hideModalDialogs() {
self.$createModalWindow.hide();
self.$editModalWindow.hide();
$.each([self.$createModalWindow.find("input"), self.$editModalWindow.find("input")],
function(index, item) {
$.each(item,
function(index, input) {
$(input).removeClass("error");
});
});
self.createModel.Age("");
self.createModel.Name("");
self.createModel.Position("");
self.createModel.StartDate("");
} | [
"function clearDialog() {\n $(\".dialog\").empty();\n }",
"_hideModel() {\n this._model.classList.add('hidden');\n }",
"_closeModel() {\n this._model.querySelector('.close').addEventListener('click', e => {\n this._hideModel();\n });\n }",
"function clearAndHideForm() {\n clearForm();\n hideForm();\n}",
"function _remove() \n {\n dialog.remove();\n }",
"function hide_global_supplier_settings()\n{\n\t//Empty the html \n\t$(\"#sup_list_view_global\").html(\"\");\n\t//Hide the modal box \n\t$('.overlay').hide(); \n\t$('#setng_supplier_global').hide();\n\t//Nothing else to be done \n}",
"function clearUI() {\n clearProjectFields();\n clearTestingFields();\n clearIssueFields();\n}",
"function hide_global_supplier_settings()\n{\n\t//Empty the html \n\t$(\"#sup_list_view_global\").html(\"\");\n\t\n\t//Hide the modal box \n\t$('.overlay').hide(); \n\t$('#setng_supplier_global').hide();\n\t\n\t//update back array\n\tonBackKeyDown();\n}",
"function hideCreateDialog() {\n if (document.getElementById('editID').value != '-1') {\n $('#rfelement' + document.getElementById('editID').value).show();\n document.getElementById('editID').value = '-1';\n }\n $('#textarea_preview').hide();\n $('#singlechoice_preview').hide();\n $('#multiplechoice_preview').hide();\n $('#matrix_preview').hide();\n $('#grading_preview').hide();\n $('#tendency_preview').hide();\n $('#newquestion').hide();\n $('#text_preview').show();\n //$('#newquestion_button').show();\n}",
"function closeTaxDetail() {\r\n if (!$isOnView)\r\n $validateTax.resetForm(); \r\n $('#divTaxBreakdown').dialog('close');\r\n}",
"@action closeDialog() {\r\n\t\tif (this.dialog) this.dialog.opened = false;\r\n\t}",
"function f_resetAll(){\n fdoc.find('.spEdit').removeAttr('contenteditable').removeClass('spEdit');\n fdoc.find('.targetOutline').removeAttr('contenteditable').removeClass('targetOutline');\n fdoc.find('#ipkMenu').hide();\n fdoc.find('.ipkMenuCopyAnime').removeClass('ipkMenuCopyAnime');\n $('.sp-show-edit-only-place').css('opacity','0.2');\n f_resetHiddenBox();\n }",
"_hideFormElements()\r\n {\r\n $(this.el).find('#filter-inputs div input').val('');\r\n $(this.el).find('#filter-inputs div select').val('');\r\n $(this.el).find('#filter-inputs').children().hide();\r\n }",
"_onDialogClosed() {\n this._selectedApplication = {};\n this.$.appscoApplicationAddSearch.reset();\n this.$.appscoApplicationAddSettings.reset();\n this._selected = 'appsco-application-add-search';\n this._dialogTitle = 'Add application';\n this._hideLoader();\n }",
"function alterCalculationsScreen(){\n\t$(\"#youHaveNoProjects\").hide();\n\t$(\"#youHaveSomeProjects\").hide();\n\t$(\"#youHaveUntimelyProjects\").show();\n}",
"function _resetIssuesUI() {\n var $noIssues = $issuesWrapper.find(\".no-issues\"),\n $noGithub = $issuesWrapper.find(\".no-github\"),\n $errors = $issuesWrapper.find(\".errors\"),\n $state = $issuesPanel.find(\".issue-state\"),\n $assignee = $issuesPanel.find(\".issue-assignee\");\n \n $issuesWrapper.removeClass(\"loading\");\n $noIssues.addClass(\"hide\");\n $noGithub.addClass(\"hide\");\n $errors.addClass(\"hide\");\n $state.addClass(\"disabled\");\n $assignee.addClass(\"disabled\");\n \n $issuesList.empty();\n }",
"hideVisit() {\n\t\tthis.modalContainer.classList.remove(\"visible\");\n\t}",
"function hideLayoutDialog() {\n if (document.getElementById('editID').value != '-1') {\n $('#rfelement' + document.getElementById('editID').value).show();\n document.getElementById('editID').value = '-1';\n }\n $('#newlayout').hide();\n //$('#newquestion_button').show();\n}",
"function clearScope() {\n scope.title = '';\n scope.body = '';\n scope.buttons.length = 0;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Chapter 101 RopeGroup Player is chaste and cannot be plugged | function C101_KinbakuClub_RopeGroup_ChastityPlug() {
if (Common_PlayerChaste) {
OverridenIntroText = GetText("CannotPlug");
C101_KinbakuClub_RopeGroup_CurrentStage = 856;
}
} | [
"function C101_KinbakuClub_RopeGroup_PlayerWhimperLucy() {\n\tif (C101_KinbakuClub_RopeGroup_LucyIsAnnoyed <= 0) {\n\t\tPlayerUngag();\n\t\tActorChangeAttitude( 1, -1)\n\t} else {\n\t\tif (C101_KinbakuClub_RopeGroup_LucyIsAnnoyed >= 2 || ActorGetValue(ActorLove) >= 1) {\n\t\t\tOverridenIntroText = GetText(\"AnnoyedNoUngag\");\n\t\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 640;\n\t\t} else {\n\t\t\tPlayerUngag();\n\t\t\tOverridenIntroText = GetText(\"AnnoyedUngag\");\n\t\t}\n\t}\n}",
"function C101_KinbakuClub_RopeGroup_PluggedHappily() {\n\tC101_KinbakuClub_RopeGroup_PlugMood = \"Happily\";\n\tC101_KinbakuClub_RopeGroup_PlayerPlugged();\n}",
"function C101_KinbakuClub_RopeGroup_PluggedPanic() {\n\tC101_KinbakuClub_RopeGroup_PlugMood = \"Panic\";\n\tC101_KinbakuClub_RopeGroup_PlayerPlugged();\n}",
"function C101_KinbakuClub_RopeGroup_WillLucyTie() {\n\tif (ActorGetValue(ActorLove) >= 3 || ActorGetValue(ActorSubmission) >= 2) {\n\t\tOverridenIntroText = GetText(\"LucyNotTieYou\");\n\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 600;\n\t} else C101_KinbakuClub_RopeGroup_PlayerTied();\n}",
"function C101_KinbakuClub_RopeGroup_PluggedAccept() {\n\tC101_KinbakuClub_RopeGroup_PlugMood = \"Accept\";\n\tC101_KinbakuClub_RopeGroup_PlayerPlugged();\n}",
"function C101_KinbakuClub_RopeGroup_HelplessStruggle() {\n\tif (Common_PlayerChaste) OverridenIntroText = GetText(\"ChasteStruggle\");\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 830) C101_KinbakuClub_RopeGroup_WaitingForMistress();\n\telse C101_KinbakuClub_RopeGroup_HelplessTime();\n}",
"function C101_KinbakuClub_RopeGroup_HelplessKnot() {\n\tif (Common_PlayerChaste) OverridenIntroText = GetText(\"ChasteKnot\");\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 830) C101_KinbakuClub_RopeGroup_WaitingForMistress();\n\telse C101_KinbakuClub_RopeGroup_HelplessTime();\n}",
"function C101_KinbakuClub_RopeGroup_PluggedPanic() {\n\tC101_KinbakuClub_RopeGroup_PlugMood = \"Panic\";\n\tPlayerLockInventory(\"ButtPlug\");\n}",
"function C101_KinbakuClub_RopeGroup_PlayerCollared() {\n\tCommon_PlayerOwner = CurrentActor;\n\tCommon_ActorIsOwner = true;\n\tPlayerLockInventory(\"Collar\");\n\tCurrentTime = CurrentTime + 50000;\n}",
"function C101_KinbakuClub_RopeGroup_PlayerSusExpression() {\n\tC101_KinbakuClub_RopeGroup_PlayerPose = \"SusPlr_LookDownNeutral\";\n\tif (ActorGetValue(ActorSubmission) >= 2) C101_KinbakuClub_RopeGroup_PlayerPose = \"SusPlr_LookDownDominant\";\n\tif (ActorGetValue(ActorSubmission) <= -2) C101_KinbakuClub_RopeGroup_PlayerPose = \"SusPlr_LookDownSubmissive\";\n}",
"static needPlayers() {\n\t\talert('There\\'s not enough players in the room');\n\t}",
"function C006_Isolation_Yuki_AddRope() {\n\tPlayerClothes(\"Underwear\");\n\tPlayerLockInventory(\"Rope\");\n}",
"function C101_KinbakuClub_RopeGroup_PlayerTapeGagged() {\n\tPlayerRemoveInventory(\"TapeGag\", 1);\n\tPlayerLockInventory(\"TapeGag\");\n\tCurrentTime = CurrentTime + 30000;\n\tC101_KinbakuClub_RopeGroup_PlayerPose = \"SusPlr_JustTapeGagged\";\n}",
"function C101_KinbakuClub_RopeGroup_StruggleForLucy() {\n\tif (!C101_KinbakuClub_RopeGroup_StruggledForLucy) ActorChangeAttitude( 1, -1)\n\tC101_KinbakuClub_RopeGroup_StruggledForLucy = true;\n}",
"function C101_KinbakuClub_RopeGroup_SafeWord() {\n\tC101_KinbakuClub_RopeGroup_Guessing = true;\n\tC101_KinbakuClub_RopeGroup_HeatherTugging = false;\n}",
"function C101_KinbakuClub_RopeGroup_AddedExtras(ExtraNumber) {\n\tif (ExtraNumber == 1 && ActorGetValue(ActorSubmission) >= 3) {\n\t\tOverridenIntroText = GetText(\"NotBelted\");\n\t\tC101_KinbakuClub_RopeGroup_PlayerFreed()\n\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 691;\n\t} else {\n\t\tif (!PlayerHasLockedInventory(\"VibratingEgg\") && !PlayerHasLockedInventory(\"ButtPlug\")) {\n\t\t\tPlayerLockInventory(\"VibratingEgg\");\n\t\t\tPlayerLockInventory(\"ButtPlug\");\n\t\t} else {\n\t\t\tif (!PlayerHasLockedInventory(\"VibratingEgg\")) {\n\t\t\t\tPlayerLockInventory(\"VibratingEgg\");\n\t\t\t\tif (ExtraNumber == 1) OverridenIntroText = GetText(\"ArgueEggNBelted\");\n\t\t\t\telse OverridenIntroText = GetText(\"EggNBelted\");\n\t\t\t} else {\n\t\t\t\tif (!PlayerHasLockedInventory(\"ButtPlug\")) {\n\t\t\t\t\tPlayerLockInventory(\"ButtPlug\");\n\t\t\t\t\tif (ExtraNumber == 1) OverridenIntroText = GetText(\"ArguePlugNBelted\");\n\t\t\t\t\telse OverridenIntroText = GetText(\"PlugNBelted\");\n\t\t\t\t} else {\n\t\t\t\t\tif (ExtraNumber == 1) OverridenIntroText = GetText(\"ArgueJustBelted\");\n\t\t\t\t\telse OverridenIntroText = GetText(\"JustBelted\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tC101_KinbakuClub_RopeGroup_FullyExposed = false;\n\t\tPlayerLockInventory(\"ChastityBelt\");\n\t}\n}",
"function oteleport(err) {\n var tmp;\n if (err) {\n if (rnd(151) < 3) {\n /*\n 12.4.5 - you shouldn't get trapped in solid rock with WTW\n */\n if (player.WTW == 0) {\n updateLog(`You are trapped in solid rock!`)\n died(264, false); /* trapped in solid rock */\n }\n else {\n updateLog(`You feel lucky!`)\n }\n }\n }\n\n if (player.TELEFLAG == 0 && level != 0) {\n changedDepth = millis(); // notify when depth changes to '?'\n }\n\n player.TELEFLAG = 1; /* show ? on bottomline if been teleported */\n if (level == 0) {\n tmp = 0;\n } else if (level < MAXLEVEL) {\n tmp = rnd(5) + level - 3;\n if (tmp >= MAXLEVEL)\n tmp = MAXLEVEL - 1;\n if (tmp < 1)\n tmp = 1;\n } else {\n tmp = rnd(3) + level - 2;\n if (tmp >= MAXLEVEL + MAXVLEVEL)\n tmp = MAXLEVEL + MAXVLEVEL - 1;\n if (tmp < MAXLEVEL)\n tmp = MAXLEVEL;\n }\n player.x = rnd(MAXX - 2);\n player.y = rnd(MAXY - 2);\n if (level != tmp) {\n newcavelevel(tmp);\n }\n positionplayer();\n}",
"function requestPlayerChoice() {\n const rockPaperScissors = prompt(\"Rock? Paper? or Scissors?\");\n\n if (\n /^rock$/i.test(rockPaperScissors) ||\n /^paper$/i.test(rockPaperScissors) ||\n /^scissors$/i.test(rockPaperScissors)\n ) {\n playerChoice = rockPaperScissors.toLowerCase();\n return playerChoice;\n } else {\n console.log(\"offffffff\");\n requestPlayerChoice();\n }\n}",
"function playPlayerVsComputer(){\n setPlayerVsPlayer({\n AI:true,\n AImove:false\n });\n }",
"function C101_KinbakuClub_RopeGroup_CassiContinue() {\n\tActorAddOrgasm();\n\tC101_KinbakuClub_RopeGroup_PlayerArousal = C101_KinbakuClub_RopeGroup_PlayerArousal - 200;\n\tC101_KinbakuClub_RopeGroup_ForcingCassi = false;\n\tC101_KinbakuClub_RopeGroup_PressingCassi = false;\n\tC101_KinbakuClub_RopeGroup_CanPressCassi = true;\n\tif (ActorGetValue(ActorLove) <= 2) {\n\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 686;\n\t\tif (ActorHasInventory(\"Cuffs\")) {\n\t\t\tOverridenIntroText = GetText(\"CassiDoneUnCuff\");\n\t\t\tActorRemoveInventory(\"Cuffs\");\n\t\t} else OverridenIntroText = GetText(\"CassiDone\");\n\t} else {\n\t\tC101_KinbakuClub_RopeGroup_OrgasmCount++\n\t\tif (C101_KinbakuClub_RopeGroup_OrgasmCount >= 2) {\n\t\t\tC101_KinbakuClub_RopeGroup_AnkleGrab = false;\n\t\t\tC101_KinbakuClub_RopeGroup_fingerinsertion = false;\n\t\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 685;\n\t\t\tOverridenIntroText = GetText(\"CassiAsks\");\n\t\t}\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save blog as draft handler | function saveBlogAsNewDraft(e) {
// Get content data from ckeditor
var contentInput = CKEDITOR.instances.ckeditor.getData();
// Make 'tags' string to array
var tagsArr = [];
var tagsList = document.querySelectorAll('#myTags li .tagit-label');
function tagsToArr() {
for (var i = 0; i < tagsList.length; i++) {
tagsArr.push(tagsList[i].innerText)
};
return tagsArr;
};
// time now
var date = new Date();
var dateAndTimeNow = date.getFullYear() + "-" + (((+date.getMonth() + 1) < 10) ? "0" + (+date.getMonth() + 1) : (+date.getMonth() + 1)) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes();
// Save blog as draft data to send
var saveBlogAsDraft = {
title: document.querySelector('.article-title input').value,
description: "create draft",
content: contentInput,
tags: tagsToArr(),
publish_in: (!document.getElementById('datetimepicker').value ? dateAndTimeNow : document.getElementById('datetimepicker').value),
published: false
}
// Init Blog service
var blog = BlogService();
blog.newBlog(saveBlogAsDraft);
// console.log(saveBlogAsDraft);
} | [
"function save () {\n\n\tvar title = postTitle.value;\n\tvar content = postContent.value;\n\tvar savedPost = { \"title\": title, \"content\": content };\n\n\tsaving = setInterval( saveItemToLocalStorage, 5000, savedPost, 'savedPost' );\n\n}",
"async create(draft) {\n return this.apiClient.createDraft(draft);\n }",
"function handleEdit(event,ele){\n event.preventDefault();\n setEditing(true);\n setCurrentBlog(ele);\n\n }",
"function savePost(req, res) {\n shared.verifyPID(req, res, () => {\n const user = db.users[res.locals.userid];\n const post = db.posts.feed[req.params.pid];\n if (!user.saved.includes(post.id)) {\n user.saved.push(post.id);\n db.writeUsers();\n }\n res.send(\"Saved post.\")\n })\n}",
"archivePost() {\n var post = {};\n\n if(document.getElementById(\"title\").value) {\n post.title = document.getElementById(\"title\").value;\n }\n else {\n post.title = \"Untitled post\";\n }\n\n if(document.getElementById(\"post\").value) {\n post.post = document.getElementById(\"post\").value;\n }\n else {\n post.post = \"\";\n }\n\n /*If the current post was previously loaded, updates it*/\n if (this.loadedPost) {\n this.postArray[this.loadedPost].title = post.title;\n this.postArray[this.loadedPost].post = post.post;\n }\n /*Else, the post is stored as a new one*/\n else{\n post.id = this.postId;\n this.postId = this.postId + 1; // Updates the post ID for the next post to be created\n this.postArray.push(post);\n }\n\n /*Clears the text area*/\n this.clearPost();\n }",
"listenLoadEditForm() {\n editor.clearMenus();\n const slugs = h.getAfterHash(this.href),\n post = model.getPostBySlugs(slugs);\n\n editor.currentPost = post;\n editor.currentPostType = post.type;\n\n if (editor.currentPostType !== 'settings') {\n view.currentPost = post;\n view.update();\n } else {\n event.preventDefault();\n }\n\n editor.showEditPanel();\n }",
"function addBlogPost() {\n clearDialogInputs();\n showDialog(blogPosts, \"add\");\n}",
"fillEditForm() {\n let post = editor.currentPost,\n editTitle = document.getElementById('editTitle'),\n postTitle = h.getPostTitle(),\n titleField = h.getEditorTitleField();\n\n // Update the title and content fields\n editTitle.value = post.title;\n editContent.value = post.content;\n\n // Initialize the wysiwyg editor\n wysiwyg = wysiwygEditor(document.getElementById('editContent'));\n\n // Add listeners to update the view on field changes\n if (post.type !== 'settings') {\n // Actions if not editing a setting\n titleField.addEventListener('input', function () {\n editor.currentPost.title = this.value;\n view.updateTitle(this.value);\n }, false);\n wysiwyg.onUpdate(function () {\n view.updateContent(wysiwyg.read());\n editor.currentPost.content = wysiwyg.read();\n });\n } else {\n // Live update controls for settings\n if (post.slug === 'site-name') {\n wysiwyg.onUpdate(function () {\n view.updateSiteName(wysiwyg.read());\n editor.currentPost.content = wysiwyg.read();\n });\n } else if (post.slug == 'site-description') {\n wysiwyg.onUpdate(function () {\n view.updateSiteDescription(wysiwyg.read());\n editor.currentPost.content = wysiwyg.read();\n });\n } else {}\n }\n }",
"function saveOrUpdatePost(){\n\t\t\n\t\t//get the values from the input elements\n\t\tvar title=$('#edittitle').val();\n\t\tvar text=$('#edittext').val();\n\t\tvar id=$('#postid').val();\n\t\t\n\t\t//create the data object and fill it in\n\t\tvar dataObj = {};\n\t\tdataObj[\"id\"] = id;\n\t\tdataObj[\"title\"] = title;\n\t\tdataObj[\"text\"] = text;\n\t\t\n\t\t//make the call to saveorupdate REST Service\n\t\t$.ajax({ \n\t\t url: \"saveorupdatepost\", \n\t\t type: 'POST', \n\t\t dataType: 'json', \n\t\t data: JSON.stringify(dataObj), //convert to JSON String to pass to the service\n\t\t contentType: 'application/json',\n\t\t mimeType: 'application/json',\n\t\t success: function(data) { \n\t\t \tshowPost(data.id);\n\t\t },\n\t\t error:function(data,status,er) { \n\t\t alert(status+\",\"+er);\n\t\t }\n\t\t});\n\t\t\n\t}",
"function edit(post_id) {\n console.log(\"edit function\", post_id);\n txt_area = document.createElement(\"textarea\");\n txt_area.className = \"txt_area\";\n txt_area.id = \"txt_area_\" + post_id;\n txt_area.innerHTML = document.getElementById(\"text_\" + post_id).innerHTML;\n\n document.getElementById(\"text_\" + post_id).innerHTML = \"\";\n document.getElementById(\"text_\" + post_id).append(txt_area);\n document.getElementById(\"edit_\" + post_id).hidden = true;\n\n save_button = document.createElement(\"button\");\n save_button.className = \"btn btn-primary\";\n save_button.innerHTML = \"Save\";\n save_button.addEventListener(\"click\", function () {\n console.log(document.getElementById(\"txt_area_\" + post_id).value)\n save_post(post_id);\n })\n document.getElementById(\"text_\" + post_id).append(save_button);\n\n}",
"function editablePost(){\n var postBody = document.getElementById('postBody');\n var postText = postBody.innerText;\n if(postText.startsWith(\"UPDATED:\\n\"))\n postText = postText.replace(\"UPDATED:\\n\",\"\");\n postBody.innerHTML = postText;\n postBody.contentEditable = \"true\";\n postBody.classList.add(\"edit\");\n}",
"save() {\n var elem = this._view.getNote(),\n data = validate.getSanitizedNote({\n id: this.id,\n content: elem.html(),\n settings: elem.data(\"settings\")\n });\n \n this._model.setData(\n data,\n (d) => {\n console.log(\"saved\");\n }, (e) => {\n console.log(e);\n }\n );\n }",
"async publish(draftLinks) {\n return this.apiClient.publishDraft(draftLinks);\n }",
"function PublishToSave() { $('#wpSave').attr('value','Save changes'); $('a[data-id=\"move\"]').html('Move'); }",
"save(event) {\n let data = {\n agenda: Agenda.file,\n attach: this.props.item.attach,\n initials: document.getElementById(\"comment-initials\").value || User.initials,\n comment: this.state.comment\n };\n\n this.setState({ disabled: true });\n\n Pending.update(\"comment\", data, (pending) => {\n jQuery(\"#comment-form\").modal(\"hide\");\n document.body.classList.remove(\"modal-open\");\n this.setState({ disabled: false });\n Pending.load(pending)\n })\n }",
"function updatePost (user, post, fileName, title, datePublished, content, commitId) {\n var newRevision = new RevisionModel ({\n author : user,\n commitId : commitId,\n revisionDate : datePublished,\n content : content,\n });\n\n\n fetchRevisionsByIds (post.revisions, function (revisions) {\n if (revisions != null) {\n // check through the revisions to make sure the commitId doesn't already exist.\n for (key in revisions) {\n if (revisions[key].commitId == commitId) {\n console.log ('This revision already exists');\n return; \n }\n }\n\n // create a new revision for the post\n newRevision.save (function (error) {\n if (!error) {\n post.revisions.push (newRevision);\n post.currentRevision = newRevision;\n post.save (function (error) {\n if (!error) {\n user.revisions.push (newRevision);\n user.save (function (error) {\n if (!error) {\n console.log (\"A new revision was saved\"); \n }\n else {\n console.log (\"A new revision wasn't saved to a user\");\n }\n });\n }\n else {\n console.log (\"A revision was saved but not attributed to the post\");\n }\n });\n }\n else {\n console.log ('an error occured while saving a new revision: ' + error);\n }\n });\n\n }\n else {\n console.log (\"Trying to update a post that doesn't have any revisions\");\n }\n });\n}",
"update() {\n view.updateTitle(view.currentPost.title);\n view.updateContent(view.currentPost.content);\n\n view.removeBlogPosts();\n if (view.currentPost.slug === 'blog') {\n // Append blog posts to blog page\n view.loadBlogPosts();\n }\n }",
"async submitDraft(doc) {\n const action = window.apos.modules[doc.type].action;\n try {\n const submitted = await apos.http.post(`${action}/${doc._id}/submit`, {\n busy: true,\n body: {},\n draft: true\n });\n apos.notify('apostrophe:submittedForReview', {\n type: 'success',\n icon: 'list-status-icon',\n dismiss: true\n });\n apos.bus.$emit('content-changed', {\n doc: submitted,\n action: 'submit'\n });\n return submitted;\n } catch (e) {\n await apos.alert({\n heading: this.$t('apostrophe:errorWhileSubmitting'),\n description: e.message || this.$t('apostrophe:errorWhileSubmittingDescription'),\n localize: false\n });\n return false;\n }\n }",
"function saveDB(){\n clearInterval( intervalId );\n setInterval( saveDB, 60*60*1000 );\n PostsService.save();\n //$rootScope.postCount = $rootScope.postCount + 1;\n $rootScope.posthacked = [];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Continues the chunk upload session with an additional fragment. The current file content is not changed. Use the uploadId value that was passed to the StartUpload method that started the upload session. This method is currently available only on Office 365. | async continueUpload(uploadId, fileOffset, fragment) {
let n = await spPost(File(this, `continueUpload(uploadId=guid'${uploadId}',fileOffset=${fileOffset})`), { body: fragment });
if (typeof n === "object") {
// When OData=verbose the payload has the following shape:
// { ContinueUpload: "20971520" }
n = n.ContinueUpload;
}
return parseFloat(n);
} | [
"async finishUpload(uploadId, fileOffset, fragment) {\n const response = await spPost(File(this, `finishUpload(uploadId=guid'${uploadId}',fileOffset=${fileOffset})`), { body: fragment });\n return {\n data: response,\n file: fileFromServerRelativePath(this, response.ServerRelativeUrl),\n };\n }",
"async setContentChunked(file, progress, chunkSize = 10485760) {\n if (!isFunc(progress)) {\n progress = () => null;\n }\n const fileSize = (file === null || file === void 0 ? void 0 : file.size) || file.length;\n const totalBlocks = parseInt((fileSize / chunkSize).toString(), 10) + ((fileSize % chunkSize === 0) ? 1 : 0);\n const uploadId = getGUID();\n const fileRef = File(this).using(CancelAction(() => {\n return File(fileRef).cancelUpload(uploadId);\n }));\n // report that we are starting\n progress({ uploadId, blockNumber: 1, chunkSize, currentPointer: 0, fileSize, stage: \"starting\", totalBlocks });\n let currentPointer = await fileRef.startUpload(uploadId, file.slice(0, chunkSize));\n // skip the first and last blocks\n for (let i = 2; i < totalBlocks; i++) {\n progress({ uploadId, blockNumber: i, chunkSize, currentPointer, fileSize, stage: \"continue\", totalBlocks });\n currentPointer = await fileRef.continueUpload(uploadId, currentPointer, file.slice(currentPointer, currentPointer + chunkSize));\n }\n progress({ uploadId, blockNumber: totalBlocks, chunkSize, currentPointer, fileSize, stage: \"finishing\", totalBlocks });\n return fileRef.finishUpload(uploadId, currentPointer, file.slice(currentPointer));\n }",
"async startUpload(uploadId, fragment) {\n let n = await spPost(File(this, `startUpload(uploadId=guid'${uploadId}')`), { body: fragment });\n if (typeof n === \"object\") {\n // When OData=verbose the payload has the following shape:\n // { StartUpload: \"10485760\" }\n n = n.StartUpload;\n }\n return parseFloat(n);\n }",
"static upload(uploadTokenId, fileData, resume = false, finalChunk = true, resumeAt = -1){\n\t\tlet kparams = {};\n\t\tkparams.uploadTokenId = uploadTokenId;\n\t\tlet kfiles = {};\n\t\tkfiles.fileData = fileData;\n\t\tkparams.resume = resume;\n\t\tkparams.finalChunk = finalChunk;\n\t\tkparams.resumeAt = resumeAt;\n\t\treturn new kaltura.RequestBuilder('uploadtoken', 'upload', kparams, kfiles);\n\t}",
"function uploadDocumentAttachment() {\n console.log(\"uploadDocumentAttachment() started\");\n current.requestAttachmentUpload(function(response) {\n console.log(\"uploadDocumentAttachment() response is \" + JSON.stringify(response));\n loadDocuments();\n })\n}",
"function sendFile() {\n // const peer = peerRef.current;\n // const stream = file.stream();\n // const reader = stream.getReader();\n\n //console.log(file.size);\n console.log(Math.abs(file.size / 1000));\n //hybridsendFile();// calling a function inside this function can slow done the performance and file after selecting not showing immediately if code is called from hybrid module, writting code in here can fast and shows up file quickly\n\n // simple original one(less than 50kb)\n // reader.read().then((obj) => {\n // handlereading(obj.done, obj.value);\n // });\n\n /* w/o chuncking sending files(less than 50kb) & Sending more than 50kb files(but not possibile for very large files) */\n // file.arrayBuffer().then((buffer) => {\n // // Off goes the file!\n // peer.send(buffer);\n // });\n\n /* Sending more than 50kb files spliting in chunks(with chuncking) */\n // We convert the file from Blob to ArrayBuffer\n // file.arrayBuffer().then((buffer) => {\n // /**\n // * A chunkSize (in Bytes) is set here\n // * I have it set to 16KB\n // */\n // const chunkSize = 16 * 1024;\n\n // // Keep chunking, and sending the chunks to the other peer\n // while (buffer.byteLength) {\n // const chunk = buffer.slice(0, chunkSize);\n // buffer = buffer.slice(chunkSize, buffer.byteLength);\n\n // // Off goes the chunk!\n // peer.send(chunk);\n // }\n\n // //peer.send(JSON.stringify({ init: true, fileName: file.name }));\n\n // // End message to signal that all chunks have been sent\n // //peer.send(\"done!\");\n // peer.send(JSON.stringify({ done: true, fileName: file.name }));\n // });\n\n // simple original one(less than 50kb)\n // function handlereading(done, value) {\n // if (done) {\n // peer.write(JSON.stringify({ done: true, fileName: file.name }));\n // return;\n // }\n\n // //peer.write(value);//for less than 50mb\n // //peer.send(value); //for more than 50mb that too to some extend based on ram\n\n // reader.read().then((obj) => {\n // handlereading(obj.done, obj.value);\n // });\n // }\n /**********************************************************************************************************************************/\n const peer = peerRef.current;\n const stream = file.stream();\n const reader = stream.getReader();\n if (Math.abs(file.size / 1000) < 50) {\n //Math.floor()\n //less than 50kb\n /* w/o chuncking sending files(less than 50kb) & Sending more than 50kb files */\n console.log(\"Sender w/o chunking\");\n file.arrayBuffer().then((buffer) => {\n // Off goes the file!\n peer.send(buffer);\n peer.write(\n JSON.stringify({\n withoutchunking: true,\n done: true,\n fileName: file.name,\n })\n );\n //file = \"\";//assignment to constant error\n //setFile(\"\");//not working just reload sender,receiver so multiple duplicate prob not comes\n //return;\n });\n } else {\n //more than 50kb\n /* Sending more than 50kb files spliting in chunks(with chuncking) */\n // We convert the file from Blob to ArrayBuffer\n console.log(\"Sender w chunking\");\n file.arrayBuffer().then((buffer) => {\n /**\n * A chunkSize (in Bytes) is set here\n * I have it set to 16KB\n */\n const chunkSize = 16 * 1024;\n\n // Keep chunking, and sending the chunks to the other peer\n while (buffer.byteLength) {\n const chunk = buffer.slice(0, chunkSize);\n buffer = buffer.slice(chunkSize, buffer.byteLength);\n\n // Off goes the chunk!\n peer.send(chunk);\n }\n\n //peer.send(JSON.stringify({ init: true, fileName: file.name }));\n\n // End message to signal that all chunks have been sent\n //peer.send(\"done!\");\n peer.send(\n JSON.stringify({\n done: true,\n fileName: file.name,\n withchunking: true,\n })\n );\n //file = \"\";//assignment to constant error\n //setFile(\"\");//not working just reload sender,receiver so multiple duplicate prob not comes\n //return;\n });\n }\n }",
"function uploadDone(name, myRId) {\r\n var frame = frames[name];\r\n if (frame) {\r\n var ret = frame.document.getElementsByTagName(\"body\")[0].innerHTML;\r\n if (ret.length) {\r\n alert(ret);\r\n frame.document.getElementsByTagName(\"body\")[0].innerHTML = \"\";\r\n showRecordView(myRId);\r\n }\r\n }\r\n }",
"function upload() {\n\n isCanceled = false;\n indexNumbers = [];\n space = undefined;\n progress = 0;\n let path = $('#file-chooser').val();\n if (validatePath(path) & validateKey.call($('#space-key')) & validateTitle.call($('#space-title'))) {\n space = {\n name: $('#space-title').val(),\n key: $('#space-key').val()\n };\n setUploadMessage(i18n.PREPARING_FOR_UPLOAD, \"generic\");\n createDialog();\n if (AJS.$('#radioButtonUpdate').prop(\"checked\")) {\n\n } else if (AJS.$('#radioButtonClone').prop(\"checked\")) {\n specif = specIFLoader(URL.createObjectURL($('#file-chooser').prop('files')[0]), i18n, cloneToOldSpace, error);\n } else {\n specif = specIFLoader(URL.createObjectURL($('#file-chooser').prop('files')[0]), i18n, deleteOldSpace, error);\n }\n\n }\n }",
"function uploadDone()\r\n{\r\n\tvar htmlAreaObj = _getWorkAreaDefaultObj();\r\n\tvar objAjax = htmlAreaObj.getHTMLAjax();\r\n\tvar docview = objAjax.getDocViewId();\r\n\tif (docview==132)\r\n\t{\r\n\t\tshowProductOverview(null);\r\n\t}\r\n\telse if (docview==2406 || docview==2409)\r\n\t{\r\n\t\ttabSelectionAction(null, 'fitevaloverview.do', 'view', '100', '100')\r\n\t}\r\n\telse if (docview==4007)\r\n\t{\r\n\t\ttabSelectionAction(null, 'sampleeval.do', 'view', '4000', '4000');\r\n\t}\r\n\r\n}",
"handleUpload() {\n if (!this.bShowUploadSection) {\n this.bShowUploadSection = true;\n this.sLabelUpload = 'Collapse Upload Section';\n this.uIconName = 'utility:down';\n }\n else {\n this.bShowUploadSection = false;\n this.sLabelUpload = 'Expand Upload Section';\n this.uIconName = 'utility:right';\n }\n }",
"function handleReaderLoadEnd(evt) {\n // update the editor with the files content\n editor.getSession().setValue(evt.target.result);\n}",
"saveChunk() {\n console.log(\"Saving Chunk for \" + this.name + \" @ \" + this.path + \"/fullLog.json\");\n\n // Load the Full Log.\n let fullLogRaw = fs.readFileSync(this.path + \"/fullLog.json\");\n let fullLog = JSON.parse(fullLogRaw);\n\n // Push the Current Chunk.\n fullLog.push(this.currentChunk);\n\n // Clear the Current Chunk.\n this.currentChunk = [];\n let logJSON = JSON.stringify(fullLog, null, 2);\n\n // Write the New Full Log.\n fs.writeFileSync(this.path + \"/fullLog.json\", logJSON);\n this.currentChunkIndex++;\n }",
"function initFlow() {\n return {\n chunkSize: 104857600, // 100mb\n target: config.REST_URL + '/publish/email/mensagem/upload',\n //target: 'http://localhost:8500/rest/seeaway-app/contabil/upload',\n query: {\n type: 'contabil-upload'\n }\n };\n }",
"_ensure (size) {\n const toWriteSize = this._chunkOpen ? size : size + _CHUNK_HEADER_SIZE\n if (this._buffer.remaining() < toWriteSize) {\n this.flush()\n }\n\n if (!this._chunkOpen) {\n this._currentChunkStart = this._buffer.position\n this._buffer.position = this._buffer.position + _CHUNK_HEADER_SIZE\n this._chunkOpen = true\n }\n }",
"function iFrameUpload(fieldId, fieldTypeId, contentTypeId, resultdata)\n{\n\tvar field = {id:fieldId, fieldtypeid:fieldTypeId, contenttypeid:contentTypeId};\n\tvar data = jQuery.parseJSON(resultdata);\n\t\n\t// test for error\n\tif(data['error'] == '')\n\t{\n\t\tif(fieldTypeId == 18) // Image Gallery\n\t\t{\n\t\t\taddImageGalleryRow(fieldId, data);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsetPreview(field, data);\n\t\t}\t\n\t}\n\telse\n\t{\n\t\talert(data['error']);\n\t}\t\n\t\n\tjQuery.unblockUI();\n}",
"function appendToFileOverwritingLastBlock(file, initContent, content) {\n let blockSizeInBytes = 16;\n let fileSizeInBytes = 0;\n if (fs.existsSync(file)) {\n fileSizeInBytes = fs.statSync(file)[\"size\"];\n } else {\n fs.closeSync(fs.openSync(file, 'w'));\n content = Buffer.concat([initContent, content]);\n }\n\n let pos = 0;\n let bytesWrote;\n let start = Math.max(0, fileSizeInBytes - blockSizeInBytes);\n let length = Buffer.byteLength(content);\n let fd = fs.openSync(file, 'r+');\n do {\n bytesWrote = tryWriteSync(fd, content, pos, length, start);\n pos += bytesWrote;\n start = null;\n } while (bytesWrote !== 0 && pos < length);\n\n fs.closeSync(fd);\n}",
"addPart ({ id, owner, file, partNum }, portalOpts) {\n const args = this.addOptions({\n id,\n owner,\n file,\n partNum\n }, portalOpts);\n\n return addItemPart(args)\n .catch(handleError);\n }",
"function upload() {\n if (! canUpload()) {\n return alert(\"Can't upload right now.\");\n }\n\n // sanity check queued files\n var totalSize = 0;\n for (var i = 0; i < allFiles.length; i++) {\n totalSize += allFiles[i].size;\n }\n if (totalSize > maxUploadSize) {\n return alert(\n 'Sorry, you can only upload ' +\n humanSize(maxUploadSize) +\n ' at a time (you tried to upload ' +\n humanSize(totalSize) +\n ')!'\n );\n }\n\n uploading = true;\n\n // update UI\n var uploadButton = $(\"#upload\");\n uploadButton.text(\"Cancel Upload\");\n\n $(\"#statusText\").show();\n $(\"#selectFiles\").slideUp(200);\n $(\".remove\").fadeOut(200);\n\n // start the upload\n // http://stackoverflow.com/a/8244082\n var request = $.ajax({\n url: \"/upload?json\",\n type: \"POST\",\n contentType: false,\n\n data: getFormData(),\n processData: false,\n\n xhr: function() {\n var req = $.ajaxSettings.xhr();\n\n req.upload.addEventListener(\"progress\", function(e) {\n if (request != uploadRequest) {\n return; // upload was cancelled\n }\n\n if (e.lengthComputable) {\n updateProgress(e.loaded, e.total);\n }\n }, false);\n\n return req;\n },\n\n error: function(xhr, status) {\n if (request !== uploadRequest) {\n return; // upload was cancelled\n }\n\n if (xhr.responseJSON) {\n alert(xhr.responseJSON.error);\n cancelUpload();\n } else {\n // TODO: improve error handling\n console.log(\"Unhandled failure: \" + status + \", status=\" + xhr.status + \", statusText=\" + xhr.statusText);\n alert(\"Sorry, an unexpected error occured.\");\n cancelUpload();\n }\n },\n\n success: function(data) {\n if (request != uploadRequest) {\n return; // upload was cancelled\n }\n\n // TODO: improve error handling\n if (! data.success) {\n return alert(data.error);\n }\n\n if (uploadHistory.enabled()) {\n uploadHistory.addItemToHistory({\n url: data.redirect,\n time: new Date(),\n fileDetails: Object.entries(data.uploaded_files).map(([filename, metadata]) => ({\n filename,\n bytes: metadata.bytes,\n rawUrl: metadata.raw,\n pasteUrl: metadata.paste,\n })),\n });\n }\n\n window.location.href = data.redirect;\n }\n });\n\n uploadRequest = request;\n}",
"_uploadFile(upload, file) {\n const formData = new FormData();\n\n // Copy the keys from our upload instructions into the form data\n for (const key in upload.fields) {\n formData.append(key, upload.fields[key]);\n }\n\n // AWS ignores all fields in the request after the file field, so all other\n // fields must appear before the file.\n formData.append('file', file);\n\n // Now we can upload the file\n fetch(upload.url, {\n method: 'post',\n body: formData\n }).then((response) => {\n if (response.ok) {\n this._finalizeFileUpload(upload, file);\n } else {\n this.options.onError(new AssetUploaderError(\"There was an error uploading the file. Please try again.\"));\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decrements max listeners by one, if they are not zero. | decrementMaxListeners() {
const maxListeners = this.getMaxListeners();
if (maxListeners !== 0) {
this.setMaxListeners(maxListeners - 1);
}
} | [
"function getMaximumListeners() {\n const { settings } = state_1.getStore();\n return settings.options.maximumProcessListeners;\n}",
"unregisterListener(aListener) {\n let idx = this._listeners.indexOf(aListener);\n if (idx >= 0) {\n this._listeners.splice(idx, 1);\n }\n }",
"function listenerSetCallback(listeners) {\n var listenersAlive = _.map(listeners, function(listener) {\n if (listener.condition()) {\n listener.callback(angular.copy(directory[listeners.listName].options));\n return true;\n }\n });\n for (var i = listenersAlive.length - 1; i >= 0; i--) {\n if (!listenersAlive[i]) { listeners.splice(i,1); }\n }\n\n // if there are no listeners left then kill the watcher\n if (listeners.length === 0) { listeners.watcher(); }\n }",
"resetToMax() {\n this._currentBaseMs = this._maxDelayMs;\n }",
"function removeListeners() {\n removeEventListener('pointerup', onPointerUp, listenerOpts);\n removeEventListener('pointercancel', onPointerCancel, listenerOpts);\n }",
"removeEventListener(listener) {\n const index = this.listeners.indexOf(listener);\n\n if (index === -1) {\n throw new Error(\n \"Cannot remove an unknown listener. This listener has never been registered\"\n );\n }\n\n this.listeners.splice(index, 1);\n }",
"removeUpdateListener(cb) {\n let idx = this.updateCallbacks.findIndex(o => o === cb);\n this.updateCallbacks.slice(idx);\n }",
"incStreamLoses(type) {\n this.streamLosses[type] = this.streamLosses[type] ? this.streamLosses[type] + 1 : 1;\n }",
"function decrease() {\n\t_interval && clearInterval( _interval );\n\t_interval = setInterval(function(){\n\t\t_counter = parseInt(_counter) - 5;\n\t\tif( _counter <= 0 ){\n\t\t\t_counter = 0;\n\t\t\tif( _cinterval++ > 25 ){\n\t\t\t\t_interval && clearInterval( _interval );\n\t\t\t\t_cinterval = 0;\n\t\t\t}\n\t\t}\n\t\t_headerbar.refresh_advice.setHeight( _counter + '%' );\n\t\t_headerbar.refresh_counter.setWidth( _counter + '%' );\n\t\t/**** /\tTi.API.info( 'decrease >>> _counter:' + _counter ); /****/\n\t\treturn true;\n\t}, 20);\n\treturn true;\n}",
"function tiproxy_remove_fire_listener(e) {\r\n throw new Error(\"should not be called\");\r\n }",
"countDecrease(item) {\n if (item.count <= 1) {\n this.msg2;\n }\n else {\n item.count = item.count - 1;\n this.isErrorMsg = false;\n }\n }",
"function listeners_(){this.listeners$bq6g=( {});}",
"decrementTotalPeople() {\n\t\tlet totalPerson = document.getElementById('totalPerson').value;\n\t\tif(totalPerson > 1) {\n\t\t\t\t// decrease totalPerson one by one\n\t\t\ttotalPerson = totalPerson - 1;\n\t\t\tdocument.getElementById('totalPerson').value = totalPerson;\n\t\t}\n\t}",
"deactivateListenersForSocket(socket) {\n SOCKET_EVENTS.forEach((socketEvent, index) => {\n socket.removeAllListeners(socketEvent);\n });\n }",
"withMaximum(maximum) {\n max = maximum;\n return timer;\n }",
"async deleteIfMoreThan(maxNum) {\n console.log(`== Try to delete data if the stored records is more than ${maxNum} ==`);\n\n const count = await this.baseModel.model.count();\n\n if (count > maxNum) {\n await this.delete([{\n $sort: {\n timestap: -1\n },\n }, {\n $limit: count - maxNum\n }]);\n }\n\n console.log(`== Success to delete data if the stored records is more than ${maxNum} ==`);\n }",
"static detachListener(cb) {\n firebase.database().ref(BASE).off(\"value\", cb);\n }",
"function lectureStudentCountListener(){\n dbRef.child(\"lectures/\" + sessionStorage.currentSubject + \"/\" + sessionStorage.lectureDate+ \"/viewers\").on(\"child_removed\", function(snapshot){\n incrementStudCountLecture(-1)\n })\n}",
"function decrementCount(key) {\n if (counts[key] < 2) {\n delete counts[key];\n } else {\n counts[key] -= 1;\n }\n }",
"removeDragFinishedListener(listener) {\n if (this.dragFinishedListener === listener) {\n this.dragFinishedListener = null;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialise theme image cache, and fetch any secondary branding image (if present) | async getThemeImages() {
// Check if we know what our theme name is
let themeconf = null;
try {
// Read our theme configuration (if any)
data_string = await AsyncStorage.getItem(`@TexecomStore:theme`);
if (data_string !== null) {
themeconf = JSON.parse(data_string);
}
} catch (error) {
// No cached theme info
}
// If we have a theme name, initialise the theme image cache.
// Also look for any existing cached secondary branding image.
let logoSecondaryImage = null;
if (themeconf) {
console.log("Theme: " + themeconf.theme);
// Initialise the Theme module cache, so that we know in advance of
// getting any image URIs which are already cached, rather than
// looking for file existence every time we reference an image.
ThemeInitialiseCache(themeconf.theme);
// Set last theme name locally so we can update this.props.theme
this.setState({ last_theme: themeconf.theme });
// Check if we have a theme "powered-by" logo image
const logo_secondary_path = await imageWithName(
ThemeFolder(themeconf.theme),
"logo-login-secondary"
);
if (logo_secondary_path !== null) {
// Found a cached logo image
logoSecondaryImage = ThemeImage(
themeconf.theme,
"logo-login-secondary.png"
);
}
}
// Set the final value of secondary image (will be null if no secondary image)
this.setState({ logoSecondaryImage });
} | [
"function getImagesByTheme() {\n const themes = ['dogs', 'cats', 'cars', 'motorcycles', 'beach', 'california', 'new-york'];\n const randTheme = Math.floor(Math.random() * themes.length);\n return getImageData(themes[randTheme]);\n}",
"function initBgImages() {\n if ($('.has-background-image').length) {\n $(\".has-background-image\").each(function () {\n var bgImage = $(this).attr('data-background');\n if (bgImage !== undefined) {\n $(this).css('background-image', 'url(' + bgImage + ')');\n }\n }\n )\n }\n}",
"function fetchHighResolutionImages() {\n\n /**\n * After page is loaded, check the viewport size and display density.\n * If the window size is bigger than 750px, load the medium size images.\n * If window size is bigger than 750px and retina, or bigger than 1500px,\n * load the large size images.\n */\n\n var viewpirtWidth = $(window).width();\n var mediumImageSourceAttribute = 'data-image-medium-src';\n var largeImageSourceAttribue = 'data-image-large-src';\n var isHighDensity = (window.devicePixelRatio >= 2) ? true : false;\n\n if (viewpirtWidth > 750) {\n if (isHighDensity && viewpirtWidth > 1500) {\n $('img').each(function() {\n var img = $(this);\n img.attr('src', img.attr(largeImageSourceAttribue));\n });\n } else {\n $('img').each(function() {\n var img = $(this);\n img.attr('src', img.attr(mediumImageSourceAttribute));\n });\n }\n };\n\n}",
"function setBannerImage() {\n if (!document.styleSheets) return;\n if (AVAILABLE_BANNERS < 2) return;\n\n var imageIndex = bannerImageIndex == null ? 1 :\n parseInt(bannerImageIndex);\n if (imageIndex < 0 || imageIndex > AVAILABLE_BANNERS)\n imageIndex = 1;\n\n var rules = new Array();\n if (document.styleSheets[STYLESHEET_INDEX].cssRules)\n rules = document.styleSheets[STYLESHEET_INDEX].cssRules;\n else\n rules = document.styleSheets[STYLESHEET_INDEX].rules;\n rules[0].style.backgroundImage =\n \"url(http://visualvm.java.net/images/main_background_\" + imageIndex + \".jpg)\";\n\n setCookie(BANNER_IMAGE_INDEX, ++imageIndex + '');\n}",
"function overwriteLegalImage(region, locale) {\n\tif (location.pathname == '/sc2/' + region + '/buy-now/digital-deluxe' || location.pathname == '/sc2/' + region + '/buy-now/collectors-edition') {\n\t\t$('.legal-image').attr('src', '/sc2/static/local-common/images/legal/'+ locale + '/sc2-hots.png');\t\t\n\t}\n}",
"function preLoadImages() {\n var args_len = arguments.length;\n for (var i = args_len; i--;) {\n var cacheImage = document.createElement('img');\n cacheImage.src = arguments[i];\n __cache.push(cacheImage);\n }\n }",
"function get_background_image()\n{\n\t//Get bg image\n \t$('#instagram-feed .slick-active:not(.loaded)').each(function()\n \t{\n\t var $bg = $(this).attr(\"data-background\");\n\t \t\n\t $(this).css('background-image','url(' + $bg + ')').addClass(\"loaded\");\t \n \t});\t\n}",
"function generateThemeThumb (themeSrc, pageObj)\n{\n\t/* don't do a directory list if one already exists */\n\tif (!gCENTRAL_THUMB_DIR_LIST)\n\t\tgCENTRAL_THUMB_DIR_LIST = doActionBDO (\"DATA_DIRECTORYLIST\", \"ObjectName\", \"Central\",\n\t\t\t\t\t\t\t\t\t\t\t \"SubDirectoryPath\", gIMAGES_DIR + \"thumbs/*.*\");\n\t\t\t\t\t\t\t\t\t\t\t\t\n\tvar labels = gCENTRAL_THUMB_DIR_LIST.GetLabels();\n\t\n\tif (!pageObj)\n\t{\n\t\tvar basePage = generateSEObjects (gBASE_PAGE);\n\t\tpageObj = basePage.pageObjArray[gBASE_PAGE];\n\t}\n\t\n\tvar leftWidth = (isNaN (pageObj.layoutObjArray.left.width) ? 0 : parseInt (pageObj.layoutObjArray.left.width));\n\tvar topHeight = (isNaN (pageObj.layoutObjArray.top.height) ? 0 : parseInt (pageObj.layoutObjArray.top.height));\n\tvar themeID = \"t_\";\n\tif (leftWidth <= 0 && topHeight <= 0)\n\t\tthemeID = \"tf_\";\n\telse if (leftWidth <= 0 && topHeight > 0)\n\t\tthemeID = \"tt_\";\n\telse if (leftWidth > 0 && topHeight <= 0)\n\t\tthemeID = \"tl_\";\n\t\n\tvar bFound = false;\n\tvar curTheme = themeID + themeSrc.substring (3, themeSrc.lastIndexOf (\".\")) + \".gif\";\n\tvar curThemeJpg = themeID + themeSrc.substring (3, themeSrc.lastIndexOf (\".\")) + \".jpg\";\n\tfor (var n = 0; n < labels.length && !bFound; n++)\n\t{\n\t\tif (gCENTRAL_THUMB_DIR_LIST[labels[n]] == curTheme)\n\t\t\tbFound = true;\n\t\telse if (gCENTRAL_THUMB_DIR_LIST[labels[n]] == curThemeJpg)\n\t\t{\n\t\t\tbFound = true;\n\t\t\tcurTheme = curThemeJpg;\n\t\t}\n\t}\n\tif (bFound)\n\t\treturn (\"<img src='\"+gCOMMON_URL + gWEB_ALIAS_IMAGES + \"/thumbs/\"+curTheme+\"'>\");\n\telse\n\t\treturn (generateThemeTableHTML (themeSrc, pageObj, ''));\n}",
"function preload(){\n\thelicopterIMG=loadImage(\"helicopter.png\")\n\tpackageIMG=loadImage(\"package.png\")\n}",
"function init() {\n var img = new Image();\n img.name = url;\n img.onload = setDimensions;\n img.src = url;\n }",
"function ReLoadImages() {\n $('img[data-lazysrc]').each(function() {\n $(this).attr('src', $(this).attr('data-lazysrc'));\n });\n}",
"function load_hearth_image() {\n var hearth = new Image();\n hearth.src = 'assets/img/hearth.png';\n return hearth;\n }",
"function lazyLoadImages(){\n\t\tvar wrappers = document.querySelector('#image_container');\n\t\tvar imgLoad = imagesLoaded( wrappers );\n\t\tfunction onAlways( instance ) {\n\t\t\t//This should only happen once all of the images have finished being loaded\n\t\t\tconsole.log(\"All images loaded\");\n\t\t\tcollage();\n\t\t\t$('.Collage').collageCaption();\n\t\t}\n\t\timgLoad.on( 'always', onAlways );\n\t}",
"static imageSrcSetUrlForRestaurant(restaurant) {\r\n return (`/img2/${restaurant.id}` + `-300_small.webp 300w, ` + `/img/${restaurant.id}` + `.webp 600w`);\r\n }",
"function loadInitial() {\n var nameContainer = $('#list-recent-title');\n var dateContainer = $('#list-recent-time');\n var imageContainer = $('#list-recent-image');\n\n var vis = visuals[0];\n var id = vis.id;\n var name = vis.name;\n var image = vis.imageall;\n var datecreated = vis.datecreated;\n\n firstImage = name;\n selectedImage = firstImage;\n\n nameContainer.html(name);\n dateContainer.html(datecreated);\n imageContainer.attr('src', 'assets/vis/' + image);\n}",
"function generateDefaultShibeImgs() {\n const shibeImg = document.getElementsByClassName(\"img-bk\")\n\n for(let i = 0; i < shibeImg.length; i++) {\n shibeImg[i].style.backgroundImage = `url(${shibeImgs[Math.floor(\n Math.random() * shibeImgs.length)]}\n )`\n }\n}",
"function preload() {\n\tkernelImg = loadImage(\"assets/kernel.png\");\n\tpopcornImg = loadImage(\"assets/popcorn.png\");\n\tburntImg = loadImage(\"assets/burnt.png\");\n}",
"function load_planets_image() {\n planets_image.source = new Image();\n planets_image.source.src = 'assets/img/planets.png';\n planets_image.source.onload = function() {\n planets_image.loaded = true;\n };\n }",
"getDefaultImage() {\n return this.icon_.get(this.getBaseSize());\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET Endpoint to retrieve a blocks by address, url: '/api/stars/address:address' | getBlocksByAddress() {
this.app.get('/stars/address::address', async (req, res) => {
const { address } = req.params;
// ensure address is valid
if (checkAddress(address)) {
try {
// search through blockchain, add any blocks with matching address to total.
const chainData = await this.chain.getFormattedData();
const blocks = chainData.reduce((total, block) =>
(block && block.body && block.body.address === address)
? [...total, block]
: total,
[]
);
// blocks with address were found
if (blocks.length > 0) {
const decodedBlocks = blocks.map(block => decryptStarStory(block));
return res.json(decodedBlocks);
}
throw new Error('No blocks found');
} catch (error) {
// no blocks were found
return res.json({
status: false,
message: `Error: Blockchain doesn't have any blocks with address of ${address}.`
});
}
}
// address is junk or missing
return res.json(INVALID_REQUEST);
});
} | [
"getBlockByAddress() {\n this.server.route({\n method: 'GET',\n path: '/stars/address:{address}',\n handler: (request, h) => {\n return this.blockchain.getAllBlocksForAddress(request.params.address).then((blocks) => {\n blocks.forEach((block) => {\n block.body.star.storyDecoded = new Buffer(block.body.star.story, 'hex').toString('ascii');\n })\n return blocks;\n })\n .catch((err) => {\n throw Boom.badRequest(err);\n });\n }\n });\n }",
"getStarBlockByHash() {\n this.app.get(\"/stars/hash::index\", (req, res) => {\n let hash = req.params.index;\n blockchain.getBlockByHash(hash).then((block) => {\n res.status(200).send(block);\n }).catch(() => {\n res.status(404).send({ error: { message: 'Block #' + index + ' not found' } });\n });\n });\n }",
"async searchBlockchainWalletAddress() {\n\n this.app.get(\"/stars/address::address\", async (req, res) => {\n\n\n try {\n \n console.log(\"Address Block Hit\");\n let blockchain = new Blockchain();\n let val = req.params.address;\n\n if(val == \"\" || val == null) {\n return res.send({\"Error\": \"stars address cannot be empty\"});\n }\n\n console.log(\"HIt\",val);\n let myBlocks = await blockchain.getBlockByWalletAddressAsync(val);\n \n if(myBlocks instanceof Error) {\n res.send({\"Error\": \"Wallet Address not found in database\"});\n } else {\n res.send(myBlocks);\n } \n\n } catch (error) {\n return res.send({\"Error\": \"There is an error in the Request\"});\n }\n\n }); \n }",
"getBlockByHash() {\n this.server.route({\n method: 'GET',\n path: '/stars/hash:{hash}',\n handler: (request, h) => {\n return this.blockchain.getBlockByHash(request.params.hash).then((block) => {\n if (block == null) {\n throw Boom.badRequest('No block found for hash');\n }\n block.body.star.storyDecoded = new Buffer(block.body.star.story, 'hex').toString('ascii');\n return block;\n })\n .catch((err) => {\n throw Boom.badRequest(err);\n });\n }\n });\n }",
"getStarsByWalletAddress(address) {\n let self = this;\n let stars = [];\n return new Promise(async (resolve, reject) => {\n for (var i = 1; i < self.chain.length; i++) {\n let data;\n await self.chain[i]\n .getBData()\n .then((blockData) => {\n data = blockData;\n })\n .catch((err) => {\n console.log(err);\n console.log(\"The block data is not retrievable\");\n });\n if (data.address === address) {\n let starData = {\n owner: address,\n star: data.star,\n };\n stars.push(starData);\n }\n }\n if (stars.length > 0) {\n resolve(stars);\n } else {\n reject(\"Address doesn't have any stars registered\");\n }\n });\n }",
"getBlockByHash() {\n this.app.get(\"/stars/hash::hash\", async (req, res) => {\n let hash = req.params.hash;\n console.log(`GET /stars/hash:${hash}`);\n let block = await this.blockChain.getBlockByHash(hash);\n if (undefined === block || null === block) {\n res.status(404)\n res.send(`Error Block #${hash} not found`);\n } else {\n block = this.decodeStory(block); // block.body.star.storyDecoded = hex2ascii(block.body.star.story);\n res.json(block);\n }\n });\n }",
"async getBlockByAddress(addr) {\n //retrieve data from levelDB\n const block = await l_DB.getBlockByAddress(addr)\n return block;\n }",
"getAllStarsOfWallet(walletAdress) {\n try {\n let stars = this.chain.starsOfWalletAddress(walletAdress);\n return stars;\n } catch (e) {\n console.log(\"getAllStarsOfWallet ===> \", e.stack);\n }\n }",
"function getBalance(address) {\r\n apiwaves.getAssets(address).then(onGetAssetsSuccess, onError); //Get Asset Balance\r\n }",
"getAddressByUserIdAddressId(userId, addressId) {\n return http.get(`/address/${userId}/${addressId}`);\n }",
"async function getBusLocations(){\n\tvar url = 'https://api-v3.mbta.com/vehicles?sort=direction_id&include=route&filter%5Broute%5D=1&api_key=5480903a65764e129cf91c942b08de49';\t\n\tvar response = await fetch(url);\n\tvar json = await response.json();\n\treturn json.data;\n}",
"getAssetsOwnedByAddress(address) {\n return rxjs_1.of(\"mosaic/owned?address=\" + address.plain())\n .pipe(operators_1.flatMap((url) => requestPromise.get(this.nextNode() + url, { json: true })), operators_1.retryWhen(this.replyWhenRequestError), operators_1.map((mosaicsData) => {\n return mosaicsData.data.map((mosaicDTO) => {\n return Asset_1.Asset.createFromMosaicDTO(mosaicDTO);\n });\n }));\n }",
"function loadBlockExplorerData(node,publicKey) {\n\tvar xhr = new XMLHttpRequest();\n\txhr.onreadystatechange = function() {\n\t\tif (xhr.readyState == 4) {\n\t\t\tvar status = xhr.status;\n\t\t\tif (status == 200) {\n\t\t\t\tvar myBalance = xhr.response;\n\t\t\t\tloadBlockExplorerReceived(node,publicKey,myBalance);\n\t\t\t} else {\n\t\t\t\tnode.innerHTML = '<a href=\"https://blockexplorer.com/address/'+ publicKey +'\" target=\"_blank\">BlockExplorer</a> not available.';\n\t\t\t\tconsole.log('BlockExplorer not available. Error '+status+'.');\n\t\t\t}\n\t\t}\n\t}\n\tvar url = 'https://blockexplorer.com/q/addressbalance/'+publicKey;\n\t\n\txhr.open(\"GET\", url, true);\n\txhr.send();\n}",
"async balanceOf(address) {\n await this.getContract()\n return await this.contract.methods.balanceOf(address).call()\n }",
"async function ipfs_get(block) {\n const hash = block.data.data\n const url = `${config.ipfsConfig.protocol}://${config.ipfsConfig.host}:${config.ipfsConfig.port}/api/v0/cat`\n const params = {\n arg: hash,\n }\n \n try {\n /* arraybuffer to prevent automatic parsing of response data as JSON */\n const res = await axios.get(url, {params, responseType: 'arraybuffer'})\n return res.data.toString()\n } catch(e) {\n console.log(`Error in block ${JSON.stringify(block)}: ${e}`)\n }\n}",
"async function getReps(lat, lon) {\n const url = baseURL + 'representatives';\n const q = { point: `${lat},${lon}` };\n const response = await request({ url: url, qs: q });\n try {\n const json = JSON.parse(response);\n if (json.objects.length === 0) {\n throw Error(`No representatives found for address ${lat},${lon}`);\n }\n return json;\n } catch (e) {\n console.log(e);\n console.log(response);\n throw e;\n }\n}",
"function getReceived(btcAddress) {\n var response = UrlFetchApp.fetch('http://blockchain.info/address/' + btcAddress + '?format=json');\n var json = response.getContentText();\n var data = JSON.parse(json);\n return data.total_received * Math.pow(10,-8);\n}",
"async latestDsBlock() {\n return await this.baseJsonRpcRequest('GetLatestDsBlock');\n }",
"function getDashBalance(dashAddress) {\n var response = UrlFetchApp.fetch('http://explorer.darkcoin.io/chain/Dash/q/addressbalance/' + dashAddress);\n var json = response.getContentText();\n var data = JSON.parse(json);\n return data;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Same as "whereNull", but for the pivot table only | whereNullPivot(key) {
this.pivotHelpers.whereNullPivot('and', key);
return this;
} | [
"get isPivotOnlyQuery() {\n return this.pivotQuery;\n }",
"function filterOutNulls(response) {\n let dataTable = response.getDataTable();\n\n let filtered = [];\n for (const i in dataTable.wg) {\n // remove nulls and objects with null as their value\n filtered[i] = dataTable.wg[i].c.filter(function (value, index, arr) {\n const kept = value !== null && value.v !== null;\n return kept;\n });\n\n // remove empty arrays\n if (!filtered[i].length) {\n filtered.splice(i, 1);\n break;\n }\n }\n\n dataTable.wg = filtered;\n return dataTable;\n}",
"_handleWhereNull(field, isNull = true, conj = \"and\") {\r\n if (this._where) this._where += ` ${conj} `;\r\n this._where += this.backquote(field) + \" is \" +\r\n (isNull ? \"\" : \"not \") + \"null\";\r\n return this;\r\n }",
"visitRespect_or_ignore_nulls(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"_getAreaZero() {\n let newArr = [];\n this.area.map(el => {\n newArr.push(...el)\n });\n\n return newArr.some(el => el === null);\n }",
"visitPivot_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function testEval_In_WithNull() {\n var table = schema.table('tableA');\n var sampleRows = getSampleRows(6);\n sampleRows.push(table.createRow({\n 'id': 'sampleId6', 'name': null}));\n var inValues = ['sampleName0', 'sampleName2', 'sampleName4'];\n checkEval_In(sampleRows, inValues, inValues, false);\n checkEval_In(sampleRows, inValues.concat(null), inValues, false);\n}",
"function removeNull(data){\n data.forEach(data => {\n for (let key in data) {\n if (data[key] == '#NULL!') {\n delete data[key];\n }\n }\n });\n return data;\n}",
"static isNull(value) { return value === null; }",
"addWhereConstraints() {\n const queryAction = this.queryAction();\n /**\n * Eager query contraints\n */\n if (Array.isArray(this.parent)) {\n this.wrapExisting().whereInPivot(this.relation.pivotForeignKey, utils_1.unique(this.parent.map((model) => {\n return utils_1.getValue(model, this.relation.localKey, this.relation, queryAction);\n })));\n return;\n }\n /**\n * Query constraints\n */\n const value = utils_1.getValue(this.parent, this.relation.localKey, this.relation, queryAction);\n this.wrapExisting().wherePivot(this.relation.pivotForeignKey, value);\n }",
"visitNull_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitDatatype_null_enable(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function null_1(i) /* (i : int) -> null<int> */ {\n return $null(maybe_7(i));\n}",
"function nullFields()\n{\n\treturn isEmpty(\"#myPattern\") || isEmpty(\"#frameRate\");\n}",
"function notNullish(value) {\n return value !== null && value !== undefined;\n}",
"isna() {\n const newData = this.values.map((value) => {\n if (isNaN(value) && typeof value != \"string\") {\n return true;\n } else {\n return false;\n }\n });\n const sf = new Series(newData,\n {\n index: this.index,\n dtypes: [\"boolean\"],\n config: this.config\n });\n return sf;\n }",
"function isNull(input){\n return input==null || \n input==\"\" || \n input<0 ||\n input=='NA' ||\n input=='na' ||\n input=='Na' ||\n input=='NaN' ||\n input=='none' ||\n input=='999'\n}",
"function isNull(user) {\n return user == null;\n}",
"function filterUndefined(obj) {\n if (Array.isArray(obj)) {\n return obj.filter(x => x !== undefined).map(x => filterUndefined(x));\n }\n if (typeof (obj) === 'object') {\n const ret = {};\n for (const [key, value] of Object.entries(obj)) {\n if (value === undefined) {\n continue;\n }\n ret[key] = filterUndefined(value);\n }\n return ret;\n }\n return obj;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visit a parse tree produced by PlSqlParserparameter_spec. | visitParameter_spec(ctx) {
return this.visitChildren(ctx);
} | [
"visitCompiler_parameters_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitType_elements_parameter(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function isParameter(node) {\n\t return node.kind() == \"Parameter\" && node.RAMLVersion() == \"RAML08\";\n\t}",
"visitParameter_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitC_parameters_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitOdci_parameters(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitXmlroot_param_standalone_part(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitProcedure_spec(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitLob_parameters(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function Parameter(parent, name, param, mval, bval) {\n this.getClass = function() { return \"Parameter\" };\n this.parent = parent;\n this.name = name;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// ime parametra v bazi \n this.param = param;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// stevilka parametra v bazi\n this.mval = parseInt(mval);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// oznaka za manjkajoco vrednost v bazi\n this.bval = (bval == null)? parseInt(mval) : parseInt(bval);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// vrednost parametra v baz zo. manjkajoca vrednost\n this.msr = isParamMeasured(this.parent.parent.postaje, this.parent.parent.parametri, this.param, this.parent.idmm, this.parent.datum); \t// ali se parameter meri\n this.edit = setEdit; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// ali se parameter lahko editira\t\n this.val = (this.bval != this.mval)? new Number(this.bval) : null;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// vrednost parametra\t\n this.toXml = param2xml;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// transformacija v xml element \t\t\t\t\t\t\t\t\t\t\t\t\n this.nval; \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// nova vrednost parametra\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n this.oval = this.val;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// stara vrednost parametra\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n this.isChanged = isValueChanged;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// ali se je vrednost spremenila\n this.nval2bval = nval2bvalParam;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// izracun vrednosti za vnos v bazo\n this.correct = correctParam;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// popravek parametra\t\t\n this.generateErrorsSearch = generateErrorsSearchParam;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// funkcije za izvajanje kontrol\n this.generateErrorsBehavior = generateErrorsBehaviorParam;\n this.setNewVal = setNewValueParam;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// dolocanje nove vrednosti\n this.setOldVal = setOldValueParam;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// dolocanje stare vrednosti\n}",
"function parse_StatementList(){\n\t\n\n\t\n\n\tvar tempDesc = tokenstreamCOPY[parseCounter][0]; //check desc of token\n\tvar tempType = tokenstreamCOPY[parseCounter][1]; //check type of token\n\n\tif (tempDesc == ' print' || tempType == 'identifier' || tempType == 'type' || tempDesc == ' while' || tempDesc == ' if' || tempDesc == '{' ){ //if next token is a statment\n\t\tdocument.getElementById(\"tree\").value += \"PARSER: parse_StatementList()\" + '\\n';\n\t\tCSTREE.addNode('StatementList', 'branch');\n\t\t\n\t\t\n\t\tparse_Statement(); \n\t\n\t\tparse_StatementList();\n\t\t\n\t\tCSTREE.endChildren();\n\t\n\t\t\n\t\t\n\t}\n\telse{\n\t\t\n\t\t\n\t\t//e production\n\t}\n\n\n\n\n\t\n\t\n}",
"visitType_procedure_spec(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitTypedargslist(ctx) {\r\n console.log(\"visitTypedargslist\");\r\n // TODO: support *args, **kwargs\r\n let length = ctx.getChildCount();\r\n let returnlist = [];\r\n let comma = [];\r\n let current = -1;\r\n if (ctx.STAR() === null && ctx.POWER() === null) {\r\n for (var i = 0; i < length; i++) {\r\n if (ctx.getChild(i).getText() === \",\") {\r\n comma.push(i);\r\n }\r\n }\r\n comma.push(length);\r\n for (var i = 0; i < comma.length; i++) {\r\n if (comma[i] - current === 2) {\r\n returnlist.push({\r\n type: \"Parameter\",\r\n name: this.visit(ctx.getChild(comma[i] - 1)),\r\n default: null,\r\n });\r\n current = current + 2;\r\n console.log(this.visit(ctx.getChild(comma[i] - 1)));\r\n } else {\r\n returnlist.push({\r\n type: \"Parameter\",\r\n name: this.visit(ctx.getChild(comma[i] - 3)),\r\n default: this.visit(ctx.getChild(comma[i] - 1)),\r\n });\r\n current = current + 4;\r\n }\r\n }\r\n } else {\r\n throw \"*args and **kwargs have not been implemented!\";\r\n }\r\n return returnlist;\r\n }",
"function ParameterSonTrajanje(parent, name, id, mval, bval) { \n Parameter.apply(this, [parent, name, id, mval, bval]);\n this.min = new Number(0);\n this.max = setMaxSonTrajanje;\n}",
"function ParameterKliStanjeTal(parent, name, id, mval, bval) {\n Parameter.apply(this, [parent, name, id, mval, bval]);\n this.values = [0,1,2,3,4,5,6,7,8,9];\n}",
"_processParams(params, isUpdate) {\n params = utils._flatten.apply(this, params);\n if (typeof params === \"undefined\") {\n params = [];\n }\n\n for (let param of params) {\n let type = typeof param;\n\n if (param === null) {\n // Do nothing\n }\n else if (type === \"number\" || type === \"string\") {\n this.contents.push({type: JstElementType.TEXTNODE, value: param});\n }\n else if (type === \"boolean\") {\n this.contents.push({type: JstElementType.TEXTNODE, value: param.toString()});\n }\n else if (param instanceof JstComponent) {\n\n // Put the JstComponent into this element's contents\n this.contents.push({type: JstElementType.JST_COMPONENT, value: param});\n\n // Let the JstComponent render itself\n param.refresh({isParentUpdate: true});\n \n }\n else if (param instanceof JstElement) {\n param.add();\n this.contents.push({type: JstElementType.JST_ELEMENT, value: param});\n }\n else if (typeof HTMLElement !== 'undefined' && param instanceof HTMLElement) {\n let jstEl = new JstElement(param);\n jstEl.add();\n this.contents.push({type: JstElementType.JST_ELEMENT, value: jstEl});\n }\n else if (type === \"object\") {\n for (let name of Object.keys(param)) {\n if (typeof(param[name]) === \"undefined\") {\n param[name] = \"\";\n }\n if (name === \"jstoptions\" && param.jstoptions instanceof Object) {\n this.opts = param.jstoptions;\n }\n else if (name === \"properties\" && param.properties instanceof Array) {\n for (let prop of param.properties) {\n this.props.push(prop);\n }\n }\n else if (name === \"events\" && typeof param.events === \"object\") {\n for (let event of Object.keys(param.events)) {\n if (param.events[event] instanceof Function) {\n this.events[event] = {listener: param.events[event]};\n }\n else {\n this.events[event] = param.events[event];\n }\n }\n }\n else if (name === \"ref\") {\n this.ref = param[name];\n this.attrs.ref = param[name];\n }\n else if (name === \"cn\") {\n // A bit of magic for the \"class\" attribute: cn -> class\n // We also will append to the class if there already is one\n if (this.attrs['class']) {\n this.attrs['class'] += \" \" + param[name];\n }\n else {\n this.attrs['class'] = param[name];\n }\n }\n else if (param[name] !== \"\"){\n this.attrs[name] = param[name];\n }\n }\n }\n else if (type === \"undefined\") {\n // skip\n }\n else if (param.toString) {\n this.contents.push({type: JstElementType.TEXTNODE, value: param.toString()});\n }\n else {\n console.warn(\"Unknown JstElement parameter type: \", type);\n }\n }\n }",
"visitModify_lob_parameters(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitXmlroot_param_version_part(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"get params(){\n\t\treturn Array.prototype.filter( this.children, function( el){ return el.tagName== \"param\" })\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given x, y coordinates of a cell, return an id. This id can both be used to index a hash, and as an CSS id | function id (x, y) {
return "cell-" + x + "-" + y;
} | [
"function toId(xPos, yPos) {\n\t return \"boulder_\" + xPos + \"_\" + yPos;\n}",
"function getCell(row, col) {\n return document.getElementById(`cell-${row}-${col}`);\n }",
"function toCoordinate(id_num) {\n // Math doesnn't work properly for last cell\n if (id_num === \"256\") {\n return [15, 15];\n }\n else {\n id_num = parseInt(id_num);\n var x = Math.floor((id_num-1)/16);\n var y = id_num-(16*x);\n return [x, y-1];\n }\n}",
"GetCellIndexAt(x, y) {\n let x_idx = parseInt(x / this.cell_size);\n let y_idx = parseInt(y / this.cell_size);\n if (x_idx >= 0 && x_idx < this.num_cells_in_row && y_idx >= 0 &&\n y_idx < this.num_cells_in_row) {\n return y_idx * this.num_cells_in_row + x_idx;\n } else {\n return null;\n }\n }",
"showCellsId(G,ctx){\n\t\t\tconst cells = [...G.cells];\n\t\t\tfor (let i = 0; i < boardHeight; i++) {\n\t\t\t\tfor(let j=0;j<boardWidth;j++) {\n\t\t\t\t\tlet id = boardWidth * i + j;\n\t\t\t\t\tcells[id].setDisplay(id);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {...G,cells};\n\t\t}",
"function idPieces (ele, x)\r\n\t{\r\n\t\tvar row, column;\r\n\r\n\t\t//calculates the row and column based on each puzzle pieces' position\r\n\t\tif (x <= 3)\r\n\t\t{\r\n\t\t\trow = x;\r\n\t\t\tcolumn = 0;\r\n\t\t}\r\n\t\telse if (x <= 7)\r\n\t\t{\r\n\t\t\trow = x - 4;\r\n\t\t\tcolumn = 1;\r\n\t\t}\r\n\t\telse if (x <= 11)\r\n\t\t{\r\n\t\t\trow = x - 8;\r\n\t\t\tcolumn = 2;\r\n\t\t}\r\n\t\telse if (x <= 14)\r\n\t\t{\r\n\t\t\trow = x - 12;\r\n\t\t\tcolumn = 3;\r\n\t\t}\r\n\r\n\t\tele.setAttribute(\"id\", row + \" \" + column); //sets the puzzle piece's id based on its position\r\n\t}",
"getCellXY(cellEl) {\n const rowEl = cellEl.parentElement;\n const rowIndex = Array.from(rowEl.parentElement.children).indexOf(rowEl);\n const cellIndex = Array.from(rowEl.children).indexOf(cellEl);\n return { x: cellIndex, y: rowIndex };\n }",
"function getTileIndex(x, y) {\n return y * 12 + x;\n}",
"function findCellByCoord(cellCoordinates) {\n if(cellCoordinates) {\n let my_cells = document.getElementsByClassName('game-cell');\n for (let cell of my_cells) {\n let cellRow = cell.getAttribute('data-coordinate-x');\n let cellCol = cell.getAttribute('data-coordinate-y');\n if (cellCoordinates[1] === +cellRow && cellCoordinates[0] === +cellCol) {\n return cell;\n }\n }\n }\n}",
"function findGridCell(x, y, grid) {\n return (\n Math.floor(Math.min(y / grid.spacing, grid.cellsY - 1)) * grid.cellsX +\n Math.floor(Math.min(x / grid.spacing, grid.cellsX - 1))\n );\n}",
"function getCellAsDomElement(coord) {\n // you can change # to . if you use class selector\n var elCell = document.querySelector(`#cell${coord.i}-${coord.j}`);\n return elCell;\n}",
"function abs2index(x, y) {\n return pos2index(x - canvasX[ci], y - canvasY[ci], g_cal_params.grid_w, g_cal_params.cell_h);\n}",
"function getCoordsFromId(elem_id)\n{\t\n\tvar delimiter_pos = elem_id.indexOf('_');\n\tvar elem_y = parseInt(elem_id.substring(0, delimiter_pos), 10);\n\tvar elem_x = parseInt(elem_id.substring(delimiter_pos + 1), 10);\n\tvar coords = new Array(elem_y, elem_x);\n\treturn coords;\n}",
"function placeInTable(y, x) {\n // TODO: make a div and insert into correct table cell \n const spot = document.getElementById(`${y}-${x}`);\n spot.append(createPiece(y, x));\n}",
"tileToRemoteId(tile) {\n // tile contains [zoomLevel, xPos, yPos]\n return `${tile.join('.')}`;\n }",
"function index(x, y) {\n return x * gridSize + y;\n}",
"getColumnIndex(): number {\n const { row, cell } = this;\n const cells = row.nodes;\n\n return cells.findIndex(x => x === cell);\n }",
"posById(id){\n let slot = this._index[id];\n return slot ? slot[1] : -1\n }",
"tileToLocalId(tile) {\n // tile contains [zoomLevel, xPos, yPos]\n return `${tile.join('.')}`;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
createTagAppend function that creates an element on the page at a given location and appends that element then returns the created the element. | function createTagAppend(loc, tag, id='', el_class='', text='') {
var element = document.createElement(tag);
if (id != '') {
element.setAttribute('id', id);
}
if (el_class != '') {
element.setAttribute('class', el_class);
}
if (text != '') {
element.innerText = text;
}
loc.append(element);
return element;
} | [
"function createElement(loc, tag, id='', el_class='', text='') {\n var element = document.createElement(tag);\n if (id != '') {\n element.setAttribute('id', id);\n }\n if (el_class != '') {\n element.setAttribute('class', el_class);\n }\n if (text != '') {\n element.innerText = text;\n }\n loc.prepend(element);\n return element;\n}",
"function createTag(loc, tag, id='', el_class='', text='') {\n var element = document.createElement(tag);\n if (id != '') {\n element.setAttribute('id', id);\n }\n if (el_class != '') {\n element.setAttribute('class', el_class);\n }\n if (text != '') {\n element.innerText = text;\n }\n loc.prepend(element);\n return element;\n}",
"function createNode(location, tag, ListOfAttributs = {}) {\n \n let node = document.querySelector(location);\n let createdTag = document.createElement(tag);\n\n // Get the list of attributs and creates tag(s) in fonction of it\n for(const [key, value] of Object.entries(ListOfAttributs)){\n createdTag[key] = value;\n }\n node.appendChild(createdTag);\n}",
"function addTag(input) {\n if (!input) {\n return;\n }\n var tag = createTag(input);\n tagOutput.appendChild(tag);\n}",
"function createSpan(){\n return document.createElement('span');\n}",
"function createTag(content) {\n var tag = document.createElement(\"div\");\n tag.setAttribute(\"class\", \"tag\");\n tag.innerText = content;\n return tag;\n}",
"function addElement(doc, parent, name, text) {\n\tvar e = doc.createElement(name);\n\tvar txt = doc.createTextNode(text);\n\t\n\te.appendChild(txt);\n\tparent.appendChild(e);\n\t\n\treturn e;\n}",
"function createSearchElement() {\n appendSearchElementToDOM();\n addDynamicSearchFunctionality();\n}",
"function crappend(type,par){\r\n var child = document.createElement(type);\t\t\t\t// Create element of given type.\r\n par.appendChild(child);\t\t\t\t\t\t\t\t// Append it to given parent.\r\n return child;\r\n}",
"function addToDOM(element, someHTML) {\n var div = document.createElement('div');\n div.id = \"b\";\n div.innerHTML = someHTML;\n element.appendChild(div);\n}",
"function addLocationName(location) {\n let header = createHeader(\"Location Name\")\n let b = document.createElement(\"p\")\n b.innerHTML += location.name\n weatherDiv.append(header,b)\n}",
"function createTag(tag) {\n var btn = $('<button>').text(tag);\n btn.attr(\"value\", tag);\n btn.attr(\"class\", \"tag\");\n\n $(\"#tagsDiv\").append(btn);\n}",
"function elt(type) {\n var node = document.createElement(type);\n for (var i = 1; i < arguments.length; i++) {\n var child = arguments[i];\n if (typeof child == \"string\")\n child = document.createTextNode(child);\n node.appendChild(child);\n }\n return node;\n}",
"function buildNode(id, name, parent){\n\t\tvar element = $(\"<li><a>\" + name + \"</i></a></li>\");\n\t\t\n\t\t$('a', element).attr('data-remote','true');\n\t\t$('a', element).attr('data-tagname', name);\n\t\t$('a', element).attr('href', window.location.href + '/?tag=' + name);\n\t\tparent.append(element); \n\t\treturn element;\n\t}",
"create_dom_url_element(arg_dom_element, arg_tag, arg_id, arg_url, arg_type)\n\t{\n\t\t// SEARCH DEVAPT BOOTSTRAP SCRIPT TAG\n\t\tconst devapt_bootstrap_element = document.getElementById('js-devapt-bootstrap')\n\t\tconst has_bootstrap_element = devapt_bootstrap_element ? arg_dom_element == devapt_bootstrap_element.parentNode : false\n\n\t\tlet e = document.getElementById(arg_id)\n\t\tif (e)\n\t\t{\n\t\t\tif (e.getAttribute('src') == arg_url)\n\t\t\t{\n\t\t\t\twindow.devapt().monitor_asset_loading(arg_tag, arg_id, arg_url, e, true)\n\t\t\t\treturn\n\t\t\t}\n\t\t\te.parentNode.removeChild(e)\n\t\t}\n\t\t\n\t\te = document.createElement(arg_tag)\n\t\te.setAttribute('id', arg_id)\n\t\te.setAttribute('src', arg_url)\n\t\te.setAttribute('type', arg_type)\n\t\t// e.setAttribute('async', 'false')\n\n\t\twindow.devapt().monitor_asset_loading(arg_tag, arg_id, arg_url, e, false)\n\n\t\tif (has_bootstrap_element)\n\t\t{\n\t\t\targ_dom_element.insertBefore(e, devapt_bootstrap_element)\n\n\t\t\treturn\n\t\t}\n\t\targ_dom_element.appendChild(e)\n\t}",
"createHTMLElement(parent){\n let htmlElement=document.createElement(this.htmlTagName);\n this.parent=parent;\n this.parent.appendChild(htmlElement);\n this.htmlElementId=getUniqueId(parent,this.htmlTagName);\n htmlElement.id=this.htmlElementId;\n this.applyStyleToElement();\n widgets[this.htmlElementId]=this;\n }",
"static attach(element) {\n return new DomBuilder(element);\n }",
"function addElement(prevElement, element, attribute, attrValue) {\n if (prevElement != \"\") {\n prevElement.after(element);\n if (attribute != \"\" || attrValue != \"\") {\n let attr = document.createAttribute(attribute);\n attr.value = attrValue;\n element.setAttributeNode(attr);\n }\n } else {\n document.querySelector(\"body\").appendChild(element);\n if (attribute != \"\" || attrValue != \"\") {\n let attr = document.createAttribute(attribute);\n attr.value = attrValue;\n element.setAttributeNode(attr);\n }\n }\n}",
"function createArtistHTML (artist) {\r\n const cr = document.getElementById('artist-container');\r\n // cr.append(fillArtistHTML(artist));\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that isKeyRangeCompatible() returns false when the predicate involves 'null' values. | function testIsKeyRangeCompatible_False() {
var table = schema.table('tableA');
var p = new lf.pred.ValuePredicate(
table['id'], null, lf.eval.Type.EQ);
assertFalse(p.isKeyRangeCompatible());
} | [
"static evalLowerRangeIsEmpty(dict) {\n return libVal.evalIsEmpty(dict.LowerRange);\n }",
"static evalUpperRangeIsEmpty(dict) {\n return libVal.evalIsEmpty(dict.UpperRange);\n }",
"function notNullish(value) {\n return value !== null && value !== undefined;\n}",
"whereNullPivot(key) {\n this.pivotHelpers.whereNullPivot('and', key);\n return this;\n }",
"static is_subset(map_a, map_b){\n for( let key of map_b.keys()){\n if(!map_a.has(key))\n return false\n }\n return true\n }",
"function intervalHasOldInternalDrawables( interval, oldFirstStitchDrawable, oldLastStitchDrawable ) {\n if ( interval.drawableBefore ) {\n return interval.drawableBefore.oldNextDrawable !== interval.drawableAfter; // OK for after to be null\n }\n else if ( interval.drawableAfter ) {\n return interval.drawableAfter.oldPreviousDrawable !== interval.drawableBefore; // OK for before to be null\n }\n else {\n return oldFirstStitchDrawable !== null;\n }\n}",
"function testEval_In_WithNull() {\n var table = schema.table('tableA');\n var sampleRows = getSampleRows(6);\n sampleRows.push(table.createRow({\n 'id': 'sampleId6', 'name': null}));\n var inValues = ['sampleName0', 'sampleName2', 'sampleName4'];\n checkEval_In(sampleRows, inValues, inValues, false);\n checkEval_In(sampleRows, inValues.concat(null), inValues, false);\n}",
"testRangeOverlap() {\n assertEquals(RangeOverlap.LEFT, rangeOverlap(1, 2, 3, 4));\n assertEquals(RangeOverlap.LEFT, rangeOverlap(2, 3, 3, 4));\n assertEquals(RangeOverlap.LEFT_IN, rangeOverlap(1, 3, 2, 4));\n assertEquals(RangeOverlap.IN, rangeOverlap(1, 3, 1, 4));\n assertEquals(RangeOverlap.IN, rangeOverlap(2, 3, 1, 4));\n assertEquals(RangeOverlap.IN, rangeOverlap(3, 4, 1, 4));\n assertEquals(RangeOverlap.RIGHT_IN, rangeOverlap(2, 4, 1, 3));\n assertEquals(RangeOverlap.RIGHT, rangeOverlap(2, 3, 1, 2));\n assertEquals(RangeOverlap.RIGHT, rangeOverlap(3, 4, 1, 2));\n assertEquals(RangeOverlap.CONTAINS, rangeOverlap(1, 4, 2, 3));\n }",
"_verifyNoOptionValueCollisions() {\n this.options.changes.pipe(startWith(this.options), takeUntil(this.destroyed)).subscribe(() => {\n var _a;\n const isEqual = (_a = this.compareWith) !== null && _a !== void 0 ? _a : Object.is;\n for (let i = 0; i < this.options.length; i++) {\n const option = this.options.get(i);\n let duplicate = null;\n for (let j = i + 1; j < this.options.length; j++) {\n const other = this.options.get(j);\n if (isEqual(option.value, other.value)) {\n duplicate = other;\n break;\n }\n }\n if (duplicate) {\n // TODO(mmalerba): Link to docs about this.\n if (this.compareWith) {\n console.warn(`Found multiple CdkOption representing the same value under the given compareWith function`, {\n option1: option.element,\n option2: duplicate.element,\n compareWith: this.compareWith,\n });\n }\n else {\n console.warn(`Found multiple CdkOption with the same value`, {\n option1: option.element,\n option2: duplicate.element,\n });\n }\n return;\n }\n }\n });\n }",
"function ensureVisibleEventRange(range) {\n\t\t\tvar allDay;\n\t\n\t\t\tif (!range.end) {\n\t\n\t\t\t\tallDay = range.allDay; // range might be more event-ish than we think\n\t\t\t\tif (allDay == null) {\n\t\t\t\t\tallDay = !range.start.hasTime();\n\t\t\t\t}\n\t\n\t\t\t\trange = $.extend({}, range); // make a copy, copying over other misc properties\n\t\t\t\trange.end = t.getDefaultEventEnd(allDay, range.start);\n\t\t\t}\n\t\t\treturn range;\n\t\t}",
"forEachInRange(t, e) {\n const n = this.data.getIteratorFrom(t[0]);\n\n for (; n.hasNext();) {\n const s = n.getNext();\n if (this.comparator(s.key, t[1]) >= 0) return;\n e(s.key);\n }\n }",
"function intervalHasNewInternalDrawables( interval, firstStitchDrawable, lastStitchDrawable ) {\n if ( interval.drawableBefore ) {\n return interval.drawableBefore.nextDrawable !== interval.drawableAfter; // OK for after to be null\n }\n else if ( interval.drawableAfter ) {\n return interval.drawableAfter.previousDrawable !== interval.drawableBefore; // OK for before to be null\n }\n else {\n return firstStitchDrawable !== null;\n }\n}",
"static isNull(value) { return value === null; }",
"function isHeatmapDataEqual(objA, objB) {\n var isEql = !emptyXOR(objA, objB);\n _.forEach(objA, function (xBucket, x) {\n if (objB[x]) {\n if (emptyXOR(xBucket.buckets, objB[x].buckets)) {\n isEql = false;\n return false;\n }\n _.forEach(xBucket.buckets, function (yBucket, y) {\n if (objB[x].buckets && objB[x].buckets[y]) {\n if (objB[x].buckets[y].values) {\n isEql = _.isEqual(_.sortBy(yBucket.values), _.sortBy(objB[x].buckets[y].values));\n if (!isEql) {\n return false;\n }\n else {\n return true;\n }\n }\n else {\n isEql = false;\n return false;\n }\n }\n else {\n isEql = false;\n return false;\n }\n });\n if (!isEql) {\n return false;\n }\n else {\n return true;\n }\n }\n else {\n isEql = false;\n return false;\n }\n });\n return isEql;\n}",
"function isCompatibleProperty(a, b) {\n\tif (a.blockStructure === b) {\n\t\treturn a.version > b.version ? 1 : 0\n\t}\n\tif (a.code === b.code && a.extendedType === b.extendedType) {\n\t\tvar sharedLength = Math.min(a.length, b.length)\n\t\tvar compatibility = 0\n\t\tfor (var i = 0; i < sharedLength; i++) {\n\t\t\tif (a[i].key !== b[i].key)\n\t\t\t\treturn -2\n\t\t\tvar childCompatibility = isCompatibleProperty(a[i], b[i])\n\t\t\tif (childCompatibility === -2)\n\t\t\t\treturn -2\n\t\t\tif (childCompatibility === -1) {\n\t\t\t\tif (compatibility === 1)\n\t\t\t\t\treturn -2\n\t\t\t\tcompatibility = -1\n\t\t\t}\n\t\t\tif (childCompatibility === 1) {\n\t\t\t\tif (compatibility === -1)\n\t\t\t\t\treturn -2\n\t\t\t\tcompatibility = 1\n\t\t\t}\n\t\t}\n\t\tvar sharedValuesLength = Math.min(a.values ? a.values.length : 0, b.values ? b.values.length : 0)\n\t\tfor (var i = 0; i < sharedValuesLength; i++) {\n\t\t\tif (a.values[i] !== b.values[i]) {\n\t\t\t\treturn -2\n\t\t\t}\n\t\t}\n\t\tif (a.length < b.length) {\n\t\t\tif (compatibility === 1) {\n\t\t\t\treturn -2\n\t\t\t}\n\t\t\tcompatibility = -1\n\t\t} else if (a.length < b.length) {\n\t\t\tif (compatibility === -1) {\n\t\t\t\treturn -2\n\t\t\t}\n\t\t\tcompatibility = 1\n\t\t}\n\t\t/*if (a.values.length < b.values.length) {\n\t\t\tif (compatibility === 1) {\n\t\t\t\treturn -2\n\t\t\t}\n\t\t\tcompatibility = -1\n\t\t} else if (a.values.length < b.values.length) {\n\t\t\tif (compatibility === -1) {\n\t\t\t\treturn -2\n\t\t\t}\n\t\t\tcompatibility = 1\n\t\t}*/\n\t\treturn compatibility\n\t} else {\n\t\treturn -2\n\t}\n}",
"function range_ques_(exception_info) /* (exception-info : exception-info) -> bool */ {\n return (exception_info._tag === _tag_Range);\n}",
"static isNoOpUpdate(data, mergeStrategy) {\n return (\n Object.keys(data).length === 0 && mergeStrategy === SHALLOW_MERGE_STRATEGY\n );\n }",
"static evalIsPreviousReadingEmpty(dict) {\n return libVal.evalIsEmpty(dict.PrevReadingValue);\n }",
"function hasProps(keys, x) {\n if(!isFoldable(keys)) {\n throw new TypeError(err)\n }\n\n if(isNil(x)) {\n return false\n }\n\n var result = keys.reduce(\n every(hasKey(x)),\n null\n )\n\n return result === null || result\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
const gpu = new GPU() Generate connection matrices from genes | function generateNetwork() {
globalInfo = getGlobalInfo()
let connections = new Array()
genome.forEach(g => {
let gene = g.split(".")
connections[gene[1]] = [...(connections[gene[1]] ?? []), {out: parseInt(gene[2]), weight: gene[3] / 100, enabled: !!parseInt(gene[4])}]
})
// Order of inputs and hidden nodes in mask/matrix
maskOrder = new Array()
connections.forEach((c, i) => {
if (c != null) maskOrder.push(i)
})
// Connection matrix
networkMatrix = Array.apply(null, Array(maskOrder.length)).map(
() => Array.apply(null, Array(maskOrder.length)).map(() => 0))
// Output matrix
outputMatrix = Array.apply(null, Array(maskOrder.length)).map(
() => Array.apply(null, Array(globalInfo.outputs)).map(() => 0))
// Populating the weights of the matrices
connections.forEach((n, i) => {
if (n != null) {
let inputI = maskOrder.indexOf(i) // Get the ith node's index in the mask
n.forEach(o => { // for each output of the node
if (o.enabled) { // If the connection is enabled
if (o.out < globalInfo.outputs) { // If an output node
outputMatrix[inputI][o.out] = o.weight
} else { // Otherwise must be a hidden node
networkMatrix[inputI][maskOrder.indexOf(o.out)] = o.weight
}
}
})
}
})
// Set mask
// All numbers represented by [real, imaginary]
mask = maskOrder.map((v) => {
if (v < (globalInfo.outputs + globalInfo.inputs)) return gpuMult ? [0, 0] : 0
return gpuMult ? [0, 1] : complex('i')
})
return {
networkMatrix,
outputMatrix,
maskOrder,
mask
}
} | [
"function WebGLNetworkDevice() {}",
"_setupFramebuffers(opts) {\n const {\n textures,\n framebuffers,\n maxMinFramebuffers,\n minFramebuffers,\n maxFramebuffers,\n meanTextures,\n equations\n } = this.state;\n const {weights} = opts;\n const {numCol, numRow} = opts;\n const framebufferSize = {width: numCol, height: numRow};\n for (const id in weights) {\n const {needMin, needMax, combineMaxMin, operation} = weights[id];\n textures[id] =\n weights[id].aggregationTexture ||\n textures[id] ||\n Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFloatTexture\"])(this.gl, {id: `${id}-texture`, width: numCol, height: numRow});\n textures[id].resize(framebufferSize);\n let texture = textures[id];\n if (operation === _aggregation_operation_utils__WEBPACK_IMPORTED_MODULE_3__[\"AGGREGATION_OPERATION\"].MEAN) {\n // For MEAN, we first aggregatet into a temp texture\n meanTextures[id] =\n meanTextures[id] ||\n Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFloatTexture\"])(this.gl, {id: `${id}-mean-texture`, width: numCol, height: numRow});\n meanTextures[id].resize(framebufferSize);\n texture = meanTextures[id];\n }\n if (framebuffers[id]) {\n framebuffers[id].attach({[_luma_gl_constants__WEBPACK_IMPORTED_MODULE_0___default.a.COLOR_ATTACHMENT0]: texture});\n } else {\n framebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-fb`,\n width: numCol,\n height: numRow,\n texture\n });\n }\n framebuffers[id].resize(framebufferSize);\n equations[id] = _gpu_grid_aggregator_constants__WEBPACK_IMPORTED_MODULE_2__[\"EQUATION_MAP\"][operation] || _gpu_grid_aggregator_constants__WEBPACK_IMPORTED_MODULE_2__[\"EQUATION_MAP\"].SUM;\n // For min/max framebuffers will use default size 1X1\n if (needMin || needMax) {\n if (needMin && needMax && combineMaxMin) {\n if (!maxMinFramebuffers[id]) {\n texture = weights[id].maxMinTexture || this._getMinMaxTexture(`${id}-maxMinTexture`);\n maxMinFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFramebuffer\"])(this.gl, {id: `${id}-maxMinFb`, texture});\n }\n } else {\n if (needMin) {\n if (!minFramebuffers[id]) {\n texture = weights[id].minTexture || this._getMinMaxTexture(`${id}-minTexture`);\n minFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-minFb`,\n texture\n });\n }\n }\n if (needMax) {\n if (!maxFramebuffers[id]) {\n texture = weights[id].maxTexture || this._getMinMaxTexture(`${id}-maxTexture`);\n maxFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_9__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-maxFb`,\n texture\n });\n }\n }\n }\n }\n }\n }",
"_setupFramebuffers(opts) {\n const {\n textures,\n framebuffers,\n maxMinFramebuffers,\n minFramebuffers,\n maxFramebuffers,\n meanTextures,\n equations\n } = this.state;\n const {\n weights\n } = opts;\n const {\n numCol,\n numRow\n } = opts;\n const framebufferSize = {\n width: numCol,\n height: numRow\n };\n\n for (const id in weights) {\n const {\n needMin,\n needMax,\n combineMaxMin,\n operation\n } = weights[id];\n textures[id] = weights[id].aggregationTexture || textures[id] || Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFloatTexture\"])(this.gl, {\n id: `${id}-texture`,\n width: numCol,\n height: numRow\n });\n textures[id].resize(framebufferSize);\n let texture = textures[id];\n\n if (operation === _aggregation_operation_utils__WEBPACK_IMPORTED_MODULE_5__[\"AGGREGATION_OPERATION\"].MEAN) {\n // For MEAN, we first aggregatet into a temp texture\n meanTextures[id] = meanTextures[id] || Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFloatTexture\"])(this.gl, {\n id: `${id}-mean-texture`,\n width: numCol,\n height: numRow\n });\n meanTextures[id].resize(framebufferSize);\n texture = meanTextures[id];\n }\n\n if (framebuffers[id]) {\n framebuffers[id].attach({\n [_luma_gl_constants__WEBPACK_IMPORTED_MODULE_0__[\"default\"].COLOR_ATTACHMENT0]: texture\n });\n } else {\n framebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-fb`,\n width: numCol,\n height: numRow,\n texture\n });\n }\n\n framebuffers[id].resize(framebufferSize);\n equations[id] = _gpu_grid_aggregator_constants__WEBPACK_IMPORTED_MODULE_4__[\"EQUATION_MAP\"][operation] || _gpu_grid_aggregator_constants__WEBPACK_IMPORTED_MODULE_4__[\"EQUATION_MAP\"].SUM; // For min/max framebuffers will use default size 1X1\n\n if (needMin || needMax) {\n if (needMin && needMax && combineMaxMin) {\n if (!maxMinFramebuffers[id]) {\n texture = weights[id].maxMinTexture || this._getMinMaxTexture(`${id}-maxMinTexture`);\n maxMinFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-maxMinFb`,\n texture\n });\n }\n } else {\n if (needMin) {\n if (!minFramebuffers[id]) {\n texture = weights[id].minTexture || this._getMinMaxTexture(`${id}-minTexture`);\n minFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-minFb`,\n texture\n });\n }\n }\n\n if (needMax) {\n if (!maxFramebuffers[id]) {\n texture = weights[id].maxTexture || this._getMinMaxTexture(`${id}-maxTexture`);\n maxFramebuffers[id] = Object(_resource_utils_js__WEBPACK_IMPORTED_MODULE_11__[\"getFramebuffer\"])(this.gl, {\n id: `${id}-maxFb`,\n texture\n });\n }\n }\n }\n }\n }\n }",
"function indcpaGenMatrix(seed, transposed, paramsK) {\r\n var a = new Array(3);\r\n var output = new Array(3 * 168);\r\n const xof = new SHAKE(128);\r\n var ctr = 0;\r\n var buflen, offset;\r\n for (var i = 0; i < paramsK; i++) {\r\n\r\n a[i] = polyvecNew(paramsK);\r\n var transpose = new Array(2);\r\n\r\n for (var j = 0; j < paramsK; j++) {\r\n\r\n // set if transposed matrix or not\r\n transpose[0] = j;\r\n transpose[1] = i;\r\n if (transposed) {\r\n transpose[0] = i;\r\n transpose[1] = j;\r\n }\r\n\r\n // obtain xof of (seed+i+j) or (seed+j+i) depending on above code\r\n // output is 504 bytes in length\r\n xof.reset();\r\n const buffer1 = Buffer.from(seed);\r\n const buffer2 = Buffer.from(transpose);\r\n xof.update(buffer1).update(buffer2);\r\n var buf_str = xof.digest({ buffer: Buffer.alloc(504), format: 'hex' });\r\n // convert hex string to array\r\n for (var n = 0; n < 504; n++) {\r\n output[n] = hexToDec(buf_str[2 * n] + buf_str[2 * n + 1]);\r\n }\r\n\r\n // run rejection sampling on the output from above\r\n outputlen = 3 * 168; // 504\r\n var result = new Array(2);\r\n result = indcpaRejUniform(output, outputlen);\r\n a[i][j] = result[0]; // the result here is an NTT-representation\r\n ctr = result[1]; // keeps track of index of output array from sampling function\r\n\r\n while (ctr < paramsN) { // if the polynomial hasnt been filled yet with mod q entries\r\n var outputn = output.slice(0, 168); // take first 168 bytes of byte array from xof\r\n var result1 = new Array(2);\r\n result1 = indcpaRejUniform(outputn, 168); // run sampling function again\r\n var missing = result1[0]; // here is additional mod q polynomial coefficients\r\n var ctrn = result1[1]; // how many coefficients were accepted and are in the output\r\n\r\n // starting at last position of output array from first sampling function until 256 is reached\r\n for (var k = ctr; k < paramsN - ctr; k++) {\r\n a[i][j][k] = missing[k - ctr]; // fill rest of array with the additional coefficients until full\r\n }\r\n ctr = ctr + ctrn; // update index\r\n }\r\n\r\n }\r\n }\r\n return a;\r\n}",
"constructor(inputs, hiddens, outputs) {\n\n this.inputs = inputs;\n this.hiddens = hiddens;\n this.outputs = outputs;\n\n //Creates a series of Matrices whose size is determined by the node counts above\n this.hiddensInputs = new Matrix(hiddens, inputs + 1);\n this.hiddenshiddens = new Matrix(hiddens, hiddens + 1);\n this.hiddensOutputs = new Matrix(outputs, hiddens + 1);\n\n\n //randomly populates each of the matrices with 1s and -1s\n this.hiddensInputs.randomise();\n this.hiddenshiddens.randomise();\n this.hiddensOutputs.randomise();\n\n }",
"function preproc()\n{\n // nodal coordinates as passed to opengl\n let coords = []\n // 3 corner nodes of a face to compute the face normal in the shader\n let As = []\n let Bs = []\n let Cs = []\n // triangles as passed to open gl\n let trias = []\n // displacement vector per vertex to displace said vertex\n let disps = []\n // global min/max to normalize result amplitudes\n let min = 0.0\n let max = 0.0\n // texture coordinates to properly map results per face\n let texcoords = []\n // all four corner nodes to compute the texture mapping\n let corners = []\n\n // for each quad\n for(let i = 0; i < quads.length; ++i) {\n let quad = quads[i]\n // triangulate\n trias.push(4 * i + 0, 4 * i + 1, 4 * i + 2, 4 * i + 0, 4 * i + 2, 4 * i + 3)\n // set texture coordinates\n texcoords.push(\n 0.0, 0.0,\n 0.0, 1.0,\n 1.0, 1.0,\n 1.0, 0.0\n )\n // push coordinates\n coords.push(\n nodes[3 * quad[0] + 0],\n nodes[3 * quad[0] + 1],\n nodes[3 * quad[0] + 2],\n nodes[3 * quad[1] + 0],\n nodes[3 * quad[1] + 1],\n nodes[3 * quad[1] + 2],\n nodes[3 * quad[2] + 0],\n nodes[3 * quad[2] + 1],\n nodes[3 * quad[2] + 2],\n nodes[3 * quad[3] + 0],\n nodes[3 * quad[3] + 1],\n nodes[3 * quad[3] + 2])\n // push A,B and C corner nodes to compute the face normal\n As.push(\n nodes[3 * quad[0] + 0] + results[3 * quad[0] + 0],\n nodes[3 * quad[0] + 1] + results[3 * quad[0] + 1],\n nodes[3 * quad[0] + 2] + results[3 * quad[0] + 2],\n nodes[3 * quad[0] + 0] + results[3 * quad[0] + 0],\n nodes[3 * quad[0] + 1] + results[3 * quad[0] + 1],\n nodes[3 * quad[0] + 2] + results[3 * quad[0] + 2],\n nodes[3 * quad[0] + 0] + results[3 * quad[0] + 0],\n nodes[3 * quad[0] + 1] + results[3 * quad[0] + 1],\n nodes[3 * quad[0] + 2] + results[3 * quad[0] + 2],\n nodes[3 * quad[0] + 0] + results[3 * quad[0] + 0],\n nodes[3 * quad[0] + 1] + results[3 * quad[0] + 1],\n nodes[3 * quad[0] + 2] + results[3 * quad[0] + 2])\n Bs.push(\n nodes[3 * quad[1] + 0] + results[3 * quad[1] + 0],\n nodes[3 * quad[1] + 1] + results[3 * quad[1] + 1],\n nodes[3 * quad[1] + 2] + results[3 * quad[1] + 2],\n nodes[3 * quad[1] + 0] + results[3 * quad[1] + 0],\n nodes[3 * quad[1] + 1] + results[3 * quad[1] + 1],\n nodes[3 * quad[1] + 2] + results[3 * quad[1] + 2],\n nodes[3 * quad[1] + 0] + results[3 * quad[1] + 0],\n nodes[3 * quad[1] + 1] + results[3 * quad[1] + 1],\n nodes[3 * quad[1] + 2] + results[3 * quad[1] + 2],\n nodes[3 * quad[1] + 0] + results[3 * quad[1] + 0],\n nodes[3 * quad[1] + 1] + results[3 * quad[1] + 1],\n nodes[3 * quad[1] + 2] + results[3 * quad[1] + 2])\n Cs.push(\n nodes[3 * quad[2] + 0] + results[3 * quad[2] + 0],\n nodes[3 * quad[2] + 1] + results[3 * quad[2] + 1],\n nodes[3 * quad[2] + 2] + results[3 * quad[2] + 2],\n nodes[3 * quad[2] + 0] + results[3 * quad[2] + 0],\n nodes[3 * quad[2] + 1] + results[3 * quad[2] + 1],\n nodes[3 * quad[2] + 2] + results[3 * quad[2] + 2],\n nodes[3 * quad[2] + 0] + results[3 * quad[2] + 0],\n nodes[3 * quad[2] + 1] + results[3 * quad[2] + 1],\n nodes[3 * quad[2] + 2] + results[3 * quad[2] + 2],\n nodes[3 * quad[2] + 0] + results[3 * quad[2] + 0],\n nodes[3 * quad[2] + 1] + results[3 * quad[2] + 1],\n nodes[3 * quad[2] + 2] + results[3 * quad[2] + 2])\n // push displacements\n disps.push(\n results[3 * quad[0] + 0],\n results[3 * quad[0] + 1],\n results[3 * quad[0] + 2],\n results[3 * quad[1] + 0],\n results[3 * quad[1] + 1],\n results[3 * quad[1] + 2],\n results[3 * quad[2] + 0],\n results[3 * quad[2] + 1],\n results[3 * quad[2] + 2],\n results[3 * quad[3] + 0],\n results[3 * quad[3] + 1],\n results[3 * quad[3] + 2])\n let sqr = x => x*x;\n min = globalMin\n max = globalMax\n let result = state.component\n if(result == 3) {\n let sqr = (x) => x*x;\n corners.push(\n Math.sqrt(sqr(results[3 * quad[0] + 0]) + sqr(results[3 * quad[0] + 1]) + sqr(results[3 * quad[0] + 2])),\n Math.sqrt(sqr(results[3 * quad[1] + 0]) + sqr(results[3 * quad[1] + 1]) + sqr(results[3 * quad[1] + 2])),\n Math.sqrt(sqr(results[3 * quad[2] + 0]) + sqr(results[3 * quad[2] + 1]) + sqr(results[3 * quad[2] + 2])),\n Math.sqrt(sqr(results[3 * quad[3] + 0]) + sqr(results[3 * quad[3] + 1]) + sqr(results[3 * quad[3] + 2])),\n Math.sqrt(sqr(results[3 * quad[0] + 0]) + sqr(results[3 * quad[0] + 1]) + sqr(results[3 * quad[0] + 2])),\n Math.sqrt(sqr(results[3 * quad[1] + 0]) + sqr(results[3 * quad[1] + 1]) + sqr(results[3 * quad[1] + 2])),\n Math.sqrt(sqr(results[3 * quad[2] + 0]) + sqr(results[3 * quad[2] + 1]) + sqr(results[3 * quad[2] + 2])),\n Math.sqrt(sqr(results[3 * quad[3] + 0]) + sqr(results[3 * quad[3] + 1]) + sqr(results[3 * quad[3] + 2])),\n Math.sqrt(sqr(results[3 * quad[0] + 0]) + sqr(results[3 * quad[0] + 1]) + sqr(results[3 * quad[0] + 2])),\n Math.sqrt(sqr(results[3 * quad[1] + 0]) + sqr(results[3 * quad[1] + 1]) + sqr(results[3 * quad[1] + 2])),\n Math.sqrt(sqr(results[3 * quad[2] + 0]) + sqr(results[3 * quad[2] + 1]) + sqr(results[3 * quad[2] + 2])),\n Math.sqrt(sqr(results[3 * quad[3] + 0]) + sqr(results[3 * quad[3] + 1]) + sqr(results[3 * quad[3] + 2])),\n Math.sqrt(sqr(results[3 * quad[0] + 0]) + sqr(results[3 * quad[0] + 1]) + sqr(results[3 * quad[0] + 2])),\n Math.sqrt(sqr(results[3 * quad[1] + 0]) + sqr(results[3 * quad[1] + 1]) + sqr(results[3 * quad[1] + 2])),\n Math.sqrt(sqr(results[3 * quad[2] + 0]) + sqr(results[3 * quad[2] + 1]) + sqr(results[3 * quad[2] + 2])),\n Math.sqrt(sqr(results[3 * quad[3] + 0]) + sqr(results[3 * quad[3] + 1]) + sqr(results[3 * quad[3] + 2])))\n } else {\n corners.push(\n results[3 * quad[0] + result],\n results[3 * quad[1] + result],\n results[3 * quad[2] + result],\n results[3 * quad[3] + result],\n results[3 * quad[0] + result],\n results[3 * quad[1] + result],\n results[3 * quad[2] + result],\n results[3 * quad[3] + result],\n results[3 * quad[0] + result],\n results[3 * quad[1] + result],\n results[3 * quad[2] + result],\n results[3 * quad[3] + result],\n results[3 * quad[0] + result],\n results[3 * quad[1] + result],\n results[3 * quad[2] + result],\n results[3 * quad[3] + result])\n }\n // pick the appropriate min/max per the selected component\n max = max[result]\n min = min[result]\n }\n\n document.getElementById('progress').innerHTML = ''\n return {\n coords: coords,\n trias: trias,\n disps: disps,\n As: As,\n Bs: Bs,\n Cs, Cs,\n min: min,\n max: max,\n texcoords: texcoords,\n corners: corners\n }\n}",
"function nextGen(matrix) {\n if (!isInitialized){\n drawGrid(matrix); // use hard-coded matrix first time\n } else {\n // already initialized\n var tempMatrix = matrix;\n\n for(var i=0; i<tempMatrix.length; i++){\n for (var j=0; j<tempMatrix[i].length; j++){\n if (tempMatrix[i][j].liveNeighborCount === 2 || tempMatrix[i][j].liveNeighborCount === 3){\n tempMatrix[i][j].state = true;\n // console.log(tempMatrix[i][j], ' is alive');\n } else if (tempMatrix[i][j].liveNeighborCount < 2 || tempMatrix[i][j].liveNeighborCount >= 4 ) { \n tempMatrix[i][j].state = false;\n // console.log(tempMatrix[i][j], ' is dead');\n }\n }\n }\n \n clearBoard(tempMatrix);\n var newMatrix = countLiveNeighbors(tempMatrix);\n \n drawGrid(newMatrix);\n } // end of else. isInitialized === true\n\n generationCount++;\n if (generationCount > 1){\n $(\"#goback\").css('display', 'inline-block');\n } else {\n $(\"#goback\").css('display', 'none'); \n }\n $(\"#genCount\").html('<h4>Generation: ' + generationCount + '</h4>');\n // console.log(neighborArray);\n}",
"constructor(attrs = {}) {\n super(attrs);\n this.name = '_Pool2D';\n const { \n kernel_size = [2, 2], \n strides = [2, 2], \n padding = 'VALID', \n data_format = 'NHWC',\n activation = 'NONE'\n } = attrs;\n\n if (Array.isArray(kernel_size)) {\n this.kernelShape = kernel_size;\n } else {\n this.kernelShape = [kernel_size, kernel_size];\n }\n\n if (Array.isArray(strides)) {\n this.strides = strides;\n } else {\n this.strides = [strides, strides];\n }\n\n if (Array.isArray(padding)) {\n if (padding.length !== 4) {\n this.throwError('Invalid padding.');\n // if all numbers in padding are 0, use padding = 'VALID'\n } else if (padding.every((x)=>!x)) {\n this.padding = 'VALID';\n } else {\n this.padding = padding;\n }\n } else if (padding === 'VALID' || padding === 'SAME') {\n this.padding = padding;\n } else {\n this.throwError('Invalid padding.');\n }\n\n if (data_format === 'NHWC') {\n this.dataFormat = data_format;\n } else {\n this.throwError('Only NHWC data formats are allowed.');\n }\n\n this.activation = activation;\n if (this.activation !== 'NONE') {\n this.activationProgram = webgl2.createProgram(activations[this.activation]);\n }\n }",
"initComputeRenderer() {\n this.gpuCompute = new GPUComputationRenderer( 64, 64, this.renderer );\n const dtPosition = this.gpuCompute.createTexture();\n const dtVelocity = this.gpuCompute.createTexture();\n this.fillPositionTexture( dtPosition );\n this.fillVelocityTexture( dtVelocity );\n this.velocityVariable = this.gpuCompute.addVariable( \"textureVelocity\", fragmentShaderVelocity, dtVelocity );\n this.positionVariable = this.gpuCompute.addVariable( \"texturePosition\", fragmentShaderPosition, dtPosition );\n this.gpuCompute.setVariableDependencies( this.velocityVariable, [ this.positionVariable, this.velocityVariable ] );\n this.gpuCompute.setVariableDependencies( this.positionVariable, [ this.positionVariable, this.velocityVariable ] );\n this.positionUniforms = this.positionVariable.material.uniforms;\n this.velocityUniforms = this.velocityVariable.material.uniforms;\n this.positionUniforms.time = { value: 0.0 };\n this.positionUniforms.delta = { value: 0.0 };\n this.velocityUniforms.time = { value: 1.0 };\n this.velocityUniforms.delta = { value: 0.0 };\n this.velocityUniforms.testing = { value: 1.0 };\n this.velocityUniforms.seperationDistance = { value: 1.0 };\n this.velocityUniforms.alignmentDistance = { value: 1.0 };\n this.velocityUniforms.cohesionDistance = { value: 1.0 };\n this.velocityUniforms.freedomFactor = { value: 1.0 };\n this.velocityUniforms.predator = { value: new Vector3() };\n this.velocityVariable.material.defines.BOUNDS = this.BOUNDS.toFixed( 2 );\n this.velocityVariable.wrapS = RepeatWrapping;\n this.velocityVariable.wrapT = RepeatWrapping;\n this.positionVariable.wrapS = RepeatWrapping;\n this.positionVariable.wrapT = RepeatWrapping;\n const error = this.gpuCompute.init();\n if ( error !== null ) {\n console.error(error);\n }\n }",
"function generateSerialDevices() {\n SerialPort.list(function (err, result) {\n log.log(result)\n result.forEach(device => {\n log.log(device)\n // var dev = new SerialMasterNode(device)\n // nodeDeviceList.push(dev)\n device.id = device.comName;\n\n DeviceManager.addNewDevice(device, DeviceManager.NodeType.SERIAL, true); //add new serial devices and overwrite\n });\n })\n}",
"generateCPU() {\n return {\n /** 16 bit counter to iterate through the memory array */\n programCounter: 512,\n /** array representing the register which is 8bit data register and 16 bloc of 8bit long */\n register: new Uint8Array(16),\n /** 16 bit counter to iterate through the Memory array (called I in most documentation) */\n I: 0,\n //array representing the stack\n stack: new Uint16Array(16),\n /** stack jump counter to iterate through the stack array must not go past 15 since the stack is 16 indexes long*/\n stackJumpCounter: 0,\n /** */\n delayTimer: 0,\n /** */\n soundTimer: 0\n }\n }",
"initializeNeurons() {\n this.neurons = [];\n\n for (let i = 0; i < INPUT_NEURONS; i++) {\n this.neurons.push(this.createNeuron(i))\n }\n\n for (let i = 0; i < OUTPUT_NEURONS; i++) {\n let id = config.maxNeurons + i;\n this.neurons[id] = this.createNeuron(id);\n }\n\n this.genes.forEach((gene) => {\n if (!gene.enabled) return;\n\n if (this.neurons[gene.to] == null) {\n this.neurons[gene.to] = new Neuron(gene.to);\n }\n this.neurons[gene.to].incoming.push(gene);\n\n if (this.neurons[gene.from] == null) {\n this.neurons[gene.from] = new Neuron(gene.from);\n }\n });\n }",
"function createGameGrid() {\n var grid = new Array(Constants.numberOfRows);\n for (var row = 0; row < Constants.numberOfRows; row++) {\n grid[row] = new Array(Constants.numberOfColumns);\n for (var col = 0; col < Constants.numberOfColumns; col++) {\n grid[row][col] = {\n state: 0,\n liveNeighbors: 0,\n bool: false,\n distance: 1000,\n indexRow: row,\n indexColumn: col,\n parent: null,\n\n };\n }\n }\n return grid;\n}",
"init() {\n let default_input = new Array(8);\n default_input.fill(0);\n\n // Map data to all slave devices using the specific address\n for (var device_name in this.devices) {\n\n // Get the device\n var device = this.devices[device_name];\n\n this.updateDevice(device, default_input);\n\n }\n\n }",
"constructor() {\n // map module.id -> [outgoing connections]\n this.outEdges = {};\n\n // map module.id -> [incoming connections]\n this.inEdges = {};\n\n // map module.id -> module\n this.modules = {};\n\n this.allEdges = [];\n }",
"makeCube(cx, cy, cz, sx, sy, sz) {\n let v0 = [ cx - sx / 2, cy - sy / 2, cz - sz / 2 ];\n let v1 = [ cx - sx / 2, cy - sy / 2, cz + sz / 2 ];\n let v2 = [ cx - sx / 2, cy + sy / 2, cz - sz / 2 ];\n let v3 = [ cx - sx / 2, cy + sy / 2, cz + sz / 2 ];\n let v4 = [ cx + sx / 2, cy - sy / 2, cz - sz / 2 ];\n let v5 = [ cx + sx / 2, cy - sy / 2, cz + sz / 2 ];\n let v6 = [ cx + sx / 2, cy + sy / 2, cz - sz / 2 ];\n let v7 = [ cx + sx / 2, cy + sy / 2, cz + sz / 2 ];\n\n let vertices = [];\n\n let insert = (x) => {\n vertices.push(x[0]);\n vertices.push(x[1]);\n vertices.push(x[2]);\n };\n\n insert(v0); insert(v3); insert(v1); insert(v0); insert(v2); insert(v3);\n insert(v3); insert(v5); insert(v1); insert(v3); insert(v7); insert(v5);\n insert(v3); insert(v6); insert(v7); insert(v3); insert(v2); insert(v6);\n insert(v1); insert(v4); insert(v0); insert(v1); insert(v5); insert(v4);\n insert(v5); insert(v6); insert(v4); insert(v5); insert(v7); insert(v6);\n insert(v0); insert(v6); insert(v2); insert(v0); insert(v4); insert(v6);\n\n let buffer = new Float32Array(vertices);\n\n let vertex_buffer = new GL.Buffer();\n let vertex_array = new GL.VertexArray();\n GL.bindBuffer(GL.ARRAY_BUFFER, vertex_buffer);\n GL.bufferData(GL.ARRAY_BUFFER, buffer.length * 4, buffer, GL.STATIC_DRAW);\n GL.bindVertexArray(vertex_array);\n GL.enableVertexAttribArray(0);\n GL.bindBuffer(GL.ARRAY_BUFFER, vertex_buffer);\n GL.vertexAttribPointer(0, 3, GL.FLOAT, GL.FALSE, 12, 0);\n GL.bindVertexArray(0);\n let m = { };\n m.vertex_buffer = vertex_buffer;\n m.vertex_array = vertex_array;\n m.vertex_count = vertices.length / 3;\n return m;\n }",
"generateNetwork () {\n const nbHidden = this.nodes.filter(node => node.type === 'hidden').length\n const network = new Network(this.nbInput, nbHidden, this.nbOutput)\n return network\n }",
"function createWebcamTensor(){\n\t// Get the img from the canvas and normalize the values\n\tlet webcamImg = [];\n\tloadPixels();\n\tfor(let j=0 ; j<height ; j++){\n\t\tfor(let i=0 ; i<width ; i++){\n\t\t\tlet pix = (i + j*width)*4;\n\t\t\twebcamImg.push(map(pixels[pix+0], 0, 255, -1, 1));\n\t\t\twebcamImg.push(map(pixels[pix+1], 0, 255, -1, 1));\n\t\t\twebcamImg.push(map(pixels[pix+2], 0, 255, -1, 1));\n\t\t}\n\t}\n\twebcamImg = tf.tensor4d(webcamImg, [1, 224, 224, 3]);\n\treturn webcamImg;\n}",
"function create_matrix(index, global_mode,global_rotation,shapes_tx,shapes_ty,shapes_rotation,shapes_scale){\n var mvMatrix = mat4.create(); // this is the matrix for transforming each shape before draw\n //set into an identity matrix (after create you don't know if there's junk in it)\n // set identity - fresh matrix\n mat4.identity(mvMatrix); \n if(global_mode[index]){\n for(var j = 0; j < global_rotation[index].length; j++){\n mat4.rotate(mvMatrix,degToRad(global_rotation[index][j]),[0,0,1]);\n } \n var scale = [1,1,1];\n scale[0] = scale[1] = scale[2] = global_scale;\n // finish consruct matrix here but haven't set it\n mvMatrix = mat4.scale(mvMatrix, scale);\n }\n var trans = [0,0,0];\n trans[0] = shapes_tx[index]; \n trans[1] = shapes_ty[index];\n trans[2] = 0.0;\n //translate is multiplied to the right side of the mvMatrix \n mvMatrix = mat4.translate(mvMatrix, trans); // move from origin to mouse click\n //2d x-y in 3d x-z rotate around z\n // only accept radian, not degree. so we use degToRad\n mvMatrix = mat4.rotate(mvMatrix, degToRad(shapes_rotation[index]), [0, 0, 1]); // rotate if any \n var scale = [1,1,1];\n scale[0] = scale[1] = scale[2] = shapes_scale[index];\n // finish consruct matrix here but haven't set it\n mvMatrix = mat4.scale(mvMatrix, scale); // scale if any \n //var mvMatrix1 = mat4.inverse(mvMatrix);\n //mvMatrix = mat4.multiply(mvMatrix1,mvMatrix);\n return mvMatrix;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function combines user inputs such as address, city, province and country to find the longitude and latitude | function geocodeAddress(geocoder) {
var address = document.getElementById('addressBox').value;
var city = document.getElementById('cityBox').value;
var province = document.getElementById('provinceBox').value;
var country = document.getElementById('countryBox').value;
var totalAddress=address+", "+city+ ", "+province+", "+country;
//google geocode api call
geocoder.geocode({'address': totalAddress}, function(results, status) {
if (status === 'OK') {
text.innerHTML="<h4>Your Location is:</h4> "+"Latitude: " + results[0].geometry.location.lat() +
"<br>Longitude: " + results[0].geometry.location.lng();
latitudeInput.value=results[0].geometry.location.lat();
longitudeInput.value=results[0].geometry.location.lng();
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
} | [
"function processAddress()\n{\n\tvar address = getAddress();\n\n\t//creating a geocoder object\n\tvar geocoder = new google.maps.Geocoder();\n\n\tgeocoder.geocode({'address': address}, function(results, status)\n\t{\n\t\t//If this was successful, then...\n\t\tif (status === 'OK')\n\t\t{\n\t\t\t//get the latitude and longitude: Note this is part of what I would store to the database or session\n\t\t\tvar latitude = results[0].geometry.location.lat();\n\t\t\tvar longitude = results[0].geometry.location.lng();\n\t\t\tsetMarker(results[0].geometry.location);\n\t\t\tsaveUserLocation(address, latitude, longitude);\n\t\t} else if (status==\"ZERO_RESULTS\")\n\t\t{\n\t\t\t//get the latitude and longitude in case when coordinates are provided in the address field and set the marker as well as string to the database or session\n\t\t\tvar location=address.replace(/[()]/g, '').split(',');\n\t\t\tvar latitude = location[0];\n\t\t\tvar longitude = location[1];\n\t\t\tvar new_location = {lat: parseFloat(latitude), lng: parseFloat(longitude)};\n\t\t\tsetMarker(new_location);\n\t\t\tsaveUserLocation(address, latitude, longitude);\n\t\t} else \n\t\t{\n\t\t\tconsole.error('Geocode was not successful for the following reason: ' + status);\n\t\t}\n\t});\n}",
"function geocode(e) {\n //prevent actual submit\n e.preventDefault();\n var location = document.getElementById('location-input').value;\n $.ajax(\"https://maps.googleapis.com/maps/api/geocode/json?\", {\n method: \"get\",\n data: {\n address: location,\n key: \"AIzaSyD2vYz71KVg4PUiyae7M21lCA1Wkh0b8RY\"\n },\n success: function (data) {\n if(data.results.length===0){\n geo_info_object = {\n lat: null,\n lon: null,\n city: null,\n state: null\n };\n callApi();\n return;\n }\n //geometry\n var city;\n var state;\n var addressComponentArray = data.results[0].address_components;\n var updatedLocation= data.results[0].geometry.location;\n for (var i = 0; i < addressComponentArray.length; i++) {\n for(var j =0; j<addressComponentArray[i].types.length; j++){\n if (addressComponentArray[i].types[j] === 'administrative_area_level_1') {\n state = addressComponentArray[i].long_name;\n }\n if (addressComponentArray[i].types[j] === 'locality') {\n city = addressComponentArray[i].long_name;\n }\n }\n }\n geo_info_object = {\n lat: (updatedLocation.lat),\n lon: (updatedLocation.lng),\n city: city,\n state: state\n };\n callApi();\n }\n });\n}",
"function getCustomerAddress() {\n //inputs\n let districtInp = document.getElementById(\"az-add-dist\"),\n upazillaInp = document.getElementById(\"az-add-upazilla\"),\n areaInp = document.getElementById(\"az-add-vill\"),\n zipCodeInp = document.getElementById(\"az-add-zip\"),\n streetInp = document.getElementById(\"az-add-street\"),\n contactNumInp = document.getElementById(\"az-add-mobile\"),\n checkboxInp = document.getElementById(\"az-check-default-address\");\n\n return {\n district: districtInp.value || \"\",\n upazilla: upazillaInp.value || \"\",\n area: areaInp.value || \"\",\n zipcode: zipCodeInp.value || \"\",\n street: streetInp.value || \"\",\n contactNum: contactNumInp.value || \"\",\n setDefault: checkboxInp.checked || false,\n };\n}",
"function searchAddressFrom() {\n var geocoder = new google.maps.Geocoder();\n var address = $(\"#addressFrom\").val();\n geocoder.geocode( { 'address': address}, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n var coords = results[0].geometry.location;\n $(\"#map\").putMarker({coords: [coords.lat(), coords.lng()]});\n $(\"#map\").setCenter(coords);\n } else {\n alert(\"Le geocodage n\\'a pu etre effectue pour la raison suivante: \" + status);\n }\n });\n}",
"function postalCodeLookup() {\n\tlet postalcode = document.getElementById(\"postalcodeInput\").value;\n\tlet selectedCountry = getDataId('countryInput', 'countries');\n\tctry = countryInput.value;\n\n\t//example: http://api.geonames.org/postalCodeLookupJSON?postalcode=6600&country=AT&username=demo\n\tlet request = `http://api.geonames.org/postalCodeLookupJSON?postalcode=${postalcode}&country=${selectedCountry}&username=atschpe`;\n\n\tretrieveData(request)\n\t.then(receivedData => {\n\t\tif (receivedData == null) {\n\t\t\treturn;// There was a problem parsing search results\n\t\t}\n\t\tpostalcodes = receivedData.postalcodes;// save array of 'postalcodes'\n\t\t\n\t\tlet placeList = document.getElementById(\"places\");\n\t\tif (postalcodes.length > 1) {\n\t\t\tlet postalCodeList = postalcodes.map((item, index) => {\n\t\t\t\tplaceList.innerHTML += `<option value=\"${item.placeName}\" data-id=\"${index}\"></option>`;\n\t\t\t})\n\t\t} else {\n\t\t\tif (postalcodes.length == 1) {\n\t\t\t\tplaceInput.value = postalcodes[0].placeName;// The postalcode only refers to one place pop it into the input \n\t\t\t\tcity = placeInput.value;\n\t\t\t\tsetLongLat(postalcodes[0]);\n\t\t\t\tClient.getPix();\n\t\t\t} \n\t \t}\n\t});\n}",
"function directionsParseAddressAndValidate() {\n // part 0 - cleanup\n\n // clear the Feature identification, as they likely did not use a Feature search and will likely need to go through a Did You Mean autocomplete sorta thing\n // if they did mean it, this gets populated in the \"features\" switch case below\n var form = $('#page-directions');\n form.find('input[name=\"feature_gid\"]').val('');\n form.find('input[name=\"feature_type\"]').val('');\n\n // clear any prior directions text, map lines, etc.\n directionsClear();\n\n // part 1 - simple params we can extract now\n // we use these to fine-tune some of the routing params, e.g. re-geocoding opints to their nearest parking lot; see part 3\n // prior versions of this app and website, had selectors for some of these options; but we decided to simplify and hardcode the defaults\n // historical note: that's why Bike is called bike_advanced; prior versions had us select bicycle difficulty\n\n var via = form.find('div.directions_buttons img[data-selected=\"true\"]').attr('data-mode');\n var tofrom = \"to\";\n var prefer = \"recommended\";\n\n // part 2 - figure out the origin\n\n // can be any of address geocode, latlon already properly formatted, current GPS location, etc.\n // this must be done before the target is resolved (below) because resolving the target can mean weighting based on the starting point\n // e.g. directions to parks/reservations pick the closest gate or parking lot to our starting location\n // this also has our bail conditions, e.g. an address search that cannot be resolved, a feature name that is ambiguous, ... look for \"return\" statements below\n\n // we must do some AJAX for the target location and the origin location, but it must be done precisely in this sequence\n var sourcelat, sourcelng;\n var addresstype = form.find('select[name=\"origin\"]').val();\n var address = form.find('input[name=\"address\"]').val();\n switch (addresstype) {\n // GPS origin: simplest possible case: lat and lng are already had\n case 'gps':\n sourcelat = MARKER_GPS.getLatLng().lat;\n sourcelng = MARKER_GPS.getLatLng().lng;\n break;\n // GEOCODE origin: but a hack (of course), that it can be either an address or else GPS coordinates in either of 2 formats\n case 'geocode':\n if (! address) return navigator.notification.alert('Please enter an address, city, or landmark.', null, 'Enter an Address');\n var is_decdeg = /^\\s*(\\d+\\.\\d+)\\s*\\,\\s*(\\-\\d+\\.\\d+)\\s*$/.exec(address); // regional assumption in this regular expression: negative lng, positive lat\n var is_gps = /^\\s*N\\s+(\\d+)\\s+(\\d+\\.\\d+)\\s+W\\s+(\\d+)\\s+(\\d+\\.\\d+)\\s*$/.exec(address); // again, regional assumption that we're North and West\n if (is_decdeg) {\n sourcelat = parseFloat( is_decdeg[1] );\n sourcelng = parseFloat( is_decdeg[2] );\n } else if (is_gps) {\n var latd = parseFloat( is_gps[1] );\n var latm = parseFloat( is_gps[2] );\n var lngd = parseFloat( is_gps[3] );\n var lngm = parseFloat( is_gps[4] );\n sourcelat = latd + (latm/60); // regional assumption; lat increases as magnitude increases cuz we're North\n sourcelng = -lngd - (lngm/60); // regional assumption; lng dereases as magnitude increases cuz we're West\n } else {\n var params = {};\n params.address = address;\n params.bing_key = BING_API_KEY;\n params.bbox = GEOCODE_BIAS_BOX;\n\n $.ajaxSetup({ async:false });\n $.get(BASE_URL + '/ajax/geocode', params, function (result) {\n $.ajaxSetup({ async:true });\n\n if (! result) return navigator.notification.alert('Could not find that address.', null, 'Address Not Found');\n sourcelat = result.lat;\n sourcelng = result.lng;\n },'json').error(function (error) {\n $.ajaxSetup({ async:true });\n\n return navigator.notification.alert('Could not find that address. Check the address, and that you have data service turned on and a good signal.', null, 'No connection?');\n });\n }\n break;\n // FEATURES origin: use a variant of the keyword autocomplete concept, to provide a list of names as they type\n // having exactly one result, or the first result matching your search exactly, fills in the Feature Type and GID for later, as well as grabbing its latlng\n // to clarify: submitting the form\n case 'features':\n var params = {};\n params.keyword = address;\n params.limit = 25;\n params.lat = MARKER_GPS.getLatLng().lat;\n params.lng = MARKER_GPS.getLatLng().lng;\n params.via = via;\n\n $.ajaxSetup({ async:false });\n $.get(BASE_URL + '/ajax/keyword', params, function (candidates) {\n $.ajaxSetup({ async:true });\n\n // we got back a list of autocomplete candidates\n // see if any of them are an exact match for what we typed, if so then truncate the list to that 1 perfect item\n // see if there's only 1 autocomplete candidate (perhaps the one we picked above), in which case we call that a match\n var matchme = address.replace(/\\W/g,'').toLowerCase();\n for (var i=0, l=candidates.length; i<l; i++) {\n var stripped = candidates[i].name.replace(/\\W/g,'').toLowerCase();\n if (stripped == matchme) { candidates = [ candidates[i] ]; break; }\n }\n\n if (candidates.length == 1) {\n // only 1 autocomplete candidate\n // save the lat/lng and the type/gid\n // and fill in the name so it's all spelled nicely, instead of the user's presumably-partial wording\n // then empty the autocomplete candidate listing, cuz we only had 1 and it's now in effect\n form.find('input[name=\"feature_gid\"]').val(candidates[0].gid);\n form.find('input[name=\"feature_type\"]').val(candidates[0].type);\n sourcelat = candidates[0].lat;\n sourcelng = candidates[0].lng;\n form.find('input[name=\"address\"]').val( candidates[0].name );\n $('#directions_autocomplete').empty().hide();\n } else {\n // okay, there's more than 1 candidate for this autocomplete, so fill in that listview of options\n // each option has a click handler to basically do what the \"length == 1\" option did above: fill it in, empty listing, ...\n // note: item 0 is not a result, but the words \"Did you mean...\" and has no click behavior\n var listing = $('#directions_autocomplete').empty().show();\n for (var i=0, l=candidates.length; i<l; i++) {\n var name = candidates[i].name.replace(/^\\s*/,'').replace(/\\s*$/,'');\n var item = $('<li></li>').data('raw',candidates[i]).appendTo(listing);\n $('<span></span>').addClass('ui-li-heading').text(name).appendTo(item);\n item.click(function () {\n // click this item: fill in the name, gid and type, lat and lng, ... empty the listing cuz we made a choice\n var info = $(this).data('raw');\n form.find('input[name=\"feature_gid\"]').val(info.gid);\n form.find('input[name=\"feature_type\"]').val(info.type);\n sourcelat = info.lat;\n sourcelng = info.lng;\n form.find('input[name=\"address\"]').val( info.name );\n $('#directions_autocomplete').empty().hide();\n });\n }\n listing.listview('refresh');\n }\n },'json').error(function (error) {\n $.ajaxSetup({ async:true });\n\n return navigator.notification.alert('Could fetch any locations. Check that you have data service turned on and a good signal.', null, 'No connection?');\n });\n break;\n }\n if (! sourcelat || ! sourcelng) return; // if this failed, do nothing; likely indicates that an AJAX call was used to do something other than bail or get coordinates, e.g. Features search\n // if we got here then we either loaded sourcelat and sourcelng, or else bailed with an error or some other task completed\n\n // part 3 - figure out the target location and perhaps re-figure-out the starting location as well\n // seems dead simple at first: we got here from the Details Panel and it has data('raw') with lat and lng\n // but some routing scenarios actually use alternate points e.g. the entrance gate or parking lot closest to each other\n // so we likely will do a re-geocode for target AND source to find their closest geocoding-target-points\n\n // 3a: start with the default points for the target location\n var targetlat = $('#page-details').data('raw').lat;\n var targetlng = $('#page-details').data('raw').lng;\n var targettype = $('#page-details').data('raw').type;\n var targetgid = $('#page-details').data('raw').gid;\n\n var origtype = form.find('input[name=\"feature_type\"]').val();\n var origgid = form.find('input[name=\"feature_gid\"]').val();\n\n // 3b: if the origin is a Feature AND it's a type that supports alternate destinations\n // then do some AJAX and replace sourcelat and sourcelng with the version that's closest to our target location\n if (origtype && origgid) {\n switch (origtype) {\n case 'poi':\n case 'reservation':\n case 'building':\n case 'trail':\n var params = {};\n params.type = origtype;\n params.gid = origgid;\n params.lat = targetlat;\n params.lng = targetlng;\n params.via = via;\n\n $.ajaxSetup({ async:false });\n $.get(BASE_URL + '/ajax/geocode_for_directions', params, function (reply) {\n $.ajaxSetup({ async:true });\n sourcelat = reply.lat;\n sourcelng = reply.lng;\n }, 'json').error(function (error) {\n $.ajaxSetup({ async:true });\n // error handling here, would be simply to leave sourcelat and sourcelng alone\n // rather than bug the uer that we couldn't find an even-better location than the ones they already picked\n });\n break;\n }\n }\n\n // 3c: if the target is a Feature and it's a type that supports alternate destinations\n // then do some AJAX and replace sourcelat and sourcelng with the version that's closest to our origin location\n // yes, we potentially revised the origin above; now we potentially adjust the target as well\n // hypothetically this could have a situation where we now route to a point further away, shuffling both points back and forth\n // but that's not a realistic problem; parking lots aren't on the far side of town from their facility, for example\n if (targettype && targetgid) {\n switch (targettype) {\n case 'poi':\n case 'reservation':\n case 'building':\n case 'trail':\n var params = {};\n params.type = targettype;\n params.gid = targetgid;\n params.lat = sourcelat;\n params.lng = sourcelng;\n params.via = via;\n\n $.ajaxSetup({ async:false });\n $.get(BASE_URL + '/ajax/geocode_for_directions', params, function (reply) {\n $.ajaxSetup({ async:true });\n targetlat = reply.lat;\n targetlng = reply.lng;\n }, 'json').error(function (error) {\n $.ajaxSetup({ async:true });\n // error handling here, would be simply to leave targetlat and targetlng alone\n // rather than bug the uer that we couldn't find an even-better location than the ones they already picked\n });\n break;\n }\n }\n // if we got here then we successfully loaded targetlat and targetlng\n\n // afterthought: they decided that they want to use native navigation for all transit & driving directions,\n // rather than our own UI. So if they're aksing for those types of directions, bail to do that\n if (via == 'car' || via == 'bus') {\n openDirections(sourcelat,sourcelng,targetlat,targetlng);\n return false;\n }\n\n // part 100 - done and ready!\n // slot the numbers into the form, really for debugging\n // then do the directions-getting from all those params we fetched and calculated above\n\n form.find('input[name=\"origlat\"]').val(sourcelat);\n form.find('input[name=\"origlng\"]').val(sourcelng);\n form.find('input[name=\"destlat\"]').val(targetlat);\n form.find('input[name=\"destlng\"]').val(targetlng);\n\n directionsFetch(sourcelat,sourcelng,targetlat,targetlng,tofrom,via,prefer);\n}",
"function searchAddressTo() {\n var geocoder = new google.maps.Geocoder();\n var address = $(\"#addressTo\").val();\n geocoder.geocode( { 'address': address}, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n var coords = results[0].geometry.location;\n $(\"#map\").putMarker({coords: [coords.lat(), coords.lng()]});\n $(\"#map\").setCenter(coords);\n } else {\n alert(\"Le geocodage n\\'a pu etre effectue pour la raison suivante: \" + status);\n }\n });\n}",
"getLocation() {\n // using fetch API to get AJAX calls you can use XHP also\n fetch(\"https://geoip-db.com/json/\")\n .then(res => res.json())\n .then(result => {\n name.innerHTML += `${res.city}, ${res.state}`;\n });\n }",
"function getZip(city, state)\n {\n var zip;\n \n $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + city + ',' + state + '&sensor=true', function(json)\n {\n console.log(json);\n \n zip = json.results[0].address_components[4].long_name;\n console.log(zip);\n \n //if the city and state are invalid, json.status = ZERO_RESULTS\n \n });\n \n return zip;\n \n }",
"function geocoder(state) {\n geocoder = new google.maps.Geocoder();\n\n geocoder.geocode( { 'address': state}, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n\n var lat = results[0].geometry.location.lat();\n var lng = results[0].geometry.location.lng();\n dispLoc = results[0].formatted_address;\n var placeID = results[0].place_id;\n console.log(dispLoc);\n console.log(placeID);\n\n placeSearch(lat, lng);\n\n console.log(\"lat: \"+lat+\" lng: \"+ lng);\n console.log(results);\n }\n else {\n alert(\"Geocode was not successful for the following reason: \" + status);\n }\n });\n\n}",
"function getLongitude(input) {\n // we know input is validated so we know we can go from North/South to the end\n var search = input.search(/[NS]/);\n\n var longitude = \"\";\n if (search == -1) {\n longitude = input.substr(input.search(' '));\n } else {\n longitude = input.substring(search + 1);\n }\n\n return longitude;\n}",
"function convertCityLatLong(inputCity){\n let directGeocodingAPI = 'https://api.openweathermap.org/geo/1.0/direct?q=' + inputCity + '&limit=5&appid=fe69a8ae1bfba9fa932a4b4358617cbf'\n fetch(directGeocodingAPI)\n .then(function(response){\n return response.json();\n })\n .then(function(data){\n var lat = data[0].lat\n var long = data[0].lon\n fiveDayForecastAPI(lat,long)\n })\n \n \n}",
"function zoomToNeighborhood() {\n var geocoder = new google.maps.Geocoder();\n //obtain the user-input adress\n var neighborhood = $(\"#neighborhood\").val() + ' Chicago';\n //make sure the input value is not blank\n if (neighborhood == '') {\n window.alert ('You must enter an valid neighborhood name');\n } else {\n geocoder.geocode ({\n address: neighborhood,\n //componentRestrictions: {locality: 'Chicago'}\n }, function(results, status) {\n if (status == google.maps.GeocoderStatus.OK) {\n map.setCenter(results[0].geometry.location);\n map.setZoom(15);\n }\n else {\n window.alert ('We cannot locate your neighborhood. Please try again!');\n }\n });\n }\n}",
"function getnearestweather(latinput, longinput)\n{\n // var forecastobj = {\n // BR: \"Mist\",\n // CL: \"Cloudy\",\n // CR: \"Drizzle\",\n // FA: \"Fair(Day)\",\n // FG: \"Fog\",\n // FN: \"Fair(Night)\",\n // FW: \"Fair & Warm\",\n // HG: \"Heavy Thundery Showers with Gusty Winds\",\n // HR: \"Heavy Rain\",\n // HS: \"Heavy Showers\",\n // HT: \"Heavy Thundery Showers\",\n // HZ: \"Hazy\",\n // LH: \"Slightly Hazy\",\n // LR: \"Light Rain\",\n // LS: \"Light Showers\",\n // OC: \"Overcast\",\n // PC: \"Partly Cloudy (Day)\",\n // PN: \"Partly Cloudy (Night)\",\n // PS: \"Passing Showers\",\n // RA: \"Moderate Rain\",\n // SH: \"Showers\",\n // SK: \"Strong Winds,Showers\",\n // SN: \"Snow\",\n // SR: \"Strong Winds, Rain\",\n // SS: \"Snow Showers\",\n // SU: \"Sunny\",\n // SW: \"Strong Winds\",\n // TL: \"Thundery Showers\",\n // WC: \"Windy,Cloudy\",\n // WD: \"Windy\",\n // WF: \"Windy,Fair\",\n // WR: \"Windy,Rain\",\n // WS: \"Windy, Showers\"\n // };\n\n var forecastobj = {\n BR: \"Not Raining\",\n CL: \"Not Raining\",\n CR: \"Raining\",\n FA: \"Not Raining\",\n FG: \"Not Raining\",\n FN: \"Not Raining\",\n FW: \"Not Raining\",\n HG: \"Raining\",\n HR: \"Raining\",\n HS: \"Raining\",\n HT: \"Raining\",\n HZ: \"Not Raining\",\n LH: \"Not Raining\",\n LR: \"Raining\",\n LS: \"Raining\",\n OC: \"Not Raining\",\n PC: \"Not Raining\",\n PN: \"Not Raining\",\n PS: \"Raining\",\n RA: \"Raining\",\n SH: \"Raining\",\n SK: \"Raining\",\n SN: \"Not Raining\",\n SR: \"Raining\",\n SS: \"Not Raining\",\n SU: \"Not Raining\",\n SW: \"Not Raining\",\n TL: \"Raining\",\n WC: \"Not Raining\",\n WD: \"Not Raining\",\n WF: \"Not Raining\",\n WR: \"Raining\",\n WS: \"Raining\"\n };\n\n var getlatfromuser = latinput;\n var getlongfromuser = longinput;\n //var getlatfromuser = 1.332401;\n //var getlongfromuser = 103.848438;\n\n var parser1 = new xml2js.Parser({explicitArray : true, attrkey : 'Child'});\n\n http.get('http://api.nea.gov.sg/api/WebAPI/?dataset=2hr_nowcast&keyref=781CF461BB6606ADC767F3B357E848ED3A27067168AB8007', function(res)\n {\n var response_data = '';\n res.setEncoding('utf8');\n res.on('data', function(chunk)\n {\n response_data += chunk;\n });\n \n res.on('end', function() \n {\n parser1.parseString(response_data, function(err, result) \n {\n if (err) \n {\n console.log('Got error: ' + err.message);\n }\n else \n {\n eyes.inspect(result);\n \n //convert into JSON object\n console.log('Converting to JSON object.');\n var jsonobject2 = JSON.parse(JSON.stringify(result));\n console.log(util.inspect(jsonobject2, false, null));\n\n //read and traverse JSON object\n var nearestdistance1 = 0;\n var showdistanceformat1;\n var showdistance1;\n \n var showlat1;\n var showlong1;\n var nearestForeCast;\n var nearestForeCastName;\n\n console.log(\"name 1: \" + jsonobject2.channel.title);\n console.log(\"name 2: \" + jsonobject2.channel.source);\n console.log(\"date3 : \" +jsonobject2.channel.item[0].forecastIssue[0].Child.date);\n console.log(\"length \"+jsonobject2.channel.item[0].weatherForecast[0].area.length)\n\n for (var i = 0; i < jsonobject2.channel.item[0].weatherForecast[0].area.length; ++i)\n {\n showlat1 = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.lat;\n showlong1 = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.lon;\n showdistance1 = calculatedistance(showlat1, showlong1, getlatfromuser, getlongfromuser, 'K');\n //round to 3 decimal places\n showdistanceformat1 = Math.round(showdistance1*1000)/1000;\n console.log(\"Distance(in km) : \" + showdistanceformat1);\n\n var tempdistance1 = showdistanceformat1;\n if (i == 0)\n {\n nearestdistance1 = tempdistance1;\n nearestForeCast = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.forecast;\n nearestForeCastName = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.name;\n }\n if (nearestdistance1 > tempdistance1)\n {\n nearestdistance1 = tempdistance1;\n nearestForeCast = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.forecast;\n nearestForeCastName = jsonobject2.channel.item[0].weatherForecast[0].area[i].Child.name;\n }\n }\n console.log(\"Distance to Nearest Town : \" + nearestdistance1);\n console.log(\"Forecast in Nearest Town : \" + nearestForeCast);\n console.log(\"Nearest Town : \" + nearestForeCastName);\n\n var forecast = forecastobj[nearestForeCast];\n console.log(\"Forecast in Current Location : \" + forecast);\n }\n });\n });\n\n res.on('error', function(err) \n {\n console.log('Got error: ' + err.message);\n });\n });\n}",
"function getCity(address) {\r\n\tvar lastCommaPos = address.lastIndexOf(\",\", address.length);\r\n\tvar firstCommaPos = address.indexOf(\",\");\r\n\tif (lastCommaPos != firstCommaPos)\r\n\t\treturn address.substring(firstCommaPos + 8, lastCommaPos);\r\n\telse\r\n\t\treturn address.substring(0, lastCommaPos);\r\n}",
"function getLocationName(lat, long) {\n console.log(lat, long)\n fetch(`https://api.geocod.io/v1.4/reverse?q=${lat},${long}&fields=census2010&api_key=8cccc5825cc2d2dc042d3db2d00b2d5dcd85bcd`)\n .then(response => {\n if (response.ok) {\n return response.json();\n } else console.log(\"That didn't work.\")\n })\n .then(responseJson => grabCensusData(responseJson))\n .catch(err => {\n console.log(err)\n })\n }",
"function SearchCity(){\n \n var citycode = document.getElementById(\"city_searchbar\").value;\n var countrycode = document.getElementById(\"country_searchbar\").value;\n\n // Check every letter of the citycode string\n for(zl = 0; zl < citycode.length; ++zl){\n\n // If citycode contains a number => error\n if(!(isNaN(citycode[zl]))){\n alert(\"A name does not include a number ;)\");\n return \"\";\n } \n }\n\n // Check every letter of the countrycode string\n for(zl = 0; zl < countrycode.length; ++zl){\n\n // If countrycode contains a number => error\n if(!(isNaN(countrycode[zl]))){\n alert(\"A name does not include a number ;)\");\n return \"\";\n } \n }\n\n // If citycode or countrycode are empty => error\n if(!citycode || !countrycode){\n alert(\"Type in a text!\");\n return \"\"\n }\n\n else{\n var weatherURL = `https://api.openweathermap.org/data/2.5/weather?q=${citycode},${countrycode}&mode=json&appid=77d410ccec3766ca5513a1ace872f0f1`;\n \n LoadWeather(weatherURL);\n }\n }",
"function checkCity(lat, lng) {\n if (lat.toFixed(3) >= 50.000 && lat.toFixed(3) <= 52.000) {\n if (lng.toFixed(3) >= 5.000 && lng.toFixed(3) <= 7.000) {\n inCity = true;\n $('#content_overzicht').empty();\n getWeetjes();\n getKoepons();\n } else {\n if (inCity) {\n notInCity(1);\n }\n else {\n notInCity(0);\n }\n }\n } else {\n if (inCity) {\n notInCity(1);\n }\n else {\n notInCity(0);\n }\n }\n}",
"function getCityName() {\n 'use strict';\n\n var keyGoogle = 'AIzaSyBmCk28nEs1OWXgwS0VQ1752o_cYwrkxHs',\n url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=',\n location = latitude + ',' + longitude;\n\n $.ajax({\n url: url + location,\n type: 'GET',\n dataType: 'json',\n data: {\n //location_type: 'GEOMETRIC_CENTER',\n key: keyGoogle\n }\n }).done(function (googleResponse) {\n $city.text(googleResponse.results[0].formatted_address);\n }).fail(function (googleResponse) {\n Materialize.toast('Cannot get City Name from google', 600);\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handles the drop event on an icon. | function dropIcon(dropTarget) {
// Handle icon drop reordering
event.preventDefault();
var oldPosition = getAppIndexById(event.dataTransfer.getData("text/plain"));
var newPosition = getAppIndexById(dropTarget.id);
apps.move(oldPosition, newPosition);
drawIcons();
localStorage["apps"] = JSON.stringify(apps);
$(".icons").attr("aria-dropeffect", "none"); // Mark no icons targets
} | [
"function dragOverIcon(dropTarget) {\n event.preventDefault();\n}",
"function trashHandleItemDrop(evt) {\n evt.stopPropagation();\n evt.preventDefault();\n var data = event.dataTransfer.getData(internalDNDType);\n console.log(\"drop detected for:\",data) \n dropFile(data) \n\n}",
"function onDrop(event, ui) {\n // Icons scale down (shrinks) until it disappears on face\n ui.draggable.hide('scale');\n\n // When user hovers drops icon onto face, display image where face is looking\n // towards center and appears a bit less sad ('temporary happiness')\n $faceImg.attr('src', 'assets/images/sad-face-3.png');\n\n // Also play 'huh' sound effect\n huhSound.play();\n huhSound.volume = 0.2;\n}",
"onDropItem(aItem) {\n // method that may be overridden by derived bindings...\n }",
"function handleDrop(e) {\n let dt = e.dataTransfer\n let files = dt.files\n handleFiles(files)\n }",
"_onDrop(e) {\n e.stopPropagation();\n e.preventDefault();\n\n const dt = e.originalEvent.dataTransfer;\n const files = dt && dt.files;\n\n if (files) {\n this.trigger('filesDropped', files);\n }\n\n this.close();\n }",
"function drop(ev) {\n $('.tile').removeClass('hover');\n ev.preventDefault();\n\n const tile = $(ev.target);\n const row = tile.attr('row');\n const col = tile.attr('col');\n\n if (row !== undefined) {\n if (dragElement.attr('row') !== undefined) {\n const oldRow = dragElement.attr('row');\n const oldCol = dragElement.attr('col');\n craftingTable.insertItem(oldRow, oldCol, null);\n }\n\n craftingTable.insertItem(row, col, dragItem);\n craftingTable.removeResult();\n craftingTable.display();\n }\n}",
"function mouseDrop(e) {\n\n if(dropValid(mousePiece)) {\n\n alignPiece(mousePiece);\n\n removeEvent(document, \"mousemove\", mouseMove, false);\n removeEvent(document, \"mouseup\", mouseDrop, false);\n mousePiece.style.cursor = \"pointer\";\n solveCheck()\n }\n }",
"async _onDropItem(event, data) {\n if ( !this.actor.owner ) return false;\n const item = await Item.fromDropData(data);\n /*-----------Beginning of added code--------------*/\n // Check if droped item is a Focus and then confirm if Actor already has a Focus with the same name\n // If positive, then returns FALSE\n if (item.data.type === \"focus\") {\n const itemNameLowerCase = item.name.toLowerCase();\n const ownedFoci = this.actor.itemTypes.focus;\n for (let i = 0; i < ownedFoci.length; i++) {\n const e = ownedFoci[i];\n const eName = e.data.data.nameLowerCase;\n if (eName === itemNameLowerCase) {\n let warning = game.i18n.localize(\"age-system.WARNING.duplicatedFocus\");\n warning += `\"${eName.toUpperCase()}\"`;\n ui.notifications.warn(warning);\n return false;\n }; \n };\n };\n if (item.data.type === \"shipfeatures\") {\n let warning = game.i18n.localize(\"age-system.WARNING.shipPartsOnChar\");\n ui.notifications.warn(warning);\n return false;\n }\n /*-------------End of added code------------------*/\n const itemData = duplicate(item.data);\n \n const actor = this.actor;\n // Handle item sorting within the same Actor\n let sameActor = (data.actorId === actor._id) || (actor.isToken && (data.tokenId === actor.token.id));\n if (sameActor) return this._onSortItem(event, itemData);\n\n // Create the owned item\n return this._onDropItemCreate(itemData);\n }",
"function dragHandler(e) {\n const cardId = e.currentTarget.getAttribute('id');\n // console.info(e);\n e.dataTransfer.setData('text', cardId);\n }",
"function onBMTreeDragDrop()\n {\n BookmarkTags.BookmarkCmds.handleDragDrop(queryBuilder.query.tagIds());\n }",
"function drop(e) {\n var color = e.dataTransfer.getData('color');\n setColor('picker', parseColor(color));\n }",
"function dragStartIcon(dragSource) {\n var dragIcon = $(\"<img>\").attr(\"src\", getAppIcon(dragSource.id))[0];\n var width = dragIcon.width/2, height = dragIcon.height/2;\n if (!width) width = 64;\n if (!height) height = 64;\n // dragIcon.width = 128;\n // dragIcon.height = 128;\n event.dataTransfer.setDragImage(dragIcon, width, height);\n event.dataTransfer.effectsAllowed = \"move\";\n event.dataTransfer.setData(\"text/uri-list\", dragSource.href);\n event.dataTransfer.setData(\"text/plain\", dragSource.id);\n\n $(dragSource).css(\"opacity\", \"0.25\")\n .attr(\"aria-grabbed\", \"true\");\n $(\".icons\").attr(\"aria-dropeffect\", \"move\"); // Mark all icons targets\n}",
"onDragDrop() {\n this.onDragEnd();\n\n // If we dropped a flower at a new position, report that we made a move\n // and generate new flowers\n if (!Map(this._originalTargetCell).equals(Map(this._currentCell))) {\n this.board.resolveMoveAt(this._currentCell);\n }\n }",
"function componentDropHandler(event, ui) {\n\tconst $item = $(ui.item);\n\tif (!$item.hasClass('drag-component')) {\n\t\t// if it is not dragged from the side; do nothing\n\t\treturn;\n\t}\n\n\t// remove leftover #just-dropped-down element, which could have spawned\n\t// from creating component with modal\n\tlet cnt = 0;\n\twhile ($(\"#just-dropped-down\").length != 0) {\n\t\t$div = $(\"#just-dropped-down\");\n\t\t$div.removeAttr('id');\n\t\tif ($div.html() == \"\") {\n\t\t\t$div.remove();\n\t\t}\n\t\tcnt++; // avoid infinite loop for some reason. should always run only 1 time.\n\t\tif (cnt > 5) {\n\t\t\tconsole.error('Fatal error: infinite loop in removing just-dropped-down!')\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tvar cmp = $item.attr('id');\n\t$item.empty();\n\t$item.removeAttr(\"style\");\n\t$item.removeAttr(\"class\");\n\t$item.off();\n\t$item.addClass('ud');\n\t$item.attr(\"id\", \"just-dropped-down\"); // drop to this element & remove later\n if (cmp === \"img-cmp\") {\n open_img_selection();\n }\n else if (cmp === 'textbox-cmp') {\n\t\t$item.append($('<div class=\"editable\">'+\n\t\t\t\t\t\t'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Dictum at tempor commodo ullamcorper. Ac turpis egestas maecenas pharetra convallis posuere morbi. Neque viverra justo nec ultrices. Commodo odio aenean sed adipiscing diam donec. Habitant morbi tristique senectus et netus et malesuada fames ac. Iaculis nunc sed augue lacus viverra. Cras sed felis eget velit aliquet sagittis id consectetur. Nunc scelerisque viverra mauris in aliquam. Vel fringilla est ullamcorper eget nulla facilisi etiam dignissim.'+\n\t\t\t\t\t '</div>'));\n editor = new MediumEditor('.editable', editable_settings);\n }\n else if (cmp === 'rule-cmp') {\n $item.append('<div class=\"ud\"><br><hr><br></div>');\n }\n else if (cmp === 'space-cmp') {\n $item.append('<div class=\"ud space\"></div>');\n }\n else if (cmp === 'quote-cmp') {\n $item.append(\n '<blockquote class=\"ud\">' +\n '<span class=\"editable ud\">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae! Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae!</span>' +\n '<cite class=\"editable ud\">Somebody famous</cite>' +\n '</blockquote>'\n );\n initializeEditable();\n }\n else if (cmp === 'embed-cmp') {\n resetGeneralModal();\n $('#embed-target').removeAttr('id');\n $('#add-general-input').click(addTargetEmbed);\n $('#general-modal .modal-header').text('ADD EMBED HTML CONTENT');\n $('#general-modal').modal('open');\n }\n else if (cmp === 'row-cmp') {\n $item.append(\n '<div class=\"row\">' +\n \t'<div class=\"col s4\">' +\n \t\t'<div class=\"editable\">This a column. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor</div>' +\n \t'</div>' +\n \t'<div class=\"col s4\">' +\n \t\t'<div class=\"editable\">This a column. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor</div>' +\n \t'</div>' +\n \t'<div class=\"col s4\">' +\n \t\t'<div class=\"editable\">This a column. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor</div>' +\n \t'</div>' +\n '</div>'\n );\n initializeEditable();\n }\n console.log('you dropped ' + cmp +' into the page preview!');\n}",
"function drop(e){\r\n \r\n e.preventDefault();\r\n \r\n background_squares_paint(e.target.id.slice(4, 6), type, dir, \"#7e7e08\"); //It restores the original color of the lockers where the ship was dropped.\r\n\r\n if(ship_validation(type, Number(e.target.id.slice(4,6)), dir, own_board)){ //If the new position is validated...\r\n\r\n click_sound.play();\r\n \r\n var id = e.dataTransfer.getData(\"text/plain\");\r\n \r\n e.target.appendChild(document.getElementById(id)); //...the ship image is put on the board...\r\n\r\n switch(id){ //...and the Ship object is added to the user fleet array. Also the corresponding board positions are overwritten with the ship number.\r\n \r\n case \"ca\":\r\n own_fleet[0] = new Ship(5, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 0);\r\n break;\r\n \r\n case \"v1\":\r\n own_fleet[1] = new Ship(4, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 1);\r\n break;\r\n \r\n case \"v2\":\r\n own_fleet[2] = new Ship(4, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 2);\r\n break;\r\n \r\n case \"s1\":\r\n own_fleet[3] = new Ship(3, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 3);\r\n break;\r\n \r\n case \"s2\":\r\n own_fleet[4] = new Ship(3, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 4);\r\n break;\r\n \r\n case \"s3\":\r\n own_fleet[5] = new Ship(3, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 5);\r\n break;\r\n \r\n case \"c1\":\r\n own_fleet[6] = new Ship(2, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 6);\r\n break;\r\n \r\n case \"c2\":\r\n own_fleet[7] = new Ship(2, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 7);\r\n break;\r\n \r\n case \"c3\":\r\n own_fleet[8] = new Ship(2, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 8);\r\n break;\r\n \r\n case \"c4\":\r\n own_fleet[9] = new Ship(2, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 9);\r\n break;\r\n \r\n case \"b1\":\r\n own_fleet[10] = new Ship(1, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 10);\r\n break;\r\n \r\n case \"b2\":\r\n own_fleet[11] = new Ship(1, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 11);\r\n break;\r\n \r\n case \"b3\":\r\n own_fleet[12] = new Ship(1, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 12);\r\n break;\r\n \r\n case \"b4\":\r\n own_fleet[13] = new Ship(1, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 13);\r\n break;\r\n \r\n case \"b5\":\r\n own_fleet[14] = new Ship(1, Number(e.target.id.slice(4,6)), dir);\r\n board_overwrite(own_fleet, 14);\r\n break;\r\n } \r\n }else{ //If the position was not validated, it reports the rejection to the user.\r\n\r\n sign(\"Forbidden place! \\n Please, try again.\");\r\n }\r\n}",
"function dragItem(event){\n draggedItem = whereInLists(event.target);\n draggedItem.list = document.getElementById(draggedItem.list);\n\tevent.dataTransfer.setData('text/html', event.target);\n\tevent.dataTransfer.dropEffect = 'move';\n}",
"function setupIconLibrarySelectionListener() {\n $('li[class^=ion]').click(function(e) {\n var originalElement = e.target;\n var imageName = originalElement.classList[0].slice(4);\n $('#IconLibraryModal').modal('hide');\n generateFlatIconFromImage('/img/ionicons/512/' + imageName + '.png');\n });\n}",
"function drag_start(e){\r\n \r\n e.preventDefault\r\n \r\n//It prepares the image dragged to fit the right size.\r\n dragged_ship.src = e.target.getAttribute(\"src\");\r\n \r\n dragged_ship.className = e.target.className;\r\n \r\n e.dataTransfer.setDragImage(dragged_ship, 15, 15);\r\n \r\n//It stores the dragged ship orientation for the next \"Drag and Drop\" functions.\r\n if(e.target.className == \"vertical\")\r\n dir = 0;\r\n else\r\n dir = 1;\r\n \r\n//It stores the dragged ship type for the next \"Drag and Drop\" functions.\r\n if(e.target.id.startsWith(\"ca\")) \r\n type = 5;\r\n\r\n else if(e.target.id.startsWith(\"v\"))\r\n type = 4;\r\n\r\n else if(e.target.id.startsWith(\"s\"))\r\n type = 3;\r\n\r\n else if(e.target.id.startsWith(\"c\"))\r\n type = 2;\r\n else\r\n type = 1;\r\n \r\n//It set up the Id of event Target as data to be transferred.\r\n e.dataTransfer.setData(\"text/plain\", e.target.id);\r\n \r\n//It cleans the board if the dragged ship still was on it.\r\n if(e.target.parentElement.className == \"square\")\r\n clean_position_ship_draw(e.target, e.target.parentElement.id.slice(4, 6));\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
read course data from Courses.txt and return it as text | readCourseData(){
let url="https://maeyler.github.io/JS/data/Courses.txt";
fetch(url)
.then(res => res.text())
.then(res => this.addCoursesToMap(res,this.courses));
} | [
"readText() {\n const filePath = this._fullname;\n const text = fs.readFileSync(filePath, 'utf-8');\n return text;\n }",
"createCourse(txtLine){\r\n let words = txtLine.split(\"\\t\");\r\n let course;\r\n course = new Course(words[0], words[1], words[2], words.slice(3));\r\n return course;\r\n }",
"function getCourses(filePath) {\n return new Promise((resolve, reject) => {\n fs.readFile(filePath, 'utf8', (err, fileContents) => {\n if (err) {\n console.error(err);\n return reject(err);\n }\n /* Use d3.dsv to turn the CSV file into an array of objects */\n var csvArray = d3.csvParse(fileContents);\n\n /* Retrieve the courses' ids and names from the CSV */\n var courses = csvArray.map(csv => {\n return {\n id: csv.id, // expecting an id column in the CSV\n name: csv.name // expecting a name column in the CSV\n }\n });\n /* Return the courses from the csv */\n resolve(courses);\n });\n });\n}",
"addCoursesToMap(txt,courses){\r\n \tlet lines = txt.split(\"\\n\");//split the text of Courses.txt line by line\r\n\t\tfor(let line of lines) {\r\n\t\tlet course = this.createCourse(line);\r\n\t\tcourses.set(course.name,course);\r\n }\r\n\t}",
"function read_text_file_data(file) {\n var rawFile = new XMLHttpRequest();\n rawFile.open(\"GET\", file, false);\n rawFile.onreadystatechange = function() {\n if (rawFile.readyState === 4) {\n if (rawFile.status === 200 || rawFile.status == 0) {\n raw_text_file_data = rawFile.responseText;\n }\n }\n }\n rawFile.send(null);\n}",
"function readTextFile(file) {\r\n var rawFile = new XMLHttpRequest();\r\n rawFile.open(\"GET\", file, false);\r\n rawFile.onreadystatechange = function ()\r\n {\r\n if(rawFile.readyState === 4)\r\n {\r\n if(rawFile.status === 200 || rawFile.status == 0)\r\n {\r\n var allText = rawFile.responseText.split('\\n');\r\n document.getElementById(\"tmr\").innerHTML = allText[0];\r\n document.getElementById(\"chance\").innerHTML = allText[1];\r\n document.getElementById(\"weather\").innerHTML = allText[2];\r\n document.getElementById(\"equip\").innerHTML = allText[3];\r\n }\r\n }\r\n }\r\n rawFile.send(null);\r\n}",
"function readSubtitle(path) {\n return new Promise((resolve, reject) => {\n fs.readFile(path, 'utf-8', function (err,data) {\n if (err) {\n console.error(err);\n reject();\n }\n resolve(data);\n });\n });\n}",
"function loadFileAsText() {\n\tvar fileToLoad = document.getElementById(\"fileToLoad\").files[0];\n\tvar textFromFileLoaded = \"\";\n\tvar fileReader = new FileReader();\n\tfileReader.onload = function(fileLoadedEvent) {\n\t\ttextFromFileLoaded = fileLoadedEvent.target.result;\n\t\tdocument.getElementById(\"inputTextToSave\").value = fileLoadedEvent.target.result;\n\t\tparseFile(textFromFileLoaded)\n\t\tsetCharacterInfo(fileInfo.character.class_name.toLowerCase())\n\t};\n\tfileReader.readAsText(fileToLoad, \"UTF-8\");\n}",
"async function getTextFromSource(){\n let text;\n if (process.argv[2] === 'file') {\n let filePath = process.argv[3];\n text = await cat(filePath);\n }\n else if (process.argv[2] === 'url') {\n let url = process.argv[3];\n text = await webCat(url);\n }\n else {\n console.error(`Bad input. Please try again.\n * Example: $ node makeText.js file eggs.txt\n * Example2: $ node makeText.js url http://www.gutenberg.org/files/11/11-0.txt`);\n process.exit(1);\n }\n return text;\n}",
"readStudentData(){\r\n let url=\"https://maeyler.github.io/JS/data/Students.txt\";\r\n fetch(url)\r\n .then(res => res.text())\r\n .then(res => this.addStudentsToMap(res,this.students));\r\n }",
"function readRomanTxtFile() {\r\n var request = require('request');\r\n var url = \"https://projecteuler.net/project/resources/p089_roman.txt\";\r\n return new Promise(function (resolve, reject) {\r\n request.get(url, function (error, response, body) {\r\n if (response.statusCode === 200) {\r\n resolve(response.body);\r\n } else {\r\n reject(error);\r\n }\r\n\r\n });\r\n });\r\n}",
"retrieveCourse (id) {\n return apiClient.retrieveCourse(id)\n }",
"createStudent(txtLine){\r\n let words = txtLine.split(\"\\t\");\r\n let student;\r\n let studentCourseList = this.findStudentCourses(words.slice(3));\r\n student = new Student(words[0], words[1], words[2], studentCourseList);\r\n return student;\r\n }",
"static async getCourseById(id) {\n const coursesData = await CourseModel.getAllCourses();\n let course = null;\n if(coursesData.length){\n course = coursesData.find(item => item.id === id);\n }\n return course;\n }",
"getCourseInfoById(id) {\n return request({\n url: `${API_NAME}/${id}`,\n method: 'get'\n })\n }",
"list(languageId) {\r\n const path = `courses/${languageId}`;\r\n return this._call(\"get\", path, undefined);\r\n }",
"function listCourses() {\n gapi.client.classroom.courses.list({\n pageSize: 10\n }).then(function(response) {\n var courses = response.result.courses;\n appendPre('Courses:');\n\n if (courses.length > 0) {\n for (i = 0; i < courses.length; i++) {\n var course = courses[i];\n appendPre(course.name)\n }\n } else {\n appendPre('No courses found.');\n }\n });\n}",
"function fetchAllCoursesAndStoreInDataBase() {\n fetch(\"http://courses.rice.edu/admweb/!SWKSECX.main?term=202020\")\n .then(handleErrors)\n .then((resp) => resp.text()) // Transform the data into text\n .then(xmlString => $.parseXML(xmlString))\n .then(function(data) {\n // console.log(data);\n \n var $data = $(data);\n var $course = $data.find(\"course\");\n \n \n //open transaction, read-write to update any old entries\n db.transaction('rw', db.courses, () => {\n \n //refresh all courses\n db.courses.clear().then(function() {\n $course.each(function() {\n \n var SUBJ = $(this).find(\"subject\").text();\n var NUMB = $(this).find(\"course-number\").text();\n var TITLE = $(this).find(\"title\").text();\n var CRN = $(this).find(\"crn\").text();\n var INSTRUCTOR = $(this).find(\"instructor\").text();\n var DESCRIPTION = $(this).find(\"description\").text();\n var CREDIT_HRS = $(this).find(\"credit-hours\").text();\n var PREREQS = $(this).find(\"pre-requisites\").text();\n var DISTRIBUTION = $(this).find(\"distribution-group\").text();\n var START_TIMES = $(this).find(\"start-time\").text();\n var END_TIMES = $(this).find(\"end-time\").text();\n var MEET_DAYS = $(this).find(\"meeting-days\").text();\n var MAX_ENROLLMENT = $(this).find(\"max-enrollment\").text();\n var ACTUAL_ENROLLMENT = $(this).find(\"actual-enrollment\").text();\n \n var courseObj = {\n crn: CRN,\n subject : SUBJ,\n number : NUMB,\n title : TITLE,\n instructor : INSTRUCTOR,\n description : DESCRIPTION,\n distribution : DISTRIBUTION,\n prereqs : PREREQS,\n credit_hrs: CREDIT_HRS,\n start_times: START_TIMES,\n end_times : END_TIMES,\n meet_days : MEET_DAYS,\n enrollment: ACTUAL_ENROLLMENT + \"/\" + MAX_ENROLLMENT\n };\n \n \n db.courses.put(courseObj);\n \n \n \n });\n });\n\n });\n \n \n });\n }",
"function getWords() {\n fs.readFile(\"./words.txt\", \"utf8\", function(error, data) {\n if (error) {\n console.log(error);\n } else {\n var wordArray = data.split(\"\\n\");\n // do something after creating wordArray\n pickWord(wordArray);\n }\n })\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a string like ($1, $2, $3, $4...) | function createValueString(fields) {
const valueString = Object.values(fields).map( (_, index) => `$${index + 1}` ).join(', ');
return valueString;
} | [
"function buildString() {\n var outString = arguments[0];\n for(var i = 1; i < arguments.length; i++) {\n outString = outString.replace(new RegExp(\"\\\\$\\\\[\" + i + \"\\\\]\", \"g\"), arguments[i]);\n }\n return outString;\n }",
"function CONCATENATE() {\n for (var _len4 = arguments.length, values = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n values[_key4] = arguments[_key4];\n }\n\n // Combine into a single string value\n return values.reduce(function (acc, item) {\n return \"\" + acc + item;\n });\n}",
"function format(string, vars) {\n\tif (vars) {\n\t\tfor (var k in vars) {\n\t\t\tstring = string.replace(new RegExp('\\\\{' + k + '\\\\}', 'g'), vars[k]);\n\t\t}\n\t}\n\treturn string;\n}",
"function echoTag(literals, ...substitutions) {\n let result = \"\";\n for (let i = 0; i < substitutions.length; i++) {\n result += literals[i];\n result += substitutions[i];\n }\n // add the last literal.\n result += literals[literals.length - 1];\n return result\n }",
"function echoReduce(strings, ...values) {\n // console.log(`Strings len=${strings.length} Values len=${values.length}`);\n // console.log(strings);\n // console.log(values);\n return strings.reduce((fullStr, value, idx) => {\n return `${fullStr}${idx > 0 ? values[idx - 1] : \"\"}${value}`\n });\n }",
"function string(n){\n \tvar i =0;\n \twhile(i<n){\n i++; \n \t return i,\" \",n;\n \t}\n\n }",
"function formatParameters() {\n if (!this.params) return '';\n return '(' + this.params.map(function (param) {\n return formatParameter(param);\n }).join(', ') + ')';\n}",
"function threeStrings(x,y,z) {\n return x + \" \" + y + \" \" + z;\n}",
"function makeExerciseSqlStr(exercisesValuesArr) {\n let finalStr = \"\";\n for (let c in exercisesValuesArr) {\n if (c < exercisesValuesArr.length -1) {\n finalStr = finalStr + makeStr(exercisesValuesArr[c]) + ','}\n else {\n finalStr = finalStr + makeStr(exercisesValuesArr[c])\n }\n }\nreturn finalStr\n}",
"function ego (...s) {\n return `__egolatron_${s.join('')}__`\n }",
"function sc_stringAppend() {\n for (var i = 0; i < arguments.length; i++)\n\targuments[i] = arguments[i].val;\n return new sc_String(\"\".concat.apply(\"\", arguments));\n}",
"function createString(number,letter){\n let result = \"\"\n for (let i=0; i<number; i++){\n result +=letter\n }\n return result\n}",
"function strConvert() {\n let result = \"\";\n for (let i = 0; i < 4; i++) {\n result += randCombo[i];\n\n }\n return result;\n }",
"function strOfProducts(list) {\n var txt = '';\n for (var i = 0; i < list.length; i++) {\n if (i == 0) {\n txt = ProductMgr.getProduct(list[i].ID).name;\n } else {\n txt += ', ' + ProductMgr.getProduct(list[i].ID).name;\n }\n }\n return txt;\n}",
"function concat(string, n) {\n n = n || 1;\n var con = '';\n for (var i = 0; i < n; i++) {\n con += string;\n }\n return con;\n}",
"function concatName(firstName, lastName) {\n\treturn lastName + \", \" + firstName;\n}",
"function generateNotificationString(invitedName, pageName){\n return (invitedName + \",\" + pageName);\n }",
"function callString(method) {\n var params = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n params[_i - 1] = arguments[_i];\n }\n var s = method + \"(\";\n s += paramsString(params);\n s += \")\";\n return s;\n}",
"function construct_phrase()\n{\n\tif (!arguments || arguments.length < 1 || !is_regexp)\n\t{\n\t\treturn false;\n\t}\n\n\tvar args = arguments;\n\tvar str = args[0];\n\tvar re;\n\n\tfor (var i = 1; i < args.length; i++)\n\t{\n\t\tre = new RegExp(\"%\" + i + \"\\\\$s\", \"gi\");\n\t\tstr = str.replace(re, args[i]);\n\t}\n\treturn str;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function GetWindowHeight return the client browser height modified by : Manish Sharma modified on : 10032009 | function GetWindowHeight() {
//return window.innerHeight||
//document.documentElement&&document.documentElement.clientHeight||
//document.body.clientHeight||0;
var windowHeight = 0;
if (typeof(window.innerHeight) == 'number') {
windowHeight = window.innerHeight;
}
else {
if (document.documentElement && document.documentElement.clientHeight) {
windowHeight = document.documentElement.clientHeight;
}
else {
if (document.body && document.body.clientHeight) {
windowHeight = document.body.clientHeight;
}
}
}
return windowHeight;
} | [
"getGameHeight() {\n return this.scene.sys.game.config.height;\n }",
"function windowDimensions(){\n\tvar win = window;\n\twin.height = $(window).height();\n\twin.width = $(window).width();\n\treturn win;\n}",
"_calculateHeight() {\n\t\tif (this.options.height) {\n\t\t\treturn this.jumper.evaluate(this.options.height, { '%': this.jumper.getAvailableHeight() });\n\t\t}\n\n\t\treturn this.naturalHeight() + (this.hasScrollBarX() ? 1 : 0);\n\t}",
"function get_actual_scroll_distance() {\n return $document.innerHeight() - $window.height();\n }",
"function height() {\n return gl.drawingBufferHeight / scale();\n }",
"function resizeWindow () {\n\t\tparent.postMessage($('body').height(), '*');\n\t}",
"function calcScrollValues() {\n\t\twindowHeight = $(window).height();\n\t\twindowScrollPosTop = $(window).scrollTop();\n\t\twindowScrollPosBottom = windowHeight + windowScrollPosTop;\n\t} // end calcScrollValues",
"setHeight() {\n this.$().outerHeight(this.$(window).height() - this.get('fixedHeight'));\n }",
"function vh(v) {\n let h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);\n return (v * h) / 100;\n}",
"function GetWindowSize(out = new ImVec2()) {\r\n return bind.GetWindowSize(out);\r\n }",
"static getMaxHeight() { \n var result = Math.max(MainUtil.findAllRooms().map(room => (room.memory.console && room.memory.console.height)));\n return result || 10;\n }",
"function getheight(){\n var ff = (navigator.userAgent.toLowerCase().indexOf('firefox') != -1);\n var NS = (navigator.userAgent.toLowerCase().indexOf('netscape') != -1);\n var IE = (navigator.userAgent.toLowerCase().indexOf('msie') != -1);\n if(isgE('MET_MediaModule_Half')) \n {\n var height_SpLogo=0;\n var height_adser=0;\n var margincount=0;\n var height_MMhalf=document.getElementById('MET_MediaModule_Half').offsetHeight;\n if(isgE('MET_Adser300x250')){\n var height_adser=document.getElementById('MET_Adser300x250').offsetHeight;\n if (IE){\n margincount=margincount-19\n }\n }\n if(isgE('MET_sponserLogo') && !(isgE('MET_Adser300x250'))){\n height_SpLogo=document.getElementById('MET_sponserLogo').offsetHeight;\n if (ff || NS){\n margincount=margincount+8\n }\n else {\n margincount=margincount+0\n }\n }\n if(isgE('MET_sponserLogo') && isgE('MET_Adser300x250')){\n height_SpLogo=document.getElementById('MET_sponserLogo').offsetHeight;\n if (ff || NS){\n margincount=margincount+16\n }\n else {\n margincount=margincount+8\n }\n }\n if(!(isgE('MET_sponserLogo')) && !(isgE('MET_Adser300x250'))){\n margincount=margincount-16\n }\n var variableHeight = height_SpLogo+height_adser+margincount;\n if (height_MMhalf>=variableHeight)\n {\n \n var Margin_TowerAd= -(height_MMhalf-variableHeight);\n if(document.getElementById('MET_RightTowerAd_float2')){\n document.getElementById('MET_RightTowerAd_float2').style.marginTop = Margin_TowerAd+\"px\";\n }\n else if(document.getElementById('MET_RightTowerAd_float1')){\n document.getElementById('MET_RightTowerAd_float1').style.marginTop = Margin_TowerAd+\"px\";\n }\n }\n \n if(document.getElementById('MET_RightTowerAd_float2')){\n document.getElementById('MET_RightTowerAd_float2').style.visibility = \"visible\";\n }\n else if(document.getElementById('MET_RightTowerAd_float1')){\n document.getElementById('MET_RightTowerAd_float1').style.visibility = \"visible\";\n }\n\n } \n if(isgE('MET_MediaModule_Full')){ \n var height_SpLogo=document.getElementById('MET_sponserLogo_MMFull').offsetHeight;\n var height_MMfull=document.getElementById('MET_MediaModule_Full').offsetHeight;\n var margintop_SLogo;\n if(isgE('sponsorbyText')) {\n margintop_SLogo = 34 \n }\n else {\n margintop_SLogo = 24\n }\n var Top_SponsorLogo = (height_MMfull-margintop_SLogo);\n if (is.isIE){\n document.getElementById('MET_sponserLogo_MMFull').style.marginTop = -(Top_SponsorLogo+7)+\"px\";\n document.getElementById('MET_sponserLogo_MMFull').style.marginBottom = (Top_SponsorLogo-7)+\"px\";\n }\n else{\n document.getElementById('MET_sponserLogo_MMFull').style.position = \"relative\";\n document.getElementById('MET_sponserLogo_MMFull').style.marginTop = -(Top_SponsorLogo)+\"px\";\n document.getElementById('MET_sponserLogo_MMFull').style.marginBottom = (Top_SponsorLogo)+\"px\";\n } \n document.getElementById('MET_sponserLogo_MMFull').style.visibility = \"visible\";\n\n \n } \n}",
"function getScreenHeight(percentage = 100) {\r\n return screenHeight * (percentage / 100);\r\n}",
"function getHeight() {\n return 2;\n }",
"function getBleedHeightInPx() {\n // Creating temporary div with height set in mm and appending it to body\n const tempBleedDiv = document.createElement('div');\n tempBleedDiv.style.height = '8.82mm';\n document.body.appendChild(tempBleedDiv);\n \n // Getting new element's height in px and putting it in a variable\n const bleedHeightInPx = tempBleedDiv.offsetHeight;\n \n // Removing temporary div from the div as we no longer need it\n tempBleedDiv.remove();\n \n // Returning the value in px\n return bleedHeightInPx;\n }",
"function GetHeaderHeight() {\n var styleSheetName = SiebelApp.S_App.GetStyleSheetName();\n var headerheight = utils.GetstyleSheetPropVal(styleSheetName, \".siebui .ListAppletHeader\", \"height\");\n\n return headerheight || siebConsts.get(\"DFLT_HEADHGT\");\n }",
"function getHeight() {\n return maxy + 1;\n }",
"function heightFullscreen() {\n if ($('#jarviswidget-fullscreen-mode').length) {\n\n /**\t\t\t\t\t\t\n * Setting height variables.\n **/\n var heightWindow = $(window).height();\n var heightHeader = $('#jarviswidget-fullscreen-mode').find(self.o.widgets).children(\n 'header').height();\n\n /**\t\t\t\t\t\t\n * Setting the height to the right widget.\n **/\n $('#jarviswidget-fullscreen-mode')\n .find(self.o.widgets)\n .children('div')\n .height(heightWindow - heightHeader - 15);\n }\n }",
"function getWindowAdjustedDivDimensions() {\n\t \tvar height = window.innerHeight,\n\t\t\twidth = window.innerWidth,\n\t\t\tdiv_height,\n\t\t\tdiv_width,\n\t\t\tMIN_WINDOW_HEIGHT = 574,\n\t\t\tMIN_WINDOW_WIDTH = 750;\n\n\t\t// restrict map from resizing to a size smaller than its\n\t\t// minimum-allowed size\n\t\tif(height < MIN_WINDOW_HEIGHT && width < MIN_WINDOW_WIDTH) {\n\t\t\theight = MIN_WINDOW_HEIGHT;\n\t\t\twidth = MIN_WINDOW_WIDTH;\n\t\t} else if (height < MIN_WINDOW_HEIGHT) {\n\t\t\theight = MIN_WINDOW_HEIGHT;\n\t\t} else if (width < MIN_WINDOW_WIDTH) {\n\t\t\twidth = MIN_WINDOW_WIDTH;\n\t\t}\n\t\t\n\t\t// calculates new dimensions of divs to fit window size while\n\t\t// maintaining aspect ratio; aspect ratio is determined\n\t\t// by original basemap image size\n\t\tif(width/height > MAP_WIDTH/MAP_HEIGHT) {\n\t\t\tdiv_height = height;\n\t\t\tdiv_width = div_height*MAP_WIDTH/MAP_HEIGHT;\n\t\t} else {\n\t\t\tdiv_width = width;\n\t\t\tdiv_height = div_width*MAP_HEIGHT/MAP_WIDTH;\n\t\t}\n\n\t\treturn [div_width,div_height];\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the weight of a 23 bit codeword. | function weight(cw) {
return w[cw & 0xf] + w[(cw >> 4) & 0xf] + w[(cw >> 8) & 0xf] +
w[(cw >> 12) & 0xf] + w[(cw >> 16) & 0xf] + w[(cw >> 20) & 0xf];
} | [
"function extUtils_getWeightNum(weight)\n{\n if (typeof weight == \"string\")\n {\n var pos = weight.indexOf(\"+\");\n weight = parseInt((pos > 0)? weight.substring(pos+1) : weight);\n }\n\n return weight;\n}",
"function hammingWeight(x){\n return x.toString(2).split('').filter(e => e === '1').length;\n}",
"function weight(keywords, obj, fields, weights) {\n var value = 0;\n parseKeywords(keywords).forEach(function(keyword) {\n var pattern = new RegExp(keyword, \"img\"); // Global, Multi-line, Case-insensitive\n fields.forEach(function(field, index) {\n if (obj.hasOwnProperty(field)) {\n var matches = obj[field].match(pattern);\n value += matches ? matches.length * weights[index] : 0;\n }\n });\n });\n return value;\n }",
"function GToKG(weight) {\n if (weight === null) return null;\n else if (weight.includes('кг')) return weight.substring(0, weight.length - 3).match(/\\d+/gm)[0];\n else return weight.substring(0, weight.length - 2).match(/\\d+/gm)[0]/1000;\n}",
"getWeight() {\r\n let pounds = this.weight * 2.205;\r\n let weight = Math.round(pounds * 10) / 100;\r\n return `${weight} lbs.`;\r\n }",
"function inWord(bit) {\n return Math.floor((bit | 0) / 32);\n }",
"function bmi(weight,height){\n\n if((weight / (height ** 2)) <= 18.5){\n return `Underweight`\n }\n if((weight / (height ** 2)) <= 25.0){\n return `Normal`\n }\n if((weight / (height ** 2)) <= 30.0){\n return `Overweight`\n }\n if((weight / (height ** 2)) > 30){\n return `Obese`\n }\n}",
"static bytes23(v) { return b(v, 23); }",
"static bytes21(v) { return b(v, 21); }",
"function extPart_getWeight(partName, theNode)\n{\n //get the weight information\n var retVal = extPart.getLocation(partName);\n\n //if the insert weight is nodeAttribute, add the position of the matched string\n if (retVal == \"nodeAttribute\")\n {\n //get the node string\n var nodeStr = extUtils.convertNodeToString(theNode);\n\n var foundPos = extUtils.findPatternsInString(nodeStr, extPart.getQuickSearch(partName),\n extPart.getSearchPatterns(partName));\n\n if (foundPos)\n {\n retVal += \"+\" + foundPos[0] + \",\" + foundPos[1];\n }\n }\n\n return retVal;\n}",
"function ComputeWeightFromVolumeAndType(weightOutput, volumeInput, typeInput) {\n LinEqComputeYfromMandX.call(this, weightOutput, volumeInput, typeInput);\n}",
"function dynamicProgramming(shop, weight) {\n if (shop.length < 1 || weight < 1) return 0\n const table = [...Array(shop.length)].map(e => Array(weight + 1).fill(0))\n // for 0 weight capacity, the max value we can get is always 0\n for (let i = 0; i < shop.length; i++) {\n table[i][0] = 0\n }\n // if there's only 1 item, then it's just a matter of whether the capacity weight\n // can pick this item\n for (let i = 0; i < table[0].length; i++) {\n if (i < shop[0].weight) {\n table[0][i] = 0\n } else {\n table[0][i] = shop[0].value\n }\n \n }\n for (let row = 1; row < table.length; row++) {\n for (col = 1; col < table[row].length; col++) {\n if (col < shop[row].weight) {\n table[row][col] = table[row-1][col]\n } else {\n table[row][col] = Math.max(\n table[row-1][col],\n table[row-1][col - shop[row].weight] + shop[row].value\n )\n }\n }\n }\n return table[table.length-1][table[0].length-1]\n}",
"static bytes26(v) { return b(v, 26); }",
"static bytes22(v) { return b(v, 22); }",
"crotonWeight(state) {\n var crotonWeight = 0;\n for (var i = 0; i < state.recordsList.length; i++) {\n if (state.recordsList[i].reservoir === \"Croton\") {\n var weight = state.recordsList[i].weight;\n crotonWeight += weight;\n }\n }\n return crotonWeight;\n }",
"static bytes18(v) { return b(v, 18); }",
"static bytes17(v) { return b(v, 17); }",
"function getHashDifficulty(hash) {\n let difficulty = 0\n\n for (let i = 0; i < hash.length; i++) {\n if (hash[i] === 0) {\n difficulty += 8\n continue\n } else if (hash[i] === 1) {\n difficulty += 7\n } else if (hash[i] < 4) {\n difficulty += 6\n } else if (hash[i] < 8) {\n difficulty += 5\n } else if (hash[i] < 16) {\n difficulty += 4\n } else if (hash[i] < 32) {\n difficulty += 3\n } else if (hash[i] < 64) {\n difficulty += 2\n } else if (hash[i] < 128) {\n difficulty += 1\n }\n break\n }\n\n return difficulty\n}",
"static bytes11(v) { return b(v, 11); }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function adjusts the audio and cc_streaminfo elements to match the selected station. It must be called before the js from thassos is loaded. | function chooseStation() {
var stationId = window.location.hash.substr(1);
if (!stationId) {
// this is the default if none selected
stationId = 'nac_radio';
}
var station = STATIONS[stationId];
var streamId = station.streamId;
var url = station.url;
var logo = station.logo;
$('.cc_streaminfo').each(function(idx, elem) {
// add the selected streamId onto .cc_streaminfo element IDs,
// e.g. cc_strinfo_title => cc_strinfo_title_nundahac
elem = $(elem);
elem.attr('id', elem.attr('id') + '_' + streamId);
});
$('#radio').attr('src', url);
$('.radiologo img').attr('src',logo);
} | [
"function chooseStation() {\n var stationId = window.location.hash.substr(1);\n\n if (!stationId) {\n // this is the default if none selected\n stationId = 'nac_radio';\n }\n\n var station = STATIONS[stationId];\n var streamId = station.streamId;\n var url = station.url;\n var logo = station.logo;\n\n $('.cc_streaminfo').each(function (idx, elem) {\n // add the selected streamId onto .cc_streaminfo element IDs,\n // e.g. cc_strinfo_title => cc_strinfo_title_nundahac\n elem = $(elem);\n elem.attr('id', elem.attr('id') + '_' + streamId);\n });\n $('#radio').attr('src', url);\n $('.radiologo img').attr('src', logo);\n}",
"function updateCurrSongDiv(song){\n let currTitle = document.getElementById('curr-playing-song-title')\n let currArtist = document.getElementById('curr-playing-song-artist')\n let currImg = document.getElementById('curr-playing-song-img')\n let currSongData = document.getElementById('curr-song-audio-control-con').dataset\n let currSongAudio = document.querySelector('.curr-audio')\n let currHeart = document.getElementById('curr-song-heart')\n\n currTitle.innerText = song.title\n currArtist.innerText = song.artist\n currImg.src = song.img\n currSongData.songid = song.id\n currSongData.songidx = song.idx\n //pll = playlist length\n currSongData.pll = song.pll\n currSongAudio.id = song.id\n currSongAudio.src = `../static/audio/${song.file}`\n currHeart.src = \"../static/img/heart1.png\" \n}",
"_initAudioParams() {\n this.pan = this.audioComponents.channelStrip.pan;\n this.gain = this.audioComponents.channelStrip.outputGain;\n // TODO: can also expose frequency as frequency of first overtone?\n }",
"function setPlaybackSource() {\n var activePlayer = GUI.libraryhome.ActivePlayer;\n // update the playback section\n $('#overlay-playsource-open button').text(activePlayer);\n $('#overlay-playsource a').addClass('inactive');\n var source = activePlayer.toLowerCase();\n $('#playsource-' + source).removeClass('inactive');\n // update volume knob and control buttons\n if (activePlayer === 'Spotify' || activePlayer === 'Airplay') {\n $('#volume').trigger('configure', {'readOnly': true, 'fgColor': '#1A242F'}).css({'color': '#1A242F'});\n $('#volume-knob').addClass('nomixer');\n $('#volume-knob button').prop('disabled', true);\n $('#single').addClass('disabled');\n } else {\n $('#volume').trigger('configure', {'readOnly': false, 'fgColor': '#0095D8'}).css({'color': '#0095D8'});\n $('#volume-knob').removeClass('nomixer');\n $('#volume-knob button').prop('disabled', false);\n $('#single').removeClass('disabled');\n }\n // style the queue\n $('#playlist-entries').removeClass(function(index, css) {\n return (css.match (/(^|\\s)playlist-\\S+/g) || []).join(' ');\n }).addClass('playlist-' + source);\n // toggle queue buttons\n $('#pl-manage').removeClass(function(index, css) {\n return (css.match (/(^|\\s)pl-manage-\\S+/g) || []).join(' ');\n }).addClass('pl-manage-' + source);\n}",
"function updatePrevSongDiv(prevSong){\n let prevTitle = document.getElementById('prev-playing-song-title')\n let prevArtist = document.getElementById('prev-playing-song-artist')\n let prevImg = document.getElementById('prev-playing-song-img')\n let prevSongData = document.getElementById('prev-playing-con').dataset\n let prevSongAudio = document.querySelector('.prev-audio')\n let prevHeart = document.getElementById('prev-song-heart')\n let nextDuration = document.getElementById('prev-playing-con').dataset\n\n prevTitle.innerText = prevSong.title\n prevArtist.innerText = prevSong.artist\n prevImg.src = prevSong.img\n prevSongData.songid = prevSong.id\n prevSongData.songidx = prevSong.idx\n prevSongData.pll = prevSong.pll\n nextDuration.duration = prevSong.duration\n prevSongAudio.id = prevSong.id\n prevSongAudio.src = `../static/audio/${prevSong.file}`\n prevHeart.src = \"../static/img/heart1.png\"\n}",
"function updateNextSongDiv(nextSong){\n let nextTitle = document.getElementById('next-playing-song-title')\n let nextArtist = document.getElementById('next-playing-song-artist')\n let nextImg = document.getElementById('next-playing-song-img')\n let nextSongData = document.getElementById('next-playing-con').dataset\n let nextSongAudio = document.querySelector('.next-audio')\n let nextHeart = document.getElementById('next-song-heart')\n let nextDuration = document.getElementById('next-playing-con').dataset \n \n nextTitle.innerText = nextSong.title\n nextArtist.innerText = nextSong.artist\n nextImg.src = nextSong.img\n nextSongData.songid = nextSong.id\n nextSongData.songidx = nextSong.idx\n nextSongData.pll = nextSong.pll\n nextDuration.duration = nextSong.duration\n nextSongAudio.id = nextSong.id\n nextSongAudio.src = `../static/audio/${nextSong.file}`\n nextHeart.src = \"../static/img/heart1.png\"\n}",
"function privateDisplaySongMetadata(){\n\t\t/*\n\t\t\tSets all elements that will contain the active song's name metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"name\"]') ){\n\t\t\tvar metaNames = document.querySelectorAll('[amplitude-song-info=\"name\"]');\n\t\t\tfor( i = 0; i < metaNames.length; i++ ){\n\t\t\t\tmetaNames[i].innerHTML = config.active_metadata.name;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tSets all elements that will contain the active song's artist metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"artist\"]') ){\n\t\t\tvar metaArtist = document.querySelectorAll('[amplitude-song-info=\"artist\"]');\n\t\t\tfor( i = 0; i < metaArtist.length; i++ ){\n\t\t\t\tmetaArtist[i].innerHTML = config.active_metadata.artist;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tSets all elements that will contain the active song's album metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"album\"]') ){\n\t\t\tvar metaAlbum = document.querySelectorAll('[amplitude-song-info=\"album\"]');\n\t\t\tfor( i = 0; i < metaAlbum.length; i++ ){\n\t\t\t\tmetaAlbum[i].innerHTML = config.active_metadata.album;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tSets all elements that will contain the active song's cover art metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"cover\"]') ){\n\t\t\tvar coverImages = document.querySelectorAll('[amplitude-song-info=\"cover\"]');\n\t\t\tfor( i = 0; i < coverImages.length; i++ ){\n\t\t\t\t/*\n\t\t\t\t\tChecks to see if first, the song has a defined cover art and uses\n\t\t\t\t\tthat. If it does NOT have defined cover art, checks to see if there\n\t\t\t\t\tis a default. Otherwise it just sets the src to '';\n\t\t\t\t*/\n\t\t\t\tif( config.active_metadata.cover_art_url != undefined){\n\t\t\t\t\tcoverImages[i].setAttribute('src', config.active_metadata.cover_art_url);\n\t\t\t\t}else if( config.default_album_art != '' ){\n\t\t\t\t\tcoverImages[i].setAttribute('src', config.default_album_art);\n\t\t\t\t}else{\n\t\t\t\t\tcoverImages[i].setAttribute('src', '');\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\t/*\n\t\t\tStation information for live streams\n\t\t*/\n\n\t\t/*\n\t\t\tSets all of the elements that will contain the live stream's call sign metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"call-sign\"]') ){\n\t\t\tvar metaCallSign = document.querySelectorAll('[amplitude-song-info=\"call-sign\"]');\n\t\t\tfor( i = 0; i < metaCallSign.length; i++ ){\n\t\t\t\tmetaCallSign[i].innerHTML = config.active_metadata.call_sign;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tSets all of the elements that will contain the live stream's station name metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"station-name\"]') ){\n\t\t\tvar metaStationName = document.querySelectorAll('[amplitude-song-info=\"station-name\"]');\n\t\t\tfor( i = 0; i < metaStationName.length; i++ ){\n\t\t\t\tmetaStationName[i].innerHTML = config.active_metadata.station_name;\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tSets all of the elements that will contain the live stream's location metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"location\"]') ){\n\t\t\tvar metaStationLocation = document.querySelectorAll('[amplitude-song-info=\"location\"]');\n\t\t\tfor( i = 0; i < metaStationLocation.length; i++ ){\n\t\t\t\tmetaStationLocation[i].innerHTML = config.active_metadata.location; \n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t\tSets all of the elements that will contain the live stream's frequency metadata\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"frequency\"]') ){\n\t\t\tvar metaStationFrequency = document.querySelectorAll('[amplitude-song-info=\"frequency\"]');\n\t\t\tfor( i = 0; i < metaStationFrequency.length; i++ ){\n\t\t\t\tmetaStationFrequency[i].innerHTML = config.active_metadata.frequency;\n\t\t\t}\t\n\t\t}\n\n\t\t/*\n\t\t\tSets all of the elements that will contain the live stream's station art metadata\n\t\t\tTODO: Rename coverImages to stationArtImages\n\t\t*/\n\t\tif( document.querySelectorAll('[amplitude-song-info=\"station-art\"]') ){\n\t\t\tvar coverImages = document.querySelectorAll('[amplitude-song-info=\"station-art\"]');\n\t\t\t/*\n\t\t\t\t\tChecks to see if first, the song has a defined station art and uses\n\t\t\t\t\tthat. If it does NOT have defined station art, checks to see if there\n\t\t\t\t\tis a default. Otherwise it just sets the src to '';\n\t\t\t\t*/\n\t\t\tfor( i = 0; i < coverImages.length; i++ ){\n\t\t\t\tif( config.active_metadata.cover_art_url != undefined){\n\t\t\t\t\tcoverImages[i].setAttribute('src', config.active_metadata.station_art_url);\n\t\t\t\t}else if( config.default_album_art != '' ){\n\t\t\t\t\tcoverImages[i].setAttribute('src', config.default_album_art);\n\t\t\t\t}else{\n\t\t\t\t\tcoverImages[i].setAttribute('src', '');\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\t}",
"selectPlaylist() {\n let effectiveBitrate;\n let sortedPlaylists = this.playlists.master.playlists.slice();\n let bandwidthPlaylists = [];\n let now = +new Date();\n let i;\n let variant;\n let bandwidthBestVariant;\n let resolutionPlusOne;\n let resolutionPlusOneAttribute;\n let resolutionBestVariant;\n let width;\n let height;\n\n sortedPlaylists.sort(Hls.comparePlaylistBandwidth);\n\n // filter out any playlists that have been excluded due to\n // incompatible configurations or playback errors\n sortedPlaylists = sortedPlaylists.filter((localVariant) => {\n if (typeof localVariant.excludeUntil !== 'undefined') {\n return now >= localVariant.excludeUntil;\n }\n return true;\n });\n\n // filter out any variant that has greater effective bitrate\n // than the current estimated bandwidth\n i = sortedPlaylists.length;\n while (i--) {\n variant = sortedPlaylists[i];\n\n // ignore playlists without bandwidth information\n if (!variant.attributes || !variant.attributes.BANDWIDTH) {\n continue;\n }\n\n effectiveBitrate = variant.attributes.BANDWIDTH * bandwidthVariance;\n\n if (effectiveBitrate < this.bandwidth) {\n bandwidthPlaylists.push(variant);\n\n // since the playlists are sorted in ascending order by\n // bandwidth, the first viable variant is the best\n if (!bandwidthBestVariant) {\n bandwidthBestVariant = variant;\n }\n }\n }\n\n i = bandwidthPlaylists.length;\n\n // sort variants by resolution\n bandwidthPlaylists.sort(Hls.comparePlaylistResolution);\n\n // forget our old variant from above,\n // or we might choose that in high-bandwidth scenarios\n // (this could be the lowest bitrate rendition as we go through all of them above)\n variant = null;\n\n width = parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10);\n height = parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10);\n\n // iterate through the bandwidth-filtered playlists and find\n // best rendition by player dimension\n while (i--) {\n variant = bandwidthPlaylists[i];\n\n // ignore playlists without resolution information\n if (!variant.attributes ||\n !variant.attributes.RESOLUTION ||\n !variant.attributes.RESOLUTION.width ||\n !variant.attributes.RESOLUTION.height) {\n continue;\n }\n\n // since the playlists are sorted, the first variant that has\n // dimensions less than or equal to the player size is the best\n\n let variantResolution = variant.attributes.RESOLUTION;\n\n if (variantResolution.width === width &&\n variantResolution.height === height) {\n // if we have the exact resolution as the player use it\n resolutionPlusOne = null;\n resolutionBestVariant = variant;\n break;\n } else if (variantResolution.width < width &&\n variantResolution.height < height) {\n // if both dimensions are less than the player use the\n // previous (next-largest) variant\n break;\n } else if (!resolutionPlusOne ||\n (variantResolution.width < resolutionPlusOneAttribute.width &&\n variantResolution.height < resolutionPlusOneAttribute.height)) {\n // If we still haven't found a good match keep a\n // reference to the previous variant for the next loop\n // iteration\n\n // By only saving variants if they are smaller than the\n // previously saved variant, we ensure that we also pick\n // the highest bandwidth variant that is just-larger-than\n // the video player\n resolutionPlusOne = variant;\n resolutionPlusOneAttribute = resolutionPlusOne.attributes.RESOLUTION;\n }\n }\n\n // fallback chain of variants\n return resolutionPlusOne ||\n resolutionBestVariant ||\n bandwidthBestVariant ||\n sortedPlaylists[0];\n }",
"function update_slider_positions() {\n $('.playing').each(function() {\n var width = $(this).data('sound').seek() / $(this).data('sound').duration() * 100;\n $(this).find('.slider').css(\n 'width', \n width + '%'\n );\n });\n }",
"function audioPlayerUpdate(event) {\n\tvar time=event.jPlayer.status.currentTime;\n\t// This if ensures that the update event doesn't fire right after the learner presses the replay button, and so the first item isn't displayed right away again because it thinks it is later than it is.\n\tif (!(shell.caption.currPosition == 0 && time > 0.5)) {\n\t\t//console.log('shell.caption.currPosition: ' + shell.caption.currPosition + \" time: \" + time);\n\t\tshell.audio.currentTime = time;\n\t\tif (shell.caption.isTimedCC && shell.caption.data[shell.currPageId]) {\n\t\t\tvar ccObjArray = shell.caption.data[shell.currPageId].mainPage;\n\t\t\tif (shell.caption.onSubPage) {\n\t\t\t\tif (shell.caption.onSubSubPage) {\n\t\t\t\t\tccObjArray = shell.caption.data[shell.currPageId].subPages[shell.caption.subPageNum].subPages[shell.caption.subSubPageNum];\n\t\t\t\t} else {\n\t\t\t\t\tif(shell.caption.data[shell.currPageId].subPages) {\n\t\t\t\t\t\t//console.log(\"subpages: \" +shell.caption.data[shell.currPageId].subPages);\n\t\t\t\t\t\tccObjArray = shell.caption.data[shell.currPageId].subPages[shell.caption.subPageNum].mainPage;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t//console.log(ccObjArray);\n\t\t\tif (shell.caption.currPosition < ccObjArray.length) {\n\t\t\t\tvar pageInfo = ccObjArray[shell.caption.currPosition];\t\t\t\t\t\t\n\t\t\t\t//console.log('pageInfo: ' + pageInfo);\n\t\t\t\tif (time >= pageInfo.time) {\n\t\t\t\t\tloadCCText(pageInfo.html);\n\t\t\t\t\tshell.caption.currPosition++;\n\t\t\t\t}\n\t\t\t} \n\t\t}\n\t\t// Set up timed content display\n\t\tif (shell.timedContent.data[shell.currPageId]) {\n\t\t\tif (!shell.timedContent.onSubPage && !shell.timedContent.onSubSubPage) {\n\t\t\t\tif (shell.timedContent.currPosition < shell.timedContent.data[shell.currPageId].mainPage.length) {\n\t\t\t\t\t//console.log('shell.timedContent.currPosition: ' + shell.timedContent.currPosition + ' and shell.timedContent.data[shell.currPageId].mainPage.length: ' + shell.timedContent.data[shell.currPageId].mainPage.length);\n\t\t\t\t\tvar timeInfo = shell.timedContent.data[shell.currPageId].mainPage[shell.timedContent.currPosition];\t\t\t\t\t\t\n\t\t\t\t\tif (time >= timeInfo.time) {\n\t\t\t\t\t\t//console.log(timeInfo.displayType + \" \" + timeInfo.contentId);\n\t\t\t\t\t\tdisplayTimedItem(timeInfo);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (shell.timedContent.onSubPage) {\n\t\t\t\t//console.log(\"I'm on a sub page\");\n\t\t\t\t//If ths subpage has timed content (outside of CC text)\n\t\t\t\tif (shell.timedContent.data[shell.currPageId].subPages) {\n\t\t\t\t\t//console.log(\"shell.timedContent.currPosition: \"+ shell.timedContent.currPosition);\n\t\t\t\t\tif (shell.timedContent.currPosition < shell.timedContent.data[shell.currPageId].subPages[shell.caption.subPageNum].length) {\n\t\t\t\t\t\t//console.log('shell.timedContent.currPosition: ' + shell.timedContent.currPosition + ' and shell.timedContent.data[shell.currPageId].mainPage.length: ' + shell.timedContent.data[shell.currPageId].mainPage.length);\n\t\t\t\t\t\tvar timeInfo = shell.timedContent.data[shell.currPageId].subPages[shell.caption.subPageNum][shell.timedContent.currPosition];\t\t\t\t\t\t\n\t\t\t\t\t\t//console.log(\"time: \"+ time);\n\t\t\t\t\t\tif (time >= timeInfo.time) {\n\t\t\t\t\t\t\t//console.log(timeInfo.displayType + \" \" + timeInfo.contentId);\n\t\t\t\t\t\t\tdisplayTimedItem(timeInfo);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n//console.log('time is being updated: ' + event.jPlayer.status.currentTime);\t\t\n}",
"function updateDeviceSA(device) {\n $.each(jsPlumbInstance.getConnections({\n source: device.attr(\"id\")\n }), function(index, connection) {\n var target = $(connection.target);\n if (target.attr(\"class\").indexOf(\"device\") == -1) {\n target.data(\"device\", device.data(\"name\"));\n target.data(\"deviceId\", device.data(\"id\"));\n }\n });\n }",
"function privateAfterSongChanges(){\n\t\t/*\n\t\t\tAfter the new song is set, we see if we need to change\n\t\t\tthe visualization. If it's different, we need to start \n\t\t\tthe new one.\n\t\t*/\n\t\tif( privateCheckSongVisualization() ){\n\t\t\tprivateStartVisualization();\n\t\t}\n\n\t\t/*\n\t\t\tAfter the new song is set, Amplitude will update the\n\t\t\tvisual elements containing information about the\n\t\t\tnew song if the user wants Amplitude to.\n\t\t*/\n\t\tif( config.handle_song_elements ){\n\t\t\tprivateDisplaySongMetadata();\n\t\t}\n\n\t\t/*\n\t\t\tSync song status sliders. Sets them back to 0 because\n\t\t\twhen the song is changing there won't be any songs currently\n\t\t\tplaying.\n\t\t*/\n\t\tprivateResetSongStatusSliders();\n\n\t\t/*\n\t\t\tWe set the current times to 0:00 when song changes\n\t\t\tso all of the page's players will be synchronized.\n\t\t*/\n\t\tprivateSyncCurrentTimes();\n\n\t\t/*\n\t\t\tRemove class from all containers\n\t\t*/\n\t\tprivateSyncVisualPlayingContainers();\n\n\t\t/*\n\t\t\tSet new active song container by applying a class\n\t\t\tto the visual element containing the visual representation\n\t\t\tof the song that is actively playing.\n\t\t*/\n\t\tprivateSetActiveContainer();\n\n\t\t/*\n\t\t\tPlays the new song.\n\t\t*/\n\t\tprivatePlay();\n\t}",
"function applySettings(wrapper) {\n var source = wrapper.attr('data-social-media-source');\n var entity = wrapper.attr('data-social-media-entity');\n var target = $('.js-social-media-code', wrapper);\n\n // Show the code if source is enabled.\n if (sources.hasOwnProperty(source) && sources[source] === true && code.hasOwnProperty(entity)) {\n target.html(code[entity]);\n\n if (source === 'twitter') {\n initTwitter(wrapper);\n }\n\n if (source === 'instagram') {\n initInstagram();\n }\n }\n else {\n if (Drupal.eu_cookie_compliance !== undefined && Drupal.eu_cookie_compliance.hasAgreed()) {\n var link = $('<div class=\"js-social-media-code__message\">' + settings.link + '</div>');\n\n $('.js-social-media-settings-open', link).click(function (e) {\n e.preventDefault();\n openModal();\n });\n\n target.html(link);\n }\n else {\n target.html(settings.cookie);\n }\n }\n }",
"function audioControl() {\n var oO = \"\";\n if((document.getElementById(\"sample-audio\").currentTime % 60) < 10) {\n oO = \"0\";\n }\n document.getElementById(\"track1Position\").innerHTML = Math.floor(document.getElementById(\"sample-audio\").currentTime / 60) + \":\" + oO + Math.floor(document.getElementById(\"sample-audio\").currentTime % 60);\n if(document.getElementById(\"sample-audio\").currentTime < (document.getElementById(\"sample-audio\").duration * .1)) {\n document.getElementById(\"tenp-tr\").style.color=\"#e76e55\";\n document.getElementById(\"twentyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"thirtyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"fortyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"fiftyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"sixtyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"seventyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"eightyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"ninetyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"hundyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"tenp-tr\").style.backgroundColor=\"#e76e55\";\n document.getElementById(\"twentyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"thirtyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"fortyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"fiftyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"sixtyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"seventyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"eightyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"ninetyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"hundyp-tr\").style.backgroundColor=\"#d3d3d3\";\n } else if(document.getElementById(\"sample-audio\").currentTime < (document.getElementById(\"sample-audio\").duration * .2)) {\n document.getElementById(\"tenp-tr\").style.color=\"#e76e55\";\n document.getElementById(\"twentyp-tr\").style.color=\"#e76e55\";\n document.getElementById(\"thirtyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"fortyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"fiftyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"sixtyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"seventyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"eightyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"ninetyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"hundyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"tenp-tr\").style.backgroundColor=\"#e76e55\";\n document.getElementById(\"twentyp-tr\").style.backgroundColor=\"#e76e55\";\n document.getElementById(\"thirtyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"fortyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"fiftyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"sixtyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"seventyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"eightyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"ninetyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"hundyp-tr\").style.backgroundColor=\"#d3d3d3\";\n } else if(document.getElementById(\"sample-audio\").currentTime < (document.getElementById(\"sample-audio\").duration * .3)) {\n document.getElementById(\"tenp-tr\").style.color=\"#f7d51d\";\n document.getElementById(\"twentyp-tr\").style.color=\"#f7d51d\";\n document.getElementById(\"thirtyp-tr\").style.color=\"#f7d51d\";\n document.getElementById(\"fortyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"fiftyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"sixtyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"seventyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"eightyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"ninetyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"hundyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"tenp-tr\").style.backgroundColor=\"#f7d51d\";\n document.getElementById(\"twentyp-tr\").style.backgroundColor=\"#f7d51d\";\n document.getElementById(\"thirtyp-tr\").style.backgroundColor=\"#f7d51d\";\n document.getElementById(\"fortyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"fiftyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"sixtyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"seventyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"eightyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"ninetyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"hundyp-tr\").style.backgroundColor=\"#d3d3d3\";\n } else if(document.getElementById(\"sample-audio\").currentTime < (document.getElementById(\"sample-audio\").duration * .4)) {\n document.getElementById(\"tenp-tr\").style.color=\"#f7d51d\";\n document.getElementById(\"twentyp-tr\").style.color=\"#f7d51d\";\n document.getElementById(\"thirtyp-tr\").style.color=\"#f7d51d\";\n document.getElementById(\"fortyp-tr\").style.color=\"#f7d51d\";\n document.getElementById(\"fiftyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"sixtyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"seventyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"eightyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"ninetyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"hundyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"tenp-tr\").style.backgroundColor=\"#f7d51d\";\n document.getElementById(\"twentyp-tr\").style.backgroundColor=\"#f7d51d\";\n document.getElementById(\"thirtyp-tr\").style.backgroundColor=\"#f7d51d\";\n document.getElementById(\"fortyp-tr\").style.backgroundColor=\"#f7d51d\";\n document.getElementById(\"fiftyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"sixtyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"seventyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"eightyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"ninetyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"hundyp-tr\").style.backgroundColor=\"#d3d3d3\";\n } else if(document.getElementById(\"sample-audio\").currentTime < (document.getElementById(\"sample-audio\").duration * .5)) {\n document.getElementById(\"tenp-tr\").style.color=\"#f7d51d\";\n document.getElementById(\"twentyp-tr\").style.color=\"#f7d51d\";\n document.getElementById(\"thirtyp-tr\").style.color=\"#f7d51d\";\n document.getElementById(\"fortyp-tr\").style.color=\"#f7d51d\";\n document.getElementById(\"fiftyp-tr\").style.color=\"#f7d51d\";\n document.getElementById(\"sixtyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"seventyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"eightyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"ninetyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"hundyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"tenp-tr\").style.backgroundColor=\"#f7d51d\";\n document.getElementById(\"twentyp-tr\").style.backgroundColor=\"#f7d51d\";\n document.getElementById(\"thirtyp-tr\").style.backgroundColor=\"#f7d51d\";\n document.getElementById(\"fortyp-tr\").style.backgroundColor=\"#f7d51d\";\n document.getElementById(\"fiftyp-tr\").style.backgroundColor=\"#f7d51d\";\n document.getElementById(\"sixtyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"seventyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"eightyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"ninetyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"hundyp-tr\").style.backgroundColor=\"#d3d3d3\";\n } else if(document.getElementById(\"sample-audio\").currentTime < (document.getElementById(\"sample-audio\").duration * .6)) {\n document.getElementById(\"tenp-tr\").style.color=\"#209cee\";\n document.getElementById(\"twentyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"thirtyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"fortyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"fiftyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"sixtyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"seventyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"eightyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"ninetyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"hundyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"tenp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"twentyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"thirtyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"fortyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"fiftyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"sixtyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"seventyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"eightyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"ninetyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"hundyp-tr\").style.backgroundColor=\"#d3d3d3\";\n } else if(document.getElementById(\"sample-audio\").currentTime < (document.getElementById(\"sample-audio\").duration * .7)) {\n document.getElementById(\"tenp-tr\").style.color=\"#209cee\";\n document.getElementById(\"twentyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"thirtyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"fortyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"fiftyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"sixtyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"seventyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"eightyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"ninetyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"hundyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"tenp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"twentyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"thirtyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"fortyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"fiftyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"sixtyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"seventyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"eightyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"ninetyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"hundyp-tr\").style.backgroundColor=\"#d3d3d3\";\n } else if(document.getElementById(\"sample-audio\").currentTime < (document.getElementById(\"sample-audio\").duration * .8)) {\n document.getElementById(\"tenp-tr\").style.color=\"#209cee\";\n document.getElementById(\"twentyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"thirtyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"fortyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"fiftyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"sixtyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"seventyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"eightyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"ninetyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"hundyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"tenp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"twentyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"thirtyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"fortyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"fiftyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"sixtyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"seventyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"eightyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"ninetyp-tr\").style.backgroundColor=\"#d3d3d3\";\n document.getElementById(\"hundyp-tr\").style.backgroundColor=\"#d3d3d3\";\n } else if(document.getElementById(\"sample-audio\").currentTime <= (document.getElementById(\"sample-audio\").duration * .9)) {\n document.getElementById(\"tenp-tr\").style.color=\"#209cee\";\n document.getElementById(\"twentyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"thirtyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"fortyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"fiftyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"sixtyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"seventyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"eightyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"ninetyp-tr\").style.color=\"#209cee\";\n document.getElementById(\"hundyp-tr\").style.color=\"#d3d3d3\";\n document.getElementById(\"tenp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"twentyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"thirtyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"fortyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"fiftyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"sixtyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"seventyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"eightyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"ninetyp-tr\").style.backgroundColor=\"#209cee\";\n document.getElementById(\"hundyp-tr\").style.backgroundColor=\"#d3d3d3\";\n } else if(document.getElementById(\"sample-audio\").currentTime > (document.getElementById(\"sample-audio\").duration * .9)) {\n document.getElementById(\"tenp-tr\").style.color=\"#92cc41\";\n document.getElementById(\"twentyp-tr\").style.color=\"#92cc41\";\n document.getElementById(\"thirtyp-tr\").style.color=\"#92cc41\";\n document.getElementById(\"fortyp-tr\").style.color=\"#92cc41\";\n document.getElementById(\"fiftyp-tr\").style.color=\"#92cc41\";\n document.getElementById(\"sixtyp-tr\").style.color=\"#92cc41\";\n document.getElementById(\"seventyp-tr\").style.color=\"#92cc41\";\n document.getElementById(\"eightyp-tr\").style.color=\"#92cc41\";\n document.getElementById(\"ninetyp-tr\").style.color=\"#92cc41\";\n document.getElementById(\"hundyp-tr\").style.color=\"#92cc41\";\n document.getElementById(\"tenp-tr\").style.backgroundColor=\"#92cc41\";\n document.getElementById(\"twentyp-tr\").style.backgroundColor=\"#92cc41\";\n document.getElementById(\"thirtyp-tr\").style.backgroundColor=\"#92cc41\";\n document.getElementById(\"fortyp-tr\").style.backgroundColor=\"#92cc41\";\n document.getElementById(\"fiftyp-tr\").style.backgroundColor=\"#92cc41\";\n document.getElementById(\"sixtyp-tr\").style.backgroundColor=\"#92cc41\";\n document.getElementById(\"seventyp-tr\").style.backgroundColor=\"#92cc41\";\n document.getElementById(\"eightyp-tr\").style.backgroundColor=\"#92cc41\";\n document.getElementById(\"ninetyp-tr\").style.backgroundColor=\"#92cc41\";\n document.getElementById(\"hundyp-tr\").style.backgroundColor=\"#92cc41\";\n }\n}",
"function updateStats()\n{\n $.getJSON(Routing.generate(\"dj_panel_api_station_info\"), function(d) {\n if (d.onAir) {\n $(\"#station-nowplaying-title\").text(d.nowPlaying.title);\n $(\"#station-nowplaying-artist\").text(d.nowPlaying.artist);\n if (!$(\"#station-onair\").text(\"On Air\").hasClass(\"label-success\")) {\n $(\"#station-onair\").addClass(\"label-success\");\n }\n } else {\n $(\"#station-nowplaying-title\").text(\"...\");\n $(\"#station-nowplaying-artist\").text(\"...\");\n if ($(\"#station-onair\").text(\"Off Air\").hasClass(\"label-success\")) {\n $(\"#station-onair\").removeClass(\"label-success\");\n }\n }\n });\n}",
"_initAudioParams() {\n this.inputGain = this.audioComponents.inputGain.gain;\n this.outputGain = this.audioComponents.outputGain.gain;\n this.pan = this.audioComponents.panner.pan;\n }",
"function privateSyncVolumeSliders(){\n\t\tvar amplitude_volume_sliders = document.getElementsByClassName(\"amplitude-volume-slider\");\n\n\t\t/*\n\t\t\tIterates over all of the volume sliders for the song, setting the value\n\t\t\tto the config value.\n\t\t*/\n\t\tfor( var i = 0; i < amplitude_volume_sliders.length; i++ ){\n\t\t\tamplitude_volume_sliders[i].value = config.active_song.volume * 100;\n\t\t}\n\t}",
"function loadCurrentStation() {\n chrome.storage.local.get('currentStation', function(cfg) {\n if ('number' === typeof cfg['currentStation']) {\n selectedStations = {\n 'currentBand': 'FM',\n 'bands': {\n 'FM': cfg['currentStation']\n }\n };\n } else if (cfg['currentStation']) {\n selectedStations = cfg['currentStation'];\n }\n selectBand(Bands[settings.region][selectedStations['currentBand']]);\n var newFreq = selectedStations['bands'][band.getName()];\n if (newFreq) {\n setFrequency(newFreq, false);\n }\n });\n }",
"function loadSongs(){\n var x = 0;\n $('.audio-song').each(function(){\n x++;\n var m4a = $(this).find(\".jp-audio\").data( \"audio-ma\" ),\n ogg = $(this).find(\".jp-audio\").data( \"audio-ogg\" );\n\n $(this).find(\".jp-jplayer\").attr('id', 'jquery_jplayer_'+x);\n $(this).find(\".jp-audio\").attr('id', 'jp_interface_'+x);\n // callback js_audioPlayer to create jPlayer\n js_audioPlayer(m4a, ogg, x);\n // console.log(m4a +\" \"+ogg +\" \"+ x);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove an investment from the portfolio after a sale | function removeInvestment (symbol) {
portfolio = portfolio.filter(item => item.symbol !== symbol)
// blacklist.push(symbol) //
buying = true
} | [
"function removeFromPortfolio() { \n portfolioArr = JSON.parse(localStorage.getItem(\"stock\"));\n portfolioCash = localStorage.getItem(\"cash\");\n let quantity = parseInt(stockSaleInput.val());\n console.log(sellQuantityAvailable);\n console.log(quantity);\n\n if(sellQuantityAvailable < quantity){\n $(\"#errorMessageDiv\").text(\"Insufficient shares available.\")\n }\n else {\n let saleTotal = quantity * sellPrice;\n portfolioCash = parseFloat(portfolioCash) + saleTotal;\n localStorage.setItem(\"cash\", portfolioCash);\n for (i=0 ; i<portfolioArr.length; i++){\n if(sellStock === portfolioArr[i].name){\n portfolioArr[i].quantity -= quantity;\n }\n }\n stockArr = JSON.stringify(portfolioArr);\n localStorage.setItem(\"stock\", stockArr);\n $(\"#portfolioDisplayDiv\").empty();\n generatePortfolio();\n $(\"#modalSell\").modal('close');\n }\n}",
"function hold (investment) {\n portfolio.forEach(elem => {\n if(elem.symbol === investment.symbol) {\n elem.abort = elem.target - (elem.target * 0.1)\n elem.target += investment.increase\n elem.holding = true\n }\n })\n}",
"function removeRisk(event) {\n // Capture which category to add criteria too\n var categoryId = $(event.currentTarget).attr('data-id');\n // Remove last criteria from array\n projectManager.removeRiskFrom(projectManager.getCategory(categoryId));\n // Update interface\n update();\n}",
"function removeEmployee() {\n let idNum = Number($(this).parents('tr').data('id'));\n newCompany.removeEmployee(idNum);\n $(this).parents('tr').remove();\n $('#salTotal').html(newCompany.averageSalary());\n} // end removeEmployee()",
"async function removeDueByReturn(req, res) {\n var returnId = req.body.id;\n var amountReceived = Number(req.body.amount);\n try {\n var dataAuth = await user.checkAsync(req, 1);\n if (!dataAuth) {\n res.send({ msg: 'not permitted', err: true });\n return;\n }\n var upData = await mdb.Return.findOne({ where: { id: returnId } });\n if (isNaN(amountReceived)) amountReceived = Number(upData.dueAmount);\n upData.totalTendered = Number(upData.totalTendered) + amountReceived;\n if (Number(upData.dueAmount) - amountReceived <= 0) upData.dueDate = null;\n upData.dueAmount = Number(upData.dueAmount) - amountReceived;\n\n await upData.save();\n\n await saleData.transactionAdd('return', 'products', 'income', 'short term', amountReceived, amountReceived, null, 'income from return');\n res.send({ err: false, msg: 'done!' });\n } catch (e) {\n console.log(e);\n res.send({ err: true, msg: 'some error' });\n }\n}",
"function removeScheduled(ticket) {\n return ticket.id !== invoiceToRemove\n }",
"function removeItem() {\n \n var idxToRemove = $('.remove-from-cart').attr('data-index');\n \n cart.items.splice(idxToRemove, 1);\n renderCart(cart, $('.template-cart'), $('.cart-container'));\n}",
"async function remove() {\n const x = await Pair.find({ gpu: 'GeForce RTX 2070 Super' });\n for (pair of x) {\n for (let i = 0; i < pair.priceHistory.length; i++) {\n if (pair.priceHistory[i].price > pair.priceHistory[pair.priceHistory.length - 1].price + 200) {\n pair.priceHistory.splice(i, 1);\n pair.save();\n }\n }\n }\n}",
"async removePaymentInstrument() {\n let paymentInstrumentId =\n basket.paymentInstruments && basket.paymentInstruments[0]?.paymentInstrumentId\n\n if (!paymentInstrumentId) {\n return\n }\n\n const response = await api.shopperBaskets.removePaymentInstrumentFromBasket({\n parameters: {\n basketId: basket.basketId,\n paymentInstrumentId: paymentInstrumentId\n }\n })\n\n setBasket(response)\n }",
"function deleteStock() {\n rows = getSelectedRowBoxes();\n\n for (var i=rows.length - 1; i >= 0; i--) {\n var prodId = rows[i].parentNode.parentNode.id;\n delete products[prodId];\n products.splice(prodId, 1);\n }\n saveData();\n displayInventory();\n}",
"removeStockFromChart(symbol) {\n for (let i = 0, n = this.stockChart.series.length; i < n; i++) {\n const series = this.stockChart.series[i];\n if (series.name === symbol) {\n this.stockChart.series[i].remove();\n return;\n }\n }\n }",
"function deleteBought(product, boughtBtn) {\n let itemWrapper = Array.from(allLists.querySelectorAll('.itemWrapper')).filter(elem => elem.getAttribute('id') === product.id)[0];\n let boughtPrice = allLists.querySelector('.boughtPrice');\n product.bought = false;\n product.boughtPrice = 0;\n boughtPrice.innerHTML = `€ ${product.boughtPrice}`;\n itemWrapper.style.border = 'none';\n boughtPrice.style.display = 'none';\n changeState(boughtBtn);\n}",
"function deleteExpense(id) {\n console.log(\"DELETE BUTTON WORKS\");\n }",
"function removeBasketItem(event) {\n let buttonClicked = event.target;\n let id = buttonClicked.previousElementSibling.innerText;\n buttonClicked.parentElement.parentElement.remove();\n let itemToRemove = { productId: id }\n basketArrayItemRemove(itemToRemove)\n updateBasketTotal();\n}",
"function deleteFragranceFromCart(id) {\n delete shoppingCart[id];\n}",
"function removeRowDiscount(){\n \t$('.coupon_discount_amount .new_price').empty();\n }",
"function deletePriceAlert(product) {\n //Search for the alert button \n try{\n let alertBtn = Array.from(popover.querySelectorAll('.setAlert')).filter(alert => alert.getAttribute('id') === product.id)[0];\n changeState(alertBtn);\n }catch{\n //nothing\n }\n\n //Set price alert to false\n product.priceAlert = false;\n let index = allPriceAlerts.indexOf(product);\n allPriceAlerts.splice(index, 1);\n calcPriceAlerts();\n}",
"function removeCart() {\n\tconsole.log(\"removing from cart\");\n\ttotal -= 1;\n\t$(\"#cartName\").html(\"cart (\" + total + \")\");\n\n\tlet itemDiv = document.getElementById(\"itemStart\");\n\titemDiv.style.display = \"none\";\n}",
"function removeWantToVisitPark(visit){\nwantToVisitPark.splice(visit, 1);\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Timer class saves time stamp and counts time difference between current time (update() method) and saved time stamp. | function Timer() {
/**
* Time difference between last update() call and last set() call
*
* @member Timer
*/
this.elapsed = 0;
/**
* Time stamp
*
* @member Timer
*/
this.stamp = null;
} | [
"function _updateTimer(){\n _timeNow = Date.now();\n var $dt = (_timeNow-_timeThen);\n\n _delta = _delta + $dt; // accumulate delta time between trips, but not more than trip window\n _now = _now+_delta; // accumulate total time since start of timer\n _timeThen = _timeNow;\n\n // record the number of trip windows passed since last reset\n _passedTrips = Math.floor(_delta / _trip);\n\n // determine if timer tripped\n if(_delta > _trip){\n _isTripped = true;\n _timeNow = Date.now();\n // assign current value to the excess amount beyond tripping point,\n // reset the accumulation to whatever is less than the trip window\n _delta = _delta % _trip;\n _timeThen = Date.now();\n }\n }",
"function update_timer() {\n seconds = Math.floor(game.time.time / 1000);\n milliseconds = Math.floor(game.time.time);\n elapsed = game.time.time - starting_time;\n}",
"calculate() {\n this.times.miliseconds += 1;\n if (this.times.miliseconds >= 100) {\n this.times.seconds += 1;\n this.times.miliseconds = 0;\n }\n if (this.times.seconds >= 60) {\n this.times.minutes += 1;\n this.times.seconds = 0;\n }\n }",
"function timerCounter() {\n\tvar currentDate = new Date();\n\tvar remainingNow = targetDate.valueOf() - currentDate.valueOf();\n\n\n if (! roundStarting) {\n\t\tif (remainingNow < 0) {\n\t\t\t$('#time').html(\"(Kierros päättynyt)\");\n\t\t\troundEnded();\n\t\t} else {\n\t\t\tvar seconds = Math.floor((remainingNow / 1000)) % 60;\n\t\t\tvar minutes = Math.floor((remainingNow / 1000) / 60);\n\t\t\tif (seconds < 10) { seconds = '0' + seconds; }\n\t\t\t$(\"#time\").text(minutes + \":\" + seconds);\n\t\t}\n\t\n\t\tif (remainingNow < 60000) {\n\t\t\tif (lastMinute == false) {\n\t\t\t\tlastMinute = true;\n\t\t\t\tupdateButtons();\n\t\t\t}\n\t\t} else {\n\t\t\tif (lastMinute == true) {\n\t\t\t\tlastMinute = false;\n\t\t\t\tupdateButtons();\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (remainingNow < 0) {\n\t\t\t$('#time').html(\"Alkaa: 0:00\");\n//\t\t\troundEnded();\n\t\t} else {\n\t\t\tvar seconds = Math.floor((remainingNow / 1000)) % 60;\n\t\t\tvar minutes = Math.floor((remainingNow / 1000) / 60);\n\t\t\tif (seconds < 10) { seconds = '0' + seconds; }\n\t\t\t$(\"#time\").text(\"Alkaa: \" + minutes + \":\" + seconds);\n\t\t}\n\t}\n\n}",
"function UpdateTimer() {\n playSound();\n \n var strTmp = toMinutes(TotalSeconds).split(\":\");\n \n if (strTmp[2])\n var strtime = pad(strTmp[0], 2)+\":\"+pad(strTmp[1], 2)+\":\"+pad(strTmp[2], 2);\n else\n var strtime = pad(strTmp[0], 2)+\":\"+pad(strTmp[1], 2);\n \n Timer.innerHTML = strtime;\n $j('#roundsRemaining').html(pad(cycles, 2));\n \n if (workoutType == 2){ // Advanced\n $j('#repeatsRemaining').html(pad(repeat, 2));\n }\n \n if (totTimeRemaining <= 0){\n var tmpRes = \"00:00\";\n }else{\n var tmpRes = toMinutes(totTimeRemaining).split(\":\"); \n }\n \n if (tmpRes[0] && tmpRes[1]){\n if (tmpRes[2])\n $j('#totTimeRemaining').html(pad(tmpRes[0], 2)+\":\"+pad(tmpRes[1], 2)+\":\"+pad(tmpRes[2], 2)); \n else\n $j('#totTimeRemaining').html(pad(tmpRes[0], 2)+\":\"+pad(tmpRes[1], 2)); \n }\n else\n $j('#totTimeRemaining').html(\"00:00\");\n \n}",
"function timerUpdate() {\n // update display of timer on browser window\n var timeString = timerMilliSeconds / 1000;\n $(\"#timer\").text(timeString + \" seconds until next update\");\n}",
"function stopwatchUpdate(){\n\n rawTime += intervalRate\n stopwatchTime.innerHTML = formatTime(rawTime)\n}",
"ms () { return this.now() - this.startMS }",
"updateCurrentTime () {\n const now = new Date();\n this.hour = now.getHours();\n this.minute = now.getMinutes();\n this.second = now.getSeconds();\n }",
"function updateTimer() {\n //get time since last update\n var timeDiff = Date.now() - lastUpdateTime;\n\n //was long enough ago\n if (timeDiff > updateIntervalTime) {\n //update now, will reset timer\n updateList();\n\n //set to start again in 30 seconds\n setTimeout(updateTimer, updateIntervalTime);\n } else {\n //try again in how much time is left until 30 seconds is reached\n setTimeout(updateTimer, updateIntervalTime - timeDiff);\n }\n}",
"function time() {\n timer = 63;\n timerId = setInterval(decrement, 1000);\n}",
"updateTimeProperties () {\r\n this.timeAtThisFrame = new Date().getTime();\r\n\r\n // divide by 1000 to get it into seconds\r\n this.time = (this.timeAtThisFrame - this.timeAtFirstFrame) / 1000.0;\r\n\r\n this.deltaTime = (this.timeAtThisFrame - this.timeAtLastFrame) / 1000.0;\r\n this.timeAtLastFrame = this.timeAtThisFrame;\r\n\r\n // update and set our scene time uniforms\r\n this.t = this.time / 10;\r\n this.dt = this.deltaTime;\r\n }",
"function timer() {\n d3.range(nodes.length).map(function (i) {\n var curr_node = nodes[i],\n curr_moves = curr_node.moves;\n\n // Time to go to next activity\n if (curr_node.next_move_time == curr_minute) {\n if (curr_node.moves == curr_node.sched.length - 1) {\n curr_moves = 0;\n } else {\n curr_moves += 1;\n }\n\n // Subtract from current activity count\n act_counts[curr_node.act] -= 1;\n\n // Move on to next activity\n curr_node.act = curr_node.sched[curr_moves].act;\n\n // Add to new activity count\n act_counts[curr_node.act] += 1;\n\n curr_node.moves = curr_moves;\n curr_node.cx = foci[curr_node.act].x;\n curr_node.cy = foci[curr_node.act].y;\n\n nodes[i].next_move_time += nodes[i].sched[curr_node.moves].duration;\n }\n\n });\n\n force.resume();\n curr_minute += 1;\n\n // Update percentages\n label.selectAll(\"tspan.actpct\")\n .text(function (d) {\n return readablePercent(act_counts[d.index]);\n });\n\n // Update time\n var true_minute = curr_minute % 1440;\n d3.select(\"#current_time\").text(minutesToTime(true_minute));\n\n setTimeout(timer, speeds[USER_SPEED]);\n }",
"increaseTime() {\r\n this.duration += 1;\r\n }",
"function fastupdateGodTimer(){\r\n\t\r\n\t//Check if round is ongoing\r\n\tif(godtimer_in_seconds > 0){\r\n\t\tgodtimer_in_seconds = godtimer_in_seconds - 0.2;\r\n\t\t////console.log(godtimer_in_seconds);\r\n\t\tgod_numhours = Math.floor(godtimer_in_seconds / 3600);\r\n\t\tgod_numminutes = Math.floor((godtimer_in_seconds % 3600) / 60);\r\n\t\tgod_numseconds = parseFloat((godtimer_in_seconds % 3600) % 60).toFixed(0);\r\n\t\t\r\n\t\ta_godTimer = god_numhours + \"h \" + god_numminutes + \"m \" + god_numseconds + \"s \";\r\n\t\tgodtimerdoc.textContent = a_godTimer;\r\n\t}\r\n}",
"_addTime () {\r\n this._totalTime += (this._limit - this._timeLeft)\r\n }",
"function Timer(){\n\n var env = model.parseFile(model.currProjectFile);\n\n function _getStartData(args){\n let logData = {},\n task,\n project;\n\n if(args.hasArg('task') || args.hasArg('project')){\n task = args.getArg('task');\n project = args.getArg('project');\n }else{\n let projpos = args.getValuePos('project'),\n taskpos = args.getValuePos('task');\n\n project = projpos > -1 ? args.getPos(projpos + 1) : null;\n task = taskpos > -1 ? args.getPos(taskpos + 1) : null;\n }\n\n if(!_.isEmpty(project)) logData.project = project;\n if(!_.isEmpty(task)) logData.task = task;\n return logData;\n }\n \n function start(args){\n let data = _getStartData(args);\n if(_.isEmpty(data) && !_.isEmpty(env)){\n data = env; \n }\n // putting description here so that I can keep the environment variables but change the description on the fly\n if(args.hasArg('description')){\n data.description = args.getArg('description');\n }\n\n data.startTime = + new Date();\n let ret = model.start(data);\n if(!ret){\n console.log(\"Something went wrong. Couldn't start timer.\");\n }\n return ret;\n }\n\n function stop(args){\n model.stop(args);\n }\n\n function distract(args){\n model.distract(args);\n }\n\n /* \n * check the status of the timer \n * timelog status\n * returns the current project, task, start time, ellapsed time and whether or not we are in distract mode\n */\n function status(){\n if(!_.isEmpty(env)){\n console.log(\"Currently in the following environment:\");\n console.log(columnify(env));\n console.log(\" \"); \n }\n \n var ret = model.checkStatus();\n if(ret === false){\n console.log(\"You currently do not have any timers running\");\n }else{\n console.log(columnify(ret));\n }\n }\n\n\n /* \n * analyze the time we've spent\n * timelog analyze <today | date> - defaults to today\n */\n function analyze(args){\n let passData = {};\n passData.date = new Date();\n \n if(args.hasArg('date')){\n passData.date = new Date(args.getArg('date'));\n }\n \n if(args.hasArg('groupby')){\n passData.groupby = args.getArg('groupby');\n if(args.hasArg('and')){\n passData.and = args.getArg('and');\n }\n }\n\n var data = model.analyze(passData);\n if(_.isEmpty(data)){\n console.log(\"There are no timers for this date\");\n }else{\n\n console.log(columnify(data, {config: { description: {maxWidth: 30}}}));\n }\n }\n\n return {start, stop, distract, status, analyze};\n}",
"function setTimestamp_() {\n const currentTime = formatTime_(sketchPlayer.sketch.getCurrentTime());\n const duration = formatTime_(sketchPlayer.sketch.videoDuration());\n $timestamp.text(currentTime + '/' + duration);\n\n // Clear any pending timer, since this function could either be called as the\n // result of an onSeekUpdate update event, or from a previous timer firing.\n clearTimeout(timestampUpdateTimer);\n timestampUpdateTimer = setTimeout(setTimestamp_, 500);\n}",
"function getTime() {\n const timeStamp = Date.now();\n const { startTime, currentTime, previousLapTime, nextId } = state;\n const currTime = startTime ? (timeStamp - startTime) : currentTime;\n const currLapTime = currTime - previousLapTime;\n const currentLap = createLapNode(({ id: nextId, lapTime: currLapTime }))\n\n currentLapDisplay.innerHTML = '';\n currentLapDisplay.appendChild(currentLap);\n currentTimeDisplay.innerHTML = getTimeAsAString(currTime);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
radius: radius of dot (will be capped at 1/4 of size, so dots don't overflow image bounds) size: size of twodot image (square) SVGs scale up/down very well, so there's no need to set a large size. Just use 100 and scale the image in CSS. | static makePolkaDotsSVG (radius=20, size=100) {
let left = size * 0.25;
let right = size * 0.75;
let r = radius > size * 0.25 ? size * 0.25 : radius;
let svgTag = `<svg xmlns='http://www.w3.org/2000/svg' width='${size}' height='${size}'><circle shape-rendering='geometricPrecision' cx='${left}' cy='${left}' r='${r}' fill='black'/><circle shape-rendering='geometricPrecision' cx='${right}' cy='${right}' r='${r}' fill='black'/></svg>`;
return svgTag;
} | [
"function size_to_radius(size){\r\n\t\tswitch (size) {\r\n\t\t\t\tcase \"small\":\r\n\t\t\t\t\treturn 2;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase \"normal\":\r\n\t\t\t\t\treturn 5;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase \"large\":\r\n\t\t\t\t\treturn 10;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase \"huge\":\r\n\t\t\t\t\treturn 20;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tdefault:\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t}",
"function squareAreaToCircle(size){\n return +(Math.PI * size / 4).toFixed(8);\n}",
"function fontSize(d) {\n d.fontsize = Math.floor(d.radius/3);\n return d.fontsize + \"px\";\n }",
"function dotInCircle(dot){\r\n\t \t\r\n\t \t//Determine if it is the left or right circle and calculate the distance from the circle center\r\n\t \tif(stimulusSide === 'left'){\r\n\t \t\treturn Math.sqrt(Math.pow(dot.x-stimulusLeftX,2) + Math.pow(dot.y-stimulusLeftY,2)) <= stimulusRadius;\r\n\t \t}else if(stimulusSide === 'right'){\r\n\t \t\treturn Math.sqrt(Math.pow(dot.x-stimulusRightX,2) + Math.pow(dot.y-stimulusRightY,2)) <= stimulusRadius;\r\n\t \t}\r\n\t \t}",
"function radius(e)\n{\n return 4*Math.sqrt(e.size);\n}",
"function circleDiameter(ratio) {\n return ratio * 2;\n}",
"function circle(annotation) {\n const element = rectangle(annotation);\n element.type = 'circle';\n element.radius = Math.max(element.width, element.height) / 2;\n delete element.width;\n delete element.height;\n delete element.rotation;\n delete element.normal;\n return element;\n}",
"function ThreeDot() {\n return (\n <svg width=\"24\" height=\"24\" viewBox=\"0 0 512 512\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M288 384C288 366.327 273.673 352 256 352C238.327 352 224 366.327 224 384C224 401.673 238.327 416 256 416C273.673 416 288 401.673 288 384Z\" fill=\"#011B53\"/>\n <path d=\"M288 256C288 238.327 273.673 224 256 224C238.327 224 224 238.327 224 256C224 273.673 238.327 288 256 288C273.673 288 288 273.673 288 256Z\" fill=\"#011B53\"/>\n <path d=\"M288 128C288 110.327 273.673 96 256 96C238.327 96 224 110.327 224 128C224 145.673 238.327 160 256 160C273.673 160 288 145.673 288 128Z\" fill=\"#011B53\"/>\n </svg>\n )\n}",
"function addRadius(){\n\tcircle = new google.maps.Circle({\n\t map: map,\n\t radius: sizeOfRadius, \t\t\t\t\t\t\t\t// 250mts\n\t fillColor: '#00BFFF',\n\t strokeWeight: '1px'\n\t});\n\tcircle.bindTo('center', marker, 'position');\n}",
"function updateRadius(rad){\n circle.setRadius(rad);\n}",
"function drawDots() {\n var circles = dotg.selectAll('circle')\n .data(dots);\n circles.enter()\n .append('circle');\n circles.exit().remove();\n circles\n .transition()\n .duration(200)\n .attr('cx', function(d) { return d.x; })\n .attr('cy', function(d) { return d.y; })\n //Initialize dot color\n .attr('fill', function(d) { return d.group ? d.group.color : '#BDBDBD'; })\n .attr('r', 8);\n}",
"function setPebbleRadius(d){\n if (d.group1 || d.group2){ // if a member of a group, need to calculate radius size\n var uppersize = 7\n var ng1 = (d.group1) ? zparams.zgroup1.length : 1; // size of group1, if a member of group 1\n var ng2 = (d.group2) ? zparams.zgroup2.length : 1; // size of group2, if a member of group 2\n var maxng = Math.max(ng1, ng2); // size of the largest group variable is member of\n return (maxng>uppersize) ? RADIUS*Math.sqrt(uppersize/maxng) : RADIUS; // keep total area of pebbles bounded to pi * RADIUS^2 * uppersize, thus shrinking radius for pebbles in larger groups\n } else {\n return RADIUS; // nongroup members get the common global radius\n }\n}",
"addRandomDots(n_dots){\n for(let i= 0; i<n_dots;i++){\n this.addRandomDot();\n }\n }",
"function determineDiameter() {\n var height = square_div_array[0].clientHeight;\n var width = square_div_array[0].clientWidth;\n // how to return most correct size circle?\n return (lessThan(height, width)-5)+'px';\n}",
"function omtrek (diameter) {\n return diameter * Math.PI;\n}",
"_pulsingDot(col = [255, 100, 100, true]) {\n const dotSize = 20;\n let self = this;\n return {\n pulse: col[3],\n color: col.splice(0,3),\n width: dotSize,\n height: dotSize,\n data: new Uint8Array(dotSize * dotSize * 4),\n\n // get rendering context for the map canvas when layer is added to the map\n onAdd: function () {\n let canvas = document.createElement('canvas');\n canvas.width = this.width;\n canvas.height = this.height;\n this.context = canvas.getContext('2d');\n },\n\n // called once before every frame where the icon will be used\n render: function () {\n let duration = 1500;\n let t = this.pulse ? ((performance.now() % duration) / duration) : 1;\n\n let radius = (dotSize / 2) * 0.5;\n let outerRadius = ((dotSize / 2) - radius) * t + radius;\n let context = this.context;\n let color = this.color;\n\n // draw outer circle\n context.clearRect(0, 0, this.width, this.height);\n context.beginPath();\n context.arc(\n this.width / 2,\n this.height / 2,\n outerRadius,\n 0,\n Math.PI * 2\n );\n context.fillStyle = 'rgba(' + color[0] + ', ' + color[1] + ', ' + color[2] + ',' + (1 - t) + ')';\n context.fill();\n\n // draw inner circle\n context.beginPath();\n context.arc(\n this.width / 2,\n this.height / 2,\n radius,\n 0,\n Math.PI * 2\n );\n context.fillStyle = this.pulse?\n 'rgba(' + color[0] + ', ' + color[1] + ', ' + color[2] + ', 1)' :\n 'rgba(155, 155, 155, 0.7)';\n context.strokeStyle = this.pulse? 'white' : 'rgba(' + color[0] + ', ' + color[1] + ', ' + color[2] + ', 0.8)';\n context.lineWidth = 2 + 4 * Math.max(0, 1 - 5 * t);\n context.fill();\n context.stroke();\n\n // update this image's data with data from the canvas\n this.data = context.getImageData(\n 0,\n 0,\n this.width,\n this.height\n ).data;\n\n // continuously repaint the map, resulting in the smooth animation of the dot\n self.map.triggerRepaint();\n\n // return `true` to let the map know that the image was updated\n return true;\n }\n }\n }",
"function getRadius(d, other) {\n let multiplier = d3Scales[d.cat] || d3Scales[\"default\"];\n\n let result = d3CircleRadius * multiplier;\n\n return result;\n }",
"function generateDots(n) {\n var dots = [];\n while (dots.length < n) {\n var candidate_dot = [Math.floor(Math.random() * 480) + 10, Math.floor(Math.random() * 480) + 10];\n for (var i=0; i<dots.length; i++) if (euclidianDistance(dots[i], candidate_dot) < 20) break;\n if (i == dots.length) dots.push(candidate_dot);\n }\n return dots;\n}",
"function strokedCircle(ctx, x, y, radius) {\r\n ctx.beginPath();\r\n ctx.arc(x, y, radius, 0, 2 * Math.PI, false);\r\n ctx.stroke();\r\n }",
"function clearDots(){\r\n\t \t//Loop through the dots one by one and draw them\r\n\t \tfor (var i = 0; i < nDots; i++) {\r\n\t \t\tdot = dotArray[i];\r\n\t \t\tctx.beginPath();\r\n\t \t\tctx.arc(dot.x, dot.y, dotRadius+1, 0, Math.PI * 2);\r\n\t \t\tctx.fillStyle = backgroundColor;\r\n\t \t\tctx.fill();\r\n\t \t}\r\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a base64 encoded SHA1 hash from a string | function sha1(str) {
return hash('sha1').update(str).digest('base64');
} | [
"function rstr_sha1(s)\n\t\t{\n\t\t return binb2rstr(binb_sha1(rstr2binb(s), s.length * 8));\n\t\t}",
"function hex2base64(s){ return Crypto.util.bytesToBase64(hex2bytes(s)) }",
"function hmacsha1(key, text)\n {\n return crypto.createHmac('sha1', key).update(text).digest('base64')\n }",
"function AlignSHA1(str) {\n\t\t\t\t\t\t\tvar nblk = ((str.length + 8) >> 6) + 1,\n\t\t\t\t\t\t\t\tblks = new Array(nblk * 16);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfor (var i = 0; i < nblk * 16; i++)\n\t\t\t\t\t\t\t\tblks[i] = 0;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfor (i = 0; i < str.length; i++)\n\t\t\t\t\t\t\t\tblks[i >> 2] |= str.charCodeAt(i) << (24 - (i & 3) * 8);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tblks[i >> 2] |= 0x80 << (24 - (i & 3) * 8);\n\t\t\t\t\t\t\tblks[nblk * 16 - 1] = str.length * 8;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\treturn blks;\n\t\t\t\t\t\t}",
"function generateHash(string) {\n\treturn crypto.createHash('sha256').update(string + configuration.encryption.salt).digest('hex');\n}",
"function AlignSHA1(str) {\n\n\t\tvar nblk = ((str.length + 8) >> 6) + 1, blks = new Array(nblk * 16);\n\n\t\tfor (var i = 0; i < nblk * 16; i++)\n\t\t\tblks[i] = 0;\n\n\t\tfor (i = 0; i < str.length; i++)\n\n\t\t\tblks[i >> 2] |= str.charCodeAt(i) << (24 - (i & 3) * 8);\n\n\t\tblks[i >> 2] |= 0x80 << (24 - (i & 3) * 8);\n\n\t\tblks[nblk * 16 - 1] = str.length * 8;\n\n\t\treturn blks;\n\n\t}",
"function core_sha1(x, len) {\n /* append padding */\n x[len >> 5] |= 0x80 << (24 - len % 32);\n x[((len + 64 >> 9) << 4) + 15] = len;\n\n var w = Array(80);\n var a = 1732584193;\n var b = -271733879;\n var c = -1732584194;\n var d = 271733878;\n var e = -1009589776;\n\n for (var i = 0; i < x.length; i += 16) {\n var olda = a;\n var oldb = b;\n var oldc = c;\n var oldd = d;\n var olde = e;\n\n for (var j = 0; j < 80; j++) {\n if (j < 16) w[j] = x[i + j];\n else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);\n var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));\n e = d;\n d = c;\n c = rol(b, 30);\n b = a;\n a = t;\n }\n\n a = safe_add(a, olda);\n b = safe_add(b, oldb);\n c = safe_add(c, oldc);\n d = safe_add(d, oldd);\n e = safe_add(e, olde);\n }\n return Array(a, b, c, d, e);\n\n }",
"function core_sha1(x, len) {\n\t/* append padding */\n\tx[len >> 5] |= 0x80 << (24 - len % 32);\n\tx[((len + 64 >> 9) << 4) + 15] = len;\n\n\tvar w = Array(80);\n\tvar a =\t1732584193;\n\tvar b = -271733879;\n\tvar c = -1732584194;\n\tvar d =\t271733878;\n\tvar e = -1009589776;\n\n\tfor(var i = 0; i < x.length; i += 16) {\n\t\tvar olda = a;\n\t\tvar oldb = b;\n\t\tvar oldc = c;\n\t\tvar oldd = d;\n\t\tvar olde = e;\n\n\t\tfor(var j = 0; j < 80; j++) {\n\t\t\tif(j < 16) w[j] = x[i + j];\n\t\t\telse w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);\n\t\t\tvar t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),\n\t\t\t\t\t\t\t\t\t\t\t safe_add(safe_add(e, w[j]), sha1_kt(j)));\n\t\t\te = d;\n\t\t\td = c;\n\t\t\tc = rol(b, 30);\n\t\t\tb = a;\n\t\t\ta = t;\n\t\t}\n\n\t\ta = safe_add(a, olda);\n\t\tb = safe_add(b, oldb);\n\t\tc = safe_add(c, oldc);\n\t\td = safe_add(d, oldd);\n\t\te = safe_add(e, olde);\n\t}\n\treturn Array(a, b, c, d, e);\n\n}",
"function hasher(data) {\n var pre_string = data.lastname + data.firstname + data.gender + data.dob + data.drug;\n var hash = '', curr_str;\n\n hash = Sha1.hash(pre_string);\n\n /**\n // Increment 5 characters at a time\n for (var i = 0, len = pre_string.length; i < len; i += 5) {\n curr_str = '';\n\n // Extract 5 characters at a time\n for (var j = 0; j < 5; j++) {\n if (pre_string[i + j]) {\n curr_str += pre_string[i + j]\n }\n }\n\n // Hash the characters and append to hash\n var temp = mini_hash(curr_str); // Get number from the string\n var fromCode = String.fromCharCode(mini_hash(curr_str));\n hash += fromCode;\n\n } */\n\n\n return hash;\n}",
"function sha1Hmac(pass) {\n sjcl.misc.hmac.call(this, pass, sjcl.hash.sha1);\n }",
"function hash(text) {\n return crypto.createHash('md5').update(text).digest('hex')\n}",
"function generateTrip(str)\n{\n var MD5 = crypto.createHash(\"MD5\");\n MD5.update(str);\n var trip = MD5.digest(\"base64\").slice(0, 6);\n console.log(\"Generated trip \" + trip);\n return trip;\n}",
"inputHash(input) {\n return \"\";\n }",
"function core_hmac_sha1(key, data) \n { \n var bkey = str2binb(key); \n if(bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz); \n \n var ipad = Array(16), opad = Array(16); \n for(var i = 0; i < 16; i++) \n { \n ipad[i] = bkey[i] ^ 0x36363636; \n opad[i] = bkey[i] ^ 0x5C5C5C5C; \n } \n \n var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz); \n return core_sha1(opad.concat(hash), 512 + 160); \n }",
"function createDataHash(data){\n const hash = crypto.createHash('sha256');\n hash.update(data);\n\n return hash.digest('base64');\n}",
"function checksum (str, algorithm, encoding) {\n return crypto\n .createHash(algorithm || 'sha256')\n .update(str, 'utf8')\n .digest(encoding || 'hex');\n}",
"function md5uri64(strings) {\n\tvar sum = crypto.createHash('md5');\n\tstrings.forEach(function(str) {\n\t\tsum.update(str, 'utf8');\n\t});\n\treturn sum.digest('base64').replace(/[\\+\\/=]/g, function(ch) {\n\t\treturn { '+': 'a', '/': 'b', '=': '' }[ch];\n\t});\n}",
"function shortId(body, length) {\n var hmac = __webpack_require__(/*! crypto */ \"crypto\").createHmac('sha1', body).digest();\n var base62 = __webpack_require__(/*! base-x */ \"base-x\")('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');\n var fullkey = base62.encode(hmac);\n return fullkey.slice(0, length); // if length undefined, return the whole thing\n}",
"static async hash(data) {\n if (! (\"subtle\" in window.crypto)) {\n return undefined;\n }\n\n let input = new TextEncoder().encode(data);\n let hash = await window.crypto.subtle.digest(\"SHA-512\", input);\n let bytes = new Uint8Array(hash);\n\t let hex = Array.from(bytes).map(byte => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\n\t return hex.slice(0, 32);\n }",
"toBase64() {\n return this._byteString.toBase64();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constraint: only one change from previous state | function onlyOneChangeFromLastState(){
var constraints = [];
for(var i = 1; i <= 9; i++){
var name = "cell-"+i;
constraints.push(
// Cell changed from un-marked to marked
Logic.and(
// was empty
Logic.equiv(Logic.TRUE, (lastState[name+"$0"] ? Logic.TRUE : Logic.FALSE) ),
// now marked
Logic.equiv(Logic.FALSE, name+"$0")
)
);
}
var constraint = Logic.exactlyOne.apply(Logic.exactlyOne, constraints);
bp.addConstraint(constraint);
} | [
"function SetAnyChangeToTrue()\t\n\t\t{\n\t\t\t//Change has taken place\n\t\t\tanyChange = 1;\n\t\t}",
"function checkChange(index0,index1,funCB){\n var bias_order0=calculateBias_order(arrIndexMap[index0],arrIndexMap[index1])\n var bias_cross0=calculateBias_cross(arrIndexMap[index0],arrIndexMap[index1])\n funCB();\n arrIndexMap[index1]=generateIndexMap(hierarchy_array[index1])\n var bias_order1=calculateBias_order(arrIndexMap[index0],arrIndexMap[index1])\n var bias_cross1=calculateBias_cross(arrIndexMap[index0],arrIndexMap[index1])\n console.log('(',bias_order0,'->',bias_order1,');(',bias_cross0,'->',bias_cross1,')')\n\n }",
"visitConstraint_state(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"previous(attributeName) {\n const arg = this.args[attributeName];\n if (arg && arg.delta(arg, -1)) {\n this.emit('state.change.previous', {\n delta: -1,\n value: arg.values[arg.idx],\n idx: arg.idx,\n name: attributeName,\n instance: this,\n });\n return true;\n }\n return false;\n }",
"haveChanges() {\n return this.code !== this.codeFromTableau;\n }",
"dirty() {\n this.signal();\n }",
"addActivityConstraint(name, newConstraint) {\n let {activities} = this.state;\n let activity = activities[name];\n if (!activity) {\n throw new Error('No activity to add a constraint to for the given activity name: ' + name);\n }\n const constraints = Object.assign({}, activity.constraints);\n constraints[newConstraint] = true;\n activity = Object.assign({}, activity, {constraints});\n activities = Object.assign({}, activities, {[name]: activity});\n this.setState({activities});\n }",
"function checkState(value){\r\n\t\t\t//Checking if value updated violates the LO limit set\r\n\t\t\tif (scope.config.LO.limit != undefined && value <= scope.config.LO.limit) {\r\n\t\t\t\t//If value violates LO check if violates LOLO\r\n\t\t\t\tif (scope.config.LOLO.limit != undefined && value <= scope.config.LOLO.limit) {\r\n\t\t\t\t\tstateChange(\"LOLO\");\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\t\t//If it does not, it violates LO\r\n\t\t\t\t\tstateChange(\"LO\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t//Checking if value updated violates the HI limit set\r\n\t\t\telse if (scope.config.HI.limit != undefined && value >= scope.config.HI.limit) {\r\n\t\t\t\t//If value violates HI check if violates HIHI\r\n\t\t\t\tif (scope.config.HIHI.limit != undefined && value >= scope.config.HIHI.limit) {\r\n\t\t\t\t\tstateChange(\"HIHI\");\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\t\tstateChange(\"HI\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t//Nothing is being Violated Change display back to Normal\r\n\t\t\telse{\r\n\t\t\t\tstateChange(\"Normal\");\r\n\t\t\t}\r\n\t\t}",
"parametersChanged() {\n let arr = Object.entries(this.parameters)\n let res = arr.map(item=>{\n return this.prevParameters[item[0]] == item[1]\n }).find(item=>!item)\n\n this.prevParameters = {...this.parameters}\n return !res\n }",
"function update_throw_state() {\n console.log(\"next throw\");\n if (throwFocus === 1) {\n throwFocus = 2;\n check_if_valid_score();\n $throwFocus = $(\"#throw2\");\n } else if (throwFocus === 2) {\n throwFocus = 3;\n check_if_valid_score();\n $throwFocus = $(\"#throw3\");\n } else {\n throwFocus = 1;\n check_if_valid_score();\n $throwFocus = $(\"#throw1\");\n }\n }",
"function hasActionChanged() {\r\n\r\n return( action !== previousAction );\r\n\r\n }",
"startChanged () {\r\n this.$nextTick(() => {\r\n if (this.model.end) {\r\n this.$validator.validate('end')\r\n }\r\n })\r\n this.errors.remove('start')\r\n }",
"_checkIfDirty(){\n if (this._isDirty === true){\n this._isDirty = false;\n this._refresh();\n }\n }",
"function markedStayMarked(){\n\tvar constraints = [];\n\tfor(var i = 1; i <= 9; i++){\n\t\tvar name = \"cell-\"+i;\n\t\t//if marked\n\t\tif(!lastState[name+\"$0\"]){\n\t\t\tconstraints.push(\n\t\t\t\t// Cell changed from un-marked to marked\n\t\t\t\tLogic.and(\n\t\t\t\t\tLogic.equiv(name+\"$0\", (lastState[name+\"$0\"] ? Logic.TRUE : Logic.FALSE) ),\n\t\t\t\t\tLogic.equiv(name+\"$1\", (lastState[name+\"$1\"] ? Logic.TRUE : Logic.FALSE) ),\n\t\t\t\t\tLogic.equiv(name+\"$2\", (lastState[name+\"$2\"] ? Logic.TRUE : Logic.FALSE) )\n\t\t\t\t)\n\t\t\t);\n\t\t}\n\t}\n\n\tvar constraint = Logic.and.apply(Logic.and, constraints);\n\tbp.addConstraint(constraint);\n}",
"__koRule (tempBoard) {\n // prevents checking invalid indecies of history[], ko rule can't occur\n // during the first 3 moves\n if (this.history.length < 3) {\n return true;\n }\n return !GameBoard.equal(tempBoard, this.history[this.history.length - 2]);\n }",
"function change(x) {\n var u = this;\n var debug = u._upwardableDebug;\n\n if (x !== this.valueOf()) {\n u = make(x, { debug });\n getNotifier(this).notify({object: this, newValue: u, type: 'upward'});\n\n if (debug) {\n console.debug(...channel.debug(\"Replaced upwardable\", this._upwardableId, \"with\", u._upwardableId));\n }\n }\n return u;\n}",
"first(attributeName) {\n const arg = this.args[attributeName];\n\n if (arg && arg.idx !== 0) {\n arg.idx = 0;\n this.emit('state.change.first', {\n value: arg.values[arg.idx],\n idx: arg.idx,\n name: attributeName,\n instance: this,\n });\n return true;\n }\n\n return false;\n }",
"function undo() {\n if (stateCurrent === 0) return false;\n stateCurrent--;\n return true;\n}",
"shouldUpdateState(params) {\n return params.changeFlags.propsOrDataChanged;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Store cast & crew details | function creditsDetails(data, movieData, item) {
movieData[item]['cast'] = data.cast;
movieData[item]['crew'] = data.crew;
movieData[item]['cast_crew'] = combineLists([data.cast, data.crew]);
movieData[item]['cast_crew_stats'] = {'cast': {}, 'crew': {}, 'overall': {}};
return movieData
} // END: creditsDetails | [
"function createCastCrewDIV(person, parent) {\n // creating elements\n var div1 = document.createElement(\"div\");\n var div2 = document.createElement(\"div\");\n var p = document.createElement(\"p\");\n var h4 = document.createElement(\"h4\");\n var a = document.createElement(\"a\");\n\n // assigning classes\n div1.className = \"cast-it\";\n div2.className = \"cast-left\";\n\n // Extracting data for Person Profile Pic e.g. Haroon Rashid = HR\n var dp = person.name.split(\" \")[0][0] + person.name.split(\" \")[1][0];\n\n // Addigning data\n h4.innerText = dp;\n a.innerText = person.name;\n p.innerText = person.job;\n\n // Appending elements\n div2.appendChild(h4);\n div2.appendChild(a);\n div1.appendChild(div2);\n div1.appendChild(p);\n\n // Adding to HTML document\n document.getElementById(parent).appendChild(div1);\n}",
"function handleSaveTheatrePrefInfo(agent) {\n const genere = agent.parameters.genere;\n const titolo = agent.parameters.titolo;\n const autore = agent.parameters.autore;\n\n // Test ok\n const senderID = getSenderID();\n\n // Ottengo la posizione dei contatori delle preferenze\n let theatreTasteCounterPath = admin.database().ref('pazienti/' + senderID + '/counters/teatro');\n\n return theatreTasteCounterPath.once('value').then((snapshot) => {\n\n // Controllo quanti gusti teatrali ha inserito il paziente\n let theatreTasteCounterForUser = snapshot.val();\n console.log('Num gusti teatro gia\\' espressi: ' + theatreTasteCounterForUser);\n\n // Test sender id\n console.log('SenderID: ' + senderID);\n\n // Creo path con id pari a quantita' di preferenze espresse\n let theatreTastePath = admin.database().ref('pazienti/' + senderID + '/preferenze/teatro/' + theatreTasteCounterForUser);\n\n const musica = {\n genere:genere,\n titolo:titolo,\n autore:autore\n };\n\n // Salvo il gusto teatrale\n theatreTastePath.set(musica);\n\n // Incremento il numero di gusti teatrali di una unita'\n let theatreTasteCounterPath = admin.database().ref('pazienti/' + senderID + '/counters/teatro');\n theatreTasteCounterPath.set(theatreTasteCounterForUser + 1);\n });\n }",
"function storeCCData() {\n\tif (!shell.caption.data[shell.currPageId]) {\n\t\tshell.caption.data[shell.currPageId] = new Object();\n\t}\n\t// If content for the main page hasn't already been stored\n\tvar curr = shell.caption.data[shell.currPageId];\n\tif (!curr.mainPage) {\n\t\tcurr.mainPage = new Array();\n\t\tif (currPageData.closedCaption.length != 0 && currPageData.closedCaption != ''){\n\t\t\tvar ccData = currPageData.closedCaption;\n\t\t\tvar storageArray = new Array();\n\t\t\tfor (var i=0, j=ccData.length; i<j; i++) {\n\t\t\t\tvar ccObject = new Object();\n\t\t\t\tccObject.time = ccData[i].time;\n\t\t\t\tccObject.html = ccData[i].html;\n\t\t\t\tstorageArray[storageArray.length] = ccObject;\n\t\t\t}\t\t\n\t\t\tcurr.mainPage = storageArray;\n\t\t\t//console.log(curr);\n\t\t} else {\n\t\t\t//console.log('There is no CC text for this page');\t\n\t\t}\n\t} \n}",
"function handleSaveSportPrefInfo(agent) {\n const genere = agent.parameters.genere;\n const personaggio = agent.parameters.personaggio;\n\n const senderID = getSenderID();\n\n // Ottengo la posizione dei contatori delle preferenze\n let sportTasteCounterPath = admin.database().ref('pazienti/' + senderID + '/counters/sport');\n\n return sportTasteCounterPath.once('value').then((snapshot) => {\n\n // Controllo quanti gusti sport ha inserito il paziente\n let sportTasteCounterForUser = snapshot.val();\n console.log('Num gusti sport gia\\' espressi: ' + sportTasteCounterForUser);\n\n // Test sender id\n console.log('SenderID: ' + senderID);\n\n // Creo path con id pari a quantita' di preferenze espresse\n let sportTastePath = admin.database().ref('pazienti/' + senderID + '/preferenze/sport/' + sportTasteCounterForUser);\n\n const sport = {\n genere:genere,\n personaggio:personaggio,\n };\n\n // Salvo il gusto sportivo\n sportTastePath.set(sport);\n\n // Incremento il numero di gusti sportivi di una unita'\n let sportTasteCounterPath = admin.database().ref('pazienti/' + senderID + '/counters/sport');\n sportTasteCounterPath.set(sportTasteCounterForUser + 1);\n });\n }",
"function handleSaveMoviePrefInfo(agent) {\n const genere = agent.parameters.genere;\n const titolo = agent.parameters.titolo;\n const regista = agent.parameters.regista;\n\n // Test ok\n const senderID = getSenderID();\n\n // Ottengo la posizione dei contatori delle preferenze\n let movieTasteCounterPath = admin.database().ref('pazienti/' + senderID + '/counters/cinema');\n\n return movieTasteCounterPath.once('value').then((snapshot) => {\n\n // Controllo quanti gusti cinematografici ha inserito il paziente\n let movieTasteCounterForUser = snapshot.val();\n console.log('Num gusti cinema gia\\' espressi: ' + movieTasteCounterForUser);\n\n // Test sender id\n console.log('SenderID: ' + senderID);\n\n // Creo path con id pari a quantita' di preferenze espresse\n let movieTastePath = admin.database().ref('pazienti/' + senderID + '/preferenze/cinema/' + movieTasteCounterForUser);\n\n const musica = {\n genere:genere,\n titolo:titolo,\n regista:regista\n };\n\n // Salvo il gusto musicale\n movieTastePath.set(musica);\n\n // Incremento il numero di gusti cinematografici di una unita'\n let movieTasteCounterPath = admin.database().ref('pazienti/' + senderID + '/counters/cinema');\n movieTasteCounterPath.set(movieTasteCounterForUser + 1);\n });\n }",
"addActor(scene, name, actor) {\n //console.log(`\\n@@@ narrative.addActor ${name} actor=${actor}:`);\n //console.dir(actor);\n //console.log(`addActor: et = ${devclock.getElapsedTime()}`);\n if (scene && actor && name && name.length > 0) {\n if (cast[name]) {\n narrative.removeActor(scene, name); //if replace actor with same name?\n }\n actor.name = name; // possible diagnostic use\n cast[name] = actor;\n //console.log(`addActor: et = ${devclock.getElapsedTime()}`);\n //prevent sglens and vrlens from becoming children of sgscene/vrscene\n //NOTE: if exp vrlens is child of vrscene vrcontrols FAIL!\n //NOTE: vrkeymap still works\n if (!/lens/.test(name)) {\n scene.add(actor);\n }\n //console.log(`n.addActor: scene.children.l = ${scene.children.length}`);\n //console.log(`n.addActor: cast size = ${Object.keys(cast).length}`);\n //console.log(`n.addActor: cast = ${Object.keys(cast)}`);\n }\n else {\n console.log(`n.addActor:FAILED to add actor ${actor} w. name ${name}!!`);\n }\n }",
"function getCastAndCrew (cb, movieId) {\n\tlet url = `${API_URL}movie/${movieId}/credits?api_key=${API_KEY}`;\n\tfetch(url, {\n\t\tmethod: 'GET'\n\t}).then(response => response.json()).then(data => {\n\t\tcb(data);\n\t}).catch(err => {\n\t\tconsole.log('error while fetching details', err);\n\t})\n\n}",
"function handleSaveFoodPrefInfo(agent) {\n const tipologia = agent.parameters.tipologia;\n\n const senderID = getSenderID();\n\n // Ottengo la posizione dei contatori delle preferenze\n let foodTasteCounterPath = admin.database().ref('pazienti/' + senderID + '/counters/cibo');\n\n return foodTasteCounterPath.once('value').then((snapshot) => {\n\n // Controllo quanti gusti sport ha inserito il paziente\n let foodTasteCounterForUser = snapshot.val();\n console.log('Num gusti cibo gia\\' espressi: ' + foodTasteCounterForUser);\n\n // Test sender id\n console.log('SenderID: ' + senderID);\n\n // Creo path con id pari a quantita' di preferenze espresse\n let foodTastePath = admin.database().ref('pazienti/' + senderID + '/preferenze/cibo/' + foodTasteCounterForUser);\n\n const food = {\n tipologia:tipologia\n };\n\n // Salvo il gusto sportivo\n foodTastePath.set(food);\n\n // Incremento il numero di gusti alimentari di una unita'\n let foodTasteCounterPath = admin.database().ref('pazienti/' + senderID + '/counters/cibo');\n foodTasteCounterPath.set(foodTasteCounterForUser + 1);\n });\n }",
"function save_type() {\n\tvar type = $('#type_list').find(\":selected\").val();\n\tupdate_cue_type(event_obj.cue_list, cue_id, type);\n}",
"function createCallInfoEntry(){\r\n\tdb.transaction(\r\n\t\tfunction(transaction) {\r\n\t\t\ttransaction.executeSql(\r\n\t\t\t\t'INSERT INTO call_info (patient, assessed, attendant1, attendant1_other, attendant2, attendant2_other, driver, driver_other, ' +\r\n\t\t\t\t' unit_nb, run_nb, respond, milage_start, milage_end, ' + //13\r\n\t\t\t\t' code_en_route, code_return, transported_to, transported_position, time_notified, time_route, time_on_scene, ' + //20\r\n\t\t\t\t' time_depart, time_destination, time_transfer, time_back_service, time_patient_contact, ppe_gloves, ppe_eyes, ppe_reflective, ' +\r\n\t\t\t\t' ppe_isolation, ppe_mask, det1, det2, det3, assistance, other, time)' + //36\r\n\t\t\t\t' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);', \r\n\t\t\t\t[getCurrentPatientId(), 'false', '0', '', '0', '', '0', '', '', '', '', '', '', '', '',\r\n\t\t\t\t'', '0', '', '', '', '', '', '', '', '', 'negative', //23\r\n\t\t\t\t'negative', 'negative', 'negative', 'negative', '', '0', '', '0', '', getSystemTime()], \r\n\t\t\t\tnull,\r\n\t\t\t\terrorHandler\r\n\t\t\t);\r\n\t\t}\r\n\t);\r\n}",
"function doSaveMonster()\r\n{\r\n\tconsole.log(\"saving monster\");\r\n\tvar blank = bestiary[0]; \r\n\tblank.name = $('#m_name').val();\r\n\tblank.classes.class1.name = $('#m_class1').val(); \r\n\tblank.classes.class2.name = $('#m_class2').val();\r\n\tblank.alignment = $('#m_alignment').val();\r\n\tblank.hitPoints.hp = $('#m_hp').val();\r\n\tblank.hitPoints.hitDie = $('#m_hitdie').val(); \r\n\tblank.spatial.size = $('#m_size').val(); \r\n\tblank.combatInfo.ac = $('#m_ac').val(); \r\n\tblank.combatInfo.cr = $('#m_cr').val(); \r\n\tblank.combatInfo.melee = $('#m_melee').val(); \r\n\tblank.combatInfo.ranged = $('#m_ranged').val(); \r\n\tblank.combatInfo.ac_touch = $('#m_actouch').val(); \r\n\tblank.combatInfo.ac_flatFooted = $('#m_acflat').val(); \r\n\tblank.savingThrows.fort = $('#m_forts').val(); \r\n\tblank.savingThrows.ref = $('#m_refs').val(); \r\n\tblank.savingThrows.wil = $('#m_wils').val(); \r\n\r\n\tblank.abilityScores.str = $('#m_str').val(); \r\n\tblank.abilityScores.dex = $('#m_dex').val(); \r\n\tblank.abilityScores.con = $('#m_con').val(); \r\n\tblank.abilityScores.int = $('#m_int').val(); \r\n\tblank.abilityScores.wis = $('#m_wis').val();\r\n\tblank.abilityScores.cha = $('#m_cha').val(); \r\n\r\n\tblank.notes = $('#notesarea').val();\r\n\r\n\tblank.classes.class1.levels = $('#m_class1levels').val(); \r\n\tblank.classes.class2.levels = $('#m_class2levels').val(); \r\n\r\n\tvar skills = $('#m_skills').val(); \r\n\tskills = skills.split(','); \r\n\tfor(var i = 0; i < skills.length; i++)\r\n\t{\r\n\t\tblank.skills.push(skills[i]);\r\n\t}\r\n\r\n\tvar feats = $('#m_feats').val(); \r\n\tfeats = feats.split(','); \r\n\tfor(var i = 0; i < feats.length; i++)\r\n\t{\r\n\t\tblank.feats.push(feats[i]);\r\n\t}\r\n\r\n\tconsole.log(blank);\r\n\r\n\r\n\t var a = document.createElement('div'); \r\n\t $(a).addClass('iconarea')\r\n\t var b = document.createElement('div'); \r\n\t $(b).addClass('monstericon genericicon');\r\n\t $(a).append(b); \r\n\t var p = document.createElement('p'); \r\n\t $(p).html(blank.name);\r\n\t $(a).append(p); \r\n\t $('#newmonster').before(a);\r\n}",
"saveVisit() {\n\t\tthis.errorBox.style.display = \"none\";\n\n\t\t//Assemble the names.\n\t\tvar name = \"\";\n\t\tvar nameTokens = this.namesBox.querySelectorAll(\".name-token\");\n\t\tfor (var i = 0; i < nameTokens.length; i++) {\n\t\t\tvar token = nameTokens[i];\n\t\t\tif (name != \"\") {\n\t\t\t\tname += \", \";\n\t\t\t}\n\t\t\tname += nameTokens[i].innerText;\n\t\t}\n\n\t\t//If there are no names, display an error.\n\t\tif (name == \"\") {\n\t\t\tthis.errorBox.innerText = \"Du musst mindestens einen Namen eingeben.\";\n\t\t\tthis.errorBox.style.display = \"\";\n\t\t\treturn;\n\t\t}\n\n\t\t//Gather the served meals.\n\t\tvar meals = [ ];\n\t\tvar mealRows = this.servedMealsContainer.querySelectorAll(\".meal-row\");\n\t\tfor (var i = 0; i < mealRows.length; i++) {\n\t\t\tvar row = mealRows[i];\n\t\t\tvar mealTypeField = row.querySelector(\".meal-type-field\");\n\t\t\tvar mealField = row.querySelector(\".meal-field\");\n\n\t\t\t//If both fields are empty, skip this meal row.\n\t\t\tif (!mealTypeField.value && !mealField.value) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tmeals.push({\n\t\t\t\tmeal_type: mealTypeField.value,\n\t\t\t\tmeal: mealField.value\n\t\t\t});\n\t\t}\n\n\t\tvar visit = {\n\t\t\tname: name,\n\t\t\tdate: this.dateField.value,\n\t\t\tvisit_type: this.visitTypeSelect.value,\n\t\t\tvisit_purpose: this.visitPurposeField.value,\n\t\t\tmeals: meals,\n\t\t\tbrought_items: this.broughtItemsField.value,\n\t\t\tdescription: this.descriptionField.value\n\t\t};\n\n\t\tif (this.visitId) {\n\t\t\tvisit.visit_id = this.visitId;\n\t\t}\n\n\t\tthis.saveVisitRequest.send(visit);\n\t}",
"function storeTrainInfo() {\n database.ref(\"/trainData\").push({\n trainName: trainName\n ,destination: destination\n ,firstTrain: firstTrain\n ,frequency: freq\n })\n}",
"function storeToLS(tvShow) {\n seriesObj = {\n Id: tvShow.id,\n First_air_date: tvShow.first_air_date,\n Name: tvShow.name,\n Origin_country: tvShow.origin_country,\n Original_language: tvShow.original_language,\n Overview: tvShow.overview,\n Popularity: tvShow.popularity,\n Poster_path: imagePath + tvShow.poster_path\n }\n extras = {\n\n Backdrop_path: imagePath + tvShow.backdrop_path,\n Genre_ids: tvShow.genre_ids\n\n }\n totalSeries = {\n seriesObj,\n extras\n }\n localStorage.setItem(\"series\", JSON.stringify(totalSeries));\n}",
"function handleReadAllTheatrePrefInfo(agent) {\n // Payload base\n var localBasePayload = fbBasePayload;\n var senderID = getSenderID();\n\n return admin.database().ref('pazienti/' + senderID + '/preferenze/teatro/').once('value').then((snapshot) => {\n let theatrePref = snapshot.val();\n console.log('snapshot.val() : ' + JSON.stringify(theatrePref));\n let i;\n\n let elements = [];\n\n let tgTitle = \"Generi:\";\n let tgSubtitle = \"Titoli e autori:\";\n\n if (theatrePref !== null) {\n for (i=0; i < theatrePref.length; i++) {\n let genere = snapshot.child(i.toString() + '/genere').val();\n let titolo = snapshot.child(i.toString() + '/titolo').val();\n let autore = snapshot.child(i.toString() + '/autore').val();\n\n if (senderID.toString().length > 9) {\n let title = 'Genere: ' + genere;\n let subtitle = 'Titolo: ' + titolo + '\\n' + 'Autore: ' + autore;\n elements[i] = element(title, teatroURL, subtitle);\n localBasePayload.facebook.attachment.payload.elements[i] = elements[i];\n } else {\n\n if (i == theatrePref.length - 1) {\n tgTitle += \" \" + genere;\n tgSubtitle += \" \" + titolo + \" - \" + autore;\n } else {\n tgTitle += \" \" + genere + \",\";\n tgSubtitle += \" \" + titolo + \" - \" + autore + \",\";\n }\n\n }\n }\n if (senderID.toString().length > 9) {\n agent.add(new Payload('FACEBOOK', localBasePayload, {rawPayload: true, sendAsMessage: true}));\n } else {\n tgCard(teatroURL, tgTitle, tgSubtitle);\n }\n } else {\n let question = 'Non mi hai parlato delle tue preferenze teatrali! Ti va di aggiungerle?';\n let suggestions = [\n \"Teatro\",\n 'Più tardi',\n \"No grazie\",\n \"Cancella\"\n ];\n setSuggestions(question, suggestions, senderID);\n }\n });\n }",
"function storePageViewData() {\n storeVisit(itemId, new Visit({\n commentCount,\n maxCommentId,\n time: new Date(),\n }))\n }",
"function setupCastReceiver() {\n window.castReceiverManager = cast.receiver.CastReceiverManager.getInstance();\n\n window.castReceiverManager.onSenderConnected = function(event) {\n senders = window.castReceiverManager.getSenders();\n printDebugMessage(\"connected senders\", senders);\n }\n\n window.castReceiverManager.onSenderDisconnected = function(event) {\n senders = window.castReceiverManager.getSenders();\n // if the last sender disconnects, then stop the cast session entirely if it\n // was an explicit disconnection\n if ((senders.length === 0) && (event.reason == cast.receiver.system.DisconnectReason.REQUESTED_BY_SENDER)) {\n if (player !== null){\n player.destroy(function(){\n window.castReceiverManager.stop();\n });\n } else {\n window.castReceiverManager.stop();\n } \n }\n }\n\n window.castReceiverManager.onShutdown = function(event) {\n senders = window.castReceiverManager.getSenders();\n }\n }",
"getPokeDetails() {\n let pokeData = this.state;\n return {\n name: pokeData.name,\n imgData: this.getPokeImgs(pokeData.sprites),\n type: this.getPokeType(pokeData.types),\n hp: pokeData.base_experience,\n weight: pokeData.weight,\n height: pokeData.height,\n stats: this.getPokeStats(pokeData.stats),\n moves: this.getPokeMoves(pokeData.moves)\n }\n }",
"function handleReadAllSportPrefInfo(agent) {\n // Payload base\n var localBasePayload = fbBasePayload;\n var senderID = getSenderID();\n\n return admin.database().ref('pazienti/' + senderID + '/preferenze/sport/').once('value').then((snapshot) => {\n let sportPref = snapshot.val();\n console.log('snapshot.val() : ' + JSON.stringify(sportPref));\n let i;\n\n let elements = [];\n let tgTitle = 'Sport:';\n let tgSubtitle = 'Personaggio:';\n\n if(sportPref !== null) {\n for (i=0; i < sportPref.length; i++) {\n let genere = snapshot.child(i.toString() + '/genere').val();\n let personaggio = snapshot.child(i.toString() + '/personaggio').val();\n\n if (senderID.toString().length > 9) {\n let title = 'Sport: ' + genere;\n let subtitle = 'Personaggio: ' + personaggio;\n elements[i] = element(title, sportURL, subtitle);\n localBasePayload.facebook.attachment.payload.elements[i] = elements[i];\n } else {\n if (i == sportPref.length - 1) {\n tgTitle += \" \" + genere;\n tgSubtitle += \" \" + personaggio;\n } else {\n tgTitle += \" \" + genere + \",\";\n tgSubtitle += \" \" + personaggio;\n }\n }\n }\n if (senderID.toString().length > 9) {\n agent.add(new Payload('FACEBOOK', localBasePayload, {rawPayload: true, sendAsMessage: true}));\n } else {\n tgCard(sportURL, tgTitle, tgSubtitle);\n }\n } else {\n let question = 'Non mi hai parlato delle tue preferenze sportive. Vuoi aggiungerlo?';\n let suggestions = [\n \"Sport\",\n 'Più tardi',\n \"No grazie\",\n \"Cancella\"\n ];\n setSuggestions(question, suggestions, senderID);\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if the user and partner share a number of similar kinks. | function similiarKinks(userKinks, partnerKinks, similarities) {
var similar = 0;
for (var i = 0; i < userKinks.length; i++) {
if (partnerKinks.indexOf(userKinks[i]) !== -1) {
similar++;
}
if (similar >= similarities) {
return true;
}
}
return false;
} | [
"function userHasBeenReferredByPartnerWhoSuppliesPromocodes() {\n for (var i = 0; i < referralPartnersWhoSupplyPromocodes.length; i++) {\n if (linkshareReferrerID == referralPartnersWhoSupplyPromocodes[i]) { // If the referrer is in the list of referral partners who supply voucher codes\n console.log('The user has been referred by a partner who supplies promocodes');\n return true;\n break;\n }\n }\n console.log('The user has not been referred by a partner who supplies coupons.');\n return false; // If the user has not been referred by a partner who supplies coupons, then return false. This means the pixel can still fire.\n }",
"function checkNumFavs(){\n if( conf.minFavs && tweet.favorited && conf.minFavs <= tweet.favorite_count ){\n console.log('Keeping tweet favourited '+tweet.favorite_count+' times');\n return nextTweet();\n }\n checkTags();\n }",
"function checkOwnFavs(){\n if( ! conf.ownFavs || ! tweet.favorited ){\n return checkFinal();\n }\n checkOwnFavourite( tweet.id_str, function( favourited ){\n if( favourited ){\n console.log('Keeping tweet favourited by self');\n return nextTweet();\n }\n checkFinal();\n } );\n }",
"checkKingsStatus(player){\n\t\tlet tile = this.boardMatrix[player.figureList.King[0].positionY][player.figureList.King[0].positionX];\n\t\tfor(let threat of tile.threatenedBy){\n\t\t\tif(player.number !== threat.team) return true;\n\t\t}\n\t\treturn false;\n\t}",
"function validateSharedElectronsCount() {\n var type, i, len;\n\n for (i = 0, len = engine.getNumberOfAtoms(); i < len; i++) {\n atoms.sharedElectrons[i] = 0;\n }\n\n for (i = 0, len = engine.getNumberOfRadialBonds(); i < len; i++) {\n type = getBondType(i);\n atoms.sharedElectrons[radialBonds.atom1[i]] += type;\n atoms.sharedElectrons[radialBonds.atom2[i]] += type;\n }\n }",
"allChecked() {\n return this.playedUser === this.remainingUsers\n }",
"async function checkTweetIsLikedByUser (id, user) {\n // get the likes\n const likes = await getTweetLikes(id)\n // look for the user among the likes\n return !!likes.find(likeUserName => likeUserName === user)\n }",
"async function likeAlot(n, maxUsers){\n\tlet i = 0;\n\twhile (i++ <= n){\n\t\tlet user = gen.getRandomInt(1, maxUsers);\n\t\tlet profileId = gen.getRandomInt(1, maxUsers);\n\t\tif (user != profileId)\n\t\t\tawait likeUser(user, profileId);\n\t}\n}",
"function sockMerchant(n, ar) {\n const socks = ar.sort();\n let sockCount = 0;\n let currentSock = null;\n let prevSock = null;\n let pairs = 0;\n\n for (let i = 0; i < socks.length; i++) {\n prevSock = currentSock;\n currentSock = socks[i];\n\n if (currentSock === prevSock) {\n if (sockCount >= 2) {\n sockCount = 1;\n } else {\n sockCount += 1;\n }\n } else {\n sockCount = 1;\n }\n\n if (sockCount === 2) {\n pairs += 1;\n }\n }\n\n return pairs;\n}",
"isStrongerThan(hand) {\n // ˅\n return this.judgeGame(hand) === 1;\n // ˄\n }",
"function checkAllBidsResponseReceived(){\n\t\tvar available = true;\n\n\t\tutils._each(bidResponseReceivedCount, function(count, bidderCode){\n\t\t\tvar expectedCount = getExpectedBidsCount(bidderCode);\n\n\t\t\t// expectedCount should be set in the adapter, or it will be set\n\t\t\t// after we call adapter.callBids()\n\t\t\tif ((typeof expectedCount === objectType_undefined) || (count < expectedCount)) {\n\t\t\t\tavailable = false;\n\t\t\t}\n\t\t});\n\n\t\treturn available;\n\t}",
"checkNaturalWin(){\n let win = false;\n\n //Player has natural 9\n if(this.playerHand.total === 9 && this.bankerHand.total <= 8 || \n //Player has natural 8\n this.playerHand.total === 8 && this.bankerHand.total <= 7 \n ){\n this.playerHand.win = true;\n win = true;\n }\n //Banker has a natural 9\n else if(this.bankerHand.total === 9 && this.playerHand.total <= 8 || \n //Player has natural 8\n this.bankerHand.total === 8 && this.playerHand.total <= 7 \n ){\n this.bankerHand.win = true;\n win = true;\n }\n\n return win;\n }",
"function getPlayersOverVerify(objForm) {\n\tvar playersNumber = parseInt(objForm.total_players.value);\n\tvar playersMax = parseInt(objForm.max_players.value);\n\t\n\tif (playersNumber > playersMax) {\n\t\tvar answer = confirm(\"There will be \" + playersNumber + \" players when only \" + playersMax + \" players are allowed! Are you sure you want to override this setting?\");\n\t\t\n\t\tif (answer === true) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t} \n\t}\n\t\n\treturn true;\n}",
"function allSecureConnectionsEstablished(game){\n return game.secure_channels.length == Math.pow(game.players.length,2)-game.players.length\n}",
"function sameNumberOfEvens(n1,n2){\n //inputs: two numbers (ints?)\n //outputs: true or false\n //data storage -- might get away with simple n1Evens and n2Evens counts\n arr1 = [...n1.toString()];\n arr2 = [...n2.toString()];\n n1Evens = 0;\n n2Evens = 0;\n for(let i = 0; i<arr1.length; i++) {\n if(arr1[i] % 2 === 0) {n1Evens++}\n }\n for(let j = 0; j<arr2.length; j++) {\n if(arr2[j] % 2 === 0) {n2Evens++}\n }\n return n1Evens === n2Evens;\n}",
"isPokerHand(cards) {\n if (cards.length != 5) {\n return 'false';\n }\n\n var flushSuit = cards[0].getSuit();\n var prevRank = cards[0].getRank();\n\n var i;\n // check if STRAIGHT FLUSH / ROYAL FLUSH\n for (i = 1; i < cards.length; i++) {\n if ((cards[i].getSuit() == flushSuit) && (cards[i].getRank() == (prevRank + 1))) {\n prevRank = cards[i].getRank();\n }\n else if (cards[i].getRank() === 2 && prevRank === 14) {\n // if the card is a 2, it could be valid\n prevRank = cards[i].getRank();\n }\n else {\n break;\n }\n }\n if (i == cards.length) {\n return 'sf';\n }\n\n // check if FOUR OF A KIND\n var sameCardCount = 1;\n prevRank = cards[0].getRank();\n for (i = 1; i < cards.length; i++) {\n\n if (sameCardCount == 4) {\n // 4 cards in a row\n return '4k';\n }\n else if (cards[i].getRank() == prevRank) {\n // card is set, increase rank\n sameCardCount++;\n }\n else {\n // card is not set, set it and update rank\n sameCardCount = 1;\n prevRank = cards[i].getRank();\n }\n }\n if (sameCardCount == 4) {\n return \"4k\";\n }\n\n // check if FULL HOUSE\n let firstCardCount = 1;\n let firstRank = cards[0].getRank();\n let secondCardCount = 0;\n let secondRank = null;\n\n for (i = 1; i < cards.length; i++) {\n if (cards[i].getRank() == firstRank) {\n // card is same as first card\n firstCardCount++;\n }\n else if (secondRank == null) {\n // second rank is not set, set it and \n // update count\n secondRank = cards[i].getRank();\n secondCardCount++;\n }\n else if (cards[i].getRank() == secondRank) {\n // second rank is set and card is same, \n // update counts\n secondCardCount++;\n }\n else {\n // second rank is set, card is not same\n // thus not a full house\n break;\n }\n }\n if ((firstCardCount + secondCardCount) == 5) {\n return \"fh\";\n }\n\n\n // check if STRAIGHT\n prevRank = cards[0].getRank();\n\n for (i = 1; i < cards.length; i++) {\n // to be a straight, the cards must be in ascending order by rank\n if (cards[i].getRank() == (prevRank + 1)) {\n prevRank = cards[i].getRank();\n }\n else if (cards[i].getRank() === 2 && prevRank === 14) {\n // if the card is a 2, and the previous is an ace, it could be valid\n prevRank = cards[i].getRank();\n }\n else {\n break; // not a straight, but could be another poker hand\n }\n }\n if (i == cards.length) {\n return 's';\n }\n\n // check if FLUSH\n for (i = 1; i < cards.length; i++) {\n // to be a flush, the cards must have the same suit\n if (!(cards[i].getSuit() == flushSuit)) {\n break; // not a flush, but could be another poker hand\n }\n }\n // check if we got to the end of the loop\n if (i == cards.length) {\n return 'f';\n }\n\n // none of the poker hands are valid\n return 'false';\n }",
"function berserkableBy(data) {\n return data.tournament &&\n data.tournament.berserkable &&\n isPlayerPlaying(data) &&\n playedTurns(data) < 2 &&\n !berserkOf(data, data.player.color);\n}",
"function numberOfPairs(gloves) {\n gloves = gloves.sort();\n let count = 0;\n for (let i = 0; i < gloves.length; i++) {\n if (gloves[i] === gloves[i+1]) {\n count += 1;\n i++;\n }\n }\n return count;\n}",
"function userHasBeenReferredByPartnerWhoSuppliesPromocodesAndUserUsedPromocode() {\n if (userHasBeenReferredByPartnerWhoSuppliesPromocodes() == true) {\n if (digitalData.bag.promocodes.length > 0) {\n console.log('The user has come from a referral partner who provides a promocode, and they used promocode(s) \"' + digitalData.bag.promocodes + '\"');\n return true;\n }\n else {\n console.error('The user came from a referral partner that provides promocodes, but did not apply any promocodes. The pixel will not fire.');\n return false; // return false if the user did not use a promocode from a referral partner.\n }\n }\n }",
"function calculateRecall(user, recommendations) {\n const visitedPlaces = getVisitedPlaces(user);\n\n let matches = 0;\n\n visitedPlaces.forEach(visitedPlace => {\n if (recommendations.indexOf(visitedPlace) > -1) {\n matches++;\n }\n });\n\n return matches/visitedPlaces.length;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load the viewer document called when user click the load button in UI | function LoadDocumentBtnClicked()
{
//Initialize Viwer
OnInitializeViwer();
//get the document provided by the user
documentId = document.getElementById("DocIdTB").value;
//load the document
Autodesk.Viewing.Document.load(documentId, Autodesk.Viewing.Private.getAuthObject(), onSuccessDocumentLoadCB, onErrorDocumentLoadCB);
//update the command line text.
UpdateCommandLine("Loading document : " + documentId);
} | [
"static loadDocument(urn) {\n\n return new Promise((resolve, reject) => {\n\n const paramUrn = !urn.startsWith('urn:')\n ? 'urn:' + urn\n : urn\n\n Autodesk.Viewing.Document.load(paramUrn, (doc) => {\n\n resolve(doc)\n\n }, (error) => {\n\n reject(error)\n })\n })\n }",
"function onFileLoaded(doc) {\n collaborativeString = doc.getModel().getRoot().get('collabString');\n wireTextBoxes(collaborativeString);\n}",
"function previewOnLoad() {\n pwindow = iframe.contentWindow;\n var p$ = pwindow && pwindow.$; // preview jquery object\n if (!p$ || p$.editorLoaded) return; // not ready || already initialized\n\n var pdoc = pwindow.document;\n\n // handle pane adjust event over preview\n pdoc.addEventListener('dragover', function(e) {\n adjustPanes(e.clientX, e.clientY, true); // handle over preview\n e.preventDefault();\n });\n\n // handle pane adjuster drop event over preview\n // (firefox will try to navigate to the url if text is dropped on it)\n pdoc.addEventListener('drop', function(e) {\n e.preventDefault();\n });\n\n pRef = pwindow.pubRef || {};\n var relPath = pRef.relPath || '';\n\n $css = p$('<link rel=\"stylesheet\" href=\"' + relPath + '/pub/css/pub-preview.css\">');\n p$('head').append($css);\n $css.get(0).disabled = true;\n\n var $script = p$('<script src=\"' + relPath + '/pub/js/pub-preview.js\"></script>');\n p$('body').append($script);\n\n p$.editorLoaded = true;\n clearInterval(previewPoller);\n }",
"function _SourceViewer() {\r\n\r\n\r\n\r\n\t\t/**\r\n\t\t * CONSTANTS\r\n\t\t * Private members that aren't ment to be altered in any way.\r\n\t\t * @private\r\n\t\t * @constant\r\n\t\t */\r\n\t\t// @AIR runtime:\r\n\t\tvar HTMLLoader = window.runtime.flash.html.HTMLLoader;\r\n\t\tvar NativeWindowInitOptions = window.runtime.flash.display.\r\n\t\t\t\t\t\t\t\t\t NativeWindowInitOptions;\r\n\t\tvar Rectangle = window.runtime.flash.geom.Rectangle;\r\n\t\tvar NativeWindowType = window.runtime.flash.display.\r\n\t\t NativeWindowType;\r\n\t\tvar File = window.runtime.flash.filesystem.File;\r\n\t\tvar FileStream = window.runtime.flash.filesystem.\r\n\t\t FileStream;\r\n\r\n\t\t// @application\r\n\t\tvar VALID_EXTENSIONS = ['txt', 'xml', 'mxml', 'htm', 'html',\r\n\t\t 'js', 'as', 'css', 'properties', \r\n\t\t 'config', 'ini', 'bat', 'readme'];\r\n\r\n\t\t// @events\r\n\t\tvar WINDOW_CREATED_EVENT = 'windowCreatedEvent';\r\n\t\tvar FILES_LIST_READY_EVENT = 'filesListReadyEvent';\r\n\t\tvar FILE_LISTED_EVENT = 'fileListedEvent';\r\n\t\tvar FOLDER_CHECKED_EVENT = 'folderCheckedEvent';\r\n\t\tvar FOLDER_FIRST_CLICKED_EVENT = 'folderFirstClickedEvent';\r\n\t\tvar FOLDER_STATE_CHANGED_EVENT = 'folderStateChanged';\r\n\t\tvar ITEM_MOUSE_OVER_EVENT = 'itemMouseOverEvent';\r\n\t\tvar ITEM_MOUSE_OUT_EVENT = 'itemMouseOutEvent';\r\n\t\tvar ITEM_MOUSE_CLICK_EVENT = 'itemMouseClickEvent';\r\n\t\tvar FILE_ITEM_CLICKED = 'fileItemClicked';\r\n\t\tvar BROWSER_UNLOAD_EVENT\t = 'browserUnloadEvent'; \r\n\t\t\r\n\t\tvar FILE_CONTENT_READY_EVENT = 'fileContentReady';\r\n\r\n\t\t// @strings\r\n\t\tvar CANNOT_READ_TEXT_MESSAGE = 'Cannot retrieve text content from ' +\r\n\t\t\t 'this filetype.';\r\n\t\tvar IO_ERROR_MESSAGE = 'An IO Error occured while trying to ' +\r\n\t\t\t\t 'read this text.';\r\n\t\tvar TREE_DESCRIPTION_MESSAGE = 'Select a source file in the tree to ' +\r\n\t\t\t 'see its content in the right pane:';\r\n\t\tvar COPYRIGHT_MESSAGE = '� 2007 Copyright Adobe Systems ' +\r\n\t\t\t\t 'Incorporated';\r\n\r\n\r\n\r\n\t\t/**\r\n\t\t * The DOMProvider instance shared by all application components. It\r\n\t\t * will get instantiated by WindowsManager.makeMainWindow().\r\n\t\t * @field\r\n\t\t * @private\r\n\t\t */\r\n\t\tvar domProvider;\r\n\t\t\r\n\t\t/**\r\n\t\t * The CSSProvider instance shared by all application components. It\r\n\t\t * will get instantiated by WindowsManager.makeMainWindow().\r\n\t\t * @field\r\n\t\t * @private \r\n\t\t */\t\t\r\n\t\tvar cssProvider;\r\n\t\t\r\n\t\t/**\r\n\t\t * The UIBuilder instance shared by all application components. It\r\n\t\t * will get instantiated by WindowsManager.makeMainWindow().\r\n\t\t * @field\r\n\t\t * @private\r\n\t\t */\r\n\t\tvar uiBuilder;\r\n\t\t\r\n\t\t/**\r\n\t\t * The EventManager instance shared by all application components.\r\n\t\t * @field\r\n\t\t * @private \r\n\t\t */\r\n\t\tvar eventManager = new EventManager();\r\n\t\t\r\n\t\t/**\r\n\t\t * The WindowsManager instance shared by all application components.\r\n\t\t * @field\r\n\t\t * @private\r\n\t\t */\r\n\t\tvar windowManager = new WindowsManager();\r\n\t\t\r\n\t\t/**\r\n\t\t * The LayoutProvider instance shared by all application components.\r\n\t\t * @field\r\n\t\t * @private\r\n\t\t */\r\n\t\tvar layoutProvider = new LayoutProvider();\r\n\r\n\t\t/**\r\n\t\t * The FileSystemWalker instance shared by all application components.\r\n\t\t * @field\r\n\t\t * @private\r\n\t\t */\t\t\r\n\t\tvar fileSystemWalker = new FileSystemWalker();\r\n\t\r\n\t\t/**\r\n\t\t * The main method to be called by the client programmer. Opens the \r\n\t\t * Source Viewer UI and lists the first level of source files.\r\n\t\t * @method\r\n\t\t * @public\r\n\t\t */\t\r\n\t\tthis.viewSource = function() {\r\n\t\t\teventManager.addListener(WINDOW_CREATED_EVENT, function(event){\r\n\t\t\t\tinitUI(event.body.window.document);\r\n\t\t\t})\r\n\t\t\twindowManager.makeMainWindow (function(oWindow) {});\r\n\t\t}\r\n\t\t\r\n\t\t/**\r\n\t\t * Holds the configuration object provided bythe client programmer.\r\n\t\t * @field\r\n\t\t * @private\r\n\t\t */\r\n\t\tvar oConfig = {};\r\n\t\t\r\n\t\t/**\r\n\t\t * Also part of the public API. Transmits the settings to the internal\r\n\t\t * core.\r\n\t\t * @method\r\n\t\t * @public\r\n\t\t * @param cfg { Object }\r\n\t\t * \t\tObject literal containing settings for the Source Viewer.\r\n\t\t * \t\tCurrently only supports:\r\n\t\t * \t\t- exclude { Array }\r\n\t\t * \t\t\tAn app root relative array of paths. Files or folders\r\n\t\t * \t\t\tstarting with one of these paths will not show in the tree. \r\n\t\t */\r\n\t\tthis.setup = function (cfg) {\r\n\t\t\toConfig = cfg;\r\n\t\t}\r\n\r\n\t\t/**\r\n\t\t * Checks whether the given 'file' is to be hidden according to config\r\n\t\t * regulations.\r\n\t\t * @method\r\n\t\t * @private\r\n\t\t * @param file { File }\r\n\t\t * \t\tThe file to check.\r\n\t\t */\r\n\t\tfunction isFileToBeHidden( file ) {\r\n\t\t\tvar url = Utils.getRelativeURL(file.url);\r\n\t\t\tvar toHide = oConfig.exclude;\r\n\t\t\tif (toHide) {\r\n\t\t\t\tfor(var i=0; i<toHide.length; i++) {\r\n\t\t\t\t\tif(toHide[i] == url) { return true }\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\t/**\r\n\t\t * Initializes the application UI.\r\n\t\t * @method\r\n\t\t * @private\r\n\t\t * @param oDocument { HTML Document Object }\r\n\t\t * \t\tThe document object to be used by classes responsible with UI\r\n\t\t * \t\tcreation.\r\n\t\t */\r\n\t\tfunction initUI (oDocument) {\r\n\t\t\tcssProvider = new CSSProvider(oDocument);\r\n\t\t\tdomProvider = new DOMProvider(oDocument);\r\n\t\t\tuiBuilder = new UIBuilder(domProvider);\r\n\t\t\tvar UI = uiBuilder.createMainLayout();\r\n\t\t\teventManager.addListener(BROWSER_UNLOAD_EVENT, function(event) {\r\n\t\t\t\tunloadAll();\r\n\t\t\t})\r\n\t\t\tpopulateTree(UI.tree);\r\n\t\t}\r\n\t\t\r\n\t\t/**\r\n\t\t * Fills the tree with the first level of files.\r\n\t\t * @method\r\n\t\t * @private\r\n\t\t * @param treeRoot { HTML Element }\r\n\t\t * \t\tAn HTML Element representing the root of the tree.\r\n\t\t */\r\n\t\tfunction populateTree (treeRoot) {\r\n\t\t\teventManager.addListener(FILES_LIST_READY_EVENT, function(event){\r\n\t\t\t\tuiBuilder.displayFilesList(treeRoot, event.body.filesList);\r\n\t\t\t\tcssProvider.updateCSS();\r\n\t\t\t\t// @this is a one-time callback:\r\n\t\t\t\teventManager.removeListener(FILES_LIST_READY_EVENT,\r\n\t\t\t\t\targuments.callee);\r\n\t\t\t});\r\n\t\t\tfileSystemWalker.makeInitialQuery();\r\n\t\t}\r\n\r\n\t\t/**\r\n\t\t * Frees memory after the Source Viewer is closed.\r\n\t\t * @method\r\n\t\t * @private \r\n\t\t */\r\n\t\tfunction unloadAll() {\r\n\t\t\tcontext.instance = null;\r\n\t\t}\r\n\r\n\t\t/**\r\n\t\t * CLASS\r\n\t\t * \t\tWindowsManager\r\n\t\t * DESCRIPTION\r\n\t\t * \t\tHandles window creation and manipulation for this application.\r\n\t\t * SAMPLE USAGE\r\n\t\t * \t\tN/A (internal use only)\r\n\t\t * @class\r\n\t\t * @private\r\n\t\t */\r\n\t\t function WindowsManager () {\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Flag to raise while the main window is open.\r\n\t\t\t * @field\r\n\t\t\t * @private\r\n\t\t\t */\r\n\t\t\tvar isMainWindowOpen = false;\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Returns the default display options for a newly created window.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @return { NativeWindowInitOptions }\r\n\t\t\t * \t\tAn object specifying display options for a new window. \r\n\t\t\t */\r\n\t\t\tfunction getDefWindowOptions () {\r\n\t\t\t\tvar options = new NativeWindowInitOptions();\r\n\t\t\t\toptions.type = NativeWindowType.UTILITY;\r\n\t\t\t\treturn options;\r\n\t\t\t}\r\n\r\n\t\t\t/**\r\n\t\t\t * Returns the default display boundaries for a newly created \r\n\t\t\t * window.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @return { Rectangle }\r\n\t\t\t * \t\tA rectangle defining the boundaries of this new window.\r\n\t\t\t */\t\t\t\r\n\t\t\tfunction getDefBoundaries () {\r\n\t\t\t\tvar bounds = new Rectangle();\r\n\t\t\t\tbounds.x = Math.max(0, (screen.width-800)/2);\r\n\t\t\t\tbounds.y = Math.max(0, (screen.height-600)/2);\r\n\t\t\t\tbounds.width = 800;\r\n\t\t\t\tbounds.height = 600;\r\n\t\t\t\treturn bounds;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Creates the main window of the application.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t */\r\n\t\t\tthis.makeMainWindow = function () {\r\n\t\t\t\tvar htmlLoader = HTMLLoader.createRootWindow (\r\n\t\t\t\t\ttrue,\r\n\t\t\t\t\tgetDefWindowOptions(), \r\n\t\t\t\t\tfalse,\r\n\t\t\t\t\tgetDefBoundaries()\r\n\t\t\t\t);\r\n\t\t\t\thtmlLoader.addEventListener('htmlDOMInitialize', function() {\r\n\t\t\t\t\tisMainWindowOpen = true;\r\n\t\t\t\t\tmakeWindowModal (htmlLoader.window, self);\r\n\t\t\t\t\thtmlLoader.window.nativeWindow.addEventListener (\r\n\t\t\t\t\t\t'close',\r\n\t\t\t\t\t\t function() {isMainWindowOpen = false}\r\n\t\t\t\t\t);\r\n\t\t\t\t\tvar event = eventManager.createEvent(\r\n\t\t\t\t\t\tWINDOW_CREATED_EVENT,\r\n\t\t\t\t\t\t{'window': htmlLoader.window}\r\n\t\t\t\t\t);\r\n\t\t\t\t\teventManager.fireEvent(event);\r\n\t\t\t\t});\r\n\t\t\t\thtmlLoader.loadString(' ');\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Makes a window modal to a certain parent window.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param oWindow { Object Window }\r\n\t\t\t * \t\tThe window to be made modal.\r\n\t\t\t * @param oParentWindow { Object Window }\r\n\t\t\t * \t\tThe parent of the modal window. Any attempt to access the \r\n\t\t\t * \t\tparent while the modal window is open will fail.\r\n\t\t\t */\r\n\t\t\tfunction makeWindowModal (oWindow, oParentWindow) {\r\n\t\t\t\t\r\n\t\t\t\toParentWindow.nativeWindow.addEventListener (\r\n\t\t\t\t\t'closing',\r\n\t\t\t\t\tfunction (event) {\r\n\t\t\t\t\t\t//if (isMainWindowOpen) { event.preventDefault() };\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\toParentWindow.nativeWindow.addEventListener (\r\n\t\t\t\t\t'displayStateChanging', \r\n\t\t\t\t\tfunction (event) {\r\n\t\t\t\t\t\t//if (isMainWindowOpen) { event.preventDefault() };\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\toParentWindow.nativeWindow.addEventListener (\r\n\t\t\t\t\t'moving',\r\n\t\t\t\t\tfunction (event) {\r\n\t\t\t\t\t\t//if (isMainWindowOpen) { event.preventDefault() };\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\toParentWindow.nativeWindow.addEventListener (\r\n\t\t\t\t\t'resizing', \r\n\t\t\t\t\tfunction(event) {\r\n\t\t\t\t\t\t//if(isMainWindowOpen) { event.preventDefault() };\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\toWindow.nativeWindow.addEventListener(\r\n\t\t\t\t\t'deactivate',\r\n\t\t\t\t\tfunction() {\r\n\t\t\t\t\t\t//oWindow.nativeWindow.activate();\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\toWindow.nativeWindow.addEventListener(\r\n\t\t\t\t\t'closing',\r\n\t\t\t\t\tfunction(){\r\n\t\t\t\t\t\tvar ev = eventManager.createEvent(BROWSER_UNLOAD_EVENT);\r\n\t\t\t\t\t\teventManager.fireEvent(ev);\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\t \r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\r\n\t\t/**\r\n\t\t * CLASS\r\n\t\t * \t\tUIBuilder\r\n\t\t * DESCRIPTION\r\n\t\t * \t\tPrivate class that handles the application's layout creation.\r\n\t\t * SAMPLE USAGE\r\n\t\t * \t\tN/A (internal use only)\r\n\t\t * @class\r\n\t\t * @private\r\n\t\t * @param oDomProvider { DOMProvider }\r\n\t\t * \t\tAn instance of the DOMProvider class. Required, in order to be \r\n\t\t * \t\table to build the layout blocks.\r\n\t\t */\r\n\t\tfunction UIBuilder (oDomProvider) {\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Custom initialization for the class UIBuilder.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t */\r\n\t\t\tfunction init() {\r\n\t\t\t\teventManager.addListener(FOLDER_STATE_CHANGED_EVENT, \r\n\t\t\t\t\tfunction (event) {\r\n\t\t\t\t\t\tuiBuilder.toggleItemContent(event.body.folder);\r\n\t\t\t\t\t}\r\n\t\t\t\t)\r\n\t\t\t\teventManager.addListener(FILE_CONTENT_READY_EVENT, \r\n\t\t\t\t\tfunction (event) {\r\n\t\t\t\t\t\tvar content = event.body.content;\r\n\t\t\t\t\t\tvar oDocument = event.body.document;\r\n\t\t\t\t\t\tuiBuilder.showFilecontent(content, oDocument);\r\n\t\t\t\t\t}\r\n\t\t\t\t)\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Displays the content of the selected file item inside the source\r\n\t\t\t * area element.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t * @param content { String }\r\n\t\t\t * \t\tThe content to be displayed.\r\n\t\t\t * @param oDocument { HTML Document Object }\r\n\t\t\t * \t\tThe document object to display the content in.\r\n\t\t\t */\r\n\t\t\tthis.showFilecontent = function(content, oDocument) {\r\n\t\t\t\tvar el = oDocument.getElementById('sourceCodeArea');\r\n\t\t\t\tdProvider.destroyText(el);\r\n\t\t\t\tdProvider.makeText(content, el, 'sourceCodeText');\r\n\t\t\t\tvar noContentText = oDocument.getElementById('srcAreaBgText');\r\n\t\t\t\tCSSProvider.setStyle(noContentText, 'visibility', 'hidden');\r\n\t\t\t\tvar ruler = oDocument.getElementById('lineNoRuler');\r\n\t\t\t\tuiBuilder.initRuler (ruler, content);\r\n\t\t\t\tcssProvider.updateCSS();\r\n\t\t\t\tCSSProvider.setStyle(ruler, 'visibility', 'visible');\r\n\t\t\t\tCSSProvider.setStyle(el, 'visibility', 'visible');\r\n\t\t\t\tel.scrollTop = 0;\r\n\t\t\t\truler.scrollTop = 0;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * The DOM provider instance used for building UI elements.\r\n\t\t\t * @field\r\n\t\t\t * @private\r\n\t\t\t */\r\n\t\t\tvar dProvider = oDomProvider;\r\n\r\n\t\t\t/**\r\n\t\t\t * Creates an item in the files list on the left.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t * @param parentEl { HTML Element }\r\n\t\t\t * \t\tThe HTML element to build the new item in. Both 'ul' or 'li'\r\n\t\t\t * \t\telements can be specified here.\r\n\t\t\t * @param text { String }\r\n\t\t\t * \t\tThe text to display inside the newly created item (i.e, file\r\n\t\t\t * \t\tname).\r\n\t\t\t * @param className { String }\r\n\t\t\t * \t\tThe css class to apply to the newly created element.\r\n\t\t\t * @return { HTML Element }\r\n\t\t\t * \t\tThe 'li' element created\r\n\t\t\t */\r\n\t\t\tthis.makeItem = function(parentEl, text, className) {\r\n\t\t\t\tvar item = makeTreeItem(parentEl, text, className);\r\n\t\t\t\treturn item;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Transparently creates a generic tree item, regardless of the \r\n\t\t\t * actual HTML Element given as parent.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param parentEl { HTML Element }\r\n\t\t\t * \t\tThe HTML element to build the new item in. Both 'ul' or 'li'\r\n\t\t\t * \t\telements can be specified here.\r\n\t\t\t * @param text { String }\r\n\t\t\t * \t\tThe text to display inside the newly created item (i.e, file\r\n\t\t\t * \t\tname).\r\n\t\t\t * @param className { String }\r\n\t\t\t * \t\tThe css class to apply to the newly created element.\r\n\t\t\t */\r\n\t\t\tfunction makeTreeItem (parentEl, text, className) {\r\n\t\t\t\tvar isUL = \r\n\t\t\t\t\tparentEl.nodeName &&\r\n\t\t\t\t\tparentEl.nodeName.toLowerCase() == 'ul';\r\n\t\t\t\tvar isLI = \r\n\t\t\t\t\tparentEl.nodeName &&\r\n\t\t\t\t\tparentEl.nodeName.toLowerCase() == 'li';\r\n\t\t\t\tvar clsName = className? className : 'item';\r\n\t\t\t\tvar item;\r\n\t\t\t\tif(isUL) {item = dProvider.makeElement('li', parentEl, clsName)} \r\n\t\t\t\telse if(isLI) {\r\n\t\t\t\t\tvar wrapper = \r\n\t\t\t\t\t\tparentEl.getElementsByTagName('ul')[0] || \r\n\t\t\t\t\t\tdProvider.makeElement('ul', parentEl);\r\n\t\t\t\t\titem = dProvider.makeElement('li', wrapper, clsName);\r\n\t\t\t\t}\r\n\t\t\t\tvar textClsName = className? className+'Text' : 'itemText';\r\n\t\t\t\tvar txt = dProvider.makeText(text, item, textClsName);\r\n\t\t\t\ttxt.addEventListener('mouseover', function (event){\r\n\t\t\t\t\tvar evt = eventManager.createEvent (\r\n\t\t\t\t\t\tITEM_MOUSE_OVER_EVENT,\r\n\t\t\t\t\t\t{ htmlElement: event.target }\r\n\t\t\t\t\t);\r\n\t\t\t\t\teventManager.fireEvent(evt);\r\n\t\t\t\t}, false);\r\n\t\t\t\ttxt.addEventListener('mouseout', function (event){\r\n\t\t\t\t\tvar evt = eventManager.createEvent (\r\n\t\t\t\t\t\tITEM_MOUSE_OUT_EVENT,\r\n\t\t\t\t\t\t{ htmlElement: event.target }\r\n\t\t\t\t\t);\r\n\t\t\t\t\teventManager.fireEvent(evt);\r\n\t\t\t\t}, false);\r\n\t\t\t\ttxt.addEventListener('click', function( event ) {\r\n\t\t\t\t\tvar evt = eventManager.createEvent (\r\n\t\t\t\t\t\tITEM_MOUSE_CLICK_EVENT,\r\n\t\t\t\t\t\t{ htmlElement: event.target }\r\n\t\t\t\t\t);\r\n\t\t\t\t\teventManager.fireEvent(evt);\r\n\t\t\t\t}, false);\r\n\t\t\t\treturn item;\r\n\t\t\t}\r\n\r\n\t\t\t/**\r\n\t\t\t * Displays all given files as sibling items in the tree.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t * @param parentEl { HTML Element }\r\n\t\t\t * \t\tThe HTML element to build the list in. This can be either a\r\n\t\t\t * \t\t'li' node or the root, 'ul' node.\r\n\t\t\t * \t\tNote:\r\n\t\t\t * \t\tAny required wrapping is done transparently.\r\n\t\t\t * @param files { Array }\r\n\t\t\t * \t\tAn array containing File objects that are to be\r\n\t\t\t * \t\tlisted.\r\n\t\t\t */\r\n\t\t\tthis.displayFilesList = function(parentEl, files) {\r\n\t\t\t\tthis.removeProgressIndicator(parentEl);\r\n\t\t\t\tfor(var i=0; i<files.length; i++) {\r\n\t\t\t\t\tvar file = files[i];\r\n\t\t\t\t\tvar className = 'leaf';\r\n\t\t\t\t\tvar name = Utils.getNameFromURL(file.url);\r\n\t\t\t\t\tif(file.isDirectory) {\r\n\t\t\t\t\t\tname = '[' +name+ ']';\r\n\t\t\t\t\t\tclassName = 'branch';\r\n\t\t\t\t\t}\r\n\t\t\t\t\tvar item = this.makeItem(parentEl, name, className);\r\n\t\t\t\t\tvar event = eventManager.createEvent(FILE_LISTED_EVENT,\r\n\t\t\t\t\t\t{'file': file, 'item': item});\r\n\t\t\t\t\teventManager.fireEvent(event);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Adds visual clues that the given item has children i.e., a \r\n\t\t\t * different CSS style, a progress indicator.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param item { HTML Element }\r\n\t\t\t * \t\tThe element that is to be marked as non empty. \r\n\t\t\t */\r\n\t\t\tthis.markItemAsNonEmpty = function(item) {\r\n\t\t\t\tcssProvider.unregisterCssClass('branch', item);\r\n\t\t\t\tcssProvider.registerCssClass('nonEmptyBranch', item);\r\n\t\t\t\tvar textEl = item.getElementsByTagName('span')[0];\r\n\t\t\t\tcssProvider.unregisterCssClass('branchText', textEl);\r\n\t\t\t\tcssProvider.registerCssClass('nonEmptyBranchText', textEl);\r\n\t\t\t\tthis.addProgressIndicator(item);\r\n\t\t\t\tthis.toggleItemContent(item);\r\n\t\t\t\tcssProvider.updateCSS();\r\n\t\t\t\tthis.setupAsClickableFolderItem(textEl);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Sets the given item as a clickable folder, i.e., clicking on it\r\n\t\t\t * will fetch its children, and will collapse/expand it afterwards.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t * @param item { HTML Element }\r\n\t\t\t * \t\tThe element that is to be setup as a clickable folder.\r\n\t\t\t */\r\n\t\t\tthis.setupAsClickableFolderItem = function(item) {\r\n\t\t\t\tvar cb = function(DOMEvent) {\r\n\t\t\t\t\tvar el = DOMEvent.target;\r\n\t\t\t\t\tvar notYetExpanded = hasProgressIndicator(el.parentNode);\r\n\t\t\t\t\tif(notYetExpanded) {\r\n\t\t\t\t\t\tvar event = eventManager.createEvent(\r\n\t\t\t\t\t\t\tFOLDER_FIRST_CLICKED_EVENT, \r\n\t\t\t\t\t\t\t{'folder': el.parentNode}\r\n\t\t\t\t\t\t);\r\n\t\t\t\t\t\teventManager.fireEvent(event);\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tvar event = eventManager.createEvent(\r\n\t\t\t\t\t\t\tFOLDER_STATE_CHANGED_EVENT, {'folder': \r\n\t\t\t\t\t\t\tel.parentNode});\r\n\t\t\t\t\t\teventManager.fireEvent(event);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\titem.onclick = cb;\r\n\t\t\t}\r\n\r\n\t\t\t/**\r\n\t\t\t * Sets the given file as clickable, i.e., clicking on it will \r\n\t\t\t * display its content in the right pane.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param item { HTML Element }\r\n\t\t\t * \t\tThe element that is to be setup as a clickable file.\r\n\t\t\t * @param file { File }\r\n\t\t\t * \t\tThe file object associated to the item to setup.\r\n\t\t\t */\r\n\t\t\tthis.setupAsClickableFileItem = function(item, file) {\r\n\t\t\t\titem.addEventListener('click', function(){\r\n\t\t\t\t\tvar event = eventManager.createEvent(FILE_ITEM_CLICKED, {\r\n\t\t\t\t\t\t'item': item, 'file': file });\r\n\t\t\t\t\teventManager.fireEvent(event);\r\n\t\t\t\t});\r\n\t\t\t}\r\n\r\n\t\t\t/**\r\n\t\t\t * Sets up visual feedback in response to user interacting with the\r\n\t\t\t * tree items (i.e., mouse-hovering an item, etc).\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @see CSSProvider.dynamicCSS\r\n\t\t\t */\r\n\t\t\tfunction hookItemsVisualFeedback() {\r\n\t\t\t\tvar current = arguments.callee;\r\n\t\t\t\tvar dynCss = CSSProvider.dynamicCSS;\r\n\t\t\t\t// @visual effect for mouse over on tree items.\r\n\t\t\t\tvar hoverCb = function(event) {\r\n\t\t\t\t\tvar el = event.body.htmlElement;\r\n\t\t\t\t\tif (current.lastClicked &&\r\n\t\t\t\t\t\tcurrent.lastClicked === el) {\r\n\t\t\t\t\t\treturn;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcssProvider.unregisterCssClass ('itemOut', el);\r\n\t\t\t\t\tcssProvider.registerCssClass ('itemOver', el);\r\n\t\t\t\t\tcssProvider.applyCSS (dynCss);\r\n\t\t\t\t};\r\n\t\t\t\teventManager.addListener(ITEM_MOUSE_OVER_EVENT, hoverCb);\r\n\t\t\t\t// @visual effect for mouse out on tree items.\r\n\t\t\t\tvar outCb = function(event) {\r\n\t\t\t\t\tvar el = event.body.htmlElement;\r\n\t\t\t\t\tif (current.lastClicked &&\r\n\t\t\t\t\t\tcurrent.lastClicked === el) {\r\n\t\t\t\t\t\treturn;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcssProvider.unregisterCssClass ('itemOver', el);\r\n\t\t\t\t\tcssProvider.registerCssClass ('itemOut', el);\r\n\t\t\t\t\tcssProvider.applyCSS (dynCss);\r\n\t\t\t\t};\r\n\t\t\t\teventManager.addListener (ITEM_MOUSE_OUT_EVENT, outCb);\r\n\t\t\t\t// @visual effect for mouse click on tree items.\r\n\t\t\t\tvar clickCb = function(event) {\r\n\t\t\t\t\tvar el = event.body.htmlElement;\r\n\t\t\t\t\tvar old = current.lastClicked; \r\n\t\t\t\t\tif (old) {\r\n\t\t\t\t\t\tcssProvider.unregisterCssClass ('itemClick', old);\r\n\t\t\t\t\t\tcssProvider.registerCssClass ('itemOut', old);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcssProvider.unregisterCssClass ('itemOut', el);\r\n\t\t\t\t\tcssProvider.unregisterCssClass ('itemOver', el);\r\n\t\t\t\t\tcssProvider.registerCssClass ('itemClick', el);\r\n\t\t\t\t\tcurrent.lastClicked = el;\r\n\t\t\t\t\tcssProvider.applyCSS (dynCss);\r\n\t\t\t\t};\r\n\t\t\t\teventManager.addListener(ITEM_MOUSE_CLICK_EVENT, clickCb);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Alternatively collapses or expands the children of a tree item.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t * @param { HTML Element }\r\n\t\t\t * \t\tThe item to be collapsed or expanded (based on its current \r\n\t\t\t * \t\tstate).\r\n\t\t\t */\r\n\t\t\tthis.toggleItemContent = function(item) {\r\n\t\t\t\tvar wrapper = item.getElementsByTagName('ul')[0];\r\n\t\t\t\tif (wrapper) {\r\n\t\t\t\t\tvar visible = wrapper.style.display == 'none'? false: true;\r\n\t\t\t\t\tCSSProvider.setStyle ( wrapper, 'display',\r\n\t\t\t\t\t\tvisible? 'none' : 'block'\r\n\t\t\t\t\t);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Adds a special, temporary child to the given item, indicating \r\n\t\t\t * that its actual children are being loaded in background.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t * @param item { HTML Element }\r\n\t\t\t * \t\tThe element to signalize background loading for.\r\n\t\t\t */\r\n\t\t\tthis.addProgressIndicator = function(item) {\r\n\t\t\t\tif (!hasProgressIndicator(item)) {\r\n\t\t\t\t\tmakeTreeItem (item, 'loading...', 'progress');\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Removes the 'progress indicator' from the given item, should it \r\n\t\t\t * have one. \r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t * @param item { HTML Element }\r\n\t\t\t * \t\tThe element to remove the progress indicator from.\r\n\t\t\t */\r\n\t\t\tthis.removeProgressIndicator = function(item) {\r\n\t\t\t\tvar children = item.getElementsByTagName('span');\r\n\t\t\t\tfor(var i=0; i<children.length; i++) {\r\n\t\t\t\t\tvar child = children[i];\r\n\t\t\t\t\tvar value = child.innerHTML; \r\n\t\t\t\t\tif (value == 'loading...') {\r\n\t\t\t\t\t\tvar itemToRemove = child.parentNode;\r\n\t\t\t\t\t\tvar _parent = itemToRemove.parentNode;\r\n\t\t\t\t\t\t_parent.removeChild(itemToRemove);\r\n\t\t\t\t\t\treturn;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Checks whether a given item currently presents a 'progress \r\n\t\t\t * indicator' instead of its actual content.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param item { HTML Element }\r\n\t\t\t * \t\tThe element to be checked.\r\n\t\t\t * @return { Boolean }\r\n\t\t\t * \t\tTrue if the element has a 'progress indicator' in place, \r\n\t\t\t * \t\tfalse otherwise.\r\n\t\t\t */\r\n\t\t\tfunction hasProgressIndicator (item) {\r\n\t\t\t\tvar firstWrapper = item.getElementsByTagName('ul')[0];\r\n\t\t\t\tif(firstWrapper) {\r\n\t\t\t\t\tvar firstTextEl = firstWrapper.\r\n\t\t\t\t\t\tgetElementsByTagName('span')[0];\r\n\t\t\t\t\tif (firstTextEl) {\r\n\t\t\t\t\t\tvar value = firstTextEl.innerHTML;\r\n\t\t\t\t\t\tif (value == 'loading...') {return true};\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Creates the header of the application UI.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param parentEl { HTML Element }\r\n\t\t\t * \t\tThe HTML Element to build in.\r\n\t\t\t * @return { HTML Element }\r\n\t\t\t * \t\tThe HTML Element holding the UI header.\r\n\t\t\t */\r\n\t\t\tfunction createHeader (parentEl) {\r\n\t\t\t\tvar header = dProvider.makeDiv( parentEl, 'rcHeader' );\r\n\t\t\t\tlayoutProvider.setupBox(header, {h: 3})\r\n\t\t\t\tlayoutProvider.setupStretched(header, { bottom: -1 })\r\n\t\t\t\tdProvider.makeText('AIR', header, 'airToken');\r\n\t\t\t\tdProvider.makeText('HTML View Source Framework', header,\r\n\t\t\t\t\t'sbrToken');\r\n\t\t\t\tdProvider.makeText('1.2a', header, 'vToken');\r\n\t\t\t\treturn header;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Creates the left side of the application UI -- the side bar that\r\n\t\t\t * contains the tree list showing files and folders.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param parentEl { HTML Element }\r\n\t\t\t * \t\tThe HTML Element to build in.\r\n\t\t\t * @return { HTML Element }\r\n\t\t\t * \t\tThe HTML Element holding the UI sidebar.\r\n\t\t\t */\r\n\t\t\tfunction createSideBar (parentEl) {\r\n\t\t\t\tvar left = dProvider.makeDiv( parentEl, 'rcTree' );\r\n\t\t\t\tlayoutProvider.setupBox(left, {w: 13.85});\r\n\t\t\t\tlayoutProvider.setupStretched(left, {top: 3.2, bottom: 2, right: -1});\r\n\t\t\t\tdProvider.makeText(TREE_DESCRIPTION_MESSAGE, left,\r\n\t\t\t\t\t'listDescr');\r\n\t\t\t\tvar lstBackground = dProvider.makeDiv(left, 'listBackground');\r\n\t\t\t\tlayoutProvider.setupBox(lstBackground);\r\n\t\t\t\tlayoutProvider.setupStretched(lstBackground, {top:3, right:0.5, bottom:1, \r\n\t\t\t\t\tleft:0.5});\r\n\t\t\t\treturn left;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Creates the tree list that displays source files.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param parentEl { HTML Element }\r\n\t\t\t * \t\tThe HTML element to build the tree in.\r\n\t\t\t * @return { HTML Element }\r\n\t\t\t * \t\tThe HTML Element holding the UI tree's root.\r\n\t\t\t */\r\n\t\t\tfunction createTree (parentEl) {\r\n\t\t\t\tvar root = dProvider.makeElement('ul', parentEl, 'tree');\r\n\t\t\t\tlayoutProvider.setupBox(root);\r\n\t\t\t\tlayoutProvider.setupStretched(root, {top:2.5, right:1, \r\n\t\t\t\t\tbottom:0.5, left: 1});\r\n\t\t\t\tCSSProvider.setStyle(root, 'overflow', 'auto');\r\n\t\t\t\treturn root;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Creates the right side of the application UI -- the area that \r\n\t\t\t * displays selected file's content.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param parentEl { HTML Element }\r\n\t\t\t * \t\tThe HTML Element to build in.\r\n\t\t\t * @return { HTML Element}\r\n\t\t\t * \t\tThe HTML Element holding the UI content area.\r\n\t\t\t */\r\n\t\t\tfunction createContentArea (parentEl) {\r\n\t\t\t\tvar right = dProvider.makeDiv( parentEl, 'rcContent' );\r\n\t\t\t\tlayoutProvider.setupBox(right);\r\n\t\t\t\tlayoutProvider.setupStretched(right, {top: 3.2, left: 14, bottom: 2});\r\n\t\t\t\tvar txt = dProvider.makeText('no content to display', right, \r\n\t\t\t\t\t'noContent');\r\n\t\t\t\tlayoutProvider.setupBox(txt, {w:10, h:1});\r\n\t\t\t\tlayoutProvider.setupCentered(txt);\r\n\t\t\t\ttxt.setAttribute('id', 'srcAreaBgText');\r\n\t\t\t\treturn right; \r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Creates the ruler showing line numbering for displayed file's \r\n\t\t\t * content.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n \t\t\t * @param parentEl { HTML Element }\r\n\t\t\t * \t\tThe HTML Element to build in.\r\n\t\t\t * @return { HTML Element }\r\n\t\t\t * \t\tThe HTML Element holding the UI ruler\r\n\t\t\t */\r\n\t\t\tfunction createRuler(parentEl) {\r\n\t\t\t\tvar lnNumb = dProvider.makeDiv(parentEl, 'ruler');\r\n\t\t\t\tlayoutProvider.setupBox (lnNumb, {w:2.5});\r\n\t\t\t\tlayoutProvider.setupStretched (lnNumb, {left:0.5, top:0.5, \r\n\t\t\t\t\tright:-1, bottom:0.8 });\r\n\t\t\t\tlnNumb.setAttribute('id', 'lineNoRuler');\r\n\t\t\t\treturn lnNumb;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Creates the UI element that will display the selected source \r\n\t\t\t * file's source code.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n \t\t\t * @param parentEl { HTML Element }\r\n\t\t\t * \t\tThe HTML Element to build in.\r\n\t\t\t * @return { HTML Element }\r\n\t\t\t * \t\tThe HTML Element holding the UI source area.\r\n\t\t\t */\r\n\t\t\tfunction createSourceArea(parentEl) {\r\n\t\t\t\tvar srcArea = dProvider.makeDiv(parentEl, 'srcCodeArea');\r\n\t\t\t\tlayoutProvider.setupBox (srcArea);\r\n\t\t\t\tlayoutProvider.setupStretched (srcArea, {left:3.1, top:0.5, \r\n\t\t\t\t\tright:0.35, bottom:0.8, });\r\n\t\t\t\tsrcArea.setAttribute('id', 'sourceCodeArea');\r\n\t\t\t\treturn srcArea;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Creates the footer of the application UI.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param parentEl { HTML Element }\r\n\t\t\t * \t\tThe HTML Element to build in.\r\n\t\t\t * @return { HTML Element }\r\n\t\t\t * \t\tThe HTML Element holding the UI footer area.\r\n\t\t\t */\r\n\t\t\tfunction createFooter (parentEl) {\r\n\t\t\t\tvar footer = dProvider.makeDiv( parentEl, 'rcFooter' );\r\n\t\t\t\tlayoutProvider.setupBox(footer, {h: 2});\r\n\t\t\t\tlayoutProvider.setupStretched(footer, {top: -1});\r\n\t\t\t\tdProvider.makeText(COPYRIGHT_MESSAGE, footer, \r\n\t\t\t\t\t'copyrightText');\r\n\t\t\t\treturn footer;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Creates the application user interface.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t * @param parentEl { HTML Element }\r\n\t\t\t * \t\tThe HTML Element to build in.\r\n\t\t\t * @return { Object }\r\n\t\t\t * \t\tA hash with all UI elements created.\r\n\t\t\t */\r\n\t\t\tthis.createMainLayout = function(parentEl) {\r\n\t\t\t\tvar header = createHeader(parentEl);\r\n\t\t\t\tvar sidebar = createSideBar(parentEl);\r\n\t\t\t\tvar tree = createTree(sidebar);\r\n\t\t\t\tthis.addProgressIndicator (tree);\r\n\t\t\t\tvar contentArea = createContentArea(parentEl);\r\n\t\t\t\tvar ruler = createRuler(contentArea);\r\n\t\t\t\tvar sourceArea = createSourceArea(contentArea);\r\n\t\t\t\tlinkScrollable(ruler, sourceArea);\r\n\t\t\t\tvar footer = createFooter(parentEl);\r\n\t\t\t\tcssProvider.updateCSS();\r\n\t\t\t\thookItemsVisualFeedback();\r\n\t\t\t\treturn {\r\n\t\t\t\t\t'header'\t\t:\theader,\r\n\t\t\t\t\t'sidebar'\t\t:\tsidebar,\r\n\t\t\t\t\t'tree'\t\t\t:\ttree,\r\n\t\t\t\t\t'contentArea'\t:\tcontentArea,\r\n\t\t\t\t\t'ruler'\t\t\t:\truler,\r\n\t\t\t\t\t'sourceArea'\t:\tsourceArea,\r\n\t\t\t\t\t'footer'\t\t:\tfooter\r\n\t\t\t\t};\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Initiates the linked ruler that shows line numbers for the file \r\n\t\t\t * content being displayed.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t * @param parentEl { HTML Element }\r\n\t\t\t * \t\tThe HTML Element to build in.\r\n\t\t\t * @assocText { String }\r\n\t\t\t * \t\tA formatted string to show line numbers for. The ruler will \r\n\t\t\t * \t\tadd a new number for each occurence of the new line \r\n\t\t\t * \t\tcharacter in this string.\r\n\t\t\t */\r\n\t\t\tthis.initRuler = function(parentEl, assocText) {\r\n\t\t\t\tvar count = 0;\r\n\t\t\t\tvar index = 0\r\n\t\t\t\tdomProvider.destroyText(parentEl);\r\n\t\t\t\tdo {\r\n\t\t\t\t\tvar searchIndex = assocText.indexOf(\"\\n\", index);\r\n\t\t\t\t\tcount++;\r\n\t\t\t\t\tdProvider.makeText(count, parentEl, 'lineMark');\r\n\t\t\t\t\tindex = searchIndex + 1;\r\n\t\t\t\t\tif (searchIndex == -1) { \r\n\t\t\t\t\t\tvar t = dProvider.makeText(\"---\", parentEl, 'lineMark');\r\n\t\t\t\t\t\tCSSProvider.setStyle(t, 'visibility', 'hidden');\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t};\r\n\t\t\t\t} while (true);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Links two elements, so that they scroll together.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param scrollable { HTML Element }\r\n\t\t\t * \t\tThe target element to be linked.\r\n\t\t\t * @param related { HTML Element }\r\n\t\t\t * \t\tThe source element to link with.\r\n\t\t\t * @param proxy { Function }\r\n\t\t\t * \t\tAn optional function that specifies how the scroll value of \r\n\t\t\t * \t\tthe 'related' element applies to the 'scrollable' element. \r\n\t\t\t * \t\tDefault is to just pass the 'scrollTop' value from 'related' \r\n\t\t\t * \t\tto 'scrollable'.\r\n\t\t\t */\r\n\t\t\tfunction linkScrollable (scrollable, related, proxy) {\r\n\t\t\t\t// @private function; scrolls a given element.\r\n\t\t\t\tvar scrollElement = function(element, offset) {\r\n\t\t\t\t\telement.scrollTop = offset;\t\r\n\t\t\t\t}\r\n\t\t\t\trelated.addEventListener('scroll', function() {\r\n\t\t\t\t\tscrollElement (scrollable, \r\n\t\t\t\t\t\tUtils.isFunction(proxy)? proxy.call(this, related.scrollTop):\r\n\t\t\t\t\t\trelated.scrollTop\r\n\t\t\t\t\t); \r\n\t\t\t\t}, false );\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t// @perform custom initialization of this class.\r\n\t\t\tinit();\r\n\t\t}\r\n\r\n\r\n\r\n\t\t/**\r\n\t\t* CLASS\r\n\t\t* \tFileSystemWalker\r\n\t\t* DESCRIPTION\r\n\t\t* \tPrivate class that encapsulates functionality related to file\r\n\t\t* \tsystem traversal (i.e., recursively iterating through a folder's\r\n\t\t* \tchildren).\r\n\t\t* SAMPLE USAGE\r\n\t\t* \tN/A (internal use only)\r\n\t\t* @class\r\n\t\t* @private\r\n\t\t*/\r\n\t\tfunction FileSystemWalker() {\r\n\r\n\t\t\t/**\r\n\t\t\t * Keeps a record of all listed files.\r\n\t\t\t * @field\r\n\t\t\t * @private\r\n\t\t\t */\r\n\t\t\tvar listedFiles = {};\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Custom initialization for the FileSystemWalker class.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t */\r\n\t\t\tfunction init() {\r\n\t\t\t\teventManager.addListener(FOLDER_FIRST_CLICKED_EVENT,\r\n\t\t\t\t\tfunction(event) {\r\n\t\t\t\t\t\tvar folderItem = event.body.folder;\r\n\t\t\t\t\t\tvar file = getRegisteredFileByItem(folderItem);\r\n\t\t\t\t\t\t// @nested listener\r\n\t\t\t\t\t\teventManager.addListener(FILES_LIST_READY_EVENT, \r\n\t\t\t\t\t\t\tfunction(evt) {\r\n\t\t\t\t\t\t\t\tuiBuilder.displayFilesList(folderItem, \r\n\t\t\t\t\t\t\t\t\tevt.body.filesList);\r\n\t\t\t\t\t\t\t\tcssProvider.updateCSS();\r\n\t\t\t\t\t\t\t\t// @this is a one-time callback:\r\n\t\t\t\t\t\t\t\teventManager.removeListener(\r\n\t\t\t\t\t\t\t\t\tFILES_LIST_READY_EVENT, arguments.callee);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t)\r\n\t\t\t\t\t\tqueryChildren(file);\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\teventManager.addListener(FOLDER_CHECKED_EVENT, function(event){\r\n\t\t\t\t\tvar file = event.body.folder;\r\n\t\t\t\t\tvar item = getRegisteredFile(file.url).item;\r\n\t\t\t\t\tvar hasChildren = event.body.result;\r\n\t\t\t\t\tif(hasChildren) {\r\n\t\t\t\t\t\tuiBuilder.markItemAsNonEmpty(item);\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\teventManager.addListener(FILE_LISTED_EVENT, function(event){\r\n\t\t\t\t\tvar file = event.body.file;\r\n\t\t\t\t\tvar item = event.body.item;\r\n\t\t\t\t\tregisterListedFile (file, item);\r\n\t\t\t\t\tif (file.isDirectory) {\r\n\t\t\t\t\t\tqueryIfHasChildren(file);\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tuiBuilder.setupAsClickableFileItem(item, file);\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\teventManager.addListener(FILE_ITEM_CLICKED, function(event){\r\n\t\t\t\t\tvar file = event.body.file;\r\n\t\t\t\t\tvar oDocument = event.body.item.ownerDocument;\r\n\t\t\t\t\tqueryFileContent(file, oDocument);\r\n\t\t\t\t})\r\n\t\t\t}\r\n\r\n\t\t\t/**\r\n\t\t\t * Checks whether the given 'file' object has already been listed.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param file { File }\r\n\t\t\t * \t\tA file object to look up.\r\n\t\t\t * @return { Boolean }\r\n\t\t\t * \t\tTrue is the file was already listed, false otherwise. \r\n\t\t\t */\r\n\t\t\tfunction isFileAlreadyListed (file) {\r\n\t\t\t\treturn listedFiles[file.url]? true: false;\r\n\t\t\t}\r\n\r\n\t\t\t/**\r\n\t\t\t * Retrieves a file previously registered as 'already listed'.\r\n\t\t \t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param url { String }\r\n\t\t\t * \t\tThe url of the file to retrieve.\r\n\t\t\t * @return { Object }\r\n\t\t\t * \t\tA hash with two keys, 'file': the registered file, and \r\n\t\t\t * \t\t'item': its associated item. Returns undefined if the file\r\n\t\t\t * \t\tcannot be found. \r\n\t\t\t */\r\n\t\t\tfunction getRegisteredFile (url) {\r\n\t\t\t\treturn listedFiles[url];\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Performs a reverse lookup through the registry, possibly finding\r\n\t\t\t * the file associated with the given item.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param item { HTML Element }\r\n\t\t\t * \t\tThe item associated with the file object to search for.\r\n\t\t\t * @return { File }\r\n\t\t\t * \t\tThe associated file object, or null if it cannot be found.\r\n\t\t\t */\r\n\t\t\tfunction getRegisteredFileByItem (item) {\r\n\t\t\t\tfor (var url in listedFiles) {\r\n\t\t\t\t\tvar entry = listedFiles[url];\r\n\t\t\t\t\tif(entry.item == item) {\r\n\t\t\t\t\t\treturn entry.file;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\treturn null;\r\n\t\t\t}\r\n\r\n\t\t\t/**\r\n\t\t\t * Registers a file as 'already listed'.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param file { File }\r\n\t\t\t * \t\tA file object to register.\r\n\t\t\t * @param item { HTML Element }\r\n\t\t\t * \t\tThe HTML element that has been created in order to list the \r\n\t\t\t * \t\tfile.\r\n\t\t\t */ \r\n\t\t\tfunction registerListedFile (file, item) {\r\n\t\t\t\tvar item = item? item: null;\r\n\t\t\t\tlistedFiles[file.url] = {'file':file, 'item': item};\r\n\t\t\t};\r\n\r\n\t\t\t/**\r\n\t\t\t * Retrieves direct children of the application directory folder.\r\n\t\t\t * All subsequent retrieval is made on demand.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t */\r\n\t\t\tthis.makeInitialQuery = function() {\r\n\t\t\t\tvar appDir = File.applicationDirectory.resolvePath(\"SourceViewer\");\r\n\t\t\t\tqueryChildren (appDir);\r\n\t\t\t}\r\n\r\n\t\t\t/**\r\n\t\t\t * Lists the children of the given parent file, provided it is a \r\n\t\t\t * directory.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param parentFile { File }\r\n\t\t\t * \t\tThe directory file to list.\r\n\t\t\t */\r\n\t\t\tfunction queryChildren (parentFile) {\r\n\t\t\t\tif (!parentFile.isDirectory) {return};\r\n\t\t\t\tparentFile.addEventListener( 'directoryListing', function(e){\r\n\t\t\t\t\tvar files = [];\r\n\t\t\t\t\tfor (var i=0; i<e.files.length; i++) {\r\n\t\t\t\t\t\tvar file = e.files[i];\r\n\t\t\t\t\t\tif(isFileToBeHidden(file)) {continue};\r\n\t\t\t\t\t\tfiles.push(file);\r\n\t\t\t\t\t};\r\n\t\t\t\t\tfiles.sort (function(a, b) {return b.isDirectory?-1:\r\n\t\t\t\t\t\t!a.isDirectory? 1: 0;\r\n\t\t\t\t\t});\r\n\t\t\t\t\tvar evt = eventManager.createEvent (\r\n\t\t\t\t\t\tFILES_LIST_READY_EVENT, {'filesList': files});\r\n\t\t\t\t\teventManager.fireEvent(evt);\r\n\t\t\t\t}, false);\r\n\t\t\t\tparentFile.getDirectoryListingAsync();\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Checks whether the given file object has children, i.e., it is a\r\n\t\t\t * directory containing other files.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param file { File }\r\n\t\t\t * \t\tThe file object to check.\r\n\t\t\t */\r\n\t\t\tfunction queryIfHasChildren (file) {\r\n\t\t\t\tfile.addEventListener('directoryListing', function( event ) {\r\n\t\t\t\t\tvar result = event.files.length? true: false;\r\n\t\t\t\t\tvar evt = eventManager.createEvent (\r\n\t\t\t\t\t\tFOLDER_CHECKED_EVENT,\r\n\t\t\t\t\t\t{folder: file, 'result': result}\r\n\t\t\t\t\t);\r\n\t\t\t\t\teventManager.fireEvent(evt);\r\n\t\t\t\t});\r\n\t\t\t\tfile.getDirectoryListingAsync();\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Possibly obtains the text content of the given file object.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param file { File }\r\n\t\t\t * \t\tThe file object to retrieve text content from.\r\n\t\t\t * @param oDocument { HTML Document Object}\r\n\t\t\t * \t\tThe associated document object to display retrieved content\r\n\t\t\t * \t\tin.\r\n\t\t\t */\r\n\t\t\tfunction queryFileContent(file, oDocument) {\r\n\t\t\t\tif(!file) {return};\r\n\t\t\t\tif(!file.exists) {return};\r\n\t\t\t\tif(file.isDirectory) {return};\r\n\t\t\t\tif(!isLegalFile(file)) {\r\n\t\t\t\t\tuiBuilder.showFilecontent(CANNOT_READ_TEXT_MESSAGE, \r\n\t\t\t\t\t\toDocument);\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t\tvar fileStream = new FileStream();\r\n\t\t\t\tfileStream.addEventListener('complete', function() {\r\n\t\t\t\t\tvar fileCnt = fileStream.readUTFBytes (\r\n\t\t\t\t\t\tfileStream.bytesAvailable);\r\n\t\t\t\t\tfileStream.close();\r\n\t\t\t\t\tvar event = eventManager.createEvent(\r\n\t\t\t\t\t\tFILE_CONTENT_READY_EVENT,\r\n\t\t\t\t\t\t{'content': fileCnt, 'document': oDocument}\r\n\t\t\t\t\t);\r\n\t\t\t\t\teventManager.fireEvent(event);\r\n\t\t\t\t}, false);\r\n\t\t\t\tfileStream.addEventListener('ioError', function(event) {\r\n\t\t\t\t\tvar msg = IO_ERROR_MESSAGE+'\\n'+\r\n\t\t\t\t\t\tevent.errorID+'\\n'+\r\n\t\t\t\t\t\tevent.text;\r\n\t\t\t\t\t\tfileStream.close();\r\n\t\t\t\t\tuiBuilder.showFilecontent(msg, oDocument);\r\n\t\t\t\t}, false);\r\n\t\t\t\tfileStream.openAsync(file, 'read');\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Checks whether the given file is of a legal type. We do not want\r\n\t\t\t * to retrieve text for binary files, for instance.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param file { File }\r\n\t\t\t * \t\tThe file object to check.\r\n\t\t\t * @return { Boolean }\r\n\t\t\t * \t\tReturns true if the file extension is in the \r\n\t\t\t * \t\tVALID_EXTENSIONS list, false otherwise.\r\n\t\t\t */\r\n\t\t\tfunction isLegalFile(file) {\r\n\t\t\t\tvar fileName = Utils.getNameFromURL(file.url);\r\n\t\t\t\tvar match = fileName.match(/\\.([^\\.]*)$/);\r\n\t\t\t\tvar extension = (match? match[1] : fileName).toLowerCase();\r\n\t\t\t\tfor(var i=0; i<VALID_EXTENSIONS.length; i++) {\r\n\t\t\t\t\tif (VALID_EXTENSIONS[i] == extension) {\r\n\t\t\t\t\t\treturn true;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t// @perform custom initialization of this class.\r\n\t\t\tinit();\r\n\t\t}\r\n\r\n\r\n\t\t/**\r\n\t\t* CLASS\r\n\t\t* \tUtils\r\n\t\t* DESCRIPTION\r\n\t\t* \tPrivate class; holds only static members that aid in dealing \r\n\t\t* with file paths & URLs.\r\n\t\t* SAMPLE USAGE\r\n\t\t* \tN/A (internal use only)\r\n\t\t* @class\r\n\t\t* @private\r\n\t\t*/\r\n\t\tvar Utils = {\r\n\t\t\t/**\r\n\t\t\t * Retrieves the last segment from a file url.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t * @static\r\n\t\t\t * @param url { String }\r\n\t\t\t * \t\tA file URL to retrieve a file name from.\r\n\t\t\t * \r\n\t\t\t * @return { String }\r\n\t\t\t * \t\tThe file name, or null if the url is malformed.\r\n\t\t\t */ \r\n\t\t\tgetNameFromURL: function (url) {\r\n\t\t\t\tvar match = url.match(/[^\\/]*$/);\r\n\t\t\t\treturn match? match[0]: null;\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Removes spaces from beginning and end of a string.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t * @static\r\n\t\t\t * @param str { String }\r\n\t\t\t * \t\tThe string to trim.\r\n\t\t\t * @return { String }\r\n\t\t\t * \t\tThe given string, with all the leading and trailing spaces \r\n\t\t\t * \t\tremoved.\r\n\t\t\t */\r\n\t\t\ttrim: function (str) {\r\n\t\t\t\tvar str = String(str);\r\n\t\t\t\tvar isNotEmpty = (str && str.length && /[^\\s]/.test(str));\r\n\t\t\t\tif(isNotEmpty) {\r\n\t\t\t\t\treturn ret = str.replace(/\\s*$/, '').replace(/^\\s*/, '');\r\n\t\t\t\t}\r\n\t\t\t\treturn '';\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Tests whether the given argument is a function.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t * @static\r\n\t\t\t * @param arg { * }\r\n\t\t\t * \t\tThe argument that is to be checked for being a function.\r\n\t\t\t * @return { Boolean }\r\n\t\t\t * \t\tTrue, if the given argument is a function, false otherwise.\r\n\t\t\t */\r\n\t\t\t isFunction : function (arg) {\r\n\t\t\t \treturn arg instanceof Function;\r\n\t\t\t },\r\n\t\t\t \r\n\t\t\t/**\r\n\t\t\t * Translates an absolute file URL into an application root relative\r\n\t\t\t * one.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t * @static\r\n\t\t\t * @param absUrl { String }\r\n\t\t\t * \t\tThe absolute file URL to translate.\r\n\t\t\t * @return { String }\r\n\t\t\t * \t\tThe translated file url. Will allways have a leading slash,\r\n\t\t\t * \t\tnever a trailing one: \"/my/relative/url\"\r\n\t\t\t */ \r\n\t\t\tgetRelativeURL: function (absURL) {\r\n\t\t\t\tvar appDir = File.applicationDirectory;\r\n\t\t\t\tvar appDirURL = Utils.translateToURL (appDir.nativePath);\r\n\t\t\t\tvar relURL = absURL.replace (appDirURL, '');\r\n\t\t\t\trelURL = relURL.replace(/\\/{2,}/g, '/');\r\n\t\t\t\tif (relURL[0] != '/') {relURL = '/' + relURL};\r\n\t\t\t\tif (relURL[relURL.length-1] == '/') {\r\n\t\t\t\t\trelURL.substr(0, relURL.length-2);\r\n\t\t\t\t}\r\n\t\t\t\treturn relURL;\r\n\t\t\t},\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Translates a native path into a file URL.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t * @static\r\n\t\t\t * @param nativePath { String }\r\n\t\t\t * \t\tThe native path to translate.\r\n\t\t\t * @return { String }\r\n\t\t\t * \t\tA file URL, translated from the given native path.\r\n\t\t\t */ \r\n\t\t\ttranslateToURL: function (nativePath) {\r\n\t\t\t\tnativePath = nativePath.replace(/\\\\/g, '/');\r\n\t\t\t\tnativePath = encodeURI(nativePath);\r\n\t\t\t\tvar url = 'file:///' + nativePath;\r\n\t\t\t\treturn url;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t/**\r\n\t\t* CLASS\r\n\t\t* \tEventManager\r\n\t\t* DESCRIPTION\r\n\t\t* \tPrivate class that provides abstract event management functionality.\r\n\t\t* SAMPLE USAGE\r\n\t\t* \tN/A (internal use only)\r\n\t\t* @class\r\n\t\t* @private\r\n\t\t*/\t\t\r\n\t\tfunction EventManager() {\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Holds all the registered event listeners.\r\n\t\t\t * @field\r\n\t\t\t * @private\r\n\t\t\t */\r\n\t\t\tvar listeners = {};\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Registers an event listener.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t * @param type { String }\r\n\t\t\t * \t\tThe type of events this listener is interested in.\r\n\t\t\t * @param callback { Function }\r\n\t\t\t * \t\tThe callback to activate when a listener of this type will \r\n\t\t\t * \t\tbe notified.\r\n\t\t\t */\r\n\t\t\tthis.addListener = function(type, callback) {\r\n\t\t\t\tvar list = listeners[type] || (listeners[type] = []);\r\n\t\t\t\tlist.push (callback);\r\n\t\t\t}\r\n\r\n\t\t\t/**\r\n\t\t\t * Unregisters an event listener.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t * @param type { String }\r\n\t\t\t * \t\tThe type of the listener(s) to remove.\r\n\t\t\t * @param callback { Function }\r\n\t\t\t * \t\tThe callback registered with the listener(s) to remove.\r\n\t\t\t */\r\n\t\t\tthis.removeListener = function(type, callback) {\r\n\t\t\t\tvar list = listeners[type];\r\n\t\t\t\tfor(var i=0; i<list.length; i++) {\r\n\t\t\t\t\tvar cb = list[i];\r\n\t\t\t\t\tif(cb === callback) {\r\n\t\t\t\t\t\tlist[i] = null;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tlist.sort(function(a,b){return a === null? 1:0});\r\n\t\t\t\twhile (list[Math.min(0, list.length-1)] === null) {\r\n\t\t\t\t\tlist.length -= 1;\t\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Unregisters all event listeners of a specific type.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t * @param type { String }\r\n\t\t\t * \t\tThe type of the listeners to be removed.\r\n\t\t\t */\r\n\t\t\tthis.removeListenersFor = function(type) {\r\n\t\t\t\tlisteners[type] = null;\r\n\t\t\t\tdelete listeners[type];\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Notifies all event listeners of a specific type.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t * @param event { EventManager.Event }\r\n\t\t\t * \t\tThe event object being passed to the callback.\r\n\t\t\t */\r\n\t\t\tthis.fireEvent = function (event) {\r\n\t\t\t\tvar type = event.type;\r\n\t\t\t\tif(!listeners[type]) {return};\r\n\t\t\t\tfor (var i=0; i<listeners[type].length; i++) {\r\n\t\t\t\t\tvar callback = listeners[type][i];\r\n\t\t\t\t\tcallback(event);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Returns an instance of the Event class to the caller.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t * @param type { String }\r\n\t\t\t * \t\tThe type of this event.\r\n\t\t\t * @param body { Object }\r\n\t\t\t * \t\tAn object literal that holds the information this event\r\n\t\t\t * \t\ttransports. Both notifier and callback must have agreed upon\r\n\t\t\t * \t\tthis object literal structure.\r\n\t\t\t * @param id { String }\r\n\t\t\t * \t\tAn optional unique id for this event, should it need be \r\n\t\t\t * \t\trecognized at some later time.\r\n\t\t\t * @return { EventManager.Event }\r\n\t\t\t * \t\tAn event object having the specified type, body and id.\r\n\t\t\t */\r\n\t\t\tthis.createEvent = function(type, body, id) {\r\n\t\t\t\treturn new Event(type, body, id);\r\n\t\t\t}\r\n\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * CLASS\r\n\t\t\t * \t\tEvent\r\n\t\t\t * DESCRIPTION\r\n\t\t\t * \t\tPrivate class that provides a vehicle for transporting \r\n\t\t\t * \t\tinformation from the notifier to the callback.\r\n\t\t\t * SAMPLE USAGE\r\n\t\t\t * \t\tN/A (internal use only)\r\n\t\t\t * @class\r\n\t\t\t * @private\r\n\t\t\t * @param type { String }\r\n\t\t\t * \t\tThe type of this event.\r\n\t\t\t * @param body { Object }\r\n\t\t\t * \t\tAn object literal that holds the information this event\r\n\t\t\t * \t\ttransports. Both notifier and must have agreed upon\r\n\t\t\t * \t\tthis object literal structure.\r\n\t\t\t * @param id { String }\r\n\t\t\t * \t\tAn optional unique id for this event, should it need be \r\n\t\t\t * \t\trecognized at some later time.\r\n\t\t\t */\r\n\t\t\tfunction Event(type, body, id) {\r\n\t\t\t\tthis.type = type;\r\n\t\t\t\tthis.body = body? body: {};\r\n\t\t\t\tthis.id = id? id : 'anonymous';\r\n\t\t\t\tthis.toString = function() {\r\n\t\t\t\t\tvar ret = '['+this.id+']: '+this.type+' event; ';\r\n\t\t\t\t\tfor(var prop in this.body) {\r\n\t\t\t\t\t\tret += '\\n'+prop+': '+(\r\n\t\t\t\t\t\t\tthis.body[prop] instanceof Function? 'function':\r\n\t\t\t\t\t\t\tthis.body[prop]? this.body[prop].toString():\r\n\t\t\t\t\t\t\tthis.body[prop] === null? 'null value':\r\n\t\t\t\t\t\t\t'undefined value');\r\n\t\t\t\t\t}\r\n\t\t\t\t\treturn ret;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\r\n\t\t/**\r\n\t\t* CLASS\r\n\t\t* \tLayoutProvider\r\n\t\t* DESCRIPTION\r\n\t\t* \tPrivate class that provides layout building blocks for the\r\n\t\t* \tapplication UI.\r\n\t\t* SAMPLE USAGE\r\n\t\t* \tN/A (internal use only)\r\n\t\t* @class\r\n\t\t* @private\r\n\t\t*/\r\n\t\tfunction LayoutProvider () {\r\n\r\n\t\t\t/**\r\n\t\t\t* Turns a certain HTML element into a CSS box.\r\n\t\t\t* @method\r\n\t\t\t* @public\r\n\t\t\t* @param target { HTML Element }\r\n\t\t\t* \t\tThe HTML element that is to be set up as a CSS box. This \r\n\t\t\t* \t\timplies both out-of-page-flow(1) positioning and fixed \r\n\t\t\t* \t\tdimensions(2).\r\n\t\t\t* @param oPoint { Object }\r\n\t\t\t* \t\tAn object literal that specifies the box's boundaries. Use:\r\n\t\t\t* \t\t- x: The horizontal position of top left corner.\r\n\t\t\t* \t\t- y: The vertical position of top left corner.\r\n\t\t\t* \t\t- w: The width of the box.\r\n\t\t\t* \t\t- h: The height of the box.\r\n\t\t\t* \t\tAll are optional. Not defining one of the above members will\r\n\t\t\t* \t\tunset the corresponding CSS property.\r\n\t\t\t* \t\tNote:\r\n\t\t\t* \t\t(1) Out-of-page-flow positioning translates to 'fixed' if \r\n\t\t\t* the target element is a direct child of the body \r\n\t\t\t* element; it translates to 'absolute' otherwise.\r\n\t\t\t* \t\t(2) All values are computed as ems.\r\n\t\t\t*/\r\n\t\t\tthis.setupBox = function(target, oPoint) {\r\n\t\t\t\tvar isTopLevel = target.parentNode.nodeName\r\n\t\t\t\t\t.toLowerCase() == 'body';\r\n\t\t\t\tCSSProvider.setStyle (target, 'position', \r\n\t\t\t\t\tisTopLevel? \"fixed\": \"absolute\");\r\n\t\t\t\tCSSProvider.setStyle (target, 'left', \r\n\t\t\t\t\toPoint && oPoint.x? (oPoint.x + \"em\") : '');\r\n\t\t\t\tCSSProvider.setStyle (target, 'top', \r\n\t\t\t\t\toPoint && oPoint.y? (oPoint.y + \"em\") : '');\r\n\t\t\t\tCSSProvider.setStyle (target, 'width', \r\n\t\t\t\t\toPoint && oPoint.w? (oPoint.w + \"em\") : '');\r\n\t\t\t\tCSSProvider.setStyle (target, 'height', \r\n\t\t\t\t\toPoint && oPoint.h? (oPoint.h + \"em\") : '');\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Centers a certain CSS box inside its parent.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param target { HTML Element }\r\n\t\t\t * \t\tThe HTML element (already set up as a box) that is to be \r\n\t\t\t * \t\tcentered.\r\n\t\t\t * @param oPoint { Object }\r\n\t\t\t * \t\tAn object literal that describes an optional offset from the \r\n\t\t\t * \t\tcomputed 'center' position. Use:\r\n\t\t\t * \t\t- x: a positive value will move the box right.\r\n\t\t\t * \t\t- y: a positive value will move to box down.\r\n\t\t\t * Note:\r\n\t\t\t * All values are computed as ems.\r\n\t\t\t */\r\n\t\t\tthis.setupCentered = function(target, oPoint) {\r\n\t\t\t\tvar w = parseFloat(target.style.width);\r\n\t\t\t\tvar h = parseFloat(target.style.height);\r\n\t\t\t\tvar xOff = oPoint && oPoint.x? parseFloat(oPoint.x) : 0;\r\n\t\t\t\tvar yOff = oPoint && oPoint.y? parseFloat(oPoint.y) : 0;\r\n\t\t\t\tCSSProvider.setStyle(target, 'left', '50%');\r\n\t\t\t\tCSSProvider.setStyle(target, 'top', '50%');\r\n\t\t\t\tCSSProvider.setStyle(target, 'marginLeft', -1*(w/2-xOff)+'em');\r\n\t\t\t\tCSSProvider.setStyle(target, 'marginTop', -1*(h/2-yOff)+'em');\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Makes a certain CSS box stretch.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param target { HTML Element }\r\n\t\t\t * \t\tThe HTML element (already set up as a box) that has to \r\n\t\t\t * \t\tstretch.\r\n\t\t\t * @param oPoint { Object }\r\n\t\t\t * \t\tAn object literal that defines one to four anchor points. \r\n\t\t\t * \t\tThe box will stretch, the way that its boundaries stay \r\n\t\t\t * \t\taligned to each defined anchor point, respectivelly.\r\n\t\t\t * \t\tExample:\r\n\t\t\t * \t\toPoint = { bottom: 1.5, top: 0 }\r\n\t\t\t * \t\tThe box's bottom boundary will be anchored at 1.5 em away \r\n\t\t\t * \t\tfrom the parent-box's bottom boundary; also the top boundary\r\n\t\t\t * \t\tof the box will be anchored at the parent-box's top \r\n\t\t\t * \t\tboundary. As the parent box resizes, the box resizes with\r\n\t\t\t * \t\tit, while keeping the given anchors.\r\n\t\t\t */\r\n\t\t\tthis.setupStretched = function(target, oPoint) {\r\n\t\t\t\tvar topA = oPoint && oPoint.top?\r\n\t\t\t\t\tparseFloat(oPoint.top) : 0;\r\n\t\t\t\tvar rightA = oPoint && oPoint.right?\r\n\t\t\t\t\tparseFloat(oPoint.right) : 0;\r\n\t\t\t\tvar bottomA = oPoint && oPoint.bottom?\r\n\t\t\t\t\tparseFloat(oPoint.bottom) : 0;\r\n\t\t\t\tvar leftA = oPoint && oPoint.left?\r\n\t\t\t\t\tparseFloat(oPoint.left) : 0;\r\n\t\t\t\tif(topA >= 0) {\r\n\t\t\t\t\tCSSProvider.setStyle(target, 'top', topA+ 'em');\r\n\t\t\t\t}\r\n\t\t\t\tif(rightA >= 0) {\r\n\t\t\t\t\tCSSProvider.setStyle(target, 'right', rightA+ 'em');\r\n\t\t\t\t}\r\n\t\t\t\tif(bottomA >= 0) {\r\n\t\t\t\t\tCSSProvider.setStyle(target, 'bottom', bottomA+ 'em');\r\n\t\t\t\t}\r\n\t\t\t\tif(leftA >= 0) {\r\n\t\t\t\t\tCSSProvider.setStyle(target, 'left', leftA+ 'em');\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\r\n\t\t/**\r\n\t\t* CLASS\r\n\t\t* \t\tDOMProvider\r\n\t\t* DESCRIPTION\r\n\t\t* \t\tPrivate class that provides DOM element creation tools and \r\n\t\t* \t\trelated functionality for the application.\r\n\t\t* SAMPLE USAGE\r\n\t\t* \t\tN/A (internal use only)\r\n\t\t* @class\r\n\t\t* @private\r\n\t\t* @param oDocument { Object }\r\n\t\t*\t\tThe document object to provide DOM services for.\r\n\t\t*/\r\n\t\tfunction DOMProvider (oDocument) {\r\n\t\t\t/**\r\n\t\t\t* The client document object we are providing DOM services for.\r\n \t\t\t* @field\r\n\t\t\t* @private\r\n\t\t\t*/\r\n\t\t\tvar clientDoc = oDocument;\r\n\r\n\t\t\t/**\r\n\t\t\t* Generic functionality for creating DOM nodes.\r\n\t\t\t* @method\r\n\t\t\t* @public\r\n\t\t\t* @param elName { String }\r\n\t\t\t* \t\tThe name of the node to create.\r\n\t\t\t* @param elParent { Object }\r\n\t\t\t* \t\tThe parent of the node to create (optional, defaults to \r\n\t\t\t* \t\t'clientDoc'). Can be one of the following:\r\n\t\t\t* \t\t- a Document node;\r\n\t\t\t* \t\t- the global 'window' object;\r\n\t\t\t* \t\t- an Element node.\r\n\t\t\t* \t\tFor the first two cases, the new node will be appended to \r\n\t\t\t* \t\tthe Body element (which, in turn, will be created if it \r\n\t\t\t* \t\tdoesn't exist.\r\n\t\t\t* @param cssClass { String }\r\n\t\t\t* \t\tThe name of a CSS class to add to this node (optional, \r\n\t\t\t* \t\tdefaults to empty string - i.e., no class attribute).\r\n\t\t\t* @param attributes { Object }\r\n\t\t\t* \t\tA hash defining a number of arbitrary attributes.\r\n\t\t\t* \t\tNote:\r\n\t\t\t* \t\tDOM event listeners will not fire if defined this way. Use\r\n\t\t\t* \t\t'addEventListener()' instead.\r\n\t\t\t* @return { HTML Object }\r\n\t\t\t* \t\tThe newly created HTML Object.\r\n\t\t\t*/\r\n\t\t\tthis.makeElement = function(elName, elParent, cssClass, attributes){\r\n\t\t\t\t// @private function; gracefully returns the 'html' HTML node. \r\n\t\t\t\tvar getHtmlNode = function(oDoc) {\r\n\t\t\t\t\tif(arguments.callee.node) { return arguments.callee.node };\r\n\t\t\t\t\tvar node = oDoc.getElementsByTagName('html')[0];\r\n\t\t\t\t\tif(!node) {\r\n\t\t\t\t\t\tnode = oDoc.appendChild(oDoc.createElement('html'));\r\n\t\t\t\t\t}\r\n\t\t\t\t\targuments.callee.node = node;\r\n\t\t\t\t\treturn node;\r\n\t\t\t\t}\r\n\t\t\t\t// @private function; gracefully returns the 'head' HTML node.\r\n\t\t\t\tvar getHeadNode = function(oDoc) {\r\n\t\t\t\t\tif(arguments.callee.node) { return arguments.callee.node };\r\n\t\t\t\t\tvar node = oDoc.getElementsByTagName('head')[0];\r\n\t\t\t\t\tif(!node) {\r\n\t\t\t\t\t\tvar htmlNode = getHtmlNode(oDoc);\r\n\t\t\t\t\t\tnode = htmlNode.insertBefore(oDoc.createElement('head'),\r\n\t\t\t\t\t\t\thtmlNode.firstNode);\r\n\t\t\t\t\t}\r\n\t\t\t\t\targuments.callee.node = node;\r\n\t\t\t\t\treturn node;\r\n\t\t\t\t}\r\n\t\t\t\t// @private function; gracefully returns the 'body' HTML node.\r\n\t\t\t\tvar getBodyNode = function(oDoc) {\r\n\t\t\t\t\tif(arguments.callee.node) { return arguments.callee.node };\r\n\t\t\t\t\tvar node = oDoc.getElementsByTagName('body')[0];\r\n\t\t\t\t\tif(!node) {\r\n\t\t\t\t\t\tvar htmlNode = getHtmlNode(oDoc);\r\n\t\t\t\t\t\tvar headNode = getHeadNode(oDoc);\r\n\t\t\t\t\t\tnode = htmlNode.insertBefore(oDoc.createElement('body'),\r\n\t\t\t\t\t\t\theadNode.nextSibling);\r\n\t\t\t\t\t}\r\n\t\t\t\t\targuments.callee.node = node;\r\n\t\t\t\t\treturn node;\r\n\t\t\t\t}\r\n\t\t\t\tvar parentType = \r\n\t\t\t\t\t(elParent)?\r\n\t\t\t\t\t\t(elParent.nativeWindow)? \r\n\t\t\t\t\t\t\t'WINDOW_OBJECT' :\r\n\t\t\t\t\t\t(elParent.nodeType && elParent.nodeType == 9)? \r\n\t\t\t\t\t\t\t'DOCUMENT' :\r\n\t\t\t\t\t\t(elParent.nodeType && elParent.nodeType == 1)? \r\n\t\t\t\t\t\t\t'ELEMENT' :\r\n\t\t\t\t\t\tnull :\r\n\t\t\t\t\tnull;\r\n\t\t\t\tvar _parent;\r\n\t\t\t\tswitch (parentType) {\r\n\t\t\t\t\tcase 'WINDOW_OBJECT':\r\n\t\t\t\t\t\tvar oDoc = elParent.document;\r\n\t\t\t\t\t\t_parent = getBodyNode(oDoc);\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase 'DOCUMENT':\r\n\t\t\t\t\t\tvar oDoc = elParent;\r\n\t\t\t\t\t\t_parent = getBodyNode(oDoc);\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase 'ELEMENT':\r\n\t\t\t\t\t\t_parent = elParent;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tdefault:\r\n\t\t\t\t\t\tvar oDoc = clientDoc;\r\n\t\t\t\t\t\t_parent = getBodyNode(oDoc);\r\n\t\t\t\t}\r\n\t\t\t\tvar el = _parent.ownerDocument.createElement (elName);\r\n\t\t\t\tif (cssClass) { \r\n\t\t\t\t\tel.className = cssClass;\r\n\t\t\t\t\tcssProvider.registerCssClass(cssClass, el);\r\n\t\t\t\t};\r\n\t\t\t\tif (attributes) {\r\n\t\t\t\t\tfor (atrName in attributes) {\r\n\t\t\t\t\t\tel.setAttribute (atrName, attributes[atrName]);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tel = _parent.appendChild(el);\r\n\t\t\t\treturn el;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Convenience method to create an empty div element.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @see makeElement()\r\n\t\t\t * @param className { String }\r\n\t\t\t * \t\tThe name of the css class to apply to the newly created div.\r\n\t\t\t * \t\tOptional, defaults to empty string (i.e., no class \r\n\t\t\t * \t\tattribute).\r\n\t\t\t * @param _parent { Object }\r\n\t\t\t * \t\tThe parent to create the new div in. Optional, defaults \r\n\t\t\t * \t\tin effect to the body element.\r\n\t\t\t * @return { HTML Object }\r\n\t\t\t * \t\tThe newly created div element.\r\n\t\t\t */\r\n\t\t\tthis.makeDiv = function (_parent, className) {\r\n\t\t\t\treturn this.makeElement('div', _parent, className);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Creates a styled text node.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @see makeElement()\r\n\t\t\t * @param value { String }\r\n\t\t\t * \t\tThe content of the text node to create. \r\n\t\t\t * \t\tNote:\r\n\t\t\t * \t\tHTML markup will not be expanded.\r\n\t\t\t * @param _parent { Object }\r\n\t\t\t * \t\tThe parent to create the new text node in. Optional, \r\n\t\t\t * \t\tdefaults to the body element.\r\n\t\t\t * @param className { String }\r\n\t\t\t * \t\tThe css class name to apply to the newly created text node.\r\n\t\t\t * \t\tNote:\r\n\t\t\t * \t\tThe class name is rather applied to a 'span' wrapper that \r\n\t\t\t * \t\tholds the text node. The span wrapper is added regardless of\r\n\t\t\t * \t\tthe fact that the 'className' attribute is present or not.\r\n\t\t\t * @return { HTML element }\r\n\t\t\t * \t\tA span element wrapping the newly created text node.\r\n\t\t\t */\r\n\t\t\tthis.makeText = function(value, _parent, className) {\r\n\t\t\t\tvar wrapper = this.makeElement('span', _parent, className);\r\n\t\t\t\tvar text = wrapper.ownerDocument.createTextNode(value);\r\n\t\t\t\twrapper.appendChild(text);\r\n\t\t\t\treturn wrapper;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Removes the text blocks created via makeText();\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param _parent { HTML Element }\r\n\t\t\t * \t\tThe element to remove the text blocks from.\r\n\t\t\t */\r\n\t\t\tthis.destroyText = function(_parent) {\r\n\t\t\t\tvar sp = null;\r\n\t\t\t\twhile (sp = _parent.getElementsByTagName('span')[0]) {\r\n\t\t\t\t\tsp = _parent.removeChild (sp);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\r\n\t\t/**\r\n\t\t* CLASS\r\n\t\t* \t\tCSSProvider\r\n\t\t* DESCRIPTION\r\n\t\t* \t\tPrivate class that provides CSS styling services for the \r\n\t\t* \t\tapplication.\r\n\t\t* SAMPLE USAGE\r\n\t\t* \t\tN/A (internal use only)\r\n\t\t* @class\r\n\t\t* @private\r\n\t\t* @param oDocument { Object }\r\n\t\t* \t\tThe document object to provide CSS for.\r\n\t\t*/\r\n\t\tfunction CSSProvider ( oDocument ) {\r\n\t\t\t/**\r\n\t\t\t * Change the current color scheme with the specified one, if a \r\n\t\t\t * scheme with the given name can be found.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t * @since 1.2 alpha\r\n\t\t\t * @param scheme { String }\r\n\t\t\t * \t\tThe name of the new color scheme to apply. It will fail \r\n\t\t\t * \t\tsilently if such a color scheme does not exist.\r\n\t\t\t */\r\n\t\t\tthis.changeColorScheme = function (scheme) {\r\n\t\t\t\tcolorScheme = scheme;\r\n\t\t\t\tthis.updateCSS();\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Enforces a global CSS reparsing, using CSSProvider.cssContent.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t */\r\n\t\t\tthis.updateCSS = function () {\r\n\t\t\t\tthis.applyCSS (CSSProvider.cssContent);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * The client document object we are providing CSS services for.\r\n \t\t\t * @field\r\n\t\t\t * @private\r\n\t\t\t */\r\n\t\t\tvar clientDoc = oDocument;\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Default color scheme to use in the application CSS.\r\n\t\t\t * @field\r\n\t\t\t * @private\r\n\t\t\t */\r\n\t\t\tvar defaultColorScheme = 'proffesionalBlue'; \r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Holds the name of the color scheme to be applied. Defaults to\r\n\t\t\t * 'proffesionalBlue'.\r\n\t\t\t * @field\r\n\t\t\t * @private \r\n\t\t\t */\r\n\t\t\tvar colorScheme = defaultColorScheme;\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Holds the CSS classes we declare; optimizes the CSS parsing time\r\n\t\t\t * @field\r\n\t\t\t * @private \r\n\t\t\t */\r\n\t\t\tvar cssClassRegistry = {};\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Links a particular DOM object with a CSS class name.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t * @param className {String}\r\n\t\t\t * \t\tThe name of a CSS class.\r\n\t\t\t * @param obj {DOM Element}\r\n\t\t\t * \t\tA DOM Element to associate with the above class name\r\n\t\t\t */\r\n\t\t\tthis.registerCssClass = function(className, obj) {\r\n\t\t\t\tif (!cssClassRegistry[className]) {\r\n\t\t\t\t\tcssClassRegistry[className] = [];\r\n\t\t\t\t}\r\n\t\t\t\tobj.className = className;\r\n\t\t\t\tcssClassRegistry[className].push(obj);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Unlinks a particular DOM object, previously linked with a CSS \r\n\t\t\t * class name.\r\n \t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t * @param className { String }\r\n\t\t\t * \t\tThe name of a CSS class.\r\n\t\t\t * @param obj { DOM Element }\r\n\t\t\t * \t\tA DOM Element to unlink.\r\n\t\t\t */\r\n\t\t\tthis.unregisterCssClass = function(className, obj) {\r\n\t\t\t\tvar set = cssClassRegistry[className];\r\n\t\t\t\tif (set) {\r\n\t\t\t\t\tfor(var i=0; i<set.length; i++) {\r\n\t\t\t\t\t\tvar registeredObj = set[i];\r\n\t\t\t\t\t\tif(registeredObj === obj) {\r\n\t\t\t\t\t\t\tregisteredObj = null;\r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tset.sort(function(a, b){ return a === null? 1: 0 });\r\n\t\t\t\t\twhile(set[Math.min(0, set.length-1)] === null) {\r\n\t\t\t\t\t\tset.length -= 1;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Unlinks all the CSS class names linked via registerCssClass().\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t */\r\n\t\t\tfunction clearClassRegistry() {\r\n\t\t\t\tcssClassRegistry = {};\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Applies the colors in the current color scheme to the application\r\n\t\t\t * CSS, then returns the modified CSS\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @return {String}\r\n\t\t\t * \t\tA copy of CSSProvider.cssContent with all the colors place\r\n\t\t\t * \t\tholders resolved to the current color scheme.\r\n\t\t\t */\r\n\t\t\tfunction resolveColorNames (cssText) {\r\n\t\t\t\tvar colors = CSSProvider.colorSchemes[colorScheme];\r\n\t\t\t\tif (!colors) {\r\n\t\t\t\t\tcolors = CSSProvider.colorSchemes[defaultColorScheme];\r\n\t\t\t\t}\r\n\t\t\t\tvar newCss = cssText;\r\n\t\t\t\tfor (colorName in colors) {\r\n\t\t\t\t\tvar p;\r\n\t\t\t\t\tp = new RegExp(colorName, \"g\");\r\n\t\t\t\t\tnewCss = newCss.replace(p, colors[colorName]);\r\n\t\t\t\t}\r\n\t\t\t\treturn newCss;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Custom CSS parsing engine. This seems to be more reliable than \r\n\t\t\t * the current Webkit's implementation. Only supports class names\r\n\t\t\t * linked via registerCssClass() and tag names.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @cssText { String }\r\n\t\t\t * \t\tThe CSS declarations to parse.\r\n\t\t\t */\r\n\t\t\tthis.applyCSS = function(cssText) {\r\n\t\t\t\tvar cssText = Utils.trim (cssText);\t\r\n\t\t\t\tcssText = resolveColorNames (cssText);\r\n\t\t\t\tvar blocks = cssText.split('}');\r\n\t\t\t\tfor (var i=0; i<blocks.length; i++) {\r\n\t\t\t\t\tvar block = Utils.trim(blocks[i]);\r\n\t\t\t\t\tif (!block) { continue };\r\n\t\t\t\t\tvar operands = block.split('{');\r\n\t\t\t\t\tvar selectors = Utils.trim(operands[0]).split(',');\r\n\t\t\t\t\tvar directives = Utils.trim(operands[1]).split(';');\r\n\t\t\t\t\tfor (var j=0; j<directives.length; j++) {\r\n\t\t\t\t\t\tif (!directives[j]) {\r\n\t\t\t\t\t\t\tdirectives[j] = null; //@i.e., marking for deletion.\r\n\t\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tdirectives[j] = Utils.trim(directives[j]).split(':');\r\n\t\t\t\t\t\tdirectives[j][0] = Utils.trim(directives[j][0]);\r\n\t\t\t\t\t\tdirectives[j][1] = Utils.trim(directives[j][1]);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tdirectives.sort (function(a,b){return a === null? 1: 0});\r\n\t\t\t\t\twhile(directives[Math.max(0,directives.length-1)] === null){\r\n\t\t\t\t\t\tdirectives.pop();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tfor (var k=0; k<selectors.length; k++) {\r\n\t\t\t\t\t\tvar selector = Utils.trim(selectors[k]);\r\n\t\t\t\t\t\tvar targetObjects = [];\r\n\t\t\t\t\t\tif (/^\\./.test(selector)) {\r\n\t\t\t\t\t\t\tvar key = selector.replace (/^\\./,'');\r\n\t\t\t\t\t\t\tif (cssClassRegistry[key]) {\r\n\t\t\t\t\t\t\t\tvar tmpArr = cssClassRegistry[key];\r\n\t\t\t\t\t\t\t\tfor (var l=0; l<tmpArr.length; l++) {\r\n\t\t\t\t\t\t\t\t\ttargetObjects[l] = tmpArr[l];\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t} else if (/^\\w/.test(selector)) {\r\n\t\t\t\t\t\t\ttargetObjects = clientDoc.\r\n\t\t\t\t\t\t\t\tgetElementsByTagName(selector) || targetObjects;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tfor(var m=0; m<targetObjects.length; m++) {\r\n\t\t\t\t\t\t\tvar currTarget = targetObjects[m];\r\n\t\t\t\t\t\t\tfor(var n=0; n<directives.length; n++) {\r\n\t\t\t\t\t\t\t\tvar currDecl = directives[n];\r\n\t\t\t\t\t\t\t\tvar property = currDecl[0];\r\n\t\t\t\t\t\t\t\tvar value = currDecl[1];\r\n\t\t\t\t\t\t\t\tCSSProvider.setStyle(currTarget, property,\r\n\t\t\t\t\t\t\t\t\tvalue);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tclearClassRegistry();\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\t/**\r\n\t\t * Sets the provided style on an HTML element.\r\n\t\t * @field\r\n\t\t * @public\r\n\t\t * @static\r\n\t\t * @param target {HTML Element}\r\n\t\t * \t\tAn HTML Element to set CSS style on.\r\n\t\t * @param property (String)\r\n\t\t * \t\tThe name of the CSS property to be set\r\n\t\t * @param value {String}\r\n\t\t * \t\tThe new value to set\r\n\t\t */\r\n\t\tCSSProvider.setStyle = function (target, property, value) {\r\n\t\t\ttarget.style[property] = String(value);\r\n\t\t}\r\n\t\t\r\n\t\t/**\r\n\t\t * Unsets a style property on an HTML element.\r\n\t\t * @field\r\n\t\t * @public\r\n\t\t * @static\r\n\t\t * @see CSSProvider.setStyle\r\n\t\t */\r\n\t\tCSSProvider.clearStyle = function(target, property) {\r\n\t\t\tCSSProvider.setStyle(target, property, '');\r\n\t\t}\r\n\t\t \r\n\t\t/**\r\n\t\t * Holds color schemes for the application\r\n\t\t * @field\r\n\t\t * @public\r\n\t\t * @static\r\n\t\t */\r\n\t\tCSSProvider.colorSchemes = {\r\n\t\t\tproffesionalBlue : {\r\n\t\t\t\tabsLight\t\t\t:\t'#ffffff',\r\n\t\t\t\tabsDark\t\t\t\t:\t'#000000',\r\n\t\t\t\tlightNeutral\t\t:\t\"#d3dcf2\",\r\n\t\t\t\tdarkNeutral\t\t\t:\t\"#9197a6\",\r\n\t\t\t\tcolorMain\t\t\t:\t\"#7690cf\",\r\n\t\t\t\tlighterColorAccent\t:\t\"#48577d\",\r\n\t\t\t\tdarkerColorAccent\t:\t\"#4e5159\"\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\t/**\r\n\t\t * Holds all the CSS information for the application's layout\r\n\t\t * @field\r\n\t\t * @public\r\n\t\t * @static\r\n\t\t */\r\n\t\tCSSProvider.cssContent = '\\\r\n\t\t\tbody {\\\r\n\t\t\t\t-khtml-user-select: none;\\\r\n\t\t\t\tfont-size: 16px;\\\r\n\t\t\t}\\\r\n\t\t\t.rcHeader {\\\r\n\t\t\t\tbackground-color: lightNeutral;\\\r\n\t\t\t\tborder-bottom: 0.2em solid darkNeutral;\\\r\n\t\t\t}\\\r\n\t\t\t.airToken, .sbrToken, .vToken {\\\r\n\t\t\t\tfont-family: arial, verdana, sans_;\\\r\n\t\t\t\tpadding: 0.2em;\\\r\n\t\t\t\tfont-weight: bold;\\\r\n\t\t\t\tcursor: default;\\\r\n\t\t\t\tline-height: 1.5em;\\\r\n\t\t\t}\\\r\n\t\t\t.airToken {\\\r\n\t\t\t\tcolor: darkNeutral;\\\r\n\t\t\t\tfont-size: 200%;\\\r\n\t\t\t}\\\r\n\t\t\t.sbrToken, .vToken {\\\r\n\t\t\t\tcolor: darkerColorAccent;\\\r\n\t\t\t\tfont-size: 80%;\\\r\n\t\t\t}\\\r\n\t\t\t.vToken {\\\r\n\t\t\t\tfont-style: italic;\\\r\n\t\t\t}\\\r\n\t\t\t.rcTree {\\\r\n\t\t\t\tbackground-color: colorMain;\\\r\n\t\t\t\tborder-right: 0.2em solid lightNeutral;\\\r\n\t\t\t}\\\r\n\t\t\t.listDescr {\\\r\n\t\t\t\tfont-family: arial, verdana, sans_;\\\r\n\t\t\t\tfont-size: 0.8em;\\\r\n\t\t\t\tcolor: absLight;\\\r\n\t\t\t\tdisplay: block;\\\r\n\t\t\t\tpadding: 0.5em;\\\r\n\t\t\t}\\\r\n\t\t\t.listBackground {\\\r\n\t\t\t\tborder: 0.1em solid absLight;\\\r\n\t\t\t\tbackground-color: lighterColorAccent;\\\r\n\t\t\t\topacity: 0.1;\\\r\n\t\t\t}\\\r\n\t\t\t.tree, ul {\\\r\n\t\t\t\tpadding: 0;\\\r\n\t\t\t\tcolor: absLight;\\\r\n\t\t\t\tlist-style-type: none;\\\r\n\t\t\t}\\\r\n\t\t\t.item, .branch, .nonEmptyBranch, .leaf {\\\r\n\t\t\t\tmargin-left: 1.5em;\\\r\n\t\t\t\tpadding: 0;\\\r\n\t\t\t}\\\r\n\t\t\t.branch, .nonEmptyBranch {\\\r\n\t\t\t\tlist-style-type: circle;\\\r\n\t\t\t}\\\r\n\t\t\t.nonEmptyBranch {\\\r\n\t\t\t\tlist-style-type: disc;\\\r\n\t\t\t}\\\r\n\t\t\t.leaf {\\\r\n\t\t\t\tlist-style-type: square;\\\r\n\t\t\t}\\\r\n\t\t\t.itemText, .branchText, .nonEmptyBranchText, .leafText {\\\r\n\t\t\t\tfont-family: arial, verdana, sans_;\\\r\n\t\t\t\tfont-size: 0.8em;\\\r\n\t\t\t\tdisplay: block;\\\r\n\t\t\t\tcursor: default;\\\r\n\t\t\t\tpadding-left: 0.2em;\\\r\n\t\t\t}\\\r\n\t\t\t.branchText, .nonEmptyBranchText {\\\r\n\t\t\t\tfont-weight: bold;\\\r\n\t\t\t\tfont-style: italic;\\\r\n\t\t\t\tcursor: text;\\\r\n\t\t\t}\\\r\n\t\t\t.nonEmptyBranchText {\\\r\n\t\t\t\tfont-style: normal;\\\r\n\t\t\t\tcursor: pointer;\\\r\n\t\t\t}\\\r\n\t\t\t.progress {\\\r\n\t\t\t\tfont-family: arial, verdana, sans_;\\\r\n\t\t\t\tfont-size: 0.7em;\\\r\n\t\t\t\tfont-style: italic;\\\r\n\t\t\t}\\\r\n\t\t\t.rcContent {\\\r\n\t\t\t\tbackground-color: absDark;\\\r\n\t\t\t}\\\r\n\t\t\t.noContent {\\\r\n\t\t\t\tfont-family: arial, verdana, sans_;\\\r\n\t\t\t\tcolor: lighterColorAccent;\\\r\n\t\t\t\tfont-size: 1em;\\\r\n\t\t\t\tfont-weight: bold;\\\r\n\t\t\t\tfont-style: italic;\\\r\n\t\t\t}\\\r\n\t\t\t.srcCodeArea, .ruler {\\\r\n\t\t\t\tborder: 0.1em solid colorMain;\\\r\n\t\t\t\tbackground-color: absLight;\\\r\n\t\t\t\topacity: 0.95;\\\r\n\t\t\t\toverflow: auto;\\\r\n\t\t\t\tpadding-left: 0.2;\\\r\n\t\t\t\tvisibility: hidden;\\\r\n\t\t\t\tline-height: 1.2em;\\\r\n\t\t\t\tfont-size: 0.9em;\\\r\n\t\t\t}\\\r\n\t\t\t.ruler {\\\r\n\t\t\t\tpadding-left: 0;\\\r\n\t\t\t\tborder-width: 0.1em;\\\r\n\t\t\t\tbackground-color: lighterColorAccent;\\\r\n\t\t\t\tz-index: 2;\\\r\n\t\t\t\toverflow: hidden;\\\r\n\t\t\t}\\\r\n\t\t\t.lineMark {\\\r\n\t\t\t\tdisplay: block;\\\r\n\t\t\t\tcolor: lightNeutral;\\\r\n\t\t\t\ttext-align: right;\\\r\n\t\t\t\tpadding-right: 0.2em;\\\r\n\t\t\t}\\\r\n\t\t\t.sourceCodeText {\\\r\n\t\t\t\tfont-family: courier new, courier, mono_;\\\r\n\t\t\t\twhite-space: pre;\\\r\n\t\t\t\tcolor: absDark;\\\r\n\t\t\t\t-khtml-user-select: auto;\\\r\n\t\t\t}\\\r\n\t\t\t.rcFooter {\\\r\n\t\t\t\tborder-top: 0.2em solid lightNeutral;\\\r\n\t\t\t\tbackground-color: darkNeutral;\\\r\n\t\t\t}\\\r\n\t\t\t.copyrightText {\\\r\n\t\t\t\tcolor: lightNeutral;\\\r\n\t\t\t\tfont-family: arial, verdana, sans_;\\\r\n\t\t\t\tfont-size: 80%;\\\r\n\t\t\t\tfont-weight: bold;\\\r\n\t\t\t\ttext-align: right;\\\r\n\t\t\t\tdisplay: block;\\\r\n\t\t\t\tmargin: 0.5em;\\\r\n\t\t\t}\\\r\n\t\t\t';\r\n\t\t\r\n\t\t/**\r\n\t\t * Holds specific CSS styling information that is to be used dynamically\r\n\t\t * on the list items.\r\n\t\t * @field\r\n\t\t * @public\r\n\t\t * @static \r\n\t\t */\r\n\t\tCSSProvider.dynamicCSS = '\\\r\n\t\t\t.itemOver {\\\r\n\t\t\t\tbackground-color: darkNeutral;\\\r\n\t\t\t}\\\r\n\t\t\t.itemOut {\\\r\n\t\t\t\tbackground-color: transparent;\\\r\n\t\t\t}\\\r\n\t\t\t.itemClick {\\\r\n\t\t\t\tbackgroundColor: lighterColorAccent;\\\r\n\t\t\t}\\\r\n\t\t';\r\n\t}",
"function loadDocuments() {\n console.log(\"loadDocuments() started\");\n showMessage(\"Loading private documents for '\" + user.name + \"' ...\");\n user.privateDocuments.get({\n limit : 1000\n }).execute(function(response) {\n console.log(\"loadDocuments() response = \" + JSON.stringify(response));\n var html = '<ul>';\n documents = response.data;\n $.each(documents, function(index, doc) {\n html += '<li>';\n html += '<a href=\"#\" class=\"document-select\" data-index=\"' + index + '\">' + doc.subject + '</a>';\n html += ' (' + doc.viewCount + ' views)';\n html += '</li>';\n });\n html += '</ul>';\n $(\"#documents-list\").html(\"\").html(html);\n $(\".document-select\").click(function () {\n var index = $(this).attr(\"data-index\");\n current = documents[index];\n $(\".document-subject\").html(\"\").html(current.subject);\n showDocument();\n });\n showOnly(\"documents-div\");\n });\n}",
"function Viewer() { \n if (acceptedFileTypes.includes(fileType)) return PdfViewer() \n else if (acceptedMsOfficeTypes.includes(fileType)) \n return DisplayUsingOfficeApps()\n else return error()\n}",
"function ReportLoad(strFilname) {\n if (strFilname != '')\n var m_WindowHandle = window.open(strFilname, 'New', 'location=no, toolbar=no, menubar=yes, resizable=yes, scrollbars=yes');\n try { m_WindowHandle.focus(); } catch (e) { }\n}",
"function resourceOnload() {\n initShowdownExt();\n hljs.initHighlightingOnLoad();\n mermaidAPI.initialize({\n startOnLoad: false\n });\n mermaid.parseError = function(err, hash) {\n console.error(err);\n };\n\n onLoadCallback.call(self);\n }",
"function handleReaderLoadEnd(evt) {\n // update the editor with the files content\n editor.getSession().setValue(evt.target.result);\n}",
"function onOpen(event){\n\t\tvar oQuickViewContent = event.getSource().getContent()[0];\n\t\t// Data is loaded and content is rendered at this point of time, \n\t\t// so call the setKeyboardNavigation function directly\n\t\t//setKeyboardNavigation.call(oQuickViewContent);\n\t}",
"function load() {\n _data_id = m_data.load(FIRST_SCENE, load_cb, preloader_cb);\n}",
"function loadPredefinedPanorama( ) {\n\tvar evt=window.event;\n\tevt.preventDefault();\n var div = document.getElementById('container');\n\tvar PSV = new PhotoSphereViewer({\n\tpanorama: 'house.jpg',\n container: div,\n\t\ttime_anim: false,\n\t\tnavbar: true,\n\t\tsize: {\n\t\t\twidth: '45%',\n\t\t\theight: '400px'\n\t\t}\n\t});\n}",
"function loadInitial() {\n var nameContainer = $('#list-recent-title');\n var dateContainer = $('#list-recent-time');\n var imageContainer = $('#list-recent-image');\n\n var vis = visuals[0];\n var id = vis.id;\n var name = vis.name;\n var image = vis.imageall;\n var datecreated = vis.datecreated;\n\n firstImage = name;\n selectedImage = firstImage;\n\n nameContainer.html(name);\n dateContainer.html(datecreated);\n imageContainer.attr('src', 'assets/vis/' + image);\n}",
"function loadContentViewer(imageId,position,rotation) {\r\n\t// When a RHS thumbnail is clicked, this function is called. \r\n\t// Because of that, and the fact we know if the page has already been loaded, we can reset the pageBeginLoadTime if needed.\r\n\t// Only Perform when debug = p.\r\n\t\r\n\tif (pageLoadDebug != -1 && initialPageLoad == false) {\r\n\t\tpageStartLoadTime = new Date();\r\n\t}\r\n\tinitialPageLoad = false;\r\n\t\r\n\t// Load the active page object into a global variable.\r\n\tobjPage = window.opener.objCase.pages[window.opener.activePageJsonId];\r\n\t\r\n\t// Clear the content viewer so we do not have non-used DOM elements on the page.\r\n\tclearContentViewer();\r\n\t\r\n\t// Get the image path from the spContentId field.\r\n\tcontentId = objPage.spContentID;\r\n\timagePath = 'ucm/getFile?contentId=' + contentId + '&rendition=web';\r\n\r\n\t// Load the preview image objects and set the preview image src attributes. \r\n\t// These are used for the 8 zoom levels.\r\n\t$('#content_preview_image1').attr('src', imagePath);\r\n\t$('#content_preview_image2').attr('src', imagePath);\r\n\t$('#content_preview_image3').attr('src', imagePath);\r\n\t$('#content_preview_image4').attr('src', imagePath);\r\n\t$('#content_preview_image5').attr('src', imagePath);\r\n\t$('#content_preview_image6').attr('src', imagePath);\r\n\t$('#content_preview_image7').attr('src', imagePath);\r\n\t$('#content_preview_image8').attr('src', imagePath);\r\n\t$('#content_preview_image9').attr('src', imagePath);\r\n\t\r\n\t// Set the names to the thumbnail id so we can retrive when rotating the images.\r\n\t$('#content_preview_image1').attr('name', imageId);\r\n\t\r\n\t// Initialize the map/zooming functionality\r\n\t$(\"#map-1\").mapz({\r\n\t\tzoom : true,\r\n\t\tcreatemaps : true,\r\n\t\tmousewheel : false\r\n\t});\r\n\r\n\t// Check which position the active document is within the thumbnail sequence and set the navigation controls appropriately.\r\n\tswitch(position) {\r\n\t\tcase 'first':\r\n\t\t\t$(\"#nav_prev_content\").attr('disabled','disabled');\r\n\t\t\t$(\"#nav_next_content\").removeAttr('disabled');\r\n\t\t\tbreak;\r\n\t\tcase 'last':\r\n\t\t\t$(\"#nav_prev_content\").removeAttr('disabled');\r\n\t\t\t$(\"#nav_next_content\").attr('disabled','disabled');\r\n\t\t\tbreak;\r\n\t\tcase 'only':\r\n\t\t\t$(\"#nav_prev_content\").attr('disabled','disabled');\r\n\t\t\t$(\"#nav_next_content\").attr('disabled','disabled');\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\t$(\"#nav_prev_content\").removeAttr('disabled');\r\n\t\t\t$(\"#nav_next_content\").removeAttr('disabled');\r\n\t}\r\n\t\r\n\t// If we are in step 2, display the grid lines\r\n\tif (step == 2) {\r\n\t\t$('#map-1').griddy({height:1350});\r\n\t\t$('.griddy').toggle(); \r\n\t}\r\n\t\r\n\t// Update sequencing information based on the current step.\r\n\tif (step == 1) {\r\n\t\t// Update the active page and final page number.\r\n\t\tupdateActivePageNumber();\r\n\t\tupdateActiveDocumentPageFinalNumber();\r\n\t\tupdateActiveDocumentPageDocDateAndType();\r\n\t} else if (step == 2) {\r\n\t\t// Update sequencing display data.\r\n\t\tupdateActiveDocumentNumber();\r\n\t\tupdateActiveDocumentPageNumber();\r\n\t\tupdateActiveDocumentPageFinalNumber();\r\n\t\tupdateActiveDocumentPageDocDateAndType();\r\n\t\tupdateDocumentCount();\r\n\t\tupdateDocumentPageCount();\r\n\t\t\r\n\t\t// Update sequencing controls.\r\n\t\tupdateDocumentControls();\r\n\t\tupdatePageControls();\r\n\t}\r\n\t\r\n\t/*IWS-357 : Not all the thumbnail image is showing, thumbnails are off center and far to the right*/\r\n\t\r\n\t/* Recommended Resolution - 1920 x 1080(Landscape) or 1080 x 1920(Portrait) \r\n\t To make the images to the center of screen \r\n\t if screen having resolution - 1080 x 1920(Portrait) */\r\n\tif($(screen)[0].width!='1920' || $(screen)[0].height!='1080'){\r\n\t\t$(\"#content_preview_image1\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image2\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image3\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image4\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image5\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image6\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image7\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image8\").addClass('removeMargin');\r\n\t\t$(\"#content_preview_image9\").addClass('removeMargin');\r\n\t}else{\r\n\t\t$(\"#content_preview_image1\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image2\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image3\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image4\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image5\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image6\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image7\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image8\").removeClass('removeMargin');\r\n\t\t$(\"#content_preview_image9\").removeClass('removeMargin');\r\n\t}\r\n\t// To load the gridding to 100%\r\n\tvar stageId = window.opener.qsStageId;\r\n\tif(stageId == 4 || stageId == 5){ // stageId = 4 & stageId = 5 is for step1-OP and Step1-QA respectively\r\n\t\t$(\"#map-1\").css({ left : '0', width: '100%' });\r\n\t}else{\r\n\t\t$(\"#map-1\").addClass('map-override');\r\n\t}\r\n\t\r\n\t// Update the rotation.\r\n\t$(\"#content_preview_image1\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image2\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image3\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image4\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image5\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image6\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image7\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image8\").rotate({angle: rotation});\r\n\t$(\"#content_preview_image9\").rotate({angle: rotation});\r\n\t\r\n\t// Postioining the image if rotation angle is 90/270 degrees\r\n\tif(rotation == '90' || rotation == '270'){\r\n\t\t$('#content_preview_image2').addClass('landscapeImg2Zoom');\r\n\t\t$('#content_preview_image3').addClass('landscapeImg3Zoom');\r\n\t\t$('#content_preview_image4').addClass('landscapeImg4Zoom');\r\n\t\t$('#content_preview_image5').addClass('landscapeImg5Zoom');\r\n\t\t$('#content_preview_image6').addClass('landscapeImg6Zoom');\r\n\t\t$('#content_preview_image7').addClass('landscapeImg7Zoom');\r\n\t\t$('#content_preview_image8').addClass('landscapeImg8Zoom');\r\n\t\t$('#content_preview_image9').addClass('landscapeImg9Zoom');\r\n\t}else{\r\n\t\t$('#content_preview_image2').removeClass('landscapeImg2Zoom');\r\n\t\t$('#content_preview_image3').removeClass('landscapeImg3Zoom');\r\n\t\t$('#content_preview_image4').removeClass('landscapeImg4Zoom');\r\n\t\t$('#content_preview_image5').removeClass('landscapeImg5Zoom');\r\n\t\t$('#content_preview_image6').removeClass('landscapeImg6Zoom');\r\n\t\t$('#content_preview_image7').removeClass('landscapeImg7Zoom');\r\n\t\t$('#content_preview_image8').removeClass('landscapeImg8Zoom');\r\n\t\t$('#content_preview_image9').removeClass('landscapeImg9Zoom');\r\n\t}\r\n\t// Only show the rotation controls if the page is not complete, suspended or excluded.\r\n\tpgCompleted = objPage.completed;\r\n\tpgDeleted = objPage.deleted;\r\n\tif (pgCompleted != true && pgCompleted != 'true' && pgDeleted != true && pgDeleted != 'true') {\r\n\t\tdisplayRotationControls();\r\n\t} else {\r\n\t\thideRotationControls();\r\n\t}\r\n}",
"function loadPdf(url){\n console.log(\"Load pdf document: \", url);\n // Asynchronously downloads PDF. \n PDFJS.getDocument(url).then(function (pdfDoc_) {\n pdfDoc = pdfDoc_;\n console.log(\"PDF \", url, \" is ready to be rendered\"); \n console.log(\"Render page: \", DigiMag.currentBucketPageNum); \n renderPage(DigiMag.currentBucketPageNum); \n }); \n }",
"function load() {\n numOfPages();\n loadList();\n}",
"function Load_Book_File(evt)\n{\n if(evt.target.files[0]) //if the file is available\n {\n var reader = new FileReader(); //create new reader file\n reader.readAsText(evt.target.files[0]); //get file\n reader.onload = function(e) //wait for the file to load\n {\n book_text = reader.result; //store the result\n\t\t\tEnable_Word_Count_Button(); //check if the Word Count button can be enabled\n };\n }\n}",
"open() {\n return spPost(WebPartDefinition(this, \"OpenWebPart\"));\n }",
"function initialize() {\n const urlString = window.location.search;\n const urlParams = new URLSearchParams(urlString);\n var isbn = urlParams.get(\"isbn\");\n var viewer = new google.books.DefaultViewer(document.getElementById('viewerCanvas'));\n viewer.load(`ISBN:${isbn}`, alertNotFound, removePreviewFooter);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Automatically generated. Retrieves the `len` constructor field of the `:sslice` type. | function len(sslice) /* (sslice : sslice) -> int32 */ {
return sslice.len;
} | [
"static get length() {\n return 0;\n }",
"function start(sslice) /* (sslice : sslice) -> int32 */ {\n return sslice.start;\n}",
"function len( obj )\n {\n if ( undefined === obj.length && \"number\" !== typeof obj.length )\n { return undefined; }\n \n return obj.length\n }",
"char_length() {\n return [...this.buf].length;\n }",
"size() {\n return this.buf.byteLength;\n }",
"len() {\n return quat.length(this);\n }",
"function _sslice_extend( slice, count ) {\r\n if (count===0) return slice;\r\n var idx = slice.start + slice.len;\r\n if (count > 0) {\r\n _char_iter(slice.str, idx, function(c,i,nexti) {\r\n count--;\r\n idx = nexti;\r\n return (count <= 0);\r\n });\r\n }\r\n else {\r\n _char_reviter(slice.str, idx-1, function(c,i,nexti) {\r\n count++;\r\n idx = i;\r\n return (count >= 0 || idx <= slice.start);\r\n });\r\n }\r\n return { str: slice.str, start: slice.start, len: (idx > slice.start ? idx - slice.start : 0) };\r\n}",
"function getLength(data) {\n\treturn Object.keys(data).length;\n}",
"function str(sslice) /* (sslice : sslice) -> string */ {\n return sslice.str;\n}",
"sizeUnion() {\n return this.size\n }",
"getSize(attributeName) {\n const arg = this.args[attributeName];\n return arg ? arg.values.length : null;\n }",
"function get_item_size() {\n var sz = 220;\n return sz;\n}",
"get size(){\r\n return this.cards.length;\r\n }",
"function getLength(arr, cb) {\n\tcb(arr.length);\n}",
"function length () {\r\n return this.node.getComputedTextLength()\r\n}",
"function getLength(string){\n\n\n}",
"function length() {\n return this.top;\n}",
"getSize() {\n return this.queue.length;\n }",
"function getFieldLength(type, value) {\n\tvar remainder, length;\n\tswitch(type) {\n\t\tcase Types.STRUCTURE: //is the total length of all of the sub-items contained in the structure, including any padding.\n\t\t\tif (value) {\n\t\t\t\tvar tmpLen = getByteLen(value);\n\t\t\t\treturn tmpLen.toString(16);\n\t\t\t}\n\t\tcase Types.INTEGER:\n\t\t\treturn 4;\n\t\tcase Types.LONG_INTEGER:\n\t\t\treturn 8;\n\t\tcase Types.BIG_INTEGER:\n\t\tcase Types.ENUMERATION:\n\t\t\treturn 4;\n\t\tcase Types.BOOLEAN:\n\t\t\treturn 8;\n\t\tcase Types.TEXT_STRING:\n\t\tif (value) {\n\t\t\tvar tmpLen = value.length/2; //ex: 0000000(size 8) / 2 = 4\n\t\t\treturn parseInt(tmpLen.toString(16));\n\t\t}\n\t\tcase Types.BYTE_STRING:\n\t\tcase Types.DATE_TIME:\n\t\t\treturn 8;\n\t\tcase Types.INTERVAL:\n\t\t\treturn 4;\n\t\tdefault:\n\t\t\treturn 4;\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Optional, empty implementation, called from createScene. Should return a ShadowGenerator. | async createShadows() {} | [
"function ShadowGenerator(mapSize,light,useFullFloatFirst){this._bias=0.00005;this._normalBias=0;this._blurBoxOffset=1;this._blurScale=2;this._blurKernel=1;this._useKernelBlur=false;this._filter=ShadowGenerator.FILTER_NONE;this._filteringQuality=ShadowGenerator.QUALITY_HIGH;this._contactHardeningLightSizeUVRatio=0.1;this._darkness=0;this._transparencyShadow=false;/**\n * Controls the extent to which the shadows fade out at the edge of the frustum\n * Used only by directionals and spots\n */this.frustumEdgeFalloff=0;/**\n * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.\n * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.\n * It might on the other hand introduce peter panning.\n */this.forceBackFacesOnly=false;this._lightDirection=BABYLON.Vector3.Zero();this._viewMatrix=BABYLON.Matrix.Zero();this._projectionMatrix=BABYLON.Matrix.Zero();this._transformMatrix=BABYLON.Matrix.Zero();this._cachedPosition=new BABYLON.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);this._cachedDirection=new BABYLON.Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);this._currentFaceIndex=0;this._currentFaceIndexCache=0;this._defaultTextureMatrix=BABYLON.Matrix.Identity();this._mapSize=mapSize;this._light=light;this._scene=light.getScene();light._shadowGenerator=this;var component=this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);if(!component){component=new BABYLON.ShadowGeneratorSceneComponent(this._scene);this._scene._addComponent(component);}// Texture type fallback from float to int if not supported.\nvar caps=this._scene.getEngine().getCaps();if(!useFullFloatFirst){if(caps.textureHalfFloatRender&&caps.textureHalfFloatLinearFiltering){this._textureType=BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;}else if(caps.textureFloatRender&&caps.textureFloatLinearFiltering){this._textureType=BABYLON.Engine.TEXTURETYPE_FLOAT;}else{this._textureType=BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;}}else{if(caps.textureFloatRender&&caps.textureFloatLinearFiltering){this._textureType=BABYLON.Engine.TEXTURETYPE_FLOAT;}else if(caps.textureHalfFloatRender&&caps.textureHalfFloatLinearFiltering){this._textureType=BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;}else{this._textureType=BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;}}this._initializeGenerator();this._applyFilterValues();}",
"function ShadowGenerator(mapSize, light, useFullFloatFirst) {\n // Members\n this._bias = 0.00005;\n this._blurBoxOffset = 1;\n this._blurScale = 2;\n this._blurKernel = 1;\n this._useKernelBlur = false;\n this._filter = ShadowGenerator.FILTER_NONE;\n this._darkness = 0;\n this._transparencyShadow = false;\n this.forceBackFacesOnly = false;\n this._lightDirection = BABYLON.Vector3.Zero();\n this._viewMatrix = BABYLON.Matrix.Zero();\n this._projectionMatrix = BABYLON.Matrix.Zero();\n this._transformMatrix = BABYLON.Matrix.Zero();\n this._worldViewProjection = BABYLON.Matrix.Zero();\n this._currentFaceIndex = 0;\n this._currentFaceIndexCache = 0;\n this._isCube = false;\n this._defaultTextureMatrix = BABYLON.Matrix.Identity();\n this._mapSize = mapSize;\n this._light = light;\n this._scene = light.getScene();\n light._shadowGenerator = this;\n // Texture type fallback from float to int if not supported.\n var caps = this._scene.getEngine().getCaps();\n if (!useFullFloatFirst) {\n if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {\n this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n }\n else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {\n this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;\n }\n else {\n this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n }\n }\n else {\n if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {\n this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;\n }\n else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {\n this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;\n }\n else {\n this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;\n }\n }\n this._initializeGenerator();\n }",
"get Shadowmap() {}",
"generateShadowObject(contextType, attrs) {\n let shadow = new Group(this, 'group', contextType, attrs);\n let queue = get(this, '_shadowRegistrationQueue');\n set(this, '_shadowRegistrationQueue', []);\n\n set(this, 'shadow', shadow);\n queue.forEach(childShadow => {\n shadow.add(childShadow);\n });\n }",
"_recreateNoiseGenerators() {\r\n\r\n\t\tconst rnd = new MersenneTwister( Math.trunc( this._noiseSeed * 0xFFFFFFFF ) );\t\r\n\r\n\t\tfor( let i = 0; i < this._options.noise.octaves; ++i ){\r\n\t\t\tconst derivedSeed = rnd.random();\r\n\r\n\t\t\tconst gen = this._noiseGenes[ i ];\r\n\t\t\tif( gen ){\r\n\t\t\t\tgen.seed = derivedSeed;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tthis._noiseGenes[ i ] = new noise.NoiseGen( derivedSeed );\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"function ShadowMapScene() {\r\n\t// Setup inherited members.\r\n\tBaseScene.call(this);\r\n\r\n\t// Point light source.\r\n\tthis.mPointLight = null;\r\n\r\n\t// Directional light source. Always points towards the origin.\r\n\tthis.mDirectionalLight = null;\r\n\r\n\t// Gets or sets the current light position for either the point light or\r\n\t// the directional light.\r\n\tthis.mLightPosition = new Point();\r\n\r\n\t// Gets or sets the current angle of the light source, in radians. Used for\r\n\t// animating the light source around in a circle.\r\n\tthis.mAnimLightPosition\r\n\r\n\t// Stores the inverse view matrix.\r\n\tthis.mInvViewMatrix = null;\r\n\r\n\t// Projection matrix used by the light sources. Typically a 90' perspective\r\n\t// frustum with 1.0 aspect ratio.\r\n\tthis.mLightProjection = null;\r\n\r\n\t// Point light view array of matrices. This is used for rendering the scene\r\n\t// from the light's point of view. There are 6 view matrices in all, one\r\n\t// for each face of the cube.\r\n\tthis.mPointLightViewMatrix = null;\r\n\r\n\t// The framebuffer object to store the depth map. This will be fed into the\r\n\t// shadow map shader.\r\n\tthis.mFboDepth = null;\r\n\r\n\t// The framebuffer object for performing the first pass [horizontal] blur using\r\n\t// the\r\n\t// seperable blur algorithm. On the second pass, the final bluring will be stored\r\n\t// back\r\n\t// into the mFboDepth object.\r\n\tthis.mFboBlur = null;\r\n\r\n\t// Framebuffer objects.\r\n\tthis.mFboDepthColourBuffer = null;\r\n\tthis.mFboDepthDepthBuffer = null;\r\n\tthis.mFboBlurColourBuffer = null;\r\n\r\n\t// Gets or sets the dimensions of the FBO, or in other words the size of the\r\n\t// shadow map.\r\n\tthis.mFboDimension = null;\r\n\r\n\t// The depth shader is responsible for rendering the depth values. The scene will\r\n\t// be\r\n\t// rendered from the light's point of view. For point lights, this will be\r\n\t// iterated\r\n\t// six times, one for each face of the cube.\r\n\tthis.mDepthShader = null;\r\n\r\n\t// The shader uses gaussian to blur a texture. It uses the seperable blur\r\n\t// algorithm, which\r\n\t// divides blurring into two passes. The first pass will render a horizontal\r\n\t// blur. The second\r\n\t// pass will render the vertical blur. This is much faster than using a\r\n\t// traditional convolution\r\n\t// filter algorithm.\r\n\tthis.mGaussianBlurShader = null;\r\n\tthis.mGaussianBlurCubeShader = null;\r\n\r\n\t// The shadowmap shader is identical to the basic lighting shader except that\r\n\t// it performs an additional check to determine if the pixel is inside a shadow.\r\n\tthis.mShadowMapShader = null;\r\n\tthis.mShadowMapCubeShader = null;\r\n\r\n\t// This shader renders a simple texture to the screen. It is used for displaying\r\n\t// the depth map.\r\n\tthis.mDepthRenderShader = null;\r\n\tthis.mDepthRenderCubeShader = null;\r\n\r\n\t// Surface (rectangle) containing a texture to manipulate or view. Used for\r\n\t// blurring or\r\n\t// showing the depth map.\r\n\tthis.mSurface = null;\r\n\r\n\t// Stores a reference to the canvas DOM element, which is used to reset the\r\n\t// viewport\r\n\t// back to its original size after rendering to the FBO, which uses a different\r\n\t// dimension.\r\n\tthis.mCanvas = null;\r\n\r\n\t// UI members.\r\n\tthis.mDivLoading = null;\r\n\tthis.mTxtLoadingProgress = null;\r\n\tthis.mCboxResolution = null;\r\n\tthis.mCboxBlurDepthMap = null;\r\n\tthis.mCboxFilter = null;\r\n\tthis.mCboxViewState = null;\r\n\tthis.mCboxEnableAnimation = null;\r\n\tthis.mRadioDirectionalLight = null;\r\n\tthis.mRadioPointLight = null;\r\n\r\n\tthis.mViewState = 0;\r\n\tthis.mIsPointLightActive = false;\r\n}",
"function makeChinShadow(){\n var chin = makeNoFaceMask(0xB58EFF);\n chin.scale.set(0.1, 0.015, 0.075);\n return chin;\n}",
"initShadows($MIRROR, $SHADOWS_PANEL, _SOC_DATA) {\n const $mirror_content = $($MIRROR.contents());\n console.debug(\n \"Mirror is loaded: width[%s], height[%s]\",\n $mirror_content.width(),\n $mirror_content.height()\n );\n\n // Set width and height for proper position\n $MIRROR.height($mirror_content.height());\n $SHADOWS_PANEL.height($mirror_content.height());\n\n // Calculate shadows and set correct positions\n const mirrorUtil = new MirrorUtil();\n _SOC_DATA.rootNode = mirrorUtil.getPageComponents($mirror_content.find(\"body\"));\n const pageUtil = new PageUtil();\n pageUtil.shadowsTreeNodes(_SOC_DATA.rootNode).forEach((el) => {\n $SHADOWS_PANEL.append(el);\n });\n\n const HOVER_BORDER_SIZE = 2; // in px\n mirrorUtil\n .getShadows(_SOC_DATA.rootNode.children)\n .forEach((el) => {\n console.debug(\"Set position of: %s\", el[4]);\n const shadow = $(\"#\" + el[4]);\n if (shadow) {\n shadow.css({\n \"top\": el[0],\n \"left\": el[1] + HOVER_BORDER_SIZE,\n \"width\": el[2] - HOVER_BORDER_SIZE * 4,\n \"height\": el[3] - HOVER_BORDER_SIZE * 2\n });\n }\n });\n\n const _menu = new ShadowComponentMenu();\n\n $SHADOWS_PANEL.on(\"click\", \".shadow-component\", (e) => {\n const id = $(e.target).attr(\"id\");\n if (id) {\n const selectedShadow = _SOC_DATA.rootNode.getChildById(id);\n if (selectedShadow) {\n _SOC_DATA.selectedEl = selectedShadow;\n }\n }\n _menu.showToolbar(e.target);\n });\n $SHADOWS_PANEL.show();\n }",
"plantSeed() {\n\t\tthis.stop();\n\t\tthis.loops = 0;\n\t\tthis.myTree = new FractalTree({x: ground.width/2-100, y: ground.height-20}, this.myDNA);\n\t\tthis.settingsClose();\n\t\tthis.play();\n\t}",
"function ShadowDepthWrapper(baseMaterial, scene, options) {\n var _this = this;\n this._baseMaterial = baseMaterial;\n this._scene = scene;\n this._options = options;\n this._subMeshToEffect = new Map();\n this._subMeshToDepthEffect = new MapMap();\n this._meshes = new Map();\n var prefix = baseMaterial.getClassName() === \"NodeMaterial\" ? \"u_\" : \"\";\n if (prefix) {\n this._matriceNames = {\n \"world\": prefix + \"World\",\n \"view\": prefix + \"View\",\n \"projection\": prefix + \"Projection\",\n \"viewProjection\": prefix + \"ViewProjection\",\n \"worldView\": prefix + \"WorldxView\",\n \"worldViewProjection\": prefix + \"WorldxViewxProjection\",\n };\n var nodeMat = baseMaterial;\n var inputBlocks = nodeMat.getInputBlocks();\n for (var i = 0; i < inputBlocks.length; ++i) {\n switch (inputBlocks[i]._systemValue) {\n case NodeMaterialSystemValues.World:\n this._matriceNames[\"world\"] = inputBlocks[i].associatedVariableName;\n break;\n case NodeMaterialSystemValues.View:\n this._matriceNames[\"view\"] = inputBlocks[i].associatedVariableName;\n break;\n case NodeMaterialSystemValues.Projection:\n this._matriceNames[\"projection\"] = inputBlocks[i].associatedVariableName;\n break;\n case NodeMaterialSystemValues.ViewProjection:\n this._matriceNames[\"viewProjection\"] = inputBlocks[i].associatedVariableName;\n break;\n case NodeMaterialSystemValues.WorldView:\n this._matriceNames[\"worldView\"] = inputBlocks[i].associatedVariableName;\n break;\n case NodeMaterialSystemValues.WorldViewProjection:\n this._matriceNames[\"worldViewProjection\"] = inputBlocks[i].associatedVariableName;\n break;\n }\n }\n }\n else {\n this._matriceNames = {\n \"world\": prefix + \"world\",\n \"view\": prefix + \"view\",\n \"projection\": prefix + \"projection\",\n \"viewProjection\": prefix + \"viewProjection\",\n \"worldView\": prefix + \"worldView\",\n \"worldViewProjection\": prefix + \"worldViewProjection\",\n };\n }\n // Register for onEffectCreated to store the effect of the base material when it is (re)generated. This effect will be used\n // to create the depth effect later on\n this._onEffectCreatedObserver = this._baseMaterial.onEffectCreatedObservable.add(function (params) {\n var _a;\n var mesh = (_a = params.subMesh) === null || _a === void 0 ? void 0 : _a.getMesh();\n if (mesh && !_this._meshes.has(mesh)) {\n // Register for mesh onDispose to clean up our internal maps when a mesh is disposed\n _this._meshes.set(mesh, mesh.onDisposeObservable.add(function (mesh) {\n var iterator = _this._subMeshToEffect.keys();\n for (var key = iterator.next(); key.done !== true; key = iterator.next()) {\n var subMesh = key.value;\n if ((subMesh === null || subMesh === void 0 ? void 0 : subMesh.getMesh()) === mesh) {\n _this._subMeshToEffect.delete(subMesh);\n _this._subMeshToDepthEffect.mm.delete(subMesh);\n }\n }\n }));\n }\n _this._subMeshToEffect.set(params.subMesh, params.effect);\n _this._subMeshToDepthEffect.mm.delete(params.subMesh); // trigger a depth effect recreation\n });\n }",
"function GenNoise()\n{\n var value;\n for (var i = 0; i < PATTERN_PIXELS; i += 4)\n {\n value = (Math.random() * 255);\n pattern_data.data[i] = value;\n pattern_data.data[i+1] = value;\n pattern_data.data[i+2] = value;\n pattern_data.data[i+3] = PATTERN_ALPHA;\n\n var frame_ind;\n if (transition)\n \tframe_ind = FRAME_IND_ANIM[still_current][anim_frame_current];\n else\n \tframe_ind = FRAME_IND_STILL[still_current];\n\t\tpattern_data.data[i+3] *= FRAME_GRAIN_ALPHA[frame_ind];\n }\n pattern_ctx.putImageData(pattern_data, 0, 0);\n}",
"function generateZerg() {\n if (frames % 70 === 0) {\n enemies.push(new Zerg())\n }\n }",
"createEffect() {\n return new FilterEffect()\n }",
"function setShadow(data, clock) {\n clock.rotateElement(shadow, data.angle);\n shadow.style.opacity = data.opacity;\n}",
"createPointerMoveEffect()\n {\n let effect = this.add.particles('glow').createEmitter({\n x: 400,\n y: 300,\n speed: { min: 0, max: 0 },\n angle: { min: 0, max: 180 },\n scale: { start: 1, end: 0, ease: 'Quart.easeOut' },\n alpha: { start: 1, end: 0, ease: 'Quart.easeOut' },\n blendMode: 'SCREEN',\n _frequency: 60,\n lifespan: 3000,\n active: true\n });\n\n effect.reserve(64);\n effect.stop();\n\n return effect;\n }",
"addDropShadows() {\n let offset = this.calendarView.mShadowOffset;\n let shadowStartDate = this.date.clone();\n shadowStartDate.addDuration(offset);\n this.calendarView.mDropShadows = [];\n for (let i = 0; i < this.calendarView.mDropShadowsLength; i++) {\n let box = this.calendarView.findDayBoxForDate(shadowStartDate);\n if (box) {\n box.setDropShadow(true);\n this.calendarView.mDropShadows.push(box);\n }\n shadowStartDate.day += 1;\n }\n }",
"syncShadow() {\n if (!this.memory) {\n this.memory = assert(this.options.getMemory());\n this.shadow = new WebAssembly.Memory({\n initial: ((this.memory.buffer.byteLength + PAGE_MASK) & ~PAGE_MASK) >>> PAGE_SIZE_BITS\n });\n } else {\n var diff = this.memory.buffer.byteLength - this.shadow.buffer.byteLength;\n if (diff > 0) this.shadow.grow(diff >>> 16);\n }\n }",
"function disableShadowsForLight(light) {\n renderer.shadowMapAutoUpdate = false;\n renderer.clearTarget(light.shadowMap);\n renderer.shadowMapAutoUpdate = true;\n}",
"function WoodenToysFactory(){}",
"function resetShadow(canvasContext) {\n canvasContext.shadowColor = \"rgba(0, 0, 0, 0.0)\";\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes all occurrences of needle from the beginning of haystack. | function ltrim(haystack, needle) {
if (!haystack || !needle) {
return haystack;
}
var needleLen = needle.length;
if (needleLen === 0 || haystack.length === 0) {
return haystack;
}
var offset = 0, idx = -1;
while ((idx = haystack.indexOf(needle, offset)) === offset) {
offset = offset + needleLen;
}
return haystack.substring(offset);
} | [
"function trim_left_1(s, sub) /* (s : string, sub : string) -> string */ { tailcall: while(1)\n{\n if (empty_ques__1(sub)) {\n return s;\n }\n else {\n var _x34 = starts_with(s, sub);\n if (_x34 != null) {\n {\n // tail call\n var _x35 = (string_3(_x34.value));\n s = _x35;\n continue tailcall;\n }\n }\n else {\n return s;\n }\n }\n}}",
"function startsWith(self, phrase) {\r\n return phrase.length && self.length && !self.indexOf(phrase);\r\n }",
"function removeWord () {\n firstWord.remove();\n}",
"function substringsAtStart(string) {\n var result = [];\n\n for (var i = 0; i < string.length; i++) {\n result.push(string.substr(0, i+1));\n }\n\n return result;\n}",
"function clearRange(value, start, end) {\n return value.substring(0, start) + value.substring(end);\n }",
"function arrayRemoveIntersect(a, b){\n var i, j, k, dup = arrayIntersect(a, b);\n for(i = 0, j = dup.length; i < j; i++){\n if ((k = a.indexOf(dup[i])) === -1) continue;\n a.splice(k, 1);\n }\n}",
"removeWord(word) {\n if(typeof word !== 'string' || word === '') {\n throw(`Expected parameter string, received ${typeof word}`);\n }\n\n const { prefixFound, prefixNode } = checkPrefix(trie, word);\n\n if(prefixFound) {\n delete prefixNode[config.END_WORD];\n }\n\n return this;\n }",
"function keepFirst(str) {\n return str.slice(0, 2);\n}",
"function moveMarkersToFront(x) {\n const re = /^(\\s+)!!/gm;\n return x.replace(re, (_, spaces) => `!!${spaces.substring(0, spaces.length - 2)}`);\n }",
"function titleSplice(arr, phrase, front) {\n console.log(\"array length \" + arr.length);\n for (var i = 0; i < arr.length; i++) {\n temp = arr[i];\n index = temp.indexOf(phrase);\n \n if (front && index > 0) {\n \n \ttemp = temp.slice(0, index);\n \n } else if (!front && index > 0) {\n temp = temp.slice(index, temp.length-1);\n }\n console.log(temp);\n arr[i] = temp;\n }\n return arr;\n}",
"function leftTrimString(astrValue)\n{\n var lstrValue = astrValue;\n\n lstrValue=lstrValue.replace(/^\\s*(.*)/, \"$1\");\n return lstrValue;\n}",
"function replaceAll(Source,stringToFind,stringToReplace){\n var temp = Source;\n var index = temp.indexOf(stringToFind);\n while(index != -1){\n temp = temp.replace(stringToFind,stringToReplace);\n index = temp.indexOf(stringToFind);\n }\n return temp;\n}",
"clearSourceSearch() {\n this.sourceQuery = '';\n this.sourceCategoryResults.length = 0;\n }",
"function cleanBookmark(s) {\n\tvar n = s.indexOf(\"#\");\n\tif (n>0) {\n\t\treturn s.substring(0,n);\n\t} else {\n\t\treturn s;\n\t}\n}",
"function getFront(mainStr,searchStr)\r\n{\r\n var foundOffset=mainStr.indexOf(searchStr);\r\n if(foundOffset==-1)\r\n return null;\r\n return mainStr.substring(0,foundOffset);\r\n}",
"function strpos(haystack, needle, offset)\n {\n var i = (haystack+'').indexOf(needle, (offset || 0));\n return i === -1 ? false : i;\n }",
"function removeStrainSearch() {\n const resultsContainer = document.querySelector('.results-container')\n while (resultsContainer.lastChild) {\n resultsContainer.removeChild(resultsContainer.lastChild)\n }\n}",
"function find(haystack, needle) {\n if (haystack.indexOf(needle) != -1) {\n return 0;\n }\n var hi = 0;\n var ni = 0;\n var penalty = 0;\n var started = false;\n while (true) {\n while (needle[ni] < 'a' || needle[ni] > 'z') {\n ++ni;\n if (ni == needle.length) {\n return penalty;\n }\n }\n while (haystack[hi] != needle[ni]) {\n ++hi;\n if (started) {\n ++penalty;\n }\n if (hi == haystack.length) {\n return -1;\n }\n }\n ++hi;\n ++ni;\n started = true;\n if (ni == needle.length) {\n return penalty;\n }\n if (hi == haystack.length) {\n return -1;\n }\n }\n}",
"function removeSelect2Search(snselector) {\n snselector.select2({\n minimumResultsForSearch: -1\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
recursively walk the visual tree, collecting objects as we go | function traverseVisualTree(obj, parent) {
obj.vtkey = visualNodeDataArray.length;
visualNodeDataArray.push(obj);
if (parent) {
obj.parentKey = parent.vtkey;
}
if (obj instanceof go.Diagram) {
var lit = obj.layers;
while (lit.next()) traverseVisualTree(lit.value, obj);
} else if (obj instanceof go.Layer) {
var pit = obj.parts;
while (pit.next()) traverseVisualTree(pit.value, obj);
} else if (obj instanceof go.Panel) {
var eit = obj.elements;
while (eit.next()) traverseVisualTree(eit.value, obj);
}
} | [
"render() {\n const properties = Memory.getObject(allProperties, this);\n if (properties.recycle) {\n properties.recycle = false;\n if (properties.component && properties.component.canRecycle(properties.state)) {\n properties.state = properties.component.state;\n const results = properties.component.render();\n const oldChildren = properties.children;\n const newChildren = results instanceof Array ? results : [results];\n properties.children = Engine.update(this, allProperties, newChildren, oldChildren);\n }\n else {\n for (const child of properties.children) {\n child.render();\n }\n }\n }\n }",
"function walkViewTree(rootView, fn) {\n let visit_ = view => {\n fn(view);\n\n let nsArray = view.subviews();\n let count = nsArray.count();\n for (let i = 0; i < count; i++) {\n visit_(nsArray.objectAtIndex(i));\n }\n };\n\n visit_(rootView);\n}",
"visitWindowing_elements(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"updateMeshDrawings() {\n let canvas = this;\n let scene = this.scene;\n if ('children' in this.scene) {\n scene.children.forEach(function(child) {\n canvas.updateMeshDrawingsRecurse(child);\n });\n }\n }",
"function flattenVisible(root){\n var nodes = [], i = 0;\n\n function recurse(node, indx, arr) {\n if (node.children) node.children.forEach(recurse);\n nodes.push(node);\n }\n\n recurse(root, 0, null);\n return nodes;\n}",
"displayScene() {\n //To do: Create display loop for transversing the scene graph, calling the root node's display function\n this.scene.pushMatrix();\n this.processDescendants(this.nodes[this.idRoot]);\n this.scene.popMatrix();\n }",
"buildTree() {\n if (!this.drawnAnnotations.length && !this.annosToBeDrawnAsInsets.size) {\n // Remove all exlisting clusters\n this.areaClusterer.cleanUp(new KeySet());\n return;\n }\n\n // if (this.newAnno) this.tree.load(this.drawnAnnotations);\n\n this.createInsets();\n }",
"function SplayTree() { }",
"findRegions(state) {\n let lang = state.facet(language)\n if (\n (lang === null || lang === void 0 ? void 0 : lang.data) == this.data\n )\n return [{ from: 0, to: state.doc.length }]\n if (!lang || !lang.allowsNesting) return []\n let result = []\n let explore = (tree, from) => {\n if (tree.prop(languageDataProp) == this.data) {\n result.push({ from, to: from + tree.length })\n return\n }\n let mount = tree.prop(dist_NodeProp.mounted)\n if (mount) {\n if (mount.tree.prop(languageDataProp) == this.data) {\n if (mount.overlay)\n for (let r of mount.overlay)\n result.push({ from: r.from + from, to: r.to + from })\n else result.push({ from: from, to: from + tree.length })\n return\n } else if (mount.overlay) {\n let size = result.length\n explore(mount.tree, mount.overlay[0].from + from)\n if (result.length > size) return\n }\n }\n for (let i = 0; i < tree.children.length; i++) {\n let ch = tree.children[i]\n if (ch instanceof dist_Tree) explore(ch, tree.positions[i] + from)\n }\n }\n explore(dist_syntaxTree(state), 0)\n return result\n }",
"function recursiveDispose ( object ) {\n\n\t\t\tfor ( var i = object.children.length - 1; i >= 0; i-- ) {\n\n\t\t\t\trecursiveDispose( object.children[i] );\n\t\t\t\tobject.remove( object.children[i] );\n\n\t\t\t}\n\n\t\t\tif ( object instanceof PANOLENS.Infospot ) {\n\n\t\t\t\tobject.dispose();\n\n\t\t\t}\n\t\t\t\n\t\t\tobject.geometry && object.geometry.dispose();\n\t\t\tobject.material && object.material.dispose();\n\t\t\tobject.texture && object.texture.dispose();\n\t\t\t\n\t\t}",
"function update() {\n\n //cast ray to go through objects\n raycaster.setFromCamera(mouse, camera);\n //array of targeted objects, ordered by distance - near to far\n var intersects = raycaster.intersectObjects( scene.children );\n //black out targeted partition of sunburst\n if (intersects.length > 0) {\n\n var targetedObject = intersects[0];\n\n //color out targeted node\n setColorHighlight(targetedObject.object.material.color);\n\n\n var targetedObjectNode = getSceneObjectNodeById(subtree.root, targetedObject.object);\n document.getElementById(\"latinWindow\").innerHTML = targetedObjectNode.latin;\n //get node of blacked out object\n var lastAccessedObjectNode = getSceneObjectNodeById(subtree.root, lastAccessedObject);\n\n //create new color by force - #000000 format to 0x000000 format\n var colors = lastAccessedObjectNode.color.split(\"#\");\n var color = (\"0x\" + colors[1]);\n \n //if I moved on another object\n if(targetedObject.object != lastAccessedObject) {\n //apply the original color\n if (lastAccessedObjectNode != null) {\n lastAccessedObjectNode.sceneObject.material.color.setHex(color);\n }\n }\n\n lastAccessedObject = targetedObject.object;\n }\n //if you run down from a node, remove highlighting and innerHTML\n else{\n var lastAccessedObjectNode = getSceneObjectNodeById(subtree.root, lastAccessedObject);\n var colors = lastAccessedObjectNode.color.split(\"#\");\n var color = (\"0x\" + colors[1]);\n if (lastAccessedObjectNode != null) {\n lastAccessedObjectNode.sceneObject.material.color.setHex(color);\n }\n //clear the display of latin name\n document.getElementById(\"latinWindow\").innerHTML = \"\";\n }\n}",
"function collectRefsRecursive(host, content, refs) {\n var childNodes = host.childNodes;\n for (var i = 0, n = content.length; i < n; ++i) {\n var elem = content[i];\n var type = elem.type;\n if (type === 1 /* Node */) {\n var node = childNodes[i];\n var ref = elem.data.ref;\n if (ref)\n refs[ref] = node;\n collectRefsRecursive(node, elem.children, refs);\n }\n else if (type === 2 /* Component */) {\n var ref = elem.data.ref;\n if (ref)\n refs[ref] = componentMap.get(childNodes[i]);\n }\n }\n }",
"function renderChildAndPartnerLinks() {\n for (const [, persons] of generations)\n for (const person of persons) {\n const personBox = jQuery(\"#box-\" + person.id);\n if (person.children)\n for (const child of person.children)\n drawPath(personBox, jQuery(\"#box-\" + child.id), \"link-child\");\n if (person.partners)\n for (const partner of person.partners)\n drawPartnerPath(personBox, jQuery(\"#box-\" + partner.id));\n }\n}",
"function _processHierarchy() {\n const {nodeMap, parameterMap, constMap, root} = processedGraph;\n const nodes = Object.values(nodeMap);\n const usedAuxiliaryNodes = {parameter: {}, const: {}};\n\n // record the input and output of all nodes\n for (const node of nodes) {\n if (node.type === NODE_TYPE.name_scope) continue;\n const parent = node.parent ? nodeMap[node.parent] : root;\n parent.children.push(node.id);\n\n for (const inputId of node.input) {\n const source =\n nodeMap[inputId] || parameterMap[inputId] || constMap[inputId];\n if (!source) continue;\n if (\n source.type === NODE_TYPE.parameter ||\n source.type === NODE_TYPE.const\n ) {\n source.parent = parent.id;\n node[source.type + 's'][source.id] = source;\n usedAuxiliaryNodes[source.type][source.id] = source;\n } else {\n if (\n node.parent &&\n !source.scope.startsWith(node.parent)\n ) {\n nodeMap[node.parent].input.push(inputId);\n }\n if (\n source.parent &&\n !node.scope.startsWith(source.parent)\n ) {\n nodeMap[source.parent].output.push(node.id);\n }\n }\n }\n }\n processedGraph.parameterMap = usedAuxiliaryNodes.parameter;\n processedGraph.constMap = usedAuxiliaryNodes.const;\n\n // record the input and output of namescopes\n for (let len = nameScopeIds.length - 1, i = len; i >= 0; i--) {\n const id = nameScopeIds[i];\n const nameScope = nodeMap[id];\n nameScope.children = Array.from(new Set(nameScope.children));\n nameScope.input = Array.from(new Set(nameScope.input));\n nameScope.output = Array.from(new Set(nameScope.output));\n\n if (!nameScope.parent) continue;\n const parent = nodeMap[nameScope.parent];\n parent.input = parent.input.concat(\n Object.values(_filterIOData(nameScope.input, parent.id)),\n );\n parent.output = parent.output.concat(\n Object.values(_filterIOData(nameScope.output, parent.id)),\n );\n }\n}",
"outChildComponents() {\n if(Array.isArray(this.props.loopedComponents)) {\n this.props.loopedComponents.forEach((component) => {\n if(Array.isArray(component.renderedComponents)) {\n Array.from(component.renderedComponents).forEach(comp => {\n comp.out();\n })\n component.renderedComponents = [];\n }\n })\n }\n if(typeof this.childsObj == \"object\") {\n Object.values(this.childsObj).map((component) => {\n component.out();\n })\n }\n }",
"build() {\n\t\tconst self = this;\n\n\t\tself.buildTags();\n\t\tself.buildTree();\n\t}",
"printDebug()\n {\n console.log(\"Tree contents\");\n this.iterateTree(function(node)\n {\n console.log(node);\n });\n }",
"draw() {\n if (this.paused) return;\n \n clear();\n this.quadtree.clear();\n \n // add each blob to quadtree\n this.blobs.forEach(blob => {\n this.quadtree.insert(blob);\n });\n \n // move and draw each blob\n this.blobs.forEach(blob => {\n // what the blob sees\n let saw = blob.see(this.quadtree);\n \n // TODO: turn saw into inputs\n let input = [];\n let output = blob.network.compute(input);\n blob.move(output[0] * TWO_PI, output[1]);\n \n let collidedWith = blob.checkCollision(this.quadtree);\n if (collidedWith) {\n if (collidedWith.size > blob.size) {\n // blob dies\n \n } else {\n // collidedWith dies\n \n }\n }\n \n if (this.dead.length == this.population) {\n this.allDead();\n return;\n }\n \n blob.draw();\n });\n }",
"function Recurse(a) { // loop through an array\n\t\n\t\tif (a.constructor == Array) {\n\t\t\tfor (var i = 0; i < a.length; i++)\n\t\t\t\tRecurse(a[i]);\n\t\t}\n\t\telse element.innerHTML += a + \"<br />\";\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a function that reverses your telephone number. It should return the reversed telephone number. your code... | function reversePhone(number) {
} | [
"function reversePhone(phone) {\n phone = phone + \"\";\n return phone.split(\"\").reverse().join(\"\");\n}",
"function reverseDigitsOfNumber(enteredNumber) {\n var reversedNumber = enteredNumber.split(\"\").reverse().join(\"\");\n console.log(reversedNumber);\n}",
"function reverseNumber(n) {\n let num = parseFloat(n.toString().split('').reverse().join(''))\n //multiply the reversed with the positive or negative of the original number passed through the function to keep the sign\n return num *Math.sign(n)\n}",
"function reverse(input) {\n return input.split('').reverse().join('');\n}",
"function reverse(){\n const a = 'ierdnA si eman yM iH'\n const result = a.split('').reverse().join('');\n\n console.log(result)\n}",
"function reverseStr (string) {\n // this function just returns the string split, into an array with the split method, with no space so it goes by character in an array with the split method, then using the reverse array method it reverses it, then rejoins with the join array method to be the reversed string.\n return string.split(\"\").reverse().join(\"\");\n \n \n \n}",
"function reverseStringBuiltInFn(originalString) {\n chars = originalString.split(\"\");\n reversedArray = chars.reverse()\n reversedString = reversedArray.join(\"\");\n return reversedString;\n}",
"function reverseAndNot(i) {\n return parseInt(i.toString().split(\"\").reverse().join(\"\") + i);\n}",
"function invertirFrase(n) {\n let frase = \"\";\n for (let i = n.length - 1; i >= 0; i--) {\n frase += n[i];\n }\n return frase;\n }",
"function reverseOrder(s){\n return s.split('').reverse().join('');\n}",
"function palindromize(number){\n let numStr = number.toString();\n let numStrRev = numStr.split('').reverse().join('');\n let ctr = 0;\n \n while(numStr != numStrRev){\n numStr = (+numStr + +numStrRev).toString();\n numStrRev = numStr.split('').reverse().join('');\n ctr++;\n };\n \n return ctr + ' ' + numStr;\n}",
"reverseNth(n) {\n // YOUR CODE HERE\n }",
"reverse() {\n //current node\n let node = this.head;\n //assign tail to the head\n this.head = this.tail;\n //assign the current node to the tail\n this.tail = node;\n let next;\n //create a previous variable and set it to null because you want to make sure that the end of the tail.next is pointing to null\n let prev = null;\n //loop through the list\n for (var i = 0; i < this.length; i++) {\n // keeps track of what the current node is pointing to so that you can move onto it\n next = node.next;\n //set the next property on the current node to point to whatever the prev is, this is the start of the reversing of the list\n node.next = prev;\n //set prev to be the value of the current node variable, assigning what is currently the node to the previous spot in preparation for the loop to increment the index to the next node\n prev = node;\n //set the node variable to the value of the next variable, the next variable stores what the current node is pointing at, therefore you assign what is the next node to the current node spot \n node = next;\n }\n return this;\n\n\n }",
"reverse() {\n this.reverseHelper(this.head, this.tail);\n }",
"reverse() {\n const compareOriginial = this.compare;\n this.compare = (a, b) => compareOriginial(b, a);\n }",
"function returnReversed(arr) {\n var temp;\n for (var i = 0; i < arr.length / 2; i++) {\n temp = arr[arr.length - 1 - i];\n arr[arr.length - 1 - i] = arr[i];\n arr[i] = temp;\n }\n return arr;\n}",
"function invertNum(num)\n{\n\treturn num *= -1;\n}",
"function invertirUnaPalabra(String){\r\n let alreves = \"\";\r\n let tamano = 3;\r\n let array = String.split(\"\");\r\n for(let i = tamano; i >= 0; i--){\r\n alreves+= array[i];\r\n }\r\n console.log(\"La palabra al reves es: \"+ alreves);\r\n return alreves;\r\n}",
"function problem4() {\r\n\tdocument.getElementById(\"problem4\")\r\n\t\r\n\t// Creates a function to split the entered word, reverse the letters\r\n\t// and then join the letters back together in reverse order. \r\n\tfunction testWord(word1){\r\n\t\treturn word1.split(\"\").reverse().join(\"\");\r\n\t\tstr.split(\"\").reverse().join(\"\");\r\n\t}\r\n\t\r\n\tvar word1 = prompt(\"Please enter a word.\");\r\n\t\r\n\tvar originalWord = word1;\r\n\tvar reverseWord = word1.split(\"\").reverse().join(\"\");\r\n\t\r\n\t\r\n\tif(originalWord === reverseWord) {\r\n\t\tdocument.write(\"The reverse of \" + originalWord + \" is \" + testWord(word1) + \".\" + \" This is a palindrome!\");\r\n\t}\r\n\t\telse {\r\n\t\t\tdocument.write(\"The reverse of \" + originalWord + \" is \" + testWord(word1) + \".\" + \" This is not a palindrome!\");\r\n\t\t}\r\n\ts\r\n\trefreshIt();\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
used to tell all server viewers that a user left | function SendUserLeftServer(ws) {
var returnMessage = {}
returnMessage["type"] = "user-left-server";
returnMessage["data"] = {};
returnMessage.data["user-id"] = ws.userId;
// don't use SendToAllServerViewers because we don't want to send this to the newly joined viewer //
for (var i=0; i<serverViewers.length; i++) {
if (serverViewers[i].userId != ws.userId) {
serverViewers[i].send(JSON.stringify(returnMessage));
}
}
} | [
"function SendUserLeft(ws, lobbyId) {\n var returnMessage = {}\n returnMessage[\"type\"] = \"user-left\";\n returnMessage[\"data\"] = {};\n returnMessage.data[\"user-id\"] = ws.userId;\n\n // tell all users in the lobby that a user joined the lobby //\n LobbyUserBroadcast(ws, lobbyId, returnMessage);\n\n // tell server viewers a user joined a lobby //\n ServerViewerBroadcastUserUpdate(ws);\n}",
"static sPlayerLeft(sid, room, username) {\n // Sending new state of the room.\n Signals.emit(sid, \"sPlayerLeft\", {\n \"username\": username, \"playerList\": getPlayerList(room.users),\n \"host\": getHostUsername(room.users)\n });\n }",
"function checkLogedInUser() {\n\n}",
"setUsersOnline (state, count) {\n state.usersOnline = count\n }",
"function SendUserJoinedServer(ws) {\n var returnMessage = {}\n returnMessage[\"type\"] = \"user-joined-server\";\n returnMessage[\"data\"] = {};\n returnMessage.data[\"user-id\"] = ws.userId;\n returnMessage.data[\"user-name\"] = ws.userName;\n returnMessage.data[\"lobby-id\"] = ws.lobbyId;\n returnMessage.data[\"gamemode\"] = ws.gamemode;\n\n // don't use SendToAllServerViewers because we don't want to send this to the newly joined viewer //\n for (var i=0; i<serverViewers.length; i++) {\n if (serverViewers[i].userId != ws.userId) {\n serverViewers[i].send(JSON.stringify(returnMessage));\n }\n }\n}",
"urlForLeaving() {\n return `/settings/${Spark.teamsPrefix}/${this.leavingTeam.id}/members/${this.user.id}`;\n }",
"function listRooms(user) {\n user.notify(Room.getRoomList());\n}",
"function getOnlineUsers(e){\n\tvar data = {\n\t\t\"session\": localStorage.sessionId\n\t}\n\tperformPostRequest(\"online-users.php\", data, function(data){\n\t\tswitch(data.status) {\n\t\t\tcase 470:\n\t\t\t\tlogOut();\n\t\t\t\tbreak;\n\t\t\tcase 200:\n\t\t\t\tshowOnlineUsersHtml(data);\n\t\t\t\tbreak;\n\t\t}\n\t});\n}",
"getRemovedUsers () {\n\t\treturn this.users.slice(1).map(data => data.user);\n\t}",
"function ServerHandleUserDisconnected(connectionID, user) {\n\t\n\tvar avatarEntityName = \"Watcher\" + user.GetProperty('username');\n\tvar avatarEntity = scene.GetEntityByName(avatarEntityName);\n\tif (avatarEntity != null) {\n\t\tscene.RemoveEntity(avatarEntity.id);\n\t\n\t\tif (user != null) {\n\t\t\tprint(\"[Avatar Application] User \" + user.GetProperty(\"username\") + \" disconnected, destroyed avatar entity.\");\n\t\t\t\n\t\t}\n\t}\n\t\n}",
"function setOnlineUser(user) {\n onlineUsers.push(user)\n console.log(`[ ${user.username.toUpperCase()}: IS NOW ONLINE ]`)\n console.log('[ONLINE USERS:]')\n \n function allOnlineUsers(onlineUsers) {\n for (user of onlineUsers) {\n console.log(`* ${user.username}`)\n }\n }\n \n allOnlineUsers(onlineUsers)\n \n }",
"function announceResults() {\n socket.sockets.emit(\"gameOver\");\n}",
"function _tellThatIamNotConnectionFor(memberNames,dontTellTo) {\n\n\tvar\n\t\tself = this,\n\t\tdontTellHash = { },\n\t\ttellTo = {};\n\n\t// Hash the values of dontTell\n\t(dontTellTo || []).forEach(function(who){\n\t\tdontTellHash[who] = true;\n\t});\n\n\tself._debug(5,\"Telling (not telling to \"+dontTellTo.join(',')+\") that I am not anymore connection for \",memberNames);\n\n\t// Tell\n\tself.everybody().forEach(function(somebody){\n\t\tvar who = [];\n\t\tif ( dontTellHash[somebody.name] )\n\t\t\treturn;\n\n\t\t// Dont tell to the own member\n\t\tfor ( var x = 0 ; x < memberNames.length ; x++ ) {\n\t\t\tif ( somebody.name != memberNames[x] && self.name != memberNames[x] ) {\n\t\t\t\tif ( somebody.toldHimAbout[memberNames[x]] ) {\n\t\t\t\t\tself._debug(5,\"Telling \"+(somebody.name||somebody.id)+\" that now I am not anymore connection for \"+memberNames[x]);\n\t\t\t\t\tdelete somebody.toldHimAbout[memberNames[x]];\n\t\t\t\t\twho.push(memberNames[x]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ( who.length > 0 )\n\t\t\tself.__send(somebody,{c:\"im!con4\",who:who});\n\t});\n\n\t// Tell\n\treturn Object.keys(tellTo,function(who){\n\t\tself._debug(9,\"!!!LOST!!!\",tellTo[who]);\n\t\tself._send(who,{c:\"lost\",who:tellTo[who]});\n\t});\n\n}",
"function KickUser(ws, currentLobbyId, newLobbyId, customMessage) {\n // TODO: distinguish between being kicked and disconnecting, the current disconnect gives a kicked from lobby message\n if (currentLobbyId === nullLobbyId) {\n return;\n }\n\n // remove user from server list //\n var index = lobbies[currentLobbyId][\"users\"].indexOf(ws);\n if (index > -1) {\n lobbies[currentLobbyId][\"users\"].splice(index, 1);\n ws.lobbyId = nullLobbyId;\n } else {\n return; // user is not in lobby\n }\n\n // tell user they've been kicked //\n ws.lobbyId = newLobbyId;\n if (ws.connected) {\n var returnMessage = {\n \"type\": \"kicked-from-lobby\",\n \"data\": {\n \"new-lobby\": newLobbyId,\n \"reason\": customMessage\n }\n };\n ws.send(JSON.stringify(returnMessage));\n }\n\n // tell all users in the lobby that the user left //\n SendUserLeft(ws, currentLobbyId);\n\n // tell server viewers the user left the lobby //\n ServerViewerBroadcastUserUpdate(ws);\n\n // delete lobby if everyone left //\n if (lobbies[currentLobbyId].users.length === 0) {\n DeleteLobby(currentLobbyId);\n }\n}",
"sendUserlist() {\n this.print('Current Users');\n this.print(JSON.stringify(this.users, null, 2));\n this.namespace.emit('username list', this.getUsernames());\n }",
"function send_current_users (socket) {\n var info = client_info[socket.id];\n var users = [];\n var now_timestamp = moment().local().format('h:mm:ss a');\n\n if (typeof info === 'undefined') {\n return;\n }\n\n Object.keys(client_info).forEach(function (socket_id) {\n var user_info = client_info[socket_id];\n if (info.room === user_info.room) {\n users.push(user_info.name);\n }\n });\n\n socket.emit('message', {\n name: 'System',\n text: 'Current Users: '+ users.join(', '),\n timestamp: now_timestamp\n });\n}",
"hasRemainingUsers() {\n return this.remainingUsers !== 0\n }",
"async function notify_unverified_users(){\n var notifications = 0;\n if(configured){\n log(\"Beginning: Notifiying Unverified Users\");\n guild.members.fetch().then((members)=>{\n members.forEach((guildMember)=>{\n if(!guildMember.roles.cache.find( role => role.id === server.roles.Verified)){\n send_user_auth_url(guildMember);\n notifications++;\n }\n });\n log(notifications + \" users notified!\");\n log(\"Ending: Notifiying Unverified Users\");\n })\n \n }else{\n log(\"Can't send verification stuff, configuration not set!\");\n }\n}",
"function leftSession(\n/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/\n /**\n * No arguments. */\n)\n/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/\n{\n console.log(2, \"User has successfully left the session.\");\n $('#participant-list').empty();\n $('#participant-list').append('<p>[None Yet]</p>');\n\n $(\"#leave_button\").attr('disabled', 'disabled');\n $('#join_button').removeAttr('disabled');\n $('#rooms select').removeAttr('disabled');\n\n $('#send_chat').attr('disabled', 'disabled');\n $('#chat_text').attr('disabled', 'disabled');\n\n $('#send_link').attr('disabled', 'disabled');\n $('#link_text').attr('disabled', 'disabled');\n \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
array of census tract modal splits, usually returned using readonlyStore.findByIds(). Each modal split is displayed as a row. | @computed('acsModalSplits', 'ctppModalSplits', 'isRJTW')
get selectedCensusTractData() {
if (this.isRJTW) {
return this.ctppModalSplits;
}
return this.acsModalSplits;
} | [
"splitRows() {\n let rows = [];\n const shields = this.state.shields;\n\n for(var i = 0; i < shields.length; i+=6) {\n let oneRow = [];\n oneRow.push(shields.slice(i, i+6).map( (shield, idx) => {\n return (\n <div className=\"two columns\" key={i + idx} >\n <Shield\n shieldColor={shield.value.shieldColor}\n partition={shield.value.partition}\n partitionColor={shield.value.partitionColor}\n piece={shield.value.piece}\n pieceColor={shield.value.pieceColor}\n meubles={shield.value.meubles}\n />\n </div> )\n }));\n rows.push(oneRow.map(itm => {\n return <div className=\"row\" key={'r'+i}>{itm}</div>\n }))\n }\n return rows;\n }",
"function iterSplitters(root, cb) {\n var result = cb(root);\n if (result !== void 0) {\n return result;\n }\n for (var i = 0, n = root.count; i < n; ++i) {\n var widget = root.widgetAt(i);\n if (widget instanceof DockSplitter) {\n result = iterSplitters(widget, cb);\n if (result !== void 0) {\n return result;\n }\n }\n }\n }",
"generateRows() {\n let rowsArray = this.props.equivalencySlice.map( (row, index) => {\n return (\n <RequirementRow key={2 * index}\n lookupTable={this.props.lookupTable}\n equivalencyRow={this.props.equivalencySlice[index]}\n isComplete={this.props.isComplete.row(row)} \n handleToggle={this.props.handleToggle.bind(this)} />\n )\n })\n\n let len = rowsArray.length\n for (let i = 1; i < len; i++) {\n let operator = this.props.equivalencySlice[i - 1][0].relationToNext\n \n rowsArray.splice(i, 0, \n <div key={i} className=\"level\">\n <span className=\"level-item operator_box\"> {operator} </span>\n </div>\n )\n }\n return rowsArray\n }",
"function WalletsGrid({ wallets, columns }) {\n const getRow = (_wallets, row) => (\n <div className={styles.walletRow} key={`wallet-row-${row}`}>\n {_wallets.map((wallet) => (\n <WalletTile {...wallet} key={wallet.id} />\n ))}\n </div>\n );\n\n const rows = Math.ceil(wallets.length / columns);\n const components = [];\n for (let i = 0; i < rows; i += 1) {\n const rowWallets = wallets.slice(i * columns, i * columns + columns);\n components.push(getRow(rowWallets, i));\n }\n return <div className={styles.walletGrid}>{components}</div>;\n}",
"_makeRow(rowCtrlNames) {\n\t\tconst row = [];\n\t\tfor (let y = 0; y < rowCtrlNames.length; y++) {\n\t\t\tconst control = this._getSubControlDef(rowCtrlNames[y]);\n\t\t\tif (control && control.visible) {\n\t\t\t\tconst childPropertyId = {\n\t\t\t\t\tname: this.props.control.name,\n\t\t\t\t\tcol: this._getColumnIndex(rowCtrlNames[y])\n\t\t\t\t};\n\t\t\t\tconst parentPropertyId = cloneDeep(this.props.propertyId);\n\n\t\t\t\tlet propertyId = childPropertyId;\n\t\t\t\tif (parentPropertyId.name !== childPropertyId.name) {\n\t\t\t\t\tpropertyId = this.props.controller.setChildPropertyId(parentPropertyId, childPropertyId);\n\t\t\t\t}\n\t\t\t\trow.push(this.controlFactory.createControlItem(control, propertyId));\n\t\t\t}\n\t\t}\n\t\treturn row;\n\t}",
"showGroupingsModal() {\n MyModal = new ModalClass();\n const idName = MyModal.prepareModal(null, '800px', 'pcm-groupingsModal', 'modal-lg', 'List Groupings', '', '', '', 'invisible', 'No', null, 'invisible', 'No', null, 'invisible', 'Close');\n let divContainer = $(`<table class='table table-dark table-sm pcm-detailsTable table-bordered'></table>`).append($(`<tbody></tbody>`)).appendTo(`#${idName} .${MyModal.classModalBody}`);\n MyModal.showModal(null, async () => {\n $(`#${idName} .${MyModal.classModalBody}`).addClass('pcm-groupingModalBody')\n let df = document.createDocumentFragment(), isPanda = (this.type === 'panda'), gType = (isPanda) ? 'pandas' : 'triggers';\n for (const grouping of Object.keys(this.groups)) {\n await this.goCheckGroup(grouping, true);\n const bgClass = (this.groupStatus[grouping].collecting) ? 'pcm-groupCollect' : ((Object.keys(this.groups[grouping][gType]).length === 0) ? 'pcm-groupEmpty' : '');\n displayObjectData([\n {'string':'Grouping Name and Description', 'type':'keyValue', 'key':'name', 'id':`pcm-nameDesc-${grouping}`, 'andKey':'description', 'andString':`<span class='small'>${Object.keys(this.groups[grouping][gType]).length} ${(isPanda) ? 'Job(s)' : 'Trigger(s)'}</span>`, 'unique':grouping, 'tooltip':`Grouping Name with description and the number of ${(isPanda) ? 'Job(s)' : 'Trigger(s)'} it contains.`, 'addTdClass':'pcm-groupingNameDesc'},\n {'btnLabel':'Edit', 'type':'button', 'addClass':' btn-xxs pcm-groupingEdit pcm-myPrimary', 'idStart':'pcm-editButton1', 'width':'45px', 'unique':grouping, 'btnFunc': () => {\n this.showgroupingEditModal(grouping,_,_, () => {});\n }, 'tooltip':`Edit this grouping by selecting or deselecting ${(isPanda) ? 'Job(s)' : 'Trigger(s)'}.`},\n {'btnLabel':'Del', 'type':'button', 'addClass':' btn-xxs pcm-groupingDelete pcm-myPrimary', 'idStart':'pcm-deleteButton1', 'width':'45px', 'unique':grouping, 'btnFunc': (e) => {\n this.delete(grouping);\n $(e.target).closest('tr').remove();\n }, 'tooltip':'Delete this grouping right away.'},\n ], df, this.groups[grouping], true, true, true, `pcm-groupingItem ${bgClass}`);\n };\n divContainer.append(df);\n $('.pcm-groupingNameDesc').dblclick( e => { let unique = $(e.target).data('unique'); if (unique) this.toggle(unique); } );\n df = null; divContainer = null;\n }, () => { MyModal = null; });\n }",
"function splitObjectIntoGrid() {\n\n for (let j = 0; j < obj.numRows; j++) {\n for (let i = 0; i < obj.numCols; i++) {\n\n let moleculeCollection = molecules.filter(molecule =>\n molecule.position.x > (i * colWidth) &&\n molecule.position.x < ((i + 1) * colWidth) &&\n molecule.position.y > j * rowHeight &&\n molecule.position.y < (j + 1) * rowHeight\n ).map(molecule => molecule.index);\n\n checkIntersections(moleculeCollection);\n }\n }\n}",
"split() {\n\n\t\tconst min = this.min;\n\t\tconst mid = this.getCenter(c);\n\t\tconst halfSize = this.size * 0.5;\n\n\t\tconst children = this.children = [\n\n\t\t\tnull, null,\n\t\t\tnull, null,\n\t\t\tnull, null,\n\t\t\tnull, null\n\n\t\t];\n\n\t\tlet i, combination;\n\n\t\tfor(i = 0; i < 8; ++i) {\n\n\t\t\tcombination = pattern[i];\n\n\t\t\tchildren[i] = new this.constructor(\n\n\t\t\t\tnew Vector3(\n\t\t\t\t\t(combination[0] === 0) ? min.x : mid.x,\n\t\t\t\t\t(combination[1] === 0) ? min.y : mid.y,\n\t\t\t\t\t(combination[2] === 0) ? min.z : mid.z\n\t\t\t\t),\n\n\t\t\t\thalfSize\n\n\t\t\t);\n\n\t\t}\n\n\t}",
"listLaunchInfo(launchData) {\n return launchData.map((launch, index) => {\n return (\n <tr key={index} onClick={this.handleClick.bind(launch)} data-testid=\"launch-row\">\n <td test-dataid=\"flight-number\">{launch.flight_number}</td>\n <td test-dataid=\"flight-year\">{launch.date_local.slice(0,4)}</td>\n <td test-dataid=\"launch-name\">{launch.name}</td>\n <td test-dataid=\"launch-details\">{launch.details}</td>\n </tr>\n )\n })\n }",
"function getCards(){\r\n mosaic.innerHTML = ''\r\n fetch(SURVEY_URL)\r\n .then(resp => resp.json())\r\n .then(surveys => {\r\n const surveysArray = surveys['data']\r\n for (const survey of surveysArray) {\r\n mosaic.innerHTML += `\r\n <div class=\"card\" id=\"${survey.id}\">\r\n <div class=\"card-body\">\r\n <h5 class=\"card-title\">${survey['attributes']['name']}</h5>\r\n <p class=\"card-text survey_description\">${survey['attributes']['description']}</p>\r\n <button type=\"button\" class=\"btn btn-success\" data-toggle=\"modal\" data-target=\"#takeSurvey\" onclick=\"Survey.populate(${survey.id})\"> Take Survey </button>\r\n <button type=\"button\" class=\"btn btn-info\" data-toggle=\"modal\" data-target=\"#surveyResults\" onclick=\"Survey.results(${survey.id})\"> See Results </button>\r\n <br /><br />\r\n <button type=\"button\" class=\"btn btn-primary\" onclick=\"Survey.deleteSurvey(${survey.id})\"> Delete Survey </button>\r\n\r\n </div>\r\n </div>\r\n `\r\n }\r\n })\r\n}",
"getBettingSplitsByBettingMarketIdPromise(marketId){\n var parameters = {};\n parameters['marketId']=marketId;\n return this.GetPromise('/v3/nhl/odds/{format}/BettingSplitsByMarketId/{marketId}', parameters);\n }",
"function getIds() {\n\tlet ids = []\n\tlet mdls = document.getElementsByClassName('modal')\n\tlet idPrefix = \"product-modal \"\n\tfor (i = 0; i < mdls.length; i++) {\n\t\tlet id = mdls[i].id\n\t\tid = id.slice(idPrefix.length, id.length)\n\t\tids.push(id)\n\t}\n\treturn ids\n}",
"function showActiveCoinsInModalWindow() {\n $(\"#activeModalCoins\").empty();\n for (item of state.activeCoins) {\n createDivCoinMain(item, $(\"#activeModalCoins\"));\n }\n }",
"function addAdditionalSplit()\r\n{\r\n // initialize splitButton\r\n splitButton = null\r\n \r\n // get all link elements in split input table\r\n possibleButtons = splitTable.getElementsByTagName('a')\r\n\r\n // use the last split button as the used split button\r\n for (let possibleButton of possibleButtons) {\r\n if (possibleButton.name === 'split') {\r\n splitButton = possibleButton\r\n }\r\n }\r\n \r\n // click the split button\r\n splitButton.click()\r\n \r\n}",
"getBettingSplitsByGameIDPromise(gameId){\n var parameters = {};\n parameters['gameId']=gameId;\n return this.GetPromise('/v3/nhl/odds/{format}/BettingSplitsByGameId/{gameId}', parameters);\n }",
"function displayOwnedSecurities() {\n // $(this).closest(\".info-box\")\n // data-id=\"...\"\n querySecurities()\n .then(function(data) {\n data.forEach(function(sec) {\n $('#securities-container').append(\n `<div class=\"info-box\">\n <div class=\"ticker\"><h4>${sec.symbol}</h4></div>\n <div class=\"ticker-name\"><h4>${sec.name}</h4></div>\n <div class=\"shares-owned\"><h4>Total Shares: ${sec.numShares}</h4></div>\n <p class=\"share-price\">Share Price: $${sec.currentPrice}</p>\n <div class=\"shares-owned-value\"><h4>Total Value: $${Math.round(sec.currentPrice * sec.numShares * 100) / 100}</h4></div>\n <p> \n <button type=\"button\" class=\"btn btn-primary btn-lg\" data-toggle=\"modal\" data-target=\"#sellModal\" data-whatever=\"sell\">\n Sell\n </button>\n <button type=\"button\" class=\"btn btn-success btn-lg\" data-toggle=\"modal\" data-target=\"#buyModal\" data-whatever=\"buy\">\n Buy\n </button>\n </p>\n </div>\n <div class=\"modal fade\" id=\"sellModal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"myModalLabel\">\n <div class=\"modal-dialog\" role=\"document\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">×</span></button>\n <h4 class=\"modal-title\" id=\"myModalLabel\">Place Trade</h4>\n </div>\n <div class=\"modal-body\">\n <h4>${sec.symbol}</h4>\n <p class=\"share-price\">Share Price: $${sec.currentPrice}</p>\n <p class=\"owned-shares\">Number of Shares: ${sec.numShares}</p>\n <p class=\"owned-share-value\">Total value: $${Math.round(sec.currentPrice * sec.numShares * 100) / 100}</p>\n <p id=\"to-sell-input\">\n Shares to sell:\n <input required type=\"text\" pattern=\"\\d*\" class=\"accountvalue\" placeholder=\"e.g. 10\">\n </p>\n <label>\n <input id=\"sell-checkbox\" type=\"checkbox\"> Sell all\n </label>\n <p class=\"total-sell-amt\">Total: </p>\n </div>\n <div class=\"modal-footer\">\n <button type=\"button\" class=\"btn btn-primary\" data-dismiss=\"modal\">Submit</button>\n <button type=\"button\" class=\"btn btn-danger\" data-dismiss=\"modal\">Cancel</button>\n </div>\n </div>\n </div>\n </div>\n\n <div class=\"modal fade\" id=\"buyModal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"myModalLabel\" data-symbol=${sec.symbol} data-numshares=${sec.numShares} data-currentprice=${sec.currentPrice} >\n <div class=\"modal-dialog\" role=\"document\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">×</span></button>\n <h4 class=\"modal-title\" id=\"myModalLabel\">Place Trade</h4>\n </div>\n <div class=\"modal-body\">\n <h4>${sec.symbol}</h4>\n <p class=\"share-price\">Share Price: $${sec.currentPrice}</p>\n <p class=\"owned-shares\">Number of Shares: ${sec.numShares}</p>\n <p class=\"owned-share-value\">Total value: $${Math.round(sec.currentPrice * sec.numShares * 100) / 100}</p>\n <p id=\"to-buy-input\">\n Shares to buy:\n <input required type=\"text\" pattern=\"\\d*\" class=\"accountvalue\" placeholder=\"e.g. 10\">\n </p>\n <label>\n <input id=\"buy-checkbox\" type=\"checkbox\"> Buy max\n </label>\n <p class=\"total-sell-amt\">Total: </p>\n <!--<p class=\"account-balance\">Account total: </p>-->\n </div>\n <div class=\"modal-footer\">\n <button type=\"button\" id=\"buy-shares\" class=\"btn btn-primary\" data-dismiss=\"modal\">Submit</button>\n <button type=\"button\" id=\"cancel\" class=\"btn btn-danger\" data-dismiss=\"modal\">Cancel</button>\n </div>\n </div>\n </div>\n </div>`\n );\n });\n\n $('#buy-shares').click(function(event) {\n const container = $(this).closest('.modal');\n const sec = container[0].dataset;\n const requestedShares = $(this).closest('#buyModal').find('input.accountvalue').val();\n updatePurchasedSecurities(portfolio.link, sec.symbol, sec.currentprice, requestedShares);\n });\n \n\n $('#buy-checkbox').change(function() {\n if ($(this).is(':checked')) {\n const accountVal = unFormatMoney($('body').find('#portfolio-value').text());\n const sharePrice = unFormatMoney($(this).parent().siblings('.share-price').text().split(' ')[2]);\n $(this)\n .parent()\n .siblings('#to-buy-input')\n .children('input.accountvalue')\n .val(Math.floor(accountVal / sharePrice));\n } \n });\n \n $('#sell-checkbox').change(function() {\n if ($(this).is(':checked')) {\n const ownedShares = unFormatMoney($(this).parent().siblings('.owned-shares').text());\n $(this)\n .parent()\n .siblings('#to-sell-input')\n .children('input.accountvalue')\n .val(ownedShares);\n } \n });\n\n });\n}",
"getParkings (parkings) {\n let html = '<div class=\"row parkings\">';\n let index = 0;\n parkings.map ( (parking) => {\n index ++;\n html += `<div class=\"column-1-${index} custom-column\">${parking.price}<br>${this.isIndoor(parking.indoor)}<br>${this.isInsurance(parking.insurance)}</div>`;\n });\n\n html += '</div>';\n\n return html;\n }",
"function splitDataByCity(data) {\n printToConsole(\"Splitting data to cities\\n\");\n var blackMarket = [];\n var fortSterling = [];\n var thetford = [];\n var lymhurst = [];\n var bridgewatch = [];\n var martlock = [];\n var caerleon = [];\n\n for (var i = 0; i < data.length; i++) {\n switch (data[i].city) {\n case \"Black Market\":\n blackMarket.push(data[i]);\n break;\n case \"Fort Sterling\":\n fortSterling.push(data[i]);\n break;\n case \"Thetford\":\n thetford.push(data[i]);\n break;\n case \"Lymhurst\":\n lymhurst.push(data[i]);\n break;\n case \"Bridgewatch\":\n bridgewatch.push(data[i]);\n break;\n case \"Martlock\":\n martlock.push(data[i]);\n break;\n case \"Caerleon\":\n caerleon.push(data[i]);\n break;\n }\n }\n\n return [blackMarket, fortSterling, thetford, lymhurst, bridgewatch, martlock, caerleon];\n}",
"function colunaComoLinha(coluna) {\n var elems = [];\n for (var i = 0; i < 3; i++) {\n elems.push(getTab()[i][coluna]);\n }\n return elems;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draws a team Banner | function drawTeamBanner (x, y, width, height, teamName) {
return svg.append("svg:image")
.attr("xlink:href", "../Resources/banners/banner_" + teamName + ".png")
.attr("x", x)
.attr("y", y)
.attr("width", width)
.attr("height", height);
} | [
"drawLobbyView() {\n this.drawState();\n\n this.ctx.font = '20px Arial';\n this.ctx.fillStyle = '#FFF';\n this.ctx.textAlign = 'center';\n this.ctx.fillText('Waiting on another player...', this.canvas.width / 2,\n this.canvas.height / 2 - 60);\n this.ctx.fillStyle = '#000';\n }",
"function C101_KinbakuClub_RopeGroup_Run() {\n\tBuildInteraction(C101_KinbakuClub_RopeGroup_CurrentStage);\n\t\n\t// changing images\n\t// Group view\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 100) {\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupAmelia.png\", 600, 20);\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupCharlotte.jpg\", 818, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinLeftStart.png\", 985, 98);\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"Released\" || C101_KinbakuClub_RopeGroup_RightTwinStatus == \"Released\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinFree.png\", 1005, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_RightTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinRightStart.png\", 847, 110);\n\t}\n\n\t// Twins image after releasing one of them\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 430) {\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwin == \"Lucy\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/LeftTwin.jpg\", 600, 0);\n\t\telse DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RightTwin.jpg\", 600, 0);\n\t}\n\tif ((C101_KinbakuClub_RopeGroup_CurrentStage >= 600 && C101_KinbakuClub_RopeGroup_CurrentStage <= 631) || (C101_KinbakuClub_RopeGroup_CurrentStage >= 700 && C101_KinbakuClub_RopeGroup_CurrentStage <= 710) || C101_KinbakuClub_RopeGroup_CurrentStage == 900) {\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinLeftStillTied.png\", 600, 167);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage <= 700) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinJustReleased.png\", 750, 5);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 710) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinReleased.png\", 750, 5);\n\t\tif (C101_KinbakuClub_RopeGroup_RightTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinRightStillTied.png\", 930, 230);\n\t}\n\n\t// During Tsuri Kinbaku (Suspension)\n\t// Suspended1\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 633) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended1BallGag.jpg\", 878, 94);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended1ClothGag.jpg\", 878, 94);\n\t}\n\t// Suspended2\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 634) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended2BallGag.jpg\", 904, 105);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended2ClothGag.jpg\", 904, 105);\n\t}\n\t// Suspended3\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 635) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended3BallGag.jpg\", 890, 105);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended3ClothGag.jpg\", 890, 105);\n\t}\n\t// Suspended4\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 636 && C101_KinbakuClub_RopeGroup_CurrentStage <= 660) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4BallGag.jpg\", 863, 125);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4ClothGag.jpg\", 863, 125);\n\t}\n\t// Suspended5\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 661 && C101_KinbakuClub_RopeGroup_CurrentStage <= 662) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5BallGag.jpg\", 865, 126);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5ClothGag.jpg\", 865, 126);\n\t\tif (PlayerHasLockedInventory(\"TapeGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5TapeGag.jpg\", 865, 126);\n\t}\n\n\t//Suspended\n\tif ((C101_KinbakuClub_RopeGroup_CurrentStage >= 636 && C101_KinbakuClub_RopeGroup_CurrentStage <= 642) || (C101_KinbakuClub_RopeGroup_CurrentStage >= 650 && C101_KinbakuClub_RopeGroup_CurrentStage <= 690)) {\n\t\t// Player images\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 672 && C101_KinbakuClub_RopeGroup_PlayerPose != \"\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/\" + C101_KinbakuClub_RopeGroup_PlayerPose + \".jpg\", 835, 75);\n\t\tif (PlayerHasLockedInventory(\"ChastityBelt\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4ChastityBelt.jpg\", 880, 290);\n\t\tif (C101_KinbakuClub_RopeGroup_TsuriFrogTied) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5FrogTie.png\", 769, 231);\n\t\tif (C101_KinbakuClub_RopeGroup_FullyExposed) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5Pantieless.jpg\", 880, 294);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 662) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5LookUp.png\", 864, 136);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 671 && PlayerHasLockedInventory(\"SockGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended8S.jpg\", 888, 157);\n\t\t\n\t\t// Cassi iamges\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 662) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5Cassi1.png\", 948, 65);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 666) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_InspectBelt.jpg\", 842, 72);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 667) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_InspectKey.jpg\", 842, 72);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 668) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_RemovingBelt.jpg\", 842, 72);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 672) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_LeftHoldingTape.jpg\", 608, 70);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 673) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_Scissors.png\", 700, 77);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 674) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_KneelDown.png\", 660, 120);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 674 && ActorGetValue(ActorSubmission) >= 0) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_KneelDownCuffs.png\", 776, 403);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 675 && C101_KinbakuClub_RopeGroup_CurrentStage <= 686){\n\t\t\tif (C101_KinbakuClub_RopeGroup_PressingCassi) {\n\t\t\t\tif (ActorHasInventory(\"Cuffs\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniCuffedPressed.png\", 770, 230);\n\t\t\t\telse {\n\t\t\t\t\tif (C101_KinbakuClub_RopeGroup_fingerinsertion) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniFingerPressed.png\", 770, 230);\n\t\t\t\t\telse DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniPressed.png\", 770, 230);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (C101_KinbakuClub_RopeGroup_ForcingCassi) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniCuffedStruggle.png\", 770, 230);\n\t\t\t\telse {\n\t\t\t\t\tif (C101_KinbakuClub_RopeGroup_AnkleGrab) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniAnkleHold.png\", 770, 230);\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (ActorHasInventory(\"Cuffs\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniCuffed.png\", 825, 251);\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif (C101_KinbakuClub_RopeGroup_fingerinsertion) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_CunniFinger.png\", 825, 251);\n\t\t\t\t\t\t\telse DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_Cunni.png\", 825, 251);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 687) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_Done.png\", 835, 73);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 687 && ActorHasInventory(\"Cuffs\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_DoneCuffs.png\", 874, 193);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 688 && C101_KinbakuClub_RopeGroup_CurrentStage <= 689) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_DoneBelt.png\", 835, 63);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 690) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/SusCas_DoneBelted.png\", 835, 66);\n\t\t\n\n\t\t// Lucy images\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 662 && C101_KinbakuClub_RopeGroup_CurrentStage <= 665) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended5Lucy.png\", 629, 51);\n\t\t\n\t\t// Player arousal\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 675 && C101_KinbakuClub_RopeGroup_CurrentStage <= 680) {\n\t\t\tif (C101_KinbakuClub_RopeGroup_PreviousTime == 0) C101_KinbakuClub_RopeGroup_PreviousTime = CurrentTime;\n\t\t\tif (CurrentTime > (C101_KinbakuClub_RopeGroup_PreviousTime + 1000)) {\n\t\t\t\tC101_KinbakuClub_RopeGroup_PreviousTime = CurrentTime;\n\t\t\t\tC101_KinbakuClub_RopeGroup_PlayerArousal++;\n\t\t\t\tif (ActorGetValue(ActorSubmission) < 0) C101_KinbakuClub_RopeGroup_PlayerArousal++;\n\t\t\t\tif (PlayerHasLockedInventory(\"VibratingEgg\")) C101_KinbakuClub_RopeGroup_PlayerArousal++;\n\t\t\t}\n\t\t\tif (C101_KinbakuClub_RopeGroup_PlayerArousal > 500) {\n\t\t\t\tC101_KinbakuClub_RopeGroup_PlayerArousal = 500;\n\t\t\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 681\n\t\t\t\tOverridenIntroText = GetText(\"SuspendedOrgasm\");\n\t\t\t}\n\t\t}\n\t\t// Draw the players arousal level\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 675 && C101_KinbakuClub_RopeGroup_CurrentStage <= 681) {\n\t\t\tDrawRect(638, 48, 14, 504, \"white\");\n\t\t\tDrawRect(640, 50, 10, (500 - C101_KinbakuClub_RopeGroup_PlayerArousal), \"#66FF66\");\n\t\t\tDrawRect(640, (550 - C101_KinbakuClub_RopeGroup_PlayerArousal), 10, C101_KinbakuClub_RopeGroup_PlayerArousal, \"red\");\n\t\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 300) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Gushing.png\", 601, 2);\n\t\t}\n\t}\n\t\n\t// Images when Hether uses nipple clamps\n\tif ((C101_KinbakuClub_RopeGroup_CurrentStage >= 800 && C101_KinbakuClub_RopeGroup_CurrentStage <= 841) || C101_KinbakuClub_RopeGroup_CurrentStage == 850) {\n\t\tif (C101_KinbakuClub_RopeGroup_NipplesExposed) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherExposed.jpg\", 600, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_NippleClamped) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherNippleClamped.jpg\", 600, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_HeatherTugging) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherNippleTug.jpg\", 600, 0);\n\t\tif (!C101_KinbakuClub_RopeGroup_Expression == \"\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/\" + C101_KinbakuClub_RopeGroup_Expression + \".jpg\", 1040, 280);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 830) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/HeatherGone.jpg\", 600, 392);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 841) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/JennaIntervene.jpg\", 600, 0);\n\t}\n\n\t// Images during plug play\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 854 && C101_KinbakuClub_RopeGroup_Clentched) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/PluggingClentch.jpg\", 617, 354);\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 855) {\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Plugged.jpg\", 900, 110);\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Plugged\" + C101_KinbakuClub_RopeGroup_PlugMood + \".jpg\", 617, 354);\n\t}\n}",
"function C101_KinbakuClub_RopeGroup_Run() {\n\tBuildInteraction(C101_KinbakuClub_RopeGroup_CurrentStage);\n\t\n\t// changing images\n\t// Group view\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 100) {\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupAmelia.png\", 600, 20);\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupCharlotte.jpg\", 818, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinLeftStart.png\", 985, 98);\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"Released\" || C101_KinbakuClub_RopeGroup_RightTwinStatus == \"Released\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinFree.png\", 1005, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_RightTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RopeGroupTwinRightStart.png\", 847, 110);\n\t}\n\n\t// Twins image after releasing one of them\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 430) {\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwin == \"Lucy\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/LeftTwin.jpg\", 600, 0);\n\t\telse DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/RightTwin.jpg\", 600, 0);\n\t}\n\tif ((C101_KinbakuClub_RopeGroup_CurrentStage >= 600 && C101_KinbakuClub_RopeGroup_CurrentStage <= 631) || (C101_KinbakuClub_RopeGroup_CurrentStage >= 700 && C101_KinbakuClub_RopeGroup_CurrentStage <= 710) || C101_KinbakuClub_RopeGroup_CurrentStage == 900) {\n\t\tif (C101_KinbakuClub_RopeGroup_LeftTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinLeftStillTied.png\", 600, 167);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage <= 700) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinJustReleased.png\", 750, 5);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage >= 710) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinReleased.png\", 750, 5);\n\t\tif (C101_KinbakuClub_RopeGroup_RightTwinStatus == \"StartTied\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/TwinRightStillTied.png\", 930, 230);\n\t}\n\n\t// Images during Tsuri Kinbaku (Suspension)\n\t// Suspended1\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 633) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended1BallGag.jpg\", 878, 94);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended1ClothGag.jpg\", 878, 94);\n\t}\n\t// Suspended2\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 634) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended2BallGag.jpg\", 904, 105);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended2ClothGag.jpg\", 904, 105);\n\t}\n\t// Suspended3\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 635) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended3BallGag.jpg\", 890, 105);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended3ClothGag.jpg\", 890, 105);\n\t}\n\t// Suspended4\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 636) {\n\t\tif (PlayerHasLockedInventory(\"BallGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4BallGag.jpg\", 863, 125);\n\t\tif (PlayerHasLockedInventory(\"ClothGag\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4ClothGag.jpg\", 863, 125);\n\t\tif (PlayerHasLockedInventory(\"ChastityBelt\")) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Suspended4ChastityBelt.jpg\", 880, 290);\n\t}\n\t\n\t// Images when Hether uses nipple clamps\n\tif ((C101_KinbakuClub_RopeGroup_CurrentStage >= 800 && C101_KinbakuClub_RopeGroup_CurrentStage <= 841) || C101_KinbakuClub_RopeGroup_CurrentStage == 850) {\n\t\tif (C101_KinbakuClub_RopeGroup_NipplesExposed) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherExposed.jpg\", 600, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_NippleClamped) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherNippleClamped.jpg\", 600, 0);\n\t\tif (C101_KinbakuClub_RopeGroup_HeatherTugging) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/WithHeatherNippleTug.jpg\", 600, 0);\n\t\tif (!C101_KinbakuClub_RopeGroup_Expression == \"\") DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/\" + C101_KinbakuClub_RopeGroup_Expression + \".jpg\", 1040, 280);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 830) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/HeatherGone.jpg\", 600, 392);\n\t\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 841) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/JennaIntervene.jpg\", 600, 0);\n\t}\n\n\t// Images during plug play\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 854 && C101_KinbakuClub_RopeGroup_Clentched) DrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/PluggingClentch.jpg\", 617, 354);\n\tif (C101_KinbakuClub_RopeGroup_CurrentStage == 855) {\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Plugged.jpg\", 900, 110);\n\t\tDrawImage(CurrentChapter + \"/\" + CurrentScreen + \"/Plugged\" + C101_KinbakuClub_RopeGroup_PlugMood + \".jpg\", 617, 354);\n\t}\n}",
"function drawCenterOrb (r, fill, stroke, strokeWidth, teamTitle, strokeOpacity){\n\t\tvar role = paper.circle(centerX, centerY, r).animate({fill: fill, stroke: stroke, \"stroke-width\": strokeWidth, \"stroke-opacity\": strokeOpacity}, 1000);\n\t\t// add text to orb\n\t\tvar tt = paper.text(centerX, centerY, teamTitle);\n\t\ttt.attr({ \"font-size\": (baseSize * 2.2), \"font-family\": \"BebasNeue, Arial, Helvetica, sans-serif\", \"fill\" : \"#24201f\", \"width\" : (baseSize * 3) });\n\t}",
"function displayBall() {\n rect(ball.x, ball.y, ball.size, ball.size);\n}",
"function drawBanner (year) {\n\treturn drawAnImage(arrowSize, svgHeight - arrowSize-barPadding, svgWidth-arrowSize*2, arrowSize, \"../Resources/banners/banner_\"+year+\".png\" );\n}",
"function createMatchSpoilers(LRtext, currentMatch) {\n\tvar team1 = getTeam(\"team1\", currentMatch);\n\tvar team2 = getTeam(\"team2\", currentMatch);\n\n\t$(LRtext).append(\"[i]\");\n\t$(LRtext).append(team1 + \" vs \" + team2);\n\t$(LRtext).append(\"[/i]\\n\");\n\t$(LRtext).append(\"[spoiler][/spoiler]\\n\\n\");\n}",
"setPlayerTeam(player, zone, team = undefined) {\n const location = DeathMatchLocation.getById(zone);\n if (!location.hasTeams)\n return;\n\n if (!this.teamScore_.has(zone))\n this.teamScore_.set(zone, new DeathMatchTeamScore());\n\n if (!this.zoneTextDraws_.has(zone)) {\n this.zoneTextDraws_.set(zone, -1);\n const textDraw = new TextDraw({\n position: [482, 311],\n text: '_',\n\n color: Color.fromNumberRGBA(-1),\n shadowColor: Color.fromRGBA(0, 0, 0, 255),\n font: 2,\n letterSize: [0.33, 1.5],\n outlineSize: 1,\n proportional: true,\n });\n\n\n this.zoneTextDraws_.set(zone, textDraw);\n textDraw.displayForPlayer(player);\n } else {\n const textDraw = this.zoneTextDraws_.get(zone);\n textDraw.displayForPlayer(player);\n }\n\n this.updateTextDraw(zone);\n\n if (!isNaN(team) && team < 2) {\n this.playerTeam_.set(player, { zone: zone, team: team });\n return;\n }\n\n const teams = [...this.playerTeam_]\n .filter(item => item[1].zone === zone)\n .map(item => item[1].team);\n\n const amountOfRedTeam = teams.filter(item => item === RED_TEAM).length;\n const amountOfBlueTeam = teams.filter(item => item === BLUE_TEAM).length;\n\n const newTeam = amountOfRedTeam <= amountOfBlueTeam ? RED_TEAM : BLUE_TEAM;\n\n this.playerTeam_.set(player, { zone: zone, team: newTeam });\n }",
"function drawArcade(x, y)\n{\n\t\tif(back1){\n \t\t\t\tpush();\n \t\t\t\ttranslate(arcadeVX, 0)\n \t\t\t\tscale(arcadeSC)\n\n \t\t\t\t\t\tvar arcadeX = 0\n\n \t\t\t\tfill(255, 165, 0)\n \t\t\t\trect(arcadeX, 0, 500, 500)\n\n \tfor (i = 0; i < 5; i++)\n \t\t{\n \tfill(0); //body\n rect(arcadeX, 100, 100, 300)\n\t\t\t\t\t\t\n fill(255); //header\n rect(arcadeX + 10, 110, 80, 30)\n fill(250, 128, 114)\n rect(arcadeX + 15, 115, 70, 20, 5)\n\n fill(random(100, 150)); //screen\n rect(arcadeX + 10, 170, 80, 80)\n\n fill(128); //remote\n rect(arcadeX + 18, 230, 2, 20)\n fill(128, 0, 0)\n ellipse(arcadeX + 20, 235, 10)\n rect(arcadeX + 40, 248, 10, 2)\n rect(arcadeX + 55, 248, 10, 2)\n rect(arcadeX + 70, 248, 10, 2)\n\n fill(0, 0, 205); //body detail\n rect(arcadeX + 10, 280, 80, 100)\n fill(255); //balls\n ellipse(arcadeX + 30, 320, 10)\n ellipse(arcadeX + 50, 320, 10)\n ellipse(arcadeX + 70, 320, 10)\n\n fill(255, 215, 0) //pacman\n arc(arcadeX + 30, 320, 30, 30, PI/4, 7*PI/4, PIE)\n\n arcadeX+=100\n \t\t}\n pop();\n\t}\n\n}",
"drawPlayhead() {\n // If the playhead should be draw.\n if (this._drawPlayhead) {\n if (this.istimeInView(this._playHeadTime)) {\n this._canvas.fillStyle = COLOR_PLAYHEAD;\n this._canvas.fillRect(this.timeToXCoord(this._playHeadTime), 0, THICKNESS_PLAYHEAD, this._canvasHeight);\n }\n }\n }",
"function render_gamer() {\n render_aim_helper_line();\n\n if(!processing) {\n gamer.planet.x = gamer.x;\n gamer.planet.y = gamer.y;\n }\n\n if(!remove_animation) {\n var crop = get_planet_crop(gamer.planet.type);\n context.drawImage(planets_image.source, crop, 0, map.planet_w, map.planet_h, gamer.planet.x, gamer.planet.y, map.planet_w, map.planet_h);\n }\n }",
"buildTeamBoxes(){\n new TeamBox(this, \"team goes here\", 80, 70).create()\n .setInteractive().on('pointerup', ()=>{\n this.scene.sleep('battle')\n this.scene.launch('switch')\n },this);\n new TeamBox(this, \"enemy team goes here\", 530, 70).create();\n }",
"function draw()\r\n\t{\r\n\t\tvar canvas = document.getElementById('canvas');\r\n\t\tif(canvas.getContext)\r\n\t\t{\r\n\t\t\tvar context = canvas.getContext('2d');\r\n\t\t\t// draw body\r\n\t\t\tif(this.state == playerStates.respawning) context.fillStyle= \"rgba(0,200,0,0.4)\"; // set fillStyle to dark green\r\n\t\t\telse context.fillStyle= \"rgb(0,200,0)\"; // set fillStyle to dark green\r\n\t\t\t\t\r\n\t\t\tcontext.fillRect(this.rect.pos.x,this.rect.pos.y,this.rect.dim.width,this.rect.dim.height);\r\n\t\t\t\r\n\t\t\t// left arm\r\n\t\t\tcontext.fillRect(this.arms.leftArm.pos.x,this.arms.leftArm.pos.y,this.arms.leftArm.dim.width,this.arms.leftArm.dim.height);\r\n\t\t\t// right arm\r\n\t\t\tcontext.fillRect(this.arms.rightArm.pos.x,this.arms.rightArm.pos.y,this.arms.rightArm.dim.width,this.arms.rightArm.dim.height);\r\n\t\t\t// left leg\r\n\t\t\tcontext.fillRect(this.legs.leftLeg.pos.x,this.legs.leftLeg.pos.y,this.legs.leftLeg.dim.width,this.legs.leftLeg.dim.height);\r\n\t\t\t//right leg\r\n\t\t\tcontext.fillRect(this.legs.rightLeg.pos.x,this.legs.rightLeg.pos.y,this.legs.rightLeg.dim.width,this.legs.rightLeg.dim.height);\r\n\t\t\t\r\n\t\t\t// switch to black for eyes\r\n\t\t\tcontext.fillStyle= \"rgb(0,0,0)\"; // set fillStyle to black\r\n\t\t\t// left eye\r\n\t\t\tcontext.fillRect(this.eyes.left.pos.x,this.eyes.left.pos.y,this.eyes.left.dim.width,this.eyes.left.dim.height);\r\n\t\t\t//right eye\r\n\t\t\tcontext.fillRect(this.eyes.right.pos.x,this.eyes.right.pos.y,this.eyes.right.dim.width,this.eyes.right.dim.height);\r\n\t\t\t\r\n\t\t\tif(this.drawJumpZone)\r\n\t\t\t{\r\n\t\t\t\t// draw jumpzone\r\n\t\t\t\tif(this.jumpZone.inZone)\r\n\t\t\t\t\tcontext.strokeStyle= \"rgb(0,255,0)\"; // set fillStyle to green\r\n\t\t\t\telse\r\n\t\t\t\t\tcontext.strokeStyle= \"rgb(255,0,0)\"; // set fillStyle to red\r\n\t\t\t\t\r\n\t\t\t\tcontext.lineWidth = 2;\r\n\t\t\t\tcontext.strokeRect(this.jumpZone.rect.pos.x, this.jumpZone.rect.pos.y, this.jumpZone.rect.dim.width, this.jumpZone.rect.dim.height);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t// draw lives\r\n\t\t\tthis.lifeBar.draw();\r\n\t\t}\r\n\t}",
"function drawBombers() {\n\t\tfor (var b = 0; b < bombers.length; b++) {\n\t\t\tif (bombers[b].isActive) {\n\t\t\t\tctx.save();\n\t\t\t\tctx.globalAlpha = bombers[b].health * 0.1;\n\t\t\t\tctx.translate(bombers[b].x, bombers[b].y);\n\t\t\t\tctx.rotate(Math.atan2(player.y - bombers[b].y, player.x-bombers[b].x));\n\t\t\t\tctx.drawImage(bomberImage, -15, -15, 30, 30);\n\t\t\t\t//ctx.drawImage(bomberImage, -10, -10);\n\t\t\t\tctx.fillStyle = 'red';\n\t\t\t\tctx.fillRect(-20, -10, 5, bombers[b].health/5);\n\t\t\t\tctx.strokeRect(-20, -10, 5, 20);\n\t\t\t\tctx.restore();\n//\t\t\t\tctx.globalAlpha = 1.0;\n\t\t\t}\n\t\t}\n\t}",
"function drawInfo(){\n image(blueprint, 0, 0, imgSize, imgSize*5/9);\n fill('#fff8');\n rect(0, height-200, width, 200);\n \n fill(0);\n textStyle(ITALIC);\n textSize(22);\n var infoText = [\"Use WASD directions to navigate the rooms of the house.\", \"Hit 'X' to return to the splash screen.\", \"Hit 'I' to return to the map screen.\", \"Click or press any key again to start house tour.\"] \n for(var i = 0; i<infoText.length; i++){\n text(infoText[i], 175, height-150+i*30, width-350, 100);\n }\n}",
"drawPlayersScore() {\n fill('#BDBDBD');\n textFont('Helvetica', 28);\n text(this.player1.score, 4 * this.lateralPadding, 40);\n text(this.player2.score, canvasWidth - 4 * this.lateralPadding - 10, 40);\n }",
"function drawPlayer() {\n push();\n tint(255,playerHealth);\n image(playerHunter,playerX,playerY,playerRadius*5, playerRadius*5);\n pop();\n}",
"show() {\n var pos = this.body.position;\n var angle = this.body.angle;\n\n push();\n translate(pos.x, pos.y);\n rotate(angle);\n rectMode(CENTER);\n\n drawSprite(this.birdspr);\n /* strokeWeight(1);\n stroke(255);\n fill(127);\n ellipse(0, 0, this.r * 2);\n line(0, 0, this.r, 0);*/\n pop();\n }",
"function drawPausePopup(){\n ctx.fillStyle = menu.background.color;\n ctx.fillRect(gameWindow.x,gameWindow.y,200,70);\n\n ctx.strokeStyle = menu.borderColor;\n ctx.lineWidth = menu.borderWidth;\n ctx.strokeRect(gameWindow.x,gameWindow.y,200,70);\n\n var pauseText = new Text(gameWindow.x+20,gameWindow.y+50,\"Paused\",-1,\"black\",50);\n pauseText.paint();\n}",
"function drawGoal(x, y, size, alpha){\r\n\tvar blue = color(\"blue\");\r\n\tblue.setAlpha(alpha);\r\n\r\n\tfill(blue);\r\n circle(x+size/2, y+size/2, size*5/6);\r\n erase();\r\n circle(x+size/2, y+size/2, size*7/12);\r\n noErase();\r\n fill(blue);\r\n circle(x+size/2, y+size/2, size/3);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds all of the dice that are fives to the box for fives, when the checkbox is checked, so long as the user has not done so already. If the user has already added a score value, the AddAlert() function is called to let them know they can't do that. | function AddFives(){
checkCtrl = document.getElementById("keepFives");
boxCtrl = document.getElementById("FivesValue");
NumberCheck = 5;
UpperCheck();
} | [
"function AddFours(){\n\t\t\t\tcheckCtrl = document.getElementById(\"keepFours\");\n\t\t\t\tboxCtrl = document.getElementById(\"FoursValue\");\n\t\t\t\tNumberCheck = 4;\n\n\t\t\t\tUpperCheck();\n\t\t\t}",
"function updateScore() {\n rollScore = 0\n\t\tlet numOfDice = 0\n let ones = '', twos = '', threes = '', fours = '', fives = '', sixs = ''\n for(let i = 0 ; i < Object.keys(diceDef).length; i++) {\n if(diceDef[i][1] === 'selected' && diceDef[i][2] === true) {\n switch (diceDef[i][0]) {\n case 1:\n ones += '1'\n break\n case 2:\n twos += '2'\n break\n case 3:\n threes += '3'\n break\n case 4:\n fours += '4'\n break\n case 5:\n fives += '5'\n break\n case 6:\n sixs += '6'\n break\n }\n }\n }\n if(oneValues[ones]) {\n\t\t\trollScore += oneValues[ones]\n\t\t\tnumOfDice += ones.length\n\t\t}\n if(twoValues[twos]) {\n\t\t\trollScore += twoValues[twos]\n\t\t\tnumOfDice += twos.length\n\t\t}\n if(threeValues[threes]) {\n\t\t\trollScore += threeValues[threes]\n\t\t\tnumOfDice += threes.length\n\t\t}\n if(fourValues[fours]) {\n\t\t\trollScore += fourValues[fours]\n\t\t\tnumOfDice += fours.length\n\t\t}\n if(fiveValues[fives]) {\n\t\t\trollScore += fiveValues[fives]\n\t\t\tnumOfDice += fives.length\n\t\t}\n if(sixValues[sixs]) {\n\t\t\trollScore += sixValues[sixs]\n\t\t\tnumOfDice += sixs.length\n\t\t}\n if((ones + twos + threes + fours + fives + sixs) === '123456') {\n\t\t\trollScore = 1500\n\t\t\tnumOfDice = 6\n\t\t}\n if((((ones.length === 2) || (ones.length === 0)) &&\n ((twos.length === 2) || (twos.length === 0)) &&\n ((threes.length === 2) || (threes.length === 0)) &&\n ((fours.length === 2) || (fours.length === 0)) &&\n ((fives.length === 2) || (fives.length === 0)) &&\n ((sixs.length === 2) || (sixs.length === 0))) &&\n ((ones.length + twos.length + threes.length +\n\t\t\tfours.length + fives.length + sixs.length) === 6)) {\n\t\t\trollScore = 1000\n\t\t\tnumOfDice = 6\n\t\t}\n score.innerText = 'roll score ' + rollScore\n let tempScore = totalScore + rollScore\n total.innerText = 'total score ' + tempScore\n tempScore < 350 ? total.classList.add('lowscore') : total.classList.remove('lowscore')\n roundButton.removeAttribute('disabled')\n let countSelected = 0 \n let countSelectedEnabled = 0\n for(let i = 0 ; i < Object.keys(diceDef).length; i++) {\n if(diceDef[i][1] === 'selected') countSelected++\n if((diceDef[i][1] === 'selected') && (diceDef[i][2] === true)) countSelectedEnabled++\n }\n if((countSelected === 6) && (rollScore > 0)) roundButton.setAttribute('disabled', true)\n if((rollScore > 0) && (countSelectedEnabled === numOfDice)) {\n rollButton.removeAttribute('disabled')\n } else {\n rollButton.setAttribute('disabled', true)\n } \n }",
"function addScore() {\n if (streak > 17) {\n $(\"#scoreMultiplier\").text(\"10\");\n scoreAninmation();\n score = score + 10;\n }\n else if (streak > 5) {\n $(\"#scoreMultiplier\").text(\"5\");\n scoreAninmation();\n score = score + 5;\n }\n else if (streak == 5) {\n $(\"#scoreMultiplier\").text(\"4\");\n scoreAninmation();\n score = score + 4;\n setTimeout(function () {\n $(\"#heatMed\").fadeOut(1000);\n $(\"#heatHi\").fadeIn(1000);\n }, 1500);\n }\n else if (streak == 4) {\n $(\"#scoreMultiplier\").text(\"2\");\n scoreAninmation();\n score = score + 2;\n setTimeout(function () {\n $(\"#heatLo\").fadeOut(1000);\n $(\"#heatMed\").fadeIn(1000);\n }, 1500);\n }\n else if (streak == 3) {\n $(\"#scoreMultiplier\").text(\"2\");\n scoreAninmation();\n score = score + 2;\n }\n else if (streak == 2) {\n $(\".deactive\").fadeOut(1000)\n $(\"#heatLo\").fadeIn(1000)\n score = score + 1;\n }\n else {\n score = score + 1;\n }\n }",
"function AddSixes(){\n\t\t\t\tcheckCtrl = document.getElementById(\"keepSixes\");\n\t\t\t\tboxCtrl = document.getElementById(\"SixesValue\");\n\t\t\t\tNumberCheck = 6;\n\t\t\t\n\t\t\t\tUpperCheck();\n\t\t\t}",
"function AddAlert(){\n\t\t\t\talert(\"You already added a score of \" + boxCtrl.value + \" to this box.\");\n\t\t\t}",
"function closeRoll() {\n let countSelected = 0\n\t\tfor(let i = 0 ; i < Object.keys(diceDef).length; i++) {\n\t\t\tif(diceDef[i][1] === 'selected') {\n countSelected ++\n\t\t\t\tdiceDef[i][2] = false\n\t\t\t\tconst dice = document.getElementById(i)\n\t\t\t\tdice.classList.add('disabled')\n\t\t\t}\n\t\t}\n\t\ttotalScore += rollScore\n\t\tupdateScore()\n\t\t\n\t\tif(countSelected === 6) {\n for(let i = 0 ; i < Object.keys(diceDef).length; i++) {\n\t\t\t\tconst dice = document.getElementById(i)\n\t\t\t\tdice.classList.remove('selected')\n\t\t\t\tdice.classList.remove('disabled')\n\t\t\t\tdiceDef[i][1] = 'unselected'\n\t\t\t\tdiceDef[i][2] = true\n\t\t\t}\n }\n\t}",
"function addVeggies(runningPrice) {\n var veggiePrice = 0;\n var veggieCount = 0;\n var veggieText = \"\";\n var veggieOptions = document.getElementsByClassName('veggie');\n for (var i = 0; i < veggieOptions.length; i++) {\n if (veggieCount >= 1) {\n if (veggieOptions[i].checked) {\n veggieText += \"<p>\" + veggieOptions[i].value + \" +$1.00</p>\";\n veggieCount += 1;\n veggiePrice += 1;\n }\n } else {\n if (veggieOptions[i].checked) {\n veggieText += \"<p>\" + veggieOptions[i].value +\"</p>\";\n veggieCount += 1;\n }\n }\n }\n document.getElementById('selectedVeggies').innerHTML = veggieText;\n runningPrice += veggiePrice;\n updateRunning(runningPrice);\n}",
"function LowerCheck(){\n\t\t\t\tMatches = 0;\n\t\t\t\tif(boxCtrl.value == -1){\n\t\t\t\t\tfor (var LoopCounter1 = 0; LoopCounter1 < Rolls.length; LoopCounter1++){\n\t\t\t\t\t\tfor (var LoopCounter2 = 0; LoopCounter2 < Rolls.length; LoopCounter2++){\n\t\t\t\t\t\t\tif (Rolls[LoopCounter1] == Rolls[LoopCounter2]){\n\t\t\t\t\t\t\t\tMatches++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tLoopCounter2 = 0;\n\t\t\t\t\t}\n\t\t\t\t\t//First, we check to see if the number of Matches is 13 on the nose (9 Matches\n\t\t\t\t\t//from having 3 of the same number, and 4 more Matches from 2 of the same number).\n\t\t\t\t\t//We combine this with a check to see if the FullBoolean variable is set to true,\n\t\t\t\t\t//which it will be if the user clicked on the button for Full House (important to\n\t\t\t\t\t//do so because the same dice that qualify as a Full House can also be used as\n\t\t\t\t\t//a Three of a kind).\n\t\t\t\t\tif ((Matches == NumberCheck) && (YahtzeeBoolean == false) && (FullBoolean == true) && (ThreeKindBoolean == false) && (FourKindBoolean == false)){\n\t\t\t\t\t\tSum = 25;\n\t\t\t\t\t}else if ((LgStraightBoolean == true) || (SmStraightBoolean == true)){\n\t\t\t\t\t\t//If the user clicked the Small Straight button, we want to be able to\n\t\t\t\t\t\t//make sure it is a Small Straight. So, we make a duplicate array, run\n\t\t\t\t\t\t//it through a loop splice() out any duplicates, and do an if check to\n\t\t\t\t\t\t//make sure that each value in the array differs by 1.\n\t\t\t\t\t\tvar points = Rolls;\n\t\t\t\t\t\tpoints.sort(function(a, b){return a-b});\n\t\t\t\t\t\t// var MaxRoll = Math.max.apply( null, points);\n\t\t\t\t\t\t// var MinRoll = Math.min.apply( null, points);\n\t\t\t\t\t\t// console.log(\"LgStraightBoolean is \" + LgStraightBoolean + \" and SmStraightBoolean is \" + SmStraightBoolean);\n\t\t\t\t\t\tif (LgStraightBoolean == true){\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif ((points[4] - points[3]) == 1 && (points[3] - points[2]) == 1 && (points[2] - points[1]) == 1 && (points[1] - points[0]) == 1){\n\t\t\t\t\t\t\t\tSum = 40;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (SmStraightBoolean == true){\n\t\t\t\t\t\t\tfor (var LoopCounter1 = 0; LoopCounter1 < (points.length - 1); LoopCounter1++){\n\t\t\t\t\t\t\t\tif (points[LoopCounter1] == points[(LoopCounter1 + 1)]){\n\t\t\t\t\t\t\t\t\tpoints.splice(LoopCounter1, 1);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (points.length >= 4){\n\t\t\t\t\t\t\t\tif ((points[3] - points[2]) == 1 && (points[2] - points[1]) == 1 && (points[1] - points[0]) == 1){\n\t\t\t\t\t\t\t\t\tSum = 30;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t//If it is a Three or Four of a kind, add the numbers in Rolls[] to get the\n\t\t\t\t\t//Sum. If it is a Yahtzee, the Sum is 50 points.\n\t\t\t\t\t}else if (Matches >= NumberCheck && (YahtzeeBoolean == false) && (ThreeKindBoolean == true) || (FourKindBoolean == true)){\n\t\t\t\t\t\tSum = Rolls[0] + Rolls[1] + Rolls[2] + Rolls[3] + Rolls[4];\t\t\t\t\t\t\n\t\t\t\t\t}else if ((Matches == 25) && (YahtzeeBoolean == true)){\n\t\t\t\t\t\tSum = 50;\n\t\t\t\t\t}\n\t\t\t\t\tboxCtrl.value = Sum;\n\t\t\t\t\tLowerScore.push(Sum);\n\t\t\t\t\tResetAfterAdd();\n\t\t\t\t\t}else{\n\t\t\t\t\t\tAddAlert();\n\t\t\t\t\t}\n\t\t\t}",
"function ResetAfterAdd(){\n\t\t\t\tTallyUpper();\n\t\t\t\tTallyLower();\n\t\t\t\tTallyGrand();\n\n\t\t\t\tSum = 0;\n\t\t\t\tNumberRolls = 0;\n\t\t\t\tdocument.getElementById(\"keepRoll1\").checked = false;\n\t\t\t\tdocument.getElementById(\"keepRoll2\").checked = false;\n\t\t\t\tdocument.getElementById(\"keepRoll3\").checked = false;\n\t\t\t\tdocument.getElementById(\"keepRoll4\").checked = false;\n\t\t\t\tdocument.getElementById(\"keepRoll5\").checked = false;\n\t\t\t\t\n\t\t\t\tboxCtrl = document.getElementById(\"Roll1Value\");\n\t\t\t\tboxCtrl.value = -1;\n\t\t\t\tboxCtrl = document.getElementById(\"Roll2Value\");\n\t\t\t\tboxCtrl.value = -2;\n\t\t\t\tboxCtrl = document.getElementById(\"Roll3Value\");\n\t\t\t\tboxCtrl.value = -3;\n\t\t\t\tboxCtrl = document.getElementById(\"Roll4Value\");\n\t\t\t\tboxCtrl.value = -4;\n\t\t\t\tboxCtrl = document.getElementById(\"Roll5Value\");\n\t\t\t\tboxCtrl.value = -5;\n\t\t\t\tboxCtrl = document.getElementById(\"NumberRollsValue\");\n\t\t\t\tboxCtrl.value = 0;\n\n\t\t\t\tRollBoolean = false;\n\t\t\t\tFullBoolean = false;\n\t\t\t\tThreeKindBoolean == false;\n\t\t\t\tFourKindBoolean == false;\n\t\t\t\tSmStraightBoolean = false;\n\t\t\t LgStraightBoolean = false;\n\t\t\t YahtzeeBoolean = false;\t\t\t\t\n\t\t\t}",
"function rollDice(player) { \r\n var die1=rollSingleDice(); \r\n // console.log(\"Die 1: \" + die1);\r\n var die2=rollSingleDice(); \r\n // console.log(\"Die 2: \" + die2);\r\n // var score=die1+die2; \r\n player.addToScore(die1 + die2);\r\n // console.log(\"Score: \" + player.getScore());\r\n\twhile (die1===die2){ \r\n\t\tif (die1 === 1 && die2 === 1) { \r\n\t\tconsole.log(\"Snake Eyes!\");\r\n\t\tsnakeEyes = true; \r\n\t\treturn snakeEyes; \r\n\t\t}\r\n console.log(\"Congratulations! Doubles Thrown!\");\r\n\t\tdie1=rollSingleDice(); \r\n // console.log(\"Die 1: \" + die1);\r\n\t\tdie2=rollSingleDice();\r\n // console.log(\"Die 2: \" + die2);\r\n\t\t// score+=die1+die2; \r\n player.addToScore(die1 + die2);\r\n // console.log(\"Score: \" + player.getScore());\r\n \r\n\t}\r\n\treturn false;\r\n}",
"function checkScore() {\n if (totalScoreNumber === currentGoalNumber && currentGoalNumber != 0) {\n wins++;\n $(\"#wins\").text(\"Wins: \" + wins);\n setNumbers();\n }\n else if (totalScoreNumber > currentGoalNumber) {\n losses++;\n $(\"#losses\").text(\"Losses: \" + losses);\n setNumbers();\n }\n }",
"function makeGuess() {\n let radioButtons = Array.from(document.getElementsByName(\"counties\"));\n radioButtons.forEach((radio) => {\n if (radio.checked) {\n props.setDepth(-1);\n if (radio.value === props.county) {\n props.quit();\n alert(\"Correct!\");\n return;\n } else {\n props.setScore(props.score - 10);\n alert(\"Wrong!\");\n }\n }\n });\n }",
"function RollAlert(){\n\t\t\t\talert(\"You must enter a score before continuing.\");\n\t\t\t}",
"function scoreTally() {\n getQ10Answers(); // Call the corresponding getQ#Answers function\n arrScore.push(q10FinalAnswer); // Push the final submitted answer to a array to hold all answers selected\n let timeDelay = 2; // Set a 2 sec. delay to show the answer validation message\n if (q10Answers.value == \"true\") {\n // If the answer selected is correct...\n q10CorrectMsg.classList.remove(\"hidden\"); // ...Show the \"Correct\" validation message\n } else {\n // If it's incorrect...\n q10IncorrectMsg.classList.remove(\"hidden\"); // ...Show the \"Incorrect\" validation message\n }\n let timeDelayInterval = setInterval(function () {\n // Create the timer interval\n timeDelay--; // Decrement the previously set time delay for showing messaging by once per loop\n if (timeDelay === 0) {\n // Once the interval loop hits 0...\n clearInterval(timeDelayInterval); // ...Clear the timer interval\n q10CorrectMsg.classList.add(\"hidden\"); // ...Hide the correct answer validation message again\n q10IncorrectMsg.classList.add(\"hidden\"); // ...Hide the wrong answer validation message again\n qz10Div.classList.add(\"hidden\"); // ...Hide the current question\n qz11Div.classList.remove(\"hidden\"); // ...Show the next question\n }\n }, 1000); // ...Set the interval looping at 1000 milliseconds (aka 1 sec. per interval loop)\n scoreTitle.textContent = \"You have completed this quiz.\"; // Updates the div title with a \"completed\" notice.\n spanTime.textContent = finalTimeRemaining; // sets a var to the final time displayed on quiz completion\n finalTimeRemaining = parseInt(finalTimeRemaining); // parses that displayed time string into an integer resets the timeRemaining value to it\n correctCount = 0; // set the correct count var to 0\n for (i = 0; i < arrScore.length; i++) {\n // for loop to loop through the answers array\n if (arrScore[i] == \"true\") {\n // if the current index position has a value of \"true\" (our value for \"correct\")\n correctCount++; // increment the correct counter global variable by 1\n } else {\n // if it's false or empty, make some space in the console and do nothing\n console.log(\"---\");\n }\n }\n spanNumCorrect.textContent = correctCount; // set the text in the page that relays the # correct\n let percentTimeMultiplier = \"\"; // create a var to hold a calculated multiplier to use for a weighted score\n if (finalTimeRemaining < 1) {\n // if the time has run out (or possible been driven below zero due to penalties)\n percentTimeMultiplier = 0; // set the multiplier to 0\n } else {\n // if the quiz was completed in time\n percentTimeMultiplier =\n 1 - (originalTimerValue - finalTimeRemaining) / originalTimerValue; // calculate a % change in time for adjusting the score\n }\n weightedScore = Math.ceil(\n correctCount * percentTimeMultiplier + correctCount\n ); // set a weighted score var to be the rounded up sum of the correct responses and the correct responses * the % change in time multipier\n spanFinalScore.textContent = weightedScore; // set the text relaing the final weighted score to the calculated variable\n}",
"function score(dice) {\n let score = 0, one = 0,\n two = 0, three = 0,\n four = 0, five = 0,\n six = 0;\n\n for (let i = 0; i < dice.length; i++) {\n switch (dice[i]) {\n case 1: one++;\n break\n case 2: two++;\n break\n case 3: three++;\n break\n case 4: four++;\n break\n case 5: five++;\n break\n case 6: six++;\n break\n }\n }\n if (one > 2) {\n score += 1000\n }\n if (one > 3) {\n score += 100 * (one - 3)\n }\n if (one < 3) {\n score += 100 * one\n }\n if (two > 2) {\n score += 200\n }\n if (three > 2) {\n score += 300\n }\n if (four > 2) {\n score += 400\n }\n if (five > 2) {\n score += 500\n }\n if (five > 3) {\n score += 50 * (five - 3)\n }\n if (five < 3) {\n score += 50 * five\n }\n if (six > 2) {\n score += 600\n }\n return score\n}",
"function saveChecked(ID) {\r\nexperiment.tempcausaldata = [];\r\n\r\nvar radio = document.getElementById(ID);\r\nvar none = 0;\r\n\r\nif (ID == \"caused_boxes\") {\r\nfor (i = 0; i < radio.length; i++) {\r\n if (radio[i].checked) {\r\n if (i == 15) {\r\n experiment.causaldata.push(\"none\");\r\n experiment.causaldata_strengths.push(\"0\");\r\n experiment.causaltargets.push(experiment.temptarget[0])\r\n radio[i].checked = false; //turn off checked checkboxes\r\n none = 1;\r\n experiment.next();\r\n } \r\n\r\n else {\r\n checkedFeature = caused_list[i];\r\n experiment.causaldata.push(checkedFeature);\r\n experiment.tempcausaldata.push(checkedFeature);\r\n experiment.causaltargets.push(experiment.temptarget[0])\r\n radio[i].checked = false; //turn off checked checkboxes\r\n }\r\n}\r\n}\r\n\r\nif (experiment.tempcausaldata.length == 0 & experiment.temptarget != \"attncheck1\" & experiment.temptarget != \"attncheck2\" & none != 1) {\r\n$(\"#error_att\").html('<font color=\"red\">' + \r\n 'Please make a response!' + \r\n '</font>');\r\n}\r\n\r\nnone = 0;\r\n\r\nif (experiment.tempcausaldata.length > 0 & ID != \"caused_boxes_attn\") {\r\ngetStrengths(targetfeat);\r\n}\r\n}\r\n\r\nif (ID == \"caused_boxes_attn\") {\r\n var fail = 0;\r\nfor (i = 0; i < radio.length; i++) {\r\n if (radio[i].checked) {\r\n experiment.causaldata.push(\"fail\");\r\n experiment.causaldata_strengths.push(\"NA\");\r\n experiment.causaltargets.push(\"attention_check\")\r\n fail = 1;\r\n radio[i].checked = false;\r\n }\r\n}\r\n\r\nif (fail == 0) {\r\n experiment.causaldata.push(\"pass\");\r\n experiment.causaldata_strengths.push(\"NA\");\r\n experiment.causaltargets.push(\"attention_check\")\r\n}\r\n\r\nexperiment.next();\r\n}\r\n}",
"function AddThrees(){\n\t\t\t\tcheckCtrl = document.getElementById(\"keepThrees\");\n\t\t\t\tboxCtrl = document.getElementById(\"ThreesValue\");\n\t\t\t\tNumberCheck = 3;\n\n\t\t\t\tUpperCheck();\n\t\t\t}",
"function review () { \n\tfor (var i = 0; i < questions.length; i++) {\n\t\tvar userChoice = $(\"input[name = 'question-\" + i +\"']:checked\");\n\t\tif (userChoice.val() == questions[i].correctAnswer) {\n\t\t\tcorrectAnswers++; \n\n\t\t\t} else {\n\t\t\t\tincorrectAnswers++;\n\t\t\t\t\n\t\t}\n\t}\n\t$(\"#correctAnswers\").append(\" \" + correctAnswers);\n\t$(\"#incorrectAnswers\").append(\" \" + incorrectAnswers); \n}",
"function givePoints1() {\n sumScore = sumScore + number1;\n console.log(\"Total score: \" + sumScore);\n $(\"#totalScore\").text(sumScore);\n if (sumScore == randomNum) {\n winGame();\n }\n else if (sumScore > randomNum) {\n looseGame();\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if the given result is from a failed function trigger. | static isFailedFuncTrigger(result) {
if (CommonUtil.isDict(result)) {
for (const fid in result) {
const funcResult = result[fid];
if (CommonUtil.isFailedFuncResultCode(funcResult.code)) {
return true;
}
if (!CommonUtil.isEmpty(funcResult.op_results)) {
for (const opResult of Object.values(funcResult.op_results)) {
if (CommonUtil.isFailedTx(opResult.result)) {
return true;
}
}
}
}
}
return false;
} | [
"static isFailedTx(result) {\n if (!result) {\n return true;\n }\n if (CommonUtil.isDict(result.result_list)) {\n for (const subResult of Object.values(result.result_list)) {\n if (CommonUtil.isFailedTxResultCode(subResult.code)) {\n return true;\n }\n if (subResult.func_results) {\n if (CommonUtil.isFailedFuncTrigger(subResult.func_results)) {\n return true;\n }\n }\n }\n return false;\n }\n if (CommonUtil.isFailedTxResultCode(result.code)) {\n return true;\n }\n if (result.func_results) {\n if (CommonUtil.isFailedFuncTrigger(result.func_results)) {\n return true;\n }\n }\n return false;\n }",
"static txPrecheckFailed(result) {\n const precheckFailureCode = [21, 22, 3, 15, 33, 16, 17, 34, 35];\n return precheckFailureCode.includes(result.code);\n }",
"function failedTestFn() {\n throw new Error('test failed');\n }",
"function passedFailed(expectation, message1, message2) {\n\treturn result(expectation.isNot, message1, message2);\n}",
"isErrored() {\n return !!this.keycatError;\n }",
"function failure() {\n return { solution: false };\n}",
"function checkErrors(data) {\n\tif (data['error'] !== false) {\n\t\tconsole.log(data['error']);\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}",
"static checkCallbackFnOrThrow(callbackFn){if(!callbackFn){throw new ArgumentException('`callbackFn` is a required parameter, you cannot capture results without it.');}}",
"expectValidationError(fn, shouldError = true) {\n // If no error is expected, we let the scope surrounding the test catch it.\n if (shouldError) {\n this.device.pushErrorScope('validation');\n }\n\n // Note: A return value is not allowed for the callback function. This is to avoid confusion\n // about what the actual behavior would be; either of the following could be reasonable:\n // - Make expectValidationError async, and have it await on fn(). This causes an async split\n // between pushErrorScope and popErrorScope, so if the caller doesn't `await` on\n // expectValidationError (either accidentally or because it doesn't care to do so), then\n // other test code will be (nondeterministically) caught by the error scope.\n // - Make expectValidationError NOT await fn(), but just execute its first block (until the\n // first await) and return the return value (a Promise). This would be confusing because it\n // would look like the error scope includes the whole async function, but doesn't.\n // If we do decide we need to return a value, we should use the latter semantic.\n const returnValue = fn();\n assert(\n returnValue === undefined,\n 'expectValidationError callback should not return a value (or be async)'\n );\n\n if (shouldError) {\n const promise = this.device.popErrorScope();\n\n this.eventualAsyncExpectation(async niceStack => {\n const gpuValidationError = await promise;\n if (!gpuValidationError) {\n niceStack.message = 'Validation succeeded unexpectedly.';\n this.rec.validationFailed(niceStack);\n } else if (gpuValidationError instanceof GPUValidationError) {\n niceStack.message = `Validation failed, as expected - ${gpuValidationError.message}`;\n this.rec.debug(niceStack);\n }\n });\n }\n }",
"function toFailure(result, context, struct, value) {\n if (result === true) {\n return;\n } else if (result === false) {\n result = {};\n } else if (typeof result === 'string') {\n result = {\n message: result\n };\n }\n\n const {\n path,\n branch\n } = context;\n const {\n type\n } = struct;\n const {\n refinement,\n message = \"Expected a value of type `\" + type + \"`\" + (refinement ? \" with refinement `\" + refinement + \"`\" : '') + \", but received: `\" + print(value) + \"`\"\n } = result;\n return {\n value,\n type,\n refinement,\n key: path[path.length - 1],\n path,\n branch,\n ...result,\n message\n };\n}",
"function check(callback,input){\n try{\n return callback(input);\n }catch(error){\n return false;\n }\n}",
"logIfError() {\n if (!this.ok)\n console.error(this.error);\n return !this.ok;\n }",
"function errorRRRV(){\n\tvar RRRV1 = document.getElementById('TRV_RRRV1_id').value\n\tvar RRRV2 = document.getElementById('TRV_RRRV2_id').value\n\t\n\tif (RRRV1 != 0 && RRRV2 ==0){\n\t\treturn true\n\t}\n\tif (RRRV2 == 0 && RRRV1 == 0){\n\t\treturn true\n\t} \n\telse \n\t\treturn false\n}",
"function isResult(x) {\n return x instanceof Result || className(x) === \"Result\" /* Tag.RESULT */;\n}",
"function haveOutputErr() {\n return OUTPUT_ERROR;\n}",
"_validateMultiResults (results, callback) {\n const errors = results.map(result => result[0])\n\n if (errors.some(error => !!error)) {\n callback(new Error(`${compact(errors)}`))\n } else {\n callback()\n }\n }",
"get isError() {\n return (this.flags & 4) /* NodeFlag.Error */ > 0\n }",
"checkFailure() {\n\t\tif(this.failureDetector.checkFailure()) {\n\t\t\tthis.requestDisconnect();\n\t\t}\n\t}",
"function isSuccessful(json) {\n\t\treturn json.STATUS_DATA.STATUS.toUpperCase() === \"S\" ? true : false;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
it hides the title of the expanded coupon. | function hideTitle() {
UIController.getExpandedCoupon().firstElementChild.firstElementChild.classList.remove('show');
} | [
"function CtrlExpandCoupon() {\n var cpnClickedId;\n if(event.target.classList.contains('coupon')){ // check if the clicked element is indeed a coupon.\n cpnClickedId = event.target.id;\n UICtrl.expandCoupon(cpnClickedId);\n\n //decide what value we give to checkedFields\n if(jackpotCtrl.hasCoupon(cpnClickedId)){ checkedFields = 4; UICtrl.showNextCouponButton(); decrementTotalFlag = 1;} // if the coupon is saved. then it is already filled.\n else { checkedFields = 0; UICtrl.fieldsClickable(); } //if the coupon is not filled, we make the fields clickable. so we can check them. \n UICtrl.CouponUnclickable(); //Either way , whenever we expand a coupon. we always make the coupon unclickable.\n \n //show and hide buttons\n UICtrl.showGobackButton();\n UICtrl.changeNameOfDeleteAllBtn(); // changes from deleting the coupons , to deleting the fields of the expanded coupon.\n }\n }",
"function showHideAuthor () {\n\n //chair description is hidden here\n chairText.style.display=displayNone;\n\n if (authorDisplay.style.display === displayNone || authorDisplay.style.display === \"\") {\n authorDisplay.setAttribute(\"class\", \"grid-item slide-left\");\n\n authorDisplay.style.display = displayBlock;\n aboutAuthor.style.display=displayBlock;\n\n authorMenu.innerHTML=\"close the description\";\n aboutMenu.style.display=displayNone;\n\n } else {\n authorDisplay.setAttribute(\"class\", \"grid-item\");\n\n authorDisplay.style.display = displayNone;\n aboutAuthor.style.display=displayNone;\n\n authorMenu.innerHTML=\"about the author\";\n aboutMenu.style.display=displayBlock;\n }\n}",
"_collapseHeading(heading) {\n heading.expanded = false;\n }",
"hide() {\n this.StartOverPopoverBlock.remove();\n this.StartOverPopoverDiv.remove();\n }",
"function toggleInfo() {\n\tvar state = document.getElementById('description').className;\n\tif (state == 'hide') {\n\t\t// Info anzeigen\n\t\tdocument.getElementById('description').className = '';\n\t\tdocument.getElementById('descriptionToggle').innerHTML = text[1];\n\t}\n\telse {\n\t\t// Info verstecken\n\t\tdocument.getElementById('description').className = 'hide';\n\t\tdocument.getElementById('descriptionToggle').innerHTML = text[0];\n\t}\t\n}",
"function div_hide_deck(){\n\t\tdocument.getElementById('def').style.display = \"none\";\n\t}",
"shouldHide(show_condition) {\n return ClassNames({\n 'should-hide': show_condition ? false : true\n })\n }",
"function hideTipShowText() {\n tipElement.style.opacity = '0'\n nodeElement.style.opacity = '1'\n nodeTitleElement.textContent = title\n }",
"function showHelper(event, element) {\n $ctrl.ide.tooltip.hide();\n for(const menuButton of dropdownButtons){\n if(element.parentNode !== menuButton) {\n menuButton.hideDropdown(event);\n }\n }\n \n element.style.visibility = \"visible\";\n element.setAttribute(\"visible\", \"\");\n }",
"show() {\n\t\tthis.element.style.visibility = '';\n\t}",
"function CtrlShrinkCoupon() {\n // we allowed to go back . only if the coupon is fully filled , or completely emtpy.\n if(checkedFields === 4 || checkedFields === 0 ) {\n if(checkedFields === 4) { if(addNewCouponFlag) { CtrlAddNewCoupon(); addNewCouponFlag = 0; } } // if addNewCouponFlag is released, then we save the new coupon.\n // if the user unchecked all the fields , then we (try to) delete that coupon from the data structure.\n if(checkedFields === 0) { jackpotCtrl.removeCoupon((UICtrl.getExpandedCoupon()).id); UICtrl.CouponClickable(); } //\n\n UICtrl.makeAllFilledCouponsClickable(jackpotCtrl.getAllCoupons());\n UICtrl.shrinkCoupon();\n UICtrl.hideNextCouponButton();\n UICtrl.hideGobackButton();\n updateTotal();\n\n //dont change name , when we click on nextCouponButton\n if(event.target !== selectedElementIs.nextCouponButton) { UICtrl.changeNameOfDeleteAllBtn(); }\n UICtrl.exposeNextCoupon(jackpotCtrl.getAllCoupons()); // expose the next empty coupon in state 1. so we can click , expand it and fill it.\n \n //we activate DoneFilling button , only if there are saved coupons. otherwise deactivate and dispaly initialUI\n if(Object.keys(jackpotCtrl.getAllCoupons()).length > 0) { UICtrl.activateDoneFillingBtn(); } // if there are any saved coupons . activate DoneFillingBtn\n else { UICtrl.deactivateDoneFillingBtn(); UICtrl.setInitialUI(); } \n \n }\n else { alert('In order to be able to submit the coupon, it must be completed or completely cleared.'); } \n }",
"function closeProductDetail() {\n const productDetailDiv = document.querySelector('#product-detail');\n productDetailDiv.innerHTML = '';\n productDetailDiv.style.display = \"none\";\n}",
"displayLess() {\n let that = this;\n return () => that.collapseToolTip(that.tooltip, that.tooltipExt);\n }",
"seeLess(){\n let i = 0;\n for(i=0; i<topSongsItems.length; ++i){\n if(i>2){\n helper.hideOrShow(topSongsItems[i], true);\n }\n }\n //Add class used to determine buttons state\n seeMoreBtn.classList.add('see-more-js');\n //Swap text out on button\n seeMoreBtn.innerHTML = 'See More';\n }",
"function hide_global_supplier_settings()\n{\n\t//Empty the html \n\t$(\"#sup_list_view_global\").html(\"\");\n\t//Hide the modal box \n\t$('.overlay').hide(); \n\t$('#setng_supplier_global').hide();\n\t//Nothing else to be done \n}",
"function onLearnMoreClick(){\n $('#learnmoretext').slideDown();\n $('.learnmore').hide();\n }",
"function div_hide_learn() {\n\t\tdocument.getElementById('ghi').style.display = \"none\";\n\t}",
"seeMore(){\n let i = 0;\n for(i=0; i<topSongsItems.length; ++i){\n helper.hideOrShow(topSongsItems[i], false);\n }\n //Remove class used to determine buttons state\n seeMoreBtn.classList.remove('see-more-js');\n //Swap text out on button\n seeMoreBtn.innerHTML = 'See Less';\n }",
"close( item ) {\n item.classList.remove( 'is-expanded' )\n\n const [ tab, panel ] = item.children\n\n // ARIA\n tab.setAttribute( 'aria-selected', false )\n panel.setAttribute( 'hidden', '' )\n\n // Styling & transition\n panel.style.transitionProperty = 'height, padding'\n panel.style.transitionDuration = this.settings.duration + 'ms'\n panel.style.height = panel.offsetHeight + 'px'\n panel.offsetHeight\n panel.style.overflow = 'hidden'\n panel.style.height = 0\n panel.style.paddingTop = 0\n panel.style.paddingBottom = 0\n\n setTimeout( () => {\n panel.style.display = 'none';\n panel.style.removeProperty( 'height' )\n panel.style.removeProperty( 'padding-top' )\n panel.style.removeProperty( 'padding-bottom' )\n panel.style.removeProperty( 'overflow' )\n panel.style.removeProperty( 'transition-duration' )\n panel.style.removeProperty( 'transition-property' )\n }, this.settings.duration )\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
author: Ali El Zoheiry. description: sets the language of the words to be fetched from the database, based on which button the gamer clicked. params: l: is an integer value, 0 meaning the language is english, 1 meaning it is arabic, 2 meaning it is both. success: the button is clicked and the language is set. failure: | function setLang(l){
if(lockLangButtons == true){
return;
}
disableNav();
$('.zone').empty();
$(".zone").slideUp(1000);
$(".zone").slideDown(1000);
lang = l;
setTimeout(function(){
newGame();
}, 1100);
} | [
"function updateLanguage(select_language, select_dialect) {\n var list = langs[select_language.selectedIndex];\n select_dialect.style.visibility = list[1].length == 1 ? 'hidden' : 'visible';\n localStorage['dialect'] = select_dialect.selectedIndex; \n document.getElementById('voiceBtn').setAttribute('lang', list[select_dialect.selectedIndex + 1][0]);\n}",
"function setLanguage() {\n const queryParams = new URLSearchParams(window.location.search);\n const language = (queryParams.get(\"language\") || localStorage.getItem(\"language\") || \"\").toLowerCase();\n const languages = new Map();\n const codeTabs = document.querySelectorAll(\".multitab-code:not(.dependencies) li\") || [];\n Array.from(codeTabs).forEach(it => {\n languages.set(it.textContent.toLowerCase(), it.getAttribute(\"data-tab\")); // language and index\n });\n if (languages.get(language) !== undefined) {\n codeTabs[0].parentElement.querySelector(`[data-tab='${languages.get(language)}']`).click();\n }\n }",
"function menutoshowlang(){\n}",
"function updateLanguageToKorean() {\n localStorage.setItem('lang', 'ko');\n document.title = $('#title-ko').val();\n $('.navbar__language--english').removeClass('language--active');\n $('.navbar__language--korean').addClass('language--active');\n $('[data-lang=\"en\"]').addClass('hidden');\n $('[data-lang=\"ko\"]').removeClass('hidden');\n}",
"function setLangByUrl() {\n var url = document.URL;\n var id = url.substring(url.lastIndexOf('#') + 1);\n getLang(id);\n\n // update #lang-select based on url segment\n var rightOption = \"lang-\" + id;\n $(\"#lang-select option\").filter(function(){\n return this.id == rightOption;\n }).prop('selected', true);\n}",
"function languageChangeHandler() {\n if (document.getElementById('selectLanguage').value == \"en\") {\n //alert('selected value is english');\n transliterationControl.disableTransliteration();\n //return;\n } else {\n //enableTransliteration()\n var dropdown = document.getElementById('selectLanguage');\n transliterationControl.setLanguagePair(\n google.elements.transliteration.LanguageCode.ENGLISH,\n dropdown.options[dropdown.selectedIndex].value);\n transliterationControl.enableTransliteration();\n }\n\n }",
"function manage_magickeys_change_lang(value) {\n\t$.ajax({\n\t\ttype: \"POST\",\n\t\turl: \"scripts/manage_magickeys/manage_magickeys.php\",\n\t\tdata: { editLang: value }\n\t})\n\t.done(function( html ) {\n\t\t$(\"#content_wrapper\").html(html);\n\t});\n}",
"function setMenuLang(){\n \n // Browser basic settings\n var currentLang = \"lang_\"+getNavigatorLang();\n \n \n if(localStorage.myLang)\n {\n currentLang= \"lang_\"+localStorage.myLang;\n }\n\n //Menu setting\n \n var menu = document.querySelectorAll(\"ul.nav li a\");\n for(var i=0; i<menu.length; i++)\n {\n var data = menu[i].getAttribute(\"data-name\");\n menu[i].innerHTML= window[currentLang][data];\n }\n \n // Navbar title and header setting\n \n var getSelector = document.querySelector(\".navbar-header a\");\n \n var dataName = getSelector.getAttribute(\"data-title\");\n \n getSelector.innerHTML = window[currentLang][dataName];\n \n \n var getSelector = document.querySelector(\".starter-template h1\");\n \n var dataName = getSelector.getAttribute(\"header-title\");\n \n getSelector.innerHTML = window[currentLang][dataName]; \n}",
"function checkboxClickHandler() {\n if (document.getElementById('selectLanguage').value == \"en\") {\n transliterationControl.disableTransliteration();\n } else {\n transliterationControl.toggleTransliteration();\n }\n }",
"languageSwitch(changedLanguage)\n\t{\n\t\tif(this.state.language.lang !== changedLanguage)\n\t\t{\n\t\t\tthis.setState({changedLang: changedLanguage})\n\t\t\tthis.setState({dialog: true})\n\t\t}\n\t}",
"function handleLangSelect ( event ) {\r\n\t\t\r\n\t\t// prevent going to #\r\n\t\tevent.preventDefault()\r\n\r\n\t\tlet selectElement = event.srcElement\r\n\t\t// to be shown as placeholder\r\n\t\tlet buttonElement = selectElement.parentElement.previousElementSibling\r\n\t\t// element in with data to be saved of selected language\r\n\t\tlet dataElement = buttonElement.parentElement\r\n\r\n\t\t// save the selected info\r\n\t\tlet selectedInfo = {\r\n\t\t\tvalue: selectElement.getAttribute(\"data-val\"),\r\n\t\t\ttext: selectElement.innerHTML\r\n\t\t}\r\n\r\n\t\t// toogle data b/w selected element and \r\n\t\t// placeholder element\r\n\t\tselectElement.innerHTML = buttonElement.innerHTML\r\n\t\tselectElement.setAttribute(\"data-val\", dataElement.getAttribute(\"data-val\"))\r\n\t\tdataElement.setAttribute(\"data-val\", selectedInfo.value)\r\n\t\tbuttonElement.innerHTML = selectedInfo.text\r\n\t\t\r\n\t\tif ( DEBUG.Log ) {\r\n\t\t\tconsole.log(event)\r\n\t\t}\r\n\t}",
"function initLangMenu() {\n\t\n\tvar linkFr = document.getElementById(\"link-fr\");\n\tvar linkEn = document.getElementById(\"link-en\");\n\t\n\tif (currentCriteriaListName) {\n\t\tlinkFr.setAttribute('href', './?lang=fr&list=' + currentCriteriaListName);\n\t\tlinkEn.setAttribute('href', './?lang=en&list=' + currentCriteriaListName);\n\t} else {\n\t\tlinkFr.setAttribute('href', './?lang=fr');\n\t\tlinkEn.setAttribute('href', './?lang=en');\n\t}\n\t\n\tif (globalLang === \"fr\") {\n\t\tlinkFr.setAttribute('aria-current', true);\t\n\t\tlinkFr.classList.add(\"active\");\n\t\t\n\t\tlinkEn.removeAttribute('aria-current');\n\t\tlinkEn.classList.remove(\"active\");\n\t\t\n\t} else {\n\t\tlinkEn.setAttribute('aria-current', true);\n\t\tlinkEn.classList.add(\"active\");\n\t\t\n\t\tlinkFr.removeAttribute('aria-current');\n\t\tlinkFr.classList.remove(\"active\");\n\t}\n}",
"function createLocalizedAlertDialog(labelArray, userId) {\n\tvar labelIdList = new Array();\n\tvar buttonLabelArray = new Array();\n\tlabelIdList[0] = labelArray[\"title\"][0];\n\tlabelIdList[1] = labelArray['message'][0];\n\tvar inPlaceholder = '( ?,?';\n\tvar j = 1;\n\t//building the array of label ids to pass to database query\n\twhile (true) {\n\t\tif (labelArray[j] == null) {\n\t\t\tbreak;\n\t\t} else {\n\t\t\tinPlaceholder = inPlaceholder + ',';\n\t\t}\n\t\tlabelIdList[j + 1] = labelArray[j][0];\n\t\tinPlaceholder = inPlaceholder + '?';\n\t\tj++;\n\t}\n\tinPlaceholder = inPlaceholder + ')';\n\t//Fetching localized text for all the titles,message and button names\n\tvar db = Titanium.Database.open('Miscue');\n\tvar paramList = [userId];\n\tparamList = paramList.concat(labelIdList);\n\n\tvar localizedAlertLabelnamerow = db.execute('SELECT * FROM Language WHERE userId =? AND labelId IN ' + inPlaceholder, paramList);\n\n\tif (localizedAlertLabelnamerow.rowCount > 0) {\n\n\t\tfor (var i = 0; i < localizedAlertLabelnamerow.rowCount; i++) {\n\t\t\tvar labelName = localizedAlertLabelnamerow.fieldByName('label');\n\t\t\tvar labelId = localizedAlertLabelnamerow.fieldByName('labelId');\n\t\t\t//Replacing the default values fetch from database\n\t\t\tif (labelArray[\"title\"][0] == labelId) {\n\t\t\t\tlabelArray[\"title\"][1] = labelName;\n\t\t\t}\n\t\t\tif (labelArray[\"message\"][0] == labelId) {\n\t\t\t\tlabelArray['message'][1] = labelName;\n\t\t\t}\n\t\t\tvar j = 1;\n\t\t\t//Replacing default values with db text for button names\n\t\t\twhile (true) {\n\t\t\t\tif (labelArray[j + 1] == null) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (labelArray[j+1][0] == labelId) {\n\t\t\t\t\tlabelArray[j + 1][1] = labelName;\n\t\t\t\t}\n\t\t\t\tj++;\n\t\t\t}\n\t\t\tlocalizedAlertLabelnamerow.next();\n\t\t}\n\t\tdb.close();\n\t} else {\n\t\tdb.close();\n\t}\n\t//Creating button name labels\n\tvar j = 1;\n\twhile (true) {\n\t\tif (labelArray[j] == null) {\n\t\t\tbreak;\n\t\t}\n\t\tbuttonLabelArray.push(labelArray[j][1]);\n\t\tj++;\n\t}\n\n\tvar dialog = Ti.UI.createAlertDialog({\n\t\tmessage : labelArray['message'][1],\n\t\tbuttonNames : buttonLabelArray,\n\t\ttitle : labelArray['title'][1]\n\t});\n\treturn dialog;\n}",
"function manage_blog_change_lang(value) {\n\t$.ajax({\n\t\ttype: \"POST\",\n\t\turl: \"scripts/manage_blog/manage_blog.php\",\n\t\tdata: { editLang: value }\n\t})\n\t.done(function( html ) {\n\t\t$(\"#content_wrapper\").html(html);\n\t});\n}",
"setDefaultWordlist(language) {\n bip39.setDefaultWordlist(language);\n }",
"function setLanguage(args) {\n\tSETTINGS.LANGUAGE = args.next() || SETTINGS.LANGUAGE\n}",
"function setCodeLanguage(lang) {\n selectedLanguageName = lang;\n selectedLanguageCodes = allCodes[lang];\n return;\n }",
"function getLanguage(){\n\tvar lang=document.getElementById(\"language\").value;\n\tswitch(lang){\n\t\tcase \"C\":\n\t\t\tlang=1;\n\t\t\tbreak;\n\t\tcase \"C++\":\n\t\t\tlang=2;\n\t\t\tbreak;\n\t\tcase \"Java\":\n\t\t\tlang=3;\n\t\t\tbreak;\n\t\tcase \"Python\":\n\t\t\tlang=5;\n\t\t\tbreak;\n\t}\n\treturn lang;\n}",
"function onLocaleChange(e)\r\n{\r\n\tvar flashObj = getFlashObject();\r\n\t\r\n\t/* Change the active locale of the flash object. */\r\n\tif (flashObj && flashObj['changeLocale'])\r\n\t{\r\n\t\tflashObj.changeLocale(e.locale);\r\n\t}\r\n\t\r\n\t/* Remove the active-class from the all tabs, add it to the current language. */\r\n\t$(\"#locale a.active\").removeClass('active');\r\n\t$(\"#locale a.\" + e.locale).addClass('active');\r\n\t\r\n\t/* Change alert message if no flash. */\r\n\tif ($(\"#noflash-message div\"))\r\n\t{\r\n\t\t$(\"#noflash-message div\").addClass('hidden');\r\n\t\t$(\"#noflash-message div.\" + e.locale).removeClass('hidden');\r\n\t}\r\n\t\r\n\t/* Update the URL with the selected language. */\r\n\tif (window.history && window.history.pushState)\r\n\t{\r\n\t\twindow.history.pushState(\r\n\t\t{\r\n\t\t\tlocale: e.locale\r\n\t\t}, document.title, \"?locale=\" + e.locale);\r\n\t}\r\n\t\r\n /* Sets a cookie to remember the language use. */\r\n $.cookie(\"locale\", e.locale);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the CSV file from a list of users | function createCSV(users){
console.log("%s users found. Writing to CSV file...", users.length);
var csfFile = csv.createCsvStreamWriter(
fs.createWriteStream('users.csv'),
{
'separator': ';',
'quote': '"',
'escape': '"',
'encoding': 'utf16le'
}
);
csfFile.writeRecord(["identifiant", "nom", "prenom","email","domaine mail", "actif ?","licence","derniere connexion"]);
var index = 0;
var promises = [];
bar = new ProgressBar(':bar :current/:total (:percent)', { total: users.length, width:20 });
for(let user of users){
promises.push(function(){
return getLastLoginDate(user).then(lastConnectionDate => {
csfFile.writeRecord([
user.userName,
user.firstName,
user.lastName,
user.email,
user.email != null ? user.email.split("@")[1] : "",
user.enabled ? "X" : "",
user.authorizationStatus == "NEVER_AUTHORIZED" ? "" : "X",
lastConnectionDate
]);
bar.tick();
})
}
);
}
pacu.series(promises);
} | [
"async generateSampleUsers() {\n // Create an arbitrary number of user details and add them to an array\n for (let newUsersNumber = 0; newUsersNumber < this.totalNumberOfUsers; newUsersNumber++) {\n this.allUsers.push(\n {\n username: faker.name.firstName(),\n company: faker.company.companyName(),\n phone: faker.phone.phoneNumber(),\n email: faker.internet.email(),\n }\n );\n }\n const usersListContent = JSON.stringify(this.allUsers);\n await fs.writeFile(`${__dirname}/users.json`, usersListContent, 'utf8', function (err) {\n if (err) {\n console.log('An error occured while writing users to File.');\n return console.log(err);\n }\n });\n\n }",
"function makeCSV() {\n logger.info('Creating CSV file...');\n\n var csv = json2csv({ data: posts, newLine: \"\\r\\n\" });\n var outputFilename = inputCSV + '-withCountries-' + new Date().getTime() + '.csv';\n\n fs.writeFile(outputFilename, csv, function(err) {\n if (err) {\n logger.error('Error encountered while exporting posts to ' + outputFilename + ' file. More details: ' + err);\n } else {\n logger.info('Successfully exported posts to ' + outputFilename + ' file.');\n }\n });\n}",
"function export_instances_to_csv(instances) {\n\n var csv = \"data:text/csv;charset=utf-8,\";\n var header = \"User Name, Email,Condition Type, Conditiong Info\\n\";\n csv += header;\n\n instances.forEach(instance => {\n let condition_type = `\"${JSON.stringify(Object.keys(instance.conditions)).replaceAll('\"', '\"\"')}\"`;\n let condition_info = `\"${JSON.stringify(instance[\"conditions\"]).replaceAll('\"', '\"\"')}\"`;\n csv += `${instance.name},${instance.email},${condition_type},${condition_info}\\n`;\n });\n\n var encodedUri = encodeURI(csv);\n var link = document.createElement(\"a\");\n link.setAttribute(\"href\", encodedUri);\n // create file name with current date and time\n link.setAttribute(\"download\", `student_metrics_${new Date().toLocaleString()}.csv`);\n document.body.appendChild(link); // Required for FF\n link.click(); \n document.body.removeChild(link);\n\n}",
"function csvExportRecommenderData() {\n csvExportUser()\n csvExportVideoHistory()\n csvExportVideoAnalytics()\n csvExportFavouritedVideos()\n csvExportSkillsSelectedFreq()\n}",
"saveUsers(users) {\n Jsonfile.spaces = 4;\n Jsonfile.writeFileSync(usersFile, users);\n }",
"function saveAllUsers() {\n\tfs.writeFile(\n\t\t\"./users.json\",\n\t\tJSON.stringify(usersArr),\n\t\tfunction(err) {\n\t\t\tif (err) {\n\t\t\t\tconsole.log(err);\n\t\t\t}\n\t\t}\n\t);\n}",
"function csvExportFavouritedVideos(){\n var data_array = [];\n var csv_data;\n firebase.database().ref('users').once(\"value\", function(snapshot){\n let user_array = snapshot.val()\n let data;\n let videoFavourites;\n\n for(id in user_array){\n for(i in user_array[id]['videoFavourite']){\n \n if(user_array[id]['videoFavourite'] !== undefined){\n videoFavourites = user_array[id]['videoFavourite']\n \n data = {\n user_id: user_array[id]['phone'],\n username: user_array[id]['username'],\n phone: user_array[id]['phone'],\n post_id: user_array[id]['videoFavourite'][i]['postId'],\n video_title: user_array[id]['videoFavourite'][i]['videoTitle'],\n video_url: user_array[id]['videoFavourite'][i]['videoUrl'],\n video_interest: user_array[id]['videoFavourite'][i]['interest'],\n post_id: user_array[id]['videoFavourite'][i]['postId']\n\n } \n \n\n data_array.push(data)\n \n \n }\n }\n \n }\n\n }).then(() => {\n csv_data = convertObjectToCSV(data_array); \n }).then(() => {\n csvDownload(csv_data, \"recommender_user_favourited_videos\");\n });\n}",
"export() {\n let { output, outputFrozen } = this.appState.data.seizureData;\n\n // Generate CSV\n let csv = 'is-seizure,is-seizure-user-corrected\\n';\n\n for( let i = 0; i < output.length; i++ ) {\n csv += `${Number(outputFrozen[i])},${Number(output[i])}\\n`;\n }\n\n // Generate data URI and associated link\n let blob = new Blob([csv], {type: 'text/csv'});\n let filename = 'export.csv';\n let objectURL = window.URL.createObjectURL(blob);\n\n const a = document.createElement('a');\n a.setAttribute('download', filename);\n a.setAttribute('href', objectURL);\n\n // Trigger download\n a.click();\n\n // Clear blob from memory\n window.URL.revokeObjectURL(objectURL);\n }",
"function createUsersLinkList(usersList, parent) {\n // for each user\n usersList.forEach(user => {\n // create new form element\n const newForm = document.createElement(\"form\");\n newForm.method = \"get\";\n newForm.action = \"/options\";\n newForm.className = \"usersLinkList\";\n // create new user list element with an evenet listener\n const newUser = document.createElement(\"li\");\n newUser.innerHTML = user;\n newUser.className = \"users-list-style\";\n newUser.addEventListener('click', function() {\n localStorage.setItem(\"actualUser\", user);\n newUser.parentElement.submit();\n });\n // add it to the form\n newForm.appendChild(newUser);\n // create a new hidden input element containing the username as value\n const usernameInput = document.createElement(\"input\");\n usernameInput.type = \"text\";\n usernameInput.name = \"username\";\n usernameInput.value = user;\n usernameInput.hidden = true;\n // add it to the form\n newForm.appendChild(usernameInput);\n // add the form to a parent element\n parent.appendChild(newForm);\n });\n}",
"list() {\n const usersData = fs.readFileSync(`${__dirname}/users.json`, 'utf8');\n return JSON.parse(usersData);\n }",
"static createCsv() {\n //Check if start.csv exist, if not create it\n try {\n fs.statSync(pathCsvStart);\n } catch (error) {\n if(error.code === 'ENOENT') {\n ExcelServices.addStartTime('dossard', 'time');\n }\n }\n //Check if start.csv exist, if not create it\n try {\n fs.statSync(pathCsvStop);\n } catch (error) {\n if(error.code === 'ENOENT') {\n ExcelServices.addStopTime('dossard', 'time');\n }\n }\n //Check if participants.csv exist, if not create it\n try {\n fs.statSync(pathCsvParticipants);\n } catch (error) {\n if(error.code === 'ENOENT') {\n ExcelServices.addParticipant('dossard', 'lastname', 'firstname', 'team');\n }\n }\n }",
"function Csv () {}",
"function csvExportVideoAnalytics(){\n var data_array = [];\n var csv_data;\n firebase.database().ref('users').once(\"value\", function(snapshot){\n let user_array = snapshot.val()\n let data;\n let videoAnalytics;\n\n for(id in user_array){\n for(i in user_array[id]['videoHistory']){\n \n if(user_array[id]['videoHistory'][i]['videoAnalytics'] !== undefined){\n videoAnalytics = user_array[id]['videoHistory'][i]['videoAnalytics']\n \n for(j in videoAnalytics){\n for(k in videoAnalytics[j]){\n data = {\n user_id: user_array[id]['phone'],\n username: user_array[id]['username'],\n phone: user_array[id]['phone'],\n post_id: user_array[id]['videoHistory'][i]['postId'],\n video_watch_date: j,\n video_last_watched_time: k, // timestamp\n video_duration_seconds: videoAnalytics[j][k]['videoDuration'],\n video_current_time_seconds: videoAnalytics[j][k]['videoCurrentTime'],\n video_elapsed_time_seconds: videoAnalytics[j][k]['videoElapsedTime'],\n video_status: videoAnalytics[j][k]['videoStatus'],\n video_percent_done: videoAnalytics[j][k]['videoPercent'],\n video_visible_on_screen: videoAnalytics[j][k]['videoVisible']\n \n } \n }\n\n data_array.push(data)\n }\n \n }\n }\n \n }\n\n }).then(() => {\n csv_data = convertObjectToCSV(data_array); \n }).then(() => {\n csvDownload(csv_data, \"recommender_user_video_analytics\");\n });\n}",
"function listUsersView(targetid, users){\n apply_template(targetid, \"users-list-template\", {'users': users});\n}",
"function handleExportProfile() {\n // TODO: multiple employments?\n const employment = employee?.employments ? employee.employments[0] : null\n const filename = employee?.user?.lastName + '_' + employee?.user?.firstName + '_' + employment?.job?.client?.name + '_' + employment?.country?.name + '.csv'\n formsHelper.exportFormFieldValuesForUserAsCSV(employee?.user?.id, ee_form_slugs, filename, aDownloadProfileTag)\n }",
"function convertIntoUserObjects(rows) {\n var userObjects = [];\n rows.forEach( function(item) {\n var user = new User();\n user.setId(item.id)\n .setSalutation(item.salutation)\n .setFirstName(item.first_name)\n .setMiddleName(item.middle_name)\n .setLastName(item.last_name)\n .setSex(item.sex)\n .setEmail(item.email)\n .setPicpath(item.photopath)\n .setRole(item.role)\n .setAddress(item.city, item.state, item.country, item.pincode)\n .setContactNo(item.contactNo)\n .setDepartment(item.dept_name, item.dept_typ);\n userObjects.push(user);\n });\n return userObjects;\n}",
"sendUserlist() {\n this.print('Current Users');\n this.print(JSON.stringify(this.users, null, 2));\n this.namespace.emit('username list', this.getUsernames());\n }",
"function buildTestUsers() {\n\tvar user1 = new newUser(\"test\", \"test\");\n\tvar user2 = new newUser(\"timothy\", \"test\");\n\n\tusers.push(user1);\n\tusers.push(user2);\n}",
"function writeCsv(shirtsData){\n const pathCsvFile = `data\\\\${dateFormat(Date.now(), \"yyyy-mm-d\")}.csv`;\n // create csv file\n const csvWriter = createCsvWriter({\n path: pathCsvFile,\n header: [\n {id: 'title', title: 'Title'},\n {id: 'price', title: 'Price'},\n {id: 'imageURL', title: 'ImageURL'},\n {id: 'url', title: 'URL'},\n {id: 'time', title: 'Time'},\n ]\n });\n\n // write to csv file\n csvWriter.writeRecords(shirtsData).then(() => {\n console.log('...Done');\n console.log(`Please check this file: ${__dirname}\\\\${pathCsvFile}`);\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to grabs followup cards from the database and update the view | function getFolUp() {
$.get("/api/followup", function(data) {
console.log("FollowUp", data);
folUpCards = data;
if (!folUpCards || !folUpCards.length) {
displayEmpty();
}
else {
initializeCards();
}
})
.then(function() {
})
} | [
"function populate_followers_list() {\n $.get('/dashboard/get_followers', function (data) {\n $('#followers_list').html(data);\n \n // Click handler.\n $('#followers_list .add_following').confirmDiv(function (clicked_elem) {\n $.get('/dashboard/add_user_following', {\n following_id: clicked_elem.parent().attr('user_id')\n }, function (data) {\n populate_followers_list();\n });\n });\n \n // Make followers selectable\n $('#followers_list .user_entry').click(function() {\n if(!$(this).hasClass('selected_follower'))\n {\n // setup spinner\n var friends_opts = spinner_options();\n var friends_target = document.getElementById('friends_spinner');\n var friends_spinner = new Spinner(friends_opts).spin(friends_target);\n \n $('.user_entry.selected_follower').removeClass('selected_follower');\n $(this).addClass('selected_follower');\n $.get('/dashboard/get_profile', {\n user_id: $(this).attr('user_id')\n }, function (data) {\n $('#friends_content .right').hide();\n $('#friends_content .right').html(data);\n $('#friends_content .right').show(\"fast\");\n }).complete(function(){\n friends_spinner.stop();\n });\n }\n });\n });\n}",
"viewCards() {\n this.cardsViewed = true;\n this.viewConfigCards(); // Subjects/Grades, Schedule, and Service Hrs\n this.viewLocationCards();\n }",
"function draw() {\n\n // Create the endpoint url \n const path = (deckId === '') ? `new/draw/?count=1` : `${deckId}/draw/?count=1`;\n const url = endpoint + path;\n\n // Call the endpoint\n fetch(url)\n .then(response => response.json())\n .then(json => { \n deckId = json.deck_id;\n document.cookie = deckId;\n displayCard(json.cards[0]); // Read the first card\n updateCount(json.remaining); //3. Update the count remaining\n });\n\n}",
"function takeCardAndReplenish(db, card) {\n const rank = card.rank;\n const cards = db.get(['game', 'cards' + rank]);\n let index = -1;\n for(let i = 0; i < cards.length; i ++) {\n if(cards[i].key == card.key) {\n index = i;\n break;\n }\n }\n if(index < 0) {\n return;\n }\n const nextCard = db.get(['game', 'deck' + rank, 0]);\n if(nextCard) {\n db.set(['game', 'cards' + rank, index], nextCard);\n db.set(['game', 'cards' + rank, index, 'status'], 'board');\n } else {\n db.set(['game', 'cards' + rank, index], {\n status: 'empty'\n });\n }\n db.shift(['game', 'deck' + rank]);\n}",
"function updateFollowButton(id,searchId)\n{\n var FollowUnfollow = \"\";\n fetch(`/follow_page/${id}/${searchId}`,{ method:\"POST\", 'Content-Type': 'application/json' })\n .then(res => res.json())\n .then(function(data){\n debugger;\n document.getElementById(\"nbFollowers_id\").innerHTML = data.sNbFollowers;\n\n if(data.bIsFollowing)\n {\n FollowUnfollow = \"Unfollow\";\n }\n else {\n FollowUnfollow = \"Follow\";\n }\n document.getElementById(\"sFollow\").innerHTML = FollowUnfollow;\n })\n .catch((err) => {\n alert(\"Follow Error\");\n })\n}",
"function checkCardsUpdated(){\n\n}",
"function updateFeedAndBank() {\n $('#bank').text(game.bank);\n $('#feedCount').text(game.feed);\n }",
"function handleListarCompeticionesFavoritas(agent) {\n const nickname = agent.parameters.nickname;\n let refFavoritos = db.ref(`users/${nickname}/favoritos/competiciones`);\n return refFavoritos.once('value').then((snapshot) => {\n if (snapshot.exists()) {\n return snapshot.forEach((childSnapshot) => {\n\n var aux = childSnapshot.val();\n let nombre = childSnapshot.key;\n let logo = aux.logo;\n let pais = aux.pais;\n agent.add(new Card({ title: `Nombre: ${nombre}`, imageUrl: logo, text: `País: ${pais}`, buttonText: \"Ver detalles\", buttonUrl: `Quiero información sobre la competición ${nombre}` }));\n agent.add(new Card({ title: `Nombre: ${nombre}`, buttonText: \"Quitar de favoritos\", buttonUrl: `Quiero eliminar la competición ${nombre} de favoritos` }));\n agent.add(new Card({ title: `Clasificación de la ${nombre}`, buttonText: \"Ver clasificación\", buttonUrl: `Ver la clasificación de la ${nombre}` }));\n agent.add(new Card({ title: `Lista de máximos goleadores de la ${nombre}`, buttonText: \"Ver lista de máximos goleadores\", buttonUrl: `Ver los máximos goleadores de la ${nombre}` }));\n agent.setContext({ \"name\": \"Home\", \"lifespan\": 1, \"parameters\": { \"nickname\": nickname } });\n\n });\n } else {\n agent.add(\"Vaya, parece que tu lista de favoritos está vacía. Puedes añadir competiciones a tu lista de favoritos al buscar información sobre ellas.\");\n agent.setContext({ \"name\": \"Home\", \"lifespan\": 1, \"parameters\": { \"nickname\": nickname } });\n }\n });\n }",
"function processCards(){\n setInterval(function () {\n let cardColl = _.at(window,'__dhpwa__.cardCollection');\n if(cardColl && !_.isEmpty(cardColl)){\n push(format(_.uniq(cardColl,'item_id'),'STORY_CARD_VIEW'));\n window.__dhpwa__.cardCollection = [];\n }\n },PROCESS_CARDS_INTERVAL)\n}",
"function refresh() {\n $scope.award = {};\n $scope.awardLocation = {};\n\n getAwardList(personReferenceKey);\n\n\n\n\n }",
"function updateCards(observations) {\n // Remove any current cards\n clearAllCards();\n\n // Populate the page with new cards for all observation data we want to show\n observations.forEach((observation) => {\n const observationCard = buildCardForObservation(observation);\n addCard(observationCard);\n });\n}",
"function followUser() {\n UserService\n .followUser(vm.uid, vm.loggedInUser)\n .then(function (response) {\n console.log(response.data);\n $route.reload();\n });\n }",
"async loadCards() {\n await JsonPlaceholder.get(\"/posts\", {\n params: {\n _start: this.props.cardList.length + 1,\n },\n })\n .then((res) => {\n this.props.fetchCardsSuccess({\n loadMore: !(res.data.length < 10),\n cardList: res.data,\n });\n })\n .catch((err) => {\n this.props.fetchCardsFailed();\n });\n }",
"function igAddToCard (gram) {\n var card = '<div class=\"card card-ig\"><div class=\"profile\"><div class=\"media-type pull-right\">' \n + '<i class=\"fa fa-instagram\"></i></div>' \n + '<div class=\"img-wrap\"><img class= \"img-circle\" src=\"' \n + gram.userPhoto + '\"></div>' \n + '<div class=\"user-wrap\"><h2 class=\"user\">' \n + gram.userName + '</h2><h3 class=\"handle\">@' \n + gram.user + '</h3></div></div><div id=\"ig-' \n + gram.id + '\" class=\"photo\"><img src=\"' \n + gram.photo + '\" /></div><div class=\"text\"><h2 class=\"message\">' \n + gram.text + '</h2><ul class=\"stats\"><li class=\"likes\"><i class=\"fa fa-heart\"></i></span><span class=\"count\">' \n + gram.likes + '</span></li><li class=\"time pull-right\"><span class=\"glyphicon glyphicon-time\"></span><span class=\"ago\">' \n + gram.time + '</span></li></ul></div></div>';\n return card;\n}",
"async function drawCard(){\n if (deckIsEmpty) {\n alert(\"NO CARDS REMAINING\");\n } else { \n const resp = await axios.get(`${CARDSAPI}/${deckID}/draw/?count=1`);\n const newCard = resp.data.cards[0];\n setDrawnCards(cards => [newCard, ...cards]) \n if (resp.data.remaining === 0) setDeckIsEmpty(true);\n }\n }",
"function update_user_elements() {\n $('.echo-item-authorName, .echo-item-avatar').each( function() {\n if(!$(this).hasClass('initialized')) {\n var container = $(this).parents('.echo-item-container');\n \n var userName = container.find('.echo-item-authorName').text();\n var userID = container.find('.echo-item-metadata-userID .echo-item-metadata-value').text();\n \n var url = '/echo2-users.php?user_id=' + UrlEncoderTool.encode(userID) + '&d=' + new Date().getTime();\n \n $(this).html($('<a></a>').attr('href',url).attr('title', 'user page: ' + userName).addClass('echo-linkColor').html($(this).html()));\n $(this).find('img').removeAttr('height');\n $(this).addClass('initialized');\n }\n });\n }",
"function displayNextProfile(){\r\n \r\n //We need to iterate with profiles.next().value as the profile variable is init(set) to the iterator ;so we need to call next here for the current profile:\r\n const currentProfile = profiles.next().value;\r\n console.log(currentProfile);\r\n///Display next profile data\r\nif(currentProfile !== undefined){\r\n //Display Data (except Image)\r\n document.getElementById('profileDisplay').innerHTML = `\r\n <ul class=\"list-group\">\r\n <li class=\"list-group-item\">Name: ${currentProfile.name}</li>\r\n <li class=\"list-group-item\">Age: ${currentProfile.age}</li>\r\n <li class=\"list-group-item\">Gender: ${currentProfile.gender}</li>\r\n <li class=\"list-group-item\">Preference: ${currentProfile.gender} looking for ${currentProfile.lookingfor}</li>\r\n <li class=\"list-group-item\"> Location: ${currentProfile.location}</li>\r\n </ul>\r\n `;\r\n //Display Image\r\n document.getElementById('imageDisplay').innerHTML = `<img src=\"${currentProfile.image}\">`\r\n}else{\r\n////If No more profiles\r\nwindow.location.reload(); ///reload the page to start again\r\n}\r\n\r\n}",
"function prepareLeaderboard() {\r\n\t\t var fsq = require('node-foursquare')(context.foursquare.config);\r\n\t\t fsq.Users.getLeaderboard(\r\n\t\t { neighbors: 2 },\r\n\t\t r.oat,\r\n\t\t function (err,res) {\r\n\t\t if (err) {\r\n\t\t clientResults.log(\"Couldn't get the leaderboard from fsq.\");\r\n\t\t // move on anyway.\r\n\t\t } else {\r\n\r\n\t\t \t// TODO: Sometimes these results are not sorted!\r\n\r\n\t\t var leaders = [];\r\n\t\t if (res && res.leaderboard && res.leaderboard.items) {\r\n\t\t for (var t = 0; t < res.leaderboard.items.length; t++) {\r\n\t\t var item = res.leaderboard.items[t];\r\n\t\t if (item.user && item.scores && item.rank && item.scores.recent) {\r\n\t\t \r\n\t\t // Localization.\r\n\t\t // ---\r\n\t\t // TODO: Note that for localization to work, the \"Me\" \r\n\t\t // string will need to be slightly localized.\r\n\r\n\t\t var leader = {\r\n\t\t name: item.user.relationship == 'self' ? 'Me' : item.user.firstName,\r\n\t\t rank: '#' + item.rank,\r\n\t\t score: item.scores.recent + ' pts',\r\n\t\t photo: item.user.photo,\r\n\t\t id: item.user.id\r\n\t\t };\r\n\t\t leaders.push(leader);\r\n\t\t }\r\n\t\t }\r\n\t\t }\r\n\t\t if (leaders.length > 0) {\r\n\t\t var u = 'http://www.4thandmayor.com/leaderTile.php?';\r\n\t\t for (var y = 0; y < leaders.length; ) {\r\n\t\t var ldr = leaders[y];\r\n\t\t y++;\r\n\r\n\t\t u += \"l\" + y + \"=\" + querystring.escape(ldr.rank + \" \" + ldr.name);\r\n\t\t u += \"&\";\r\n\t\t u += \"l\" + y + \"u=\" + ldr.id;\r\n\t\t u += \"&\";\r\n\t\t u += \"l\" + y + \"p=\" + querystring.escape(ldr.photo);\r\n\t\t u += \"&\";\r\n\t\t u += \"l\" + y + \"score=\" + querystring.escape(ldr.score);\r\n\t\t u += \"&\";\r\n\t\t }\r\n\r\n\t\t // TODO: Consider storing this using task.storage.* instead.\r\n\t\t clientResults.leaderboardImageUri = u;\r\n\r\n\t\t var nextLeaderboardPingTime = dateutil.returnNewDatePlusMinutes(new Date(), context.configuration.constants.REFRESH_LEADERBOARD_MINUTES);\r\n\t\t r.lp = nextLeaderboardPingTime;\r\n\r\n\t\t clientResults.isDirty = true;\r\n\t\t }\r\n\t\t }\r\n\r\n\t\t // should be ready if it worked, let's get the tile out next.\r\n\t\t callback(null, null);\r\n\t\t });\r\n\t\t}",
"function refreshCreditsRemaining() {\n $(\"#credits_remaining\").html(user.creditsRemaining());\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Welcome a new user with a message | function welcomeUser(user) {
user.notify('Welcome ' + user.getName() + '!');
} | [
"function welcomeUser() {\n let greeting = \"No Current User\";\n\n if (isLoggedIn === true) {\n greeting = \"Welcome, \" + currentUser.name;\n }\n\n return greeting;\n }",
"showWelcomeMessage(welcomeMessageMode) {\n Instabug.showWelcomeMessageWithMode(welcomeMessageMode);\n }",
"function showWelcome() {\n\n\tconst welcomeHeader = `\n\n=================================================================\n|| ||\n| Employee Summary Generator |\n|| ||\n=================================================================\n\n`\n\n\tconst welcomeMessage = `\n\nWelcome to the Employee Summary Generator!\nThis application will generate a roster of employee details based on information you provide.\n\n`\n\n\tconsole.clear();\n\n\tconsole.log(colors.brightCyan(welcomeHeader));\n\tconsole.log(colors.brightCyan(welcomeMessage));\n\n}",
"function userLoggedIn() {\n let username = sessionStorage.getItem('username');\n $('#spanMenuLoggedInUser').text(`Welcome, ` + username + '!');\n $('#viewUserHomeHeading').text(`Welcome, ` + username + '!');\n $('.anonymous').hide();\n $('.useronly').show();\n showView('UserHome')\n }",
"setWelcomeMessageMode(welcomeMessageMode) {\n Instabug.setWelcomeMessageMode(welcomeMessageMode);\n }",
"function displayUsername() {\n $navWelcome.children('#nav-user-profile').text(currentUser.username);\n $navWelcome.show();\n }",
"function welcome() {\n console.log(`Hello ${this.name}`);\n}",
"greet() {\n return (`${this.name} offers a greeting in ${this.language}`);\n }",
"function GetWelcomeMessege(name)\n{ \n console.log('Assignment 1: Get Welcome Messege ');\n if(name != null && name != \"\" )\n\t{\n console.log(`Welcome ${name} to Tavisca!`);\n }\n else\n {\n console.log('Name is blank!');\n }\n}",
"botInfo(ctx) {\n Logger.push(`@${ctx.from.username} has just joined!`);\n }",
"function attemptLogin(user, text) {\n if(!/^[a-zA-Z0-9_]+$/.test(text)) {\n user.notify('Sorry, name contains illegal characters.');\n return false;\n }\n\n if(User.getUserByName(text)) {\n user.notify('Sorry, name taken.');\n return false;\n }\n\n user.setName(text);\n return true;\n}",
"_sendWelcomeEmail(model, user) {\n this.log.debug('Sending welcome email to', user.email)\n var link\n if (user.password) {\n link = \"http://\"+application.config.baseUrl+this.baseUrl+\"login\"\n } else {\n link = \"http://\"+application.config.baseUrl+this.baseUrl+\"login-link?token=\"+user.resetPasswordToken\n }\n\n let tempPass = user.tempPassword\n delete user.tempPassword\n templater.render('user-welcome-email', {user, tempPass, link, siteName: application.config.siteName}).then((html) => {\n let fromEmail = (application.config.users && application.config.users.forgotPasswordEmail) ? application.config.users.forgotPasswordEmail : \"noreply@\"+((application.config.mailer && application.config.mailer.emailDomain) || application.config.host)\n return mailer.send(user.email, fromEmail, \"Welcome to \"+application.config.siteName, striptags(html), {html})\n })\n }",
"async function createUserWithMessage() {\n await models.User.create(\n {\n username: 'andyliwr',\n email: 'andyliwr@outlook.com',\n password: '12345678',\n role: 'admin',\n messages: [\n {\n text: 'Hello, GraphQL!',\n createdAt: new Date()\n }\n ]\n },\n {\n include: [models.Message]\n }\n )\n await models.User.create(\n {\n username: 'andyliwr2',\n email: 'andyliwr2@outlook.com',\n password: '12345678',\n role: 'user',\n messages: [\n {\n text: 'I love you!',\n createdAt: new Date()\n }\n ]\n },\n {\n include: [models.Message]\n }\n )\n}",
"function greeting(name){\n return \"Welcome \" + name\n}",
"create(req, res) {\r\n req.session.reset();\r\n db.get(\"SELECT * FROM users WHERE username_text = ?\", req.body.Username, (err, user) => {\r\n if (err) return res.render('login', {\r\n message: \"Username/Password not found. Please try again.\"\r\n });\r\n if (!user) return res.render('login', {\r\n message: \"Username/Password not found. Please try again.\"\r\n });\r\n if (user.password != req.body.Password) return res.render('login', {\r\n message: \"Username/Password not found. Please try again.\"\r\n });\r\n req.session.user_id = user.userID;\r\n req.user = user;\r\n return res.redirect('/');\r\n });\r\n }",
"updateUserToShell() {\n const user = this.authService.readUserFromSessionStorage();\n this.postMessageToShell(MessageType.user, user);\n }",
"function promptUsername() {\n setInputFlow(submitUsername, true);\n\n print('Please enter your username in the box below');\n}",
"renderWelcomeMessage(language) {\n switch(language) {\n case 'en':\n this.setState({welcomeMessage: 'Welcome message from STORMRIDER'});\n break;\n case 'is':\n this.setState({welcomeMessage: 'Bulbulbul asfgwthyt sadasd STORMRIDER'});\n break;\n default:\n break;\n }\n }",
"function greeter (name) {\n return \"hoi \" + name + \"!\";\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Opens the dialog to edit the properties for a folder | editFolder(aTabID, aFolder) {
let folder = aFolder || GetSelectedMsgFolders()[0];
// If a server is selected, view settings for that account.
if (folder.isServer) {
MsgAccountManager(null, folder.server);
return;
}
if (folder.flags & Ci.nsMsgFolderFlags.Virtual) {
// virtual folders get their own property dialog that contains all of the
// search information related to the virtual folder.
this.editVirtualFolder(folder);
return;
}
let title = gMessengerBundle.getString("folderProperties");
function editFolderCallback(aNewName, aOldName, aUri) {
if (aNewName != aOldName)
folder.rename(aNewName, msgWindow);
}
function rebuildSummary(msgFolder) {
if (msgFolder.locked) {
msgFolder.throwAlertMsg("operationFailedFolderBusy", msgWindow);
return;
}
if (msgFolder.supportsOffline) {
// Remove the offline store, if any.
let offlineStore = msgFolder.filePath;
if (offlineStore.exists())
offlineStore.remove(false);
}
msgFolder.msgDatabase.summaryValid = false;
try {
msgFolder.closeAndBackupFolderDB("");
}
catch(e) {
// In a failure, proceed anyway since we're dealing with problems
msgFolder.ForceDBClosed();
}
// these two lines will cause the thread pane to get reloaded
// when the download/reparse is finished. Only do this
// if the selected folder is loaded (i.e., not thru the
// context menu on a non-loaded folder).
if (msgFolder == GetLoadedMsgFolder()) {
gRerootOnFolderLoad = true;
gCurrentFolderToReroot = msgFolder.URI;
}
msgFolder.updateFolder(msgWindow);
}
window.openDialog("chrome://messenger/content/folderProps.xul",
"", "chrome,modal,centerscreen",
{folder: folder, serverType: folder.server.type,
msgWindow: msgWindow, title: title,
okCallback: editFolderCallback, tabID: aTabID,
name: folder.prettyName,
rebuildSummaryCallback: rebuildSummary});
} | [
"editVirtualFolder(aFolder) {\n let folder = aFolder || GetSelectedMsgFolders()[0];\n\n function editVirtualCallback(aURI) {\n // we need to reload the folder if it is the currently loaded folder...\n if (gMsgFolderSelected && aURI == gMsgFolderSelected.URI) {\n // force the folder pane to reload the virtual folder\n gMsgFolderSelected = null;\n FolderPaneSelectionChange();\n }\n }\n window.openDialog(\"chrome://messenger/content/virtualFolderProperties.xul\",\n \"\", \"chrome,modal,centerscreen\",\n {folder: folder, editExistingFolder: true,\n onOKCallback: editVirtualCallback,\n msgWindow:msgWindow});\n }",
"function createSettings() {\n\t\tvar dialog = new Window (\"dialog\", \"Settings\");\n\t\t\n\t\t// filename\n\t\tvar fileNameGroup = dialog.add (\"group\");\n\t\tfileNameGroup.orientation = \"row\";\n\t\tfileNameGroup.alignment = \"center\";\n\t\tvar fileNameLabel = fileNameGroup.add(\"statictext\", undefined, \"File name\");\n\t\tvar fileNameInput = fileNameGroup.add(\"edittext\", [15,30,305,50], fileName);\n\t\t\n\t\t// file size\n\t\tvar fileSizeGroup = dialog.add(\"panel\",undefined,'Size of the mdpi (px)');\n\t\t\n\t\tvar fileSizeRelatedCheckbox = fileSizeGroup.add(\"checkbox\", undefined, \"Same width and height\");\n\t\t\n\t\tvar fileSizeWidthGroup = fileSizeGroup.add (\"group\");\n\t\tfileSizeWidthGroup.orientation = \"row\";\n\t\tfileSizeWidthGroup.alignment = \"center\";\n\t\tvar fileSizeWidthLabel = fileSizeWidthGroup.add(\"statictext\", undefined, \"Width\");\n\t\tvar fileSizeWidthInput = fileSizeWidthGroup.add(\"edittext\", [15,30,60,50], mdpiWidth);\n\t\t\n\t\tvar fileSizeHeightGroup = fileSizeGroup.add (\"group\");\n\t\tfileSizeHeightGroup.orientation = \"row\";\n\t\tfileSizeHeightGroup.alignment = \"center\";\n\t\tvar fileSizeHeightLabel = fileSizeHeightGroup.add(\"statictext\", undefined, \"Height\");\n\t\tvar fileSizeHeightInput = fileSizeHeightGroup.add(\"edittext\", [15,30,60,50], mdpiHeight);\n\t\t\n\t\t// file type\n\t\tvar fileTypeGroup = dialog.add(\"panel\",undefined,'File type');\n\t\tfileTypeGroup.orientation=\"row\";\n\t\tvar pngType=fileTypeGroup.add(\"radiobutton\", undefined, \"png\");\n\t\tpngType.value = isPng;\n\t\tvar jpgType=fileTypeGroup.add(\"radiobutton\", undefined, \"jpg\");\n\t\tjpgType.value = !isPng;\n\t\t\n\t\t// custom folder path\n\t\tvar customFolderPathBt = dialog.add (\"button\", undefined, \"Use custom folder path\");\n\t\t\n\t\t// buttons\n\t\tvar btnGroup = dialog.add (\"group\");\n\t\tbtnGroup.orientation = \"row\";\n\t\tbtnGroup.alignment = \"center\";\n\t\tvar okButton = btnGroup.add (\"button\", undefined, \"OK\");\n\t\tvar cancelButton = btnGroup.add (\"button\", undefined, \"Cancel\");\n\t\t\n\t\t\n\t\t// user interaction functions\n\t\tfileNameInput.onChange = function() {\n\t\t\tfileName = fileNameInput.text;\n\t\t}\n\t\t\n\t\tfileSizeRelatedCheckbox.onClick = function () {\n\t\t\tif (fileSizeRelatedCheckbox.value === true) {\n\t\t\t\tfileSizeHeightInput.text = fileSizeWidthInput.text;\n\t\t\t\tmdpiHeight = mdpiWidth;\n\t\t\t}\n\t\t}\n\t\t\n\t\tfileSizeHeightInput.onChanging = function() {\n\t\t\tif (isNaN(fileSizeHeightInput.text)) {\n\t\t\t\tfileSizeHeightInput.text = mdpiHeight;\n\t\t\t} else {\n\t\t\t\tmdpiHeight = fileSizeHeightInput.text;\n\t\t\t\t// if the size are the same, also change the width\n\t\t\t\tif (fileSizeRelatedCheckbox.value === true) {\n\t\t\t\t\t// don't set again the height value, which will set the width, which will set the height...\n\t\t\t\t\tfileSizeRelatedCheckbox.value = false;\n\t\t\t\t\tfileSizeWidthInput.text = mdpiHeight;\n\t\t\t\t\tmdpiWidth = mdpiHeight;\n\t\t\t\t\tfileSizeRelatedCheckbox.value = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tfileSizeWidthInput.onChanging = function() {\n\t\t\tif (isNaN(fileSizeWidthInput.text)) {\n\t\t\t\tfileSizeWidthInput.text = mdpiWidth;\n\t\t\t} else {\n\t\t\t\tmdpiWidth = fileSizeWidthInput.text;\n\t\t\t\t// if the size are the same, also change the width\n\t\t\t\tif (fileSizeRelatedCheckbox.value === true) {\n\t\t\t\t\t// don't set again the width value, which will set the height, which will set the width...\n\t\t\t\t\tfileSizeRelatedCheckbox.value = false;\n\t\t\t\t\tfileSizeHeightInput.text = mdpiWidth;\n\t\t\t\t\tmdpiHeight = mdpiWidth;\n\t\t\t\t\tfileSizeRelatedCheckbox.value = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tpngType.onClick = function() {\n\t\t\tisPng = pngType.value;\n\t\t}\n\t\t\n\t\tjpgType.onClick = function() {\n\t\t\tisPng = !jpgType.value;\n\t\t}\n\t\t\n\t\tcustomFolderPathBt.onClick = function () {\n\t\t\tvar folderPathTmp = Folder.selectDialog(\"Select folder where you want to put the drawable-mdpi folder and others\");\n\t\t\tif (folderPathTmp != null) {\n\t\t\t\tfolderPath = folderPathTmp;\n\t\t\t}\n\t\t}\n\t\t\n\t\tokButton.onClick = function() {\n\t\t\tdialog.hide();\n\t\t\tsaveAllResources();\n\t\t}\n\t\t\n\t\tdialog.center();\n\t\treturn dialog;\n\t}",
"openProjectOptionsDialog(project) {\n this.projectOptionsSelected = project;\n\n // reset the dialog\n this.shadowRoot.getElementById(\"connected-group-name\").style.removeProperty(\"display\");\n this.shadowRoot.getElementById(\"input-edit-group-name\").style.setProperty(\"display\", \"none\");\n\n this.shadowRoot.getElementById(\"connected-group-project-name\").innerText = project.name;\n this.shadowRoot.getElementById(\"connected-group-name\").innerText = project.groupName;\n\n // open the dialog\n this.shadowRoot.getElementById(\"dialog-project-options\").open();\n }",
"function showLinkDialog(propert_key, title) {\n\tif( typeof title === 'undefined' ) title = 'Save link';\n\t/** Get link form properties\n\t */\n\tvar getLink = function() {\n\t\tvar url = PropertiesService.getDocumentProperties().getProperty(propert_key);\n\t\treturn url ? url : '';\n\t};\n\t\n\tvar save_script = 'google.script.run.showLinkDialog_LinkSave(\\''+propert_key+'\\', document.getElementById(\\'saved-link\\').value);';\n\tvar htmlString = '<link rel=\"stylesheet\" href=\"https://ssl.gstatic.com/docs/script/css/add-ons.css\">'+\n\t\t\t\t\t\t'<style rel=\"stylesheet\">input[type=\"button\"]{margin-right:16px}</style>'+\n\t\t\t\t\t\t'<div>' +\n\t\t\t\t\t\t\t'<input type=\"text\"\tvalue=\"'+getLink()+'\"\tid=\"saved-link\"\tstyle=\"width:100%\" /><br><br>' +\n\t\t\t\t\t\t\t'<input type=\"button\"\tvalue=\"Open\"\tid=\"saved-link-open\"\tonclick=\"'+save_script+'window.open(document.getElementById(\\'saved-link\\').value);google.script.host.close();\"/ class=\"green\">' +\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t'<input type=\"button\"\tvalue=\"Save\"\t\tonclick=\"'+save_script+'google.script.host.close();\" />' +\n\t\t\t\t\t\t\t'<input type=\"button\"\tvalue=\"Remove\"\t\tonclick=\"google.script.run.showLinkDialog_LinkRemove(\\''+propert_key+'\\');google.script.host.close();\" />' +\n\t\t\t\t\t\t'</div>';\n\t\t\t\t \n\tvar htmlOutput = HtmlService.createHtmlOutput(htmlString).setSandboxMode(HtmlService.SandboxMode.IFRAME).setHeight(96);\n\tSpreadsheetApp.getUi().showModalDialog(htmlOutput, title);\n}",
"function browseFolder() \n{\n\t//Is the folder writable/unlocked?\n\tif (isSiteRootSane()) {\n\t\t//Set lib source folder\n\t\tvar libFolder = settings.cssType == SPLIT_CSS ? PREF_SPLIT_JQLIB_SOURCE_FOLDER : PREF_JQLIB_SOURCE_FOLDER;\n\t\t\n\t\t// Call Dw to bring up the browse for folder dialog\n\t\tvar browseRoot = dw.getPreferenceString(PREF_SECTION, libFolder, dw.getConfigurationPath()+\"/\"+assetDir);\n\t\tvar jQuerySourceFolder = dw.browseForFolderURL(dw.loadString(\"Commands/jQM/files/alert/browseFile\"), browseRoot, false);\n\t \n\t\tfindjQMFiles(jQuerySourceFolder);\n\t} else {\n\t\talert(dw.loadString(\"Commands/jQM/files/alert/lockedFolder\"));\n\t}\n}",
"function updateUI() {\n showFolderOrFileContentById(navigationHistory.getCurrentId(), true);\n var treeState = getExplorerState();\n showFoldersTree(treeState);\n }",
"function FilesDlg(form, element,directory, tag_id) {\n tag_id = parseInt(\"0\"+tag_id)*1;\n window.open('?page=filestoragedlg&isOpen=1&form=' + form + '&element=' + element + '&directory=' + directory + '&tag_id=' + tag_id,\n 'FilesDlg', 'menubar=no,width=400,height=400,scrollbars=yes,resizable=no');\n }",
"function showLinkDialog_LinkSave(propert_key, url) {\n\tPropertiesService.getDocumentProperties().setProperty(propert_key, url);\n}",
"function recordsetDialog_setCommandDialogPref(cmdFilename)\r\n{\r\n\tvar cIdx = recordsetDialog.searchByCommand(cmdFilename);\r\n\tif ((cIdx > -1) && (MM.rsTypes[cIdx].saveUI)) {\r\n\t\tdw.setPreferenceString(recordsetDialog.CMD_FILENAME_PREF_SECTION, \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t recordsetDialog.CMD_FILENAME_PREF_KEY, \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t cmdFilename\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t); \r\n\t}\r\n}",
"renameFolder(aFolder) {\n let folder = aFolder || GetSelectedMsgFolders()[0];\n\n let controller = this;\n function renameCallback(aName, aUri) {\n if (aUri != folder.URI)\n Cu.reportError(\"got back a different folder to rename!\");\n\n controller._resetThreadPane();\n let folderTree = GetFolderTree();\n folderTree.view.selection.clearSelection();\n\n folder.rename(aName, msgWindow);\n }\n\n window.openDialog(\"chrome://messenger/content/renameFolderDialog.xul\",\n \"\", \"chrome,modal,centerscreen\",\n {preselectedURI: folder.URI,\n okCallback: renameCallback, name: folder.prettyName});\n }",
"_openDialog() {\n if(this.readonly)\n return\n\n this.colorDialog.color = this.value||this.colorDialog.color;\n this.colorDialog.colors = this.colors||this.colorDialog.colors;\n this.colorDialog.hideAdvanced = this.hideAdvanced;\n this.colorDialog.open();\n }",
"function show_edit_location (location_id) {\n\t\t$(\"#modal_title_location\").html(\"Edit location\");\n\t\t$(\"#location_id\").val(location_id);\n\t\t$(\"#location_name\").val($(\"#location_name_\"+location_id).html());\n\t\t$(\"#location_place\").val($(\"#location_place_\"+location_id).val());\n\t\t$(\"#location_building\").val($(\"#location_building_\"+location_id).val());\n\t\t$(\"#location_floor\").val($(\"#location_floor_\"+location_id).val());\n\t\t$(\"#active\").val($(\"#lactive_\"+location_id).val());\n\t\t$(\"#action\").val(\"edit_location\");\n\t\t$(\"select\").trigger(\"chosen:updated\");\n\t\t$(\"#modal_dialog_location\").modal(\"show\");\n\t}",
"function getDialogPath() {\n var gAuthor = Granite.author,\n currentDialog = gAuthor.DialogFrame.currentDialog, dialogPath;\n\n if (currentDialog instanceof gAuthor.actions.PagePropertiesDialog) {\n var dialogSrc = currentDialog.getConfig().src;\n dialogPath = dialogSrc.substring(0, dialogSrc.indexOf(\".html\"));\n } else {\n var editable = gAuthor.DialogFrame.currentDialog.editable;\n\n if (!editable) {\n console.log(\"EAEM - editable not available\");\n return;\n }\n\n dialogPath = editable.config.dialog;\n }\n\n return dialogPath;\n }",
"updateGridProperties() {\n this.internal.gridPropertiesGUI.modal('show');\n return false;\n }",
"function popupUpload(event, fieldid, serverFolder, uploadPath, stylesheet) {\r\n\tvar width = 400;\r\n\tvar height = 140;\r\n\tvar x = event.screenX - width / 2;\r\n\tvar y = event.screenY - height / 2;\r\n\twindow.open(document.location.origin + contextPath + '/resources/upload.jsp?'\r\n\t\t+ 'fieldid=' + fieldid\r\n\t\t+ '&uploadPath=' + uploadPath\r\n\t\t+ '&serverFolder=' + serverFolder\r\n\t\t+ '&stylesheet=' + contextPath + '/resources/nwu.css',\r\n\t fieldid,\r\n\t \"toolbar=no,menubar=no,status=no,resizable=yes,width=\" + width + \",height=\" + height + \",left=\" + x + \",top=\" + y + \",screenX=\" + x + \",screenY=\" + y);\r\n}",
"function showDirectory(){\n\twindow.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {\n// \talert(\"Root = \" + fs.root.fullPath);\n\t\tvar directoryReader = fs.root.createReader();\n\t\tdirectoryReader.readEntries(success,failDir);\n\t}, function (error) {\n\t\talert(error.code);\n\t});\n\tfunction success(entries) {\n\t\tvar ent=\"<option>Select File</option>\";\n\t\tfor (var i=0; i<entries.length; i++) {\n\t\t\tent += \"<option value=\"+entries[i].name+\">\"+entries[i].name+\"</option>\";\n\t\t}\n\t\t$(\"#loadConfSelect\").html(ent);\t\t\n//\t\talert(\"pasok sa success?\"+ent);\n\t}\n\tfunction failDir(error) {\n\t\talert(\"Failed to list directory contents: \" + error.code);\n\t}\n}",
"function displayChooseProjDialog(resource_id,link_to_project_id) {\r\n\t// If project_id is supplied, then pre-select the drop-down when the dialog appears\r\n\tif (link_to_project_id > 0) {\r\n\t\t$('#choose_project_select').val(link_to_project_id);\r\n\t\t// Make sure current user has access to the project that is current set (if not, don't allow them to change).\r\n\t\tif ($('#choose_project_select').val() != link_to_project_id) {\r\n\t\t\talert('NOTICE: It appears that you do not have access to this particular REDCap project, so you will not be able to modify the link here that points to that project. However, you may delete the link to that project, if you wish.');\r\n\t\t\tenableResourceTableEdit();\r\n\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\tenableResourceTableEdit();\r\n\t// Open the dialog\r\n\t$('#choose_project_div').dialog({ bgiframe: true, modal: true, width: 700, open: function(){fitDialog(this)}, buttons: { \r\n\t\tClose: function() { $(this).dialog('close'); },\r\n\t\tSave: function() { \r\n\t\t\tif ($('#choose_project_select').val().length < 1) {\r\n\t\t\t\talert(\"Please choose a project\");\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\tif (resource_id != 0) {\r\n\t\t\t\t// Edit existing link\r\n\t\t\t\t$.post(app_path_webroot+'ExternalLinks/edit_resource_ajax.php?pid='+pid, { link_to_project_id: $('#choose_project_select').val(), action: 'edit', link_type: 'REDCAP_PROJECT', ext_id: resource_id }, function(data){\r\n\t\t\t\t\tif (data != '0') {\r\n\t\t\t\t\t\t$('#table-resources-parent').html(data);\r\n\t\t\t\t\t\tenableResourceTableEdit();\r\n\t\t\t\t\t\thighlightResourceRow(resource_id);\r\n\t\t\t\t\t\tupdateResourcePanel();\r\n\t\t\t\t\t\t$('#choose_project_div').dialog('close');\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\talert(woops);\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t} else {\r\n\t\t\t\t// Creating new link (will get saved but not here)\r\n\t\t\t\tvar newprojtitle = $(\"#choose_project_select option:selected\").text();\t\r\n\t\t\t\t$('#new_projtitle_id_0').html(newprojtitle);\r\n\t\t\t\t$('#input_Resourceprojectlink_id_0').val( $(\"#choose_project_select\").val() );\r\n\t\t\t\tenableResourceTableEdit();\r\n\t\t\t\t$(this).dialog('close');\r\n\t\t\t}\r\n\t\t} \r\n\t}});\r\n}",
"function newFolderActionHandle(_container, _context, _fileTablePanel){\n\t\t\ton(registry.byId(\"da_newFolderMenuItem\"), \"click\", function(){\n\t\t\t\tvar dialog = registry.byId(\"de_dialog_newFolder\");\n\t\t\t\tdialog.show();\n\t\t\t});\n\n\t\t\t//new folder\n\t\t\ton(registry.byId(\"de_dialog_newFolder_okBtn\"), \"click\", function(){\n\t\t\t\tvar inputValue = registry.byId(\"de_dialog_newFolder_dirName\").value;\n\t\t\t\t\n\t\t\t\tvar cHost = _fileTablePanel.getHost();\n\t\t\t\tvar cPath = _fileTablePanel.getPath();\n\t\t\t\t\n\t\t\t\tvar url = _context.contextPath + \"/webservice/pac/data/action/mkdir?rnd=\" + (new Date()).getTime();\n\t\t\t\tvar path = encodeURIComponent(cPath + \"/\" + inputValue);\n\t\t\t\tvar postData = \"filePath=\" + path + \"&hostName=\" + cHost;\n\n\t\t\t\trequest.post(url, {\n\t\t\t\t\tdata : postData\n\t\t\t\t}).then(function(data) {\n\t\t\t\t\t\tvar dialog = registry.byId(\"de_dialog_newFolder\");\n\t\t\t\t\t\tif(data != null && data != \"\"){\n\t\t\t\t\t\t\tdialog.hide();\n\t\t\t\t\t\t\tshowMessage(data);\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t//close the dialog and refrsh the file table\n\t\t\t\t\t\t\t_fileTablePanel.refresh(cHost, cPath);\n\t\t\t\t\t\t\tdialog.hide();\n\t\t\t\t\t\t}\n\t\t\t\t\t}, function(err) {\n\t\t\t\t\t\tconsole.log(err);\n\t\t\t\t\t}, function(evt) {\n\t\t\t\t\t\t//console.log(evt);\n\t\t\t\t});\n\t\t\t});\n\t\t}",
"function addProject(){\n\n\t\t\t\tvar addProjWindow = new Window(\"palette\", \"Add Project\");\n\n\t\t\t\t// group for custom project\n\t\t\t\tvar customProjGroup = addProjWindow.add(\"group\");\n\t\t\t\t\tcustomProjGroup.orientation = \"column\";\n\t\t\t\t\tcustomProjGroup.alignChildren = ['left', 'fill']\n\n\t\t\t\t\t// Project name group\n\t\t\t\t\tvar projNameGroup = customProjGroup.add(\"group\");\n\n\t\t\t\t\t\tprojNameGroup.add(\"statictext\", undefined, \"Project Name:\")\n\t\t\t\t\t\t// Project Name\n\t\t\t\t\t\tvar projName = projNameGroup.add(\"edittext\", undefined, \"Project Name\");\n\t\t\t\t\t\t\tprojName.characters = 32;\n\n\t\t\t\t\t// Project location group\n\t\t\t\t\tvar projLocGroup = customProjGroup.add(\"group\");\n\n\t\t\t\t\t\tprojLocGroup.add(\"statictext\", undefined, \"Project Location:\")\n\n\t\t\t\t\t\t// Project Location\n\t\t\t\t\t\tvar projLoc = projLocGroup.add(\"edittext\", undefined, \"Project Location\");\n\t\t\t\t\t\t\tprojLoc.characters = 24;\n\n\t\t\t\t\t\tvar getProjLoc = projLocGroup.add(\"button\", undefined, \"...\");\n\t\t\t\t\t\t\tgetProjLoc.preferredSize = [31, 20];\n\n\t\t\t\t// group for buttons\n\t\t\t\tvar addProjBtns = addProjWindow.add(\"group\");\n\n\t\t\t\t\t// button for current project\n\t\t\t\t\tvar setCurProjBtn = addProjBtns.add(\"button\", undefined, \"Set Current\");\n\n\t\t\t\t\t// button to add the project\n\t\t\t\t\tvar addProjBtn = addProjBtns.add(\"button\", undefined, \"Add Project\");\n\t\t\t\t\t\n\t\t\t\t\t// button to cancel\n\t\t\t\t\tvar cancelAddBtn = addProjBtns.add(\"button\", undefined, \"Close\");\n\n\t\t\t\t// ----- SHOW WINDOW -----\n\t\t\t\taddProjWindow.show();\n\t\t\t\t\n\t\t\t\t// ----- Add Project Window Functionality -----\n\t\t\t\tgetProjLoc.onClick = function(){\n\t\t\t\t\tvar getAEP = File.openDialog(\"Please select the location of an AEP.\");\n\t\t\t\t\tif (getAEP != null){\n\n\t\t\t\t\t\tif (getAEP.fsName.split(\".\").pop() == \"aep\"){\n\n\t\t\t\t\t\t\tprojName.text = getAEP.fsName.split(\"/\").pop();\n\t\t\t\t\t\t\tprojLoc.text = getAEP.fsName;\n\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\talert(getAEP.name.split(\".\")[0] + \" is a \" + getAEP.fsName.split(\".\").pop() + \" file. Please select an AEP!\")\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\talert(\"Could not open file. Please make sure you selected something!\")\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tsetCurProjBtn.onClick = function(){\n\n\t\t\t\t\tif (app.project){\n\n\t\t\t\t\t\tprojName.text = String(app.project.file).split(\"/\").pop();\n\t\t\t\t\t\tprojLoc.text = app.project.file;\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\talert(\"Please open a Project!\");\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\taddProjBtn.onClick = function(){\n\n\t\t\t\t\tif (new File(projLoc.text).exists){\n\t\t\t\t\t\tif(projName.text.length > 0 && projName.text != \"Project Name\"){\n\t\t\t\t\t\t\ttheList[projName.text] = projLoc.text;\n\t\t\t\t\t\t\tupdateProjList(getProjectNames(theList));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\talert(\"The name \\'\" + projName.text + \"\\' is not valid. Please choose a better name.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\talert(\"File at \" + projLoc.text + \" does not exist. Please double check that you've selected the correct file.\")\n\t\t\t\t\t}\n\n\t\t\t\t\t\n\t\t\t\t}\n\n\t\t\t\tcancelAddBtn.onClick = function(){\n\n\t\t\t\t\treturn addProjWindow.close();\n\t\t\t\t}\n\n\t\t\t} // ----- End Add Project Window -----"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Append a posting row to an .entryform. | function addPostingRow(form) {
const newPosting = $('#posting-template').children[0].cloneNode(true);
form.querySelector('.postings').appendChild(newPosting);
return newPosting;
} | [
"function createPostRow(postData) {\n var postId = \"post\" + postData.id;\n\n var newTr = $(\"<tr>\");\n newTr.attr('id', postId);\n newTr.data(\"posts\", postData);\n newTr.append(\"<td>\" + postData.title + \"</td>\");\n newTr.append(\"<td>\" + postData.body + \"</td>\");\n newTr.append(\"<td><button data-toggle='modal' class='btn-success' id='editBtn' href='#editPost'>Edit Post</button></td>\");\n newTr.append(\"<td><button data-toggle='modal' class='btn-danger' id='completeBtn' href='#completePost'>Complete Post</button></td>\");\n return newTr;\n }",
"function postEntries(entries){\n\tvar display = document.getElementById(\"display\");\n\tvar newSection = document.createElement(\"section\");\n\tvar header = document.createElement(\"h2\");\n\tvar deleteButton = document.createElement(\"button\");\n\tdeleteButton.innerHTML = \"X\";\n\tdeleteButton.setAttribute(\"class\", \"close\");\n\tnewSection.appendChild(deleteButton);\n\tdeleteButton.addEventListener(\"click\", function(){\n\t\tdeletePost(entries.Name);\n\t});\n\theader.innerHTML = entries.Name;\n\tnewSection.appendChild(header);\n\n\tfor(var key in entries) {\n\t\tlet container = document.createElement(\"div\");\n\t\tcontainer.innerHTML = `<h5>${key}:</h5> ${entries[key]}`;\n\t\tnewSection.appendChild(container);\n\t}\n\tdisplay.appendChild(newSection);\n}",
"function addBlogPost() {\n clearDialogInputs();\n showDialog(blogPosts, \"add\");\n}",
"addEntryView(entryView) {\n const entry = entryView.model;\n\n this._entryViews.push(entryView);\n this._entryViewsByID[entry.id] = entryView;\n this.model.addEntry(entry);\n\n if (this._rendered) {\n entryView.render();\n }\n }",
"function addFields () {\n\t\n\t$(\"#contestantsForm\").append('<input type=\"text\" /><br/><input type=\"text\" /><br/>');\n}",
"static add(entry, type = null){\n\t\tlet kparams = {};\n\t\tkparams.entry = entry;\n\t\tkparams.type = type;\n\t\treturn new kaltura.RequestBuilder('baseentry', 'add', kparams);\n\t}",
"function addRecord() {\r\n var sel = \"#searchresults .section-content\";\r\n $(sel).append(\"<tr></tr>\");\r\n sel = sel + \" tr:last\";\r\n \r\n var id = $(this).find(\"applicantId\").text();\r\n addCell(sel, id);\r\n \r\n var fullName = $(this).find(\"firstName\").text() + \" \" + $(this).find(\"lastName\").text() \r\n addCell(sel, \"<a id=\" + id + \" href='#details'>\" + fullName + \"</a>\");\r\n \r\n var position = $(this).find(\"title\").text();\r\n addCell(sel, position);\r\n \r\n var dateApplied = $.format.date($(this).find(\"dateApplied\").text(), \"dd.MM.yyyy\");\r\n addCell(sel, dateApplied);\r\n \r\n var status = $(this).find(\"status\").text();\r\n addCell(sel, status);\r\n}",
"function addMetadataRow(form) {\n const newMetadata = $('#metadata-template').children[0].cloneNode(true);\n form.querySelector('.metadata').appendChild(newMetadata);\n return newMetadata;\n}",
"function handleFormSubmit() {\n\t// Get values of inputs\n\t// Pass values to addNewPost()\n var inputName = document.getElementById(\"input-username\").value;\n var inputCaption = document.getElementById(\"input-caption\").value;\n var inputPicture = document.getElementById(\"input-picture\").value;\n addNewPost(inputName, inputPicture, inputCaption);\n}",
"function addEventRow(date) {\n var row = document.createElement(\"div\");\n row.isNewRow = !date;\n var labelInput = document.createElement(\"input\");\n labelInput.type = \"text\";\n labelInput.className = \"editEventLabel\";\n labelInput.value = date ? date.shortLabel : \"\";\n labelInput.placeholder = date ? date.shortLabel : \"New Event\";\n labelInput.onchange = changeEventHandler;\n row.appendChild(labelInput);\n var dateInput = document.createElement(\"input\");\n dateInput.type = \"text\";\n dateInput.className = \"editEventDate\";\n dateInput.placeholder = date ? dateFormat(date.value, \"mmm dS, yyyy\") : \"Date\";\n var picker = new Pikaday({ field: dateInput });\n pickers.push(picker);\n if (date) picker.setDate(date.value);\n dateInput.onchange = changeEventHandler;\n row.appendChild(dateInput);\n var deleteButton = document.createElement(\"a\");\n deleteButton.innerHTML = \"✖\"\n deleteButton.className = \"deleteButton\";\n deleteButton.onclick = deleteEventHandler;\n deleteButton.style.display = date ? 'inline' : 'none';\n row.deleteButton = deleteButton;\n row.appendChild(deleteButton);\n editor.appendChild(row);\n }",
"function addEntry() {\n inq.prompt({\n name: \"addChoice\",\n type: \"rawlist\",\n message: \"What would you like to add?\",\n choices: [\n \"employee\",\n \"role\",\n \"department\",\n \"return to start\"\n ]\n // switch cases to draw in questions, then answers are pushed to DB rather than array. INSERT command.\n }).then(answer => {\n console.log(\"You chose: \" + JSON.stringify(answer));\n switch (answer.addChoice) {\n case \"employee\":\n addEmployee();\n break;\n\n case \"role\":\n addRole();\n break;\n\n case \"department\":\n addDepartment();\n break;\n\n case \"return to start\":\n startPage();\n\n }\n });\n}",
"static addContent(entryId, resource){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\tkparams.resource = resource;\n\t\treturn new kaltura.RequestBuilder('baseentry', 'addContent', kparams);\n\t}",
"function addJobRow(data)\n{\n var node = document.getElementById(\"jobs-table-body\");\n addJobRowAt(node,data);\n}",
"function addAddressForm($formPlaceholder, rows) {\n updateAddress = false;\n // clears div element\n $formPlaceholder.empty();\n\n const $form = $('<form/>', {\n class: 'form',\n id: addressFormId\n });\n\n $idAddressInput = $('<input/>',{\n type: 'hidden',\n id: 'id',\n name: 'addressId'\n });\n $form.append($idAddressInput);\n\n $formPlaceholder.append($form);\n appendRows($form, rows);\n appendButton($form, \"Register new Address\", true, true);\n}",
"function createNewPostPage(e){\n\t\te.preventDefault();\n\t\t// If the user clicked the button with id newPost, then display the posting page on the right part of the screen.\n\t\tif (e.target.id == 'newPost'){\n\t\t\tmainContent.innerHTML = `\n\t\t\t\t<form>\n\t\t\t\t\t<p class=\"newPostPageText\">Title: </p> <textarea id=\"newPostTitle\"></textarea><br>\n\t\t\t\t\t<p class=\"newPostPageText\">Content:</p> <textarea id=\"newPostContent\"></textarea><br>\n\t\t\t\t\t<button id=\"submitPostButton\" onclick=\"location.href = '/forum/webpage';\">Post</button>\n\t\t\t\t</form>\n\t\t\t`\n\t\t\treplyBlock.innerHTML = `\n\t\t\t<p class=\"readTerms\">\n\t\t\tPlease do not post NSFW material in the forum.\n\t\t\t<br> <br>\n\t\t\tAny NSFW material and its corresponding post/reply will be deleted.\n\t\t\t</p>\n\t\t\t`\n\t\t}\n\t}",
"function createNewRow(post) {\n //CREATE NEW post card\n var newPostCard = $(\"<div>\");\n newPostCard.addClass(\"card m-2\");\n\n //CREATE NEW post card img\n var newPostCardImg = $(\"<img>\");\n newPostCardImg.addClass(\"card-img-top\");\n\n //CREATE NEW post card body\n var newPostCardBody = $(\"<div>\");\n newPostCardBody.addClass(\"card-body\");\n\n //CREATE NEW post title\n var newPostTitle = $(\"<h5>\");\n newPostTitle.addClass(\"card-title\");\n\n //CREATE NEW post date\n var newPostDate = $(\"<p>\");\n newPostDate.addClass(\"card-text\");\n\n //CREATE NEW post time\n var newPostTime = $(\"<small>\")\n newPostTime.addClass(\"text-muted\");\n\n //CREATE NEW card text\n var newPostCardText = $(\"<p>\");\n newPostCardText.addClass(\"card-text\");\n\n //CREATE NEW username\n var userName = $(\"<p>\").text(post.Blogger.name);\n userName.addClass(\"username\");\n\n var upvoteImg = $(\"<img>\").attr('src', \"assets/images/bone.jpg\");\n upvoteImg.addClass(\"bone\");\n\n newPostTitle.text(post.title + \" \"); //grab title from post\n newPostCardText.text(post.body); //grab body from post\n\n // Formatted date with moments\n formattedDate = post.createdAt\n formattedDate = moment(formattedDate).format(\"MMMM Do YYYY, h:mm:ss a\")\n\n newPostTime.text(formattedDate); //grab created at from post\n newPostDate.append(newPostTime);\n newPostCardImg.attr('src', post.image);\n\n //CREATE NEW upvote button\n var likeBtn = $(\"<button>\");\n likeBtn.addClass(\"btn-sm btn-primary\");\n\n //CREATE NEW like counter\n var newPostLikes = $(\"<small>\");\n newPostLikes.attr('id', post.id);\n newPostLikes.text(post.likes);\n\n // Determine if user has already liked post and adjust like button as necessary\n if (post.Likes.length != 0) {\n likeBtn.text(\"Dislike\");\n likeBtn.addClass(\"downvote\");\n likeBtn.data(\"like\", post.Likes[0].id);\n } else {\n likeBtn.text(\"Like\");\n likeBtn.addClass(\"upvote\");\n }\n\n likeBtn.attr('value', post.id);\n\n // Appends all created elements to the new post card\n newPostCardBody.append(newPostTitle, newPostCardText, newPostDate, newPostLikes, likeBtn, upvoteImg, userName);\n newPostCard.append(newPostCardImg, newPostCardBody);\n newPostCard.data(\"post\", post);\n\n return newPostCard;\n}",
"static add(userEntry){\n\t\tlet kparams = {};\n\t\tkparams.userEntry = userEntry;\n\t\treturn new kaltura.RequestBuilder('userentry', 'add', kparams);\n\t}",
"function editEntry(ENTRY){\n // making entry the variable that represents the entry id which includes amount, name,type\n let entry = ENTRY_LIST[ENTRY.id];\n // if the entry type is an input, we are going to update the item name and cost in the input section\n if (entry.type == \"inputs\"){\n itemName.value = entry.title;\n itemCost.value = entry.amount;\n }\n // run the delete entry function again so you can delete the previous entry before you add a new edited entry\n deleteEntry(ENTRY);\n }",
"function insertJournalEntry(doc) {\n var html = '';\n html += '<tr name=\"journal_entry_metadata\" class=\"row-vm journal_view_header\" data-id=\"' + doc._id + '\">';\n html += '<td>' + ++glob_journal_counter + '</td>';\n html += '<td>' + escapeHtml(doc.author) + '</td>';\n html += '<td>' + wordwrap(escapeHtml(doc.subject), 60, '<br />', 1) + '</td>';\n html += '<td>' + moment(doc.event_time).format('YYYY/MM/DD HH:mm:ss ZZ') + '</td>';\n html += '<td title=\"' + doc.classification + '\">' + classReplacement(doc.classification) + '</td>';\n html += '<td> </td>'; // Here comes the number of comments\n html += '<td> </td>'; // Here comes the number of actions\n html += '<td title=\"YYYY-MM-DD HH:MM:SS TZ (Difference from external and local time)\" nowrap>' + moment(doc.added_timestamp_local).format('YYYY/MM/DD HH:mm:ss ZZ');\n \n // If the doc doesn't have Internet time, then we display \"N/A\" in the offset\n if (doc.added_timestamp_external) {\n offset = getTimeOffset(doc.added_timestamp_external, doc.added_timestamp_local);\n html += ' (' + (offset >= 0? '+' :'') + Math.round(offset / 1000) + ')';\n } else {\n html += ' (N/A)';\n }\n \n html += '</td>';\n html += '</tr>';\n html += '<tr name=\"journal_entry_content\" class=\"row-details expand-child\" data-id=\"' + doc._id + '\">';\n html += '<td class=\"journal_view_content\" colspan=\"8\">' + wordwrap(doc.content, 120, '<br />', 1);\n \n if (doc.keywords) {\n html += ' <span class=\"keywords\">(' + escapeHtml(doc.keywords) + ')</span>';\n }\n \n html += '</td>';\n html += '</tr>';\n html += '<tr name=\"journal_entry_appendices\" class=\"expand-child\" data-id=\"' + doc._id + '\">';\n html += '<td data-id=\"' + doc._id + '\" colspan=\"8\" style=\"border: 0px;\">';\n \n // Appendix table\n html += '<table name=\"table_appendix\" data-id=\"' + doc._id + '\" style=\"display:none;\" class=\"tablesorter-child\">';\n html += '<thead>';\n html += '<tr>';\n html += '<th><span>Author</span></th>';\n html += '<th><span>Comment</span></th>';\n html += '<th><span>Marked solved by</span></td>';\n html += '<th><span>Attachment / Deadline</span></th>';\n html += '<th><span>Added Time (Offset)</span></th>';\n html += '<th>Goto</th>';\n html += '</tr>';\n html += '</thead>';\n html += '<tbody>';\n html += '</tbody>';\n html += '</table>';\n\n html += '</td>';\n html += '</tr>';\n html += '<tr name=\"journal_entry_appendix_form\" class=\"row-details expand-child\" data-id=\"' + doc._id + '\">';\n html += '<td name=\"appendix_form\" data-id=\"' + doc._id + '\" colspan=\"8\">';\n \n // Appendix submission form\n html += '<table name=\"table_appendix_form\" data-id=\"' + doc._id + '\" style=\"margin-top:20px; display:none;\">';\n html += '<tr>';\n html += '<td>';\n html += '<form class=\"add_appendix\" id=\"' + doc._id + '\" method=\"post\" action=\"\" enctype=\"multipart/form-data\">';\n html += '<input id=\"add_appendix_refers_to\" type=\"hidden\" value=\"' + doc._id + '\" />';\n html += '<select id=\"add_appendix_type\" data-id=\"' + doc._id + '\">';\n html += '<option value=\"comment\" default>Comment</option>';\n html += '<option value=\"action\">Action</option>';\n html += '</select><br />';\n html += '<div class=\"row\">';\n html += '<div style=\"float:left;\" class=\"col-md-4\">';\n html += '<textarea id=\"add_appendix_cont\" style=\"resize: vertical;\" cols=\"80\" rows=\"4\" class=\"form-control\" placeholder=\"Content\"></textarea>';\n html += '</div>';\n html += '<input id=\"_id\" name=\"_id\" type=\"hidden\" />';\n html += '<input id=\"_rev\" name=\"_rev\" type=\"hidden\" />';\n html += '<input id=\"_db\" name=\"_db\" type=\"hidden\" value=\"journal\" />';\n \n html += '<div name=\"add_appendix_type_action\" style=\"display:none;\" class=\"col-md-4\" data-id=\"' + doc._id + '\">';\n html += '<div class=\"input-group\">';\n html += '<span class=\"input-group-addon\">Add a deadline</span>';\n html += '<input id=\"add_appendix_deadline\" placeholder=\"yyyy/mm/dd hh:mm:ss\" type=\"text\" class=\"form-control\" size=\"33\" />';\n html += '</div>';\n html += '<div class=\"input-group\">';\n html += '<span class=\"input-group-addon\">Who is responsible</span>';\n html += '<input id=\"add_appendix_responsible\" placeholder=\"Username, real name, role etc\" size=\"33\" type=\"text\" class=\"form-control\" />';\n html += '</div>';\n html += '</div>';\n \n html += '<div name=\"add_appendix_type_comment\" class=\"col-md-4\" data-id=\"' + doc._id + '\">';\n html += '<span class=\"label label-secondary\">Upload file or use filed copy</span>';\n html += '<div class=\"input-group\">';\n html += '<span class=\"input-group-btn\">';\n html += '<span class=\"btn btn-secondary btn-file\">';\n html += 'Browse… <input id=\"_attachments\" name=\"_attachments\" type=\"file\" class=\"form-control\" style=\"width:100%;\" />';\n html += '</span>';\n html += '</span>';\n html += '<input id=\"add_attachment_filename_label\" type=\"text\" class=\"form-control\" readonly>';\n html += '</div>';\n html += '<div class=\"input-group\">';\n html += '<span class=\"input-group-addon\">Filed copy</span>';\n html += '<span class=\"input-group-addon\"><input id=\"add_appendix_use_filed_copy\" type=\"checkbox\"/></span>';\n html += '<input id=\"add_appendix_filed_copy\" type=\"text\" value=\"' + randStr(5) + '\" size=\"28\" readonly class=\"text-center form-control\"/>';\n html += '</div>';\n html += '</div>';\n \n html += '<div style=\"float:left; padding-left:3%;\">';\n html += '<input name=\"appendix_submit_button\" type=\"submit\" class=\"btn btn-secondary\" class=\"Submit\" value=\"Add comment\" data-id=\"' + doc._id + '\"/>';\n html += '</div>';\n\n html += '</div>';\n html += '</form>';\n html += '</td>';\n html += '</tr>';\n html += '</table>';\n \n html += '</td>';\n html += '</tr>';\n $('#table_journal > tbody').append(html);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
parse a quotedfield character | function qfParseChar() {
if (curCh === '"') {
inValue = !inValue;
return;
}
if (inValue) {
value += curCh;
return;
}
if (curCh === ',') {
addValue();
}
} | [
"function nqfParseChar() {\n if (escape) {\n value += curCh;\n escape = false;\n } else if (curCh === '\\\\') {\n escape = true;\n } else if (curCh === ',') {\n addValue();\n } else {\n value += curCh;\n }\n }",
"visitQuoted_string(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function jsParseSpChr(argString) {\n var parsedString = argString.replace(/[']/g,\"\\'\");\n parsedString = argString.replace(/[\"]/g,\"\\\"\");\n return parsedString;\n }",
"function parsestr (c, s) {\n var encodeUtf8 = function (s) {\n return unescape(encodeURIComponent(s));\n };\n var decodeUtf8 = function (s) {\n return decodeURIComponent(escape(s));\n };\n var decodeEscape = function (s, quote) {\n var d3;\n var d2;\n var d1;\n var d0;\n var c;\n var i;\n var len = s.length;\n var ret = \"\";\n for (i = 0; i < len; ++i) {\n c = s.charAt(i);\n if (c === \"\\\\\") {\n ++i;\n c = s.charAt(i);\n if (c === \"n\") {\n ret += \"\\n\";\n }\n else if (c === \"\\\\\") {\n ret += \"\\\\\";\n }\n else if (c === \"t\") {\n ret += \"\\t\";\n }\n else if (c === \"r\") {\n ret += \"\\r\";\n }\n else if (c === \"b\") {\n ret += \"\\b\";\n }\n else if (c === \"f\") {\n ret += \"\\f\";\n }\n else if (c === \"v\") {\n ret += \"\\v\";\n }\n else if (c === \"0\") {\n ret += \"\\0\";\n }\n else if (c === '\"') {\n ret += '\"';\n }\n else if (c === '\\'') {\n ret += '\\'';\n }\n else if (c === \"\\n\") /* escaped newline, join lines */ {\n }\n else if (c === \"x\") {\n d0 = s.charAt(++i);\n d1 = s.charAt(++i);\n ret += String.fromCharCode(parseInt(d0 + d1, 16));\n }\n else if (c === \"u\" || c === \"U\") {\n d0 = s.charAt(++i);\n d1 = s.charAt(++i);\n d2 = s.charAt(++i);\n d3 = s.charAt(++i);\n ret += String.fromCharCode(parseInt(d0 + d1, 16), parseInt(d2 + d3, 16));\n }\n else {\n // Leave it alone\n ret += \"\\\\\" + c;\n // goog.asserts.fail(\"unhandled escape: '\" + c.charCodeAt(0) + \"'\");\n }\n }\n else {\n ret += c;\n }\n }\n return ret;\n };\n\n //print(\"parsestr\", s);\n\n var quote = s.charAt(0);\n var rawmode = false;\n var unicode = false;\n\n // treats every sequence as unicodes even if they are not treated with uU prefix\n // kinda hacking though working for most purposes\n if((c.c_flags & Parser.CO_FUTURE_UNICODE_LITERALS || Sk.python3 === true)) {\n unicode = true;\n }\n\n if (quote === \"u\" || quote === \"U\") {\n s = s.substr(1);\n quote = s.charAt(0);\n unicode = true;\n }\n else if (quote === \"r\" || quote === \"R\") {\n s = s.substr(1);\n quote = s.charAt(0);\n rawmode = true;\n }\n goog.asserts.assert(quote !== \"b\" && quote !== \"B\", \"todo; haven't done b'' strings yet\");\n\n goog.asserts.assert(quote === \"'\" || quote === '\"' && s.charAt(s.length - 1) === quote);\n s = s.substr(1, s.length - 2);\n if (unicode) {\n s = encodeUtf8(s);\n }\n\n if (s.length >= 4 && s.charAt(0) === quote && s.charAt(1) === quote) {\n goog.asserts.assert(s.charAt(s.length - 1) === quote && s.charAt(s.length - 2) === quote);\n s = s.substr(2, s.length - 4);\n }\n\n if (rawmode || s.indexOf(\"\\\\\") === -1) {\n return strobj(decodeUtf8(s));\n }\n return strobj(decodeEscape(s, quote));\n}",
"tokenizeString(offset) {\n const quotation = this.cssText[offset];\n let escaped = false;\n const start = offset;\n let character;\n while (character = this.cssText[++offset]) {\n if (escaped) {\n escaped = false;\n continue;\n }\n if (character === quotation) {\n ++offset;\n break;\n }\n if (character === '\\\\') {\n escaped = true;\n }\n }\n return new token_1.Token(token_1.Token.type.string, start, offset);\n }",
"function isPhoneNumberSeparatorChar(char) {\n return separatorCharRe.test(char);\n }",
"function getDelimiter(theForm){\n var retVal;\n var selInd = theForm.Delimiter.selectedIndex;\n\n switch (selInd){\n case 0:\n\t retVal = \"\\t\";\n\t\t break;\n\t case 1:\n\t retVal = \" \";\n\t\t break;\n\t case 2:\n\t retVal = \",\";\n\t\t break;\n\t case 3:\n\t retVal = \";\";\n\t\t break;\n\t case 4:\n\t retVal = \":\";\n\t\t break;\n }\n return retVal;\n}",
"function inString (delimiter, previousTokenizer) {\n return function (stream, state) {\n if (!state.escapeNext && stream.eat(delimiter)) {\n state.tokenize = previousTokenizer;\n } else {\n if (state.escapeNext) {\n state.escapeNext = false;\n }\n\n var ch = stream.next();\n\n // Take into account the backslash for escaping characters, such as\n // the string delimiter.\n if (ch == \"\\\\\") {\n state.escapeNext = true;\n }\n }\n\n return \"string\";\n };\n }",
"function whitespace(character) {\n return re$2.test(\n typeof character === 'number' ? fromCode(character) : character.charAt(0)\n )\n }",
"function escapeCSVstring (str) {\n if (/[\";]/.test(str)) {\n return `\"${str.replace(/\"/g, '\"\"')}\"`;\n }\n return str || '';\n}",
"encodeSpecials() {\n const value = this.value;\n const regex = /(\\'|\"|\\\\x00|\\\\\\\\(?![\\\\\\\\NGETHLnlr]))/g;\n return value.replace(regex, '\\\\\\\\$0');\n }",
"function addQualifiers(cellData,delimiter){\n \n var dataLen = cellData.length;\n var qualifier = '\"' //qualifier is double quotes\n var counter=0;\n var i; \n var currChar;\n var bSurroundWithQualifier = false;\n \n //precede all double quotes (\") with another, so:\n // \" --> \"\"\n cellData = cellData.replace(/\"/g, '\"\"'); \n\n //surround any word containing comma,quotes,or delimiters with double quotes\n dataLen = cellData.length;\n \n for (i=0;i<dataLen;i++){\n if ( cellData.charAt( i ) == \",\" ||\n\t cellData.charAt( i ) == qualifier ||\n\t\t\tcellData.charAt( i ) == delimiter ){\n\t \n\t bSurroundWithQualifier = true;\n\t\t break;\n\t\t\t}\n }\n \n if (bSurroundWithQualifier)\n cellData = qualifier + cellData + qualifier;\n\t \n return cellData;\n \n}",
"function isValidDelim(state, pos) {\n let max = state.posMax, can_open = true, can_close = true;\n const prevChar = pos > 0 ? state.src.charCodeAt(pos - 1) : -1, nextChar = pos + 1 <= max ? state.src.charCodeAt(pos + 1) : -1;\n // Check non-whitespace conditions for opening and closing, and\n // check that closing delimeter isn't followed by a number\n if (prevChar === 0x20 /* \" \" */ ||\n prevChar === 0x09 /* \\t */ ||\n (nextChar >= 0x30 /* \"0\" */ && nextChar <= 0x39) /* \"9\" */) {\n can_close = false;\n }\n if (nextChar === 0x20 /* \" \" */ || nextChar === 0x09 /* \\t */) {\n can_open = false;\n }\n return {\n can_open: can_open,\n can_close: can_close,\n };\n}",
"function _fixQuotes(data) {\n var aaIndex=[],msIndex=[];\n var mapping = data.mapping;\n var fields = data.fields;\n var table = data.table;\n var distinguish = function(dataName){\n var indexName=[];\n dataName.forEach(function(ds){\n mapping[ds].forEach(function(dimension){\n fields.forEach(function(field,index){\n if(dimension===field){\n indexName.push(index);\n }\n })\n })\n })\n return indexName;\n };\n //distinguish the aa from the field\n aaIndex = distinguish(_cs.dataTypeName.dimensionName);\n msIndex = distinguish(_cs.dataTypeName.measureName);\n //add quotes\n for(i=0;i<aaIndex.length;i++){\n for(j=0;j<table.length;j++){\n if((typeof table[j][aaIndex[i]])==='number'){\n data.table[j][aaIndex[i]]=table[j][aaIndex[i]]+\"\"; //float2string\n }\n }\n }\n //remove quotes\n for(i=0;i<msIndex.length;i++){\n for(j=0;j<table.length;j++){\n if((typeof Number(table[j][msIndex[i]]))==='number'){\n data.table[j][msIndex[i]]=Number(table[j][msIndex[i]]); //string2float\n }\n }\n }\n return data;\n }",
"function isAlphanum(c) {\n\treturn c != EOF && (ALNUM.indexOf(c) !== -1 || c.charCodeAt(0) > 126);\n }",
"function splitWithEscape(value, splitChar, escapeChar) {\n var results = [];\n var escapeMode = false;\n var currentResult = \"\";\n for (var pos = 0; pos < value.length; pos++) {\n if (!escapeMode) {\n if (value[pos] === splitChar) {\n results.push(currentResult);\n currentResult = \"\";\n } else if (value[pos] === escapeChar) {\n escapeMode = true;\n } else {\n currentResult += value[pos];\n }\n } else {\n currentResult += value[pos];\n escapeMode = false;\n }\n }\n if (currentResult !== \"\") {\n results.push(currentResult);\n }\n return results;\n }",
"function getSongFromQuotedTitle(vidTitle, quoteString) {\r\n\tvar song = new Object();\r\n\tsong.title = stringBetweenChars(vidTitle, quoteString);\r\n\tvar regex = new RegExp(quoteString + song.title + quoteString);\r\n\tsong.artist = vidTitle.replace(regex, \"\");\r\n\treturn song;\r\n}",
"handleQuoteInput(e) {\n this.setState({ quote: e.target.value });\n }",
"function stateMentionTextChar(stateMachine, char) {\n if (isMentionTextChar(char)) ;\n else if (alphaNumericAndMarksRe.test(char)) {\n // Char is invalid for a mention text char, not a valid match.\n // Note that ascii alphanumeric chars are okay (which are tested\n // in the previous 'if' statement, but others are not)\n remove(stateMachines, stateMachine);\n }\n else {\n captureMatchIfValidAndRemove(stateMachine);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Call to action at the beginning of every turn this would be the main function, which in turn calls upon other potential behaviours; action determined by positioning random yet deterministic need to figure out a way to define neighbors add bite, fight, etc as object methods | function action(){
for (var neighbor in neighbors){
if(agent.type === 'Zombie' && neighbor.type === 'Human'){
bite(neighbor);
}
else if(agent.type === 'Zombie' && neighbor.type === 'Zombie'){
agent.move();
}
else if(agent.type === 'Human' && neighbor.type === 'Zombie'){
fight(neighbor);
}
else if(agent.type === 'Human' && neighbor.type === 'Human'){
agent.move();
}
}
return neighbors;
} | [
"function takeAIturn () {\n const ships = state.shipArray.filter(s => s.owner === state.playerTurn)\n const viewHexes = Object.entries(getUpdatedViewMask(state)).filter(([k, v]) => v > 1).map(([k, v]) => Hex.getFromID(k))\n\n ships.forEach(ship => {\n for (let i = 0; i < 5; i++) {\n const { attacks, moves } = findPossibleActions(ship.hex, ship)\n if (attacks.length && Math.random() > 0.5) {\n const attack = attacks[Math.floor(Math.random() * attacks.length)]\n applyDamage(ship, getShipOnHex(attack), true, getTerrainDefVal(getShipOnHex(attack), attack))\n state.history[subTurn()].push({ type: 'attack', rand: Math.random(), path: [attack, ship.hex] })\n } else if (moves.length && Math.random() > 0.5) {\n const [move, ...hist] = moves[Math.floor(Math.random() * moves.length)]\n if (!getTerrainDamage(ship, move) || Math.random() > 0.5) {\n ship.hex = move\n applyTerrainDamage(ship, getTerrainDamage(ship, move))\n state.history[subTurn()].push({ type: 'move', rand: Math.random(), path: [move, ...hist] })\n }\n }\n }\n })\n\n const tech = data.techs[Math.floor(Math.random() * data.techs.length)]\n const player = state.playerData[state.playerTurn]\n\n if (!player.tech[tech.tech] && player.money >= tech.cost && Math.random() > 0.5) {\n player.tech[tech.tech] = true\n player.money -= tech.cost\n }\n\n viewHexes.forEach(hex => {\n const menu = makeBuildBar(hex)\n if (menu.length && Math.random() > 0.5) {\n const choice = menu[Math.floor(Math.random() * menu.length)]\n onTopPanelItemClicked(choice, hex)\n }\n })\n}",
"function battleRound(){\n chooseAction1();\n chooseAction2();\n}",
"function RobotAction()\n{\n\tif(roboActionArray.length > 0)\n\t{\n\t\trobotBusy = true;\n\t\tRobotActionName = roboActionArray.Pop();\n\t\tvar logString = \"{\"+boardPosition.X+\",\"+boardPosition.Y+\",\"+facing+\"} - \"+ RobotActionName;\n\t\tif(RobotActionName != \"\")\n\t\t\tlastPath += logString + '\\n';\n\t\t\n\t\tswitch(RobotActionName)\n\t\t{\n\t\t\tcase \"Forward\": MoveForward(); break;\n \t\t\tcase \"Backward\" : MoveBackward();\tbreak;\n \t\t\tcase \"Turn Right\" : RotateRight(); break;\n \t\t\tcase \"Turn Left\" : RotateLeft(); break;\n \t\t\tcase \"Jump\" : Jump(); break;\n \t\t\tcase \"Pick Up/Put Down\": PickUp(); break;\n \t\t\t//case \"Set Step\": PlaceStep(); break;\n \t\t\tcase \"Place Switch\": PlaceSwitch(); break;\n \t\t\tcase \"Place Box\": PlaceBox(); break;\n \t\t\tcase \"Set Spawn\": SetSpawn(); break;\n \t\t\tcase \"Raise Ground\": PlaceStep(); break;\n \t\t\tcase \"Lower Ground\": RemoveStep(); Debug.Log(\"blam\"); break;\n case \"HeavyBox\": PlaceHeavyBox(); break;\n \t\t\tcase \"Activate\" : Activate(); break;\n \t\t\tcase \"Error\" : ErrorOut(\"WAY too many instructions! Check your loops and recursions...\"); break;\n\t\t\tcase \"\" : break;\n \t\t\tdefault : Debug.Log(\"error: illegal action type \" + RobotActionName);\n\t\t}\n\t}\n\telse\n\t{\n\t\tStop();\n\t}\n}",
"#fireRandomlyAdjacent(boardObj) {\n // Here we need to still be firing randomly, so we need to pick a direction to fire in\n let randDirX = Math.floor(Math.random() * 3) - 1; // This will generate a far from -1 to 1\n let randDirY = (randDirX != 0) ? 0 : Math.floor(Math.random() * 3 - 1); // If the x direction isn't 0, then choose a random Y, otherwise no Y direction\n\n let randDir = [randDirY, randDirX];\n\n // There's a chance this will generate a random direction of [0, 0]. this is bad because it means we'll be firing at the same spot\n // If that happens then we just try to fire randomly again\n if(randDir[0] == 0 && randDir[1] == 0) {\n return this.#fireRandomlyAdjacent(boardObj);\n }\n\n // Create a new location from the last found ship and the random direction\n let newLoc = this.lastFound.map((coord, i) => coord + randDir[i]);\n\n // Check for OOB shot\n if(!newLoc.every(coord => coord >= 0))\n {\n // If OOB, try firing again, because this direction isn't any good\n return this.#fireRandomlyAdjacent(boardObj);\n }\n\n // We want to see if this is a repeat location\n // The way I stored locations makes indexOf not work, so I need to check for it like this, which is gross but not as gross as main.js\n if(this.triedAdjacent.findIndex(coord => coord[0] == newLoc[0] && coord[1] == newLoc[1]) >= 0) {\n // If it is, then we just try to fire again, and break out of this function call afterwards\n return this.#fireRandomlyAdjacent(boardObj);\n }\n\n // Once we have a valid direction, we want to attempt a shot at that location\n let fireRes = boardObj.attemptedShot(newLoc[0], newLoc[1]);\n\n // Checks if we hit a ship\n if(fireRes == 'H') {\n // If we hit, we need to set our direction so the AI knows to keep firing this way\n this.lastDir = [randDirY, randDirX];\n\n // We also want to clear the attempted adjacent arr since we now have a direction\n this.triedAdjacent = [];\n }\n else if(fireRes == 'I') {\n // Add this to tried adjacent var\n this.triedAdjacent.push(newLoc);\n\n // If we're already fired there then we try again\n return this.#fireRandomlyAdjacent(boardObj);\n }\n else {\n // Here we've missed, so we want to update the triedAdjacent var so we don't fire on it again\n this.triedAdjacent.push(newLoc);\n }\n\n // We want to update the last fired on var\n this.lastFiredOn = newLoc;\n\n // Return fire result\n return fireRes;\n }",
"jumpToRandom(){\n\t\tthis.coinCount -= 5;\n\t\tthis.updateCoinCount();\n\t\tconst randomTile = Math.floor(Math.random()*40 +1);\n\t\tthis.currentPosition = randomTile;\n\t\tthis.movePiece();\n\t\t$('.resultmessage__container').html(`<p>${this.character} hopped in the vortex and landed on tile [${this.currentPosition}]!</p>`);\n\t\tthis.checkForStar();\n\t\thandleStarFoundMessage();\n\t}",
"setup() {\n\t\tthis.reset();\n\t\tconst all = this.m.getAliveAgents();\n\t\tfor (const agent of all) {\n\t\t\t// who will fight with the current agent\n\t\t\t// includes the current agent + all that matches its position\n\t\t\tconst fighting = all\n\t\t\t\t.filter(e => this.m.samePosition(e, agent) && !this.fighters.includes(e.name) );\n\n\t\t\t// add to current fighters\n\t\t\tfighting.forEach(e => this.fighters.push(e.name) );\n\t\t\t\n\t\t\t// everyone fight two by two (every combination)\n\t\t\tfor (let i = 0; i < fighting.length; ++i) {\n\t\t\t\tfor (let j = i + 1; j < fighting.length; ++j) {\n\t\t\t\t\t// delay fights\n\t\t\t\t\tthis.battles.push( [fighting[i], fighting[j]] );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.ready = true;\n\t}",
"processEngineStep(state, action) {\n let stateDelta = []; // Holds an array of objects marking all x, y coordinate updated\n\n // The change in the coordinates of the head, based on the direction facing\n let deltaX = SnakeEngine.DIRECTIONS[state.direction].x;\n let deltaY = SnakeEngine.DIRECTIONS[state.direction].y;\n\n let newHeadX = state.headX + deltaX;\n let newHeadY = state.headY + deltaY;\n\n let utilities = [0];\n\n state = state.clone();\n\n if (this.isGameOverPos(newHeadX, newHeadY, state)) {\n state.terminalState = true;\n\n } else {\n if (state.getTile(newHeadX, newHeadY) == SnakeState.FOOD) {\n utilities = [1]; // Get 1 utility if food was eaten\n\n let {foodX, foodY} = state.addFood();\n stateDelta.push({x: foodX, y: foodY});\n\n } else {\n let {tailX, tailY} = state.removeTail();\n stateDelta.push({x: tailX, y:tailY});\n }\n\n // Update the head position last to avoid overwriting the food position too early\n state.updateHead(newHeadX, newHeadY);\n stateDelta.push({x: newHeadX, y: newHeadY});\n }\n\n return this.makeProcessedActionOutcome(utilities, state, stateDelta);\n }",
"function doAi() {\n $('#ai').style.display = 'block';\n aiActive = true;\n\n // If the blue general is visible, that becomes everyone's waypoint\n var canSeeGeneral = false;\n for (var i = 6; i < 12; i++) {\n if (canSee(units[i], units[0].x, units[0].y)) {\n canSeeGeneral = true;\n break;\n }\n }\n\n if (canSeeGeneral) {\n for (var i = 7; i < 12; i++) {\n units[i].currWaypoint = 0;\n units[i].waypoints = [xy(units[0].x, units[0].y)];\n }\n }\n\n for (var i = 6; i < 12; i++) {\n for (var j = 0; j < 4; j++) {\n var result = doAi2(units[i]);\n if (result === AI_VISIBLE_ACTION) {\n // Unit took an action\n // Delay for 0.5 seconds for animations\n aiDelayCount++;\n window.setTimeout(doAi, 400);\n return;\n }\n }\n }\n\n if (aiDelayCount === 0) {\n // Delay at least 1 time to show the overlay\n aiDelayCount++;\n window.setTimeout(doAi, 1000);\n return;\n }\n\n // No action, so AI is done\n $('#ai').style.display = 'none';\n aiActive = false;\n aiDelayCount = 0;\n endRound();\n}",
"startGame() {\r\n this.generateInitialBoard();\r\n this.printBoard();\r\n this.getMoveInput();\r\n }",
"function aiMove(){\r\n\r\n let aiMoves = [\"a\", \"w\", \"d\", \"x\", \"aw\", \"wd\", \"ax\", \"xd\"];\r\n let random = Math.random();\r\n let totalMoves = aiMoves.length;\r\n let randomIndex = Math.floor(random * totalMoves);\r\n let randomMove = aiMoves[randomIndex];\r\n\r\n movement(randomMove);\r\n\r\n}",
"function startBattle() {\n console.log(numBattles);\n if (numBattles < 0) {\n console.log(chalk.yellow(\"VICTORY!\"));\n console.log(player.name + \" moves further into the dungeon...\");\n numBattles++;\n }\n\n // if player hitpoints are less than or equal to 0 (dead), console log GAME OVER and end game...\n if (player.hitpoints <= 0) {\n gameOver();\n }\n // Reset the enemy HP in this area, and say what the enemy is\n var enemy = randomEnemy();\n console.log(player.name + \" the \" + player.class + \" encountered a \" + Enemy.name + \"!\");\n console.log(chalk.red(\"Battle Start!\"));\n battleMenu();\n}",
"function initSimon() {\n $('[data-action=start]').on('click', startGame);\n\n }",
"function SpaceshipAI() {\n GameObject.call(this);\n\n this.parentObj = null; // The spaceship that has this AI obj\n this.knowledge = null; // The rest of the \"knowledge\" (i.e. the gameLogic object)\n this.defaultState = null;\n\n // a JS array object, to be used as a queue of actions (FIFO)\n // In JS, enqueue with push() (i.e. add to tail); remove with shift() (i.e. pop from head)\n // each \"action\" will actually be a reference to a function to execute\n\n // This queue is a basic JS \"queue\". (it's an array object)\n // For a fancier, more heavily-engineered queue idea, see the MessageQueue\n this.actionQueue = [];\n\n // And now, the actions/behaviors.\n // Each aiState is a simple JS object, with a priority level and a function to call\n // Priority 0 is the highest/most important priority level.\n // The functions are members of this SpaceshipAI class -- each aiState obj will\n // store a reference to the function\n\n this.aiStateDelayNextAction = { \"priority\": 0, \"function\": this.aiBehaviorDelayNextAction };\n\n this.aiStateAlignToReduceVelocity = { \"priority\": 1, \"function\": this.aiBehaviorAlignToReduceVelocity };\n this.aiStateThrustToReduceVelocity = { \"priority\": 1, \"function\": this.aiBehaviorThrustToReduceVelocity };\n\n this.aiStateAlignToEvadeThreat = { \"priority\": 2, \"function\": this.aiBehaviorAlignToEvadeThreat }; // TODO: write this function.. Same as AlignToTarget, but will use a different vector\n this.aiStateThrustToEvadeThreat = { \"priority\": 2, \"function\": this.aiBehaviorThrustToEvadeThreat }; // TODO write this function.. essentially the same as ThrustToTarget, but with different transitions\n\n this.aiStateSelectTarget = { \"priority\": 3, \"function\": this.aiBehaviorSelectTarget };\n this.aiStateAlignToTarget = { \"priority\": 3, \"function\": this.aiBehaviorAlignToTarget };\n this.aiStateThrustToTarget = { \"priority\": 3, \"function\": this.aiBehaviorThrustToTarget };\n this.aiStateAttackTarget = { \"priority\": 3, \"function\": this.aiBehaviorAttackTarget };\n\n}",
"function randomMove() {\n\t\tvar availTiles = emptyTiles(board);\n\t\trandom = Math.floor( Math.random() * availTiles.length );\n\t\tmove = availTiles[random];\n\t\tcomputerPlays(move);\n \t}",
"function placeTorch(){\r\n\t\t\tif(currentLocation===\"skeletonRoom\" && inventory[0]===\"torch\"){\r\n\t\t\t\tvar msg=(\"You put the torch in the skeleton's hands. A door to the west opens up. \")\r\n\t\t\t\tupdateText(msg);\r\n\t\t\t\ttorchPlaced=true;\r\n\t\t\t\tdocument.getElementById(\"west_button\").disabled=false;\r\n\t\t\t\tinventory[0]=\"nothing\"\r\n\t\t\t}else{\r\n\t\t\tvar msg=(\"What torch?\");\r\n\t\t\tupdateText(msg);\r\n\t\t\t}\r\n\t\t}",
"function init() {\n squares.forEach((q) => {\n q.innerText = \"\";\n q.addEventListener(\"click\", handleTurn);\n })\n win = null;\n moveCount = 0;\n render();\n}",
"function runThings(){\n food.run();\n snake.run();\n}",
"function start(){\n\n // this is the real number of players updated\n updateNumberOfPlayers();\n\n plEvenOdd = numberOfPlayers;\n\n plEvenOdd % 2 !== 0 ? ++numberOfPlayers : numberOfPlayers;\n\n plEvenOdd % 2 == 0 ? updateTotalRounds() : updateTotalRoundsOdd();\n\n // update totalRounds\n // updateTotalRounds();\n\n // change classes to display screen 3\n screen3(); \n\n\n plEvenOdd % 2 == 0 ? getNames() : getNamesOdd();\n\n // get the player names\n // getNames();\n // put all the names inside position array\n // getPosition(); ******************ready to delete*****************\n\n\n\n \n\n plEvenOdd % 2 == 0 ? makeCouple() : makeCoupleOdd();\n\n // create couples based on player position\n // makeCouple();\n\n // diplay round\n displayRound();\n\n \n // update the current round\n updateCurrentRound();\n\n plEvenOdd % 2 == 0 ? displayCouples() : displayCouplesOdd();\n\n // display couple + passes input\n // displayCouples(); \n}",
"function nextMove() {\n\n nodes = 0;\n leaves = 0;\n\n console.time(\"ai move\");\n\n let alpha = -Infinity;\n let beta = Infinity;\n\n let bestScore = Infinity;\n let bestPiecePos = null;\n let bestMove = null;\n\n if (opening) {\n\n if (move_n >= opening_move.length) {\n opening = false;\n }\n else {\n\n let next_move = opening_move[move_n].move;\n let next_piece = opening_move[move_n].piece;\n\n if (isAiMoveValid(board[next_piece.y][next_piece.x], next_move.x, next_move.y)) {\n\n bestPiecePos = next_piece;\n bestMove = next_move;\n\n }\n else {\n\n opening = false;\n\n }\n\n move_n++;\n\n } \n \n }\n\n if (!opening) {\n\n for (let y = 0; y < CELLS; y++) {\n\n for (let x = 0; x < CELLS; x++) {\n\n let piece = board[y][x];\n\n //Find next AI piece\n if (piece != null && piece.player == 'ai') {\n\n //Store piece's original position so it can be reverted later\n let piece_x = piece.x;\n let piece_y = piece.y;\n let firstMove;\n if (piece instanceof Pawn || piece instanceof King || piece instanceof Rook) {\n firstMove = piece.firstMove;\n }\n\n let moves = piece.getMoves();\n\n //Loop through piece's possible moves\n for (let key in moves) {\n\n for (let i = 0; i < moves[key].length; i++) {\n\n let move = moves[key][i];\n\n //Check if move is valid\n if (isAiMoveValid(piece, move.x, move.y)) {\n\n nodes++;\n\n //if (key == 'special_l' || key == 'special_r') console.log(\"king check\");\n\n //Castling\n let isCastling = (piece instanceof King && (key == 'special_r' || key == 'special_l'));\n let rook;\n let rook_x;\n let rook_firstMove;\n\n if (isCastling) { \n\n rook = castleRook(piece, move.x, move.y);\n\n if (rook == null || !rook.firstMove) {\n continue;\n } else {\n\n piece.hasCastled = true;\n\n //Store castle rooks original data\n rook_x = rook.x;\n rook_firstMove = rook.firstMove;\n\n //Move rook\n board[rook.y][rook.x] = null;\n board[rook.y][rook.castlex] = rook;\n\n //Update pos in rook\n rook.x = rook.castlex;\n rook.firstMove = false;\n }\n\n }\n \n\n //Store destination cell's content (piece or null) so it can be reverted\n let dest_cell = board[move.y][move.x];\n\n //Move piece on board\n board[move.y][move.x] = piece;\n board[piece.y][piece.x] = null;\n\n //Update pos in piece\n piece.x = move.x;\n piece.y = move.y;\n\n if (piece instanceof Pawn || piece instanceof King || piece instanceof Rook) {\n piece.firstMove = false;\n }\n\n //Run minimax and calculate score\n let score = Infinity;\n\n if (!isInCheck(_cking)) {\n score = alphabetaMax(0, alpha, beta);\n }\n\n if (score < beta) {\n beta = score;\n }\n\n //Check if score is better than best score\n if (score < bestScore) {\n\n bestScore = score;\n bestPiecePos = { x: piece_x, y: piece_y };\n bestMove = move;\n\n }\n\n //Revert values\n board[move.y][move.x] = dest_cell;\n board[piece_y][piece_x] = piece;\n piece.x = piece_x;\n piece.y = piece_y;\n if (piece instanceof Pawn || piece instanceof King || piece instanceof Rook) {\n piece.firstMove = firstMove;\n }\n\n if (isCastling) {\n\n piece.hasCastled = false;\n\n //Revert rook values\n rook.x = rook_x;\n rook.firstMove = rook_firstMove;\n board[rook.y][rook.castlex] = null;\n board[rook.y][rook.x] = rook;\n\n }\n\n } else {\n\n break;\n\n }\n\n }\n\n }\n\n }\n\n\n }\n\n }\n\n }\n\n if (bestPiecePos == null) {\n alert(\"You win!\");\n console.timeEnd(\"ai move\");\n playerTurn = false;\n return;\n }\n \n\n //Move piece\n let piece = board[bestPiecePos.y][bestPiecePos.x];\n\n //Check if it was a castling move\n if (piece instanceof King) {\n\n //Distance king moved along x axis\n let dx = Math.abs(bestPiecePos.x - bestMove.x);\n\n //Check if king was moved more than one space\n if (dx > 1) {\n\n let rook = castleRook(piece, bestMove.x, bestMove.y);\n\n piece.hasCastled = true;\n\n //Move rook\n board[rook.y][rook.x] = null;\n board[rook.y][rook.castlex] = rook;\n\n clearCell(rook.x, rook.y);\n\n rook.x = rook.castlex;\n rook.firstMove = false;\n\n drawPiece(rook);\n\n }\n\n }\n\n //Add move notation before updating piece\n addMoveNotation(piece, bestMove.x, bestMove.y);\n\n board[bestMove.y][bestMove.x] = piece;\n board[piece.y][piece.x] = null;\n\n //Clear cells\n clearCell(piece.x, piece.y);\n clearCell(bestMove.x, bestMove.y); \n\n //Update piece\n piece.x = bestMove.x;\n piece.y = bestMove.y;\n\n if (piece instanceof Pawn || piece instanceof King || piece instanceof Rook) {\n\n if (piece.firstMove) {\n piece.firstMove = false;\n }\n\n }\n\n //Draw piece\n drawPiece(piece);\n\n updateScoreArea();\n updateMoveList();\n\n if (playerColor == 'white') move_no++;\n\n playerTurn = true;\n\n console.timeEnd(\"ai move\");\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If an options object has an axisLabels property then it reverses the values of the array. Should this check to see if the property is an array? | function reverseAxisLabels(opts) {
if (opts.axisLabels) {
opts.axisLabels.reverse();
}
return opts;
} | [
"function onAxisAfterSetOptions() {\n var axis = this;\n if (axis.brokenAxis && axis.brokenAxis.hasBreaks) {\n axis.options.ordinal = false;\n }\n }",
"function onAxisDestroy() {\n if (this.chart &&\n this.chart.labelCollectors) {\n var index = (this.labelCollector ?\n this.chart.labelCollectors.indexOf(this.labelCollector) :\n -1);\n if (index >= 0) {\n this.chart.labelCollectors.splice(index, 1);\n }\n }\n }",
"function mapJsonToChartLabels(labels) {\n\t\tvar r = '';\n\t\tfor (label in labels) {\n\t\t\tr += label + \"|\";\n\t\t}\n\t\treturn r.slice(0, -1);\n\t}",
"getAxes() {\n return [];\n }",
"function createYAxisLabels(labels, names)\n{\n let x = 0;\n let y = 0;\n let i = 0;\n\n names.forEach(name => \n {\n yLabels[i] = labels.append(\"text\")\n .attr(\"transform\", \"rotate(-90)\")\n .attr(\"y\", y - margin.left)\n .attr(\"x\", 0 - (height / 2))\n .attr(\"text-anchor\", \"middle\")\n .attr(\"dy\", \"1em\")\n .classed(name === chosenYAxis ? \"active\" : \"inactive\", true)\n .attr(\"value\",name)\n .text(yAxisText[i]);\n\n y += 20;\n i += 1;\n });\n return labels;\n}",
"createYTicks() {\n var labelsArray = [];\n for (let i = this.yDomainArray[0]; i <= this.yDomainArray[1]; i += this.yStep) {\n labelsArray.push(this.roundFloat(i));\n }\n this.yTicksArray = labelsArray;\n }",
"function onAxisInit(e) {\n var chart = this.chart, inverted = chart.inverted, angular = chart.angular, polar = chart.polar, isX = this.isXAxis, coll = this.coll, isHidden = angular && isX, chartOptions = chart.options, paneIndex = e.userOptions.pane || 0, pane = this.pane = chart.pane && chart.pane[paneIndex];\n var isCircular;\n // Prevent changes for colorAxis\n if (coll === 'colorAxis') {\n this.isRadial = false;\n return;\n }\n // Before prototype.init\n if (angular) {\n if (isHidden) {\n modifyAsHidden(this);\n }\n else {\n modify(this);\n }\n isCircular = !isX;\n if (isCircular) {\n this.defaultPolarOptions = defaultRadialGaugeOptions;\n }\n }\n else if (polar) {\n modify(this);\n // Check which axis is circular\n isCircular = this.horiz;\n this.defaultPolarOptions = isCircular ?\n defaultCircularOptions :\n merge(coll === 'xAxis' ?\n _AxisDefaults_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].defaultXAxisOptions :\n _AxisDefaults_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].defaultYAxisOptions, defaultRadialOptions);\n // Apply the stack labels for yAxis in case of inverted chart\n if (inverted && coll === 'yAxis') {\n this.defaultPolarOptions.stackLabels = _AxisDefaults_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].defaultYAxisOptions.stackLabels;\n this.defaultPolarOptions.reversedStacks = true;\n }\n }\n // Disable certain features on angular and polar axes\n if (angular || polar) {\n this.isRadial = true;\n chartOptions.chart.zoomType = null;\n if (!this.labelCollector) {\n this.labelCollector = this.createLabelCollector();\n }\n if (this.labelCollector) {\n // Prevent overlapping axis labels (#9761)\n chart.labelCollectors.push(this.labelCollector);\n }\n }\n else {\n this.isRadial = false;\n }\n // A pointer back to this axis to borrow geometry\n if (pane && isCircular) {\n pane.axis = this;\n }\n this.isCircular = isCircular;\n }",
"function createAxisDataY(){\n const obesityAxis = new axisData(\n dataColumns.obesity, \n \"Obesity (%)\"\n );\n obesityAxis.setScalarMin(.9);\n obesityAxis.setScalarMax(1.05);\n\n const smokeAxis = new axisData(\n dataColumns.smokes,\n \"Smokes (%)\"\n );\n smokeAxis.setScalarMin(.8);\n\n const healthcareAxis = new axisData(\n dataColumns.healthcare,\n \"Lacks Healthcare (%)\"\n );\n healthcareAxis.setScalarMin(.5);\n\n return [\n obesityAxis,\n smokeAxis,\n healthcareAxis\n ];\n}",
"invert() {\n for (let i = 0; i < this._data.length; i++) {\n this._data[i] = ~this._data[i];\n }\n }",
"function hideAxis() {\n g.select('.x.axis')\n .transition().duration(500)\n .style('opacity', 0);\n }",
"function ClearSelectOptions( obj )\n{\n if( obj == undefined || obj == null ) return ;\n try\n {\n for( var i = obj.options.length - 1; i >= 0 ; i -- )\n obj.options.remove(i) ;\n return ;\n }\n catch(err)\n {\n return ;\n }\n}",
"get hasLabels() {\n return this._hasLabels;\n }",
"function formatByteAxis(data) {\n var toFormat = '',yLbl = '';\n var dValues = $.map(data,function(obj,idx) {\n return obj['values'];\n });\n dValues = flattenList(dValues);\n yMaxMin = $.map(d3.extent(dValues, function (obj) {\n return obj['y']\n }), function (value, idx) {\n return formatBytes(value);\n });\n if (yMaxMin[0].split(' ')[1] == yMaxMin[1].split(' ')[1]) {\n toFormat = yMaxMin[0].split(' ')[1];\n } else {\n toFormat = yMaxMin[1].split(' ')[1];\n }\n $.each(data,function(idx,obj) {\n data[idx]['values'] = $.map(data[idx]['values'], function (obj, idx) {\n obj['origY'] = obj['y'];\n obj['y'] = prettifyBytes({bytes:obj['y'], stripUnit:true, prefix:toFormat});\n return obj;\n });\n });\n if (toFormat != null) {\n yLbl += ' (' + toFormat + ')';\n }\n return {data:data,yLbl:yLbl};\n}",
"function evalOptions( options, labels, series ){\n\n if( options != \"\" ){\n\n try {\n\n return Function( \"labels\", \"series\", \"return \" + options)(); // jshint ignore:line\n\n } catch( err ) {\n\n console.log ( \"Options eval err\", err, options );\n return null;\n\n }\n }\n}",
"function printArrayLabel(label, arrayObj) {\n console.log('\\n====== ' + label + ' ======');\n printArray(arrayObj);\n}",
"function arrayToString()\n{\n\tif ( ! arguments.length ) { return '/' + this.map( mapValue ).join( '/' ) ; } // jshint ignore:line\n\telse { return '/' + Array.prototype.slice.apply( this , arguments ).map( mapValue ).join( '/' ) ; } // jshint ignore:line\n}",
"setDefaultAxes() {\n let defaultAxes = this.dataHandler._getDefaultAxes();\n this.options.xAxis = defaultAxes.x;\n this.options.yAxis = defaultAxes.y;\n this.options.zAxis = defaultAxes.z;\n }",
"function populateChartData(data, dataOptions) {\n return {\n labels: Object.keys(data), // Retrieve keys of data as labels\n datasets: [Object.assign({data: Object.values(data)}, dataOptions)] // Combine data and data options\n }\n} // END: populateChartData",
"function deprecateFromOptionsMap(chart, rootOldAsArray, rootNewAsArray, mapToNewOptions) {\n /**\n * @private\n */\n function getChildProp(root, propAsArray) {\n return propAsArray.reduce(function (acc, cur) {\n return acc[cur];\n }, root);\n }\n var rootOld = getChildProp(chart.options, rootOldAsArray), rootNew = getChildProp(chart.options, rootNewAsArray);\n Object.keys(mapToNewOptions).forEach(function (oldOptionKey) {\n var _a;\n var val = rootOld[oldOptionKey];\n if (typeof val !== 'undefined') {\n traverseSetOption(rootNew, mapToNewOptions[oldOptionKey], val);\n error(32, false, chart, (_a = {},\n _a[rootOldAsArray.join('.') + \".\" + oldOptionKey] = rootNewAsArray.join('.') + \".\" + mapToNewOptions[oldOptionKey].join('.'),\n _a));\n }\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
devuelve verdadero si el archivo es una imagen | is_image() {
if (
this.file_type == "jpg" ||
this.file_type == "png" ||
this.file_type == "gif"
) {
return true;
}
return false;
} | [
"function validarFormatoImagen() {\n var extensionImagenes = /(.jpg|.jpeg|.png)$/i;\n var imagen = document.getElementById(\"img_area\");\n var archivo = imagen.value;\n if (!extensionImagenes.test(archivo)) {\n console.log(archivo);\n alert(\"El formato de la imagen no es válido.\");\n document.getElementById(\"img_area\").value = \"\"; \n }\n}",
"function selectImage(file) {\n const extension = extname(file);\n return extension === '.jpg' || extension === '.jpeg';\n}",
"function imageisloaded(image) {\n if (image == null || ! image.complete()) {\n alert(\"image not loaded :(\");\n return false;\n }\n else {\n return true; \n }\n}",
"function escogerImagen(objeto)\n{\n var imagen=\"\";\n\n if(objeto.estado == \"Clear\")\n {\n imagen=\"sol.png\";\n }\n else if(objeto.estado == \"Rain\")\n {\n imagen=\"lluvia.png\";\n }\n else if(objeto.estado == \"Clouds\")\n {\n imagen=\"nublado.png\";\n }\n else\n {\n imagen=\"nevado.png\";\n }\n\n return imagen;\n}",
"function cargar_imagen() {\n\t\t\t\n\t\t\tlet input = document.querySelector('.inp_cargar');\n\n\t\t\tinput.onchange = e => {\n\t\t\t\tlet canvas = document.querySelector(\"#canvas\");\n\t\t\t\tlet context = canvas.getContext(\"2d\");\n\n\t\t\t\tlet file = e.target.files[0];\n\t\t\t\tlet reader = new FileReader();\n\t\t\t\treader.readAsDataURL(file); \n\t\n\t\t\t\treader.onload = readerEvent => {\n\t\t\t\t\tlet content = readerEvent.target.result; \n\t\t\t\t\tlet image = new Image();\n\t\t\t\t\timage.src = content;\n\t\n\t\t\t\t\timage.onload = function () {\n\t\t\t\t\t\tlet imageAspectRatio = (1.0 * this.height) / this.width;\n\t\t\t\t\t\tlet imageScaledWidth = canvas.width;\n\t\t\t\t\t\tlet imageScaledHeight = canvas.width * imageAspectRatio;\n\t\t\t\t\t\tlet startWidth = 0;\n\t\t\t\t\t\tlet startHeigh = 0;\n\t\t\t\t\t\tif (this.width < this.height) {\n\t\t\t\t\t\t\timageAspectRatio = (1.0 * this.width) / this.height;\n\t\t\t\t\t\t\timageScaledWidth = canvas.height * imageAspectRatio;\n\t\t\t\t\t\t\timageScaledHeight = canvas.height;\n\t\t\t\t\t\t\tstartWidth = (canvas.width / 2) - (imageScaledWidth / 2);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tstartHeigh = (canvas.height / 2) - (imageScaledHeight / 2);\n\t\t\t\t\t\t}\t\n\t\t\t\t\t\tcontext.drawImage(this, startWidth, startHeigh, imageScaledWidth, imageScaledHeight);\t\t\t\t\t\t\n\t\t\t\t\t\tlet imageData = context.getImageData(0, 0, c.width, c.height);\t\t\t\t\t\n\t\t\t\t\t\tctx.putImageData(imageData, 0, 0);\n\t\t\t\t\t\timg_original = ctx.getImageData(0, 0, c.width, c.height);\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\t\t\t\n\t\t}",
"function comprobarImagenes(){\n\tvar elementos = document.querySelectorAll('.contenedor-imagen>picture>label>img');\n\tvar respuesta = false;\n\n\tif(elementos.length!=0){\n\t\t\n\t\tfor(let i=0;i<elementos.length;i++){\n\t\t\t\n\t\t\tlet lastSlash = elementos[i].src.lastIndexOf('/');\n\t\t\tlet nombre = elementos[i].src.substring(lastSlash+1);\n\t\t\t\n\t\t\tif(nombre!=\"foto-placeholder.jpg\"){\n\t\t\t\tconsole.log('Si que hay imagenes');\n\t\t\t\trespuesta=true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t}else{\n\t\tconsole.log('No hay imagenes...');\n\t\tvar divError = document.getElementById('errorImagen'),\n\t\t\tdivNormal = document.getElementById('contenedor-nueva-receta');\n\n\t\tdivError.children[0].innerHTML = 'No hay ninguna imagen';\n\t\tdivNormal.style.display = \"none\";\n\t\tdivError.style.display = \"block\";\n\n\t\trespuesta=false;\n\t}\n\treturn respuesta;\n\t\n}",
"static isImageLoaded(img){// During the onload event, IE correctly identifies any images that\n// weren’t downloaded as not complete. Others should too. Gecko-based\n// browsers act like NS4 in that they report this incorrectly.\nif(!img.complete){return false;}// However, they do have two very useful properties: naturalWidth and\n// naturalHeight. These give the true size of the image. If it failed\n// to load, either of these should be zero.\nif(img.naturalWidth===0){return false;}// No other way of checking: assume it’s ok.\nreturn true;}",
"function isPictureValid(buffer)\n {\n if (buffer.length === 0)\n {\n return false;\n }\n else if (buffer.length < 4)\n {\n return false;\n }\n else if (buffer.slice(1, 4).indexOf(\"PNG\") !== -1)\n {\n // PNG\n return true;\n }\n else if (buffer.slice(0, 16).indexOf(\"JFIF\") !== -1)\n {\n // JPEG/JFIF\n return true;\n }\n else if (buffer.slice(0, 16).indexOf(\"Exif\") !== -1)\n {\n // JPEG/Exif\n return true;\n }\n else\n {\n return false;\n }\n }",
"function cargarFotoPerfil() {\n let fotoPostulante = document.getElementById(\"fotoPostulante\");\n if (postulante.foto)\n fotoPostulante.src = \"../fotos_perfil/\" + postulante.foto;\n else fotoPostulante.src = \"../fotos_perfil/no_image.png\";\n}",
"_computeHasImage(fields) {\n if (\n fields &&\n typeof fields.images !== typeof undefined &&\n typeof fields.images[0] !== typeof undefined &&\n typeof fields.images[0].src !== typeof undefined\n ) {\n return true;\n }\n return false;\n }",
"function pasarFoto() {\r\n if(posicionActual >= IMAGENES.length - 1) {\r\n posicionActual = 0;\r\n } else {\r\n posicionActual++;\r\n }\r\n renderizarImagen();\r\n }",
"function loadImg(img, target_name) {\n if (img.files && img.files[0]) {\n var FR = new FileReader();\n FR.onload = function (e) {\n //e.target.result = base64 format picture\n $('#' + target_name + '_preview').attr(\"src\", e.target.result);\n $('#' + target_name + '_input').val(e.target.result);\n };\n FR.readAsDataURL(img.files[0]);\n }\n}",
"function MyFile(nombre){\n this.name = nombre; //nombre del archivo con su extension\n this.type; //tipo de archivo (ej application, image etc) \n this.codeType; //tipo codificacion del contenido (ej base64, base32, etc)\n this.data; //contenido del archivo\n \n //trabajamos sobre el dataURL --> \"data:application/pdf;base64,datossss\" \"data:image/png;base64,datosss\"\n this.parseDataURL = function(dataURL){\n var dataURLSeparado = dataURL.split(\",\");\n \n //obtenemos los datos\n this.data = dataURLSeparado[1];\n //la primera parte es la cabecera del archivo\n var cabecera = dataURLSeparado[0].split(\";\"); \n \n //obtenemos el typo de codificacion\n this.codeType = cabecera[1];\n //obtenemos el tipo de archivo\n this.type = cabecera[0].split(\":\")[1];\n };\n}",
"_renderPhotoConv(conv) {\n if(conv.photo == undefined) {\n if(conv.joueur == undefined) {\n return(\n <Image\n source = {require('../../../res/group.png')}\n style = {styles.image_conv}/>\n )\n } else {\n return(\n <Image\n source = {{uri : conv.joueur.photo }}\n style = {styles.image_conv}/>\n )\n }\n } else {\n return(\n <Image\n source = {{uri : conv.photo }}\n style = {styles.image_conv}/>\n )\n }\n }",
"function getImg(name){\r\n\tlet myList = readFile(\"Members\", name);\r\n\tlet json = myList;\r\n\tfor(let i = 0; i < json.length; i++){\r\n\t\tif(!json[i].endsWith(\".txt\")){\r\n\t\t\treturn json[i];\r\n\t\t}\r\n\t}\r\n\treturn \"none\";\r\n}",
"function gfnFileExtCheck(obj, arr){\n\tif( $(obj).val() != \"\" ){\n var ext = $(obj).val().split('.').pop().toLowerCase();\n\t\tif($.inArray(ext, arr) == -1) {\n\t\t\talert(arr+' 파일만 업로드 할 수 있습니다.');\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\treturn null;\n}",
"function isFullSizeImageLoaded() {\n var el = document.getElementById('lightBoxImage');\n return el && el.width && el.width >= MINIMUM_IMAGE_WIDTH;\n }",
"function cargarFile(event) {\r\n var file = event.target.files[0];\r\n\r\n if (file.type.match('video.*')) {\r\n var fileURL = URL.createObjectURL(file);\r\n video.src = fileURL;\r\n cargando.classList.remove(\"ocultar\");\r\n } else {\r\n fileSelector.value = \"\";\r\n alert(\"Error: Tipo de fichero incorrecto\");\r\n }\r\n}",
"imageLoaded(){}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sends a command to the server to reboot the stb | function reboot() {
sendPowerCommand('reboot');
} | [
"function restartGame(){\r\n\tsocket.emit(\"restart\");\r\n}",
"function powerOff() {\n sendPowerCommand('off');\n}",
"function rebootComputer(computerName) {\n // Wrapped in a promise due to the time it takes to execute the reboot command. Must be able init reboot on multiple computers at the same time.\n return new Promise(async (resolve, reject) => {\n const newRebootInfo = {\n computer: computerName,\n deployResult: { success: null, running: true }\n };\n\n // Add/update the reboot info, so that the client can ask for current status.\n updateRebootInfo([newRebootInfo]);\n\n try {\n // Run the reboot command with the help of PsExec.\n const result = await runPsexecCommand(\n computerName,\n \"cscript.exe /nologo c:\\\\temp\\\\setboot.vbs /accepteula\"\n );\n\n // Add relevant information about the result.\n newRebootInfo.deployResult.started = new Date();\n newRebootInfo.deployResult.success = true;\n newRebootInfo.deployResult.running = false;\n newRebootInfo.deployResult.data = result;\n } catch (err) {\n // The remote reboot failed. Add relevant information.\n newRebootInfo.deployResult.success = false;\n newRebootInfo.deployResult.running = false;\n newRebootInfo.deployResult.err = err;\n }\n\n // Update the reboot info once again.\n updateRebootInfo([newRebootInfo]);\n });\n}",
"sendReset() {\n this.sendMessage('reset');\n }",
"function restartAgent() {\n $(\".page\").css(\"display\", \"none\");\n $(\".active\").removeClass(\"active\");\n $(\"#main\").append('<i class=\"fa fa-spinner fa-pulse fa-3x fa-fw center loading_spinner\"></i>');\n\n $(\"#agent_status\").html(\"Not connected<br> to Agent\");\n $(\"#agent_status\").css({\n \"background\": 'linear-gradient(to bottom, #c62d1f 5%, #f24437 100%)',\n \"background-color\": '#c62d1f',\n \"border\": '1px solid #d02718',\n \"text-shadow\": '0px 1px 0px #810e05',\n 'left': '-180px'\n });\n\n // Disable the restart button to prevent multiple consecutive clicks\n $(\"#restart_button\").css(\"pointer-events\", \"none\");\n\n sendMessage(\"agent/restart\", \"\", \"post\",\n function(data, status, xhr){\n // Wait a few seconds to give the server a chance to restart\n setTimeout(function(){\n $(\".loading_spinner\").remove();\n $(\"#restart_button\").css(\"pointer-events\", \"auto\");\n\n if (data != \"Success\") {\n $(\"#general_status\").css(\"display\", \"block\");\n $('#general_status').html(\"<span class='center'>Error restarting agent: \" + DOMPurify.sanitize(data) + \"</span>\");\n } else loadStatus(\"general\");\n }, 10000);\n }, function() {\n $(\".loading_spinner\").remove();\n $(\"#general_status\").css(\"display\", \"block\");\n $('#general_status').html(\"<span class='center'>An error occurred.</span>\");\n $(\"#restart_button\").css(\"pointer-events\", \"auto\");\n });\n}",
"restartGattService() {\n logit('Clearing all notifications...');\n this.gattService.clearAllNotifications(allCharacteristics);\n logit('Unregistering Gatt Service...');\n this.gattService.unRegisterGattService();\n logit('Reregistering Gatt Service...');\n this.gattService.registerGattService();\n }",
"function powerOn() {\n sendPowerCommand('on');\n}",
"function receivePlayerRestart() {\n\tsocket.on('player restart', function(_) {\n\t console.log('player restart');\n\t restore();\n\t});\n }",
"function resetSyncSession() {\n function resetSucc() {\n kony.print(\"syncResetSuccess\");\n }\n\n function resetFail() {\n kony.print(\"syncResetFailure\");\n }\n sync.reset(resetSucc, resetFail);\n}",
"function sendPowerCommand(command) {\n var deviceIds = LayoutUtil.getCheckedDevices();\n\n var cmdPattern = \"command:\"+ command;\n updateEventLog(\"Sending POWER \"+ cmdPattern, deviceIds);\n\n var powerPayload = {\n deviceIds : deviceIds,\n command : command\n };\n dismissPrompt();\n var posting = $.post(CXT_PATH + '/power', powerPayload);\n validatePostEvent(posting, cmdPattern);\n}",
"function waitForReboot(cpuid)\r\n{\r\n\t// it's not present - switch to the WaitForReboot page\r\n\twindow.navigate(\"WaitForReboot.htm?ID=\" + cpuid + \"&return=\" + encodeURIComponent(window.location.href));\r\n\treturn false;\r\n}",
"function Respawn() {\n if (character.rip) {\n get_socket().emit(\"respawn\");\n return true;\n }\n return false;\n}",
"sendBooted() {\n this.sendMessage('applicationBooted', {\n booted: this.get('namespace.owner.__inspector__booted'),\n });\n }",
"function restart() {\n force.start();\n t = 1;\n }",
"offline () {\n log.warn(`Replica \"${this}\" got offline`);\n this.isDown = true;\n this.pool.node.emit('replica', {\n eventType: 'mod',\n object: this\n });\n }",
"function sendCmd(cmd) {\n return sendJson(ip+\"/cmd/{'c':\"+cmd+\"}\");\n}",
"restartInstance(instance) {\n return $.ajax({\n url: `${config.apiUrl}/instance/${instance._id}`,\n method: 'PUT',\n headers: {\n 'Girder-Token': this.get('tokenHandler').getWholeTaleAuthToken()\n },\n data: JSON.stringify(instance),\n dataType: 'json',\n contentType: 'application/json',\n timeout: 3000, // ms\n success: function(response) {\n console.log('Restarted Tale instance:', response);\n },\n error: function(err) {\n console.log('Failed to restart Tale instance:', err);\n }\n });\n }",
"function SendCommand(Command)\n{\n var Output = SSHClient.RunCommand(Command)\n Log.Message(\"Output from Device is :- \"+ Output.Result)\n return Output.Result\n}",
"function wakeUpServer() {\n\tvar h = require(\"http\");\n\th.get(SERVER_URL);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
binary search to find char in a line | findInsertIndexInLine(char, line) {
let left = 0;
let right = line.length - 1;
let mid, compareNum;
if (line.length === 0 || char.compareTo(line[left]) < 0) {
return left;
} else if (char.compareTo(line[right]) > 0) {
return this.struct.length;
}
while (left + 1 < right) {
mid = Math.floor(left + (right - left) / 2);
compareNum = char.compareTo(line[mid]);
if (compareNum === 0) {
return mid;
} else if (compareNum > 0) {
left = mid;
} else {
right = mid;
}
}
if (char.compareTo(line[left]) === 0) {
return left;
} else {
return right;
}
} | [
"binarySearch6() {\n var read = require('fs');\n var text = read.readFileSync(\"./mytext.txt\", 'utf-8');\n var word = text.split(\" \");\n word.sort();\n return word;\n }",
"function findMarker(buf, pos) {\n for (var i = pos; i < buf.length; i++) {\n if (0xff === buf[i ] &&\n 0xe1 === buf[i+1]) {\n return i;\n }\n }\n return -1;\n }",
"function findMatchingLine(lines, re, startIndex) {\n re = new RegExp(re);\n if (!startIndex) startIndex = 0;\n\n var found = false, index;\n\n for (index = startIndex; index < lines.length; index++) {\n if (re.test(lines[index])) {\n found = true;\n break;\n }\n }\n\n return found ? index : -1;\n}",
"function myIndexOf(string, searchTerm) {}",
"function find_word(file_path,searchstring)\n{\n\tvar fso,f,s_SearchString,s_FilePath,s_FileContent;\n\tvar ForReading = 1, ForWriting = 2, ForAppending =8;\n\ts_SearchString = /searchstring/i;\n\t//s_SearchString = new String(searchstring);\n\ts_FilePath = new String (file_path);\n\tfso = new ActiveXObject(\"Scripting.FileSystemObject\");\n\tf = fso.OpenTextFile(s_FilePath , ForReading);\n\ts_FileContent = new String (f.ReadAll());\n\tif (s_FileContent.search(s_SearchString) == -1)\n\t{\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\treturn true;\n\t}\n}",
"function firstOcc(string, character) {\n for (var i = 0; i < string.length; i++) {\n if (string[i] === character) {\n return i;\n }\n }\n return -1;\n}",
"function char_position_finder(steps, base){\n\tlet counter = 0,\n\t\t\tposition;\n\t\t// \"arr.some\" is used instead of \"arr.forEach\" so we can break out of the loop as soon as we find the position we're searching for\n\t\tsteps.some( (step, i) => {\n\t\tcounter = step_counter(step, counter);\n\t\tif(counter === base) {\n\t\t\tposition = i+1;\n\t\t\treturn true;\n\t\t}\n\t})\n\t\treturn position || \"Santa Never Reaches the Base\";\n}",
"function InStr(start, srchStr, fndStr, cmp) {\n if (!fndStr || fndStr==null || fndStr==\"\") {\n\t\tfndStr += \"\";\n if (fndStr.length == 0) {\n if (!start || start==null || !isNumeric(start) || start=='' || start < 1 ) { start=1; }\n start=Math.floor(start);\n if (!srchStr || srchStr==null) { srchStr=''; }\n if (start > srchStr.toString().length) { return 0; }\n return start;\n }\n\t\tcmp=0;\n fndStr=srchStr;\n srchStr=start;\n start=1;\n }\n\tif (!isNumeric(Math.floor(start))) {\n cmp=fndStr;\n\t\tfndStr=srchStr;\n srchStr=start;\n start=1;\n\t}\n if (!start || start==null || !isNumeric(start) || start=='' || start < 1 ) { start=1; }\n if (!srchStr || srchStr==null) { srchStr=''; }\n if (!fndStr || fndStr==null) { fndStr=''; }\n start=Math.floor(start);\n\n if (srchStr == \"\") { return 0; }\n var osrchStr=srchStr.toString();\n if (start > osrchStr.length) { return 0; }\n if (fndStr == \"\") { return start; }\n\n srchStr=osrchStr;\n fndStr=fndStr.toString();\n if (start>1) { srchStr=srchStr.substr(start-1); }\n\tcmp = cmp + \"\";\n\tvar loc=0;\n\tif (cmp=='1') { //insensitive\n\t\tvar osrchStr=srchStr.toLowerCase();\n\t\tvar ofndStr=fndStr.toLowerCase();\n\t\tif (osrchStr.indexOf(ofndStr) == -1) { return 0; }\n\t\tloc=osrchStr.indexOf(ofndStr)+1+(start-1);\n\t} else {\n\t\tif (srchStr.indexOf(fndStr) == -1) { return 0; }\n\t\tloc=srchStr.indexOf(fndStr)+1+(start-1);\n\t}\n return loc;\n}",
"function cari(){\n\tvar isi = \"saya beajar di rumah teman\";\n\tconsole.log(isi.search(\"beajar\"));\n\tconsole.log(isi.search(/beajar/));\n}",
"function locate_line(elt) {\n var found\n var initlen = elt.textContent.length\n var textlen = 0\n var count = 10000\n var wentup = false\n\n while (count > 0 && elt) {\n count = count - 1\n // console.log(\"at\", elt)\n if (elt.nodeType == 3) {\n textlen += textContentLength(elt)\n } else if (found = atLineStart(elt)) {\n break;\n } else if (!wentup) {\n textlen += textContentLength(elt)\n }\n wentup = false\n var next = elt.previousSibling\n if (!next) {\n next = elt.parentNode\n wentup = true\n if (!next || next == elt) {\n break\n }\n }\n elt = next\n }\n if (found) {\n var minCol = textlen - initlen + 1\n var maxCol = textlen + 1\n return [found, minCol, maxCol, elt]\n } else {\n return\n }\n}",
"readcharoreof()\n\t{\n\t\tif (this.pos >= this.input.length)\n\t\t\treturn null;\n\t\treturn this.input.charAt(this.pos++);\n\t}",
"function find(haystack, needle) {\n if (haystack.indexOf(needle) != -1) {\n return 0;\n }\n var hi = 0;\n var ni = 0;\n var penalty = 0;\n var started = false;\n while (true) {\n while (needle[ni] < 'a' || needle[ni] > 'z') {\n ++ni;\n if (ni == needle.length) {\n return penalty;\n }\n }\n while (haystack[hi] != needle[ni]) {\n ++hi;\n if (started) {\n ++penalty;\n }\n if (hi == haystack.length) {\n return -1;\n }\n }\n ++hi;\n ++ni;\n started = true;\n if (ni == needle.length) {\n return penalty;\n }\n if (hi == haystack.length) {\n return -1;\n }\n }\n}",
"function binarySeach(arr, target) {\n\n arr = arr.sort()\n\n left = 0; // index [ 0 ]\n\n right = arr.length - 1 // index [ 4 ]\n\n while (left <= right) {\n\n middle = Math.floor((left + right) / 2)\n\n if (target === arr[middle]) {\n\n return \"Target Exist at index : \" + middle\n }\n\n if (target > arr[middle]) {\n\n left = middle + 1\n } else {\n right = middle - 1\n }\n\n }\n return \"Does not exist in Array\"\n\n}",
"function tSearch(hSlice) {\n var n = hSlice.length;\n do {\n if(hSlice[n] == needle) return true;\n } while(--n);\n\n return false;\n\t}",
"function FindMotif(targetMotif, dnaString){\n\tvar indexLoc = '';\n\tvar notDone = true;\n\tvar counter = 0;\n\tvar lastFound = 0;\n\twhile(notDone && counter <10000){\n\t\tvar pos = dnaString.toString().indexOf(targetMotif,lastFound);\n\t\tif(pos == -1)\n\t\t\tnotDone = false;\n\t\telse{\n\t\t\tpos++\n\t\t\tindexLoc += (pos-1) + ' ';\n\t\t\tlastFound = pos;\n\t\t}\n\t\tconsole.log(pos);\n\t\tcounter++;\n\t}//end while\n\n\tconsole.log(indexLoc);\n\treturn indexLoc;\n}",
"function aBCheck(string){\n var firstA = string.indexOf(\"a\");\n console.log(firstA);\n // console.log(string[firstA]);\n // string[firstA] returns what is at index position 1, 'a'\n console.log(firstA + 3)\n if (string[firstA + 3] == \"a\" || string[firstA + 3] == \"b\"){\n return true;\n }else{\n return false;\n }\n }",
"function wordSearch(board, word) {\n if (word === \"\") return true;\n for (var row = 0; row < board.length; row++) {\n for (var col = 0; col < board[row].length; col++) {\n if (board[row][col] === word[0]) {\n if (dfs(0, row, col)) return true;\n }\n }\n }\n return false;\n\n function dfs(index, x, y) {\n if (index === word.length) return true;\n if (!board[x] || !board[x][y]) return false;\n if (board[x][y] !== '#' && board[x][y] === word[index]) {\n var ch = board[x][y];\n board[x][y] = '#';\n if (dfs(index + 1, x - 1, y)) return true; //up\n if (dfs(index + 1, x + 1, y)) return true; //down\n if (dfs(index + 1, x, y - 1)) return true; //left\n if (dfs(index + 1, x, y + 1)) return true; //right\n board[x][y] = ch;\n // backtracking到前一個節點\n }\n return false;\n }\n}",
"function charIndex(word, char) {\n\tif(!word.includes(char)) {\n\t\treturn undefined;\n\t} else return [word.indexOf(char), word.lastIndexOf(char)];\n}",
"function charIndex(word, char) {\n\tconst arr = word.split(\"\")\n\tif(arr.includes(char)) {\n\t\treturn [arr.indexOf(char), arr.lastIndexOf(char)]\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load JSON file for highscores | function loadJson(){
for(let i = 0; i < hiScoreJSON.scores.length; i++){
let user = hiScoreJSON.scores[i].user;
let carNum = hiScoreJSON.scores[i].cars;
let difMode = hiScoreJSON.scores[i].mode;
let rate = hiScoreJSON.scores[i].rating;
let score = {
"scores": {
"user": user,
"cars": carNum,
"mode": difMode,
"rating": rate
}
};
hiScoreArray.push(score);
}
} | [
"static loadJson(pathToJson) {\n\t\tconsole.log(\"Loading story.json...\");\n\t\tvar r = new XMLHttpRequest();\n\t\tr.open(\"GET\", pathToJson, true);\n\t\tr.onload = function() {\n\t\t\tif (this.status >= 200 && this.status < 400)\n\t\t\t{\n\t\t\t\t// Set the active story to the loaded JSON\n\t\t\t\tstoryData.story = JSON.parse(this.responseText);\n\t\t\t\tStoryPlayer.initStory();\n\t\t\t}\n\t\t};\n\t\tr.send();\n\t\tconsole.log(\"story.js loaded!\");\n\t}",
"function LoadJson(){}",
"load(statsFile = Statistics.defaultLocation) {\n if (!fs.existsSync(path.dirname(statsFile))) {\n fs.mkdirSync(path.dirname(statsFile), { recursive: true });\n }\n if (!fs.existsSync(statsFile)) {\n if (fs.existsSync(\"./data/stats.json\")) {\n fs.renameSync(\"./data/stats.json\", statsFile);\n }\n else {\n console.error(\"No existing file! Creating file\");\n this.save();\n return;\n }\n }\n let object = JSON.parse(fs.readFileSync(statsFile, \"utf-8\"));\n for (const key in this) {\n if (this.hasOwnProperty(key) && object.hasOwnProperty(key)) {\n this[key] = object[key];\n }\n }\n }",
"function saveJson(){\n saveJSON(hiScoreArray, 'hiscores.json');\n}",
"function loadJSON(file) {\n return JSON.parse(FS.readFileSync(file, \"utf8\"));\n}",
"static loadGames() {\n let gameList = [];\n let dataFile = fs.readFileSync('./data/currentGames.json', 'utf8');\n if (dataFile === '') return gameList;\n\n let gameData = JSON.parse(dataFile);\n if (!Array.isArray(gameData)) {\n gameData = [gameData];\n }\n gameData.forEach((element) => {\n gameList.push(\n new Game(\n element.Name,\n element.Creator,\n element.CreatedOn,\n element.Players\n )\n );\n });\n\n return gameList;\n }",
"load(){\n const file_name = \"hashdumpyard.json\"\n const fs = require('fs')\n const dumped = fs.readFileSync(file_name)\n this.primary_table = JSON.parse(dumped).primary_table\n this.slot_size = this.primary_table.length\n this.processed = true\n }",
"function loadBatches(){\n let batch_data = fs.readFileSync('./batches.txt');\n batches = JSON.parse(batch_data);\n //console.log(batches);\n}",
"function loadJSON() {\n var client = new XMLHttpRequest();\n client.open(\"GET\", databasefilename, true);\n client.onreadystatechange = function () { //callback\n if (client.readyState === 4) {\n if (client.status === 200 || client.status === 0) {\n database_obj = JSON.parse(client.responseText);\n processInput();\n }\n }\n };\n client.send();\n }",
"function loadJSON() {\n return {\n resolve: {\n extensions: [\".json\"],\n },\n };\n}",
"function _load_hit_config() {\n var content = fs.readFileSync(task_directory_name + '/hit_config.json');\n return JSON.parse(content);\n}",
"function parseAudioJson() {\n fs.readFile(audioJson, 'utf8', function (err, data) {\n if (err) throw err;\n let newJson = JSON.parse(data);\n if (audio) {\n compareJson(audio, newJson);\n }\n audio = newJson;\n });\n}",
"function jsonObjFromFile(fn) {\n var jsonObj = [];\n try {\n var data = fs.readFileSync(fn, 'utf-8');\n if (data) {\n jsonObj = JSON.parse(data);\n } else {\n console.log(basicFile + \": no data\");\n }\n } catch (err) {\n if (err.code === 'ENOENT') {\n console.log('File not found:' + fn);\n } else {\n throw err;\n }\n }\n return jsonObj;\n}",
"static loadFromFile(statsFile = Statistics.defaultLocation) {\n if (!fs.existsSync(path.dirname(statsFile))) {\n fs.mkdirSync(path.dirname(statsFile), { recursive: true });\n }\n if (!fs.existsSync(statsFile)) {\n if (fs.existsSync(\"./data/stats.json\")) {\n fs.renameSync(\"./data/stats.json\", statsFile);\n }\n else {\n console.log(\"No existing statistics file! Creating file.\");\n let s = new Statistics({});\n s.save();\n return s;\n }\n }\n return new Statistics(JSON.parse(fs.readFileSync(statsFile, \"utf-8\")));\n }",
"function loadHoses() {\n $.get(\"/api/list/hoses\", {}\n ).done(function (data) {\n updateHoses(data.hoses);\n });\n}",
"function loadScores()\n{\n\tvar highscoresElement = document.getElementById(\"highscores\");\n\thighscoresElement.innerHTML = \"Highscores\";\n\tvar scores = new Array(LIST_SIZE);\n\t\n\tfor(var i = 0; i < scores.length; ++i){\n\t\tvar tmp;\n\t\tif(tmp = localStorage.getItem(SAVE_NAME + i)){\n\t\t\tscores[i] = tmp;\n\t\t}\n\t\telse{\n\t\t\tscores[i] = Math.floor(500/(i+1));\n\t\t}\n\t\t\n\t\thighscoresElement.innerHTML += \"<li>\" + (i + 1) + \". \" + scores[i] + \"</li>\";\n\t}\n\t\n\treturn scores;\n}",
"function getHighscores() {\n var highScores = JSON.parse(localStorage.getItem(highScoresLS));\n var hsMenu = $(\"#highscores-menu\").children();\n for (i=0; i<10; i++) {\n var displayItem = hsMenu[i];\n var scoredata = highScores[i+1];\n displayItem.innerHTML = `#${scoredata.rank} - ${scoredata.username}: ${scoredata.score}`;\n }\n return highScores;\n}",
"function loadJSON(url, callback) {\n // return immediately if data is in cache\n if (JayWalker.data[url]) {\n callback(JayWalker.data[url]);\n return;\n }\n // choose load method depending on protocol\n switch (window.location.protocol) {\n // loading over http/https\n case 'http:':\n case 'https:':\n var XHR_1 = new XMLHttpRequest();\n // override MIME in case server is misconfigured.\n XHR_1.overrideMimeType('application/json');\n XHR_1.open('GET', url, true);\n // Note: add after open to save cycles\n XHR_1.onreadystatechange = function () {\n if (XHR_1.readyState === 4 && XHR_1.status === 200) {\n JayWalker.data[url] = JSON.parse(XHR_1.responseText);\n callback(JayWalker.data[url]);\n }\n };\n XHR_1.send();\n break;\n // loading from local file system\n case 'file:':\n // inserts compiled JSON as script\n var script = document.createElement('script');\n script.type = 'text/javascript';\n script.onload = function () {\n callback(JayWalker.data[url]);\n };\n script.src = url.substring(0, url.length - 2);\n document.head.appendChild(script);\n break;\n // throw error if protocol unknown; I'm sorry future\n default:\n throw new Error('Unknown protocol');\n }\n }",
"function loadInentory() {\n let invFile = fs.readFileSync('inventory.json', 'utf8');\n\n return JSON.parse(invFile);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply the given update down the component hierarchy from this node, optionally excluding one node's subtree. This is useful for applying a full state update to one component while sending only "shared" state updates to the app root. | updateSelfAndChildren(stateUpdate, options = {}) {
if (!this.initialized) {
return;
}
const {store, cascade} = options;
Object.assign(this[store], stateUpdate);
if (store !== `state` || this.shouldComponentUpdate(null, this[store])) {
this.domPatcher.update(this.state);
if (cascade) {
for (const child of this.$panelChildren) {
if (options.exclude !== child) {
child.updateSelfAndChildren(stateUpdate, options);
}
}
}
}
} | [
"_updateStore(stateUpdate, options = {}) {\n const {cascade, store} = options;\n if (!this.initialized) {\n // just update store without patching DOM etc\n Object.assign(this[store], stateUpdate);\n } else {\n // update DOM, router, descendants etc.\n const updateHash = `$fragment` in stateUpdate && stateUpdate.$fragment !== this[store].$fragment;\n const cascadeFromRoot = cascade && !this.isPanelRoot;\n const updateOptions = {cascade, store};\n const rootOptions = {exclude: this, cascade, store};\n\n this.runHook(`preUpdate`, updateOptions, stateUpdate);\n if (cascadeFromRoot) {\n this.$panelRoot.runHook(`preUpdate`, rootOptions, stateUpdate);\n }\n\n this.updateSelfAndChildren(stateUpdate, updateOptions);\n if (cascadeFromRoot) {\n this.$panelRoot.updateSelfAndChildren(stateUpdate, rootOptions);\n }\n if (updateHash) {\n this.router.replaceHash(this[store].$fragment);\n }\n\n this.runHook(`postUpdate`, updateOptions, stateUpdate);\n if (cascadeFromRoot) {\n this.$panelRoot.runHook(`postUpdate`, rootOptions, stateUpdate);\n }\n }\n }",
"componentWillUpdate( nextProps ) {\n if ( this.props.packageId !== nextProps.packageId ) {\n this.props.actions.loadPackageDetailsAction(nextProps.packageId);\n this.props.actions.loadPackageDependenciesAction(nextProps.packageId);\n this.props.actions.loadPackageParentsAction(nextProps.packageId);\n }\n }",
"visitMerge_update_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"async _enqueueUpdate(){// Mark state updating...\nthis._updateState=this._updateState|STATE_UPDATE_REQUESTED;let resolve;const previousUpdatePromise=this._updatePromise;this._updatePromise=new Promise(res=>resolve=res);// Ensure any previous update has resolved before updating.\n// This `await` also ensures that property changes are batched.\nawait previousUpdatePromise;// Make sure the element has connected before updating.\nif(!this._hasConnected){await new Promise(res=>this._hasConnectedResolver=res);}// Allow `performUpdate` to be asynchronous to enable scheduling of updates.\nconst result=this.performUpdate();// Note, this is to avoid delaying an additional microtask unless we need\n// to.\nif(result!=null&&typeof result.then==='function'){await result;}resolve(!this._hasRequestedUpdate);}",
"update(transactions) {\n if (this.updateState != 0 /* Idle */)\n throw new Error(\"Calls to EditorView.update are not allowed while an update is in progress\");\n this.updateState = 2 /* Updating */;\n let state = this.state;\n for (let tr of transactions) {\n if (tr.startState != state)\n throw new RangeError(\"Trying to update state with a transaction that doesn't start from the previous state.\");\n state = tr.state;\n }\n let update = new ViewUpdate(this, state, transactions);\n let scrollTo = transactions.some(tr => tr.scrollIntoView) ? state.selection.primary : null;\n this.viewState.update(update, scrollTo);\n this.bidiCache = CachedOrder.update(this.bidiCache, update.changes);\n if (!update.empty)\n this.updatePlugins(update);\n let redrawn = this.docView.update(update);\n if (this.state.facet(styleModule) != this.styleModules)\n this.mountStyles();\n this.updateAttrs();\n this.updateState = 0 /* Idle */;\n if (redrawn || scrollTo || this.viewState.mustEnforceCursorAssoc)\n this.requestMeasure();\n for (let listener of this.state.facet(updateListener))\n listener(update);\n }",
"setState(updateObject) {\n super.setState(updateObject); // Trigger a layer update\n // Although conceptually layer.draw and compositeLayer.renderLayers are equivalent,\n // they are executed during different lifecycles.\n // draw can be called without calling updateState (e.g. most viewport changes),\n // while renderLayers can only be called during a recursive layer update.\n\n this.setNeedsUpdate();\n }",
"function modifyState (patch) {\n autoUpdate(patch); //apply changes to UIs\n appState = _.merge(appState, patch); //destructively update appState\n Object.freeze(appState); //freeze!\n }",
"_postUpdate(updateParams, forceUpdate) {\n // @ts-ignore (TS2531) this method is only called internally when internalState is defined\n let subLayers = this.internalState.subLayers;\n const shouldUpdate = !subLayers || this.needsUpdate();\n\n if (shouldUpdate) {\n const subLayersList = this.renderLayers(); // Flatten the returned array, removing any null, undefined or false\n // this allows layers to render sublayers conditionally\n // (see CompositeLayer.renderLayers docs)\n\n subLayers = Object(_utils_flatten__WEBPACK_IMPORTED_MODULE_2__[\"flatten\"])(subLayersList, Boolean); // @ts-ignore (TS2531) this method is only called internally when internalState is defined\n\n this.internalState.subLayers = subLayers;\n }\n\n Object(_debug__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(TRACE_RENDER_LAYERS, this, shouldUpdate, subLayers); // populate reference to parent layer (this layer)\n // NOTE: needs to be done even when reusing layers as the parent may have changed\n\n for (const layer of subLayers) {\n layer.parent = this;\n }\n }",
"visitFor_update_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitUpdate_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"_onApplyingUpdate(view, metadata) {\n if (view && _.isFunction(view.beforeApplyUpdate)) {\n view.beforeApplyUpdate(metadata);\n }\n }",
"function test_view_update_depth_logic() {\n let viewWrapper = make_view_wrapper();\n\n // create an instance-specific dummy method that counts calls t\n // _applyViewChanges\n let applyViewCount = 0;\n viewWrapper._applyViewChanges = function() {\n applyViewCount++;\n };\n\n // - view update depth basics\n Assert.equal(viewWrapper._viewUpdateDepth, 0);\n viewWrapper.beginViewUpdate();\n Assert.equal(viewWrapper._viewUpdateDepth, 1);\n viewWrapper.beginViewUpdate();\n Assert.equal(viewWrapper._viewUpdateDepth, 2);\n viewWrapper.endViewUpdate();\n Assert.equal(applyViewCount, 0);\n Assert.equal(viewWrapper._viewUpdateDepth, 1);\n viewWrapper.endViewUpdate();\n Assert.equal(applyViewCount, 1);\n Assert.equal(viewWrapper._viewUpdateDepth, 0);\n\n // - don't go below zero! (and don't trigger.)\n applyViewCount = 0;\n viewWrapper.endViewUpdate();\n Assert.equal(applyViewCount, 0);\n Assert.equal(viewWrapper._viewUpdateDepth, 0);\n\n // - depth zeroed on clear\n viewWrapper.beginViewUpdate();\n viewWrapper.close(); // this does little else because there is nothing open\n Assert.equal(viewWrapper._viewUpdateDepth, 0);\n}",
"_onAppliedUpdate(view, metadata) {\n if (view && _.isFunction(view.afterApplyUpdate)) {\n view.afterApplyUpdate(metadata);\n }\n }",
"updateLayers() {\n // NOTE: For now, even if only some layer has changed, we update all layers\n // to ensure that layer id maps etc remain consistent even if different\n // sublayers are rendered\n const reason = this.needsUpdate();\n\n if (reason) {\n this.setNeedsRedraw(`updating layers: ${reason}`); // Force a full update\n\n this.setLayers(this._nextLayers || this._lastRenderedLayers, reason);\n } // Updated, clear the backlog\n\n\n this._nextLayers = null;\n }",
"setNeedsUpdate() {\n if (this.internalState) {\n this.context.layerManager.setNeedsUpdate(String(this));\n this.internalState.needsUpdate = true;\n }\n }",
"_update() {\r\n // Clear the dirty flag to indicate the update occurred.\r\n this._dirty = false;\r\n // Bail early if there are no widgets to layout.\r\n let widgets = this.order || this.widgets;\r\n if (widgets.length === 0) {\r\n return;\r\n }\r\n // Set spacing by margins\r\n let spacing = this.minimumSpacing.toString() + 'px';\r\n if (this.isHorizontal()) {\r\n for (let i = 0; i < widgets.length - 1; ++i) {\r\n widgets[i].node.style.marginRight = spacing;\r\n }\r\n }\r\n else {\r\n for (let i = 0; i < widgets.length - 1; ++i) {\r\n widgets[i].node.style.marginBottom = spacing;\r\n }\r\n }\r\n // Update stretch styles if set\r\n if (this._evenSizes || this.stretchType) {\r\n let basis = null;\r\n let grow = null;\r\n let shrink = null;\r\n if (this._evenSizes) {\r\n basis = 0;\r\n grow = 1;\r\n }\r\n else {\r\n switch (this._stretchType) {\r\n case 'grow':\r\n // Allow items to grow from default size\r\n grow = 1;\r\n shrink = 0;\r\n break;\r\n case 'shrink':\r\n // Allow items to shrink from default size\r\n grow = 0;\r\n shrink = 1;\r\n break;\r\n case 'both':\r\n // Both growing and shrinking is allowed.\r\n grow = 1;\r\n shrink = 1;\r\n break;\r\n case 'fixed':\r\n // Disallow both growing and shrinking.\r\n grow = 0;\r\n shrink = 0;\r\n break;\r\n default:\r\n throw new TypeError('Invalid stretch type: ' + this._stretchType);\r\n }\r\n }\r\n for (let i = 0; i < widgets.length; ++i) {\r\n let style = widgets[i].node.style;\r\n if (basis !== null) {\r\n // Can only be 0, so no unit needed\r\n style.flexBasis = basis.toString();\r\n }\r\n if (grow !== null) {\r\n style.flexGrow = grow.toString();\r\n }\r\n if (shrink !== null) {\r\n style.flexShrink = shrink.toString();\r\n }\r\n }\r\n }\r\n // Update display order\r\n for (let i = 0; i < widgets.length; ++i) {\r\n let widget = widgets[i];\r\n widget.node.style.order = this.order ? i.toString() : null;\r\n }\r\n }",
"onUpdateFolder() {\n this.store.query(\"folder\", {})\n .then((results) => {\n // Rebuild the tree\n this.send('buildTree', { folders: results });\n })\n .catch(() => {\n this.growl.error('Error', 'Error while retrieving folders');\n });\n }",
"applyMutator(mutator) {\n const delta = mutator(this._state);\n // add to current list of deltas\n this._deltas = this._joinFunction(this._deltas, delta);\n // update the current backend state\n this._state = this._joinFunction(this._state, delta);\n }",
"_compareAndCopy(newJst, topNode, jstComponent, forceUpdate, level) {\n let oldIndex = 0;\n let newIndex = 0;\n let itemsToDelete = [];\n let indicesToRemove = [];\n\n // console.log(\"CAC>\" + \" \".repeat(level*2), this.tag + this.id, newJst.tag+newJst.id);\n\n // Check to see if this the old and new node are the same\n if (this.id == newJst.id) {\n return false;\n }\n\n // First check the attributes, props and events\n // But only if we aren't the topNode\n if (!topNode) {\n if (forceUpdate || this.opts.forceUpdate || this.tag !== newJst.tag) {\n return true;\n }\n\n // Blindly copy the JST options\n this.opts = newJst.opts;\n \n // Just fix all the attributes inline\n for (let attrName of Object.keys(this.attrs)) {\n if (!newJst.attrs[attrName]) {\n delete this.attrs[attrName];\n if (this.isDomified) {\n this.el.removeAttribute(attrName);\n }\n }\n else if (newJst.attrs[attrName] !== this.attrs[attrName]) {\n this.attrs[attrName] = newJst.attrs[attrName];\n if (this.isDomified) {\n //refactor\n let val = newJst.attrs[attrName];\n if (this.jstComponent && (attrName === \"class\" || attrName === \"id\") &&\n val.match(/(^|\\s)-/)) {\n // Add scoping for IDs and Class names\n val = val.replace(/(^|\\s)(--?)/g,\n (m, p1, p2) => p1 + (p2 === \"-\" ?\n this.jstComponent.getClassPrefix() :\n this.jstComponent.getFullPrefix()));\n }\n this.el.setAttribute(attrName, val);\n }\n }\n }\n for (let attrName of Object.keys(newJst.attrs)) {\n if (!this.attrs[attrName]) {\n this.attrs[attrName] = newJst.attrs[attrName];\n if (this.isDomified) {\n //refactor\n let val = newJst.attrs[attrName];\n if (this.jstComponent && (attrName === \"class\" || attrName === \"id\") &&\n val.match(/(^|\\s)-/)) {\n // Add scoping for IDs and Class names\n val = val.replace(/(^|\\s)(--?)/g,\n (m, p1, p2) => p1 + (p2 === \"-\" ?\n this.jstComponent.getClassPrefix() :\n this.jstComponent.getFullPrefix()));\n }\n this.el.setAttribute(attrName, val);\n }\n }\n }\n\n if (this.props.length || newJst.props.length) {\n let fixProps = false;\n \n // Just compare them in order - if they happen to be the same,\n // but in a different order, we will do a bit more work than necessary\n // but it should be very unlikely that that would happen\n if (this.props.length != newJst.props.length) {\n fixProps = true;\n }\n else {\n for (let i = 0; i < this.props.length; i++) {\n if (this.props[i] !== newJst.props[i]) {\n fixProps = true;\n break;\n }\n }\n }\n \n if (fixProps) {\n if (this.isDomified) {\n for (let prop of this.props) {\n delete this.el[prop];\n }\n for (let prop of newJst.props) {\n this.el[prop] = true;\n }\n }\n this.props = newJst.props;\n }\n }\n \n // Fix all the events\n for (let eventName of Object.keys(this.events)) {\n if (!newJst.events[eventName]) {\n if (this.isDomified) {\n this.el.removeEventListener(eventName, this.events[eventName].listener);\n }\n delete this.events[eventName];\n }\n else if (newJst.events[eventName].listener !== this.events[eventName].listener) {\n if (this.isDomified) {\n this.el.removeEventListener(eventName, this.events[eventName].listener);\n this.el.addEventListener(eventName, newJst.events[eventName].listener);\n }\n this.events[eventName] = newJst.events[eventName];\n }\n }\n for (let eventName of Object.keys(newJst.events)) {\n if (!this.events[eventName]) {\n this.events[eventName] = newJst.events[eventName];\n if (this.isDomified) {\n this.el.addEventListener(eventName, newJst.events[eventName].listener);\n }\n }\n }\n \n }\n\n if (!forceUpdate && !this.opts.forceUpdate) {\n // First a shortcut in the case where all\n // contents are removed\n\n // TODO - can clear the DOM in one action, but\n // need to take care of the components so that they\n // aren't still thinking they are in the DOM\n // if (this.contents.length && !newJst.contents.length) {\n // if (this.el) {\n // this.el.textContent = \"\";\n // //this.contents = [];\n // //return false;\n // }\n // }\n \n \n // Loop through the contents of this element and compare\n // to the contents of the newly created element\n while (true) {\n let oldItem = this.contents[oldIndex];\n let newItem = newJst.contents[newIndex];\n\n if (!oldItem || !newItem) {\n break;\n }\n\n // Types of items in the contents must match or don't continue\n if (oldItem.type !== newItem.type) {\n break;\n }\n\n if (oldItem.type === JstElementType.JST_ELEMENT) {\n\n // This detects items that are being replaced by pre-existing items\n // They are too complicated to try to do in place replacements\n if (oldItem.value.id !== newItem.value.id && newItem.value._refCount > 1) {\n break;\n }\n \n // Descend into the JstElement and compare them and possibly copy their\n // content in place\n let doReplace = oldItem.value._compareAndCopy(newItem.value, false,\n jstComponent, undefined, level+1);\n if (doReplace) {\n break;\n }\n\n // Need to decrement the ref counts for items that didn't change\n if (oldItem.value.id === newItem.value.id) {\n this._deleteItem(newItem);\n }\n \n }\n else if (oldItem.type === JstElementType.JST_COMPONENT) {\n // If the tags are the same, then we must descend and compare\n if (oldItem.value._jstId !== newItem.value._jstId) {\n\n // Small optimization since often a list is modified with a\n // single add or remove\n\n let nextOldItem = this.contents[oldIndex+1];\n let nextNewItem = newJst.contents[newIndex+1];\n\n if (!nextOldItem || !nextNewItem) {\n // no value of optimizing when we are at the end of the list\n break;\n }\n\n if (nextNewItem.type === JstElementType.JST_COMPONENT &&\n oldItem.value._jstId === nextNewItem.value._jstId) {\n // We have added a single item - TBD\n let nextEl = oldItem.value._jstEl._getFirstEl();\n this._moveOrRenderInDom(newItem, jstComponent, nextEl);\n this.contents.splice(oldIndex, 0, newItem);\n newIndex++;\n oldIndex++;\n newItem = nextNewItem;\n }\n else if (nextOldItem.type === JstElementType.JST_COMPONENT &&\n nextOldItem.value._jstId === newItem.value._jstId) {\n // We have deleted a single item\n this.contents.splice(oldIndex, 1);\n itemsToDelete.push(oldItem);\n }\n else if (nextOldItem.type === JstElementType.JST_COMPONENT &&\n nextNewItem.type === JstElementType.JST_COMPONENT &&\n nextOldItem.value._jstId === nextNewItem.value._jstId) {\n // We have swapped in an item\n let nextEl = nextOldItem.value._jstEl._getFirstEl();\n this._moveOrRenderInDom(newItem, jstComponent, nextEl);\n this.contents[oldIndex] = newItem;\n oldIndex++;\n newIndex++;\n newItem = nextNewItem;\n itemsToDelete.push(oldItem);\n }\n else {\n break;\n }\n\n }\n\n // Don't bother descending into JstComponents - they take care of themselves\n \n }\n else if (oldItem.type === JstElementType.TEXTNODE) {\n\n if (oldItem.value !== newItem.value) {\n\n // For textnodes, we just fix them inline\n if (oldItem.el) {\n oldItem.el.textContent = newItem.value;\n }\n oldItem.value = newItem.value;\n }\n }\n\n oldIndex++;\n newIndex++;\n \n if (newItem.type === JstElementType.JST_COMPONENT) {\n // Unhook this reference\n newItem.value._unrender();\n }\n }\n }\n\n // Need to copy stuff - first delete all the old contents\n let oldStartIndex = oldIndex;\n let oldItem = this.contents[oldIndex];\n\n while (oldItem) {\n // console.log(\"CAC> \" + \" \".repeat(level*2), \"deleting old item :\", oldItem.value.tag, oldItem.value.id);\n itemsToDelete.push(oldItem);\n oldIndex++;\n oldItem = this.contents[oldIndex];\n }\n\n // Remove unneeded items from the contents list\n this.contents.splice(oldStartIndex, oldIndex - oldStartIndex);\n\n if (newJst.contents[newIndex]) {\n\n // Get list of new items that will be inserted\n let newItems = newJst.contents.splice(newIndex, newJst.contents.length - newIndex);\n\n //console.log(\"CAC> \" + \" \".repeat(level*2), \"new items being added:\", newItems);\n \n newItems.forEach(item => {\n if (item.type === JstElementType.JST_ELEMENT) {\n if (item.value.el && item.value.el.parentNode) {\n item.value.el.parentNode.removeChild(item.value.el);\n if (this.el) {\n this.el.appendChild(item.value.el);\n }\n else {\n delete(this.el);\n }\n }\n else if (this.el) {\n // Need to add it\n this.el.appendChild(item.value.dom(jstComponent));\n }\n else if (jstComponent && jstComponent.parentEl) {\n jstComponent.parentEl.appendChild(item.value.dom(jstComponent));\n }\n else {\n console.warn(\"Not adding an element to the DOM\", item.value.tag, item, this, jstComponent);\n }\n }\n else if (item.type === JstElementType.TEXTNODE) {\n if (this.el) {\n // Need to add it\n if (item.el) {\n if (item.el.parentNode) {\n item.el.parentNode.removeChild(item.el);\n }\n this.el.appendChild(item.el);\n }\n else {\n item.el = document.createTextNode(item.value);\n this.el.appendChild(item.el);\n }\n }\n else if (jstComponent && jstComponent.parentEl) {\n item.el = document.createTextNode(item.value);\n jstComponent.parentEl.appendChild(item.el);\n }\n else {\n console.warn(\"Not adding an element to the DOM\", item.value.tag, item, this, jstComponent);\n }\n }\n else if (item.type === JstElementType.JST_COMPONENT) {\n this._moveOrRenderInDom(item, jstComponent);\n }\n });\n this.contents.splice(oldStartIndex, 0, ...newItems);\n }\n\n for (let itemToDelete of itemsToDelete) {\n this._deleteItem(itemToDelete); \n } \n \n // console.log(\"CAC>\" + \" \".repeat(level*2), \"/\" + this.tag+this.id);\n return false;\n \n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
if the email isn't already in the database, insert it | function insertEmail (email,callback){
console.log('insertEmail: ' + email);
db.connect(function(error){
if (error){
return console.log('CONNECTION error: ' + error);
}
this.query().insert('emails', ['email'], [email] )
.execute(function(error, result) {
if (error) {
return console.log('ERROR: ' + error);
}
console.log('GENERATED id: ' + result.id);
callback(result);
})
});
} | [
"function saveEmail(email) {\n var newSubscriptionRef = db.push();\n newSubscriptionRef.set({\n email: email,\n });\n}",
"function checkEmail (email,callback){\n console.log('checkEmail');\n db.connect(function(error){\n if (error){\n return console.log('CONNECTION error: ' + error);\n }\n this.query().select('*').from('emails').where('email=?',[email])\n .execute(function(error, rows) {\n if (error) {\n return console.log('ERROR: ' + error);\n }\n console.log(rows.length + ' ROWS');\n if (isEmpty(rows)){\n insertEmail(email,callback);\n } else {\n updateCount(rows[0],callback);\n }\n })\n });\n}",
"async ensureUnique () {\n\t\tconst user = await this.data.users.getOneByQuery(\n\t\t\t{\n\t\t\t\tsearchableEmail: decodeURIComponent(this.request.body.toEmail).toLowerCase()\n\t\t\t},\n\t\t\t{\n\t\t\t\thint: UserIndexes.bySearchableEmail\n\t\t\t}\n\t\t);\n\t\tif (user) {\n\t\t\tthrow this.errorHandler.error('emailTaken');\n\t\t}\n\t}",
"async uniqueEmail(email){\n let user=await dao.find(this.USERS,{email: email})\n if(user.length)\n return false\n return true\n }",
"static checkUserExists(req, res, next) {\n User.getUserByEmail(req.body.email)\n .then(newUser =>{\n if (newUser.rows[0]) return errHandle(409, 'user already exists', res);\n return next();\n })\n }",
"function saveSubmission (req) {\n //open DB connection\n const pool = db.connection.INSTANCE();\n \n var name = [req.body.email];\n var sql = \"INSERT INTO tokenswap(email) VALUES($1)\";\n //Save to DB and close connection\n pool.query(sql, name, (err, res) => {\n console.log(err, res);\n });\n return;\n}",
"function insertData(e) {\n e.preventDefault();\n const fullName = document.getElementById('signup-name').value + \" \" + document.getElementById('signup-surname').value;\n const email = document.querySelector('#signup-email').value;\n const password = document.querySelector('#signup-password').value;\n idUser++;\n set(ref(database, \"Users/\" + idUser), {\n id: idUser,\n userName: fullName,\n userEmail: email\n })\n .then(() => {\n createUserWithEmailAndPassword(auth, email, password)\n .then((userCredential) => {\n signupForm.reset();\n $('#signupModal').modal('hide');\n })\n .catch((error) => {\n const errorCode = error.code;\n const errorMessage = error.message;\n });\n alert(\"Datos guardados correctamente\");\n })\n .catch((error) => {\n alert(\"Ha ocurrido un error\" + error);\n })\n}",
"async function addFamilyMember(name, date, email, role) {\n let sql = `\n INSERT INTO family\n (familyId, name, birthday, email, role)\n VALUES\n (?, ?, ?, ?, ?)\n ;\n `;\n let sqlId = `SELECT userId FROM users WHERE email = ?`;\n\n try {\n let id = await db.query(sqlId, [email]);\n await db.query(sql, [id[0].userId, name, date, email, role]);\n return \"/user\";\n } catch (error) {\n return \"/user/AddFamilyMember?valid=false\"\n }\n}",
"function saveWithEmail(data, cb) {\n actions.log('saveWithEmail=' + JSON.stringify(data));\n actions.check(data, ['_diag', 'diagStart', 'diagEnd'\n\n , 'diags', 'address', 'price'\n ], (err, r) => {\n if (err) return cb(err, r);\n //\n orderExists(data, (err, r) => {\n if (err) return cb(err, r);\n\n if (data._client) {\n return save(data, cb);\n }\n\n if (data._client) {\n if (data._client._id) data._client = data._client._id;\n return save(data, cb);\n }\n else {\n\n\n actions.check(data, ['email', 'clientType'], (err, r) => {\n if (err) return cb(err, r);\n _setUserUsingEmailAndClientType();\n });\n }\n\n function _setUserUsingEmailAndClientType() {\n UserAction.get({\n email: data.email,\n userType: 'client',\n clientType: data.clientType,\n }, (err, r) => {\n if (err) return cb(err, r);\n actions.log('saveWithEmail=user:get:return' + JSON.stringify(r));\n if (r) {\n data._client = r._id;\n return save(data, cb);\n }\n else {\n UserAction.createClientIfNew({\n email: data.email\n }, (err, r) => {\n if (err) return cb(err, r);\n data._client = r._id;\n return save(data, cb);\n });\n }\n });\n }\n });\n // \n });\n}",
"signup(username, password, email, callback) {\n let sql = \"SELECT * FROM users WHERE username=$username\";\n var self = this;\n this.db.get(sql, {\n $username: username\n }, (err, rows) => {\n if(err) {\n throw(err);\n } else if(!rows) {\n let insert_statement = \"INSERT INTO users(username, password, admin, email) VALUES ($username, $password, $admin, $email)\";\n this.db.run(insert_statement, {\n $username: username,\n $password: password,\n $admin: false,\n $email: email,\n }, (err) => {\n if(err) {\n throw(err);\n }\n });\n // logs in if conditions are met\n //console.log(\"gave true\");\n callback(true);\n } else {\n //console.log(rows);\n callback(false);\n }\n\n });\n }",
"function insertRecord (data, done) {\n Klass.DB().collection(Klass.getCollectionName()).insert(data, {safe: true, new: true}, function (err, newRecord) {\n if (err || !newRecord) {\n return done(new Klass.Error('persistence', err ? err.toString() : newRecord));\n }\n return done(null, newRecord);\n });\n }",
"function addNewUser(socket, user){\n var findUsers = users.filter(function(us){\n if(us.email === user.email)\n return true;\n return false;\n });\n if(!findUsers.length){\n isNewUser = true;\n socket.email = user.email;\n socket.nickname = user.nickname;\n socket.avatar = user.avatar;\n socket.unique = getUnique(user.email);\n users.push(socket);\n io.sockets.emit('newUserConnect', {unique: getUnique(), nickname: user.nickname, avatar: user.avatar});\n }else{\n //User connect again.......\n }\n }",
"async function addSnack(company_ID, snack_ID) {\n //\n //Check if the user has already added the snack\n let record = await db('company_snacks').where({ company_ID, snack_ID });\n console.log('record: ', record);\n //\n //If the record exists, just let them know\n if (record && record.length) {\n return Promise.resolve([\n {\n status: 200,\n message: 'Already saved snack',\n },\n ]);\n } else {\n //\n //Else create it\n return db('company_snacks')\n .returning('*')\n .insert({\n company_ID,\n snack_ID,\n });\n }\n}",
"function addAccount(message, userID, steam32ID, mmr){\n sql.run(\"REPLACE INTO accounts (userID, steam32ID, mmr, submitTime) VALUES (?, ?, ?, ?)\",\n [userID, steam32ID, mmr, (new Date).getTime()]).then(()=>{\n message.channel.send(\"Success! <@\"+userID+\">'s MMR has be linked\");\n }).catch(()=>{\n sql.run(\"CREATE TABLE IF NOT EXISTS accounts (userID TEXT PRIMARY KEY, steam32ID TEXT, mmr INTEGER, submitTime INTEGER)\").then(() => {\n sql.run(\"INSERT INTO accounts (userID, steam32ID, mmr, submitTime) VALUES (?, ?, ?, ?)\",\n [userID, steam32ID, mmr, (new Date).getTime()]).then(() =>{\n message.channel.send(\"Success! <@\"+userID+\">'s MMR has be linked\");\n });\n });\n });\n}",
"function RegisterAccount(username, pass, email, phone, name, birthday, sex, avatarLink) {\n user.ThemUser(username, name, birthday, sex, phone, email, pass, avatarLink);\n return userIsExisting(username);\n}",
"async registerNewUser(email, password, displayName) {\n console.log(\"registering new user\");\n try {\n let user = await app\n .auth()\n .createUserWithEmailAndPassword(email, password);\n let userObj = {\n id: user.user.uid,\n displayName,\n favorites: [],\n store: defaultSpices,\n };\n localStorage.setItem(\"sprackId\", user.user.uid);\n await db.collection(\"users\").doc(userObj.id).set(userObj);\n return await this.fetchUserData(user.user.uid);\n } catch (error) {\n console.log(error);\n return error;\n }\n }",
"function create(req, res) {\n const { firstName, lastName, email: emailAnycase, password } = req.body;\n const email = String(emailAnycase).toLowerCase();\n if (firstName && lastName && email && password) {\n // Validate email address\n if (!Auth.isValidEmail(email)) {\n res.status(400).send({ success: false, message: 'email is invalid' });\n return;\n }\n\n // Verify nobody exists as an applicant with that email\n ApplicantModel.findOne({ email }, (err, applicant) => {\n if (err) throw err;\n if (!applicant) {\n // Verify nobody exists as an organizer with that email\n OrganizerModel.findOne({ email }, (err, duplicate) => {\n if (err) throw err;\n if (duplicate) {\n res\n .status(403)\n .send({ success: false, message: 'organizer with that email already exists' });\n return;\n }\n // If the email is unique, create the organizer\n\n // hash password\n const passwordHash = bcrypt.hashSync(password, 10);\n\n // create applicant object\n const applicant = new ApplicantModel({\n firstName,\n lastName,\n email,\n passwordHash\n });\n\n // store applicant in Mongo\n applicant\n .save()\n .then(() => res.send({ success: true }))\n .catch(err => res.status(500).send({ message: err.message }));\n });\n } else {\n res\n .status(403)\n .send({ success: false, message: 'applicant with that email already exists' });\n }\n });\n } else {\n res.status(400).send({ success: false, message: 'Malformed input' });\n }\n}",
"function addUser(userInfo){\n const db = firebase.firestore()\n const usersCollection = db.collection('users')\n usersCollection.add({\n email: userInfo.email,\n name: userInfo.displayName,\n \n })\n .then(function(docRef){\n console.log(\"Document written with ID: \", docRef.id)\n\n })\n .catch(function(error){\n console.error(\"Error adding document: \", error)\n })\n}",
"function insert(user) {\n return dataBase('users').insert(user)\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function name : validateNewsLetterMailForm Return type : none Date created :02May2011 Date last modified : 02May2011 Author : Deepesh Pathak Last modified by : Deepesh Pathak Comments : This function is used to validate the news letter mail form User instruction : validateNewsLetterMailForm(formID) | function validateNewsLetterMailForm(formID)
{
if(validateForm(formID, 'frmNewsLetterName', 'Title', 'R','frmSubscriberList','Subscriber','R'))
{
return true;
}
else
{
return false;
}
} | [
"function validateMessage(formname)\n{\n\t\n if(validateForm(formname,'frmSendToIds', 'Select Users', 'R', 'frmMessageType', 'Message Type', 'R', 'frmMessageSubject', 'message Subject', 'R'))\n {\t\n\t\t\n\t\t\n return true;\n } \n else \n {\n return false;\n } \n}",
"function validateForm() {\n clientErrorStorage = new Object();\n var summaryTextExistence = new Object();\n var validForm = true;\n\n jQuery.watermark.hideAll();\n pauseTooltipDisplay = true;\n\n if (validateClient) {\n // Turn on this flag to avoid prematurely writing out messages which will cause performance issues if MANY\n // fields have validation errors simultaneously (first we are only checking for errors, not checking and\n // writing simultaneously like normal)\n clientErrorExistsCheck = true;\n\n // Temporarily turn off this flag to avoid traversing unneeded logic (all messages will be shown at the end)\n messageSummariesShown = false;\n\n // Validate the whole form\n validForm = jq(\"#kualiForm\").valid();\n\n // Handle field message bubbling manually, but do not write messages out yet\n jQuery(\"div[data-role='InputField']\").each(function () {\n var id = jQuery(this).attr('id');\n var field = jQuery(\"#\" + id);\n var data = getValidationData(field);\n var parent = field.data(\"parent\");\n handleMessagesAtGroup(parent, id, data, true);\n });\n\n // Toggle the flag back to default\n clientErrorExistsCheck = false;\n\n // Message summaries are going to be shown\n messageSummariesShown = true;\n\n // Finally, write the result of the validation messages\n writeMessagesForPage();\n }\n\n if (!validForm) {\n validForm = false;\n\n //ensure all non-visible controls are visible to the user\n jQuery(\".error:not(:visible)\").each(function () {\n cascadeOpen(jQuery(this));\n });\n\n jumpToTop();\n showClientSideErrorNotification();\n jQuery(\".uif-pageValidationMessages li.uif-errorMessageItem:first > a\").focus();\n }\n\n jq.watermark.showAll();\n pauseTooltipDisplay = false;\n\n return validForm;\n}",
"function validate_techEdit(){\n\tvar emailExp = /^[\\w\\-\\.\\+]+\\@[a-zA-Z0-9\\.\\-]+\\.[a-zA-z0-9]{2,4}$/;\t\n\tif(document.frmTech.TechFirstName.value == ''){\n\t\tdocument.getElementById('lblTechFirstName').innerHTML = 'This field is required';\n\t\tdocument.frmTech.TechFirstName.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechFirstName').innerHTML = '';\n\t}\n\tif(regex.test(document.frmTech.TechFirstName.value)){\n\t\tdocument.getElementById('lblTechFirstName').innerHTML = 'This field contains special chars';\n\t\tdocument.frmTech.TechFirstName.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechFirstName').innerHTML = '';\n\t}\n\tif(document.frmTech.TechMiddleName.value == ''){\n\t\tdocument.getElementById('lblTechMiddleName').innerHTML = 'This field is required';\n\t\tdocument.frmTech.TechMiddleName.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechMiddleName').innerHTML = '';\n\t}\n\tif(regex.test(document.frmTech.TechMiddleName.value)){\n\t\tdocument.getElementById('lblTechMiddleName').innerHTML = 'This field contains special chars';\n\t\tdocument.frmTech.TechMiddleName.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechMiddleName').innerHTML = '';\n\t}\t\n\tif(document.frmTech.TechLastName.value == ''){\n\t\tdocument.getElementById('lblTechLastName').innerHTML = 'This field is required';\n\t\tdocument.frmTech.TechLastName.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechLastName').innerHTML = '';\n\t}\n\tif(regex.test(document.frmTech.TechLastName.value)){\n\t\tdocument.getElementById('lblTechLastName').innerHTML = 'This field contains special chars';\n\t\tdocument.frmTech.TechLastName.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechLastName').innerHTML = '';\n\t}\t\t\t\n\tif(document.frmTech.TechEmailID.value == ''){\n\t\tdocument.getElementById('lblTechEmailID').innerHTML = 'This field is required';\n\t\tdocument.frmTech.TechEmailID.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechEmailID').innerHTML = '';\n\t}\n\tif(!document.frmTech.TechEmailID.value.match(emailExp)){\n\t\tdocument.getElementById('lblTechEmailID').innerHTML = \"Required Valid Email ID.\";\n\t\tdocument.frmTech.TechEmailID.focus();\n\t\treturn false;\n\t}\n\telse{\n\t\tdocument.getElementById('lblTechEmailID').innerHTML = '';\n\t}\n\tif(document.frmTech.TechContactNo.value == ''){\n\t\tdocument.getElementById('lblTechContactNo').innerHTML = 'This field is required';\n\t\tdocument.frmTech.TechContactNo.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechContactNo').innerHTML = '';\n\t}\n\tif(regex.test(document.frmTech.TechContactNo.value)){\n\t\tdocument.getElementById('lblTechContactNo').innerHTML = 'This field contains special chars';\n\t\tdocument.frmTech.TechContactNo.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechContactNo').innerHTML = '';\n\t}\t\n\t/*if(document.frmTech.TechAltPhone.value == ''){\n\t\tdocument.getElementById('lblTechAltPhone').innerHTML = 'This field is required';\n\t\tdocument.frmTech.TechAltPhone.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechAltPhone').innerHTML = '';\n\t}*/\n\t/*if(regex.test(document.frmTech.TechAltPhone.value)){\n\t\tdocument.getElementById('lblTechAltPhone').innerHTML = 'This field contains special chars';\n\t\tdocument.frmTech.TechAltPhone.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechAltPhone').innerHTML = '';\n\t}*/\n\tif(document.frmTech.TechPicture.value != ''){\n\t\tvar str=document.getElementById('TechPicture').value;\n\t\tvar bigstr=str.lastIndexOf(\".\");\n\t\tvar ext=str.substring(bigstr+1);\n\t\tif(ext == 'jpg' || ext == 'JPG' || ext == 'jpeg' || ext == 'JPEG' || ext == 'png' || ext == 'PNG' || ext == 'gif' || ext == 'GIF' ){\n\t\t\tdocument.getElementById('lblTechPicture').innerHTML = '';\n\t\t}else{\n\t\t\tdocument.getElementById('lblTechPicture').innerHTML = 'Please enter a valid image';\n\t\t\treturn false;\n\t\t}\n\t}\n\tif(document.frmTech.TechAddress.value == ''){\n\t\tdocument.getElementById('lblTechAddress').innerHTML = 'This field is required';\n\t\tdocument.frmTech.TechAddress.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechAddress').innerHTML = '';\n\t}\n\tif(document.frmTech.TechCity.value == ''){\n\t\tdocument.getElementById('lblTechCity').innerHTML = 'This field is required';\n\t\tdocument.frmTech.TechCity.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechCity').innerHTML = '';\n\t}\n\tif(regex.test(document.frmTech.TechCity.value)){\n\t\tdocument.getElementById('lblTechCity').innerHTML = 'This field contains special chars';\n\t\tdocument.frmTech.TechCity.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechCity').innerHTML = '';\n\t}\t\n\tif(document.frmTech.TechState.value == ''){\n\t\tdocument.getElementById('lblTechState').innerHTML = 'This field is required';\n\t\tdocument.frmTech.TechState.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechState').innerHTML = '';\n\t}\n\tif(regex.test(document.frmTech.TechState.value)){\n\t\tdocument.getElementById('lblTechState').innerHTML = 'This field contains special chars';\n\t\tdocument.frmTech.TechState.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechState').innerHTML = '';\n\t}\t\n\tif(document.frmTech.TechZipcode.value == ''){\n\t\tdocument.getElementById('lblTechZipcode').innerHTML = 'This field is required';\n\t\tdocument.frmTech.TechZipcode.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechZipcode').innerHTML = '';\n\t}\n\tif(regex.test(document.frmTech.TechZipcode.value)){\n\t\tdocument.getElementById('lblTechZipcode').innerHTML = 'This field contains special chars';\n\t\tdocument.frmTech.TechZipcode.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechZipcode').innerHTML = '';\n\t}\t\n\tif(document.frmTech.TechDateBirth.value == ''){\n\t\tdocument.getElementById('lblTechDateBirth').innerHTML = 'This field is required';\n\t\tdocument.frmTech.TechDateBirth.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechDateBirth').innerHTML = '';\n\t}\n\t/*if(document.frmTech.TechCompanyName.value == ''){\n\t\tdocument.getElementById('lblTechCompanyName').innerHTML = 'This field is required';\n\t\tdocument.frmTech.TechCompanyName.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechCompanyName').innerHTML = '';\n\t}*/\n\t/*if(document.frmTech.TechSSN.value == ''){\n\t\tdocument.getElementById('lblTechSSN').innerHTML = 'This field is required';\n\t\tdocument.frmTech.TechSSN.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechSSN').innerHTML = '';\n\t}*/\n\t/*if(document.frmTech.TechFEIN.value == ''){\n\t\tdocument.getElementById('lblTechFEIN').innerHTML = 'This field is required';\n\t\tdocument.frmTech.TechFEIN.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechFEIN').innerHTML = '';\n\t}*/\n\t/*if(document.frmTech.TechPicture.value == ''){\n\t\tdocument.getElementById('lblTechPicture').innerHTML = 'This field is required';\n\t\tdocument.frmTech.TechPicture.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechPicture').innerHTML = '';\n\t}*/\n\tif(document.frmTech.TechPayGrade.value == ''){\n\t\tdocument.getElementById('lblTechPayGrade').innerHTML = 'This field is required';\n\t\tdocument.frmTech.TechPayGrade.focus();\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechPayGrade').innerHTML = '';\n\t}\n\tvar chk=$('input:checkbox[name=TechPayble[]]:checked').length;\n\tif(chk == 0){\n\t\tdocument.getElementById('lblTechPayble').innerHTML = 'This field is required';\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('lblTechPayble').innerHTML = '';\n\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\n}",
"function formVerify() {\n if (formInfo.contactMsg.value !== \"\") {\n if (emailRegex.test(formInfo.contactEmail.value)) {\n if (formInfo.contactName.value !== \"\") {\n return \"allGood\";\n }\n return \"nameInvalid\";\n }\n return \"emailInvalid\";\n }\n\n return \"msgInvalid\";\n}",
"function ValidateViewCheck()\n\t{\n\t\t//Set short message with the error code\t\n\t\tvar ShortMessage=ErChkLstSht002;\n\t\t//set long message as empty\n\t\tvar LongMessage=\"\";\n\t\tLongMessage=CheckDDL(LongMessage);\n\t\t//check textbox [from] check number is empty\n\t\tif(true==IstxtEmpty('txtFrom'))\n\t\t{\n\t\t\t//check long message is empty\n\t\t\tif(\"\"==LongMessage)\n\t\t\t{\n\t\t\t\t//set long message\n\t\t\t\tLongMessage=ErChkLstLng003;\n\t\t\t\t//set focus on [from] check number\n\t\t\t\tdocument.getElementById('txtFrom').focus();\n\t\t\t}\n\t\t\t//if long message is not empty\n\t\t\telse\n\t\t\t{\n\t\t\t\t//set longmessage with newline char and long message code\n\t\t\t\tLongMessage=LongMessage + '\\n' + ErChkLstLng003;\t\t\t\t\n\t\t\t}\t\t\t\n\t\t}\n\t\t\n\t\t//If [from] check number is empty\n\t\tif(false==IstxtEmpty('txtFrom'))\n\t\t{\n\t\t\t//check textbox [from] check number is number\n\t\t\tif(false==IsNumeric(document.getElementById('txtFrom').value))\n\t\t\t{\n\t\t\t\t//check long message is empty\n\t\t\t\tif(\"\"==LongMessage)\n\t\t\t\t{\n\t\t\t\t\t//set long message\n\t\t\t\t\tLongMessage=ErChkLstLng004;\n\t\t\t\t\t//set focus on [from] check number\n\t\t\t\t\tdocument.getElementById('txtFrom').focus();\n\t\t\t\t}\n\t\t\t\t//if long message is not empty\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t//set longmessage with newline char and long message code\n\t\t\t\t\tLongMessage=LongMessage + '\\n' + ErChkLstLng004;\n\t\t\t\t} \n\t\t\t}\n\t\t}\n\t\t\n\t\t//check textbox [to] check number is empty\n\t\tif(true==IstxtEmpty('txtTo'))\n\t\t{\n\t\t\t//check long message is empty\n\t\t\tif(\"\"==LongMessage)\n\t\t\t{\n\t\t\t\t//set long message\n\t\t\t\tLongMessage=ErChkLstLng005;\n\t\t\t\t//set focus on [to] check number\n\t\t\t\tdocument.getElementById('txtTo').focus();\n\t\t\t}\n\t\t\t//if long message is not empty\n\t\t\telse\n\t\t\t{\n\t\t\t\t//set longmessage with newline char and long message code\n\t\t\t\tLongMessage=LongMessage + '\\n' + ErChkLstLng005;\t\t\t\t\n\t\t\t}\t\t\t\n\t\t}\n\t\t\n\t\t//If [to] check number is not empty then check\n\t\tif(false==IstxtEmpty('txtTo'))\n\t\t{\n\t\t\t//check textbox [to] check number is number\n\t\t\tif(false==IsNumeric(document.getElementById('txtTo').value))\n\t\t\t{\n\t\t\t\t//check long message is empty\n\t\t\t\tif(\"\"==LongMessage)\n\t\t\t\t{\n\t\t\t\t\t//set long message\n\t\t\t\t\tLongMessage=ErChkLstLng006;\n\t\t\t\t\t//set focus on [to] check number\n\t\t\t\t\tdocument.getElementById('txtTo').focus();\n\t\t\t\t}\n\t\t\t\t//if long message is not empty\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t//set longmessage with newline char and long message code\n\t\t\t\t\tLongMessage=LongMessage + '\\n' + ErChkLstLng006;\n\t\t\t\t} \n\t\t\t}\n\t\t}\n\t\t//if long message is empty\n\t\tif(\"\"==LongMessage)\n\t\t{\n\t\t\t//Validation success\n\t\t\treturn true;\n\t\t}\n\t\t//if long message is not empty\n\t\telse\n\t\t{\n\t\t\t//set error message on toppage\n\t\t\tSetErrorMessage(ShortMessage,LongMessage);\n\t\t\t//validation failure\n\t\t\treturn false;\n\t\t}\n\t}",
"function ssw_js_validate_email() {\n\n var email_regex = /^([\\w-]+(?:\\.[\\w-]+)*)@((?:[\\w-]+\\.)*\\w[\\w-]{0,66})\\.([a-z]{2,6}(?:\\.[a-z]{2})?)$/;\n var email = document.getElementById('ssw-steps').admin_email.value;\n \n if (!email_regex.test(email)) {\n document.getElementById(\"ssw-validate-email-error-label\").innerHTML=ssw_email_invalid_msg;\n document.getElementById(\"ssw-validate-email-error\").style.display=\"block\"; \n return false;\n }\n else {\n document.getElementById(\"ssw-validate-email-error\").style.display=\"none\";\n return true;\n }\n}",
"function validPdfForm() {\r\n return true;\r\n}",
"function validateCMSAddPageForm(formname)\n{\n \n if($('#frmDisplayPageTitle').val() == '')\n {\n alert(PAGE_DISP_TITLE);\n $('#frmDisplayPageTitle').focus()\n return false;\n }\n if($('#frmPageTitle').val() == '')\n {\n alert(PAGE_TIT_REQ);\n $('#frmPageTitle').focus()\n return false;\n } \n if($('#frmPageDisplayOrder').val() == '' )\n {\n alert(PAGE_ORDER_REQ);\n $('#frmPageDisplayOrder').focus()\n return false;\n } \n \n}",
"function email_check() {\r\n email_warn(email_validate());\r\n final_validate();\r\n}",
"function validaFormAdnRetail(){\n\tvar idSegmento = document.forms[\"adnRetailForm\"][\"idSegmentoLocal\"].value;\n\tif(esCampoNoValido(idSegmento, nombreIdSegmento, 10, false)){\n\t\treturn;\n\t}\n\tvar descripcion = document.forms[\"adnRetailForm\"][\"descripcion\"].value;\n\tif(esCampoNoValido(descripcion, nombreDescripcion, 50, false)){\n\t\treturn;\n\t}\n\tvar flagRetail = document.forms[\"adnRetailForm\"][\"flagRetail\"].value;\n\tif(esCampoBanderaNoValido(flagRetail, nombreFlagRetail)){\n\t\treturn;\n\t}\n\tvar confirmacionUsuario = confirm(mensajeConfirmacion + ' ' + idSegmento + '?');\n\tif(confirmacionUsuario){\n\t\tdocument.forms[\"adnRetailForm\"].submit();\n\t}\n}",
"function validateGetCalendarForm() {\r\n //TODO: Check valid years, etc.\r\n}",
"function doValidateSubscriptionForm(formData) {\r\n\tvar reg = new RegExp(emailregex);\r\n\tvar $theEmailField = $(formData).find('[name=email]');\r\n\r\n\tif ( reg.test($theEmailField.val()) ) {\r\n\t\treturn true;\r\n\t} else if ( $theEmailField.val().length ) {\r\n\t\talert(jsStr.tcemailnotvalid.unescapeHTML());\r\n\t} else {\r\n\t\talert(jsStr.tcemailaddressrequired.unescapeHTML());\r\n\t}\r\n\r\n\treturn false;\r\n}",
"function validateNewsletter() {\r\n let checkbox = document.getElementById(\"newsletter\");\r\n let email = document.getElementById(\"email\").value;\r\n let show = \"none\";\r\n if (checkbox.checked === true && email === \"\")\r\n show = \"block\";\r\n else\r\n show = \"none\";\r\n document.getElementById(\"emailMandatory\").style.display = show;\r\n return (show === 'none' && checkbox.checked);\r\n}",
"function validateJoinMail(valForm) {\r\n\t\r\n\tvar resultValidate = true;\r\n\t\r\n\tif(validateRequiredField($(valForm).find(\"#firstName\")) == false) {\r\n\t\tresultValidate = false;\r\n\t}\r\n\t\r\n\tif(validateEmailField($(valForm).find(\"#email\")) == false) {\r\n\t\tresultValidate = false;\r\n\t}\r\n\t\r\n\tif (resultValidate == true) {\r\n\t\t$(valForm).find(\".error\").hide();\r\n\t} else {\r\n\t\t$(valForm).find(\".error\").show();\r\n\t}\r\n\t\r\n\treturn resultValidate;\r\n}",
"function validateOrganFrm(){\n\tif (document.formOrgan.organization.value==null || document.formOrgan.organization.value==\"\"){\n\t\talert(\"Please enter org name.\");\n\t\tdocument.formOrgan.organization.focus();\n\t\treturn false;\n\t}\n\tif (document.formOrgan.cemail.value==null || document.formOrgan.cemail.value==\"\"){\n\t\talert(\"Please enter org email.\");\n\t\tdocument.formOrgan.cemail.focus();\n\t\treturn false;\n\t}\n\tif (echeck(document.formOrgan.cemail.value)==false){\n\t\tdocument.formOrgan.cemail.value=\"\";\n\t\tdocument.formOrgan.cemail.focus();\n\t\treturn false;\n\t}\n\tif (document.formOrgan.chgstate.value==\"new\"){\n\t\tif (document.getElementById(\"meadmin1\").checked == false){//Admin1: if admin not default, validate all fields\n\t\t\tif (document.formOrgan.cd1firstname.value==null || document.formOrgan.cd1firstname.value==\"\"){\n\t\t\t\talert(\"Please enter Admin 1 first name.\");\n\t\t\t\tdocument.formOrgan.cd1firstname.focus();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (document.formOrgan.cd1lastname.value==null || document.formOrgan.cd1lastname.value==\"\"){\n\t\t\t\talert(\"Please enter Admin 1 last name.\");\n\t\t\t\tdocument.formOrgan.cd1lastname.focus();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (document.formOrgan.cd1email.value==null || document.formOrgan.cd1email.value==\"\"){\n\t\t\t\talert(\"Please enter Admin 1 e-mail.\");\n\t\t\t\tdocument.formOrgan.cd1email.focus();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t//=>function*js/\n\t\t\tif (echeck(document.formOrgan.cd1email.value)==false){\n\t\t\t\tdocument.formOrgan.cd1email.value=\"\";\n\t\t\t\tdocument.formOrgan.cd1email.focus();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (document.getElementById(\"meadmin2\").checked == false){//Admin1: if admin not default, validate all fields\n\t\t\tif (document.formOrgan.cd2firstname.value!=\"\" && document.formOrgan.cd2lastname.value!=\"\" && document.formOrgan.cd2email.value!=\"\"){\n\t\t\t\tif (document.formOrgan.cd2firstname.value==null || document.formOrgan.cd2firstname.value==\"\"){\n\t\t\t\t\talert(\"Please enter Admin 2 first name.\");\n\t\t\t\t\tdocument.formOrgan.cd2firstname.focus();\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (document.formOrgan.cd2lastname.value==null || document.formOrgan.cd2lastname.value==\"\"){\n\t\t\t\t\talert(\"Please enter Admin 2 last name.\");\n\t\t\t\t\tdocument.formOrgan.cd2lastname.focus();\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (document.formOrgan.cd2email.value==null || document.formOrgan.cd2email.value==\"\"){\n\t\t\t\t\talert(\"Please enter Admin 2 e-mail.\");\n\t\t\t\t\tdocument.formOrgan.cd2email.focus();\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\t//=>function*js/\n\t\t\t\tif (echeck(document.formOrgan.cd2email.value)==false){\n\t\t\t\t\tdocument.formOrgan.cd2email.value=\"\";\n\t\t\t\t\tdocument.formOrgan.cd2email.focus();\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}//end admin2\n\t\t}\n\t}//end of new process\n}",
"function validateEmail()\n{\n//variable email is set by element id contactEmail from the form\n\tvar email = document.getElementById(\"contactEmail\").value; \n\t\n\t//validation for email\n\tif(email.length == 0)\n\t{\n\t\tproducePrompt(\"Email is Required\", \"emailPrompt\", \"red\"); \n\t\treturn false; \n\t}\n\tif(!email.match(/^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/)){\n\t\tproducePrompt(\"Email Address is Invalid\", \"emailPrompt\", \"red\"); \n\t\treturn false; \n\t}\n\tproducePrompt(\"Valid Email\", \"emailPrompt\", \"green\"); \n\t\treturn true; \n}",
"function validateEnquiryEmailsForm()\n{\n var regEmail = /^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/;\n if(document.frmAddEditEmail.frmEnquiryEmail.value == \"\")\n {\n alert(ENTER_EMAIL);\n document.frmAddEditEmail.frmEnquiryEmail.focus() ;\n return false;\n }\n if(document.frmAddEditEmail.frmEnquiryEmail.value != \"\")\n {\n var result = document.frmAddEditEmail.frmEnquiryEmail.value.split(\",\");\n // alert(result);\n for(var i = 0;i < result.length;i++)\n {\n if(!regEmail.test(result[i])) \n {\n alert(result[i]+EMAIL_SEEMS_WRONG); \t\t\n document.frmAddEditEmail.frmEnquiryEmail.focus();\n return false;\n }\n }\n }\n}",
"function checkValid() {\n\tif(!document.getElementById(\"email\").value.match(/\\S+@\\S+\\.\\S+/)){\n\t\tif (document.getElementById(\"email\").value != \"\") {\n\t\t\talert(\"Email Format is wrong!\")\n\t\t\treturn false;\n\t\t} \n\t}\n\tif (!document.getElementById(\"phone_number\").value.match(\"^\\\\d{3}-\\\\d{3}-\\\\d{4}$\")) {\n\t\tif (document.getElementById(\"phone_number\").value != \"\") {\n\t\t\talert(\"Phone Format is wrong!\")\n\t\t\treturn false;\n\t\t}\n\t}\n\tif (!document.getElementById(\"zipcode\").value.match(\"^\\\\d{5}$\")) {\n\t\tif (document.getElementById(\"zipcode\").value != \"\") {\n\t\t\talert(\"Zipcode Format is wrong!\")\n\t\t\treturn false;\n\t\t}\n\t}\n\tvar password = document.getElementById(\"password\")\n\tvar password2 = document.getElementById(\"password2\")\n\tif (password.value == \"\" && password2.value != \"\") {\n\t\talert(\"Password is empty !\")\n\t\treturn false;\n\t} else if (password2.value == \"\" && password.value != \"\"){\n\t\talert(\"Confirmation Password is empty !\")\n\t\treturn false;\n\t}\n\treturn true;\n}",
"function validateCoupon(formname)\n{\n \n if(validateForm(formname, 'frmCouponCode', 'Coupon Code', 'R','frmCouponPriceValue', 'Price Value', 'RisDecimal', 'frmMinimumPurchaseAmount', 'Minimum Purchase Amount', 'RisDecimal', 'frmCouponPriceValue', 'Price Value', 'regDecimal','frmCouponActivateDate', 'Coupon Activate date', 'R','frmCouponExpiryDate', 'coupon expiry date', 'R'))\n {\t\n \t\n var CouponActivateDate=document.forms[0].frmCouponActivateDate.value;\n var CouponExpiryDate=document.forms[0].frmCouponExpiryDate.value;\n if(CouponActivateDate > CouponExpiryDate)\n {\n alert(SORRY_CANT_COMPLETE_YOUR_REQ);\n return false;\n }\n } \n else \n {\n return false;\n } \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates conditionsTrack chart on click | function updateConditionsTrackChart() {
updateConditionsTrackChart2();
} | [
"function updateConditionsTrackChart2(){\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar temp = getDpsActive();\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar myData = \t[{\r\n\t\t\t\t\t\t\t\t\t\ttype: \"bar\",\r\n\t\t\t\t\t\t\t\t\t\tshowInLegend: true,\r\n\t\t\t\t\t\t\t\t\t\tcolor: \"blue\",\r\n\t\t\t\t\t\t\t\t\t\tname: \"Active\",\r\n\t\t\t\t\t\t\t\t\t\tdataPoints: dpsActive\r\n\t\t\t\t\t\t\t\t\t}, {\r\n\t\t\t\t\t\t\t\t\t\ttype: \"bar\",\r\n\t\t\t\t\t\t\t\t\t\tshowInLegend: true,\r\n\t\t\t\t\t\t\t\t\t\tcolor: \"green\",\r\n\t\t\t\t\t\t\t\t\t\tname: \"winCount\",\r\n\t\t\t\t\t\t\t\t\t\tdataPoints: [\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond1.winCount, label: \"cond1\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond2.winCount, label: \"cond2\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond3.winCount, label: \"cond3\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond4.winCount, label: \"cond4\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond5.winCount, label: \"cond5\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond6.winCount, label: \"cond6\"}\r\n\t\t\t\t\t\t\t\t\t\t]\r\n\t\t\t\t\t\t\t\t\t},{\r\n\t\t\t\t\t\t\t\t\t\ttype: \"bar\",\r\n\t\t\t\t\t\t\t\t\t\tshowInLegend: true,\r\n\t\t\t\t\t\t\t\t\t\tcolor: \"red\",\r\n\t\t\t\t\t\t\t\t\t\tname: \"lossCount\",\r\n\t\t\t\t\t\t\t\t\t\tdataPoints: [\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond1.lossCount, label: \"cond1\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond2.lossCount, label: \"cond2\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond3.lossCount, label: \"cond3\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond4.lossCount, label: \"cond4\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond5.lossCount, label: \"cond5\"},\r\n\t\t\t\t\t\t\t\t\t\t{y: conditionsTrack.cond6.lossCount, label: \"cond6\"}\r\n\t\t\t\t\t\t\t\t\t\t]\r\n\t\t\t\t\t\t\t\t\t}];\r\n\t\t\t\r\n\t\t\t\t\t// Options to display value on top of bars\r\n\t\t\t\t\tvar myoption = {\r\n\t\t\t\t\t\ttooltips: {\r\n\t\t\t\t\t\t\tenabled: true\r\n\t\t\t\t\t\t},\r\n\t\t\t\t\t\thover: {\r\n\t\t\t\t\t\t\tanimationDuration: 1\r\n\t\t\t\t\t\t},\r\n\t\t\t\t\t\tanimation: {\r\n\t\t\t\t\t\tduration: 1,\r\n\t\t\t\t\t\tonComplete: function () {\r\n\t\t\t\t\t\t\tvar chartInstance = this.chart,\r\n\t\t\t\t\t\t\t\tctx = chartInstance.ctx;\r\n\t\t\t\t\t\t\t\tctx.textAlign = 'center';\r\n\t\t\t\t\t\t\t\tctx.fillStyle = \"rgba(0, 0, 0, 1)\";\r\n\t\t\t\t\t\t\t\tctx.textBaseline = 'bottom';\r\n\t\t\t\t\t\t\t\tthis.data.datasets.forEach(function (dataset, i) {\r\n\t\t\t\t\t\t\t\t\tvar meta = chartInstance.controller.getDatasetMeta(i);\r\n\t\t\t\t\t\t\t\t\tmeta.data.forEach(function (bar, index) {\r\n\t\t\t\t\t\t\t\t\t\tvar data = dataset.data[index];\r\n\t\t\t\t\t\t\t\t\t\tctx.fillText(data, bar._model.x, bar._model.y - 5);\r\n\t\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}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t};\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\tconditionsTrackChart = new CanvasJS.Chart(\"chartContainer5\", {\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\tbackgroundColor: \"black\",\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\ttitle: {\r\n\t\t\t\t\t\t\t\t\t\ttext: \"Conditions Success Rate\",\r\n\t\t\t\t\t\t\t\t\t\tfontColor: \"white\"\r\n\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\taxisX: {\r\n\t\t\t\t\t\t\t\t\t\t//title: \"Conditions\",\r\n\t\t\t\t\t\t\t\t\t\ttitleFontColor: \"green\",\r\n\t\t\t\t\t\t\t\t\t\tlabelFontColor: \"white\"\r\n\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\taxisY: {\r\n\t\t\t\t\t\t\t\t\t\ttitle: \"Count\",\r\n\t\t\t\t\t\t\t\t\t\ttitleFontColor: \"red\",\r\n\t\t\t\t\t\t\t\t\t\tlabelFontColor: \"white\"\r\n\t\t\t\t\t\t\t\t\t\t//interval: 10\r\n\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\tlegend: {\r\n\t\t\t\t\t\t\t\t\t\tcursor:\"pointer\",\r\n\t\t\t\t\t\t\t\t\t\titemclick : toggleDataSeries\r\n\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\ttoolTip: {\r\n\t\t\t\t\t\t\t\t\t\tshared: true,\r\n\t\t\t\t\t\t\t\t\t\tcontent: toolTipFormatter\r\n\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\tdata: myData, \t// Chart data\r\n\t\t\t\t\t\t\t\t\toptions: myoption \t// Chart Options [This is optional paramenter use to add some extra things in the chart].\r\n\t\t\t\t\t});\r\n\t\t\t\t\t\r\n\t\t\t\t\tconditionsTrackChart.render();\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t }",
"function updateLoSideChart() {\r\n\t\t\t\t\thandleLoSideTrack(2);\r\n\t\t\t\t\tupdateLoSideChart2();\r\n\t\t\t\t}",
"function updateHiSideChart() {\r\n\t\t\t\t\thandleHiSideTrack(2);\r\n\t\t\t\t\tupdateHiSideChart2();\r\n\t\t\t\t}",
"function drawTracks(screen, data) {\n data.tracks.forEach(function(track, row) {\n track.steps.forEach(function(on, column) {\n drawButton(screen,\n column,\n row,\n on ? track.color : \"lightgray\");\n });\n });\n}",
"function updateHiSideBreakChart() {\r\n\t\t\t\t\thandleHiSideTrack(3);\r\n\t\t\t\t\tupdateHiSideBreakChart2();\r\n\t\t\t\t}",
"function updateLoSideBreakChart() {\r\n\t\t\t\t\thandleLoSideTrack(3);\r\n\t\t\t\t\tupdateLoSideBreakChart2();\r\n\t\t\t\t}",
"function updateBidChart() {\r\n\t\t\t\t\tupdateBidChart2();\r\n\t\t\t\t}",
"function updateChart() {\n const extent = d3.event.selection;\n \n if(!extent) {\n if (!idleTimeout) return idleTimeout = setTimeout(idled, 350); // This allows to wait a little bit\n x.domain(d3.extent(computedData, function(d) {\n return d.dateObj }))\n } else {\n x.domain([ x.invert(extent[0]), x.invert(extent[1]) ])\n areaChart.select(\".brush\").call(brush.move, null)\n }\n\n // Update axis and area position\n xAxis.transition().duration(1000).call(d3.axisBottom(x).ticks(6))\n areaChart\n .selectAll(\"path\")\n .transition().duration(1000)\n .attr(\"d\", area);\n \n }",
"function drawCharts(event) {\r\n\tfetchLineChart(event.target.textContent).then(res => {\r\n\t\tconsole.log(res);\r\n\t\t//updating the chart with the data of the selected activity\r\n\t\tline.data.datasets[0].data = res;\r\n\t\tline.update();\r\n\t});\r\n\r\n\tfetchBarChart(event.target.textContent).then(res => {\r\n\t\tconsole.log(res);\r\n\t\t//updating the chart with the data of the selected activity\r\n\t\tbar.data.datasets[0].data = res;\r\n\t\tbar.update();\r\n\t});\r\n}",
"function updateChartModo(mode) {\r\n var actual;\r\n var title = 'Metro Comparison - Drive Alone';\r\n $('#T18-A .chart-title').html(title);\r\n $('#T18-A-chart').highcharts({\r\n chart: {\r\n type: 'line'\r\n },\r\n title: {\r\n text: ''\r\n },\r\n exporting: {\r\n chartOptions: {\r\n title: {\r\n text: title\r\n }\r\n }\r\n },\r\n xAxis: {\r\n categories: yearNames\r\n },\r\n yAxis: {\r\n min: 0,\r\n title: {\r\n text: 'Weighted Share of Structurally Deficient Bridges'\r\n }\r\n },\r\n legend: {\r\n reversed: true\r\n },\r\n // tooltip: {\r\n // enabled: true,\r\n // pointFormat: '<span style=\"color:{series.color}\">{series.name}</span>: <b>{point.percentage:.1f}%</b> ({point.y:,.0f})</b>',\r\n // shared: true\r\n // },\r\n colors: altColors,\r\n /*plotOptions: {\r\n series: {\r\n stacking: 'normal',\r\n point: {\r\n events: {\r\n mouseOver: function() {\r\n //console.log(this);\r\n update_areachartinfot14t15a(this.category, this.y);\r\n\r\n },\r\n click: function() {\r\n update_areachartinfot14t15a(this.category, this.y);\r\n }\r\n }\r\n }\r\n }\r\n },*/\r\n series: [{\r\n name: 'Bay Area',\r\n data: vmtRegion\r\n }]\r\n });\r\n }",
"onChartRender() {\n this.updateProxyOverlays();\n }",
"updateCheck() {\r\n this.setState((oldState) => {\r\n return {\r\n checked: !oldState.checked,\r\n };\r\n });\r\n this.updateChart(this.state.checked)\r\n }",
"function setupBtnsSensorData() {\n\n //select the sensor data buttons\n $(\"#sensorDataBtns button\").click(function () {\n \n var btn = $(this);\n\n //check for current class on button\n if (!btn.hasClass(\"current\")) //if not then\n {\n $(\"#sensorDataBtns button.current\").removeClass(\"current\"); //find and remove current of buttons\n btn.addClass(\"current\"); //add current to this one\n }\n changeChartData(\"data-graph-data\", btn.attr(\"data-graph-data\")); //change the chart data and refresh the chart.\n });\n}",
"function updateVis() {\n //saves parameters by which to split the bubbles / stack the data\n var splitParams = {\n depiction: 0,\n gender: 0,\n typeOfPic: 0\n };\n \n splitParams.depiction = document.getElementById(\"checkWithDepiction\").checked\n ? 1\n : 0;\n splitParams.gender = document.getElementById(\"checkGender\").checked ? 1 : 0;\n splitParams.typeOfPic = document.getElementById(\"checkPicType\").checked\n ? 1\n : 0;\n \n //console.log(\"splitparams\", splitParams);\n \n var arr = [splitParams.depiction, splitParams.gender, splitParams.typeOfPic];\n \n //erste Filteroption bei Filtern nach Abbildung unanklickbar und ungeklickt machen\n if (arr[2] == 1) {\n document.getElementById(\"checkWithDepiction\").checked = false;\n document.getElementById(\"checkWithDepiction\").disabled = true;\n } else {\n document.getElementById(\"checkWithDepiction\").disabled = false;\n }\n if(arr[0] == 1){ // if first option is checked, disable third option\n document.getElementById(\"checkPicType\").checked = false;\n document.getElementById(\"checkPicType\").disabled = true;\n } else{\n document.getElementById(\"checkPicType\").disabled = false;\n }\n \n /**updates bubble chart with filter as defined in arr array that contains the filter booleans */\n if(splitparamsArray[2] != arr[2]){ \n needToChangeYScaleStack = true;\n } else{\n needToChangeYScaleStack = false;\n }\n splitparamsArray = arr;\n updateBubbleChart();\n updateStackedAreaChart();\n \n \n }",
"function clickTrack(e) {\n if(!disabled) {\n if(!activeElement) activeElement = mprsSlider.querySelector(\".mprs-triangle-target.from\");\n if(!inactiveElement) inactiveElement = mprsSlider.querySelector(\".mprs-triangle-target.to\")\n const btnDimensions = activeElement.getBoundingClientRect();\n const offset = e.currentTarget.getBoundingClientRect().left;\n const btnWidth = btnDimensions.width - 2;\n const rangeWidth = activeElement.parentElement.getBoundingClientRect().width;\n let newLeft = (e.clientX - offset);\n if(newLeft < 0) newLeft = 0;\n if(newLeft > rangeWidth) newLeft = rangeWidth;\n activeElement.style.left = newLeft + \"px\";\n let newValue = calculateBtnValue(activeElement);\n from = newValue;\n let percent = ((Math.abs(from - topStart) / topRange) * 100).toPrecision(4);\n activeElement.style.left = percent + \"%\";\n positionRangeBlock();\n const rangeBlock = activeElement.parentElement.querySelector(\".mprs-range-block\");\n rangeBlock.style.width = percent + \"%\";\n updateValueBoxes();\n if(onMove) onMove();\n if(onUpdate) onUpdate();\n setFocus(\"top\");\n // Prevent moveEnd from performing redundant operations.\n trackClicked = true;\n }\n }",
"componentDidUpdate() {\n this.buildChart();\n }",
"function update_indicators(i)\r\n{\r\n\r\n // how many plots are being displayed?\r\n var num_plots_displayed = plots_displayed[0] + plots_displayed[1] + plots_displayed[2];\r\n\r\n // if the user has rapidly clicked the difference button\r\n // we may get behind the actual display -- check if we need up date\r\n if (i >= num_plots_displayed) {\r\n return;\r\n }\r\n\r\n\t// update resolution indicator\r\n\ttoggle_resolution (i, plots_selected_resolution[i]);\r\n\r\n\t// update selection max indicator\r\n\tif (plots_selected_displayed[i] == 0)\r\n\t{\r\n\r\n\t\t// do not show display indicator\r\n\t\t$(\"#dac-plots-displayed-\" + (i+1)).hide();\r\n\t\t$(\"#dac-plots-not-displayed-\" + (i+1)).hide();\r\n\r\n\t}\r\n\telse if (limit_indicator_color == \"green\") {\r\n\r\n\t\t// all plots displayed\r\n\t\t$(\"#dac-plots-not-displayed-\" + (i+1)).hide();\r\n\t\t$(\"#dac-plots-displayed-\" + (i+1)).show();\r\n\r\n\t} else {\r\n\r\n\t\t// some plot not displayed\r\n\t\t$(\"#dac-plots-displayed-\" + (i+1)).hide();\r\n\t\t$(\"#dac-plots-not-displayed-\" + (i+1)).css(\"color\", limit_indicator_color);\r\n\t\t$(\"#dac-plots-not-displayed-\" + (i+1)).show();\r\n\r\n\t}\r\n}",
"function update(){\n\t\t\tlet h = xAxis.invert(currentValue),\n\t\t\t\tyear = formatDateIntoYear(h);\n\t\t\tsendYearAndMovingStatus(year,that.isMoving);\n\t\t\thandle.attr(\"cx\", xAxis(h));\n\t\t\tlabel\n\t\t\t\t.attr(\"x\", xAxis(h))\n\t\t\t\t.text(formatDateIntoYear(h));\n\t\t}",
"function severityReport() {\r\n selectedReport = \"Severity\";\r\n\r\n document.getElementById(\"severity\").style.backgroundColor = \"#ebeaea\";\r\n document.getElementById(\"status\").style.backgroundColor = \"\";\r\n document.getElementById(\"assignee\").style.backgroundColor = \"\";\r\n document.getElementById(\"individual\").style = \"\";\r\n\r\n document.getElementById(\"right\").innerHTML = \"\";\r\n\r\n let countLow = 0, countMedium = 0, countHigh = 0;\r\n var issuesItem = JSON.parse(localStorage.getItem('bugs'));\r\n\r\n for (let i = 0; i < issuesItem.length; ++i) {\r\n if (issuesItem[i].severity == \"Low\") {\r\n countLow++;\r\n }\r\n else if (issuesItem[i].severity == \"Medium\") {\r\n countMedium++;\r\n }\r\n else {\r\n countHigh++;\r\n }\r\n }\r\n\r\n var data = [\r\n { x: \"Low\", value: countLow },\r\n { x: \"Medium\", value: countMedium },\r\n { x: \"High\", value: countHigh }\r\n ];\r\n\r\n var chart;\r\n if (selectedChart == \"pie\") {\r\n chart = anychart.pie();\r\n }\r\n else if (selectedChart == \"column\") {\r\n chart = anychart.column();\r\n chart.yAxis().title(\"Number of bugs\");\r\n }\r\n else {\r\n chart = anychart.bar();\r\n chart.yAxis().title(\"Number of bugs\");\r\n }\r\n\r\n chart.labels(true);\r\n chart.title(\"Number of bugs according to SEVERITY\");\r\n chart.data(data);\r\n chart.container(document.getElementById(\"right\"));\r\n chart.draw();\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders the content of body cells using a renderer. | _renderBodyCellsContent(renderer, cells) {
if (!cells || !renderer) {
return;
}
this.__renderCellsContent(renderer, cells);
} | [
"static renderTableBody() {\n\n // Reset options list of each filter\n filterRegistry.forEach(obj => obj.options = ['']);\n\n // This is how table body is created. D3 does its magic.\n var tableBody = d3.select('tbody');\n tableBody.selectAll('tr')\n .data(data.filter(encounter => SelectFilter.filter(encounter)))\n .join('tr')\n .selectAll('td')\n .data(encounter => Object.values(encounter))\n .join('td')\n .text(value => value);\n\n // Based on filtered data update option lists for UNSET filters\n // (their options were already populated via SelectFilter.filter() calls above)\n filterRegistry.forEach(obj => obj.selectedOpt ? null : obj.makeOptions());\n\n // Update option lists for ACTIVE filters (at this moment they have only one option in the list - the one selected)\n // For each active filter we have to recreate a dataset WITHOUT that filter\n var activeFilters = [];\n filterRegistry.forEach(obj => obj.selectedOpt ? activeFilters.push(obj) : null);\n\n activeFilters.forEach(obj => {\n // temporary remove the filter from the registry\n let idx = filterRegistry.indexOf(obj);\n filterRegistry.splice(idx, 1);\n\n // Now apply remaining filters to the dataset, but only for the purpose of populating options of the removed filter\n // calling SelectFilter.filter() with obj as the second argument - only that obj options will be populated\n data.forEach(encounter => SelectFilter.filter(encounter, obj));\n\n // At this point the filter options should be repopulated and have to be transferred to the 'option' elements\n obj.makeOptions();\n\n // Put the filter back to the registry\n filterRegistry.splice(idx, 0, obj);\n });\n }",
"requestContentUpdate() {\n if (this._columnTree) {\n // header and footer renderers\n this._columnTree.forEach((level) => {\n level.forEach((column) => {\n column._renderHeaderAndFooter();\n });\n });\n\n // body and row details renderers\n this.__updateVisibleRows();\n }\n }",
"function NotebookRenderer(model, rendermime) {\n _super.call(this);\n this._model = null;\n this._rendermime = null;\n this._mimetype = 'text/plain';\n this._langInfoCursor = null;\n this.node.tabIndex = -1; // Allow the widget to take focus.\n this.addClass(NB_CLASS);\n this._model = model;\n this._rendermime = rendermime;\n this._langInfoCursor = model.getMetadata('language_info');\n this._mimetype = this.getMimetype();\n this.layout = new phosphor_panel_1.PanelLayout();\n // Add the current cells.\n if (model.cells.length === 0) {\n // Add a new code cell if there are no cells.\n var cell = model.createCodeCell();\n model.cells.add(cell);\n }\n var layout = this.layout;\n var constructor = this.constructor;\n var factory = constructor.createCell;\n for (var i = 0; i < model.cells.length; i++) {\n var widget = factory(model.cells.get(i), rendermime);\n this.initializeCellWidget(widget);\n layout.addChild(widget);\n }\n model.cells.changed.connect(this.onCellsChanged, this);\n model.metadataChanged.connect(this.onMetadataChanged, this);\n }",
"_renderFooterCellContent(footerRenderer, footerCell) {\n if (!footerCell || !footerRenderer) {\n return;\n }\n\n this.__renderCellsContent(footerRenderer, [footerCell]);\n if (this._grid) {\n this._grid.__updateHeaderFooterRowVisibility(footerCell.parentElement);\n }\n }",
"_renderHeaderCellContent(headerRenderer, headerCell) {\n if (!headerCell || !headerRenderer) {\n return;\n }\n\n this.__renderCellsContent(headerRenderer, [headerCell]);\n if (this._grid) {\n this._grid.__updateHeaderFooterRowVisibility(headerCell.parentElement);\n }\n }",
"_renderFood(foodCells) {\n for (var key in foodCells) {\n if (!foodCells.hasOwnProperty(key)) continue;\n this._setCellStyle(foodCells[key].x, foodCells[key].y, 'food');\n }\n\n for(var i = 0; i < foodCells.length; i++) {\n this._setCellStyle(foodCells[i].x, foodCells[i].y, 'food');\n }\n }",
"function renderJobsTable()\n{\n var data = globalJobList;\n var node = document.getElementById(\"jobs-table-body\");\n var tablenode = node.parentNode;\n tablenode.removeChild(node);\n\n // clear table\n {\n var n = node.firstElementChild;\n while (n != null)\n {\n var cn = n.nextElementSibling;\n node.removeChild(n)\n n = cn;\n }\n }\n\n if (data.length > 0)\n {\n for (var i = 0; i < data.length; ++i)\n {\n addJobRowAt(node,i);\n }\n }\n else\n {\n var tr = document.createElement(\"tr\");\n var td = document.createElement(\"td\"); td.setAttribute(\"colspan\",\"8\");\n var div = document.createElement(\"div\"); div.setAttribute(\"style\",\"margin : 10px 0px 10px 0px; text-align : center;\");\n div.appendChild(document.createTextNode(\"No entries\"));\n td.appendChild(div);\n tr.appendChild(td);\n node.appendChild(tr);\n\n rerenderSelection(node);\n }\n\n tablenode.appendChild(node);\n}",
"__textHeaderRenderer() {\n this.__setTextContent(this._headerCell._content, this.header);\n }",
"function renderCells()\n{\n //RENDER ALL DEAD CELLS (WHITE)\n canvas2D.fillStyle = \"#ffffff\";\n for (var i = 0; i <= gridHeight; i++)\n {\n for (var j = 0; j < gridWidth; j++)\n {\n var x = j * cellLength;\n var y = i * cellLength;\n canvas2D.fillRect(x, y, cellLength, cellLength);\n }\n }\n \n // SET THE PROPER RENDER COLOR\n canvas2D.fillStyle = LIVE_COLOR;\n for (var i = 0; i <= gridHeight; i++)\n {\n for (var j = 0; j < gridWidth; j++)\n {\n var cell = getGridCell(renderGrid, i, j);\n if (cell === LIVE_CELL)\n {\n var x = j * cellLength;\n var y = i * cellLength;\n canvas2D.fillRect(x, y, cellLength, cellLength);\n }\n }\n } \n \n canvas2D.fillStyle = VOID_COLOR;\n for (var i = 0; i <= gridHeight; i++)\n {\n for (var j = 0; j < gridWidth; j++)\n {\n var cell = getGridCell(renderGrid, i, j);\n if (cell === VOID_CELL)\n {\n var x = j * cellLength;\n var y = i * cellLength;\n canvas2D.fillRect(x, y, cellLength, cellLength);\n }\n }\n }\n \n canvas2D.fillStyle = PLACEMENT_COLOR;\n for (var i = 0; i <= gridHeight; i++)\n {\n for (var j = 0; j < gridWidth; j++)\n {\n var cell = getGridCell(renderGrid, i, j);\n if (cell === PLACEMENT_CELL)\n {\n var x = j * cellLength;\n var y = i * cellLength;\n canvas2D.fillRect(x, y, cellLength, cellLength);\n }\n }\n }\n \n canvas2D.fillStyle = TURRET_COLOR;\n for (var i = 0; i <= gridHeight; i++)\n {\n for (var j = 0; j < gridWidth; j++)\n {\n var cell = getGridCell(renderGrid, i, j);\n if (cell === TURRET_CELL)\n {\n var x = j * cellLength;\n var y = i * cellLength;\n canvas2D.fillRect(x, y, cellLength, cellLength);\n }\n }\n }\n \n canvas2D.fillStyle = TURRET_SPAWN_STRAIGHT_UP_COLOR;\n for (var i = 0; i <= gridHeight; i++)\n {\n for (var j = 0; j < gridWidth; j++)\n {\n var cell = getGridCell(renderGrid, i, j);\n if (cell === TURRET_SPAWN_STRAIGHT_UP)\n {\n var x = j * cellLength;\n var y = i * cellLength;\n canvas2D.fillRect(x, y, cellLength, cellLength);\n }\n }\n }\n \n canvas2D.fillStyle = TURRET_SPAWN_STRAIGHT_DOWN_COLOR;\n for (var i = 0; i <= gridHeight; i++)\n {\n for (var j = 0; j < gridWidth; j++)\n {\n var cell = getGridCell(renderGrid, i, j);\n if (cell === TURRET_SPAWN_STRAIGHT_DOWN)\n {\n var x = j * cellLength;\n var y = i * cellLength;\n canvas2D.fillRect(x, y, cellLength, cellLength);\n }\n }\n }\n \n canvas2D.fillStyle = TURRET_SPAWN_STRAIGHT_LEFT_COLOR;\n for (var i = 0; i <= gridHeight; i++)\n {\n for (var j = 0; j < gridWidth; j++)\n {\n var cell = getGridCell(renderGrid, i, j);\n if (cell === TURRET_SPAWN_STRAIGHT_LEFT)\n {\n var x = j * cellLength;\n var y = i * cellLength;\n canvas2D.fillRect(x, y, cellLength, cellLength);\n }\n }\n }\n \n canvas2D.fillStyle = TURRET_SPAWN_STRAIGHT_RIGHT_COLOR;\n for (var i = 0; i <= gridHeight; i++)\n {\n for (var j = 0; j < gridWidth; j++)\n {\n var cell = getGridCell(renderGrid, i, j);\n if (cell === TURRET_SPAWN_STRAIGHT_RIGHT)\n {\n var x = j * cellLength;\n var y = i * cellLength;\n canvas2D.fillRect(x, y, cellLength, cellLength);\n }\n }\n }\n \n canvas2D.fillStyle = TURRET_SPAWN_DIAGONAL_UP_COLOR;\n for (var i = 0; i <= gridHeight; i++)\n {\n for (var j = 0; j < gridWidth; j++)\n {\n var cell = getGridCell(renderGrid, i, j);\n if (cell === TURRET_SPAWN_DIAGONAL_UP)\n {\n var x = j * cellLength;\n var y = i * cellLength;\n canvas2D.fillRect(x, y, cellLength, cellLength);\n }\n }\n }\n \n canvas2D.fillStyle = TURRET_SPAWN_DIAGONAL_DOWN_COLOR;\n for (var i = 0; i <= gridHeight; i++)\n {\n for (var j = 0; j < gridWidth; j++)\n {\n var cell = getGridCell(renderGrid, i, j);\n if (cell === TURRET_SPAWN_DIAGONAL_DOWN)\n {\n var x = j * cellLength;\n var y = i * cellLength;\n canvas2D.fillRect(x, y, cellLength, cellLength);\n }\n }\n }\n \n canvas2D.fillStyle = TURRET_SPAWN_DIAGONAL_LEFT_COLOR;\n for (var i = 0; i <= gridHeight; i++)\n {\n for (var j = 0; j < gridWidth; j++)\n {\n var cell = getGridCell(renderGrid, i, j);\n if (cell === TURRET_SPAWN_DIAGONAL_LEFT)\n {\n var x = j * cellLength;\n var y = i * cellLength;\n canvas2D.fillRect(x, y, cellLength, cellLength);\n }\n }\n }\n \n canvas2D.fillStyle = TURRET_SPAWN_DIAGONAL_RIGHT_COLOR;\n for (var i = 0; i <= gridHeight; i++)\n {\n for (var j = 0; j < gridWidth; j++)\n {\n var cell = getGridCell(renderGrid, i, j);\n if (cell === TURRET_SPAWN_DIAGONAL_RIGHT)\n {\n var x = j * cellLength;\n var y = i * cellLength;\n canvas2D.fillRect(x, y, cellLength, cellLength);\n }\n }\n }\n}",
"render() {\n RB.ReviewablePageView.prototype.render.call(this);\n\n /*\n * Render each of the entries on the page.\n */\n this._entryViews.forEach(entryView => entryView.render());\n\n /*\n * Navigate to the right anchor on the page, if there's a valid hash\n * in the URL. We'll also do this whenever it changes, if the browser\n * supports this.\n */\n this._onHashChanged();\n\n if ('onhashchange' in window) {\n window.onhashchange = this._onHashChanged.bind(this);\n }\n\n /*\n * Load all the diff fragments queued up in each review.\n */\n this.diffFragmentQueue.loadFragments();\n\n /*\n * Set up the Issue Summary Table and begin listening for related\n * events.\n */\n this._issueSummaryTableView =\n new RB.ReviewRequestPage.IssueSummaryTableView({\n el: $('#issue-summary'),\n model: this.model.commentIssueManager,\n });\n\n this._issueSummaryTableView.render();\n\n this.listenTo(this._issueSummaryTableView,\n 'issueClicked',\n this._onIssueClicked);\n this.listenTo(this.model, 'appliedUpdate:issue-summary-table',\n (metadata, html) => {\n this._reloadView(this._issueSummaryTableView, html);\n });\n\n this._rendered = true;\n\n return this;\n }",
"function renderTable() {\n // Set the value of ending index\n var endingIndex = startingIndex + resultsPerPage;\n\n $tbody.innerHTML = \"\";\n // Set the value of ending index\n for (var i = 0; i < filteredAliens.length; i++) {\n // Get the current address object and its fields\n var alien = filteredAliens[i];\n var fields = Object.keys(alien);\n // Create a new row in the tbody, set the index to be i + startingIndex\n var $row = $tbody.insertRow(i);\n for (var j = 0; j < fields.length; j++) {\n // For every field in the address object, create a new cell and set its inner text to be the current value at the current address's field\n var field = fields[j];\n var $cell = $row.insertCell(j);\n $cell.innerText = alien[field];\n };\n };\n}",
"function renderTable() {date\r\n $tbody.innerHTML = \"\";\r\n for (var i = 0; i < datetime.length; i++) {\r\n // Get get the current datetime object and its fields\r\n var date = datetime[i];\r\n var fields = Object.keys(date)\r\n // Create a new row in the tbody, set the index to be i + startingIndex\r\n var $row = $tbody.insertRow(i);\r\n for (var j = 0; j < fields.length; j++) {\r\n // For every field in the address object, create a new cell at set its inner text to be the current value at the current address's field\r\n var field = fields[j];\r\n var $cell = $row.insertCell(j);\r\n $cell.innerText = date[field];\r\n }\r\n }\r\n}",
"function renderForecastBody(day) {\r\n\t\tvar icon = 'http://icons.wxug.com/i/c/g/' + day.icon + '.gif';\r\n\t\tvar report = $('<div/>', {'class':'reportSingle'})\r\n\t\t .append($('<div/>', {\r\n\t\t \t\t'class':'reportHeader',\r\n\t\t \t\t'text': isToday(day.date) ? \"Today\" : day.date.weekday + \":\"\r\n\t\t \t\t}))\r\n\t\t .append($('<div/>', {'class':'reportBody'})\r\n\t\t \t\t.html($(\"<img/>\")\r\n\t\t \t\t\t.attr({'class':'tempIcon','src':icon}))\r\n\t\t \t\t.append($('<div/>', {'class':'temperature'})\r\n\t\t \t\t\t.html(day.conditions + \"<br /><strong>\" + day.high.fahrenheit + \"°</strong> / \" + day.low.fahrenheit + \"° F\")\r\n\t\t \t\t)\r\n\t\t \t);\r\n\r\n\t\treturn $('<div>').append(report).html(); \r\n\t}",
"_create_table_body(self, daily_data, station_tz, serie_id)\r\n\t{\r\n\t\t\r\n\t\tvar tablebody = document.getElementById(self.__dchar_table_body_id);\r\n\t\t\r\n\t\tfor(var ts in daily_data)\r\n\t\t{\t\r\n\t\t\tif(ts != \"general\")\r\n\t\t\t{\t\r\n\t\t\t\tvar sampleRowEl = document.createElement(\"tr\");\r\n\t\t\t\tvar hm = moment(parseInt(ts)*1000).tz(station_tz)\r\n\t\t\t\t\t\t\t\t\t\t\t\t .format(\"HH:mm\");\r\n\r\n\t\t\t\tvar act = daily_data[ts][\"f_act\"].toFixed(1).toString();\r\n\t\t\t\tvar avg = daily_data[ts][\"f_avg\"].toFixed(1).toString();\r\n\t\t\t\tvar min = daily_data[ts][\"f_min\"].toFixed(1).toString();\r\n\t\t\t\tvar max = daily_data[ts][\"f_max\"].toFixed(1).toString();\r\n\t\t\t\t\r\n\t\t\t\tvar t_min = moment(daily_data[ts][\"i_min_ts\"]*1000)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t.tz(station_tz)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t.format(\"HH:mm\");\r\n\t\t\t\t\r\n\t\t\t\tvar t_max = moment(daily_data[ts][\"i_max_ts\"]*1000)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t.tz(station_tz)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t.format(\"HH:mm\");\r\n\t\t\t\tvar serieUnit = serie_getUnit(serie_id);\r\n\t\t\t\t\r\n\t\t\t\tvar tsEl = document.createElement(\"td\");\r\n\t\t\t\ttsEl.innerHTML = hm;\r\n\t\t\t\ttsEl.style = \"text-align: center;\";\r\n\t\t\t\tvar actEl = document.createElement(\"td\");\r\n\t\t\t\tactEl.innerHTML = act+serieUnit;\r\n\t\t\t\tactEl.style = \"text-align: center;\";\r\n\t\t\t\tvar avgEl = document.createElement(\"td\");\r\n\t\t\t\tavgEl.innerHTML = avg+serieUnit;\r\n\t\t\t\tavgEl.style = \"text-align: center;\";\r\n\t\t\t\tvar minEl = document.createElement(\"td\");\r\n\t\t\t\tminEl.innerHTML = min+serieUnit;\r\n\t\t\t\tminEl.style = \"text-align: center;\";\r\n\t\t\t\tvar maxEl = document.createElement(\"td\");\r\n\t\t\t\tmaxEl.innerHTML = max+serieUnit;\r\n\t\t\t\tmaxEl.style = \"text-align: center;\";\r\n\t\t\t\tvar tMaxEl = document.createElement(\"td\");\r\n\t\t\t\ttMaxEl.innerHTML = t_max;\r\n\t\t\t\ttMaxEl.style = \"text-align: center;\";\r\n\t\t\t\tvar tMinEl = document.createElement(\"td\");\r\n\t\t\t\ttMinEl.innerHTML = t_min;\r\n\t\t\t\ttMinEl.style = \"text-align: center;\";\r\n\t\t\t\t\r\n\t\t\t\tsampleRowEl.append(tsEl);\r\n\t\t\t\tsampleRowEl.append(actEl);\r\n\t\t\t\tsampleRowEl.append(avgEl);\r\n\t\t\t\tsampleRowEl.append(maxEl);\r\n\t\t\t\tsampleRowEl.append(tMaxEl);\r\n\t\t\t\tsampleRowEl.append(minEl);\r\n\t\t\t\tsampleRowEl.append(tMinEl);\r\n\t\t\t\ttablebody.append(sampleRowEl);\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"renderTableData() {\n window.$(\"#expenses\").find(\"tr:gt(0)\").remove();\n let table = document.getElementById(\"expenses\");\n for (let i = 0; i<exps.length; i++) {\n let row = table.insertRow();\n let cell0 = row.insertCell(0);\n let cell1 = row.insertCell(1);\n let cell2 = row.insertCell(2);\n cell0.innerHTML = exps[i].name;\n cell1.innerHTML = exps[i].cost;\n cell2.innerHTML = exps[i].category;\n }\n }",
"function renderAll()\n\t {\n\t \t// Sorting filters arrays.\n\t \tsortFilterArrays();\n\n\t \t// Rendering filters\n\t \trenderFilters();\n\n\t\t// Rendering publications\n\t\trenderPublications();\n\t}",
"function createCell(row, content) {\n // insert cell at the end of the row\n var cell = row.insertCell();\n cell.textContent = content;\n}",
"function renderPage(text){\n //Convert data to table\n var data = textToMatrix(text);\n //Draw teh chart with this data\n drawChart(data);\n \n}",
"function renderGame()\n{\n // CLEAR THE CANVAS\n canvas2D.clearRect(0, 0, canvasWidth, canvasHeight);\n \n // RENDER THE GRID LINES, IF NEEDED\n if (cellLength >= GRID_LINE_LENGTH_RENDERING_THRESHOLD)\n renderGridLines();\n \n // RENDER THE GAME CELLS\n drawBorders();\n renderCells();\n \n // AND RENDER THE TEXT\n renderText();\n \n // THE GRID WE RENDER THIS FRAME WILL BE USED AS THE BASIS\n // FOR THE UPDATE GRID NEXT FRAME\n swapGrids();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set state of the replica to offline. This is typically called when mayastor stops running on the node and the replicas become inaccessible. | offline () {
log.warn(`Replica "${this}" got offline`);
this.isDown = true;
this.pool.node.emit('replica', {
eventType: 'mod',
object: this
});
} | [
"function stayOffline() {\n\t\t\tthis.$stayOffline = true;\n\t\t\tif (this.$retryPromise) {\n\t\t\t\tif ($timeout.cancel(this.$retryPromise)) {\n\t\t\t\t\tthis.$retryPromise = null;\n\t\t\t\t\tthis.$retryCount = 0;\n\t\t\t\t\tthis.$retryScheduled = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}",
"function setOfflineState(userSystem, num, override) {\n\tif (override == \"override\") {\n\t\t// disregard all of the logic below and execute the request silently\n\t\tofflineState = num;\n\t\t$('body').attr('data-offline-mode', offlineState);\n\t\tidbSnapshotUpdate(\"conn\");\n\t\treturn offlineState;\n\t}\n\tif (offlineState == 3) return null;// this variable can never be other than \"3\" in the absence of IDB support; bail\n\tvar originalState = offlineState;\n\tif (typeof num !== 'undefined') {\n\t\tif (num == offlineState) return null;// the offline state is already the specified value; bail\n\t\tif ((offlineState == 2) && (num == 0) && (userSystem == \"system\")) {\n\t\t\treturn null;// the user turned on offline mode and the system is trying to turn it off; don't let it\n\t\t} else if ((offlineState == 2) && (num == 1)) {\n\t\t\treturn null;// the user had already turned offline mode on; don't let the system claim credit for it\n\t\t} else {\n\t\t\tofflineState = num;\n\t\t}\n\t} else {\n\t\tswitch (offlineState) {\n\t\t\tcase 0:\n\t\t\t\tofflineState = (userSystem == \"user\") ? 2 : 1;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tofflineState = 0;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tif (userSystem == \"user\") {\n\t\t\t\t\tofflineState = 0;\n\t\t\t\t} else {\n\t\t\t\t\treturn null;// the user turned on offline mode and the system is trying to turn it off; don't let it\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t// if we weren't online, but now we are -- and there's any data out of sync -- revert this change and bring up the sync modal now\n\t// or, if the application is still launching, flag the sync modal to appear later, right as the splash screen is cleared\n\tif ((originalState != 0) && (offlineState == 0) && (globalSync == false)) {\n\t\tofflineState = originalState;\n\t\tif (appLaunched == true) {\n\t\t\tsyncModal(\"dialog\");\n\t\t} else {\n\t\t\twindow.syncOnLaunch = true;\n\t\t}\n\t} else {\n\t\t// otherwise, commit the change to DOM attribute and IndexedDB\n\t\t$('body').attr('data-offline-mode', offlineState);\n\t\tidbSnapshotUpdate(\"conn\");\n\t\t// convey messaging via pop ups\n\t\tif (offlineState == 0) {\n\t\t\tif (userSystem == \"user\") popupMsg(locale.popup.offline.disabled_user, \"green\");\n\t\t\tif (userSystem == \"system\") popupMsg(locale.popup.offline.disabled_sys, \"green\");\n\t\t} else if (offlineState == 1) {\n\t\t\tpopupMsg(locale.popup.offline.enabled_sys, \"red\");\n\t\t} else if (offlineState == 2) {\n\t\t\tpopupMsg(locale.popup.offline.enabled_user, \"red\");\n\t\t}\n\t}\n\treturn offlineState;\n}",
"toggleOfflineStatus() {\n // the offline manager(goOnline and synchronizeForOffline) actually does the dirty work of\n // changing the offline state with the networking service.\n if (!this.isOnline()) {\n // We do the go online stuff in our listener for the online state change.\n Services.io.offline = false;\n // resume managing offline status now that we are going back online.\n Services.io.manageOfflineStatus = Services.prefs.getBoolPref(\n \"offline.autoDetect\"\n );\n } else {\n // going offline\n // Stop automatic management of the offline status since the user has\n // decided to go offline.\n Services.io.manageOfflineStatus = false;\n var prefDownloadMessages = Services.prefs.getIntPref(\n \"offline.download.download_messages\"\n );\n // 0 == Ask, 1 == Always Download, 2 == Never Download\n var downloadForOfflineUse =\n (prefDownloadMessages == 0 &&\n this.confirmDownloadMessagesForOfflineUse()) ||\n prefDownloadMessages == 1;\n this.offlineManager.synchronizeForOffline(\n downloadForOfflineUse,\n downloadForOfflineUse,\n false,\n true,\n msgWindow\n );\n }\n }",
"isOffline () {\n return this.isDown;\n }",
"static markOffline(serverNodeId){\n\t\tlet kparams = {};\n\t\tkparams.serverNodeId = serverNodeId;\n\t\treturn new kaltura.RequestBuilder('servernode', 'markOffline', kparams);\n\t}",
"function setAtmState(newState) {\n atmMachine = Object.create(newState);\n}",
"_resetForNewReconnection() {\n this[STATE].shouldReconnect = true;\n this[STATE].reconnectDelay = Constants.RECONNECT_DELAY_MS;\n this[STATE].reconnectAttempts = 0;\n }",
"function off(pin) {\n return set(pin, OFF);\n}",
"unbind () {\n log.debug(`Removing replica \"${this}\" from the list of replicas`);\n this.pool.unregisterReplica(this);\n this.pool.node.emit('replica', {\n eventType: 'del',\n object: this\n });\n this.pool = null;\n }",
"function markOffline(accessPointId) {\n\treturn redis.psrem(SET_ACCESS_POINTS_ONLINE, accessPointId)\n}",
"turnOff() {\n\t\tthis.lightMap.makeDarkness();\n\t}",
"function offLine() {\n // var icons = $(\".icon\");\n // for (var i = 0; i < apps.length; i++) {\n // if (!apps[i].offlineEnabled && apps[i].enabled) {\n // // The app is not offline-enabled\n // $(icons[i]).css(\"opacity\", \"0.3\");\n // }\n // }\n $(\"#launcher\").addClass(\"offline\");\n}",
"setRoomUnlocked() {\n if (this.isModerator) {\n this.getRoomLocker().lock().then(() => {\n APP.UI.emitEvent(UIEvents.TOGGLE_ROOM_LOCK);\n this.updateView();\n });\n }\n }",
"pollute(n, addr) {\n this.sets[addr.idx][n].dirty = true;\n }",
"isDatabaseOffline() {\n const serverResponse = this.props.serverResponse;\n // objects that have status of error will have all the errorEvent properties needed.\n return serverResponse.status === \"error\" && serverResponse.errorEvent === \"database offline\"\n && this.isEventForUs(serverResponse.event);\n }",
"function vm_replica_status_update(hostname, result) {\n var rep_status = $(jq('vm_replica_status_' + hostname));\n\n if (!rep_status.length) {\n return; // Not on server details page\n }\n\n if (typeof(result.last_sync) === 'undefined') {\n return; // Missing last_sync -> nothing to do\n }\n\n function set_last_sync() {\n var last_sync;\n if (result.last_sync) {\n last_sync = moment(result.last_sync).tz(CURRENT_TZ).strftime(LONG_DATETIME_FORMAT);\n rep_status.find('.vm_replica_last_sync').html(last_sync);\n }\n }\n\n if (result._event_ == 'vm_replica_synced') {\n // VM replica sync event -> update only last_sync datetime\n set_last_sync();\n return;\n }\n\n if (result.enabled === null) {\n // Replica was deleted\n rep_status.hide();\n } else if (result.enabled === false) {\n rep_status.find('.vm_replica_sync_status').removeClass('icon-enabled').addClass('icon-disabled');\n set_last_sync();\n rep_status.show();\n } else if (result.enabled === true) {\n rep_status.find('.vm_replica_sync_status').removeClass('icon-disabled').addClass('icon-enabled');\n set_last_sync();\n rep_status.show();\n }\n}",
"restore() {\n FetchServer.restore();\n }",
"resetBackoff() {\n process.nextTick(() => {\n this.backoffTimeout.reset();\n this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.CONNECTING);\n });\n }",
"relocateMole() {\n\t\tgameState.mole.anims.play('disappear');\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts this LatLngPoint to a Universal Transverse Mercator point using the WGS84 datum. The coordinate pair's units will be in meters, and should be usable to make distance calculations over short distances. | toUTM() {
return new UTMPoint().fromLatLng(this);
} | [
"function CHtoWGSlat(y, x) {\n\n // Converts military to civil and to unit = 1000km\n // Auxiliary values (% Bern)\n var y_aux = (y - 600000)/1000000;\n var x_aux = (x - 200000)/1000000;\n \n // Process lat\n lat = 16.9023892\n + 3.238272 * x_aux\n - 0.270978 * Math.pow(y_aux,2)\n - 0.002528 * Math.pow(x_aux,2)\n - 0.0447 * Math.pow(y_aux,2) * x_aux\n - 0.0140 * Math.pow(x_aux,3);\n \n // Unit 10000\" to 1 \" and converts seconds to degrees (dec)\n lat = lat * 100/36;\n \n return lat;\n \n}",
"toDefaultProjection(lat, long) {\n return ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857');\n }",
"multiplyXYZWQuietRenormalize(x, y, z, w, result) {\n result = result ? result : Point3dVector3d_1.Point3d.createZero();\n result.set(this._coffs[0] * x + this._coffs[1] * y + this._coffs[2] * z + this._coffs[3] * w, this._coffs[4] * x + this._coffs[5] * y + this._coffs[6] * z + this._coffs[7] * w, this._coffs[8] * x + this._coffs[9] * y + this._coffs[10] * z + this._coffs[11] * w);\n const w1 = this._coffs[12] * x + this._coffs[13] * y + this._coffs[14] * z + this._coffs[15] * w;\n if (!Geometry_1.Geometry.isSmallMetricDistance(w1)) {\n const a = 1.0 / w1;\n result.x *= a;\n result.y *= a;\n result.z *= a;\n }\n return result;\n }",
"function ToLL(north,east,utmZone)\n{ \n // This is the lambda knot value in the reference\n var LngOrigin = DegToRad(utmZone * 6 - 183)\n\n // The following set of class constants define characteristics of the\n // ellipsoid, as defined my the WGS84 datum. These values need to be\n // changed if a different dataum is used. \n\n var FalseNorth = 0. // South or North?\n //if (lat < 0.) FalseNorth = 10000000. // South or North?\n //else FalseNorth = 0. \n\n var Ecc = 0.081819190842622 // Eccentricity\n var EccSq = Ecc * Ecc\n var Ecc2Sq = EccSq / (1. - EccSq)\n var Ecc2 = Math.sqrt(Ecc2Sq) // Secondary eccentricity\n var E1 = ( 1 - Math.sqrt(1-EccSq) ) / ( 1 + Math.sqrt(1-EccSq) )\n var E12 = E1 * E1\n var E13 = E12 * E1\n var E14 = E13 * E1\n\n var SemiMajor = 6378137.0 // Ellipsoidal semi-major axis (Meters)\n var FalseEast = 500000.0 // UTM East bias (Meters)\n var ScaleFactor = 0.9996 // Scale at natural origin\n\n // Calculate the Cassini projection parameters\n\n var M1 = (north - FalseNorth) / ScaleFactor\n var Mu1 = M1 / ( SemiMajor * (1 - EccSq/4.0 - 3.0*EccSq*EccSq/64.0 -\n 5.0*EccSq*EccSq*EccSq/256.0) )\n\n var Phi1 = Mu1 + (3.0*E1/2.0 - 27.0*E13/32.0) * Math.sin(2.0*Mu1)\n + (21.0*E12/16.0 - 55.0*E14/32.0) * Math.sin(4.0*Mu1)\n + (151.0*E13/96.0) * Math.sin(6.0*Mu1)\n + (1097.0*E14/512.0) * Math.sin(8.0*Mu1)\n\n var sin2phi1 = Math.sin(Phi1) * Math.sin(Phi1)\n var Rho1 = (SemiMajor * (1.0-EccSq) ) / Math.pow(1.0-EccSq*sin2phi1,1.5)\n var Nu1 = SemiMajor / Math.sqrt(1.0-EccSq*sin2phi1)\n\n // Compute parameters as defined in the POSC specification. T, C and D\n\n var T1 = Math.tan(Phi1) * Math.tan(Phi1)\n var T12 = T1 * T1\n var C1 = Ecc2Sq * Math.cos(Phi1) * Math.cos(Phi1)\n var C12 = C1 * C1\n var D = (east - FalseEast) / (ScaleFactor * Nu1)\n var D2 = D * D\n var D3 = D2 * D\n var D4 = D3 * D\n var D5 = D4 * D\n var D6 = D5 * D\n\n // Compute the Latitude and Longitude and convert to degrees\n var lat = Phi1 - Nu1*Math.tan(Phi1)/Rho1 *\n ( D2/2.0 - (5.0 + 3.0*T1 + 10.0*C1 - 4.0*C12 - 9.0*Ecc2Sq)*D4/24.0\n + (61.0 + 90.0*T1 + 298.0*C1 + 45.0*T12 - 252.0*Ecc2Sq - 3.0*C12)*D6/720.0 )\n\n lat = RadToDeg(lat)\n\n var lon = LngOrigin + \n ( D - (1.0 + 2.0*T1 + C1)*D3/6.0\n + (5.0 - 2.0*C1 + 28.0*T1 - 3.0*C12 + 8.0*Ecc2Sq + 24.0*T12)*D5/120.0) / Math.cos(Phi1)\n\n lon = RadToDeg(lon)\n\n // Create a object to store the calculated Latitude and Longitude values\n var sendLatLon = new PC_LatLon(lat,lon)\n\n // Returns a PC_LatLon object\n return sendLatLon\n}",
"function formVector(p, q)\n{\n var pq = {lantitude: 0.0, longitude: 0.0, height: 0.0};\n pq.lantitude = q.lantitude - p.lantitude;\n pq.longitude = q.longitude - p.longitude;\n pq.height = q.height - p.height;\n return pq;\n}",
"viewerCoordsToSphericalCoords(viewerPoint) {\n const vector = this.viewerCoordsToVector3(viewerPoint);\n return vector ? this.vector3ToSphericalCoords(vector) : null;\n }",
"function CHtoWGSlng(y, x) {\n\n // Converts military to civil and to unit = 1000km\n // Auxiliary values (% Bern)\n var y_aux = (y - 600000)/1000000;\n var x_aux = (x - 200000)/1000000;\n \n // Process long\n lng = 2.6779094\n + 4.728982 * y_aux\n + 0.791484 * y_aux * x_aux\n + 0.1306 * y_aux * Math.pow(x_aux,2)\n - 0.0436 * Math.pow(y_aux,3);\n \n // Unit 10000\" to 1 \" and converts seconds to degrees (dec)\n lng = lng * 100/36;\n \n return lng;\n \n}",
"function hackMapProjection(lat, lon, originLat, originLon) {\n var lonCorrection = 1.5;\n var rMajor = 6378137.0;\n\n function lonToX(lon) {\n return rMajor * (lon * Math.PI / 180);\n }\n\n function latToY(lat) {\n if (lat === 0) {\n return 0;\n } else {\n return rMajor * Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI / 180) / 2));\n }\n }\n\n var x = lonToX(lon - originLon) / lonCorrection;\n var y = latToY(lat - originLat);\n return {'x': x, 'y': y};\n}",
"toCoordinate() {\n assertParameters(arguments);\n \n return new Coordinate(this._width, this._height);\n }",
"function unproject(coord) {\n return map.unproject(coord, map.getMaxZoom());\n}",
"latitudeToMetersY(latitude) {\n return this.WGS84.EQUATORIALRADIUS * Math.log(Math.tan(Math.PI / 4 + 0.5 * ((latitude * Math.PI) / 180)));\n }",
"function moveWest() {\n currentLonPoint -= 0.00050\n console.log(currentLonPoint)\n map.setView([currentLatPoint, currentLonPoint], 18)\n\n }",
"getDistance() {\n const {origin, destination} = this.props;\n if (app.google && origin && destination) {\n const geometry = app.google.maps.geometry.spherical;\n const meters = geometry.computeDistanceBetween(origin, destination);\n const units = unitsMap[this.state.units];\n const distance = meters * units.value;\n const s = distance === 1 ? '' : 's';\n return `${distance.toFixed(3)} ${units.name}${s}`;\n }\n }",
"function translateG() {\r\n svgMapOverlay.selectAll('g.gLocation')\r\n .each(function(d) {\r\n\t x = getX(d.Lat, d.Long);\r\n\t y = getY(d.Lat)\r\n\t d3.select(this)\r\n\t .attr('transform', `translate(${x}, ${y})`);\r\n\t});\r\n}",
"longitudeToMetersX(longitude) {\n return this.WGS84.EQUATORIALRADIUS * ((Math.PI * longitude)/ 180);\n }",
"latLng(){\r\n return L.latLng(this.latitude, this.longitude);\r\n }",
"function moveSouth() {\n currentLatPoint -= 0.00050\n console.log(currentLatPoint)\n map.setView([currentLatPoint, currentLonPoint], 18)\n\n }",
"function unitConverter() {\n\n var unit = document.getElementById(\"basic-addon2\").value;\n var num = document.getElementById(\"inputDistance\").value;\n\n if (unit === 'miles') {\n carbonConverter(num)}\n if (unit === 'km'){\n var newNum = num * 0.621371;\n carbonConverter(newNum)\n }\n}",
"function ComputeLatFromTrueCourseAndDistance(Lat2output, Lat1input, Lon1input, TCinput, DistInput) {\n Equation.call(this, Lat2output, Lat1input, Lon1input, TCinput, DistInput);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a new ``uint160`` type for %%v%%. | static uint160(v) { return n(v, 160); } | [
"static uint(v) { return n(v, 256); }",
"static uint168(v) { return n(v, 168); }",
"static uint208(v) { return n(v, 208); }",
"static uint120(v) { return n(v, 120); }",
"static uint240(v) { return n(v, 240); }",
"static uint80(v) { return n(v, 80); }",
"static uint256(v) { return n(v, 256); }",
"static uint112(v) { return n(v, 112); }",
"static uint176(v) { return n(v, 176); }",
"static uint40(v) { return n(v, 40); }",
"static uint56(v) { return n(v, 56); }",
"static uint192(v) { return n(v, 192); }",
"static uint144(v) { return n(v, 144); }",
"static uint32(v) { return n(v, 32); }",
"static uint184(v) { return n(v, 184); }",
"static uint88(v) { return n(v, 88); }",
"static uint216(v) { return n(v, 216); }",
"static uint136(v) { return n(v, 136); }",
"static uint248(v) { return n(v, 248); }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the private key fields N, e, and d from hex strings | function RSASetPrivate(N, E, D)
{
if (N != null && E != null && N.length > 0 && E.length > 0)
{
this.n = parseBigInt(N, 16);
this.e = parseInt(E, 16);
this.d = parseBigInt(D, 16);
}
else alert("Invalid RSA private key");
} | [
"function RSASetPrivate(N,E,D) {\r\n if(N != null && E != null && N.length > 0 && E.length > 0) {\r\n this.n = parseBigInt(N,16);\r\n this.e = parseInt(E,16);\r\n this.d = parseBigInt(D,16);\r\n }\r\n else\r\n alert(\"Invalid RSA private key\");\r\n}",
"function seed2key(pk, c){ return hex2hexKey(hash256(pk+c)); }",
"getPrivKey() {\n var output = PrivKeyAsn1.encode({\n d: this.key.priv.toString(10),\n }, \"der\")\n return output.toString('hex')\n }",
"function generatePrivateKey(prefix, username){\n return prefix + '.' + 'component' + '.' + username;\n}",
"generatePrivateKey() {\n // Generates 64 hexadecimal values then concatenates all 64 values\n let r = [];\n for (let i = 0; i < 64; i++) {\n r.push(this.random.integer(0, 15).toString(16));\n }\n return r.join('');\n }",
"function generateAndSetKeypair () {\n opts.log(`generating ${opts.bits}-bit RSA keypair...`, false)\n var keys = peerId.create({\n bits: opts.bits\n })\n config.Identity = {\n PeerID: keys.toB58String(),\n PrivKey: keys.privKey.bytes.toString('base64')\n }\n opts.log('done')\n opts.log('peer identity: ' + config.Identity.PeerID)\n\n writeVersion()\n }",
"function expandkey(key56) {\n\tvar key64 = new Buffer(8);\n\n\tkey64[0] = key56[0] & 0xFE;\n\tkey64[1] = key56[0] << 7 & 0xFF | key56[1] >> 1;\n\tkey64[2] = key56[1] << 6 & 0xFF | key56[2] >> 2;\n\tkey64[3] = key56[2] << 5 & 0xFF | key56[3] >> 3;\n\tkey64[4] = key56[3] << 4 & 0xFF | key56[4] >> 4;\n\tkey64[5] = key56[4] << 3 & 0xFF | key56[5] >> 5;\n\tkey64[6] = key56[5] << 2 & 0xFF | key56[6] >> 6;\n\tkey64[7] = key56[6] << 1 & 0xFF;\n\n\treturn key64;\n}",
"function deriveKey(N, token) {\n // the exact bits of the string \"hash_derive_key\"\n const tagBits = sjcl.codec.hex.toBits(\"686173685f6465726976655f6b6579\");\n const h = new sjcl.misc.hmac(tagBits, sjcl.hash.sha256);\n\n const encodedPoint = sec1EncodePoint(N);\n const tokenBits = sjcl.codec.bytes.toBits(token);\n const pointBits = sjcl.codec.bytes.toBits(encodedPoint);\n\n h.update(tokenBits);\n h.update(pointBits);\n\n const keyBytes = sjcl.codec.bytes.fromBits(h.digest());\n return keyBytes;\n}",
"InitializeFromEncodedPublicKeyInfo(string, EncodingType) {\n\n }",
"function toDecimalFrom4Hex(h, k) {\r\n return h * 3 + k;\r\n }",
"walletSetup(seed) {\n\n const root = Hdkey.fromMasterSeed(seed);\n const masterPrivateKey = root.privateKey.toString('hex');\n\n const addrNode = root.derive(\"m/44'/60'/0'/0/0\"); //line 1\n const pubKey = EthUtil.privateToPublic(addrNode._privateKey);\n const addr = EthUtil.publicToAddress(pubKey).toString('hex');\n const address = EthUtil.toChecksumAddress(addr);\n const key = {\n 'root': root,\n 'masterPrivateKey': masterPrivateKey,\n 'addrNode': addrNode,\n 'pubKey': pubKey,\n 'addr': addr,\n 'address': address\n };\n const hexPrivateKey = EthUtil.bufferToHex(addrNode._privateKey)\n this.props.setKeys(masterPrivateKey, address, hexPrivateKey);\n\n this.props.navigation.navigate('HomeScreen');\n /*\n If using ethereumjs-wallet instead do after line 1:\n const address = addrNode.getWallet().getChecksumAddressString();\n */\n }",
"function hex2hexKey(s){ return bigInt2hex(hex2bigIntKey(removeWhiteSpace(s))); }",
"function setPassword(password, callback){\n webSocket.shh.generateSymKeyFromPassword(password, callback);\n}",
"function bigInt2ECKey(i){ return new Bitcoin.ECKey(bigInt2bigIntKey(i)); }",
"set key(key) {\n console.info('initializing crypt');\n\n // Fresh RC4's\n this._encrypt = new RC4();\n this._decrypt = new RC4();\n\n // Calculate the encryption hash (through the server decryption key)\n const enckey = ArrayUtil.fromHex('C2B3723CC6AED9B5343C53EE2F4367CE');\n const enchash = HMAC.fromArrays(enckey, key);\n\n // Calculate the decryption hash (through the client decryption key)\n const deckey = ArrayUtil.fromHex('CC98AE04E897EACA12DDC09342915357');\n const dechash = HMAC.fromArrays(deckey, key);\n\n // Seed RC4's with the computed hashes\n this._encrypt.init(enchash);\n this._decrypt.init(dechash);\n\n // Ensure the buffer is synchronized\n for (let i = 0; i < 1024; ++i) {\n this._encrypt.next();\n this._decrypt.next();\n }\n }",
"function pubKeyHash2bitAdd(k){\r\n var b = new Bitcoin.Address(hex2bytes(k));\r\n return b.toString();\r\n}",
"function indcpaPackPrivateKey(privateKey, paramsK) {\r\n return polyvecToBytes(privateKey, paramsK);\r\n}",
"function pkcs1pad2(s,n) {\r\n if(n < s.length + 11) {\r\n alert(\"Message too long for RSA\");\r\n return null;\r\n }\r\n var ba = new Array();\r\n var i = s.length - 1;\r\n while(i >= 0 && n > 0) ba[--n] = s.charCodeAt(i--);\r\n ba[--n] = 0;\r\n var rng = new SecureRandom();\r\n var x = new Array();\r\n while(n > 2) { // random non-zero pad\r\n x[0] = 0;\r\n while(x[0] == 0) rng.nextBytes(x);\r\n ba[--n] = x[0];\r\n }\r\n ba[--n] = 2;\r\n ba[--n] = 0;\r\n return new BigInteger(ba);\r\n}",
"function InitHashKeys() {\n var index = 0;\n for (index = 0; index < 14 * 120; ++index) {\n PieceKeys[index] = RAND_32();\n }\n\n SideKey = RAND_32();\n\n for(index = 0; index < 16; ++index) {\n CastleKeys[index] = RAND_32();\n }\n}",
"function indcpaUnpackPrivateKey(packedPrivateKey, paramsK) {\r\n return polyvecFromBytes(packedPrivateKey, paramsK);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shortcut for getting the current col value (one based) Returns the column (position) where the last token starts | function col () {
return index - token.length + 1;
} | [
"function col(numCol) {\n return numCol * COL + COL_OFFSET;\n}",
"get goalColumn() {\n let value = this.flags >> 5 /* RangeFlag.GoalColumnOffset */\n return value == 33554431 /* RangeFlag.NoGoalColumn */\n ? undefined\n : value\n }",
"rightMostColumn(){\n let headers = this.props.tableData.headers\n if(headers.fixedLeft<headers.headers.length){\n let windowSize=headers.columns-1-headers.fixedLeft\n return headers.currentLeft+windowSize-1\n }else{\n return headers.headers.length-1\n }\n }",
"getLastColumn(){\n\t\tif(!this.isGroup){\n\t\t\treturn this;\n\t\t}else{\n\t\t\tif(this.columns.length){\n\t\t\t\treturn this.columns[this.columns.length -1].getLastColumn();\n\t\t\t}else{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}",
"getColumnIndex(): number {\n const { row, cell } = this;\n const cells = row.nodes;\n\n return cells.findIndex(x => x === cell);\n }",
"getCol(){\n\t\treturn this._col.centerAt(this.pos);\n\t}",
"get row() {\n return INDEX2ROW(getTop()) + 1;\n }",
"function getOffset() {\n var indentation = [];\n var pos = line + 1;\n\n /* Done. Called when the last character is\n * eaten to retrieve the range’s offsets. */\n return function () {\n var last = line + 1;\n\n while (pos < last) {\n indentation.push((offset[pos] || 0) + 1);\n\n pos++;\n }\n\n return indentation;\n };\n }",
"function findSpotForCol(x) {\n const y = board.findIndex((row) => row[x] === null)\n return y !== -1 ? y : null; \n}",
"get currentLine() {\n return this.lines[ this.cursor.y ].textContent;\n }",
"function getCol(id) {\n\treturn /spot\\d(\\d)/.exec(id)[1];\n }",
"function findLastEmptyCell(incoming_col){\n const container = document.querySelector('#connect4');\n const containerRow = container.querySelectorAll('.row');\n cellsArr = [];\n containerRow.forEach(function(row){\n cells = row.querySelector('[data-col=\"'+ incoming_col +'\"]');\n cellsArr.push(cells);\n });\n\n // Looping through array of each column to find the last empty spot\n for(let i = cellsArr.length-1; i>=0; i--){\n const classes = cellsArr[i].classList\n if(classes == 'col empty'){\n console.log(classes)\n return cellsArr[i];\n }\n }\n return null;\n }",
"function COLUMN(value) {\n\n // Return `#VALUE!` when the value is not a reference.\n if (!ISREF(value)) {\n return error$2.value;\n }\n\n // Run the COLUMNNUMBER and convert to base 1.\n return COLUMNNUMBER(value.column) + 1;\n}",
"function getLastPositionOfCurrentWord(editableDiv) {\n\tvar {first: lineFirstPos, last: lineLastPos} = getExtremePosInCurrentLine(editableDiv);\n\tvar caretPos = getCaretPositionInDiv(editableDiv);\n\tvar curPos = caretPos;\n\tvar curLetter = getCharAtPosInDiv(editableDiv, curPos);\n\tif (curPos == lineLastPos){\n\t\treturn curPos-1;\n\t}\n\twhile (curLetter != ' ' && curPos < lineLastPos) {\n\t\tcurPos += 1;\n\t\t// change to getCharAtPosInDiv, when it's correct\n\t\tcurLetter = getCharAtPosInDiv(editableDiv, curPos);\n\t}\n\tif (curLetter == ' ' || curPos == lineLastPos) {\n\t\treturn curPos-1;\n\t} else {\n\t\treturn curPos;\n\t}\n}",
"cellToTextEditorPosition(row, column) {\n invariant(row < this.screen.cells.length, 'row must be < than grid row count');\n const lineNumberText = this.screen.cells[row].slice(0, this.lineNumberColumns).join('');\n const lineNumber = Number(lineNumberText) - 1;\n invariant(\n !Number.isNaN(lineNumber),\n `Invalid line number parsed for row ${row}. Line was ${lineNumberText}.`);\n return [lineNumber, column - this.lineNumberColumns];\n }",
"function INDEX2COL(index) {\n return index - INDEX2ROW(index) * MaxCols;\n}",
"function getSheetEndColumn() {\r\n\t\r\n\tif(sheetEndColumns.length==0){\r\n\t\t//Here, I have to define which is the last valid column for each spreadsheet\r\n\t\t//The second sheet contains the data, here the nr of columns is always 4 + nr of data elements:\r\n\t\t//Update the column index if the layout of the template changes!\r\n\t\tcolumnIndex=4+dataElementIDs.size;\t\r\n\t\tvar div = Math.floor(columnIndex/26);\r\n\t\tvar rem = columnIndex % 26;\t\r\n\t\tvar lastColumn = \"\";\r\n\t\t\r\n\t\tif(div==0){\r\n\t\t\tlastColumn=letters[rem];\r\n\t\t}else{\r\n\t\t\tlastColumn=letters[div].concat(letters[rem])\r\n\t\t}\t\t\r\n\t\tconsole.log(\"div: \"+ div +\"rem: \"+ rem ,\"letter:\"+ lastColumn)\r\n\t\t\r\n\t\tsheetEndColumns.push(lastColumn);\r\n\t\t//The second sheet always contains a legend with two columns.\r\n\t\t//sheetEndColumns.push('B');\r\n\t\t//The third sheet always contains a legend with two columns.\r\n\t\t//sheetEndColumns.push(letter[div].concat(letter[rem]));\r\n\t}\r\n\treturn lastColumn\r\n}",
"getTopColumn(){\n\t\tif(this.parent.isGroup){\n\t\t\treturn this.parent.getTopColumn();\n\t\t}else{\n\t\t\treturn this;\n\t\t}\n\t}",
"isLastColumn(): boolean {\n return this.getColumnIndex() === this.getWidth() - 1;\n }",
"function lineColPositionFromOffset(offset, lineBreaks) {\n let line = remix_lib_1.util.findLowerBound(offset, lineBreaks);\n\n if (lineBreaks[line] !== offset) {\n line += 1;\n }\n\n const beginColumn = line === 0 ? 0 : lineBreaks[line - 1] + 1;\n return {\n line: line + 1,\n character: offset - beginColumn + 1\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves the FIO public key assigned to the FIOSDK instance. | getFioPublicKey() {
return this.publicKey;
} | [
"function getPublicKey(req, res) {\n var key_path = './server/keystore/key/public_key.pem';\n return g_fs.readFileAsync(key_path, \"ascii\")\n .then(function (content) {\n return res.send(content);\n })\n .catch(function (exception) {\n console.log(\"error fetching key\");\n res.sendStatus(400);\n });\n }",
"function getClientKey() {\n\n }",
"function getPubkey(callback) {\n sbot.whoami(function(err, msg) {\n if(err) { \n console.log('getPubkey(callback) err', err, '\\n\\n\\n\\n')\n return callback(err)\n } else {\n console.log('getPubkey(callback) msg', msg, '\\n\\n\\n\\n')\n return callback(null, msg)\n }\n })\n }",
"getPrivKey() {\n var output = PrivKeyAsn1.encode({\n d: this.key.priv.toString(10),\n }, \"der\")\n return output.toString('hex')\n }",
"ComputeKeyIdentifier() {\n\n }",
"function forgeKey(privateKey) {\n return function() {\n // convert PEM-formatted private key to a Forge private key\n const forgePrivateKey = forge.pki.privateKeyFromPem(privateKey);\n // get a Forge public key from the Forge private key\n const forgePublicKey = forge.pki.setRsaPublicKey(\n forgePrivateKey.n,\n forgePrivateKey.e\n );\n // convert the Forge public key to a PEM-formatted public key\n const publicKey = forge.pki.publicKeyToPem(forgePublicKey);\n\n return publicKey;\n\n // Below is a curried version with arrow functions\n // Given a private key, get a function that can generate a public key\n // const getPublicKey = (forgePrivateKey) => () => forge.pki.publicKeyToPem(forge.pki.setRsaPublicKey(forgePrivateKey.n, forgePrivateKey.e));\n };\n}",
"async _publicKeyFromCertificate (crtPath) {\n let output = '';\n await this.opensslCommand(\n ['x509', '-noout', '-in', crtPath, '-pubkey', '-outform', 'pem'],\n (o => { output += o; })\n );\n return output;\n }",
"getPublicAddress(fioAddress, chainCode, tokenCode) {\n const publicAddressLookUp = new queries.GetPublicAddress(fioAddress, chainCode, tokenCode);\n return publicAddressLookUp.execute(this.publicKey);\n }",
"async function fingerprint(pubJWK) {\n const pub = await _import(pubJWK);\n const spki = await cs.exportKey(\"spki\", pub);\n const digest = await cs.digest(\"SHA-256\", spki);\n return base64.stringify(digest);\n}",
"static generateKey(){\n\t\tlet kparams = {};\n\t\treturn new kaltura.RequestBuilder('playready_playreadydrm', 'generateKey', kparams);\n\t}",
"function getConsumerKey(){\n prompt( 'Enter OAuth consumer key:', function( key ){\n consumerKey = key;\n getConsumerSecret();\n } );\n }",
"function getProjectKey(projectOrKey){if(typeof projectOrKey==='string'){return projectOrKey;}else if(!projectOrKey){throw new Error(AJS.I18n.getText('bitbucket.web.error.no.project'));}return projectOrKey.getKey?projectOrKey.getKey():projectOrKey.key;}",
"getKey() {\n return new DependencyKey(this.context, this.identifier);\n }",
"function ApiKey(props) {\n return __assign({ Type: 'AWS::AppSync::ApiKey' }, props);\n }",
"get apiKeySource() {\n return this.getStringAttribute('api_key_source');\n }",
"ListOfYourPublicSSHKeys() {\n let url = `/me/sshKey`;\n return this.client.request('GET', url);\n }",
"function importPubKey() {\n var newPubKey = new PubKeys(\n {raw_key: ctrl.raw_key, self_signature: ctrl.self_signature}\n );\n newPubKey.$save(\n function(newPubKey_) {\n raiseAlert('success', '', 'Public key saved successfully');\n $uibModalInstance.close(newPubKey_);\n },\n function(httpResp) {\n raiseAlert('danger',\n httpResp.statusText, httpResp.data.title);\n ctrl.cancel();\n }\n );\n }",
"generateOnionService(){\n let pkraw = forge.rsa.generateKeyPair(1024);\n let pkfp = forge.pki.getPublicKeyFingerprint(pkraw.publicKey, {encoding: 'hex', md: forge.md.sha1.create()})\n let pem = forge.pki.privateKeyToPem(pkraw.privateKey);\n\n if (pkfp.length % 2 !== 0) {\n // odd number of characters\n pkfp = '0' + pkfp;\n }\n let bytes = [];\n for (let i = 0; i < pkfp.length/2; i = i + 2) {\n bytes.push(parseInt(pkfp.slice(i, i + 2), 16));\n }\n\n let onion = base32.encode(bytes).toLowerCase() + \".onion\";\n return {onion: onion, privateKey: pem};\n }",
"function issueKeyPair(accessPointId) {\n\tconst keys = keypair(),\n \t publicKey = forge.pki.publicKeyFromPem(keys.public)\n\n \tkeys.public_ssh = forge.ssh.publicKeyToOpenSSH(publicKey, accessPointId)\n \t\n \treturn keys;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checking if there is something within a distance of the specified coords excludes the specified entity | function isSpaceOccupied(entity, distance, x, y){
if(entity !== 'tree'){
for(var i in treeList){
if(distanceBetweenCoords(treeList[i].x,treeList[i].y,x,y) < distance){
return true;
}
}
}
if(entity !== 'berryBush'){
for(var i in berryBushList){
if(distanceBetweenCoords(berryBushList[i].x,berryBushList[i].y,x,y) < distance){
return true;
}
}
}
if(entity !== 'villager'){
for(var i in villagerList){
if(distanceBetweenCoords(villagerList[i].x,villagerList[i].y,x,y) < distance){
return true;
}
}
}
if(entity !== 'depot'){
for(var i in depotList){
if(distanceBetweenCoords(depotList[i].x,depotList[i].y,x,y) < distance){
return true;
}
}
}
return false;
} | [
"function isInDistance (player, block) {\n const firstCondition = (Math.abs(block.dataset['x'] - player.position.x) <= 3)\n && (block.dataset['y'] === player.position.y);\n const secondCondition = (Math.abs(block.dataset['y'] - player.position.y) <= 3) \n && (block.dataset['x'] === player.position.x);\n return (firstCondition || secondCondition);\n }",
"function isInCoords( coords ) {\n\t\t\t\t// get current drop position\n\t\t\t\tvar dropX = getX();\n\t\t\t\tvar dropY = getY();\n\t\t\t\t\n\t\t\t\t//console.log(\"isInCoords: x = \" + getX() + \", y = \" + getY() + \", coords = \" + coords.top + \", \" + coords.right + \", \" + coords.bottom + \", \" + coords.left );\n\t\t\t\t\n\t\t\t\t// test if parameter is valid\n\t\t\t\tif (!coords || !coords.hasOwnProperty(\"top\") || !coords.hasOwnProperty(\"right\") || !coords.hasOwnProperty(\"bottom\") || !coords.hasOwnProperty(\"left\") ) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\t// test drop position versus coordinates\n\t\t\t\tif ( dropY > coords.top && dropY < coords.bottom && dropX > coords.left && dropX < coords.right ) {\n\t\t\t\t\treturn true;\n\t\t\t\t} else {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}",
"reachedTargetPosition() {\n if (this.target !== undefined) {\n let targetCenter = this.getTargetCenter();\n let ownCenter = this.getCenter();\n // console.log(ownCenter);\n // console.log(targetCenter);\n var distance = Phaser.Math.Distance.Between(\n ownCenter.x,\n ownCenter.y,\n targetCenter.x,\n targetCenter.y\n );\n if (distance < 10) {\n return true;\n }\n // console.log(distance);\n }\n return false;\n }",
"function dist(distance, x1, y1, x2, y2) {\n if(Math.abs(x1-x2) === distance && y1 === y2 || x1 === x2 && Math.abs(y1-y2) === distance) {\n return true;\n }\n else {\n return false;\n }\n \n}",
"isInside(modelSpacePoint) {\n\t\t// jshint unused:vars\n\t\treturn false;\n\t}",
"function checkCollision(location, collisionDistance) {\n //first have to project...\n var locationProj = getScreenCoords(location);\n if (!locationProj)\n return true;\n\n var hitTestResult = ge.getView().hitTest(locationProj[0], ge.UNITS_PIXELS, locationProj[1], ge.UNITS_PIXELS, ge.HIT_TEST_BUILDINGS);\n //var hitTestResult = ge.getView().hitTest(0.5, ge.UNITS_FRACTION, 0.75, ge.UNITS_FRACTION, ge.HIT_TEST_BUILDINGS); //0.75 is a guestemate. Not worth calculating\n if (hitTestResult) {\n var charGLat = new GLatLng(me.characterLla[0], me.characterLla[1]);\n var distFromResult = charGLat.distanceFrom(new GLatLng(hitTestResult.getLatitude(), hitTestResult.getLongitude()));\n if (distFromResult < DISTANCE_FROM_COLLISION) {\n currentSpeed = 0;\n return true;\n }\n }\n return false;\n}",
"function getEnemy(x, y, distance) {\n const enemyUnits = enemies1.getChildren().concat(enemies2.getChildren());\n for (let i = 0; i < enemyUnits.length; i++) {\n if (enemyUnits[i].active && Phaser.Math.Distance.Between(x, y, enemyUnits[i].x, enemyUnits[i].y) <= distance) {\n return enemyUnits[i];\n }\n }\n return false;\n}",
"function checkEnemyFromBob(enemy,player,noOfCells) {\n var checkdistance=room.cellsize*noOfCells;\n var distance =math.getDistanceBetweenTwoPoints(enemy,player);\n if(distance<=checkdistance)\n return true;\n else\n return false;\n }",
"function isFree(aLocation) {\n //for (var liste in locations) {\n // for (var i in liste) {\n // if (i.x == aLocation.x && i.y == aLocation.y) {\n // return false;\n // }\n // }\n //}\n return true;\n}",
"function checkFood(food){\n if ((Math.pow(this.endX - food.xLoc, 2) + Math.pow(this.endY - food.yLoc, 2)) < Math.pow(foodSize/2, 2)){\n food.remove();\n }\n}",
"function out_of_screen(){\r\n ax = airplane_pos.worldMatrix[6];\r\n ay = airplane_pos.worldMatrix[7];\r\n if (ax < -30 || ax > width + 30 || ay < -30 || ay > height + 30) return true;\r\n return false;\r\n}",
"function isInBound(x,y){\n\treturn x>-1&&x<9&&y>-1&&y<9;\n}",
"contains(x, y) {\r\n if (!this.isEnabled()) return false;\r\n if (x < this.at().x || x > (this.at().x + this.width())) return false;\r\n if (y < this.at().y || y > (this.at().y + this.height())) return false;\r\n return true;\r\n }",
"function safeCoordinate(x, y) {\r\n if (x < 0 || x >= row) return false;\r\n if (y < 0 || y >= col) return false;\r\n if (grid[x][y].state == 'block') return false;\r\n\r\n return true;\r\n}",
"function outOfGameWindow(x,y){\n return (x > gameWindow.x + gameWindow.width || x < gameWindow.x) || (y > gameWindow.y + gameWindow.height || y < gameWindow.y);\n}",
"function isNeighbors(tile1, tile2) {\r\n\t\tvar left1 = parseInt(window.getComputedStyle(tile1).left);\r\n\t\tvar top1 = parseInt(window.getComputedStyle(tile1).top);\r\n\t\tvar left2 = parseInt(window.getComputedStyle(tile2).left);\r\n\t\tvar top2 = parseInt(window.getComputedStyle(tile2).top);\r\n\t\tif (Math.abs(left1 + top1 - left2 - top2) == 100) {\r\n\t\t\treturn true;\r\n\t\t} else {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}",
"function checkGeometry(includeDrawNode) {\n var nopeDisabled = context.surface().classed('nope-disabled');\n var isInvalid = isInvalidGeometry(includeDrawNode);\n\n if (nopeDisabled) {\n context.surface()\n .classed('nope', false)\n .classed('nope-suppressed', isInvalid);\n } else {\n context.surface()\n .classed('nope', isInvalid)\n .classed('nope-suppressed', false);\n }\n }",
"getExistingAdjacentPosns(posn) {\n\t\tvar theWorld = this;\n\t\treturn posn.getAdjacentPosnsWithWraparound(theWorld).filter(function(p) {\n\t\t\treturn !!theWorld.get(p);\n\t\t})\n\t}",
"function validTile(x, y) {\n if (x > (xmax - 1) || (x < 0)) {\n return false;\n }\n\n if (y > (ymax - 1) || (y < 0)) {\n return false;\n }\n return true;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
send a single emoji message | function sendEmoji(message, emojiName) {
var emoji = message.guild.emojis.find(emoji => emoji.name === emojiName);
message.channel.send('<:'+emoji.name+':'+emoji.id+'>')
.catch(console.warn);
} | [
"function sendmessage(type, message)\n\t{\n\t\tvar channel = 0;\n\t\tvar nums = [0,1,2,3,4,5,6,7,8,9];\n\t\tvar indexpos = 0;\n\t\tif(message.substr(0,1) == \"/\")\n\t\t{\n\t\t\tif(message.substr(1,1) == \"/\")\n\t\t\t{\n\t\t\t\tchannel = last_channel;\n\t\t\t\tmessage = message.substr(2);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfor(var i = 1; i < message.length; ++i)\n\t\t\t\t{\n\t\t\t\t\tif(nums.indexOf(message.substr(i,1)) > -1)\n\t\t\t\t\t{\n\t\t\t\t\t\tindexpos = i;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(indexpos > 0)\n\t\t\t\t{\n\t\t\t\t\tchannel = message.substr(1,indexpos);\n\t\t\t\t\tlast_channel = channel;\n\t\t\t\t\tmessage = message.substr(indexpos+1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tAjaxLife.Network.Send(\"SpatialChat\", {\n\t\t\tMessage: message,\n\t\t\tChannel: channel,\n\t\t\tType: type\n\t\t});\n\t}",
"onSendButtonClick() {\n const userInputValue = this.userInput.value;\n if (userInputValue != \"\" && userInputValue.replace(/\\s/g, \"\").length > 0) {\n window.character.send(userInputValue);\n }\n }",
"function sendMessage (target, context, message) {\r\n if (context['message-type'] === 'whisper') {\r\n client.whisper(target, message)\r\n } else {\r\n client.say(target, message)\r\n }\r\n}",
"function sendToChannel(msg) {\n bot.channels.get(curryBotChannel).send(msg);\n}",
"function chooseEmoji(e) {\n if(e.target.matches(\".emoji\")) {\n textarea.value += e.target.innerHTML\n }\n}",
"function send() {\n // Create a new message object\n var message = {\n text: vm.body\n };\n\n var Message = MessageService.message();\n var item = new Message({\n body: vm.body,\n channelId: vm.channel\n });\n\n item.$save(function (response) {\n // Emit a 'chatMessage' message event\n Socket.emit('message', {channel: vm.channel, item: item});\n // Clear the message text\n vm.body = '';\n }, function (errorResponse) {\n console.log(errorResponse);\n vm.error = errorResponse.data.message;\n });\n }",
"function sendMessageToServer(message) {\n socket.send(message);\n }",
"function chuckJoke() {\n axios.get('https://api.icndb.com/jokes/random').then(res => {\n const joke = res.data.value.joke;\n\n const params = {\n icon_emoji: ':joy_cat:'\n };\n\n bot.postMessageToChannel('random', `Chuck Norris: ${joke}`, params);\n });\n}",
"function send_message_player_added(uuid){\r\n let data = {\r\n \"cmd\" : \"player_added\"\r\n }\r\n send_message(uuid, data);\r\n}",
"function emojiClickEventHandler(emoji){\n\twriteToClipboard(emoji.char);\n\taddToFavorite(emoji);\n}",
"function sendChatMessege()\n{\n var chat = cleanInput($(\"#chat-box\").val().substring(0, 100));\n\n if($.isBlank(chat))\n return;\n\n socket.emit('chat', chat);\n setPlayerMessege(player, chat);\n $(\"#chat-box\").val(\"\");\n}",
"sendMessage(text) {\n\t\tthis.setTextToInput(text);\n\t\tthis.sendBtn.click();\n\t\tbrowser.waitUntil(function() {\n\t\t\tbrowser.waitForVisible('.message:last-child .body', 5000);\n\t\t\treturn browser.getText('.message:last-child .body') === text;\n\t\t}, 5000);\n\t}",
"function sendChooseQuestionsMSG() {\n let message = {\n messageType: \"CHOOSE QUESTION\",\n };\n\n theSocket.sendJSON(message);\n}",
"function poids()\n{\n message.channel.send({ embed: {\n color:0x00AE86,\n title:'Création du personnage',\n description: 'Quel est votre poids (en kg)?',\n } });\n}",
"function sendEndGameMSG() {\n let message = {\n messageType: \"END GAME\",\n };\n\n theSocket.sendJSON(message);\n}",
"function sendQuestionClosedMSG() {\n let message = {\n messageType: \"QUESTION CLOSED\",\n };\n\n theSocket.sendJSON(message);\n}",
"function sendMessage(message) {\n port.postMessage(message);\n}",
"_send(type, data) {\n this._midiOutput.send(type, _.extend(data, { channel: this._midiChannel } )); \n }",
"function dadJoke() {\n const config = {\n headers: { Accept: 'application/json' }\n };\n\n axios.get('https://icanhazdadjoke.com/', config).then(res => {\n console.log(res.data);\n const joke = res.data.joke;\n\n const params = {\n icon_emoji: ':joy_cat:'\n };\n\n bot.postMessageToChannel('random', `Dad: ${joke}`, params);\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FUNCTION NAME : deleteSpecificLink AUTHOR : Juvindle C Tina DATE : March 26, 2014 MODIFIED BY : REVISION DATE : REVISION : DESCRIPTION : delete specific link PARAMETERS : | function deleteSpecificLink(){
var linkArray = new Array();
$('.linkiddelete').each(function(){
if($(this).is(':checked')){
linkArray.push($(this).attr('did'));
}
});
if(linkArray.length == 0){
alerts("Please select one entry.");
return;
}
for(var t=0; t<linkArray.length; t++){
var pathArr = linkArray[t].split("::");
var port= getPortObject2(pathArr[0]);
var port2= getPortObject2(pathArr[1]);
port.PORTMAP = [];
port2.PORTMAP = [];
}
drawImage();
$('#deleteLinkPopUp').empty();
closeDialog("deleteLinkPopUp");
} | [
"function deleteLink(source,destination){\n\tif(globalInfoType == \"JSON\"){\n\t\tvar devices = getDevicesNodeJSON();\n var prtArr =[];\n for(var s=0;s < devices.length; s++){\n prtArr = getDeviceChildPort(devices[s],prtArr);\n }\n }else{\n var prtArr= portArr;\n }\n\tfor(var i = 0; i < window['variable' + dynamicLineConnected[pageCanvas]].length; i++){\n\t\tif(window['variable' + dynamicLineConnected[pageCanvas]][i].Destination == destination && window['variable' + dynamicLineConnected[pageCanvas]][i].Source == source){\n\t\t\tif(window['variable' + dynamicLineConnected[pageCanvas]][i].DestinationDeviceName != \"\" || window['variable' + dynamicLineConnected[pageCanvas]][i].SourceDeviceName != \"\"){\n\t\t\t\tfor(var a=0; a < prtArr.length; a++){\n\t\t\t\t\tif(prtArr[a].ObjectPath == destination || prtArr[a].ObjectPath == source){\n\t\t\t\t\t\tif(prtArr[a].Status == \"Reserved\"){\n\t\t\t\t\t\t\taddEvent2History(\"Device Link Deleted\");\n\t\t\t\t\t\t\tprtArr[a].UpdateFlag = \"delete\";\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\taddEvent2History(\"Device Link Deleted\");\n\t\t\t\t\t\t\tprtArr.splice(a,1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\twindow['variable' + dynamicLineConnected[pageCanvas]].splice(i,1);\n\t\t\t}else{\n\t\t\t\twindow['variable' + dynamicLineConnected[pageCanvas]].splice(i,1);\n\t\t\t}\n\t\t}\n\t}\n\tdrawImage();\n}",
"function deleteLinkByKind(linkKind) {\n return spPost(SPInstance(this, \"deleteLinkByKind\"), request_builders_body({ linkKind }));\n}",
"function deleteSelectedLink(level,id){\n\tswitch(level){\n\t\tcase \"cancel\":\n\t\t\tswitch(id){\n\t\t\t\tcase \"openConsoleSelect\":\n\t\t\t\t\tvalidDevices = [];\n\t\t\t\t\tvalidSessionDevices = [];\n\t\t\t\tbreak;\n\t\t\t\tcase \"invitePeoplePopUp\":\n\t\t\t\t\tuserExistArray = [];\n\t\t\t\t\tuserNotExistArray = [];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t$('#'+id).empty();\n\t\t\tcloseDialog(id);\n\t\tbreak;\n\t\tdefault:\n\t\t\tswitch(id){\n\t\t\t\tcase \"deleteLinkPopUp\":\n\t\t\t\t\tdeleteSpecificLink();\n\t\t\t\tbreak;\n\t\t\t\tcase \"openConsoleSelect\":\n\t\t\t\t\tselectDataforOpenConsole(id);\n\t\t\t\tbreak;\n\t\t\t\tcase \"invitePeoplePopUp\":\n\t\t\t\t\tsavedatainsession(id);\n\t\t\t\tbreak;\n\t\t\t}\n\t\tbreak;\n\t}\n}",
"function deleteLinkFromDev(dev){\n\tif(globalInfoType == \"JSON\"){\n var devices = getDevicesNodeJSON();\n }else{\n var devices =devicesArr;\n }\n\tvar allline =[];\n\tfor(var i = 0; i < devices.length; i++){ // checks if the hitted object is equal to the array\n\t\tallline = gettargetmap(devices[i].ObjectPath,allline);\n\t}\n\tfor(var t=0; t<allline.length; t++){\n\t\tvar source = allline[t].Source;\n\t\tvar destination = allline[t].Destination;\n\t\tvar srcArr = source.split(\".\");\n\t\tvar dstArr = destination.split(\".\");\n\t\tif(srcArr[0] == dev){\n\t\t\tvar portobject = getPortObject2(destination);\n\t\t\taddEvent2History(\"Device Link Deleted\");\n\t\t\tportobject.PORTMAP = [];\n\t\t}\n\t\tif(dstArr[0] == dev){\n\t\t\tvar portobject = getPortObject2(source);\n\t\t\taddEvent2History(\"Device Link Deleted\");\n\t\t\tportobject.PORTMAP = [];\n\t\t}\n\t}\n\tdrawImage();\n}",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('shortlink_shortlink', 'delete', kparams);\n\t}",
"function removeLink(b1: int, b2: int)\n{\n\tlinksDrawn[b1,b2] = linksDrawn[b2, b1] = false;\n\tDestroy(GameObject.Find(b2 + \" \" + b1));\n\t\n\t// if the buildings were mutually linked, move the remaining link back to normal position\n\tif (CheckForMutualLink(b2, b1))\n\t{\n\t\tvar inputLink : GameObject = GameObject.Find(b1 + \" \" + b2);\n\t\tif (inputLink)\n\t\t\tinputLink.transform.localPosition = Vector3(0,10,0);\n\t}\t\n}",
"removeLink(startPortal, endPortal) {\n var newLinks = [];\n for (let link_ in this.links) {\n if (!(this.links[link_].fromPortalId == startPortal && this.links[link_].toPortalId == endPortal)) {\n newLinks.push(this.links[link_])\n }\n }\n this.links = newLinks;\n this.cleanAnchorList()\n this.cleanPortalList()\n this.update()\n }",
"function AM_policy_delete(amServer, inputAccountIntentId){\n\n var result = {};\n var ssoToken = amServer.ssoToken;\n\n restCall = {};\n restCall.url = constructAmUri(amServer) + \"/json/realms/\" + amServer.policyRealm + \"/policies/\" + inputAccountIntentId;\n\n\tconsole.log(\"[DEBUG]: url to delete - \" + restCall.url);\n\n restCall.headers = { \"contentType\" : \"application/json\",\n \"Accept-API-Version\" : \"protocol=1.0\",\n \"iPlanetDirectoryPro\" : ssoToken};\n restCall.method = \"DELETE\";\n\n executeRest(restCall);\n\n return;\n\n}",
"function CompleteRemoveLink() {\n var jLinkDialog = g(\"linkDialog\");\n jLinkDialog.style.display = \"none\";\n restoreSelection(jLinkDialog.savedSelection);\n if (isInNode(window.getSelection().anchorNode, \"popuptext\")) {\n document.execCommand(\"Unlink\");\n }\n}",
"function cleanupLinks(callback) {\n var linkcount = 0, cbcount = 0;\n var links = db.get(\"shortlinks\");\n if (Object.keys(links).length === 0)\n callback();\n else {\n Object.keys(links).forEach(function (link) {\n linkcount++;\n (function (shortlink, location) {\n fs.stat(path.join(paths.files, location), function (error, stats) {\n cbcount++;\n if (!stats || error) {\n delete links[shortlink];\n }\n if (cbcount === linkcount) {\n db.set(\"shortlinks\", links, function () {\n callback();\n });\n }\n });\n })(link, links[link]);\n });\n }\n}",
"function deleteDevSub(imgId){\n\tif(globalInfoType == \"JSON\"){\n \t\tvar devices = getDevicesNodeJSON();\n\t\tfor(var a=0; a<devices.length;a++){\n\t\t\tif(devices[a].Status == \"Reserved\" && devices[a].ObjectPath == imgId){\n\t\t\t\tdevices[a].UpdateFlag = \"delete\";\n\t\t\t\tdeleteLinkFromDev(devices[a].ObjectPath);\n\t\t\t\tdevices.splice(a,1);\n\t\t\t\taddEvent2History(\"Device deleted\");\n\t\t\t\ta = devices.length;\n\t\t\t}else if(devices[a].ObjectPath == imgId && devices[a].Status != \"Reserved\"){\n\t\t\t\tdeleteLinkFromDev(devices[a].ObjectPath);\n\t\t\t\tdevices.splice(a,1);\n\t\t\t\taddEvent2History(\"Device deleted\");\n\t\t\t\ta = devices.length;\n\t\t\t}\n\t\t}\n \t}\n\tdrawImage();\n}",
"function updateLink(value) {\n var item = new Array;\n\n //! Update Link\n item.modified = new Date();\n item.id = 1\n item.link = value;\n Storage.updateLink(item);\n strLink = value;\n}",
"function clear_link(mhc){ \n\t\tvar unlinked = 0;\n\t\tvar aNav = $(mhc);\n\t\tvar a = aNav.getElementsByTagName('a');\n\t\tvar mysplit = window.location.href.split('#')[0];\n\t\tfor(var i=1;i<a.length;i++)\n\t\t\tif(a[i].href == mysplit){\n\t\t\t\tremoveNode(a[i]);\n\n \t\t\tvar unlinked = 1;\n\t\t\t\t}\t\t\t\t\n\t\t\tif (unlinked == 0){\n\t\t\t\tvar newHit = a[0];\n\t\t\t\tnewHit.parentNode.setProperty ('id','active_nav'); \n\t\t\t}\n\t}",
"function getDatabaseParameterDeleteCategory (params, query, body){\r\n\tvar parameters = {\r\n\t\twhere: { category_id: params.id },\r\n\t};\r\n\treturn parameters;\r\n}",
"function removeBookmark(url, title) {\n //console.debug(\"Called removeBookmark with arguments \" + url + \" \" + title)\n var db = getDatabase();\n var respath=\"\";\n if (url != undefined && url != \"\" && (title == undefined || title == \"\")) {\n db.transaction(function(tx) {\n var rs = tx.executeSql('DELETE FROM bookmarks WHERE url=(?);', [url]);\n // if (rs.rowsAffected > 0) {\n // console.debug(\"Url found and removed\");\n // } else {\n // console.debug(\"Url not found\");\n // }\n })\n }\n else if (title != undefined && title != \"\") {\n //console.debug(\"Remove oldtitle \" + title)\n db.transaction(function(tx) {\n var rs = tx.executeSql('DELETE FROM bookmarks WHERE title=(?);', [title]);\n // if (rs.rowsAffected > 0) {\n // console.debug(\"Url found and removed\");\n // } else {\n // console.debug(\"Url not found\");\n // }\n })\n }\n else {\n db.transaction(function(tx) {\n var rs = tx.executeSql('DELETE FROM bookmarks WHERE url=(?) AND title=(?);', [url,title]);\n // if (rs.rowsAffected > 0) {\n // console.debug(\"Url found and removed\");\n // } else {\n // console.debug(\"Url not found\");\n // }\n })\n }\n}",
"function para_del(name) {\n\tif (confirm(\"Do you want to delete this parameter?\")) {\n\t\tpara.remove(\"task='\" + document.getElementById('task').value + \"' and name='\" + name + \"'\");\n\t\tpara_fetch();\n\t\t$('#' + name.replace(/[^a-zA-Z 0-9]+/g, '').replace(/\\s+/g, \"\")).remove();\n\t\ttot();\n\t}\n}",
"function onclick_remove(e, video_id) {\n flixstack_api.remove_from_stack(video_id, function(data, textStatus) {\n update_link(video_id, false);\n }); \n\n e.preventDefault();\n e.stopPropagation();\n return false;\n}",
"static async remove(id, item_type, link, ownershipCheck) {\n // Compose the query to find the comment.\n const query = {\n id,\n 'tags.tag.name': {\n $eq: link.tag.name,\n },\n };\n\n // If ownership verification is required, ensure that the person that is\n // assigning the tag is the same person that owns the comment.\n if (ownershipCheck) {\n // Modify the query to support an ownership verification.\n ownershipQuery(item_type, link, query);\n }\n\n // Get the Model to perform the update.\n return updateModel(item_type, query, {\n $pull: {\n tags: {\n 'tag.name': link.tag.name,\n },\n },\n });\n }",
"faceListDeleteAFaceFromAFaceListDelete(queryParams, headerParams, pathParams) {\n const queryParamsMapped = {};\n const headerParamsMapped = {};\n const pathParamsMapped = {};\n Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, FaceListDeleteAFaceFromAFaceListDeleteQueryParametersNameMap));\n Object.assign(headerParamsMapped, convertParamsToRealParams(headerParams, FaceListDeleteAFaceFromAFaceListDeleteHeaderParametersNameMap));\n Object.assign(pathParamsMapped, convertParamsToRealParams(pathParams, FaceListDeleteAFaceFromAFaceListDeletePathParametersNameMap));\n return this.makeRequest('/facelists/{faceListId}/persistedFaces/{persistedFaceId}', 'delete', queryParamsMapped, headerParamsMapped, pathParamsMapped);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a simple 'function' that is also a RxJS AsyncSubject. | function async(mapFunction) {
return factory(Rx.AsyncSubject, mapFunction);
} | [
"async function asyncFunc() {\n return 123;\n}",
"extendRxObservables() {\n return require('nylas-observables');\n }",
"function Subject() {\n // create an Observers list instance, passing all methods on\n this.observers = new ObserverList()\n}",
"static of (a) {\n return new Signal(emit => {\n emit.next(a)\n emit.complete()\n })\n }",
"async(fn) {\n return (req, res, next) => {\n fn(req, res, next).then(data => {\n // On success, save the result of the Promise in req.data.\n req.data = data\n next()\n }).catch(error => {\n // On error, pass error to the next error middleware.\n next(error)\n })\n }\n }",
"startWith (a) {\n return new Signal(emit => {\n emit.next(a)\n return this.subscribe(emit)\n })\n }",
"subscribe(subject) {\n const attached = subject.attach(this);\n if (attached)\n this.subject = subject;\n\n return attached;\n }",
"function create(fetchFn, subscribe) {\n // Convert to functions that returns RelayObservable.\n var observeFetch = convertFetch(fetchFn);\n\n function execute(request, variables, cacheConfig, uploadables, logRequestInfo) {\n if (request.operationKind === 'subscription') {\n !subscribe ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayNetwork: This network layer does not support Subscriptions. ' + 'To use Subscriptions, provide a custom network layer.') : invariant(false) : void 0;\n !!uploadables ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayNetwork: Cannot provide uploadables while subscribing.') : invariant(false) : void 0;\n return subscribe(request, variables, cacheConfig);\n }\n\n var pollInterval = cacheConfig.poll;\n\n if (pollInterval != null) {\n !!uploadables ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'RelayNetwork: Cannot provide uploadables while polling.') : invariant(false) : void 0;\n return observeFetch(request, variables, {\n force: true\n }).poll(pollInterval);\n }\n\n return observeFetch(request, variables, cacheConfig, uploadables, logRequestInfo);\n }\n\n return {\n execute: execute\n };\n}",
"function factory () {\n // Just forwards the call to the resolver by setting itself as context.\n function fn (value) {\n return resolver.call(fn, value);\n }\n\n created += 1;\n fn.id = created;\n\n // The state is attached to the function object so it's available to the\n // state-less functions when running under `this.`.\n fn.locks = 0;\n fn.chain = null;\n fn.resolved = [];\n fn.filters = [];\n fn.forks = [];\n\n // Expose the behaviour in the functor\n fn.pause = pause;\n fn.resume = resume;\n fn.filter = filter;\n fn.fork = fork;\n fn.merge = merge;\n fn.completed = completed;\n\n return fn;\n}",
"function fun(body) {\n return \"async function foo() { \" + body + \" }\";\n}",
"function Subject() {\n this.observers = new ObserverList();\n}",
"static fromCallback (f) {\n return new Signal(emit => {\n f((e, a) => {\n if (typeof e !== 'undefined' && e !== null) {\n emit.error(e)\n } else {\n emit.next(a)\n }\n })\n })\n }",
"function replay(bufferSize, mapFunction) {\n return factory(Rx.ReplaySubject, mapFunction, bufferSize);\n}",
"subscribe (emit, ...args) {\n if (typeof emit === 'function') {\n emit = {next: emit, error: args[0], complete: args[1]}\n } else if (typeof emit !== 'object') {\n emit = {}\n }\n\n const next = value => {\n for (let s of this._subscriptions) {\n if (typeof s.emit.next === 'function') {\n s.emit.next(value)\n }\n }\n }\n\n const error = value => {\n for (let s of this._subscriptions) {\n if (typeof s.emit.error === 'function') {\n s.emit.error(value)\n }\n }\n }\n\n const complete = () => {\n for (let s of this._subscriptions) {\n if (typeof s.emit.complete === 'function') {\n s.emit.complete()\n }\n }\n }\n\n // Create a new subscription to the signal.\n const subscription = new Subscription(emit, () => {\n // Remove the subscription.\n this._subscriptions.delete(subscription)\n\n // Call the unmount function if we're removing the last subscription.\n if (this._subscriptions.size === 0) {\n this.unmount()\n }\n })\n\n // Add the subscription.\n this._subscriptions.add(subscription)\n\n // Call the mount function if we added the first subscription.\n if (this._subscriptions.size === 1) {\n this.mount({next, error, complete})\n }\n\n return subscription\n }",
"static sequential (n, as) {\n let id\n\n return new Signal(emit => {\n id = setInterval(() => {\n emit.next(head(as))\n\n as = tail(as)\n\n if (empty(as)) {\n clearInterval(id)\n emit.complete()\n }\n }, n)\n\n return () => clearInterval(id)\n })\n }",
"function moments_request() {\n return async function (observers, ...args) {\n if (!isArray(observers) || observers.length < 1) {\n return undefined;\n }\n const handler = observers[0];\n return Reflect.apply(handler, this, args);\n };\n}",
"constructor(filterFunc) {\n this._observers = [];\n this._otherCallbacks = [];\n this._filterFunc = filterFunc;\n this._nextId = 111;\n }",
"function Subject() {\n this._observerList = [];\n}",
"async function makeCoffee(){...}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
apply_selector Apply the selected filters to the page's elements. The function uses get_selector to get the filters. The filters are applied based on availability filter value. If availability is set means that we must check what is the availability of each domain at the end of our query. To avoid confusion when the results arrive we create the requests with the elements in question hidden. A loader is appended after the domains to indicate that there is an active search. Results that match both the selector and availability rule are shown before answers to our requests arrive. If there is no request created and there is no element matched an error message will appear. If availability is not set then function the selector is used and the matched elements are revealed and requested. If there are no results an error message will appear. Based on the visible results and total results the show more button will be visible or hidden. | function apply_selector(){
$('.list').show();
handleErrorBox('hide');
var selector = get_selector();
$('.availabilityLoader').remove();
if($('.colored_tld').length){
single = $('.singleResult');
single.find('.tld').html(single.attr('data-tld'));
$('.tldResults:has(.colored_tld)').each(function(){
tld = $(this).attr('data-tld');
$(this).find('.tld').html(tld);
});
}
if(fundamental_vars.appliedCriteria.availability != ''){
var matching_selector = '.list ' + createAvailabilitySelector(selector),
target = null;
matching_results = $(matching_selector); //Find all the results that at this moment match the query to question.
fundamental_vars.expected_results = matching_results.length + fundamental_vars.defaultLimit;
if(matching_results.length < fundamental_vars.defaultLimit) { //If the matching results are too few fetch more.
$('.list .tld-line').hide(); //hide all active results
target = $('.list .tldResults' + selector + ' .tld-line:not(.asked):lt(' + fundamental_vars.defaultLimit + ')');
/*
* Find the results that match the filters and availability and show them before the search begins.
* If there are tlds available for search perform a request and show the availability loader.
* If there is nothing to search and no visible result hide list show border is not visible on mobile and display the error message.
*/
if (fundamental_vars.appliedCriteria.availability == 'available') {
selector = '.list .tldResults' + selector + '[data-status="1"] .tld-line.asked, .tldResults' + selector + '[data-status="2"] .tld-line.asked, .tldResults' + selector + '[data-status="3"] .tld-line.asked';
} else {
selector = '.list .tldResults' + selector + '[data-status!="1"][data-status!="2"][data-status!="3"][data-status!=""][data-status] .tld-line.asked';
}
var already_fetched = $(selector);
already_fetched.show();
colorRows();
if (target.length) { //Tlds available for search.
if(jQuery.active < 2){
createRequests(target);
}
if ($('.availabilityLoader').length < 1) {
$('#show_more').hide();
$('.show-more-btn').before(fundamental_vars.availTemp);
if ($('.list .tld-line:visible').length < 1) {
$('.list').hide();
}
}
} else {
if (jQuery.active < 2 && already_fetched.length < 1 && $('.availabilityLoader').length < 1){ //No tlds available for search. Show what is searched.
handleErrorBox('show', DOMAINS_LANG.DOMAIN_SEARCH.ALERTS.NO_RESULTS)
}
}
return false;
}else{
total_matching = '.list ' + selector;
selector = matching_selector; //If the results suffice show them.
}
}else{
if(selector != ''){
selector = '.list .tldResults' + selector;
total_matching = selector;
selector = selector + ' .tld-line:hidden:lt(' + fundamental_vars.defaultLimit + '), ' + selector + ' .asked'; //If filters are applied select the first in default limit
}else{
selector = '.list .tld-line.asked'; //If no filter is applied show all the asked.
total_matching = '.list .tld-line';
}
}
$('.list .tld-line').hide(); //hide all active results
fetched = $(selector); //Fetched by selector
fetched.show();
colorRows();
createRequests();
total_matching_length = $(total_matching).length;
total_visible_length = $('.tld-line:visible').length;
if(total_matching_length == total_visible_length){
$('#show_more').hide();
}else{
$('#show_more').trigger('show');
}
if(fundamental_vars.appliedCriteria.availability == '' && total_visible_length < 1){
handleErrorBox('show', DOMAINS_LANG.DOMAIN_SEARCH.ALERTS.NO_RESULTS, false);
}
return false;
} | [
"function createAvailabilitySelector(selector){\n if(selector.indexOf('.tldResults') < 0){\n selector = '.tldResults' + selector;\n }\n\n if(fundamental_vars.appliedCriteria.availability == 'available'){\n selector = selector + '[data-status=\"1\"] .tld-line.asked,' + selector + '[data-status=\"2\"] .tld-line.asked,' + selector + '[data-status=\"3\"] .tld-line.asked';\n }else{\n selector = selector + '[data-status!=\"1\"][data-status!=\"2\"][data-status!=\"3\"][data-status!=\"\"][data-status] .tld-line.asked';\n }\n\n return selector\n}",
"function filterByjQuerySelector(filter_id, selector_callback) {\n let filter_name = filter_id.replace(/^#filter_/, '');\n ContentFrame.findElementInContentFrame(filter_id, '#webview-tooltip').click(function (e) {\n if (filter_id === \"#filter_class\" && (referenceElement.className === '' || referenceElement.className === undefined)) {\n alert(\"This element has no Class attribute!\");\n ContentFrame.findElementInContentFrame('#filter_class', '#webview-tooltip').attr(\"disabled\",\"true\");\n return;\n }\n if (filter_id === \"#filter_id\" && (referenceElement.id === '' || referenceElement.id === undefined)) {\n alert(\"This element has no Id attribute!\");\n ContentFrame.findElementInContentFrame('#filter_id', '#webview-tooltip').attr(\"disabled\",\"true\");\n return;\n }\n\n let cur = e.target;\n if (cur.value === \"0\") { //Add model to collection\n cur.value = \"1\";\n currentFilters.add(filter_name);\n cur_query.jQuerySelector[filter_name] = selector_callback;\n helper(referenceElement, cur_query, 0);\n }\n\n else { //Take model off collection\n cur.value = \"0\";\n currentFilters.delete(filter_name);\n delete cur_query.jQuerySelector[filter_name];\n helper(referenceElement, cur_query, 1);\n }\n });\n }",
"function initFiltering(groupSelector, elementSelector, attributeExtractor) {\n const filterFunction = (query) => {\n return filterByQuery(query, groupSelector, elementSelector, attributeExtractor);\n };\n\n // remove spurious \"\\\"\n if (document.location.hash.indexOf(\"\\\\\") > 0) {\n document.location.hash = document.location.hash.replace(/\\\\/g, \"\");\n }\n\n // Set up filter field\n const filterField = document.getElementById(\"filter-field\");\n if (document.location.hash.startsWith(\"#?q=\")) {\n const query = decodeURIComponent(document.location.hash.substr(4));\n filterField.value = query;\n }\n filterField.addEventListener(\"input\", event => filterFunction(event.target.value));\n filterFunction(filterField.value);\n if (document.location.hash.startsWith(\"#?q=\") || document.location.hash === \"\") {\n filterField.focus();\n }\n\n // Update if hash in URL changed (e.g., browser back button)\n window.addEventListener(\"hashchange\", event => {\n if (document.location.hash.startsWith(\"#?q=\")) {\n const query = decodeURIComponent(document.location.hash.substr(4));\n if (query !== filterField.value) {\n filterField.value = query;\n filterFunction(query);\n }\n }\n });\n}",
"function cs_page_composer_filterable(id) {\n\n var $container = jQuery(\"#page_element_container\" + id),\n elclass = \"cs-filter-item\";\n $container.find('.element-item').addClass(\"cs-filter-item\");\n jQuery(document).on('click', '#filters' + id + ' li', function (event) {\n var $selector = jQuery(this).attr('data-filter'),\n $elem = $container.find(\".\" + $selector + \"\");\n jQuery(\"#filters\" + id + \" li\").removeClass(\"active\");\n jQuery(this).addClass(\"active\");\n $container.find('.element-item').removeClass(elclass);\n if ($selector == \"all\") {\n $container.find('.element-item').addClass(elclass);\n } else {\n jQuery($elem).addClass(elclass);\n }\n event.preventDefault();\n });\n // Search By input\n jQuery(\"#quicksearch\" + id).keyup(function () {\n var _val = jQuery(this).val(),\n $this = jQuery(this);\n $container.find('.element-item').addClass(\"cs-filter-item\");\n jQuery(\"#filters\" + id + \" li\").removeClass(\"active\");\n var filter = jQuery(this).val(),\n count = 0;\n jQuery(\"#page_element_container\" + id + \" .element-item span\").each(function () {\n if (jQuery(this).text().search(new RegExp(filter, \"i\")) < 0) {\n jQuery(this).parents(\".element-item\").removeClass(elclass);\n } else {\n jQuery(this).parents(\".element-item\").addClass(elclass);\n count++;\n }\n });\n })\n}",
"function startingConditions(){\n $('dl,dd').removeClass('inactive');\n $('.domains-more-results').removeClass('hide');\n $('.domain-results').addClass('hide');\n $('.list, div.filters').show();\n $('.filters-on-use').text(DOMAINS_LANG['DOMAIN_SEARCH']['HEAD_TEXT']['ALL']);\n $('dd').removeClass('selected');\n $('.searchInResults').val('');\n\n $('.resultsPanel').html(fundamental_vars.startingState);\n $('.domain-results').html(fundamental_vars.startingStateSingle);\n\n if(!($('.domains-more-results').is(':visible'))) {\n $('.domains-more-results').show();\n }\n\n\n temp = [];\n fundamental_vars.filtersOn = false;\n fundamental_vars.retry = true;\n universalKeyword = null;\n}",
"function find_unresolved_domains_from_filters () {\n var keyword = fundamental_vars.search_in_results_unresolved[0];\n fundamental_vars.search_in_results_unresolved.splice(0,1);\n\n var target = $('[data-fqdn^=\"' + keyword + '\"] .tld-line:has(.spinner):visible');\n\n if(target.length) {\n createRequests(target);\n }\n}",
"getRules(selector, selectorNum) {\n\n // Generate the options for the category dropdown\n var categoryOptions = [\"All\", \"Chicken\",\"Beef\",\"Salad\",\"Soup\",\"Stew\",\"Pasta\",\"Egg\",\"Pork\",\"Fish\",\"Sandwich\",\"Seafood\",\"Baked\",\"Fried\",\"Bread\",\"Pizza\"].map(category => {\n return(<option value={category}/>)\n })\n categoryOptions.push(<option value=\"\" hidden/>)\n\n var i = -1\n // Generate each rule element\n var rules = selector.rules.map((rule) => {\n i++\n\n // Get the rule parameters\n var parameters = rule.parameters\n\n if ((selector.parameters.includes(\"all\") || selector.parameters.length > 1) && parameters) { // If there are multiple selector parameters, add the for (each/all) parameter\n var forSelector = (\n <div class=\"forSelector\">\n <div style={{display: \"inline\"}}>for </div>\n <select value={parameters.for} class=\"forSelectorSelect\" id={i} onChange={(e) => this.changeRuleParameter(e, selectorNum, \"for\")}>\n <option value=\"\" selected disabled hidden></option>\n <option value=\"each\">each</option>\n <option value=\"all\">all</option>\n </select>\n </div>\n )\n } else { // If there is just one selector parameter, don't show the for (each/all) option\n var forSelector = (\n <div style={{display: \"none\"}}></div>\n )\n }\n \n var ruleName;\n if (rule.new) { // If it is a new rule make the rulename a selector\n ruleName = (\n <select class=\"selectSelector\" value={rule.rule} id={i} onChange={(e) => this.changeRuleType(e, selectorNum)}>\n <option value=\"\" selected disabled hidden></option>\n <option value=\"Total\">Total</option>\n <option value=\"Repeats\">Repeats</option>\n <option value=\"Filter\">Filter</option>\n </select>\n )\n } else { // Otherwise just make it the name of the rule type\n ruleName = rule.rule\n }\n\n var actionButton;\n if (rule.new) { // If the rule is new make the rightmost button an add rule button\n actionButton = (\n <span class=\"plusiconrule\" id={i} onClick={(e) => this.addRule(e, selectorNum)}>+</span>\n )\n } else { // Otherwise make it a remove rule button\n actionButton = ( \n <span class=\"xicon\" id={i} onClick={(e) => this.removeSelectorRule(e, selectorNum)}>✕</span>\n )\n }\n\n if (rule.rule == \"Total\") { // If the rule is a \"total\" command\n var category = capitalize(parameters.category)\n return (\n <table class=\"rule\">\n <tr>\n <th class=\"ruleName\" style={{\"background-color\":\"red\"}}>\n {ruleName}\n </th>\n <th class=\"ruleParameters\">\n <select selected={parameters.condition} value={parameters.condition} class=\"ruleCondition\" id={i} onChange={(e) => this.changeRuleParameter(e, selectorNum, \"condition\")}>\n <option value=\"\" selected disabled hidden></option>\n <option value=\"at most\">At most</option>\n <option value=\"exactly\">Exactly</option>\n <option value=\"at least\">At least</option>\n </select>\n <input type=\"number\" min=\"0\" value={parameters.amount} id={i} onChange={(e) => this.changeRuleParameter(e, selectorNum, \"amount\")}></input>\n <input type=\"text\" list=\"categoryOptions\" class=\"catgeoryInput\" value={category} id={i} onChange={(e) => this.changeRuleParameter(e, selectorNum, \"category\")}/>\n <datalist id=\"categoryOptions\" >\n {categoryOptions}\n </datalist>\n <div class=\"mealsText\">meals</div>\n {forSelector}\n {actionButton}\n </th>\n </tr>\n </table>\n )\n } else if (rule.rule == \"Filter\") { // If the rule is a \"filter\" command\n return (\n <table class=\"rule\">\n <tr>\n <th class=\"ruleName\" style={{\"background-color\":\"green\"}}>\n {ruleName}\n </th>\n <th class=\"ruleParameters\">\n <select value={parameters.type} class=\"ruleCondition\" id={i} onChange={(e) => this.changeRuleParameter(e, selectorNum, \"type\")}>\n <option value=\"\" selected disabled hidden></option>\n <option value=\"exclude\">Exclude</option>\n <option value=\"apply\">Apply</option>\n </select>\n <input type=\"text\" class=\"filterInput\" value={parameters.filter} id={i} onChange={(e) => this.changeRuleParameter(e, selectorNum, \"filter\")}/>\n {actionButton}\n </th>\n </tr>\n </table>\n )\n } else if (rule.rule == \"Repeats\") { // If the rule is a \"repeats\" command\n var category = capitalize(parameters.category)\n return (\n <table class=\"rule\">\n <tr>\n <th class=\"ruleName\" style={{\"background-color\":\"blue\"}}>\n {ruleName}\n </th>\n <th class=\"ruleParameters\">\n <div class=\"filterRuleText\">At most</div>\n <input type=\"number\" min=\"0\" value={parameters.amount} id={i} onChange={(e) => this.changeRuleParameter(e, selectorNum, \"amount\")}></input>\n <input type=\"text\" list=\"categoryOptions\" class=\"catgeoryInput\" value={category} id={i} onChange={(e) => this.changeRuleParameter(e, selectorNum, \"category\")}/>\n <datalist id=\"categoryOptions\">\n {categoryOptions}\n </datalist>\n <div class=\"filterRuleText2\">meals in a row</div>\n {actionButton}\n </th>\n </tr>\n </table>\n )\n } else { // Otherwise display a empty new rule\n return (\n <table class=\"rule\">\n <tr>\n <th class=\"ruleName\" style={{\"background-color\":\"#ccc\"}}>\n {ruleName}\n </th>\n <th class=\"ruleParameters\">\n {actionButton}\n </th>\n </tr>\n </table>\n )\n }\n })\n\n return rules\n }",
"function processFilters() {\n var selectedUsers = [];\n var selectedCategories = [];\n var users = $('#facets-users');\n var categories = $('#facets-categories');\n users.find('input:checked').each(function() { selectedUsers.push(this.id); });\n categories.find('input:checked').each(function() { selectedCategories.push(this.id); });\n \n // Display all products if no options are selected\n if(selectedUsers.length + selectedCategories.length == 0) {\n $('#product-listings>ul>li').show();\n }\n else {\n var productTitles = getProducts(selectedUsers, selectedCategories);\n var products = $('#product-listings>ul>li');\n products.each(function() {\n var title = $(this).find('h2').text();\n // Leave the final 'how to submit your product' listing,\n // but show and hide all others\n if(title !== '{{ site.data.submission-listing.title }}') {\n if(productTitles[title]) {\n $(this).show();\n }\n else {\n $(this).hide();\n }\n }\n });\n }\n }",
"function loadEquipmentsByFilter( )\n{\n\tvar orgUnitId = document.getElementById('selectedOrgunitID').value;\n\tvar equipmentType = document.getElementById('equipmentType');\n\tvar equipmentTypeId = equipmentType.options[ equipmentType.selectedIndex ].value;\n\tvar searchText = document.getElementById('searchText').value;\n\t\n\tif( equipmentTypeId == 0 )\n\t{\t\n\t\t//alert(\"Plese select Equipmenttype\");\n\t\tshowWarningMessage( i18n_select_equipmenttype );\n\t\treturn;\n\t}\n\t\n\tvar equipmentTypeAttribute = document.getElementById('searchingAttributeId');\n\tvar equipmentTypeAttributeId = equipmentTypeAttribute.options[ equipmentTypeAttribute.selectedIndex ].value;\n\thideById('editEquipmentDiv');\n\thideById('resultSearchDiv');\n\thideById('editEquipmentStatusDiv');\n\thideById('equipmentDataEntryDiv');\n\tshowById('selectDiv');\n\tshowById('searchEquipmentDiv');\n\t\n\n\tjQuery('#loaderDiv').show();\n\tcontentDiv = 'listEquipmentDiv';\n\tisAjax = true;\n\t\n\tjQuery('#listEquipmentDiv').load('getEquipments.action',{\t\t\n\t\torgUnitId:orgUnitId, \n\t\tequipmentTypeId:equipmentTypeId,\n\t\tequipmentTypeAttributeId:equipmentTypeAttributeId,\n\t\tsearchText:searchText\n\t},\n\tfunction(){\n\t\tstatusSearching = 0;\n\t\tshowById('listEquipmentDiv');\n\t\tjQuery('#loaderDiv').hide();\n\t});\n\thideLoader();\n}",
"function ApplyFilter(bezl) {\n if (bezl.data.Accounts) { // Avoid throwing errors if the account data hasn't been returned yet\n for (var i = 0; i < bezl.data.Accounts.length; i++) {\n if (bezl.vars.filterString) { // Make sure we have something to filter on\n if (bezl.data.Accounts[i].ID.toUpperCase().indexOf(bezl.vars.filterString.toUpperCase()) !== -1 ||\n bezl.data.Accounts[i].Name.toUpperCase().indexOf(bezl.vars.filterString.toUpperCase()) !== -1 ||\n bezl.data.Accounts[i].Territory.toUpperCase().indexOf(bezl.vars.filterString.toUpperCase()) !== -1 ||\n bezl.data.Accounts[i].Address.toUpperCase().indexOf(bezl.vars.filterString.toUpperCase()) !== -1) {\n bezl.data.Accounts[i].show = true;\n } else {\n bezl.data.Accounts[i].show = false;\n }\n } else {\n bezl.data.Accounts[i].show = true;\n }\n };\n }\n}",
"function init_tag_selector() {\n if(query('#tag_selector')) {\n\tlet fieldset = query('#add_topic_form > fieldset');\n\tlet banned = fieldset && fieldset.disabled;\n\tlet tags_input = query('select[name=\"tags\"]');\n\tfor(let I of tags_input.options) {\n\t let option = I;\n\t let checkbox = (\n\t\ttag_selector.querySelector(\n\t\t printf('input[data-slug=\"%1\"]', option.value)\n\t\t)\n\t );\n\t let event_handler = function() {\n\t\toption.selected = this.checked;\n\t };\n\t checkbox.addEventListener('change', event_handler);\n\t event_handler.call(checkbox);\n\t if(!banned) {\n\t\tcheckbox.parentElement.addEventListener('click', function(ev) {\n\t\t if(ev.target != checkbox) {\n\t\t\tcheckbox.checked = !checkbox.checked;\n\t\t\tevent_handler.call(checkbox);\n\t\t }\n\t\t});\n\t } else {\n\t\tcheckbox.parentElement.style.color = 'gray';\n\t }\n\t checkbox.nextElementSibling.unselectable = 'on';\n\t checkbox.nextElementSibling.onselectstart = (function() {\n\t\treturn false;\n\t });\n\t}\n\ttags_input.style.display = 'none';\n\ttag_selector.style.display = '';\n }\n}",
"function searchVisibleResults(){\n target = $('.list .asked');\n target = target.filter(function () {\n return $(this).css('visibility') == 'visible'\n });\n target = target.filter(function () {\n return $(this).closest('.tldResults').css('display') != 'none'\n });\n return target;\n}",
"function $Q(selector) {\n\n //declare events:\n\n console.log(selector);\n\n var query = [];\n\n //handle selector / selection of objects:\n\n if (typeof selector !== 'string') {\n\n if (selector instanceof Array) {\n\n } else {\n\n\n }\n\n } else {\n\n\n if (selector && selector !== '*') {\n\n var s = selector || '';\n\n console.info('selector:' + s);\n\n\n var mainSelector = $Q.before('[', s).trim(),\n msfChar = mainSelector.substring(0, 1);\n\n var __targetClassName = \"*\";\n\n var output = [];\n\n var cleanSelectorString = function(str) {\n return str.replace(\",\", \"\");\n };\n\n switch (msfChar.toLowerCase()) {\n case \".\":\n\n console.info('Selecting by \".\" or class');\n\n __targetClassName = cleanSelectorString($Q.after('.', mainSelector));\n\n console.info('Target class is:' + __targetClassName);\n\n break;\n\n case \"*\":\n\n console.info('Selecting by \"*\" or ANY object in the library instance');\n\n __targetClassName = \"*\";\n\n break;\n\n }\n\n var criterion = $Q.between('[', ']', s),\n cparts = criterion.split('=');\n\n var __targetGroup = \"*\",\n __targetName = \"*\";\n\n var getParts = function() {\n\n if (cparts.length >= 2) {\n\n switch (cparts[0].toLowerCase()) {\n\n case \"name\":\n\n //get all objects according to name=name\n\n console.log('Q():Detected parts in selector:' + jstr(cparts));\n\n __targetName = cleanSelectorString(cparts[1]);\n\n break;\n\n case \"group\":\n\n console.log('Q():Detected parts in selector:' + jstr(cparts));\n\n __targetGroup = cleanSelectorString(cparts[1]);\n\n break;\n\n }\n\n }\n\n if (cparts.length >= 4) {\n\n cparts[2] = cparts[2].replace(\",\", \"\");\n\n switch (cparts[2].toLowerCase()) {\n\n case \"name\":\n\n //get all objects according to name=name\n\n console.log('Q():Detected parts in selector:' + jstr(cparts));\n\n __targetName = cleanSelectorString(cparts[3]);\n\n break;\n\n case \"group\":\n\n console.log('Q():Detected parts in selector:' + jstr(cparts));\n\n __targetGroup = cleanSelectorString(cparts[3]);\n\n break;\n\n }\n\n }\n\n };\n\n getParts(cparts);\n\n query = Gamelab.select(__targetClassName, __targetName, __targetGroup);\n\n } else if (selector == '*') {\n\n query = Gamelab.all();\n\n }\n\n }\n\n\n query.each = function(callback) {\n\n var objects = [];\n\n for (var x = 0; x < this.length; x++) {\n if (typeof x == 'number') {\n\n callback(x, this[x]);\n }\n\n }\n\n\n };\n\n query.on = function(evt_key, selectorObject, controller_ix, callback) //handle each event such as on('collide') OR on('stick_left_0') << first controller stick_left\n {\n\n if (typeof evt_key == 'function' && typeof selectorObject == 'function') {\n //this is a special pattern of if(f() == true){ runFunction(); };\n\n var boolTrigger = evt_key,\n boolCall = selectorObject,\n\n boolEvent = new Gamelab.BoolEvent().On(boolTrigger).Call(boolCall);\n\n }\n\n\n var criterion = $Q.between('[', ']', evt_key);\n\n if (criterion.indexOf('===') >= 0) {\n criterion = criterion.replace('===', '=');\n }\n\n if (criterion.indexOf('==') >= 0) {\n criterion = criterion.replace('==', '=').replace('==', 0);\n }\n\n var cparts = criterion.split('=');\n\n var __targetGroup = \"*\",\n __targetName = \"*\";\n\n if (evt_key.indexOf('[') >= 0) {\n evt_key = $Q.before('[', evt_key).trim();\n\n }\n\n\n var padding = 0;\n\n //if controller_ix is function, and callback not present, then controller_ix is the callback aka optional argument\n\n if (controller_ix && typeof controller_ix == 'function' && !callback) {\n callback = controller_ix;\n controller_ix = 0;\n }\n\n //optional argument: if controller_ix is function, and callback not present, then callback is selectorObject\n\n if (selectorObject && typeof selectorObject == 'function' && !callback) {\n\n callback = selectorObject;\n\n selectorObject = $Q('*');\n\n controller_ix = 0;\n };\n\n var evt_profile = {};\n\n //which controller?\n\n evt_profile.cix = controller_ix;\n\n //Need the control key: 'left_stick', 'button_0', etc..\n\n evt_profile.evt_key = evt_key;\n\n if ($Q.contains_any(['stick', 'button', 'click', 'key'], evt_profile.evt_key)) {\n\n var button_mode = evt_profile.evt_key.indexOf('button') >= 0;\n\n Gamelab.GamepadAdapter.on(evt_profile.evt_key, 0, function(x, y) {\n\n callback(x, y);\n\n });\n\n console.info('detected input event key in:' + evt_profile.evt_key);\n\n console.info('TODO: rig events');\n\n }\n\n //TODO: test collision events:\n else if ($Q.contains_any(['collide', 'collision', 'hit', 'touch'], evt_profile.evt_key)) {\n\n // console.info('Rigging a collision event');\n\n // console.info('detected collision event key in:' + evt_profile.evt_key);\n\n // console.info('TODO: rig collision events');\n\n this.each(function(ix, item1) {\n\n // console.info('Collision Processing 1:' + item1.name);\n // console.info('Collision Processing 1:' + item1.type);\n\n selectorObject.each(function(iy, item2) {\n\n // console.info('Collision Processing 2:' + item2.name);\n // console.info('Collision Processing 2:' + item2.type);\n\n if (typeof(item1.onUpdate) == 'function') {\n\n var update = function(sprite) {\n\n console.log('Box collide::' + jstr([this, item2]));\n\n if (this.hasBoxCollision(item2, padding)) {\n\n callback(this, item2);\n\n };\n\n };\n\n item1.onUpdate(update);\n\n }\n\n\n });\n\n });\n\n\n } else {\n console.info('Rigging a property event');\n\n //TODO: test property-watch events:\n\n console.info('detected property threshhold event key in:' + evt_profile.evt_key);\n\n console.info('TODO: rig property events');\n\n var condition = \"_\",\n key = criterion || evt_profile.evt_key;\n\n if (key.indexOf('[') >= 0 || key.indexOf(']') >= 0) {\n key = $Q.between('[', ']', key);\n\n }\n\n var evt_parts = [];\n\n var run = function() {\n console.error('Sprite property check was not set correctly');\n\n };\n\n if (key.indexOf('>=') >= 0) {\n condition = \">=\";\n\n\n } else if (key.indexOf('<=') >= 0) {\n condition = \"<=\";\n } else if (key.indexOf('>') >= 0) {\n condition = \">\";\n } else if (key.indexOf('<') >= 0) {\n condition = \"<\";\n } else if (key.indexOf('=') >= 0) {\n condition = \"=\";\n }\n\n evt_parts = key.split(condition);\n\n for (var x = 0; x < evt_parts.length; x++) {\n evt_parts[x] = evt_parts[x].replace('=', '').replace('=', '').trim(); //remove any trailing equals and trim()\n\n }\n\n var mykey, number;\n\n // alert(evt_parts[0]);\n\n try {\n\n mykey = evt_parts[0];\n\n number = parseFloat(evt_parts[1]);\n\n } catch (e) {\n console.log(e);\n }\n\n console.info('Gamelab:Processing condition with:' + condition);\n\n switch (condition) {\n\n case \">=\":\n\n\n run = function(obj, key) {\n if (obj[key] >= number) {\n callback();\n }\n };\n\n break;\n\n case \"<=\":\n\n run = function(obj, key) {\n if (obj[key] <= number) {\n callback();\n }\n };\n\n break;\n\n\n case \">\":\n\n run = function(obj, key) {\n if (obj[key] > number) {\n callback();\n }\n };\n\n break;\n\n case \"<\":\n\n run = function(obj, key) {\n if (obj[key] < number) {\n callback();\n }\n };\n\n break;\n\n case \"=\":\n\n run = function(obj, key) {\n if (obj[key] == number) {\n callback();\n }\n };\n\n break;\n\n }\n\n\n /************\n * Attach update to each member\n *\n * **************/\n\n var keys = mykey.split('.'),\n propkey = \"\";\n\n this.each(function(ix, item) {\n\n var object = {};\n\n if (keys.length == 1) {\n object = item;\n\n propkey = mykey;\n\n } else if (keys.length == 2) {\n object = item[keys[0]];\n\n propkey = keys[1];\n\n\n } else if (keys.length == 3) {\n object = item[keys[0]][keys[1]];\n\n propkey = keys[2];\n\n } else {\n console.error(\":length of '.' notation out of range. We use max length of 3 or prop.prop.key.\");\n\n }\n\n if (typeof item.onUpdate == 'function') {\n\n\n var spr = item;\n\n item.onUpdate(function(sprite) {\n\n run(object, propkey);\n\n });\n\n }\n\n });\n\n }\n\n };\n\n\n return query;\n\n}",
"function evaluateScripts(selector) {\n if (selector) {\n //run dataScript first always\n jQuery(selector).find(\"input[data-role='dataScript']\").each(function () {\n evalHiddenScript(jQuery(this));\n });\n\n jQuery(selector).find(\"input[name='script']\").each(function () {\n evalHiddenScript(jQuery(this));\n });\n }\n else {\n //run scripts for entire document if no selector defined\n //run dataScript first always\n jQuery(\"input[data-role='dataScript']\").each(function () {\n evalHiddenScript(jQuery(this));\n });\n\n jQuery(\"input[name='script']\").each(function () {\n evalHiddenScript(jQuery(this));\n });\n }\n}",
"function addFilterFunctionality() {\n var bubble,\n form,\n input,\n submit;\n\n // filter is available only for logged in users\n if ( !Site.remoteUser ) {\n return;\n }\n\n bubble = $('#lj_controlstrip_new .w-cs-filter-inner');\n\n // exit if filter content is not currently on the page\n if ( bubble.length === 0 ) {\n return;\n }\n\n form = $('#sortByPoster');\n input = form.find('[name=poster]');\n submit = form.find('[type=image]');\n\n bubble.bubble({\n target: '#lj_controlstrip_new .w-cs-filter-icon',\n showOn: 'click',\n closeControl: false\n });\n\n input.input(function () {\n if( this.value.length ) {\n submit.css('opacity', 1)\n .prop('disabled', false);\n } else {\n submit.css('opacity', 0)\n .prop('disabled', true);\n }\n });\n\n form.on('submit', function (e) {\n if( !input.val().length ) {\n e.preventDefault();\n }\n });\n }",
"function filterLinks() {\n var filterRadio = get_current_filter_radio();\n var filterValue = get_current_filter_value();\n\n if (document.getElementById('regex').checked || filterRadio.id != 'custom_filter') {\n visibleLinks = allLinks.filter(function(link) {\n return link.match(filterValue);\n });\n } else {\n var terms = filterValue.split(' ');\n visibleLinks = allLinks.filter(function(link) {\n for (var termI = 0; termI < terms.length; ++termI) {\n var term = terms[termI];\n if (term.length != 0) {\n var expected = (term[0] != '-');\n if (!expected) {\n term = term.substr(1);\n if (term.length == 0) {\n continue;\n }\n }\n var found = (-1 !== link.indexOf(term));\n if (found != expected) {\n return false;\n }\n }\n }\n return true;\n });\n }\n showLinks();\n}",
"function handle_requested_domains () {\n if(fundamental_vars.keywords[universalKeyword].length == 1){\n //If name is to big shorten name's presentation to fit on this screen width.\n finalName = single_domain_keyword_length_fix();\n tld = fundamental_vars.keywords[universalKeyword][0];\n\n var target = $('.list [data-tld=\"' + tld + '\"]'),\n singleResult = build_single_domain(target);\n\n //Target tld has a discount.\n if(target.find('.reduced-price').length > 0){\n singleResult.find('.reduced-price').html(target.find('.reduced-price').html());\n singleResult.find('.regular-price').addClass('discount');\n }\n\n //Remove source tld from the list.\n target.remove();\n\n //Show the single specified tld.\n $('.top-targets').removeClass('hide');\n }else{// Many specific domains requested.\n\n //Since the specified tlds are more than one then bring them to the top of the list in the order the user typed them.\n $.each($.upDownTable(fundamental_vars.keywords[universalKeyword]),function(key,value){\n $('.list').prepend($('[data-tld=\"' + value + '\"]'));\n });\n }\n}",
"function filterNames() {\n document.getElementsByClassName(\"pagination\")[0].innerHTML = ' '; \n let filterValue = document.getElementById('input').value.toUpperCase(); \n let ul = document.getElementById('names'); \n let li = ul.querySelectorAll('li.student-item'); \n const searchResults = []; \n for(let i = 0; i < li.length; i++) {\n li[i].style.display = 'none'; \n let h3 = li[i].getElementsByTagName('h3')[0]; \n \n if (h3.innerHTML.toUpperCase().includes(filterValue)) { \n searchResults.push(li[i]); \n li[i].style.display = '' \n } \n \n if(searchResults.length === 0) {\n noNamesDiv.style.display = '' \n } else {\n noNamesDiv.style.display = 'none' \n }\n \n } \n showPage(searchResults,1); \n appendPageLinks(searchResults); \n}",
"function renderFilterChoices() {\n filteredParks = allParks.filter( d => {\n if(filters[0].legend) {\n return d['Overall court grouping'] == filters[0].legend\n }\n else {\n return d\n }\n }).filter( d => {\n if(filters[1].borough) {\n return d['Borough'] == filters[1].borough\n } else {\n return d\n }\n }).filter( d => {\n if(filters[2].park) {\n return d['parkId'] == filters[2].park\n }\n else {\n return d\n }\n })\n\n renderParks(filteredParks) \n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
class that controls the population of birds, and evolves them | constructor(size) {
this.birds = [];
this.size = size;
this.actualBird = 0; //kind of an index for the population
for (let i = 0; i < size; i++) {
this.birds.push(new bird());
}
this.generation = 0;
this.melhor = this.birds[0];
this.lastmelhor = 0;
} | [
"function Population() {\n\n this.rockets = [];\n\n // creates initial rockets\n this.populate = () => {\n if (this.rockets.length > 0) this.rockets = [];\n for (let i = 0; i < popSize; i++) {\n this.rockets[i] = new Rocket(30, canvas.height/2);\n this.rockets[i].initiate();\n }\n };\n\n this.evaluate = () => {\n for (let rocket of this.rockets) {\n rocket.findFitness();\n }\n };\n\n // replaces rockets in current population with new bred rockets\n this.repopulate = () => {\n console.log('repopulating');\n let breedingPool = [];\n for (let rocket of this.rockets) {\n for (let i = 0; i < rocket.fitness; i++) {\n breedingPool.push(rocket);\n }\n }\n\n let newPop = [];\n for (let i = 0; i < popSize; i++) {\n let parent1 = breedingPool[Math.floor(Math.random() * breedingPool.length)];\n let parent2 = breedingPool[Math.floor(Math.random() * breedingPool.length)];\n let child = new Rocket(30, canvas.height/2);\n child.breed(parent1.dna, parent2.dna);\n newPop.push(child);\n }\n this.rockets = newPop;\n };\n\n // updates every rocket in the population\n this.update = () => {\n for (let rocket of this.rockets) {\n rocket.update();\n }\n };\n\n // draws every rocket in the population\n this.draw = () => {\n for (let rocket of this.rockets) {\n rocket.draw();\n }\n };\n}",
"breed () {\n for (let i = 0; i < this.population.length; i ++) {\n let A = this.matingPool.random();\n let B = this.matingPool.random();\n let child = A.crossover(B);\n child.mutate(this.mutationRate);\n this.population[i] = child;\n }\n\n this.finished = false;\n this.generations ++;\n }",
"initBirds() {\n this.geometry = new BirdGeometry(this.WIDTH);\n\n // For Vertex and Fragment\n this.birdUniforms = {\n color: { value: new Color( 0xff2200 ) },\n texturePosition: { value: null },\n textureVelocity: { value: null },\n time: { value: 1.0 },\n delta: { value: 0.0 }\n };\n // ShaderMaterial\n this.material = new ShaderMaterial( {\n uniforms: this.birdUniforms,\n vertexShader: birdVS,\n fragmentShader: birdFS,\n side: DoubleSide\n });\n var birdMesh = new Mesh( this.geometry, this.material );\n birdMesh.rotation.y = Math.PI / 2;\n birdMesh.matrixAutoUpdate = false;\n birdMesh.updateMatrix();\n this.scene.add(birdMesh);\n }",
"function create_main_obj(){\n chart_container.show();\n var newValues={};\n newValues.pop=population_slider.slider(\"value\");\n newValues.genome=genome_slider.slider(\"value\");\n newValues.mutate=mutation_prob_slider.slider(\"value\");\n newValues.fight=tournament_size_slider.slider(\"value\");\n newValues.gens=generations_slider.slider(\"value\");\n main_evolution_obj = new ea(newValues.pop, newValues.genome, newValues.mutate, newValues.fight);\n }",
"function pickABird() {\n var index=0;\n var r = random(1);\n\n while (r>0) {\n r=r-savedBirds[index].fitness;\n index++;\n }\n index--;\n var newBird = savedBirds[index];\n var child = new Bird(newBird.brain);\n child.mutate();\n return child;\n}",
"function Population(ninfected,nhealthy,nimmune,pinfect,socialcoef,\n\t\t infticks, death_probability)\n{\n //var Population = new Object();\n //var empty = 0;\n this.ninfected = ninfected;\n this.nhealthy = nhealthy;\n this.nimmune = nimmune;\n //var death_probability = 0.01;\n this.pinfect = pinfect;\n this.socialcoef = socialcoef; //multiplier of of healthy peeps that one infected person exposes infection to\n //var ninteractions = 0;\n this.infticks = infticks; //time in ticks that a person stays infected. On the last tick, they become immune. \n this.infarr = new Array(this.infticks);\n this.pdeath = new Array(this.infticks); //probability of infected to die every day. \n this.infarr[0] = this.ninfected;\n for(i=1; i<this.infarr.length;i++)\n\tthis.infarr[i] = 0;\n //death probability based on time exposed to infection.\n //consider changing this so that people are more likely to die \n //the longer they are exposed. \n for(i=0; i< this.pdeath.length; i++)\n\tthis.pdeath[i] = death_probability;\n this.updatePopulation=updatePopulation;\n function updatePopulation()\n {\n\t//this.ninfected++;\n\tvar tempinfarr = new Array(this.infarr.length);\n\tfor(i=0; i<this.infarr.length;i++)\n\t{\n\t this.infarr[i] -= Math.round(this.pdeath[i]*this.infarr[i]) //kill off a percentage\n\t tempinfarr[i] = this.infarr[i];\n\t}\n\tthis.ninfected = 0;\n\tfor(i=0; i<this.infarr.length-1;i++) \n\t{\n\t //print(infarr[i+1],tempinfarr[i]);\n\t this.infarr[i+1] = tempinfarr[i];\n\t this.ninfected += tempinfarr[i];\t\n\t}\n\t\n\tvar newimmune = this.infarr[this.infarr.length-1];\n\tthis.ninfected -= newimmune; //they are no longer infected.\n\tthis.infarr[this.infarr.length-1] = 0;\n\t\n\t//# healthy pop exposed to infection (can be greater than total pop)\n\tvar x = (this.ninfected * returnInteractions(this.nhealthy, this.ninfected,this.nimmune,this.socialcoef));\n\t//print(\"x:\",x)\n\tif (this.nhealthy == 0 || x>this.nhealthy)\n\t{\n\t print(\"Entire healthy population has been exposed.\");\n\t //newinfected = Math.round(nhealthy*pinfect);\n\t x = this.nhealthy;\n\t}\n\tvar newinfected = Math.round(x*this.pinfect);\n\tprint (\"newinfects: \",newinfected);\n\tthis.infarr[0] = newinfected;\n\tthis.nhealthy -= newinfected;\n\tthis.nimmune += newimmune;\n\t//return ninfected;\n\t//infarr[0] \n }\n function returnInteractions(nhealthy, ninfected,nimmune,socialcoef)\n {\n\t//if entire pop is sick, return 0\n\t//if entire pop is healthy, return ...\n\t//ratio = (nhealthy/ninfected)\n\t//if (ratio < 1)\n\t//\tratio = 1/ratio;\n\tratio = nhealthy/(ninfected+nimmune+nhealthy);\n\tninteractions = socialcoef*ratio;\n\tprint(\"interactions/tick: \",ninteractions);\n\treturn ninteractions; \n }\n}",
"throwBall(event, extraRuns = 0) {\n if ([\"Wd\", \"N\"].includes(event)) {\n // Extras\n this.bowl.runs += 1 + extraRuns;\n } else if (event == \"W\") {\n //Wicket\n this.bowl.overs += 1;\n this.bowl.wickets += 1;\n this.bowl.runs += extraRuns;\n } else {\n // Hit for runs\n this.bowl.overs += 1;\n this.bowl.runs += event;\n }\n\n // Update bowler stats in DOM\n const row = document.querySelector(`#${this.name}-bowl`).children;\n row[1].innerText = `${Math.floor(this.bowl.overs / 6)}.${\n this.bowl.overs % 6\n }`; // Convert balls to overs\n row[2].innerText = this.bowl.runs;\n row[3].innerText = this.bowl.wickets;\n }",
"function change_num_to_brick(){\n for (let z = 0; z < arr.length; z++) {\n arr1.push([]);\n brick_pos_x = 69.5; //69.5\n brick_pos_y = 69.5; //69.5\n count = 0;\n for (let x = 0; x < arr[z].length; x++) {\n arr1[z].push([]);\n for (let y = 0; y < arr[z][x].length; y++) {\n count++;\n if (arr[z][x][y] == 1) {\n brick_count++;\n arr1[z][x][y] = new bricks(GAME_WIDTH, GAME_HEIGHT, brick_pos_x, brick_pos_y);\n brick_pos_x += 91;\n }\n if (arr[z][x][y] == 2) {\n brick_count++;\n arr1[z][x][y] = new golden_brick(GAME_WIDTH, GAME_HEIGHT, brick_pos_x, brick_pos_y);\n brick_pos_x += 91;\n }\n if (arr[z][x][y] == 0) {\n arr1[z][x][y] = new no_brick(GAME_WIDTH, GAME_HEIGHT, brick_pos_x, brick_pos_y);\n brick_pos_x += 91;//101\n }\n if (count % 5 == 0) {\n brick_pos_y += 33;\n brick_pos_x = 69.5; //69.5\n }\n } \n } \n arr_len.push(brick_count);\n brick_count = 0\n }\n}",
"function master_controller() {\n\tthis.base_levels = [];\n\tthis.base_levels['frog'] = 1;\n\tthis.base_levels['bunny'] =1;\n\tthis.base_levels['bird'] = 1;\n\tthis.base_levels['deer'] = 1;\n\t\n\tthis.animals = [];\n\t\n\tthis.party_limit = 5;\n\t\n\t\n\tthis.timer = 0;\n\t\n\tthis.area_level = 1;\n\tthis.areaSeason = 'spring';\n\t\n\tthis.usableEvents = badEventsSpringDay.slice();\n\tvar evR = roll(2,0);\n\tthis.usableEvents.push(badEventsCatastrophe[evR]);\n\t\n\t\n\t\n\tthis.removalQ = [];\n\t\n\t//this.lifespans = new p_queue();\n\t\n\tthis.animations = [];\n\t\n\tthis.getAreaLevel = function(){\n\t\treturn this.area_level;\n\t}\n\t\n\tthis.areaLevelUp = function(){\n\t\tthis.area_level+=1;\n\t\tif(this.area_level % 10 == 1){\n\t\t\tswitch(this.areaSeason){\n\t\t\t\tcase 'spring':\n\t\t\t\t this.areaSeason = 'summer';\n\t\t\t\t\tbackground.layer2.setSrc(\"image_resources/layer2_sumer.png\")\n\t\t\t\t\tbackground.layer3.setSrc(\"image_resources/layer3_summer.png\")\n\t\t\t\t break;\n\t\t\t\tcase 'summer':\n\t\t\t\t this.areaSeason = 'fall';\n\t\t\t\t\tbackground.layer2.setSrc(\"image_resources/layer2_fall.png\")\n\t\t\t\t\tbackground.layer3.setSrc(\"image_resources/layer3_fall.png\")\n\t\t\t\t break;\n\t\t\t\tcase 'fall':\n\t\t\t\t this.areaSeason = 'winter'\n\t\t\t\t background.layer1.setSrc(\"image_resources/moun_snow.png\")\n\t\t\t\t\tbackground.layer2.setSrc(\"image_resources/layer2_winter.png\")\n\t\t\t\t\tbackground.layer3.setSrc(\"image_resources/layer3_winter.png\")\n\t\t\t\t break;\n\t\t\t\tcase 'winter': \n\t\t\t\t this.areaSeason = 'spring';\n\t\t\t\t background.layer1.setSrc(\"image_resources/mountain.png\")\n\t\t\t\t\tbackground.layer2.setSrc(\"image_resources/layer2_spring.png\")\n\t\t\t\t\tbackground.layer3.setSrc(\"image_resources/layer3_spring.png\")\n\t\t\t\t break;\n\t\t\t}\n\t\t}\n\t\tswitch(this.areaSeason){\n\t\t\t\tcase 'spring':\n\t\t\t\t if(this.areaLevel % 2 == 0){\n\t\t\t\t \tthis.usableEvents = badEventsSpringNight.slice();\n\t\t\t\t } else {\n\t\t\t\t \tthis.usableEvents = badEventsSpringDay.slice();\n\t\t\t\t }\n\t\t\t\t break;\n\t\t\t\tcase 'summer':\n\t\t\t\t if(this.areaLevel % 2 == 0){\n\t\t\t\t \tthis.usableEvents = badEventsSummerNight.slice();\n\t\t\t\t } else {\n\t\t\t\t \tthis.usableEvents = badEventsSummerDay.slice();\n\t\t\t\t }\n\t\t\t\t break;\n\t\t\t\tcase 'fall':\n\t\t\t\t if(this.areaLevel % 2 == 0){\n\t\t\t\t \tthis.usableEvents = badEventsFallNight.slice();\n\t\t\t\t } else {\n\t\t\t\t \tthis.usableEvents = badEventsFallDay.slice();\n\t\t\t\t }\n\t\t\t\t break;\n\t\t\t\tcase 'winter': \n\t\t\t\t if(this.areaLevel % 2 == 0){\n\t\t\t\t \tthis.usableEvents = badEventsWinterNight.slice();\n\t\t\t\t } else {\n\t\t\t\t \tthis.usableEvents = badEventsWinterDay.slice();\n\t\t\t\t }\n\t\t\t\t break;\n\t\t}\n\tvar cata = roll(2,0);\n\t//this.usableEvents.push(badEventsCatastrophe[cata]);\n\t}\n\t\n\tthis.areaLevelDown = function(){\n\t\tthis.area_level-=1;\n\t\tif(this.area_level % 10 == 0){\n\t\t\tswitch(this.areaSeason){\n\t\t\t\tcase 'spring':\n\t\t\t\t this.areaSeason = 'winter';\n\t\t\t\t break;\n\t\t\t\tcase 'summer':\n\t\t\t\t this.areaSeason = 'spring';\n\t\t\t\t break;\n\t\t\t\tcase 'fall':\n\t\t\t\t this.areaSeason = 'summer'\n\t\t\t\t break;\n\t\t\t\tcase 'winter': \n\t\t\t\t this.areaSeason = 'fall';\n\t\t\t\t break;\n\t\t\t}\n\t\t}\n\t\tswitch(this.areaSeason){\n\t\t\t\tcase 'spring':\n\t\t\t\t if(this.areaLevel % 2 == 0){\n\t\t\t\t \tthis.usableEvents = badEventsSpringNight.slice();\n\t\t\t\t } else {\n\t\t\t\t \tthis.usableEvents = badEventsSpringDay.slice();\n\t\t\t\t }\n\t\t\t\t break;\n\t\t\t\tcase 'summer':\n\t\t\t\t if(this.areaLevel % 2 == 0){\n\t\t\t\t \tthis.usableEvents = badEventsSummerNight.slice();\n\t\t\t\t } else {\n\t\t\t\t \tthis.usableEvents = badEventsSummerDay.slice();\n\t\t\t\t }\n\t\t\t\t break;\n\t\t\t\tcase 'fall':\n\t\t\t\t if(this.areaLevel % 2 == 0){\n\t\t\t\t \tthis.usableEvents = badEventsFallNight.slice();\n\t\t\t\t } else {\n\t\t\t\t \tthis.usableEvents = badEventsFallDay.slice();\n\t\t\t\t }\n\t\t\t\t break;\n\t\t\t\tcase 'winter': \n\t\t\t\t if(this.areaLevel % 2 == 0){\n\t\t\t\t \tthis.usableEvents = badEventsWinterNight.slice();\n\t\t\t\t } else {\n\t\t\t\t \tthis.usableEvents = badEventsWinterDay.slice();\n\t\t\t\t }\n\t\t\t\t break;\n\t\t}\n\tvar cata = roll(2,0);\n\tthis.usableEvents.push(badEventsCatastrophe[cata]);\n\t}\n\t\n\tthis.getBadEvents = function(){\n\t\treturn this.usableEvents;\n\t}\n\t\n\tthis.query = function(){\n\t\tfor(var i = 0; i < this.animals.length; i++){\n\t\t\tif(this.animals[i].canDie == true){\n\t\t\t\tif(Date.now() >= this.animals[i].deathTime){\n\t\t\t\t\tvar arr = this.animals[i].name.concat(\" died peacefully of old age.\")\n\t\t\t\t\teventLogAry.push(arr);\n\t\t\t\t\t//this.removeAnimal[i];\n\t\t\t\t\t//i--;\n\t\t\t\t\tthis.queueRemove(i);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.removeAllQueue();\n\t\t\n\t\t\n\t}\n\t\n\tthis.baseLevelUp = function(animal){\n\t\tthis.base_levels[animal] += 1;\n\t}\n\t\n\tthis.levelUpAnimal = function(num){\n\t\tthis.animals[num].levelUp();\n\t}\n\t\n\tthis.partySizeUp = function(){\n\t\tthis.party_limit += 1;\n\t}\n\t\n\tthis.addAnimal = function(animal){\n\t\tif(this.animals.length < this.party_limit) {\n\t\t\tvar ani = new animalClass(animal);\n\t\t\t//console.log(animal);\n\t\t\tani.setLevel(this.base_levels[animal]);\n\n\t\t\tvar text = \"\";\n\n\t\t switch(ani.type) {\n \t\t\tcase \"frog\":\n \t\t\ttext = nameFrog();\n \t\t\tbreak;\n \t\t\tcase \"bunny\":\n \t\t\ttext = nameBunny();\n \t\t\tbreak;\n \t\tcase \"bird\":\n \t\t\ttext = nameBird();\n \t\t\tbreak;\n \t\tcase \"deer\":\n \t\t\ttext = nameDeer();\n \t\t\tbreak;\n \t\t\tdefault:\n \t\t\ttext = \"random name\";\n\t\t\t}\n\t\t \n\t\t \n\t\t ani.name= text;\n\t\t\tthis.animals.push(ani);\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n \n\t}\n\t\n\tthis.queueRemove = function(index){\n\t\tthis.removalQ.push(index);\n\t}\n\t\n\tthis.removeAllQueue = function(){\n\t\tvar numInd = 0;\n\t\tfor(var i = 0; i < this.removalQ.length; i++){\n\t\t\tthis.removeAnimal(this.removalQ[i] - numInd);\n\t\t\tnumInd++;\n\t\t}\n\t\tthis.removalQ = [];\n\t}\n\t\n\tthis.removeAnimal = function(num){\n\t\tif(num < this.animals.length){\n\t\t\tthis.animals.splice(num,1);\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tthis.getAnimalData = function(){\n\t\tvar data = [];\n\t\tfor(var i = 0; i < this.animals.length; i++){\n\t\t\tvar dat = [];\n\n\t\t\tdat.push(this.animals[i].type)\n\t\t\tdat.push(this.animals[i].level)\n\t\t\tfor(var j = 0; j < 3; j++){\n\t\t\t\tvar stat = 1;\n\t\t\t\tfor(var k = 0; k < this.animals[i].level; k++){\n\t\t\t\t\tstat = Math.ceil(stat * animal_data[this.animals[i].type][j]);\n\t\t\t\t}\n\t\t\t\tdat.push(stat);\n\t\t\t}\n\t\t\tdat.push(this.animals[i].name)\n\t\t\tdata.push(dat);\n\t\t}\n\t\treturn data;\n\t}\n\n\tthis.getBaseData = function(animal) {\n var data = [];\n data.push(this.base_levels[animal]);\n for(var i = 0; i < 3; i++){\n var stat = 1;\n for(var k = 0; k < this.base_levels[animal]; k++){\n stat = Math.ceil(stat * animal_data[animal][i]);\n }\n data.push(stat);\n }\n return data;\n }\n\n\t\n\tthis.getAnimalBaseLevel = function(animal){\n\t\treturn this.base_levels[animal];\n\t}\n\t\n\tthis.getNumAnimals = function(){\n\t\treturn this.animals.length;\n\t\t\n\t}\n\t\n\t//get the amount of a certain animal\n\tthis.getAnimalCount = function(animal) {\n\t\tvar count = 0;\n\t\tfor (var a=0; a < this.getNumAnimals();a++ ) {\n\t\t\tif (this.animals[a].type == animal) count++;\n\t\t}\n\t\treturn count;\n\t}\n\n\tthis.update = function() {\n\t\tthis.timer++;\n\t\t//console.log(this.lifespans)\n\t\tif(this.timer == 15){\n\t\t\tthis.query();\n\t\t\tthis.timer = 0;\t\n\t\t}\t\n\t\t\n\t}\n\t\n\tthis.draw = function() {\n\n\t}\n}",
"function updateBombers() {\n\n\t\t// what's the wave count?\n\t\tif (waveCounter >= 5) {\n\n\t\t\tif (bomberSpawnTimer === 0) {\n\n\t\t\t\tvar allActive = true;\n\t\t\t\tfor (var a = 0; a < bombers.length; a++) {\n\t\t\t\t\tif (!bombers[a].isActive) {\n\t\t\t\t\t\tallActive = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!allActive) {\n\t\t\t\t\tvar r = 0;\n\n\t\t\t\t\tdo\n\t\t\t\t\t{\n\t\t\t\t\t\tr = Math.floor(randomNumber(0, bombers.length));\n\t\t\t\t\t}\n\t\t\t\t\twhile (bombers[r].isActive);\n\n\t\t\t\t\tbombers[r].isActive = true;\n\t\t\t\t\tbombers[r].health = 100;\n\t\t\t\t\tbombers[r].shootTime = BOMBER_SHOOT_TIME;\n\t\t\t\t\tbomberSpawnTimer = BOMBER_SPAWN_TIME;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tbomberSpawnTimer--;\n\t\t\t}\n\t\t}\n\n\t\tfor (var b = 0; b < bombers.length; b++) {\n\t\t\tif (bombers[b].isActive) {\n\t\t\t\tif (bombers[b].health <= 0)\n\t\t\t\t{\n\t\t\t\t\tcreateExplosion(bombers[b].x, bombers[b].y, 'bomber', bulletColours[0]);\n\t\t\t\t\tbombers[b].isActive = false;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (bombers[b].shootTime === 0) {\n\t\t\t\t\t\tbomberShoot(b);\n\t\t\t\t\t\tbombers[b].shootTime = BOMBER_SHOOT_TIME;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tbombers[b].shootTime--;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"function makeGrinder(args) {\n\tvar layer = new Layer({imageName: \"lever\"})\n\n\tlayer.touchEndedHandler = function(touchSequence) {\n\t\tnew Sound({name: \"beep-boop\"}).play()\n\t\trotateColors()\n\t\tafterDuration(0.25, function() {\n\t\t\tmoveColors()\n\t\t})\n\t\tafterDuration(1.50, function() {\n\t\t\tdripColors()\n\t\t})\n\t}\n\n\n\tfunction rotateColors() {\n\t\tred.rotateBricks()\n\t\tgreen.rotateBricks()\n\t\tblue.rotateBricks()\n\t}\n\n\n\tfunction moveColors() {\n\t\tred.moveToMixer()\n\t\tgreen.moveToMixer()\n\t\tblue.moveToMixer()\n\t}\n\n\tfunction dripColors() {\n\t\tvar bgColor = currentColor()\n\t\tvar totalCount = red.totalCount() + green.totalCount() + blue.totalCount()\n\t\tvar totalDripDuration = 2 // seconds\n\t\tvar timeIntervalBetweenDrips = totalDripDuration / totalCount\n\n\n\t\tfor (var counter = 0; counter < totalCount; counter++) {\n\t\t\tafterDuration(counter * timeIntervalBetweenDrips, function() {\n\t\t\t\tvar drip = new Layer()\n\t\t\t\tvar size = 24\n\t\t\t\tdrip.size = new Size({width: size, height: size})\n\t\t\t\tdrip.cornerRadius = drip.height / 2.0\n\t\t\t\tdrip.backgroundColor = bgColor\n\t\t\t\tdrip.scale = 0.01\n\t\t\t\tdrip.position = new Point({x: args.tap.frameMaxX, y: args.tap.frameMaxY})\n\n\t\t\t\tdrip.animators.scale.target = new Point({x: 1, y: 1})\n\t\t\t\tdrip.animators.position.target = new Point({x: args.bowl.x, y: args.bowl.y + 20})\n\t\t\t})\n\t\t}\n\t\tred.removeAllBricks()\n\t\tgreen.removeAllBricks()\n\t\tblue.removeAllBricks()\n\t}\n\n\treturn layer\n}",
"constructor(brain) {\n // All the physics stuff\n this.fx = 0;\n this.vx = 0;\n this.x = random(width);\n this.r = 8;\n this.y = height - this.r * 2;\n\n // This indicates how well it is doing\n this.score = 0;\n\n // How many sensors does each vehicle have?\n // How far can each vehicle see?\n // What's the angle in between sensors\n\n // Create an array of sensors\n this.sensors = [];\n const deltaAngle = PI / TOTALSENSORS;\n for (let angle = PI; angle <= TWO_PI; angle += deltaAngle) {\n this.sensors.push(new Sensor(angle, deltaAngle));\n }\n\n // If a brain is passed via constructor copy it\n if (brain) {\n this.brain = brain.copy();\n this.brain.mutate(0.1);\n // Otherwise make a new brain\n } else {\n // inputs are all the sensors plus position and velocity info\n let inputs = this.sensors.length + 2;\n this.brain = new NeuralNetwork(inputs, inputs, 1);\n }\n }",
"evolvePopulation(pop) {\n let newPopulation = new Population(pop.size(), false);\n\n // Keep our best individual if elitism is enabled\n let elitismOffset = 0;\n if (this.elitism) {\n newPopulation.saveTour(0, pop.getFittest());\n elitismOffset = 1;\n }\n\n // Crossover population\n // Loop over the new population's size and create\n // individuals from current population\n for (let i = elitismOffset; i < newPopulation.size(); i++) {\n // Select parents\n let parent1 = this.tournamentSelection(pop);\n let parent2 = this.tournamentSelection(pop);\n // Crossover parents\n let child = this.crossover(parent1, parent2);\n // Add child to new population\n newPopulation.saveTour(i, child);\n }\n\n // Mutate the new population a bit to add some new genetic material\n for (let i = elitismOffset; i < newPopulation.size(); i++) {\n this.mutate(newPopulation.getTour(i));\n }\n\n return newPopulation;\n }",
"function setup() {\n createCanvas(700, 500);\n dinoStegosaurus = new Dino(200, 200, 5, 40, 87, 83, 65, 68, 16, dinoStegosaurusImage);\n dinoTriceratops = new Dino(100, 100, 5, 40, UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW, 32, dinoTriceratopsImage);\n foodLeaves = new Food(100, 100, 10, 25, foodLeavesImage);\n foodBerries = new Food(100, 100, 8, 25, foodBerriesImage);\n foodPlant = new Food(100, 100, 20, 25, foodPlantImage);\n // New classes - Legendary\n // articuno = new CatalystFlood(100, 100, 20, 100, articunoImage);\n // moltres = new CatalystFire(50, 100, 20, 100, moltresImage);\n // zapdos = new CatalystMeteor(50, 100, 20, 100, zapdosImage);\n // Place dinos into array\n dinos = [dinoStegosaurus, dinoTriceratops];\n}",
"static updateBaloons(array) {\r\n for(var i = 0; i < array.length; i++) {\r\n var obj = array[i];\r\n \r\n if(obj.hp <= 0) {\r\n someoneIsDead(i); // gameLogic.js\r\n array.splice(i,1);\r\n i--;\r\n continue;\r\n }\r\n // Gravity\r\n else if(Math.abs(obj.y) < world[obj.x] - obj.ballRadius && !obj.goingUp){\r\n array[i].y += obj.dy;\r\n if(obj.dy < 1) \r\n obj.dy = 1.05;\r\n else \r\n obj.dy *= 1.04; \r\n }\r\n }\r\n }",
"draw(){\n\n for(let i=0; i<this.belt.length;i++){\n this.belt[i].draw();\n }\n }",
"function popgear(gearList) {\n gearUI = new GearUI(document.getElementById('gear'), gearList);\n\n var importVal = location.hash.substr(1);\n\n if (importVal.length > 0) {\n importGear(importVal);\n } else {\n var glist = defaultGear;\n var gearCache = localStorage.getItem('cachedGear.v2');\n if (gearCache && gearCache.length > 0) {\n var parsedGear = JSON.parse(gearCache);\n if (parsedGear.length > 0) {\n glist = parsedGear;\n }\n }\n gearUI.updateEquipped(glist);\n }\n\n var currentGear = gearUI.currentGear;\n\n gearUI.addChangeListener((item, slot) => {\n updateGearStats(gearUI.currentGear);\n });\n updateGearStats(currentGear)\n\n var simlogrun = document.getElementById(\"simlogrun\");\n simlogrun.addEventListener(\"click\", (event) => {\n runSimWithLogs(toGearSpec(gearUI.currentGear));\n });\n\n var simrunbut = document.getElementById(\"simrunbut\");\n simrunbut.addEventListener(\"click\", (event) => {\n runSim(toGearSpec(gearUI.currentGear));\n });\n\n var rotationRunButton = document.getElementById(\"rotationRunButton\");\n rotationRunButton.addEventListener(\"click\", (event) => {\n runRotationSim(toGearSpec(gearUI.currentGear));\n });\n\n var caclweights = document.getElementById(\"calcstatweight\");\n caclweights.addEventListener(\"click\", (event) => {\n calcStatWeights(toGearSpec(gearUI.currentGear));\n });\n\n var inputs = document.querySelectorAll(\"#buffs input\");\n for (var i = 0; i < inputs.length; i++) {\n var inp = inputs[i];\n inp.addEventListener(\"input\", (e) => {\n updateGearStats(gearUI.currentGear);\n });\n }\n var selects = document.querySelectorAll(\"#buffs select\");\n for (var i = 0; i < selects.length; i++) {\n var sel = selects[i];\n sel.addEventListener(\"change\", (e) => {\n updateGearStats(gearUI.currentGear);\n })\n }\n\n updateGearSetList();\n\n loadSettings(); // load phase/quality settings\n\n // This will perform all the setup needed to use the stored settings from above.\n changePhaseFilter({ target: document.getElementById(\"phasesel\") });\n changeQualityFilter({ target: document.getElementById(\"qualsel\") })\n\n\n window.addEventListener('hashchange', () => {\n var importVal = location.hash;\n if (importVal.length > 0) {\n importVal = importVal.substr(1);\n if (importVal != currentHash) {\n currentHash = importVal;\n importGear(importVal);\n }\n }\n });\n}",
"function HippoBee(creature){\n\n //------- Properties Definition ---------\n //this.hasLanded = false;\n this.health = new Health();\n this.stamina = new Stamina();\n this.happiness = new Happiness(); \n this.hippoImg = new Image();\n this.path = \"creatures/hippoBee/media/\";\n this.loadedImgSet = new Array();\n this.pos = {x:100,y:100};\n this.up = this.left = -1;\n this.down = this.right = 1;\n this.dirX = 1;\n this.dirY = -1;\n this.count=0;\n this.frameSpeed=4;\n this.angle = 45;\n \n //-------- Methods Definition ------------\n \n this.health.prototype=new State();\n this.stamina.prototype=new State();\n this.happiness.prototype=new State();\n \n //----------- Getters ---------------\n this.getHealth = function(){\n return this.health.getValue();\n }\n this.getStamina = function(){\n return this.stamina.getValue();\n }\n this.getHappiness = function(){\n return this.happiness.getValue();\n }\n \n //------------- Setters --------------\n this.setHealth = function(value){\n return this.health.setValue(value);\n }\n this.setStamina = function(value){\n return this.stamina.setValue(value);\n }\n this.setHappiness = function(value){\n return this.happiness.setValue(value);\n }\n \n //------------- Other Methods ----------------\n this.checkState = function(stateType,thereshold){\n return stateType.prototype.checkState(stateType.prototype,thereshold);\n }\n /* This decreases the value of one of the types of states. \n * @param dec int the decrement\n * @param stateType object an object inheriting from State\n */\n this.decreaseState = function(stateType,dec){\n stateType.prototype.decreaseState(stateType.prototype,dec);\n }\n /* This increases the value of one of the types of states. \n * @param inc int the increment\n * @param stateType object an object inheriting from State\n */\n this.increaseState = function(stateType,inc){\n stateType.prototype.increaseState(stateType.prototype,inc);\n }\n /* This draws a new image on the canvas \n * @param img Image the image to be drawn\n * TODO: Move the code that draws the glow around the image\n */\n this.drawImg = function(img){\n context.clearRect(0, 0, canvas.width, canvas.height);\n context.drawImage(img, 0, 0, canvas.width, canvas.height);\n context.shadowBlur = 40;\n context.shadowColor = \"rgb(250, 250, 250)\";\n }\n /* This loads the next sequence of images used to animate the bee.\n * @param nextImgSequence an Array of strings, i.e. the names of the images to load\n */\n this.loadImgSequence = function(nextImgSequence){\n \n this.loadedImgSet = nextImgSequence;\n \n }\n /* \n * This loads the first image to be drawn on the canvas.\n */\n this.initImg = function(){\n this.hippoImg.src = this.path + this.loadedImgSet[0];\n }\n /* \n * This will change the image to be drawn on the canvas\n * \n */\n this.animate = function(){\n //constrain values of i between 1 and maxFrm value\n i = (i+1)%this.loadedImgSet.length;\n this.hippoImg.width = canvas.width/2;\n this.hippoImg.height = canvas.height/2;\n this.hippoImg.src = this.path + this.loadedImgSet[i]; \n }\n /* \n * Utility fucntion: converts degrees to radiants.\n * @param angle int an angle in degree\n * @return angle in radiants\n * \n */\n this.toRadiants = function(angle){\n return (angle * Math.PI / 180);\n }\n \n this.boundariesCheck=function(angle)\n {\n var reflectionAngle = angle;\n if(this.pos.x<=0)\n {\n if(angle>90&&angle<180)\n {\n reflectionAngle=angle-90;\n }\n else if(angle<270&&angle>180)\n {\n reflectionAngle=angle+90;\n }\n else if(angle==180)\n {\n reflectionAngle=0;\n }\n }\n else if(this.pos.x >= world.width - width )\n {\n if(angle<90&&angle>0)\n {\n reflectionAngle=angle+90;\n }\n else if(angle<360&&angle>270)\n {\n reflectionAngle=angle-90;\n }\n else if(angle==0||angle==360)\n {\n reflectionAngle=180;\n }\n }\n if(this.pos.y<=0)\n {\n if(angle>270&&angle<360)\n {\n reflectionAngle=angle-270;\n }\n else if(angle<270&&angle>180)\n {\n reflectionAngle=angle-90;\n }\n else if(angle==270)\n {\n reflectionAngle=90;\n }\n }\n else if(this.pos.y >= world.height - height+5 )\n {\n \n if(angle>0&&angle<90)\n {\n reflectionAngle=angle+270;\n }\n else if(angle<180&&angle>90)\n {\n reflectionAngle=angle+90;\n }\n else if(angle==90)\n {\n reflectionAngle=270;\n }\n }\n return reflectionAngle;\n }\n \n /* \n * This is responsible for moving the creature.\n * @param angle int the angle in radiants between the moving direction and the x axis.\n * @param speed int the movement speed \n * \n */\n this.move = function(angle, speed){\n this.angle=this.boundariesCheck(angle);\n var radiants = this.toRadiants(this.angle);\n this.pos.x = this.pos.x + (Math.cos(radiants)*speed);\n this.pos.y = this.pos.y + (Math.sin(radiants)*speed); \n this.updatePosition();\n \n }\n \n /* This performs the creature landing.\n * @param xPos int the current hippoBee horizontal position\n * @param yPos int the current hippoBee vertical position\n * @param xInc int the value to be added or subracted\n * @param yInc int the value to be added or subracted\n * @return object pos the X and Y position object\n */\n this.land = function(){\n if(this.pos.y>=world.height-canvas.height+5){\n creature.trigger(\"landed\");\n }else\n {\n this.move(90, 5);\n }\n }\n \n /* This is responsible for the flying process. Invoked at every tick.\n * @param xPos int the current hippoBee horizontal position\n * @param yPos int the current hippoBee vertical position\n * @param xInc int the value to be added/subracted to/from xPos\n * @param yInc int the value to be added/subracted to/from yPos\n * @return object pos the X and Y position object\n */\n this.fly = function(){\n \n if(!(this.count%100)){\n this.angle = Math.random()*360; \n }\n this.move(this.angle, 5);\n if(!(this.count%this.frameSpeed))\n {\n this.decreaseState(this.health, 1);\n this.decreaseState(this.stamina, 1);\n }\n this.count++;\n }\n /* This is responsible for the eating process.\n * @param xPos int the current hippoBee horizontal position\n * @param yPos int the current hippoBee vertical position\n * @param xInc int the value to be added/subracted to/from xPos\n * @param yInc int the value to be added/subracted to/from yPos\n * @return object pos the X and Y position object\n */\n this.eat = function(){\n var theGrass = jj.get(\"grass\");\n theGrass.eat();\n \n \n this.increaseState(this.health, 2);\n }\n \n this.sleep = function(){\n this.increaseState(this.stamina,2);\n }\n \n /* \n * This is responsible for passing the upddated poisition to the creature object.\n */\n this.updatePosition = function()\n {\n creature.position({\n top:this.pos.y, \n left:this.pos.x\n });\n }\n \n \n }",
"function alldB() {\n\t\t\t\tins[0] = p.newdefault(x1, y1, \"inlet\");\n\t\t\t\tdbtoas[0] = p.newdefault(x1, y2, \"mindB\", mindB);\n\t\t\t\ttriggers[0] = p.newdefault(x1, y3, \"t\", \"l\", \"target\");\n\t\t\t\tappends[0] = p.newdefault(x1+20, y4, \"append\", 0);\t\t\t\n\t\t\t\tout = p.newdefault(x1, y5, \"outlet\");\n\t\t\t\tp.connect(ins[0], 0, dbtoas[0], 0);\n\t\t\t\tp.connect(dbtoas[0], 0, triggers[0],0);\n\t\t\t\tp.connect(triggers[0], 1, appends[0], 0);\n\t\t\t\tp.connect(appends[0], 0, out, 0);\n\t\t\t\tp.connect(triggers[0], 0, out, 0);\t\t\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Define the custom Writable class | function CustomWritable() {
Writable.call(this);
} | [
"function writerOf(type) {\n var self = getInstance(this, writerOf);\n self.type = type;\n return self;\n}",
"function createObjWriter(obj) {\n wasmInternalMemory.memoryToRead = obj;\n var module = new WebAssembly.Instance(webAssemblyModule, importObject);\n return {read_i8: module.exports.read_i8, write_i8: module.exports.write_i8, read_i16: module.exports.read_i16, write_i16: module.exports.write_i16, read_i32: module.exports.read_i32, write_i32: module.exports.write_i32, read_i64: read_i64.bind(null, module.exports.read_i16), write_i64: write_i64.bind(null, module.exports.write_i16), module: module}\n }",
"ins() {\n this.write.apply( this, arguments );\n }",
"function JsonLdWriter() {\n if (!(this instanceof JsonLdWriter))\n return new JsonLdWriter();\n}",
"write(str) {\n Files.write(nodePath.join(Files.gitletPath(), 'objects', Util.hash(str)), str);\n return Util.hash(str);\n }",
"function FileWriter() {\n}",
"static create(w, size = DEFAULT_BUF_SIZE) {\n return w instanceof BufWriter ? w : new BufWriter(w, size);\n }",
"function File() {\n \n /**\n The id of the file (if stored in the FC).\n * @name File#id\n * @type number\n * @readonly\n * @throws READ_ONLY_PROPERTY when setting the property is attempted\n */ \n this.prototype.id = undefined; \n /**\n The size of the file in bytes.\n * @name File#size\n * @type number\n * @readonly\n * @throws READ_ONLY_PROPERTY when setting the property is attempted\n */ \n this.prototype.size = undefined; \n /**\n Return the URL of the file (if stored in the FC).\n * @name File#url\n * @type string\n * @readonly\n * @throws READ_ONLY_PROPERTY when setting the property is attempted\n */ \n this.prototype.url = undefined; \n /**\n The path to the file in the file cabinet.\n * @name File#path\n * @type string\n * @readonly\n * @throws READ_ONLY_PROPERTY when setting the property is attempted\n */ \n this.prototype.path = undefined; \n /**\n The type of the file.\n * @name File#fileType\n * @type string\n * @readonly\n * @throws READ_ONLY_PROPERTY when setting the property is attempted\n */ \n this.prototype.fileType = undefined; \n /**\n * Indicates whether or not the file is text-based or binary.\n * @name File#isText\n * @type boolean\n * @readonly\n * @throws READ_ONLY_PROPERTY when setting the property is attempted\n */ \n this.prototype.isText = undefined; \n /**\n * The character encoding for the file.\n * @name File#encoding\n * @type string\n */ \n this.prototype.encoding = undefined; \n /**\n * The name of the file.\n * @name File#name\n * @type string\n */ \n this.prototype.name = undefined; \n /**\n * The internal ID of the folder that this file is in.\n * @name File#folder\n * @type number\n */ \n this.prototype.folder = undefined; \n /**\n * The file description.\n * @name File#description\n * @type string\n */ \n this.prototype.description = undefined; \n /**\n * The file's inactive status.\n * @name File#isInactive\n * @type boolean\n */ \n this.prototype.isInactive = undefined; \n /**\n * The file's \"Available without Login\" status.\n * @name File#isOnline\n * @type boolean\n */ \n this.prototype.isOnline = undefined; \n /**\n * @name File#lines\n * @type {Iterator} iterator - Iterator which provides the next line of text from the text file to the iterator function.\n * <pre> file.lines.iterator().each(function(lineContext){...}); </pre>\n *\n * @throws {SuiteScriptError} YOU_CANNOT_READ_FROM_A_FILE_AFTER_YOU_BEGAN_WRITING_TO_IT if you call after having called appendLine\n * @readonly\n */ \n this.prototype.lines = undefined; \n /**\n * Return the value (Base64 encoded for binary types) of the file.\n * Note: Contents are lazy loaded and must be less than 10MB in size in order to access.\n *\n * @throws {SuiteScriptError} SSS_FILE_CONTENT_SIZE_EXCEEDED when trying to get contents of a file larger than 10MB\n *\n * @return {string}\n */ \n this.prototype.getContents = function(options) {}; \n \n /**\n * Add/update a file in the file cabinet based on the properties of this object.\n *\n * @governance 20 units\n *\n * @throws {SuiteScriptError} SSS_MISSING_REQD_ARGUMENT when the folder property is not set\n * @throws {SuiteScriptError} INVALID_KEY_OR_REF if trying to save to a non-existing folder\n *\n * @return {number} return internal ID of file in the file cabinet\n *\n * @since 2015.2\n */ \n this.prototype.save = function(options) {}; \n \n /**\n * Append a chunk of text to the file.\n *\n * @param {Object} options\n * @param {string} options.value text to append\n * @return {file} Returns this file\n * @throws {SuiteScriptError} YOU_CANNOT_WRITE_TO_A_FILE_AFTER_YOU_BEGAN_READING_FROM_IT If you call it after having called FileLines#each\n * @since 2017.1\n */ \n this.prototype.append = function(options) {}; \n \n /**\n * Append a line of text to the file.\n *\n * @param {Object} options\n * @param {string} options.value text to append\n * @return {file} Returns this file\n * @throws {SuiteScriptError} YOU_CANNOT_WRITE_TO_A_FILE_AFTER_YOU_BEGAN_READING_FROM_IT If you call it after having called FileLines#each\n * @since 2017.1\n */ \n this.prototype.appendLine = function(options) {}; \n \n /**\n * Reset the reading and writing streams that may have been opened by appendLine or FileLines#each\n *\n * @since 2017.1\n */ \n this.prototype.resetStream = function(options) {}; \n \n /**\n * Returns the object type name (file.File)\n *\n * @returns {string}\n */ \n this.prototype.toString = function(options) {}; \n \n /**\n * JSON.stringify() implementation.\n *\n * @returns {{type: string, id: *, name: *, description: *, path: *, url: *, folder: *, fileType: *, isText: *,\n * size: *, encoding: *, isInactive: *, isOnline: *, contents: *}}\n */ \n this.prototype.toJSON = function(options) {}; \n}",
"bind(path, type, options = {}) {\n // Maps objects that are stored in a specific path to a constructor method,\n // so they are automatically deserialized\n if (typeof path !== \"string\") {\n throw new TypeError(\"path must be a string\");\n }\n if (typeof type !== \"function\") {\n throw new TypeError(\"constructor must be a function\");\n }\n if (typeof options.serializer === 'undefined') {\n // if (typeof type.prototype.serialize === 'function') {\n // // Use .serialize instance method\n // options.serializer = type.prototype.serialize;\n // }\n // Use object's serialize method upon serialization (if available)\n }\n else if (typeof options.serializer === 'string') {\n if (typeof type.prototype[options.serializer] === 'function') {\n options.serializer = type.prototype[options.serializer];\n }\n else {\n throw new TypeError(`${type.name}.prototype.${options.serializer} is not a function, cannot use it as serializer`);\n }\n }\n else if (typeof options.serializer !== 'function') {\n throw new TypeError(`serializer for class ${type.name} must be a function, or the name of a prototype method`);\n }\n if (typeof options.creator === 'undefined') {\n if (typeof type.create === 'function') {\n // Use static .create as creator method\n options.creator = type.create;\n }\n }\n else if (typeof options.creator === 'string') {\n if (typeof type[options.creator] === 'function') {\n options.creator = type[options.creator];\n }\n else {\n throw new TypeError(`${type.name}.${options.creator} is not a function, cannot use it as creator`);\n }\n }\n else if (typeof options.creator !== 'function') {\n throw new TypeError(`creator for class ${type.name} must be a function, or the name of a static method`);\n }\n path = path.replace(/^\\/|\\/$/g, \"\"); // trim slashes\n this[_mappings][path] = {\n db: this.db,\n type,\n creator: options.creator,\n serializer: options.serializer,\n deserialize(snap) {\n // run constructor method\n let obj;\n if (this.creator) {\n obj = this.creator.call(this.type, snap);\n }\n else {\n obj = new this.type(snap);\n }\n return obj;\n },\n serialize(obj, ref) {\n if (this.serializer) {\n obj = this.serializer.call(obj, ref, obj);\n }\n else if (obj && typeof obj.serialize === 'function') {\n obj = obj.serialize(ref, obj);\n }\n return obj;\n }\n };\n }",
"toString() {\n const buffer = [];\n\n // create `class {`\n buffer.push(`class ${this.name} {\\n`);\n\n // check if there are fields items\n if (this.fields.length > 0) {\n // create `constructor(`\n buffer.push(' constructor(');\n\n // loop over fields\n for (let i = 0; i < this.fields.length; i++) {\n // add field name to argurmnet list in constuctor `contructor(arg, `\n buffer.push(this.fields[i].name);\n\n // if i is not equal to length of fields add `,` for next argument\n if (i + 1 !== this.fields.length) {\n buffer.push(', ');\n }\n }\n\n // close arguments brackets for contructor `contructor(arg1, arg2) {`\n buffer.push(') {\\n');\n\n // loop over fields and init each field in contructor\n // this.arg = arg\n for (let field of this.fields) {\n buffer.push(` this.${field.name} = ${field.name};\\n`);\n }\n\n // close constructor function\n buffer.push(' }\\n');\n }\n\n // close class itself\n buffer.push('}');\n\n // return as string\n return buffer.join('');\n }",
"function createOutputJsonInstance()\n{\n\tvar output = \n\t\t{\n\t\t\t\"status\": null,\n\t\t\t\"message\": null,\n\t\t\t\"data\": null\n\t\n\t\t}\n\n\treturn output;\n\n}",
"writeStringLiteralType(enumeration, options) {\n if (!enumeration)\n return this;\n if (!options)\n options = {};\n this.writeJsDocDescription(enumeration.ownedComments);\n this.writeIndent();\n if (options.export) {\n this.write(`export `);\n }\n if (options.declare) {\n this.write('declare ');\n }\n this.write(`type ${enumeration.name} = `);\n this.joinWrite(enumeration.ownedLiterals, ' | ', lit => `'${lit.name}'`);\n this.writeEndOfLine(';');\n return this;\n }",
"set(id, data) {\n let oldData = this.raw();\n oldData[id] = data;\n this._write(oldData);\n }",
"constructor(type, driver, config) {\n // Create an anonymous class\n let Clone = function() {}\n // Set its prototype to the prototype of Node or Relationshp\n // but add driver and config as non-enumerable, write-only fields\n Clone.prototype = Object.create(base[ type ].prototype, {\n driver: {\n writable: false,\n configurable: false,\n enumerable: false,\n value: driver\n },\n config: {\n writable: false,\n configurable: false,\n enumerable: false,\n value: config\n }\n })\n\n return Clone\n }",
"function Transform() {\n stream.Transform.call(this, {objectMode: true});\n }",
"set CustomProvidedInput(value) {}",
"function IcecastWriteStack(stream, metaint) {\n StreamStack.call(this, stream);\n this.metaint = metaint;\n this.counter = 0;\n this._metadataQueue = [];\n}",
"function createItem(value) {\n return (value instanceof Buffer) ? Item.createBuffer(value) : Item.createString(value);\n}",
"error(e = undefined) {\n\t\t if (!IsWritableStreamDefaultController(this)) {\n\t\t throw new TypeError('WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController');\n\t\t }\n\t\t const state = this._controlledWritableStream._state;\n\t\t if (state !== 'writable') {\n\t\t // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n\t\t // just treat it as a no-op.\n\t\t return;\n\t\t }\n\t\t WritableStreamDefaultControllerError(this, e);\n\t\t }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
the average number. Examples: avgValue([10, 20]); // => 15 avgValue([2, 3, 7]); // => 4 avgValue([100, 60, 64]); // => 74.66666666666667 | function avgValue(array)
{
var sum = 0;
for(var i = 0; i <= array.length - 1; i++)
{
sum += array[i];
}
var arrayLength = array.length;
return sum/arrayLength;
} | [
"function avg(v){\n s = 0.0;\n for(var i=0; i<v.length; i++)\n s += v[i];\n return s/v.length;\n}",
"function averageNumbers(array){\n let sum = 0;\n let avg;\n for ( let i = 0 ; i < array.length ; i++ ){\n sum = sum + array[i];\n avg = sum / array.length\n }\n return avg\n}",
"function absAvg(arr){\n // arr is a typed array! \n var abs_avg = arr.reduce((a,b) => (a+Math.abs(b))) / arr.length;\n return abs_avg; \n}",
"function calculateAverage(ratings){\n var sum = 0;\n for(var i = 0; i < ratings.length; i++){\n sum += parseInt(ratings[i], 10);\n }\n\n var avg = sum/ratings.length;\n\n return avg;\n }",
"function mean(num) {\n\treturn [...num.toString()].reduce((x, i) => (Number(x) + Number(i))) / num.toString().length; \n}",
"function calculateAverage(grades) {\n // grades is an array of numbers\n total = 0\n for(let i = 0; i <grades.length; i++){\n total += grades[i];\n }\n return Math.round(total / grades.length);\n}",
"function average() {\n\tvar total = 0;\n\tfor (var i = 0; i < this.grades.length; ++i) {\n\t\ttotal += this.grades[i];\n\t}//end for\n\treturn print(total / this.grades.length);\n}//end average function",
"function maxMinAvg(arr){\n var max = arr[0];\n var min = arr[0];\n var avg = null;\n for(i=0;i<arr.length;i++){\n if(arr[i]<min){\n min = arr[i];\n }\n if(arr[i]>max){\n max = arr[i];\n }\n avg+=arr[i];\n }\n var newArr = [max, min, avg/arr.length]\n return newArr;\n}",
"function calculateAverage(){\n var sum = 0;\n for(var i = 0; i < self.video.ratings.length; i++){\n sum += parseInt(self.video.ratings[i], 10);\n }\n\n self.avg = sum/self.video.ratings.length;\n }",
"function average(){\n\t\t\tvar sum = 0;\n\t\t\tlist.forEach(function(item){\n\t\t\t\tsum += item.age;\n\t\t\t});\n\n\t\t\treturn sum / list.length;\n\t\t}",
"function avg(num1, num2, num3){\n return (num1 + num2 + num3)/3;\n }",
"function avg(num1, num2, num3){\n return (num1 + num2 + num3)/3;\n}",
"function mean(values) {\n var average = []\n for (var i = 0; i < values.length; i++) {\n var sum = 0;\n for (var j = 0; j < values[i].length; j++) {\n sum = sum + values[i][j]\n }\n average.push(sum/values[i].length)\n }\n return average;\n }",
"average(stats) {\n return this.add(stats).scale(0.5);\n }",
"function calculateMean() {\n var mean = 0;\n for (var j = 0; j < $scope.data2.length; j++) {\n mean = mean + $scope.data2[j].y;\n }\n return mean = ((mean / 24).toFixed(2));\n }",
"function average(x1, x2, x3, x4, x5) {\n var sum = x1 + x2 + x3 + x4 + x5;\n var avg = sum / 5;\n return console.log(avg)\n}",
"function find_average() {\n number_of_accounts = accounts.length;\n console.log(\"Number of bank accounts: \" + number_of_accounts);\n total = total_cash();\n average = total / number_of_accounts;\n console.log(\"Average bank account value: £\" + average);\n}",
"function toAvg(temp) {\n return (temp <= result.avg && temp >= (result.avg - 5));\n}",
"getAverageHR() {\n let retval=0;\n if (this.countHR>0) { retval=parseInt(this.totalHR/this.countHR) }\n return retval;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turns a glob string into a regexp | function fs_glob_to_regexp(glob) {
if (typeof glob !== 'string') {
throw new Error("file_glob_to_regexp: glob must be a string");
}
// make sure absolute
glob = fs_expand_path(glob);
// console.log("full glob is: " + glob);
var parts = glob.split(''), length = parts.length, result = '';
var opt_group_stack = 0;
for (var i = 0; i < length; i++) {
var cur = parts[i];
switch (cur) {
case '*':
if (parts[i + 1] == '*') {
result += '.*';
i++;
}
else {
result += '[^/]*';
}
break;
case '.':
result += '\\';
result += cur;
break;
case ',':
if (opt_group_stack) {
result += '|';
}
else {
result += ',';
}
break;
case '{':
result += '(';
opt_group_stack++;
break;
case '}':
if (opt_group_stack) {
result += ')';
opt_group_stack--;
}
else {
result += '}'
}
break;
default:
result += cur;
}
}
return new RegExp('^' + result + '$');
} | [
"function normalizeGlob(glob, { globstar = false } = {}) {\n if (!!glob.match(/\\0/g)) {\n throw new DenoError(ErrorKind.InvalidPath, `Glob contains invalid characters: \"${glob}\"`);\n }\n if (!globstar) {\n return mod_ts_1.normalize(glob);\n }\n const s = constants_ts_4.SEP_PATTERN.source;\n const badParentPattern = new RegExp(`(?<=(${s}|^)\\\\*\\\\*${s})\\\\.\\\\.(?=${s}|$)`, \"g\");\n return mod_ts_1.normalize(glob.replace(badParentPattern, \"\\0\")).replace(/\\0/g, \"..\");\n }",
"function buildGlobMatcher(globs, root, isExclude) {\n const withRoots = globs.map((g) => {\n const source = typeof g === 'string' ? 'command line' : undefined;\n return { source, ...(0, cspell_glob_1.fileOrGlobToGlob)(g, root) };\n });\n return new cspell_glob_1.GlobMatcher(withRoots, { root, mode: isExclude ? 'exclude' : 'include' });\n}",
"function regexpFrom(string, flags) {\n return new RegExp(core.escapeRegExp(string), flags);\n }",
"function _globalize($regexp) {\n return new RegExp(String($regexp).slice(1, -1), \"g\");\n }",
"function generateRegExp() {\n\n\tvar str = '';\n\tvar arr = [];\n\tvar tmp = \"@(types)\";\n\t\n\tfor (type in corpus) {\n\t\tarr.push(type);\n\t}\n\t\n\tvar exp = tmp.replace(\"types\", arr.join('|'));\n\t\n\treturn new RegExp(exp, \"ig\");\n}",
"function createGlobPatternsForDependencies(dirPath, fileGlobPattern) {\n const filenameRelativeToWorkspaceRoot = path_1.relative(app_root_1.appRootPath, dirPath);\n const projectGraph = project_graph_1.readCachedProjectGraph('4.0');\n // find the project\n let projectName;\n try {\n projectName = project_graph_utils_1.getProjectNameFromDirPath(filenameRelativeToWorkspaceRoot, projectGraph);\n }\n catch (e) {\n throw new Error(`createGlobPatternsForDependencies: Error when trying to determine main project.\\n${e === null || e === void 0 ? void 0 : e.message}`);\n }\n // generate the glob\n try {\n const projectDirs = project_graph_utils_1.getSourceDirOfDependentProjects(projectName, projectGraph);\n return projectDirs.map((sourceDir) => path_1.resolve(app_root_1.appRootPath, devkit_1.joinPathFragments(sourceDir, fileGlobPattern)));\n }\n catch (e) {\n throw new Error(`createGlobPatternsForDependencies: Error when generating globs.\\n${e === null || e === void 0 ? void 0 : e.message}`);\n }\n}",
"function match(pattern) {\n var paths = glob.sync(pattern, { cwd: ASSETS_ROOT });\n\n if (paths.length === 0) {\n console.warn('Asset pattern ' + pattern + ' did not match any files');\n }\n\n // @NOTE: we have to explicitly make them relative to conform with commonJs\n // require syntax, otherwise webpack will try to look for them\n // in the node_modules\n return paths.map(function(filepath) {\n return './' + filepath;\n });\n}",
"function getRegExp(pattern, flags) {\n var safeFlags = angular.isString(flags) ? flags : \"\";\n return (angular.isString(pattern) && pattern.length > 0) ? new RegExp(pattern, safeFlags) : null;\n }",
"function generateRegExp() {\n\n\tvar str = '';\n\tvar arr = [];\n\tvar tmp = \"@(types)\";\n\t\n\t// Get all the replaceable keywords from corpus, stick them into an array\n\tfor(type in corpus) {\n\t\tarr.push(type);\n\t}\n\t\n\t// Construct regular expression in the form of '@(keyword1,keyword2,keyword3,...)'\n\tvar exp = tmp.replace(\"types\", arr.join('|'));\n\t\n\treturn new RegExp(exp, \"ig\");\n}",
"generateExcludePattern() {\n const transpile = this.transpileModules;\n\n if (transpile === true) {\n return /(\\b@babel|core-js|webpack|(css)-loader)\\b/;\n } else if (!transpile || (Array.isArray(transpile) && !transpile.length)) {\n return /node_modules/;\n } else {\n const includeModules = transpile.map(escapeRegExp).join(\"|\");\n return new RegExp(\n `node_modules${slashPattern}(?!(${includeModules})${slashPattern})`\n );\n }\n }",
"function oneStar(dotfile) {\r\n return dotfile ? '(?!' + dotfileGlob + ')(?=.)' + star : (nodot + star);\r\n}",
"function compileRegExp(lexer, str) {\n if (typeof (str) !== 'string') {\n return null;\n }\n var n = 0;\n while (str.indexOf('@') >= 0 && n < 5) { // at most 5 expansions\n n++;\n str = str.replace(/@(\\w+)/g, function (s, attr) {\n var sub = '';\n if (typeof (lexer[attr]) === 'string') {\n sub = lexer[attr];\n }\n else if (lexer[attr] && lexer[attr] instanceof RegExp) {\n sub = lexer[attr].source;\n }\n else {\n if (lexer[attr] === undefined) {\n _monarchCommon_js__WEBPACK_IMPORTED_MODULE_1__[\"throwError\"](lexer, 'language definition does not contain attribute \\'' + attr + '\\', used at: ' + str);\n }\n else {\n _monarchCommon_js__WEBPACK_IMPORTED_MODULE_1__[\"throwError\"](lexer, 'attribute reference \\'' + attr + '\\' must be a string, used at: ' + str);\n }\n }\n return (_monarchCommon_js__WEBPACK_IMPORTED_MODULE_1__[\"empty\"](sub) ? '' : '(?:' + sub + ')');\n });\n }\n return new RegExp(str, (lexer.ignoreCase ? 'i' : ''));\n}",
"function patternCache() {\n pattern = new RegExp(settings.start + \"\\\\s*(\" + settings.path + \")\\\\s*\" + settings.end, \"gi\");\n }",
"function wildcardify(name) {\n var parts = name.split(\".\");\n if (parts.length == 1) {\n parts[0] += \"*\";\n } else {\n parts[parts.length-2] += \"*\";\n }\n return parts.join(\".\");\n }",
"function regenerateRegExp(){\r\n\t\tpseudoRE = new RegExp('::?(' + Object.keys(pseudos).join('|') + ')(\\\\\\\\[0-9]+)?');\r\n\t}",
"function getOrCreateGlob(pattern) {\n if (patternCache.has(pattern)) {\n return patternCache.get(pattern);\n }\n var glob = new minimatch_1.Minimatch(pattern, { dot: true });\n patternCache.set(pattern, glob);\n return glob;\n }",
"function getEntryFileGlobs({ fixtures, tests }) {\n let globs = [];\n for (let patterns of [fixtures, tests]) {\n for (let pattern of patterns) {\n if (typeof pattern === \"string\") {\n globs.push(pattern);\n }\n else if (pattern.included !== false) {\n globs.push(pattern.pattern);\n }\n }\n }\n return globs;\n}",
"function parseRegExp(node) {\n const evaluated = (0, util_1.getStaticValue)(node, globalScope);\n if (evaluated == null || !(evaluated.value instanceof RegExp)) {\n return null;\n }\n const { source, flags } = evaluated.value;\n const isStartsWith = source.startsWith('^');\n const isEndsWith = source.endsWith('$');\n if (isStartsWith === isEndsWith ||\n flags.includes('i') ||\n flags.includes('m')) {\n return null;\n }\n const text = parseRegExpText(source, flags.includes('u'));\n if (text == null) {\n return null;\n }\n return { isEndsWith, isStartsWith, text };\n }",
"function getSampleDataRegExp(domainType) {\n if (angular.isUndefined(domainType.$regexp)) {\n domainType.$regexp = getRegExp(domainType.regexPattern, domainType.regexFlags);\n }\n return domainType.$regexp;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Escape for template's expression charactors. | function escapeTemplateExp(src) {
// eslint-disable-next-line
return src.replace(/[-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
} | [
"encodeSpecials() {\n const value = this.value;\n const regex = /(\\'|\"|\\\\x00|\\\\\\\\(?![\\\\\\\\NGETHLnlr]))/g;\n return value.replace(regex, '\\\\\\\\$0');\n }",
"function escapeRegex(target)\n{\n return String(target).replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g, '\\\\$1').replace(/\\x08/g, '\\\\x08');\n}",
"function escapeSelector(sel) {\n return sel.replace(/[/$]/g, '\\\\$&');\n }",
"function escapeChar(ch) {\n\tlet charCode = ch.charCodeAt(0);\n\tif(charCode <= 0xFF) {\n\t\treturn '\\\\x' + pad(charCode.toString(16).toUpperCase());\n\t} else {\n\t\treturn '\\\\u' + pad(charCode.toString(16).toUpperCase(),4);\n\t}\n}",
"function escape(s) {\n let result = \"\";\n _.each(s, function (ch) {\n switch (ch) {\n case \":\":\n result += \"\\\\:\";\n break;\n case \"\\\\\":\n result += \"\\\\\\\\\";\n break;\n default:\n result += ch;\n }\n });\n return result;\n}",
"function escape(code){\n \tcode = code\n \t\t//.replace(/[\\s\\t]+/g, '') // �ո���Tab\n .replace(/('|\"|\\\\)/g, '\\\\$1')// ��˫�����뷴б��ת��\n .replace(/\\r/g, '\\\\r')// ���з�ת��(windows + linux)\n .replace(/\\n/g, '\\\\n');\n \treturn outCode + '\"' + code + '\";';\n }",
"function escapeQueryChars(unescaped, preserveWildcards) {\n if (!unescaped) {\n return '';\n }\n unescaped = unescaped.replace(/([\\\\\\+\\-\\!\\(\\)\\:\\^\\[\\]\\\"\\{\\}\\~\\|\\&\\;\\/\\s])/g, '\\\\$1');\n if (!preserveWildcards) {\n unescaped = unescaped.replace(/([\\*\\?])/g, '');\n }\n return unescaped;\n}",
"function escapeArg (value) {\n function hexencode (match) {\n return \"\\\\x\" + match.charCodeAt(0).toString(16);\n }\n return value.replace(/[\\\\\", \\n]/g, hexencode);\n}",
"function qexpr(expr) {\n if( expr instanceof Expr ) {\n return expr.toString();\n } else {\n return quoteIdentifier(expr);\n }\n}",
"testReplaceAll_specialReplacement() {\n assertEquals('Xyz'.replaceAll('Xyz', '$$'), '$');\n assertEquals('PreXyzPost'.replaceAll('Xyz', '$&'), 'PreXyzPost');\n assertEquals('PreXyzPost'.replaceAll('Xyz', '$`'), 'PrePrePost');\n assertEquals('PreXyzPost'.replaceAll('Xyz', '$\\''), 'PrePostPost');\n assertEquals('PreXyzPostXyz'.replaceAll('Xyz', '$\\''), 'PrePostXyzPost');\n assertEquals('123'.replaceAll('2', '$`'), '113');\n }",
"function escapeXml(xml) \n{\n return xml.replace(/[<>&'\"]/g, function (c) {\n switch (c) {\n case '<': return '<';\n case '>': return '>';\n case '&': return '&';\n case '\\'': return ''';\n case '\"': return '"';\n }\n });\n}",
"function formatMath(expr) {\n\treturn `${expr} = ${eval(expr.replace(\"x\", \"*\"))}`\n}",
"function echoTag(literals, ...substitutions) {\n let result = \"\";\n for (let i = 0; i < substitutions.length; i++) {\n result += literals[i];\n result += substitutions[i];\n }\n // add the last literal.\n result += literals[literals.length - 1];\n return result\n }",
"function escapeSqlIdentifier(str) {\n var escaped = '\"';\n for (var _i = 0, str_1 = str; _i < str_1.length; _i++) {\n var c = str_1[_i];\n if (c === '\"')\n escaped += c + c;\n else\n escaped += c;\n }\n escaped += '\"';\n return escaped;\n }",
"function escapeRightAngleBracketsInCdataTerminator(str) {\r\n return str.replace(/]]>/g, \"]]>\");\r\n}",
"function qplCharFormat(ko, Format) {\n var SB = Components.classes[\"@mozilla.org/intl/stringbundle;1\"]\n .getService(Components.interfaces.nsIStringBundleService)\n .createBundle(\"chrome://qplwrapper/locale/qplwrapper.properties\");\n\n var QPLWrapper = SB.GetStringFromName('QPLWrapper');\n var SelectTextToEscape = SB.GetStringFromName('SelectTextToEscape');\n\n var prompts = Components.classes[\"@mozilla.org/embedcomp/prompt-service;1\"]\n .getService(Components.interfaces.nsIPromptService);\n\n ko.views.manager.currentView.setFocus();\n ko.views.manager.currentView.scimoz.beginUndoAction();\n \n var SourceText = \"\";\n\n switch (Format) {\n case \"+\":\n var SourceText = ko.views.manager.currentView.scimoz.selText.replace(/\\+/g, \"\");\n break;\n \n case \"~\":\n var SourceText = ko.views.manager.currentView.scimoz.selText.replace(/\\~/g, \"\");\n break;\n \n case \"_\":\n var SourceText = ko.views.manager.currentView.scimoz.selText.replace(/\\_/g, \"\");\n break;\n \n default: \n var SourceText = ko.views.manager.currentView.scimoz.selText.replace(/\\+/g, \"\");\n break;\n }\n \n if (SourceText.length) {\n SourceText = Format + SourceText + Format;\n ko.views.manager.currentView.scimoz.replaceSel(SourceText);\n } else {\n prompts.alert(window, QPLWrapper, SelectTextToEscape);\n }\n\n ko.views.manager.currentView.scimoz.endUndoAction();\n\n return;\n\n}",
"enterUnescapedAnnotation(ctx) {\n\t}",
"function nqfParseChar() {\n if (escape) {\n value += curCh;\n escape = false;\n } else if (curCh === '\\\\') {\n escape = true;\n } else if (curCh === ',') {\n addValue();\n } else {\n value += curCh;\n }\n }",
"function show_char(c) /* (c : char) -> string */ {\n var _x24 = (((c < 0x0020)) || ((c > 0x007E)));\n if (_x24) {\n if ((c === 0x000A)) {\n return \"\\\\n\";\n }\n else {\n if ((c === 0x000D)) {\n return \"\\\\r\";\n }\n else {\n if ((c === 0x0009)) {\n return \"\\\\t\";\n }\n else {\n var _x25 = $std_core._int_le(c,255);\n if (_x25) {\n return ((\"\\\\x\") + (show_hex(c, 2, undefined, \"\")));\n }\n else {\n var _x26 = $std_core._int_le(c,65535);\n if (_x26) {\n return ((\"\\\\u\") + (show_hex(c, 4, undefined, \"\")));\n }\n else {\n return ((\"\\\\U\") + (show_hex(c, 6, undefined, \"\")));\n }\n }\n }\n }\n }\n }\n else {\n if ((c === 0x0027)) {\n return \"\\\\\\'\";\n }\n else {\n if ((c === 0x0022)) {\n return \"\\\\\\\"\";\n }\n else {\n return ((c === 0x005C)) ? \"\\\\\\\\\" : string(c);\n }\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This thread runs regardless of whether autosaving is enabled. mode = 'start' or 'stop' | function autosaveThread(mode) {
// Start/restart the wait.
if (mode === 'start') {
clearInterval(autosaveTimer);
autosaveTimer = setInterval(function(){ autosaveNotepad(); }, AUTOSAVE_SECONDS * 1000);
}
// Destroy the event.
else if (mode === 'stop') {
clearInterval(autosaveTimer);
}
} | [
"start() {\n if (!this.stop) return\n this.stop = false\n this.__poll()\n }",
"function run() {\n if (running) {\n // all times in msec\n // minimum time per frame for not exceeding the given fps speed\n // fps=60 means maximum speed\n const minimumFrameTime = 1000 / animation.fps - 1000 / 60;\n // do the current frame\n const startOfFrame = Date.now();\n advance();\n if (recorder.recording) {\n const filename = makeFilename();\n guiUtils.saveCanvasAsFile(output.canvas, filename, recorder.movieType,\n function() {\n const timeUsed = Date.now() - startOfFrame;\n // prepare next frame\n timeoutID = setTimeout(function() {\n requestAnimationFrame(run);\n }, minimumFrameTime - timeUsed);\n });\n } else {\n const timeUsed = Date.now() - startOfFrame;\n // prepare next frame\n timeoutID = setTimeout(function() {\n requestAnimationFrame(run);\n }, minimumFrameTime - timeUsed);\n }\n }\n}",
"start(){\n this.recording = true ;\n }",
"resume() {\n this.lastTime = performance.now();\n const _ = this;\n setInterval(_.update.bind(_), 1000/this.desiredFPS);\n }",
"loop() {\n clearTimeout(this.persistentLoop);\n // emit loop event to any active persistent tool\n EventBus.$emit(\"loop\", this.loopCount);\n\n // redraw canvas\n if (this.file && this.file.selectionCanvas) this.onRedrawCanvas();\n\n // increase loop iteration\n ++this.loopCount;\n\n // re-run persistence loop\n this.persistentLoop = setTimeout(() => this.loop(), 25);\n }",
"onInterval() {\n if (this.queue.length <= 0) {\n this.wait();\n return;\n }\n\n if (this.running) {\n const next = this.queue.dequeue();\n next.run();\n }\n }",
"function start(){\n\tAutofresh();\n}",
"start(){\n\t\t// Run immediately to avoid having to wait for the first timeout\n\t\tthis.onUpdate();\n\n\t\tvar updater = this.onUpdate.bind(this);\n\t\tthis.interval = setInterval(updater, this.updateInterval);\n\t}",
"function doRunButton(e) {\n if (state === 'running') {\n state = 'paused';\n clearInterval(timer);\n this.innerHTML = \"Run\";\n }\n else {\n state = 'running';\n this.innerHTML = \"Stop\";\n timer = setInterval(runBatch, 30);\n }\n}",
"function start() {\n // Disables the text area (place where the user provides input)\n $(\"txtarea_input\").disabled = true;\n \n // Enables the Stop button & disables the Start button\n disableBtn($(\"stop\"), false);\n disableBtn($(\"start\"), true);\n \n // Processes user input\n wordsList = processInput($(\"txtarea_input\").value);\n \n // Sets the timer (frame speed)\n var speed = changeSpeed(); // let the timer tick once\n timer = setInterval(readWordFramePerFrame, speed);\n }",
"startLoop() {\n clearTimeout(this.persistentLoop);\n this.persistentLoop = setTimeout(() => this.loop(), 25);\n }",
"function startGame()\n{\n if(mediaCount.image == 0 && mediaCount.audio==0 && canStart==1)\n {\n //Initiate the game\n gameRestart();//initiate the game\n\n //Start the game\n gameLoop();//this sets automatically the game looping\n //var interval = setInterval(gameLoop, 30); //runs gameLoop ciclicly\n }\n else\n {\n console.log(\"Wait for \" + (canStart==1?\"media\":\"Main\") );\n }\n}",
"startGame() {\n let self = this\n this.props.changeSetupConfigClass(\"setupconfig__holder setupconfig__holder__deactive\")\n setTimeout(()=>{\n self.props.changeResetCoords(true)\n self.props.changeMarkerCoords([0,0])\n self.props.changeResetCoords(false)\n self.props.changeActiveHandler(this.props.game.id, false, true)\n self.props.changeActiveState(this.props.game.id, true)\n }, 1600)\n }",
"resume() {\n this.paused_ = false;\n this.resetAutoAdvance_();\n }",
"function eventLoop() {\n\tgetState()\n\tif (++updateCount % 5 == 0) {\n\t\t$.post(\"/browse\", {method: \"get-queue-contents\"}, onQueue, \"json\");\n\t}\n}",
"function checkState() {\n \n \n if(currentState.running == false) {\n return;\n }\n \n // get request of the job information\n $.ajax({\n url: \"job?id=\" + currentState.currentId\n , type: \"GET\"\n\n , success: function (data) {\n \n currentState.running = data.finished !== true;\n currentState.ready = data.finished;\n currentState.status = data.status;\n currentState.fileName = data.fileName;\n if (currentState.running) {\n setTimeout(checkState, 1000);\n }\n updateView();\n } \n });\n}",
"start() {\n\n this.isPlaying = true; // set the 'playing' boolean to true\n\n this.playing = 0; // reset to the beginning\n this.playCurrent(); // start playing the current track\n }",
"function tooSoon(mode)\n\t{\n\t\tvar delay = capture.delay[mode] || 0;\n\t\tif (!delay) return false;\n\t\t\n\t\tvar queue = EZ.capture.get(mode);\n\t\tif (!queue || !queue[0]) return false;\n\t\t\n\t\tvar elapsed = new Date().getTime() - queue[0].getTime();\n\t\tif (delay > elapsed) return false;\n\t\t\t\n\t\tcounter = 'delay'\n\t\treturn true;\n\t}",
"playScheduler() {\n this.deselect();\n this.scheduler.play();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draws shapes to represent sound creates a 3 row repersentation based on what is the current shape being drawn will either display according to waveform data OR frequencey data | function drawSound(){
//drawCtx.clearRect(0, 0, drawCtx.canvas.width, drawCtx.canvas.height);
let circleWidth = 1;
let circleSpacing = 17.5;
let topSpacing = 130;
let currentHeight;
for(let i=0; i<audioData.length;i++){
if (playButton.dataset.playing == "yes") currentHeight = (topSpacing-60) + 256-audioData[i];
else if (currentHeight < (canvasElement.height - 65)) currentHeight + 5;
else currentHeight = canvasElement.height - 65;
drawCtx.save();
drawCtx.beginPath();
drawCtx.fillStyle = drawCtx.strokeStyle = makeColor(color.red, color.green, color.blue, color.alpha);
// draw appropriete shape
if(circle){
drawCtx.arc(i * (circleWidth + circleSpacing),currentHeight + 60, 5, 0, Math.PI * 2, false);
drawCtx.arc(i * (circleWidth + circleSpacing),currentHeight+30, 5, 0, Math.PI * 2, false);
drawCtx.arc(i * (circleWidth + circleSpacing),currentHeight, 5, 0, Math.PI * 2, false);
}
else if(triangle){
drawCtx.moveTo(i * (circleWidth + circleSpacing),currentHeight + 60);
drawCtx.lineTo(i * (circleWidth + circleSpacing) - 5,currentHeight + 60 - 10);
drawCtx.lineTo(i * (circleWidth + circleSpacing) + 5,currentHeight + 60 - 10);
drawCtx.moveTo(i * (circleWidth + circleSpacing),currentHeight+30);
drawCtx.lineTo(i * (circleWidth + circleSpacing) - 5,currentHeight+30 - 10);
drawCtx.lineTo(i * (circleWidth + circleSpacing) + 5,currentHeight+30 - 10);
drawCtx.moveTo(i * (circleWidth + circleSpacing),(currentHeight));
drawCtx.lineTo(i * (circleWidth + circleSpacing) - 5,currentHeight - 10);
drawCtx.lineTo(i * (circleWidth + circleSpacing) + 5,currentHeight - 10);
}
else if(square){
drawCtx.rect(i * (circleWidth + circleSpacing),currentHeight + 60, 5, 5);
drawCtx.rect(i * (circleWidth + circleSpacing),currentHeight+30, 5, 5);
drawCtx.rect(i * (circleWidth + circleSpacing),currentHeight, 5, 5);
}
else{
drawCtx.moveTo(i * (circleWidth + circleSpacing),currentHeight + 60);
drawCtx.lineTo(i * (circleWidth + circleSpacing),currentHeight + 70);
drawCtx.moveTo(i * (circleWidth + circleSpacing),currentHeight+30);
drawCtx.lineTo(i * (circleWidth + circleSpacing),currentHeight+40);
drawCtx.moveTo(i * (circleWidth + circleSpacing),currentHeight);
drawCtx.lineTo(i * (circleWidth + circleSpacing),currentHeight + 10);
drawCtx.stroke();
}
drawCtx.closePath();
drawCtx.fill();
drawCtx.restore();
}
} | [
"function createSpeakers(){\r\n drawCtx.strokeStyle = \"gray\";\r\n drawCtx.fillStyle = \"black\";\r\n\r\n drawCtx.lineWidth = 5;\r\n\r\n drawCtx.fillRect(50,100, 100,200);\r\n drawCtx.strokeRect(50,100, 100,200);\r\n drawCtx.strokeRect(50,100, 100,50);\r\n\r\n drawCtx.lineWidth = 3;\r\n drawCtx.beginPath();\r\n drawCtx.moveTo(50,100);\r\n drawCtx.lineTo(80,75);\r\n drawCtx.lineTo(180, 75);\r\n drawCtx.lineTo(150,100);\r\n drawCtx.fill();\r\n drawCtx.stroke();\r\n\r\n drawCtx.beginPath();\r\n drawCtx.moveTo(150,100);\r\n drawCtx.lineTo(180,75);\r\n drawCtx.lineTo(180,275);\r\n drawCtx.lineTo(150, 300);\r\n drawCtx.fill();\r\n drawCtx.stroke();\r\n \r\n drawCtx.lineWidth = 5;\r\n \r\n drawCtx.fillRect(450,100, 100,200);\r\n drawCtx.strokeRect(450,100, 100,200);\r\n drawCtx.strokeRect(450,100, 100,50);\r\n\r\n drawCtx.lineWidth = 3;\r\n drawCtx.beginPath();\r\n drawCtx.moveTo(550,100);\r\n drawCtx.lineTo(520,75);\r\n drawCtx.lineTo(420, 75);\r\n drawCtx.lineTo(450,100);\r\n drawCtx.fill();\r\n drawCtx.stroke();\r\n\r\n drawCtx.beginPath();\r\n drawCtx.moveTo(450,100);\r\n drawCtx.lineTo(420,75);\r\n drawCtx.lineTo(420,275);\r\n drawCtx.lineTo(450, 300);\r\n drawCtx.fill();\r\n drawCtx.stroke();\r\n \r\n drawCtx.lineWidth = 5;\r\n \r\n drawCtx.fillRect(237,85, 125,225);\r\n drawCtx.strokeRect(237,85, 125,225);\r\n drawCtx.strokeRect(237,85, 125,50);\r\n \r\n \r\n drawCtx.lineWidth = 3;\r\n drawCtx.beginPath();\r\n drawCtx.moveTo(237,85);\r\n drawCtx.lineTo(260,55);\r\n drawCtx.lineTo(340, 55);\r\n drawCtx.lineTo(362,85);\r\n drawCtx.fill();\r\n drawCtx.stroke();\r\n\r\n \r\n}",
"function drawShapes() {\n\tfor (var i = 0; i < shapes.length; i++) {\n\t\tvar points = shapes[i];\n\t\tdrawFinishedShape(points);\n\t}\n}",
"draw() {\n for (const waveform of this.waveforms) {\n this.drawInCanvas(waveform.canvas, waveform.samples);\n }\n }",
"function draw(numOfWaves, xOffset, yOffset, waveLength, waveHeight, circleSize, frequency, xSpacing, ySpacing, shiftX, shiftWave, color) {\n //wave shift start\n var shift = 0;\n //create waves\n while (numOfWaves > 0) {\n //set starting point\n var x = 0 + xOffset, y = 0 + yOffset;\n //length of waves\n while (x < waveLength) {\n //move to point\n ctx.moveTo(x,y);\n ctx.beginPath();\n //to do \\/ make arc great again (add more config possibilities)\n ctx.arc(x, y, circleSize, 0, 2 * Math.PI);\n ctx.fillStyle = \"hsla(\" + color[0] + \", \" + color[1] + \"%, \" + (color[2] + 1.3 * getY(x, frequency, waveHeight, shift)) + \"%, \" + color[3] + \")\";\n ctx.fill();\n y = getY(x, frequency, waveHeight, shift, yOffset);\n console.log(\"x = \" + x + \"; y = \" + getY(x, frequency, waveHeight, shift, yOffset));\n ctx.closePath();\n x += xSpacing;\n }\n shift += shiftWave;\n yOffset += ySpacing;\n xOffset -= shiftX;\n numOfWaves--;\n }\n}",
"function clearAndRedraw() {\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n\n for (let i = 0; i < shapes.length; i++) {\n shape = shapes[i];\n\n if (shape.r) {\n ctx.beginPath();\n ctx.strokeStyle = \"black\";\n ctx.lineWidth = 2;\n ctx.fillStyle = shape.color;\n ctx.arc(shape.x, shape.y, Math.abs(shape.r), 0, 2 * Math.PI);\n ctx.fill();\n ctx.stroke();\n } else if (shape.w) {\n drawRectangleBorder(shape.x, shape.y, shape.w, shape.h);\n\n ctx.fillStyle = shape.color;\n ctx.beginPath();\n ctx.rect(shape.x, shape.y, shape.w, shape.h);\n ctx.fill()\n } else {\n ctx.beginPath();\n ctx.lineWidth = 3;\n ctx.strokeStyle = shape.color;\n ctx.moveTo(shape.x, shape.y);\n ctx.lineTo(shape.lx, shape.ly);\n ctx.stroke();\n }\n }\n }",
"function drawbasiclayout()\n {\n points = []; // for storng title area points inorder\n linepoints = []; // for storing linegap points in discription area\n dispoints = []; // for storng title area points inorder\n\n // Initially titlearea and discriptionarea disabled\n titlekeyactive = false;\n diskeyactive = false;\n\n // Starting cursor positions for title and discription area\n pretitleposx = 0.25 * width;\n predisposx = 0.05 * width;\n pretitleposy = 0.7*0.1*height;\n predisposy = 0.3 * height;\n \n // Drawing Title , line and , Discription on each note \n ctx.clearRect(0,0,width,height);\n ctx.fillStyle = \"bisque\";\n ctx.fillRect(0,0,width,height);\n ctx.fillStyle = \"#141e30\";\n ctx.font = \"30px Pacifico\"; \n ctx.fillText(\"TITLE --\",4,0.7*0.1*height);\n ctx.beginPath();\n ctx.moveTo(0,0.12*height);\n ctx.lineTo(width,0.12*height);\n ctx.stroke();\n ctx.fillStyle='#141e30';\n ctx.font = \"30px Oleo Script\";\n ctx.fillText('DESCRIPTION' , 0.4*width , 0.17*height);\n }",
"drawSequence() {\n\n // chords which are used in the sequence (in the correct order!)\n this.chords = ['C', 'F', 'G', 'Am'];\n\n // get the current sequence\n this.sequence = this.musicMenu.getSequence();\n\n this.chordTexts = [];\n let chord;\n\n // draw each chord of the sequence\n for (let i in this.sequence) {\n\n chord = this.add.text(this.xStart + i * this.distance, this.yPosition, this.chords[this.sequence[i]], this.styles.get(7)).setOrigin(0.5);\n this.chordTexts.push(chord);\n\n }\n\n }",
"function createPitch() {\n ctx.beginPath();\n ctx.moveTo(boardWidth/2,0);\n ctx.lineTo(boardWidth/2,boardHeight);\n ctx.closePath();\n ctx.lineWidth = 8;\n ctx.strokeStyle = \"white\";\n ctx.stroke();\n\n ctx.beginPath();\n ctx.arc(boardWidth/2,boardHeight/2,2*step,0,Math.PI*2,true);\n ctx.stroke();\n \n function goalArea(x0,x1){\n ctx.beginPath();\n ctx.moveTo(x0,boardHeight/2-2*step);\n ctx.lineTo(x1,boardHeight/2-2*step);\n ctx.lineTo(x1,boardHeight/2+2*step);\n ctx.lineTo(x0,boardHeight/2+2*step);\n ctx.stroke();\n }\n\n goalArea(0,2*step)\n goalArea(boardWidth,boardWidth-2*step)\n\n function goalLine(x0,color){\n ctx.beginPath();\n ctx.moveTo(x0,boardHeight/2);\n ctx.lineTo(x0,boardHeight/2-step);\n ctx.lineTo(x0,boardHeight/2+step);\n ctx.strokeStyle = color;\n ctx.stroke();\n }\n\n goalLine(0,\"green\");\n goalLine(boardWidth,\"red\");\n\n function corners(x0,y0,direction){\n ctx.beginPath();\n ctx.arc(x0,y0,step/2,0,Math.PI*0.5,direction);\n ctx.strokeStyle = \"white\";\n ctx.stroke();\n }\n \n corners(0,0,false)\n corners(boardWidth,0,true)\n corners(0,boardHeight,true)\n corners(boardWidth,boardHeight,true)\n\n function semicircle(x0,direction){\n ctx.beginPath();\n ctx.arc(x0,boardHeight/2,step,Math.PI*0.5,Math.PI*1.5,direction);\n ctx.stroke();\n }\n \n semicircle(2*step,true)\n semicircle(boardWidth-2*step,false)\n }",
"draw() {\n this.context.clear();\n this.stave = this.drawStave();\n this.stave.draw();\n const notes = this.drawNotes(this.noteData);\n\n // eslint-disable-next-line new-cap\n this.VF.Formatter.FormatAndDraw(this.context, this.stave, notes);\n }",
"function draw(){\n\n mCanvas.background(255);\n drawBirdsGraphics();\n\n push();\n\n if(soundWater.isPlaying()){\n drawWaterGraphics();\n push(); \n }\n\n if(soundBell.isPlaying()){\n drawBellGraphics();\n push();\n }\n\n if(soundGlass.isPlaying()){\n drawGlassGraphics();\n push();\n }\n\n if(soundSeller.isPlaying()){\n drawSellerGraphics();\n push();\n }\n\n if(soundGong.isPlaying()){\n drawGongGraphics();\n push();\n }\n\n if(soundGuitar.isPlaying()){\n drawGuitarGraphics();\n push();\n }\n\n if(soundTrafficLight.isPlaying()){\n drawTrafficlightGraphics();\n push();\n }\n\n}",
"function drawWave() {\n requestAnimationFrame(drawWave);\n analyser.getByteTimeDomainData(dataArray);\n canvasCtx.fillStyle = \"rgb(0,0,0)\";\n canvasCtx.fillRect(0, 0, canvas.width, canvas.height);\n canvasCtx.lineWidth = 2;\n canvasCtx.strokeStyle = \"rgb(255,255,255)\";\n canvasCtx.beginPath();\n const sliceWidth = (canvas.width * 1.0) / bufferLength;\n let x = 0;\n for (let i = 0; i < bufferLength; i++) {\n let v = dataArray[i] / 128;\n let y = (v * canvas.height) / 2;\n if (i === 0) {\n canvasCtx.moveTo(x, y);\n } else {\n canvasCtx.lineTo(x, y);\n }\n x += sliceWidth;\n }\n canvasCtx.stroke();\n}",
"displayBrushers(){\r\n\r\n if(!this.audioAnalyser) return;\r\n\r\n this.audioAnalyser.analyser.getByteTimeDomainData(this.audioAnalyser.dataArray);\r\n\r\n let amout;\r\n for (let i = 0; i < this.audioAnalyser.bufferLength; i++) {\r\n\r\n\r\n amout = this.audioAnalyser.dataArray[i]/2;\r\n\r\n if(amout > 80 && Math.random()>0.85){\r\n\r\n if(this.popText[i] ){\r\n this.popText[i].color = `rgb(${this.rgb[0]}, ${this.rgb[1] } , ${this.rgb[2]})`;\r\n this.popText[i].isActif = true;\r\n } \r\n } \r\n\r\n if(amout > 70){\r\n \r\n if(Math.random()>0.995){\r\n this.rgb[0] = Math.floor(Math.random()* 200);\r\n this.rgb[1] = Math.floor(Math.random()* 200 );\r\n this.rgb[2] = Math.floor(Math.random()* 200 );\r\n this.currentVideo.rgb = this.rgb;\r\n \r\n }\r\n\r\n\r\n if(this.brushers[i] && !this.brushers[i].isActive ){\r\n\r\n this.brushers[i].start(); \r\n }\r\n \r\n }\r\n\r\n if(this.brushers[i]){\r\n this.brushers[i].draw();\r\n \r\n }\r\n\r\n if(this.popText[i] && this.popText[i].isActif) this.popText[i].draw();\r\n \r\n \r\n }\r\n\r\n }",
"function addNonBlinkingShapes() {\n // Start it out clean.\n ctx.clearRect(0, 0, corralWidth, corralHeight);\n clearInterval(shapeBlink);\n shapesWhite = false;\n\n // Draw the triangles.\n setTriangleStart();\n drawTriangles();\n}",
"function addTriangles(num) {\n var $viz = $('.audio-visualizer');\n var triangles = [];\n\n function addTriangle() {\n var t = $('<div>').addClass('audio-triangle');\n var color = kutility.randColor();\n var size = Math.floor(Math.random() * 60) + 20;\n\n var style = kutility.choice(triangleStyles);\n for (var i = 0; i < style.length - 1; i++) {\n t.css(style[i], size + 'px solid transparent');\n }\n t.css(style[style.length - 1], size + 'px solid ' + color);\n\n var left = Math.floor(Math.random() * ($(window).width() - 120)) + 20;\n var top = Math.floor(Math.random() * ($viz.height() - 120)) + 20;\n t.css('left', left + 'px');\n t.css('top', top + 'px');\n\n $viz.append(t);\n triangles.push(t);\n }\n\n for (var n = 0; n < num; n++) {\n setTimeout(function() {\n addTriangle();\n }, n * 75);\n }\n\n setTimeout(function() {\n var ti = 0;\n var remover = setInterval(function() {\n triangles[ti].remove();\n ti++;\n if (ti >= triangles.length)\n clearInterval(remover);\n }, 75);\n }, RECORD_TIME);\n}",
"drawNote() {\n push();\n colorMode(HSB, 360, 100, 100);\n stroke(this.color, 100, 100, 100);\n fill(this.color, 100, 100, 100);\n let v = this;\n let v2 = createVector(v.x + 5, v.y - 15);\n circle(v.x, v.y, 7);\n strokeWeight(3);\n line(v.x + 3, v.y, v2.x, v2.y);\n quad(v2.x, v2.y, v2.x + 5, v2.y + 2, v2.x + 6, v2.y, v2.x, v2.y - 2);\n pop();\n }",
"function visualize() {\n\n visualizer.updatePitchChart(audioProcessor.getPitches(), audioProcessor.getTimestamps());\n visualizer.updateRateChart(audioProcessor.getVibratoRates(), audioProcessor.getTimestamps());\n visualizer.updateWidthChart(audioProcessor.getVibratoWidths(), audioProcessor.getTimestamps());\n calcPitch();\n}",
"displayShapes() {\n // Displays shapes when the space bar is pressed\n if (keyIsDown(32)) {\n // If the central position of the shape is not given...\n if (this.positionIsGiven === false) {\n // Set it to the mouse position\n this.x = mouseX;\n this.y = mouseY;\n // And change state so the central position stays the same as long as the space bar is pressed\n this.positionIsGiven = true;\n }\n // If the central position is given...\n else if (this.positionIsGiven === true) {\n // Handle keys inputs to change the color of the stroke\n this.changeColor();\n // Play breath in sound when the width of the shape is increasing and oplay the breath out sound if the width is decreasing\n this.handleSound();\n // Change the size of the shape according to the mouse position\n this.changeSize();\n // Display the ellipse from the center, color the stroke with the rgb values and don't fill it\n ellipseMode(CENTER);\n stroke(this.red, this.green, this.blue);\n noFill();\n // Draw the ellipse\n ellipse(this.x, this.y, this.width, this.height);\n }\n }\n // If the space bar is released, change the state of positionIsGiven to false to be able to set a new position when we press space bar again\n else {\n this.positionIsGiven = false;\n }\n }",
"function peace(drawCtx,playButton,audioData,speaker,speaker2,disc,canvasElement){\n\t\t\tdrawCtx.save();\n\t\t\tdrawCtx.drawImage(speaker, 10,60,150,100);\n\t\t\tdrawCtx.drawImage(speaker2, canvasElement.width-165,60,150,100);\n\t\t\tlet xPos = 400;\n\t\t\tlet yPos = 400;\n\t\t\tfor(let i = 0; i < 7; i++){ // draw symbols from speakers\n\t\t\t\tdrawCtx.scale(.7,.7);\n\t\t\t\tif(i!=0 && i!=1&&playButton.dataset.playing == \"yes\"){\n\t\t\t\t\tlet moveX1 = audioData[10];\n\t\t\t\t\tdrawCtx.drawImage(disc, xPos, yPos,moveX1,moveX1);\n\t\t\t\t\tif(i==2)drawCtx.drawImage(disc, canvasElement.width+900, yPos,moveX1,moveX1);\n\t\t\t\t\tif(i==3)drawCtx.drawImage(disc, canvasElement.width+1800, yPos,moveX1,moveX1);\n\t\t\t\t\tif(i==4)drawCtx.drawImage(disc, canvasElement.width+3100, yPos,moveX1,moveX1);\n\t\t\t\t\tif(i==5)drawCtx.drawImage(disc, canvasElement.width+5000, yPos,moveX1,moveX1);\n\t\t\t\t\tif(i==6)drawCtx.drawImage(disc, canvasElement.width+7700, yPos,moveX1,moveX1);\n\t\t\t\t}\n\t\t\t\txPos+=100;\n\t\t\t\tyPos+=150;\n\n\t\t\t\t\n\t\t\t}\n\t\t\tdrawCtx.restore();\n\t\t}",
"function genpoly()\n\t\t{\n\t\t\tfind_coordinates(420,0,820,230,numberOfDivsion,1); \n\t\t\t//console.log(\"****************\");\n\t\t\tfind_coordinates(0,230,420,460,numberOfDivsion,0);\n\t\t\tdraw_polygon(m_context);\n\t\t\t//render(mycanvas_context);\n\t\t\tpush_into_stack();\n\t\t\tempty();\n\t\t\t//console.log(\"****************\");\n\t\t\tfind_coordinates(420,460,820,230,numberOfDivsion2,1); \n\t\t\t//console.log(\"****************\");\n\t\t\tfind_coordinates(0,230,420,0,numberOfDivsion2,0);\t\t\n\t\t\tdraw_polygon(m_context);\n\t\t\t//mycanvas_context.drawImage(m_canvas, 0, 0);\n\t\t\tpoint_store();\n \t\t\t//draw_triangles(m_context);\n\n \t\t\tvar triangle_upper_left_colour = $(data).find('triangle_upper_left_colour').text();\n \t\t\tdraw_triangles(m_context,triangle_upper_left_colour,0,0,100,0,0,100);\n\n \t\t\tvar triangle_lower_left_colour = $(data).find('triangle_lower_left_colour').text();\t\n \t\t\tdraw_triangles(m_context,triangle_lower_left_colour,0,460,90,460,0,370); \t\n\n \t\t\tvar triangle_lower_right_colour = $(data).find('triangle_lower_right_colour').text();\t\n \t\t\tdraw_triangles(m_context,triangle_lower_right_colour,820,460,720,460,820,370); \n\n \t\t\tvar triangle_upper_right_colour = $(data).find('triangle_upper_right_colour').text();\n \t\t\tdraw_triangles(m_context,triangle_upper_right_colour,820,0,730,0,820,90); \t\t\t \t\t\t\t\t\n\n\t\t\trender_user_interface();\n\n\t\t}"
] | {
"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.