query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Pings the server to wake it up and handle messages | function wakeUpServer() {
var h = require("http");
h.get(SERVER_URL);
} | [
"function ping() {\n primus.clearTimeout('ping').write('primus::ping::'+ (+new Date));\n primus.emit('outgoing::ping');\n primus.timers.pong = setTimeout(pong, primus.options.pong);\n }",
"function messageLoop()\r\n{\r\n\tvar timeNow = new Date();\r\n\tvar year = timeNow.getFullYear();\r\n\tvar month = timeNow.getMonth() + 1;\r\n\tvar day = timeNow.getDate();\r\n\tvar hour = timeNow.getHours();\r\n\tvar minute = timeNow.getMinutes();\r\n\tvar status = deviceState ? \"On\" : \"Off\";\r\n\tvar usage = deviceState \r\n\t\t? usageRating*(0.9 + 0.2*Math.random()) // If the device is on, run at usageRate with 10% variance\r\n\t\t: Math.random()/messageInterval; // Otherwise just simulate the IoT device requiring power\r\n\r\n\tintervalUsage += usage;\r\n\tsecondCount += 1;\r\n\tif (secondCount === messageInterval)\r\n\t{\r\n\t\tvar data = \r\n\t\t{\r\n\t\t\tyear: year,\r\n\t\t\tmonth: month,\r\n\t\t\tday: day,\r\n\t\t\thour: hour,\r\n\t\t\tminute: minute,\r\n\t\t\tdeviceId: deviceId,\r\n\t\t\tstatus: status,\r\n\t\t\tusage: intervalUsage.toFixed(2),\r\n\t\t}\r\n\t\r\n\t\tsendMessageToCloud(data);\r\n\r\n\t\tintervalUsage = 0;\r\n\t\tsecondCount = 0;\r\n\t}\r\n}",
"function startHeartbeats() {\n setInterval(() => {\n const heartbeatMessage = JSON.stringify({ type: \"heartbeat\" });\n for (var userWebId in socketsByWebId) {\n try {\n const socket = socketsByWebId[userWebId];\n socket.send(heartbeatMessage);\n } catch (err) {\n console.log(`ws>> Failed to send '${heartbeatMessage}' message to socket for ${userWebId}:`, err);\n }\n }\n }, 30000);\n}",
"maybeStartKeepalivePingTimer() {\n var _a, _b;\n if (!this.canSendPing()) {\n return;\n }\n if (this.pendingSendKeepalivePing) {\n this.pendingSendKeepalivePing = false;\n this.maybeSendPing();\n }\n else if (!this.keepaliveTimerId && !this.keepaliveTimeoutId) {\n this.keepaliveTrace('Starting keepalive timer for ' + this.keepaliveTimeMs + 'ms');\n this.keepaliveTimerId = (_b = (_a = setTimeout(() => {\n this.maybeSendPing();\n }, this.keepaliveTimeMs)).unref) === null || _b === void 0 ? void 0 : _b.call(_a);\n }\n /* Otherwise, there is already either a keepalive timer or a ping pending,\n * wait for those to resolve. */\n }",
"function sendIdle() {\r\n sendStatus(status = \"idle\");\r\n}",
"function ping() {\n rpc.tunnel.ping(function (err, _ts) {\n if (err) return console.error(err)\n clearTimeout(timer)\n timer = setTimeout(ping, 10e3)\n })\n }",
"function hangUp() {\n if (gPeerConnection == null)\n failTest('hanging up, but no call is active');\n sendToPeer(gRemotePeerId, 'BYE');\n closeCall();\n returnToPyAuto('ok-call-hung-up');\n}",
"function onSocketServerBusy(on) {\n this[owner_symbol][kServerBusy](!!on);\n}",
"[kServerBusy](on) {\n this.#serverBusy = on;\n process.nextTick(emit.bind(this, 'busy', on));\n }",
"function hangUp(){\r\n socket.emit(\"end\", ID, self);\r\n fetch(\"/end\", {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json'\r\n },\r\n body: JSON.stringify({\r\n ID: ID\r\n })\r\n }).then(response => {\r\n response.redirected;\r\n window.location.href = response.url;\r\n });\r\n}",
"sendLoop() {\n\n while (this.sends.length > 0) {\n // TODO: Need to actually do resends for my own packets. This is related\n // if (this.packetsSent > this.congestionWindow) break;\n let packet = this.sends.pop();\n\n this.packetsSent++;\n let index = this.sendMessageNumberIndex;\n this.sendMessageNumberIndex++;\n\n this.sendMessage(packet.packet, index, packet.reliability, packet.orderingIndex, undefined);\n }\n\n if(!this.acks.isEmpty()) {\n let send = new BitStream();\n send.writeBit(true);\n send.writeLong(this.remoteSystemTime);\n send.writeBitStream(this.acks.serialize());\n this.acks.empty();\n this.server.send(send.data, this.connection.port, this.connection.address);\n }\n }",
"markAlive()\n\t{\n\t\tif ( ! this.m_bAlive )\n\t\t{\n\t\t\tthis.m_bAlive = true;\n\t\t\tthis.emit( 'peer_alive' );\n\t\t}\n\t}",
"recv_hello (h, info) {\n if (info.address) {\n this.address = info.address\n }\n clearTimeout(this.dropConnectionTimer)\n }",
"function heartbeat() {\n for (var key in this._nodes) {\n var node = this._nodes[key];\n\n // ensure more` than a second has elapsed since the last send. this works\n // because this use of hrtime returns a tuple of [seconds, nanoseconds] and\n // if the seconds field is non-zero it will evaluate to true. also ensure\n // there's actually a node and that the node is connected\n if (process.hrtime(node.lastSend)[0] && node && node.stream) {\n heartbug(this.id, 'hearbeat to', key);\n // node.stream.conn.write('true\\r\\n');\n\n node.stream.send({ $masterless: { heartbeat: true } });\n }\n }\n}",
"function flushPings() {\n var sqldata = 'DELETE FROM app_clients WHERE lastping < (UNIX_TIMESTAMP() - 600)';\n pool.getConnection(function(err, connection) {\n connection.query(sqldata, [ip, GetUnixTimestamp(), GetUnixTimestamp()], function(err, results) {\n console.log('Query: Flush Clients');\n console.log('Result: ' + JSON.stringify(results) + ' Error: '+err);\n if (!err) {\n return results;\n } else {\n return \"Fehler: \" + err;\n }\n });\n // And done with the connection.\n connection.release(); \n });\n }",
"function doHangupAll() {\n debug.log('doHangupAll()');\n if (MSG_DO_HANGUP_ALL) { wrtcChat.addSystem(MSG_DO_HANGUP_ALL); }\n\n peerConnections.hangupFromLocalAll();\n\n // Если больше соединений не осталось, завершим локальное видео\n if ( FLAG_STOP_LOCAL_ON_NO_REMOTE && remoteVideos.count() === 0) {\n doHangupLocalMedia();\n }\n\n setHangupStates();\n}",
"start() {\n if (!this.stop) return\n this.stop = false\n this.__poll()\n }",
"sendQueuedRequests() {\n this._startTimer();\n }",
"_startPingInterval () {\n const setPongTimeout = () => {\n this._pongTimeout = setTimeout(\n () => this._reconnect(),\n this._options.pongTimeout\n )\n }\n\n this._pingInterval = setInterval(\n () => {\n this.ping()\n setPongTimeout()\n },\n this._options.pingInterval\n )\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
define the function to return custom filter | function customFilterFactory(){
return function(input){
//change input
return 'customFilter applied';
}
} | [
"function custom1FilterFactory(){\n //this filter will take extra argument:arg1 along with the input on which this filter works on.\n return function(input,arg1){\n //change input\n return 'customFilter applied from html with '+ arg1 ;\n }\n }",
"createEffect() {\n return new FilterEffect()\n }",
"function createFilterFor(query) {\n var lowercaseQuery = angular.lowercase(query);\n\n return function filterFn(item) {\n var toMatch = angular.lowercase(item.name);\n\n return (toMatch.indexOf(lowercaseQuery) !== -1);\n };\n }",
"function createGreaterThanFilter(base) {\n // YOUR CODE BELOW HERE //\n //I: base (value could be string or number)\n //O: return number > base return true, else false\n //O: return string > base return true, else false\n //Need to compare if the typeof parameter(base) is a number or string\n //If it is, if needs to return a function \n \n if (typeof base === 'number') {\n return numberFunction;\n } \n \n if (typeof base === \"string\") {\n return stringFunction;\n }\n \n //Create function to compare the base with a number. If base is less than the \n //number, return true. Else, return false.\n function numberFunction(num) {\n \n if (base < num) {\n return true;\n } else {\n return false;\n }\n };\n \n //Create function to compare base with a string. If base is less than string,\n //return true. Else, return false.\n \n function stringFunction(string) {\n \n if (base < string) {\n return true;\n } else {\n return false;\n }\n };\n \n \n \n \n // YOUR CODE ABOVE HERE //\n}",
"applyNodeFilters(name: string, node: NodeInterface): NodeInterface {\n return this.filters.reduce((nextNode, filter) => {\n // Allow null to be returned\n if (nextNode && typeof filter.node === 'function') {\n return filter.node(name, nextNode);\n }\n\n return nextNode;\n }, node);\n }",
"getBackendFilter() {\n const { filter } = this.props;\n const b = this.mappedFilter();\n return {\n back: b,\n front: filter,\n };\n }",
"function createLessThanFilter(base) {\n // YOUR CODE BELOW HERE //\n if (typeof base === \"string\"){\n return function testString(input){\n if(base.localeCompare(input) === -1){return false;}\n else if (base.localeCompare(input)=== 1){return true;}\n };\n } else if (typeof base === 'number'){\n return function testNumber(input){\n if (base > input){return true;}\n else if(base < input){return false;}\n };\n } else {\n console.log('Error: Enter correct data type / \"string\" or a \"number\"');\n }\n \n \n \n // YOUR CODE ABOVE HERE //\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 createLessThanFilter(base) {\n // YOUR CODE BELOW HERE //\n //I: base (value could be string or number)\n //O: return typeOf number < base\n //O: return typeOf string < base\n \n //Compare the typeof base with number. If it is a number, return \n //lessThanNumber function\n \n if (typeof base === \"number\") {\n return lessThanNumber;\n }\n \n //Compare the typeof base with string. If it is a string, return\n //lessThanString function\n if (typeof base === \"string\") {\n return lessThanString;\n }\n \n //Create a function that compares if the number is less than the base. If yes,\n //return true. Else, return false.\n \n function lessThanNumber(number) {\n if (base > number) {\n return true;\n } else {\n return false;\n }\n };\n \n //Create a function that compares if the string is less than the base. If yes,\n //return true. Else, return false.\n \n function lessThanString(string) {\n if (base > string) {\n return true;\n } else {\n return false;\n }\n };\n \n \n // YOUR CODE ABOVE HERE //\n}",
"eth_newFilter(filter) {\n return this.request(\"eth_newFilter\", Array.from(arguments));\n }",
"filter (p) {\n return filter(p, this)\n }",
"filterSubLayer(context) {\n return true;\n }",
"filter(fn) {\n let newSet = new SpecialSet();\n // copy over elements that pass the filter\n for (let item of this) {\n if (fn(item) === true) {\n newSet.add(item);\n }\n }\n return newSet;\n }",
"function createStartsWithFilter(startsWith) {\n // YOUR CODE BELOW HERE //\n // I = string character\n // O = function that returns Boolean\n // if else conditional to see if first letter of string === startsWith arg\n // find value of first letter of newString using charAt() method\n // use .toLowerCase string method on both arguments so that strict equality gives desired result\n return function(newString) {\n if (newString.charAt(0).toLowerCase() === startsWith.toLowerCase()) {\n return true;\n } else {\n return false;\n }\n \n }\n \n // YOUR CODE ABOVE HERE //\n}",
"'css.chunk.conditionalFilter'(obj, defaultString) {\n return defaultString\n }",
"function filter_wrapper(filter_obj,meta_switch){\r\n\r\n // fetch filter inputs from the html user interface\r\n var age_from_val = +document.getElementById(\"FROM\").value;\r\n var age_to_val = +document.getElementById(\"TO\").value;\r\n var sex_val = document.getElementById(\"btn_sex\").value;\r\n var nationality_val = document.getElementById(\"btn_nationality\").value;\r\n var bmi_val = document.getElementById(\"btn_bmi\").value;\r\n\r\n //fetch sort order from html user interface\r\n var sort_val = document.getElementById(\"btn_sortby\").value;\r\n\r\n //fetch column sort string from hrml user interface\r\n var keep_cols = document.getElementById(\"COLS\").value;\r\n\r\n //calculte the SampleID-lists from the fetched filteres\r\n var age_filter = filter_obj.generic_filter(\"Age\",[age_from_val,age_to_val])\r\n var sex_filter = filter_obj.generic_filter(\"Sex\",sex_val)\r\n var nationality_filter = filter_obj.generic_filter(\"Nationality\",nationality_val)\r\n var bmi_filter = filter_obj.generic_filter(\"BMI_group\",bmi_val)\r\n\r\n //calculate intersection of the previously generated SampleID lists\r\n var filtered_objects = filter_obj.intersection([age_filter,sex_filter,nationality_filter,bmi_filter])\r\n\r\n //sort the samples by the fetched sort logic (only if not in PCoA mode)\r\n if(!(meta_switch === \"pcoa\")){\r\n filtered_objects = filtered_objects.sort(sort_by(sort_val))\r\n }\r\n\r\n //generate Array for filtering of columns\r\n var bool_array = generate_bool_array(keep_cols)\r\n\r\n var filter_sampleIDs = []\r\n filtered_objects.forEach(function(elem){\r\n filter_sampleIDs.push(elem.SampleID)\r\n })\r\n\r\n //depending on the use case calculate the final dataset\r\n switch (meta_switch) {\r\n case \"Data\":\r\n var filtered_data = filter_obj.filter_data(filter_sampleIDs,bool_array)\r\n return filtered_data\r\n break;\r\n case \"Meta\":\r\n var filtered_data = filter_obj.filter_metadata(filter_sampleIDs)\r\n return filtered_data\r\n break;\r\n case \"pcoa\":\r\n var filtered_data = filter_obj.filter_data(filter_sampleIDs)\r\n var filtered_meta_data = filter_obj.filter_metadata(filter_sampleIDs)\r\n filtered_data[\"metadataOverview\"] = filtered_meta_data\r\n return filtered_data\r\n break;\r\n default:\r\n var filtered_data = filter_obj.filter_data(filter_sampleIDs)\r\n return filtered_data\r\n\r\n }\r\n\r\n}",
"apply_filters() {\n return this.data\n .filter(d => this.selected_towns[d.town])\n .filter(d => this.selected_categories[d.object_category])\n .filter(d => d.date_full >= this.selected_start && d.date_full <= this.selected_end);\n }",
"function filtro1(){\n $('#foto').html( '<img src=\"'+im+'\" id=\"foto_filtro\"/>');\n Caman('#foto_filtro', function () {\n this.greyscale();\n this.contrast(5);\n this.noise(3);\n this.sepia(100);\n this.channels({red:8,blue:2,green:4});\n this.gamma(0.87);\n this.render();\n });\n}",
"function Filter(props) {\n return __assign({ Type: 'AWS::GuardDuty::Filter' }, props);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
convert an epoch timestamp into a calendar object with the given offset | function tsToObj(ts, offset) {
ts += offset * 60 * 1000;
var d = new Date(ts);
return {
year: d.getUTCFullYear(),
month: d.getUTCMonth() + 1,
day: d.getUTCDate(),
hour: d.getUTCHours(),
minute: d.getUTCMinutes(),
second: d.getUTCSeconds(),
millisecond: d.getUTCMilliseconds()
};
} | [
"function epochToDate(epoch) {\n const date = new Date(0)\n date.setUTCSeconds(epoch)\n return date\n}",
"function dateToEpoch(date) {\n return date.getTime() / 1000\n}",
"function getDay(offset) {\n var d = new Date();\n return new Date(d.setDate(d.getDate() + offset)).setHours(0,0,0,0);\n}",
"function unixTimestampToDate(timestamp) {\n return new Date(timestamp * 1000);\n}",
"function makeAs(input, model) {\n return model._isUTC ? moment(input).zone(model._offset || 0) :\n moment(input).local();\n }",
"function offsetTime(time) {\n if (Number.isInteger(time)) {\n offset = time;\n }\n return offset;\n }",
"function epochToHours(date) {\n\t\t date = new Date(date * 1000);\n\t\t var hours = date.getHours();\n\t\t var minutes = date.getMinutes();\n\t\t var ampm = hours >= 12 ? 'PM' : 'AM';\n\t\t hours = hours % 12;\n\t\t hours = hours ? hours : 12; // the hour '0' should be '12'\n\t\t minutes = minutes < 10 ? '0'+minutes : minutes;\n\t\t var strTime = hours + ':' + minutes + ' ' + ampm;\n\t\t return strTime;\n\t\t}",
"function makeDate(min, sec) {\n return new Date(Date.UTC(1970, 0, 1, 0, min, sec));\n }",
"function calculateDay(someDate, offsetInDays) {\n var offsetInMillis = offsetInDays * ONE_DAY;\n return new Date(someDate.getTime() + offsetInMillis);\n}",
"static async incrementEpoch() {\n try {\n await db.incr('epoch', 1);\n } catch (err) {\n throw new Error(`system db: error when incrementing epoch! ${err}`);\n }\n }",
"scale(time) {\n const dateOffsetMilli = this.dateOffset.getTime();\n const timeOffsetMilli = this.timeOffset\n .scale(this.scaleFactor).milliseconds;\n const newMilli = time.scale(this.scaleFactor).milliseconds;\n\n return new Date(dateOffsetMilli + timeOffsetMilli + newMilli);\n }",
"function fromUnixToNatural(timestamp){\n var naturalDate = new Date(timestamp*1000).toString();\n naturalDate = naturalDate.split(\" \");\n naturalDate = months[naturalDate[1]] +\" \"+naturalDate[2]+ \", \"+ naturalDate[3];\n return naturalDate;\n}",
"function fetchMatchDate(matchObj)\n{\n const TIME_EPOCH = matchObj.start_time;\n var date = new Date(0);\n date.setUTCSeconds(TIME_EPOCH);\n return date;\n}",
"function getEndOfDayOfDate(unixTimestamp)\n{\n var date = new Date(unixTimestamp * 1000);\n date.setHours(23);\n date.setMinutes(59);\n date.setSeconds(59);\n \n return date.getTime() / 1000;\n}",
"browser_timezone_offset(minute_offset) {\n const offset_string = (minute_offset / -60).toString()\n\n var sign;\n var hours;\n\n if (offset_string.includes(\".\")) {\n throw \"Critter4Us doesn't work in timezones a fractional hour away from UTC\";\n }\n\n if (offset_string.slice(0, 1) == \"-\") {\n sign = \"-\";\n hours = offset_string.slice(1);\n } else {\n sign = \"+\";\n hours = offset_string;\n }\n\n if (hours.length == 1) {\n hours = \"0\" + hours;\n }\n\n return sign + hours + \":00\";\n }",
"function getOnsetAsUTC(obs, localdate) {\n //return new Date(localdate.getTime() - obs.offsetFrom);\n return localdate - obs.offsetFrom;\n }",
"constructor() {\n super(expressionType_1.ExpressionType.FormatEpoch, FormatEpoch.evaluator(), returnType_1.ReturnType.String, FormatEpoch.validator);\n }",
"function idAppointment2Day(id){\n let dateList = id.split(\"-\");\n return new Date(dateList[4], dateList[5]-1, dateList[6]);\n}",
"function calcOffset() {\n var serverTime = $.cookie('serverTime');\n serverTime = serverTime == null ? null : Math.abs(serverTime);\n var clientTimeOffset = (new Date()).getTime() - serverTime;\n $.cookie('clientTimeOffset', clientTimeOffset);\n}",
"function objectIdWithTimestamp(timestamp) {\n // Convert string date to Date object (otherwise assume timestamp is a date)\n // if (typeof timestamp == \"string\") {\n // timestamp = new Date(timestamp);\n // }\n\n logger.log({ timestamp });\n\n // Convert date object to hex seconds since Unix epoch\n var hexSeconds = Math.floor(timestamp / 1000).toString(16);\n logger.log({ hexSeconds });\n // Create an ObjectId with that hex timestamp\n var constructedObjectId = mongoose.Types.ObjectId(\n hexSeconds + \"0000000000000000\"\n );\n logger.log({ constructedObjectId });\n\n return constructedObjectId;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
deletes the selected file from local storage | function removeFile() {
var listbox = document.getElementById("mySavedFiles2");
// get selected filename
var fileName = undefined;
for (var i = 0; i < listbox.options.length; i++) {
if (listbox.options[i].selected) fileName = listbox.options[i].text; // selected file
}
if (fileName !== undefined) {
// removes file from local storage
window.localStorage.removeItem(fileName);
// the current document remains open, even if its storage was deleted
}
closeElement("removeDocument");
} | [
"function handleDeleteUpload() {\n setFiles([])\n deleteFile(document)\n handleDocumentDelete(document)\n fileInputField.current.value = null\n }",
"remove () {\n removeFile(this._filePath)\n }",
"function removeMediaFile() {\n vm.modelContentNew.mediaFile = null;\n }",
"vaciarLocalStorage() {\n localStorage.clear();\n }",
"function clearStorage() {\n Object.keys(localStorage).filter(function (key) {\n return key.startsWith(options.name);\n }).forEach(function (key) {\n return localStorage.removeItem(key);\n });\n}",
"function deleteExtensionStorage() {\n var deleteStorageContent = document.getElementById(\"deleteExtStorage\");\n deleteExtStorage.addEventListener(\"click\", function() {\n chrome.storage.local.clear();\n location.reload();\n });\n}",
"function doDeleteFromSaveFile(sel) {\n // if we have an open record in the editor\n if (Ext.get('marceditor').isVisible() ){\n try {\n var id = currOpenRecord;\n db.execute(\"update Records set savefile = null where id = ?\", [id]);\n }\n catch(ex) {\n Ext.Msg.alert('Error', 'db error: ' + ex.message);\n }\n displaySaveView();\n }\n // if records have been dropped onto the trash icon\n else if( sel ) {\n for( var i = 0; i < sel.length; i++) {\n var id = sel[i].data.Id;\n try {\n db.execute(\"update Records set savefile = null where id = ?\", [id]);\n }\n catch(ex) {\n if(bibliosdebug){console.error('db error: ' + ex.message);}\n }\n }\n showStatusMsg(\"Deleted \"+ sel.length + \" record(s).\");\n\tclearStatusMsg();\n // redisplay current savefile (to show moved record)\n var currentNode = folderTree.getSelectionModel().getSelectedNode();\n displaySaveFile(currentNode.attributes.savefileid, currentNode.text);\n displaySaveView();\n }\n}",
"function removeLocalFile(file) {\n var q = $q.defer();\n\n $cordovaFile.checkFile(file).then(function() {\n $cordovaFile.removeFile(file).then(q.resolve);\n }, q.resolve);\n\n return q.promise;\n }",
"function clearInputValue() {\n let input = document.getElementById(\"fileSelector\");\n input.value = \"\";\n}",
"static delete (targetPath, onComplete) {\n fs.unlink(targetPath, function (err) {\n if (err) {\n return logging.logger.error(`AssetManager: Failed to delete ${targetPath}, reason ${err.message}`, err);\n }\n logging.logger.info(`AssetManager: Deleted ${targetPath}`);\n if (onComplete) onComplete();\n });\n }",
"function deleteFile() {\r\n\t\tif(!keepTmpFile) {\r\n\t\t\tfs.unlink(tmpFilePath, function() {});\r\n\t\t}\r\n\t}",
"function reset_upload_button() {\n $('#modal-upload-file').modal('hide');\n $('#modal-upload-file-button').button('reset');\n }",
"function emptyFavorite() {\n $(\"#favorites\").empty();\n localStorage.clear();\n }",
"deleteTasks(){\n\t\tlocalStorage.clear();\n\t}",
"function removeOldFileSelections(){\n\t\tvar filenames = document.getElementsByClassName(\"choose-file\");\n\t\tfor (var i = 0; i < filenames.length; ++i){\n\t\t\tfilenames[i].value = \"\";\n\t\t}\n\t}",
"function clear() {\n localStorage.clear();\n location.reload();\n}",
"function vaciarCarritoLS(){\r\n localStorage.removeItem('cursos');\r\n}",
"function clearFileAsync() {\n // TODO: set to nil if nillable\n om.setNodeValueAsync(field.getNode(), \"\");\n return field.setValueAsync('');\n }",
"delete(event) {\n event.preventDefault()\n if (this.onDelete == \"reload\") {\n this.reload(event)\n } else {\n const item = event.target.closest(\"[data-target*='pshr-uploads.item']\")\n item.parentNode.removeChild(item)\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
search for last name in database takes last name to be searched for | function searchDatabaseLast(lastNameFind) {
// for each person in array
for (let people = 0; people < users.length; people++) {
// if current person's last name matches last name to be found
if (users[people].lastName.toLowerCase() === lastNameFind.toLowerCase()) {
// return true
return true;
}
}
// if nothing found, return false
return false;
} | [
"function searchDatabaseFirst(firstNameFind) {\n for (let people = 1; people < users.length; people++) {\n if (users[people].firstName.toLowerCase() === firstNameFind.toLowerCase()) {\n return true;\n }\n }\n return false;\n}",
"static async findProfile(string){\n const result=await pool.query(\"select *,LOWER(fname),INSTR(LOWER(fname),?) FROM student,studdata WHERE INSTR(LOWER(fname),?)>0 AND student.email=studdata.email ORDER BY INSTR(LOWER(fname),?);\",[string,string,string]);\n return result;\n }",
"static async exists (name, last_name) {\n name = name.toUpperCase();\n last_name = last_name.toUpperCase();\n const author = await Author.findOne({ where: { name, last_name }});\n if (author) {\n return author.dataValues.id_author;\n } else {\n return null;\n }\n }",
"function validateLastName() {\n return checkPersonalInfo(\"last-name\", \"Last name must have at least 3 characters\");\n}",
"function getLastNames() {\n return _.map(users, function (user) {\n return _.split(user.name, ' ')[1];\n })\n}",
"getNames( fullName ) {\n \"use strict\";\n // Return firstName, middleName and lastName based on fullName components ([0],[1],[2])\n }",
"searchUserByName(name) {\n const users = this.getUsers(); //Returns the collection of Users\n\n //Filter each user name based on the name we are interested in.\n const results = users.filter(\n user => user.firstName === name || user.lastName === name\n );\n\n return results.length === 0 ? false : results; //Returns false if no result found else returns true\n }",
"static async findCollege(string){\n const result=await pool.query('SELECT *,LOWER(collegename),INSTR(LOWER(collegename),?) FROM college WHERE INSTR(LOWER(collegename),?)>0 ORDER BY INSTR(LOWER(collegename),?)',[string,string,string]);\n return result;\n }",
"function getMiddleName(fullName) {\n fullName = fullName.trim();\n fullName = fullName.split(\" \");\n\n // console.log(fullName)\n if (fullName.length > 2) {\n middleName = fullName[1];\n // middleName = student.fullName.substring(0, 1).toUpperCase() + student.fullName.substring(1).toLowerCase();\n\n // console.log(middleName)\n }\n // console.log(middleName)\n // if (middleName.includes(\" \") == true) {\n // middleName = student.middleName.substring(0, 1).toUpperCase() + student.middleName.substring(1).toLowerCase();\n else {\n middleName = \" \";\n }\n\n return middleName;\n}",
"function printSurnameIndex()\n{\n\tif (Dwr.search.Ndx >= 0)\n\t{\n\t\tvar html = '';\n\t\tif (N(Dwr.search.Ndx, 'persons').length == 0)\n\t\t{\n\t\t\thtml += '<p>' + _('No matching surname.') + '</p>';\n\t\t}\n\t\telse if (N(Dwr.search.Ndx, 'persons').length == 1)\n\t\t{\n\t\t\twindow.location.replace(indiHref(N(Dwr.search.Ndx, 'persons')[0]));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvar txt = htmlPersonsIndex(N(Dwr.search.Ndx, 'persons'));\n\t\t\thtml +=\n\t\t\t\t'<h2 class=\"page-header\">' +\n\t\t\t\t(N(Dwr.search.Ndx, 'surname') || empty(_('Without surname'))) +\n\t\t\t\t'</h2>' +\n\t\t\t\ttxt;\n\t\t}\n\t\treturn html;\n\t}\n\telse\n\t{\n\t\treturn printSurnamesIndex();\n\t}\n}",
"function customerHasValidLastName (cust) {\n return typeof cust === 'string' && cust !== '' && cust.length < 501;\n}",
"function sortByLname() {\n if (allNames !== null && allNames.length > 0) {\n allNames.sort((a, b) => {\n var valA = a.surname.toLowerCase();\n var valB = b.surname.toLowerCase();\n\n var secA = a.name.toLowerCase();\n var secB = b.name.toLowerCase();\n\n if (valA < valB) return -1;\n if (valA > valB) return 1;\n\n if (secA < secB) return -1;\n if (secA > secB) return 1;\n\n return 0;\n });\n search();\n }\n}",
"function getEmployees(name_part){\n let emps = employees.filter(function(emp){\n return emp.first_name.toLowerCase().startsWith(name_part.toLowerCase()); \n })\n displayEmployees(emps);\n}",
"function getDBUserNames ( )\n {\n\tif ( api_data.user_names ) return;\n\t\n\tapi_data.user_names = entererNames();\n\tapi_data.valid_name = { };\n\tapi_data.user_match = [ ];\n\tapi_data.user_matchinit = [ ];\n\t\n\t// The names might be either in the form \"last, first\" or \"first last\". We have to check\n\t// both patterns. We add the object 'valid_name', whose properties include all of the\n\t// valid names in the form \"first last\" plus all last names.\n\t\n\tfor ( var i = 0; i < api_data.user_names.length; i++ )\n\t{\n\t var match;\n\t \n\t if ( match = api_data.user_names[i].match(patt_name) )\n\t {\n\t\tapi_data.valid_name[match[1]] = 1;\n\t\tvar rebuilt = match[2].substr(0,1) + '. ' + match[1];\n\t\tapi_data.valid_name[rebuilt] = 1;\n\t\tapi_data.user_names[i] = rebuilt;\n\t\tapi_data.user_match[i] = match[1].toLowerCase();\n\t\tapi_data.user_matchinit[i] = match[2].substr(0,1).toLowerCase();\n\t }\n\t \n\t else if ( match = api_data.user_names[i].match(patt_name2) )\n\t {\n\t\tapi_data.valid_name[match[2]] = 1;\n\t\tvar rebuilt = match[1].substr(0,1) + '. ' + match[2];\n\t\tapi_data.valid_name[rebuilt] = 1;\n\t\tapi_data.user_names[i] = rebuilt;\n\t\tapi_data.user_match[i] = match[2].toLowerCase();\n\t\tapi_data.user_matchinit[i] = match[1].substr(0,1).toLowerCase();\n\t }\n\t}\n }",
"function getLastWord() {\n console.log(\"get last word start\");\n var lastWord = \"\";\n \n var input = document.getElementById(\"searchInput\").value;\n \n var parsedInput = input.substr(0, input.length).replace(/[.,\\/#!$%\\^&\\*;:{}=\\-_`~()]/g, \"\");\n \n if (/\\S/.test(parsedInput)) {\n \n lastWord = parsedInput.split(\" \").pop();\n }\n\n /* Return the word */\n console.log(\"get last word end\");\n return lastWord;\n}",
"searchOnChange(event) {\n const search = event.target.value.toLowerCase();\n\n const searchResults = names.filter( (val, index) => val.name.toLowerCase().startsWith(search) );\n const totalResults = searchResults.length;\n\n if (totalResults >= 1 && totalResults < names.length) {\n this.setState({\n totalResults: totalResults,\n matchFound: true,\n bestMatch: searchResults[0]\n });\n } else {\n this.setState({\n totalResults: totalResults,\n matchFound: false,\n bestMatch: null\n });\n }\n }",
"function findfullName() {\n console.log('\\n\\n======================================================================================');\n console.log('Return full name of employee:');\n console.log(\"======================================================================================\");\n for (var _i = 0, emp_1 = exports.emp; _i < emp_1.length; _i++) {\n var fullName = emp_1[_i];\n // var fname = fullName.firstname;\n // var lname = fullName.lastname;\n // var wholeName = `${fname} ${lname}`;\n // return wholeName;\n var fname = fullName.firstname;\n var lname = fullName.lastname;\n console.log(fname + \" \" + lname);\n // var empfullname = fullName.firstname +\" \"+fullName.lastname;\n // console.log(empfullname);\n }\n}",
"validate(name, callback){\n let sql = \"SELECT admin FROM users WHERE username=$name\";\n this.db.all(sql, {\n $name: name\n }, (err, rows) => {\n if(err) {\n throw(err);\n }\n if(rows.length != 0) {\n return callback(rows[0].admin);\n }\n });\n }",
"function subtest_persist_name_in_search_field_part_2(w) {\n mc.waitFor(() => w.e(\"name\").value == NAME);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the Date of yesterday | function yesterday() {
var curLocDate = new Date();
curLocDate.setDate(curLocDate.getDate() - 1);
return curLocDate;
} | [
"function getYesterdaysDate() {\n var date = new Date();\n date.setDate(date.getDate()-1);\n return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();\n}",
"function getPreviousSunday(date) {\n // Using midday avoids any possibility of Daylight Savings Time (DST) messing things up\n var midday = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 12, 0, 0);\n var previousSunday = new Date(midday.getTime() - date.getDay() * DateConstants.MILLIS_PER_DAY);\n return newMidnightDate(previousSunday.getFullYear(), previousSunday.getMonth(), previousSunday.getDate());\n }",
"function getDebeDate() {\n let date = new Date();\n \n if(date.getUTCHours() < 4) {\n date.setDate(date.getDate() - 1);\n }\n return date.toJSON().split(\"T\")[0]\n}",
"function obtener_fecha_hoy() {\n return new Date();\n}",
"lastMonday(value){\r\n\t\tlet date = new Date();\r\n\t\tif(value) date = new Date(value);\r\n\t\tdate.setDate(date.getDate() - (date.getDay() + 6) % 7);\r\n\t\tconst day = (\"0\" + date.getDate()).slice(-2);\r\n\t\tconst month = (\"0\" + (date.getMonth() + 1)).slice(-2);\r\n\t\tdate = date.getFullYear()+\"-\"+(month)+\"-\"+(day) ;\r\n\t\treturn date;\r\n\t}",
"function LastLastSunday(){\r\n var d = new Date();\r\n d.setDate(d.getDate() - d.getDay() - 7);\r\n return d.getDate();\r\n}",
"function dateReset() {\n var date = new Date();\n document.write(\"Current date \"+ date);\n var hr = date.getHours();\n date.setHours(hr-1);\n document.write(\"<br> 1 hour ago, it was \"+ date);\n}",
"function minusDays(date, days){\n let result = new Date(date);\n result.setTime(result.getTime() - days * 86400000);\n return result;\n }",
"static today() {\n return NepaliDate.fromgregorian(new Date());\n }",
"findLastMonday() {\n let prevMonday = new Date();\n prevMonday.setDate(prevMonday.getDate() - ((prevMonday.getDay() + 6) % 7));\n return prevMonday;\n }",
"function getReportPreviousStartDate(reportNextStartDate, daysPrior)\n{\n let dateParts = reportNextStartDate.split('-');\n var setreportPreviousStartDate = new Date(dateParts[0], dateParts[1]-1, dateParts[2]);\n var reportPreviousStartDate = new Date(setreportPreviousStartDate.setDate(setreportPreviousStartDate.getDate() - daysPrior)).toISOString().slice(0,10);\n return reportPreviousStartDate;\n}",
"function getTempDate(){\n if(tempDate == undefined) {\n tempDate = getRightNow();\n }\n return tempDate;\n}",
"function atBeginningOfDay(date) {\n var d = new Date();\n d.setDate(date.getDate());\n d.setHours(0);\n d.setMinutes(0);\n d.setSeconds(0);\n d.setMilliseconds(0);\n return d;\n}",
"function getLastWednesday () {\r\n var currentDayOfWeek = currentDate.getDay(); \r\n var wednesday = 3; // 0 = Sun, 3 = Wed, 6 = Sat \r\n var goBackDays;\r\n var pastWednesday;\r\n\r\n if (currentDayOfWeek >= wednesday) { \r\n goBackDays = currentDayOfWeek - wednesday; \r\n } \r\n else { \r\n goBackDays = (7 - wednesday) + currentDayOfWeek; \r\n } \r\n\r\n // Convert days to milliseconds \r\n goBackDays = goBackDays * 24 * 60 * 60 * 1000; \r\n\r\n //set past wednesday\r\n pastWednesday = new Date(currentDate.getTime() - goBackDays);\r\n\r\n\r\n return pastWednesday;\r\n }",
"function getPreviousDates (){ \n\tvar dd = new Date();\n\tvar datStr = new Array();\n\tfor (i = 1; i < 4; i++){\n\t\tvar ddiff = new Date();\n\t\tddiff.setDate(dd.getDate()-i);\n\t\tvar shift_date = ddiff.getUTCDate();\n\t\t//zero pad date\n\t\tif (shift_date < 10){\n\t\t\tvar dateS = \"0\"+String(shift_date);\n\t\t}\n\t\telse{\n\t\t\tvar dateS = String(shift_date);\n\t\t}\n\t\tvar shift_month = ddiff.getUTCMonth()+1;\n\t\t//zero pad month\n\t\tif (shift_month < 10){\n\t\t\tvar monthS = \"0\"+String(shift_month);\n\t\t}\n\t\telse{\n\t\t\tvar monthS = String(shift_month);\n\t\t}\n\t\tvar diff_year = ddiff.getUTCFullYear();\n\t\tdatStr[i] = String(diff_year)+monthS+dateS;\n\t}\n\treturn datStr;\n}",
"function datePrecedente(date) {\n var dt = date.split('/');\n var myDate = new Date(dt[2] + '-' + dt[1] + '-' + dt[0]);\n myDate.setDate(myDate.getDate() + -1);\n newDate = formatDateSlash(myDate);\n return newDate;\n}",
"function getEndOfDayOfDate(unixTimestamp)\n{\n var date = new Date(unixTimestamp * 1000);\n date.setHours(23);\n date.setMinutes(59);\n date.setSeconds(59);\n \n return date.getTime() / 1000;\n}",
"function previous() {\n // if month equals to the value of 0 so the year will subtracts 1 then month will go to 11 that the value of Dec\n // else just only subtract the month and keep year in the same year\n if (month == 0) {\n year = year - 1;\n month = 11;\n } else {\n month = month - 1;\n }\n showCalendar(month, year);\n}",
"function get_tv_day_start(t, date_only) {\n var d = new Date(Math.floor(t) * 1000);\n return Math.floor((((d.getTime() - d.getTimezoneOffset() * 60000) / 1000.0) - (date_only ? 0 : day_start)) / 86400) * 86400 + (day_start + d.getTimezoneOffset() * 60);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wrapper for all showing/hiding of game prizes/completion certificates | function toggleCertAndPrizes() {
showOrHide('game_enable_completion_certificates', 'game_completion_certificate_template_field')
showOrHide('game_prizes_available', 'game_prizes_text_field')
} | [
"function paymentOptions(option) {\r\n const ccDIV = document.getElementById(\"credit-card\");\r\n const ppDIV = document.getElementById(\"paypal\");\r\n const bitcoinDIV =document.getElementById(\"bitcoin\");\r\n if(option == \"credit card\"){\r\n ccDIV.style.display = \"inherit\";\r\n ppDIV.style.display = \"none\";\r\n bitcoinDIV.style.display = \"none\";\r\n } else if (option == \"paypal\"){\r\n ccDIV.style.display = \"none\";\r\n ppDIV.style.display = \"inherit\";\r\n bitcoinDIV.style.display = \"none\";\r\n } else if (option == \"bitcoin\"){\r\n ccDIV.style.display = \"none\";\r\n ppDIV.style.display = \"none\";\r\n bitcoinDIV.style.display = \"inherit\";\r\n }\r\n}",
"function hidePaymentOptions() {\n // loop through paymentOptions object and set display to none\n for (prop in paymentOptions)\n toggleView(paymentOptions[prop], false);\n }",
"function capacitanceEnabled() {\n var capacitanceCheck = document.getElementById('TRV_capacitance_id').checked\n \n if (capacitanceCheck == '1') {\n document.getElementById('breaker_capacitance_id').style.display = '';\n }\n else {\n document.getElementById('breaker_capacitance_id').style.display = 'none';\n }\n}",
"function caesar_select() \r\n{\r\n document.getElementById(\"caesar_cipher_text\").innerHTML = \"\";\r\n var x = document.getElementById(\"welcome\");\r\n x.style.display = \"none\";\r\n var x = document.getElementById(\"viginere\");\r\n x.style.display = \"none\";\r\n var x = document.getElementById(\"morse\");\r\n x.style.display = \"none\";\r\n var x = document.getElementById(\"templar\");\r\n x.style.display = \"none\";\r\n var x = document.getElementById(\"base64\");\r\n x.style.display = \"none\";\r\n var x = document.getElementById(\"adfgvx\");\r\n x.style.display = \"none\";\r\n var x = document.getElementById(\"polybius\");\r\n x.style.display = \"none\";\r\n var x = document.getElementById(\"users\");\r\n x.style.display = \"none\";\r\n\r\n var x = document.getElementById(\"caesar\");\r\n if (x.style.display === \"none\") \r\n {\r\n x.style.display = \"block\";\r\n } \r\n else \r\n {\r\n x.style.display = \"none\";\r\n }\r\n}",
"function hideAllPaymentOptions() {\n creditCard.style.display = 'none';\n paypal.style.display = 'none';\n bitcoin.style.display = 'none';\n}",
"function choiceBoxesVisibility (vis) {\n playerChoiceBox.style.visibility = vis ;\n compChoiceBox.style.visibility = vis ;\n }",
"function show_hide_partner(obj,show_section)\n{\n}",
"toggleClosedCaptions () {\n if (!this.OOPlayer) {\n logger.warn('Attempt to toggle closed captions for player that is not loaded yet');\n return;\n }\n this.OOPlayer.toggleClosedCaptions();\n }",
"function hidesale() {\n if (document.getElementById(\"saleOff\").checked) {\n surprise_choose.style.display = \"none\";\n document.getElementById(\"surpise_choose\").classList.remove(\"required\");\n }\n}",
"function displayGameInfo(){\n // Game Stats\n document.getElementById(\"dealer-points\").innerHTML = dealer.points;\n document.getElementById(\"player-points\").innerHTML = player.points;\n document.getElementById(\"bet-amount\").innerHTML = player.bet;\n document.getElementById(\"bank-amount\").innerHTML = player.bank;\n document.getElementById(\"wins\").innerHTML = player.wins;\n document.getElementById(\"totalhands\").innerHTML = player.totalhands;\n // Control Buttons\n // document.getElementById(\"bet-button\").style.display = \"none\";\n // document.getElementById(\"cancel-button\").style.display = \"none\";\n // document.getElementById(\"deal-button\").style.display = \"none\";\n // document.getElementById(\"hit-button\").style.display = \"none\";\n // document.getElementById(\"stand-button\").style.display = \"none\";\n document.getElementById(\"messages\").innerHTML = \"Pick the bet amount\";\n document.getElementById(\"playerSection\").style.display = \"flex\";\n\n\n // Array.from(chip).forEach(function(element){\n // element.style.display = \"\";\n // });\n chipbuttons.style.display = \"flex\";\n // document.getElementById(\"controlbuttons\").style.display = \"none\";\n }",
"function showAllCoins() {\n let allCoins = state.getAllCacheCoins();\n showCoinsUI(allCoins);\n $(\".loading-spinner-page\").hide();\n }",
"function showHideLicenseRoleDiv(){ \n\tif(document.getElementById('licenseMenuViewId').checked==true){\n\t\tdocument.getElementById('licenseMenuSubTableDivId').style.display = \"block\";\n\t}else{\n\t\tdocument.getElementById('licenseMenuSubTableDivId').style.display = \"none\";\n\t}\n}",
"function showHidePayStubRoleDiv(){ \n\tif(document.getElementById('paystubMenuViewId').checked==true){\n\t\tdocument.getElementById('payStubMenuSubTableDivId').style.display = \"block\";\n\t}else{\n\t\tdocument.getElementById('payStubMenuSubTableDivId').style.display = \"none\";\n\t}\n}",
"function showHideOptions() {\r\n\r\n // Toggle show options status in CurStepObj and draw code window\r\n // TODO: It is not necessary to draw the entire code window. Separate\r\n // drawCodeWindow() function into 2 (or 3) functions, and call the\r\n // the one responsible for drawing buttons.\r\n //\r\n CurStepObj.showOptions = !CurStepObj.showOptions;\r\n drawCodeWindow(CurStepObj);\r\n}",
"function show_global_supplier_settings()\n{\n\t//Check if order list is empty \n\tif (order_list.length>0)\n\t{\t\n\t\tif (!ask_notification(\"Changing global supplier settings will change individual product supplier settings. Are you sure you want to proceed?\"))\n\t\t\treturn;\n\t}\n\t//Draw the global supplier settings page \n\t//Draw the items on the page as per global settings values \n\t$.each(suppliers_list, function (supplier_id, supplier_details)\n\t{\n\t\tvar supplier_name = supplier_details.name;\n\t\tvar checked = \"\";\n\t\tvar premium = 0;\n\t\t//Check if this global \n\t\tif (supplier_id in global_supplier_settings) \n\t\t{\n\t\t\tchecked = \" checked \";\n\t\t\tpremium = global_supplier_settings[supplier_id].premium;\n\t\t}\n\t\t//Write the HTML\n\t\tstr = str + \"<div class='ss-supplier'><div class='ss-supplier-selector'><input type='checkbox' id='glob_\"+supplier_id+\"' \"+checked+\" /></div><div class='ss-supplier-label'>\"+supplier_name+\"</div><div class='ss-supplier-percentage' ><input type='number' value='\"+premium+\"' id='gprem\"+supplier_id+\"' /> %</div></div>\";\n\n\t});\n\t//Include the HTML into basic frame\n\t$(\"#sup_list_view_global\").html(str);\t\t\n\t//make things visible\n\t$('.overlay').fadeIn(100); \n\t$('#setng_supplier_global').fadeIn(100);\n\n}",
"function pickRetroMode() {\n gameInstructions.classList.remove('hide')\n easyStartButton.classList.remove('hide')\n easyStartButton.addEventListener('click', startRetroMode)\n logoutButton.classList.add('hide')\n slideshow.classList.add('hide')\n showLeaderboard.classList.add('hide')\n gamemodeText.classList.add('hide')\n easyMode.classList.add('hide')\n hardMode.classList.add('hide')\n retroMode.classList.add('hide')\n redirectHome.classList.remove('hide')\n}",
"function toggleHiddenCheckItems() { \n STORE.hide = !STORE.hide;\n}",
"function checkCardReq(id)\r\n{\r\n\tvar rc;\r\n\tvar temp;\r\n\r\n\trc = showMenuItem('cardpay');\r\n\tif (rc == '0'){\r\n \ttemp = document.getElementById(id);\r\n \ttemp.style.display = 'none';\r\n\t}\r\n}//end checkCardReq",
"function hidePaymentNotSelectedModal() {\n return { type: types.PAYMENT_SELECTED };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
JSON Breed API Endpoints GET /api documentation | function apiDoc(req, res) {
//console.log('GET /api');
res.json({
message: 'Welcome to the stashy sheep breed list!',
documentation_url: 'https://github.com/SpindleMonkey/project-2/api.md',
base_url: 'http://localhost:3000',
notes: 'If you search for a breed with more than one word in it\'s name, use \'%20\' for the space between words. If you\'re updating the infoSources field, use \', \' to separage multiple sources.',
endpoints: [
{method: 'GET', path: '/api', description: 'Describes available endpoints'},
{method: 'GET', path: '/api/breed', description: 'Lists all sheep breeds'},
{method: 'GET', path: '/api/breed/:name', description: 'Lists info for a single breed'},
{method: 'GET', path: '/api/breed/all', description: 'Lists all info for all breeds'},
{method: 'POST', path: '/api/breed', description: 'Add a new sheep breed'},
{method: 'PUT', path: 'api/breed/:name', description: 'Update one of the breeds in the db'},
{method: 'DELETE', path: '/api/breed/:name', description: 'Delete a sheep breed by name'}
]
});
} | [
"function apiShow(req, res) {\n //console.log('GET /api/breed/:name');\n // return JSON object of specified breed\n db.Breed.find({name: req.params.name}, function(err, oneBreed) {\n if (err) {\n res.send('ERROR::' + err);\n } else {\n res.json({breeds: oneBreed});\n }\n });\n}",
"function apiShowAll(req, res) {\n //console.log('GET /api/breed/all');\n // return JSON object of specified breed\n db.Breed.find({}, function(err, allBreeds) {\n if (err) {\n res.send('ERROR::' + err);\n } else {\n res.json({breeds: allBreeds});\n }\n });\n}",
"indexAction(req, res) {\n this.jsonResponse(res, 200, { 'message': 'Default API route!' });\n }",
"static async apiGetPostits(req, res, next) {\n try {\n const postits = await PostitsDAO.getPostits();\n res.json(postits);\n } catch (e) {\n console.log(`api, ${e}`);\n }\n }",
"async function api(endpoint, params) {\n\tconst BUNGIE_API_KEY = process.env.BUNGIE_API_KEY;\n\tconst baseUrl = 'https://www.bungie.net/Platform/Destiny/';\n\tconst trailing = '/';\n\tconst queryParams = params ? `?${params}` : '';\n\tconst url = baseUrl + endpoint + trailing + queryParams;\n\treturn new Promise((resolve, reject) => {\n\t\trequest({\n\t\t\turl: url,\n\t\t\theaders: {\n\t\t\t\t'X-API-Key': BUNGIE_API_KEY\n\t\t\t}\n\t\t}, (err, res, body) => {\n//\t\t\tconsole.log('api: err=%j', err);\n//\t\t\tconsole.log('api: res=%j', res);\n//\t\t\tconsole.log('api: body=%j', body);\t\t\t\n\t\t\tlet object = JSON.parse(body);\n\t\t\tresolve(object.Response);\n\t\t});\n\t});\n}",
"function getFoodInformation(Ean) {\n //https://world.openfoodfacts.org/api/v0/product/\n var opts = {\n hostname: 'world.openfoodfacts.org',\n path: '/api/v0/product/' + Ean,\n method: 'GET',\n headers: {\n 'connection': 'keep-alive',\n \"Content-Type\": \"application/json\",\n }\n };\n console.log(opts.hostname + opts.path);\n var req = https.request(opts, function (res) {\n res.on('data', function (d) {\n // console.log(d);\n });\n });\n req.end();\n}",
"indexAction(req, res) {\n Robot.find((err, robots) => {\n if (err)\n this.jsonResponse(res, 400, { 'error': err });\n\n this.jsonResponse(res, 200, { 'robots': robots });\n });\n }",
"function list(req, res) {\n res.json({ data: dishes });\n}",
"getJabraApi() {\r\n return this.jabraApi;\r\n }",
"function apiDelete(req, res) {\n //console.log('DELETE /api/breed/:name');\n \n // delete the specified breed\n db.Breed.remove({'name': req.params.name}, function(err, lostSheep) {\n if (err) {\n res.status(404).send('could not remove that sheep');\n } else {\n res.json(lostSheep);\n }\n });\n}",
"function indexRoute(req, res, next) {\n Package\n .find()\n .then(packages => res.json(packages))\n .catch(next)\n}",
"methodsAction(req, res) {\n const routes = [];\n const scenes = Object.keys(config.tradfri.scenes);\n\n for(let route = 0; route < scenes.length; route++) {\n routes.push(`/api/scene/${scenes[route]}`);\n }\n\n routes.push('/api/disco');\n\n this.jsonResponse(res, 200, { 'routes': routes });\n }",
"getResourceDetailsAPI() {\n const endpointGET = environment.apiUrl + moduleUrls.ProjectResources + '?_where=(projectId,eq,' + this.state.projectId + ')';\n return $.ajax({\n url: endpointGET,\n type: Type.get,\n data: ''\n });\n }",
"static listAllOfMyNews() {\n\t\treturn RestService.get('api/news');\n\t}",
"function getDogs() {\n fetch(dogsURL)\n .then(resp => resp.json())\n .then(renderDogs)\n}",
"function get(model, config = {}) {\n const api = new AbcApi_1.AbcApi(model, config);\n return api.get;\n}",
"getAllInterests() {\n return fetch(\"http://localhost:8088/interests\")\n .then(response => response.json())\n }",
"function getAllBerries(){\n\n}",
"function apiClient_() {\n this.get = function(url) {\n var options = {\n 'method': 'get',\n 'muteHttpExceptions': true,\n 'headers': {\n 'Authorization': 'Bearer ' + getOAuthToken_()\n }\n };\n try {\n var response = UrlFetchApp.fetch(url, options);\n } catch (err) {\n Utilities.sleep(3000);\n var response = UrlFetchApp.fetch(url, options);\n // Try again after 3 seconds. If sleeping doesn't help, don't catch the error\n }\n var responseCode = response.getResponseCode();\n var responseText = response.getContentText();\n if (responseCode !== 200) {\n throw 'Robinhood API request failed. ' + responseCode + ': ' + responseText;\n }\n var responseJson = JSON.parse(responseText);\n return responseJson;\n };\n\n this.pagedGet = function(url) {\n var responseJson = this.get(url);\n var results = responseJson.results;\n var nextUrl = responseJson.next;\n while (nextUrl) {\n responseJson = this.get(nextUrl);\n results.push.apply(results, responseJson.results);\n nextUrl = responseJson.next;\n }\n return results;\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that saves challenge infos | function saveChallengeInfo(challengeData, reSubmission) {
return new Promise((resolve, reject) => {
dashboardModel.saveChallengeInfo(challengeData, reSubmission).then((data) => {
resolve(true);
}).catch((err) => {
if (err.message === message.INTERNAL_SERVER_ERROR)
reject({ code: code.INTERNAL_SERVER_ERROR, message: err.message, data: {} })
else
reject({ code: code.BAD_REQUEST, message: err.message, data: {} })
})
})
} | [
"function SaveHourInfo(hour, data){\n localStorage.setItem(hour, data);\n}",
"buildDungeonPrompts() {\n let dataToWrite = {};\n\n Object.values(DungeonManagersList.ByID).forEach((dungeonManager) => {\n // Add this dungeon info to the catalogue.\n dataToWrite[dungeonManager.id] = {\n id: dungeonManager.id,\n nameDefinitionID: dungeonManager.nameDefinitionID,\n difficulty: dungeonManager.difficultyName,\n gloryCost: dungeonManager.gloryCost,\n maxPlayers: dungeonManager.maxPlayers,\n };\n });\n\n // Turn the data into a string.\n dataToWrite = JSON.stringify(dataToWrite);\n\n Utils.checkClientCataloguesExists();\n\n // Write the data to the file in the client files.\n fs.writeFileSync(\"../client/src/catalogues/DungeonPrompts.json\", dataToWrite);\n\n Utils.message(\"Dungeon prompts info catalogue written to file.\");\n }",
"save() {\n\n let files = new Visitor(\n this.fullName,\n this.age,\n this.visitDate,\n this.visitTime,\n this.comments,\n this.assistedBy\n );\n let fileData = JSON.stringify(files)\n const fs = require('fs');\n\n id++;\n\n fs.writeFile(`visitor${id}.json`, fileData, err => {\n if (err) {\n throw (Error + 'Cannot save file');\n } else {\n console.log('File was saved');\n\n }\n });\n\n return 'File was saved';\n }",
"function save(){\n const a = JSON.stringify(answers);\n localStorage.setItem(\"answers\", a);\n}",
"function saveState(){\n writeToFile(userFile, users);\n writeToFile(campusFile, campus);\n}",
"static persist() {\n let questionsJson = JSON.stringify(questions);\n fs.writeFileSync(storagePath, questionsJson, 'utf-8');\n }",
"function saveParticipantData() {\n \n var nameStr = []; valStr = [];\n var firstPFpauses = 0; secondPFpauses = 0;\n var firstPFcorrect = 0; secondPFcorrect = 0;\n var SLcorrect = 0; numCorr = 0; \n exp_data[\"SL2subject\"] = subjectID;\n exp_data[\"SL2condition\"] = condition;\n exp_data[\"PF1type\"] = lasttime;\n exp_data[\"PF2type\"] = condition;\n exp_data[\"lasttime\"] = lasttime;\n for (i = 0; i < (demographics.length-1); i++) {\n exp_data[demographics[i].name] = demographics[i].value;\n }\n for (var i = 0; i<4; i++) {\n str = \"SL2easy\" + (i+1);\n exp_data[str] = easy[i];\n str = \"SL2hard\" + (i+1);\n exp_data[str] = hard[i];\n }\n for (i=0; i<testitems.length; i++) {\n str = 'SL2item' + (i+1);\n exp_data[str] = testitems[i];\n str = 'SL2answer' + (i+1);\n exp_data[str] = testanswers[i];\n if (testanswers[i]==\"correct\") {\n SLcorrect = SLcorrect + 1;\n }\n }\n exp_data[\"SL2correct\"] = SLcorrect/(testitems.length);\n englishwords[0].value = englishwords[0].value.toLowerCase();\n englishwords[0].value = englishwords[0].value.replace(/\\s+/g, '');\n \n for (var i=0; i<5; i++) {\n var word = testwords[i].replace(\".jpg\",\"\");\n if (englishwords[0].value.indexOf(word) > -1) {\n numCorr = numCorr + 1;\n }\n }\n exp_data[\"SL2traincorr\"] = numCorr;\n \n for (i=0; i<pfApauses.length; i++) {\n str = 'PF1pause' + (i+1);\n exp_data[str] = pfApauses[i];\n str = 'PF1answer' + (i+1);\n exp_data[str] = pfAanswers[i];\n str = 'PF1target' + (i+1);\n exp_data[str] = pfTaskAtargets[i];\n firstPFpauses = firstPFpauses + pfApauses[i];\n if (pfAanswers[i]==\"correct\") {\n firstPFcorrect = firstPFcorrect + 1;\n }\n }\n for (i=0; i<pfBpauses.length; i++) {\n str = 'PF2pause' + (i+1);\n exp_data[str] = pfBpauses[i];\n str = 'PF2answer' + (i+1);\n exp_data[str] = pfBanswers[i];\n str = 'PF2target' + (i+1);\n exp_data[str] = pfTaskBtargets[i];\n secondPFpauses = secondPFpauses + pfBpauses[i];\n if (pfBanswers[i]==\"correct\") {\n secondPFcorrect = secondPFcorrect + 1;\n }\n }\n exp_data[\"PF1pauseavg\"] = firstPFpauses/pfApauses.length;\n exp_data[\"PF2pauseavg\"] = secondPFpauses/pfBpauses.length;\n exp_data[\"PF1correct\"] = firstPFcorrect/pfAanswers.length;\n exp_data[\"PF2correct\"] = secondPFcorrect/pfBanswers.length;\n \n console.log(exp_data);\n saveData(exp_data); \n}",
"saveData() {\n let jsonData = {\n lastTicket: this.lastTicket,\n today: this.today,\n tickets: this.tickets,\n lastFour: this.lastFour\n }\n\n let jsonDataString = JSON.stringify(jsonData);\n \n fs.writeFileSync('./server/data/data.json', jsonDataString);\n }",
"function saveJson(){\n saveJSON(hiScoreArray, 'hiscores.json');\n}",
"function MEXQ_Save() {\n console.log(\"===== MEXQ_Save ===== \");\n console.log( \"mod_MEX_dict: \", mod_MEX_dict);\n/*\n partex: \"1;1;4;20;Praktijkexamen onderdeel A # 3;1;8;12;Minitoets 1 BLAUW onderdeel A # ...\n format of partex_str is:\n partex are divided by \"#\"\n each item of partex contains: partex_pk ; partex_examperiod ; partex_amount ; max_score ; partex_name #\n\n assignment: \"1;4;20|1;;6;|2;;4;|3;;4;|4;;6; # 3;8;12|1;D;3;|2;C;2;|3;C;;|4;;1;|5;;1;|6;;1;|7;D;;|8;;2; # ...\n format of assignment_str is:\n partex are divided by \"#\"\n first item of partex contains partex info: partex_pk ; partex_amount ; max_score |\n other items = | q_number ; max_char ; max_score ; min_score |\n\n keys: \"1 # 3|1;ac|2;b|3;ab|7;d # ...\n format of keys_str is:\n partex are divided by \"#\"\n first item of partex contains partex_pk |\n other items = | q_number ; keys |\n\n*/\n\n if(mod_MEX_dict.is_permit_admin){\n const upload_dict = {\n table: \"ete_exam\",\n mode: ((mod_MEX_dict.is_addnew) ? \"create\" : \"update\"),\n examyear_pk: mod_MEX_dict.examyear_pk,\n depbase_pk: mod_MEX_dict.depbase_pk,\n lvlbase_pk: mod_MEX_dict.lvlbase_pk,\n examtype: \"ete\",\n exam_pk: mod_MEX_dict.exam_pk,\n subject_pk: mod_MEX_dict.subject_pk,\n subject_code: mod_MEX_dict.subject_code,\n\n examperiod: mod_MEX_dict.examperiod,\n version: mod_MEX_dict.version,\n has_partex: mod_MEX_dict.has_partex\n // amount and blanks will be added further on\n };\n\n let partex_str = \"\", assignment_str = \"\", keys_str = \"\";\n let total_amount = 0, non_blanks = 0;\n\n console.log( \"mod_MEX_dict.partex_dict: \", mod_MEX_dict.partex_dict, typeof mod_MEX_dict.partex_dict);\n for (const data_dict of Object.values(mod_MEX_dict.partex_dict)) {\n const partex_pk = data_dict.pk;\n if (partex_pk) {\n // calc max score\n const partex_name = (data_dict.name) ? data_dict.name : \"\";\n const partex_examperiod = (data_dict.examperiod) ? data_dict.examperiod : 1;\n const partex_amount = (data_dict.amount) ? data_dict.amount : 0;\n const max_score = MEXQ_calc_max_score(partex_pk);\n partex_str += [\"#\", partex_pk, \";\",\n partex_examperiod, \";\",\n partex_amount, \";\",\n max_score, \";\",\n partex_name\n ].join(\"\");\n if (partex_amount){\n total_amount += partex_amount;\n\n// --- add partex to assignment_str\n assignment_str += \"#\" + partex_pk + \";\" + partex_amount + \";\" + max_score;\n keys_str += \"#\" + partex_pk;\n\n const p_dict = mod_MEX_dict.partex_dict[partex_pk];\n if (p_dict.a_dict){\n for (let q_number = 1, dict; q_number <= partex_amount; q_number++) {\n const value_dict = p_dict.a_dict[q_number];\n if(value_dict){\n // value_dict: {max_score: '', max_char: 'B', min_score: ''}\n const max_char = (value_dict.max_char) ? value_dict.max_char : \"\";\n const max_score = (value_dict.max_score) ? value_dict.max_score : \"\";\n const min_score = (value_dict.min_score) ? value_dict.min_score : \"\";\n if (max_char || max_score) {\n assignment_str += [\n \"|\", q_number,\n \";\", max_char,\n \";\", max_score,\n \";\", min_score\n ].join(\"\");\n non_blanks += 1;\n };\n if (value_dict.keys) {\n keys_str += [\n \"|\", q_number,\n \";\", value_dict.keys\n ].join(\"\");\n };\n }}};\n };\n };\n };\n // remove first # from string\n if(partex_str) {partex_str = partex_str.slice(1)};\n if(assignment_str) {assignment_str = assignment_str.slice(1)};\n if(keys_str) {keys_str = keys_str.slice(1)};\n\n upload_dict.partex = (partex_str) ? partex_str : null;\n upload_dict.assignment = (assignment_str) ? assignment_str : null;\n upload_dict.keys = (keys_str) ? keys_str : null;\n upload_dict.amount = (total_amount) ? total_amount : 0;\n upload_dict.blanks = (total_amount > non_blanks) ? (total_amount - non_blanks) : 0;\n\n upload_dict.scalelength = (mod_MEX_dict.scalelength) ? mod_MEX_dict.scalelength : null;\n\n UploadChanges(upload_dict, urls.url_exam_upload);\n }; // if(mod_MEX_dict.is_permit_admin)\n// --- hide modal\n $(\"#id_mod_exam_questions\").modal(\"hide\");\n } // MEXQ_Save",
"function saveDataCreateReport() {\n console.log('Writing data to JSON...');\n const jsonFile = fileName(client,'results/','json');\n fs.writeFileSync(jsonFile, JSON.stringify(AllResults));\n console.log(`Created ${jsonFile}`);\n\n console.log('Creating A11y report...');\n var data = mapReportData(AllResults);\n var report = reportHTML(data, tests, client, runner, standard);\n var dateStamp = dateStamp();\n var name = `${client} Accessibility Audit ${dateStamp}`;\n\n console.log('Writing report to HTML...');\n const htmlFile = fileName(client,'reports/','html');\n fs.writeFileSync(htmlFile, report);\n console.log(`Created ${htmlFile}`);\n\n console.log('Creating Google Doc...');\n googleAPI.createGoogleDoc(name, report);\n }",
"function getChallenge(cb) {\n var challenge = {};\n challenge.id = randomstring.generate(10);\n\n var categories = chance.pickset(config.groups, 3),\n cat1 = getRandomImages(categories[0], 4, true),\n cat2 = getRandomImages(categories[1], 3, false),\n cat3 = getRandomImages(categories[2], 3, false),\n images = _.concat(cat2, cat3, cat1),\n queryImage,\n answer = [],\n imageMap = {};\n\n //add a mapping between random names and the actual image paths\n images.forEach(function (e) {\n imageMap[e.name] = e.img;\n });\n queryImage = path.join('image', challenge.id, images.pop().name);\n\n images = chance.shuffle(images);//images should be in a random order\n\n //set answer\n images.forEach(function (e, i) {\n if (e.isCorrect) {\n answer.push(i.toString());\n }\n });\n answer.sort();\n\n //reduce images to masked name only\n images = images.map(function (e) {\n return path.join('image', challenge.id, e.name)\n });\n\n //create challenge obj to return\n challenge.challenge = queryImage;\n challenge.options = images;\n\n //corresponding secret with answers and resolver for image names\n var challengeSecret = {\n answer: answer,\n imageResolver: imageMap\n };\n\n //save challenge answer in a temporary storage that is deleted after around 60 seconds\n challengeCache.set(challenge.id, challengeSecret, function (err, success) {\n if (!err && success) {\n cb(null, challenge);\n } else {\n cb('failed to create challenge');\n }\n });\n }",
"function initSaveWork() {\n // If we can't fetch AssignmentState, that means we are not\n // a Carnap assignment. So we'll just go ahead and create an\n // empty object.\n let as = {};\n try {\n as = JSON.parse(AssignmentState);\n } catch {\n console.log('Unable to parse AssignmentState');\n const dummyAssignmentState = '{\"Saved Work\":{\"saveAs:1.3\":\"Bob\",\"saveAs:1.7\":\"Badly\",\"saveAs:1.5\":\"Show (Q → P)\\\\nP :PR\",\"saveAs:1.4\":[\"-\",\"-\",\"-\",\"F\",\"-\",\"F\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"T\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\",\"-\"]}}';\n as = JSON.parse(dummyAssignmentState);\n }\n\n // If this is the first time we run on a given assignment page,\n // we need to create as[\"Saved Work\"]\n if (typeof as['Saved Work'] === 'undefined') {\n as['Saved Work'] = {};\n }\n\n function saveWork() {\n // Syntax Checking (not implemented)\n // Translation, and Qualitative Short Answer\n $('[data-carnap-type=translate]',\n '[data-carnap-type=qualitative]',\n '[data-carnap-type=proofchecker]').each(function () {\n const exerciseId = $(this).attr('data-carnap-submission');\n const studentWork = $(this).find('input', 'textarea').val();\n as['Saved Work'][exerciseId] = studentWork;\n });\n\n // Truth Tables\n $('[data-carnap-type=truthtable]').each(function () {\n const exerciseId = $(this).attr('data-carnap-submission');\n as['Saved Work'][exerciseId] = [];\n $(this).find('select').each(function () {\n as['Saved Work'][exerciseId].push($(this).val());\n });\n });\n // Derivations\n $('[data-carnap-type=proofchecker]').each(function () {\n const exerciseId = $(this).attr('data-carnap-submission');\n const studentWork = $(this).find('textarea').val();\n as['Saved Work'][exerciseId] = studentWork;\n });\n // Model Checking\n // Multiple Choice and Numerical\n // Sequent Calculus Problems\n // Gentzen-Prawitz Natural Deduction Problems\n\n console.log(JSON.stringify(as));\n\n // If we can't putArgumentState, that probably means we aren't\n // a Carnap.io assignment.\n try {\n putAssignmentState(JSON.stringify(as));\n } catch {\n console.log('Unable to putArgumentState');\n }\n }\n\n function loadWork() {\n // Syntax Checking (not implemented)\n //\n // Translation and Qualitative Short Answer\n $('[data-carnap-type=translate]',\n '[data-carnap-type=qualitative]').each(function () {\n const exerciseId = $(this).attr('data-carnap-submission');\n if (typeof as['Saved Work'][exerciseId] !== 'undefined') {\n const studentWork = as['Saved Work'][exerciseId];\n $(this).find('input', 'textarea').val(studentWork);\n }\n });\n\n // Truth Tables\n $('[data-carnap-type=truthtable]').each(function () {\n const exerciseId = $(this).attr('data-carnap-submission');\n if (typeof as['Saved Work'][exerciseId] !== 'undefined') {\n $(this).find('select').each(function () {\n const value = as['Saved Work'][exerciseId].shift();\n $(this).val(value);\n });\n }\n });\n // Derivations\n $('[data-carnap-type=proofchecker]').each(function () {\n const exerciseId = $(this).attr('data-carnap-submission');\n if (typeof as['Saved Work'][exerciseId] !== 'undefined') {\n const studentWork = as['Saved Work'][exerciseId];\n $(this).find('textarea').val(studentWork);\n }\n });\n // Model Checking\n // Multiple Choice and Numerical\n // Sequent Calculus Problems\n // Gentzen-Prawitz Natural Deduction Problems\n\n // For debugging\n console.log(as);\n }\n\n loadWork();\n $(window).on('beforeunload', saveWork);\n $(window).on('blur', saveWork);\n}",
"function saveToolRemember(toolname) {\n //var tool = getTool();\n //Number(sizemodifier.querySelector(\"[data-selected]\").id.replace(\"size\",\"\"));\n globals.toolRemember[toolname] = {\n \"sizemodifier\" : document.getElementById(\"sizemodifier\").querySelector(\"[data-selected]\").id,\n \"sizetext\" : document.getElementById(\"sizetext\").value, \n \"patternselect\" : document.getElementById(\"patternselect\").value\n };\n console.log(`Saved tool ${toolname}: `, globals.toolRemember[toolname]);\n}",
"function save_all() {\n\tvar type = $('#type_list').find(\":selected\").val();\n\t// if it's for a new cue, we fetch everything from the UI\n\tif (cue_id == 'xx') {\t\n\t\tvar channel = Number($(\"#channel\").val());\n\t\tvar delay = Number($(\"#delay\").val());\n\t\tvar options = {};\n\t\tvar name = $('#cue_name').val();\n\t\tvar cue = create_cue(type, channel, delay, name, options);\n\t\tcue_id = add_cue(event_obj.cue_list, cue);\n\t\tdocument.getElementById(\"cue_id\").innerHTML = \", Cue n°\"+cue_id;\n\t}\n\t// updates the cue (command == edit_cue)\n\telse{\n\t\tsave_delay();\n\t\tsave_type();\n\t\tsave_channel();\n\t\tsave_name();\n\t}\n\tsave_options();\n\n\tfs.writeFileSync(data_file, JSON.stringify(project, null, 2));\n}",
"function handleSaveRoutineReminderInfo() {\n const desc = agent.parameters.descrizione;\n const ripetizione = agent.parameters.ripetizione;\n const giorni = agent.parameters.giorni;\n const orario = agent.parameters.orario;\n\n // Test\n const senderID = getSenderID();\n\n // Ottengo la posizione dei contatori dei promemoria routine\n let progRoutineCounterPath = admin.database().ref('pazienti/' + senderID + '/counters/promemoriaRoutine');\n\n return progRoutineCounterPath.once('value').then((snapshot) => {\n\n // Controllo quanti prom di routine ha inserito il paziente\n let progRoutineCounterForUser = snapshot.val();\n console.log('promemoria di routine gia\\' espressi: ' + progRoutineCounterForUser);\n\n // Test sender id\n console.log('SenderID: ' + senderID);\n\n // Creo path con id pari a quantita' di prom routine espressi\n let progRoutinePath = admin.database().ref('pazienti/' + senderID + '/promemoria/routine/' + progRoutineCounterForUser);\n\n const promemoria = {\n descrizione:desc,\n ripetizione: ripetizione,\n giorni:giorni,\n orario:orario\n };\n\n progRoutinePath.set(promemoria);\n\n // Incremento il numero di prom di routine di una unita'\n let progRoutineCounterPath = admin.database().ref('pazienti/' + senderID + '/counters/promemoriaRoutine');\n progRoutineCounterPath.set(progRoutineCounterForUser + 1);\n });\n }",
"function getChallengeInfo(challengeData) {\r\n return new Promise((resolve, reject) => {\r\n dashboardModel.getChallengeInfo(challengeData).then((data) => {\r\n resolve({ code: code.OK, message: '', data: data })\r\n }).catch((err) => {\r\n if (err.message === message.INTERNAL_SERVER_ERROR)\r\n reject({ code: code.INTERNAL_SERVER_ERROR, message: err.message, data: {} })\r\n else\r\n reject({ code: code.BAD_REQUEST, message: err.message, data: {} })\r\n })\r\n })\r\n}",
"function saveChar(na, re, gen, gol, sin, le, ti, at){ \n\n\t\t/*console.log( \"\" +\n\n\t\t\tna + ',' + re + ',' + gen + ',' + gold + \",\" + sin + ',' + INDEX + ',' + ti + ',' \n \t+ upgrades.attributes[5].level + \",\" \n \t+ upgrades.attributes[4].level + \",\"\n \t+ upgrades.attributes[3].level + \",\"\n \t+ upgrades.attributes[2].level + \",\"\n \t+ upgrades.attributes[1].level + \",\"\n \t+ upgrades.attributes[0].level + \"\"\n\t\t);*/\n\n \t document.cookie = na + ',' + re + ',' + gen + ',' + gold + \",\" + sin + ',' + INDEX + ',' + ti + ',' \n\t\t\t+ upgrades.attributes[5].level + \",\" \n\t + upgrades.attributes[4].level + \",\"\n\t + upgrades.attributes[3].level + \",\"\n\t + upgrades.attributes[2].level + \",\"\n \t + upgrades.attributes[1].level + \",\"\n \t+ upgrades.attributes[0].level + \"\"\t\n\t \t+ \";expires=Thu, 01 Jan 2020 00:00:00 UTC\";\n\t}",
"function WriteData() {\n setCookie_e(COOKIE_NAMES.user, MyUser);\n setCookie_e(COOKIE_NAMES.password, MyPass);\n setCookie_e(COOKIE_NAMES.zoom, MyZoom);\n setCookie_e(COOKIE_NAMES.lat, wlat);\n setCookie_e(COOKIE_NAMES.lng, wlon);\n setCookie_e(COOKIE_NAMES.id, myloginid);\n setCookie_e(COOKIE_NAMES.tel, mytel);\n setCookie_e(COOKIE_NAMES.myid, myid);\n\n\t\n\tconsole.log(\"writing: \"+MyUser+ \" - \"+MyPass+ \" - \"+MyZoom+ \" - \"+wlat+ \" - \"+wlon+ \" - \"+myloginid+ \" - \"+mytel+ \" - \"+myid);\n // window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotfswrite, fail);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Register event handlers so element can be selected, dragged and resized. | registerEventHandlers() {
this.el
.dblclick(event => {
this.handleDoubleClick(event);
})
.mousedown(event => {
this.handleClick(event, false);
})
.on('touchstart', event => {
if (!this.rb.isSelectedObject(this.id)) {
this.handleClick(event, true);
} else {
let absPos = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5__utils__["c" /* getEventAbsPos */])(event);
this.rb.getDocument().startDrag(absPos.x, absPos.y,
this.id, this.containerId, this.linkedContainerId,
this.getElementType(), DocElement.dragType.element);
event.preventDefault();
}
})
.on('touchmove', event => {
if (this.rb.isSelectedObject(this.id)) {
this.rb.getDocument().processDrag(event);
}
})
.on('touchend', event => {
if (this.rb.isSelectedObject(this.id)) {
this.rb.getDocument().stopDrag();
}
});
} | [
"registerContainerEventHandlers() {\n this.el\n .dblclick(event => {\n if (!this.rb.isSelectedObject(this.id)) {\n this.rb.selectObject(this.id, true);\n event.stopPropagation();\n }\n })\n .mousedown(event => {\n if (event.shiftKey) {\n this.rb.deselectObject(this.id);\n } else {\n if (this.rb.isSelectedObject(this.id)) {\n this.rb.getDocument().startDrag(event.originalEvent.pageX, event.originalEvent.pageY,\n this.id, this.containerId, this.linkedContainerId,\n this.getElementType(), DocElement.dragType.element);\n } else {\n this.rb.deselectAll();\n }\n }\n event.stopPropagation();\n })\n .on('touchstart', event => {\n if (this.rb.isSelectedObject(this.id)) {\n let absPos = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5__utils__[\"c\" /* getEventAbsPos */])(event);\n this.rb.getDocument().startDrag(absPos.x, absPos.y,\n this.id, this.containerId, this.linkedContainerId,\n this.getElementType(), DocElement.dragType.element);\n }\n event.preventDefault();\n })\n .on('touchmove', event => {\n this.rb.getDocument().processDrag(event);\n })\n .on('touchend', event => {\n this.rb.getDocument().stopDrag();\n });\n }",
"function registerEventHandlers() {\n // SVG Click event\n Data.Svg.Node.addEventListener('click', clickSvgEvent);\n\n // Capture right click / other click event\n window.addEventListener('auxclick', auxClickEvent);\n\n // Mouse actions for scrolling, drawing, and moving text\n window.addEventListener('mousedown', mouseDown);\n window.addEventListener('mouseup', pointerUp);\n window.addEventListener('mousemove', mouseMove);\n\n // Touch actions for scrolling, drawing, and moving text\n window.addEventListener(\"touchstart\", touchStart);\n window.addEventListener(\"touchend\", pointerUp);\n window.addEventListener(\"touchmove\", touchMove);\n\n // Key presses for zooming / reset zoom\n window.addEventListener('keyup', keyUpEvent);\n\n // Listen for the scroll wheel for zooming\n window.addEventListener('wheel', wheelEvent, { passive: false });\n // Data.Svg.Node.addEventListener('wheel', wheelEvent, { passive: false });\n\n // Detect window resize events (coud be an orientation change!)\n window.addEventListener('resize', windowResize);\n\n // File selector for uploading images\n document.getElementById('file-selector').\n addEventListener('change', fileSelectorUploadEvent);\n\n // Setup timer function for zooming actions outside the event listener\n setInterval(zoomTimer, 100);\n}",
"function addDraggableEventHandlers() {\n listParentNode = getListParentNode();\n updateNodeReferenceData();\n if (draggableNodes.length > 0) {\n draggableNodes.forEach(function (element) {\n element.setAttribute('draggable', 'true');\n element.addEventListener('dragstart', handleDragStart);\n element.addEventListener('dragover', handleDragOver);\n element.addEventListener('dragenter', handleDragEnter);\n element.addEventListener('dragleave', handleDragLeave);\n element.addEventListener('drop', handleDrop);\n });\n }\n }",
"function addDragHandlers(elem)\n{\n elem.addEventListener('dragstart', handleDragStart, false);\n elem.addEventListener('dragover', handleDragOver, false);\n elem.addEventListener('drop', handleDrop, false);\n elem.addEventListener('dragleave', handleDragLeave, false);\n\n}",
"#registerEventListeners() {\n this.#addOnFocusEventListener();\n this.#addOnHelpIconClickEventListener();\n }",
"function attachHandlers(options) {\n // XXXBramble: we want to reuse this code for the UploadFiles extension\n // so we add support for passing exra options here.\n options = options || {};\n options.elem = options.elem || window.document.body;\n // Support optional events hooks\n var noop = function(){};\n options.ondragover = options.ondragover || noop;\n options.ondragleave = options.ondragleave || noop;\n options.ondrop = options.ondrop || noop;\n options.onfilesdone = options.onfilesdone || noop;\n\n // XXXBramble: extra dragleave event for UI updates in UploadFiles\n function handleDragLeave(event) {\n event = event.originalEvent || event;\n event.stopPropagation();\n event.preventDefault();\n\n options.ondragleave(event);\n }\n\n function handleDragOver(event) {\n event = event.originalEvent || event;\n stopURIListPropagation(event);\n\n event.stopPropagation();\n event.preventDefault();\n options.ondragover(event);\n\n var dropEffect = \"none\";\n // XXXBramble: we want to reuse this in the UploadFiles modal, so treat body differently\n if(isValidDrop(event.dataTransfer.types)) {\n if(options.elem === window.document.body) {\n if($(\".modal.instance\").length === 0) {\n dropEffect = \"copy\";\n }\n } else {\n dropEffect = \"copy\";\n }\n }\n event.dataTransfer.dropEffect = dropEffect;\n }\n\n function handleDrop(event) {\n event = event.originalEvent || event;\n stopURIListPropagation(event);\n\n event.stopPropagation();\n event.preventDefault();\n options.ondrop(event);\n\n processFiles(event.dataTransfer, function(err) {\n if(err) {\n console.log(\"[Bramble] error handling dropped files\", err);\n }\n\n options.onfilesdone();\n\n if(options.autoRemoveHandlers) {\n var elem = options.elem;\n $(elem)\n .off(\"dragover\", handleDragOver)\n .off(\"dragleave\", handleDragLeave)\n .off(\"drop\", handleDrop);\n\n elem.removeEventListener(\"dragover\", codeMirrorDragOverHandler, true);\n elem.removeEventListener(\"dragleave\", codeMirrorDragLeaveHandler, true);\n elem.removeEventListener(\"drop\", codeMirrorDropHandler, true);\n }\n });\n }\n\n // For most of the window, only respond if nothing more specific in the UI has already grabbed the event (e.g.\n // the Extension Manager drop-to-install zone, or an extension with a drop-to-upload zone in its panel)\n $(options.elem)\n .on(\"dragover\", handleDragOver)\n .on(\"dragleave\", handleDragLeave)\n .on(\"drop\", handleDrop);\n\n // Over CodeMirror specifically, always pre-empt CodeMirror's drag event handling if files are being dragged - CM stops\n // propagation on any drag event it sees, even when it's not a text drag/drop. But allow CM to handle all non-file drag\n // events. See bug #10617.\n var codeMirrorDragOverHandler = function (event) {\n if ($(event.target).closest(\".CodeMirror\").length) {\n handleDragOver(event);\n }\n };\n var codeMirrorDropHandler = function (event) {\n if ($(event.target).closest(\".CodeMirror\").length) {\n handleDrop(event);\n }\n };\n var codeMirrorDragLeaveHandler = function (event) {\n if ($(event.target).closest(\".CodeMirror\").length) {\n handleDragLeave(event);\n }\n };\n options.elem.addEventListener(\"dragover\", codeMirrorDragOverHandler, true);\n options.elem.addEventListener(\"dragleave\", codeMirrorDragLeaveHandler, true);\n options.elem.addEventListener(\"drop\", codeMirrorDropHandler, true);\n }",
"registerEvents() {\n\t\t\tthis.container = this.getContainer();\n\t\t\tthis.registerListEvents();\n\t\t\tthis.registerForm();\n\t\t}",
"function registerEventsOnDomElements() {\r\n // Position the clicked container on top\r\n $(\".container\").on( \"click\", function() {\r\n $(\".sideBox\").css( \"z-index\", 0 );\r\n $(\".mainBox\").css( \"z-index\", 1 );\r\n $(this).css( \"z-index\", 2 );\r\n });\r\n \r\n $(\".name\").on( \"click\", function() {\r\n $( \".menuItems li .menutable\").hide();\r\n $( this ).parent().find(\".menutable\").show();\r\n });\r\n \r\n $(\".logo\").on( \"click\", function() {\r\n location.reload();\r\n });\r\n \r\n $(\".mask\").on( \"click\", function() {\r\n $(\".mask\").hide();\r\n $(\".maskData\").hide();\r\n });\r\n }",
"createEvents() {\n this.slider.addEventListener(this.deviceEvents.down, this.eventStartAll);\n window.addEventListener('resize', this.eventResize);\n }",
"_setAllDiagramElementsHandler() {\n const dragStarted = (event, d) => {\n d.dragY = event.y\n }\n const dragged = (event, d) => {\n this._moveNetworkLayer(d.path, event.y - d.dragY)\n d.dragY = event.y\n }\n const dragEnded = (event, d) => {\n delete d.dragY\n }\n\n // add event handler to current svg object\n this.rootSVGGroupSelection\n .selectAll('.dep2')\n .on('click', (event, d) => this.clickHandler(d))\n .on('mouseover', (event, d) => this._mouseOverHandler(event, d))\n .on('mouseout', (event, d) => this._mouseOutHandler(d))\n .call(\n drag().on('start', dragStarted).on('drag', dragged).on('end', dragEnded)\n )\n }",
"function registerEventHandlers() {\n const kUpKey = 38;\n const kDownKey = 40;\n\n document.addEventListener('keydown', function(event) {\n if (event.keyCode == kUpKey) updateMovement(directives.movePlayerUp);\n else if (event.keyCode == kDownKey) updateMovement(directives.movePlayerDown);\n });\n document.addEventListener('keyup', function(event) {\n updateMovement(directives.stopMovingPlayer);\n });\n\n document.addEventListener('touchstart', function(event) {\n let y = event.touches[0].clientY;\n if (y > window.innerHeight / 2) updateMovement(directives.movePlayerDown);\n else if (y < window.innerHeight / 2) updateMovement(directives.movePlayerUp);\n });\n document.addEventListener('touchend', function(event) {\n updateMovement(directives.stopMovingPlayer);\n });\n}",
"function setupEvents() {\n if (typeof window.ontouchstart !== 'undefined') {\n view.addEventListener('touchstart', tap);\n view.addEventListener('touchmove', drag);\n view.addEventListener('touchend', release);\n }\n view.addEventListener('mousedown', tap);\n view.addEventListener('mousemove', drag);\n view.addEventListener('mouseup', release);\n }",
"function addListeners(element) {\n element.addEventListener('click', showCell);\n element.addEventListener('contextmenu', markCell);\n}",
"function addElementListeners() {\n addDarkModeListener();\n addColorSchemeListener();\n addResizeListener();\n addCreateNoteListener();\n addDeleteNoteListener();\n addFilterNoteListener();\n addFilterHashesListener();\n addTitleListener();\n addDownloadListener();\n addCitationButtonListener();\n addModeSwitchListeners();\n addOnCloseListener();\n addOptionsListeners();\n}",
"setEventListeners() {\n this.on('edit',this.onEdit.bind(this));\n this.on('panelObjectAdded',this.onPanelObjectAdded.bind(this));\n this.on('panelObjectRemoved',this.onPanelObjectRemoved.bind(this));\n }",
"function createEventListeners(){\n var leftarrow=document.getElementById(\"leftarrow\");\n if (leftarrow.addEventListener){\n leftarrow.addEventListener(\"click\",leftArrow,false);\n } else if (leftarrow.attachEvent){\n leftarrow.attachEvent(\"onclcick\",leftArrow);\n }\n var rightarrow=document.getElementById(\"rightarrow\");\n if (rightarrow.addEventListener){\n rightarrow.addEventListener(\"click\",rightArrow,false);\n } else if (rightarrow.attachEvent){\n rightarrow.attachEvent(\"onclcick\",rightArrow);\n }\n var mainFig=document.getElementsByTagName(\"img\")[1];\n if (mainFig.addEventListener){\n mainFig.addEventListener(\"click\",zoomFig,false);\n } else if (mainFig.attachEvent){\n mainFig.attachEvent(\"onclick\",zoomFig);\n }\n var showAllButton=document.querySelector(\"#fiveButton p\");\n if (showAllButton.addEventListener){\n showAllButton.addEventListener(\"click\",previewFive,false);\n } else if (showAllButton.attachEvent){\n showAllButton.attachEvent(\"onclick\",previewFive);\n }\n}",
"onSelectionEdited(func){ return this.eventSelectionEdited.register(func); }",
"attachEvents() {\n const data = {\n mode: this.drawingMode,\n container: this.canvasDrawer,\n target: this.target\n };\n //When clicking the <label>, fire this event.\n $(this.target).click(data, function () {\n data.container.drawingMode = data.mode;\n data.container.componentSelected(data.target);\n });\n }",
"_defineListeners() {\n this.editor.model.on('insertContent', (eventInfo, [modelElement]) => {\n if (!isDrupalMedia(modelElement)) {\n return;\n }\n this.upcastDrupalMediaIsImage(modelElement);\n // Need to upcast DrupalMediaType to model so it can be used to show\n // correct buttons based on bundle.\n this.upcastDrupalMediaType(modelElement);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test opening embeded flash content | function testFlashViaEmbedTag() {
controller.open(TEST_DATA);
controller.waitForPageLoad(TIMEOUT_PAGE);
} | [
"function onFlashContentEmbedded(e)\r\n{\r\n\tfocusRef = e.ref;\r\n}",
"function TinyMCE_flash_execCommand(editor_id, element, command, user_interface, value) {\n // Handle commands\n switch (command) {\n case \"mceFlash\":\n var template = new Array();\n template['file'] = '../../plugins/flash/flash.htm'; // Relative to theme\n template['width'] = 400;\n template['height'] = 180;\n var name = \"\", swffile = \"\", swfwidth = \"\", swfheight = \"\", mceDo = \"insert\";\n if (tinyMCE.selectedElement != null && tinyMCE.selectedElement.nodeName.toLowerCase() == \"img\"){\n tinyMCE.flashElement = tinyMCE.selectedElement;\n if (tinyMCE.flashElement) {\n name = tinyMCE.flashElement.getAttribute('name') ? tinyMCE.flashElement.getAttribute('name') : \"\";\n if (name!='mce_plugin_flash')\n return;\n swfwidth = tinyMCE.flashElement.getAttribute('width') ? tinyMCE.flashElement.getAttribute('width') : \"\";\n swfheight = tinyMCE.flashElement.getAttribute('height') ? tinyMCE.flashElement.getAttribute('height') : \"\";\n swffile = tinyMCE.flashElement.getAttribute('alt') ? tinyMCE.flashElement.getAttribute('alt') : \"\";\n mceDo = \"update\";\n }\n }\n tinyMCE.openWindow(template, {editor_id : editor_id, swffile : swffile, swfwidth : swfwidth, swfheight : swfheight, mceDo : mceDo}); \n return true;\n }\n // Pass to next handler in chain\n return false;\n}",
"function openFlashWin(winFile,winName,myWidth,myHeight) {\r\n\tmyPopup = window.open(winFile,winName,'status=no,toolbar=no,scrollbars=no,width=' + myWidth + ',height=' + myHeight);\r\n}",
"function iefixNindexi1f1() {\r\n document.write('<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0\" width=\"100%\" height=\"100%\">\\n')\r\n document.write(' <param name=\"movie\" value=\"lab1.swf\">\\n')\r\n document.write(' <param name=\"quality\" value=\"high\">\\n')\r\n document.write(' <embed src=\"lab1.swf\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" type=\"application/x-shockwave-flash\" width=\"100%\" height=\"100%\"></embed></object>\\n')\r\n\r\n}",
"function addFlash(blockId) {\n netscape.security.PrivilegeManager.enablePrivilege(\"UniversalXPConnect\");\n var nsIFilePicker = Components.interfaces.nsIFilePicker;\n var fp = Components.classes[\"@mozilla.org/filepicker;1\"].createInstance(nsIFilePicker);\n fp.init(window, \"Select a file\", nsIFilePicker.modeOpen);\n fp.appendFilter(\"Flash Object\", \"*.swf\");\n fp.appendFilters(nsIFilePicker.filterAll);\n var res = fp.show();\n if (res == nsIFilePicker.returnOK) {\n var path = document.getElementById('path'+blockId);\n path.type = 'text';\n path.value = fp.file.path;\n }\n}",
"function addFlashDiv(filename, width, height) {\r\n\r\n flash_data ='<div id=\"temp_flash\" style=\"visibility:hidden; \"><object id=\"detectme\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0\"><param name=\"movie\" value=\"../editor/uploads/'+filename+'\"><param name=\"quality\" value=\"high\"><param name=\"allowscriptaccess\" value=\"samedomain\"><embed src=\"../../js/editor/uploads/'+filename+'\" name=\"detectme\" swliveconnect=\"true\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" type=\"application/x-shockwave-flash\"></embed></object></div>';\r\n \r\n \r\n $(\"#container #lection_content\").append(flash_data);\r\n window.setTimeout('addFlashDiv_new(\"'+filename+'\")',400);\r\n\r\n}",
"function addFlashMovie(blockId) {\n netscape.security.PrivilegeManager.enablePrivilege(\"UniversalXPConnect\");\n var nsIFilePicker = Components.interfaces.nsIFilePicker;\n var fp = Components.classes[\"@mozilla.org/filepicker;1\"].createInstance(nsIFilePicker);\n fp.init(window, \"Select a file\", nsIFilePicker.modeOpen);\n fp.appendFilter(\"Flash Movie\", \"*.flv\");\n fp.appendFilters(nsIFilePicker.filterAll);\n var res = fp.show();\n if (res == nsIFilePicker.returnOK) {\n var path = document.getElementById('path'+blockId);\n path.type = 'text';\n path.value = fp.file.path;\n }\n}",
"function pmRmMsgFlash (message) {\r\n var client_id = message[0];\r\n var room_id = message[1];\r\n var url = message[2];\r\n var comment = message[3];\r\n var x = userFind(client_id);\r\n\r\n if (x < 0) {\r\n printPlus(\"text_div\", '<span class=\"cln_err\">RM_MSG_FLASH from '+client_id+'</span>');\r\n return 0;\r\n }\r\n\r\n g_user_msg_v[x] = url;\r\n\r\n if ((my_client_id == client_id) || (g_user_admin[x] == 1)) {\r\n mboxView('media_div');\r\n output = '';\r\n output += '<object width=\"100%\" height=\"100%\">';\r\n output += ' <param name=\"movie\" value=\"'+url+'\"></param>';\r\n output += ' <param name=\"allowFullScreen\" value=\"true\"></param>';\r\n output += ' <param name=\"allowscriptaccess\" value=\"always\"></param>';\r\n output += ' <embed src=\"'+url+'&autoplay=1\"';\r\n output += ' type=\"application/x-shockwave-flash\"';\r\n output += ' allowscriptaccess=\"always\"';\r\n output += ' allowfullscreen=\"true\"';\r\n output += ' autoplay=\"true\"';\r\n output += ' width=\"100%\"';\r\n output += ' height=\"100%\">';\r\n output += ' </embed>';\r\n output += '</object>';\r\n print(\"media_div\", output);\r\n } else {\r\n output = '<span class=\"media\">';\r\n output += g_user_name[x]+\" Loaded: \";\r\n output += \"<a href=\\\"#\\\" onclick=\\\"document.getElementById('input_box').value='/flash \"+url+\"';clientInput();\\\">Video (\"+comment+\")</a></span><br />\";\r\n printPlus(\"text_div\", output);\r\n }\r\n return 1;\r\n}",
"function onFlashLoaded() {\n\t\ttrace(\"onFlashLoaded (from Flash)\");\n\t\t\n\t\tset_ready();\n\t}",
"function openUploadFile() {\n $('#game-file').click();\n }",
"function onCreate(e) {\n if (!e.success || !e.ref ) {\n vpaidjs.log(\"Failed to embed SWF.\");\n return false;\n }\n\n // wait just a smidge for Flash to start\n var readyCheck = setInterval(function () {\n if (typeof e.ref.PercentLoaded === \"function\") {\n clearInterval(readyCheck);\n // timer to wait for swf object to fully load\n var loadCheck = setInterval(function () {\n vpaidjs.log(player.options.swfPath + \" \" + e.ref.PercentLoaded() + \"% loaded.\" );\n if (e.ref.PercentLoaded() === 100) {\n player.ad = document.getElementById(player.playerId);\n\n if (typeof player.ad.initAd == \"function\") {\n clearInterval(loadCheck);\n\n if (typeof player.options.success == \"function\") {\n player.options.success();\n }\n }\n }\n }, 100);\n }\n }, 100);\n }",
"function flashWindow( param ) {\n\t\t\n\t\tvar\n\t\t\thWnd = typeof param === 'object' ? param.hWnd : param,\n\t\t\twin = $( '#' + hWnd ),\n\t\t\tcounter = 0,\n\t\t\ttimer;\n\n\t\tif( persistent.windows[ hWnd ] ) {\n\t\t\tif( timer ) {\n\t\t\t\tclearInterval( timer );\n\t\t\t\ttimer = 0;\n\t\t\t\tcounter = 0;\n\t\t\t}\n\t\t\ttimer =\n\t\t\t\tsetInterval( function( e ) {\n\t\t\t\t\tif( ++counter >= 8 ) {\n\t\t\t\t\t\tclearInterval( timer );\n\t\t\t\t\t\ttimer = 0;\n\t\t\t\t\t\twin.removeClass( 'flash' );\n\t\t\t\t\t\tcounter = 0;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\twin.toggleClass( 'flash' );\n\t\t\t\t\t}\n\t\t\t\t}, 50 );\n\t\t}\n\t}",
"function renderFlashTransition(){\n\t\n}",
"function editFVSSL()\n{\n //get the original code\n var dom = dw.getDocumentDOM();\n var theObj = dom.getSelectedNode();\n var objectCode = theObj.outerHTML;\n\n //set the variables to be the default for Flash Video\n MM.CalledFromFVSSLPI = true;\n dw.runCommand(\"FlashVideo\");\n MM.CalledFromFVSSLPI = false;\n}",
"function saveFlashDivContent(s_div) {\r\n\t\r\n\tvar myIFrame = document.getElementById(\"iView\");\r\n var iframe_body_html = myIFrame.contentWindow.document.body.innerHTML;\r\n \r\n if ((div_from=='t')) { \r\n \t $(\"#text\"+s_div).html(iframe_body_html);\r\n\t $(\"#text\"+s_div).css('visibility','');\r\n\t} \r\n\t\r\n\t$(\"#iView\").css('visibility','hidden');\r\n $(\"#iView\").css('z-index','-1000');\r\n\t\r\n\t\r\n\t\r\n\thideDivs(new Array());\r\n\thideImageDivs(new Array());\r\n\thideFlashDivs(new Array());\r\n\thideVideoDiv();\r\n\thideAudioDivs(new Array());\r\n}",
"function openMessage(message) {\n \n // var $container = window.parent.$('.container-message-lightbox');\n var $container = $('.container-message-lightbox');\n \n $container.find(\".js-message\").text(message);\n $container.fadeIn();\n\n //hide fncybox close\n parent.$(\"#fancybox-close\").css(\"display\", \"none !important\");\n}",
"flash () {\n if (!this.flashEffect.isRunning) {\n this.flashEffect.start()\n }\n }",
"function blockContent()\n{\n\t// show stop button\n\tdocument.getElementById('next_link').style.display = \"none\";\n\tdocument.getElementById('submit_link').style.display = \"none\";\n\tdocument.getElementById('exit_link').style.display = \"\";\n\tonLastScreen();\n\t\n\t// set progress bar to 100%\n\tdocument.getElementById('progress_bar').style.width = '100%';\n\n\t// load the screen with the information that content is blocked\n\tframes['myFrame'].location.href = getContentFolderName() + '/blocked.htm';\n}",
"function opensmoothboxurl(openURLsmoothbox){\n openSmoothBoxInUrl(openURLsmoothbox);\n\treturn false;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
triangles /////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// function that logs a triangel out of hashs based on given parameter | function triangles(number) {
var hash = '';
// for each number below the given one run the loop
for (let i = 0; i < number; i++){
// add another hash in each loop
hash += '#';
// print the hash var each loop
console.log(hash);
}
} | [
"function triangles(val) {\n //init string to contain character passed in while converting number data types to a string data type\n var str = \"\";\n //for loop to run until i = 7 not inclusive. 0 to 6 is 7 steps \n for (var i = 0; i < val; i++){\n // concatenate '#' to \n str += '#';\n //print str on each successive loop. Console.log must be within the loop block in order to function like this.\n console.log(str);\n }\n}",
"function triangulate(points){\n\tconst delaunay = Delaunator.from(points);\n\tconst tri = delaunay.triangles;\n\tvar triangles = []\n\tfor(var i=0;i<tri.length;i+=3){\n\t\ttriangles.push([tri[i], tri[i+1], tri[i+2]]);\n\t}\n\treturn(triangles);\n}",
"function getHex(x, y, hexArr) {\r\n\r\n // collisionDetect_tri(x, y, hexArr[0], hexArr[1], hexArr[2]);\r\n}",
"function drawSubTriangles(h, n) {\n var smallTriangle = n === 0 ? drawTriangle(h/2): drawSubTriangles(h/2, n - 1);\n\n var image = [];\n var width = h * 2 - 1;\n\n // add top triangle\n for (var i = 0; i < h/2; i++) {\n image.push([]);\n \n for (var j = 0; j < width / 4; j++) {\n image[i].push(\" \");\n }\n\n image[i] = image[i].concat(smallTriangle[i]);\n \n for (var j = 0; j < width / 4; j++) {\n image[i].push(\" \");\n }\n }\n\n //add bottom two triangles\n for (var i = h/2, j = 0; i < h; i++, j++) {\n image.push([]);\n image[i] = image[i].concat(smallTriangle[j]);\n image[i].push(\" \");\n image[i] = image[i].concat(smallTriangle[j]);\n }\n\n return image;\n }",
"function triangulate(rings) {\n\n var triangles = [],\n edges = [],\n i, j, k, points, p, q, len, done;\n\n for (k = 0; k < rings.length; k++) {\n\n points = rings[k];\n\n // build a set of edges from points\n for (i = 0, len = points.length; i < len; i++) {\n j = i < len - 1 ? i + 1 : 0;\n p = i ? q : shearTransform(points[i]);\n q = shearTransform(points[j]);\n edges.push(p.x > q.x ? new Edge(q, p) : new Edge(p, q));\n }\n }\n\n // shuffle(edges);\n\n var map = new TrapezoidalMap();\n\n for (i = 0; i < edges.length; i++) {\n done = map.addEdge(edges[i]);\n if (!done) return null;\n }\n done = map.collectPoints();\n if (!done) return null;\n\n // Generate the triangles\n for (i = 0; i < edges.length; i++) {\n if (edges[i].poly && edges[i].poly.length) triangulateMountain(edges[i], triangles);\n }\n\n return triangles.length ? triangles : null;\n}",
"function buildTriangle(length) {\n let triangle = '';\n let lineNumber = 1;\n for (lineNumber=1; lineNumber<=length; lineNumber++) {\n triangle = triangle + makeLine(lineNumber);\n \n }\n return triangle\n}",
"function airetriangle(base, hauteur){\n const result = (base * hauteur) / 2;\n return result \n }",
"get dihedrals() {\n\n // This array will contain three sub arrays (one for each connected face if it exists, if not it will return false),\n // With the sub arrays containing two values, the dihedral angle and if the edge is a valley or a ridge. A valley is\n // Where the two faces bend towards each other, like \\/, and a ridge is where they bend away from each other, like /\\.\n // This becomes important as when creating the struts one needs to tell the difference in order to keep the strut width\n // The same, otherwise creating a valley as a ridge will cause the struts to be wider, or even incorrect.\n // Dihedral must not go below 27 degrees for a 2x4 strut\n\n const dihedrals = [];\n\n // Iterates through each adjacent face, if it exists, and updates the dihedral and it's type\n for (const adjacentFace of this.adjacentFaces) {\n\n // Extract the adjacent face\n // const adjacentFace = this.adjacentFaces[i];\n\n // Checks the face exists, if so proceed\n if (adjacentFace) {\n\n // Finds the angle between their normals\n const angle = acos(divide(dot(this.normal, adjacentFace.normal), multiply(norm(this.normal), norm(adjacentFace.normal))));\n\n // Finds the dihedral angle (interior angle)\n const dihedral = divide(subtract(pi, angle), 2);\n\n // // Creates a test point to see if the normal direction is inside or outside the tetrahedron formed by the two faces\n // // Note: assumes face winding has already been performed.\n // const testpoint = multiply(multiply(epsilon, 2), adjacentFace.normal);\n\n // // Finds the four points that make up the tetrahedron\n // const tetrahedron = this.vertices;\n\n // // Iterate through each of the points in the adjacent face\n // for (const point of adjacentFace) {\n\n // // Check that the point is not in the face and add it to the tetrahedron\n // if (!this.contains(point)) tetrahedron.push(point);\n // }\n\n // Create a tetrahedron from the points\n\n\n // If the testpoint is in the tetrahedron, then it returns the dihedral and 'valley', else it returns the dihedral and 'ridge'\n // PointInsideTetrahedron(tetrahedron, testpoint) ? dihedrals.push([dihedral, 'valley']) : dihedrals.push([dihedral, 'ridge']);\n\n // Add the dihedrals\n dihedrals.push({ angle: dihedral, type: 'ridge' });\n\n } else {\n\n // The projected normal of the face, projected onto the xz axis\n const projectedNormal = [this.normal[0], 0, this.normal[2]];\n\n // Find the angle between the two planes\n const angle = acos(divide(dot(projectedNormal, this.normal), multiply(norm(projectedNormal), norm(this.normal))));\n\n // Finds the dihedral from the angle\n const dihedral = divide(subtract(pi, angle), 2);\n\n // Add the flat dihedral for the bottom struts\n dihedrals.push({ angle: dihedral, type: null });\n }\n }\n\n // Return the dihedrals\n return dihedrals;\n }",
"function hashCoordinates(i, j) {\n\tif (!isInBoundaries(i, j)) {\n\t\treturn 0;\n\t}\n\treturn i * gameSize + j + 1;\n}",
"function hashValues(map) {\n\t\tvar vals = [];\n\t\tfor (var o in map) {\n\t\t\tvals.push(map[o]);\n\t\t}\n\t\tvar valString = vals.join('###');\n\t\tvar hash = CryptoJS.SHA256(valString).toString(CryptoJS.enc.Base64);\n\t\treturn hash;\n\t}",
"function getNextTriangulationLevel(graph, independentSet) {\n var triangles = [];\n $.each(graph, function(key, node) {\n node.mark = false;\n });\n\n //This makes the algorithm O(n^2). It would be faster if I hashed the\n //triangles (so that this function was O(1) average case instead of O(n^2))\n function shouldAddTriangle(tri) {\n //Check if any of the points are in the independent set\n for(var i=0; i<independentSet.length; i++) {\n if(independentSet[i].equals(tri[0]) ||\n independentSet[i].equals(tri[1]) ||\n independentSet[i].equals(tri[2])) {\n return false;\n }\n }\n //Check if we've already seen this triangle\n for(var i=0; i<triangles.length; i++) {\n if(tri[0].equals(triangles[i][0]) &&\n tri[1].equals(triangles[i][1]) &&\n tri[2].equals(triangles[i][2])) {\n return false;\n }\n }\n return true;\n }\n\n independentSet.forEach(function (p) {\n graph[p.hash()].mark = true;\n var hole = getOneHoleInPolygon(graph, p);\n var holeTriangles = triangulate(hole);\n holeTriangles.forEach(function (tri) {\n //The triangle might not overlap all of these, but it will overlap at most\n //6, so in terms of Big O, O(1) == O(6)\n tri.overlaps = graph[p.hash()].triangles.filter(function (tri2) {\n return trianglesIntersect(tri, tri2);\n });\n console.assert(tri.overlaps.length > 0);\n });\n triangles = triangles.concat(holeTriangles);\n });\n\n $.each(graph, function(key, node) {\n if(!node.mark) {\n var nodeTriangles = node.triangles;\n nodeTriangles.forEach(function (tri) {\n if(shouldAddTriangle(tri)) {\n var nextTriangle = tri.slice(0);\n nextTriangle.overlaps = [tri];\n triangles.push(nextTriangle);\n }\n });\n }\n delete node.mark;\n });\n\n return triangles;\n}",
"triangulate(bound, isReal) {\n\t\t\tif (bound.length < 2) {\n\t\t\t\tLog(\"BREAK ! the hole has less than 2 edges\");\n\t\t\t\treturn; // if the hole is a 2 edges polygon, we have a big problem\n\t\t\t} else if (bound.length === 2) {\n\t\t\t\tLog(\"BREAK ! the hole has only 2 edges\"); // DDLS.Debug.trace(\"\t- edge0: \" + bound[0].originVertex.id + \" -> \" + bound[0].destinationVertex.id,{ fileName : \"Mesh.hx\", lineNumber : 1404, className : \"DDLS.Mesh\", methodName : \"triangulate\"});\n\t\t\t\t// DDLS.Debug.trace(\"\t- edge1: \" + bound[1].originVertex.id + \" -> \" + bound[1].destinationVertex.id,{ fileName : \"Mesh.hx\", lineNumber : 1405, className : \"DDLS.Mesh\", methodName : \"triangulate\"});\n\n\t\t\t\treturn; // if the hole is a 3 edges polygon:\n\t\t\t} else if (bound.length === 3) {\n\t\t\t\tlet f = new Face();\n\t\t\t\tf.setDatas(bound[0], isReal);\n\n\t\t\t\tthis._faces.push(f);\n\n\t\t\t\tbound[0].leftFace = f;\n\t\t\t\tbound[1].leftFace = f;\n\t\t\t\tbound[2].leftFace = f;\n\t\t\t\tbound[0].nextLeftEdge = bound[1];\n\t\t\t\tbound[1].nextLeftEdge = bound[2];\n\t\t\t\tbound[2].nextLeftEdge = bound[0]; // if more than 3 edges, we process recursively:\n\t\t\t} else {\n\t\t\t\tlet baseEdge = bound[0];\n\t\t\t\tlet vertexA = baseEdge.originVertex;\n\t\t\t\tlet vertexB = baseEdge.destinationVertex;\n\t\t\t\tlet vertexC;\n\t\t\t\tlet vertexCheck;\n\t\t\t\tlet circumcenter = new Point();\n\t\t\t\tlet radiusSquared = 0;\n\t\t\t\tlet distanceSquared = 0;\n\t\t\t\tlet isDelaunay = false;\n\t\t\t\tlet index = 0;\n\t\t\t\tlet _g1 = 2;\n\t\t\t\tlet _g = bound.length;\n\n\t\t\t\twhile (_g1 < _g) {\n\t\t\t\t\tlet i1 = _g1++;\n\t\t\t\t\tvertexC = bound[i1].originVertex;\n\n\t\t\t\t\tif (Geom2D.getRelativePosition2(vertexC.pos, baseEdge) == 1) {\n\t\t\t\t\t\tindex = i1;\n\t\t\t\t\t\tisDelaunay = true; //DDLS.Geom2D.getCircumcenter(vertexA.pos.x,vertexA.pos.y,vertexB.pos.x,vertexB.pos.y,vertexC.pos.x,vertexC.pos.y,circumcenter);\n\n\t\t\t\t\t\tGeom2D.getCircumcenter(vertexA.pos, vertexB.pos, vertexC.pos, circumcenter);\n\t\t\t\t\t\tradiusSquared = Squared(vertexA.pos.x - circumcenter.x, vertexA.pos.y - circumcenter.y); // for perfect regular n-sides polygons, checking strict delaunay circumcircle condition is not possible, so we substract EPSILON to circumcircle radius:\n\n\t\t\t\t\t\tradiusSquared -= EPSILON_SQUARED;\n\t\t\t\t\t\tlet _g3 = 2;\n\t\t\t\t\t\tlet _g2 = bound.length;\n\n\t\t\t\t\t\twhile (_g3 < _g2) {\n\t\t\t\t\t\t\tlet j = _g3++;\n\n\t\t\t\t\t\t\tif (j != i1) {\n\t\t\t\t\t\t\t\tvertexCheck = bound[j].originVertex;\n\t\t\t\t\t\t\t\tdistanceSquared = Squared(vertexCheck.pos.x - circumcenter.x, vertexCheck.pos.y - circumcenter.y);\n\n\t\t\t\t\t\t\t\tif (distanceSquared < radiusSquared) {\n\t\t\t\t\t\t\t\t\tisDelaunay = false;\n\t\t\t\t\t\t\t\t\tbreak;\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\n\t\t\t\t\t\tif (isDelaunay) break;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!isDelaunay) {\n\t\t\t\t\t// for perfect regular n-sides polygons, checking delaunay circumcircle condition is not possible\n\t\t\t\t\tLog(\"NO DELAUNAY FOUND\");\n\t\t\t\t\t/*let s = \"\";\n\t\t\t\t\tlet _g11 = 0;\n\t\t\t\t\tlet _g4 = bound.length;\n\t\t\t\t\twhile(_g11 < _g4) {\n\t\t\t\t\t\t\tlet i2 = _g11++;\n\t\t\t\t\t\t\ts += bound[i2].originVertex.pos.x + \" , \";\n\t\t\t\t\t\t\ts += bound[i2].originVertex.pos.y + \" , \";\n\t\t\t\t\t\t\ts += bound[i2].destinationVertex.pos.x + \" , \";\n\t\t\t\t\t\t\ts += bound[i2].destinationVertex.pos.y + \" , \";\n\t\t\t\t\t}*/\n\n\t\t\t\t\tindex = 2;\n\t\t\t\t}\n\n\t\t\t\tlet edgeA,\n\t\t\t\t\t\tedgeAopp,\n\t\t\t\t\t\tedgeB,\n\t\t\t\t\t\tedgeBopp,\n\t\t\t\t\t\tboundA,\n\t\t\t\t\t\tboundB,\n\t\t\t\t\t\tboundM = [];\n\n\t\t\t\tif (index < bound.length - 1) {\n\t\t\t\t\tedgeA = new Edge();\n\t\t\t\t\tedgeAopp = new Edge();\n\n\t\t\t\t\tthis._edges.push(edgeA, edgeAopp); //this._edges.push(edgeAopp);\n\n\n\t\t\t\t\tedgeA.setDatas(vertexA, edgeAopp, null, null, isReal, false);\n\t\t\t\t\tedgeAopp.setDatas(bound[index].originVertex, edgeA, null, null, isReal, false);\n\t\t\t\t\tboundA = bound.slice(index);\n\t\t\t\t\tboundA.push(edgeA);\n\t\t\t\t\tthis.triangulate(boundA, isReal);\n\t\t\t\t}\n\n\t\t\t\tif (index > 2) {\n\t\t\t\t\tedgeB = new Edge();\n\t\t\t\t\tedgeBopp = new Edge();\n\n\t\t\t\t\tthis._edges.push(edgeB, edgeBopp); //this._edges.push(edgeBopp);\n\n\n\t\t\t\t\tedgeB.setDatas(bound[1].originVertex, edgeBopp, null, null, isReal, false);\n\t\t\t\t\tedgeBopp.setDatas(bound[index].originVertex, edgeB, null, null, isReal, false);\n\t\t\t\t\tboundB = bound.slice(1, index);\n\t\t\t\t\tboundB.push(edgeBopp);\n\t\t\t\t\tthis.triangulate(boundB, isReal);\n\t\t\t\t}\n\n\t\t\t\tif (index === 2) boundM.push(baseEdge, bound[1], edgeAopp);else if (index === bound.length - 1) boundM.push(baseEdge, edgeB, bound[index]);else boundM.push(baseEdge, edgeB, edgeAopp);\n\t\t\t\tthis.triangulate(boundM, isReal);\n\t\t\t} // test\n\t\t\t//this.deDuplicEdge();\n\n\t\t}",
"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 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 }",
"function hash(uuid) {\n var hash = 0, i, chr;\n if (uuid.length === 0) return hash;\n for (i = 0; i < uuid.length; i++) {\n chr = uuid.charCodeAt(i);\n hash = ((hash << 5) - hash) + chr;\n hash |= 0; // Convert to 32bit integer\n }\n if (hash < 0) {\n hash += 1;\n hash *= -1;\n }\n return hash % constants.localStorage.numBins;\n}",
"function tables() {\n /////////////////////////////////////\n // Marching cubes lookup tables\n /////////////////////////////////////\n\n // These tables are straight from Paul Bourke's page:\n // http://local.wasp.uwa.edu.au/~pbourke/geometry/polygonise/\n // who in turn got them from Cory Gene Bloyd.\n\n // // table of used edges. Implicit in triTable.\n // var unusededgeTable = new Float32Array([\n // 0x0, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c,\n // 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00,\n // 0x190, 0x99, 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c,\n // 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90,\n // 0x230, 0x339, 0x33, 0x13a, 0x636, 0x73f, 0x435, 0x53c,\n // 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30,\n // 0x3a0, 0x2a9, 0x1a3, 0xaa, 0x7a6, 0x6af, 0x5a5, 0x4ac,\n // 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0,\n // 0x460, 0x569, 0x663, 0x76a, 0x66, 0x16f, 0x265, 0x36c,\n // 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60,\n // 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff, 0x3f5, 0x2fc,\n // 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0,\n // 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55, 0x15c,\n // 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950,\n // 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc,\n // 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0,\n // 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc,\n // 0xcc, 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0,\n // 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c,\n // 0x15c, 0x55, 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650,\n // 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc,\n // 0x2fc, 0x3f5, 0xff, 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0,\n // 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c,\n // 0x36c, 0x265, 0x16f, 0x66, 0x76a, 0x663, 0x569, 0x460,\n // 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac,\n // 0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa, 0x1a3, 0x2a9, 0x3a0,\n // 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c,\n // 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33, 0x339, 0x230,\n // 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c,\n // 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99, 0x190,\n // 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c,\n // 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x0\n // ]);\n\n // table of how the edges are used to create triangles\n triTable = new Float32Array([\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1,\n 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1,\n 3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1,\n 3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1,\n 9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1,\n 1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1,\n 9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1,\n 2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1,\n 8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1,\n 9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1,\n 4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1,\n 3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1,\n 1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1,\n 4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1,\n 4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1,\n 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1,\n 1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1,\n 5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1,\n 2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1,\n 9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1,\n 0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1,\n 2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1,\n 10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1,\n 4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1,\n 5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1,\n 5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1,\n 9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1,\n 0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1,\n 1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1,\n 10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1,\n 8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1,\n 2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1,\n 7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1,\n 9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1,\n 2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1,\n 11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1,\n 9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1,\n 5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1,\n 11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1,\n 11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1,\n 1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1,\n 9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1,\n 5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1,\n 2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1,\n 0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1,\n 5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1,\n 6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1,\n 0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1,\n 3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1,\n 6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1,\n 5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1,\n 1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1,\n 10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1,\n 6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1,\n 1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1,\n 8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1,\n 7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1,\n 3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1,\n 5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1,\n 0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1,\n 9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1,\n 8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1,\n 5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1,\n 0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1,\n 6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1,\n 10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1,\n 10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1,\n 8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1,\n 1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1,\n 3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1,\n 0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1,\n 10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1,\n 0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1,\n 3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1,\n 6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1,\n 9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1,\n 8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1,\n 3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1,\n 6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1,\n 0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1,\n 10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1,\n 10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1,\n 1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1,\n 2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1,\n 7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1,\n 7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1,\n 2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1,\n 1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1,\n 11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1,\n 8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1,\n 0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1,\n 7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1,\n 10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1,\n 2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1,\n 6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1,\n 7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1,\n 2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1,\n 1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1,\n 10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1,\n 10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1,\n 0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1,\n 7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1,\n 6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1,\n 8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1,\n 9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1,\n 6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1,\n 1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1,\n 4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1,\n 10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1,\n 8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1,\n 0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1,\n 1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1,\n 8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1,\n 10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1,\n 4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1,\n 10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1,\n 5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1,\n 11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1,\n 9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1,\n 6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1,\n 7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1,\n 3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1,\n 7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1,\n 9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1,\n 3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1,\n 6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1,\n 9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1,\n 1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1,\n 4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1,\n 7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1,\n 6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1,\n 3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1,\n 0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1,\n 6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1,\n 1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1,\n 0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1,\n 11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1,\n 6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1,\n 5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1,\n 9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1,\n 1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1,\n 1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1,\n 10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1,\n 0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1,\n 5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1,\n 10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1,\n 11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1,\n 0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1,\n 9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1,\n 7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1,\n 2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1,\n 8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1,\n 9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1,\n 9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1,\n 1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1,\n 9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1,\n 9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1,\n 5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1,\n 0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1,\n 10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1,\n 2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1,\n 0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1,\n 0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1,\n 9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1,\n 5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1,\n 3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1,\n 5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1,\n 8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1,\n 0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1,\n 9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1,\n 0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1,\n 1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1,\n 3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1,\n 4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1,\n 9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1,\n 11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1,\n 11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1,\n 2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1,\n 9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1,\n 3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1,\n 1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1,\n 4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1,\n 4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1,\n 0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1,\n 3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1,\n 3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1,\n 0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1,\n 9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1,\n 1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n 0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,\n -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1\n ]);\n}",
"getHashCode() {\n let hash = this.width || 0;\n hash = (hash * 397) ^ (this.height || 0);\n return hash;\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 get_colors(triangles){\n\tconst probs = [0.5,0.2,0.1,0.1,0.1];\n\tvar color_assignments = [];\n\tvar used_colors,new_probs;\n\tfor(var i=0;i<triangles.length;i++){\n\t\tused_colors = []\n\t\tfor(var j=0;j<color_assignments.length;j++){\n\t\t\tif(is_neighbor(triangles[i], triangles[j])){\n\t\t\t\tused_colors.push(color_assignments[j]);\n\t\t\t}\n\t\t}\n\t\tconsole.log(used_colors);\n\t\tnew_probs = [];\n\t\tfor(var j=0;j<5;j++){\n\t\t\tif(!used_colors.includes(j)){\n\t\t\t\tnew_probs.push(probs[j]);\n\t\t\t} else {\n\t\t\t\tnew_probs.push(0);\n\t\t\t}\n\t\t}\n\t\tconsole.log(new_probs);\n\t\tcolor_assignments.push(random_choice(new_probs));\n\t}\n\treturn(color_assignments);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To set permit mode, set a timeout to confirm staying in it, and also set the flag. | function set_permit () {
if (unset_permit_timeout != null)
clearTimeout(unset_permit_timeout);
// Set the flag.
current_mode = 'permit';
// Set timeout to only permit for 1 minute at a time.
unset_permit_timeout = setTimeout(
() => {
if (confirm('You are in whitelist permit mode. Continue in permit mode?')) {
set_permit();
} else {
unset_permit();
}
},
1000 * 60
);
} | [
"function unset_permit () {\n current_mode = 'forbid';\n if (unset_permit_timeout != null) {\n clearTimeout(unset_permit_timeout);\n unset_permit_timeout = null;\n }\n}",
"function Limit(delay /* ms */) {\n _ResetTimeout(delay, `Resetting active global timeout to ${delay}ms.`);\n}",
"setMode() {\n errors.throwNotImplemented(\"setting mode (dequeue options)\");\n }",
"setWait() {\n errors.throwNotImplemented(\"setting wait (dequeue options)\");\n }",
"function holdIt() {\n if (myDebug) {alert(\"--- Waiting \" + waitSeconds + \" seconds ---\");}\n\n if (waitSeconds < 1) {\n waitSeconds = 1;\n }\n\n setTimeout(tuneIt,waitSeconds*1000);\n\n}",
"function lock_read(timeout=2000){\n console.log('{DBG] locking');\n DETECTION = false;\n setTimeout(() => {\n console.log('[DBG] UNlocking');\n DETECTION = true;\n }, timeout);\n }",
"setLocked () {\n this.platform.sendMessage({ action: 'metamask-set-locked' })\n }",
"function activateRateLimited () {\n if (state.rateLimiting.active) return\n state.rateLimiting.active = true\n log(`Rate limit was exceeded!`)\n }",
"setBakingTime() {}",
"function set_timer_for_continuse_attack(){\n\tvar _p2Id = Session.get('p2Id');\n\tSession.set(_p2Id, 'locked');\n\tmakePlayerTransparent(_p2Id);\n\n\tMeteor.setTimeout(()=>{\n\t\tmakePlayerOpaque(_p2Id);\n\t\tSession.set(_p2Id, \"unlocked\");\n\t}, CONTINOUS_ATTACK_INTERVEL * 1000);\n}",
"function setExclusiveTimeout(timeId, fn, timeout)\n{\n if (timeId > 0) \n clearTimeout(timeId);\n timeId = 0;\n timeId = setTimeout(fn, timeout);\n timeoutId = timeId;\n}",
"function _canPromote() {\n return (remainingSeconds <= 0);\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}",
"setBlockMode(mode) {\n if (mode === this.blockMode) { return; } // bail if there's no change\n this.blockMode = mode;\n if(mode) {\n this.savedOpts = {}\n cmOptions.forEach(opt => this.savedOpts[opt] = this.cm.getOption(opt));\n this.wrapper.setAttribute( \"role\", \"tree\"); \n this.scroller.setAttribute(\"role\", \"presentation\");\n this.wrapper.setAttribute(\"aria-label\", \"Block Editor\");\n this.say(\"Switching to Block Mode\");\n this.ast = this.parser.parse(this.cm.getValue());\n } else {\n cmOptions.forEach(opt => this.cm.setOption(opt, this.savedOpts[opt]));\n this.wrapper.removeAttribute( \"role\"); \n this.scroller.removeAttribute(\"role\");\n this.wrapper.setAttribute(\"aria-label\", \"Text Editor\");\n this.say(\"Switching to Text Mode\");\n }\n this.renderer.animateTransition(this.ast, mode);\n }",
"timeout(){\n\n\t\tdocument.querySelector(\"audio\").play();\n\n\t\tif (this.state.currentType ===\"session\"){\n\t\t\t\t\tthis.setState({\n\t\t\t\t\t\ttimeLeft:this.state.breakLength * 60, \n\t\t\t\t\t\tcurrentType:\"break\"\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthis.setState({\n\t\t\t\t\t\ttimeLeft:this.state.sessionLength * 60, \n\t\t\t\t\t\tcurrentType:\"session\"\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\tthis.time();\n\t\t\n\t}",
"function changeDefaultTimeOut() {\n let user = db.ref('users/' + userId);\n\n const newDefaultTime = app.getArgument('newDefaultTime');\n\n if (newDefaultTime && (newDefaultTime * 60) > 0) {\n let minutes = parseInt(newDefaultTime) * 60;\n let promise = user.set({userId: userId, defaultCheckOutTime: minutes});\n\n app.tell(`Done. The new default session time out is now set to ${newDefaultTime} hours.`);\n } else {\n app.ask(`Sorry! can you please repeat that.`);\n }\n }",
"function easySettings() {\n document.getElementById(\"ezybtn\").disabled = true; // Turns off easy button\n document.getElementById(\"hrdbtn\").disabled = true; // Turns off hard button\n COUNTDOWN = 30; // Sets the spawnrate to 30\n start = 1; // Sets our game state to 1 (meaning the game will turn on and run)\n}",
"function isUserStillWaiting(request) {\n\treturn false; //Allow user to return the pool for selection.\n}",
"function switchPlayerToTheaterMode() {\n\tif ($(\"div#page\").hasClass(\"watch-non-stage-mode\"))\n\t\t$(\"button.ytp-size-button, div.ytp-size-toggle-large\").click();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates whether a vertical position property matches the expected values. | function validateVerticalPosition(property, value) {
if (value !== 'top' && value !== 'bottom' && value !== 'center') {
throw Error(`ConnectedPosition: Invalid ${property} "${value}". ` +
`Expected "top", "bottom" or "center".`);
}
} | [
"function validateVerticalAlignment(align) {\n var ALIGNMENTS = ['top', 'center', 'bottom'];\n var DEFAULT = 'top';\n return ALIGNMENTS.includes(align) ? align : DEFAULT;\n }",
"function isVertOrHorz(startCoordinate, endCoordinate){ \n let status;\n var startE = startCoordinate[0];\n var startN = startCoordinate[1];\n var endE = endCoordinate[0];\n var endN = endCoordinate[1];\n //console.log(\"startE: \" + startE + \" | endE: \" + endE);\n //console.log(\"startN: \" + startN + \" | endN: \" + endN);\n if (startN === endN) { /* if line is purely horizontal */\n status = 1;\n }else \n if (startE === endE) { /* if line is purely vertical */\n status = 2;\n } else {\n status = 0;\n }\n return status;\n}",
"_validateYRange() {\n return this.currentYRange[1] >= this.currentYRange[0];\n }",
"assertPosition_() {\n const layoutBox = this.element.getLayoutBox();\n const viewport = this.getViewport();\n const viewportHeight = viewport.getHeight();\n // TODO(jridgewell): This should really be the parent scroller, not\n // necessarily the root. But, flying carpet only works as a child of the\n // root scroller, for now.\n const docHeight = viewport.getScrollHeight();\n // Hmm, can the page height change and affect us?\n const minTop = viewportHeight * 0.75;\n const maxTop = docHeight - viewportHeight * 0.95;\n userAssert(\n layoutBox.top >= minTop,\n '<amp-fx-flying-carpet> elements must be positioned after the 75% of' +\n ' first viewport: %s Current position: %s. Min: %s',\n this.element,\n layoutBox.top,\n minTop\n );\n userAssert(\n layoutBox.top <= maxTop,\n '<amp-fx-flying-carpet> elements must be positioned before the last ' +\n 'viewport: %s Current position: %s. Max: %s',\n this.element,\n layoutBox.top,\n maxTop\n );\n }",
"isPositionWithinTableBounds(posX, posY){\n if(posX <= this.dimensions.x && posY <= this.dimensions.y && posX >= 0 && posY >= 0){\n return true\n }else{\n console.log(`The given positions are outside of the table bounds`)\n return false\n }\n }",
"function isValidPosition(position) {\n\t\t\treturn ((position[0] >= 0) && (position[1] >= 0) && (position[0] <= 4) && (position[1] <= 4));\t\n\t\t}",
"getValidYPosition(pos, dir) {\n // Check is pos is a number or not\n let posNum = Number(pos);\n if (isNaN(posNum)) {\n return this.startYDefault;\n }\n // Bound the coordinate\n if (dir == 90 || dir == 270) {\n posNum = Math.max(posNum, this.height/2 + 3);\n posNum = Math.min(posNum, this.MaxY - this.height/2 - 3);\n } else {\n posNum = Math.max(posNum, this.width/2 + 3);\n posNum = Math.min(posNum, this.MaxY - this.width/2 - 3);\n }\n return posNum\n }",
"function checkYLimit(idOrientation, idFranckyPositionY, heightOfWorld) {\r\n\r\n // Get the orientation & pos Y\r\n var orientation = document.getElementById(idOrientation).innerHTML;\r\n var intPosY = parseInt(document.getElementById(idFranckyPositionY).innerHTML, 10);\r\n\r\n // Deal with up side\r\n // -----------------------------------------\r\n if ((intPosY == heightOfWorld) && (orientation == 'North')) {\r\n return false;\r\n }\r\n\r\n // Deal with down side\r\n // -----------------------------------------\r\n if ((intPosY == 1) && (orientation == 'South')) {\r\n return false;\r\n }\r\n\r\n // End of function\r\n // -----------------------------------\r\n return true;\r\n\r\n}",
"outOfBounds() {\n const aboveTop = this.y < 0;\n const belowBottom = this.y + CONST.CAPY_HEIGHT > this.dimensions.height;\n return aboveTop || belowBottom;\n }",
"function isValid(position) {\n\n return !isNaN(position) && parseInt(grid[position]) && (position >= 0 && position <= 8);\n}",
"isVertical() {\r\n return !this.isHorizontal();\r\n }",
"function LineOrVertical(line, x) {\n this.vertical = (line === null);\n if (this.vertical) {\n this.x = x;\n } else {\n this.m = line.m;\n this.c = line.c;\n }\n}",
"checkPosition (y, x) {\n\t\t// Checks position of coordinates\n\t\treturn this.grid[y][x] === 0;\n\t}",
"function checkVisibilityConstraints(props) {\n var constraints = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _mapState.MAPBOX_LIMITS;\n\n for (var constraintName in constraints) {\n // in the format of min* or max*\n var type = constraintName.slice(0, 3);\n var propName = decapitalize(constraintName.slice(3));\n\n if (type === 'min' && props[propName] < constraints[constraintName]) {\n return false;\n }\n\n if (type === 'max' && props[propName] > constraints[constraintName]) {\n return false;\n }\n }\n\n return true;\n}",
"function validate(i, j) {\n\t\tlet valid = [];\n\n\t\t//left = [i ,j-1]\n\t\t//right = [i ,j+1]\n\t\t//top = [i-1 ,j]\n\t\t//bottom = [i+1 ,j]\n\n\t\tif (i - 1 >= 0) {\n\t\t\tvalid.push([ i - 1, j ]);\n\t\t} //top\n\t\tif (j - 1 >= 0) {\n\t\t\tvalid.push([ i, j - 1 ]);\n\t\t} //left\n\t\tif (j + 1 < grid[0].length) {\n\t\t\tvalid.push([ i, j + 1 ]);\n\t\t} //right\n\t\tif (i + 1 < grid.length) {\n\t\t\tvalid.push([ i + 1, j ]);\n\t\t} //bottom\n\n\t\treturn valid;\n\t}",
"function checkShipPlacement() {\n if (isHorizontal) {\n if (shipLength + col > 10) {\n return false;\n } else {\n return true;\n }\n } else {\n if (shipLength + row > 10) {\n return false;\n } else {\n return true;\n }\n }\n}",
"function checkCellPositions( flkty, expecteds ) {\n var isOK;\n for ( var i=0, len = expecteds.length; i < len; i++ ) {\n var expected = expecteds[i];\n var cell = flkty.cells[i];\n var position = cell.element.style.left;\n isOK = isPositionApprox( position, expected );\n if ( !isOK ) {\n console.error( 'wrong cell position, index: ' + i + '. ' +\n 'expected: ' + expected + '. position: ' + position );\n break;\n }\n }\n return isOK;\n}",
"function checkInput(input) {\n var essentialColumns = input.name && input.x && input.y;\n if (essentialColumns === undefined) {\n console.error(\"X or Y or Z Column cannot be empty.\");\n return false;\n }\n input.name = parseName(input.name);\n input.x = parseX(input.x);\n input.y = parseY(input.y);\n\n var constraints = null, viz = null, processe = null, z = null;\n if (input.z !== undefined) {\n input.z = parseZ(input.z);\n }\n if (input.constraints !== undefined) {\n if (0 === input.constraints.length)\n {\n input.constraints = undefined;\n }\n //input.constraints = input.constraints //parseConstraints(input.constraints);\n }\n if (input.viz !== undefined) {\n input.viz = parseViz(input.viz);\n }\n return (name && x && y && z && constraints && viz) !== undefined;\n}",
"function areDimensionsValid(dim, x, y){\n\n // Compare set dimensions to x and y coordinates\n if(x > dim || y > dim)\n {\n alert(\"Invalid player coordinates. Load a different file or fix the current one.\");\n window.location.replace(\"index.html\");\n }\n // The coordinates to dimensions are valid\n else\n return true;\n}",
"function verticalLinePosition(p_event) {\n\tdocument.getElementById('vertical-resize-line').style.top = p_event.pageY;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the scoped slots from `node` template children. Templates for default slots are processed as regular children in `processNode`. | function slotsToData(node, h, doc) {
const data = {};
const children = node.children || [];
children.forEach(child => {
// Regular children and default templates are processed inside `processNode`.
if (!isTemplate(child) || isDefaultTemplate(child)) {
return;
} // Non-default templates are converted into slots.
data.scopedSlots = data.scopedSlots || {};
const template = child;
const name = getSlotName(template);
const vDomTree = template.content.map(tmplNode => processNode(tmplNode, h, doc));
data.scopedSlots[name] = function () {
return vDomTree;
};
});
return data;
} | [
"function shiftSlotNodeDeeper(node) {\n if (!node.children) {\n return;\n }\n\n node.children.forEach((child) => {\n const vslotShorthandName = getVslotShorthandName(child);\n if (vslotShorthandName && child.name !== 'template') {\n const newSlotNode = cheerio.parseHTML('<template></template>')[0];\n\n const vslotShorthand = `#${vslotShorthandName}`;\n newSlotNode.attribs[vslotShorthand] = '';\n delete child.attribs[vslotShorthand];\n\n newSlotNode.parent = node;\n child.parent = newSlotNode;\n\n newSlotNode.children.push(child);\n\n // replace the shifted old child node with the new slot node\n node.children.forEach((childNode, idx) => {\n if (childNode === child) {\n node.children[idx] = newSlotNode;\n }\n });\n }\n });\n}",
"_processNodes(){\n this.shadowRoot\n .querySelector('slot')\n .assignedNodes()\n .forEach((n) => this._processNode(n));\n }",
"function createSlots(slots, dynamicSlots) {\n for (let i = 0; i < dynamicSlots.length; i++) {\n const slot = dynamicSlots[i];\n // array of dynamic slot generated by <template v-for=\"...\" #[...]>\n if ((0,_vue_shared__WEBPACK_IMPORTED_MODULE_1__.isArray)(slot)) {\n for (let j = 0; j < slot.length; j++) {\n slots[slot[j].name] = slot[j].fn;\n }\n }\n else if (slot) {\n // conditional single slot generated by <template v-if=\"...\" #foo>\n slots[slot.name] = slot.key\n ? (...args) => {\n const res = slot.fn(...args);\n // attach branch key so each conditional branch is considered a\n // different fragment\n if (res)\n res.key = slot.key;\n return res;\n }\n : slot.fn;\n }\n }\n return slots;\n}",
"function transformOldSlotSyntax(node) {\n if (!node.children) {\n return;\n }\n\n node.children.forEach((child) => {\n if (_.has(child.attribs, 'slot')) {\n const vslotShorthandName = `#${child.attribs.slot}`;\n child.attribs[vslotShorthandName] = '';\n delete child.attribs.slot;\n }\n });\n}",
"function wrapNode(node, template){\n return function() {\n return {\n name: template,\n data: node\n };\n };\n }",
"function generateStatementList(node)\n\t{\n\t\tfor(var i = 0; i < node.children.length; i++)\n\t\t{\n\t\t\tgenerateStatement(node.children[i]);\n\t\t}\n\t}",
"_findInnerSlotInfos() {\n return Array.from(this._dom.querySelectorAll(\"[slotid]\")).map(s => {\n return {\n context: s,\n id: s.getAttribute('slotid')\n }\n });\n }",
"slot$(name,ctx){\n\t\tvar slots_;\n\t\tif (name == '__' && !this.render) {\n\t\t\treturn this;\n\t\t}\t\t\n\t\treturn (slots_ = this.__slots)[name] || (slots_[name] = imba$1.createLiveFragment(0,null,this));\n\t}",
"visitCreate_tablespace(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitSubpartition_template(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"updateTemplateForNode(node) {\n \tconsole.log('Updating for node: ' + node.node_id);\n\n \t// Lookup related question for given node\n \tvar matchingQuestion = this.findQuestionForQuestionId(node.question_id);\n\n \t// Reset\n \tdocument.getElementById(\"sp-text\").value = null;\n \tdocument.getElementById(\"sp-radio-1\").checked = false;\n \tdocument.getElementById(\"sp-radio-2\").checked = false;\n\n \tif (matchingQuestion.type == \"text\") {\n \t\tvar textGroup = document.getElementById(\"sp-text-group\");\n \t\ttextGroup.style.display = \"block\";\n \t\tvar radioGroup = document.getElementById(\"sp-radio-group\");\n \t\tradioGroup.style.display = \"none\";\n \t\tvar textQuestionLabel = document.getElementById(\"sp-text-label\");\n\t \ttextQuestionLabel.innerHTML = matchingQuestion.label;\n \t} else {\n \t\tvar textGroup = document.getElementById(\"sp-text-group\");\n \t\ttextGroup.style.display = \"none\";\n \t\tvar radioGroup = document.getElementById(\"sp-radio-group\");\n \t\tradioGroup.style.display = \"block\";\n\t \tvar radioQuestionLabel = document.getElementById(\"sp-radio-label\");\n\t \tvar radioAnswer1Label = document.getElementById(\"sp-radio1-label\");\n\t \tvar radioAnswer2Label = document.getElementById(\"sp-radio2-label\");\n\t \tradioQuestionLabel.innerHTML = matchingQuestion.label;\n\t \tradioAnswer1Label.innerHTML = matchingQuestion.options[0];\n\t \tradioAnswer2Label.innerHTML = matchingQuestion.options[1];\n\n \t}\n\n \t// Reset and hide any error message\n \tvar errorSummary = document.getElementById(\"sp-error-summary\");\n \terrorSummary.style.display = \"none\";\n }",
"function generateElements(){\n // Generate as many as needed.\n for (i = 0; i < MAX_TIMESLOTS; i++){\n // The timeblock div.\n var timeslot = document.createElement(\"div\");\n timeslot.classList.add(\"time-block\");\n\n // The row div.\n var row = document.createElement(\"div\");\n row.classList.add(\"row\");\n\n // The hour span.\n var hour = document.createElement(\"span\");\n hour.classList.add(\"hour\");\n\n // The text area.\n var textArea = document.createElement(\"textarea\");\n textArea.classList.add(\"textarea\");\n\n // The save buttons.\n var saveBtn = document.createElement(\"button\");\n saveBtn.classList.add(\"saveBtn\");\n saveBtn.textContent = \"Save\";\n\n // Get the container for all of the timeblocks.\n var container = document.getElementsByClassName(\"container\");\n // Append the timeslots on to the container.\n container[0].appendChild(timeslot);\n // Append the row onto the timeslot.\n timeslot.appendChild(row);\n // Append the hour onto the row.\n row.appendChild(hour);\n // Append the textArea onto the row.\n row.appendChild(textArea);\n // Append the saveBtn onto the row.\n row.appendChild(saveBtn);\n }\n}",
"function _processNameScope() {\n processedGraph.root = {id: '', children: [], stacked: false};\n const {nodeMap, root} = processedGraph;\n\n for (const id of nameScopeIds) {\n const nameScope = _createNameScope(id);\n nodeMap[id] = nameScope;\n const parent = nameScope.parent ? nodeMap[nameScope.parent] : root;\n parent.children.push(id);\n }\n}",
"async function createTimeSlots() {\n if (!formData.slot1 || !formData.slot2 || !formData.slot3) return;\n \n formData.userid = (await Auth.currentSession()).getIdToken().payload[\"cognito:username\"];\n\n // Loop through TimeSlots and remove any that belong to the current user\n var timeSlots;\n for (timeSlots in timeSlotss) {\n var tempTimeSlots = timeSlotss.[timeSlots];\n if (re.localeCompare(new String(tempTimeSlots.userid)) == 0) {\n deleteTimeSlots(tempTimeSlots);\n }\n }\n await API.graphql({ query: createTimeSlotsMutation, variables: { input: formData } });\n setTimeSlots([...timeSlotss, formData]);\n setFormData(initialFormState);\n }",
"function setupHandlers( node ) {\n node_ref = node;\n setTimeout( reloadJadeTemplate, 5000 );\n }",
"addSlotKeys() {\n\t\t\tthis.$slots.default.forEach((item, index) => {\n\t\t\t\titem.key = item.key!=null?item.key:index;\n\t\t\t});\n\t\t}",
"function recurse(node, parent) {\n node.children.forEach((c) => {\n let card = parent.addCard(c.id);\n card.attach(c.spec);\n card.type = c.type;\n card.content = c.content;\n card.tags = c.tags;\n card.source = c.source;\n card.autorun = c.autorun;\n\n initCard(card);\n if (card.autorun) {\n new Function(card.source)();\n }\n\n if (c.children.length != 0) recurse(c, card);\n });\n }",
"#setActiveStepAttributes() {\n let { activeStep } = this;\n for (let step of this.children) {\n let name = step.getAttribute(\"name\");\n if (name === activeStep) {\n step.slot = \"active\";\n } else {\n step.slot = \"\";\n }\n }\n }",
"function generateNodes (packageName, node) {\n // draw a node\n const nameVersion = `${packageName}@${node.version}`\n let score = scoreMap.get(nameVersion)\n if (score == null) score = NoScoreAvailable\n const url = `https://platform.nodesource.io/registry?name=${packageName}${Amp}version=${node.version}`\n\n const scoreString = score === NoScoreAvailable ? NoScoreAvailable : `${score}%`\n\n let color\n if (score === NoScoreAvailable) {\n color = '#CFCFCF'\n } else if (score === 100) {\n color = '#9FFF9F'\n } else if (score > config.score) {\n color = '#FFFF7F'\n } else {\n color = '#FF9F9F'\n }\n\n // const level = `${packageName}\\\\l${node.version}\\\\lscore: ${scoreString}\\\\l`\n const label = `<font point-size=\"20\">${packageName}</font><br align='left'/>${node.version}<br align='left'/>score: ${scoreString}<br align='left'/>`\n\n out.push(` \"${nameVersion}\" [`)\n out.push(' shape = box,')\n out.push(' style = filled,')\n out.push(` fillcolor = \"${color}\",`)\n out.push(` URL = \"${url}\",`)\n out.push(` tooltip = \"${packageName} @ ${node.version} - score: ${scoreString}\",`)\n out.push(` label = <${label}>,`)\n out.push(' ]')\n\n // recurse\n const deps = node.dependencies || {}\n for (let depName in deps) {\n generateNodes(depName, deps[depName])\n }\n }",
"maintainImmediateChildren(CE) {\n let blockEls = BlockElements;\n\n let P,\n children = [].slice.apply(CE.childNodes);\n\n children.forEach(child => {\n if(blockEls[child.nodeName]) {\n\n /** Removes empty span tags. */\n if(child.firstChild && child.childNodes.length) {\n let nodes = [].slice.apply(child.children);\n nodes.forEach(node => {\n if(node.nodeName === 'SPAN' && !node.textContent.length) {\n child.removeChild(node);\n }\n });\n }\n\n return; // Node is legit, boot out early.\n } else if(child.nodeName === 'BR') {\n CE.removeChild(child);\n } else if(!blockEls[child.nodeName] && child.nodeType === 1) {\n P = document.createElement('p');\n P.setAttribute('data-hash', hashids.encode(Math.floor(Math.random() * 9999 + 1)));\n // Copy nodes children over.\n if(child.hasChildNodes()) {\n P.appendChild(child.cloneNode(true));\n }\n CE.replaceChild(P, child);\n } else if(!blockEls[child.nodeName] && child.nodeType === 3) {\n P = document.createElement('p');\n P.setAttribute('data-hash', hashids.encode(Math.floor(Math.random() * 9999 + 1)));\n P.textContent = child.textContent;\n CE.replaceChild(P, child);\n } else {\n return;\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Getters Getter of the damage caused by hardware components. | get hardwareDamage () {
return this._hardwareDamage
} | [
"get softwareDamage () {\n return this._softwareDamage\n }",
"getEnergyPercent() {\n return this.getNetEnergy() / this.maxEnergy\n }",
"set hardwareDamage (hardwareDamage) {\n this._hardwareDamage = hardwareDamage\n }",
"getNetEnergy() {\n return this.maxEnergy - this.fatigue\n }",
"receiveDamage(damage) { \n this.health = this.health - damage ;\n }",
"function mDamage(physical) {\n var baseD = enemy.damage;\n if (physical) {\n return (baseD * enemy.phys);\n } else {\n return (baseD * enemy.mag);\n }\n}",
"applyDamage(victim, attackEntity) {\n // pre-extraction\n let pos = victim.get(Component.Position);\n let health = victim.get(Component.Health);\n let otherComps = this.ecs.getComponents(attackEntity);\n let otherBox = otherComps.get(Component.CollisionShape);\n let attackComp = otherComps.get(Component.Attack);\n let angleVtoA = System.Util.angleAtoB(this.ecs, victim.entity, attackComp.attacker);\n let angleAtoV = angleClamp(angleVtoA + Math.PI);\n // Deal damage. Note that damage could be 0 (if the attack was\n // blocked).\n health.current = Math.max(0, health.current - attackComp.info.damage);\n // Collisions are only added in the collision detection system if\n // it hasn't been resolved by either entity. so that means (a) we\n // don't need to check resolution beforehand here, and (b) we only\n // need to worry about updating a single resolution map. For (b),\n // we'll choose to update the weapon's resolution map as it has a\n // much shorter lifespan.\n otherBox.collisionsResolved.add(victim.entity);\n // Mark as hit on attack (for combo purposes).\n attackComp.hit = true;\n // Only spawn damage event when nonzero damage\n if (attackComp.info.damage > 0) {\n // Damage event (text and sound effect)\n let eName = Events.EventTypes.Damage;\n let eArgs = {\n location: pos.p.copy(),\n angleAtoV: angleAtoV,\n internalDamage: attackComp.info.damage,\n attackInfo: attackComp.info,\n victim: victim.entity,\n victimType: System.Util.getThing(this.ecs, victim.entity),\n };\n this.eventsManager.dispatch({ name: eName, args: eArgs });\n }\n return attackComp.info.damage;\n }",
"takeDamage() {\n return `${this.name} took damage.`;\n }",
"damage(damagePoints){\n this.hp -= damagePoints\n return damagePoints\n }",
"set softwareDamage (softwareDamage) {\n this._softwareDamage = softwareDamage\n }",
"function OnReceiveDamage(){}",
"computeDamage (payload) {\n this.hardwareDamage.computeDamage(payload[meetingCategoryDamage.HARDWARE])\n this.softwareDamage.computeDamage(payload[meetingCategoryDamage.SOFTWARE])\n this.journeyDamage.computeDamage(payload[meetingCategoryDamage.JOURNEY])\n\n // Compute the total damage caused by all the components of the meeting thanks to the\n // total damage caused by each category of components.\n this.totalDamage = this.softwareDamage.totalDamage.add(this.hardwareDamage.totalDamage).add(this.journeyDamage.totalDamage)\n }",
"getAverageDamage() {\n const avgAttacks = (this.minAttacks + this.maxAttacks) / 2;\n const avgDmg = (this.minDamage + this.maxDamage) / 2 * avgAttacks;\n const critDmg = this.crit / 100 * avgDmg * 2;\n\n return avgDmg + critDmg;\n }",
"receiveDamage(damage) { \n this.health = this.health - damage;\n if(this.health > 0){ \n return `${this.name} has received ${damage} points of damage`;\n } else { \n return `${this.name} has died in act of combat`; \n }\n }",
"handleDefence(weaponDamage) {\n // When player chooses to defend themselfves,\n // they get hit at half strength of opponnent's weapon\n this.health = this.health - (weaponDamage / 2);\n }",
"function dealDamage (attacker, defender){\n // Subtract the weapon damage of the attacker from the health of the defender\n defender.health-=attacker.weapon.damage;\n // Return the defender object\n return defender;\n}",
"function getDmg(card) {\n let arr;\n const reducer = (a, c) => a + c;\n\n if(card.attacks) {\n arr = card.attacks.map(atk => {\n const temp = parseInt(atk.damage.replace(/[^0-9]/g,''))\n if (Number.isNaN(temp)) {\n return 0;\n } else {\n return temp;\n }\n });\n } else {\n return 0;\n }\n\n return arr.reduce(reducer);\n }",
"get effect() {\n if (!this._effect) this._effect = this.createEffect()\n return this._effect\n }",
"damage(dmg) {\n \n var newHp = (this.hp - dmg);\n if (newHp < 0) {\n this.hp = 0;\n this.die();\n }\n else this.hp = newHp;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Manually update the remaining timeout seconds | function updateTimeout() {
$timeout(function () {
if ($scope.remainingAuthSeconds > 0) {
$scope.remainingAuthSeconds--;
$scope.$digest();
//recurse
updateTimeout();
}
}, 1000, false); // 1 second, do NOT execute a global digest
} | [
"function _tickRemaining() {\n remainingSeconds--;\n \n if(remainingSeconds <= 0 && vm.promoted) {\n vm.promoted = false;\n _Load();\n } else if (remainingSeconds <= 0) {\n vm.promoted = false;\n } else {\n vm.promoted = true;\n }\n \n vm.promotePercentage = _getPromotePercentage();\n \n if(timer && !_canPromote()) {\n $timeout.cancel(timer);\n }\n \n if (!_canPromote()) {\n globalTimerSvc.addTicker(_tickRemaining, 1000);\n // timer = $timeout(_tickRemaining, 1000);\n }\n }",
"function startCountdownTimer() {\n secondsRemaining = timelimit;\n\n updateTimerDisplay();\n countdownTicker = setInterval(updateTimerDisplay, 1000);\n }",
"getRemainingSecs() {\n return Math.floor(this.getRemaining() / 1000) + 1;\n }",
"_addTime () {\r\n this._totalTime += (this._limit - this._timeLeft)\r\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}",
"subtractTime() {\n this.endTime -= 2000;\n }",
"function updateSLSessionTimeout() {\n //Calculates and store when session will be expired\n console.log(\"Updating SL Session Expiration date in cache\")\n redisClient.hget(hash_Timeout, hash_Timeout, function (error, reply) {\n if (error) {\n console.error(\"Can't Update Session Timeout in Redis \" + error)\n } else {\n var expire = moment(moment.now()).add(reply, 'minutes')\n redisClient.hset(hash_Timeout, timout_exp, expire.format())\n }\n })\n}",
"getTimeout(){cov_50nz68pmo.f[2]++;cov_50nz68pmo.s[6]++;return this.timeout;}",
"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 setTimers(timeout)\n{\n // warning 5 mn before the end.\n setTimeout('showAlmostExpiredLock()',(timeout-5)*60000);\n setTimeout('showExpiredLock()',timeout*60000); \n}",
"function updateDuration() {\n\tconst deltaS = (dateInput(\"dateEnd\") + timeInput(\"timeEnd\") - (dateInput(\"dateStart\") + timeInput(\"timeStart\"))) / 1000;\n\tconst round = 3600 / parseInt(ele(\"timeResolutionsInput\").value);\n\tconst duration = Math.ceil(deltaS / round) * round;\n\tconst hours = Math.floor(duration / 3600);\n\tconst minutes = Math.floor((duration - hours * 3600) / 60);\n\tconst seconds = Math.floor(duration - hours * 3600 - minutes * 60);\n\tele(\"duration\").innerText = `${hours}:${pad(minutes, 2)}:${pad(seconds, 2)}`;\n}",
"calcRemainingTime() {\n return (Math.round((currentGame.endTime - Date.now()) / 100));\n }",
"function decrementLeaderboardTimer(){\n GAME.masterLeaders(currLeaderboardVersion);\n leaderboardDecrementor = leaderboardDecrementor + 1000;\n // console.log(\"leaderboardDecrementor = \" + leaderboardDecrementor);\n setTimeout(function(){\n decrementLeaderboardTimer();\n },leaderboardDecrementor);\n }",
"function updateCountdown(){\n\tif(countdownCounter !== 0)\n\t{\n countdownCounter--;\n countdownText.text = countdownCounter.toString();\n\t}else{\n window.clearInterval(countdownTimer);\n countdownText.text = \"\";\n var selectZone = $('#SelectZone');\n selectZone.prop('disabled', true);\n countdownCounter = 6;\n scene.activeCamera.angularSensibilityX = 1000000;\n scene.activeCamera.angularSensibilityY = 1000000;\n if(platform===\"web\")\n {\n autoRotationBehavior.idleRotationSpeed = 0;\n }\n scene.activeCamera.useAutoRotationBehavior = false;\n scene.activeCamera.attachPostProcess(blurH);\n scene.activeCamera.attachPostProcess(blurV);\n disablePointerInput = true;\n isFrozen = true;\n if(votedMesh!=null)\n {\n\t\t\tvotedPin.visibility = 0;\n }\n if(selectedMesh!=null)\n {\n\t\t\tselectedPin.visibility = 0;\n\t\t\tselectedMesh.material = plushMaterials[selectedMesh.name];\n\t\t}\n\t\tvar helperText = $('#helperText');\n helperText.hide();\n var voteText = $('#voteText');\n voteText.show();\n percentageTexts.forEach(function (item) {\n\t\t\titem.text = \"\";\n\t\t})\n\t}\n}",
"tmpChange(amount, time) {\n let hold = this.rate;\n this.rate = amount;\n setTimeout(() => {\n this.rate = hold;\n }, time);\n }",
"function init() {\n /* loop through each jQuery object */\n var delayed = true; // delayed only checks every 5 seconds\n that.each(function() {\n var seconds = $(this).data('expiration');\n var time = getRemainingTime(seconds);\n if ( 60 > time.seconds && 0 < time.seconds ) {\n delayed = false; // start final countdown\n }\n if ( !delayed ) {\n timeout = 1000;\n } else {\n timeout = 5000;\n }\n $(this).text(time.human_readable);\n\n });\n return setTimeout(function() {\n init();\n }, timeout);\n }",
"function spinTimerTick() {\n timeLeft = timeLeft - 1000;\n console.log(timeLeft);\n if (timeLeft < 0) {\n // Current Spin has officially ended taking in bets\n // 1) call stopTimer() to clear the Interval\n stopTimer();\n // 2) sendBets() will send a user's bets to server. \n // server will respond with spin value\n sendBets();\n // 3) send a GET to get spin results from service\n setTimeout(startSpin, 12000);\n }\n updateTimer();\n }",
"function countDownInMilliseconds(time){\n message = `Waiting ${(time/1000).toFixed(2)}s.`;\n if (time > 0){\n countInput.value = message;\n setTimeout(countDownInMilliseconds, 1, time-1);\n } else {\n countInput.value = ``;\n }\n}",
"function changeDefaultTimeOut() {\n let user = db.ref('users/' + userId);\n\n const newDefaultTime = app.getArgument('newDefaultTime');\n\n if (newDefaultTime && (newDefaultTime * 60) > 0) {\n let minutes = parseInt(newDefaultTime) * 60;\n let promise = user.set({userId: userId, defaultCheckOutTime: minutes});\n\n app.tell(`Done. The new default session time out is now set to ${newDefaultTime} hours.`);\n } else {\n app.ask(`Sorry! can you please repeat that.`);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks how many STs & TTs there are by counting titles (there's always 1 title per group) Tracking total count for sequencing; panel count for labeling | function countTexts(frameX, objectStyle) {
if(objectStyle === "National Title") {
totalST++;
panelST++;
} else if(objectStyle === "Veterans Title") {
totalTT++;
panelTT++;
}
} | [
"function reportSummary(teams) {\n var count = {};\n if ($(\"#summary-resistor-change\")[0].checked) {\n for (var k = 0; k < teams.length; k++) {\n var team = teams[k];\n if ($(\"#team-\" + team.name + team.classID)[0].checked) {\n count[team.name] = {};\n for (var j = 0; j < team.levels.length; j++) {\n var myLevel = team.levels[j];\n if ($(\"#level-\" + myLevel.label)[0].checked) {\n count[team.name][myLevel.label] = {};\n var acts = myLevel.actions;\n for (var i = 0; i < team.members.length; i++) {\n var member = team.members[i];\n count[team.name][myLevel.label][member.name] = {};\n count[team.name][myLevel.label][member.name].achieved = 0;\n count[team.name][myLevel.label][member.name].overshot = 0;\n count[team.name][myLevel.label][member.name].undershot = 0;\n count[team.name][myLevel.label][member.name].closer = 0;\n count[team.name][myLevel.label][member.name].farther = 0;;\n count[team.name][myLevel.label][member.name].total = 0;\n } //clear all the counts for all members for this level\n for (var ii = 0; ii < acts.length; ii++) {\n act = acts[ii];\n if (act.type == \"resistorChange\") {\n member = act.actor;\n switch (act.goalMsg) {\n case \". Local goal met\":\n count[team.name][myLevel.label][member.name].achieved += 1;\n count[team.name][myLevel.label][member.name].total += 1;\n break;\n case \". Goal overshot\":\n count[team.name][myLevel.label][member.name].overshot += 1;\n count[team.name][myLevel.label][member.name].total += 1;\n break;\n case \". Goal undershot\":\n count[team.name][myLevel.label][member.name].undershot += 1;\n count[team.name][myLevel.label][member.name].total += 1;\n break;\n case \". Goal closer\":\n count[team.name][myLevel.label][member.name].closer += 1;\n count[team.name][myLevel.label][member.name].total += 1;\n break;\n case \". Goal farther\":\n count[team.name][myLevel.label][member.name].farther += 1;\n count[team.name][myLevel.label][member.name].total += 1;\n break;\n } //end of goalMsg switch\n } //end of resistor change\n } //end of actions\n } //end of level check\n } //end of levels loop\n } //end of team check\n } //end of team loop\n document.getElementById(\"data\").innerHTML += ('<mark> <br> <tr> <td colspan = \"4\" align = \"center\" > Summary Resistor Change Report </td> </tr></mark>');\n for (var kk = 0; kk < teams.length; kk++) {\n team = teams[kk];\n if ($(\"#team-\" + team.name + team.classID)[0].checked) {\n document.getElementById(\"data\").innerHTML += (\"<br><br>\");\n for (var j = 0; j < team.levels.length; j++) {\n myLevel = team.levels[j];\n if ($(\"#level-\" + myLevel.label)[0].checked) {\n document.getElementById(\"data\").innerHTML += (\"<br>\");\n for (var i = 0; i < team.members.length; i++) {\n member = team.members[i];\n var ach = count[team.name][myLevel.label][member.name].achieved;\n var clo = count[team.name][myLevel.label][member.name].closer;\n var und = count[team.name][myLevel.label][member.name].undershot;\n var ove = count[team.name][myLevel.label][member.name].overshot;\n var far = count[team.name][myLevel.label][member.name].farther;\n var tot = count[team.name][myLevel.label][member.name].total;\n var score = (tot ? Math.round(100 * ((tot - far) / tot)) : 0) / 100;\n document.getElementById(\"data\").innerHTML += (\"Team: \" + team.name +\n \", level \" + myLevel.label +\n \", member \" + member.styledName + \": local goal met = \" + ach +\n \", overshot = \" + ove + \", undershot = \" + und + \", closer = \" +\n clo + \", farther = \" + far + \", total = \" + tot + \", score = \" +\n score + \"<br>\");\n }\n }\n }\n mssg = \"report-tools: resistor-change summaries for \" + team.name;\n console.log(mssg);\n }\n }\n }\n}",
"function refreshCounts () {\n containers.forEach(el => {\n // Get count of all student elements in a target element\n let count = el.querySelectorAll('.student').length\n let elHeader = el.querySelector('.count')\n // Inject count in target container\n elHeader.textContent = ` (${count})`\n })\n }",
"function getWidthOfLabels(stats)\n{\n var labelsWidth = null;\n var longestLabel = '';\n\n // Find longest label (text in vAxis)\n for (var i = 0; i < stats.length; i++) {\n if (stats[i][0].length > longestLabel.length) {\n longestLabel = stats[i][0];\n }\n }\n\n // If longest label found\n if (longestLabel !== '') {\n var $body = $('body');\n\n // Create/get test div and append longest text inside, than find the width of the div with text\n var $testDiv = $body.find('#testWidth');\n\n if (!$testDiv.length) {\n $body.append('<div id=\"testWidth\" style=\"position: absolute;visibility: hidden;height: auto;width: auto;white-space: nowrap;font-size: 12px !important;\"></div>');\n $testDiv = $body.find('#testWidth');\n }\n\n $testDiv.append(longestLabel);\n labelsWidth = $testDiv.width() + 25;\n\n $testDiv.text('');\n }\n\n return labelsWidth;\n}",
"function countCargosShortPyjamaMwfPlus() {\n\t\t\tinstantObj.noOfCargosShortPyjamaMWF = instantObj.noOfCargosShortPyjamaMWF + 1;\n\t\t\tcountTotalBill();\n\t\t}",
"function buildTrackCounts() {\n interactionEvents.sort(function (a, b) {\n return (+a[config.timePointColumn]) - (+b[config.timePointColumn]);\n });\n for (let i = 0, eventCount = interactionEvents.length; i < eventCount; i++) {\n let event = interactionEvents[i];\n let proteinA = event[config.proteinAColumn];\n let proteinB = event[config.proteinBColumn];\n let timePoint = +event[config.timePointColumn];\n addTrackCount(proteinA, proteinB, timePoint);\n addTrackCount(proteinB, proteinA, timePoint);\n }\n\n if (config.removeDuplicateInteractions === \"true\") {\n removeDuplicateInteractions();\n }\n for (let protein in trackCounts) {\n removeSmallerTrackCounts(protein);\n }\n }",
"function countHcoverHwfPlus() {\n\t\t\tinstantObj.noOfHcoverHWF = instantObj.noOfHcoverHWF + 1;\n\t\t\tcountTotalBill();\n\t\t}",
"function degreeCount() {\n var countArr = [];\n var listStyle;\n count = 0;\n // loop through all degrees\n for (var i in degreeObj) {\n var countSubArr = [];\n countSub = 0;\n var degObjChild = degreeObj[i].children;\n // loop through all degree children\n for (var j in degObjChild) {\n // setting list class style\n var listStyle = degObjChild[j].attributes;\n // counting degrees for each program\n if (listStyle) {\n console.log(listStyle)\n if (listStyle[1].value == \"display: block;\" || listStyle[1].value == \"display: block; visibility: hidden;\" || listStyle[1].value == \"display: block; visibility: visible;\") {\n countSub++;\n countSubArr.push(countSub);\n }\n }\n countSubTotal = countSubArr.length;\n // setting list parent (degree div)\n var listParent = degObjChild[j].parentElement;\n if (listStyle && listParent) {\n if (listParent.parentElement.style) {\n // setting degree container parent (container) style\n var containerStyle = listParent.parentElement.style.display;\n //checking if list div and parent container are both showing and counting if so\n if (\n listStyle[1].value == \"display: block;\" || listStyle[1].value == \"display: block; visibility: hidden;\" || listStyle[1].value == \"display: block; visibility: visible;\" &&\n containerStyle == \"block;\"\n ) {\n count++;\n // push degree count into array and get the total amount\n countArr.push(count);\n countTotal = countArr.length;\n }\n }\n }\n }\n // appending number of degrees for each program to header\n if (countSubArr.length != 0) {\n var degHeader = degreeObj[i].previousElementSibling;\n // checking if degree header p child exists\n if (degHeader) {\n if (degHeader.children[1]) {\n var degreeCount = degHeader.children[1];\n $(degreeCount).append(countSubTotal);\n }\n }\n }\n }\n $(\".count-num\").prepend(countTotal);\n }",
"function calcTotalDayAgain() {\n var eventCount = $this.find('.everyday .event-single').length;\n $this.find('.total-bar b').text(eventCount);\n $this.find('.events h3 span b').text($this.find('.events .event-single').length)\n }",
"function getCountedObjects(){\n var counted = {};\n for (var i = 0; i < detections.length; i++){\n var lbl = detections[i].label;\n if (!counted[lbl]) counted[lbl] = 0;\n counted[lbl]++;\n }\n return counted;\n}",
"function displayStatsForQuestionSetArray(questionSetArray, divName)\r\n\t\t\t{\r\n\t\t\t\t//buildTopicArray\r\n\t\t\t\tvar topicArray = Array();\r\n\t\t\t\tvar topicObj = {};\r\n\t\t\t\t//buildSubtopicArray\r\n\t\t\t\tvar subTopicArray = Array();\r\n\t\t\t\tvar subTopicObj = {};\r\n\t\t\t\t//loop thru the questionset array\r\n\t\t\t\tfor(var i=0; i < questionSetArray.length; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\t//get topic value...check if it is in topicArray...if Y then add one to its count...else add the topic with count value 1.\r\n\t\t\t\t\t//if(topicArray.indexOf(questionSetArray[i]) != -1)\r\n\t\t\t\t\tif(topicObj[questionSetArray[i].TOPIC])\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\ttopicObj[questionSetArray[i].TOPIC]['COUNT'] = topicObj[questionSetArray[i].TOPIC]['COUNT'] + 1;\r\n\t\t\t\t\t\t//console.log(topicObj[questionSetArray[i].TOPIC]['COUNT']);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t//console.log(\"2222222222222\");\r\n\t\t\t\t\t\t//add in object and array\r\n\t\t\t\t\t\ttopicArray.push(questionSetArray[i].TOPIC);\r\n\t\t\t\t\t\ttopicObj[questionSetArray[i].TOPIC] = {};\r\n\t\t\t\t\t\ttopicObj[questionSetArray[i].TOPIC]['TOPIC'] = questionSetArray[i].TOPIC;\r\n\t\t\t\t\t\ttopicObj[questionSetArray[i].TOPIC]['COUNT'] = 1;\r\n\t\t\t\t\t}\r\n\t\t\t\t\t//similarly get subtopic value...check if it is in subTopicArray...if Y then add one to it's count...else add the subtopic with count value 1 and it's topic value.\r\n\t\t\t\t\tif(subTopicObj[questionSetArray[i].SUBTOPIC])\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tsubTopicObj[questionSetArray[i].SUBTOPIC]['COUNT'] = subTopicObj[questionSetArray[i].SUBTOPIC]['COUNT'] + 1;\r\n\t\t\t\t\t\t//console.log(subTopicObj[questionSetArray[i].SUBTOPIC]['COUNT']);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t//console.log(\"2222222222222\");\r\n\t\t\t\t\t\t//add in object and array\r\n\t\t\t\t\t\tsubTopicArray.push(questionSetArray[i].SUBTOPIC);\r\n\t\t\t\t\t\tsubTopicObj[questionSetArray[i].SUBTOPIC] = {};\r\n\t\t\t\t\t\tsubTopicObj[questionSetArray[i].SUBTOPIC]['SUBTOPIC'] = questionSetArray[i].SUBTOPIC;\r\n\t\t\t\t\t\tsubTopicObj[questionSetArray[i].SUBTOPIC]['COUNT'] = 1;\r\n\t\t\t\t\t\tsubTopicObj[questionSetArray[i].SUBTOPIC]['TOPIC'] = questionSetArray[i].TOPIC;\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tvar statHtml = \"<table><tr>\";\r\n\t\t\t\t//loop topic and each subtopic of that topic\r\n\t\t\t\tfor(var j=0; j < topicArray.length; j++)\r\n\t\t\t\t{\r\n\t\t\t\t\t//console.log(topicObj[topicArray[j]]['TOPIC']+\" - \"+topicObj[topicArray[j]]['COUNT']);\r\n\t\t\t\t\tstatHtml += \"<td><h5>\"+topicObj[topicArray[j]]['TOPIC']+\" - \"+topicObj[topicArray[j]]['COUNT']+\"</h5><br>\";\r\n\t\t\t\t\tfor(var k=0; k < subTopicArray.length; k++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif(topicObj[topicArray[j]]['TOPIC'] == subTopicObj[subTopicArray[k]]['TOPIC'])\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t//console.log(subTopicObj[subTopicArray[k]]['TOPIC']+\" - \"+subTopicObj[subTopicArray[k]]['SUBTOPIC']+\" - \"+subTopicObj[subTopicArray[k]]['COUNT']);\t\r\n\t\t\t\t\t\t\tstatHtml += \"\"+subTopicObj[subTopicArray[k]]['TOPIC']+\" - \"+subTopicObj[subTopicArray[k]]['SUBTOPIC']+\" - \"+subTopicObj[subTopicArray[k]]['COUNT']+\"<br>\";\r\n\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\tstatHtml += \"</td>\";\r\n\t\t\t\t}\r\n\t\t\t\t//end table\r\n\t\t\t\tstatHtml += \"</tr></table>\";\r\n\t\t\t\t$(\"#\"+divName).html(statHtml);\r\n\t\t\t}",
"function countShirtMwfPlus() {\n\t\t\tinstantObj.noOfShirtMWF = instantObj.noOfShirtMWF + 1;\n\t\t\tcountTotalBill();\n\t\t}",
"function setupPerPlayerTextCardCounts() {\n if (disabled) return;\n\n // For each row in the supply table, add a column count cell for each player.\n $(\".txcardname\").each(function() {\n var $this = $(this);\n var cardName = $this.children(\"[cardname]\").first().attr('cardname');\n\n // Insert new cells after this one.\n var insertAfter = $this.next();\n for (var p in players) {\n var cell = createPlayerCardCountCell(players[p], cardName);\n insertAfter.after(cell);\n insertAfter = cell;\n }\n insertAfter.after($('<td class=\"availPadding\"></td>'));\n });\n growHeaderColumns();\n}",
"function task_filter_text_calculate_count(array, text) {\n array = array.filter(function(D) {\n return D.content.toLowerCase().indexOf(text.toLowerCase()) !== -1\n })\n length_total = array.length\n return length_total\n //$(div_id).html(length_total)\n}",
"function set_total_summary(total_count, fltr_count, offset)\r\n\t{\r\n\t\t_fltr_r_cnt = parseInt(fltr_count);//visible \r\n\t\t_total_r_cnt = parseInt(total_count);//total\r\n\t\t_offset = parseInt(offset);\r\n\t}",
"function updateDisplayNum(){\n var totalCount = 0; // total numver of qualified anatomy annotations\n var matchCount = 0; // total matched number of filtered anatomy annotations\n var item = null;\n\n for(var i = 0; i < vm.annotationModels.length; i++){\n item = vm.annotationModels[i];\n totalCount = item.svgID && item.groupID ? totalCount + 1 : totalCount;\n if(filterAnnotations(item)){\n matchCount += 1;\n item.isShow = true;\n }\n else{\n item.isShow = false;\n }\n }\n\n vm.totalCount = totalCount;\n vm.matchCount = matchCount;\n }",
"function countLcoverHwiPlus() {\n\t\t\tinstantObj.noOfLcoverHWI = instantObj.noOfLcoverHWI + 1;\n\t\t\tcountTotalBill();\n\t\t}",
"crotonTripsCounter(state) {\n var crotonTrips = 0;\n for (var i = 0; i < state.recordsList.length; i++) {\n if (state.recordsList[i].reservoir === \"Croton\") {\n crotonTrips++;\n }\n }\n return crotonTrips;\n }",
"function levelAndScoreCount() {\r\n if (level == 0) {\r\n $(\"h2\").hide();\r\n $(\"#play\").hide();\r\n $(\"h1\").css(\"margin-top\", \"38px\")\r\n\r\n $(\"footer\").before('<h2 id=\"level-title\" class=\"score\"></h2>');\r\n $(\".score\").text(\"score: \" + score);\r\n $(\"h1\").text(\"level \" + level);\r\n level++;\r\n\r\n } else {\r\n $(\"h1\").text(\"level \" + level);\r\n level++;\r\n score += 50;\r\n $(\".score\").text(\"score: \" + score);\r\n\r\n }\r\n userPattern = [];\r\n}",
"function relabelSubtitles (subtitles) {\n const counts = {}\n subtitles.tracks.forEach(track => {\n const lang = track.language\n counts[lang] = (counts[lang] || 0) + 1\n track.label = counts[lang] > 1 ? (lang + ' ' + counts[lang]) : lang\n })\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Filterting rules: 1. Should be at least as severe as the global level 2. Should be at least as severe as the local level 3. logger's name should pass name filter | function allow(logger, level){
if (level < gLevel) return false;
if (level < logger.level) return false;
if (gNameFilter && !gNameFilter.test(logger.name)) return false;
return true;
} | [
"visitLogging_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitSupplemental_logging_props(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitSupplemental_log_grp_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function printFilterRestrictionHint () {\n console.log(' The \"restriction\" field is used to determine the type of filter. Possible values for restriction are:')\n console.log(' \"after\" - Filters by date')\n console.log(' filter.path must lead to a date string')\n console.log(' filter.value must be a number')\n console.log(' All alerts with dates before the current time + value(hours) will be removed')\n console.log(' \"before\" - Filters by date')\n console.log(' filter.path must lead to a date string')\n console.log(' filter.value must be a number')\n console.log(' All alerts with dates after the current time + value(hours) will be removed')\n console.log(' \"contains\" - Filters by the contents of an array')\n console.log(' filter.path must lead to an array')\n console.log(' filter.value must be a primitive value potentially found in the arrays filter.path leads to')\n console.log(' All alerts with arrays containing value will be kept')\n console.log(' \"has\" - Filters by whether a path exists in the object')\n console.log(' filter.path is the path to try to access in the alert object')\n console.log(' filter.value is true if alerts with valid paths are kept false if alerts are removed')\n console.log(' All alerts with valid paths are kept is value is true false otherwise')\n console.log(' This type of filter is used before the other filters')\n console.log(' \"equals\" - Filters alerts by comparing primitive values')\n console.log(' filter.path is the path to the primitve value to be compare')\n console.log(' filter.value is the value to compare with')\n console.log(' All alerts with values at path equal to the filter value will be kept')\n console.log(' \"matches\" - Filters by testing strings in the alerts for a regex match')\n console.log(' filter.path must lead to a string')\n console.log(' filter.value must be a regex string')\n console.log(' All alerts with strings at path matching value will be kept')\n console.log('\\n Example: remove all alerts that have been overridden by a later alert.')\n console.log(' {')\n console.log(' \"restriction\": \"has\",')\n console.log(' \"path\": \"properties.replacedBy\",')\n console.log(' \"value\": 0')\n console.log(' }')\n}",
"setDefaultLogger() {\n const defaultLevel = Meteor.isProduction ? 'error' : 'trace';\n const defaultLogger = loglevel.createLogger('', defaultLevel);\n\n this.setLogger(defaultLogger);\n }",
"visitError_logging_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"setLogLevel() {\n this.chefWorkers.forEach(cw => {\n cw.worker.postMessage({\n action: \"setLogLevel\",\n data: log.getLevel()\n });\n });\n\n if (!this.dishWorker.worker) return;\n this.dishWorker.worker.postMessage({\n action: \"setLogLevel\",\n data: log.getLevel()\n });\n }",
"visitLog_grp(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function logWhisper(string) {\n console.log(string.toLowerCase());\n}",
"level() {\n const env = process.env.NODE_ENV || 'development';\n const isDevelopment = env === 'development';\n return isDevelopment ? 'debug' : 'warn';\n }",
"function getLoveLevel(name) {\n\t\tvar score = 0;\n\t\tfor(var i = 0; i < name.length; i++) {\n\t\t\tscore += name.charCodeAt(i);\n\t\t}\n\t\tscore %= 20;\n\t\tscore -= 10;\n\t\treturn score;\n\t}",
"function FilterListener() {\n\tantlr4.tree.ParseTreeListener.call(this);\n\treturn this;\n}",
"visitSupplemental_db_logging(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitLog_file_group(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitRegister_logfile_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function isLogEnabled () {\n return flags.DEBUG || flags.LOG_ENABLED\n }",
"_initRequestLogger() {\n\t\tif (this.options.requestLogging) {\n\t\t\tthis.app.use(morgan('tiny', {\n\t\t\t\tstream: {\n\t\t\t\t\twrite: (message) => {\n\t\t\t\t\t\tlogger.info(message);\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}));\n\t\t}\n\t}",
"function getFightLogVarname() {\r\n return \"estiah_pvp_fight_log_\" + getUsername();\r\n}",
"function name_check() {\r\n name_warn();\r\n final_validate();\r\n}",
"function customFilterFactory(){\n return function(input){\n //change input\n return 'customFilter applied';\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
35 Write a limit function that allows a binary function to be called a limited amount of times. | function limit(binaryFunction, limit){
var round = 0;
return function (first, second){
if (round < limit){
round += 1;
return binaryFunction(first, second);
};
}
return undefined;
} | [
"function powersOfTwo(limit, f) {\n powers(2, limit, f);\n}",
"function looptoNumber (limit) {\n for (var i = 0; i<limit; i++) {\n console.log(i);\n }\n}",
"function throttleUpdateGauge(func, limit){\n var lastRunTime;\n var lastFunctionCalled;\n return function () {\n // first call\n if (!lastRunTime) {\n func.apply(null)\n lastRunTime = Date.now()\n } else {\n clearInterval(lastFunctionCalled)\n lastFunctionCalled = setTimeout(function(){\n // throttlings\n if ((Date.now() - lastRunTime) >= limit) {\n func.apply(null)\n lastRunTime = Date.now()\n }\n }, limit - (Date.now() - lastRunTime))\n }\n }\n }",
"function randomInteger(limit){\n\treturn Math.floor(Math.random() * limit);\n}",
"function smallEnough(a, limit){\n // const isBelowThreshold = (currentValue) => currentValue < limit;\n return a.every(currentValue => currentValue <= limit)\n\n}",
"buildLimit(t, value) {\n value = parseInt(value)\n if (value === 0)\n return t\n return t.limit(value)\n }",
"throttle (n) {\n return throttle(n, this)\n }",
"function limitedInterval(callback, waitTime, limitTime){\n let checkTime = 0;\n setInterval(() => {\n checkTime += waitTime;\n if(checkTime < limitTime){ \n callback();\n } else {\n clearInterval();\n }\n }, waitTime);\n}",
"_checkRateLimit (ts: number, limit: number, rates: number[]) {\n rates.push(ts)\n let edge = rates.find((d) => ts - 1000 < d)\n if (edge) rates.splice(0, rates.indexOf(edge))\n return rates.length <= limit\n }",
"repeat (n, f, o) { for (let i = 0; i < n; i++) f(i, o); return o }",
"function findMultiples(int,limit){\n //your code here\n let array = []\n for(i=1; i <= Math.floor(limit/int); i++) {\n array.push(int * i)\n }\n return array\n}",
"static evalReadingLengthWithinLimit(dict, limit) {\n return (dict.ReadingSim.toString().length <= Number(limit));\n }",
"function repeat(fn, n) {\nfor(let i=0; i<n; i++) {\n\tfn();\n}\n\n}",
"retry (fn, max, errorFunc) {\n const f = async () => {\n let error;\n for (let i = 0; i < max; i++) {\n try {\n return await fn();\n } catch (e) {\n if (this.debugging) {\n // eslint-disable-next-line\n debugger;\n }\n console.log(`caught ${i}`)\n if (errorFunc && !errorFunc(e)) {\n throw e;\n }\n error = e;\n }\n }\n console.log('out of retries');\n throw error;\n }\n return f()\n }",
"function faculteit(n) {\n\n}",
"function scheduler (func, n) {\n function delay (ttl, callback) {\n let now = Date.now();\n let curr = Date.now();\n while (curr - now < ttl){\n curr = Date.now();\n }\n callback();\n }\n \n delay(n*1000, func);\n}",
"get_currentLimit()\n {\n return this.liveFunc._currentLimit;\n }",
"function OneShotLimitReached()\n{\n\treturn (crashesStarted + gearShiftsStarted) > oneShotLimit;\n}",
"function fireEvery() {\n var currentCount = 0;\n return function(steps) {\n if (currentCount >= steps) {\n currentCount = 0;\n return true;\n } else {\n currentCount++;\n return false;\n }\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the equivalent islamic(civil) date value for a give input Gregorian date. `gDate` is a JS Date to be converted to Hijri. | fromGregorian(gDate) {
const gYear = gDate.getFullYear(), gMonth = gDate.getMonth(), gDay = gDate.getDate();
let julianDay = GREGORIAN_EPOCH - 1 + 365 * (gYear - 1) + Math.floor((gYear - 1) / 4) +
-Math.floor((gYear - 1) / 100) + Math.floor((gYear - 1) / 400) +
Math.floor((367 * (gMonth + 1) - 362) / 12 + (gMonth + 1 <= 2 ? 0 : isGregorianLeapYear(gDate) ? -1 : -2) + gDay);
julianDay = Math.floor(julianDay) + 0.5;
const days = julianDay - ISLAMIC_EPOCH;
const hYear = Math.floor((30 * days + 10646) / 10631.0);
let hMonth = Math.ceil((days - 29 - getIslamicYearStart(hYear)) / 29.5);
hMonth = Math.min(hMonth, 11);
const hDay = Math.ceil(days - getIslamicMonthStart(hYear, hMonth)) + 1;
return new NgbDate(hYear, hMonth + 1, hDay);
} | [
"function toJalali() {\n\n const DATE_REGEX = /^((19)\\d{2}|(2)\\d{3})-(([1-9])|((1)[0-2]))-([1-9]|[1-2][0-9]|(3)[0-1])$/;\n\n if (DATE_REGEX.test(mDate)) {\n\n let dt = mDate.split('-');\n let ld;\n\n let mYear = parseInt(dt[0]);\n let mMonth = parseInt(dt[1]);\n let mDay = parseInt(dt[2]);\n\n let buf1 = [12];\n let buf2 = [12];\n\n buf1[0] = 0;\n buf1[1] = 31;\n buf1[2] = 59;\n buf1[3] = 90;\n buf1[4] = 120;\n buf1[5] = 151;\n buf1[6] = 181;\n buf1[7] = 212;\n buf1[8] = 243;\n buf1[9] = 273;\n buf1[10] = 304;\n buf1[11] = 334;\n\n buf2[0] = 0;\n buf2[1] = 31;\n buf2[2] = 60;\n buf2[3] = 91;\n buf2[4] = 121;\n buf2[5] = 152;\n buf2[6] = 182;\n buf2[7] = 213;\n buf2[8] = 244;\n buf2[9] = 274;\n buf2[10] = 305;\n buf2[11] = 335;\n\n if ((mYear % 4) !== 0) {\n day = buf1[mMonth - 1] + mDay;\n\n if (day > 79) {\n day = day - 79;\n if (day <= 186) {\n switch (day % 31) {\n case 0:\n month = day / 31;\n day = 31;\n break;\n default:\n month = (day / 31) + 1;\n day = (day % 31);\n break;\n }\n year = mYear - 621;\n } else {\n day = day - 186;\n\n switch (day % 30) {\n case 0:\n month = (day / 30) + 6;\n day = 30;\n break;\n default:\n month = (day / 30) + 7;\n day = (day % 30);\n break;\n }\n year = mYear - 621;\n }\n } else {\n if ((mYear > 1996) && (mYear % 4) === 1) {\n ld = 11;\n } else {\n ld = 10;\n }\n day = day + ld;\n\n switch (day % 30) {\n case 0:\n month = (day / 30) + 9;\n day = 30;\n break;\n default:\n month = (day / 30) + 10;\n day = (day % 30);\n break;\n }\n year = mYear - 622;\n }\n } else {\n day = buf2[mMonth - 1] + mDay;\n\n if (mYear >= 1996) {\n ld = 79;\n } else {\n ld = 80;\n }\n if (day > ld) {\n day = day - ld;\n\n if (day <= 186) {\n switch (day % 31) {\n case 0:\n month = (day / 31);\n day = 31;\n break;\n default:\n month = (day / 31) + 1;\n day = (day % 31);\n break;\n }\n year = mYear - 621;\n } else {\n day = day - 186;\n\n switch (day % 30) {\n case 0:\n month = (day / 30) + 6;\n day = 30;\n break;\n default:\n month = (day / 30) + 7;\n day = (day % 30);\n break;\n }\n year = mYear - 621;\n }\n } else {\n day = day + 10;\n\n switch (day % 30) {\n case 0:\n month = (day / 30) + 9;\n day = 30;\n break;\n default:\n month = (day / 30) + 10;\n day = (day % 30);\n break;\n }\n year = mYear - 622;\n }\n\n }\n\n return year.toString() + \"-\" + Math.floor(month).toString() + \"-\" + day.toString();\n }\n}",
"function PARSEDATE(val) {\n\n /* *******************\n Extracted from Social Calc\n convert_date_julian_to_gregorian(juliandate)\n ymd->{}\n .year\n .month\n .day\n From: http://aa.usno.navy.mil/faq/docs/JD_Formula.html\n Uses: Fliegel, H. F. and van Flandern, T. C. (1968). Communications of the ACM, Vol. 11, No. 10 (October, 1968).\n Translated from the FORTRAN\n ************************* */\n function convert_date_julian_to_gregorian(juliandate) {\n\n var L, N, I, J, K;\n\n L = juliandate + 68569;\n N = Math.floor(4 * L / 146097);\n L = L - Math.floor((146097 * N + 3) / 4);\n I = Math.floor(4000 * (L + 1) / 1461001);\n L = L - Math.floor(1461 * I / 4) + 31;\n J = Math.floor(80 * L / 2447);\n K = L - Math.floor(2447 * J / 80);\n L = Math.floor(J / 11);\n J = J + 2 - 12 * L;\n I = 100 * (N - 49) + I + L;\n\n return new Date(I, J - 1, K);\n }\n\n if (val instanceof Error) {\n return val;\n } else if (typeof val === 'number') {\n // val is assumed to be serial number.\n return convert_date_julian_to_gregorian(Math.floor(val + JulianOffset));\n } else if (typeof val === 'string') {\n var timestamp = Date.parse(val);\n if (isNaN(timestamp)) {\n return error$2.value;\n }\n return new Date(timestamp);\n }\n\n return error$2.value;\n}",
"jYearToIYear(eraCode, jYear) {\n if (!this.isValidEraCode(eraCode)) {return (-1);} // eraCode not found \n const maxJYear = this.isNowEra(eraCode) ? 99 : this.yDict[eraCode].getNumYears(); // 99 if now era\n if (jYear>=1 && jYear<=maxJYear) { return this.yDict[eraCode].getStartYear() + parseInt(jYear) - 1; }\n return 0;\n }",
"toDateColombiaString(date){\n\t\tvar diaSemana = this.dayString[date.getDay()],\n\t\t mes = this.monthString[date.getMonth()]\n\t\treturn diaSemana+\" \"+date.getDate()+\" \"+mes+\" \"+date.getFullYear()\n\t}",
"function gage_getNextRainDate(j, aDate)\n//\n// Input: j = rain gage index\n// aDate = calendar date/time\n// Output: next date with rainfall occurring\n// Purpose: finds the next date from specified date when rainfall occurs.\n//\n{\n if ( Gage[j].isUsed == false ) return aDate;\n aDate += OneSecond;\n if ( aDate < Gage[j].startDate ) return Gage[j].startDate;\n if ( aDate < Gage[j].endDate ) return Gage[j].endDate;\n return Gage[j].nextDate;\n}",
"static today() {\n return NepaliDate.fromgregorian(new Date());\n }",
"function get_value_of_year_datum(f, yr, ck=current_key) {\n\tyr = parseInt(yr);\n\treturn mort_data['$'.concat(f)] && mort_data['$'.concat(f)]['$'.concat(ck)][yr];\n}",
"convertToPersianDate(value, format='YYYY-MM-DD hh:mm:ss a') {\n if (! value) {\n return value\n }\n \n let gregorianDate = this.fromAppTimezone(value)\n \n return new persianDate(moment(gregorianDate).toDate()).format(format)\n }",
"function getEarliestGraduationDateToAccept() {\n return getHackathonStartDate().subtract(1, 'year');\n}",
"function officialHoliday(date)\n{\n\tlet monthdate = date.substring(5),\n\t\tdayofweek = (new Date(date)).getDay(),\n\t\tMon = (dayofweek === 1),\n\t\tTue = (dayofweek === 2),\n\t\tWed = (dayofweek === 3),\n\t\tThai = {\n\t\t\t\"12-31\": \"Yearend\",\n\t\t\t\"01-01\": \"Newyear\",\n\t\t\t\"01-02\": (Mon || Tue) && \"Yearendsub\",\n\t\t\t\"01-03\": (Mon || Tue) && \"Newyearsub\",\n\t\t\t\"04-06\": \"Chakri\",\n\t\t\t\"04-07\": Mon && \"Chakrisub\",\n\t\t\t\"04-08\": Mon && \"Chakrisub\",\n\t\t\t\"04-13\": \"Songkran\",\n\t\t\t\"04-14\": \"Songkran\",\n\t\t\t\"04-15\": \"Songkran\",\n\t\t\t\"04-16\": (Mon || Tue || Wed) && \"Songkransub\",\n\t\t\t\"04-17\": (Mon || Tue || Wed) && \"Songkransub\",\n\t\t\t\"07-28\": \"King10\",\n\t\t\t\"07-29\": Mon && \"King10sub\",\n\t\t\t\"07-30\": Mon && \"King10sub\",\n\t\t\t\"08-12\": \"Queen\",\n\t\t\t\"08-13\": Mon && \"Queensub\",\n\t\t\t\"08-14\": Mon && \"Queensub\",\n\t\t\t\"10-13\": \"King09\",\n\t\t\t\"10-14\": Mon && \"King09sub\",\n\t\t\t\"10-15\": Mon && \"King09sub\",\n\t\t\t\"10-23\": \"Piya\",\n\t\t\t\"10-24\": Mon && \"Piyasub\",\n\t\t\t\"10-25\": Mon && \"Piyasub\",\n\t\t\t\"12-05\": \"King9\",\n\t\t\t\"12-06\": Mon && \"King9sub\",\n\t\t\t\"12-07\": Mon && \"King9sub\",\n\t\t\t\"12-10\": \"Constitution\",\n\t\t\t\"12-11\": Mon && \"Constitutionsub\",\n\t\t\t\"12-12\": Mon && \"Constitutionsub\"\n\t\t},\n\t\tgovHoliday = Thai[monthdate]\n\n\tif (govHoliday) {\n\t\treturn `url('css/pic/holiday/${govHoliday}.png')`\n\t}\n}",
"function MascaraRG(rg) {\n if (mascaraInteiro(rg) == false) {\n event.returnValue = false;\n }\n return formataCampo(rg, '00.000.000-0', event);\n}",
"GenerateStarDate() {\n\t\tlet date = new Date();\n\t\tdate.setDate(date.getDate() - 30);\n\t\tlet month = (date.getMonth() + 1).toString();\n\t\tlet day = date.getDate().toString();\n\t\tif (day.length < 2)\n\t\t\tday = \"0\" + day;\n\t\tif (month.length < 2)\n\t\t\tmonth = \"0\" + month;\n\t\tconst stringDate = date.getFullYear() + \"-\" + month + \"-\" + day;\n\t\treturn stringDate;\n\t}",
"toDateColombiaShortString(date){\n\t\tvar dateSplit = date.split('-')\n\t\treturn this.getFullMonthName(dateSplit[1]-1)+\" \"+dateSplit[2]+\" \"+dateSplit[0]\n\t}",
"toDateString() {\n return `${this.nepaliYear.toString()}/${this.nepaliMonth}/${\n this.nepaliDay\n }`;\n }",
"function GalacticTest(year,month,day) {\n this.earthBirthday = new Date(year,month,day)\n this.testDate = new Date(2019,0,1)\n this.earthYears = Math.floor(this.dateDifference()/365)\n}",
"function dateGetYear(dateS) {\n if (!dateS) // empty, null or undefined date string\n return null;\n\n return (new Date(dateS)).getFullYear();\n}",
"function changeImmYear()\n{\n let form = this.form;\n let censusId = form.Census.value;\n let censusYear = censusId.substring(censusId.length - 4);\n let immyear = this.value;\n if (this.value == '[')\n {\n this.value = '[Blank';\n }\n let res = immyear.match(/^[0-9]{4}$/);\n if (!res)\n { // not a 4 digit number\n res = immyear.match(/^[0-9]{2}$/);\n if (res)\n { // 2 digit number\n // expand to a 4 digit number which is a year in the\n // century up to and including the census year\n immyear = (res[0] - 0) + 1900;\n while (immyear > censusYear)\n immyear -= 100;\n this.value = immyear;\n } // 2 digit number\n } // not a 4 digit number\n\n this.checkfunc();\n}",
"function obtener_fecha_hoy() {\n return new Date();\n}",
"function formaterDatePubli(dateJson, format) {\n let dateJ = new Date(dateJson);\n let dateP = formater2Digits(dateJ.getDate()) + \"/\" +\n formater2Digits(dateJ.getMonth() + 1);\n if (format === \"jma\") {\n dateP += \"/\" + dateJ.getFullYear();\n }\n return dateP;\n}",
"function setInitialDate() {\n \n // CREATE A NEW DATE OBJECT (WILL GENERALLY PARSE CORRECT DATE EXCEPT WHEN \".\" IS USED AS A DELIMITER)\n // (THIS ROUTINE DOES *NOT* CATCH ALL DATE FORMATS, IF YOU NEED TO PARSE A CUSTOM DATE FORMAT, DO IT HERE)\n calDate = new Date(inDate);\n\n // IF THE INCOMING DATE IS INVALID, USE THE CURRENT DATE\n if (isNaN(calDate) || inDate == \"\" || inDate == null) {\n\n // ADD CUSTOM DATE PARSING HERE\n // IF IT FAILS, SIMPLY CREATE A NEW DATE OBJECT WHICH DEFAULTS TO THE CURRENT DATE\n calDate = new Date();\n }\n\n // KEEP TRACK OF THE CURRENT DAY VALUE\n calDay = calDate.getDate();\n\n // SET DAY VALUE TO 1... TO AVOID JAVASCRIPT DATE CALCULATION ANOMALIES\n // (IF THE MONTH CHANGES TO FEB AND THE DAY IS 30, THE MONTH WOULD CHANGE TO MARCH\n // AND THE DAY WOULD CHANGE TO 2. SETTING THE DAY TO 1 WILL PREVENT THAT)\n calDate.setDate(1);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Patches the 'scroll' method on the Window prototype | function patchWindowScroll() {
window.scroll = function (optionsOrX, y) {
handleScrollMethod(this, "scroll", optionsOrX, y);
};
} | [
"handleWindowScroll() {\n const sectionHTMLElement = this.sectionHTMLElement.current;\n const { top } = sectionHTMLElement.getBoundingClientRect();\n\n const shouldUpdateForScroll = Section.insideScrollRangeForUpdates.call(this, top);\n if ( shouldUpdateForScroll ) {\n\n this.updateParallaxForScrollPosition(top);\n }\n }",
"__patchWheelOverScrolling() {\n this.$.selector.addEventListener('wheel', (e) => {\n const scrolledToTop = this.scrollTop === 0;\n const scrolledToBottom = this.scrollHeight - this.scrollTop - this.clientHeight <= 1;\n if (scrolledToTop && e.deltaY < 0) {\n e.preventDefault();\n } else if (scrolledToBottom && e.deltaY > 0) {\n e.preventDefault();\n }\n });\n }",
"function __scrollHandler__() {\n\t\tvar topMostDlg = __findTopMostDialog__();\n\t\tif (topMostDlg) {\n\t\t\ttopMostDlg._handleScroll();\n\t\t}\n\t}",
"handleScroll_() {\n this.resetAutoAdvance_();\n }",
"storeScrollPosition () {\n document.documentElement.dataset.scroll = window.scrollY;\n }",
"function scroll (e) {\n var xyS = scrollXY(iwin) // iframe scroll\n var ifrPos = xy.add(xyS, lastMousePos)\n coords.show(xy.str(ifrPos))\n }",
"_onScrollEvent(actor, event) {\n if (this._settings.get_boolean('disable-scroll') &&\n this._autohideStatus &&\n this._slider.slidex == 0 && // Need to check the slidex for partially showing dock\n (this._dockState == DockState.HIDDEN || this._dockState == DockState.HIDING))\n return Clutter.EVENT_STOP;\n\n let workspaceManager = global.workspace_manager;\n let activeWs = workspaceManager.get_active_workspace();\n let direction;\n switch (event.get_scroll_direction()) {\n case Clutter.ScrollDirection.UP:\n if (this._isHorizontal && this._settings.get_boolean('horizontal-workspace-switching')) {\n direction = Meta.MotionDirection.LEFT;\n } else {\n direction = Meta.MotionDirection.UP;\n }\n break;\n case Clutter.ScrollDirection.DOWN:\n if (this._isHorizontal && this._settings.get_boolean('horizontal-workspace-switching')) {\n direction = Meta.MotionDirection.RIGHT;\n } else {\n direction = Meta.MotionDirection.DOWN;\n }\n break;\n case Clutter.ScrollDirection.LEFT:\n if (this._isHorizontal && this._settings.get_boolean('horizontal-workspace-switching')) {\n direction = Meta.MotionDirection.LEFT;\n }\n break;\n case Clutter.ScrollDirection.RIGHT:\n if (this._isHorizontal && this._settings.get_boolean('horizontal-workspace-switching')) {\n direction = Meta.MotionDirection.RIGHT;\n }\n break;\n }\n\n if (direction) {\n if (this._settings.get_boolean('scroll-with-touchpad')) {\n // passingthru67: copied from dash-to-dock\n // Prevent scroll events from triggering too many workspace switches\n // by adding a 250ms deadtime between each scroll event.\n // Usefull on laptops when using a touchpad.\n\n // During the deadtime do nothing\n if(this._scrollWorkspaceSwitchDeadTimeId > 0)\n return false;\n else {\n this._scrollWorkspaceSwitchDeadTimeId =\n GLib.timeout_add(GLib.PRIORITY_DEFAULT, 250, () => {\n this._scrollWorkspaceSwitchDeadTimeId = 0;\n });\n }\n }\n\n let ws = activeWs.get_neighbor(direction);\n\n if (Main.wm._workspaceSwitcherPopup == null) {\n Main.wm._workspaceSwitcherPopup = new WorkspaceSwitcherPopup.WorkspaceSwitcherPopup();\n }\n\n // Set the workspaceSwitcherPopup actor to non reactive,\n // to prevent it from grabbing focus away from the dock\n Main.wm._workspaceSwitcherPopup.reactive = false;\n Main.wm._workspaceSwitcherPopup.connect('destroy', function() {\n Main.wm._workspaceSwitcherPopup = null;\n });\n\n // Do not show wokspaceSwitcher in overview\n if (!Main.overview.visible)\n Main.wm._workspaceSwitcherPopup.display(direction, ws.index());\n\n Main.wm.actionMoveWorkspace(ws);\n }\n\n return Clutter.EVENT_STOP;\n }",
"function detectScroll(){\n\tvar percent = _scrollTop() / ( _scrollHeight() - _innerHeight() );\n\tif(oldPercent != percent)\n\t{\n\t\tif(percent >= 0){\n\t\t\toldPercent = percent;\n\t\t\tgetFlash().scrollFlash( percent, 0 );\n\t\t} \n\t}\n}",
"function scroll(e) {\n $iFrame.contentWindow.postMessage({\n sender: sender,\n type: 'scroll',\n scroll: {\n left: ($window.pageXOffset || $documentElement.scrollLeft) - ($documentElement.clientLeft || 0),\n top: ($window.pageYOffset || $documentElement.scrollTop) - ($documentElement.clientTop || 0)\n }\n }, '*');\n }",
"function onScroll(e) {\n\n\t\t// this.scrollLeft/Top is faster then $(this).scrollLeft/Top()\n\t\tvar newLeft = this.scrollLeft;\n\t\tvar newTop = this.scrollTop;\n\n\t\tvar xVector = newLeft - e.data.left;\n\t\tvar yVector = newTop - e.data.top;\n\n\t\tif (xVector)\n\t\t\t$(this).trigger('scrollx', xVector);\n\t\tif (yVector)\n\t\t\t$(this).trigger('scrolly', yVector);\n\n\t\te.data.left = newLeft;\n\t\te.data.top = newTop;\n\t}",
"onScroll_() {\n if (!this.isActive_()) {\n return;\n }\n this.vsync_.run(\n {\n measure: state => {\n state.shouldBeFullBleed =\n this.getOverflowContainer_()./*OK*/ scrollTop >=\n FULLBLEED_THRESHOLD;\n },\n mutate: state => {\n this.getShadowRoot().classList.toggle(\n FULLBLEED_CLASSNAME,\n state.shouldBeFullBleed\n );\n },\n },\n {}\n );\n }",
"function fixScroller() {\n var messageBody = document.querySelector(\".message-scrollbar\");\n messageBody.scrollTop = messageBody.scrollHeight - messageBody.clientHeight;\n }",
"function icinga_reload_scroll_position() {\n\t/* save current scrolling position */\n\tscroll_pos = icinga_get_scroll_position();\n\n\t/* if scroll position is zero, remove it from the url and reload\n\t if scroll position is NOT zero, add/update scroll option and reload */\n\twindow.location.href = icinga_update_url_option(window.location.href, \"scroll\", (scroll_pos <= 0) ? null : scroll_pos);\n}",
"function scrollRefraction(){\n simBorder = simSection.getBoundingClientRect();\n simOrigin.y = simBorder.y;\n onScreen = false;\n if(simBorder.top < h && simBorder.bottom > 0)\n onScreen = true;\n}",
"saveScrollAndFocus () {\n this.activeElement = document.activeElement; // returning focus from ReactModal is not working properly, so storing a reference in here to return it\n this.scrollingParent = document.activeElement && findFirstScrollableParent(document.activeElement) || window;\n this.scrollTop = this.scrollingParent.pageYOffset || this.scrollingParent.scrollTop || 0; // for window it's pageYOffset, for other elements it's scrollTop\n }",
"function notifyExtensionScrollingStopped(){\n browser.runtime.sendMessage({'message': 'stopped'});\n}",
"onScroll(e) {\n let scrollTop = e.target.scrollTop;\n if (this._silent || this.smoothScroll.running || Math.abs(scrollTop - this.smoothScroll.target) <= 0.5 || !this.props.onScroll) return;\n this.props.onScroll(scrollTop);\n }",
"setupScrollSync () {\n const headerMiddleSelector = this.get('_headerMiddleSelector')\n const bodyLeftSelector = this.get('_bodyLeftSelector')\n const bodyMiddleSelector = this.get('_bodyMiddleSelector')\n const bodyRightSelector = this.get('_bodyRightSelector')\n\n this.syncScrollLeft(headerMiddleSelector, bodyMiddleSelector)\n this.syncScrollLeft(bodyMiddleSelector, headerMiddleSelector)\n\n this.syncScrollTop(bodyLeftSelector, bodyMiddleSelector, bodyRightSelector)\n this.syncScrollTop(bodyMiddleSelector, bodyLeftSelector, bodyRightSelector)\n this.syncScrollTop(bodyRightSelector, bodyLeftSelector, bodyMiddleSelector)\n }",
"_listenToScrollEvents() {\n this._viewportScrollSubscription = this._dragDropRegistry\n .scrolled(this._getShadowRoot())\n .subscribe(event => {\n if (this.isDragging()) {\n const scrollDifference = this._parentPositions.handleScroll(event);\n if (scrollDifference) {\n this._sortStrategy.updateOnScroll(scrollDifference.top, scrollDifference.left);\n }\n }\n else if (this.isReceiving()) {\n this._cacheParentPositions();\n }\n });\n }",
"function getScrollOffset() {\n return {\n x: main.scrollLeft,\n y: main.scrollTop };\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find all recipients in airtable (all pages) Resolves with a list of airtable recipient objects | findAll() {
return new Promise((resolve, reject) => {
let results = []
base('Recipients')
.select()
.eachPage(
(records, fetchNextPage) => {
results = [...results, ...records]
fetchNextPage()
},
async (err) => {
if (err) return reject(err)
resolve(results)
}
)
})
} | [
"getRecipients() {\n return new Promise((resolve, reject) => {\n Action.find().distinct('toAddress', (error, address) => {\n if(error) { reject; return; }\n resolve(address)\n })\n })\n }",
"createRecipients() {\n const recipientsCount = textUtils.getRandomNumber(1, maxConcurrency);\n const recipientsList = [];\n for (let i = 0; i < recipientsCount; i++) {\n const { name, phone, email } = coreUtils.generateRecipient();\n recipientsList.push({ fullName: name, email });\n this.database.recipients.push(new RecipientModel({\n fullName: name,\n emailAddress: email,\n phoneNumber: phone,\n isoCode: textUtils.getRandomItem(this.database.languages).isoCode,\n timezoneCode: textUtils.getRandomItem(this.database.timezones).code,\n /*\n For simplicity we will not use this field. But it worth declaration,\n because in the real world, not every recipient is subscribed to the\n mailing list.\n */\n isSubscribed: textUtils.getRandomBoolean()\n }));\n }\n return recipientsList;\n }",
"participants({includeFrom = true, includeBcc = false} = {}) {\n const seen = {}\n const all = []\n let contacts = [].concat(this.to, this.cc)\n if (includeFrom) {\n contacts = _.union(contacts, (this.from || []))\n }\n if (includeBcc) {\n contacts = _.union(contacts, (this.bcc || []))\n }\n for (const contact of contacts) {\n if (!contact.email) {\n continue\n }\n const key = contact.toString().trim().toLowerCase()\n if (seen[key]) {\n continue;\n }\n seen[key] = true\n all.push(contact)\n }\n return all\n }",
"participantsForReplyAll() {\n const excludedFroms = this.from.map((c) =>\n Utils.toEquivalentEmailForm(c.email)\n );\n\n const excludeMeAndFroms = (cc) =>\n _.reject(cc, (p) =>\n p.isMe() || _.contains(excludedFroms, Utils.toEquivalentEmailForm(p.email))\n );\n\n let to = null\n let cc = null\n\n if (this.replyTo.length) {\n to = this.replyTo\n cc = excludeMeAndFroms([].concat(this.to, this.cc))\n } else if (this.isFromMe()) {\n to = this.to\n cc = excludeMeAndFroms(this.cc)\n } else {\n to = this.from\n cc = excludeMeAndFroms([].concat(this.to, this.cc))\n }\n\n to = _.uniq(to, (p) => Utils.toEquivalentEmailForm(p.email))\n cc = _.uniq(cc, (p) => Utils.toEquivalentEmailForm(p.email))\n return {to, cc}\n }",
"ListOfSubscribers(domain, name, email) {\n let url = `/email/domain/${domain}/mailingList/${name}/subscriber?`;\n const queryParams = new query_params_1.default();\n if (email) {\n queryParams.set('email', email);\n }\n return this.client.request('GET', url + queryParams.toString());\n }",
"function getEmails() {\n let promise = userIdsRef.get().then(querySnap => {\n let usersEmails = [];\n querySnap.forEach(doc => {\n let thatEmail = doc.data().email;\n usersEmails.push(thatEmail);\n });\n return usersEmails;\n });\n return promise;\n}",
"GetResponders(domain, account) {\n let url = `/email/domain/${domain}/responder?`;\n const queryParams = new query_params_1.default();\n if (account) {\n queryParams.set('account', account);\n }\n return this.client.request('GET', url + queryParams.toString());\n }",
"function filterTableOnAddresses(){\n //get current table elements\n var tableBodyChildrenArray = Array.from(tableBody.children);\n //iterate through each element that is currently in the table and check if one of its addresses starts with the search string\n tableBodyChildrenArray.forEach(function(child){\n var contractAddressString = child.querySelector(\".contractAddress\").innerText.trim();\n var payerAddressString = child.querySelector(\".payerAddress\").innerText.trim();\n var recipientAddressString = child.querySelector(\".recipientAddress\").innerText.trim();\n\n if(!contractAddressString.startsWith(String(addressFilter.value.trim()))\n && !payerAddressString.startsWith(String(addressFilter.value.trim()))\n && !recipientAddressString.startsWith(String(addressFilter.value.trim()))){\n child.style.display = 'none';\n }\n else{\n child.style.display = 'table-row';\n }\n });\n}",
"getEmails(callback) {\n this.emailTracking\n .orderBy(\"created_at\")\n .onSnapshot(snapshot => {\n snapshot.docChanges().forEach(change => {\n if(change.type === \"added\") {\n // do stuff with all emails in the database (check for time, check for seats, etc)\n // console.log(\"going through emails\");\n callback(change.doc.data());\n }\n })\n })\n }",
"sendEmailList (e, template) {\n var subscribers = this.getSubscribers(); //list of subscriber objects\n subscribers.forEach((subscriber) => {this.sendEmail(e, template, subscriber)});\n console.log('Emails sent')\n }",
"updateRecipientsTable() {\n\t\tlet recipients = [];\n\t\tlet unreadMessages = 0;\n\n\t\t// Check number of unread messages for each recipient\n\t\tthis.manager\n\t\t\t.get(\"WWSUrecipients\")\n\t\t\t.find()\n\t\t\t.forEach(recipient => {\n\t\t\t\trecipient.unreadMessages = 0;\n\t\t\t\tthis.find({ from: recipient.host, status: \"active\" }).forEach(\n\t\t\t\t\tmessage => {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t(message.to === \"DJ\" ||\n\t\t\t\t\t\t\t\tmessage.to === \"DJ-private\" ||\n\t\t\t\t\t\t\t\tmessage.to ===\n\t\t\t\t\t\t\t\t\tthis.manager.get(\"WWSUrecipients\").recipient.host) &&\n\t\t\t\t\t\t\tthis.read.indexOf(message.ID) === -1\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\trecipient.unreadMessages++;\n\t\t\t\t\t\t\tunreadMessages++;\n\n\t\t\t\t\t\t\t// Notify new messages\n\t\t\t\t\t\t\tif (!this.firstLoad && this.notified.indexOf(message.ID) === -1) {\n\t\t\t\t\t\t\t\tthis.notified.push(message.ID);\n\t\t\t\t\t\t\t\tthis.emitEvent(\"newMessage\", [message]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t\trecipients.push(recipient);\n\t\t\t});\n\n\t\t// Update table\n\t\tthis.manager.get(\"WWSUrecipients\")._updateTable(recipients);\n\n\t\t// Update unread messages stuff\n\t\tif (unreadMessages <= 0) {\n\t\t\t$(this.menuNew).html(`0`);\n\t\t\t$(this.menuNew).removeClass(`badge-danger`);\n\t\t\t$(this.menuNew).addClass(`badge-secondary`);\n\t\t\t$(this.menuIcon).removeClass(`pulse-success`);\n\t\t} else {\n\t\t\t$(this.menuNew).html(unreadMessages);\n\t\t\t$(this.menuNew).removeClass(`badge-secondary`);\n\t\t\t$(this.menuNew).addClass(`badge-danger`);\n\t\t\t$(this.menuIcon).addClass(`pulse-success`);\n\t\t}\n\t\tthis.firstLoad = false;\n\t}",
"DelegatedEmails(accountName, domain) {\n let url = `/email/domain/delegatedAccount?`;\n const queryParams = new query_params_1.default();\n if (accountName) {\n queryParams.set('accountName', accountName);\n }\n if (domain) {\n queryParams.set('domain', domain);\n }\n return this.client.request('GET', url + queryParams.toString());\n }",
"GetMailingLists(domain, name) {\n let url = `/email/domain/${domain}/mailingList?`;\n const queryParams = new query_params_1.default();\n if (name) {\n queryParams.set('name', name);\n }\n return this.client.request('GET', url + queryParams.toString());\n }",
"function getMyEmailAddresses(){\n var myaddy = GmailApp.getAliases() || [],\n x;\n if ((x = Session.getEffectiveUser().getEmail()) && myaddy.indexOf(x) === -1){\n myaddy.push(x);\n }\n return myaddy;\n}",
"function getAddressForRecipient() {\r\n dojo.require(\"dojo.data.ItemFileWriteStore\");\r\n dojo.require(\"dojox.xml.parser\");\r\n\r\n // Get the client and activity drop down fields\r\n var recipientDropDown = dijit.byId(\"__o3id1\");\r\n var recipientAddressDropDown = dijit.byId(\"__o3id2\");\r\n\r\n var recipientDropDownStore = recipientDropDown.store;\r\n\r\n\r\n // Reset the combo box if no client is selected\r\n // BEGIN, CR00348478, SSK \r\n if(recipientDropDown.item.id == '') {\r\n // END, CR00348478\r\n var recipientAddressDropDownStore = new dojo.data.ItemFileWriteStore({\r\n data: {\r\n label: \"name\",\r\n identifier: \"value\",\r\n items: [{name:\"\", value:\"\"}]}});\r\n // BEGIN, CR00348478, SSK\r\n recipientAddressDropDown.set(\"store\", recipientAddressDropDownStore);\r\n recipientAddressDropDown.set(\"value\", \"\");\r\n // END, CR00348478\r\n return;\r\n }\r\n\r\n // Get the selected value\r\n var recipientDropDownValue = recipientDropDown.item.value;\r\n\r\n // Construct the url to retrieve the list of addresses\r\n var serverUrl = \"../servlet/FileDownload?pageID=ListAddressesForServiceRecipient&caseParticipantRoleID=\" + recipientDropDownValue;\r\n\r\n dojo.xhrGet({\r\n url: serverUrl,\r\n handleAs: \"text\",\r\n timeout: 5000,\r\n load: function(response) {\r\n\r\n // Parse the xml text returned from the server\r\n var xmlDoc = dojox.xml.parser.parse(response);\r\n var clientAddresses = xmlDoc.getElementsByTagName(\"clientAddress\");\r\n\r\n var newAddressDropDownStore = new dojo.data.ItemFileWriteStore({\r\n data: {\r\n label: \"name\",\r\n identifier: \"value\",\r\n items: [{name:\"\", value:\"\"}]}});\r\n\r\n // Loop through the list of client addresses adding them to the drop down field\r\n for (var i = 0; i < clientAddresses.length; i++) {\r\n newAddressDropDownStore.newItem({name: clientAddresses[i].getAttribute(\"displayValue\"), value: clientAddresses[i].getAttribute(\"hiddenValue\")});\r\n }\r\n\r\n\t\t// BEGIN, CR00348478, SSK \r\n recipientAddressDropDown.set(\"store\", newAddressDropDownStore);\r\n recipientAddressDropDown.set(\"value\", \"\");\r\n // END, CR00348478\r\n\r\n return response;\r\n },\r\n error: function(error) {\r\n console.log(error);\r\n return response;\r\n }\r\n });\r\n }",
"function CategoryIndexedRecipients(recipients) {\n if (recipients === void 0) { recipients = []; }\n /**\n * The selected recipients for the form\n */\n this._recipients = [];\n this._recipients = recipients.slice();\n }",
"SendModeratorsListAndSubscribersListOfThisMailingListByEmail(domain, email, name) {\n let url = `/email/domain/${domain}/mailingList/${name}/sendListByEmail`;\n return this.client.request('POST', url, { email });\n }",
"function showAddresses(addresses) {\n console.log('Address:')\n for (let address of addresses) {\n console.log(address);\n }\n}",
"function getPartnersList(radius, lat, lon, partners) {\r\n var result = [];\r\n // validate the input, if they are number\r\n if (radius && !isNaN(radius) && lat && !isNaN(lat) && lon && !isNaN(lon) && typeof (partners) === 'object') {\r\n try {\r\n for (var p of partners) {\r\n if (p && p.offices) {\r\n for (var o of p.offices) {\r\n const point2 = o.coordinates.split(','); // split coordinates to get lat & lon\r\n if (point2 && point2.length === 2) {\r\n const dist = distance(lat, lon, Number(point2[0]), Number(point2[1]));\r\n //console.log(dist);\r\n if (dist <= radius) {\r\n result.push({\r\n 'companyName': p.organization,\r\n 'address': (o.address) ? o.address : ''\r\n });\r\n }\r\n } else {\r\n throw \"Error: Invalid coordinates for \" + JSON.stringify(p);\r\n }\r\n }\r\n }\r\n }\r\n return sort(result);\r\n } catch (e) {\r\n console.log(e);\r\n }\r\n } else {\r\n console.log(\"Error: Invalid argument\");\r\n }\r\n return result;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this fucntion make a nComb random combinations of a matrix spectra | function generator(spectra, options) {
let options = Object.assign({}, {nComb: 1, threshold: 0.5}, options)
var weights = new Array(options.nComb);
var combinations = new Array(options.nComb);
for (var i = 0; i < options.nComb; i++) {
var tmp = new Array(spectra[0].length).fill(0);
var weight = new Array(spectra.length);
for(var j = 0; j < spectra.length; j++) {
weight[j] = Math.random();
if (Math.random() > options.threshold) {
for (var k = 0; k < spectra[0].length; k++) {
tmp[k] += spectra[j][k]*weight[j];
}
} else weight[j] = 0;
}
weights[i] = weight;
combinations[i] = tmp;
}
return {weights: weights, combinations: combinations};
} | [
"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}",
"function createBoard(count, colorList) {\n var board = []\n for(var i = 0 ; i < count ; i++) {\n var lane = []\n for(var j = 0 ; j < count ; j++) {\n lane.push(colorList[Math.floor(Math.random() * colorList.length)])\n }\n board.push(lane)\n }\n return board\n}",
"function generateRefractors(){\n refractorSet.clear();\n let refractorRows = Math.floor(1.5 + simHeight / 300);\n let refractorCols = Math.floor(1.5 + simWidth / 300);\n\n let rowSpace = simHeight / (refractorRows);\n let colSpace = simWidth / (refractorCols);\n\n let triangleRadius = Math.min(rowSpace / 2 - (7 + simHeight / 50), colSpace / 2 - (7 + simWidth / 50));\n\n for(let i = 0; i < refractorCols; i ++)\n {\n for(let j = 0; j < refractorRows; j ++)\n {\n if(i != 0 || refractorRows % 2 == 0 || j != Math.floor(refractorRows / 2)){\n let center = new Vector(colSpace / 2 + colSpace * i, rowSpace / 2 + rowSpace * j);\n let ang = Math.random() * Math.PI * 2;\n let p1 = addVectors(angleMagVector(ang, triangleRadius), center);\n ang += Math.PI / 3 + Math.random() * Math.PI * .4;\n let p2 = addVectors(angleMagVector(ang, triangleRadius), center);\n ang += Math.PI / 3 + Math.random() * Math.PI * .4;\n let p3 = addVectors(angleMagVector(ang, triangleRadius), center);\n\n refractorSet.add(new SimVector(p1, subVectors(p2, p1)));\n refractorSet.add(new SimVector(p2, subVectors(p3, p2)));\n refractorSet.add(new SimVector(p3, subVectors(p1, p3)));\n }\n }\n }\n}",
"function generateRandomConfig(n) {\n var object = {};\n var listOfNonUsed = [];\n\n for (var i = 0; i < n; i++) {\n listOfNonUsed.push(i);\n }\n\n for (var i=0; i < n; i++) {\n var index = Math.floor((Math.random() * listOfNonUsed.length));\n var element = listOfNonUsed.splice(index,1)[0];\n object[i] = element;\n }\n\n return object;\n}",
"function getRandomNum() {\n var random = Math.floor(Math.random() * 4);\n simonSeq.push(colorArr[random]);\n }",
"function randomColorGrid() {\n var i, j;\n for (i = 0; i < width/BLOCK_SIZE; i++) {\n for (j = 0; j < height/BLOCK_SIZE; j++) {\n colorGrid[i][j] = getRandomColor();\n }\n }\n draw();\n }",
"function deckMC(qarray, aarray, n){\n var deck = [];\n var j;\n var k;\n var l;\n var m;\n var i;\n var isUsed = [];\n isUsed.length = n;\n for (i = 0; i < n; i++){\n isUsed[i] = false;\n }\n //Randomly choose n questions from the array as well as 3 random answers\n for (i = 0; i < n; i++){\n m = (Math.floor(Math.random() * n));\n while (isUsed[m]){\n m = (Math.floor(Math.random() * n));\n isUsed[m] = true;\n } \n j = (Math.floor(Math.random() * n));\n k = (Math.floor(Math.random() * n));\n l = (Math.floor(Math.random() * n));\n while (j===m){\n j = Math.floor((Math.random() * n)); \n }\n while (k===m || k === j){\n k = Math.floor((Math.random() * n));\n }\n while (l===m || l === k || l === j){\n l = Math.floor((Math.random() * n));\n }\n var fc;\n fc = new flashCardMC(qarray[m], aarray[m], aarray[j], aarray[k], aarray[l]);\n deck.push(fc);\n }\n this.deck = deck;\n this.length = deck.length;\n }",
"function getSpec(){\n specNum = Math.floor(Math.random()*speciesA.length);\n \n }",
"function makeNewGrid(){\r\n var chromosome = [5];\r\n chromosome[0] = Math.floor(Math.random()*25);//how much each cell can deviate\r\n chromosome[1] = Math.floor(Math.random()*100);//how saturated the blocks are\r\n chromosome[2] = Math.floor(Math.random()*360);//max saturation value \r\n chromosome[3] = Math.floor(Math.random()*2);//cirlce or square\r\n chromosome[4] = Math.floor(Math.random()*4);//what kind of art style\r\n \r\n return chromosome;\r\n}",
"function createRandomCatalog(num) {\n let catalog = [];\n for(let i = 0; i < num; i++) {\n let item = createRandomObject();\n let product = {id: i+1, price: item.price, type: item.type};\n \n catalog.push(product);\n }\n return catalog;\n }",
"function createCongruencyArray(batchSize, blockLetter){\n // calc how mnay congruent/incongruent trials are needed\n let nConTrials = Math.ceil(getBlockCongruencies(blockLetter).ct_con * batchSize);\n let nIncTrials = batchSize - nConTrials;\n // nIncTrials = Math.ceil(getBlockCongruencies(blockLetter).fl_inc * batchSize);\n\n // array of congruent and incongruent trials\n let congruenciesArr = new Array(nConTrials).fill(\"c\").concat(new Array(nIncTrials).fill(\"i\"));\n\n // return shuffled array\n return shuffle(congruenciesArr);\n}",
"function generateTargets() {\n let number = 10;\n let result = [];\n while (result.length < number) {\n result.push({\n id: 'target-' + result.length,\n x: stage.width() * Math.random(),\n y: stage.height() * Math.random()\n });\n }\n return result;\n}",
"function randomSequence(){\n\t\t\tvar sequence = [];\n\t\t\tfor(var i = 0; i < 20; i++){\n\t\t\t\tsequence.push(Math.floor((Math.random()*100)%4)+1);\n\t\t\t}\n\t\t\treturn sequence;\n\t\t}",
"function getRandomCell(winCombs) {\n return winCombs[Math.floor(Math.random() * winCombs.length)];\n}",
"function genSeeds() {\r\n analyser.getByteTimeDomainData(dataArray);\r\n sliceSize = Math.floor(bufferLength / 5);\r\n\r\n var sum = 0;\r\n var scaleFactor = 138.0;\r\n\r\n // Seed A\r\n for (var i = 0; i < sliceSize; i++) {\r\n var v = dataArray[i] / scaleFactor;\r\n if (v > 1) { v = 1 };\r\n sum += v;\r\n }\r\n seedA = sum / (bufferLength/5)\r\n sum = 0;\r\n\r\n // Seed B\r\n for (var i = sliceSize; i < 2*sliceSize; i++) {\r\n var v = dataArray[i] / scaleFactor;\r\n if (v > 1) { v = 1 };\r\n sum += v;\r\n }\r\n seedB = sum / sliceSize\r\n sum = 0;\r\n\r\n // Seed C\r\n for (var i = 2*sliceSize; i < 3*sliceSize; i++) {\r\n var v = dataArray[i] / scaleFactor;\r\n if (v > 1) { v = 1 };\r\n sum += v;\r\n }\r\n seedC = sum / sliceSize\r\n sum = 0;\r\n\r\n // Seed D\r\n for (var i = 3*sliceSize; i < 4*sliceSize; i++) {\r\n var v = dataArray[i] / scaleFactor;\r\n if (v > 1) { v = 1 };\r\n sum += v;\r\n }\r\n seedD = sum / sliceSize\r\n sum = 0;\r\n\r\n // Seed E\r\n for (var i = 4*sliceSize; i < 5*sliceSize; i++) {\r\n var v = dataArray[i] / scaleFactor;\r\n if (v > 1) { v = 1 };\r\n sum += v;\r\n }\r\n seedE = sum / sliceSize\r\n sum = 0;\r\n\r\n console.log(`A: ${seedA}, B: ${seedB}, C: ${seedC}, D: ${seedD}, E: ${seedE}`);\r\n}",
"function rand(n1,n2,e) {\n if (e == undefined) { e = 0; }\n if (n1 == undefined && n2 == undefined) { return Math.random() * 2 - 1; }\n var data = Array.from(Array(n1),() => new Array(n2)); \n // benefit from creating array this way is a.length = number of rows and a[0].length = number of columns \n for (var i = 0; i < n1; i++) {\n for (var j = 0; j < n2; j++) {\n data[i][j] = e + Math.random() * 2 - 1;\n }\n }\n return round(data,10);\n}",
"function makeTestTrials() {\n \n var pr = []; pc = [];\n if (debugging) {\n pr = [0,1,2,3];\n pc = [0];\n pr = shuffleArray(pr);\n } else {\n pr = [0,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,26,27,28,29,30,31,32,33];\n pc = [0,1,2,3,4,5,6,7];\n pr = shuffleArray(pr);\n pc = shuffleArray(pc);\n }\n \n // if debugging just have one test trial of each type\n if (debugging) {\n \n // one pattern recognition item with one foil\n patternrecogTarget[pr[0]] = hardtriplets[0]; \n patternrecogFoilsone[pr[0]] = [stimset[1], stimset[12], stimset[7]];\n patternrecogFoilstwo[pr[0]] = [\"white.jpg\",\"white.jpg\",\"white.jpg\"];\n patternrecogFoilsthree[pr[0]] = [\"white.jpg\",\"white.jpg\",\"white.jpg\"];\n // one pattern recognition item with three foils\n patternrecogTarget[pr[1]] = hardtriplets[1]; \n patternrecogFoilsone[pr[1]] = [stimset[8], stimset[4], stimset[10]];\n patternrecogFoilstwo[pr[1]] = [stimset[15], stimset[10], stimset[5]];\n patternrecogFoilsthree[pr[1]] = [stimset[0], stimset[1], stimset[3]];\n // one item with only pairs, and one other answer option \n patternrecogTarget[pr[2]] = [stimset[1], stimset[2],\"white.jpg\"];\n patternrecogFoilsone[pr[2]] = [stimset[0], stimset[15],\"white.jpg\"];\n patternrecogFoilstwo[pr[2]] = [\"white.jpg\",\"white.jpg\",\"white.jpg\"];\n patternrecogFoilsthree[pr[2]] = [\"white.jpg\",\"white.jpg\",\"white.jpg\"];\n // now items with only pairs, and three other answer options \n patternrecogTarget[pr[3]] = [stimset[11], stimset[12],\"white.jpg\"];\n patternrecogFoilsone[pr[3]] = [stimset[5], stimset[10],\"white.jpg\"];\n patternrecogFoilstwo[pr[3]] = [stimset[11], stimset[14],\"white.jpg\"];\n patternrecogFoilsthree[pr[3]] = [stimset[8], stimset[3],\"white.jpg\"]; \n // give them names for easy reference (here in debugging these are meaningless)\n for (var i=0; i<pr.length; i++) {\n testitems[pr[i]] = i+1;\n }\n // now a pattern completion item. first item in foils array is always the target\n patterncompletionQuestion[0] = [stimset[0], \"blank.jpg\", stimset[2]];\n patterncompletionFoils[0] = [stimset[1], stimset[12], stimset[8]]\n testitems[pr.length] = 0; \n \n // if not debugging have all test items \n } else {\n // first set up the pattern recognition items with one foil\n patternrecogTarget[pr[0]] = hardtriplets[0]; \n patternrecogFoilsone[pr[0]] = [stimset[1], stimset[12], stimset[7]];\n patternrecogTarget[pr[1]] = hardtriplets[1]; \n patternrecogFoilsone[pr[1]] = [stimset[0], stimset[1], stimset[3]];\n patternrecogTarget[pr[2]] = hardtriplets[2]; \n patternrecogFoilsone[pr[2]] = [stimset[3], stimset[2], stimset[8]];\n patternrecogTarget[pr[3]] = hardtriplets[3]; \n patternrecogFoilsone[pr[3]] = [stimset[6], stimset[0], stimset[2]];\n patternrecogTarget[pr[4]] = easytriplets[0]; \n patternrecogFoilsone[pr[4]] = [stimset[8], stimset[4], stimset[10]];\n patternrecogTarget[pr[5]] = easytriplets[1]; \n patternrecogFoilsone[pr[5]] = [stimset[15], stimset[10], stimset[5]];\n patternrecogTarget[pr[6]] = easytriplets[2]; \n patternrecogFoilsone[pr[6]] = [stimset[13], stimset[5], stimset[9]];\n patternrecogTarget[pr[7]] = easytriplets[3]; \n patternrecogFoilsone[pr[7]] = [stimset[2], stimset[0], stimset[14]];\n patternrecogTarget[pr[8]] = hardtriplets[0]; \n patternrecogFoilsone[pr[8]] = [stimset[14], stimset[0], stimset[3]];\n patternrecogTarget[pr[9]] = hardtriplets[1]; \n patternrecogFoilsone[pr[9]] = [stimset[13], stimset[5], stimset[9]];\n patternrecogTarget[pr[10]] = hardtriplets[2]; \n patternrecogFoilsone[pr[10]] = [stimset[1], stimset[7], stimset[3]];\n patternrecogTarget[pr[11]] = hardtriplets[3]; \n patternrecogFoilsone[pr[11]] = [stimset[15], stimset[10], stimset[5]];\n patternrecogTarget[pr[12]] = easytriplets[0]; \n patternrecogFoilsone[pr[12]] = [stimset[13], stimset[2], stimset[1]];\n patternrecogTarget[pr[13]] = easytriplets[1]; \n patternrecogFoilsone[pr[13]] = [stimset[4], stimset[11], stimset[12]];\n patternrecogTarget[pr[14]] = easytriplets[2]; \n patternrecogFoilsone[pr[14]] = [stimset[0], stimset[1], stimset[3]];\n patternrecogTarget[pr[15]] = easytriplets[3]; \n patternrecogFoilsone[pr[15]] = [stimset[15], stimset[6], stimset[9]];\n for (var i=0; i<16; i++) {\n patternrecogFoilstwo[pr[i]] = [\"white.jpg\",\"white.jpg\",\"white.jpg\"];\n patternrecogFoilsthree[pr[i]] = [\"white.jpg\",\"white.jpg\",\"white.jpg\"];\n }\n\n // now set up the pattern recognition items with three foils \n patternrecogTarget[pr[16]] = hardtriplets[0]; \n patternrecogFoilsone[pr[16]] = [stimset[8], stimset[4], stimset[10]];\n patternrecogFoilstwo[pr[16]] = [stimset[1], stimset[7], stimset[3]];\n patternrecogFoilsthree[pr[16]] = [stimset[13], stimset[2], stimset[1]];\n patternrecogTarget[pr[17]] = hardtriplets[1]; \n patternrecogFoilsone[pr[17]] = [stimset[8], stimset[4], stimset[10]];\n patternrecogFoilstwo[pr[17]] = [stimset[15], stimset[10], stimset[5]];\n patternrecogFoilsthree[pr[17]] = [stimset[0], stimset[1], stimset[3]];\n patternrecogTarget[pr[18]] = hardtriplets[2]; \n patternrecogFoilsone[pr[18]] = [stimset[15], stimset[6], stimset[9]];\n patternrecogFoilstwo[pr[18]] = [stimset[1], stimset[12], stimset[7]];\n patternrecogFoilsthree[pr[18]] = [stimset[1], stimset[7], stimset[3]];\n patternrecogTarget[pr[19]] = hardtriplets[3]; \n patternrecogFoilsone[pr[19]] = [stimset[4], stimset[11], stimset[12]];\n patternrecogFoilstwo[pr[19]] = [stimset[14], stimset[0], stimset[3]];\n patternrecogFoilsthree[pr[19]] = [stimset[2], stimset[0], stimset[14]];\n patternrecogTarget[pr[20]] = easytriplets[0]; \n patternrecogFoilsone[pr[20]] = [stimset[15], stimset[6], stimset[9]];\n patternrecogFoilstwo[pr[20]] = [stimset[13], stimset[5], stimset[9]];\n patternrecogFoilsthree[pr[20]] = [stimset[1], stimset[12], stimset[7]];\n patternrecogTarget[pr[21]] = easytriplets[1]; \n patternrecogFoilsone[pr[21]] = [stimset[0], stimset[1], stimset[3]];\n patternrecogFoilstwo[pr[21]] = [stimset[3], stimset[2], stimset[8]];\n patternrecogFoilsthree[pr[21]] = [stimset[14], stimset[0], stimset[3]];\n patternrecogTarget[pr[22]] = easytriplets[2]; \n patternrecogFoilsone[pr[22]] = [stimset[13], stimset[2], stimset[1]];\n patternrecogFoilstwo[pr[22]] = [stimset[6], stimset[0], stimset[2]];\n patternrecogFoilsthree[pr[22]] = [stimset[2], stimset[0], stimset[14]];\n patternrecogTarget[pr[23]] = easytriplets[3]; \n patternrecogFoilsone[pr[23]] = [stimset[4], stimset[11], stimset[12]];\n patternrecogFoilstwo[pr[23]] = [stimset[3], stimset[2], stimset[8]];\n patternrecogFoilsthree[pr[23]] = [stimset[6], stimset[0], stimset[2]];\n \n // now items with only pairs, and one other answer option \n patternrecogTarget[pr[24]] = [stimset[1], stimset[2],\"white.jpg\"];\n patternrecogFoilsone[pr[24]] = [stimset[0], stimset[15],\"white.jpg\"];\n patternrecogTarget[pr[25]] = [stimset[0], stimset[3],\"white.jpg\"];\n patternrecogFoilsone[pr[25]] = [stimset[1], stimset[3],\"white.jpg\"];\n patternrecogTarget[pr[26]] = [stimset[2], stimset[0],\"white.jpg\"];\n patternrecogFoilsone[pr[26]] = [stimset[5], stimset[2],\"white.jpg\"];\n patternrecogTarget[pr[27]] = [stimset[3], stimset[1],\"white.jpg\"];\n patternrecogFoilsone[pr[27]] = [stimset[12], stimset[1],\"white.jpg\"];\n patternrecogTarget[pr[28]] = [stimset[5], stimset[6],\"white.jpg\"];\n patternrecogFoilsone[pr[28]] = [stimset[4], stimset[10],\"white.jpg\"];\n patternrecogTarget[pr[29]] = [stimset[7], stimset[8],\"white.jpg\"];\n patternrecogFoilsone[pr[29]] = [stimset[2], stimset[13],\"white.jpg\"];\n for (var i=24; i<30; i++) {\n patternrecogFoilstwo[pr[i]] = [\"white.jpg\",\"white.jpg\"];\n patternrecogFoilsthree[pr[i]] = [\"white.jpg\",\"white.jpg\"];\n } \n \n // now items with only pairs, and three other answer options \n patternrecogTarget[pr[30]] = [stimset[11], stimset[12],\"white.jpg\"];\n patternrecogFoilsone[pr[30]] = [stimset[5], stimset[10],\"white.jpg\"];\n patternrecogFoilstwo[pr[30]] = [stimset[11], stimset[14],\"white.jpg\"];\n patternrecogFoilsthree[pr[30]] = [stimset[8], stimset[3],\"white.jpg\"];\n patternrecogTarget[pr[31]] = [stimset[13], stimset[14],\"white.jpg\"];\n patternrecogFoilsone[pr[31]] = [stimset[7], stimset[9],\"white.jpg\"];\n patternrecogFoilstwo[pr[31]] = [stimset[0], stimset[7],\"white.jpg\"];\n patternrecogFoilsthree[pr[31]] = [stimset[14], stimset[6],\"white.jpg\"];\n patternrecogTarget[pr[32]] = [stimset[0], stimset[1],\"white.jpg\"];\n patternrecogFoilsone[pr[32]] = [stimset[6], stimset[0],\"white.jpg\"];\n patternrecogFoilstwo[pr[32]] = [stimset[2], stimset[13],\"white.jpg\"];\n patternrecogFoilsthree[pr[32]] = [stimset[12], stimset[4],\"white.jpg\"];\n patternrecogTarget[pr[33]] = [stimset[3], stimset[2],\"white.jpg\"];\n patternrecogFoilsone[pr[33]] = [stimset[8], stimset[1],\"white.jpg\"];\n patternrecogFoilstwo[pr[33]] = [stimset[9], stimset[3],\"white.jpg\"];\n patternrecogFoilsthree[pr[33]] = [stimset[15], stimset[11],\"white.jpg\"];\n \n // give them the name as in the paper for easy reference\n for (var i=0; i<pr.length; i++) {\n testitems[pr[i]] = i+1;\n }\n for (var i=0; i<pc.length; i++) {\n testitems[pr.length+pc[i]] = 35+i;\n }\n \n // now the pattern completion items\n patterncompletionQuestion[pc[0]] = [stimset[0], \"blank.jpg\", stimset[2]];\n patterncompletionFoils[pc[0]] = [stimset[1], stimset[12], stimset[8]]\n patterncompletionQuestion[pc[1]] = [stimset[1], stimset[0], \"blank.jpg\"];\n patterncompletionFoils[pc[1]] = [stimset[3], stimset[5], stimset[15]]\n patterncompletionQuestion[pc[2]] = [\"blank.jpg\", stimset[5], stimset[6]];\n patterncompletionFoils[pc[2]] = [stimset[4], stimset[13], stimset[2]]\n patterncompletionQuestion[pc[3]] = [stimset[7], \"blank.jpg\", stimset[9]];\n patterncompletionFoils[pc[3]] = [stimset[8], stimset[14], stimset[3]]\n patterncompletionQuestion[pc[4]] = [stimset[10], \"blank.jpg\", \"white.jpg\"];\n patterncompletionFoils[pc[4]] = [stimset[11], stimset[6], stimset[0]];\n patterncompletionQuestion[pc[5]] = [\"blank.jpg\", stimset[14], \"white.jpg\"];\n patterncompletionFoils[pc[5]] = [stimset[13], stimset[7], stimset[11]];\n patterncompletionQuestion[pc[6]] = [stimset[2], \"blank.jpg\", \"white.jpg\"];\n patterncompletionFoils[pc[6]] = [stimset[0], stimset[1], stimset[4]];\n patterncompletionQuestion[pc[7]] = [\"blank.jpg\", stimset[3], \"white.jpg\"];\n patterncompletionFoils[pc[7]] = [stimset[2], stimset[10], stimset[9]];\n }\n\n}",
"function generateC(){\n let CRow = []\n C = []\n for(let x = 0; x < 9; x++){\n for(let y = 0; y < 9; y++){\n CRow.push(R[y][x])\n }\n C.push(CRow)\n CRow = []\n }\n}",
"function fillRandn(m, mu, std) {\n for (let i = 0, n = m.w.length; i < n; i++) {\n m.w[i] = randn(mu, std);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function resets messages in chat box | resetChatBox() {
$('#chat-message-box').val("");
} | [
"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}",
"function clearPlayerOneChat(i) {\n if (i.toLowerCase() == \"clear\") {\n for (var j = 0; j < self.playerOneMessages.length + 1; j++) {\n self.playerOneMessages.$remove(j);\n }\n }\n }",
"clearAndResetUpdate(){\n\t\tclearTimeout(timer);\n\t\tthis.getChats();\t\n\t}",
"function clear() {\n messages = [];\n }",
"function sendAndClear(message) {\n if(message !== \"\") {\n ws.send(message);\n id(\"message\").value =\"\";\n }\n}",
"function clearSomeMessages(){\n for(var i=0;i<10;i++){\n $(DOMelements.botBody+\" div:first-child\").remove();\n }\n messagesNum=0;\n }",
"function clearPlayerTwoChat(i) {\n if (i.toLowerCase() == \"clear\") {\n for (var j = 0; j < self.playerTwoMessages.length + 1; j++) {\n self.playerTwoMessages.$remove(j);\n }\n }\n }",
"sendReset() {\n this.sendMessage('reset');\n }",
"function clearChat(){\n\tdatabase.ref().child(\"chat\").set({line:\"\"});\n}",
"function removeMessages(){\n\t//remove note message\n\tdocument.getElementById(\"notePopup1\").classList.remove(\"notePopup1\");\n\tdocument.getElementById(\"notePopup2\").classList.remove(\"notePopup2\");\n\n\t//remove win/lose/draw message\n\tvar status = Session.get(\"onMessage\");\n\tif(status == \"lock\"){\n\t\tSession.set(\"onMessage\", \"hold\");\n\t}else if(status == \"hold\" || status == \"free\"){ //should not include 'free', but hardcoded to solve a bug(rare though). look forward a better solution.\n\tdocument.getElementById(\"winPopup1\").classList.remove(\"winPopup1\");\n\tdocument.getElementById(\"winPopup2\").classList.remove(\"winPopup2\");\n\tdocument.getElementById(\"drawPopup\").classList.remove(\"drawPopup\");\n\tdocument.getElementById(\"losePopup1\").classList.remove(\"losePopup1\");\n\tdocument.getElementById(\"losePopup2\").classList.remove(\"losePopup2\");\n\n\tSession.set(\"onMessage\", \"free\");\n}\n}",
"function resetActivity() {\n displayActivity(MESSAGE);\n }",
"function emptyMessagesDiv() {\n\tsetInterval(function() {\n\t\t$('#messages').html(\"\");\n\t\t$('#messages').removeClass();\n\t}, 4000);\n}",
"function messageLosing() {\n\n $(`<section class=\"game-over\"><div class=\"message-box\"><h2>Try harder Marites 😔</h2>\n <h3>Kulang ang almusal mong tsismis</h3>\n <p>Number of attempts: ${attempts}</p>\n <p>Total Time: ${60-(seconds/1000)} seconds <p>Rating: ${stars} </p><p><i class=\"fas fa-undo\"></i><i class=\"fas fa-sign-out-alt\"></i><object data=\"leaderboard.svg\"></object>\n </p></div></section>`).insertAfter($('.gamebg'));\n restart(); goBack();\n $('.message-box').fadeIn(1000);\n }",
"function updChatroomMsgEnter(state){\n $('.messages').on('keypress','#text', function (e) {\n var key = e.which;\n if(key === 13) // the enter key code\n {\n event.preventDefault();\n setUpdatedMessages(state,$('#text').val(),$('.conversation'));\n $('#text').val('');\n }\n });\n}",
"function clear_room() {\n\tsocket.emit(\"message\", {\n\t\t\"room\": ROOM,\n\t\"command\": \"clear\"\n\t});\n}",
"function reset_risultati() {\n // resetto l'input testuale\n $('#message').val('');\n // nascondo il titolo della pagina\n $('.titolo-ricerca').removeClass('visible');\n // svuoto il contenitore dei risultati\n $('#results').empty();\n // $('#risultati .card').remove();\n // $('#risultati').html('');\n }",
"function answerBoxClear(){\n $(\"#answerBox\").val('');\n}",
"function reset() {\n\t\tclearInterval(timerId);\n\t\ttimeId = null;\n\t\tindex = 0;\n\t\tid(\"output\").textContent = \"\";\n\t\tid(\"input-text\").value = \"\";\n\t\tid(\"input-text\").disabled = false;\n\t}",
"resetGame() {\n this.setState({\n turns: 0,\n compare: null,\n turn: Array(2).fill(null),\n flipped: Array(tableSize[0] * tableSize[1]).fill(false),\n matched: [] \n });\n\n setTimeout(() => {\n emojis = getEmojis((tableSize[0] * tableSize[1]) / 2);\n }, 600);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
[animation] blink the counter display | function displayBlink() {
$("#countDisplay").animate({
opacity: '0.5',
}, "slow");
$("#countDisplay").animate({
opacity: '1',
},"slow");
} | [
"function timer() {\n number--\n $(\"#show-number\").html(\"<h2>\" + number + \"</h2>\");\n if (number === 0) {\n stop();\n }\n }",
"function blink(){\n\nlet blinked = document.querySelector('#colon');\nblinked.style.color = (blinked.style.color == \"white\" ? \"grey\" : \"white\");\nsetTimeout(blink , 500);\n}",
"function blink(elem, times, speed)\r\n{\r\nif (times > 0 || times < 0) {\r\n if ($(elem).hasClass(\"blink\"))\r\n $(elem).removeClass(\"blink\");\r\n else\r\n $(elem).addClass(\"blink\");\r\n }\r\n\r\n clearTimeout(function() { blink(elem, times, speed); });\r\n\r\n if (times > 0 || times < 0) {\r\n setTimeout(function() { blink(elem, times, speed); }, speed);\r\n times-= .5;\r\n }\r\n}",
"function blinkText(selector) {\n $(selector).animate({ opacity: 0}, 300, function() {\n $(selector).animate({ opacity: 1}, 300);\n })\n}",
"function blink(button, time){\n button.active = true;\n $timeout(function(){\n button.active = false;\n }, time)\n }",
"function flash_blacknWhite(f, flash_count){\n\tf.style.display = 'block';\n\tvar interval = 500;\n\tvar count = flash_count * 2;\n\n\tf.style.display = 'block';\n\tfor(var i = 0; i < count; i++){\n\t\tMeteor.setTimeout(()=>{\n\t\t\tf.style.color = (f.style.color == 'white' ? 'black':'white');\n\t\t}, i * interval );\n\t}\n\n\tMeteor.setTimeout(()=>{\n\t\tf.style.display = 'none';\n\t}, count * interval);\n}",
"function refreshDisplay(blinkers) {\n for (var a = 0x6000; a < 0x7000; a += 2) {\n if (!blinkers || (ccemu.rd(a + 1) & 0x40)) {\n updateChar(a);\n }\n }\n }",
"animatePlaceholderStatus() {\n Animate.blink(this);\n }",
"function BlinkAtIndex(index, color){\n\tdocument.getElementById(index).style.backgroundColor=\"red\";\n\tsetTimeout(function(){document.getElementById(index).style.backgroundColor=\"#FFD700\";}, 150);\n}",
"function runGame(){\n var i = 0;\n var interval = $interval(\n function(){ // make the buttons blink with 500 milliseconds between every blink.\n if(i >= gameList.length){\n activateButtons();\n $interval.cancel(interval);\n }\n else{\n blinkCorrectButton(i);\n i+=1;\n }\n }, 1000);\n\n }",
"startBlack() {\n this.state.timer.startTimer(\"BLACK\");\n }",
"function flashGood( success ){\n indicator.innerHTML += '<br>' + success + '!';\n indicator.classList.add('indicator-green');\n window.setTimeout( function(){ indicator.classList.remove('indicator-green'); } , 250);\n window.setTimeout( function(){ indicator.classList.add('indicator-green'); } , 500);\n window.setTimeout( function(){ indicator.classList.remove('indicator-green'); } , 750);\n}",
"function colourTimer() {\r\n colourElement.style.display = 'none';\r\n setTimeout(colourChange, 1000);\r\n setTimeout(reactColour, 2000);\r\n setTimeout(displayWord, 3000);\r\n}",
"function flash(f,flash_count,startFrom){\n\tvar interval = 300;\n\tvar count = flash_count * 2;\n\n\tfor(var i = 0; i <= count; i++){\n\t\tif(i == count){\n\t\t\tMeteor.setTimeout(()=>{f.style.visibility = 'visible'; }, i * interval + startFrom);\n\t\t}else{\n\t\t\tMeteor.setTimeout(()=>{f.style.visibility = (f.style.visibility == 'visible' ? 'hidden':'visible');}, i * interval + startFrom);\t\n\t\t}\n\t}\n}",
"function updateCounter(){\n\t//subtracts one from battery percentage \n\tbatteryPercentage -= 1;\n\t//changes text to match the new battery percentage \n\t\n\t\n}",
"function beginCountDown() {\n\n myCountDown = setInterval(countDown, 1000)\n }",
"function countdown() {\n nIntervId = setInterval(changeText, 1000);\n}",
"function countDown (num) {\n var timerId = setInterval(function() {\n num--;\n if(num <= 0) {\n clearInterval(timerId);\n console.log('DONE!');\n } else {\n console.log(num);\n }\n }, 1000);\n}",
"function blinkCursor() {\n\t\tcursor.style.textDecoration = \"underline\";\n\t\tsetTimeout(function () {\n\t\t\tcursor.style.textDecoration = \"\";\n\t\t\tsetTimeout(blinkCursor, 500);\n\t\t}, 500);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
3. Write a function named countOdds that accepts an array of numbers and returns the number of odd numbers in the array. | function countOdds(array) {
var total = 0;
for(var i = 0; i < array.length; i++) {
if(array[i] % 2 != 0) {
total++;
}
}
return total;
} | [
"function how_many_even(arr){\n count = 0;\n for(i = 0; i < arr.length; i++){\n if (arr[i] % 2 == 0){\n count ++;\n }\n }\n return count;\n}",
"function how_many_even(arr){\n var count = 0;\n for(var i = 0; i < arr.length; i++){\n if(arr[i] % 2 == 0){\n count++;\n }\n }\n return count;\n}",
"function evensAndOdds(arr) {\n var evens = 0;\n var odds = 0;\n\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] % 2 === 0) {\n odds = 0;\n evens++;\n if (evens === 3) {\n console.log(\"Even more so!\");\n evens = 0;\n }\n } else {\n evens = 0;\n odds ++;\n if (odds === 3) {\n console.log(\"That's odd!\")\n odds = 0;\n }\n }\n }\n}",
"function arrayOfOdds (arr){\n var arr = [];\n for(var i = 0; i <= 50; i++){\n if(i % 2 !== 0){\n arr.push(i);\n }\n }\n return arr;\n}",
"function isPerfectlyOdd(arr) {\n let sum = 0;\n for (let i = 1; i < arr.length; i += 2) {\n sum += arr[i];\n\n }\n if (sum % 2 !== 0) {\n return true;\n }\n return false;\n\n}",
"function addOdds(evensOnlyArray) {\n var newArr = []\n for(var i = 0; i < evensOnlyArray.length; i++) {\n newArr.push(evensOnlyArray[i] + 1)\n }\n evensOnlyArray.unshift(1)\n return allNums = evensOnlyArray.concat(newArr)\n}",
"function sumOddNumbers(numbers) {\n return numbers.filter(function removeEvenNumbers(num) {\n return num % 2 == 1;\n }).reduce(function sum(runningTotal, num) {\n return runningTotal + num;\n }, 0);\n}",
"function odds(arr) {\n return filter(arr, function(elem) {\n // remember to RETURN the filter function\n return elem % 2 !== 0;\n });\n}",
"function evenIndexedOddNumbers(arr) {\n var output = [];\n each(arr, function(e, i) {\n if ((e % 2 !== 0) && (i % 2 === 0)) {\n output.push(e)\n }\n })\n return output;\n}",
"function odds(arr) {\n oddArr = [];\n each(arr, function(element) {\n if (element % 2 !==0) {\n oddArr.push(element);\n };\n });\n return oddArr;\n}",
"function isaNumberEven(array){\n\t\n}",
"function oddities(array) {\n var oddElements = [];\n var i;\n\n for (i = 0; i < array.length; i += 2) {\n oddElements.push(array[i]);\n }\n\n return oddElements;\n}",
"function threeOdds(number1, number2) {\n var count = 0;\n for (i = number1 + 1; i < number2; i++) {\n if (i % 2 !== 0) {\n count++\n }\n }\n if (count > 2) {\n return true;\n } else {\n return false\n }\n}",
"function arrayodd() {\n var oddarray = [];\n for (var i = 1; i <= 50; i = i + 2) {\n oddarray.push(i);\n }\n return oddarray;\n}",
"function doubleOddNumbers(arr) {\n let oddNumsArr = arr.filter(function(num){\n return num%2 === 1\n })\n let oddNumsDoubledArr = oddNumsArr.map(function(num){\n return num * 2\n })\n return oddNumsDoubledArr\n}",
"function printOddNumbersOnly(arr) {\n arr.filter(num => num % 2 == 1).forEach(element => console.log(element));\n}",
"function isOdd(n) {if(!isNaN(n)){return n % 2 !== 0}}",
"function iqTest(numbers) {\n const inputArray = numbers.split(' ');\n const even = [];\n const odd = []\n\n inputArray.map((elm) => elm % 2 == 0 ? even.push(elm) : odd.push(elm));\n\n return inputArray.indexOf(even.length > odd.length ? odd[0] : even[0]) + 1;\n}",
"function hasOddNumber(arr){\n return arr.some(function(el){\n return el % 2 !== 0;\n })\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The saveUser function submits the username and password to a generated alphanumerical key in Firebase | function saveUser(username, password) {
//This newUserRef allows for a NEW user to be submitted rather than replaced
var newUserRef = usersRef.push();
//Sets the data into the database under a randomly generated key
newUserRef.set({
username: username,
password: password
});
} | [
"dbSaveUser(user) {\n let userInfo = {\n email: user.email ? user.email : null,\n displayName: user.displayName ? user.displayName : null\n };\n // Overrides any key data given, which is cool for us\n firebase.database().ref('users/' + user.uid).update(userInfo);\n }",
"storeUser (authData, userEmail, userName) {\n let userRef = new Firebase(`${firebaseURL}/user_data/${authData}`);\n userRef.set({\n uid: authData,\n email: userEmail\n });\n }",
"function guardarUsuario() {\n let nombre = $('#nombre').val();\n let apellidos = $('#apellidos').val();\n let agregarUsuarioEmail = $('#agregarUsuarioEmail').val();\n let agregarUsuarioPuesto = $('#agregarUsuarioPuesto').val();\n var agregarUsuarioContrasena;\n\n if($('#nuevacontrasena').val() == $('#confirmarcontrasena').val()) {\n agregarUsuarioContrasena = $('#nuevacontrasena').val();\n\n firebase.auth().createUserWithEmailAndPassword(agregarUsuarioEmail, agregarUsuarioContrasena)\n .then(function(data) {\n console.log(data);\n let uid = data.uid;\n console.log(uid);\n\n let usuarios = firebase.database().ref('usuarios/'+uid);\n let Usuario = {\n nombre: nombre,\n apellidos: apellidos,\n puesto: agregarUsuarioPuesto\n }\n usuarios.set(Usuario); //metodo set para insertar de Firebase\n\n })\n .catch(function(error) {\n console.log(error);\n });\n $('#agregarUsuario').modal('hide');\n\n logOut();\n }\n else {\n console.log(\"Las contraseñas no coinciden\");\n }\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}",
"pushToFirebase() {\n // Create a user for the person who just made a team\n firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)\n .then((data) => {\n this.createUser(data.uid);\n })\n .catch((error) => {\n alert(error.message)\n })\n }",
"function passwordManagerSave(aUsername, aPassword) {\n cal.auth.passwordManagerSave(aUsername, aPassword, aUsername, \"Google Calendar\");\n}",
"function signUp(username, password){\n users.insert({username,password,Balance:1500});\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 saveToDB(user, pass) {\n return bcrypt.hash(pass, salt)\n .then(hash=>{\n return User.create(user, hash)\n })\n}",
"function createUser(userid){\n users[userid] = { \"userid\": userid.toString(), \"inventory\": [\"laptop\"], \"roomid\": \"strong-hall\"};\n saveState();\n}",
"async function addUser(email, username, password) {\n const key = await generateKey();\n const response = await client.index({\n index: INDEX,\n type: \"_doc\",\n refresh: \"true\",\n body: {\n \"email\": email,\n \"username\": username,\n \"password\": bcrypt.hashSync(password, 10),\n \"key\": key,\n \"email_verified\": false,\n \"reputation\": 1\n }\n });\n\n return key;\n}",
"function save_user() {\n var user = document.getElementById(\"username\").value;\n //check that a username was inputted \n if (!user || (user.trim()).length == 0) {\n document.getElementById(\"username\").value = \"\";\n alert('No username specified.');\n return;\n }\n if (user.length>10){\n document.getElementById(\"username\").value = \"\";\n alert(\"Username exceeded 10 characters.\")\n return;\n }\n //if there is a username, save to chrome.storage\n chrome.storage.sync.set({\"user\": user}, function() {\n message('Username saved and updated.');\n });\n document.getElementById(\"username\").placeholder = \"Current Username: \" + user;\n document.getElementById(\"username\").value = \"\";\n }",
"function registerNewUser (first_name, last_name, email, password, refer) {\n var sessionToken = '';\n\n return Parse.Cloud.run(\"user.add\", {\n name: first_name + \" \" + last_name,\n email: email,\n pw: password\n }).then(function() {\n return Parse.User.logIn(email, password).then(function() {\n var currentUser = Parse.User.current();\n sessionToken = currentUser.getSessionToken();\n document.cookie = \"sessionToken=\"+sessionToken + ';path=/'; //save the sessionToken in a cookie\n }).then(function() {\n return setPlatform();\n }).then(function() {\n return Parse.Cloud.run(\"webapp.updateEmail\", {email: email, session: sessionToken\n }).then(function() {\n if(!refer) {\n refer = 'no-referral';\n }\n return Parse.Cloud.run(\"webapp.saveReferral\", {\n referral: refer,\n session: sessionToken\n });\n })\n });\n})\n}",
"static async register(data) {\n const duplicateCheck = await db.query(\n `SELECT username \n FROM users \n WHERE username = $1`,\n [data.username]\n );\n\n if (duplicateCheck.rows[0]) {\n throw new ExpressError(\n `There already exists a user with username '${data.username}`,\n 400\n );\n }\n\n const hashedPassword = await bcrypt.hash(data.password, BCRYPT_WORK_FACTOR);\n\n // create shrimpy user\n const shrimpy_user_id = await client.createUser(data.username);\n\n if (!shrimpy_user_id)\n throw new ExpressError(\"Could not create user in Shrimpy\");\n\n // create API keys in shrimpy for user management\n await client.createApiKeys(shrimpy_user_id);\n\n const result = await db.query(\n `INSERT INTO users \n (username, password, email, shrimpy_user_id) \n VALUES ($1, $2, $3, $4) \n RETURNING username, password, email, shrimpy_user_id`,\n [data.username, hashedPassword, data.email, shrimpy_user_id]\n );\n\n return result.rows[0];\n }",
"function signup(userData){\n console.log(\"creating new user \"+userData.id);\n return User.create(userData)\n }",
"async function signup(name, email, password, select, clientTrainer) {\n const newUser = await auth.createUserWithEmailAndPassword(email, password);\n\n await newUser.user.updateProfile({\n displayName: name,\n });\n\n //Gives every user (trainer or client) an email property in auth object\n await newUser.user.updateEmail(email);\n\n await setUid(newUser.user.uid);\n\n //creates user or trainer in db and sets the usertype to selected value in dropdown\n //adds clients trainer to their user information\n if (select === \"Trainer\") {\n return await db.collection(\"trainers\").doc(newUser.user.email).set({\n userType: select,\n });\n } else {\n return await db.collection(\"users\").doc(newUser.user.uid).set({\n userType: select,\n clientTrainer: clientTrainer,\n });\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 saveUser() {\n UserService.Update(vm.user)\n .then(function () {\n FlashService.Success('Usuario modificado correctamente');\n })\n .catch(function (error) {\n FlashService.Error(error);\n });\n }",
"async create(attrs) {\r\n // {email: '', password:''} this is what we assume attrs is\r\n attrs.id = this.randomId();\r\n const salt = crypto.randomBytes(8).toString('hex');\r\n const buf = await scrypt(attrs.password, salt, 64);\r\n //salt + attrs.password\r\n const records = await this.getAll() //gets existing users\r\n const record = {\r\n ...attrs,\r\n password: `${buf.toString('hex')}.${salt}`\r\n } // the fullstop splits the hashed pw from the salt\r\n records.push(record); // pushes new user into our records\r\n await this.writeAll(records);\r\n\r\n return record; // returns object with user ID, plus hash and salted pw\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates Triangular distributed numbers | distribution(n: number): RandomArray {
let triangularArray: RandomArray = [],
random: RandomArray = (prng.random(n): any);
for(let i: number = 0; i < n; i += 1){
triangularArray[i] = this._random(random[i]);
}
return triangularArray;
} | [
"function loadTris(n){\n for(var i = 0; i < n; i++){\n tris[i] = new Triangle(20,60,random(-8,8),random(-8,8));\n }\n}",
"function eightTriangleGenerator() {\n\n // step 1\n // generate 3 three random points between 0 to 45 degree\n var pointOne = randomPointGenerator();\n var pointTwo = randomPointGenerator();\n var pointThree = randomPointGenerator();\n\n var triOne = pointOne.concat(pointTwo, pointThree);\n var triTwo = triOne.slice();\n\n // step 2\n // flip each point (x, y) to (y, x)\n for (var i = 0; i < triOne.length; i += 2) {\n triTwo = swap(triTwo, i, i + 1);\n }\n\n triTwo = triOne.concat(triTwo);\n\n // step 3\n // flip each point (x, y) to (-x, y)\n var triFour = triTwo.slice()\n for (var i = 0; i < triFour.length; i += 2) {\n triFour[i] = -triFour[i];\n }\n\n triFour = triTwo.concat(triFour);\n\n // step 3\n // flip each point (x, y) to (x, -y)\n var triEight = triFour.slice()\n for (var i = 1; i < triEight.length; i += 2) {\n triFour[i] = -triFour[i];\n }\n\n triEight = triFour.concat(triEight);\n return triEight;\n}",
"function triangles(val) {\n //init string to contain character passed in while converting number data types to a string data type\n var str = \"\";\n //for loop to run until i = 7 not inclusive. 0 to 6 is 7 steps \n for (var i = 0; i < val; i++){\n // concatenate '#' to \n str += '#';\n //print str on each successive loop. Console.log must be within the loop block in order to function like this.\n console.log(str);\n }\n}",
"function generateShape(int){\n var string = []\n \n for (var i = 0; i < int; i++){\n string.push('+'.repeat(int) + '\\n')\n }\n \n return string.join('').slice(0, -1)\n}",
"function triangles(number) {\n \nvar hash = '';\n // for each number below the given one run the loop\nfor (let i = 0; i < number; i++){\n // add another hash in each loop\n hash += '#';\n // print the hash var each loop\n console.log(hash);\n}\n}",
"function triangulate(rings) {\n\n var triangles = [],\n edges = [],\n i, j, k, points, p, q, len, done;\n\n for (k = 0; k < rings.length; k++) {\n\n points = rings[k];\n\n // build a set of edges from points\n for (i = 0, len = points.length; i < len; i++) {\n j = i < len - 1 ? i + 1 : 0;\n p = i ? q : shearTransform(points[i]);\n q = shearTransform(points[j]);\n edges.push(p.x > q.x ? new Edge(q, p) : new Edge(p, q));\n }\n }\n\n // shuffle(edges);\n\n var map = new TrapezoidalMap();\n\n for (i = 0; i < edges.length; i++) {\n done = map.addEdge(edges[i]);\n if (!done) return null;\n }\n done = map.collectPoints();\n if (!done) return null;\n\n // Generate the triangles\n for (i = 0; i < edges.length; i++) {\n if (edges[i].poly && edges[i].poly.length) triangulateMountain(edges[i], triangles);\n }\n\n return triangles.length ? triangles : null;\n}",
"function buildTriangle(length) {\n let triangle = '';\n let lineNumber = 1;\n for (lineNumber=1; lineNumber<=length; lineNumber++) {\n triangle = triangle + makeLine(lineNumber);\n \n }\n return triangle\n}",
"function generateForAlice() {\n generatePrimes(\"alice\");\n }",
"function ntt(r) {\r\n var j = 0;\r\n var k = 1;\r\n var zeta;\r\n var t;\r\n // 128, 64, 32, 16, 8, 4, 2\r\n for (var l = 128; l >= 2; l >>= 1) {\r\n // 0,\r\n for (var start = 0; start < 256; start = j + l) {\r\n zeta = nttZetas[k];\r\n k = k + 1;\r\n // for each element in the subsections (128, 64, 32, 16, 8, 4, 2) starting at an offset\r\n for (j = start; j < start + l; j++) {\r\n // compute the modular multiplication of the zeta and each element in the subsection\r\n t = nttFqMul(zeta, r[j + l]); // t is mod q\r\n // overwrite each element in the subsection as the opposite subsection element minus t\r\n r[j + l] = r[j] - t;\r\n // add t back again to the opposite subsection\r\n r[j] = r[j] + t;\r\n\r\n }\r\n }\r\n }\r\n return r;\r\n}",
"nCr_wo_repitition_3(n, r) {\r\n // ht tps://www.geeks forgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/\r\n // This method is mainly based on Pascal’s Identity, i.e. ncr = n-1cr + n-1cr-1\r\n\r\n let arr = Array.from({ length: n }, (_, i) => i + 1);\r\n // console.log(arr, n, r);\r\n\r\n /* arr[] ---> Input Array \r\n\t\ttmp[] ---> Temporary array to store current combination \r\n\t\tstart & end ---> Staring and Ending indexes in arr[] \r\n\t\tindex ---> Current index in tmp[] \r\n\t\tr ---> Size of a combination to be printed */\r\n\r\n let res = [];\r\n // A temporary array to store all combination one by one\r\n let tmp = []; // new int[r]();\r\n\r\n function nCr_wo_reptn2(n, r, index, tmp, i) {\r\n // Current combination is ready to be printed, print it\r\n if (index == r) {\r\n // res.push(JSON.parse(JSON.stringify(tmp))); // ----------------\r\n // for (let j = 0; j < r; j++) System.out.print(tmp[j] + \" \");\r\n // System.out.println(\"\");\r\n return;\r\n }\r\n\r\n // When no more elements are there to put in tmp[]\r\n if (i >= n) return;\r\n\r\n // current is included, put next at next location\r\n tmp[index] = arr[i];\r\n nCr_wo_reptn2(n, r, index + 1, tmp, i + 1);\r\n\r\n // current is excluded, replace it with next (Note that\r\n // i+1 is passed, but index is not changed)\r\n nCr_wo_reptn2(n, r, index, tmp, i + 1);\r\n }\r\n\r\n // Print all combination using temprary array 'tmp[]'\r\n nCr_wo_reptn2(n, r, 0, tmp, 0);\r\n\r\n return res;\r\n }",
"function generateRefractors(){\n refractorSet.clear();\n let refractorRows = Math.floor(1.5 + simHeight / 300);\n let refractorCols = Math.floor(1.5 + simWidth / 300);\n\n let rowSpace = simHeight / (refractorRows);\n let colSpace = simWidth / (refractorCols);\n\n let triangleRadius = Math.min(rowSpace / 2 - (7 + simHeight / 50), colSpace / 2 - (7 + simWidth / 50));\n\n for(let i = 0; i < refractorCols; i ++)\n {\n for(let j = 0; j < refractorRows; j ++)\n {\n if(i != 0 || refractorRows % 2 == 0 || j != Math.floor(refractorRows / 2)){\n let center = new Vector(colSpace / 2 + colSpace * i, rowSpace / 2 + rowSpace * j);\n let ang = Math.random() * Math.PI * 2;\n let p1 = addVectors(angleMagVector(ang, triangleRadius), center);\n ang += Math.PI / 3 + Math.random() * Math.PI * .4;\n let p2 = addVectors(angleMagVector(ang, triangleRadius), center);\n ang += Math.PI / 3 + Math.random() * Math.PI * .4;\n let p3 = addVectors(angleMagVector(ang, triangleRadius), center);\n\n refractorSet.add(new SimVector(p1, subVectors(p2, p1)));\n refractorSet.add(new SimVector(p2, subVectors(p3, p2)));\n refractorSet.add(new SimVector(p3, subVectors(p1, p3)));\n }\n }\n }\n}",
"function pascalTriangle(k){\n // create a for loop: until row equals k\n // calculate current row\n // save current row\n let result = []\n for (let i = 0; i< k; i++){\n\n }\n\n\n return result\n}",
"generateDistTrav()\r\n {\r\n var distance = Math.floor((Math.random() * 2) + 1)\r\n console.log(distance + \"m\")\r\n }",
"function __genPolyNumLoop(acc,number,array,bool) {\n\t const length = array.length / 2;\n\t \n\t for (let i = 1; i <= length; i++) {\n\t\tconst byRowNum = number * 10 + i;\n\t\tconst byColNum = i * 10 + Number(number);\n\n\t\tbool ? calc = byRowNum : calc = byColNum\n\t\t\n\t\tif (number != 0 && number <= length) {\n\t\t acc.push(calc);\n\t\t}\n\t }\n\t \n\t return acc;\n\t}",
"function generateNumbers(){\n var set=new Array();\n for(i=0;i<9;i++){\n var number=Math.floor(Math.random()*9+1);\n while(set.indexOf(number)>-1){\n number=Math.floor(Math.random()*9+1);\n }\n set[i]=number;\n }\n return set;\n}",
"function kgen(key) {\r\n\r\n let result = new Array()\r\n\r\n let t\r\n let u = new Array()\r\n\r\n t = Shuffle(key, p10)\r\n\r\n //console.log(\"key through p10 : \" + t)\r\n t = splitAt((t.length / 2))(t)\r\n //console.log(\"key through first split : \" + t[0] + \" and \" + t[1])\r\n t[0] = Shift(t[0], 1)\r\n t[1] = Shift(t[1], 1)\r\n //console.log(\"key fragments through shifts for k1 : \" + t[0] + \" and \" + t[1])\r\n //aqui no recuerdo si es un shift de -1 o de -2 sobre del anterior\r\n u[0] = Shift(t[0], 2)\r\n u[1] = Shift(t[1], 2)\r\n //console.log(\"key fragments through another shift for k2 : \" + u[0] + \" and \" + u[1])\r\n\r\n let k1\r\n let k2\r\n\r\n k1 = Stitch(t[0], t[1])\r\n k2 = Stitch(u[0], u[1])\r\n\r\n k1 = Shuffle(k1, p8)\r\n k2 = Shuffle(k2, p8)\r\n\r\n result[0] = k1\r\n result[1] = k2\r\n\r\n //k1 and k2 might return more elements than what we want\r\n return result\r\n}",
"function generatePoints(n, dim, lower_bound, upper_bound) {\n var min = Math.ceil(lower_bound);\n var max = Math.floor(upper_bound);\n for (var i = 0; i < n; i++) {\n var coordinate = [];\n for (var j = 0; j < dim; j++) {\n coordinate.push(Math.floor(Math.random() * (max - min)) + min);\n }\n points.push(coordinate);\n }\n}",
"function triangulate(points){\n\tconst delaunay = Delaunator.from(points);\n\tconst tri = delaunay.triangles;\n\tvar triangles = []\n\tfor(var i=0;i<tri.length;i+=3){\n\t\ttriangles.push([tri[i], tri[i+1], tri[i+2]]);\n\t}\n\treturn(triangles);\n}",
"nCr_wo_repitition_2(n, r) {\r\n /* arr[] ---> Input Array \r\n\t\ttmp[] ---> Temporary array to store current combination \r\n\t\tstart & end ---> Staring and Ending indexes in arr[] \r\n\t\tindex ---> Current index in tmp[] \r\n\t\tr ---> Size of a combination to be printed */\r\n\r\n let arr = Array.from({ length: n }, (_, i) => i + 1);\r\n // console.log(arr, n, r);\r\n\r\n let res = [];\r\n // A temporary array to store all combination one by one\r\n let tmp = []; // new int[r]();\r\n\r\n function nCr_wo_reptn(tmp, start, end, index, r) {\r\n // Current combination is ready to be printed, print it\r\n if (index == r) {\r\n // res.push(JSON.parse(JSON.stringify(tmp))); // ----------------\r\n // for (let j = 0; j < r; j++) System.out.print(tmp[j] + \" \");\r\n // System.out.println(\"\");\r\n return;\r\n }\r\n\r\n // replace index with all possible elements. The condition\r\n // \"end-i+1 >= r-index\" makes sure that including one element\r\n // at index will make a combination with remaining elements\r\n // at remaining positions\r\n for (let i = start; i <= end && end - i + 1 >= r - index; i++) {\r\n tmp[index] = arr[i];\r\n nCr_wo_reptn(tmp, i + 1, end, index + 1, r);\r\n }\r\n }\r\n\r\n // Print all combination using temprary array 'tmp[]'\r\n nCr_wo_reptn(tmp, 0, n - 1, 0, r);\r\n\r\n return res;\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates an array of data with the selected energy company. Then it wil show a donut chart. value; selected energy company. | function createData(value) {
d3.json("data/suppliers/suppliers.json", function(error, data) {
// error checking
if (error) {
console.log("We cannot retrieve the data.");
d3.select(".donut-chart")
.html("<div class='text-center'><h3>Sorry.<br><br> Wij kunnen geen data ophalen.</h3></div>");
throw error;
};
// push the data into a list
dataList = [];
data.forEach(function(d){
if(value == d.company) {
dataList.push({"composition": d.composition, "value": parseFloat(d.score)});
}
});
// makes the actual donut
makeDonut(dataList);
});
} | [
"function draw_g_cake(data) {\n let series = [];\n let labels = [];\n for (let i = 0; i < data.length; i++) {\n series.push(data[i]['n_avistamientos'])\n labels.push(data[i]['tipo'])\n }\n // console.log(series);\n // console.log(labels);\n\n let options = {\n chart: {\n height: 380,\n width: \"100%\",\n type: 'pie',\n animations: {\n initialAnimation: {\n enabled: false\n }\n }\n },\n series: series,\n labels: labels\n };\n document.getElementById('grafico_torta_placeholder').innerText = \"\";\n let chart = new ApexCharts(document.getElementById('grafico_torta_placeholder'), options);\n\n chart.render();\n\n}",
"function drawChart() {\n\n let data = google.visualization.arrayToDataTable([\n ['City', 'Number of Employees'],\n ['Boston', boston],\n ['Orlando', orlando],\n ['Chicago', chicago],\n ['San Francisco', sanfran]\n ]);\n\n let options = {\n title: 'Number & Percentage of Employees',\n pieHole: 0.5,\n pieSliceText: 'value'\n };\n\n let chart = new google.visualization.PieChart(document.getElementById('donutchart'));\n chart.draw(data, options);\n }",
"function chartDataCreator() {\n for (var i = 0; i < products.length; i++) {\n chartData.push(products[i].votes);\n chartData.push(products[i].views);\n }\n}",
"function makeDataset(data, color) {\n return {\n label: \"TotalOdo\",\n fillColor: \"rgba(220,220,220,0)\",\n strokeColor: color,\n pointColor: \"rgba(220,220,220,0)\",\n scaleGridLineWidth : 1,\n pointDotRadius : 0,\n pointDot : false,\n pointDotStrokeWidth : 0,\n pointHitDetectionRadius : 2,\n data: data\n };\n}",
"function buildPieChart(jobsByState) {\n\n jobsByState = jobsByState.slice(0,10);\n\n var x_data = jobsByState.map(row => row.State);\n var y_data = jobsByState.map(row => row.Jobs_Count);\n\n var myPieChart = new Chart(document.getElementById(\"pie-chart\"), {\n type: 'pie',\n data: {\n labels: x_data,\n datasets: [{\n label: x_data,\n backgroundColor: colors,\n data: y_data\n }]\n },\n options: {\n title: {\n display: true,\n text: 'States with highest number of jobs',\n fontSize: 25\n },\n legend: {\n display: true,\n position: 'right',\n labels: {\n fontSize: 14,\n padding: 10,\n fontFamily: 'Arial'\n }\n }\n }\n});\n\n var canvas_donut = document.getElementById(\"pie-chart\");\n\n canvas_donut.onclick = function(evt){\n var activePoint = myPieChart.getElementsAtEvent(evt)[0];\n var try_data = activePoint._chart.config.data.datasets[0].label;\n var index = activePoint._index;\n\n console.log(try_data[index]);\n\n buildDonutChart(try_data[index]);\n}\n}",
"function chartClickData () {\n var data = [];\n for (var i = 0; i < allProducts.length ; i++) {\n data.push(allProducts[i].timesClicked);\n }\n return data;\n}",
"generatePieChart(res) {\n const inputs = res.queryInput;\n const characteristicGroups = res.results[0].values;\n // const indicator = Utility.getStringById(inputs.indicators[0][\"label.id\"]);\n const dataPoints = res.results;\n const precision = res.chartOptions.precision;\n return {\n chart: this.generateChartSettings(),\n title: this.generateTitle(inputs),\n subtitle: this.generateSubtitle(),\n tooltip: this.generateToolTip(precision),\n plotOptions: {\n pie: {\n allowPointSelect: true,\n cursor: 'pointer',\n dataLabels: {\n enabled: true,\n format: '<b>{point.name}</b>: {point.percentage:.'+precision+'f} %',\n },\n // showInLegend: true\n }\n },\n series: this.generatePieData(\n Selectors.getSelectedValue('select-characteristic-group'),\n characteristicGroups,\n dataPoints\n ),\n credits: this.generateCredits(inputs),\n legend: this.generateLegend(),\n exporting: this.generateExporting(),\n };\n // plotOptions: this.generatePlotOptions(precision),\n }",
"function createPieChart(charDataList) {\n var chart = new javafx.scene.chart.PieChart(charDataList)\n chart.setTitle(\"Population of the Continents\")\n\n return chart\n}",
"function getData() {\n // let toDate = e;\n // console.log(toDate.target.value)\n console.log(to.onchange)\n\n\n axios.get(`http://api.coindesk.com/v1/bpi/historical/close.json?start=${fromDateValue}&end=${toDateValue}`)\n .then(res => {\n let labels = Object.keys(res.data.bpi)\n let values = Object.values(res.data.bpi)\n printChart(res.data, labels, values)\n })\n}",
"function chooseCountry() {\n let firstDropdown = document.getElementById(\"countries\")\n let countryIndex;\n let countryName;\n firstDropdown.addEventListener(\"change\", function() {\n countryName = this.value\n let countries = covidData.countries\n for (let i = 0; i < countries.length; i++) {\n let country = countries[i]\n if (country === countryName) {\n countryIndex = i\n }\n }\n if (chart) {\n chart.destroy()\n }\n createBarGraph(countryIndex)\n displayTextData(countryName, countryIndex)\n })\n}",
"function reduceDataForScatterChart(){\n var personnesTemp = [];\n for (var key in personnes){\n var personneTemp = personnes[key];\n if (correspondsToCriterias(personneTemp)){\n personnesTemp.push(personneTemp);\n }\n }\n personnes = personnesTemp;\n\n var newDataset = {\n label: 'Courbe suivant les critères n°' + (counterDatasetsOfWholeTime+1).toString(),\n backgroundColor: backgroundColor[counterDatasetsOfWholeTime%4],\n borderColor: backgroundColor[counterDatasetsOfWholeTime%4],\n data: convertDatasetPersonnesToScatterDataset(personnes),\n fill: false\n };\n\n updateChart(newDataset);\n}",
"createGraph (){\n let selector = document.getElementById('container-graph');\n let html = '';\n let array = this.arrayDataObjects;\n for (let key in array) {\n this.createElementGraph(selector, `chart-${key}`);\n let title = array[key].title;\n let total = array[key].total;\n let items = array[key].items;\n for (let i in items) {\n this.labels.push(items[i].name);\n this.data.push(items[i].quantity);\n this.colors.push(items[i].color);\n this.createElementInfo(document.getElementById(`container-chart-${key}`), items[i].name, items[i].quantity, items[i].percent, items[i].color);\n }\n this.canvasGraph(this.labels, this.data, `chart-${key}`, this.colors);\n this.labels = [];\n this.data = [];\n this.colors = [];\n }\n\n }",
"function statepensionChart(statePensionAge){\n var value=0;\n var statePensionElem=new Array();\n var statePensionLine=new Array();\n\n //Before State Pension Year value = 0\n if($rootScope.stateValue==true){\n\n for (var i = parseInt($rootScope.about_ret); i <= parseInt($rootScope.timeline.upto); i++) {\n\n var labelPension = 'State Pension';\n if(statePensionAge.statePensionAge <= i){\n value=parseInt(statePensionAge.statePensionYear);\n }else{\n value=0;\n }//0 if sires less then State Pension\n //create chart Array\n //statePensionElem=[i,value];\n statePensionElem={\"x\":i,\"y\":value};\n statePensionLine.push(statePensionElem);\n }//foreach years\n }//Include\n //assemble return\n var statePensionChart={\n 'key':'State Pension',\n 'values':statePensionLine,\n 'color':'#8d8d8d',\n 'annualy':parseInt(statePensionAge.statePensionYear)\n }\n\n\n return statePensionChart;\n}",
"function finalsalaryChart(statePensionAge){\n\n //final salary chart\n var finalsalaryChartArray = new Array();\n //list of final salary colors\n var finalBarColor =['#4e4e4e','#161616','#000000'];\n\n //Array of finale salaries\n angular.forEach($rootScope.finalsalary_list, function(finalSalary, step) {\n\n //final salary element\n var finalsalaryElem= new Array();\n //final salary line\n var finalsalaryLine = new Array();\n //final salary series\n var finalsalarySeries = new Array();\n\n //RenameSeries\n var name = finalSalary.name;\n //chart x-axis\n for (var i = parseInt($rootScope.about_ret); i <= parseInt($rootScope.timeline.upto); i++) {\n\n //pay only after FROM value\n if(finalSalary.from > i){\n //finalsalaryElem=[i,0];\n finalsalaryElem={\"x\":i,\"y\":0};\n }else{\n //finalsalaryElem=[i,parseInt(finalSalary.value)];\n finalsalaryElem={\"x\":i,\"y\":parseFloat(finalSalary.value)};\n }\n finalsalaryLine.push(finalsalaryElem);\n }//time series\n finalsalarySeries={\n 'key':name,\n 'values':finalsalaryLine,\n 'color':finalBarColor[step],\n 'payableFrom':parseInt(finalSalary.from),\n 'annualy':parseFloat(finalSalary.value)\n }\n finalsalaryChartArray.push(finalsalarySeries);\n\n\n })//final salaries\n\n return finalsalaryChartArray;\n}",
"function incomeChange() {\n income = document.getElementById(incomeName + \"-select\").value;\n updateColorAxis();\n chart.series[0].setData(get_data());\n }",
"function draw(year){\n\n // filter the data for the corresponding day\n // filter the data to return only the three countries with most medals\n\n\n //TODO append data to draw circles\n // var circles = ...;\n\n //enter the data\n\n\n //exit\n\n //update\n\n\n //TODO append data for texts\n // var text = ...\n\n\n\n }",
"function generateData(index, resultData, urn) {\n\n //Store all the x and y points for the ScatterChart\n var chartData = []\n\n //Store all the school names for the ScatterChart tooltips\n var schoolNames = []\n\n //Stores whether the school urn is found\n var foundSchool = false;\n\n for (let i = 0, len = resultData.length; i < len; i++) {\n\n //Exclude schools that do not have a result \n if (resultData[i][index] !== null) {\n\n if (resultData[i][\"urn\"] === urn) {\n\n foundSchool = true;\n\n //First item in the list will be data \n //for the school searched for\n chartData.unshift({\n\n x: resultData[i][\"ptfsM6CLA1A\"],\n y: resultData[i][index]\n\n });\n\n schoolNames.unshift(resultData[i][\"schname\"]);\n\n } else {\n\n chartData.push({\n\n x: resultData[i][\"ptfsM6CLA1A\"],\n y: resultData[i][index]\n\n });\n\n schoolNames.push(resultData[i][\"schname\"]);\n }\n\n //alert printed if school exist but has no data for chosen measure\n } else if (resultData[i][\"urn\"] === urn) {\n\n alert(\"Selected data does not exist for the selected school. Please search for another school\");\n\n return null;\n }\n }\n\n //Checks if the urn entered could be found\n if (urn !== null && foundSchool === false) {\n\n alert(\"School could not be found or school has no disadvantaged pupil data available. Please try another school\");\n\n return null;\n\n } else {\n\n return [chartData, schoolNames];\n }\n}",
"function gaugechart(selectedID){\n d3.json(\"data/samples.json\").then((data) => {\n var dropdownMenu = d3.select(\"#selDataset\");\n selectedID = dropdownMenu.node().value;\n var washfreq = datametadata.filter(person => person.id == selectedID)[0].wfreq;\n // console.log(washfreq)\n\n // Create the trace for plotting\n var trace = {\n domain: { x: [0, 1], y: [0, 1] },\n\t\tvalue: washfreq,\n\t\ttitle: { text: \"Wash Frequency\" },\n\t\ttype: \"indicator\",\n mode: \"gauge+number\",\n gauge: { axis: { range: [null, 9] } }\n\n };\n \n // Define the data\n var plotdata = [trace];\n\n // Create plot using Plotly\n Plotly.newPlot('gauge', plotdata);\n\n})}",
"function assigneeReport() {\r\n selectedReport = \"Assignee\";\r\n\r\n prepareListOfAssignees();\r\n\r\n document.getElementById(\"assignee\").style.backgroundColor = \" #ebeaea\";\r\n document.getElementById(\"status\").style.backgroundColor = \"\";\r\n document.getElementById(\"severity\").style.backgroundColor = \"\";\r\n\r\n document.getElementById(\"right\").innerHTML = \"\";\r\n\r\n // here result is the object in which I am storing data regarding the number of bugs assigned to every individual \r\n let result = {};\r\n\r\n var issuesItem = JSON.parse(localStorage.getItem('bugs'));\r\n\r\n for (let i = 0; i < issuesItem.length; ++i) {\r\n if (!result[issuesItem[i].assignedTo]) {\r\n result[issuesItem[i].assignedTo] = 0;\r\n }\r\n ++result[issuesItem[i].assignedTo];\r\n }\r\n\r\n // now I will create individual object for every assignee-bugs data and then put it in the array named data\r\n var data = [];\r\n Object.entries(result).map(entry => {\r\n let obj = {\r\n x: entry[0],\r\n value: entry[1]\r\n }\r\n data.push(obj);\r\n });\r\n\r\n var chart;\r\n if (selectedChart == \"pie\") {\r\n chart = anychart.pie();\r\n\r\n chart.legend().position(\"right\");\r\n chart.legend().itemsLayout(\"vertical\");\r\n chart.sort(\"desc\");\r\n chart.labels().position(\"outside\");\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 chart.labels(true);\r\n chart.labels().format(\"{%x}\");\r\n chart.labels().rotation(-60);\r\n chart.labels().fontColor(\"Green\");\r\n chart.labels().fontWeight(900);\r\n }\r\n else {\r\n chart = anychart.bar();\r\n chart.yAxis().title(\"Number of bugs\");\r\n chart.labels(true);\r\n }\r\n\r\n chart.title(\"Number of bugs assigned to an INDIVIDUAL\");\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"
]
]
}
} |
Resume level or go to a new level. | function resumeGame()
{
if (player.life == 0) {
restartGame();
return;
}
// if it's playing, just resume
if (!screen.paused) {
screen.state = "running";
return;
}
// go to next level or restart
if (currentLevel < levelFiles.length - 1)
gotoNextLevel();
else
restartGame();
} | [
"function advanceLevel(){\n\n\t\t\tjewel.audio.play(\"levelUp\"); //p.306\n\n\t\t\tgameState.level++;\n\t\t\tannounce(\"Level \" + gameState.level);\n\t\t\tupdateGameInfo();\n\t\t\t//level value on gameInfo obj is 0 at beginning of game\n\t\t\tgameState.startTime = Date.now();\n\t\t\tgameState.endTime = jewel.settings.baseLevelTimer *\n\t\t\t\tMath.pow(gameState.level, -0.05 * gameState.level);\n\t\t\tsetLevelTimer(true);\n\t\t\tjewel.display.levelUp();\n\t\t} //end of advanceLevel()",
"function Resume(){\n\tTime.timeScale=1.0;\n\tpaused=false;\n\tpauseMenu.SetActive(false);\n\tgameManager.SendMessage(\"notInMenu\");\n}",
"function restartLevel(){\n deadPopUp();\n score=0;\n level--;\n setTimeout(startLevel,3001);\n}",
"resume() {\n this.paused_ = false;\n this.resetAutoAdvance_();\n }",
"function levelTransition() {\n if (score === 2000) {\n // Level 1 score amount.\n openTransition1();\n } else if (score === 5000) {\n // Level 1 + 2 score amount.\n openTransition2();\n } else if (score > 5000) {\n // Level 3 score amount.\n openScores();\n } else {\n return;\n }\n}",
"function resumeGame() {\n \t\treturn generateGameLoop();\n \t}",
"levelIncrease() {\n\t if (this.theInvaderCounter === 0) {\n\t this.level += 1;\n\t this.levelDisplay += 1;\n\t setTimeout(() => {\n\t this.player1.invadersAllDeadSound();\n\t }, 1000);\n\t this.levelUpEval();\n\t }\n\t }",
"function FreshResume() {\n\n }",
"function resumeTrack() {\n if (current_track_id !== null) {\n audioTracks[current_track_id].play();\n }\n}",
"resume() {\n this.lastTime = performance.now();\n const _ = this;\n setInterval(_.update.bind(_), 1000/this.desiredFPS);\n }",
"function restartGame() {\r\n level = 1;\r\n gamePattern = [];\r\n}",
"static resume() {\n TaskTimer._resolve_pause_lock();\n TaskTimer.paused = false;\n for (timer of TaskTimer.timers) timer.resume();\n }",
"function levelUp(){\n let nextlvxp = getxpforlv(player.level + 1);\n while(player.xp > nextlvxp){\n if(player.level != 100){\n player.levelup();\n adddiv_c(\"You leveled up! You are now level \" + player.level + \".\", \"lime\");\n nextlvxp = getxpforlv(player.level + 1);\n } else {\n adddiv(\"You are already max level. You cannot gain any more xp.\");\n break;\n }\n }\n {\n if(player.level != 100){\n let str = separateNum(nextlvxp - player.xp);\n adddiv(str + \" xp till next level.\");\n }\n }\n}",
"function setCurrLevel(btn) {\n if (btn.innerText === 'Easy') {\n gCurrLevel = 0;\n } else if (btn.innerText === 'Medium') {\n gCurrLevel = 1;\n } else if (btn.innerText === 'Hard') {\n gCurrLevel = 2;\n // CR: Unnecessary else statement.\n } else gCurrLevel;\n return gCurrLevel;\n}",
"function resumeWatchProgress () {\n\n var toWatchProgress = watchProgressItem ? watchProgressItem.progress : 0;\n\n if (toWatchProgress > 0) {\n player.seek(toWatchProgress * vm.item.duration);\n }\n }",
"function resumeEditing()\r\n{\r\n\twith(currObj);\r\n\tif(currObj.config['useIcons'])\r\n\t{\r\n\t\tcurrObj.actionSpan.innerHTML = \"<a class=\\\"resume_editing\\\"><img src=\\\"\" + currObj.config['imagePath'] + \"images/page_white_edit.png\\\" width=\\\"16\\\" height=\\\"16\\\" title=\\\"Resume Editing\\\" alt=\\\"Resume Editing\\\" border=\\\"0\\\" /></a>\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcurrObj.actionSpan.innerHTML = \"<a class=\\\"resume_editing\\\">Resume Editing</a>\";\r\n\t}\r\n\tif(currObj.config['useIcons'])\r\n\t{\r\n\t\tcurrObj.statusSpan.innerHTML = \"<img src=\\\"\" + currObj.config['imagePath'] + \"images/working.gif\\\" width=\\\"16\\\" height=\\\"16\\\" title=\\\"Working...\\\" alt=\\\"Working...\\\" border=\\\"0\\\" />\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcurrObj.statusSpan.innerHTML = \"Working...\";\r\n\t}\r\n\t\r\n\tif(spellingSuggestionsDiv)\r\n\t{\r\n\t\tspellingSuggestionsDiv.parentNode.removeChild(spellingSuggestionsDiv);\r\n\t\tspellingSuggestionsDiv = null;\r\n\t}\r\n\t\r\n\tcurrObj.switchText();\r\n}",
"isResume() {\n return !this.isPaused();\n }",
"function levelUpLeech(){\n if(protein >= upgradeLeechCost)\n {\n protein -= upgradeLeechCost;\n levelLeech += 1;\n\n performCalculations();\n updateLabels();\n }\n}",
"function resumePlayer(playingFromPopular = false) {\n\t// resume jPlayer\n\t$('#jquery_jplayer_1').jPlayer('play')\n\n\t// update UI state\n\treturn {\n\t\ttype: PLAY,\n\t\tplayingFromPopular,\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
funcion para evaluar el medio y forma de pago | function evaluarMetodoYFormaPago () {
if ($metodoPago.val() === '') {
bootbox.alert('Por favor, seleccione el método de pago');
return false;
}
// en efectivo
if ($metodoPago.val() === '1') {
// en efectivo
$('#cobroEfectivo').removeClass('hide');
$('#montoPago').rules('add', {
required: true,
min: Number($('#costo').val()),
messages: {
required: 'Campo obligatorio',
min: 'Ingrese una cantidad igual o mayor a ' + costo
}
});
$('#cambio').rules('add', {
required: true,
min: 0,
messages: {
required: 'Campo obligatorio',
min: 'Ingrese una cantidad igual o mayor a 0'
}
});
} else {
$('#cobroEfectivo').addClass('hide');
$('#montoPago').rules('remove');
$('#cambio').rules('remove');
}
// parcial
/*if ($formaPago.val() === '2') {
// calcular el costo minimo a cubrir
var costoMinimo = costo * 0.5;
if ($metodoPago.val() === '1') {
// en efectivo
$('#abono').removeClass('hide');
$('#cobroEfectivo').removeClass('hide');
$('#cantidadAAbonar').rules('add', {
required: true,
min: costoMinimo,
max: costo,
messages: {
required: 'Campo obligatorio',
min: 'Ingrese una cantidad igual o mayor a ' + costoMinimo,
max: 'Ingrese una cantidad menor a ' + costo
}
});
$('#montoPago').rules('add', {
required: true,
messages: {
required: 'Campo obligatorio'
}
});
$('#cambio').rules('add', {
required: true,
messages: {
required: 'Campo obligatorio'
}
});
} else {
$('#cobroEfectivo').addClass('hide');
$('#montoPago').rules('remove');
$('#cambio').rules('remove');
// tarjeta de crédito
$('#abono').removeClass('hide');
$('#cantidadAAbonar').rules('add', {
required: true,
min: costoMinimo,
max: costo,
messages: {
required: 'Campo obligatorio',
min: 'Ingrese una cantidad igual o mayor a ' + costoMinimo,
max: 'Ingrese una cantidad menor a ' + costo
}
});
}
}*/
} | [
"function calcularProm(filas)\n{\n let promedio = document.getElementById('promedio');\n let max = document.getElementById('precioMaximo');\n let min = document.getElementById('precioMinimo');\n if(filas.length != 0 )\n {\n let celdas = traerColumna(filas,'name','CELDAPRECIO').map((e)=>parseInt(precioDeServer(e.textContent)));\n let precioFinal = celdas.reduce((a,b)=> a + b) / celdas.length;\n let precioMaximo = celdas.reduce((a,b)=> a>=b ? a : b);\n let precioMinimo = celdas.reduce((a,b)=> a>=b ? b : a);\n promedio.value = precioDeForm(precioFinal);\n max.value = precioDeForm(precioMaximo);\n min.value = precioDeForm(precioMinimo);\n }\n else{\n promedio.value = precioDeForm(0);\n max.value = precioDeForm(0);\n min.value = precioDeForm(0);\n }\n porcentajeVacunados(filas);\n}",
"function calculate () {\n if (page === 1) {\n dInput = document.getElementById('d-input').value\n dInput = parseInt(dInput)\n radius = dInput / 2\n area = Math.PI * radius ** 2\n area = area.toFixed(2)\n document.getElementById('area-result').innerHTML = area\n document.getElementById('radius-result').innerHTML = radius\n document.getElementById('result-section').style.display = 'block'\n document.getElementById('formula1').style.display = 'block'\n document.getElementById('formula2').style.display = 'none'\n } else if (page === 2) {\n dInput = document.getElementById('d-input').value\n dInput = parseInt(dInput)\n radius = dInput / 2\n circumference = 2 * Math.PI * radius\n circumference = circumference.toFixed(2)\n document.getElementById('area-result2').innerHTML = circumference\n document.getElementById('radius-result2').innerHTML = radius\n document.getElementById('result-section').style.display = 'block'\n document.getElementById('formula1').style.display = 'none'\n document.getElementById('formula2').style.display = 'block'\n }\n}",
"function ultimaPagina(){\n\tif(pagina_actual!=paginas_totales){\n\t\tpagina_actual=paginas_totales;\n\t\tconsole.log('Moviendonos a la página '+pagina_actual+\"...\");\n\t\tborrar_recetas_index();\n\t\t\n\t\tlet pagina = paginas_totales-1;\n\t\tpeticionRecetas(\"./rest/receta/?pag=\"+pagina+\"&lpag=6\");\n\t\tModificar_botonera_Index();\n\t}\n}",
"function tasaSimple(meses, monto_total, monto_men){\n\t\n\t// var i = 0.05;\n\n\tvar resigual = monto_total / monto_men;\n\tvar res = 0;\n\ti = 0.00;\n\n\t// alert(\"resigual: \" + resigual);\n\n\tdo{\n\t\ti += 0.01;\n\t\tres = (1 - (Math.pow((1 + i), -1 * meses))) / i ;\n\t\t// alert(res);\n\t\t\n\t}while(res>resigual);\n\n\t// if ((Math.round(res* 100) / 100 ) == (Math.round(resigual* 100) / 100 ) ){\n\t// \t// alert(\"Tasa de interes : \" + i);\n\t// }else{\n\t// \t// alert(\"Tasa posible entre i: \" + i + \" y \"+ (i-0.01));\n\t// }\n\n\ti1 = (1 - (Math.pow((1 + i), -1 * meses))) / i ;\n\ti2 = (1 - (Math.pow((1 + (i-0.01)), -1 * meses))) / (i-0.01) ;\n\n\ti1dif = resigual - i1;\n\ti2dif = i2 - resigual;\n\n\tinterpol = 0.01 * i1dif / i2dif ;\n\n\ttasa_apro = i + interpol;\n\n\t//alert(\"Tasa Aproximada: \" +(Math.round(tasa_apro* 100) ));\n\n\treturn tasa_apro;\n}",
"function pageRequirements(book1, book2, book3) {\n const book1page = book1 * 100;\n const book2page = book2 * 200;\n const book3page = book3 * 300;\n const pageRequirement = book1page + book2page + book3page;\n return pageRequirement\n \n}",
"function fecha() {\n var a = new Date(2001, 2, 1);//valor1 para calcular el paso de 90 dias\n var b = new Date(2001, 4, 30);//valor2 para calcular el paso de 90 dias \n var x = a.getTime();//valor1 en tiempo transcurrido desde la epoca de unix\n var y = b.getTime();//valor2 en tiempo transcurrido desde la epoca de unix\n var tiempo = y - x;//calculo del tiempo pasado en 90 dias\n var fecha_actual = new Date();//fecha actual\n var hoy = fecha_actual.getTime();//fecha actual en tiempo transcurrido desde la epoca unix\n var comision = hoy + tiempo;//resultado del tiempo que transcurre en 90 dias desde la fecha actual\n var total = new Date(comision);//fecha tras los 90 dias\n //Laura: formato DD/MM/YYYY\n var dia = total.getDate();//dia tras los 90 dias\n var mes = total.getMonth() + 1;//mes tras los 90 dias en formato 1-12\n var ano = total.getFullYear();//año tras los 90 dias en formato 4 digitos\n alert(\"Empezaras a pagar comisiones el: \" + dia + \"/\" + mes + \"/\" + ano);//muestra la fecha tras 90 dias \n\n}",
"function calculRemise(total = null, remise = null) {\n if (total){ montantTotal = existence(total);}else{montantTotal = 0;}\n if (remise){ montantVerse = existence(remise);}else {montantVerse = 0;}\n var reduction = total*remise*0.01; console.log(reduction);\n var resultat = total - reduction;\n\n return resultat;\n}",
"function promedioDeEdad(a,b,c,d,e){\r\n let suma = a+b+c+d+e;\r\n let promedio = suma/5\r\n return promedio\r\n}",
"function primeraPagina(){\n\tif(pagina_actual!=1){\n\t\t\n\t\tpagina_actual = 1;\n\t\tconsole.log('Moviendonos a la página '+pagina_actual+\"...\");\n\t\tborrar_recetas_index();\n\t\tlet pagina = pagina_actual-1;\n\t\tpeticionRecetas(\"./rest/receta/?pag=\"+pagina+\"&lpag=6\");\n\t\tModificar_botonera_Index();\n\t}\n}",
"function pintar(simulacion){\r\n\r\n\t\tlimpiar();\r\n\t\tpintarAgua(simulacion);\r\n\t\tpintarAlcantarillado(simulacion);\r\n\r\n\t\t\r\n\r\n\t\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n}",
"function pagesCalculator(bookOneQuantity, bookTwoQuantity, bookThreeQuantity) {\n const bookOnePages = 100;\n const bookTwoPages = 200;\n const bookThreePages = 300;\n // page calculation\n const bookOnePagesQuantity = bookOneQuantity * bookOnePages;\n const bookTwoPagesQuantity = bookTwoQuantity * bookTwoPages;\n const bookThreePagesQuantity = bookThreeQuantity * bookThreePages;\n // total pages\n totalBookPages = bookOnePagesQuantity + bookTwoPagesQuantity + bookThreePagesQuantity;\n\n return totalBookPages;\n}",
"function resultado(result){\n if((calculadora.innerHTML === 0 || calculadora.innerHTML === \"0\") && valor2 === 0){\n console.log(\"debe ingresar un numero o realizar una operacion\");\n }else{\n if(operation === \"sum\"){\n sumar();\n }\n if(operation === \"rest\"){\n restar();\n }\n if(operation === \"div\"){\n dividir();\n }\n if(operation === \"multi\"){\n multiplicar();\n }\n }\n}",
"function medianaSalarios(lista) {\n // necesitamos la mitad de la mediana de salarios\n // parseInt le quita los decimales al resultado\n const mitad = parseInt(lista.length / 2);\n\n // verificamos si la lista de nuestro pais de personas es par o impar\n if (esPar(lista.length)) {\n // devuelo las dos posiciones la ser par\n const personitaMitad1 = lista[mitad - 1];\n const personitaMitad2 = lista[mitad]; \n\n const mediana = calcularMediaAritmetica([personitaMitad1, personitaMitad2]);\n return mediana; \n } else {\n //devuelo la posicion de lista[mitad] al ser impar\n const personitaMitad = lista[mitad];\n return personitaMitad;\n }\n}",
"function validarDados() {\n var mensagem = \"Preencha corretamente os seguintes campos:\";\n\n if (trim(document.formFormaPagamento.nome.value) == \"\") {\n mensagem = mensagem + \"\\n- Nome\";\n }\n else {\n // Linha abaixo comentada para manter acentos\n //document.formFormaPagamento.nome.value = retirarAcentos(trim(document.formFormaPagamento.nome.value)).toUpperCase();\n document.formFormaPagamento.nome.value = trim(document.formFormaPagamento.nome.value).toUpperCase();\n }\n\n if (trim(document.formFormaPagamento.descricao.value) == \"\") {\n mensagem = mensagem + \"\\n- Descricao\";\n }\n else {\n // Linha abaixo comentada para manter acentos\n //document.formFormaPagamento.descricao.value = primeirasLetrasMaiusculas(retirarAcentos(trim(document.formFormaPagamento.descricao.value)).toLowerCase());\n document.formFormaPagamento.descricao.value = primeirasLetrasMaiusculas(trim(document.formFormaPagamento.descricao.value).toLowerCase());\n }\n\n if (document.formFormaPagamento.tipo.value == \"selected\") {\n mensagem = mensagem + \"\\n- Tipo\";\n }\n\n // Trecho de codigo para quando for usar desconto no pagamento a vista\n /*if (document.formFormaPagamento.tipo.value == 'A') {\n if (trim(document.formFormaPagamento.desconto.value) == \"\") {\n mensagem = mensagem + \"\\n- Desconto(%)\";\n }\n if (trim(document.formFormaPagamento.pisoParaDesconto.value) == \"\") {\n mensagem = mensagem + \"\\n- Valor minimo para desconto(R$)\";\n }\n }*/\n\n if (document.formFormaPagamento.tipo.value == 'P') {\n if (trim(document.formFormaPagamento.valorMinimoAPrazo.value) == \"\") {\n mensagem = mensagem + \"\\n- Valor minimo\";\n }\n else {\n document.formFormaPagamento.valorMinimoAPrazo.value = document.formFormaPagamento.valorMinimoAPrazo.value.replace(\",\", \".\");\n }\n }\n\n if (mensagem == \"Preencha corretamente os seguintes campos:\") {\n return true;\n }\n else {\n alert(mensagem);\n goFocus('nome');\n return false;\n }\n}",
"function FormulaPage() {}",
"function chkFormula(obj,measName){\r\n\t\r\n\t//1. Hallamos la medida 1, el operarador y la medida2 (o number)\r\n\tvar formula = obj.value;\r\n\tif (formula == \"\"){\r\n\t\talert(MSG_MUST_ENTER_FORMULA);\r\n\t\treturn false;\r\n\t}\r\n\tvar esp1 = formula.indexOf(\" \");\r\n\tvar formula2 = formula.substring(esp1+1, formula.length);\r\n\tvar meas1 = formula.substring(0,esp1);\r\n\tvar op = formula2.substring(0,1);\r\n\tvar meas2 = formula2.substring(2, formula2.length);\r\n\t\r\n\t//2. Verificamos la medida1 exista\r\n\tif (!chkMeasExist(meas1)){\r\n\t\tif (esp1 < 0){\r\n\t\t\talert(formula + \": \" + MSG_MEAS_OP1_NAME_INVALID);\r\n\t\t}else {\r\n\t\t\talert(meas1 + \": \" + MSG_MEAS_OP1_NAME_INVALID);\r\n\t\t}\r\n\t\tobj.focus();\t\t\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\t//3. Verificamos el operador sea valido\r\n\tif (op != '/' && op != '-' && op != '+' && op != '*'){\r\n\t\talert(op + \": \" + MSG_OP_INVALID);\r\n\t\tobj.focus();\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\t//4. Verificamos la medida2 exista\r\n\tif (!chkMeasExist(meas2)){//Si no existe como medida talvez sea un numero\r\n\t\tif (isNaN(meas2)){\r\n\t\t\talert(meas2 + \": \" + MSG_MEAS_OP2_NAME_INVALID);\r\n\t\t\tobj.focus();\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\t\r\n\t//5. Verificamos no se utilice el nombre de la propia medida como un operando de la formula.\r\n\tif (measName == meas1 || measName == meas2){\r\n\t\talert(measName + \": \" + MSG_MEAS_NAME_LOOP_INVALID);\r\n\t\tobj.focus();\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\treturn true;\r\n}",
"function calcular_si_mueve(element, partes) {\n switch (puzzleElegido){\ncase \"south_park\": comprovarGanado(partes, array_south_park); break;\ncase \"peter\": comprovarGanado(partes, array_peter_partido); break;\ncase \"homer\": comprovarGanado(partes, array_homer_partido); break;\ncase \"stan \": comprovarGanado(partes, erased_value_stan); break;\n }\n \n var valor_element = element.getBoundingClientRect();\n var vacio = document.getElementById(\"vacio\");\n\n\n var valor_vacio = vacio.getBoundingClientRect();\n\n if (\n seTocanAbajo(valor_element, valor_vacio, element, vacio) ||\n seTocanArriba(valor_element, valor_vacio, element, vacio) ||\n seTocanDerechaNormal(valor_element, valor_vacio, element, vacio) ||\n seTocanIzquierda(valor_element, valor_vacio, element, vacio)\n ) {\n\n var valor_anterior = Number(document.getElementById(\"mov\").innerHTML);\n document.getElementById(\"mov\").innerHTML = valor_anterior + 1;\n\n } else {\n\n flash(element.getAttribute(\"name\"))\n\n }\n\n\n}",
"function accionCierreAplicacionNacar(parametros){\nif (parametros) { \n\t\tvar datos = parametros.split(\"||\");\n\t\tif (datos) {\n\t\t\tvar op = datos[0];\n\t\t\tswitch(op) {\n\t\t\t\tcase \"0\": // Si es pagina contenedora\n\t\t\t\t\tif (typeof (CTE_CONTENEDORES_PAGINA_CONTENEDORA)!=\"undefined\") {\n\t\t\t\t\t\tprevenirCierrePaginaContenedora();\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase \"1\": // Si es cierre de ventana modal\n\t\t\t\t\t\n\t\t\t\t\t//Pendiente de realizar para el entorno ligero\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"2\"://Cierre Mediante Notificación Tarea Invocante\n\t\t\t\t\t\n\t\t\t\t\tif (null != datos[1] && typeof(datos[1]) != \"undefined\" \n\t\t\t\t\t\t&& datos[1] != \"\" && datos[1] != \"null\" \n\t\t\t\t\t\t&& typeof(callback_notificacion_cierre_tarea)!= \"undefined\"){\n\t\t\t\t\t\tcallback_notificacion_cierre_tarea (datos[1], datos[2]);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"3\"://Notificacion a la ventana contextual\n \t\t if (typeof(utils_callBackVentanaContextual)==\"function\"){\n \t\t try{\n \t\t var objJson2=eval( \"(\" + datos[1] + \")\" );\n utils_callBackVentanaContextual(objJson2);\n }catch (errr){\n alert(errr.message);\n } \n }\n break;\n\t\t\t\t case \"4\"://Notificacion cambio contexto\n\t\t\t\t for(var i = 0; i<utils_callBackRegistroContexto.length; i++){\n\t\t\t\t\tdatos[2]=datos[2].replace(/\\+/g, \" \");\n\t\t\t\t\tif(typeof(utils_callBackRegistroContexto[i])==\"function\" && (utils_callBackRegistroContexto[i].toString().split('('))[0]==datos[2]){\n\t\t\t\t\t\ttry{\n\t\t\t\t\t\t\tvar objJson2=eval( \"(\" + datos[1] + \")\" );\n\t\t\t\t\t\t\tutils_callBackRegistroContexto[i](objJson2);\n\t\t\t\t\t\t}catch (errr){\n\t\t\t\t\t\t\talert(errr.message);\n\t\t\t\t\t\t} \n\t\t\t\t\t}\n\t\t\t\t }\n\t\t\t\t break;\n \t\t}\n\t\t}\n\t}\n}",
"function Dias_Fevereiro(ano){\n if ( ano%4==0 && ( ano%100!=0 || ano%400==0) ) return 29;\n else return 28; \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
look for secondary buttons misused, and convert them if needed | convertButtons() {
// if on the small design, or on the large design + white background
// replace white buttons by blue ones
if (
window.matchMedia('(max-width: 64rem)').matches ||
(window.matchMedia('(min-width: 64rem)').matches &&
this.design === 'bow')
)
this.querySelectorAll('.a-button--secondary--white').forEach(e => {
e.classList.replace(
'a-button--secondary--white',
'a-button--secondary'
)
})
// if on large design + blue background, replace secondary blue by white buttons
if (
window.matchMedia('(min-width: 64rem)').matches &&
this.design === 'wob'
)
this.querySelectorAll('.a-button--secondary').forEach(e => {
e.classList.replace(
'a-button--secondary',
'a-button--secondary--white'
)
})
} | [
"ensureButtonsHidden() {\n // TODO(fanlan1210)\n }",
"function disableMainPageButtons() {\n\t\t\tevents.forEach( ev => { \n\t\t\t\tev.button.mouseEnabled = false;\n\t\t\t\tev.button.cursor = \"default\";\n\t\t\t});\n\t\t\n\t\t\tcultures.forEach( cu => { \n\t\t\t\tcu.button.mouseEnabled = false;\n\t\t\t\tcu.button.cursor = \"default\";\n\t\t\t});\n\t\t\n\t\t\tself.aboutUsBtn.mouseEnabled = false;\n\t\t\tself.aboutUsBtn.cursor = \"default\";\n\t\t\n\t\t\tself.returnBtn.mouseEnabled = false;\n\t\t\tself.returnBtn.cursor = \"default\";\n\t\t}",
"updatePriorityColors() {\n // Mutation may have been one that removes the DOM\n if (!getSidebar()) { return; }\n\n const selectedPriorities = new Set();\n this.appliedLabels.forEach(b => selectedPriorities.add(b.textContent));\n\n this.buttons.forEach(button => {\n if (selectedPriorities.has(button.id)) {\n button.classList.add(`selected-${button.id}`);\n } else {\n button.classList.remove(`selected-${button.id}`);\n }\n })\n }",
"[updateButtons]() {\n\t\t\tconst self = this;\n\t\t\tconst _self = _(self);\n\n\t\t\tif (!self.isRemoved && self.showButtons()) {\n\t\t\t\t_self.controls.get(PREV_BUTTON_ID).isVisible(!_self.isAtStart());\n\t\t\t\t_self.controls.get(NEXT_BUTTON_ID).isVisible(!_self.isAtEnd());\n\t\t\t}\n\t\t}",
"get buttons() { return getSidebar().querySelectorAll('.priority-labels button'); }",
"function removeVisualiserButton(){\r\n\teRem(\"buttonWaves\");\r\n\teRem(\"buttonBars\");\r\n\teRem(\"buttonBarz\");\r\n\teRem(\"buttonCircleBars\");\r\n\teRem(\"buttonCirclePeaks\");\r\n\tremoveSliderSelector();\r\n}",
"styleButtons () {\n // Check if it was rated\n if (this.props.wasPositive !== null) {\n // Previous rating positive\n if (this.props.wasPositive) {\n // Is this a positive rating button\n return (this.props.isPositive) ? 'green' : 'grey'\n } else {\n // Previous rating was negative\n // Is this a negative rating button\n return (!(this.props.isPositive)) ? 'red' : 'grey'\n }\n } else { // There was no previous rating\n return (this.props.isPositive) ? 'lightgreen' : 'lightred'\n }\n }",
"function removeUnderscores() {\n for (i = 0; i < 4; i++) {\n var catBtnText = $(\"#categoryBtn-\" + i).text();\n var formattedText = catBtnText.replace(/_/g, \" \");\n $(\"#categoryBtn-\" + i).text(formattedText);\n }\n }",
"function highlightButtons() {\n\n\tfunction foundButton() {\n\t\t// button.style.border = '10px red solid'\n\t\tbutton.style.backgroundColor = 'red'\n\t\tbutton.disabled = false\n\n\t\tvar new_element = button.cloneNode(true);\n\t\tbutton.parentNode.replaceChild(new_element, button);\n\t\tnew_element.onclick = function() { return false }\n\n\t\tnew_element.addEventListener(\"click\", function (e) {\n\t\t\te.preventDefault()\n\t\t\te.stopPropagation();\n e.stopImmediatePropagation()\n\t\t\t// Add new keyboard shortcut\n\t\t\tkeymapList.push({ name: this.textContent, xpath: xpath(this), mapping: ''})\n\t\t\tchrome.storage.local.set({ keymapList: keymapList })\n\t\t\tlocation.reload()\n\t\t});\n\t}\n\n\tvar buttons = document.querySelectorAll('button')\n\tfor (button of buttons) {\n\t\tif (button.textContent != '') {\n\t\t\tfoundButton(button)\n\t\t}\n\t}\n\tfor (var iframe of document.querySelectorAll('iframe')) {\n\t\tvar buttons = iframe.contentWindow.document.querySelectorAll('button')\n\t\tfor (button of buttons) {\n\t\t\tif (button.textContent != '') {\n\t\t\t\tfoundButton(button)\n\t\t\t}\n\t\t}\n\t}\n}",
"function prioritize_button(on) {\n\t\t\t$prioritize_btn = $('.tasks_page').find(\"#prioritize_btn\");\n\t\t\tif (on) {\n\t\t\t\t$prioritize_btn.css('background-color', '#ffdb26');\n\t\t\t\t$prioritize_btn.css('border-color', '#f2ca00');\n\t\t\t\t$($prioritize_btn.children('.btn_name')).css('color', 'white');\n\t\t\t} else {\n\t\t\t\t$prioritize_btn.css('background-color', '#fff7cf');\n\t\t\t\t$prioritize_btn.css('border-color', '#ffdb26');\n\t\t\t\t$($prioritize_btn.children('.btn_name')).css('color', '#626262');\n\t\t\t}\n\t\t\tprioritize_mode = on;\n\t\t}",
"function enableMainPageButtons() {\n\t\t\tevents.forEach( ev => { \n\t\t\t\tev.button.mouseEnabled = true;\n\t\t\t\tev.button.cursor = \"pointer\";\n\t\t\t});\n\t\t\n\t\t\tcultures.forEach( cu => { \n\t\t\t\tcu.button.mouseEnabled = true;\n\t\t\t\tcu.button.cursor = \"pointer\";\n\t\t\t});\n\t\t\n\t\t\tself.aboutUsBtn.mouseEnabled = true;\n\t\t\tself.aboutUsBtn.cursor = \"pointer\";\n\t\t\n\t\t\tself.returnBtn.mouseEnabled = true;\n\t\t\tself.returnBtn.cursor = \"pointer\";\n\t\t}",
"switchSortButtons(selected) {\n for(let button of $(\"#btn-sort button\")) {\n if(button === selected[0]) {\n let icon = button.children[0];\n let font = icon.getAttribute(\"class\");\n let sort = button.getAttribute(\"value\").split('-');\n this.sortKey = sort[0];\n this.sortOrder = sort[1] === \"ascending\";\n // click the same button\n if(button.getAttribute(\"class\") === \"btn btn-info\") {\n // reverse icon\n icon.setAttribute(\"class\", font.indexOf(\"-alt\") > 0 ? font.replace(\"-alt\", \"\") : font + \"-alt\");\n // reverse sort order\n this.sortOrder = !this.sortOrder;\n if(this.sortOrder)\n button.setAttribute(\"value\", button.getAttribute(\"value\").replace(\"descending\", \"ascending\"));\n else\n button.setAttribute(\"value\", button.getAttribute(\"value\").replace(\"ascending\", \"descending\"));\n } else {\n button.setAttribute(\"class\", \"btn btn-info\");\n }\n } else {\n button.setAttribute(\"class\", \"btn btn-secondary\");\n }\n }\n }",
"function refreshButtonStyle(button) {\r\r\n $(button).removeClass();\r\r\n\r\r\n var addon = JSON.parse(unescape($(button).data('key')));\r\r\n\r\r\n $(button).addClass(getButtonStyle(addon));\r\t\r // $(button).attr('disabled',true);\r\t\r\n if($(button).attr('class')=='success'){\r\t\r\t$(button).prop('disabled',true); \r\t\r\t}\r\n if (studio.extension.storage.getItem('ERROR') === 'ok') {\r\r\n /// SUCCESS\r\r\n //$(button).text(studio.extension.storage.getItem(addon.name));\r\r\n\r\r\n $(button).off('click');\r\r\n } else {\r\r\n /// ERROR\r\r\n $(button).addClass('error');\r\r\n console.error(studio.extension.storage.getItem('ERROR'));\r\r\n }\r\r\n}",
"function fixDownloadButton() {\n\t\tlet dlBtn = document.getElementsByClassName('dev-page-download');\n\n\t\tfor(let i = 0; i < dlBtn.length; i++) {\n\t\t\tcleanupLink(dlBtn[i]);\n\n\t\t\tif(debug)\n\t\t\t\tconsole.info(scriptName + ': Removed junk from Download-Button');\n\t\t}\n\t}",
"function refreshWidgetAndButtonStatus() {\n var curWidget = self.currentWidget();\n if (curWidget) {\n widgetArray[curWidget.index].isSelected(false);\n self.currentWidget(null);\n }\n self.confirmBtnDisabled(true);\n }",
"function btnBuchenAusB() {\n document.getElementById('btn-buchen').classList.add('nodisplay');\n document.getElementById('btn-aendern').classList.remove('nodisplay');\n document.getElementById('btn-loeschen').classList.remove('nodisplay');\n document.getElementById('btn-abbrechen').classList.remove('nodisplay');\n document.getElementById('btn-lieferschein').classList.remove('nodisplay');\n}",
"function tooltipTextConverter(data) {\n var str = \"\"\n var e = myDiagram.lastInput\n var currobj = e.targetObject\n if (currobj !== null && (currobj.name === \"ButtonA\" ||\n (currobj.panel !== null && currobj.panel.name === \"ButtonA\"))) {\n str = data.aToolTip\n } else {\n str = data.bToolTip\n }\n return str\n }",
"ensureButtonsShown() {\n // TODO(fanlan1210)\n }",
"function resetButtons() {\n hitButton.disabled = true;\n standButton.disabled = true;\n continueButton.disabled = false;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
handel on canvas scroll | onCanvasScroll(e){
let conavasScrollPos = document.getElementById("canvas").scrollLeft;
let endWinPos = document.getElementById("endWindow");
endWinPos.style.right = - conavasScrollPos+"px";
this.props.jsPlumbRef ? this.props.jsPlumbRef.repaintEverything() : ''
} | [
"handleScroll_() {\n this.resetAutoAdvance_();\n }",
"function onScroll(e) {\n if (cameraZoom >= 1 && cameraZoom <= cameraMaxZoom) {\n if (cameraZoom + -e.deltaY / 500 < 1 || cameraZoom + -e.deltaY / 500 > cameraMaxZoom) { return; }\n cameraZoom += -e.deltaY / 500;\n }\n}",
"function scrollDown(){\n startY -= 15;\n createSVGOutput();\n}",
"onScroll_() {\n if (!this.isActive_()) {\n return;\n }\n this.vsync_.run(\n {\n measure: state => {\n state.shouldBeFullBleed =\n this.getOverflowContainer_()./*OK*/ scrollTop >=\n FULLBLEED_THRESHOLD;\n },\n mutate: state => {\n this.getShadowRoot().classList.toggle(\n FULLBLEED_CLASSNAME,\n state.shouldBeFullBleed\n );\n },\n },\n {}\n );\n }",
"function setCanvasLocation(){\n\tif( window.scrollY > canvasToTop ){\n\t\tintro.style.marginBottom = canvasComputedHeight;\n\t\tcanvas.className = 'canvas-fixed z-depth-4';\n\t}else{\n\t\tintro.style.marginBottom = 0;\n\t\tcanvas.className = '';\n\t}\n}",
"function onScroll(e) {\n\n\t\t// this.scrollLeft/Top is faster then $(this).scrollLeft/Top()\n\t\tvar newLeft = this.scrollLeft;\n\t\tvar newTop = this.scrollTop;\n\n\t\tvar xVector = newLeft - e.data.left;\n\t\tvar yVector = newTop - e.data.top;\n\n\t\tif (xVector)\n\t\t\t$(this).trigger('scrollx', xVector);\n\t\tif (yVector)\n\t\t\t$(this).trigger('scrolly', yVector);\n\n\t\te.data.left = newLeft;\n\t\te.data.top = newTop;\n\t}",
"function onScroll() {\n if (scrollContainer.current.scrollTop < 5) {\n setShowTopIndicator(false)\n }\n else {\n setShowTopIndicator(true)\n }\n if (scrollContainer.current.scrollHeight - scrollContainer.current.scrollTop > scrollContainer.current.clientHeight + 5) {\n setShowBottomIndicator(true)\n }\n else {\n setShowBottomIndicator(false)\n }\n }",
"function detectScroll(){\n\tvar percent = _scrollTop() / ( _scrollHeight() - _innerHeight() );\n\tif(oldPercent != percent)\n\t{\n\t\tif(percent >= 0){\n\t\t\toldPercent = percent;\n\t\t\tgetFlash().scrollFlash( percent, 0 );\n\t\t} \n\t}\n}",
"onScroll(e) {\n let scrollTop = e.target.scrollTop;\n if (this._silent || this.smoothScroll.running || Math.abs(scrollTop - this.smoothScroll.target) <= 0.5 || !this.props.onScroll) return;\n this.props.onScroll(scrollTop);\n }",
"function scrollbar(){\n\n if (ifTouchDevices){\n $('body').addClass('scroll-touch');\n\n $('a#open-more-info').on( \"click\", function() {\n event.preventDefault();\n var target = \"#\" + this.getAttribute('data-target');\n $('html, body').animate({\n scrollTop: $(target).offset().top\n }, 500);\n });\n } \n\n else {\n $('body').mCustomScrollbar({\n scrollInertia: 150,\n axis :\"y\"\n }); \n }\n }",
"function handleScroll() {\n const bottomDiff = document.documentElement.offsetHeight - (window.innerHeight + document.documentElement.scrollTop);\n if (bottomDiff > 300) {\n needToHitApi = true;\n return;\n }\n if (needToHitApi) setPage(page => page+1);\n needToHitApi = false;\n }",
"function scrollRefraction(){\n simBorder = simSection.getBoundingClientRect();\n simOrigin.y = simBorder.y;\n onScreen = false;\n if(simBorder.top < h && simBorder.bottom > 0)\n onScreen = true;\n}",
"function scrollUp(){\n startY += 15;\n createSVGOutput();\n}",
"handleWindowScroll() {\n const sectionHTMLElement = this.sectionHTMLElement.current;\n const { top } = sectionHTMLElement.getBoundingClientRect();\n\n const shouldUpdateForScroll = Section.insideScrollRangeForUpdates.call(this, top);\n if ( shouldUpdateForScroll ) {\n\n this.updateParallaxForScrollPosition(top);\n }\n }",
"onScroll(e) {\n\t\tconst elementHeight = e.target.scrollHeight / this.fontManager.fonts.length;\n\t\tconst downloadIndex = Math.ceil((e.target.scrollTop + e.target.clientHeight) / elementHeight);\n\t\tthis.fontManager.downloadPreviews(downloadIndex + 5);\n\t}",
"handleStart(e) {\r\n // Je touche le canvas, je dessine :\r\n this.painting = true;\r\n // Coordonnées du touch :\r\n var touches = e.changedTouches;\r\n for(var i=0; i<touches.length; i++){\r\n this.canvas[0].touchX = (touches[i].pageX - this.canvas[0].offsetLeft);\r\n this.touchY = (touches[i].pageY - this.canvas[0].offsetTop);\r\n }\r\n }",
"setCardScrollTrackerMapper() {\n document\n .querySelector('#scrl4')\n .addEventListener('scroll', this.trakerMapperBound, {\n passive: true,\n });\n }",
"function scroll (e) {\n var xyS = scrollXY(iwin) // iframe scroll\n var ifrPos = xy.add(xyS, lastMousePos)\n coords.show(xy.str(ifrPos))\n }",
"function paddleInCanvas(){\nif(mouseY+paddle1Height > height){\nmouseY=height-paddle1Height;\n}\nif(mouseY < 0){\nmouseY =0;\n}\n\n\n}",
"__patchWheelOverScrolling() {\n this.$.selector.addEventListener('wheel', (e) => {\n const scrolledToTop = this.scrollTop === 0;\n const scrolledToBottom = this.scrollHeight - this.scrollTop - this.clientHeight <= 1;\n if (scrolledToTop && e.deltaY < 0) {\n e.preventDefault();\n } else if (scrolledToBottom && e.deltaY > 0) {\n e.preventDefault();\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a face to a face list. The input face is specified as an image with a targetFace rectangle. It returns a persistedFaceId representing the added face, and persistedFaceId will not expire. Note persistedFaceId is different from faceId which represents the detected face by Face Detect. The persistedFaceId of face list is used in Face List Delete a Face from a Face List to remove face from a face list, or the output JSON of Face Find Similar JPEG, PNG, GIF(the first frame), and BMP are supported. The image file size should be larger than or equal to 1KB but no larger than 4MB. The detectable face size is between 36x36 to 4096x4096 pixels. The faces out of this range will not be detected. Rectangle specified by targetFace should contain exactly one face. Zero or multiple faces will be regarded as an error. Out of detectable face size, large headpose, or very large occlusions will also result in fail to add a person face. The given rectangle specifies both face location and face size at the same time. There is no guarantee of correct result if you are using rectangle which are not returned from Face Detect. Face list is a group of faces, and these faces will not expire. Face list is used as a parameter of source faces in Face Find Similar. Face List is useful when to find similar faces in a fixed face set very often, e.g. to find a similar face in a face list of celebrities, friends, or family members. A face list can have a maximum of 1000 faces. Http Method POST | faceListAddAFaceToAFaceListPost(queryParams, headerParams, pathParams) {
const queryParamsMapped = {};
const headerParamsMapped = {};
const pathParamsMapped = {};
Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, FaceListAddAFaceToAFaceListPostQueryParametersNameMap));
Object.assign(headerParamsMapped, convertParamsToRealParams(headerParams, FaceListAddAFaceToAFaceListPostHeaderParametersNameMap));
Object.assign(pathParamsMapped, convertParamsToRealParams(pathParams, FaceListAddAFaceToAFaceListPostPathParametersNameMap));
return this.makeRequest('/facelists/{faceListId}/persistedFaces', 'post', queryParamsMapped, headerParamsMapped, pathParamsMapped);
} | [
"faceListCreateAFaceListPut(queryParams, headerParams, pathParams) {\n const queryParamsMapped = {};\n const headerParamsMapped = {};\n const pathParamsMapped = {};\n Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, FaceListCreateAFaceListPutQueryParametersNameMap));\n Object.assign(headerParamsMapped, convertParamsToRealParams(headerParams, FaceListCreateAFaceListPutHeaderParametersNameMap));\n Object.assign(pathParamsMapped, convertParamsToRealParams(pathParams, FaceListCreateAFaceListPutPathParametersNameMap));\n return this.makeRequest('/facelists/{faceListId}', 'put', queryParamsMapped, headerParamsMapped, pathParamsMapped);\n }",
"function faces(name, title, id, data) {\n // create canvas to draw on\n const img = document.getElementById(id);\n if (!img) return;\n const canvas = document.createElement('canvas');\n canvas.style.position = 'absolute';\n canvas.style.left = `${img.offsetLeft}px`;\n canvas.style.top = `${img.offsetTop}px`;\n // @ts-ignore\n canvas.width = img.width;\n // @ts-ignore\n canvas.height = img.height;\n const ctx = canvas.getContext('2d');\n if (!ctx) return;\n // draw title\n ctx.font = '1rem sans-serif';\n ctx.fillStyle = 'black';\n ctx.fillText(name, 2, 15);\n ctx.fillText(title, 2, 35);\n for (const person of data) {\n // draw box around each face\n ctx.lineWidth = 3;\n ctx.strokeStyle = 'deepskyblue';\n ctx.fillStyle = 'deepskyblue';\n ctx.globalAlpha = 0.4;\n ctx.beginPath();\n ctx.rect(person.detection.box.x, person.detection.box.y, person.detection.box.width, person.detection.box.height);\n ctx.stroke();\n ctx.globalAlpha = 1;\n ctx.fillText(`${Math.round(100 * person.genderProbability)}% ${person.gender}`, person.detection.box.x, person.detection.box.y - 18);\n ctx.fillText(`${Math.round(person.age)} years`, person.detection.box.x, person.detection.box.y - 2);\n // draw face points for each face\n ctx.fillStyle = 'lightblue';\n ctx.globalAlpha = 0.5;\n const pointSize = 2;\n for (const pt of person.landmarks.positions) {\n ctx.beginPath();\n ctx.arc(pt.x, pt.y, pointSize, 0, 2 * Math.PI);\n ctx.fill();\n }\n }\n // add canvas to document\n document.body.appendChild(canvas);\n}",
"function detectFaces(img, faceSize = 150) {\r\n return getFacesFromLocations(img, locateFaces(img).map(mmodRect => mmodRect.rect), faceSize)\r\n }",
"function addToFacebank(name) {\n\n\t// <Prevent browser caching>\n\tmax = 9999999999999999;\n\tmin = 1000000000000000;\n\tvar id = Math.floor(Math.random() * (max - min)) + min;\n\tvar url = \"../data/facebank/\" + name + \"Banked.jpg?id=\" + id;\n\t// </ Prevent Browser Caching>\n\n\t// Hard Code a bunch of descriptions in for the people found by the face\n\t// tracker.\n\tdescription = \"\";\n\tswitch (name) {\n\tcase \"Andrew\":\n\t\tdescription = \"Northeastern Student\"\n\t\tbreak;\n\tcase \"Mark\":\n\t\tdescription = \"Northeastern Student\"\n\t\tbreak;\n\tcase \"Paul\":\n\t\tdescription = \"Northeastern Student\"\n\t\tbreak;\n\tcase \"Nick\":\n\t\tdescription = \"Northeastern Student\"\n\t\tbreak;\n\tcase \"Meg\":\n\t\tdescription = \"MIT Design student and Mentor\"\n\t\tbreak;\n\tcase \"Federico\":\n\t\tdescription = \"Director of MIT Media Labs\"\n\t\tbreak;\n\tdefault:\n\t\tdescripion = \"New Challenger!\"\n\t}\n\tfaceBank[name] = createNotification(name, description, url);\n\tconsole.log(\"ADDED TO FACEBANK\");\n}",
"function loadCubeMapFace(gl, target, texture, url){\r\n var image = new Image();\r\n image.onload = function()\r\n {\r\n \tgl.bindTexture(gl.TEXTURE_CUBE_MAP, cubeTexture);\r\n gl.texImage2D(target, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);\r\n }\r\n image.src = url;\r\n}",
"faceListUpdateAFaceListPatch(queryParams, headerParams, pathParams) {\n const queryParamsMapped = {};\n const headerParamsMapped = {};\n const pathParamsMapped = {};\n Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, FaceListUpdateAFaceListPatchQueryParametersNameMap));\n Object.assign(headerParamsMapped, convertParamsToRealParams(headerParams, FaceListUpdateAFaceListPatchHeaderParametersNameMap));\n Object.assign(pathParamsMapped, convertParamsToRealParams(pathParams, FaceListUpdateAFaceListPatchPathParametersNameMap));\n return this.makeRequest('/facelists/{faceListId}', 'patch', queryParamsMapped, headerParamsMapped, pathParamsMapped);\n }",
"setFaceColor ( face, RGB) {\n\t\t// debug\n\t\t//console.log(\"atomicGLskyBox(\"+this.name+\")::setFaceColor\");\n\t\tvar r = RGB[0];\n\t\tvar g = RGB[1];\n\t\tvar b = RGB[2];\n\t\t\n\t\t// switch face\n\t\tswitch(face){\n\t\t\tcase \"Front\":\n\t\t\t\tthis.colorsArray[0] =r;\n\t\t\t\tthis.colorsArray[1] =g;\n\t\t\t\tthis.colorsArray[2] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[3] =r;\n\t\t\t\tthis.colorsArray[4] =g;\n\t\t\t\tthis.colorsArray[5] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[6] =r;\n\t\t\t\tthis.colorsArray[7] =g;\n\t\t\t\tthis.colorsArray[8] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[9] =r;\n\t\t\t\tthis.colorsArray[10] =g;\n\t\t\t\tthis.colorsArray[11] =b;\t\t\t\n\t\t\tbreak;\n\n\t\t\tcase \"Back\":\n\t\t\t\tthis.colorsArray[12+0] =r;\n\t\t\t\tthis.colorsArray[12+1] =g;\n\t\t\t\tthis.colorsArray[12+2] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[12+3] =r;\n\t\t\t\tthis.colorsArray[12+4] =g;\n\t\t\t\tthis.colorsArray[12+5] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[12+6] =r;\n\t\t\t\tthis.colorsArray[12+7] =g;\n\t\t\t\tthis.colorsArray[12+8] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[12+9] =r;\n\t\t\t\tthis.colorsArray[12+10] =g;\n\t\t\t\tthis.colorsArray[12+11] =b;\n\t\t\tbreak;\t\t\t\n\t\t\tcase \"Top\":\n\t\t\t\tthis.colorsArray[24+0] =r;\n\t\t\t\tthis.colorsArray[24+1] =g;\n\t\t\t\tthis.colorsArray[24+2] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[24+3] =r;\n\t\t\t\tthis.colorsArray[24+4] =g;\n\t\t\t\tthis.colorsArray[24+5] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[24+6] =r;\n\t\t\t\tthis.colorsArray[24+7] =g;\n\t\t\t\tthis.colorsArray[24+8] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[24+9] =r;\n\t\t\t\tthis.colorsArray[24+10] =g;\n\t\t\t\tthis.colorsArray[24+11] =b;\n\t\t\tbreak;\t\t\t\n\t\t\tcase \"Bottom\":\n\t\t\t\tthis.colorsArray[36+0] =r;\n\t\t\t\tthis.colorsArray[36+1] =g;\n\t\t\t\tthis.colorsArray[36+2] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[36+3] =r;\n\t\t\t\tthis.colorsArray[36+4] =g;\n\t\t\t\tthis.colorsArray[36+5] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[36+6] =r;\n\t\t\t\tthis.colorsArray[36+7] =g;\n\t\t\t\tthis.colorsArray[36+8] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[36+9] =r;\n\t\t\t\tthis.colorsArray[36+10] =g;\n\t\t\t\tthis.colorsArray[36+11] =b;\n\t\t\tbreak;\t\t\t\n\t\t\tcase \"Left\":\n\t\t\t\tthis.colorsArray[48+0] =r;\n\t\t\t\tthis.colorsArray[48+1] =g;\n\t\t\t\tthis.colorsArray[48+2] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[48+3] =r;\n\t\t\t\tthis.colorsArray[48+4] =g;\n\t\t\t\tthis.colorsArray[48+5] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[48+6] =r;\n\t\t\t\tthis.colorsArray[48+7] =g;\n\t\t\t\tthis.colorsArray[48+8] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[48+9] =r;\n\t\t\t\tthis.colorsArray[48+10] =g;\n\t\t\t\tthis.colorsArray[48+11] =b;\n\t\t\tbreak;\t\t\t\t\n\t\t\tcase \"Right\":\n\t\t\t\tthis.colorsArray[60+0] =r;\n\t\t\t\tthis.colorsArray[60+1] =g;\n\t\t\t\tthis.colorsArray[60+2] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[60+3] =r;\n\t\t\t\tthis.colorsArray[60+4] =g;\n\t\t\t\tthis.colorsArray[60+5] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[60+6] =r;\n\t\t\t\tthis.colorsArray[60+7] =g;\n\t\t\t\tthis.colorsArray[60+8] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[60+9] =r;\n\t\t\t\tthis.colorsArray[60+10] =g;\n\t\t\t\tthis.colorsArray[60+11] =b;\n\t\t\tbreak;\t\n\t\t\tcase \"All\":\n\t\t\t\tthis.colorsArray = [\n\t\t\t\t\t// Front face\n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t\t// Back face\n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t\t// Top face \n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t\t// Bottom face : floor\n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t\t// Left face\n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t\t// Right face\n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t];\t\n\t\t\tbreak;\t\t\n\t\t}\n\t}",
"chatResultFace(faces) {\n let output = \"\";\n let src = \"\";\n let path = \"modules/ffg-roller/images/\";\n let imgTag = '<img src=\"fPath\" width=\"36\" height=\"36\"/>';\n //ability dice\n for (let i = 0; i < faces.abil.length; i++) {\n if (faces.abil[i] > 0) {\n switch (i) {\n case 0:\n src = path + \"Ability_Blank.png\";\n break;\n case 1:\n src = path + \"Ability_Success.png\";\n break;\n case 2:\n src = path + \"Ability_Success_2.png\";\n break;\n case 3:\n src = path + \"Ability_Advantage.png\";\n break;\n case 4:\n src = path + \"Ability_Advantage_2.png\";\n break;\n case 5:\n src = path + \"Ability_Combo.png\";\n break;\n default:\n break;\n }\n for (let j = faces.abil[i]; j > 0; j--) {\n output += imgTag.replace('fPath', src);\n }\n }\n }\n //proficiency dice\n for (let i = 0; i < faces.prof.length; i++) {\n if (faces.prof[i] > 0) {\n switch (i) {\n case 0:\n src = path + \"Proficiency_Blank.png\";\n break;\n case 1:\n src = path + \"Proficiency_Success.png\";\n break;\n case 2:\n src = path + \"Proficiency_Success_2.png\";\n break;\n case 3:\n src = path + \"Proficiency_Advantage.png\";\n break;\n case 4:\n src = path + \"Proficiency_Advantage_2.png\";\n break;\n case 5:\n src = path + \"Proficiency_Combo.png\";\n break;\n case 6:\n src = path + \"Proficiency_Triumph.png\";\n break;\n default:\n break;\n }\n for (let j = faces.prof[i]; j > 0; j--) {\n output += imgTag.replace('fPath', src);\n }\n }\n }\n //Boost dice\n for (let i = 0; i < faces.boost.length; i++) {\n if (faces.boost[i] > 0) {\n switch (i) {\n case 0:\n src = path + \"Boost_Blank.png\";\n break;\n case 1:\n src = path + \"Boost_Success.png\";\n break;\n case 2:\n src = path + \"Boost_Advantage.png\";\n break;\n case 3:\n src = path + \"Boost_Advantage_2.png\";\n break;\n case 4:\n src = path + \"Boost_Combo.png\";\n break;\n default:\n break;\n }\n for (let j = faces.boost[i]; j > 0; j--) {\n output += imgTag.replace('fPath', src);\n }\n }\n }\n //difficulty dice\n for (let i = 0; i < faces.diff.length; i++) {\n if (faces.diff[i] > 0) {\n switch (i) {\n case 0:\n src = path + \"Difficulty_Blank.png\";\n break;\n case 1:\n src = path + \"Difficulty_Fail.png\";\n break;\n case 2:\n src = path + \"Difficulty_Fail_2.png\";\n break;\n case 3:\n src = path + \"Difficulty_Threat.png\";\n break;\n case 4:\n src = path + \"Difficulty_Threat_2.png\";\n break;\n case 5:\n src = path + \"Difficulty_Combo.png\";\n break;\n default:\n break;\n }\n for (let j = faces.diff[i]; j > 0; j--) {\n output += imgTag.replace('fPath', src);\n }\n }\n }\n //Challenge dice\n for (let i = 0; i < faces.chal.length; i++) {\n if (faces.chal[i] > 0) {\n switch (i) {\n case 0:\n src = path + \"Challenge_Blank.png\";\n break;\n case 1:\n src = path + \"Challenge_Fail.png\";\n break;\n case 2:\n src = path + \"Challenge_Fail_2.png\";\n break;\n case 3:\n src = path + \"Challenge_Threat.png\";\n break;\n case 4:\n src = path + \"Challenge_Threat_2.png\";\n break;\n case 5:\n src = path + \"Challenge_Combo.png\";\n break;\n case 6:\n src = path + \"Challenge_Dispair.png\";\n break;\n default:\n break;\n }\n for (let j = faces.chal[i]; j > 0; j--) {\n output += imgTag.replace('fPath', src);\n }\n }\n }\n //Setback dice\n for (let i = 0; i < faces.setback.length; i++) {\n if (faces.setback[i] > 0) {\n switch (i) {\n case 0:\n src = path + \"Setback_Blank.png\";\n break;\n case 1:\n src = path + \"Setback_Fail.png\";\n break;\n case 2:\n src = path + \"Setback_Threat.png\";\n break;\n default:\n break;\n }\n for (let j = faces.setback[i]; j > 0; j--) {\n output += imgTag.replace('fPath', src);\n }\n }\n }\n //Force dice\n for (let i = 0; i < faces.force.length; i++) {\n if (faces.force[i] > 0) {\n switch (i) {\n case 0:\n src = path + \"Force_1B.png\";\n break;\n case 1:\n src = path + \"Force_2B.png\";\n break;\n case 2:\n src = path + \"Force_1W.png\";\n break;\n case 3:\n src = path + \"Force_2W.png\";\n break;\n default:\n break;\n }\n for (let j = faces.force[i]; j > 0; j--) {\n output += imgTag.replace('fPath', src);\n }\n }\n }\n return output;\n }",
"setEdgeRefsForFace (state, payload) {\n const { geometry_id, face_id, edgeRefs } = payload,\n geometry = state.find(g => g.id === geometry_id),\n face = geometry.faces.find(f => f.id === face_id);\n face.edgeRefs = edgeRefs.filter(ref => geometry.edges.find(e => e.id === ref.edge_id));\n }",
"saveRectangularFace() {\n this.clearHighlights();\n d3.selectAll('#grid .point-path').remove();\n\n // infer 4 corners of the rectangle based on the two points that have been drawn\n const payload = {};\n\n payload.points = [\n this.points[0],\n { x: this.points[1].x, y: this.points[0].y },\n this.points[1],\n { x: this.points[0].x, y: this.points[1].y },\n ];\n\n if (this.currentSpace) {\n payload.model_id = this.currentSpace.id;\n } else if (this.currentShading) {\n payload.model_id = this.currentShading.id;\n }\n this.$store.dispatch('geometry/createFaceFromPoints', payload);\n\n // clear points from the grid\n this.points = [];\n }",
"function getFacesFromLocations(img, rects, faceSize = 150) {\r\n const shapes = rects.map(rect => faceLandmarkPredictor.predict(img, rect))\r\n return fr.extractImageChips(img, fr.getFaceChipDetails(shapes, faceSize))\r\n }",
"function face() {\n noFill();\n stroke('white'); strokeWeight(10);\n var face = triangle(300, 100, 100, 500, 500, 500);\n var cheekl = ellipse(150, 400, 50, 10);\n var cheek2 = ellipse(450, 400, 50, 10);\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 }",
"personUpdateAPersonFacePatch(queryParams, headerParams, pathParams) {\n const queryParamsMapped = {};\n const headerParamsMapped = {};\n const pathParamsMapped = {};\n Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, PersonUpdateAPersonFacePatchQueryParametersNameMap));\n Object.assign(headerParamsMapped, convertParamsToRealParams(headerParams, PersonUpdateAPersonFacePatchHeaderParametersNameMap));\n Object.assign(pathParamsMapped, convertParamsToRealParams(pathParams, PersonUpdateAPersonFacePatchPathParametersNameMap));\n return this.makeRequest('/persongroups/{personGroupId}/persons/{personId}/persistedFaces/{persistedFaceId}', 'patch', queryParamsMapped, headerParamsMapped, pathParamsMapped);\n }",
"faceListGetAFaceListGet(queryParams, headerParams, pathParams) {\n const queryParamsMapped = {};\n const headerParamsMapped = {};\n const pathParamsMapped = {};\n Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, FaceListGetAFaceListGetQueryParametersNameMap));\n Object.assign(headerParamsMapped, convertParamsToRealParams(headerParams, FaceListGetAFaceListGetHeaderParametersNameMap));\n Object.assign(pathParamsMapped, convertParamsToRealParams(pathParams, FaceListGetAFaceListGetPathParametersNameMap));\n return this.makeRequest('/facelists/{faceListId}', 'get', queryParamsMapped, headerParamsMapped, pathParamsMapped);\n }",
"faceListDeleteAFaceListDelete(queryParams, headerParams, pathParams) {\n const queryParamsMapped = {};\n const headerParamsMapped = {};\n const pathParamsMapped = {};\n Object.assign(queryParamsMapped, convertParamsToRealParams(queryParams, FaceListDeleteAFaceListDeleteQueryParametersNameMap));\n Object.assign(headerParamsMapped, convertParamsToRealParams(headerParams, FaceListDeleteAFaceListDeleteHeaderParametersNameMap));\n Object.assign(pathParamsMapped, convertParamsToRealParams(pathParams, FaceListDeleteAFaceListDeletePathParametersNameMap));\n return this.makeRequest('/facelists/{faceListId}', 'delete', queryParamsMapped, headerParamsMapped, pathParamsMapped);\n }",
"equals(face) {\n\n // Throw an error if face is not a Face\n validate({ face }, 'Face');\n\n // Check that the faces equal the same value\n return (this.toString() === face.toString());\n }",
"computeFaces () {\n\n let vertexArr = this.vertexArr;\n\n let indexArr = this.indexArr;\n\n let len = indexArr.length;\n\n // Create the Edge and Face (triangle) arrays\n\n let faceArr = this.faceArr;\n\n // Loop through the indexArr, defining Edges and Faces, hashing back to Vertices.\n\n for ( let i = 0; i < len; i += 3 ) {\n\n const i0 = indexArr[ i ];\n\n const i1 = indexArr[ i + 1 ];\n\n const i2 = indexArr[ i + 2 ];\n\n const fi = i / 3;\n\n // Add 3 computed Edges to a Face, with Edges adding themselves to component Vertices\n\n let face = new Face(\n\n this.computeEdge( i0, i1, i2, fi ),\n\n this.computeEdge( i1, i2, i0, fi ),\n\n this.computeEdge( i2, i0, i1, fi ),\n\n fi\n\n );\n\n // NOTE TO SELF - computeEdge returns the index of the edge in the Edge array\n // Need to connect Face specifically to surrounds\n\n faceArr.push( face ); \n\n }\n\n }",
"singleCrease(origami, faceID, crease){\n let face = origami.getFaceByID(faceID);\n if (!face){\n // console.log('No such face to crease');\n return Crease.RESULT_INVALID_FACEID;\n }\n let edge = face.intersectEdge(crease, true);\n if (edge === null) {\n // console.log('No such crease');\n return Crease.RESULT_INVALID_CREASE;\n }\n\n // Assumed order\n let p1 = edge.p1;\n let p2 = edge.p2;\n let edge1Index = null;\n let edge2Index = null;\n let id = face.id; // Original id\n\n // Find the index of the two edges that the crease end points are on\n for (let i = 0; i < face.edges.length; i ++){\n if (face.edges[i].hasPoint(p1)){\n edge1Index = i;\n }\n if (face.edges[i].hasPoint(p2)){\n edge2Index = i;\n }\n }\n\n if (edge1Index === null || edge2Index === null){\n // NOTE: Maybe won't reach here\n // console.log('Crease Failed');\n return Crease.RESULT_FAILED_CREASE;\n }\n\n if (edge1Index > edge2Index){\n // Order not correct, flip\n p1 = edge.p2;\n p2 = edge.p1;\n let edgeTmpIndex = edge1Index; // Temp variable to save the index\n edge1Index = edge2Index;\n edge2Index = edgeTmpIndex;\n }\n\n // Helper function\n let addFixedEdge = (faceTmp, edgeTmp) => {\n // If invalid, don't add.\n if (!edgeTmp.isValid()) return;\n\n if (edgeTmp.isBoundary){\n // If just a boundary fix parent and add\n edgeTmp.parentFace1 = faceTmp;\n faceTmp.addEdge(edgeTmp);\n }\n if (edgeTmp.isCrease){\n // console.log('Crease', edgeTmp);\n // Fix the same crease on other face if exists\n let f = edgeTmp.parentFace2;\n let indexList = f.edgeIndexList(edgeTmp, true); // Use infinite length\n if (indexList.length > 0) {\n let index = indexList[0]; // Default to first match\n if (indexList.length > 1){\n // If more than one edge, should be able to find an exact one\n let hasExactMatch = false;\n for (let j = 0; j < indexList.length; j ++){\n if (f.edges[indexList[j]].isEqual(edgeTmp, true)){\n index = indexList[j];\n hasExactMatch = true;\n }\n }\n if (!hasExactMatch){\n console.log('Not sure which match to use');\n }\n }\n if (f.hasEdge(edgeTmp, true)){\n // Edge already exists on other face, not broken\n f.edges[index].parentFace2 = faceTmp;\n } else {\n // Create new edges for the other face\n let face = new Face(f.id);\n\n let k = 0;\n while (k < index){\n face.addEdge(f.edges[k]);\n k += 1;\n }\n\n let p; // The point not end point\n if (f.edges[k].isPointP1(edgeTmp.p1) || f.edges[k].isPointP2(edgeTmp.p1)){\n p = edgeTmp.p2.copy;\n } else {\n p = edgeTmp.p1.copy;\n }\n face.addEdge(new Edge(f.edges[k].p1.copy,p,f.edges[k].parentFace1,faceTmp));\n face.addEdge(new Edge(p,f.edges[k].p2.copy,f.edges[k].parentFace1,faceTmp));\n k += 1;\n while (k < f.edges.length){\n face.addEdge(f.edges[k]);\n k += 1;\n }\n\n f.edges = face.edges;\n }\n // parentFace1 will always be the one that need fix\n // A face's crease will always has itself as the first parent\n edgeTmp.parentFace1 = faceTmp;\n faceTmp.addEdge(edgeTmp);\n }\n }\n }\n\n // Make face 1\n let face1 = new Face(id); // face 1 use original id\n face1.layer = face.layer;\n let i = 0;\n while(i < edge1Index){\n addFixedEdge(face1, face.edges[i]);\n i ++;\n }\n // Add p1 to x1y1 edge\n addFixedEdge(face1, new Edge(face.edges[i].p1.copy,p1.copy,face.edges[i].parentFace1,face.edges[i].parentFace2));\n i ++;\n // Add x1y1 to x2y2 edge\n let newCrease1 = new Edge(p1.copy,p2.copy,face1); // Should fix the parent later in this function\n face1.addEdge(newCrease1);\n i = edge2Index;\n addFixedEdge(face1, new Edge(p2.copy,face.edges[i].p2.copy,face.edges[i].parentFace1,face.edges[i].parentFace2));\n i ++;\n while(i<face.edges.length){\n addFixedEdge(face1, face.edges[i]);\n i ++;\n }\n // Make face 2\n let face2 = new Face(origami.faces.length+1); // face 2 increment id\n face2.layer = face.layer;\n i = edge1Index;\n // Add x1y1 to p2 edge\n addFixedEdge(face2, new Edge(p1.copy,face.edges[i].p2.copy,face.edges[i].parentFace1,face.edges[i].parentFace2));\n i ++;\n while(i !== edge2Index){\n // Add edge until edge2 is found\n addFixedEdge(face2, face.edges[i]);\n i ++;\n }\n // Add p1 to x2y2 edge\n addFixedEdge(face2, new Edge(face.edges[i].p1.copy,p2.copy,face.edges[i].parentFace1,face.edges[i].parentFace2));\n i ++;\n // Add x2y2 to x1y1 edge\n newCrease1.parentFace2 = face2; // Fix previous one here\n let newCrease2 = new Edge(p2.copy,p1.copy,face2,face1);\n face2.addEdge(newCrease2);\n\n // console.log(face1);\n // console.log(face2);\n\n origami.faces.splice(origami.faces.indexOf(face), 1, face1); // Replace original face\n origami.faces.push(face2);\n\n origami.sortFaces();\n return Crease.RESULT_SUCCESSFUL;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
handler for when thumbnailsBox is resized | _thumbnailsBoxResized() {
this._updateSize();
this._redisplay();
} | [
"function resizedw(){\n loadSlider(slider);\n }",
"function resizeHandler() {\n\tvar contentHeight = $('.content').height(),\n\t\tboxHeight = $('.info_box').height(),\n\t\tpageData = CLUB.pageData,\n\t\tpageSize = Math.floor(contentHeight/(boxHeight + 15));\n\tif(pageData.pageSize !== pageSize) {\n\t\tpageData.pageSize = pageSize;\n\t\tsetPageNumber();\n\t}\n}",
"_handleResize(e) {\n this.resizeToolbar();\n }",
"function popupPVAsWindow_onresize(e)\n{\n}",
"function __resizeHandler__() {\n\t\tvar topMostDlg = __findTopMostDialog__();\n\t\t\n\t\tdoSizing();\n\t\t\n\t\tif (topMostDlg) {\n\t\t\tdoPositioning(topMostDlg);\n\t\t}\n\t}",
"function addResizeListener() {\n document.getElementById('large-btn').addEventListener('click', function(event){\n changeSize('large');\n });\n document.getElementById('normal-btn').addEventListener('click', function(event){\n changeSize('normal');\n });\n document.getElementById('small-btn').addEventListener('click', function(event){\n changeSize('small');\n });\n}",
"handleResize() {\n // if we don't have a spreader, let it come around again\n if (!this.refs.spreader) { return; }\n\n const availableWidth = ReactDOM.findDOMNode(this.refs.spreader).offsetWidth;\n this._targetHeight = ReactDOM.findDOMNode(this.refs.sizer).offsetHeight;\n\n // set the max height right away, so that the resize throttle doesn't allow line break jumps\n this.setState({ fixHeight: this._targetHeight });\n\n // was there a width change?\n if (availableWidth !== this.state.lastCalculatedWidth) {\n // first render?\n if (this.state.children === '' || availableWidth < this.state.lastCalculatedWidth) {\n this._adjustDown();\n } else {\n this._adjustUp();\n }\n }\n }",
"function setThumbnailContainerSize(thumbnailContainer){\n \n // If parent is more than 3 200px thumbnails, set width of thumbnail container as interval of 200px + 5px padding\n \n if($(thumbnailContainer).parent().width() > 630){\n \n $(thumbnailContainer).width($(thumbnailContainer).parent().width() - ($(thumbnailContainer).parent().width()) % 210);\n \n }\n \n // Otherwise, if parent is less than 3 100px thumbnails, set width of thumbnail container as interval of 100px + 5px padding\n \n else if($(thumbnailContainer).parent().width() < 330){\n \n $(thumbnailContainer).width($(thumbnailContainer).parent().width() - ($(thumbnailContainer).parent().width()) % 110);\n \n }\n \n // Otherwise, set width to 100%\n \n else{\n \n $(thumbnailContainer).css('width', '100%');\n \n }\n \n // Set height of thumbnails to equal its width\n \n $(thumbnailContainer).find('.thumbnail').each(function(){\n \n let height = $(this).height();\n let width = $(this).width();\n \n if(height != width){\n \n $(this).height(width);\n centerImage(this);\n \n }\n \n });\n \n}",
"function onTrackEventResizedLeft( trackEvent, x, w, resizeEvent ) {\n if ( x <= min ) {\n resizeEvent.blockIteration( min );\n }\n }",
"function initSizeParamsHor(){\n\t\t\n\t\tvar arrThumbs = g_objInner.children(\".ug-thumb-wrapper\");\n\t\tvar firstThumb = jQuery(arrThumbs[0]);\n\t\tvar thumbsRealHeight = firstThumb.outerHeight();\n\n\t\t//set grid size\n\t\tvar gridWidth = g_temp.gridWidth;\n\t\tvar gridHeight = g_options.grid_num_rows * thumbsRealHeight + (g_options.grid_num_rows-1) * g_options.grid_space_between_rows;\n\t\t\n\t\tg_temp.gridHeight = gridHeight;\n\t\t\n\t\tg_functions.setElementSize(g_objGrid, gridWidth, gridHeight);\n\t\n\t\t//set inner size (as grid size, will be corrected after placing thumbs\n\t\tg_functions.setElementSize(g_objInner, gridWidth, gridHeight);\n\t\t\n\t\t//set initial inner size params\n\t\tg_temp.innerWidth = gridWidth;\n\t\tg_temp.innerHeight = gridHeight;\n\t}",
"function cffResizeAlbum(){\r\n\t\tvar cffAlbumWidth = $('.cff-album-item').eq(0).find('a').innerWidth();\r\n\t\t$('.cff-album-item a').css('height', cffAlbumWidth);\r\n\t}",
"function initSizeParams(){\n\t\t\n\t\t//set thumb outer size:\n\t\tvar arrThumbs = g_objStripInner.children(\".ug-thumb-wrapper\");\n\t\tvar firstThumb = jQuery(arrThumbs[0]);\n\t\tvar thumbsRealWidth = firstThumb.outerWidth();\n\t\tvar thumbsRealHeight = firstThumb.outerHeight();\n\t\t\n\t\tif(g_isVertical == false){\t\t\t//horizontal\n\t\t\tg_sizes.thumbSize = thumbsRealWidth;\n\t\t\tg_sizes.thumbSecondSize = thumbsRealHeight;\n\t\t\tg_sizes.stripSize = g_objStrip.width();\n\t\t\tg_sizes.stripInnerSize = g_objStripInner.width();\n\t\t}else{\t\t//vertical\n\t\t\tg_sizes.thumbSize = thumbsRealHeight;\n\t\t\tg_sizes.thumbSecondSize = thumbsRealWidth;\n\t\t\tg_sizes.stripSize = g_objStrip.height();;\n\t\t\tg_sizes.stripInnerSize = g_objStripInner.height();\t\t\t\n\t\t}\n\t\t\n\t}",
"function listenWindowResize() {\n $(window).resize(_handleResize);\n }",
"function ResizeHandler() {\n setMaxWindowWidth((window.innerWidth - 800) / 2);\n setMaxWindowHeight((window.innerHeight - 700) / 2);\n }",
"function changeGridSize() {\n value = sizeSlider.value;\n container.innerHTML = \"\";\n makeRows(value, value);\n displayGridSlider.innerHTML = value.toString() + \"x\" + value.toString();\n}",
"function findMousePositionAndResizeImages(){\n $('.activeImg').css(dataService.getImageCss());\n $('#measureEnlarge').mousemove(function(event){\n enlargeOrShrinkImages(event);\n });\n $('#measureShrink').mousemove(function(event){\n enlargeOrShrinkImages(event);\n });\n}",
"function handleMouseUp() {\n isResizing = false;\n}",
"function _resized() {\n\t\t\t\t_winHeight = $window.innerHeight + 'px';\n\n\t\t\t\tif (loading.active) {\n\t\t\t\t\t_$body.css({\n\t\t\t\t\t\theight: _winHeight,\n\t\t\t\t\t\toverflowY: 'hidden'\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}",
"_setupResizerCreator() {\n\t\tconst editor = this.editor;\n\t\tconst editingView = editor.editing.view;\n\n\t\teditingView.addObserver( ImageLoadObserver );\n\n\t\tthis.listenTo( editingView.document, 'imageLoaded', ( evt, domEvent ) => {\n\t\t\t// The resizer must be attached only to images loaded by the `ImageInsert`, `ImageUpload` or `LinkImage` plugins.\n\t\t\tif ( !domEvent.target.matches( RESIZABLE_IMAGES_CSS_SELECTOR ) ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst domConverter = editor.editing.view.domConverter;\n\t\t\tconst imageView = domConverter.domToView( domEvent.target );\n\t\t\tconst widgetView = imageView.findAncestor( { classes: IMAGE_WIDGETS_CLASSES_MATCH_REGEXP } );\n\t\t\tlet resizer = this.editor.plugins.get( WidgetResize ).getResizerByViewElement( widgetView );\n\n\t\t\tif ( resizer ) {\n\t\t\t\t// There are rare cases when the image will be triggered multiple times for the same widget, e.g. when\n\t\t\t\t// the image's source was changed after upload (https://github.com/ckeditor/ckeditor5/pull/8108#issuecomment-708302992).\n\t\t\t\tresizer.redraw();\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst mapper = editor.editing.mapper;\n\t\t\tconst imageModel = mapper.toModelElement( widgetView );\n\n\t\t\tresizer = editor.plugins\n\t\t\t\t.get( WidgetResize )\n\t\t\t\t.attachTo( {\n\t\t\t\t\tunit: editor.config.get( 'image.resizeUnit' ),\n\n\t\t\t\t\tmodelElement: imageModel,\n\t\t\t\t\tviewElement: widgetView,\n\t\t\t\t\teditor,\n\n\t\t\t\t\tgetHandleHost( domWidgetElement ) {\n\t\t\t\t\t\treturn domWidgetElement.querySelector( 'img' );\n\t\t\t\t\t},\n\t\t\t\t\tgetResizeHost() {\n\t\t\t\t\t\t// Return the model image element parent to avoid setting an inline element (<a>/<span>) as a resize host.\n\t\t\t\t\t\treturn domConverter.viewToDom( mapper.toViewElement( imageModel.parent ) );\n\t\t\t\t\t},\n\t\t\t\t\t// TODO consider other positions.\n\t\t\t\t\tisCentered() {\n\t\t\t\t\t\tconst imageStyle = imageModel.getAttribute( 'imageStyle' );\n\n\t\t\t\t\t\treturn !imageStyle || imageStyle == 'block' || imageStyle == 'alignCenter';\n\t\t\t\t\t},\n\n\t\t\t\t\tonCommit( newValue ) {\n\t\t\t\t\t\t// Get rid of the CSS class in case the command execution that follows is unsuccessful\n\t\t\t\t\t\t// (e.g. Track Changes can override it and the new dimensions will not apply). Otherwise,\n\t\t\t\t\t\t// the presence of the class and the absence of the width style will cause it to take 100%\n\t\t\t\t\t\t// of the horizontal space.\n\t\t\t\t\t\teditingView.change( writer => {\n\t\t\t\t\t\t\twriter.removeClass( RESIZED_IMAGE_CLASS, widgetView );\n\t\t\t\t\t\t} );\n\n\t\t\t\t\t\teditor.execute( 'resizeImage', { width: newValue } );\n\t\t\t\t\t}\n\t\t\t\t} );\n\n\t\t\tresizer.on( 'updateSize', () => {\n\t\t\t\tif ( !widgetView.hasClass( RESIZED_IMAGE_CLASS ) ) {\n\t\t\t\t\teditingView.change( writer => {\n\t\t\t\t\t\twriter.addClass( RESIZED_IMAGE_CLASS, widgetView );\n\t\t\t\t\t} );\n\t\t\t\t}\n\t\t\t} );\n\n\t\t\tresizer.bind( 'isEnabled' ).to( this );\n\t\t} );\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates an AWS/ACMPrivateCA metric with the requested [metricName]. See for list of all metricnames. Note, individual metrics can easily be obtained without supplying the name using the other [metricXXX] functions. | function metric(metricName, change = {}) {
return new cloudwatch.Metric(Object.assign({ namespace: "AWS/ACMPrivateCA", name: metricName }, change));
} | [
"function metric(metricName, change = {}) {\n const dimensions = {};\n if (change.fileSystem !== undefined) {\n dimensions.FileSystemId = change.fileSystem.id;\n }\n return new cloudwatch.Metric(Object.assign({ namespace: \"AWS/EFS\", name: metricName }, change)).withDimensions(dimensions);\n }",
"function metric(metricName, change = {}) {\n const dimensions = {};\n if (change.queue !== undefined) {\n dimensions.QueueName = change.queue.name;\n }\n return new cloudwatch.Metric(Object.assign({ namespace: \"AWS/SQS\", name: metricName }, change)).withDimensions(dimensions);\n }",
"function metric_fetch_gen(cw, queue_name, metric_name) {\n var f = function(callback) {\n //console.log(\"fetching \" + metric_name + \" for queue \" + queue_name)\n var end = new Date();\n // fetch the last 30 minutes of data, but return the most recent data point\n var start = new Date(end.getTime() - 60 * 30 * 1000);\n var params = {\n EndTime: end,\n MetricName: metric_name, /* required */\n Namespace: 'AWS/SQS', /* required */\n Period: 60, /* required */\n StartTime: start,\n Dimensions: [{\n Name: 'QueueName', /* required */\n Value: queue_name /* required */\n }],\n Statistics: [ \"Sum\" ],\n };\n cw.getMetricStatistics(params, function(err, data) {\n if (err) {\n console.log(err, err.stack); // an error occurred\n callback(err, null);\n return;\n }\n var metric_data = 0;\n if (data['Datapoints'].length != 0) {\n var newest = null;\n for (var i in data['Datapoints']) {\n if (newest == null)\n newest = data['Datapoints'][i];\n else if (data['Datapoints'][i]['Timestamp'] > newest['Timestamp'])\n newest = data['Datapoints'][i];\n }\n metric_data = newest['Sum'];\n }\n result = {\n 'queue_name': queue_name,\n 'metric_name' : metric_name,\n 'data' : metric_data\n };\n callback(err, result);\n });\n }\n return f;\n}",
"function main(projectId) {\n // [START monitoring_create_metric]\n // Imports the Google Cloud client library\n const monitoring = require('@google-cloud/monitoring');\n\n // Creates a client\n const client = new monitoring.MetricServiceClient();\n\n /**\n * TODO(developer): Uncomment and edit the following lines of code.\n */\n // const projectId = 'YOUR_PROJECT_ID';\n async function createMetricDescriptor() {\n const request = {\n name: client.projectPath(projectId),\n metricDescriptor: {\n description: 'Daily sales records from all branch stores.',\n displayName: 'Daily Sales',\n type: 'custom.googleapis.com/stores/daily_sales',\n metricKind: 'GAUGE',\n valueType: 'DOUBLE',\n unit: '{USD}',\n labels: [\n {\n key: 'store_id',\n valueType: 'STRING',\n description: 'The ID of the store.',\n },\n ],\n },\n };\n\n // Creates a custom metric descriptor\n const [descriptor] = await client.createMetricDescriptor(request);\n console.log('Created custom Metric:\\n');\n console.log(`Name: ${descriptor.displayName}`);\n console.log(`Description: ${descriptor.description}`);\n console.log(`Type: ${descriptor.type}`);\n console.log(`Kind: ${descriptor.metricKind}`);\n console.log(`Value Type: ${descriptor.valueType}`);\n console.log(`Unit: ${descriptor.unit}`);\n console.log('Labels:');\n descriptor.labels.forEach(label => {\n console.log(` ${label.key} (${label.valueType}) - ${label.description}`);\n });\n }\n createMetricDescriptor();\n // [END monitoring_create_metric]\n}",
"function Metric() {\n var _a;\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n this.category = null;\n this.metric = null;\n this.value = null;\n var length = args.length;\n if (length > 0 && args[0] instanceof Metric) {\n _a = args[0].toArray(), this.metric = _a[0], this.category = _a[1], this.value = _a[2];\n return;\n }\n switch (length) {\n case 1:\n this.metric = args[0];\n break;\n case 2:\n if (typeof args[0] === 'string' && typeof args[1] === 'string') {\n this.category = args[0], this.metric = args[1];\n }\n else {\n this.metric = args[0], this.value = args[1];\n }\n break;\n case 3:\n this.category = args[0], this.metric = args[1], this.value = args[2];\n break;\n default:\n break;\n }\n if (this.value && this.value instanceof Date) {\n this.value = this.value.getTime();\n }\n }",
"function named(name) {\n return new CronJob({ metadata: { name } });\n }",
"function create(accessKeyId, secretAccessKey) {\n config.accessKeyId = accessKeyId;\n config.secretAccessKey = secretAccessKey;\n\n AWS.config.update(config);\n AWS.config.region = window.AWS_EC2_REGION;\n AWS.config.apiVersions = {\n cloudwatch: '2010-08-01',\n sqs: '2012-11-05'\n };\n\n cloudWatch = new AWS.CloudWatch();\n autoScaling = new AWS.AutoScaling();\n sqs = new AWS.SQS();\n }",
"function init(metric_impl) {\n metric = metric_impl;\n}",
"static kmcCollect(kmcEvent){\n\t\tlet kparams = {};\n\t\tkparams.kmcEvent = kmcEvent;\n\t\treturn new kaltura.RequestBuilder('stats', 'kmcCollect', kparams);\n\t}",
"function createFilteredMetricOID(metricOid, filterOid) {\n return \"(\" + metricOid + \"@\" + filterOid + \")\";\n }",
"function Metric(name, projectName, title, minScore, maxScore, less, more) {\n this.score = new Array();\n // Json that is used to send data to parent\n this.metricJSON = {\n // JSON strings are supposed to use \", instead '\n // Wrapping the property names in double quotation marks in JSON\n // is mandatory. Furthermore, all strings should be double quoted as follows:\n \"metric\": \"\",\n \"score\": \"\",\n \"comment\": \"\",\n \"created_at\": \"\"\n }; //metricJSON\n this.name = name || 'nps';\n this.projectName = projectName || 'this app';\n switch (this.name.toUpperCase()) {\n case 'NPS':\n this.name = 'nps';\n this.title = 'How likely are you to recommend ' + this.projectName + ' to a friend or co-worker';\n this.score = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n this.less = 'Not at all likely';\n this.more = 'Extremely likely';\n break;\n case 'CES':\n this.name = 'ces';\n this.title = 'How easy was it for you to complete this task or action?';\n this.score = [1, 2, 3, 4, 5, 6, 7];\n this.less = 'Very difficult';\n this.more = 'Very easy';\n break;\n case 'CSAT':\n this.name = 'csat';\n this.title = 'How satisfied are you with ' + this.projectName + '?';\n this.score = [1, 2, 3, 4, 5];\n this.less = 'Very unsatisfied';\n this.more = 'Very satisfied';\n break;\n default:\n this.name = name;\n this.title = title;\n for (; minScore <= maxScore; minScore++) {\n this.score.push(minScore);\n } //for\n this.less = less;\n this.more = more;\n break;\n } //switch\n this.metricJSON.metric = this.name;\n } //constructor",
"function Certificate(props) {\n return __assign({ Type: 'AWS::CertificateManager::Certificate' }, props);\n }",
"function createCourse(name)\r\n{\r\n //Determine the unique ID for the new course\r\n var maxID = 0;\r\n for(course in courses)\r\n {\r\n if(maxID < courses[course].id)\r\n maxID = courses[course].id;\r\n }\r\n //Create the course and add it to the database\r\n var newCourse = new Course(maxID + 1, name, false);\r\n courses.push(newCourse);\r\n}",
"_addK8sAttributes(attributes, clusterName) {\n attributes[resources_1.K8S_RESOURCE.CLUSTER_NAME] = clusterName;\n attributes[resources_1.K8S_RESOURCE.NAMESPACE_NAME] = process.env.NAMESPACE || '';\n attributes[resources_1.K8S_RESOURCE.POD_NAME] = process.env.HOSTNAME || os.hostname();\n attributes[resources_1.CONTAINER_RESOURCE.NAME] = process.env.CONTAINER_NAME || '';\n }",
"function createIssueLabel(labelName , projName){\n return {\n labelName : labelName,\n projname : projName\n }\n}",
"constructor(scope, id, props) {\n super(scope, id, { type: CfnAccessPoint.CFN_RESOURCE_TYPE_NAME, properties: props });\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_aws_s3_CfnAccessPointProps(props);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, CfnAccessPoint);\n }\n throw error;\n }\n cdk.requireProperty(props, 'bucket', this);\n this.attrAlias = cdk.Token.asString(this.getAtt('Alias', cdk.ResolutionTypeHint.STRING));\n this.attrArn = cdk.Token.asString(this.getAtt('Arn', cdk.ResolutionTypeHint.STRING));\n this.attrName = cdk.Token.asString(this.getAtt('Name', cdk.ResolutionTypeHint.STRING));\n this.attrNetworkOrigin = cdk.Token.asString(this.getAtt('NetworkOrigin', cdk.ResolutionTypeHint.STRING));\n this.bucket = props.bucket;\n this.bucketAccountId = props.bucketAccountId;\n this.name = props.name;\n this.policy = props.policy;\n this.policyStatus = props.policyStatus;\n this.publicAccessBlockConfiguration = props.publicAccessBlockConfiguration;\n this.vpcConfiguration = props.vpcConfiguration;\n }",
"createNodeGroup(name, args) {\n const awsProvider = this.core.awsProvider ? { aws: this.core.awsProvider } : undefined;\n return new nodegroup_1.NodeGroup(name, Object.assign(Object.assign({}, args), { cluster: this.core, nodeSecurityGroup: this.core.nodeGroupOptions.nodeSecurityGroup, clusterIngressRule: this.core.nodeGroupOptions.clusterIngressRule }), {\n parent: this,\n providers: Object.assign(Object.assign({}, awsProvider), { kubernetes: this.provider }),\n });\n }",
"function put(value, op, cb) {\n\n if (typeof value !== 'number') {\n // TODO throw error\n }\n\n var ts\n op = op || {}\n\n if (typeof op === 'function') {\n cb = op\n op = {}\n ts = ISODateString(new Date())\n } else if (typeof op === 'string') {\n // I assume you have given me an ISO 8601 timestamp\n ts = op\n op = {}\n } else if (isDate(op)) {\n ts = ISODateString(ts)\n } else {\n ts = ISODateString(new Date())\n }\n\n var metric = {\n namespace : namespace\n , name : name\n , value : value\n , unit : op.unit || _metric.unit\n , dimensions : op.dimensions || _metric.dimensions}\n\n // TODO return request stream? vs metric obj?\n if (typeof cb === 'function') {\n transport(host\n , protocol\n , putMetricData(awskey\n , secret\n , host\n , namespace\n , ts\n , metric)\n , cb)\n }\n\n return metric\n }",
"async function newCachedEnforcer(...params) {\n return enforcer_1.newEnforcerWithClass(CachedEnforcer, ...params);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shows all answers for a cloze field 'inputs' is an option argument containing a list of the 'input' elements for the field | function fillClozeInputs(ident, inputs) {
if (!inputs) {
var inputs = getCloseInputs(ident)
}
for (var i=0; i<inputs.length; i++) {
input = inputs[i];
input.value = getClozeAnswer(input);
markClozeWord(input, CORRECT);
// Toggle the readonlyness of the answers also
input.setAttribute('readonly', 'readonly');
}
} | [
"function allInputs () {\n let inputs = _.select(ractive.get('inputs'), function (input) {\n return (input.fragment === 'publicationOf' || input.fragment === 'recordId')\n })\n\n const addInput = function (input, groupIndex, inputIndex, subInputIndex) {\n inputs.push(input)\n const subInputPart = subInputIndex !== undefined ? `.subInputs.${subInputIndex}.input` : ''\n const forms = ractive.get(`applicationData.inputGroups.${groupIndex}.inputs.${inputIndex}${subInputPart}.widgetOptions.enableEditResource.forms`)\n if (forms) {\n _.each(forms, function (form) {\n inputs = inputs.concat(form.inputs)\n })\n }\n }\n\n forAllGroupInputs(addInput)\n\n _.each(ractive.get('applicationData.maintenanceInputs'), function (input, index) {\n inputs.push(input)\n const forms = (ractive.get(`applicationData.maintenanceInputs.${index}.widgetOptions.enableEditResource.forms`))\n if (forms) {\n _.each(forms, function (form) {\n inputs = inputs.concat(form.inputs)\n })\n }\n })\n return inputs\n }",
"renderInputs() {\n const template = this.querySelector('template');\n // Create fragment to only modify the main DOM tree once\n const fragment = document.createDocumentFragment();\n // We must use firstElementChild as we're adding a click handler later, which will\n // not work on DocumentFragments, see\n // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template\n this.inputs.forEach((inputConfig) => {\n // IE11 and its polyfill have issues with template.content (it is empty); use fallback\n // for IE11 by cloning the template itself, not its content.\n const clone = template.content ?\n template.content.firstElementChild.cloneNode(true) :\n template.cloneNode(true).firstElementChild;\n const cloneInput = clone.querySelector('[data-input]');\n const cloneLabel = clone.querySelector('[data-label]');\n\n this.copyLabel(inputConfig.label, cloneLabel);\n this.copySelectOptions(inputConfig.input, cloneInput);\n this.copySelectOptionLabel(inputConfig.input, cloneLabel);\n this.syncInput(inputConfig.input, cloneInput);\n this.copyPlaceholder(inputConfig.input, cloneInput);\n this.copyDisabled(inputConfig.input, cloneInput);\n this.connectLabelToInput(cloneLabel, cloneInput);\n\n fragment.appendChild(clone);\n });\n\n // Append elements after template; template must therefore be placed at the\n // place where content will be inserted\n requestAnimationFrame(() => {\n template.parentNode.appendChild(fragment);\n });\n\n }",
"function inputAnswer(text, answers) {\n\t\t\n\t\t// detect for multiple choice questions\n\t\tif (answers != null) {\n\t\t\t\n\t\t\t// detect if question has no answers\n\t\t\tif (answers.length == 0) {\n\t\t return \"This question has no answers yet\";\n\t\t } else {\n\t\t\t\tfor (var ans in answers) {\n\t\t\t\t\tanswers[ans]['text']\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t// for each answer of the multiple choice question\n\t\t\tfor (var ans in data['answers'][question][1]) {\n\t\t\t\t$('.questions').append('<b> ' + data['answers'][question][1][ans]['text'] + '</b><br />');\n\t\t\t}\n\t\t} else {\n\t\t\t$('.questions').append('<input type=\\'text\\' name=\\'' + question + '\\' /><br />');\t\t\n\t\t}\n\t\t\n\t\n\t}",
"function prefillExamples() {\n $(\"#cfg-example-input\").val(examples_.join('\\n'));\n}",
"function getOptInputs() {\n\tconsole.log(\"getting optional inputs\");\n\tvar tempField = document.getElementById('temp');\n\tvar densField = document.getElementById('dens');\n\tvar pressField = document.getElementById('press');\n\tvar tempVal = replaceNaNwithZero( tempField.value );\n\tvar densVal = replaceNaNwithZero( densField.value );\n\tvar pressVal = replaceNaNwithZero( pressField.value );\n\treturn [tempVal, densVal, pressVal];\n}",
"function getInputFieldsHtml(template_name)\n{\n //variables which change depending on the input type\n var num_input_index=0;\n var str_dynamic_index=0;\n var data = \"\";\n var cls = \"\";\n var input_type=\"\";\n var fieldName=\"\";\n\n var html=\"<div class='\"+template_name+\"-input'>\";\n var endDiv =\"</div>\";\n\n var template = getTemplateByID(template_name);\n var fieldID = template.id;\n\n //loop through all fields for each input type\n\n for(var i=0; i<template.str_fields.length; i++)\n {\n data=\"\";\n cls=\"\";\n input_type=\"\";\n fieldName = template.str_fields[i];\n\n html += wrapInputFieldHtml(fieldID, template_name, input_type, data, cls, fieldName);\n }\n\n for(var i=0; i<template.num_fields.length; i++)\n {\n input_type = \"-number\";\n num_input_index+=1;\n data = 'data-index=\"'+num_input_index+'\" ';\n cls=\" \"+fieldID+\"-input-field \";\n fieldName = template.num_fields[i];\n\n html += wrapInputFieldHtml(fieldID, template_name, input_type, data, cls, fieldName);\n }\n\n for(var i=0; i<template.img_fields.length; i++)\n {\n input_type=\"-img\";\n data=\"\";\n cls=\"\";\n fieldName = template.img_fields[i];\n\n html += wrapInputFieldHtml(fieldID, template_name, input_type, data, cls, fieldName);\n }\n\n for(var i=0; i<template.hero_icon.length; i++)\n {\n input_type=\"-hero\";\n data = 'data-folder=\"hero-icons\" ';\n cls=\"\";\n fieldName = template.hero_icon[i];\n\n html += wrapInputFieldHtml(fieldID, template_name, input_type, data, cls, fieldName);\n }\n\n for(var i=0; i<template.hero_portrait.length; i++)\n {\n input_type=\"-hero\";\n data = 'data-folder=\"hero-portraits\" ';\n cls=\"\";\n fieldName = template.hero_portrait[i];\n\n html += wrapInputFieldHtml(fieldID, template_name, input_type, data, cls, fieldName);\n }\n\n for(var i=0; i<template.str_dynamic.length; i++)\n {\n data = 'data-index=\"'+str_dynamic_index+'\" ';\n cls=\"-dynamic-str\";\n input_type=\"\";\n fieldName = template.str_dynamic[i];\n str_dynamic_index+=1;\n html += wrapInputFieldHtml(fieldID, template_name, input_type, data, cls, fieldName);\n }\n\n for(var i=0; i<template.team.length; i++)\n {\n data=\"\";\n cls=\"\";\n fieldName = template.team[i];\n input_type=\"-team\";\n\n html += wrapInputFieldHtml(fieldID, template_name, input_type, data, cls, fieldName);\n }\n\n return html + endDiv;\n}",
"function displayAll() {\r\n displayInput();\r\n displayOutput();\r\n}",
"function setupInputInteraction(interaction) {\n let qtiInteraction = QTI.DOM.getElementById(interaction.id);\n let responseVariable = getResponseVariable(interaction);\n\n switch(interaction.tagName) {\n case \"SELECT\":\n interaction.onchange=handleResponse;\n break;\n case \"BUTTON\":\n interaction.onclick=handleResponse;\n break;\n default:\n let inputs = [...interaction.querySelectorAll(\"input\")]\n .concat([...interaction.querySelectorAll(\"textarea\")]);\n inputs.forEach(input=>input.onchange=handleResponse);\n break;\n }\n\n // Called after templateProcessing, just before presentation.\n interaction.init = initInteraction;\n \n // Handler for change and click events.\n function handleResponse(evt) {\n const input = evt.currentTarget;\n\n evt.stopPropagation();\n\n if (input.tagName==\"BUTTON\" \n || input.tagName==\"SELECT\"\n || input.tagName==\"TEXTAREA\") {\n setInputResponseVariable(input);\n } else {\n if (input.checked) {\n switch(qtiInteraction.tagName) {\n case \"matchInteraction\":\n if (!validateMatchMax(input)) {\n input.checked = false;\n return;\n }\n break;\n case \"choiceInteraction\":\n case \"hottextInteraction\":\n if (!validateMaxChoices(input)) {\n input.checked = false;\n return;\n }\n break;\n default:\n break;\n }\n }\n [...interaction.querySelectorAll(\"input\")]\n .forEach(input=>setInputResponseVariable(input));\n }\n }\n\n function validateMatchMax(input) {\n let ids = input.getAttribute(ID).split(\" \");\n return !(atMatchMax(ids[0]) || atMatchMax(ids[1]));\n }\n\n function atMatchMax(id) {\n let choice = qtiInteraction.querySelector(`[identifier=${id}]`);\n let matchMax = choice.getAttribute(\"matchMax\");\n\n if (matchMax > 0) {\n let matchCount = responseVariable.value.filter(v=>{\n let ids = v.split(\" \");\n return ids[0]==id || ids[1]==id;\n }).length;\n return matchCount>=matchMax;\n } else {\n return false;\n }\n }\n\n function validateMaxChoices(input) {\n let maxChoices = qtiInteraction.getAttribute(\"maxChoices\")||1;\n return maxChoices<=1\n || !responseVariable.value\n || responseVariable.value.length<maxChoices; \n }\n \n // Inits interactions after templateProcessing and before\n // first attempt on interaction.\n function initInteraction() {\n let decl = responseVariable;\n if (decl.defaultValue) {\n decl.value = coerce(decl, decl.defaultValue);\n let sel = \"input, textarea, select, button\";\n [...interaction.querySelectorAll(sel)].forEach(input=>{\n switch(input.tagName){\n case \"INPUT\":\n switch(input.getAttribute(\"type\")){\n case \"radio\":\n case \"checkbox\":\n // choiceInteraction, hottextInteraction, matchInteraction\n input.checked = decl.value.includes(input.getAttribute(ID));\n break;\n case \"text\":\n // textEntryInteraction\n value = decl.value;\n break;\n case \"range\":\n // sliderInteraction\n value = decl.value;\n break;\n case \"file\":\n // uploadInteraction\n break;\n }\n case \"TEXTAREA\":\n // extendedTextInteraction\n value = decl.value;\n break;\n case \"SELECT\":\n // inlineChoiceInteraction\n break;\n case \"BUTTON\":\n break;\n }\n });\n }\n }\n\n // Sets response variable after the user does input.\n function setInputResponseVariable(input) {\n let value;\n switch(input.tagName) {\n case \"INPUT\":\n switch(input.getAttribute(\"type\")) {\n case \"radio\":\n case \"checkbox\":\n // choiceInteraction, hottextInteraction, matchInteraction\n value = check(input.getAttribute(ID), input.checked);\n break;\n case \"text\":\n // textEntryInteraction\n if (input.value.length)\n input.style.width = input.value.length+\"ch\";\n value = input.value;\n break;\n case \"range\":\n // sliderInteraction\n value = input.value;\n break;\n case \"file\":\n // uploadInteraction\n value = input.files[0].name;\n break;\n }\n break;\n case \"TEXTAREA\":\n // extendedTextInteraction\n value = input.value;\n break;\n case \"SELECT\":\n // inlineChoiceInteraction\n value = input.options[input.selectedIndex].getAttribute(ID);\n break;\n case \"BUTTON\":\n // endAttemptInteraction\n value = true;\n break;\n default:\n break;\n }\n postResponseVariable(interaction, value);\n }\n\n // Adds/Removes identifier to/from list of identifiers as\n // a result of checking/unchecking a checkbox or radiobutton\n function check(identifier, checked) {\n if (!responseVariable.value)\n responseVariable.value=[];\n if (!Array.isArray(responseVariable.value))\n responseVariable.value=[responseVariable.value];\n if (checked && !responseVariable.value.includes(identifier)) {\n responseVariable.value.push(identifier);\n } else if (!checked) {\n let idx = responseVariable.value.indexOf(identifier);\n if (idx >= 0)\n responseVariable.value.splice(idx, 1);\n }\n return responseVariable.value;\n }\n}",
"setInput(inputs) {\n\t\tfor (var i = 0; i < inputs.length; i++){\n\t\t\tthis.inputNodes[i].value = inputs[i]\n\t\t}\n\t}",
"function clearInputs() {\n var i;\n controlElem.value = '';\n for (i = 0; i < dilutions.length; i += 1) {\n dilElems[i].value = '';\n }\n updateResults();\n }",
"function displayOptions(arr) {\n $('input[name=\"answer\"]').prop('checked', false);\n let displayOption = [\n { A: $('.js-answer1').html(arr[0]) },\n { B: $('.js-answer2').html(arr[1]) },\n { C: $('.js-answer3').html(arr[2]) },\n { D: $('.js-answer4').html(arr[3]) },\n ];\n}",
"function initAnswerInputForm() {\n for (let i = 0; i < persons.length; i++) {\n let person = (persons[i]);\n let name = person.name;\n $('.people-dropdown-content').append('<li class=\\\"js-answer\\\">' + name + '</li>');\n }\n\n $('#myPerson').on('click', function() {\n $('.people-dropdown-content').toggle('show');\n });\n}",
"function checkAllInputs() {}",
"function clearInputOutput(){\n if (document.querySelector('input[name=\"radio\"]')) {\n document.querySelectorAll('input[name=\"radio\"]').forEach((element) => {\n element.addEventListener(\"change\", function(event) {\n // For Input\n document.getElementById(\"ui\").value = \"\";\n document.getElementById(\"ui\").placeholder = \"No. of Facts (Max 500)\";\n // For Output\n document.getElementById(\"out\").style.color = \"#2c3e50\";\n document.getElementById(\"out\").innerHTML = \"Your Input related Facts will be available here!\";\n });\n });\n }\n}",
"function genMatrixInputFields(dimentions){\n $(\"body\").append(\"<div class=\\\"inputField\\\"></div>\");\n $(\".inputField\").append(\"<button id=\\\"reset\\\">< Reselect Dimentions</button>\");\n $('#reset').click(function() {\n location.reload();\n });\n\n $(\".inputField\").append(\"<h3>Matrix A</h3>\");\n $(\".inputField\").append(\"<br>\");\n //console.log(dimentions[0][0]);\n //console.log(dimentions[0][1]);\n for(var i = 0; i < dimentions[0][0]; i++){\n for(var j = 0; j < dimentions[0][1]; j++){\n\n $(\".inputField\").append(\"<input type=\\\"text\\\" id=\\\"A\" + i + \"\" + j + \"\\\"/>\");\n\n }\n $(\".inputField\").append(\"<br>\");\n }\n\n $(\".inputField\").append(\"<h3>Matrix B</h3>\");\n $(\".inputField\").append(\"<br>\");\n\n for(var i = 0; i < dimentions[1][0]; i++){\n for(var j = 0; j < dimentions[1][1]; j++){\n $(\".inputField\").append(\"<input type=\\\"text\\\" id=\\\"B\" + i + \"\" + j + \"\\\"/>\");\n }\n $(\".inputField\").append(\"<br>\");\n }\n\n $(\".inputField\").append(\"<button id=\\\"calculate\\\">Calculate</button>\")\n\n}",
"function NeonInputBoxGenerator() {\n\tthis.inputTitles = []\n\tthis.inputs = []\n\tthis.themeColors = ['#5D0D72','#72F2E5', '#0743C8', '#CB0A88', '#FA0990']\n}",
"function gatherPaleoInputs() {\n var paleoInputs = {};\n paleoInputs.model = $('#paleo-input__model').val();\n paleoInputs.device = $('#paleo-input__device').val();\n paleoInputs.network = $('#paleo-input__network').val();\n paleoInputs.software = $('#paleo-input__software').val();\n paleoInputs.batch_size = parseInt($('#paleo-input__batch_size').html());\n paleoInputs.scaling = $('input[name=paleo-input__scaling]:checked').val();\n paleoInputs.use_cudnn = $('#paleo-input__use_cudnn').is(':checked');\n return paleoInputs;\n}",
"function getInput() {\n\tupdate(equation); // Update the equation in #equation-container\n\thandleMemory(); // Active buttons associated with memory.\n\n\t// Active keyboard for inputs.\n\tdocument.addEventListener(\"keypress\", keyboardInput, true);\n\n\t// Active buttons for inputs.\n\tvar backSpace = document.getElementsByClassName('fa-backspace');\n\tbackSpace[0].addEventListener(\"click\", buttonInput);\n\tvar buttons = document.getElementsByClassName(\"keyboard-item\");\n\tfor(i = 5; i < buttons.length; i++) {\n\t\tbuttons[i].addEventListener(\"click\", buttonInput);\n\t}\n}",
"function add_dotnotation_questions() {\n \n $(\"h3\").html(\"Category is Dot Notation\");\n $(\"h4\").html(\"Which is the correct dot notation format?\");\n\n $(\"#btn-next\").hide();\n $(\"#ans-panel\").text(\"\");\n\n uList.empty();\n uList.append($(\"<li> str1.length() <input type='checkbox' id='my-checkbox1'/></li>\"));\n\n uList.append($(\"<li>str1-length <input type='checkbox' id='my-checkbox2'/></li>\"));\n\n uList.append($(\"<li>str1[length] <input type='checkbox' id='my-checkbox3'/></li>\"));\n\n uList.append($(\"<br/>\"));\n\n uList.append($(\"<li class='no-bullet'><button type='button' class='btn btn-dark' id='btn-submit'>Submit</button></li>\"));\n\n\n var btnSubmit = $(\"#btn-submit\");\n btnSubmit.on(\"click\", function(){\n var ans = \"\";\n if ($(\"#my-checkbox1\").is(\":checked\")){\n ans = \"1\";\n }\n if ($(\"#my-checkbox2\").is(\":checked\")){\n ans = ans + \"2\";\n }\n if ($(\"#my-checkbox3\").is(\":checked\")){\n ans = ans + \"3\";\n }\n\n check_answer(ans, \"1\");\n });\n }",
"function showQuestions() {\n for (var i = 0; i < questionsArray.length; i++) {\n var questionHTML = getQuestionHTML(questionsArray[i], i + 1)\n $(\"#questions\").append(questionHTML);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Multistroke class: a container for unistrokes | function Multistroke(name, useBoundedRotationInvariance, strokes) // constructor
{
this.Name = name;
this.NumStrokes = strokes.length; // number of individual strokes
var order = new Array(strokes.length); // array of integer indices
for (var i = 0; i < strokes.length; i++)
order[i] = i; // initialize
var orders = new Array(); // array of integer arrays
HeapPermute(strokes.length, order, /*out*/ orders);
var unistrokes = MakeUnistrokes(strokes, orders); // returns array of point arrays
this.Unistrokes = new Array(unistrokes.length); // unistrokes for this multistroke
for (var j = 0; j < unistrokes.length; j++)
this.Unistrokes[j] = new Unistroke(name, useBoundedRotationInvariance, unistrokes[j]);
} | [
"function DrawHelperStrokes(){\n context.strokeStyle = 'green'\n context.beginPath();\n context.arc(Dx, Dy, 5, 0, Math.PI*2, false);\n context.stroke();\n\n context.beginPath();\n context.moveTo(Ax, Ay);\n context.lineTo(Dx-(Ax-Dx)*0.6, Dy-(Ay-Dy)*0.6);\n context.stroke();\n\n context.beginPath();\n context.moveTo(Bx, By);\n context.lineTo(Dx-(Bx-Dx)*0.6, Dy-(By-Dy)*0.6);\n context.stroke();\n\n context.beginPath();\n context.moveTo(Cx, Cy);\n context.lineTo(Dx-(Cx-Dx)*0.6, Dy-(Cy-Dy)*0.6);\n context.stroke();\n context.strokeStyle = 'black'\n }",
"constructor(canvasEl, imageData) {\n this.penDown = this.penDown.bind(this);\n this.penUp = this.penUp.bind(this);\n this.penMove = this.penMove.bind(this);\n this.undo = this.undo.bind(this);\n this.redo = this.redo.bind(this);\n this.getImageData = this.getImageData.bind(this);\n this.addStroke = this.addStroke.bind(this);\n this.resize = this.resize.bind(this);\n this.setOption = this.setOption.bind(this);\n this.zoom = this.zoom.bind(this);\n this.pan = this.pan.bind(this);\n this.reset = this.reset.bind(this);\n this.setStrokes = this.setStrokes.bind(this);\n this.onredo = this.onredo.bind(this);\n this.nextStroke = this.nextStroke.bind(this);\n\n this.canvasEl = canvasEl;\n this.isDrawing = false;\n this.brush = null;\n this.canvas = new NotepadCanvas(canvasEl);\n this.canvasEl = canvasEl;\n this.strokeHistory = new StrokeHistory(imageData.strokes);\n this.curStroke = {\n color: 'black',\n brush: 'pen',\n size: 8,\n points: []\n }; // holds the stroke currently being drawn\n\n // These are our custom events\n new Event(\"pendown\");\n new Event(\"penup\");\n new Event(\"penmove\");\n new Event(\"undo\");\n new Event(\"redo\");\n new Event(\"zoom\");\n new Event(\"pan\");\n new Event(\"notepad:ready\");\n new Event(\"notepad:stroke\");\n\n // Set up the input handlers\n const cursor = new Cursor(canvasEl);\n const keyboard = new KeyboardInput(canvasEl, cursor);\n const mouse = new MouseInput(canvasEl, keyboard, cursor);\n const touch = new TouchInput(canvasEl);\n\n // Bind our methods to our custom events\n canvasEl.addEventListener(\"pendown\", this.penDown);\n canvasEl.addEventListener(\"penup\", this.penUp);\n canvasEl.addEventListener(\"penmove\", this.penMove);\n canvasEl.addEventListener(\"undo\", () => this.broadcast(\"undo\"));\n canvasEl.addEventListener(\"redo\", this.onredo);\n canvasEl.addEventListener(\"zoom\", this.zoom);\n canvasEl.addEventListener(\"pan\", this.pan);\n\n // Refresh the canvas in case we had some initial stroke data\n this.resize();\n this.broadcast(\"ready\", this);\n }",
"function init(){\n svg.innerHTML = \"\";\n path = document.createElementNS(\"http://www.w3.org/2000/svg\",'path');\n path.setAttribute('d', `M ${anchors[anchors.length-2]} ${anchors[anchors.length-1]}`);\n path.setAttribute('fill','none');\n path.setAttribute('stroke','black');\n path.setAttribute('stroke-width','6');\n // stroke=\"black\" fill=\"none\"\n svg.appendChild(path);\n layerPoints = Array.from({length:anchors.length/2 });\n for(let i=0;i<layerPoints.length;i++){\n layerPoints[i] = Array.from({length:i+1});\n\n for(let j=0; j<layerPoints[i].length; j++){\n layerPoints[i][j] = { };\n cookSVGobj(layerPoints[i][j]);\n layerPoints[i][j].el = document.createElementNS(\"http://www.w3.org/2000/svg\",'circle');\n layerPoints[i][j].el.setAttribute('fill' ,`rgb(${Math.floor(Math.random()*256)} , ${Math.floor(Math.random()*256)} , ${Math.floor(Math.random()*256)})` );\n layerPoints[i][j].el.setAttribute('r',\"4\");\n svg.appendChild(layerPoints[i][j].el);\n }\n }\n\n layerLines = Array.from({length:anchors.length/2 });\n for(let i=0 ; i<layerLines.length;i++){\n layerLines[i] = Array.from({length:i});\n\n for(let j=0; j<layerLines[i].length;j++){\n layerLines[i][j] = {};\n cookSVGobj(layerLines[i][j]);\n\n layerLines[i][j].el = document.createElementNS(\"http://www.w3.org/2000/svg\",'line');\n layerLines[i][j].el.setAttribute('stroke' , `rgb(${Math.floor(Math.random()*256)} , ${Math.floor(Math.random()*256)} , ${Math.floor(Math.random()*256)})` );\n\n // layerLines[i][j].x1 = layerPoints[i][j].x;\n // layerLines[i][j].y1 = layerPoints[i][j].y;\n // layerLines[i][j].x2 = layerPoints[i][j+1].x;\n // layerLines[i][j].y2 = layerPoints[i][j+1].y;\n\n svg.appendChild(layerLines[i][j].el);\n\n }\n }\n \n}",
"key(x, y, squareSize, font) {\n this.ctx.font = font;\n for (let i = 0; i < this.data.length; i++) {\n this.ctx.fillStyle = this.data[i].color;\n this.ctx.textBaseline = \"top\";\n this.ctx.textAlign = \"left\";\n this.ctx.fillRect(x, y + i * squareSize * 1.5, squareSize, squareSize);\n this.ctx.fillText(`${this.data[i].label}, ${this.data[i].unit}`, x + squareSize * 1.5, y + squareSize * i * 1.5);\n }\n }",
"function setAllStrokeCaps(prop, capVal, joinVal){\n\n\t\tif(prop.matchName == \"ADBE Vector Stroke Line Cap\"){\n\t\t\tprop.setValue(capVal);\n\t\t\t++capsChangedCount;\n\t\t}\n\n\t\tif(prop.matchName == \"ADBE Vector Stroke Line Join\"){\n\t\t\tprop.setValue(joinVal);\n\t\t\t++joinsChangedCount;\n\t\t}\n\n\t\tif(prop.numProperties==0){\n\t\t\treturn\n\t\t} else {\n\t\t\tfor(var i = 1; i <= prop.numProperties; ++i){\n\t\t\t\tsetAllStrokeCaps(prop.property(i),capVal,joinVal);\n\t\t\t}\n\t\t}\n\n\t}",
"function pianoClickWhite(ctx){\r\n\t//to give chord name for each tuts\r\n\t//make array and fill with white tuts chord name\r\n\tvar keyName=[\"C\",\"D\",\"E\",\"F\",\"G\",\"A\",\"B\",\"C'\",\"D'\",\"E'\",\"F'\",\"G'\",\"A'\",\"B'\",\"C''\",\"D''\",\"E''\",\"F''\",\"G''\",\"A''\",\"B''\",\"C'''\",\"D'''\",\"E'''\",\"F'''\",\"G'''\",\"A'''\",\"B'''\"];\r\n\tvar keyNameNumber = 0;\r\n\tvar textPosition = 24;\r\n\tfor(x=0;x<1550 && keyNameNumber<29;x+=56){\r\n\t\tctx.fillStyle='white';\r\n\t\tctx.fillRect(x,250,55,300);\r\n\t\tctx.font = \"12px Arial\";\r\n\t\tctx.fillStyle = \"black\";\r\n\t\tctx.fillText(keyName[keyNameNumber],textPosition,500);\r\n\t\ttextPosition+=56;\r\n\t\tkeyNameNumber+=1;\r\n\t}\r\n\t\r\n}",
"function drawCapsForSet(set, capStyle, fillStyle, lineWidth) {\n var i = -1, x, y, w;\n\n while (++i < set.length) {\n x = getXForIndex(i, set.length);\n y = getYForValue(set[i]);\n\n if (capStyle === \"square\") {\n w = Math.max(2, lineWidth) * 2.5;\n drawRect(x - (w / 2), y + (w / 2), w, w, fillStyle);\n }\n else {\n w = lineWidth + 1;\n drawCircle(fillStyle, null, x, y, w);\n }\n }\n }",
"function removeStroke(node){\n addStroke(node, undefined, 0)\n}",
"function Drawing({ lines }) {\n\n return (\n <svg className=\"drawing\">\n {\n Object.keys(tools).flatMap(name => {\n const Renderer = tools[name].drawingComponent;\n return lines[tools[name].stateSelector].map((line, index) => (\n <Renderer key={index} line={line}/>\n ))})\n }\n </svg>\n );\n}",
"path(x, y) {\n stroke(116, 122, 117);\n strokeWeight(4);\n fill(147, 153, 148);\n for (let i = 0; i < 2; i++) {\n for (let j = 0; j < 2; j++) {\n rect(x - this.pxl * i, y + this.pxl * j, this.pxl, this.pxl);\n }\n }\n }",
"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 createPallet(){\n\tfor(let i = 0; i < numColor; i++){\n\t\tswatches.push(new ColorSwatch(\t((i*colorSwatchRadius)+colorSwatchRadius/2), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcolorSwatchRadius/2, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcolorSwatchRadius/2, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t colorArray[i]));\n\t}\n\tfillIcon = new FillIcon(canvasWidth-frameThickness*.75, canvasWidth/40, canvasWidth/20);\n}",
"setStrokeThicknessListener(){\n let input = uiElements.INPUT_STROKE;\n uiElements.TOOL_WITH_TOOLTIP.addEventListener(\"mouseover\", () => {\n uiElements.TOOLTIP_DRAW.style = \"display: flex\";\n });\n uiElements.TOOL_WITH_TOOLTIP.addEventListener(\"mouseout\", () => {\n uiElements.TOOLTIP_DRAW.style = \"display: none\";\n });\n input.addEventListener(\"input\", () => {\n uiElements.STROKE_THICKNESS_VALUE.innerHTML = input.value;\n this.canvas.freeDrawingBrush.width = parseInt(input.value, 10) || 1;\n });\n }",
"function drawOutline(){\n fill(125);\n stroke(125);\n index = buttonArr.indexOf(buttonVal2);\n rect(windowWidth/2 - 394 + 1920/42 * (index+1), windowHeight - 104, 39, 39, 4, 4) \n}",
"vShelf(x, y) {\n noStroke();\n for (let i = 0; i < 3; i++) {\n fill(51, 32, 0);\n rect(x, y + this.pxl * i, this.pxl, this.pxl);\n }\n }",
"function LetterB_drawHelpLines() {\n\talert(\"letterB: draw help lines\");\n\n\tthis.ctx.lineWidth = this.lineWidth;\n\n\tthis.ctx.beginPath();\n\tthis.ctx.moveTo(this.pt_start_x[0], this.pt_start_y[0]);\n\tthis.ctx.lineTo(this.pt_control_x[0], this.pt_control_y[0]);\n\tthis.ctx.stroke();\n\n\t// curve1\n\tthis.ctx.beginPath();\n\tthis.ctx.moveTo(this.pt_control_x[0], this.pt_control_y[0]);\n\tctx.bezierCurveTo(this.pt_control_x[0] + 100, this.pt_control_y[0],\n\t\t\tthis.pt_control_x[1] + 100, this.pt_control_y[1],\n\t\t\tthis.pt_control_x[1], this.pt_control_y[1]);\n\tthis.ctx.stroke();\n\n\t// curve2\n\tthis.ctx.beginPath();\n\tthis.ctx.moveTo(this.pt_control_x[1], this.pt_control_y[1]);\n\tctx.bezierCurveTo(this.pt_control_x[1] + 100, this.pt_control_y[1],\n\t\t\tthis.pt_end_x[0] + 100, this.pt_end_y[0] + this.radius / 2,\n\t\t\tthis.pt_end_x[0], this.pt_end_y[0] + this.radius / 2);\n\tthis.ctx.stroke();\n}",
"function GenerateLineElement(x2len, y2len, stroke_width, stroke_color) {\n\tvar aline = document.createElementNS(svgNS, \"line\");\n\taline.setAttribute(\"x2\", x2len);\n\taline.setAttribute(\"y2\", y2len);\n\taline.setAttributeNS(null, 'stroke-width', stroke_width);\n\taline.setAttributeNS(null, 'stroke', stroke_color);\n\treturn aline;\n}",
"function GlyphMaker(lineWidth, glyphDepth) {\r\n this.lineWidth = lineWidth;\r\n this.glyphDepth = glyphDepth;\r\n\r\n this.rigidModel = new RigidModel();\r\n this.mat = new Matrix44();\r\n this.vec = new Vec4();\r\n}",
"function pianoClickBlack(ctx){\r\n\t//to give chord name for each tuts\r\n\t//make array and fill with black tuts chord name\r\n\tvar keyName2=[\"C#\",\"D#\",\"F#\",\"G#\",\"A#\",\"C#'\",\"D#'\",\"F#'\",\"G#'\",\"A#'\",\"C#''\",\"D#''\",\"F#''\",\"G#''\",\"A#''\",\"C#'''\",\"D#'''\",\"F#'''\",\"G#'''\",\"A#'''\"];\r\n\tvar keyNameNumber2 = 0;\r\n\tvar textPosition2 = 46;\r\n\tfor(xBlackTuts=32;xBlackTuts<1550 && keyNameNumber2<20;xBlackTuts+=56){\r\n\t\tif(xBlackTuts != 144 && xBlackTuts != 368 && xBlackTuts != 536 && xBlackTuts != 760 && xBlackTuts != 928 & xBlackTuts != 1152 && xBlackTuts != 1320){\r\n\t\t\tctx.fillStyle='black';\r\n\t\t\tctx.fillRect(xBlackTuts,250,45,180);\r\n\t\t\tctx.font = \"12px Arial\";\r\n\t\t\tctx.fillStyle = \"white\";\r\n\t\t\tctx.fillText(keyName2[keyNameNumber2],textPosition2,390);\r\n\t\t\tkeyNameNumber2+=1;\r\n\t\t}\r\n\t\ttextPosition2+=56;\r\n\t}\r\n\t\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add the selected Veggies | function addVeggies(runningPrice) {
var veggiePrice = 0;
var veggieCount = 0;
var veggieText = "";
var veggieOptions = document.getElementsByClassName('veggie');
for (var i = 0; i < veggieOptions.length; i++) {
if (veggieCount >= 1) {
if (veggieOptions[i].checked) {
veggieText += "<p>" + veggieOptions[i].value + " +$1.00</p>";
veggieCount += 1;
veggiePrice += 1;
}
} else {
if (veggieOptions[i].checked) {
veggieText += "<p>" + veggieOptions[i].value +"</p>";
veggieCount += 1;
}
}
}
document.getElementById('selectedVeggies').innerHTML = veggieText;
runningPrice += veggiePrice;
updateRunning(runningPrice);
} | [
"function appendNewVehicleToSelect(vehicle){\n $(\"#selectCar\").append($(\"<option>\").val(vehicle.vehicleID).text(vehicle.licensePlate));\n}",
"addLenses(lenses){\n let selectLenses = document.getElementById('select_lenses');\n for (let i in lenses){\n selectLenses.innerHTML += `<option> ${lenses[i]} </option>`;\n }\n }",
"addViking(viking) {\n this.vikingArmy.push(viking);\n }",
"function addToSelect(values) {\nvalues.sort();\nvalues.unshift('None'); // Add 'None' to the array and place it to the beginning of the array\nvalues.forEach(function(value) {\n var option = document.createElement(\"option\");\n option.text = value;\n municipalSelect.add(option);\n});\nreturn setLotMunicipalExpression(municipalSelect.value);\n}",
"function populateVoices() {\n // remove current voice options\n while (voiceSelect.hasChildNodes()) {\n voiceSelect.removeChild(voiceSelect.firstChild);\n }\n\n const voices = SpeechSynthesisAdapter.getVoices();\n\n // add voice options\n voices.forEach(voice => {\n const option = document.createElement(\"option\");\n\n option.value = voice.name;\n option.innerText = voice.name;\n\n voiceSelect.appendChild(option);\n });\n}",
"function appendModelOptions() {\n modelField.innerHTML = '';\n\n modelEmptyOption();\n\n\n var brandSelect = brand.options[brand.selectedIndex].text;\n var modelArr = [];\n\n switch (brandSelect){\n case 'Audi':\n modelArr = ['A4','A6','Q7'];\n break;\n case 'BMW':\n modelArr = ['3 Series','5 Series','7 Series'];\n break;\n case 'Toyota':\n modelArr = ['Prius','Corolla','Camri'];\n break;\n case 'Mazda':\n modelArr = ['3','6'];\n break;\n case 'Volkswagen':\n modelArr = ['Golf','Passat','Toureg'];\n break;\n }\n\n addFilterOptions(modelArr, 'model');\n }",
"function addRestaurantsInSelect( xmlFromServer)\n{\n\tvar xmlListRestaurants= xmlFromServer.getElementsByTagName(\"RESTAURANT\");\n\tvar id,name;\n\t\n\t/*\n\t * J'ajoute le choix, sans restaurant pour qu'un restaurateur \n\t * ne sois assigne a aucun resataurant \n\t * au moment de la creation de son compte\n\t */\n\taddNewOptionInSelect(\"restaurantList\",0,\"Liste des Restaurants\");\n\t\n\tfor (var i=0;i<xmlListRestaurants.length;i++)\n\t { \n\t\t\n\t\tid=xmlListRestaurants[i].getElementsByTagName(\"ID\")[0].childNodes[0].nodeValue;\n\t\t\n\t\tname=xmlListRestaurants[i].getElementsByTagName(\"NAME\")[0].childNodes[0].nodeValue;\n\t\t\n\t\t//J'ajoute le restaurant dans la liste deroulante\n\t\taddNewOptionInSelect(\"restaurantList\",id,name);\n\t\n\t}\n}",
"function add_items(){\n\tget_all_items.done(function(data){\n\t var items = \"<select name='select_item' class='add-item' >\";\n\t for(var i = 0; i < data.length; i++){\n\t\titems += \"<option class='item_option' value=\" +data[i].itemId +\">\";\n\t\titems += data[i].itemName;\n\t\titems += \"</option>\";\n\t }\n\t items += \"</select>\";\n\t $(\"#add_items\").append(items);\n\t items_new_busi = items;\n\t});\n }",
"function addMorePigs() {\n // alert();\n\n var val = $(\"#combobox\").val();\n var opts = $('#combo-options').children();\n for (var i = 0; i < opts.length; i++) {\n if (opts[i].value === val) {\n // An item was selected from the list!\n\n // Add this item to the purchase list\n var selected =opts[i].value;\n var price =$(\"#\"+selected+\"_price\").text();\n\n var current_total=$(\"#total\").text();\n var sum_total=Number(current_total)+Number(price);\n\n var btn=\"<button class='btn btn-danger btn-sm' type='button' name='button' onclick='removeSale(\\\"\"+selected.replace(/ /g,\"_\")+\"\\\")'>×</button>\";\n\n var tr=\"<tr id='sales_\"+selected.replace(/ /g,\"_\")+\"'>\"+\n \"<td>\"+selected+\"</td>\"+\n \"<td id='iprice_\"+selected.replace(/ /g,\"_\")+\"'>\"+price+\"</td>\"+\n \"<td>\"+btn+\"</td>\";\n\n $(\"#total_charges\").before(tr);\n $(\"#combo-options option\").eq(i).remove();\n $(\"#combobox\").val(\"\");\n $(\"#total\").text(sum_total);\n break;\n }\n }\n}",
"function updateSelect() {\n for (var i=0;i<g_points.length;i++){\n figures.options[i+1] = new Option('Surface' +i, i);\n }\n}",
"function addOption() {\n var province = profile.province;\n var country = profile.country;\n province.options[province.options.length] = SelectProvince;\n country.options[country.options.length] = SelectCountry;\n}",
"function flavour1(){\n flavourSelect=[\"flavour1\", 100];\n }",
"function populateBreedsSelect(breeds) {\n $breed_select.empty().append(function() {\n let output = '';\n $.each(breeds, function(key, value) {\n output += '<option id=\"' + value.id + '\">' + value.name + '</option>';\n });\n return output;\n });\n}",
"function createGenresSelect(container, genres) {\n for (var i = 0; i < genres.length; i++) {\n var option = $(\".template option\").clone();\n option.val(genres[i][\"id\"]).text(genres[i][\"name\"])\n container.append(option);\n }\n}",
"function addDrink(){\n \"use strict\";\n \n // Gets the chosen tea and milk from the dropdowns\n var teaIndex = getOptionIndex(\"tea\", teaOptions[0]);\n var milkIndex = getOptionIndex(\"milk\", milkOptions[0]);\n \n // Creates a new Drink and adds it to the drinks array\n drinks.push(new Drink(teaOptions[0][teaIndex], toppingList, milkOptions[0][milkIndex]));\n \n // Update the page\n updatePage();\n}",
"addItem() {\n let newClothes = new Clothing(itemClothing.value, costClothing.value);\n this.clothes.push(newClothes); \n }",
"function loadArtistsInSelect(album) {\r\n // array per controllo nomi degli artisti da caricare nella select\r\n var arraySelect = [];\r\n // ciclo per caricare i nomi artisti nella select\r\n for (var i = 0; i < album.length; i++) {\r\n // controlla se il nome artista è già stato inserito nella select\r\n if (!arraySelect.includes(album[i].author)) {\r\n // aggiune il nome artista nell'array di controllo dei nomi\r\n arraySelect.push(album[i].author);\r\n // aggiunge il nome artista alla select\r\n $(\".select-artist\").append(\"<option value='\"+album[i].author+\"'>\"+album[i].author+\"</option>\");\r\n };\r\n };\r\n}",
"addOption(encounter) {\n var item = encounter[this.dataKey];\n if (!this.options.includes(item))\n this.options.push(item);\n }",
"function selectPoint (poi) {\n\tselectedPoints.push(poi);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sorts the player list. Resets the spinners. Displays players. | function sortPlayers() {
"use strict";
list.sort(compareByScore);
resetSpinners();
displayPlayers();
} | [
"function sortPlayers() {\n var orderHTML = '<br><table id=\"orderlist\" >';\n orderHTML+= '<caption><b>Player Order</b></caption>';\n orderHTML+= '<tr style=\"background-color: #ddffdd\">';\n orderHTML+= '<th>Player<br>Name</th></tr>';\n $.each(BID18.bid.players,function(index,listInfo) {\n if (listInfo.bid === \"10\") {\n orderHTML += '<tr> <td>' + listInfo.name + '</td></tr>';\n }\n }); // end of each 10\n $.each(BID18.bid.players,function(index,listInfo) {\n if (listInfo.bid === \"5\") {\n orderHTML += '<tr> <td>' + listInfo.name + '</td></tr>';\n }\n }); // end of each 5\n $.each(BID18.bid.players,function(index,listInfo) {\n if (listInfo.bid === \"0\") {\n orderHTML += '<tr> <td>' + listInfo.name + '</td></tr>';\n }\n }); // end of each 0\n orderHTML+= '</table>';\n $(\"#orderlist\").remove();\n $(\"#playerorder\").append(orderHTML).show();\n}",
"function orderPlayers() {\n vm.competition.players = $filter('orderBy')(vm.competition.players, 'position');\n }",
"static refreshList(sortBy = null) {\n if (typeof sortBy == \"string\") {\n Settings.current.sortBy = sortBy;\n }\n if (this.songListElement) {\n let sortFunc = (a, b) => { return 0; };\n try {\n switch (Settings.current.sortBy) {\n case \"title\":\n sortFunc = (a, b) => {\n if (a.details.title.toLowerCase() > b.details.title.toLowerCase()) {\n return 1;\n }\n if (a.details.title.toLowerCase() < b.details.title.toLowerCase()) {\n return -1;\n }\n return 0;\n };\n break;\n case \"length\":\n sortFunc = (a, b) => {\n if (typeof a.details.songLength == \"number\" && typeof b.details.songLength == \"number\" && a.details.songLength > b.details.songLength) {\n return 1;\n }\n if (typeof a.details.songLength == \"number\" && typeof b.details.songLength == \"number\" && a.details.songLength < b.details.songLength) {\n return -1;\n }\n return 0;\n };\n break;\n case \"artist\": // Fall-through\n default:\n sortFunc = (a, b) => {\n if (a.details.artist.toLowerCase() > b.details.artist.toLowerCase()) {\n return 1;\n }\n if (a.details.artist.toLowerCase() < b.details.artist.toLowerCase()) {\n return -1;\n }\n return 0;\n };\n break;\n }\n }\n catch (error) {\n }\n var _sort = function (a, b) {\n // Make order reversable\n return sortFunc(a, b);\n };\n SongManager.songList.sort(_sort);\n let nList = SongManager.songList;\n let opened = SongGroup.getAllGroupNames(false);\n opened = [...new Set(opened)];\n SongManager.songListElement.innerHTML = \"\";\n let noGrouping = false;\n // Group Songs\n if (typeof Settings.current.songGrouping == \"number\" && Settings.current.songGrouping > 0 && Settings.current.songGrouping <= 7) {\n let groups = {};\n let addToGroup = function (name, song, missingText = \"No group set\") {\n if (name == null || (typeof name == \"string\" && name.trim() == \"\")) {\n name = missingText;\n }\n if (groups.hasOwnProperty(name)) {\n groups[name].push(song);\n }\n else {\n groups[name] = [song];\n }\n };\n switch (Settings.current.songGrouping) {\n case 1:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.artist, s, \"[No artist set]\");\n });\n break;\n case 2:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.album, s, \"[No album set]\");\n });\n break;\n case 3:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.source, s, \"[No source set]\");\n });\n break;\n case 4:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.language, s, \"[No language set]\");\n });\n break;\n case 5:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.genre, s, \"[No genre set]\");\n });\n break;\n case 6:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.year, s, \"[No year set]\");\n });\n break;\n case 7:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.customGroup, s, \"[No group set]\");\n });\n break;\n case 8:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.artist[0].toUpperCase(), s, \"[No artist set]\");\n });\n break;\n case 9:\n SongManager.songList.forEach(s => {\n addToGroup(s.details.title[0].toUpperCase(), s, \"[No title set]\");\n });\n break;\n default:\n noGrouping = true;\n break;\n }\n if (noGrouping == false) {\n for (const key in groups) {\n if (groups.hasOwnProperty(key)) {\n const sg = new SongGroup(key);\n sg.songList = groups[key];\n if (opened.includes(sg.name)) {\n sg.collapsed = false;\n }\n else {\n sg.collapsed = true;\n }\n sg.refreshList();\n }\n }\n }\n }\n // Don't Group Songs\n else {\n noGrouping = true;\n }\n if (noGrouping == true) {\n for (let i = 0; i < nList.length; i++) {\n const song = nList[i];\n song.refreshElement();\n SongManager.songListElement.appendChild(song.element);\n }\n }\n SongManager.search();\n }\n else {\n console.error(\"No div element applied to SongManager.songListElement\", \"SongManager.songListElement is \" + typeof SongManager.songListElement);\n }\n Toxen.resetTray();\n }",
"function sortResults(username, friends, unheard, searchType, results) {\r\n\r\n // we use the sort function to order the results based on their score\r\n results.sort((a, b) => parseFloat(b.score) - parseFloat(a.score));\r\n\r\n if (unheard) {\r\n\r\n // first we make the progress bar visible and describe the current status\r\n document.getElementById('progress').style.width = '0%';\r\n document.getElementById('status').textContent = 'Filtering out results you have already heard...';\r\n\r\n let unheardReleases = [];\r\n filterUnheard(username, searchType, results, 0, unheardReleases);\r\n } else {\r\n // for the first 50 items in the results array, we want to display them\r\n pageDisplay(searchType, results, 0);\r\n }\r\n}",
"function printData(active) {\n const sortedNames = active.sort((first, second) => first.Jersey > second.Jersey ? 1 : -1) // idea came from w3schools: https://stackoverflow.com/questions/6712034/sort-array-by-firstname-alphabetically-in-javascript, \n sortedNames.forEach(player => {\n let div = document.createElement('div')\n div.setAttribute(\"id\", \"player-stats\")\n document.querySelector('.player-container').append(div)\n let img = document.createElement('img')\n img.setAttribute('src', player.PhotoUrl)\n document.querySelector('#player-stats').append(img)\n let p = document.createElement('p')\n p.textContent = `#${player.Jersey} | ${player.FirstName} ${player.LastName} | Position: ${player.Position} | Birthplace: ${player.BirthCity}, ${player.BirthState || player.BirthCountry} | Bats: ${player.BatHand}, Throws: ${player.ThrowHand} | College: ${player.College || ' '}`\n document.querySelector('#player-stats').append(p)\n })\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 updateLeaderboardHTML(rankedList) {\n\n // Now we actually sort the rankedList\n rankedList.sort(function (a, b) {\n if (a.value > b.value) {\n return -1;\n }\n if (a.value < b.value) {\n return 1;\n }\n // a must be equal to b\n return 0;\n });\n\n var html = '';\n\n for (var i = 0; i < rankedList.length; i++) {\n\n var timpstamp = rankedList[i].timpstamp;\n var temperature = rankedList[i].temperature;\n var listElement = '<tr><td class=\"iota__timestamp\">#' + timpstamp + '</td><td class=\"iota__temperature\">' + temperature;\n html += listElement;\n }\n\n $(\"#leaderboard\").html(html);\n}",
"function populateLeaderboardTable() {\n\t// Ordeno el json dependiendo del score y los partidos ganados, perdidos o empatados\n\tleaderboardJson = leaderboardSorted(leaderboardJson);\n\t// imprimo las 5 primeras posiciones\n\tleaderboardTable.innerHTML = \"\";\n\tleaderboardJson.slice(0, 5).forEach(player => {\n\t\tleaderboardTable.innerHTML += \"<tr><th>\" + player.playerName + \"</th><td>\" + player.score + \"</td><td>\" +\n\t\t\tplayer.won + \"</td><td>\" + player.lost + \"</td><td>\" + player.tied + \"</td></tr>\"\n\t});\n}",
"sortLeaderboard () {\n // Build the array to be sorted that will contain all the leaderboard information\n let sortedLeaderboard = []\n const leaderboard = this.state.leaderboard\n\n for (var key in leaderboard) {\n if (leaderboard.hasOwnProperty(key)) {\n if (this.checkFilters(leaderboard[key])) {\n sortedLeaderboard.push(leaderboard[key])\n }\n }\n }\n\n sortedLeaderboard.sort((a, b) => b.score - a.score)\n\n for (var i in sortedLeaderboard) {\n sortedLeaderboard[i].position = parseInt(i, 10) + 1\n }\n if (!this.state.showAll) {\n sortedLeaderboard = this.snipTableData(sortedLeaderboard)\n }\n return sortedLeaderboard\n }",
"function SortByAge() {\n player = players.sort(function (a, b) {\n return b.age - a.age\n });\n}",
"function setSortCardsListeners() {\n\tconst sortMenuButton = document.getElementById(\"sortMenuButton\");\n\tconst sortByFirstName = document.getElementById(\"sortFirstName\");\n\tconst sortByLastName = document.getElementById(\"sortLastName\");\n\tconst sortByParty = document.getElementById(\"sortParty\");\n\tconst sortByState = document.getElementById(\"sortState\");\n\tconst sortBySeniority = document.getElementById(\"sortSeniority\");\n\tconst sortByVotesWith = document.getElementById(\"sortVotesWith\");\n\tconst sortByVotesAgainst = document.getElementById(\"sortVotesAgainst\");\n\tconst sortByDistrict = document.getElementById(\"sortDistrict\");\n\n\tsortByFirstName.onclick = () => {\n\t\tlet sortStringAscendingly = '<i class=\"fas fa-sort-alpha-up\"></i> Sort on first name';\n\t\tlet sortStringDescendingly =\n\t\t\t'<i class=\"fas fa-sort-alpha-down-alt\"></i> Sort on first name';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.firstName,\n\t\t\t\"firstName\",\n\t\t\tsortByFirstNameAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByFirstName,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortByLastName.onclick = () => {\n\t\tlet sortStringAscendingly = '<i class=\"fas fa-sort-alpha-up\"></i> Sort on last name';\n\t\tlet sortStringDescendingly = '<i class=\"fas fa-sort-alpha-down-alt\"></i> Sort on last name';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.lastName,\n\t\t\t\"lastName\",\n\t\t\tsortByLastNameAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByLastName,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortByParty.onclick = () => {\n\t\tlet sortStringAscendingly = '<i class=\"fas fa-sort-alpha-up\"></i> Sort on party';\n\t\tlet sortStringDescendingly = '<i class=\"fas fa-sort-alpha-down-alt\"></i> Sort on party';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.party,\n\t\t\t\"party\",\n\t\t\tsortByPartyAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByParty,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortByState.onclick = () => {\n\t\tlet sortStringAscendingly = '<i class=\"fas fa-sort-alpha-up\"></i> Sort on state';\n\t\tlet sortStringDescendingly = '<i class=\"fas fa-sort-alpha-down-alt\"></i> Sort on state';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.state,\n\t\t\t\"state\",\n\t\t\tsortByStateAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByState,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortBySeniority.onclick = () => {\n\t\tlet sortStringAscendingly = '<i class=\"fas fa-sort-numeric-up\"></i> Sort on seniority';\n\t\tlet sortStringDescendingly =\n\t\t\t'<i class=\"fas fa-sort-numeric-down-alt\"></i> Sort on seniority';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.seniority,\n\t\t\t\"seniority\",\n\t\t\tsortBySeniorityAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortBySeniority,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortByVotesWith.onclick = () => {\n\t\tlet sortStringAscendingly =\n\t\t\t'<i class=\"fas fa-sort-numeric-up\"></i> Sort on votes with party';\n\t\tlet sortStringDescendingly =\n\t\t\t'<i class=\"fas fa-sort-numeric-down-alt\"></i> Sort on votes with party';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.partyVotesWith,\n\t\t\t\"partyVotesWith\",\n\t\t\tsortByVotesWithAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByVotesWith,\n\t\t\tundefined\n\t\t);\n\t};\n\n\tsortByVotesAgainst.onclick = () => {\n\t\tlet sortStringAscendingly =\n\t\t\t'<i class=\"fas fa-sort-numeric-up\"></i> Sort on votes against party';\n\t\tlet sortStringDescendingly =\n\t\t\t'<i class=\"fas fa-sort-numeric-down-alt\"></i> Sort on votes against party';\n\n\t\tsortClickHandler(\n\t\t\tsortedOn.partyVotesAgainst,\n\t\t\t\"partyVotesAgainst\",\n\t\t\tsortByVotesAgainstAscending,\n\t\t\tsortStringAscendingly,\n\t\t\tsortStringDescendingly,\n\t\t\tsortMenuButton,\n\t\t\tsortByVotesAgainst,\n\t\t\tundefined\n\t\t);\n\t};\n}",
"function drawPlayers(searchedPlayers) {\n if (searchedPlayers != null) {\n\n var template = '';\n\n for (let i = 0; i < searchedPlayers.length; i++) {\n let player = searchedPlayers[i];\n\n template += `\n <div class=\"player-card\" id=\"${i}\">\n <img src=\"${player.photo}\" alt=\"http://s.nflcdn.com/static/content/public/image/fantasy/transparent/200x200/\">\n <div>Name: ${player.fullname}</div>\n <div>Position: ${player.position}</div>\n <div>Team: ${player.pro_team}</div>\n <div class=\"add\"><button onclick=\"app.controllers.playerController.addToMyTeam(${player.id})\" id=\"btn${i}\">Add</button></div>\n </div>\n `\n }\n\n document.getElementById('search-results').innerHTML = template;\n }\n }",
"function sortPanes()\n {\n if(_SortGeneration !== _Generation) {\n _OptionPanes.sort(function(lhs, rhs) { return lhs.getDisplayOrder() - rhs.getDisplayOrder(); });\n _SortGeneration = _Generation;\n }\n }",
"function selectionSort()\n{\n\tfor (var i = 0; i < dataArray.length; i++)\n\t\t{\n\t\tsSort(i);\n\t\tsleep(500);\n\t\tredraw();\n\t\t}\n}",
"function sortArtist() {\r\n document.querySelector('#artH').addEventListener('click', function (e) {\r\n const artist = paintings.sort((a, b) => {\r\n return a.LastName < b.LastName ? -1 : 1;\r\n })\r\n displayPaint(artist);\r\n })\r\n }",
"function updatePlayer() {\n initializePlayer();\n newPlayer.setYearsInLeague(\"16\");\n newPlayer.display();\n\n}",
"function sortPlayerScores() {\n userArr.sort(function(a, b) {\n if (a.score > b.score) {\n return -1;\n }\n if (a.score < b.score) {\n return 1;\n }\n // scores must be equal\n return 0;\n });\n}",
"function makeList() {\n PLAYERS.forEach(function(player) {\n let div = document.createElement('div')\n div.className += `${player.name}`\n div.dataset.number = `${player.number}`\n div.innerHTML += `<h3>${player.name} (<em>${player.nickname}</em>)<h3><br><img src=\"${player.photo}\" alt=\"${player.name}\">`\n document.querySelector(\"body\").appendChild(div)\n });\n}",
"function loadNewPlayersSuccess(resp) \n{\n\tvar e, li, i, results, players, icon, link, span, count, pspan, fa, player;\n\n\te = doClearNode(document.getElementById('loadNewPlayers'));\n\n\ttry { \n\t\tresults = JSON.parse(resp);\n\t} catch (error) {\n\t\treturn;\n\t}\n\n\tcheckToggle('autoaddToggle', 'autoadd', results.autoadd);\n\tcheckToggle('autoadd2Toggle', 'autoadd2', results.autoadd);\n\tcheckToggle('autoaddTogglePreserve', 'autoaddpreserve', results.autoaddpreserve);\n\tdoValue('autoadd4', results.autoadd);\n\tdoValue('autoadd3', results.autoadd);\n\tdoValue('autoaddpreserve2', results.autoaddpreserve);\n\n\tif (results.autoadd) {\n\t\tdoUnhide('captiveGame2');\n\t\tdoUnhide('captiveGame');\n\t} else {\n\t\tdoHide('captiveGame');\n\t\tdoHide('captiveGame2');\n\t}\n\n\tplayers = results.players;\n\n\tif (0 == players.length) {\n\t\tli = document.createElement('li');\n\t\te.appendChild(li);\n\t\tli.setAttribute('class', 'error');\n\t\tli.appendChild(document.createTextNode('No participants.'));\n\t\treturn;\n\t}\n\n\tfor (count = i = 0; i < players.length; i++) {\n\t\tplayer = players[i].player;\n\t\tif (player.enabled)\n\t\t\tcount++;\n\t\tspan = document.createElement('li');\n\t\tspan.setAttribute('id', 'player' + player.id);\n\t\ticon = document.createElement('a');\n\t\ticon.setAttribute('data-playerid', player.id);\n\t\ticon.setAttribute('class', 'fa fa-remove');\n\t\ticon.setAttribute('href', '#;');\n\t\ticon.setAttribute('id', 'playerDelete' + player.id);\n\t\ticon.onclick = function() {\n\t\t\treturn function(){doDeletePlayer(this); return(false);};\n\t\t}();\n\t\tspan.appendChild(icon);\n\t\ticon = document.createElement('span');\n\t\ticon.appendChild(document.createTextNode(player.mail));\n\t\tspan.appendChild(icon);\n\t\tif (player.autoadd) {\n\t\t\ticon = document.createElement('i');\n\t\t\ticon.className = 'fa fa-thumb-tack';\n\t\t\tspan.appendChild(document.createTextNode(' '));\n\t\t\tspan.appendChild(icon);\n\t\t}\n\t\te.appendChild(span);\n\t}\n}",
"function getTopCrimePlayers() {\r\n\t\t$.get('http://nflarrest.com/api/v1/player', function(data) {\r\n\t\t\t//console.log(data)\r\n\t\t\t// compare function of array object properties to sort by arrest_count\r\n\t\t\tfunction compare(a,b) {\r\n\t\t\t\tif (a.arrest_count < b.arrest_count) {\r\n\t\t\t\t\treturn 1;\r\n\t\t\t\t} else if (a.arrest_count > b.arrest_count) {\r\n\t\t\t\t\treturn -1;\r\n\t\t\t\t} else {\r\n\t\t\t\t\treturn 0;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t// sort data by highest arrests before mapping into new array\r\n\t\t\tdata.sort(compare);\r\n\t\t\t// map top 5 arrested players into array\r\n\t\t\tlet topPlayers = new Array();\r\n\t\t\tfor (var i = 0; i < data.length; i++) {\r\n\t\t\t\tif (i < 5) {\r\n\t\t\t\t\ttopPlayers.push('<li>' + data[i].Name + ' (' + data[i].arrest_count + ')');\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t$(\"#top-players\").append(topPlayers);\r\n\t\t});\r\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Interrupt a kernel. Notes Uses the [Jupyter Notebook API]( The promise is fulfilled on a valid response and rejected otherwise. It is assumed that the API call does not mutate the kernel id or name. The promise will be rejected if the kernel status is `Dead` or if the request fails or the response is invalid. | interrupt() {
return Private.interruptKernel(this, this.serverSettings);
} | [
"function interruptAs(fiberId, __trace) {\n return (0, _core3.haltWith)(trace => Cause.traced(Cause.interrupt(fiberId), trace()), __trace);\n}",
"function unsafe_cancel_exn() /* () -> exception */ {\n return exception(\"computation is canceled\", Cancel);\n}",
"function createKernel(options, id) {\n return new Promise(function (resolve, reject) {\n var kernel = new Kernel(options, id);\n var callback = function (sender, status) {\n if (status === ikernel_1.KernelStatus.Starting || status === ikernel_1.KernelStatus.Idle) {\n kernel.statusChanged.disconnect(callback);\n runningKernels.set(kernel.id, kernel);\n resolve(kernel);\n }\n else if (status === ikernel_1.KernelStatus.Dead) {\n kernel.statusChanged.disconnect(callback);\n reject(new Error('Kernel failed to start'));\n }\n };\n kernel.statusChanged.connect(callback);\n });\n}",
"interruptA() {\n console.log('mcp23gpio Handle Interrupt A ----------------------------');\n return this.commonReadAndProcessA();\n }",
"emitInterrupt(source, interrupt) {\n // get the index of the process from the queue\n const sourceIndex = this.processes.indexOf(source);\n // splice it out using array method splice removing that from the queue it is in\n this.processes.splice(sourceIndex, 1);\n this.scheduler.handleInterrupt(this, source, interrupt);\n }",
"function sendKernelMessage(kernel, msg) {\n var future = kernel.sendShellMessage(msg, true);\n return new Promise(function (resolve, reject) {\n future.onReply = function (msg) {\n resolve(msg.content);\n };\n });\n}",
"function connectToKernel(id, options) {\n var kernel = runningKernels.get(id);\n if (kernel) {\n return Promise.resolve(kernel);\n }\n if (options === void 0) {\n return Promise.reject(new Error('Please specify kernel options'));\n }\n return listRunningKernels(options.baseUrl).then(function (kernelIds) {\n if (!kernelIds.some(function (k) { return k.id === id; })) {\n throw new Error('No running kernel with id: ' + id);\n }\n return createKernel(options, id);\n });\n}",
"function logKernelStatus(kernel) {\n if (kernel.status == ikernel_1.KernelStatus.Idle ||\n kernel.status === ikernel_1.KernelStatus.Busy ||\n kernel.status === ikernel_1.KernelStatus.Unknown) {\n return;\n }\n var status = '';\n switch (kernel.status) {\n case ikernel_1.KernelStatus.Starting:\n status = 'starting';\n break;\n case ikernel_1.KernelStatus.Restarting:\n status = 'restarting';\n break;\n case ikernel_1.KernelStatus.Dead:\n status = 'dead';\n break;\n }\n console.log('Kernel: ' + status + ' (' + kernel.id + ')');\n}",
"function systemOff (req, res) {\n\t\t// Here we will have calls to public controller functions to switch on/off a boolean\n\t\t// within each controller that lets it know whether it has permission to run\n\t}",
"function krnDiskLS(callBack)\n{\n _KernelInterruptQueue.enqueue(new Interrupt(DISK_IRQ,\n [FS_OPS.LS, null, null, callBack ? callBack : krnPutAndDrop]));\n}",
"static toggleSimulation({ eTag, enabled, id }) {\n return HttpClient.patch(`${ENDPOINT}simulations/${id}`, { ETag: eTag, Enabled: enabled })\n .map(toSimulationModel)\n .catch(resolveConflict);\n }",
"function programStop(id) {\n\tvar url = '/rainmachine/pstop';\n\tvar data = {id: id};\n\n\tfetch(url, {\n\t method: 'POST',\n\t body: JSON.stringify(data),\n\t headers: new Headers({\n\t 'Content-Type': 'application/json'\n\t })\n\t}).then(res => res.json())\n\t.catch(error => console.error('Error:', error));\n}",
"function interruptibleMask(f, __trace) {\n return (0, _core3.checkInterruptible)(flag => interruptible(f(new InterruptStatusRestoreImpl(flag))), __trace);\n}",
"function RejectRequest(requestID) {\n try {\n // Xoa yeu cau\n bookshelf.XoaYeuCau(requestID);\n return true;\n } catch (ee) {\n console.log(ee)\n return false;\n }\n}",
"function krnContextSwitch(params)\n{\n _Scheduler.processNext(_CPU,params[0]);\n}",
"abortSession() {\n if (this.isRunning) {\n this.abort = true;\n }\n }",
"abort(transaction_id) {\n this.sendCommand('ABORT', {'transaction': transaction_id});\n this.log.debug(`abort transaction: ${transaction_id}`);\n }",
"async function terminateInstance(instanceId) {\n console.log('Terminating instance', instanceId);\n\n await ec2.terminateInstances({\n InstanceIds: [\n instanceId\n ]\n }).promise();\n\n console.log('Instance was terminated')\n}",
"cancel(invitation) {\n axios.delete(`/settings/invitations/${invitation.id}`)\n .then(() => {\n this.$parent.$emit('updateInvitations');\n });\n }",
"cancelDiscovery() {\n if (Platform.OS == \"ios\")\n throw new Error(\"Method not implemented.\");\n return this._nativeModule.cancelDiscovery();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make the life sprites with the heart images after a given number of frameCount (similar to createAlien()) Give them a velocity, add them to a life group (make a new coin group in function setup()) give them a lifetime, make sure their vertical positions are random | function BoostLife()
{
if(frameCount%1000 === 0) {
lifeBoost=createSprite(0,40,10,10);
lifeBoost.addImage(lifeboostImg);
lifeBoost.scale=0.5
lifeBoostn.velocityX=2;
lifeBoost.y=random(20,height-20);
lifeBoost.lifetime=1000;
lifeBoostgroup.add(lifeBoost);
}
} | [
"function generateZerg() {\n if (frames % 70 === 0) {\n enemies.push(new Zerg())\n }\n }",
"function createExplosion() {\n function rand( size ) {\n return size * Math.random() - (size/2);\n }\n var num = 150;\n particleGroup.triggerPoolEmitter( 1, (pos.set( rand(num/10), rand(num/10), rand(num/10) )) );\n console.log('explosion!');\n}",
"generateEnemies() {\n // Run the spawn timer\n this.timer++;\n if (this.enemies.length == 0) {\n this.timer += 2;\n } else if (this.enemies.length == 1) {\n this.timer += 1;\n }\n\n if (\n this.timer >= this.spawnDelay &&\n this.enemies.length < MAX_ENEMIES.value\n ) {\n this.createEnemy(this.x, this.y);\n this.resetTimer();\n }\n }",
"function createNewAliens() {\n aliens.push(\n new Alien(width * random(0.05, 0.12), 150),\n new Alien(width * random(0.2, 0.3), 150),\n new Alien(width * random(0.35, 0.45), 150),\n new Alien(width * random(0.5, 0.6), 150),\n new Alien(width * random(0.7, 0.9), 150)\n );\n}",
"function criarFlappyBird(){\n \n const flappyBird = {\n /*Coordenadas para o objeto dentro do arquivo \"sprites.png\"*/\n sorceX: 0,\n sorceY: 0,\n\n /*Largura e Altura do objeto dentro do arquivo e da página*/\n itemWidth: 34,\n itemHeight: 24,\n\n /*Coordenadas para o objeto dentro de \"contexto\"*/\n coordX: 10,\n coordY: 50,\n\n /*Frame atual do objeto*/\n frameAtual: 0,\n\n /*Gravidade que o Flappy Bird sofrerá para queda, corresponde ao aumento de velocidade*/\n gravity: 0.25,\n\n /*Velocidade de queda do Flappy Bird*/\n speed: 0,\n\n /*Pulo do Flappy Bird*/\n pulo: 4.6,\n\n /*Movimentos realizados pelo Flappy Bird durante a animção de bater as asas, indicados pelo Y onde o se encontra o desenho de cada movimento*/\n moviBaterAsas:[\n {sorceY: 0}, //Asa para cima (padrão)\n {sorceY: 26}, //Asa no meio\n {sorceY: 52}, //Asa para baixo\n {sorceY: 26}, //Asa no meio\n ],\n\n /*Função que atualiza o frame do Flappy Bird*/\n atualizaFrame(){\n const intervaloFrames = 10;\n const intervaloChegou = frames % intervaloFrames === 0;\n \n if(intervaloChegou){\n const bsIncremento = 1;\n const incremento = bsIncremento + this.frameAtual;\n const bsRepeticao = this.moviBaterAsas.length;\n \n this.frameAtual = incremento % bsRepeticao;\n\n }\n },\n\n /*Função que faz o Flappy Bird pular*/\n pula(){ \n this.speed = - (this.pulo);\n \n },\n\n /*Função que atualiza a posição do objeto*/\n atualiza(){\n if(fazColisao(flappyBird, globais.chao)){\n console.info('Game Over');\n\n mudarTela(telas.GAMEOVER);\n \n return;\n }\n\n this.speed = this.speed + this.gravity;\n this.coordY = this.coordY + this.speed;\n },\n\n /*Função para desenhar o objeto*/\n desenha(){\n this.atualizaFrame();\n\n const {sorceY} = this.moviBaterAsas[this.frameAtual];\n \n contexto.drawImage(\n sprites,\n this.sorceX, sorceY,\n this.itemWidth, this.itemHeight,\n this.coordX, this.coordY,\n this.itemWidth, this.itemHeight\n );\n }\n }\n return flappyBird;\n}",
"function render() {\n background.removeAllChildren();\n\n // TODO: 2 - Part 2\n // this fills the background with a obnoxious yellow\n // you should modify this to suit your game\n var backgroundFill = draw.rect(canvasWidth, groundY, '#5d43a3');\n background.addChild(backgroundFill);\n \n // TODO: 3 - Add a moon and starfield //+cloud buddy\n \n var circle;\n for(var i = 0; i < 700; i++) {\n circle = draw.circle(1, '#faf67d', '#dec14e', 1);\n circle.x = canvasWidth * Math.random();\n circle.y = groundY * Math.random();\n background.addChild(circle);\n }\n \n var cursedMoon = draw.bitmap('img/cursedmoon.png');\n cursedMoon.x = 500;\n cursedMoon.y = 0;\n cursedMoon.scaleX = 0.4;\n cursedMoon.scaleY = 0.3;\n background.addChild(cursedMoon);\n \n var happyCloud = draw.bitmap('img/happycloudfriend.png');\n happyCloud.x = 0;\n happyCloud.y = 0; \n happyCloud.scaleX = 0.3;\n happyCloud.scaleY = 0.3;\n background.addChild(happyCloud);\n \n // TODO: 5 - Add buildings! Q: This is before TODO 4 for a reason! Why?\n //I added some other stuff besides the required buildings.\n \n ufo = draw.bitmap('img/pinkufo.png');\n ufo.x = 150;\n ufo.y = -100;\n ufo.scaleX = 0.8; \n ufo.scaleY = 0.8; \n background.addChild(ufo);\n \n for(var fNum = 0; fNum < 150; fNum++) {\n fish = draw.bitmap('img/flyingfish.png');\n fish.scaleX = 0.05;\n fish.scaleY = 0.05; //am very tired type type toopity toop toop tip\n fish.x = canvasWidth * Math.random(); //(translation: figure out how you're going to put this fishys in)\n fish.y = groundY * Math.random();\n background.addChild(fish);\n }\n\n //Required buildings below >>>\n for(var i = 0; i < 8; i++) {\n var buildingHeights = [300, 130, 190, 175, 250, 300, 190, 250];\n var buildingColors = ['Purple', 'Indigo', 'DarkBlue', 'Teal', 'Pink', 'Red', 'Purple', 'Indigo', 'DarkBlue', 'Teal'];\n var building = draw.rect(75, buildingHeights[i], buildingColors[i], 'LightGray', 1);\n building.x = 200 * i;\n building.y = groundY - buildingHeights[i];\n background.addChild(building);\n buildings.push(building);\n }\n //Required buildings above <<<\n \n alienHouse = draw.bitmap('img/alienhouse.png');\n alienHouse.x = 1100;\n alienHouse.y = groundY - 296;\n alienHouse.scaleX = 0.6; \n alienHouse.scaleY = 0.6;\n background.addChild(alienHouse);\n \n // TODO 4: Part 1 - Add a tree //+something else\n tree = draw.bitmap('img/weirdtree.png');\n tree.x = 930;\n tree.y = groundY - 265;\n tree.scaleX = 0.2;\n tree.scaleY = 0.2;\n background.addChild(tree);\n \n sign = draw.bitmap('img/pinkwoodsign.png');\n sign.x = 1450;\n sign.y = groundY - 395;\n sign.scaleX = 0.3;\n sign.scaleY = 0.3;\n background.addChild(sign);\n \n /*blueDuck = draw.bitmap('img/bigblueduck.png');\n blueDuck.x = 300;\n blueDuck.y = 265;\n blueDuck.scaleX = 0.4;\n blueDuck.scaleY = 0.4;\n background.addChild(blueDuck);*/\n \n } // end of render function - DO NOT DELETE",
"function createAmoeba() {\n for (var i = 0; i < 50; i++) {\n addShape('excited');\n }\n for (var i = 0; i < 40; i++) {\n addShape('neutral');\n }\n for (var i = 0; i < 10;i++) {\n addShape('calm');\n }\n setAnimation(amoeba, \"pulsate\", 15);\n}",
"function setupHUDelements(){\n\tfor (var i = 0; i < 10; i++){ //Set up bitmaps now so that all we do later is turn them on\n\t\thudElements.eggBitmaps[i] = new createjs.Bitmap(imageEgg);\n\t\thudElements.eggBitmaps[i].sourceRect = new createjs.Rectangle(0,0,20,30);\n\t\thudElements.eggBitmaps[i].x = (thecanvas.width - 20) - (15 * i);\n\t\thudElements.eggBitmaps[i].y = 245;\n\t\thudElements.eggBitmaps[i].scaleX = .5;\n\t\thudElements.eggBitmaps[i].scaleY = .5;\n\t}\n\t\n\thudElements.scoreText = new createjs.Text(\"score: \" + score, \"16px Arial\", \"#fff\");\n\thudElements.scoreText.x = 10;\n\thudElements.scoreText.y = 260;\n\tstage.addChild(hudElements.scoreText);\n\t\n\thudElements.speedText = new createjs.Text(\"speed: \", \"16px Arial\", \"#fff\");\n\thudElements.speedText.x = 150;\n\thudElements.speedText.y = 260;\n\tstage.addChild(hudElements.speedText);\n\t\n hudElements.speedBarG = new createjs.Graphics();\n\thudElements.speedBarG.beginFill(\"#d33\");\n\thudElements.speedBarG.rect(0,0,1, 20);\n\thudElements.speedBarShape = new createjs.Shape(hudElements.speedBarG);\n\thudElements.speedBarShape.x = 200;\n\thudElements.speedBarShape.y = 245;\n\t\n\tstage.addChild(hudElements.speedBarShape);\n\t\n}",
"function generateEnergies()\r\n{\r\n var position = 0;\r\n\r\n for (var i = 0; i < numOfEnergies; i++)\r\n {\r\n\r\n //add platform to array with dimensions\r\n energies[i] = new Energy(Math.random()*(width-energyRadius),position);\r\n\r\n //if platform is below screen add it to the top of the screen.... (I think lol)\r\n if (position < height - energyRadius)\r\n {\r\n position += ~~(height / numOfEnergies);\r\n }\r\n }\r\n}",
"initialise_ghosts() {\r\n\r\n // Set up the ghosts animaton sequences for the ghost movement\r\n for (var i = 0; i < this.data.ghosts.length; i ++) {\r\n for (var s=0; s<7; s++) {\r\n this.data.ghosts[i].set_animation_sequence(s, 4, 0, 3); \r\n } \r\n this.data.ghosts[i].set_sprite_status_alive();\r\n this.data.ghosts[i].set_attack_method(i); \r\n this.data.ghosts[i].animate_start(); \r\n }\r\n\r\n\r\n // Set each ghosts start position.\r\n //this.data.ghosts[0].set_position(12 * 24, 12*24 + 12);\r\n this.data.ghosts[0].set_position(16 * 24, 11 * 24 + 12); // red\r\n this.data.ghosts[1].set_position(16 * 24, 14 * 24 + 12); // pink\r\n this.data.ghosts[2].set_position(14 * 24, 14 * 24 + 12); // cyan\r\n this.data.ghosts[3].set_position(18 * 24, 14 * 24 + 12); // yellow\r\n\r\n // Set ghost target for escaping ghost house.\r\n this.data.ghosts[0].set_initial_target(372, 280); // red\r\n this.data.ghosts[1].set_initial_target(372, 280); // pink\r\n this.data.ghosts[2].set_initial_target(372, 280); // cyan\r\n this.data.ghosts[3].set_initial_target(372, 280); // yellow\r\n\r\n // default speed.\r\n var speed = 4, attack = 30, scatter = 7;\r\n var num_levels = this.game_levels.length;\r\n if (this.game_data.level < num_levels) {\r\n speed = this.game_levels[this.game_data.level].ghost_speed;\r\n attack = this.game_levels[this.game_data.level].attack;\r\n scatter = this.game_levels[this.game_data.level].scatter;\r\n }\r\n\r\n for (var i = 0; i < this.data.ghosts.length; i ++) {\r\n this.data.ghosts[i].set_home_position(16 * 24, 14 * 24 + 12);\r\n this.data.ghosts[i].initialise();\r\n this.data.ghosts[i].set_speed(speed);\r\n this.data.ghosts[i].set_attack_count(attack);\r\n this.data.ghosts[i].set_scatter_count(scatter);\r\n }\r\n\r\n this.data.ghosts[1].ghost.release_count=20;\r\n this.data.ghosts[2].ghost.release_count=30;\r\n this.data.ghosts[3].ghost.release_count=40;\r\n\r\n\r\n\r\n // Set scatter locations.\r\n this.data.ghosts[0].set_scatter_target(24*24, 0); // red\r\n this.data.ghosts[1].set_scatter_target(5*24, 0); // pink\r\n this.data.ghosts[2].set_scatter_target(24*24, 28*24) // cyan\r\n this.data.ghosts[3].set_scatter_target(3*24, 28*24) // yellow\r\n\r\n \r\n }",
"spawnFruit(x,y,velX,velY) {\r\n let random = Phaser.Math.Between(0, 9);\r\n let spawnPointX = x;\r\n let spawnPointY = y;\r\n let fruit = this.physics.add.sprite(spawnPointX, spawnPointY, 'fruit' + random).setInteractive();\r\n fruit.name = 'fruit';\r\n fruit.setScale(Phaser.Math.Between(2.0, 3.0));\r\n fruit.body.setVelocityX(Phaser.Math.Between(-velX + 500, -velX - 500));\r\n fruit.body.setVelocityY(Phaser.Math.Between(-velY + 500, -velY - 500));\r\n }",
"function LIFE_PLAYAGAIN_SETUP(evnt){\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tstageBlocker(false);\n\t\t\t\t\t\t\t\tstage.removeChild(GroundHolder);\t\n\t\t\t\t\t\t\t\tcharectorMC.visible=false;\n\t\t\t\t\t\t\t\tcreateGround();\n\t\t\t\t\t\t\t\tstageBlocker(true,\"blocker_mc\",0.9,\"Please wait...\",\"#000000\");\n\t\t\t\t\t\t\t\tresetAct();\n\t\t\t\t\t\t\t\ttotalRightAns=0;\n\t\t\t\t\t\t\t\ttotalWrongAns=0;\n\t\t\t\t\t\t\t\tstage.removeChild(lifePopUpContainer);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t}",
"createInitialEnemies() {\n this.enemies = [];\n this.checkEnemyCreation(1000);\n for (let i = 0; i < this.level.numEnemyRows - 1; ++i) this.checkEnemyCreation(2);\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 addMoreEnemies(){\n let enemyPosition = Math.random() * 184 + 50;\n enemyLocation.push(enemyPosition);\n enemy = new Enemy(0, enemyPosition, Math.random() * 256);\n allEnemies.push(enemy);\n}",
"function setupSpriteSheets(){\n \n var levelobjectimage;\n \tvar levelobjectframes;\n \tvar levelobjectanimations;\n \tvar levelobjectwidth;\n \tvar levelobjectheight;\n //Build spritesheets and animations for the level objects\n\tfor(var i = 0; i < leveldata.length; i++){\n\t\tswitch (leveldata[i].type){\n\t\t\tcase \"egg\" :\n\t\t\t\tlevelobjectimage = imageEgg;\n\t\t\t\tlevelobjectframes = {width:20, height:30, regX:0, regY:0};\n\t\t\t\tlevelobjectanimations = {\n\t\t\t\t\tdefaultanimation: [0, 15, \"defaultanimation\", .25]\n\t\t\t\t};\n\t\t\t\tlevelobjectwidth = 20;\n\t\t\t\tlevelobjectheight = 30;\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t}\n\t\t\n\t\tleveldata[i].spritesheet = new createjs.SpriteSheet({\n\t\t\timages: [levelobjectimage],\n\t\t\tframes: levelobjectframes,\n\t\t\tanimations: levelobjectanimations\n\t\t});\n\t\tleveldata[i].animation = new createjs.Sprite(leveldata[i].spritesheet);\n\t\tleveldata[i].animation.currentFrame = 0;\n\t\tleveldata[i].width = levelobjectwidth;\n\t\tleveldata[i].height = levelobjectheight;\n\t\t\n\t\tleveldata[i].resetX = leveldata[i].posX;\n\t}\n\t\n\t//Create waves\n\tvar waveSS = new createjs.SpriteSheet({\n\t\timages: [imageWave],\n\t\tframes: {width:480, height:10, regX:0, regY:0},\n\t\tanimations: {\n\t\t\tfastest: {\n\t\t\t\tframes: [0, 2, 4, 6, 8, 10],\n\t\t\t\tnext: \"fastest\",\n\t\t\t\tfrequency: 1\n\t\t\t},\n\t\t\tfaster: [0, 11, \"faster\",1],\n\t\t\tslower: [0, 11, \"slower\",2],\n\t\t\tslowest: [0, 11, \"slowest\",3]\n\t\t}\n\t});\n\twaveAnimation = new createjs.Sprite(waveSS);\n\twaveAnimation.gotoAndPlay(\"fastest\");\n\twaveAnimation.currentFrame = 0;\n\twaveAnimation.x = 0;\n\twaveAnimation.y = waterlineY-7;\n\tstage.addChild(waveAnimation);\n\t\n\t//Create sd sprite\n\tvar sharkduckSS = new createjs.SpriteSheet({\n\t\timages: [imageSharkduckAll],\n\t\tframes: {width:60, height:30, regX:0, regY:0},\n\t\tanimations: {\n\t\t\tswim: [0, 7, \"swim\", .25],\n\t\t\tswimfast: [0, 7, \"swimfast\", .5],\n\t\t\tfly: [8, 15, \"fly\", .25],\n\t\t\tflyfast: [8, 15, \"flyfast\", .5]\n\t\t}\n\t});\n\t\n\t//Make the animation\n\tsharkduckAnimation = new createjs.Sprite(sharkduckSS);\n sharkduckAnimation.gotoAndPlay(\"fly\"); \t//animate\n sharkduckAnimation.name = \"sharkduck\";\n sharkduckAnimation.currentFrame = 0;\n \n //Create container for sharkduck's animation and effects\n sharkduckContainer = new createjs.Container();\n sharkduckContainer.directionY = 1;\n sharkduckContainer.vY = 2;\n sharkduckContainer.x = 60;\n sharkduckContainer.y = waterlineY-7;\n sharkduckContainer.addChild(sharkduckAnimation);\n \n stage.addChild(sharkduckContainer);\n}",
"function loadBehaviours() {\n\n var elWidth = backgroundCanvas.width * 0.20;\n var elHeight = backgroundCanvas.height * 0.85;\n\n var turret = {};\n turret.image = new Image();\n turret.image.src = \"../Images/turret.png\";\n\n behaviours.turret = turret;\n\n plusImage = new Image();\n plusImage.src = \"../Images/plusImage.png\"\n\n}",
"function drawEnemies(){\r\n for (var _ = 0; _<4; _++){\r\n var x = Math.random()*(innerWidth-enemy_width);\r\n var y = -enemy_height; \r\n var width = enemy_width;\r\n var height = enemy_height;\r\n var speed = Math.random()*4.5;\r\n var __enemy = new Enemy(x, y, width, height, speed);\r\n _enemies.push(__enemy); \r\n }\r\n }",
"function spawnItems(top, left, x, y) {\r\n let spawnChanceItem = ~~(Math.random() * 3);\r\n\r\n if (spawnChanceItem == 1) {\r\n let whichItem = ~~(Math.random() * 2);\r\n let item = document.createElement(\"img\");\r\n\r\n switch (whichItem) {\r\n // Nombre de bombes\r\n case 0:\r\n item.src = \"./img\" + __dossier + \"/boostRayon.png\";\r\n item.id = \"boostRayonBombe_\" + parseInt(Math.random() * 1000);\r\n item.style.position = \"absolute\";\r\n item.style.left = left;\r\n item.style.top = top;\r\n item.style.width = \"50px\";\r\n item.style.height = \"50px\";\r\n item.style.zIndex = 11;\r\n item.traversable = true;\r\n item.X = x;\r\n item.Y = y;\r\n\r\n dynamique.appendChild(item);\r\n break;\r\n\r\n // Rayon\r\n case 1:\r\n item.src = \"./img\" + __dossier + \"/boostBombe.png\";\r\n item.id = \"boostNbrBombe_\" + parseInt(Math.random() * 1000);\r\n item.style.position = \"absolute\";\r\n item.style.left = left;\r\n item.style.top = top;\r\n item.style.width = \"50px\";\r\n item.style.height = \"50px\";\r\n item.style.zIndex = 11;\r\n item.traversable = true;\r\n item.X = x;\r\n item.Y = y;\r\n\r\n dynamique.appendChild(item);\r\n break;\r\n }\r\n\r\n }\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
loading more sequences for species multiselect | function loadMore() {
var jobid = $('#jobinfo').val();
var loadedSeqs = $('#speciessel > option').length - jsonOrgs["queryorgs"].length; // amount of species loaded, minus user-submitted species
//console.log(loadedSeqs);
$.ajax({
// Your server script to process the upload
contentType: 'application/json',
url: '/results/'+jobid+'/step2/orgs?start='+loadedSeqs,
async: true,
cache: false,
contentType: false,
processData: false,
success: moreSeqsSuccess,
error: moreSeqsError});
} | [
"selection() {\n // console.log(this.matingpool.length);\n let newAgents = [];\n for (let i = 0; i < this.agents.length; i++) {\n let parentAdna = random(this.matingpool).dna;\n let parentBdna = random(this.matingpool).dna;\n let childDna = parentAdna.crossOver(parentBdna);\n childDna.mutation();\n newAgents[i] = new Agent(width / 2, height, childDna);\n }\n this.agents = newAgents;\n this.matingpool.length = 0;\n }",
"mergeSequences () {\n let lastListElement;\n this.sequence.forEach((e, i) => {\n if (lastListElement && e.locationID === lastListElement.locationID && e.firstStart > lastListElement.lastEnd) {\n e.pushEvent(lastListElement.sequence);\n delete this.sequence[this.sequence.indexOf(lastListElement)];\n } else if(lastListElement && e.locationID === lastListElement.locationID) {\n lastListElement.createAlternativeSequence(e.sequence);\n delete this.sequence[this.sequence.indexOf(e)];\n e = lastListElement;\n }\n lastListElement = e;\n });\n this.updateTravelTime();\n }",
"addToSeqsBuild(type) {\n if (this.seqs.length === 0 || this.seqs[this.seqs.length - 1].type !== type) {\n this.seqs.push(new Seq(2, type));\n } else {\n this.seqs[this.seqs.length - 1].length++;\n }\n }",
"function loadArtistsInSelect(album) {\r\n // array per controllo nomi degli artisti da caricare nella select\r\n var arraySelect = [];\r\n // ciclo per caricare i nomi artisti nella select\r\n for (var i = 0; i < album.length; i++) {\r\n // controlla se il nome artista è già stato inserito nella select\r\n if (!arraySelect.includes(album[i].author)) {\r\n // aggiune il nome artista nell'array di controllo dei nomi\r\n arraySelect.push(album[i].author);\r\n // aggiunge il nome artista alla select\r\n $(\".select-artist\").append(\"<option value='\"+album[i].author+\"'>\"+album[i].author+\"</option>\");\r\n };\r\n };\r\n}",
"function loadPropertySelectData() {\n \"use strict\";\n var i;\n //depend on how many select tap.\n for (i = 0; i < getSelectID.length; i++) {\n createP_Option(getSelectID[i]);\n }\n}",
"addMultiChoice(title, properties) {\n const props = {\n ...properties,\n Choices: {\n results: properties.Choices,\n },\n };\n return this.add(title, 15, props);\n }",
"function flavour1(){\n flavourSelect=[\"flavour1\", 100];\n }",
"function loadHoseManufacturers() {\n $.get(\"/api/general/hoseManufacturers\"\n ).done(function (data) {\n var hoseManufacturer = $(\"#hoseManufacturer\");\n $.each(data.hoseManufacturers, function (index, element) {\n hoseManufacturers[element.id] = element;\n hoseManufacturer.append($(\"<option/>\", {text: element.name, value: element.id}))\n });\n loadHoseTypes();\n });\n}",
"function commonGroup() {\nvar counter, counter2, commonTaxId;\n//var selectedList = [];\nvar allGroup = {};\nvar groupList = [\"genus\",\"family\",\"order\",\"phyl\"];\n//var refOrgs = $.extend(jsonOrgs[\"reforgs\"], jsonOrgs[\"queryorgs\"]); //how to handle if only query orgs remaining?\n // for each taxonomical level, see what group each active option in species selection belongs to\n for (var group in groupList) {\n var groupId = groupList[group]+\"id\";\n var groupName = groupList[group]+\"name\";\n // iterate through all selected options\n $(\"#specieslist > .picked\").each(function(){\n var currId = $(this).val();\n var currGroup = $(this).data(groupId);\n var currName = $(this).data(groupName)\n if (currGroup != \"N/A\" && currName != \"N/A\") {\n allGroup[currGroup] = currName; //stores current option's group ID and name in allGroup; overwrites respective entry if already present\n //console.log(allGroup);\n }\n /*for (counter=0; counter<refOrgs.length; counter++) {\n var refInfo = refOrgs[counter];\n if (currId == refInfo.id) {\n //selectedList.push(refInfo);\n var currGroup = refInfo[groupId];\n var currName = refInfo[groupName];\n if (currGroup != \"N/A\" && currName != \"N/A\") {\n allGroup[currGroup] = currName;\n console.log(allGroup);\n }\n }\n }*/\n });\n // if all options belong to the same group at the level currently examined, return examined level, NCBI group ID and name of group\n if (Object.keys(allGroup).length == 1) {\n commonTaxId = Object.keys(allGroup);\n var commonInfo = [groupList[group], commonTaxId[0], allGroup[commonTaxId[0]]];\n //console.log(commonInfo);\n return commonInfo;\n } else if (groupList[group] == \"phyl\" && Object.keys(allGroup).length > 1){ // if the check has been run down to phylum level without finding one single group to which all options belong, return level (phylum), as well as NCBI ids and names of all phyla represented\n commonTaxId = Object.keys(allGroup);\n var multiGroups = [];\n for (var idkey in commonTaxId) {\n multiGroups.push(allGroup[commonTaxId[idkey]]);\n }\n var commonInfo = [groupList[group], commonTaxId, multiGroups];\n //console.log(commonInfo);\n return commonInfo\n }\n // if neither of these conditions has been satisfied, empty allGroup and repeat check at next higher taxonomical level\n allGroup = {};\n}\n}",
"function selectAllJob() {\n const selected_ids = floristjob.map((x) => x.order_item_id)\n setSelJob(selected_ids)\n }",
"spawnMore(){\n this.hitPoints =0;\n for(let i=0; i<levelData.sections+1; i++)\n this.spawnOne(i);\n }",
"renderSelects(optObject, multipleSelect){\n let selects = [];\n for(let key in optObject){\n let keyLength = optObject[key].length;\n let opts = [];\n opts.push(<option key=\"dummy\" value='unselected'>Select...</option>)\n for(let i = 0; i < keyLength; i++){\n opts.push(<option key={optObject[key][i][0]} value={optObject[key][i][0]}>{optObject[key][i][1]}</option>);\n }\n if(!multipleSelect){\n selects.push(<div key={key} className=\"col-xs-12\"><label>{key}</label><select size={keyLength} id={key} onChange={() => this.updateSourceSelection(key)} className='selectpicker sourcePicker form-control'>{opts}</select></div>);\n }\n else {\n selects.push(<div key={key} className=\"col-xs-12\"><label>{key}</label><select size={keyLength + 1} id={key} onChange={() => this.updateSourceSelection(key)} className='selectpicker sourcePicker form-control' multiple>{opts}</select></div>);\n }\n }\n return selects;\n }",
"function getSpec(){\n specNum = Math.floor(Math.random()*speciesA.length);\n \n }",
"function drumSeqOn() {\n console.log(\"playing sequencer...\");\n let index = 0;\n Tone.Transport.scheduleRepeat(repeat, '8n');\n Tone.Transport.bpm.value = 133;\n\n function repeat() {\n let step = index % 8;\n allTheKits[loadedKit].forEach(drum => {\n const drumPlayer = new Tone.Player(drum.src)\n .connect(volume)\n .chain(reverb, dist, delay);\n const row = document.getElementById(`${drum.name}Row`);\n let iCheck = row.querySelector(`input:nth-child(${step + 1})`);\n if (iCheck.checked) {\n drumPlayer.autostart = true;\n }\n });\n index++;\n }\n playButtonInit = true;\n}",
"function randomSequence(){\n\t\t\tvar sequence = [];\n\t\t\tfor(var i = 0; i < 20; i++){\n\t\t\t\tsequence.push(Math.floor((Math.random()*100)%4)+1);\n\t\t\t}\n\t\t\treturn sequence;\n\t\t}",
"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 }",
"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 reshowAllGuiGenes() {\n updateGuiGenes();\n}",
"function prefetch() {\n\tfat.search(\"id='\" + window.localStorage.getItem(\"task_id\") + \"'\", \"*\", function(results) {\n\t\tif (results.length > 0) {\n\t\t\tvar para = new Array();\n\t\t\tvar para_m = new Array();\n\t\t\tpara[0] = results.item(0).para1;\n\t\t\tpara_m[0] = results.item(0).para1_m;\n\t\t\tpara[1] = results.item(0).para2;\n\t\t\tpara_m[1] = results.item(0).para2_m;\n\t\t\tpara[2] = results.item(0).para3;\n\t\t\tpara_m[2] = results.item(0).para3_m;\n\t\t\tpara[3] = results.item(0).para4;\n\t\t\tpara_m[3] = results.item(0).para4_m;\n\t\t\tpara[4] = results.item(0).para5;\n\t\t\tpara_m[4] = results.item(0).para5_m;\n\t\t\tpara[5] = results.item(0).para6;\n\t\t\tpara_m[5] = results.item(0).para6_m;\n\t\t\tpara[6] = results.item(0).para7;\n\t\t\tpara_m[6] = results.item(0).para7_m;\n\t\t\tpara[7] = results.item(0).para8;\n\t\t\tpara_m[7] = results.item(0).para8_m;\n\t\t\tpara[8] = results.item(0).para9;\n\t\t\tpara_m[8] = results.item(0).para9_m;\n\t\t\tpara[9] = results.item(0).para10;\n\t\t\tpara_m[9] = results.item(0).para10_m;\n\n\t\t\tfor ( var i = 0; i < 10; i++) {\n\t\t\t\tif (para[i] != \"-\") {\n\t\t\t\t\tvar name1 = para[i].replace(/[^a-zA-Z 0-9]+/g, '').replace(/\\s+/g, \"\");\n\t\t\t\t\tvar name = para[i];\n\t\t\t\t\tdocument.getElementById('sel').innerHTML += \"<tr id='\" + name1 + \"' style='height:45px;'>\" + \"<td ontouchstart='js:if(confirm(\\\"Do you want to remove this parameter?\\\")){ var elem = $(\\\"#\" + name1 + \"\\\").remove();tot();}'><img src='../images/list-remove.png' width='34' height='34'></td>\" + \"<td style='font-size:20px'>\" + name + \"</td>\" + \"<td ontouchend='dec(\\\"#\" + name1 + \"_val\\\");' style='width:70px;text-align:left;'><img src='../images/sub.png' width='30' style='background-color: #00c8c8; border-radius: 40px'></td>\" + \"<td><input type='number' value='\" + para_m[i] + \"' id='\" + name1 + \"_val' onkeyup='validate(\\\"\" + name1 + \"_val\\\");'></td>\" + \"<td ontouchend='inc(\\\"#\" + name1 + \"_val\\\");' style='width:70px;text-align:right;'><img src='../images/new.png' width='30' style='background-color: #00c8c8; border-radius: 40px'></td></tr>\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tmax_id = parseInt(results.item(0).name);\n\t\t\tid = results.item(0).id;\n\t\t\tdocument.getElementById('proc').value = results.item(0).proc;\n\t\t\tif (results.item(0).comment == \"true\")\n\t\t\t\tdocument.getElementById('comment').checked = true;\n\t\t\ttask_fetch(results.item(0).task);\n\t\t\ttopic_fetch(results.item(0).topic);\n\t\t\ttot();\n\t\t}\n\t});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asynchronous function that can be used to set the snowflake_support flag on a given warehouse. | function setWhSnowflakeSupportFlag(
conn, warehouseId, snowflakeSupportFlag, callback)
{
var sqlText = util.format(
'select system$set_wh_snowflake_support_flag(%s, %s);',
warehouseId, snowflakeSupportFlag);
conn.execute(
{
sqlText: sqlText,
complete: function (err, statement, rows)
{
assert.ok(!err);
callback();
}
});
} | [
"function setMssqlHandler(){\n\treturn new Promise( function(resolve, reject){\n\t\ttry{\n\t\t\tif( __mssqlHandlerUsage ){\n\n\t\t\t\tglobal.mssqlHandler = require( __mssqlHandler );\n\n\t\t\t\tmssqlHandler.getPool()\n\t\t\t\t.then( function(_pool){\n\t\t\t\t\tglobal.pool = _pool;\n\t\t\t\t\tpool.dbms = \"mssql\";\n\t\t\t\t\tglobal.mssqlPool = _pool;\n\n\t\t\t\t\tmssqlHandler.getQueries()\n\t\t\t\t\t.then( function(_queries){\n\t\t\t\t\t\tglobal.queriesXML = _queries;\n\t\t\t\t\t\tglobal.mssqlQueriesXML = _queries;\n\n\t\t\t\t\t\tresolve( {\"message\" : \"Set MsSql Handler\"} );\n\t\t\t\t\t} )\n\t\t\t\t\t.catch( function(__err){\n\t\t\t\t\t\tconsole.log( \"\\x1b[31m%s\\x1b[0m\", \"[summer-mvc core]\", \"[exoress_was_setter.js]\", __err );\n\t\t\t\t\t\treject( {\"message\" : \"Setting MsSql Failed\", \"err\" : __err} )\n\t\t\t\t\t} );\n\t\t\t\t} )\n\t\t\t\t.catch( function(_err){\n\t\t\t\t\tconsole.log( \"\\x1b[31m%s\\x1b[0m\", \"[summer-mvc core]\", \"[exoress_was_setter.js]\", _err );\n\t\t\t\t\treject( {\"message\" : \"Setting MsSql Failed\", \"err\" : _err} );\n\t\t\t\t} );\n\t\t\t} else{\n\t\t\t\tresolve( {\"message\" : \"Mssql handler doesn't set to use.\"} );\n\t\t\t}\n\t\t} catch( err ){\n\t\t\tconsole.log( \"\\x1b[31m%s\\x1b[0m\", \"[summer-mvc core]\", \"[exoress_was_setter.js]\", err );\n\t\t\treject( {\"message\" : \"Setting MsSql Failed\", \"err\" : err} );\n\t\t}\n\t} );\n}",
"function monitorSupportsFeature(feature) {\n return __awaiter(this, void 0, void 0, function* () {\n const localStore = state_1.getStore();\n const monitorRef = getMonitor();\n if (!monitorRef) {\n return localStore.settings.featureSupport[feature];\n }\n if (localStore.settings.featureSupport[feature] === undefined) {\n const req = new resproto.SupportsFeatureRequest();\n req.setId(feature);\n const result = yield new Promise((resolve, reject) => {\n monitorRef.supportsFeature(req, (err, resp) => {\n // Back-compat case - if the monitor doesn't let us ask if it supports a feature, it doesn't support\n // secrets.\n if (err && err.code === grpc.status.UNIMPLEMENTED) {\n return resolve(false);\n }\n if (err) {\n return reject(err);\n }\n return resolve(resp.getHassupport());\n });\n });\n localStore.settings.featureSupport[feature] = result;\n }\n return localStore.settings.featureSupport[feature];\n });\n}",
"function enableVQH() {\n enableCheckBox({\n enableCheckBox: 'edit_hasvoicemail',\n enableList: ['edit_vmsecret']\n }, doc);\n enableCheckBox({\n enableCheckBox: 'edit_enable_qualify',\n enableList: ['edit_qualifyfreq']\n }, doc);\n disableCheckBox({\n enableCheckBox: 'edit_enablehotdesk',\n enableList: ['edit_authid']\n }, doc);\n enableCheckBox({\n enableCheckBox: 'edit_en_ringboth',\n enableList: ['edit_external_number', 'edit_ringboth_timetype']\n }, doc);\n enableCheckBox({\n enableCheckBox: 'edit_en_hotline',\n enableList: ['edit_hotline_number', 'edit_hotline_type']\n }, doc);\n enableCheckBox({\n enableCheckBox: 'edit_dnd',\n enableList: ['edit_dnd_timetype']\n }, doc);\n}",
"function triggerKowalksiAlert(device) {\r\n deviceMasterList.forEach((entry)=>{\r\n entry.device.state_lock = true;\r\n if(entry.device.id != device.device.id){\r\n entry.device.state = config.state.passive_kowalski;\r\n }\r\n });\r\n setTimeout(disarmKowalksiAlert, 5000);\r\n}",
"async startOrCloseTicket(req, res, next) {\n try {\n const {\n params,\n models: { Support },\n } = req;\n var { ticket, status } = params;\n let {\n info: { _id },\n role,\n } = req.user;\n let supportTicket = await Support.findById(ticket);\n if (!supportTicket) {\n throw 'No support ticket found with this ID';\n }\n supportTicket.status = status;\n if (status == 'active') {\n supportTicket.assigned = _id;\n }\n await supportTicket.save();\n return successResponse(\n res,\n 'Ticket status has been updated',\n 201,\n supportTicket\n );\n } catch (error) {\n return errorHandler(error, req, res, next);\n }\n }",
"function doActivateService(service, connection, pCallback) {\n if (!service.id) return pCallback(true, null); \n async.waterfall([\n function(callback) {\n if (service.variations && service.variations.length > 0) {\n var vids = service.variations.split(\",\");\n var updateData = [];\n vids.forEach(vv => {\n updateData.push({\n id: parseInt(vv),\n 'visible': service.status? true: false\n });\n })\n \n MyWooCommerce.post('products/' + service.swId + '/variations/batch', { update: updateData }, function(err, data, res) {\n if (err || res.message) callback(null, true, {status: \"error\", message: \"Failed updating service\"});\n else {\n var resp = JSON.parse(res);\n var allVariations = [];\n if (resp.update && resp.update.length>0) {\n resp.update.forEach(ii=> {\n //if ( ii.visible && allVariations.indexOf(ii.id) < 0)\n allVariations.push(ii.id);\n });\n }\n service.variations = allVariations.join(\",\");\n callback(null, false, null);\n }\n });\n\n } else {\n callback(null, false, null);\n } \n },\n // update service on wp\n function(error, msg, callback) {\n if (error) callback(true, msg);\n else {\n async.waterfall([\n function(callback_1) {\n var data = {\n status: service.status? 'publish': 'draft',\n 'catalog_visibility': service.status? 'visible': 'hidden' \n }\n\n MyWooCommerce.post(`products/${service.swId}`, data, function(err, data, res) {\n if (err) callback(null, true, null);\n else {\n var resp = JSON.parse(res);\n if (resp.message) callback_1(null, true, resp.message);\n else callback_1(null, false, resp);\n }\n });\n },\n function(error, msg, callback_1) {\n if (error) callback_1(null, true, msg);\n else {\n connection.query({sql: \"update promos set status=? where service_id=?\"},\n [service.status, service.id], function(error, results) {\n if (error) callback_1(null, true, {status: \"error\", message: \"Updating error\"});\n else if(results.affectedRows>0) {\n callback_1(null, false, results);\n } else callback_1(null, false, null);\n })\n }\n },\n function(error, msg, callback_1) {\n if (error) callback_1(true, msg);\n else {\n connection.query({sql: \"update services set status=? where id=?\"},\n [service.status, service.id], function(error, results) {\n if (error) callback_1(true, {status: \"error\", message: \"Updating error\"});\n else if(results.affectedRows>0) {\n callback_1(false, results);\n } else callback_1(true, {status: \"error\", message: \"Updating error\"});\n })\n }\n }\n ], function(error, result) {\n callback(error, result);\n })\n }\n } \n ], function(error, result) {\n if (error) pCallback(true, result);\n else pCallback(false, {status: \"success\", message: \"successful\"});\n })\n}",
"function markCheckboxes() {\n let check = (id) => {\n if (settings[id] == 'true') {\n $('#' + id).prop('checked', true);\n }\n }\n check('hide-hr-value');\n check('hide-upgrade-log');\n check('value-with-quantity');\n check('only-show-equipped');\n }",
"_enableExtensibility() {\n\t\t\tvar aExtensionData;\n\t\t\tABAPAccess.getExtensionData = function(sServiceUri, sEntityTypeName, sEntitySetName) {\n\t\t\t\taExtensionData = [{ businessContext: `${sEntityTypeName} EntityTypeContext`, description: \"Other BusinessContext description\" }, { businessContext: `${sEntitySetName} EntitySetContext`, description: \"Some BusinessContext description\"}];\n\t\t\t\treturn Promise.resolve({\n\t\t\t\t\textensionData: aExtensionData,\n\t\t\t\t\tentityType: sEntityTypeName,\n\t\t\t\t\tserviceVersion: \"some dummy ServiceVersion 0.0.1\",\n\t\t\t\t\tserviceName: sServiceUri\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tABAPExtensibilityVariant.prototype.getNavigationUri = function() {\n\t\t\t\treturn Promise.resolve(\"./extensibilityTool.html\");\n\t\t\t};\n\n\t\t\tvar oUshellContainer = ObjectPath.get(\"sap.ushell.Container\");\n\t\t\tif (oUshellContainer) {\n\t\t\t\tABAPAccess.isExtensibilityEnabled = function() {\n\t\t\t\t\treturn Promise.resolve(true);\n\t\t\t\t};\n\t\t\t\tsap.ushell.Container = Object.assign({}, sap.ushell.Container, {\n\t\t\t\t\tgetLogonSystem() {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tgetName() {\n\t\t\t\t\t\t\t\treturn \"ABC\";\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tgetClient() {\n\t\t\t\t\t\t\t\treturn \"123\";\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tisTrial() {\n\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\n\t\t\toCore.getEventBus().subscribe(\"sap.ui.core.UnrecoverableClientStateCorruption\", \"RequestReload\", function() {\n\t\t\t\tMessageBox.warning(\"Service Outdated, Please restart the UI - In real world other dialog will come up, that can restart the UI\");\n\t\t\t});\n\t\t}",
"async setExistsInKG() {\n if (!this.dcid || this.existsInKG) {\n return;\n }\n this.existsInKG = await doesExistsInKG(this.dcid);\n }",
"function markAddToAPI(checked) {\r\n\r\n CurFuncObj.createAPI = checked;\r\n\r\n}",
"function setInAnalysisQueue(systemId, callback) {\n var params = {\n Key: {\n SystemId: {\n S: systemId\n }\n },\n TableName: tableName,\n Expected: {\n SystemId: {\n Exists: true,\n Value: {\n S: systemId\n }\n }\n },\n AttributeUpdates: {\n InQueue: {\n Action: \"PUT\",\n Value: {\n S: 'Y'\n }\n }\n }\n };\n db.updateItem(params, callback);\n}",
"asyncUpdateOptionsDisabledState() {\n Promise.resolve().then(() => this.updateOptionsDisabledState());\n }",
"async function changeHandState() {\n isHandRaised.toggleState();\n isHandRaised.sendAttendeeHandState();\n handleParticipantUpdate();\n document.getElementById(\"hand-img\").classList.toggle(\"hidden\");\n document.querySelector(\".raise-hand-button\").innerText = `${\n attendee.handRaised ? \"Lower Hand\" : \"Raise Hand\"\n }`;\n document.querySelector(\".hand-state\").innerText = `${\n attendee.handRaised ? \"Your hand is raised 🙋\" : \"Your hand is down 💁\"\n }`;\n\n // Turn on video if hand is raised\n if (attendee.handRaised && !callFrame.participants().local.video) {\n callFrame.setLocalVideo(!callFrame.participants().local.video);\n } \n}",
"async _merchantSettingChange(event, html) {\n event.preventDefault();\n console.log(\"Loot Sheet | Merchant settings changed\");\n\n const moduleNamespace = \"lootsheetnpcpf2e\";\n const expectedKeys = [\"rolltable\", \"shopQty\", \"itemQty\"];\n\n let targetKey = event.target.name.split('.')[3];\n\n if (expectedKeys.indexOf(targetKey) === -1) {\n console.log(`Loot Sheet | Error changing stettings for \"${targetKey}\".`);\n return ui.notifications.error(`Error changing stettings for \"${targetKey}\".`);\n }\n\n if (event.target.value) {\n await this.actor.setFlag(moduleNamespace, targetKey, event.target.value);\n } else {\n await this.actor.unsetFlag(moduleNamespace, targetKey, event.target.value);\n }\n }",
"async function okCreateShift() {\n if (userRole === \"Admin\") {\n try {\n let thisShift = undefined;\n let newStart = startTimeInput.value;\n let newEnd = endTimeInput.value;\n let startDate = new Date(SelectedDate + \"T\" + newStart + \"Z\");\n let endDate = new Date(SelectedDate + \"T\" + newEnd + \"Z\");\n let newEmployee = undefined;\n let update = createUpdate(thisShift, startDate, endDate, newEmployee);\n updates.push(update);\n ShiftModalCloseAction();\n saveButtonEnable();\n alert(\"Vagten er nu oprettet! Tryk gem for at tilføje vagten\");\n } catch (e) {\n console.log(e.name + \": \" + e.message);\n }\n }\n}",
"checkCloudant() {\n const dbDefinitions = this.config[\"db-definitions\"];\n return new Promise((resolve, reject) => {\n try {\n console.log(\"Checking cloudant...\");\n let dbCheckPromises = [];\n for (const dbName of Object.keys(dbDefinitions)) {\n const dbConfig = dbDefinitions[dbName];\n dbCheckPromises.push(this.checkDatabase(this.connection, dbName, dbConfig));\n }\n console.log(\"Number of databases in configuration that will be checked : \" + dbCheckPromises.length);\n Promise.all(dbCheckPromises).then(function(dbResult) {\n console.log(\"Done checking cloudant...\");\n resolve(dbResult);\n }).catch((err) => {\n console.log(\"Error checking cloudant : \" + err);\n reject(err);\n });\n } catch (err) {\n console.log(\"Error checking cloudant : \" + err);\n reject(err);\n }\n });\n }",
"async function setupCircuits() {\n // do all the trusted setups needed\n // first, we need to find the circuits we're going to do the setup on\n const circuitsToSetup = await (\n await walk(config.CIRCUITS_HOME)\n ).filter(c => (config.USE_STUBS ? c.includes('_stub') : !c.includes('_stub')));\n // then we'll get all of the vks (some may not exist but we'll handle that in\n // a moments). We'll grab promises and then resolve them after the loop.\n const resp = [];\n\n for (const circuit of circuitsToSetup) {\n logger.debug(`checking for existing setup for ${circuit}`);\n const folderpath = circuit.slice(0, -4); // remove the .zok extension\n resp.push(\n axios.get(`${config.PROTOCOL}${config.ZOKRATES_WORKER_HOST}/vk`, {\n params: { folderpath },\n }),\n );\n }\n const vks = (await Promise.all(resp)).map(r => r.data.vk);\n // some or all of the vks will be undefined, so we need to run a trusted setup\n // on these\n for (let i = 0; i < vks.length; i++) {\n const circuit = circuitsToSetup[i];\n if (!vks[i] || config.ALWAYS_DO_TRUSTED_SETUP) {\n // we don't have an existing vk so let's generate one (TODO in parallel)\n try {\n logger.info(\n `no existing verification key. Fear not, I will make a new one: calling generate keys on ${circuit}`,\n );\n // eslint-disable-next-line no-await-in-loop\n const res2 = await axios.post(\n `${config.PROTOCOL}${config.ZOKRATES_WORKER_HOST}/generate-keys`,\n {\n filepath: circuit,\n curve: config.CURVE,\n provingScheme: config.PROVING_SCHEME,\n backend: config.BACKEND,\n },\n );\n vks[i] = res2.data.vk;\n } catch (err) {\n logger.error(err);\n }\n } else logger.info(`${circuit} verification key exists: trusted setup skipped`);\n }\n\n const keyRegistry = await waitForContract('Challenges');\n const keyRegistryAddress = await getContractAddress('Challenges');\n\n // we should register the vk now\n for (let i = 0; i < vks.length; i++) {\n const circuit = circuitsToSetup[i];\n const vk = vks[i];\n logger.info(`Registering verification key for ${circuit}`);\n try {\n delete vk.raw; // long and not needed\n logger.silly('vk:', vk);\n const vkArray = Object.values(vk).flat(Infinity); // flatten the Vk array of arrays because that's how Key_registry.sol likes it.\n const folderpath = circuit.slice(0, -4); // remove the .zok extension\n\n let tx;\n if (config.USE_STUBS) {\n tx = keyRegistry.methods.registerVerificationKey(\n vkArray,\n config.VK_IDS[folderpath.slice(0, -5)],\n );\n } else {\n tx = keyRegistry.methods.registerVerificationKey(vkArray, config.VK_IDS[folderpath]);\n }\n\n // when deploying on infura - do serial tx execution to avoid nonce issue\n if (config.USE_INFURA) {\n await Web3.submitRawTransaction(await tx.encodeABI(), keyRegistryAddress);\n } else {\n await tx.send();\n }\n } catch (err) {\n logger.error(err);\n throw new Error(err);\n }\n }\n}",
"function setSWFIsReady() {\r\n\t\t// record that the SWF has registered it's functions (i.e. that JavaScript\r\n\t\t// can safely call the ActionScript functions)\r\n\t\tswfReady = true;\r\n\t\tconsole.log(\"swfReady\");console.log(swfReady);\r\n\t\tupdateStatus();\r\n\t}",
"async function waitForZokrates() {\n logger.info('checking for zokrates_worker');\n try {\n while (\n // eslint-disable-next-line no-await-in-loop\n (await axios.get(`${config.PROTOCOL}${config.ZOKRATES_WORKER_HOST}/healthcheck`)).status !==\n 200\n ) {\n logger.warn(\n `No response from zokratesworker yet. That's ok. We'll wait three seconds and try again...`,\n );\n // eslint-disable-next-line no-await-in-loop\n await new Promise(resolve => setTimeout(resolve, 3000));\n }\n } catch (err) {\n logger.error(err);\n process.exit(1);\n }\n logger.info('zokrates_worker reports that it is healthy');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called when a bid is rejected | function bidRejected(bid) {
importer.node.account.release(bid.getValue());
} | [
"function stateRejected() {\n var FlowState = w2ui.propertyForm.record.FlowState;\n var si = getCurrentStateInfo();\n if (si == null) {\n console.log('Could not determine the current stateInfo object');\n return;\n }\n\n si.Reason = \"\";\n var x = document.getElementById(\"smRejectReason\");\n if (x != null) {\n si.Reason = x.value;\n }\n if (si.Reason.length < 2) {\n w2ui.stateChangeForm.error('ERROR: You must supply a reason');\n return;\n }\n finishStateChange(si,\"reject\");\n}",
"function bidAccepted(bid, contract) {\n console.log('Bid accepted');\n importer.node.account.complete(bid.getValue());\n importer.contracts.push(contract);\n contract.paid(bid.getValue());\n }",
"function RejectRequest(requestID) {\n try {\n // Xoa yeu cau\n bookshelf.XoaYeuCau(requestID);\n return true;\n } catch (ee) {\n console.log(ee)\n return false;\n }\n}",
"rejectTransaction() {\n stateTransition(this, this.state.onRejectTransaction);\n }",
"function rejected(x){\n\t if(async) context = cat(future.context, cat(asyncContext, context));\n\t settle(action.rejected(x));\n\t }",
"function denySell(id, partner_id, element) {\r\r\n if(jQuery('#confirmation-popup').children().length == 1) {\r\r\n jQuery('#confirmation-popup').remove();\r\r\n location.reload(true);\r\r\n } else {\r\r\n jQuery(element).parents('.confirmation').remove();\r\r\n }\r\r\n jQuery.post(\r\r\n swapchic_ajax.ajax_url,\r\r\n {\r\r\n 'action': 'ajaxDenySell',\r\r\n 'post_id': id,\r\r\n 'partner_id': partner_id\r\r\n },\r\r\n function(response){\r\r\n // console.log(response);\r\r\n }\r\r\n );\r\r\n}",
"static reject(entryId){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\treturn new kaltura.RequestBuilder('baseentry', 'reject', kparams);\n\t}",
"onHoneybadgerFailure(err) {\n if (__DEVELOPMENT__) {\n ythrow(err);\n } else {\n this.return500();\n serverLog(\"HONEYBADGER ERROR: could not report error to honeybadger.\");\n console.log(err); // eslint-disable-line no-console\n }\n }",
"function listenForCancel() {\n findCancelButton().addEventListener('click', function() {\n if (queueTicket) {\n queueTicket.cancel();\n } else {\n throw new Error('Cannot cancel queuing while not queued');\n }\n });\n}",
"function updateBidResult(result) {\n if (result === 'fail') {\n var errmsg = 'bid18xxSubmit: updtBid.php failed.\\n';\n errmsg += 'Please contact the BID18xx webmaster.\\n';\n errmsg += BID18.adminName + '\\n';\n errmsg += BID18.adminEmail;\n alert(errmsg);\n return;\n }\n if (result === 'collision') { // Back out and perhaps try again\n $('.allforms').hide();\n $('#collform').show();\n return;\n }\n if (result !== 'success') {\n // Something is definitly wrong in the code.\n var nerrmsg = 'bid18xxSubmit: Invalid return code from updtBid.php.\\n';\n nerrmsg += 'Please contact the BID18xx webmaster.\\n';\n nerrmsg += BID18.adminName + '\\n';\n nerrmsg += BID18.adminEmail;\n alert(nerrmsg);\n return;\n }\n\n// Check if all bids are done.\n if (BID18.bid.status === \"Done\") {\n bidDone();\n// send result emails \n $(\"#bid\").append(\"<br>Bid result emails will now be sent to all players.\");\n BID18.mailError = false;\n BID18.firstReply = true;\n var cString, pl, pLine;\n for (i=0; i<BID18.bid.numbPlayers; i++) {\n pl = i+1;\n cString = 'bidid=' + BID18.input.bidid;\n cString += '&playerid=' + pl;\n $.post(\"php/emailBidResult.php\", cString, emailResultCallback);\n pLine = \"<br>Prepairing bid result email for player \";\n pLine += BID18.bid.players[i].name; \n $(\"#bid\").append(pLine);\n }\n } else {\n window.location.assign(\"bid18xxGoodby.html?msgtype=2\");\n }\n}",
"emitBidAwarded(){\n\t\t\tthis.$emit('bid-awarded');\n\t\t}",
"function adBlockNotDetected() {\n }",
"bailOutActivate() {\n messaging.peerSocket.send({\n type: \"event\",\n event: \"bailout\"\n });\n }",
"function receive_close() {\n set_ui_state(UI_STATES.FUNDS_DEPLETED);\n set_channel_state(CHANNEL_STATES.RECEIVED_CLOSE);\n cancel_payments();\n}",
"handleBanTimeouts() {\n var timeout = Date.now() - this.options.banTimeout;\n Object.keys(this.bans).forEach(key => {\n if (this.bans[key].timestamp < timeout) {\n this.logger.info('Releasing IP ban for %s.', key);\n delete this.bans[key];\n }\n });\n }",
"function processBid() {\n var bidin = $(\"input[name='bid']:checked\").val(); // bid that was selected.\n var playerIndex = BID18.input.playerid - 1;\n BID18.bid.players[playerIndex].bid = bidin;\n BID18.bid.players[playerIndex].status = 'Done';\n // Check if all players have submitted a bid.\n var allDone = 'Yes';\n $.each(BID18.bid.players,function(index,playerInfo) {\n if (playerInfo.status === \"Pending\") {\n allDone = 'No';\n }\n }); // end of each\n if (allDone === \"Yes\") {\n BID18.bid.status = \"Done\";\n }\n var dataString = JSON.stringify(BID18.bid);\n var cString = \"bidid=\" + BID18.input.bidid;\n cString += \"&bid=\" + dataString;\n $.post(\"php/updtBid.php\", cString, updateBidResult);\n}",
"function OnFailure(sender, args) {\n alert(\"Error occurred at UpdateListItem. See console for details.\");\n console.log('Request failed at UpdateListItem :' + args.get_message() + '\\n' + args.get_stackTrace());\n }",
"markDead()\n\t{\n\t\tif ( this.m_bAlive )\n\t\t{\n\t\t\tthis.m_bAlive = false;\n\t\t\tthis.emit( 'peer_failed' );\n\t\t}\n\t}",
"function transmitFailure( distillation, response ) {\n\n\t\t//-- Error find the submitDistill endpoint\n\t\tif ( response.status == 404 ) {\n\t\t\tprocessFailure( distillation, \"delivery failure - API unreachable (404)\" );\n\t\t}\n\n\t\t//-- Error reaching the server\n\t\telse if ( response.status == 0 ) {\n\t\t\tprocessFailure( distillation, \"delivery failure - Server unreachable (OOO)\" );\n\t\t}\n\n\t\t//-- An unknown error has occurred\n\t\telse {\n\t\t\tprocessFailure( distillation, \"delivery failure - Cause unknown (\" + response.status + \")\" );\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build xml string from the ControlManifest's json object | getManifestXmlString() {
const jsonToXmlbuilder = new Builder();
const xml = jsonToXmlbuilder.buildObject(this.data);
return xml;
} | [
"function createManifest () {\n fs.writeFile(manifestPath + 'manifest.json', JSON.stringify(manifest))\n}",
"function createMeta() {\n\t\ttry {\n\t\t\tvar manifestData = chrome.runtime.getManifest();\n\t\t\tvar obj = {\n\t\t\t\tversion: manifestData.version, // set in manifest\n\t\t\t\tinstall: {\n\t\t\t\t\tdate: moment().format(),\n\t\t\t\t\tprompts: 0 // number prompts given to user\n\t\t\t\t},\n\t\t\t\tuserLoggedIn: false,\n\t\t\t\tuserOnline: navigator.onLine,\n\t\t\t\tserver: {\n\t\t\t\t\tlastChecked: 0,\n\t\t\t\t\tonline: 1,\n\t\t\t\t\tresponseMillis: -1\n\t\t\t\t},\n\t\t\t\tcurrentAPI: \"production\", // default to production on new installation\n\t\t\t\tapi: T.options.production.api,\n\t\t\t\twebsite: T.options.production.website,\n\t\t\t\tbrowser: Environment.getBrowserName(),\n\t\t\t\tlocation: {}\n\t\t\t};\n\n\t\t\treturn obj;\n\t\t} catch (err) {\n\t\t\tconsole.error(err);\n\t\t}\n\t}",
"function convertFromBase(manifestInfo, callback) {\r\n\r\n//check to make sure you have a manifest before you try to transform it\r\n if (!manifestInfo || !manifestInfo.content) {\r\n return Q.reject(new Error('Manifest content is empty or not initialized.')).nodeify(callback);\r\n }\r\n \r\n //good to have a local ref to work with. You'll see that you work work off of manifestInfo.content in platform.js \r\n var originalManifest = manifestInfo.content;\r\n\r\n\r\n//here we are going to convert the W3C manifest to our strawman app\r\n//note that you might need to re-map some values, or add some new ones\r\n//if your platform manifest is XML instead of JSON, you might want to read from a manifest template file, (or string\r\n// depending on how big the XML is) and insert your W3C manifest values\r\n var manifest = {\r\n 'manifest_version': 2,\r\n 'name': originalManifest.name || 'PWABuilder Rockin App',\r\n 'scope': originalManifest.scope || '/',\r\n 'display': originalManifest.display || 'browser',\r\n 'start_url': originalManifest.start_url, \r\n 'short_name': originalManifest.short_name,\r\n 'theme_color': originalManifest.theme_color || 'red'\r\n };\r\n\r\n // Here's a pretty standard practice of mapping the icons from the W3C to the manifest object you pass back to platform.js\r\n //if you don't use images in your platform, delete this stuff\r\n if (originalManifest.icons && originalManifest.icons.length) {\r\n var icons = {};\r\n for (var i = 0; i < originalManifest.icons.length; i++) {\r\n var icon = originalManifest.icons[i];\r\n var size = ['16x16', '32x32', '64x64', '128x128', '256x256', '512x512', '1024x1024'].indexOf(icon.sizes); //specify which size icons from manifest to keep\r\n if(size >=0){\r\n icons[icon.sizes] = icon.src;\r\n }\r\n\r\n }\r\n manifest.icons = icons;\r\n }\r\n\r\n // NOTE: you may need to map permissions in this file as well, if you app supports permissions, pull them from\r\n //originalManifest.mjs_api_access\r\n \r\n\r\n//This is important, this will be converted into a file that lives on your project root. Manifoldjs uses it, and it's a good record\r\n//to have around, so make sure you leave this. Add extra info to it if you think it would be handy\r\n var convertedManifestInfo = {\r\n 'content': manifest,\r\n 'format': lib.constants.STRAWMAN_MANIFEST_FORMAT\r\n };\r\n //this is the return, that's all she wrote!\r\n return Q.resolve(convertedManifestInfo).nodeify(callback);\r\n}",
"function generateUIForJSON(data){\n return `\n <div class=\"quarter\">\n <div class=\"image\">\n <img src=\"${data.picture}\"/>\n </div>\n <div class=\"info\">\n <h3>${data.name}</h3>\n <h4>${data.gender}</h3>\n <h5>${data.email}</h5>\n </div>\n </div>\n `\n}",
"handlePreviewXml(cmp) {\n let noStarAllowed = ['Report', 'CustomObject', 'Document', 'EmailTemplate', 'RecordType',\n 'CustomField', 'ValidationRule', 'Dashboard', 'CustomLabel', 'CanvasMetadata', 'Letterhead', 'IframeWhiteListUrlSettings',\n 'EmailServicesFunction', 'UIObjectRelationConfig', 'RemoteSiteSetting', 'NotificationTypeConfig', 'ManagedContentType',\n 'ApexEmailNotifications', 'ListView', 'WorkflowTask', 'WorkflowRule', 'WorkflowFieldUpdate', 'WorkflowAlert', 'WebLink',\n 'SharingOwnerRule', 'SharingReason', 'SharingCriteriaRule', 'MatchingRule', 'BusinessProcess', 'EscalationRules', 'UserCriteria'];\n let xmlList = [];\n let xmds = [];\n let options = cmp.options.filter(item => item.checked == true);\n options.forEach(value => {\n if (value.metaName == 'WaveDashboard') {\n xmds.push(value.apiName);\n }\n let index = xmlList.findIndex(val => val.obj == value.metaName);\n if (index > -1) {\n let currentList = xmlList[index].components;\n currentList.push(value.apiName);\n xmlList[index].components = currentList;\n } else {\n xmlList.push({ obj: value.metaName, components: [value.apiName] });\n }\n });\n xmlList.forEach(item => {\n let obj = cmp.viewOptions.filter(val => val.value == item.obj)[0];\n if (obj.checked == true && !noStarAllowed.includes(obj.value)) {\n item.components = ['*'];\n }\n });\n if (xmds.length > 0) {\n let index = xmlList.findIndex(val => val.obj == 'WaveXmd');\n if (index > -1) {\n xmlList[index].components = [...xmlList[index].components, ...xmds];\n } else {\n xmlList.push({ obj: 'WaveXmd', components: xmds });\n }\n }\n xmlList = this.wrenchsortarraydata(xmlList, 'ASC', 'obj');\n const payload = { xmlList: xmlList, versionId: cmp.versionId };\n publish(cmp.messageContext, xmlViewChannel, payload);\n }",
"function buildPackageXml(packageName) {\n\n var packageXml = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>';\n packageXml += '<Package xmlns=\"http://soap.sforce.com/2006/04/metadata\">';\n packageXml += (packageName !== 'unpackaged') ? '<fullName>'+ packageName +'</fullName>' : '';\n packageXml += '<types>';\n packageXml += '<members>*</members>';\n packageXml += '<name>CustomObject</name>';\n packageXml += '</types>';\n packageXml += '<types>';\n packageXml += '<members>*</members>';\n packageXml += '<name>CustomMetadata</name>';\n packageXml += '</types>';\n packageXml += '<version>33.0</version>';\n packageXml += '</Package>';\n\n return packageXml;\n\n }",
"function generateXML(){\n\t\t\t\tconsole.log(\"###### FUNCTION generateXML START\");\n\t\t\t\tvar xml2Send = '';\n\t\t\t\txml2Send += '<?xml version=\"1.0\" encoding=\"UTF-8\"?><simpledc xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dct=\"http://purl.org/dc/terms/\" xmlns:geonet=\"http://www.fao.org/geonetwork\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://purl.org/dc/elements/1.1/ http://dublincore.org/schemas/xmls/qdc/2006/01/06/simpledc.xsd http://purl.org/dc/terms/ http://dublincore.org/schemas/xmls/qdc/2006/01/06/dcterms.xsd\">';\n\t\t\t\txml2Send += '<dc:identifier>' + $scope.metadata.identifier + '</dc:identifier>';\n\t\t\t\txml2Send += '<dc:title>' + $scope.metadata.title + '</dc:title>';\n\t\t\t\tif($scope.metadata.alttitle){\n\t\t\t\t\txml2Send += '<dct:alternative>' + $scope.metadata.alttitle + '</dct:alternative>';\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\txml2Send += '<dct:alternative></dct:alternative>';\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t$scope.metadata.pubdate = $filter('date')($scope.metadata.pubdate, \"yyyy-MM-dd\");\n\t\t\t\tif($scope.metadata.pubdate){\n\t\t\t\t\txml2Send += '<dct:dateSubmitted>' + $scope.metadata.pubdate + '</dct:dateSubmitted>';\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\txml2Send += '<dct:dateSubmitted></dct:dateSubmitted>';\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t$scope.metadata.date = $filter('date')($scope.metadata.date, \"yyyy-MM-dd\");\n\t\t\t\txml2Send += '<dc:created>' + $scope.metadata.date + '</dc:created>';\n\t\t\t\tif($scope.metadata.dataidentifier){\n\t\t\t\t\txml2Send += '<dc:identifier>' + $scope.metadata.dataidentifier + '</dc:identifier>';\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\txml2Send += '<dc:identifier></dc:identifier>';\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\txml2Send += '<dc:description>' + $scope.metadata.abstract + '</dc:description>';\n\t\t\t\txml2Send += '<dc:creator>' + $scope.metadata.contact + ';' + $scope.metadata.email + '</dc:creator>';\n\t\t\t\tif ($scope.metadata.keywords) {\n\t\t\t\t\tvar keywordsString = $scope.metadata.keywords.toString();\n\t\t\t\t\tvar keywords = keywordsString.split(\",\");\n\t\t\t\t\t$.each(keywords, function (i) {\n\t\t\t\t\t\txml2Send += '<dc:subject>' + keywords[i] + '</dc:subject>';\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\txml2Send += '<dc:subject>' + $scope.metadata.keywords + '</dc:subject>';\n\t\t\t\t}\n\t\t\t\txml2Send += '<dc:type>' + $scope.metadata.theme + '</dc:type>';\n\t\t\t\tif($scope.metadata.accessuse){\n\t\t\t\t\txml2Send += '<dc:rights>' + $scope.metadata.accessuse + '</dc:rights>';\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\txml2Send += '<dc:rights></dc:rights>';\n\t\t\t\t}\n\t\t\t\tif($scope.metadata.publicaccess){\n\t\t\t\t\txml2Send += '<dct:accessRights>' + $scope.metadata.publicaccess + '</dct:accessRights>';\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\txml2Send += '<dct:accessRights></dct:accessRights>';\n\t\t\t\t}\n\t\t\t\txml2Send += '<dc:language>' + $scope.metadata.language.name + '</dc:language>';\n\t\t\t\txml2Send += '<dc:coverage>North ' + $scope.geolocation.bounds[3] + ',South ' + $scope.geolocation.bounds[1] + ',East ' + $scope.geolocation.bounds[2] + ',West ' + $scope.geolocation.bounds[0] + '. (Global)</dc:coverage>';\n\t\t\t\txml2Send += '<dc:format>' + $scope.metadata.format + '</dc:format>';\n\t\t\t\tif ($scope.metadata.url) {\n\t\t\t\t\tvar urlsString = $scope.metadata.url.toString();\n\t\t\t\t\tvar urls = urlsString.split(\",\");\n\t\t\t\t\t$.each(urls, function (i) {\n\t\t\t\t\t\txml2Send += '<dct:references>' + urls[i] + '</dct:references>';\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\txml2Send += '<dct:references>' + $scope.metadata.url + '</dct:references>';\n\t\t\t\t}\n\t\t\t\txml2Send += '<dc:source>' + $scope.metadata.lineage + '</dc:source>';\n\t\t\t\txml2Send += '</simpledc>';\n\t\t\t\tconsole.log(\"###### FUNCTION generateXML END\");\n\t\t\t\tconsole.log(\"###### FUNCTION generateXML RESULT: \" + xml2Send);\n\t\t\t\treturn xml2Send;\n\t\t\t}",
"function buildHTML(jsnObj){\n //var jsnObj=JSON.parse(JSONText);\n \n var html=\"\"; \n for(var i in jsnObj.cameras){\n html+=\"<h3>Kamera \"+jsnObj.cameras[i].id+\": \"+jsnObj.cameras[i].ip+\"</h3>\";\n html+=\"<img id=\\\"cam\"+jsnObj.cameras[i].id+\"\\\" src=\\\"\"+\n jsnObj.cameras[i].path+\"\\\" alt=\\\"Bild Kamera \"+\n jsnObj.cameras[i].id+\"\\\" width=\\\"384\\\" height=\\\"216\\\" >\\n<br>\";\n } \n \n $('images').innerHTML=html;\n \n}",
"function transformToChromeManifest(content) {\n /*\n * Keys to modify:\n * -- browser_action.default_icon: \"assets/search64.png\"\n * Keys to add:\n * -- minimum_chrome_version: \"59.0.3071\"\n * Keys to remove:\n * -- applications\n */\n const manifest = JSON.parse(content);\n delete manifest.applications;\n\n manifest.browser_action.default_icon = 'icons/logo-48.png';\n manifest.minimum_chrome_version = '59.0.3071';\n return JSON.stringify(manifest, null, 2);\n}",
"function makeImageHtmlStringFromXMLObject(obj) {\n if ($(obj)[0] && $(obj)[0].data) {\n let data = $(obj)[0].data;\n data = data.replace(/\\\\/g, \"/\");\n let name = data.substr(data.lastIndexOf('/') + 1);\n let path = '<ac:image>' +\n '<ri:attachment ri:filename=\"' + name + '\" >' +\n '<ri:page ri:content-title=\"' + space.homepage.title + '\"/>' +\n '</ri:attachment>' +\n '</ac:image>';\n return path;\n };\n return \"\"\n }",
"function set2xml() {\n var xmlstr = new java.lang.StringBuffer(\"<\" + this.name + \" datum='\" + this.parent.datum + \"' val='\" + this.val + \"'\");\n if (this.desc) xmlstr.append(\" desc='\" + this.desc + \"'\");\n xmlstr.append(\"/>\");\n return xmlstr.toString(); \n}",
"function customMetadataToXml(namespace,inputData,fields) {\n\n \n var ns = (namespace !== '' && vm.orgData.packages !== 'unpackeged') ? namespace : '';\n\n var customMetadataXml = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>';\n customMetadataXml += '<CustomMetadata xmlns=\"http://soap.sforce.com/2006/04/metadata\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">';\n customMetadataXml += '<description>'+ inputData.description + '</description>';\n customMetadataXml += '<label>' + inputData.label + '</label>';\n \n for (var c=0; c < inputData.values.length; c++){\n\n var field = inputData.values[c];\n\n customMetadataXml += '<values>';\n customMetadataXml += '<field>' + ns + fields[c].fullName + '</field>';\n customMetadataXml += '<value xsi:type=\"xsd:' + sfTypeToApexType(fields[c].type) + '\">' + field.value + '</value>';\n customMetadataXml += '</values>';\n\n }\n\n customMetadataXml += '</CustomMetadata>';\n\n\n if (typeof inputData !== 'undefined' || inputData !== {}) {\n\n return customMetadataXml;\n\n } else {\n\n return '';\n \n }\n \n }",
"function genApplicationJson() {\n return encodeURIComponent(\"application/json\");\n }",
"get manifest(){\n if(fs.existsSync(path.join(this.root, 'package.json'))){\n return JSON.parse(fs.readFileSync(path.join(this.root, 'package.json')))\n }\n }",
"async loadManifest(manifest, target = null) {\n // support a custom target or ensure event fires off window\n if (target == null && window) {\n target = window;\n }\n // @todo replace this with a schema version mapper\n // once we have versions\n if (varExists(manifest, \"metadata.siteName\")) {\n let git = varGet(manifest, \"publishing.git\", {});\n manifest.metadata.site = {\n name: manifest.metadata.siteName,\n git: git,\n created: manifest.metadata.created,\n updated: manifest.metadata.updated,\n };\n manifest.metadata.theme.variables = {\n image: manifest.metadata.image,\n icon: manifest.metadata.icon,\n hexCode: manifest.metadata.hexCode,\n cssVariable: manifest.metadata.cssVariable,\n };\n manifest.metadata.node = {\n dynamicElementLoader: manifest.metadata.dynamicElementLoader,\n fields: manifest.metadata.fields,\n };\n delete manifest.metadata.publishing;\n delete manifest.metadata.created;\n delete manifest.metadata.updated;\n delete manifest.metadata.siteName;\n delete manifest.metadata.image;\n delete manifest.metadata.icon;\n delete manifest.metadata.hexCode;\n delete manifest.metadata.cssVariable;\n delete manifest.metadata.dynamicElementLoader;\n delete manifest.metadata.fields;\n }\n // repair slug not being in earlier builds of json schema\n await manifest.items.forEach((item, index, array) => {\n // if we did not have a slug, generate one off location\n if (!item.slug) {\n array[index].slug = item.location\n .replace(\"pages/\", \"\")\n .replace(\"/index.html\", \"\");\n }\n // we default published to true if not set\n // this avoids constantly checking downstream\n if (!item.metadata.hasOwnProperty(\"published\")) {\n array[index].metadata.published = true;\n }\n // fix order typing\n array[index].order = Number(array[index].order);\n // we default locked to false if not set\n if (!item.metadata.hasOwnProperty(\"locked\")) {\n array[index].metadata.locked = false;\n }\n // we default locked to false if not set\n if (!item.metadata.hasOwnProperty(\"status\")) {\n array[index].metadata.status = \"\";\n }\n });\n var site = new JsonOutlineSchema();\n // we already have our items, pass them in\n var nodes = site.itemsToNodes(manifest.items);\n // smash outline into flat to get the correct order\n var correctOrder = site.nodesToItems(nodes);\n var newItems = [];\n // build a new array in the correct order by pushing the old items around\n for (var key in correctOrder) {\n newItems.push(\n manifest.items.find((element) => {\n return element.id === correctOrder[key].id;\n })\n );\n }\n // support for language being defined in the manifest of the site\n if (document.documentElement && manifest.metadata.site.lang) {\n document.documentElement.lang = manifest.metadata.site.lang;\n window.dispatchEvent(\n new CustomEvent(\"languagechange\", {\n detail: manifest.metadata.site.lang,\n })\n );\n }\n manifest.items = newItems;\n this.manifest = manifest;\n target.dispatchEvent(\n new CustomEvent(\"json-outline-schema-changed\", {\n bubbles: true,\n composed: true,\n cancelable: false,\n detail: manifest,\n })\n );\n window.dispatchEvent(\n new CustomEvent(\"haxcms-item-rebuild\", {\n bubbles: true,\n composed: true,\n cancelable: false,\n detail: true,\n })\n );\n }",
"function customObjectToXml(namespace,inputData) {\n\n var ns = (namespace !== '' && vm.orgData.packages !== 'unpackeged') ? namespace : '';\n\n var customObjectXml = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>';\n customObjectXml += '<CustomObject xmlns=\"http://soap.sforce.com/2006/04/metadata\">';\n \n for (var c=0; c < inputData.fields.length; c++){\n\n var field = inputData.fields[c]\n\n // TODO: build out for Email, Phone, URL, Date, Date/Time\n customObjectXml += '<fields>';\n\n customObjectXml += '<fullName>' + ns + field.fullName + '</fullName>';\n customObjectXml += '<label>'+ field.label + '</label>';\n customObjectXml += (field.type === 'Text' || field.type === 'TextArea') ? '<length>'+ (field.length || 255) + '</length>' : '';\n customObjectXml += (field.type === 'Checkbox') ? '<defaultValue>'+ field.defaultValue + '</defaultValue>' : '';\n customObjectXml += (field.type === 'Number' || field.type === 'Percent' ) ? '<precision>'+ (field.precision || '12') + '</precision>' : '';\n customObjectXml += (field.type === 'Number' || field.type === 'Percent') ? '<scale>'+ (field.scale || '0') + '</scale>' : '';\n customObjectXml += '<type>'+ field.type + '</type>';\n customObjectXml += '<externalId>'+ field.externalId + '</externalId>';\n customObjectXml += '<required>'+ field.required + '</required>';\n customObjectXml += '<unique>'+ field.unique + '</unique>';\n \n customObjectXml += '</fields>';\n\n }\n\n customObjectXml += '<label>' + inputData.label + '</label>';\n customObjectXml += '<pluralLabel>' + inputData.pluralLabel + '</pluralLabel>';\n customObjectXml += '</CustomObject>';\n\n \n if (typeof inputData !== 'undefined' || inputData !== {}) {\n\n return customObjectXml;\n\n } else {\n\n return '';\n \n }\n\n }",
"function buildFromJSON(HTMLContainer, jsonObj) {\r\n \r\n console.log(\"parsing JSON object\");\r\n console.log(jsonObj);\r\n var elementToModel = null;\r\n for ( var obj in jsonObj ) {\r\n console.log(\"THING: \"+ obj);\r\n console.log(jsonObj[obj]);\r\n \r\n switch (obj) { \r\n case 'title':\r\n var element = document.createElement(\"title\");\r\n element.textContent = jsonObj[obj];\r\n HTMLContainer.appendChild(element);\r\n break; \r\n case 'body':\r\n var body = document.createElement('body');\r\n HTMLContainer.appendChild(body);\r\n for( var e in jsonObj[obj]){\r\n buildFromJSON(body, jsonObj[obj][e]);\r\n }\r\n break;\r\n case 'type':\r\n switch(jsonObj[obj]){\r\n case 'paragraph':\r\n var p = document.createElement('p');\r\n HTMLContainer.appendChild(p);\r\n elementToModel = p;\r\n break;\r\n case 'heading':\r\n var h = document.createElement('h1');\r\n HTMLContainer.appendChild(h);\r\n elementToModel = h;\r\n break;\r\n case 'image':\r\n var image = document.createElement('img');\r\n HTMLContainer.appendChild(image);\r\n elementToModel = image;\r\n break; \r\n case 'list':\r\n var list = document.createElement('ul');\r\n HTMLContainer.appendChild(list);\r\n elementToModel = list;\r\n break;\r\n }\r\n break; \r\n case 'model':\r\n var element;\r\n if(elementToModel == null){\r\n console.log(\"modelling container\");\r\n element = HTMLContainer;\r\n }else{\r\n console.log(\"modelling element\");\r\n element = elementToModel;\r\n }\r\n for( var attribute in jsonObj[obj]){\r\n console.log(\"Attribute \" + attribute);\r\n if(attribute == 'text'){\r\n element.textContent = jsonObj[obj][attribute];\r\n }else if(attribute == 'url'){\r\n element.setAttribute('src',jsonObj[obj][attribute] )\r\n }else if(attribute == 'items'){\r\n for(var item in jsonObj[obj][attribute]){\r\n var listItem = document.createElement('li');\r\n listItem.textContent = jsonObj[obj][attribute][item];\r\n element.appendChild(listItem);\r\n } \r\n }else{\r\n element.setAttribute(attribute, jsonObj[obj][attribute])\r\n }\r\n }\r\n elementToModel = null;\r\n break; \r\n }\r\n }\r\n}",
"function createXml (options, xmlObject) {\n const createdXml = js2xmlparser.parse('licenseSummary', xmlObject);\n if (!options.silent) {\n console.log(createdXml);\n }\n if (options.xml) {\n const fileName = options.xml.substring(0, options.xml.length - path.extname(options.xml).length);\n fs.writeFileSync(path.join(licensesDir, `${fileName}.xml`), createdXml);\n }\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 }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function For Adding New Entry Creates two span leader and scor and two buttons and set there respective id Adds them to both the divs Appends them to scores and names array and increment the count The id of each set of item is based on the current value of count, which indeed is related to there current position in the array O(1)process | function Add(){
var name = "Leader"+count;
var leader = document.createElement('span');
leader.innerHTML=name;
leader.id="1a"+count;
leader.className="col-md-6";
var scor = document.createElement('span');
scor.innerHTML=0;
scor.className="col-md-2";
scor.id="1b"+count;
var btn1 = document.createElement('button');
btn1.innerHTML="INC";
btn1.className="col-md-2";
btn1.addEventListener ("click", increase);
btn1.id="1c"+count;
var btn2 = document.createElement('button');
btn2.innerHTML="DEC";
btn2.className="col-md-2";
btn2.addEventListener ("click", decrease);
btn2.id="1d"+count;
div1.appendChild(leader);
div1.appendChild(scor);
div1.appendChild(btn1);
div1.appendChild(btn2);
name1 = "Leader"+count;
leader = document.createElement('span');
leader.innerHTML=name;
leader.className="col-md-6";
leader.id="2a"+count;
scor = document.createElement('span');
scor.innerHTML=0;
scor.className="col-md-2";
scor.id="2b"+count;
btn1 = document.createElement('button');
btn1.innerHTML="INC";
btn1.className="col-md-2";
btn1.id="2c"+count;
btn1.addEventListener ("click", increase);
btn2 = document.createElement('button');
btn2.innerHTML="DEC";
btn2.className="col-md-2";
btn2.id="2d"+count;
btn2.addEventListener ("click", decrease);
div2.appendChild(leader);
div2.appendChild(scor);
div2.appendChild(btn1);
div2.appendChild(btn2);
count++;
names.push(name);
scores.push(0);
} | [
"function increase(){\n \n var str=event.target.id;\n var str=str.substr(2,str.length-2);\n var x=parseInt(str);\n console.log(x);\n scores[x-1]+=1;\n \n while(x>1 && scores[x-1]>scores[x-2]){\n var lead=names[x-1],sco=scores[x-1];\n names[x-1]=names[x-2];\n scores[x-1]=scores[x-2];\n names[x-2]=lead;\n scores[x-2]=sco;\n console.log(scores);\n var cnt1=\"1b\"+x;\n x-=1;\n var cnt2=\"1b\"+x;\n x+=1;\n document.getElementById(cnt1).innerHTML=scores[x-1];\n document.getElementById(cnt2).innerHTML=scores[x-2];\n cnt1=\"2b\"+x;\n x-=1;\n cnt2=\"2b\"+x;\n x+=1;\n document.getElementById(cnt1).innerHTML=scores[x-1];\n document.getElementById(cnt2).innerHTML=scores[x-1];\n\n cnt1=\"1a\"+x;\n x-=1;\n cnt2=\"1a\"+x;\n x+=1;\n document.getElementById(cnt1).innerHTML=names[x-1];\n document.getElementById(cnt2).innerHTML=names[x-2];\n cnt1=\"2a\"+x;\n x-=1;\n cnt2=\"2a\"+x;\n x+=1;\n document.getElementById(cnt1).innerHTML=names[x-1];\n document.getElementById(cnt2).innerHTML=names[x-2];\n x--; \n }\n if(x==1 || scores[x-1]<=scores[x-2]){\n var cnt=\"1b\"+x;\n document.getElementById(cnt).innerHTML=scores[x-1];\n cnt=\"2b\"+x;\n document.getElementById(cnt).innerHTML=scores[x-1];\n }\n \n \n}",
"function createPlayers(){\r\n\tvar playerContainer = document.getElementById(\"player_container\");\r\n\tvar numOfPlayer = document.getElementById(\"numberOfPlayers\").value; \r\n\tfor (var i = 1; i <= numOfPlayer; i++){\r\n\t\tthePlayers.push({player_id: i, playerName : 'Player ' + i, handArr : [], isDealer : false, isBust : false, finalScore : 0});\r\n\t\tplayerContainer.insertAdjacentHTML('beforeend', \"<div class='player' id='player_\" + i + \"'><h2 id='player_\" + i +\"_title'>Player \" + i + \"</h2> <div id='result_text_\" + i + \"'></div><div class='card_container' id='cards_\" + i + \"'></div></div>\");\r\n\t}\r\n\tthePlayers.push({player_id: i,playerName : 'The Dealer', handArr : [], isDealer : true, isBust : false, finalScore : 0});\r\n\tnumOfPlayer++;\r\n\tplayerContainer.insertAdjacentHTML('beforeend', \"<div class='player' id='player_\" + numOfPlayer + \"'><h2 id='player_\" + i +\"_title'>Dealer</h2> <div id='result_text_\" + numOfPlayer + \"'></div><div class='card_container' id='cards_\" + numOfPlayer + \"'></div><div id='dealers_final_score'></div>\");\t\r\n}",
"function addToHumanScore() {\n humanScore++\n $('#humanScore').text(humanScore)\n }",
"displayScores() {\r\n for (let i = 1; i <= this.total; i += 1) {\r\n const data = this.data.get(i);\r\n const div = this.createContent(data.name, data.level, Utils.formatNumber(data.score, \",\"));\r\n\r\n div.className = \"highScore\";\r\n this.scores.appendChild(div);\r\n }\r\n }",
"function addScore() {\n var input = nameInput.value;\n\n var user = {name: input, score: timer};\n // add new score to array\n leaderboardArr.push({name: input, score: timer});\n\n // updates array in local storage\n localStorage.setItem(\"leaderboard\", JSON.stringify(leaderboardArr));\n\n hideElement(endPageDiv);\n displayLeaderboard();\n highlightUserScore(user);\n}",
"function addToComputerScore() {\n computerScore++\n $('#computerScore').text(computerScore)\n }",
"function displayLeaderboard() { \n hideAll();\n clearTable();\n displayElement(leaderboardPageDiv);\n\n if (leaderboardArr.length > 0) {\n // sorts the leaderboardArr from highest \n // to lowest by score\n leaderboardArr.sort((a, b) => b.score - a.score);\n\n var rank = 1;\n\n // for each element create a new row in leaderboardTable\n for (var i = 0; i < leaderboardArr.length; i++) {\n var curr = leaderboardArr[i];\n // insert row at the bottom of the table\n var row = leaderboardTable.insertRow();\n \n\n // checks if the score is already on the leaderboard so if it \n // is everyone of that score has the same rank\n if (i !== 0 && curr.score !== leaderboardArr[i - 1].score) {\n rank++;\n }\n\n // create cell data for each heading in the table\n createCell(row, rank);\n createCell(row, curr.name);\n createCell(row, curr.score);\n }\n }\n}",
"function updateLeaderBoard(newScoreBoard,me) {\n let list = document.getElementById(\"top10\");\n let items = list.children;\n\n // While loop to remove the current items in the list.\n while(list.firstChild) {\n list.firstChild.remove();\n }\n\n // Loop to append new \"li\" items to the scoreboard.\n let boardNum = newScoreBoard.length;\n for (let i = 0; i < boardNum; i++) {\n if(i < 10) {\n let newItem = document.createElement(\"li\");\n newItem.textContent = newScoreBoard[i];\n if(me == newScoreBoard[i])newItem.className = \"myself\";\n list.appendChild(newItem);\n }\n }\n}",
"function addToCount() {\n totalButtonsPressed++;\n recentButtonsPressed++;\n}",
"function queCounter(index){\n const bottom_ques_counter = quiz_box.querySelector(\".total_que\");\n let totalQueCountTag = '<span><p>'+ index +'</p> of <p>'+ questions.length +'</p> Questions</span>';\n bottom_ques_counter.innerHTML = totalQueCountTag; //adding new span tag inside the bottom_ques_counter\n}",
"function addExamPanel(element) {\n /* '(data-exam-name', exam.testName)\n ('data-exam-code', exam.component)\n ('data-exam-tag', exam.testTag)\n ('data-exam-min-score', exam.examsMinScore)\n ('data-exam-max-score', exam.examsMaxScore)*/\n let name = $(element).attr('data-exam-name');\n let examCode = $(element).attr('data-exam-code')\n let tag = $(element).attr('data-exam-tag');\n let minScore = $(element).attr('data-exam-min-score')\n let maxScore = $(element).attr('data-exam-max-score');\n selectedExams.push(examCode);\n\n let error = \"<p class='error'>Score entered needs to be a whole number from \" + minScore + \" to \" + maxScore + \"</p>\"\n let submitButton = \"<button class='button button2' disabled onclick=submitScore(this)>Submit</button>\"\n let submitSuccessful = \"<p class='success'>Score was added successfully</p>\"\n var selectedExamTEST = $(\"<div class='exam' id='\" + name + \"' data-exam-code='\" + examCode + \"' data-exam-tag='\" + tag + \"' data-exam-min-score='\" + minScore + \"' data-exam-max-score='\" + maxScore + \"' > <h2> <span></span> \" + element.value + \" </h2> <a class='close'> <img src='style/images/close-button.svg' alt='close button' class='close-button' align='middle'/> </a> <div class='score_container'><a class='add_score'>+ Add Score</a><div class='add_score_container'><div class='add_score_input_container'><input class='add_score_input' type='text' oninput='isValidScore(this)' placeholder='Type in Score' />\" + submitButton + \"<div class='not_found'>I can't find my score</div><div class='score_list' /></div><a class='score_close' /></div><div class='selected_scores' /></div>\" + submitSuccessful + error + \"</div>\");\n\n\n $('.exam-added-container').prepend(selectedExamTEST);\n\n $('.add-exam-container').remove();\n $('#add-exam-btn').insertBefore($('.exam-added-container'));\n\n $('#add-exam-btn').show();\n\n\n var scoreList = $(selectedExamTEST).find(\".score_list\");\n\n}",
"function addSkill()\n{\n var count = document.getElementById(\"skill-count\");\n var it = count.getAttribute(\"value\");\n if (it >= 8) {\n alert(\"You have reached maximum number of skills\");\n return;\n }\n count.setAttribute(\"value\", ++it);\n\n mainDiv = document.getElementById(\"skills\");\n\n var skill = document.createElement(\"div\"); // Create a <div> node\n skill.setAttribute(\"class\",\"edit-box partition interior-box-format \");\n var divName = \"skill\" + it;\n skill.setAttribute(\"id\",divName);\n\n var deleteButton = document.createElement(\"input\");\n deleteButton.setAttribute(\"type\", \"button\");\n var deleteSkillNum = \"delete-skill\" + it;\n deleteButton.setAttribute(\"id\", deleteSkillNum);\n deleteButton.setAttribute(\"value\", \"Delete\");\n deleteButton.setAttribute(\"class\", \"btn btn-danger\")\n var functionName = \"deleteSkill(\" + it + \",-1)\";\n deleteButton.setAttribute(\"onclick\", functionName);\n skill.appendChild(deleteButton);\n\n var skillChild = document.createElement(\"div\");\n skillChild.setAttribute(\"class\", \"sm-pad form-group\");\n\n var glyphicon = document.createElement(\"span\");\n glyphicon.setAttribute(\"class\",\"glyphicon glyphicon-info-sign\");\n\n var toolTip = document.createElement(\"a\");\n toolTip.setAttribute(\"href\",\"#!\");\n toolTip.setAttribute(\"data-toggle\",\"tooltip\");\n toolTip.setAttribute(\"data-placement\", \"top\");\n toolTip.setAttribute(\"title\",\"The preferred button indicates which card will be displayed when employers search for you!\");\n\n toolTip.appendChild(glyphicon);\n\n\n var prefP = document.createElement(\"label\");\n\n var prefLabel = document.createTextNode(\" Preferred: \");\n var pref = document.createElement(\"input\");\n pref.setAttribute(\"type\", \"radio\");\n pref.setAttribute(\"class\", \"pull-right\");\n var skillID = \"skill-preference\" + it;\n prefP.setAttribute(\"for\", skillID);\n pref.setAttribute(\"id\", skillID);\n pref.setAttribute(\"name\", \"skill-preference\");\n pref.setAttribute(\"value\", it);\n if (mainDiv.childNodes.length == 6) {\n pref.checked = true;\n }\n prefP.appendChild(toolTip);\n prefP.appendChild(prefLabel);\n skillChild.appendChild(prefP);\n skillChild.appendChild(pref);\n\n skill.appendChild(skillChild);\n\n skillChild = document.createElement(\"div\");\n skillChild.setAttribute(\"class\", \"form-group\");\n\n var fieldP = document.createElement(\"label\");\n var fieldLabel = document.createTextNode(\"Field:\");\n var field = document.createElement(\"select\");\n var fieldString = \"field\";\n fieldString = fieldString.concat(it.toString(10));\n fieldP.setAttribute(\"for\", fieldString);\n\n field.setAttribute(\"class\", \"form-control\")\n field.setAttribute(\"name\", fieldString);\n field.setAttribute(\"onclick\", \"updateFields(this)\")\n field.setAttribute(\"id\", fieldString);\n\n fieldP.appendChild(fieldLabel);\n skillChild.appendChild(fieldP);\n skillChild.appendChild(field);\n\n skill.append(skillChild);\n\n skillChild = document.createElement(\"div\");\n skillChild.setAttribute(\"class\", \"form-group\");\n\n var subFieldP = document.createElement(\"label\");\n var subFieldLabel = document.createTextNode(\"Sub-Field:\");\n var subField = document.createElement(\"select\");\n var subFieldString = \"sub-field\";\n var subFieldOption = document.createElement(\"option\");\n var subFieldOptionLabel = document.createTextNode(\"All Sub-Categories\");\n subFieldOption.setAttribute(\"value\", \"blank\");\n subFieldString = subFieldString.concat(it.toString(10));\n subFieldP.setAttribute(\"for\", subFieldString);\n subField.setAttribute(\"name\", subFieldString);\n subField.setAttribute(\"id\", subFieldString);\n subField.setAttribute(\"class\", \"form-control\");\n //subField.setAttribute(\"disabled\", true);\n\n subFieldP.appendChild(subFieldLabel);\n subFieldOption.appendChild(subFieldOptionLabel);\n subField.append(subFieldOption);\n skillChild.appendChild(subFieldP);\n skillChild.appendChild(subField);\n\n skill.appendChild(skillChild);\n\n skillChild = document.createElement(\"div\");\n skillChild.setAttribute(\"class\", \"form-group\");\n\n var contentsP = document.createElement(\"label\");\n var contentsLabel = document.createTextNode(\"About:\");\n var contents = document.createElement(\"textarea\");\n var contentsString = \"contents\";\n contentsString = contentsString.concat(it.toString(10));\n contentsP.setAttribute(\"for\", contentsString);\n\n contents.setAttribute(\"name\", contentsString);\n contents.setAttribute(\"class\", \"form-control\")\n contents.setAttribute(\"type\",\"text\");\n contents.setAttribute(\"size\",40);\n contents.setAttribute(\"rows\",3);\n contents.setAttribute(\"placeholder\",\"Alphanumeric characters only\");\n contents.setAttribute(\"pattern\", \"^[a-zA-Z0-9\\\\s-]+$\");\n //contents.setAttribute(\"disable\", true);\n\n contentsP.appendChild(contentsLabel);\n skillChild.appendChild(contentsP);\n skillChild.appendChild(contents);\n\n skill.appendChild(skillChild);\n\n mainDiv.appendChild(skill);\n\n getFields(\n function () {\n document.getElementById(fieldString).innerHTML = this.responseText;\n }\n )\n return false;\n\n}",
"displayTitles() {\r\n const div = this.createContent(\"name\", \"lvl\", \"score\");\r\n div.className = \"titles\";\r\n this.scores.appendChild(div);\r\n }",
"function pointsCounter() {\n // Get the element with the \"points\" id\n var pointContainer = document.getElementById(\"points\");\n // Set it equal to the score variable\n pointContainer.innerHTML = score;\n }",
"function addLike3(element){\n like++\n var like_num = document.querySelector(\"#like_number3\")\n like_num.innerHTML = like\n \n}",
"function addToRank() {\n rank.push([name, scores]);\n}",
"function addWorkExperience()\n{\n var count = document.getElementById(\"work-experience-count\");\n var it = count.getAttribute(\"value\");\n if (it >= 8) {\n alert(\"You have reached maximum number of work-experiences\");\n return;\n }\n\n count.setAttribute(\"value\", ++it);\n\n var mainDiv = document.getElementById(\"work-experience\");\n\n var workex = document.createElement(\"div\"); // Create outer <div> node\n workex.setAttribute(\"class\",\"edit-box partition interior-box-format\");\n var divName = \"workExperience\" + it;\n workex.setAttribute(\"id\",divName);\n\n var deleteButton = document.createElement(\"input\"); //Create delete button\n deleteButton.setAttribute(\"type\", \"button\");\n var deleteWorkNum = \"delete-work-experience\" + it;\n deleteButton.setAttribute(\"id\", deleteWorkNum);\n deleteButton.setAttribute(\"value\", \"Delete\");\n deleteButton.setAttribute(\"class\", \"btn btn-danger\");\n var functionName = \"deleteWorkExperience(\" + it + \",-1)\";\n deleteButton.setAttribute(\"onclick\", functionName);\n workex.appendChild(deleteButton);\n\n var workexChild = document.createElement(\"div\"); // Create child <div> node (to put label input pairs within)\n workexChild.setAttribute(\"class\",\"sm-pad form-group\");\n\n var glyphicon = document.createElement(\"span\");\n glyphicon.setAttribute(\"class\",\"glyphicon glyphicon-info-sign\");\n\n var toolTip = document.createElement(\"a\");\n toolTip.setAttribute(\"href\",\"#!\");\n toolTip.setAttribute(\"data-toggle\",\"tooltip\");\n toolTip.setAttribute(\"data-placement\", \"top\");\n toolTip.setAttribute(\"title\",\"The preferred button indicates which card will be displayed when employers search for you!\");\n\n toolTip.appendChild(glyphicon);\n\n\n var prefP = document.createElement(\"label\");\n prefP.setAttribute(\"for\", divName);\n var prefLabel = document.createTextNode(\" Preferred: \");\n var pref = document.createElement(\"input\");\n pref.setAttribute(\"type\", \"radio\");\n pref.setAttribute(\"class\", \"pull-right\");\n if (mainDiv.childNodes.length == 6) {\n pref.checked = true;\n }\n var radID = \"work-experience-preference\" + it;\n pref.setAttribute(\"id\", radID);\n pref.setAttribute(\"name\", \"work-experience-preference\");\n pref.setAttribute(\"value\", it);\n prefP.appendChild(toolTip);\n prefP.appendChild(prefLabel);\n\n workexChild.appendChild(prefP);\n workexChild.appendChild(pref);\n\n workex.appendChild(workexChild); //Append Child div to inner div\n\n workexChild = document.createElement(\"div\"); // Create child <div> node (to put label input pairs within)\n workexChild.setAttribute(\"class\",\"form-group\");\n\n var roleP = document.createElement(\"label\");\n var roleString = \"role\" + it;\n roleP.setAttribute(\"for\", roleString);\n var roleLabel = document.createTextNode(\"Role.\"); // Create a text node\n var role = document.createElement(\"input\");\n role.setAttribute(\"name\", roleString);\n role.setAttribute(\"id\", roleString);\n role.setAttribute(\"class\", \"form-control\");\n role.setAttribute(\"type\", \"text\");\n role.setAttribute(\"size\",40);\n role.setAttribute(\"placeholder\", \"Alphabetic characters only\");\n role.setAttribute(\"pattern\", \"^[a-zA-Z\\\\s-]+$\");\n role.setAttribute(\"title\", \"Alphabetic, '-' and space characters only\");\n\n roleP.appendChild(roleLabel);\n workexChild.appendChild(roleP);\n workexChild.appendChild(role);\n\n workex.appendChild(workexChild); //Append Child div to inner div\n\n workexChild = document.createElement(\"div\"); // Create child <div> node (to put label input pairs within)\n workexChild.setAttribute(\"class\",\"form-group\");\n\n var durationP = document.createElement(\"label\");\n var durationLabel = document.createTextNode(\"Duration.\"); // Create a text node\n var duration = document.createElement(\"input\");\n var durationString = \"duration\" + it;\n durationP.setAttribute(\"for\", durationString)\n duration.setAttribute(\"name\", durationString);\n duration.setAttribute(\"id\", durationString);\n duration.setAttribute(\"type\",\"text\");\n duration.setAttribute(\"class\", \"form-control\");\n duration.setAttribute(\"size\",40);\n duration.setAttribute(\"placeholder\",\"Number in months\");\n duration.setAttribute(\"pattern\", \"^[0-9]+$\");\n duration.setAttribute(\"title\", \"Numeric characters only\");\n\n durationP.appendChild(durationLabel);\n workexChild.appendChild(durationP);\n workexChild.appendChild(duration);\n\n workex.appendChild(workexChild); //Append Child div to inner div\n\n workexChild = document.createElement(\"div\"); // Create child <div> node (to put label input pairs within)\n workexChild.setAttribute(\"class\",\"form-group\");\n\n var employerP = document.createElement(\"label\");\n var employerLabel = document.createTextNode(\"Employer.\"); // Create a text node\n var employer = document.createElement(\"input\");\n var employerString = \"employer\" + it;\n employerP.setAttribute(\"for\", employerString);\n employer.setAttribute(\"name\", employerString);\n employer.setAttribute(\"id\", employerString);\n employer.setAttribute(\"type\",\"text\");\n employer.setAttribute(\"class\", \"form-control\");\n employer.setAttribute(\"size\",40);\n employer.setAttribute(\"placeholder\",\"Alphanumeric characters only\");\n employer.setAttribute(\"pattern\", \"^[a-zA-Z0-9\\\\s-]+$\");\n employer.setAttribute(\"title\", \"Alphanumeric, '-' and space characters only\");\n\n employerP.appendChild(employerLabel);\n workexChild.appendChild(employerP);\n workexChild.appendChild(employer);\n\n workex.appendChild(workexChild); //Append Child div to inner div\n\n mainDiv.appendChild(workex);\n\n\n}",
"function addLike2(element){\n like++\n var like_num = document.querySelector(\"#like_number2\")\n like_num.innerHTML = like\n \n}",
"function refreshCounts () {\n containers.forEach(el => {\n // Get count of all student elements in a target element\n let count = el.querySelectorAll('.student').length\n let elHeader = el.querySelector('.count')\n // Inject count in target container\n elHeader.textContent = ` (${count})`\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method clicks on the wishlist icon | clickWishlistIcon() {
return this
.waitForElementVisible('@wishListBtn')
.assert.visible('@wishListBtn')
.click('@wishListBtn');
} | [
"function openFriendsMenuForSelectedFriend() {\n document.querySelectorAll('div[aria-label=\"Friends\"]')[0]\n .click();\n}",
"function addIconClickListener(callBack) {\n browserAction.onClicked.addListener(callBack);\n}",
"function clickThatCow(imageElement) {\n\tsetSaving();\n\n\t// get the image name\n var imgName = parseCowName(imageElement);\n\t// run through the cow switch\n var cowAttributes = cowClickSwitch(imgName);\n\n\t// adjust points\n\tprevClick = cowAttributes[0];\n points += cowAttributes[0];\n document.getElementById('points').innerHTML = points;\n\n // Add a log for this action!\n\tcreateLog(cowAttributes[1] + \" gave you \" + cowAttributes[0] + \" points!\", cowAttributes[0])\n}",
"toggleWishlistPanel () {\n this.toggleWishlist()\n }",
"validateWishlistCounterIconIncrement() {\n return this\n .waitForElementVisible('@wishlistCounter')\n .assert.visible('@wishlistCounter')\n .getText('@wishlistCounter', (text) => {\n this\n .assert.ok(text.value > 0, 'Item added to wishlist');\n });\n }",
"clickPayByCheckLink() {\n this.lnkPayByCheck.click();\n }",
"onLikeClick(id){\r\n\t\tthis.props.like(id)\r\n\t}",
"clickConfirmMyOrder() {\n this.waitUtil.waitForElementToBeClickable(\n this.btnConfirmMyOrder,\n 15000,\n \"Confirm My Order\"\n );\n this.btnConfirmMyOrder.click();\n }",
"function _iconClickEvent() {\n\n\t\t_toggleVisibility();\n\n\t\t// Turn of file watching when not using it\n\t\tif (false === visible) {\n\t\t\ttailDomain.exec(\"quitTail\")\n\t\t\t\t.done(function () {\n\t\t\t\t\tconsole.log(\"[brackets-tail-node] quitTail done event\");\n\t\t\t\t}).fail(function (err) {\n\t\t\t\t\tconsole.error(\"[brackets-tail-node] quitTail error event\", err);\n\t\t\t\t});\n\t\t}\n\t}",
"function goToFavoritesClick() {\n $('.favorites').show();\n $('.results').hide();\n }",
"function overviewImgClick(e){\n\tvar i,j,tname,turl,item,c,li,\n\t\ttarget = e.target || e.srcElement,\n\t\ttype = default_types_1,\n\t\tpremium;\n\n\tturl = target.u;\n\n\t//디폴트 타입에서 필요 li 검색\n\tfor (i = 0; i < type.length; i++) {\n\t\ttname = type[i].n;\n\t\tif (tname === turl) {\n\t\t\titem = type[i];\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (!item)\n\t\treturn;\n\n\t// click 된 overview Image Name을 가지고 온다.\n\titem.imgName = target.childNodes[0].innerHTML;\n\n\titem.over = true;\n\tactiveMainLi(item, false);\n}",
"click_expertTips_1stHorse(){\n this.expertTips_1stHorse.waitForExist();\n this.expertTips_1stHorse.click();\n }",
"async clickOnElement(elemenText){\n //Get Element whose span consist of specific Text\n var element = this.getElement(elemenText)\n element.click()\n }",
"click_expertTipsTab(){\n this.expertTipsTab.waitForExist();\n this.expertTipsTab.click();\n }",
"function clickArtist(artistId, index, artistName) {\n\t//deselect an artist\n\tif (index !== -1){\n\t\tdeselectArtist(index, artistId);\n\t\taddInteraction('artistDiv', 'deselect', artistId);\n\t}\n\t//select a new artist\n\telse {\n\t\tselectArtist(artistId, artistName);\n\t\taddInteraction('artistDiv', 'select', artistId);\n\t}\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}",
"attemptLike() {\n this.waitForButtons(() => {\n /*\n If the video is already liked/disliked\n or the user isn't subscribed to this channel,\n then we shouldn't do anything.\n */\n if (this.isVideoRated() || (this.options.like_what === 'subscribed' && !this.isUserSubscribed())) {\n return;\n }\n this.dom.like.click();\n\n /*\n Confirm the click registered.\n Sometimes the buttons load before the event\n handlers get attached and nothing happens.\n */\n if (!this.isVideoRated()) {\n // Persistence pays off\n setTimeout(this.attemptLike, 1000)\n }\n });\n }",
"function C101_KinbakuClub_Fight_Click() {\n\tFightClick();\n}",
"function displayWishList() {\n\t\t\t\t\t\tvar result = \" \";\n\t\t\t\t\t\tfor (var i in wishlist) {\n\t\t\t\t\t\t\tif (wishlist[i].size === \"1 roll\"){\n\t\t\t\t\t\t\tresult += \"<li>\" + \" \" + wishlist[i].name + \", \" +\" Price: \" + wishlist[i].price + \", \"\n\t\t\t\t\t\t\t+ \" Pack Size: \" + wishlist[i].size + \", \"+ \" Qunantity: \" + wishlist[i].quantity + \", \" + \"Added Flavors: NA\" \n\t\t\t\t\t\t\t+ \"<button class = 'delete-item' data-name = '\"+ wishlist[i].name+\"' data-size = '\"+ wishlist[i].size+\"' data-flavors = '\"+ wishlist[i].flavors+\"'> X </button>\"\n\t\t\t\t\t\t\t+ \"</li>\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tresult += \"<li>\" + \" \" + wishlist[i].name + \", \" +\" Price: \" + wishlist[i].price + \", \"\n\t\t\t\t\t\t\t+ \" Pack Size: \" + wishlist[i].size + \", \"+ \" Qunantity: \" + wishlist[i].quantity + \", \" \n\t\t\t\t\t\t\t+ \" Added Flavors: \"+ wishlist[i].flavors + \" \"\n\t\t\t\t\t\t\t+ \"<button class = 'delete-item' data-name = '\"+ wishlist[i].name+\"' data-size = '\"+ wishlist[i].size+\"' data-flavors = '\"+ wishlist[i].flavors+\"'> X </button>\"\n\t\t\t\t\t\t\t+ \"</li>\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$(\"#show-wishlist\").html(result);\n\t\t\t\t\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
endpoint_configuration computed: true, optional: false, required: false | endpointConfiguration(index) {
return new DataAwsApiGatewayRestApiEndpointConfiguration(this, 'endpoint_configuration', index);
} | [
"function EndpointConfig(props) {\n return __assign({ Type: 'AWS::SageMaker::EndpointConfig' }, props);\n }",
"constructAxiosRequestConfig() {\n const input = this._getInput(this.edge);\n const config = {\n url: this._getUrl(this.edge, input),\n params: this._getParams(this.edge, input),\n data: this._getRequestBody(this.edge, input),\n method: this.edge.query_operation.method,\n timeout: 50000\n }\n this.config = config;\n return config;\n }",
"addPayloadEndpoint(opts) {\n if (this.event.payload.endpoints === undefined) {\n this.event.payload.endpoints = [];\n }\n\n if (opts === undefined) {\n opts = {};\n }\n\n // construct the proper structure expected for the endpoint\n let endpoint = {\n endpointId: Utils.defaultIfNullOrEmpty(opts.endpointId, 'dummy-endpoint-001'),\n manufacturerName: Utils.defaultIfNullOrEmpty(opts.manufacturerName, 'ioBroker Group'),\n description: Utils.defaultIfNullOrEmpty(opts.description, 'Device controlled by ioBroker'),\n friendlyName: Utils.defaultIfNullOrEmpty(opts.friendlyName, 'ioBroker Stub Endpoint'),\n displayCategories: Utils.defaultIfNullOrEmpty(opts.displayCategories, ['OTHER']),\n capabilities: this.alexaCapability().concat(Utils.defaultIfNullOrEmpty(opts.capabilities, [])),\n };\n\n if (opts.hasOwnProperty('cookie')) {\n endpoint.cookie = Utils.defaultIfNullOrEmpty('cookie', {});\n }\n\n this.event.payload.endpoints.push(endpoint);\n }",
"options(params) {\n if(!params) {\n return {\n provider: _currentProvider,\n customProvider: customProvider,\n depth: depth,\n weight: weight,\n spamSeed: spamSeed,\n message: message,\n tag: tag,\n numberOfTransfersInBundle: numberOfTransfersInBundle,\n isLoadBalancing: optionsProxy.isLoadBalancing\n }\n }\n if(params.hasOwnProperty(\"provider\")) {\n _currentProvider = params.provider\n initializeIOTA()\n }\n if(params.hasOwnProperty(\"customProvider\")) {\n customProvider = params.customProvider\n initializeIOTA()\n }\n if(params.hasOwnProperty(\"depth\")) { depth = params.depth }\n if(params.hasOwnProperty(\"weight\")) { weight = params.weight }\n if(params.hasOwnProperty(\"spamSeed\")) { spamSeed = params.spamSeed }\n if(params.hasOwnProperty(\"message\")) { message = params.message }\n if(params.hasOwnProperty(\"tag\")) { tag = params.tag }\n if(params.hasOwnProperty(\"numberOfTransfersInBundle\")) { numberOfTransfersInBundle = params.numberOfTransfersInBundle }\n if(params.hasOwnProperty(\"isLoadBalancing\")) { optionsProxy.isLoadBalancing = params.isLoadBalancing }\n if(params.hasOwnProperty(\"onlySpamHTTPS\")) { onlySpamHTTPS = params.onlySpamHTTPS }\n }",
"function getConfigPricingFromResourceQuery(ownerid, elements, callback) {\n var configJson = {};\n\n // Identify configurable vs\n if((elements.uri).match('vs/') && (elements.uri).match('/configurable')){\n configJson.volumeStorageUri = elements.uri;\n if(elements.parameters && elements.parameters.sizeInGBytes){\n configJson.size = elements.parameters.sizeInGBytes;\n }\n }else if((elements.uri).match('saas/') && (elements.uri).match('/configurable')){\n configJson.uri = elements.uri;\n if(elements.parameters && elements.parameters.sizeInGBytes){\n configJson.size = elements.parameters.sizeInGBytes;\n }\n }else {\n if(elements.uri){\n configJson.instanceTypeUri = elements.uri;\n }\n if(elements.parameters && elements.parameters.imageUri){\n configJson.imageUri = elements.parameters.imageUri;\n }\n if(elements.parameters && elements.parameters.ram){\n configJson.ram = elements.parameters.ram;\n }\n if(elements.parameters && elements.parameters.cpuCount){\n configJson.cpuCount = elements.parameters.cpuCount;\n }\n if(elements.parameters && elements.parameters.localStorage){\n configJson.localStorage = elements.parameters.localStorage;\n }\n trace.info(configJson);\n }\n\n jsonObject = JSON.stringify(configJson);\n\n // prepare the header\n //TODO Implement new Auth Model\n var postheaders = {\n 'Content-Type' : 'application/json',\n 'Content-Length' : Buffer.byteLength(jsonObject, 'utf8')\n //\"Authorization\": \"Basic \" + new Buffer(ownerid + \":\" + ownerid).toString(\"base64\")\n };\n\n postheaders[authConfig.bypassHeaderName] = 'billing'+':'+authConfig.billing;\n postheaders['ownerId'] = ownerid;\n\n // the post options\n var optionspost = {\n host : config.resourceServiceHost,\n port : config.resourceServicePort,\n path : '/apiv1.0/resourceQuery/validate',\n method : 'POST',\n headers : postheaders\n };\n\n // do the POST call to resource service\n restservices.postCall(optionspost,jsonObject).then(function (resourceServiceresult) {\n return callback(resourceServiceresult);\n\n }).catch(function onReject(err) {\n trace.error('Rejected', err);\n if(err.stack)\n trace.debug('Error Occurred in : '+ err.stack);\n return callback(null);\n\n }).catch(function(error){\n trace.error('Catch Error:', error);\n if(error.stack)\n trace.debug('Error Occurred in : '+ error.stack);\n return callback(null);\n });\n}",
"setEndpoints(endpoints) {\n this.endpoints = Object.assign(this.endpoints, endpoints);\n }",
"config() {\n if (this.isBound(exports.names.APP_SERVICE_CONFIG)) {\n return this.get(exports.names.APP_SERVICE_CONFIG);\n }\n else {\n throw new Error('configuration object not yet loaded!');\n }\n }",
"function createFromConnectionConfig(config) {\n ConnectionConfig.validate(config, { isEntityPathRequired: true });\n config.getManagementAudience = () => {\n return `${config.endpoint}${config.entityPath}/$management`;\n };\n config.getManagementAddress = () => {\n return `${config.entityPath}/$management`;\n };\n config.getSenderAudience = (partitionId) => {\n if (partitionId != undefined) {\n return `${config.endpoint}${config.entityPath}/Partitions/${partitionId}`;\n }\n else {\n return `${config.endpoint}${config.entityPath}`;\n }\n };\n config.getSenderAddress = (partitionId) => {\n if (partitionId != undefined) {\n return `${config.entityPath}/Partitions/${partitionId}`;\n }\n else {\n return `${config.entityPath}`;\n }\n };\n config.getReceiverAudience = (partitionId, consumergroup) => {\n if (!consumergroup)\n consumergroup = \"$default\";\n return (`${config.endpoint}${config.entityPath}/ConsumerGroups/${consumergroup}/` +\n `Partitions/${partitionId}`);\n };\n config.getReceiverAddress = (partitionId, consumergroup) => {\n if (!consumergroup)\n consumergroup = \"$default\";\n return `${config.entityPath}/ConsumerGroups/${consumergroup}/Partitions/${partitionId}`;\n };\n return config;\n }",
"get endpointArn() {\n return this.getStringAttribute('endpoint_arn');\n }",
"configure() {\n\n let options = {};\n let pkgCloudConfiguration = this._config._configuration.pkgcloud;\n\n // openstack / rackspace / azure\n if (this._config._configuration.PKG_CLOUD_PROVIDER) {\n options.provider = this._config._configuration.PKG_CLOUD_PROVIDER\n } else if (pkgCloudConfiguration && pkgCloudConfiguration.provider) {\n options.provider = pkgCloudConfiguration.provider;\n } else {\n throw new Error('PkgClient: provider option is not defined, can\\'t create a client.')\n }\n\n if (options.provider === 'openstack' || options.provider === 'rackspace') {\n // Common option user name\n if (this._config._configuration.PKG_CLOUD_USER_NAME) {\n options.username = this._config._configuration.PKG_CLOUD_USER_NAME\n } else if (pkgCloudConfiguration && pkgCloudConfiguration.username) {\n options.username = pkgCloudConfiguration.username;\n } else {\n throw new Error('PkgClient: username option is not defined, can\\'t create a client.')\n }\n }\n\n if (options.provider == 'openstack') {\n\n if (this._config._configuration.PKG_CLOUD_AUTH_URL) {\n options.authUrl = this._config._configuration.PKG_CLOUD_AUTH_URL\n } else if (pkgCloudConfiguration && pkgCloudConfiguration.authUrl) {\n options.authUrl = pkgCloudConfiguration.authUrl;\n } else {\n throw new Error('PkgClient: authUrl option is not defined for openstack provider, can\\'t create a client.')\n }\n\n if (this._config._configuration.PKG_CLOUD_PASSWORD) {\n options.password = this._config._configuration.PKG_CLOUD_PASSWORD\n } else if (pkgCloudConfiguration && pkgCloudConfiguration.password) {\n options.password = pkgCloudConfiguration.password;\n } else {\n throw new Error('PkgClient: password option is not defined for openstack provider, can\\'t create a client.')\n }\n\n } else if (options.provider == 'rackspace') {\n\n if (this._config._configuration.PKG_CLOUD_API_KEY) {\n options.apiKey = this._config._configuration.PKG_CLOUD_API_KEY\n } else if (pkgCloudConfiguration && pkgCloudConfiguration.apiKey) {\n options.apiKey = pkgCloudConfiguration.apiKey;\n } else {\n throw new Error('PkgClient: apiKey option is not defined for openstack provider, can\\'t create a client.')\n }\n\n } else if (options.provider == 'azure') {\n\n if (this._config._configuration.PKG_CLOUD_AZURE_ACCOUNT) {\n options.storageAccount = this._config._configuration.PKG_CLOUD_AZURE_ACCOUNT;\n } else if (pkgCloudConfiguration && pkgCloudConfiguration.azureAccount) {\n options.storageAccount = pkgCloudConfiguration.azureAccount;\n } else {\n throw new Error('PkgClient: storageAccount option is not defined for azure provider, can\\'t create a client.')\n }\n\n if (this._config._configuration.PKG_CLOUD_AZURE_ACCESS_KEY) {\n options.storageAccessKey = this._config._configuration.PKG_CLOUD_AZURE_ACCESS_KEY;\n } else if (pkgCloudConfiguration && pkgCloudConfiguration.azureAccessKey) {\n options.storageAccessKey = pkgCloudConfiguration.azureAccessKey;\n } else {\n throw new Error('PkgClient: storageAccessKey option is not defined for azure provider, can\\'t create a client.')\n }\n\n } else {\n throw new Error(`PkgClient: Unexpected provider '${options.provider}'.`);\n }\n\n // Optional\n if (this._config._configuration.PKG_CLOUD_REGION) {\n options.region = this._config._configuration.PKG_CLOUD_REGION\n } else if (pkgCloudConfiguration && pkgCloudConfiguration.region) {\n options.region = pkgCloudConfiguration.region;\n }\n\n this._options = options;\n\n // Create a client\n this._client = require('pkgcloud').storage.createClient(options);\n }",
"async getConfigProperties() {\n return super.get_auth(`/config`);\n }",
"remoteConfig() {\n const configs = Object.assign({}, Remote_1.RemoteConfig);\n configs.uri = this.apiUrl();\n return configs;\n }",
"function FunctionConfiguration(props) {\n return __assign({ Type: 'AWS::AppSync::FunctionConfiguration' }, props);\n }",
"function getConfigurationModel(axios$$1, identifier) {\n return restAuthGet(axios$$1, 'instance/microservice/' + identifier + '/configuration/model');\n }",
"GetConfig () {\n return { type: types.GET_CONFIG }\n }",
"function getParams(noncurrentVersionTransitions) {\n const rule = {\n ID: 'test',\n Status: 'Enabled',\n Prefix: '',\n NoncurrentVersionTransitions: noncurrentVersionTransitions,\n };\n return {\n Bucket: bucket,\n LifecycleConfiguration: { Rules: [rule] },\n };\n }",
"function Endpoint(props) {\n return __assign({ Type: 'AWS::SageMaker::Endpoint' }, props);\n }",
"fetchConfig_() {\n const ampdoc = this.getAmpDoc();\n const policy = UrlReplacementPolicy.ALL;\n return batchFetchJsonFor(\n ampdoc, this.element, /* opt_expr */ undefined, policy);\n }",
"getOperationFromConfig(funcName, documentationConfig) {\n const operationObj = {\n operationId: funcName\n };\n if (documentationConfig.summary) {\n operationObj.summary = documentationConfig.summary;\n }\n if (documentationConfig.description) {\n operationObj.description = documentationConfig.description;\n }\n if (documentationConfig.tags) {\n operationObj.tags = documentationConfig.tags;\n }\n if (documentationConfig.deprecated) {\n operationObj.deprecated = true;\n }\n if (documentationConfig.requestModels) {\n operationObj.requestBody = this.getRequestBodiesFromConfig(documentationConfig);\n }\n operationObj.parameters = this.getParametersFromConfig(documentationConfig);\n operationObj.responses = this.getResponsesFromConfig(documentationConfig);\n if (documentationConfig.authorizer && this.config.security) {\n const security = this.config.security.find(s => s.authorizerName === documentationConfig.authorizer.name);\n if (security) {\n operationObj.security = [security];\n }\n }\n return operationObj;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
divContent(divId,divContent) Change the content of the div. | function divContent(divId,divContent) {
//console.log('divContent('+divId+','+divContent+')');
if ( document.getElementById(divId) ) {
document.getElementById(divId).innerHTML = divContent;
} else {
console.warn('document.getElementById('+divId+') == udefined');
}
} | [
"updateDivContent() {\n var server = getServer(this.serverKey);\n\n if(this.type == 'status') {\n this.#updateStatusContent(server);\n }\n\n if(this.type == 'queue') {\n this.#updateQueueContent(server);\n }\n\n if(this.type == 'controls') {\n this.#updateControlsContent();\n }\n }",
"function saveDivContent(s_div,actual) {\r\n\r\n s_div = selected_div;\r\n\r\n\tdiv_type = 't'+actual;\r\n \t\t\t\t\r\n\tif (s_div!=actual) {\r\n\r\n\t // var iframe_window = window.frames[\"iView\"];\r\n // var iframe_body_html = iframe_window.document.getElementsByTagName(\"body\")[0].innerHTML;\r\n \r\n\t \r\n\t var myIFrame = document.getElementById(\"iView\");\r\n var iframe_body_html = myIFrame.contentWindow.document.body.innerHTML;\r\n myIFrame.setAttribute(\"allowTransparency\",\"true\");\r\n \r\n \r\n\t if (div_from=='t') {\t\r\n \t // $(\"#text\"+s_div).html(iframe_body_html);\r\n \t \r\n\t\t if ($(\"iframe#iView\").css('visibility')=='visible') $(\"#text\"+s_div).html(iframe_body_html); \r\n\t\t $(\"#text\"+s_div).css('visibility','');\r\n\t }\r\n\t}\r\n\t\r\n\t\r\n\t\r\n\thideDivs(new Array());\r\n\thideImageDivs(new Array());\r\n\thideFlashDivs(new Array()); \r\n\thideVideoDiv();\r\n\thideAudioDivs(new Array());\r\n\t\r\n\t\r\n\t\r\n}",
"function saveImageDivContent(s_div) {\r\n \r\n var ttyp = div_type.substr(0,1);\r\n\r\n var myIFrame = document.getElementById(\"iView\");\r\n var iframe_body_html = myIFrame.contentWindow.document.body.innerHTML;\r\n \r\n if (div_from=='t') { \r\n $(\"#text\"+s_div).html(iframe_body_html);\r\n $(\"#text\"+s_div).css('visibility','');\r\n }\r\n\t \r\n\t \r\n $(\"#iView\").css('visibility','hidden');\r\n $(\"#iView\").css('z-index','-1000');\r\n \r\n \thideDivs(new Array());\r\n\thideImageDivs(new Array());\r\n\thideFlashDivs(new Array());\r\n\thideVideoDiv();\r\n hideAudioDivs(new Array());\r\n}",
"function saveFlashDivContent(s_div) {\r\n\t\r\n\tvar myIFrame = document.getElementById(\"iView\");\r\n var iframe_body_html = myIFrame.contentWindow.document.body.innerHTML;\r\n \r\n if ((div_from=='t')) { \r\n \t $(\"#text\"+s_div).html(iframe_body_html);\r\n\t $(\"#text\"+s_div).css('visibility','');\r\n\t} \r\n\t\r\n\t$(\"#iView\").css('visibility','hidden');\r\n $(\"#iView\").css('z-index','-1000');\r\n\t\r\n\t\r\n\t\r\n\thideDivs(new Array());\r\n\thideImageDivs(new Array());\r\n\thideFlashDivs(new Array());\r\n\thideVideoDiv();\r\n\thideAudioDivs(new Array());\r\n}",
"function DisplayContent({ content, id, style, className, placeholder }: Props) {\n let domParser = null;\n if (!__CLIENT__) {\n const JSDOM = require('jsdom').JSDOM;\n domParser = (val) => new JSDOM(val).window.document;\n }\n return (\n <div key={content} id={id} style={style} className={className}>\n <Editor\n onChange={() => {}}\n onBlur={() => {}}\n onFocus={() => {}}\n value={content}\n placeholder={placeholder}\n disabled\n domParser={domParser}\n />\n </div>\n );\n}",
"function createDiv(divId,divClass,divContent,divInsert) {\n if (divId == undefined) divId = false;\n if (divClass == undefined) divClass = false;\n if (divContent == undefined) divContent = false;\n if (divInsert == undefined) divInsert = false;\n if ( document.body == null ) {\n stackTrace = printStackTrace();\n createDivText = 'createDiv(';\n if (divId) createDivText += '\\''+divId+'\\'';\n if (divClass) createDivText += '\\''+divClass+'\\'';\n if (divContent) createDivText += '\\''+divContent+'\\'';\n if (divInsert) createDivText += '\\''+divInsert+'\\'';\n printStackTrace();\n createDivText += ')';\n alertText = 'Error in call of '+createDivText+'!\\n\\n';\n alertText += 'The document body in not loaded so the createDiv function cannot be called.\\n';\n alertText += 'To corect this, add a function that creates the div(s) then add the function to the onload event.\\n\\n';\n alertText += '// A function to create the div(s) if they are not on the page.\\nfunction createDivs() {\\n';\n alertText += ' '+createDivText+';\\n // Place any other createDiv calls below the one above\\n';\n alertText += '}\\n';\n alertText += '// Add the createDivs() function to the onload event.\\n';\n alertText += 'var oldLoad = window.onload;\\nvar newLoad = oldLoad ? function(){createDivs.call(this);oldLoad.call(this);} : createDivs\\nwindow.onload = newLoad;\\n\\n';\n alertText += 'Stack trace:\\n'+stackTrace+'\\n';\n alert(alertText+'\\n\\nThis error will be inserted into the page text so you can copy it.');\n alertText = alertText.replace(/\\n/g,'<br>');\n document.write(alertText+'<br><br>');\n return;\n }\n var newDivElement = document.createElement(\"div\");\n if (divId) newDivElement.id = divId;\n if (divClass) newDivElement.className = divClass;\n if (divContent) newDivElement.innerHTML = divContent;\n if (divInsert) {\n // Ensure that the divInsert element exists.\n divInsertId = document.getElementById(divInsert);\n //alert('divInsertId='+divInsertId.id);\n if (divInsertId) {\n // The element exists, insert the new div and return.\n //alert('document.body.insertBefore(newDivElement, \\''+divInsert+'\\');');\n divInsertId.parentNode.insertBefore(newDivElement, divInsertId);\n return;\n }\n }\n document.body.appendChild(newDivElement);\n}",
"function divShow(divId) {\n //console.log('divShow('+divId+')');\n\tif ( document.getElementById(divId) ) {\n\t document.getElementById(divId).style.display = 'block';\n\t} else {\n\t\tconsole.warn('document.getElementById('+divId+') == udefined');\n\t}\n}",
"function cargarDiv(origen, destino)\r\n{\r\n\t$.ajax(\r\n\t{\r\n\t\turl : origen,\r\n\t\tsuccess : function(data)\r\n\t\t{\r\n\t\t\t$('#' + destino).html(data);\r\n\t\t}\r\n\t});\r\n}",
"function addNewContent() {\n var para = document.createElement(\"p\");\n var node = document.createTextNode(\"The new text\");\n para.appendChild(node);\n\n var targetDiv = document.getElementById(\"theDiv\");\n targetDiv.appendChild(para);\n\n console.log(targetDiv.innerHTML);\n}",
"function SetContent(selectedContentNumber) {\n\n SetPicture(selectedContentNumber);\n SetDescriptionText(selectedContentNumber);\n\n}",
"function updateContent() {\n var objData = _buildDataObject(vm.modelContent, 'updateContentBasic');\n objData.content._id = vm.modelContent._id.toString();\n\n return CioContentService.updateContent(objData,\n function(objErr, objResult, objPendingEvent) {\n \n if (objErr) {\n // do something\n }\n if (objPendingEvent) {\n return $rootScope.pending.set(objPendingEvent.loaded, objPendingEvent.total);\n }\n if (objResult) {\n return $state.go($state.current, {}, { reload: true });\n }\n });\n }",
"function removePopupContentDiv(popupContentDiv){\n\tpopupContentDiv.remove();\n\tuploadId--;\n\tif(uploadId === 0){\n\t\tclosePopup();\n\t}\n}",
"function divHideShow(divId) {\n //console.log('divHide('+divId+')');\n\tif ( document.getElementById(divId) ) {\n\t\tif ( divDisplayState(divId) == 'none' ) {\n\t\t\tdivShow(divId);\n\t\t} else {\n\t\t\tdivHide(divId);\n\t\t}\n\t} else {\n\t\tconsole.warn('document.getElementById('+divId+') == udefined');\n\t}\n}",
"function divHide(divId) {\n //console.log('divHide('+divId+')');\n\tif ( document.getElementById(divId) ) {\n\t document.getElementById(divId).style.display = 'none';\n\t} else {\n\t\tconsole.warn('document.getElementById('+divId+') == udefined');\n\t}\n}",
"function setData(object, divID){\n\n\n var data = document.createElement('p');\n data.innerHTML = object.AUTHOR;\n data.style.fontWeight = \"bold\";\n data.style.color = \"black\";\n document.getElementById(divID).appendChild(data);\n}",
"function divShowInline(divId) {\n //console.log('divShow('+divId+')');\n\tif ( document.getElementById(divId) ) {\n\t document.getElementById(divId).style.display = 'inline';\n\t} else {\n\t\tconsole.warn('document.getElementById('+divId+') == udefined');\n\t}\n}",
"function fillBox (box, content) {\n\n box.html(content);\n }",
"function divShowOnly(divHideList,divId) {\n //console.log('divShow('+divHideList+','+divId+')');\n\tif ( document.getElementById(divId) ) {\n\t\tvar divHideArray = divHideList.split(\",\");\n\t\tfor(var i=0; i<divHideArray.length; i++){\n\t\t\tdivHide(divHideArray[i]);\n\t\t}\n\t\tdivShow(divId);\n\t} else {\n\t\tconsole.warn('document.getElementById('+divId+') == udefined');\n\t}\n}",
"setTextContent(textContent) {\n // We could set `innerHTML`, but it's better to avoid it.\n ReactDOM\n .findDOMNode(this)\n .textContent = textContent || '';\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Define a function for generating and loading a robot energy sprite | function newBattleRobotEnergySprite(battleTeam, robotKey, robotSpriteKey){
//console.log('thisGame.newBattleRobotEnergySprite()', battleTeam, robotKey, robotSpriteKey);
// Define a pointer to the appropriate team if exists, else create it
if (typeof thisGame.battleRobots[battleTeam] === 'undefined'){ thisGame.battleRobots[battleTeam] = []; }
var battleTeamRobots = thisGame.battleRobots[battleTeam];
// Create the status bar icon for this robot
var energySpriteKey = robotSpriteKey + '/energy';
var robotEnergySprite = {
filePath: thisGame.gameSettings.baseCorePath + 'images/robot-status_'+battleTeamRobots[robotKey].robotDirection+'.png',
basePosition: [0, 0, 0, 1],
currentPosition: [0, 0, 0, 1],
frameWidth: 26,
frameHeight: 71,
frameSpeed: 1,
frameLayout: 'vertical',
frameSequence: [0],
frameAnimationSequence: [{
// pan up
startPosition: [0, 0],
endPosition: [0, -5],
frameDuration: 30
}, {
// pan down
startPosition: [0, -5],
endPosition: [0, 0],
frameDuration: 30
}]
};
var statusPositionMod = function(){
var battleRobot = battleTeamRobots[robotKey];
var positionMod = battleRobot.robotDirection == 'left' ? 1 : -1;
return positionMod;
}
var statusPositionOffset = function(){
var battleRobot = battleTeamRobots[robotKey];
var positionMod = statusPositionMod();
var overflowValue = battleRobot.robotSprite.frameSize - 80;
var positionOffset = positionMod * Math.ceil(battleRobot.robotSprite.frameSize * 0.5);
if (overflowValue > 0){
positionOffset -= Math.ceil(overflowValue / 4) * positionMod;
//positionOffset -= positionMod * Math.ceil(robotEnergySprite.frameWidth / 2);
}
return positionOffset;
};
var statusPositionX = function(){
var battleRobot = battleTeamRobots[robotKey];
var positionMod = statusPositionMod();
var positionX = battleRobot.robotSprite.currentPosition[0] + statusPositionOffset();
var overflowValue = battleRobot.robotSprite.frameSize - 80;
positionX += robotEnergySprite.frameWidth;
if (overflowValue > 0){
positionX += Math.ceil(overflowValue / 2);
positionX -= positionMod * Math.ceil(robotEnergySprite.frameWidth / 2);
}
//positionX -=
return positionX;
};
var statusPositionY = function(){
var battleRobot = battleTeamRobots[robotKey];
var positionMod = statusPositionMod();
var positionY = battleRobot.robotSprite.currentPosition[1] - 20;
var overflowValue = battleRobot.robotSprite.frameSize - 80;
if (overflowValue > 0){
positionY += overflowValue;
}
return positionY;
};
var statusPositionZ = function(){
var battleRobot = battleTeamRobots[robotKey];
var positionZ = battleRobot.robotSprite.currentPosition[2] + 1;
return positionZ;
};
robotEnergySprite.basePosition = [statusPositionX, statusPositionY, statusPositionZ];
robotEnergySprite.globalFrameStart = thisGame.gameState.currentFrame;
robotEnergySprite.currentFrameKey = 0;
robotEnergySprite.spriteObject = thisGame.newCanvasSprite(
energySpriteKey,
robotEnergySprite.filePath,
robotEnergySprite.frameWidth,
robotEnergySprite.frameHeight,
robotEnergySprite.frameLayout,
robotEnergySprite.frameSpeed,
robotEnergySprite.frameSequence
);
thisGame.gameSpriteIndex[energySpriteKey] = robotEnergySprite;
thisGame.updateCanvasSpriteRenderOrder()
} | [
"function CreateSprite(paths, size_factor, size_min,\n\t\t speed_factor, speed_min, left, right){\n\n // Make the mesh \n var size = Math.random()*size_factor + size_min;\n var trand = Math.floor(Math.random()*paths.length);\n var texture= THREE.ImageUtils.loadTexture(paths[trand]);\n var material = new THREE.SpriteMaterial( { map: texture, fog: true, } );\n var sprite = new THREE.Sprite( material );\n sprite.scale.set(size, size, size);\n var speed = Math.random() *speed_factor + speed_min;\n\n // Initial placement\n x = (Math.random()*(right-left))-((right-left)/2);\n y = (Math.random()*3000)-1000;\n sprite = new FallingObject(sprite, speed, x, y, -1000, 0, -1, 0);\n sprite.set_box_rules(2000, -1000, left, right);\n\n \n //sprite.place();\n\n return sprite;\n}",
"function SLTReelSprite() {\n this.initialize.apply(this, arguments);\n}",
"constructor(name, pixelWidth, pixelHeight, pixelOffsetX, pixelOffsetY, sight, hitPoints, cost,\n spriteImages, defaults, radius, range, moveSpeed, interactSpeed, firePower, builtFrom, weaponType) {\n super(name, pixelWidth, pixelHeight, pixelOffsetX, pixelOffsetY,\n sight, hitPoints, cost, spriteImages, defaults);\n this.defaults.type = 'units';\n this.radius = radius;\n this.range = range;\n this.moveSpeed = moveSpeed;\n this.interactSpeed = interactSpeed;\n this.firePower = firePower;\n this.builtFrom = builtFrom;\n\t\tthis.weaponType = weaponType;\n this.directions = 4;\n this.animationIndex = 0;\n this.imageOffset = 0;\n this.canAttack = true;\n this.canMove = true;\n this.turnSpeed = 2;\n this.speedAdjustmentWhileTurningFactor = 0.5;\n }",
"function setupSpriteSheets(){\n \n var levelobjectimage;\n \tvar levelobjectframes;\n \tvar levelobjectanimations;\n \tvar levelobjectwidth;\n \tvar levelobjectheight;\n //Build spritesheets and animations for the level objects\n\tfor(var i = 0; i < leveldata.length; i++){\n\t\tswitch (leveldata[i].type){\n\t\t\tcase \"egg\" :\n\t\t\t\tlevelobjectimage = imageEgg;\n\t\t\t\tlevelobjectframes = {width:20, height:30, regX:0, regY:0};\n\t\t\t\tlevelobjectanimations = {\n\t\t\t\t\tdefaultanimation: [0, 15, \"defaultanimation\", .25]\n\t\t\t\t};\n\t\t\t\tlevelobjectwidth = 20;\n\t\t\t\tlevelobjectheight = 30;\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t}\n\t\t\n\t\tleveldata[i].spritesheet = new createjs.SpriteSheet({\n\t\t\timages: [levelobjectimage],\n\t\t\tframes: levelobjectframes,\n\t\t\tanimations: levelobjectanimations\n\t\t});\n\t\tleveldata[i].animation = new createjs.Sprite(leveldata[i].spritesheet);\n\t\tleveldata[i].animation.currentFrame = 0;\n\t\tleveldata[i].width = levelobjectwidth;\n\t\tleveldata[i].height = levelobjectheight;\n\t\t\n\t\tleveldata[i].resetX = leveldata[i].posX;\n\t}\n\t\n\t//Create waves\n\tvar waveSS = new createjs.SpriteSheet({\n\t\timages: [imageWave],\n\t\tframes: {width:480, height:10, regX:0, regY:0},\n\t\tanimations: {\n\t\t\tfastest: {\n\t\t\t\tframes: [0, 2, 4, 6, 8, 10],\n\t\t\t\tnext: \"fastest\",\n\t\t\t\tfrequency: 1\n\t\t\t},\n\t\t\tfaster: [0, 11, \"faster\",1],\n\t\t\tslower: [0, 11, \"slower\",2],\n\t\t\tslowest: [0, 11, \"slowest\",3]\n\t\t}\n\t});\n\twaveAnimation = new createjs.Sprite(waveSS);\n\twaveAnimation.gotoAndPlay(\"fastest\");\n\twaveAnimation.currentFrame = 0;\n\twaveAnimation.x = 0;\n\twaveAnimation.y = waterlineY-7;\n\tstage.addChild(waveAnimation);\n\t\n\t//Create sd sprite\n\tvar sharkduckSS = new createjs.SpriteSheet({\n\t\timages: [imageSharkduckAll],\n\t\tframes: {width:60, height:30, regX:0, regY:0},\n\t\tanimations: {\n\t\t\tswim: [0, 7, \"swim\", .25],\n\t\t\tswimfast: [0, 7, \"swimfast\", .5],\n\t\t\tfly: [8, 15, \"fly\", .25],\n\t\t\tflyfast: [8, 15, \"flyfast\", .5]\n\t\t}\n\t});\n\t\n\t//Make the animation\n\tsharkduckAnimation = new createjs.Sprite(sharkduckSS);\n sharkduckAnimation.gotoAndPlay(\"fly\"); \t//animate\n sharkduckAnimation.name = \"sharkduck\";\n sharkduckAnimation.currentFrame = 0;\n \n //Create container for sharkduck's animation and effects\n sharkduckContainer = new createjs.Container();\n sharkduckContainer.directionY = 1;\n sharkduckContainer.vY = 2;\n sharkduckContainer.x = 60;\n sharkduckContainer.y = waterlineY-7;\n sharkduckContainer.addChild(sharkduckAnimation);\n \n stage.addChild(sharkduckContainer);\n}",
"function Terrain_Square(x,y,w,h,type,which_sprite_array,name_of_sprite_sheet){\n\n\tthis.x = x * w;\n\tthis.y = y * h; \n\tthis.w = w;\n\tthis.h = h;\n\n\t//console.log(\"1which_sprite_array is: \" + which_sprite_array);\n\t\n\t//so that these 4 values dont need to be calculated over and over again. \n\tthis.ulc_x = this.x;\n\tthis.urc_x = this.x + this.w;\n\tthis.ulc_y = this.y;\n\tthis.llc_y = this.y + this.h;\n\n\tthis.contains_mouse = false;\n\tthis.color = \"black\";//random default. not associated with any type currently. \n\n\tif(type == 0){\n\t\tthis.color = \"yellow\";\n\t}\n\telse if(type == 1){\n\t\tthis.color = \"red\";\n\t}\n\n\t\n\tthis.type = type; //can it be walked on.\n\tthis.sprite_sheet = document.getElementById(name_of_sprite_sheet);\n\tthis.ssi = new SSI();\n\tthis.ssi.set_x_y_w_h_dw_and_dh(which_sprite_array[0],\n\t\t\t\t\t\t\t\t which_sprite_array[1],\n\t\t\t\t\t\t\t\t which_sprite_array[2],\n\t\t\t\t\t\t\t\t which_sprite_array[3],\n\t\t\t\t\t\t\t\t this.w,\n\t\t\t\t\t\t\t\t this.h\n\t\t\t\t\t\t\t\t );\n\n}",
"function createVehicle() {\n var vehicleAssets = [\"tempCar\"];\n var randomAssetNo = Math.floor(Math.random()*vehicleAssets.length);\n var v = [new Sprite(\"/sprites/vehicles/\"+vehicleAssets[randomAssetNo]),\"right\"];\n v[0].pos[0]= (window.innerWidth/2)-(10*tileSize)/2+(0*tileSize);\n v[0].pos[1]= (window.innerHeight/2)-(10*tileSize)/2+(6*tileSize);\n vehicles[vehicles.length] = v;\n}",
"createSprite() {\n this.sprite = new PIXI.Sprite(PIXI.loader.resources[this.category].textures[this.spriteName]);\n if(this.isOnFloor) {\n this.sprite.position.set(this.x, this.y);\n }\n this.sprite.width = this.sprite.height = this.spriteSize;\n this.floor.itemSprites.addChild(this.sprite);\n\n // would be nice to consolidate to a function. currently not working\n // this._textStyle = new PIXI.TextStyle({\n // fill: '#fff',\n // fontSize: 17\n // });\n // this.itemNameSprite = new PIXI.Text(this.spriteName, this._textStyle);\n // /* eslint-disable-next-line no-extra-parens */\n // this.itemNameSpriteOffset = (this.sprite.width / 2) - (this.itemNameSprite.width / 2);\n // this.itemNameSprite.position.set(\n // this.sprite.position.x + this.itemNameSpriteOffset,\n // this.sprite.position.y - 15\n // );\n // this.floor.itemSprites.addChild(this.itemNameSprite);\n }",
"function renderNPCSprites(aDev,aGame)\n{\n ////this makes a temp object of the image we want to use\n //this is so the image holder does not have to keep finding image\n tempImage1 = aDev.images.getImage(\"orb\")\n tempImage2 = aDev.images.getImage(\"fireAmmo\")\t\n for (var i = 0; i < aGame.gameSprites.getSize(); i++)\n {\t\n ////this is to make a temp object for easier code to write and understand\n tempObj = aGame.gameSprites.getIndex(i); \n switch(tempObj.name)\n {\n case \"orb\":\n aDev.renderImage(tempImage1,tempObj.posX,tempObj.posY);\n break;\n case \"fireAmmo\":\n aDev.renderImage(tempImage2,tempObj.posX,tempObj.posY);\n break;\n } \n }\n}",
"function TestEntity1() {\n this.sprite = new Sprite(0,0,20, \"blue\");\n}",
"function loadBehaviours() {\n\n var elWidth = backgroundCanvas.width * 0.20;\n var elHeight = backgroundCanvas.height * 0.85;\n\n var turret = {};\n turret.image = new Image();\n turret.image.src = \"../Images/turret.png\";\n\n behaviours.turret = turret;\n\n plusImage = new Image();\n plusImage.src = \"../Images/plusImage.png\"\n\n}",
"init() {\n\t\tdocument.body.append(this.view);\n\t\tthis.functions.load();\n\t\tthis.Loader.load(async (loader, resources) => {\n\t\t\tlet i = 0;\n\t\t\tfor (const [name, value] of Object.entries(resources)) {\n\t\t\t\tif (loader.rorkeResources[i].options) {\n\t\t\t\t\tconst urls = await this.Loader.splitSpritesheetIntoTiles(\n\t\t\t\t\t\tvalue.data,\n\t\t\t\t\t\tloader.rorkeResources[i].options,\n\t\t\t\t\t);\n\t\t\t\t\tconst textures = urls.map(tile => Texture.from(tile));\n\t\t\t\t\tthis.spritesheets.set(name, {\n\t\t\t\t\t\ttexture: value.texture,\n\t\t\t\t\t\toptions: loader.rorkeResources[i].options,\n\t\t\t\t\t\ttiles: urls,\n\t\t\t\t\t\ttextures,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tthis.textures.set(name, value.texture);\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\n\t\t\tthis.runCreate();\n\t\t});\n\t}",
"function LotLineSprite() {\n this.initialize.apply(this, arguments);\n}",
"levelSetup() {\n //mapSprites\n this.mapSprites.removeChildren();\n function maybeRandom(val) {\n if (Array.isArray(val)) {\n return val[Math.floor(Math.random() * val.length)];\n }\n return val;\n }\n for (var x = 0; x < this.level.width; x++) {\n for (var y = 0; y < this.level.height; y++) {\n const tile = this.map.getTile(x, y);\n let sprite;\n if (!tile.bitMaskMap) {\n sprite = new PIXI.Sprite(\n this.game.display.tilesetMapping[tile.tileset][maybeRandom(tile.id)]\n );\n } else {\n sprite = new PIXI.Sprite(\n this.game.display.tilesetMapping[tile.tileset][\n maybeRandom(tile.bitMaskMap[tile.bitMask])\n ]\n );\n }\n sprite.x = x * this.game.display.tileSize.x;\n sprite.y = y * this.game.display.tileSize.y;\n sprite.tint = `0x${tile.fg.substring(1)}`;\n sprite.alpha = 0;\n this.mapSprites.addChild(sprite);\n }\n }\n this.levelSprites.addChild(this.mapSprites);\n // set map position\n const screenWidth = this.game.getScreenWidth();\n const screenHeight = this.game.getScreenHeight();\n let topLeftX = Math.max(0, this.player.getX() - screenWidth / 2);\n topLeftX = Math.min(topLeftX, this.level.width - screenWidth);\n\n let topLeftY = Math.max(0, this.player.getY() - screenHeight / 2);\n topLeftY = Math.min(topLeftY, this.level.height - screenHeight);\n\n this.levelSprites.position.set(\n -topLeftX * this.game.display.tileSize.x,\n -topLeftY * this.game.display.tileSize.y\n );\n\n //entitySprites\n this.entitySprites.removeChildren();\n const entities = this.level.getEntities();\n Object.values(entities).forEach(entity => {\n const sprite = new PIXI.Sprite(\n this.game.display.tilesetMapping[entity.tileset][entity.id]\n );\n sprite.index = entity.index;\n sprite.alpha = 1;\n sprite.tint = `0x${entity.fg.substring(1)}`;\n sprite.position.set(\n entity.getX() * this.game.display.tileSize.x,\n entity.getY() * this.game.display.tileSize.y\n );\n this.entitySprites.addChild(sprite);\n });\n this.levelSprites.addChild(this.entitySprites);\n //itemSprites\n this.itemSprites.removeChildren();\n const items = this.level.getItems();\n Object.keys(items).forEach(itemKey => {\n const [x, y] = itemKey.split(',');\n const item = items[itemKey];\n let sprite = new PIXI.Sprite(\n this.game.display.tilesetMapping[item.tileset][item.id]\n );\n sprite.index = item.index;\n sprite.alpha = 1;\n sprite.tint = Colors.getHex(item.fg);\n sprite.position.set(\n x * this.game.display.tileSize.x,\n y * this.game.display.tileSize.y\n );\n this.itemSprites.addChild(sprite);\n });\n this.levelSprites.addChild(this.itemSprites);\n //playerSprite\n this.playerSprite = new PIXI.Sprite(\n this.game.display.tilesetMapping[this.player.tileset][this.player.id]\n );\n this.playerSprite.position.set(\n (this.player.getX() - topLeftX) * this.game.display.tileSize.x,\n (this.player.getY() - topLeftY) * this.game.display.tileSize.y\n );\n this.game.display.app.stage.addChild(this.playerSprite);\n this.game.display.app.stage.addChild(this.levelSprites);\n //minimap\n this.minimap = new PIXI.Container();\n // this.minimap.x = this.screenWidth * this.game.display.tileSize.x\n this.minimap.x = this.game.screenWidth * this.game.display.tileSize.x;\n this.minimap.background;\n for (let x = 0; x < this.level.map.width; x++) {\n for (let y = 0; y < this.level.map.height; y++) {\n let tile = this.level.map.getTile(x, y);\n let pixel = new PIXI.Graphics();\n pixel.beginFill(Colors.getHex(tile.fg));\n pixel.drawRect(0, 0, 2, 2);\n pixel.x = x * 2;\n pixel.y = y * 2;\n pixel.endFill();\n pixel.alpha = 0;\n this.minimap.addChild(pixel);\n }\n }\n this.playerPixel = new PIXI.Graphics();\n this.playerPixel.beginFill(Colors.getHex('#ffffff'));\n this.playerPixel.drawRect(0, 0, 2, 2);\n this.playerPixel.x = this.player.x * 2;\n this.playerPixel.y = this.player.y * 2;\n this.playerPixel.endFill();\n this.playerPixel.alpha = 1;\n this.minimap.addChild(this.playerPixel);\n this.game.display.app.stage.addChild(this.minimap);\n }",
"updateSprite() {\n\t\tif(!this.multiTexture) {\n\t\t\tthis.graphics.sprite.texture = PIXI.Texture.fromFrame('sprite_' + (this.id < 10 ? '0' : '') + this.id + '.png');\n\t\t}\n\t\telse {\n\t\t\tthis.graphics.sprite.texture = PIXI.Texture.fromFrame('sprite_' + (this.id < 10 ? '0' : '') + this.id + '_' +\n\t\t\t\t\t\t\t\t\t\t\t(this.multiTextureId < 10 ? '0' : '') + this.multiTextureId + '.png');\n\t\t}\n\t}",
"preload() {\n this.load.sprite('gun', 'assets/sprites/gun.png');\n }",
"function addRobot() {\n loader = new THREE.GLTFLoader();\n loader.load('models/GLTF/RobotExpressive.glb',\n function (gltf) {\n // Import robot and his animations and add them to the scene\n //adds shadow to the robot\n gltf.scene.traverse(function (robot) {\n if (robot instanceof THREE.Mesh) {\n robot.castShadow = true;\n }\n });\n robot = gltf.scene;\n animations = gltf.animations;\n scene.add(robot);\n // Set positions \n robot.position.y = 1.05;\n robot.position.z = 9;\n robot.scale.set(0.3, 0.3, 0.3);\n\n // Rotation\n robot.rotation.y = Math.PI;\n\n // Play Idle animation at first \n mixer = new THREE.AnimationMixer(robot);\n let clip = THREE.AnimationClip.findByName(animations, state.name);\n let action = mixer.clipAction(clip);\n action.play();\n\n })\n }",
"function Sprite_HpBar() {\n this.initialize.apply(this, arguments);\n}",
"function setupHUDelements(){\n\tfor (var i = 0; i < 10; i++){ //Set up bitmaps now so that all we do later is turn them on\n\t\thudElements.eggBitmaps[i] = new createjs.Bitmap(imageEgg);\n\t\thudElements.eggBitmaps[i].sourceRect = new createjs.Rectangle(0,0,20,30);\n\t\thudElements.eggBitmaps[i].x = (thecanvas.width - 20) - (15 * i);\n\t\thudElements.eggBitmaps[i].y = 245;\n\t\thudElements.eggBitmaps[i].scaleX = .5;\n\t\thudElements.eggBitmaps[i].scaleY = .5;\n\t}\n\t\n\thudElements.scoreText = new createjs.Text(\"score: \" + score, \"16px Arial\", \"#fff\");\n\thudElements.scoreText.x = 10;\n\thudElements.scoreText.y = 260;\n\tstage.addChild(hudElements.scoreText);\n\t\n\thudElements.speedText = new createjs.Text(\"speed: \", \"16px Arial\", \"#fff\");\n\thudElements.speedText.x = 150;\n\thudElements.speedText.y = 260;\n\tstage.addChild(hudElements.speedText);\n\t\n hudElements.speedBarG = new createjs.Graphics();\n\thudElements.speedBarG.beginFill(\"#d33\");\n\thudElements.speedBarG.rect(0,0,1, 20);\n\thudElements.speedBarShape = new createjs.Shape(hudElements.speedBarG);\n\thudElements.speedBarShape.x = 200;\n\thudElements.speedBarShape.y = 245;\n\t\n\tstage.addChild(hudElements.speedBarShape);\n\t\n}",
"reloadTexture(){\n this.blochDiagram.loadTexture('qbloch');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is a function for postV3ProjectsIdRepositoryTagsTagNameRelease | postV3ProjectsIdRepositoryTagsTagNameRelease(incomingOptions, cb) {
const Gitlab = require('./dist');
let defaultClient = Gitlab.ApiClient.instance;
// Configure API key authorization: private_token_header
let private_token_header = defaultClient.authentications['private_token_header'];
private_token_header.apiKey = 'YOUR API KEY';
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//private_token_header.apiKeyPrefix = 'Token';
// Configure API key authorization: private_token_query
let private_token_query = defaultClient.authentications['private_token_query'];
private_token_query.apiKey = 'YOUR API KEY';
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//private_token_query.apiKeyPrefix = 'Token';
let apiInstance = new Gitlab.ProjectsApi()
/*let id = "id_example";*/ // String | The ID of a projec
/*let tagName = "tagName_example";*/ // String | The name of the ta
/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE |
apiInstance.postV3ProjectsIdRepositoryTagsTagNameRelease(incomingOptions.id, incomingOptions.tagName, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {
if (error) {
cb(error, null)
} else {
cb(null, data)
}
});
} | [
"postV3ProjectsIdRepositoryTags(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdRepositoryTags(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"putV3ProjectsIdRepositoryTagsTagNameRelease(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let tagName = \"tagName_example\";*/ // String | The name of the ta\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.putV3ProjectsIdRepositoryTagsTagNameRelease(incomingOptions.id, incomingOptions.tagName, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"async _saveBlogTags() {\n for (const [key, tags] of Object.entries(this.blogTagsPerBlogPost)) {\n const proms = tags.filter(tag => typeof tag.id === 'string').map(tag => {\n return this._rpc({\n model: 'blog.tag',\n method: 'create',\n args: [{\n 'name': tag.name,\n }],\n });\n });\n const createdIDs = await Promise.all(proms);\n\n await this._rpc({\n model: 'blog.post',\n method: 'write',\n args: [parseInt(key), {\n 'tag_ids': [[6, 0, tags.filter(tag => typeof tag.id === 'number').map(tag => tag.id).concat(createdIDs)]],\n }],\n });\n }\n }",
"function Tag(repository, obj) {\n this.repository = repository;\n obj.tagger = new Signature(obj.tagger);\n _immutable(this, obj).set(\"id\").set(\"name\").set(\"message\").set(\"tagger\").set(\"target\", \"targetId\").set(\"type\");\n }",
"postV3ProjectsIdRepositoryBranches(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdRepositoryBranches(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdStatusesSha(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let sha = \"sha_example\";*/ // String | The commit has\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdStatusesSha(incomingOptions.id, incomingOptions.sha, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdLabels(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdLabels(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdIssues(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdIssues(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdTriggers(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a project\napiInstance.postV3ProjectsIdTriggers(incomingOptions.id, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdSnippets(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdSnippets(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdIssuesIssueIdAwardEmoji(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = 56;*/ // Number |\n/*let issueId = 56;*/ // Number |\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdIssuesIssueIdAwardEmoji(incomingOptions.id, incomingOptions.issueId, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdEnvironments(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The project I\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdEnvironments(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdRefReftriggerBuilds(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let ref = \"ref_example\";*/ // String | The commit sha or name of a branch or ta\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdRefReftriggerBuilds(incomingOptions.id, incomingOptions.ref, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdUploads(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdUploads(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }",
"postV3ProjectsIdIssuesNoteableIdNotes(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let noteableId = 56;*/ // Number | The ID of the noteabl\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdIssuesNoteableIdNotes(incomingOptions.id, incomingOptions.noteableId, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdLabelsSubscribableIdSubscription(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let subscribableId = \"subscribableId_example\";*/ // String | The ID of a resource\napiInstance.postV3ProjectsIdLabelsSubscribableIdSubscription(incomingOptions.id, incomingOptions.subscribableId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdSnippetsSnippetIdAwardEmoji(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = 56;*/ // Number |\n/*let snippetId = 56;*/ // Number |\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdSnippetsSnippetIdAwardEmoji(incomingOptions.id, incomingOptions.snippetId, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdDeployKeys(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of the projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdDeployKeys(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdRepositoryCommitsShaComments(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let sha = \"sha_example\";*/ // String | The commit's SH\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdRepositoryCommitsShaComments(incomingOptions.id, incomingOptions.sha, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Exit a parse tree produced by Java9ParsercompilationUnit. | exitCompilationUnit(ctx) {
} | [
"exitOrdinaryCompilation(ctx) {\n\t}",
"exitModularCompilation(ctx) {\n\t}",
"visitExit_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"exitStatementWithoutTrailingSubstatement(ctx) {\n\t}",
"function Return() {\n \t\t\tdebugMsg(\"ProgramParser : Return\");\n \t\t\tvar line=lexer.current.line;\n \t\t\t\n \t\t\tlexer.next();\n \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\tvar ast=new ASTUnaryNode(\"return\",expr);\n \t\t\tast.line=line;\n \t\t\treturn ast;\n \t\t}",
"exitBlockLevelExpression(ctx) {\n\t}",
"exitPreprocessorParenthesis(ctx) {\n\t}",
"exitNormalClassDeclaration(ctx) {\n\t}",
"exitMultiVariableDeclaration(ctx) {\n\t}",
"visitUnit_statement(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"exitJumpExpression(ctx) {\n\t}",
"exitClassLiteral(ctx) {\n\t}",
"exitPostfixUnaryExpression(ctx) {\n\t}",
"exitBasicForStatement(ctx) {\n\t}",
"exitUnannPrimitiveType(ctx) {\n\t}",
"exitStatementNoShortIf(ctx) {\n\t}",
"exitTryExpression(ctx) {\n\t}",
"endGroup() {\n if (this.undefStack.length === 0) {\n throw new ParseError(\"Unbalanced namespace destruction: attempt \" + \"to pop global namespace; please report this as a bug\");\n }\n\n const undefs = this.undefStack.pop();\n\n for (const undef in undefs) {\n if (undefs.hasOwnProperty(undef)) {\n if (undefs[undef] === undefined) {\n delete this.current[undef];\n } else {\n this.current[undef] = undefs[undef];\n }\n }\n }\n }",
"exitFunctionLiteral(ctx) {\n\t}",
"function STLangVisitor() {\n STLangParserVisitor.call(this);\n this.result = {\n \"valid\": true,\n \"error\": null,\n \"tree\": {\n \"text\": \"\",\n \"children\": null\n }\n };\n\treturn this;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes a contact with matching UID from the contact list and updates te list of letters that can be used to filter contacts | deleteContact ({ commit, state }, data) {
state.contacts = state.contacts.filter(({ uid }) => {
return uid !== data.uid
})
const letters = getLettersForFilter(state.contacts)
commit('updateFilterLetters', letters)
} | [
"function removeFriendElement(uid) {\n document.getElementById(\"user\" + uid).remove();\n\n friendCount--;\n if(friendCount == 0){\n deployFriendListEmptyNotification();\n }\n }",
"function deleteContact(){\n\tif(!confirm(\"Are you sure you want to delete this contact?\")){\n\t\treturn;\n\t}\n\tbody = {\n\t\tid: CONTACTS[currentIndex]._id\n\t}\n\n\t$.ajax({\n\t\turl: urlBase + 'api/deleteContact',\n\t\t\ttype: 'delete',\n\t\t\tdata: JSON.stringify(body),\n\t\t\theaders: { \"Content-Type\": \"application/json\", \"Authorization\": \"Bearer \" + getCookie(\"USER\") },\n\t\t\tdataType: 'json',\n\t\t\tsuccess: function (data) {\n\t\t\t\tconsole.log(data);\n\t\t\t\t\tif(data.success === false){\n\t\t\t\talert(\"Could not Delete Contact: \\n\" + data.error._message );\n\t\t\t}\n\t\t\telse{\n\t\t\t\tcurrentIndex = -1;\n\t\t\t\tgetContacts();\n\t\t\t}\n\t\t\t},\n\t\terror: function (error){\n\t\t\tconsole.log(\"ERROR DELETING USER: \");\n\t\t\t\tconsole.log(error);\n\t\t}\n\t});\n}",
"function removeThis() {\n var spaced = addSpace(document.getElementById(\"removeMe\").value);\n var Sanitize2 = spaced;\n var upperCase = Sanitize2.toUpperCase();\n var re = /^[A-Z]{4}\\s{1}[A-Z0-9]+/;\n if (re.test(upperCase) == 0) {\n alert(\"Not a Valid Input. Please follow this format: COEN 10\");\n document.getElementById(\"removeMe\").innerHTML = \"\";\n return;\n }\n\n var y = upperCase;\n var d = courses.indexOf(y);\n if (courses.indexOf(y) >= 0) {\n courses.splice(d, 1);\n populate();\n reset();\n populate();\n } else {\n alert(\"Cannot Remove\");\n }\n}",
"function removeUserFromList(listName, userName) {\r\n\tvar curList\t= getValue(listName,'');\r\n\r\n\t// We add a leading and trailing ;, so that when searching for ;username; to replace will find even the ones at the beginning or end of the string\r\n\tcurList\t\t= ';' + curList\r\n\r\n\t// escape the userName and then search for it; the string we have is an escaped version of the string\r\n\tuserName\t= ';' + urlencode( userName );\r\n\r\n\t// Remove the user from the list\r\n\tvar iUser\t= curList.search( userName );\r\n\tif ( iUser > -1 ) {\r\n\t\tcurList\t\t= getValue( listName, '');\r\n\t\tcurList\t\t= curList.replace( userName, \"\");\r\n\t\tsetValue( listName, curList );\r\n\t } else {\r\n\t}\r\n\r\n }",
"function updateAttendees(event) {\n\tvar attendee_name = $(this).attr(\"value\");\n\tvar attendee_email = \"\";\n\n\tvar contacts_list = JSON.parse(localStorage.getItem(\"contacts\"));\n\tfor(var count = 0; count < contacts_list.length; count++) {\n\t\tif(contacts_list[count].name === attendee_name) {\n\t\t\tattendee_email = contacts_list[count].email;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif($(this).prop(\"checked\")) {\n\t\tfor(var count = 0; count < attendees.length; count++) { //make sure you don't add duplicates\n\t\t\tif(attendees[count].name === attendee_name) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n attendees.push({ name: attendee_name, email: attendee_email });\n\t}\n\telse {\n\t\tfor(var count = 0; count < attendees.length; count++) { //find contact to be removed\n\t\t\tif(attendees[count].name === attendee_name) {\n\t\t\t\tattendees.splice(count, 1);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tupdateRecipientLists();\n}",
"removeUsersFromThreads() {\n const usersThreadsRef = firebaseDB.database().ref(`/Users/${this.state.userId}/Threads`)\n usersThreadsRef.on('value', snapshot => {\n let usersThreads = snapshot.val();\n for (let usersThread in usersThreads) {\n var threadRef = firebaseDB.database().ref(`/Threads/${usersThread}`)\n threadRef.update({\n author: \"[deleted]\"\n })\n }\n })\n }",
"function cleanGroupMembers () {\n // first create the group if it doesnt exist\n var group = ContactsApp.getContactGroup(GROUP_NAME);\n \n // delete everyone on it\n if (group) {\n group.getContacts().forEach(function(d) {\n d.deleteContact();\n });\n \n // delete the group\n group.deleteGroup();\n }\n \n}",
"function deleteFriend(uid) {\n //Delete on user's side\n var userFriendArrBackup = friendArr;\n var friendFriendArrBackup = [];\n var verifyDeleteBool = true;\n var toDelete = -1;\n\n for (var i = 0; i < friendArr.length; i++){\n if(friendArr[i] == uid) {\n toDelete = i;\n break;\n }\n }\n\n if(toDelete != -1) {\n friendArr.splice(toDelete, 1);\n\n for (var i = 0; i < friendArr.length; i++) {\n if (friendArr[i] == uid) {\n verifyDeleteBool = false;\n break;\n }\n }\n } else {\n verifyDeleteBool = false;\n }\n\n if(verifyDeleteBool){\n removeFriendElement(uid);\n user.friends = friendArr;\n generateAddUserBtn(); //Regenerate the button for new friendArr\n\n firebase.database().ref(\"users/\" + user.uid).update({\n friends: friendArr\n });\n\n //alert(\"Friend Successfully removed from your list!\");\n } else {\n friendArr = user.friends;\n firebase.database().ref(\"users/\" + user.uid).update({\n friends: userFriendArrBackup\n });\n alert(\"Delete failed, please try again later! (user)\");\n return;\n }\n\n\n\n //Delete on friend's side\n verifyDeleteBool = true;\n toDelete = -1;\n var friendFriendArr;//Weird name, I know, but it's the friend's friend Array...\n\n for (var i = 0; i < userArr.length; i++){\n if(userArr[i].uid == uid) {\n friendFriendArr = userArr[i].friends;\n friendFriendArrBackup = friendFriendArr;\n break;\n }\n }\n for (var i = 0; i < friendFriendArr.length; i++){\n if (friendFriendArr[i] == user.uid){\n toDelete = i;\n break;\n }\n }\n\n if(toDelete != -1) {\n friendFriendArr.splice(toDelete, 1);\n\n for (var i = 0; i < friendFriendArr.length; i++) {\n if (friendFriendArr[i] == user.uid) {\n verifyDeleteBool = false;\n break;\n }\n }\n } else {\n verifyDeleteBool = false;\n }\n\n if(verifyDeleteBool){\n firebase.database().ref(\"users/\" + uid).update({\n friends: friendFriendArr\n });\n\n //alert(\"Friend Successfully removed from their list!\");\n } else {\n firebase.database().ref(\"users/\" + uid).update({\n friends: friendFriendArrBackup\n });\n alert(\"Delete failed, please try again later! (friend)\");\n }\n }",
"function populateContacts(contacts) {\n setContacts(contacts);\n setFilteredContacts(contacts);\n }",
"static searchContacts(searchStr) {\n const searchStrLowerCase = searchStr.toLowerCase();\n const searchContacts = ContactsStorage.getContacts().then((contacts) => {\n const matches = [];\n contacts.forEach((contact) => {\n const firstNameLower = contact.first_name.toLowerCase();\n const lastNameLower = contact.last_name.toLowerCase();\n const emailLower = contact.email.toLowerCase();\n if (\n firstNameLower.startsWith(searchStrLowerCase) ||\n lastNameLower.startsWith(searchStrLowerCase) ||\n contact.email.startsWith(searchStrLowerCase)\n ) {\n matches.push(contact);\n }\n });\n const contactsRow = document.querySelector(\"#contacts-row\");\n contactsRow.innerHTML = \"\";\n if (matches.length === 0) UserInterface.errorMessage(\"No contacts found\");\n matches.forEach((match) => UserInterface.addContactsToDisplay(match));\n });\n }",
"function remove (list.bookName) {\nif (list.indexOf(bookName) => 0) {\n\nreturn list.filter(item) => !== bookName);\n}\n}",
"removeCustomer() {\n this.state.displayCustomer = 'block';\n this.setState({ state: (this.state.activeC[0] = [{ id: null }]) });\n this.setState({ state: (this.state.phrase = '') });\n this.findCustomers();\n }",
"removeUsersFromPosts() {\n const usersPostsRef = firebaseDB.database().ref(`/Users/${this.state.userId}/Posts`)\n usersPostsRef.on('value', snapshot => {\n let usersPosts = snapshot.val();\n for (let usersPost in usersPosts) {\n var postRef = firebaseDB.database().ref(`/Posts/${usersPost}`)\n postRef.update({\n author: \"[deleted]\"\n })\n }\n })\n }",
"function zoto_dual_list_contacts(options){\n\tmerge({'key': \"member_userid\"}, options);\n\tthis.$uber(options);\n}",
"function deleteRoomChars(roomID, charName, callback){\n\t\tif (charName == \"GM\"){\n\t\t\tmongoDeleteMany(\"chars\", \"roomID\", new ObjectID(roomID), null, function(result, extra){\n\t\t\t\tcallback(result);\n\t\t\t});\n\t\t}\n\t\telse{\n\t\t\tvar doc = {};\n\t\t\tdoc[\"$and\"] = [{\"roomID\" : new ObjectID(roomID)}, {\"char_name\" : charName}];\n\t\t\t\n\t\t\tmongoDeleteOneWithDoc(\"chars\", doc, null, function(result, extra){\n\t\t\t\tcallback(result);\n\t\t\t});\n\t\t}\n\t}",
"removeWorker(worker){\n console.log(worker);\n let workers = ODWorker.ListOfWorkers.filter( w => {\n return w.fullName.toUpperCase() !== worker;\n });\n ODWorker.ListOfWorkers = workers;\n }",
"function deleteMessageMemory(id){\n var i=0;\n while ((listMessages[i].id!=id) || (i>=listMessages.length)){\n i=i+1;\n }\n if (listMessages[i].id==id){\n var phone=listMessages[i].phone;\n listMessages.splice(i,1);\n loadListView();\n }\n}",
"function handleUpdateContact() {\n updateContact(editContact);\n }",
"function remove (bookList, bookName) {\n let mutatedArr = [...bookList];\n let indexToRemove = mutatedArr.indexOf(bookName);\n\n if (indexToRemove >= 0) {\n \n mutatedArr.splice(indexToRemove, 1);\n \n // Add your code above this line\n }\n return mutatedArr; \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prepends provided base to provided path | function addBase (base, path) {
var result = path
// add if exists
if (base) result = `${base}/${path}`
return result
} | [
"mergeBasePath(base, force = false) {\n if (base == null) {\n return;\n }\n\n if (!this.isAbsolute) {\n if (this.parentPath === '') {\n this.parentPath = base;\n } else {\n this.parentPath = `${base}/${this.parentPath}`;\n }\n\n this.path = `${this.parentPath}/${name}`;\n } else if (force) {\n // apply base path on a absolute path\n if (name === '') {\n // map the root path\n this.path = base;\n\n this._parse();\n } else {\n this.parentPath = `${base}/${this.parentPath}`;\n this.path = `${this.parentPath}/${name}`;\n }\n }\n }",
"_setBase(baseIRI) {\n if (!baseIRI) {\n this._base = '';\n this._basePath = '';\n }\n else {\n // Remove fragment if present\n const fragmentPos = baseIRI.indexOf('#');\n if (fragmentPos >= 0)\n baseIRI = baseIRI.substr(0, fragmentPos);\n // Set base IRI and its components\n this._base = baseIRI;\n this._basePath = baseIRI.indexOf('/') < 0 ? baseIRI :\n baseIRI.replace(/[^\\/?]*(?:\\?.*)?$/, '');\n baseIRI = baseIRI.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\\/\\/[^\\/]*)?/i);\n this._baseRoot = baseIRI[0];\n this._baseScheme = baseIRI[1];\n }\n }",
"prepare () {\n this.bloggify = path.join(this.root, this._paths.bloggify)\n iterateObject(this._paths, (value, pathName) => {\n if (pathName === \"bloggify\" || pathName === \"root\" || typeof this[pathName] === \"function\") { return; }\n this[pathName] = value.startsWith(\"/\") ?\n path.join(this.root, value)\n : path.join(this.bloggify, value)\n\n })\n }",
"function makePath(path){\n return '/' + [prefix, path].join('/');\n }",
"function buildRelativePath(jarentryname, destdir, basepath)\n{\n var baseParts = basepath.split('/');\n if (baseParts[baseParts.length-1] == '') {\n baseParts.pop();\n }\n\n var parts = jarentryname.split('/');\n\n var targetFile = Components.classes[\"@mozilla.org/file/local;1\"]\n .createInstance(Components.interfaces.nsILocalFile);\n targetFile.initWithFile(destdir);\n\n for (var i = baseParts.length; i < parts.length; i++) {\n targetFile.append(parts[i]);\n }\n\n return targetFile;\n}",
"stripPrefixFromPaths( files, base_path ){\n if (!base_path) base_path = path.join(this.base_path, this.base_name)\n base_path = this.constructor.endPathWithPathSep(base_path)\n let re_base_path = new RegExp(`^${_.escapeRegExp(base_path)}`)\n return files.map( item => item.replace(re_base_path,'') )\n }",
"function buildBasePath(type) {\n return API_BASE_URL + ( URL_PATHS[type] || '' );\n }",
"parsePath() {\n var protocol = goog.array.contains(this.map_['schemes'], 'https') ?\n 'https' : 'http';\n var host = this.map_['host'];\n var basepath = goog.isString(this.map_['basePath']) ?\n this.map_['basePath'] : '';\n var uri = new goog.Uri();\n uri.setScheme(protocol);\n uri.setDomain(host);\n uri.setPath(basepath);\n this.path = uri.toString();\n }",
"function defaultPathFixed (path){\n\t\treturn (path.lastIndexOf('/') !== path.length -1) ? path + '/' : path;\n\t}",
"setPath(basDerivationPath) {\n this._baseDerivationPath = basDerivationPath;\n }",
"async function folderFromPath(base, path) {\n return (isUrlAbsolute(path) ? folderFromAbsolutePath : folderFromServerRelativePath)(base, path);\n}",
"function createFullyQualifiedPath(pathObj) {\n var depPath = pathObj.path.replace(LEADING_SEP_PATT, \"\")\n , projectPath = `${pathObj.project.replace(DOT_PATT, \"/\")}/`\n , mod = pathObj.modifier\n , root = pathObj.root\n , path;\n\n //if this is an absolute path then return it\n if (pathObj.isAbsolute) {\n path = `${mod}${root}${depPath}`\n }\n //if the project path is not in the dependency path, then include it\n else if (depPath.indexOf(projectPath) === -1) {\n path = `${mod}${root}${projectPath}${depPath}`;\n }\n else {\n path = `${mod}${root}${depPath}`;\n }\n\n //standardize the separaters\n path = path.replace(WIN_SEP_PATT, \"/\");\n\n return path;\n }",
"static concat(parentPath, name) {\n if (parentPath === '/') {\n return `/${name}`;\n }\n\n return `${parentPath}/${name}`;\n }",
"function concatURI(a, b) {\n let started = b[0] === \"/\";\n let ended = a[a.length - 1] === \"/\";\n if (started && ended) {\n return `${a}${b.substr(1)}`;\n }\n if (started || ended) {\n return `${a}${b}`;\n }\n return `${a}/${b}`;\n}",
"function concatPath(a, b) {\n if (NodePath.sep === \"\\\\\") {\n return NodePath.normalize(a + \"/\" + b).replace(/\\\\/g, \"/\");\n }\n else {\n return NodePath.normalize(a + \"/\" + b);\n }\n}",
"function fileFromServerRelativePath(base, serverRelativePath) {\n return File([base, extractWebUrl(base.toUrl())], `_api/web/getFileByServerRelativePath(decodedUrl='${encodePath(serverRelativePath)}')`);\n}",
"function addPath(uri, path) {\n\t\turi = uri.split(\"?\")[0].split(\"#\")[0];\n\t\tif (uri.substr(-1) !== '/') {\n\t\t\turi += '/';\n\t\t}\n\n\t\t// remove special characters from the string (e.g., '/', '..', '?')\n\t\tvar lastSegment = path.replace(/[^\\w\\s\\-_]/gi, '');\n\t\treturn uri + encodeURIComponent(lastSegment)\n\t}",
"function joinPath (first, second) {\n // If the second part starts with \"./\", it can be safely removed.\n second = shortenPath(second)\n // The parent path can be undefined, if the file is located in the current directory.\n if (first !== undefined) {\n // As long as \"../\" can be removed from the second path, shorten the first one.\n while (pointsToParent(second)) {\n // Remove the leading \"../\" and trim futher all leading \"./\".\n second = shortenPath(second.substring(3));\n // Cut the last directory from the first path.\n first = parentDir(first);\n // If the last part of the first path was removed and there is no parent\n // directory to go further, return the rest of the second path.\n if (first === undefined) {\n return second;\n }\n }\n // Return what remains from the first path concatenated with the second one.\n second = first + second;\n }\n return second;\n }",
"function adjustHref(href) {\n\treturn document.quicknavBasePath + \"/\" + href;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
build the DOM structure that makes up the suggestion box and content containers. | _renderContentContainers() {
// container of all suggestion elements
this._suggestionContainer = document.createElement('div');
this._suggestionContainer.classList.add(this.options.classNames.container);
// child elements that will be populated by consumer
this._header = document.createElement('h4');
this._header.classList.add(this.options.classNames.header);
this._setHeader(this.state.header);
this._suggestionContainer.appendChild(this._header);
this._listContainer = document.createElement('ul');
this._listContainer.setAttribute('role', 'listbox');
this._listContainer.classList.add(this.options.classNames.list);
this._suggestionContainer.appendChild(this._listContainer);
// put the suggestions adjacent to the input element
// firefox does not support insertAdjacentElement
if (HTMLElement.prototype.insertAdjacentElement) {
this._input.insertAdjacentElement('afterend', this._suggestionContainer);
} else {
this._input.parentNode.insertBefore(
this._suggestionContainer,
this._input.nextSibling,
);
}
} | [
"function createElements() {\r\n _dom = {};\r\n createElementsForSelf();\r\n if (_opts.placement.popup) {\r\n createElementsForPopup();\r\n }\r\n createElementsForColorWheel();\r\n createElementsForNumbersMode();\r\n createElementsForSamples();\r\n createElementsForControls();\r\n }",
"function buildBox() {\n var innerContent = getInnerContent();\n var buttons = '';\n if(curOpt.ok){\n buttons = '<div class=\\'pm-popup-buttons\\'> <button class=\\'button\\'>OK</button></div>';\n }\n var boxHtml = '<div id=\\'pm_'+curOpt.id+'\\' class=\\'pm_popup\\'><div class=\\'pm-popup-inner\\'> '+innerContent + buttons+'</div></div>';\n var thisPopup = $(boxHtml).appendTo('body');\n if (curOpt.ok) {\n //attach events\n thisPopup.find('.button').click(function() {\n $(window).scrollTop(0);\n hide();\n curOpt.ok();\n });\n }\n }",
"function setGenerateSearchElement(elt,config){if(config.logLevel>0)alert(\"running setGenerateSearchElement\");\nvar dynamicHTML=false;\nif(dynamicHTML){ // this kind of code may be needed for IE; \nvar A=[[\"form\",\"action\",\"javascript:void(0)\",\"name\",\"searchForm\",\"id\",\"searchForm\",\n \"onsubmit\",\n \"thePlayerManager.lookup(document.forms.searchForm.searchfield.value,document.forms.searchForm)\"],\n [\"input\",\"id\",\"searchfield\",\"name\",\"searchfield\",\"type\",\"text\",\"size\",\"35\",\n \"title\",\"search text; word for dict, can be reg exp for script or commentary\"],\n [\"input\",\"id\",\"searchbutton\",\"value\",\"Search\",\"type\",\"button\",\n \"onclick\",\"thePlayerManager.lookup(this.form.searchfield.value,this.form,event)\",\n \"title\",\"search for word in dict, or for text in page or (with ctrl key down) repository\"],\n [\"br\"],\n [[\"div\",\"id\",\"boxes\"],\n [\"input\",\"onchange\",\"checkChanger.change(this)\",\"type\",\"checkbox\",\n \"checked\",\"checked\", \"name\",\"dict\", \"id\",\"dictCheckbox\"],\n [null,\"dictionary\\u00A0\\u00A0\"],\n [\"input\",\"onchange\",\"checkChanger.change(this)\",\"type\",\"checkbox\",\n \"checked\",\"checked\", \"name\",\"script\", \"id\",\"scriptCheckbox\"],\n [null,\"script\\u00A0\\u00A0\"],\n [\"input\",\"onchange\",\"checkChanger.change(this)\",\"type\",\"checkbox\",\n \"checked\",\"checked\", \"name\",\"comm\", \"id\",\"commCheckbox\"] ,\n [null,\"commentary\\u00A0\\u00A0\"]\n ]\n ];\n var X=newElt(A); elt.appendChild(X);\n} else {\n\nvar S= // ' <div id=\"search\">\\n'+\n' <form action=\"javascript:void(0)\" name=\"searchForm\"\\n'+\n' onsubmit=\"thePlayerManager.lookup(document.forms.searchForm.searchfield.value,document.forms.searchForm)\">\\n'+\n' <input id=\"searchfield\" type=\"text\" size=\"35\" \\n'+\n' title=\"search text; word for dict, can be reg exp for script or commentary\" />\\n'+\n' \\n'+\n' <input id=\"searchbutton\" type=\"button\" value=\"Search\" \\n'+\n' onclick=\"thePlayerManager.lookup(this.form.searchfield.value,this.form,event)\" \\n'+\n' title=\"search for word in dict, or for text in page or (with ctrl key down) repository\" /> <br/> \\n'+\n' <div id=\"boxes\">\\n'+\n' <input onchange=\"checkChanger.change(this)\" type=\"checkbox\" \\n'+\n' checked=\"checked\" name=\"dict\" id=\"dictCheckbox\" />dictionary\\u00A0\\u00A0\\n'+\n' <input onchange=\"checkChanger.change(this)\" type=\"checkbox\" \\n'+\n' name=\"script\" id=\"scriptCheckbox\" />script\\u00A0\\u00A0\\n'+\n' <input onchange=\"checkChanger.change(this)\" type=\"checkbox\" \\n'+\n' name=\"comm\" id=\"commCheckbox\" />commentary\\u00A0\\u00A0</div>\\n'+\n' </form>\\n';\n// '</div>';\nelt.innerHTML=S;\n}\nif(config.logLevel>0)alert(\"done setGenerateSearchElement\");\n}",
"build() {\n\t\tconst self = this;\n\n\t\tself.buildTags();\n\t\tself.buildTree();\n\t}",
"function buildDomTree() {\r\n /**\r\n * <div id=\"$root\" class=\"scheduler\"> <div class=\"timeColumn\"></div>\r\n * <div class=\"dayRow\"></div> <div id=\"scrollWrapper\"> <div\r\n * class=\"schedulerContent\"></div> </div> </div>\r\n */\r\n\r\n $root.addClass('scheduler');\r\n $timeColumn = $('<div/>', {\r\n 'class' : 'timeColumn',\r\n })\r\n\r\n $dayRow = $('<div/>', {\r\n 'class' : 'dayRow',\r\n })\r\n\r\n $scrollWrapper = $('<div/>', {\r\n 'id' : 'scrollWrapper',\r\n });\r\n $content = $('<div/>', {\r\n 'class' : 'schedulerContent',\r\n });\r\n $scrollWrapper.append($content);\r\n\r\n $root.append($timeColumn);\r\n $root.append($dayRow);\r\n $root.append($scrollWrapper);\r\n }",
"function buildTopicsList() {\n var topicsList = $('<div id=\"tutorial-topic\" class=\"topicsList hideFloating\"></div>');\n\n var topicsHeader = $('<div class=\"topicsHeader\"></div>');\n topicsHeader.append($('<h2 class=\"tutorialTitle\">' + titleText + '</h2>'));\n var topicsCloser = $('<div class=\"paneCloser\"></div>');\n topicsCloser.on('click', hideFloatingTopics);\n topicsHeader.append(topicsCloser);\n topicsList.append(topicsHeader);\n\n $('#doc-metadata').appendTo(topicsList);\n\n resetSectionVisibilityList();\n\n var topicsDOM = $('.section.level2');\n topicsDOM.each( function(topicIndex, topicElement) {\n\n var topic = {};\n topic.id = $(topicElement).attr('id');\n topic.exercisesCompleted = 0;\n topic.sectionsCompleted = 0;\n topic.sectionsSkipped = 0;\n topic.topicCompleted = false; // only relevant if topic has 0 exercises\n topic.jqElement = topicElement;\n topic.jqTitleElement = $(topicElement).children('h2')[0];\n topic.titleText = topic.jqTitleElement.innerText;\n var progressiveAttr = $(topicElement).attr('data-progressive');\n if (typeof progressiveAttr !== typeof undefined && progressiveAttr !== false) {\n topic.progressiveReveal = (progressiveAttr == 'true' || progressiveAttr == 'TRUE');\n }\n else {\n topic.progressiveReveal = docProgressiveReveal;\n }\n\n jqTopic = $('<div class=\"topic\" index=\"' + topicIndex + '\">' + topic.titleText + '</div>');\n jqTopic.on('click', handleTopicClick);\n topic.jqListElement = jqTopic;\n $(topicsList).append(jqTopic);\n\n var topicActions = $('<div class=\"topicActions\"></div>');\n if (topicIndex > 0) {\n var prevButton = $('<button class=\"btn btn-default\">Previous Topic</button>');\n prevButton.on('click', handlePreviousTopicClick);\n topicActions.append(prevButton);\n }\n if (topicIndex < topicsDOM.length - 1) {\n var nextButton = $('<button class=\"btn btn-primary\">Next Topic</button>');\n nextButton.on('click', handleNextTopicClick);\n topicActions.append(nextButton);\n }\n $(topicElement).append(topicActions);\n\n $(topicElement).on('shown', function() {\n // Some the topic can have the shown event triggered but not actually\n // be visible. This visibility check saves a little effort when it's\n // not actually visible.\n if ($(this).is(\":visible\")) {\n var sectionsDOM = $(topicElement).children('.section.level3');\n sectionsDOM.each( function(sectionIndex, sectionElement) {\n updateSectionVisibility(sectionElement);\n })\n }\n });\n\n $(topicElement).on('hidden', function() {\n var sectionsDOM = $(topicElement).children('.section.level3');\n sectionsDOM.each( function(sectionIndex, sectionElement) {\n updateSectionVisibility(sectionElement);\n })\n });\n\n topic.sections = [];\n var sectionsDOM = $(topicElement).children('.section.level3');\n sectionsDOM.each( function( sectionIndex, sectionElement) {\n\n if (topic.progressiveReveal) {\n var continueButton = $(\n '<button class=\"btn btn-default skip\" id=\"' +\n 'continuebutton-' + sectionElement.id +\n '\" data-section-id=\"' + sectionElement.id + '\">Continue</button>'\n );\n continueButton.data('n_clicks', 0);\n continueButton.on('click', handleSkipClick);\n var actions = $('<div class=\"exerciseActions\"></div>');\n actions.append(continueButton);\n $(sectionElement).append(actions);\n }\n\n $(sectionElement).on('shown', function() {\n // A 'shown' event can be triggered even when this section isn't\n // actually visible. This can happen when the parent topic isn't\n // visible. So we have to check that this section actually is\n // visible.\n updateSectionVisibility(sectionElement);\n });\n\n $(sectionElement).on('hidden', function() {\n updateSectionVisibility(sectionElement);\n });\n\n var section = {};\n section.exercises = [];\n var exercisesDOM = $(sectionElement).children('.tutorial-exercise');\n exercisesDOM.each(function(exerciseIndex, exerciseElement) {\n var exercise = {};\n exercise.dataLabel = $(exerciseElement).attr('data-label');\n exercise.completed = false;\n exercise.jqElement = exerciseElement;\n section.exercises.push(exercise);\n });\n\n var allowSkipAttr = $(sectionElement).attr('data-allow-skip');\n var sectionAllowSkip = docAllowSkip;\n if (typeof allowSkipAttr !== typeof undefined && allowSkipAttr !== false) {\n sectionAllowSkip = (allowSkipAttr == 'true' || allowSkipAttr == 'TRUE');\n }\n\n section.id = sectionElement.id;\n section.completed = false;\n section.allowSkip = sectionAllowSkip;\n section.skipped = false;\n section.jqElement = sectionElement;\n topic.sections.push(section);\n\n });\n\n topics.push(topic);\n });\n\n var topicsFooter = $('<div class=\"topicsFooter\"></div>');\n\n var resetButton = $('<span class=\"resetButton\">Start Over</span>');\n resetButton.on('click', function() {\n bootbox.confirm(\"Are you sure you want to start over? (all exercise progress will be reset)\",\n function(result) {\n if (result)\n tutorial.startOver();\n });\n });\n topicsFooter.append(resetButton);\n topicsList.append(topicsFooter);\n\n return topicsList;\n\n }",
"_buildDOM() {\n const HTML = this.render();\n if (!HTML) { return }\n this.DOMbuilder.build( HTML );\n }",
"function createSearchElement() {\n appendSearchElementToDOM();\n addDynamicSearchFunctionality();\n}",
"function createOptionsList(container, suggestions) {\n let options = '<datalist id=\"' + container.attributes[1].value + '\">';\n for (let i = 0; i < suggestions.length; i++) {\n options += '<option>' + suggestions[i].value + '</option>';\n }\n options += '</datalist>';\n $(options).insertAfter(container);\n}",
"function showSuggestions() {\n var v = getNeedle();\n\n if (v.length == 0) {\n box.css('display', 'none');\n return;\n }\n\n suggestions = 0;\n\n box.empty();\n\n options.filters.each(function(i, f) {\n if (suggestions == options.size) {\n return;\n }\n\n list.every(function(o) {\n if (f(options.get(o).toLowerCase(), v)) {\n var li = suggestions++;\n\n box.append($('<div \\>', {\n 'events': {\n 'mousemove': function() { // don't use mouseover since that will bug when the user has the mouse below the input box while typing\n if (!hiding) {\n hover = li;\n showHover();\n }\n }\n }\n }).append(options.render(o)).store('val', o));\n\n if (suggestions == options.size) {\n return false;\n }\n }\n\n return true;\n });\n });\n\n updatePosition();\n\n // If no suggestions, no need to show the box\n if (suggestions > 0) {\n box.css('display', 'block');\n } else {\n box.css('display', 'none');\n }\n }",
"function init_suggestedTags() {\n\n\t\tli_data = settings.suggestedTags;\n\t\tif(li_data && li_data.length) {\n\n\t\t\tfor(var i in li_data) {\n\n\t\t\t\tsuggestedTag = li_data[i].name;\n\t\t\t\tif($('li p', token_list).filter(\":contains('\" + suggestedTag + \"')\").length==0) {\n\n\t\t\t\t\t/*size adjust will increase/decrease tag size*/\n\t\t\t\t\tvar sizeAdjust = 0;\n\t\t\t\t\tif(typeof(li_data[i].size) != 'undefined') {\n\t\t\t\t\t\tsizeAdjust = li_data[i].size;\n\t\t\t\t\t}\n\n\t\t\t\t\tvar this_token = $('<li><a href=\"#\" style=\"font-size: ' + (settings.defaultSuggestTagSize+sizeAdjust) + settings.defaultSuggestTagSizeUnit + '\">'+suggestedTag+'</a></li>')\n\t\t\t\t\t.addClass(settings.classes.suggestedTag)\n\t\t\t\t\t.appendTo(suggested_tags)\n\t\t\t\t\t.click(function() {\n\n\t\t\t\t\t\tvar li = this;\n\t\t\t\t\t\tadd_new_token($('a', li).text());\n\t\t\t\t\t\t$(li).remove();\n\n\t\t\t\t\t\t//Should the whole ul be removed?\n\t\t\t\t\t\tif($('li',suggested_tags).length==0) {\n\t\t\t\t\t\t\t$(suggested_tags_container).remove();\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn false;\n\n\t\t\t\t\t});;\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif($('li',suggested_tags).length==0) {\n\t\t\t\t$(suggested_tags_container).remove();\n\t\t\t}\n\t\t }\n\n\t}",
"function markupSearch() {\n var _html = '';\n semdata.forEach( function(message) { _html += '<div id=\"data-title\">' + message.value + \n \"<input type=\\\"button\\\" class=\\\"removebutton\\\" onclick='ldinjs.remove(\\\"\"+\n message.id+\"\\\")' value=\\\"Remove\\\">\";\n //if (0 < message.data.size ) {\n _html += \"<input type=\\\"button\\\" class=\\\"removebutton\\\" onclick='drillDown.createSingleDatumList(\\\"\"+\n message.id+\"\\\", \\\"id-data\\\")' value=\\\"Show Details\\\">\";\n //}\n if (0 < message.similarity.length ) {\n _html += \"<input type=\\\"button\\\" class=\\\"removebutton\\\" onclick='sims.markUpSimilarity(\\\"\"+\n message.id+\"\\\")' value=\\\"Show Similar\\\">\";\n }\n _html += '</div>';\n });\n $( \"#results\" ).html(_html).prependTo( \"#results\" );\n $( \"#results\" ).scrollTop( 0 );\n }",
"function buildTags()\n {\n TagAPI.get().done((results) => {\n let $modal = $('#tags-modal'),\n id = $(this).attr('data-id'),\n tags = $(results[id]),\n tagCloud = [];\n\n if (tags.length > 0)\n {\n tags.each(function (index, tag) {\n tagCloud.push(\n '<div class=\"tag-entry\">',\n '<strong>' + tag.label + '</strong>',\n '<button type=\"button\" class=\"tag-remove\" data-id=\"' + tag.id + '\"><span class=\"glyphicon glyphicon-trash\"></span></a>',\n '</div>'\n );\n });\n\n $modal.find('#tags-list').html(tagCloud.join(\"\\n\"));\n }\n\n $modal.find('#item-tags').val('');\n $modal.find('#item-id').val(id);\n $modal.modal('show');\n });\n }",
"function SearchClause(query_object, and_pos, or_pos) {\n this.and_pos = and_pos;\n this.or_pos = or_pos;\n this.query_object = query_object;\n this.index = \"\"\n this.relation = \"\";\n this.value = \"\";\n\n //make cql_config static to make it accessible from getValues()\n //cql_config = query_object.cql_config;\n\n /** generate a widget for this SC */\n this.genCQLSearchClauseWidget = function () {\n \n //console.log(\"genCQLSearchClauseWidget(query_object)\");\n //console.log(this.query_object);\n \n var key= query_object.key; \n var input_index = $(\"<input />\");\n input_index.attr(\"id\",\"cql-\" + key + \"-index\");\n input_index.attr(\"name\",\"cql-\" + key + \"-index\")\n input_index.data(\"sc\", this); \n // update the value in data-object;\n input_index.change(function(){ $(this).data(\"sc\").index = $(this).val(); \n //console.log($(this).data(\"sc\").index + '-' + $(this).val()); \n });\n \n var select_relation = $(\"<select class=' rel_input'><option value='='>=</option><option value='>'>></option><option value='<'><</option><option value='any'>any</option><option value='contains'>contains</option><option value='all'>all</option></select>\");\n var input_value = $(\"<input />\");\n input_value.attr(\"id\",\"cql-\" + key + \"-value\");\n input_value.attr(\"name\",\"cql-\" + key + \"-value\");\n \n input_value.data(\"sc\", this); \n // update the value in data-object;\n input_value.change(function(){ $(this).data(\"sc\").value = $(this).val(); });\n \n\n var new_widget = $(\"<div id='widget-\" + key + \"' class='widget-cql'></div>\");\n new_widget.append(input_index)\n .append(select_relation)\n .append(input_value);\n \n // setup autocompletes \n if (this.query_object.cql_config) {\n \n // let the autocomplete-select refresh upon loaded index\n this.query_object.cql_config.onLoaded = function(index) { input_value.autocomplete( \"search\");\n console.log(\"onloaded-index:\" + index)};\n \n var indexes = this.query_object.cql_config.getIndexes();\n // console.log(indexes);\n \n // setting source on init did not work ??\n //input_index.autocomplete({source: indexes});\n input_index.autocomplete();\n input_index.autocomplete( \"option\", \"source\", indexes );\n // console.log(input_index.autocomplete( \"option\", \"source\" ));\n \n input_value.data(\"input_index\", input_index);\n input_value.autocomplete();\n input_value.autocomplete( \"option\", \"source\", getValues );\n }\n \n new_widget.append(this.genControls()); \n return new_widget;\n };\n\n\n getValues = function(request, response) {\n \n console.log(\"request_term:\" + request.term);\n //console.log(this.element.data(\"sc\"));\n var sc = this.element.data(\"sc\")\n values = sc.query_object.cql_config.getValues(sc.index,request.term);\n //console.log(values);\n if (values.status == 'loading') { response( [\"loading...\"]) }\n else { response(values) };\n };\n \n\n this.genControls = function () {\n \n var div_controls = $(\"<span class='controls' />\");\n var cmd_del = $(\"<span class='cmd cmd_sc_delete' />\");\n var cmd_and = $(\"<span class='cmd cmd_add_and' />\");\n var cmd_or = $(\"<span class='cmd cmd_add_or' />\");\n \n div_controls.append(cmd_del).append(cmd_and).append(cmd_or);\n \n var me = this;\n cmd_del.bind(\"click\", function(event) { me.query_object.removeSearchClause(me); });\n cmd_and.bind(\"click\", function(event) { me.query_object.addSearchClause(me,\"and\"); });\n cmd_or.bind(\"click\", function(event) { me.query_object.addSearchClause(me,\"or\"); });\n \n return div_controls;\n \n\t}\n\n\nthis.widget = this.genCQLSearchClauseWidget();\n\n\n} // end SearchClause",
"function buildMenuContainer() {\n var l_html = '<div id=\"action_container\" class=\"file-action-menu shadow hideme\">' +\n '<ul>' +\n '<li class=\"menu-tile\">Paste options</li>' +\n '<li><a href=\"#\"><span><img src=\"images/paste16.gif\" alt=\"\">Paste</span></a></li>' +\n '<li><a href=\"#\"><span>Paste special...</span></a></li>' +\n '<li class=\"separator\"><a href=\"#\"><span><img src=\"images/link16.gif\" alt=\"\">Paste link</span></a></li>' +\n '</ul>' +\n '</div>';\n\n jQuery('body').append(l_html);\n }",
"function transformDOM() {\n\n titleText = $('title')[0].innerText;\n\n var progAttr = $('meta[name=progressive]').attr(\"content\");\n docProgressiveReveal = (progAttr == 'true' || progAttr == 'TRUE');\n var allowSkipAttr = $('meta[name=allow-skip]').attr(\"content\");\n docAllowSkip = (allowSkipAttr == 'true' || allowSkipAttr == 'TRUE');\n\n var tutorialTitle = $('<h2 class=\"tutorialTitle\">' + titleText + '</h2>');\n tutorialTitle.on('click', showFloatingTopics);\n $('.topics').prepend(tutorialTitle);\n\n $('.bandContent.topicsListContainer').append(buildTopicsList());\n\n // initialize visibility of all topics' elements\n for (var t = 0; t < topics.length; t++) {\n updateVisibilityOfTopicElements(t);\n }\n\n function handleResize() {\n $('.topicsList').css(\"max-height\", window.innerHeight);\n }\n\n handleResize();\n window.addEventListener(\"resize\", handleResize);\n\n }",
"function onAutosuggestSelect(selectidandselval) {\n /*first take the selectid. It is the string before the first hyphen*/\n var tmpArray = selectidandselval.split('-');\n var selectid = tmpArray[0];\n var selval = tmpArray[1];\n /*generate the content element id and autosuggest element id from the selectid*/\n var tmpArray = selectid.split('_');\n var content_id = 'content_'+tmpArray[1]+'_'+tmpArray[2]+'_'+tmpArray[3];\n var autosuggest_id = 'autosuggest_'+tmpArray[1]+'_'+tmpArray[2]+'_'+tmpArray[3];\n var content_t = document.getElementById(content_id); //table\n var content = null; //the actual text\n //this is interesting, since if the user is browsing the list of selections by mouse,\n //the autogrown form has disapperaed and there is only the table left.. so check..\n if (content_t.innerHTML.indexOf(\"<form>\") ==0) {\n var content_f = null; //form\n var content_ta = null; //textarea\n if (content_t) {\n content_f = content_t.firstChild; //form is the sub-elem of table\n }\n if (content_f) {\n content_ta = content_f.firstChild; //textarea is the sub-elem of form\n }\n if (!(content_ta)) {return;}\n content = content_ta;\n } else {\n content = content_t;\n }\n /*put value in place*/\n if (selval) {\n content.innerHTML = selval;\n content.value = selval;\n }\n /*remove autosuggest box*/\n var autosugg_in = document.getElementById(autosuggest_id);\n autosugg_in.innerHTML = \"\";\n}",
"function populatePopups() {\n // Categories popup\n for (var key in CAT_IDS) {\n $('#categories-popup menu .scrollable').append('<button value=\"' + CAT_IDS[key] + '\">' + CATEGORIES[key] + '</button>');\n }\n\n // Locations popup\n for (var key in LOC_IDS) {\n $('#locations-popup menu .scrollable').append('<button value=\"' + LOC_IDS[key] + '\">' + LOCATIONS[key] + '</button>');\n }\n\n // Date popup\n for (var key in DATES_INT) {\n $('#dates-popup menu .scrollable').append('<button value=\"' + DATES_INT[key] + '\">' + DATES_FULL[key] + '</button>');\n }\n }",
"function AutocompleteBox(element, list, lineSplitter) {\n // deep clone of list\n var innerList = JSON.parse(JSON.stringify(list));\n\n if (!(element instanceof Element)) throw new Error(\"element is not a DOM element\");\n if (!Array.isArray(innerList)) throw new Error(\"list is not an array\"); // ?? adopt to pseudo arrays\n\n var input = document.getElementsByTagName(\"input\")[0];\n\n var POPUP_CLASS = \"autocomplete-box__popup\";\n var POPUP_ITEM_CLASS = \"autocomplete-box__popup-item\";\n var POPUP_ITEM_ACTIVE_CLASS = POPUP_ITEM_CLASS + \"--active\";\n\n var popup;\n var activeItem;\n\n\n function fillElementWithContent(el, index, string, separator) {\n if (separator != \"\" && separator != undefined && string.indexOf(separator) >= 0) {\n var cityParams = string.split(separator);\n el.innerText = cityParams[0] + \" \" + lineSplitter + \" \" + cityParams[1];\n el.setAttribute(\"data-real-param\", cityParams[2]);\n }\n else {\n el.innerText = string;\n }\n\n el.classList.add(POPUP_ITEM_CLASS);\n if (index == 0) {\n activeItem = el;\n el.classList.add(POPUP_ITEM_ACTIVE_CLASS);\n }\n }\n\n function open() {\n var els = element.querySelectorAll(\".\" + POPUP_CLASS);\n if (els.length >= 1) return;\n var listLenght = innerList.length;\n\n popup = document.createElement(\"div\");\n popup.classList.add(POPUP_CLASS);\n popup.setAttribute(\"id\", \"popup\");\n popup.style.height = (listLenght < 5) ? listLenght * 3 + \"rem\" : \"15rem\";\n popup.style[\"overflow-y\"] = \"scroll\";\n\n\n innerList.forEach(function (string, index) {\n\n var el = document.createElement(\"div\");\n el.setAttribute(\"data-index\", index);\n\n fillElementWithContent(el, index, string, lineSplitter);\n\n popup.appendChild(el);\n });\n\n element.appendChild(popup);\n\n $(popup).on(\"click\", popupClickHandler);\n }\n\n\n function popupClickHandler(ev) {\n ev.preventDefault();\n var target = ev.target;\n var index = target.getAttribute(\"data-index\");\n\n if (index == undefined) return;\n setActive(index);\n }\n\n function close() {\n var els = element.querySelectorAll(\".\" + POPUP_CLASS);\n if (els.length == 0) return;\n var oldInput = input.value;\n\n if (popup) {\n popup.removeEventListener(\"click\", popupClickHandler);\n }\n\n els[0].parentNode.removeChild(els[0]);\n activeItem = undefined;\n input.setAttribute(\"value\", \"\");\n input.value = \"\";\n input.value = oldInput;\n }\n\n function setActiveSibling(current, sibling, prevOrNextDomName) {\n current.classList.remove(POPUP_ITEM_ACTIVE_CLASS);\n sibling.classList.add(POPUP_ITEM_ACTIVE_CLASS);\n activeItem = current[prevOrNextDomName];\n }\n\n function next() {\n var current = element.querySelector(\".\" + POPUP_ITEM_ACTIVE_CLASS);\n\n if (current && current.nextSibling) {\n setActiveSibling(current, current.nextSibling, \"nextSibling\");\n select();\n adjustScrollbar(current.parentNode, activeItem);\n }\n }\n\n function prev() {\n var current = element.querySelector(\".\" + POPUP_ITEM_ACTIVE_CLASS);\n\n if (current && current.previousSibling) {\n setActiveSibling(current, current.previousSibling, \"previousSibling\");\n select();\n adjustScrollbar(current.parentNode, activeItem);\n }\n }\n\n function adjustScrollbar(parent, active) {\n var activeTop = active.getBoundingClientRect().top;\n var activeBottom = active.getBoundingClientRect().bottom;\n var parentTop = parent.getBoundingClientRect().top;\n var parentBottom = parent.getBoundingClientRect().bottom;\n\n if (activeBottom > parentBottom) {\n parent.scrollTop += activeBottom - parentBottom;\n }\n\n else if (activeTop <= parentTop) {\n parent.scrollTop += activeTop - parentTop;\n }\n }\n\n\n function setActive(index) {\n var elements = element.querySelectorAll(\".\" + POPUP_ITEM_CLASS);\n\n if (elements.length == 0 || index < 0 || index >= elements.length) return;\n\n var oldActive = element.querySelector(\".\" + POPUP_ITEM_ACTIVE_CLASS);\n var oldIndex = oldActive.getAttribute(\"data-index\");\n\n elements[oldIndex].classList.remove(POPUP_ITEM_ACTIVE_CLASS);\n elements[index].classList.add(POPUP_ITEM_ACTIVE_CLASS);\n activeItem = elements[index];\n\n select();\n }\n\n function update(newList) {\n var oldInput = input.value;\n close();\n innerList = JSON.parse(JSON.stringify(newList));\n open();\n input.value = oldInput;\n }\n\n function select() {\n var activeVal = (activeItem)? activeItem.innerText : \"\";\n var realQueryParameter = activeItem.getAttribute(\"data-real-param\");\n\n input.setAttribute(\"value\", activeVal);\n\n if (lineSplitter != \"\" && lineSplitter != undefined) {\n input.value = activeVal.split(lineSplitter)[0].trim();\n }\n else {\n input.value = activeVal.trim();\n }\n\n\n input.focus();\n input.setAttribute(\"data-real-param\", realQueryParameter);\n }\n\n function getInputText() {\n return input.value;\n }\n\n function getInputElement() {\n return input;\n }\n\n\n var publicAPI = {\n getInputText: getInputText,\n getInputElement: getInputElement,\n open: open,\n close: close,\n next: next,\n prev: prev,\n setActive: setActive,\n update: update,\n select: select\n };\n\n return publicAPI;\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Starts the connect to Sauce Labs. | function startSauce() {
console.log( 'Local server listening to', STATIC_SERVER_PORT );
console.log( 'Sauce Connect ready.' );
const opts = {
url: `https://${ SAUCE_LABS_USERNAME }:${ SAUCE_LABS_ACCESS_KEY }@saucelabs.com/rest/v1/cct-sauce/js-tests`,
method: 'POST',
json: {
platforms: [
[ 'Windows 7', 'internet explorer', '11' ],
[ 'Windows 7', 'firefox', '27' ]
],
url: 'http://localhost:' + STATIC_SERVER_PORT + '/?ci_environment=' + NODE_ENV,
framework: 'custom',
name: testName
}
};
request.post( opts, function( reqErr, httpResponse, body ) {
if ( reqErr ) {
console.error( 'An error occurred:', reqErr );
}
console.log( 'Tests started.' );
sauceTests = body['js tests'];
checkSauce();
} );
} | [
"async function initialize() {\n simulator = new Simulator(credentials);\n\n await new Promise((resolve, reject) => {\n simulator\n .on('error', (err) => {\n reject(err);\n })\n .on('connected', () => {\n resolve();\n })\n .connect();\n });\n}",
"async function connect() {\n state.setStartEthereum(false);\n if (typeof window.ethereum !== \"undefined\") {\n const accounts = await ethereum.request({ method: \"eth_requestAccounts\" });\n const provider = await detectEthereumProvider();\n\n console.log(accounts);\n\n const web3 = new Web3(provider);\n state.setWeb3(web3);\n web3.eth.defaultAccount = accounts[0];\n\n initializeContracts(web3);\n startListeners();\n\n state.setEthereumAccounts(accounts);\n state.setEthereumConnected(true);\n } else {\n throw Error(\"Could not find ethereum in window.\");\n }\n }",
"function connect() {\n client.connect(function (_remote, conn) {\n self.remote = _remote; \n clearInterval(reconnectionTimer);\n conn.on('end', function(){\n //\n // Attempt reconnection\n //\n reconnectionTimer = setInterval(function(){\n connect();\n }, 3000)\n });\n self.emit('browser::ready');\n });\n }",
"connect() {\n\t\tthis.socket.connect(this.testData.port, this.testData.host, ()=>{\n\t\t\tthis.sendWithCost('id', {robot: this.testData.robotName, account: this.testData.accountName});\n\t\t\tthis.send('message', 'hi');\n\t\t\tconsole.log('Connected');\n\t\t});\n\t}",
"async function connect() {\n\tlet endpoint = document.getElementById('endpoint').value;\n\tif (!window.substrate || global.endpoint != endpoint) {\n\t\tconst provider = new WsProvider(endpoint);\n\t\tdocument.getElementById('output').innerHTML = 'Connecting to Endpoint...';\n\t\twindow.substrate = await ApiPromise.create({ provider });\n\t\tglobal.endpoint = endpoint;\n\t\tdocument.getElementById('output').innerHTML = 'Connected';\n\t\tclearIndices();\n\t}\n}",
"function main() {\n const stompClient = StompClient.getInstance();\n stompClient.connect({}, onConnectionSuccessful, (error) => {\n console.error(\"Could not connect to server \", error);\n });\n }",
"function start() {\n test();\n var httpService = http.createServer(serve);\n httpService.listen(ports[0], '0.0.0.0');\n\n var options = {\n key: key,\n cert: cert\n };\n var httpsService = https.createServer(options, serve);\n httpsService.listen(ports[1], '0.0.0.0');\n\n var clients = clientService(httpsService);\n clients.onNewPos(updateEvents);\n\n printAddresses();\n}",
"function checkSauce() {\n const opts = {\n url: `https://${ SAUCE_LABS_USERNAME }:${ SAUCE_LABS_ACCESS_KEY }@saucelabs.com/rest/v1/cct-sauce/js-tests/status`,\n method: 'POST',\n json: {\n 'js tests': sauceTests\n }\n };\n setTimeout( function() {\n request.post( opts, function( err, httpResponse, body ) {\n if ( err ) {\n console.error( 'An error occurred:', err );\n }\n\n let failures = 0;\n\n if ( body.completed ) {\n console.log( 'Tests done.' );\n // TODO: Provide a consistent return value from the function.\n // eslint-disable-next-line consistent-return\n body['js tests'].forEach( test => {\n let errors;\n if ( test.result && test.result.failed > 0 ) {\n // TODO: remove one nested callback.\n // eslint-disable-next-line max-nested-callbacks\n errors = test.result.tests.map( result => result.message );\n failures++;\n return console.log( test.platform.join( ' ' ) + ' failed: ' + errors.join( ' ' ) );\n }\n console.log( test.platform.join( ' ' ) + ' passed.' );\n } );\n if ( failures > 0 ) {\n process.exit( 1 );\n }\n process.exit( 0 );\n } else {\n console.log( 'Tests still running... See status at https://saucelabs.com/u/' + SAUCE_LABS_USERNAME );\n checkSauce();\n }\n } );\n }, 5000 );\n}",
"function connect() {\n socket = new WebSocket('wss://' + get('server') + '/api/connect');\n socket.onopen = onopen;\n socket.onmessage = onmessage;\n socket.onerror = onerror;\n socket.onclose = onclose;\n }",
"function initializeOpcuaClient(){\n client = new OPCUAClient({keepSessionAlive:true});\n client.connect(\"opc.tcp://\" + os.hostname() + \":\" + port, onClientConnected);\n}",
"async componentDidMount() {\n // create the server chooser\n const chooser = new DefaultServerChooser();\n chooser.add(`ws://${HOST}:${PORT}/amps/json`);\n\n // create the AMPS HA client object\n const client = new Client('view-server');\n client.serverChooser(chooser);\n client.subscriptionManager(new DefaultSubscriptionManager());\n\n // now we can establish connection \n await client.connect();\n\n // update the state\n this.setState({ client });\n }",
"function startNetworkAndTest(onSuccess) {\n if (!isNetworkReady()) {\n SimpleTest.waitForExplicitFinish();\n var utils = getNetworkUtils();\n // Trigger network setup to obtain IP address before creating any PeerConnection.\n utils.prepareNetwork(onSuccess);\n } else {\n onSuccess();\n }\n}",
"function connect() {\n var connectionPromise = nodeConnection.connect(true);\n connectionPromise.fail(function () {\n console.error(\"[brackets-simple-node] failed to connect to node\");\n });\n return connectionPromise; \n }",
"function SaucelabsReporter(logger, browserMap) {\n const log = logger.create('reporter.sauce');\n let pendingUpdates = [];\n this.adapters = [];\n // This fires when a single test is executed and will update the run in sauce labs with an annotation\n // of the test including the status of the test\n this.onSpecComplete = function (browser, result) {\n const status = result.success ? '✅' : '❌';\n browserMap.get(browser.id).results.push({\n status: 'info',\n message: `${status} ${result.fullName}`,\n screenshot: null\n });\n if (!result.success && result.log.length > 0) {\n browserMap.get(browser.id).results.push({\n status: 'info',\n message: `${result.log[0]}`,\n screenshot: null\n });\n }\n };\n // This fires whenever any browser completes. This is when we want to report results\n // to the Saucelabs API, so that people can create coverage banners for their project.\n this.onBrowserComplete = function (browser) {\n const result = browser.lastResult;\n const browserId = browser.id;\n if (result.disconnected) {\n log.error('✖ Browser disconnected');\n }\n if (result.error) {\n log.error('✖ Tests errored');\n }\n const browserData = browserMap.get(browserId);\n // Do nothing if the current browser has not been launched through the Saucelabs\n // launcher.\n if (!browserData) {\n return;\n }\n const { sessionId } = browserData;\n const api = new saucelabs_1.default({\n user: browserData.username,\n key: browserData.accessKey,\n region: browserData.region,\n headless: browserData.headless\n });\n const hasPassed = !result.failed && !result.error && !result.disconnected;\n // Update the job by reporting the test results. Also we need to store the promise here\n // because in case \"onExit\" is being called, we want to wait for the API calls to finish.\n pendingUpdates.push(api.updateJob(browserData.username, sessionId, {\n id: sessionId,\n passed: hasPassed,\n 'custom-data': result\n }));\n log.info(`Check out job at ${getSauceEndpoint(browserData.region)}${sessionId}`);\n };\n // Whenever this method is being called, we just need to wait for all API calls to finish,\n // and then we can notify Karma about proceeding with the exit.\n this.onExit = (doneFn) => Promise.all(pendingUpdates).then(doneFn, (error) => {\n log.error('Could not report results to Saucelabs: %s', error);\n doneFn();\n });\n}",
"function start() {\n connection.connect(function (err) {\n if (err) throw err;\n // greeting the user \n console.log(`\n * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * \n | |\n | .--. |\n | |__| .-------. |\n | |=.| |.-----.| |\n | |--| || EMS || |\n | | | |'-----'|___________________________________________ |\n | |__|~')_____(' Welcome to The Employee Management System |\n | |\n | ~ made with care by -Erik De Luna- |\n | |\n * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * \n `);\n // run the start function after the connection is made to prompt the user\n main();\n // Test();\n });\n}",
"async function connectWebSocket() {\n try {\n const urlForWebsocket = urlBuilder.getWebSocketUrl(_collectionId, _environmentId);\n const _bearerToken = await urlBuilder.getToken();\n const headers = {\n Authorization: _bearerToken,\n };\n closeWebSocket(); // close existing websocket connection if any\n socketClient.connect(\n urlForWebsocket, [], [], headers,\n );\n } catch (error) {\n logger.warning(error.message);\n logger.warning('Connection to the App Configuration server failed with unexpected error');\n }\n }",
"startConnecting() {\n process.nextTick(() => {\n /* First, try to transition from IDLE to connecting. If that doesn't happen\n * because the state is not currently IDLE, check if it is\n * TRANSIENT_FAILURE, and if so indicate that it should go back to\n * connecting after the backoff timer ends. Otherwise do nothing */\n if (!this.transitionToState([connectivity_state_1.ConnectivityState.IDLE], connectivity_state_1.ConnectivityState.CONNECTING)) {\n if (this.connectivityState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) {\n this.continueConnecting = true;\n }\n }\n });\n }",
"function startServer() {\n console.log('*** Starting demo for developer prototyping' +\n ' kit for BeagleBone Green ***');\n\n // Starts the server.\n webserver.start();\n\n // Checks internet connection on board.\n utils.checkInternetConnection(function(result) {\n webserver.sendEventToClient('hasInternet', result);\n hasInternet = result;\n });\n}",
"_connect () {\n if (this._reconnectionInterval) {\n this._reconnectionInterval = clearInterval(this._reconnectionInterval)\n }\n\n if (this._connection && this.isConnected) {\n return\n }\n\n this._connection = new WebSocket(\n this._host + this._createQueryString()\n )\n\n this._connectionAttemps++\n this._listen()\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Getter de l'attribut difficulte retour: La valeur de difficulte | getDifficulte() {
return this.difficulte;
} | [
"get fieldValue(){}",
"get nombre(){\n return this._nombreMascota\n }",
"getData() {\n return PRIVATE.get(this).opt.data;\n }",
"get VisibilityMi() {\n return this.visibilityMi;\n }",
"getCapacidad() {\n return this.capacidad;\n }",
"get payerPhone() {\n return this[_payerPhone];\n }",
"getRawValue() {\n return this.value;\n }",
"getValue() {\n return this.node.value;\n }",
"get percentage() {\n return this._percentage;\n }",
"getDisplayValue() {}",
"getLOD() {\n return this.LOD;\n }",
"getGameLevel() {\n return this.#gameLevel\n }",
"get payerEmail() {\n return this[_payerEmail];\n }",
"get propertyName() {}",
"getValue() {\n const { form, path } = this.props\n if (form && path) return form.getValue(path)\n return this.props.value\n }",
"getChosenAdventure(){\n\t\t\treturn chosenAdventure;\n\t\t}",
"function getAge() {\n return 41;\n}",
"getResolvedValueOnDetachedSymbol() {\n var layer = this._object.layer()\n return layer.valueForOverrideAttribute(\n this.property\n )\n }",
"getUltimoTicket() {\n return `Ticket ${ this.ultimo }`;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creating the function 'addInitals' | function addInitals(first, last){
console.log ('Your Initals:', (first + last));
} | [
"function init() {\n id(\"add\").addEventListener(\"click\", newList);\n }",
"function initRolesTabs(rolesToInit) {\n for(var role in rolesToInit) {\n tabsByRoles[role] = [];\n sortTabsByRoles(tabs[role], role);\n }\n }",
"function init(){\n controllerInit(routerInitModel);\n serviceAuthorizeOps(globalEmitter,'admin',globalDataAccessCall);\n serviceAuthenticate(globalEmitter,'user',globalDataAccessCall);\n genericDataAccess(dataAccessInitModel);\n}",
"function initInviteeCreator(){ \r\n\t\t\t$inviteeCreator.on('click', '.add', scope.controller.handleAddClicked);\r\n\t\t}",
"init() {\n this._createShadowRoot()\n this._attachStyles()\n this._createElements()\n }",
"initAddons() {\n this.createFilterList();\n this.domUtil.createSortingOptions(e => this.sortingChangeListener(e));\n this.domUtil.createPaginationOptions();\n this.initPagination(this.products, defaultRecordsToShow);\n }",
"function algo_init() {\r\n\tfor(var i=0; i < AN.length; i++) {\r\n\t\tALGORITHMS.push(new Algorithm(AN[i],0,0,0,0,false));\r\n\t}\r\n}",
"initializeList(listOfIds) {\n let currentObjectivesCount = parseInt(getValue('cmi.object._count'));\n if (currentObjectivesCount) {\n DEBUG.log('objectives already initialized');\n return;\n } else {\n listOfIds.forEach(obj => this.addObjective(obj));\n }\n }",
"function addInitClass() {\n if ( !window.loaded ) {\n $el.addClass( initClass );\n }\n $( window ).on( 'load.' + pluginName, function() {\n $el.removeClass( initClass );\n window.loaded = true;\n });\n }",
"function _initApp() {\n\n this.containers.forEach(function(containerObj, i) {\n\n var offsetModifier = new Modifier({\n size: [this.options.appWidth, this.options.appHeight],\n transform: Transform.translate(-containerObj.offset.x, -containerObj.offset.y, 0)\n });\n\n var app = new this.options.app({\n transitionables: this.options.transitionables\n });\n\n containerObj.container.add(offsetModifier).add(app);\n\n }.bind(this));\n}",
"function initAutocompleterTextfields()\n{\n\t$$('input.autocompleterTextfield').each(function(el){\n\t\tnew AutocompleterTextfield(el);\n\t});\n}",
"function initializeUI(){\n var i,j,startPos,endPos,theScript;\n var theName=\"\";\n var menuIndex = 0;\n var allScripts = new Array;\n\n allScripts = getObjectTags(\"document\",\"script\");\n for (i in allScripts) {\n theScript = \"\"+allScripts[i];\n if (theScript.indexOf(\"function MM_initTimelines\") != -1) {\n j = theScript.indexOf('].MM_Name');\n while (j != -1) {\n startPos = theScript.indexOf('\"',++j);\n endPos = theScript.indexOf('\"',++startPos);\n if (0 < startPos && startPos < endPos) {\n if (theName==\"\") //first one, insert ALL option\n document.theForm.menu.options[menuIndex++] = new Option(\"** \"+MENUITEM_AllTimelines+\" **\");\n theName = theScript.substring(startPos,endPos);\n document.theForm.menu.options[menuIndex++] = new Option(theName);\n }\n j = theScript.indexOf('].MM_Name',j+1);\n }\n }\n }\n}",
"function init() {\n cache.set(\"appName\", \"Lunch Box\");\n cache.set(\"currency\", \"ETH\");\n cache.set(\"showAddBalance\", false);\n updateAccountInformation();\n\n // set up event listeners\n var contract = web3.eth.contract(deployedAbi);\n var contractInstance = contract.at(deployedAddress);\n\n var eventListener = contractInstance.allEvents();\n eventListener.watch(function(error, event) {\n // just update the meals cache whenever an event arrives\n getMeals();\n // also update single meal cache whenever the event is about the current displayed meal\n if (cache.get('meal') && cache.get('meal').id == event.args.ID.toNumber()) {\n getMeal(event.args.ID.toNumber());\n }\n // balance could also have been updated after an event, update accordingly\n updateAccountInformation();\n });\n //*/\n\n // update page when MetaMask account is changed\n ethereum.on(\"accountsChanged\", function() {\n updateAccountInformation();\n })\n}",
"enterVariableInitializerList(ctx) {\n\t}",
"static init()\n {\n let aeROM = Component.getElementsByClass(document, PCx86.APPCLASS, \"rom\");\n for (let iROM = 0; iROM < aeROM.length; iROM++) {\n let eROM = aeROM[iROM];\n let parmsROM = Component.getComponentParms(eROM);\n let rom = new ROMx86(parmsROM);\n Component.bindComponentControls(rom, eROM, PCx86.APPCLASS);\n }\n }",
"function init() {\n sortableEle = $('#sortable').sortable({\n start: $scope.dragStart,\n update: $scope.dragEnd\n });\n getFields();\n }",
"function init() {\n angular.forEach(railsBindings, function(value, key) {\n railsData[key] = toResource(value);\n });\n }",
"inicializa(){\n globais.flappyBird = criarFlappyBird();\n globais.canos = criarCanos();\n globais.chao = criarChao();\n }",
"init(){\n\t\tthis.calcStats();\n\t\tthis.hpRem = this.getStatValue(Stat.HP);\n\n\t\tthis.poisoned = false;\n\t\tthis.regen = false;\n\t\tthis.shield = false;\n\n this.healableDamage = 0; //damage that can be healed through heart collection\n\n this.eventListenReg.clear();\n\n this.warriorSkills.forEach((skill)=>{\n skill.apply();\n });\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
10 Use an HTML element event to call a function you wrote for the player object to update the yearInLeague data. Display the result (a confirmation of the update). | function updatePlayer() {
initializePlayer();
newPlayer.setYearsInLeague("16");
newPlayer.display();
} | [
"function updateSlotDisplays(player){\n\t\tdocument.getElementById(\"header\").innerHTML = \n\t\t\t\t\t\"<h3>3-of-a-Kind Slot-o-Rama</h3>\" + \n\t\t\t\t\t\"<h4>$\" + payout + \" per credit bet<br>\" +\n\t\t\t\t\t\"Max bet = \" + multiplierMax + \" credits</h4>\";\n\t\tdocument.getElementById(\"credit_cost\").innerHTML = \"<b>$\" + creditCost + \"</b><br>per credit\";\n\t\tdocument.getElementById(\"recent_win_payout\").innerHTML = \"Recent Win Payout:<br><b>$\" + recentWinPayout + \"</b>\";\n\t\tdocument.getElementById(\"previous_turn_payout\").innerHTML = \"Previous Turn Payout:<br><b>$\" + previousTurnPayout + \"</b>\";\n\t\tdocument.getElementById(\"current_bet\").innerHTML = \"Current Bet:<br><b>\" + multiplier + \" credit</b>\";\n\t\tif (player) {\n\t\t\tdocument.getElementById(\"balance\").innerHTML = \"Balance:<br><b>$\" + player.getBalance().toFixed(2) + \"</b>\";\t\n\t\t}\n\t\toutputResults();\n\t}",
"function updatePlayerTotal() {\r\n $(\"#totalAmount\").text(\"Total: \" + playerTotal);\r\n $('#highScore').text(\"High Score: \" + highScore);\r\n setHighScore();\r\n \r\n }",
"changeYear(newYear){\n this.yearReleased = newYear;\n }",
"function showWinMessage() {\n playerMoney += winnings;\n win.text = winnings;\n resetFruitTally();\n checkJackPot();\n}",
"function OnPlayerChange(event) {\n\tconst id = event.target.id\n\tlet player_copy_id = id.includes(performance_prefix)\n\t\t\t\t\t ? event.target.id.replace(performance_prefix, rank_prefix)\n\t\t\t\t\t : id.includes(rank_prefix)\n\t\t\t\t\t ? event.target.id.replace(rank_prefix, performance_prefix):\n\t\t\t\t\t null;\n\n\tif (player_copy_id != null) {\n\t\tconst row = event.target.parentElement.parentElement;\n\t\tconst player_copy = $$(player_copy_id, row);\n\t\tplayer_copy.value = event.target.value;\n\t}\n}",
"function updatePlayerName() {\n var $currentPlayerName = $playerInputs.item(currentPlayer);\n var playerName = $currentPlayerInput.value;\n $currentPlayerName.innerHTML = playerName;\n}",
"function updateStats(){\n var newStats = statsTemplate({\n money:(f.format(player.money)), tick:player.tick/1000\n });\n $(\"#tabStats\").html(newStats);\n}",
"updatePlayerData(playerData) {\n console.log(\"Updating player info...\");\n this.updateTeamData(this.contentRows, \".simLeft\", playerData);\n }",
"function updatePeriod(){\n\n\t\t\tvar tstring;\n\t\t\tvar strarray;\n\t\t\tvar period = Math.round(365 * Math.sqrt( relDist * relDist *relDist * 330001/(330000*relMassSun + relMassEarth)));\n\t\t\tvar yperiod;\n\n\t\t\t//convert the value to the string and update the field of Earth years\n\t\t\tif (period >=1 & period <= 999){\n\t\t\t\ttstring = (period).toPrecision(3);\n\t\t\t\tdocument.getElementById(\"period\").innerHTML = tstring;\n\t\t\t} else if (period < 1 & period >= 0.001) {\n\t\t\t\ttstring = (period).toFixed(3);\n\t\t\t\tdocument.getElementById(\"period\").innerHTML = tstring;\n\t\t\t} else {\n\t\t\t\ttstring = Number((period).toPrecision(3)).toExponential();\n\t\t\t\ttstring = tstring.replace(/e/g,\" × 10^\");\n\t\t\t\tstrarray = tstring.split(\"^\");\n\t\t\t\ttstring = strarray[0] + (strarray[1]).sup();\n\t\t\t\tdocument.getElementById(\"period\").innerHTML = tstring;\n\t\t\t}\n\n\n\t\t\t//convert the value to the string and update the field of Earth years\n\t\t\typeriod = period/365.0;\n\t\t\tif (yperiod >=1 & yperiod <= 999){\n\t\t\t\ttstring = ( yperiod ).toPrecision(3);\n\t\t\t\tdocument.getElementById(\"years\").innerHTML = tstring;\n\t\t\t} else if ( yperiod < 1 & yperiod >= 0.001){\n\t\t\t\ttstring = (yperiod).toFixed(3);\n\t\t\t\tdocument.getElementById(\"years\").innerHTML = tstring;\n\t\t\t} else {\n\t\t\t\ttstring = Number((yperiod).toPrecision(3)).toExponential();\n\t\t\t\ttstring = tstring.replace(/e/g,\" × 10^\");\n\t\t\t\tstrarray = tstring.split(\"^\");\n\t\t\t\ttstring = strarray[0] + (strarray[1]).sup();\n\t\t\t\tdocument.getElementById(\"years\").innerHTML = tstring;\n\t\t\t}\n\n\n\n\t\t\tif (period <= 365){\n\t\t\t\tspeed = Math.round(3600 - (365-period)*9);\n\t\t\t}else{\n\t\t\t\tspeed = Math.round(3600 + (period - 365)*0.035);\n\t\t\t}\n\n\t\t\t//convert the value to the string and update the field of Earth years\n\t\t\tvar force = ( relMassSun * relMassEarth / (relDist * relDist) );\n\t\t\tif (force >=1 & force <= 999){\n\t\t\t\ttstring = force.toPrecision(3);\n\t\t\t\tdocument.getElementById(\"force\").innerHTML= tstring;\n\t\t\t} else if (force < 1 & force >= 0.001){\n\t\t\t\ttstring = force.toFixed(3);\n\t\t\t\tdocument.getElementById(\"force\").innerHTML= tstring;\n\t\t\t} else {\n\t\t\t\ttstring = Number(force.toPrecision(3)).toExponential();\n\t\t\t\ttstring = tstring.replace(/e/g,\" × 10^\");\n\t\t\t\tstrarray = tstring.split(\"^\");\n\t\t\t\ttstring = strarray[0] + (strarray[1]).sup();\n\t\t\t\tdocument.getElementById(\"force\").innerHTML= tstring;\n\t\t\t}\n\t\t}",
"function winloss(playerID) {\n d3.json(`${baseURL}/players/${playerID}/wl`).then(function(data){\n document.getElementById('wins').innerHTML = `<h4> Wins: ${data.win} </h4>`\n document.getElementById('losses').innerHTML = `<h4> Losses: ${data.lose} </h4>`\n var perc = parseFloat(data.win / (data.win + data.lose) * 100).toFixed(2)\n document.getElementById('wlratio').innerHTML = `<h4> Winrate: ${perc}% </h4>`\n document.getElementById('diff').innerHTML = `<h4> Game Diff: ${Math.abs(data.win - data.lose)} </h4>`\n })\n}",
"function showWinner(winner){\n result.innerHTML = `<h2>${winner} Wins!</h2>`;\n modal.style.display = 'block';\n}",
"function updateGame (payout) { //this function is called and given arguments inside weatherResults function above\n\tvar bonusOneTotal;\n\tvar bonusTwoTotal;\n\n\tbonusOneTotal = game.bonusOneTotal;\n\tbonusTwoTotal = game.bonusTwoTotal;\n\n\t// Functions shared by both versions\n\n\tvar oldscore = game.score;\n\tvar newscore = oldscore + payout;\n\n\tfunction displayResultsDialog () {\n\t\t//populate spans inside all results dialogs\n\t if (gameVersion.discreteWeather == true) {\n\t \t$(\".results\").find(\"#weather_outcome\").text(game.gamtaeWeher[game.turn]);\n\t \t$(\".results\").find(\"#weather_report\").text(\" and \" + game.weatherReport);\n\t }\n\t else {\n\t \t$(\".results\").find(\"#weather_outcome\").text(parseInt(game.gamtaeWeher[game.turn]) + \" inches of rain\");\n\t \t$(\".results\").find(\"#weather_report\").removeClass(\"emphasize\").text(\", which was \" + game.weatherReport);\n\t }\n\n \t$(\".results\").find(\"#new_score\").text(payout + \" points\");\n\n \t$(\".results\").find(\"#chosen_crop\").text(\" for \" + game.cropchoice);\n\n\t\t$(\".results\").dialog({\n\t\t\tautoOpen: false,\n\t\t\tmodal: false,\n\t\t\tcloseOnEscape: false,\n\t\t\tdialogClass: \"no-close\",\n\t resizable: false,\n\t draggable: false,\n\t position: {my: 'top', at: 'top+25%', of: '#farm'},\n\t stack: false,\n\t width: '375'\n\t });\n\n\t\t// Bonus dialogs\n\t\tif (oldscore < bonusOneTotal && newscore >= bonusOneTotal) { //this only works now because I made totalRandomPoints global\n\t\t\t$(\"#bonus_count\").text(\"$\" + game.bonusOneDollars);\n\t\t\taddBonus1();\n\t\t\t$(\"#bonus_results\").dialog(\"open\");\n\t\t}\n\n\t\telse if (oldscore < bonusTwoTotal && newscore >= bonusTwoTotal) {\n\t\t\t$(\"#bonus_count\").text(\"$\" + game.bonusTwoDollars);\n\t\t\taddBonus2();\n\t\t\t$(\"#bonus_results\").dialog(\"open\");\n\t\t}\n\n\t\t//Normal results dialogs\n\t\telse {\n\t\t\t$(\"#normal_results\").dialog(\"open\");\n\t\t}\n\n\t\tsetTimeout(function() {$( \".results\" ).dialog( \"close\" )}, .75*game.turnLength);\n\t}; // end of displayResultsDialog()\n\n\tsetTimeout(displayResultsDialog, .25*game.turnLength);\n\n\tfunction addTurn () {\n\t\tif (game.turn < game.maxturn-2) {\n\t\t\tgame.turn = game.turn + 1;\n\t\t}\n\n\t\telse if (game.turn === game.maxturn-2) {\n\t\t\tgame.turn = game.turn + 1;\n\t\t\tgame.gameOver = true;\n\t\t}\n\n\t\telse {\n\t\t\tgame.turn = game.maxturn-1;\n\t\t}\n\n\t\t$(\"#turns_counter\").text(game.turn + \"/\" + game.maxturn);\n\t};\n\n\tfunction newScore () {\n\n\t\tfunction animatePoints () {\n\n\t\t\t$(\"#points_bar\").animate({ boxShadow : \"0 0 15px 10px #ffcc33\" });\n\t\t\tsetTimeout(function () {$(\"#points_bar\").animate({boxShadow : \"0 0 0 0 #fff\" })}, .9*game.turnLength);\n\n\t\t};\n\n\t\tfunction movePointsFlag (maxScore) { //increase height of #points_flag using absolute positioning\n\t\t\tvar indifferentTurn = game.discrete.indifferentTurn;\n\n\t\t\tif (gameVersion.discreteWeather) {\n\t\t\t\tmaxScore = game.discrete.maxScore;\n\t\t\t}\n\n\t\t\telse if (!gameVersion.discreteWeather) {\n\t\t\t\tmaxScore = game.bonusTwoTotal;\n\t\t\t}\n\n\t\t\t//Height of #points_bar as an integer, as defined by its CSS rule (in pixels)\n\t\t\tvar pixelHeight = parseFloat($(\"#points_bar\").css(\"height\"));\n\n\t\t\t//Current CSS position for #points_flag \"bottom\" as an integer\n\t\t\tvar flagHeight = parseFloat($(\"#points_flag\").css(\"bottom\"));\n\n\t\t\t//Current CSS height of #points_fill with \"height\" as an integer\n\t\t\tvar fillHeight = parseFloat($(\"#points_fill\").css(\"height\"));\n\n\t\t\t//Ratio of points per pixel\n\t\t\tvar pointsPerPixelRatio = maxScore/pixelHeight;\n\n\t\t\t//Points_counter moves upward this number of pixels per turn, depending on the turn payout\n\t\t\tvar perTurnHeight = payout/pointsPerPixelRatio;\n\n\t\t\t// If player has already reached bonus 2\n\t\t\tif (game.score > game.bonusTwoTotal) {\n\t\t\t\tvar remainingPixelsPerTurn;\n\n\t\t\t\tif (oldscore < game.bonusTwoTotal && newscore >= game.bonusTwoTotal) {\n\t\t\t\t\tvar remainingHeight = pixelHeight - fillHeight;\n\t\t\t\t\tremainingPixelsPerTurn = remainingHeight/((game.maxturn-game.turn)+0.5);\n\t\t\t\t}\n\n\t\t\t\tflagHeight+=remainingPixelsPerTurn;\n\t\t\t\tfillHeight = flagHeight+20;\n\t\t\t}\n\n\t\t\telse {\n\t\t\t\t// Add perTurnHeight pixels to increase height of #points_flag and #points_fill\n\t\t\t\tflagHeight+=perTurnHeight;\n\t\t\t\tfillHeight = flagHeight + 20;\n\t\t\t}\n\n\t\t\t// Set new heights in CSS style rules for #points_flag and #points_fill\n\t\t\t$(\"#points_flag\").css(\"bottom\", flagHeight);\n\t\t\t$(\"#points_fill\").css(\"height\", fillHeight);\n\n\t\t};\n\n\t\tmovePointsFlag();\n\t\tanimatePoints();\n\n\t\tgame.score += payout;\n\t\t$(\"#point_count\").html(\"<h5>\" + game.score + \"</h5>\");\n\n\t\treturn game.score; //this updates the value of game score\n\n\t}; //end of function newScore\n\n\tnewScore();\n\n\t// Call addBonus functions from displayResultsDialog function, triggered at same time as bonus dialogs\n\tfunction addBonus1 () {\n\t\tgame.realDollars += game.bonusOneDollars; //add value of bonus to realDollars\n\t\t$(\"#dollars_counter\").html(\"$\"+game.realDollars);\n\t};\n\n\tfunction addBonus2 () {\n\t\tgame.realDollars += game.bonusTwoDollars;\n\t\t$(\"#dollars_counter\").html(\"$\"+game.realDollars); //change value of realDollars to combined value of bonuses\n\t};\n\n\t//7.D Server receives selected data for the current turn\n\tfunction recordData (game) {\n\t\t// Ensure game created on server\n\t\tif (game.gameID === undefined) { return; }\n\n\t\tvar payload = {\n\t\t crop_choice: game.cropchoice,\n\t\t weather: game.gamtaeWeher[game.turn],\n\t\t game_over: game.gameOver,\n\t\t score: payout\n\t\t };\n\n\t\t $.ajax(game.serverAddress + '/games/' + game.gameID + '/rounds', {\n\t\t type: 'POST',\n\t\t dataType: 'json',\n\t\t data: payload\n\t\t }).success(function(data) {\n\t\t console.log('Round recorded successfully', data);\n\t\t }).fail(function(jqXHR, text, err) {\n\t\t console.log('Round record failed', jqXHR, text, err);\n\t\t });\n\t};\n\n\trecordData(game);\n\n\t// If maxturn has been reached or exceeded, this function is called\n\tfunction endGame () {\n\t\t//call end-of-game dialog box\n\t\t$(\"button #grow\").addClass(\"hidden\");\n\t\t$(\"#sproutA\").addClass(\"hidden\");\n\t\t$(\"#sproutB\").addClass(\"hidden\");\n\t\t$(\"#playerID\").text(game.gameID);\n\t\t$(\"#total_score\").text(game.score);\n\t\t$(\"#total_dollars\").text(game.realDollars);\n\n \t\t$( \"#end_results\" ).dialog({\n\t autoOpen: true,\n\t modal: true,\n\t sticky: true,\n\t closeOnEscape: false,\n\t resizable: false,\n\t position: {my: 'bottom', at: 'center center-15%', of: '#container'},\n\t stack: true,\n\t height: 'auto',\n\t width: '375',\n\t dialogClass: \"no-close\",\n\t });\n\t};\n\n\tif (game.gameOver === true) {\n\t\tsetTimeout(endGame, game.turnLength);\n\t}\n\n\t//Advance to the next turn\n\tsetTimeout(addTurn, game.turnLength);\n}",
"function updateScoreAndLives() {\r\n\tscoreSpan.innerHTML = score;\r\n\tlivesSpan.innerHTML = lives;\r\n\tresultScoreSpan.innerHTML = score;\r\n}",
"function updateStats(){\n\t//update p1 stats on page\n\tdocument.getElementById(\"p1def\").innerText=player1.def;\n\tdocument.getElementById(\"p1def\").innerText=player1.def;\n\tdocument.getElementById(\"p1lck\").innerText=player1.luck;\n document.getElementById(\"p1atk\").innerText=player1.atk;\n document.getElementById(\"p1spd\").innerText=player1.speed;\n\t\n\t//update p2 stats on page\n\tdocument.getElementById(\"p2def\").innerText=player2.def;\n\tdocument.getElementById(\"p2lck\").innerText=player2.luck;\n document.getElementById(\"p2atk\").innerText=player2.atk;\n document.getElementById(\"p2spd\").innerText=player2.speed;\n}",
"updatePanel() {\n document.getElementById(\"score\").innerText = this.score\n document.getElementById(\"lives\").innerText = '💖'.repeat(this.lives)\n }",
"function editPage(OR, LoD, NoR, additional, firstName, lastName, courseKey) {\n\n // Rate My Professor additions\n $(additional).append(\"<span class=ls-label>★</span>\");\n $(additional).append(\"<span>\" + OR + \"</span>\");\n $(additional).append(\"<span class=ls-label>  LoD:</span>\");\n $(additional).append(\"<span>\" + LoD + \"</span>\");\n $(additional).append(\"<span class=ls-label>  #</span>\");\n $(additional).append(\"<span>\" + NoR + \"</span>\");\n\n //Add grade distribution button\n var button = document.createElement(\"a\");\n button.className = \"grade-button\";\n button.innerText = \"Grades!\";\n\n additional.appendChild(button);\n button.setAttribute(\"courseKey\", courseKey);\n\n // Parses instructor to match Berkeley Time API\n parsedName = lastName + \", \" + firstName.substring(0, 1);\n button.setAttribute(\"instructor\", parsedName.toUpperCase());\n\n // Handles popup events due to mouse hovering over the button\n button.addEventListener(\"mouseover\", showInfo(button, additional, firstName, lastName));\n button.addEventListener(\"mouseout\", removeInfo(button, additional));\n}",
"function chanceUpdateOnUI() {\n let chanceUpdateElement = document.getElementsByClassName(\"chance\")[0];\n chanceUpdateElement.innerHTML = \"Player \" + (chance === 0 ? \"X\" : \"O\");\n}",
"function updateBetAmount() {\r\n $(\"#betAmount\").text(\"Bet Amount: \" + betAmount);\r\n }",
"function btnNextYearClick() {\n\t\terase();\n\t\tyearCheck = yearCheck + 1;\n\t\tconsole.log(monthCheck);\n\t\tsetData();\n\t\tsetMonths();\n\t\tsetYears();\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given an RGBa, RGB, or hex color value, return the alpha channel value. | function acp_get_alpha_value_from_color( value ) {
var alphaVal;
// Remove all spaces from the passed in value to help our RGBa regex.
value = value.replace( / /g, '' );
if ( value.match( /rgba\(\d+\,\d+\,\d+\,([^\)]+)\)/ ) ) {
alphaVal = parseFloat( value.match( /rgba\(\d+\,\d+\,\d+\,([^\)]+)\)/ )[1] ).toFixed(2) * 100;
alphaVal = parseInt( alphaVal );
} else {
alphaVal = 100;
}
return alphaVal;
} | [
"function rgba( r, g, b, a ) {\n\tvar alph = parseFloat( a );\n\tif( r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255 || alph < 0 || alph > 1 ) {\n\t\tconsole.log( \"rgba called with wrong params. r: \" + r + \", g: \" + g + \", b: \" + b + \", a:\" + a );\n\t}\n\telse {\n\t\treturn \"rgba(\" + r + \", \" + g + \", \" + b + \", \" + a + \" )\";\n\t}\n}",
"function GRAY_TO_RGBA() {\n var s = this.s();\n var a = this.a();\n\n return kolor.rgba(s, s, s, a);\n }",
"function RGBA_TO_HSVA() {\n var r = this.r() / 255;\n var g = this.g() / 255;\n var b = this.b() / 255;\n var a = this.a();\n var max = Math.max(r, g, b);\n var min = Math.min(r, g, b);\n var diff = max - min;\n var h;\n var s;\n\n if (max === min) {\n h = 0;\n } else if (max === r && g >= b) {\n h = 60 * (g - b) / diff + 0;\n } else if (max === r && g < b) {\n h = 60 * (g - b) / diff + 360;\n } else if (max === g) {\n h = 60 * (b - r) / diff + 120;\n } else { // max === b\n h = 60 * (r - g) / diff + 240;\n }\n\n if (max === 0) {\n s = 0;\n } else {\n s = diff / max;\n }\n\n var v = max;\n return kolor.hsva(h, s, v, a);\n }",
"function rgba(r, g, b, a) {\n\treturn vec4.fromValues(r * a, g * a, b * a, a);\n}",
"function rgb2hexa(str) {\n colors=/^rgb\\((\\d{1,3}),\\s*(\\d{1,3}),\\s*(\\d{1,3})\\)$/.exec(str);\n hexa = \"#\";\n for (i=1; i<colors.length; i++) {\n color = colors[i];\n if (color>255) color=255;\n hexacolor = parseInt(color, 10).toString(16).toLowerCase();\n hexacolor = (hexacolor.length == 1) ? '0' + hexacolor : hexacolor ;\n hexa = hexa + hexacolor;\n } \n return hexa;\n}",
"function RGBColor(red, green, blue, alpha)\n{\n\tthis.red = red;\n\tthis.green = green;\n\tthis.blue = blue;\n\tthis.alpha = alpha;\n}",
"function acp_update_alpha_value_on_color_control( alpha, $control, $alphaSlider, update_slider ) {\n var iris, colorPicker, color;\n\n iris = $control.data( 'a8cIris' );\n colorPicker = $control.data( 'wpWpColorPicker' );\n\n // Set the alpha value on the Iris object.\n iris._color._alpha = alpha;\n\n // Store the new color value.\n color = iris._color.toString();\n\n // Set the value of the input.\n $control.val( color );\n\n // Update the background color of the color picker.\n colorPicker.toggler.css({\n 'background-color': color\n });\n\n // Maybe update the alpha slider itself.\n if ( update_slider ) {\n acp_update_alpha_value_on_alpha_slider( alpha, $alphaSlider );\n }\n\n // Update the color value of the color picker object.\n $control.wpColorPicker( 'color', color );\n}",
"function CMYK_TO_RGBA() {\n var c = this.c();\n var m = this.m();\n var y = this.y();\n var black = this.b();\n\n var r = 1 - Math.min(1, c * (1 - black) + black);\n var g = 1 - Math.min(1, m * (1 - black) + black);\n var b = 1 - Math.min(1, y * (1 - black) + black);\n return kolor.rgba(r * 255, g * 255, b * 255, this.a());\n }",
"function pickColor(opacity){\n\tvar red = getRandomNumber(0, 255);\n\tvar green = getRandomNumber(0, 255);\n\tvar blue = getRandomNumber(0, 255);\n\tvar rgbaValue = 'rgba(' + red + ',' + green + ',' + blue + ',' + opacity + ')'; // Concatenate values\n\treturn rgbaValue;\n}",
"function updateAlphaInput() {\n\t\tlet hsvCol = new HSVColor (\n\t\t\tCPicker.markers.hue[0].angle,\n\t\t\tCPicker.markers.satv[0].sat,\n\t\t\tCPicker.markers.satv[0].val,\n\t\t\tctrPicker.alphaSlider.value\n\t\t);\n\t\t\n\t\tctrPicker.hexInput.value = hsvCol.getHexRGBA();\n\t\tctrPicker.alphaInput.value = (\n\t\t\tctrPicker.alphaSlider.value * 100\n\t\t).toFixed();\n\t}",
"function getHexColor(val, max) {\r\n\r\n var val2 = max - val; // difference from max \r\n var HiC = 255; // highest color value (lightest color)\r\n var LowC = 75; // lowest color value (darkest color)\r\n \r\n var x = LowC + (val2*(HiC - LowC))/max\r\n\r\n var bin = Math.floor(x).toString(16);\r\n var color = bin + bin + bin;\r\n return color;\r\n}",
"function boundAlpha(a) {\n a = parseFloat(a);\n if (isNaN(a) || a < 0 || a > 1) {\n a = 1;\n }\n return a;\n }",
"function getHexColor() {\n if (Math.round(Math.random())) {\n return \"ff\";\n } else {\n return \"00\";\n }\n}",
"lightColorWithOpacity(r, g, b, a, light) {\n r *= light;\n g *= light;\n b *= light;\n if (r > 255) r = 255;\n if (g > 255) g = 255;\n if (b > 255) b = 255;\n return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';\n }",
"function Color4(/**\n * Defines the red component (between 0 and 1, default is 0)\n */r,/**\n * Defines the green component (between 0 and 1, default is 0)\n */g,/**\n * Defines the blue component (between 0 and 1, default is 0)\n */b,/**\n * Defines the alpha component (between 0 and 1, default is 1)\n */a){if(r===void 0){r=0;}if(g===void 0){g=0;}if(b===void 0){b=0;}if(a===void 0){a=1;}this.r=r;this.g=g;this.b=b;this.a=a;}// Operators",
"function colorBasedOnDiff(diff, left, a) {\n var v = !left || Math.abs(diff) > left ? 1\n : 200 * Math.sqrt(Math.abs(diff / left));\n if (diff >= 0)\n return color_1[\"default\"].rgb(200, 200 - v, 200 - v).alpha(a);\n return color_1[\"default\"].rgb(200 - v, 200, 200 - v).alpha(a);\n}",
"function RGBA_TO_HSLA() {\n var r = this.r() / 255;\n var g = this.g() / 255;\n var b = this.b() / 255;\n var a = this.a();\n var max = Math.max(r, g, b);\n var min = Math.min(r, g, b);\n var diff = max - min;\n var sum = max + min;\n var h;\n var s;\n var l;\n\n if (max === min) {\n h = 0;\n } else if (max === r && g >= b) {\n h = 60 * (g - b) / diff + 0;\n } else if (max === r && g < b) {\n h = 60 * (g - b) / diff + 360;\n } else if (max === g) {\n h = 60 * (b - r) / diff + 120;\n } else { // max === b\n h = 60 * (r - g) / diff + 240;\n }\n\n l = sum / 2;\n\n if (l === 0 || max === min) {\n s = 0;\n } else if (0 < l && l <= 0.5) {\n s = diff / sum;\n } else { // l > 0.5\n s = diff / (2 - sum);\n }\n\n return kolor.hsla(h, s, l, a);\n }",
"toGammaSpace() {\n const convertedColor = new Color3();\n this.toGammaSpaceToRef(convertedColor);\n return convertedColor;\n }",
"function HSLA_TO_HSVA() {\n var h = this.h();\n var s = this.s();\n var l = this.l();\n var a = this.a();\n\n l *= 2;\n s *= (l <= 1) ? l : 2 - l;\n var v = (l + s) / 2;\n var sv = (2 * s) / (l + s);\n return kolor.hsva(h, sv, v, a);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Blocks the GOOGLE_APPLICATION_CREDENTIALS by default. This is necessary in case it is actually set on the host machine executing the test. | function blockGoogleApplicationCredentialEnvironmentVariable(auth) {
return insertEnvironmentVariableIntoAuth(auth, 'GOOGLE_APPLICATION_CREDENTIALS', null);
} | [
"async prepareCredentials() {\n if (this.env[DEFAULT_ENV_SECRET]) {\n const secretmanager = new SecretManager({\n projectId: this.env.GCP_PROJECT,\n });\n const secret = await secretmanager.access(this.env[DEFAULT_ENV_SECRET]);\n if (secret) {\n const secretObj = JSON.parse(secret);\n if (secretObj.token) {\n this.oauthToken = secretObj;\n } else {\n this.serviceAccountKey = secretObj;\n }\n this.logger.info(`Get secret from SM ${this.env[DEFAULT_ENV_SECRET]}.`);\n return;\n }\n this.logger.warn(`Cannot find SM ${this.env[DEFAULT_ENV_SECRET]}.`);\n }\n // To be compatible with previous solution.\n const oauthTokenFile = this.getContentFromEnvVar(DEFAULT_ENV_OAUTH);\n if (oauthTokenFile) {\n this.oauthToken = JSON.parse(oauthTokenFile);\n }\n const serviceAccountKeyFile =\n this.getContentFromEnvVar(DEFAULT_ENV_KEYFILE);\n if (serviceAccountKeyFile) {\n this.serviceAccountKey = JSON.parse(serviceAccountKeyFile);\n }\n }",
"function loadClientSecrets() {\n fs.readFile('client_secret.json', (err, content) => {\n if (err) {\n console.log('Error loading client secret file: ' + err);\n return;\n }\n // Authorize a client with the loaded credentials, then call the\n // Google Sheets API.\n authorize(JSON.parse(content), getPackageData);\n });\n}",
"async ensureAppCredentials(appLookupParams) {\n var _this$credentials2, _this$credentials2$ac, _this$credentials2$ac2;\n\n const appCredentialsIndex = this.getAppCredentialsCacheIndex(appLookupParams);\n const {\n accountName\n } = appLookupParams;\n\n if (this.isPrefetched[accountName] || (_this$credentials2 = this.credentials) !== null && _this$credentials2 !== void 0 && (_this$credentials2$ac = _this$credentials2[accountName]) !== null && _this$credentials2$ac !== void 0 && (_this$credentials2$ac2 = _this$credentials2$ac.appCredentials) !== null && _this$credentials2$ac2 !== void 0 && _this$credentials2$ac2[appCredentialsIndex]) {\n return;\n }\n\n await this.refetchAppCredentials(appLookupParams);\n }",
"function promptForCredentials(){\n var authFailure = getProperty('authFailure');\n if(authFailure == 'true'){\n clearProperties(); \n }\n \n var username = getProperty('username');\n var password = getProperty('password');\n \n //Promt for credentials\n if(username == null || password == null){\n var ui = SpreadsheetApp.getUi();\n var usernameResponse = ui.prompt('Jira Integration', 'This sheet integrates with Jira!\\n\\n Jira Username?', ui.ButtonSet.OK);\n var passwordResponse = ui.prompt('Jira Integration', 'Jira Password?', ui.ButtonSet.OK);\n \n setProperty('username', usernameResponse.getResponseText());\n setProperty('password', passwordResponse.getResponseText()); \n }\n}",
"function purgeCredentials() {\n credentials = null;\n}",
"async function doBasicAuth() {\n clearStatus();\n writeStatus(\"Attempting to retrieve API key secret from auth server\");\n\n try {\n let response = await fetch(\"/basic\");\n let data = await response.json();\n console.log(data);\n\n writeStatus(\n `Received your API key from auth server: ${data.apiKey.substr(1, 12)}...`\n );\n ably = new Ably.Realtime({ key: data.apiKey });\n ably.connection.on((stateChange) => {\n onStateChange(\"Connection\", stateChange);\n });\n } catch (error) {\n writeStatus(`Error retrieving your key from auth server: ${error}`);\n }\n}",
"function initClient() {\n \n const keys = {\n // fill\n };\n\n return new Gdax.AuthenticatedClient(\n keys[\"API-key\"],\n keys[\"API-secret\"],\n keys[\"Passphrase\"],\n keys[\"Exchange-url\"]\n );\n}",
"function fetchCredentials() {\n fetch(url, {\n credentials: `include`\n })\n}",
"function setUpStorageClient(err, credentials){\n if (err) return console.log(err);\n\n storageClient = new StorageManagementClient(credentials, subscriptionId);\n //getStorageAccountsLists();\n //getStorageKeyList();\n createStorageAccount();\n //getStorageKeyList();\n}",
"async getCredentials(keyFile) {\n const ext = path.extname(keyFile);\n switch (ext) {\n case '.json': {\n const key = await readFile(keyFile, 'utf8');\n const body = JSON.parse(key);\n const privateKey = body.private_key;\n const clientEmail = body.client_email;\n if (!privateKey || !clientEmail) {\n throw new ErrorWithCode('private_key and client_email are required.', 'MISSING_CREDENTIALS');\n }\n return { privateKey, clientEmail };\n }\n case '.der':\n case '.crt':\n case '.pem': {\n const privateKey = await readFile(keyFile, 'utf8');\n return { privateKey };\n }\n case '.p12':\n case '.pfx': {\n // NOTE: The loading of `google-p12-pem` is deferred for performance\n // reasons. The `node-forge` npm module in `google-p12-pem` adds a fair\n // bit time to overall module loading, and is likely not frequently\n // used. In a future release, p12 support will be entirely removed.\n if (!getPem) {\n getPem = (await Promise.resolve().then(() => __nccwpck_require__(2119))).getPem;\n }\n const privateKey = await getPem(keyFile);\n return { privateKey };\n }\n default:\n throw new ErrorWithCode('Unknown certificate type. Type is determined based on file extension. ' +\n 'Current supported extensions are *.json, *.pem, and *.p12.', 'UNKNOWN_CERTIFICATE_TYPE');\n }\n }",
"async initialize () {\n await this.generateKey()\n }",
"loadEnvVarsForLocal() {\n const defaultEnvVars = {\n IS_LOCAL: 'true',\n };\n\n _.merge(process.env, defaultEnvVars);\n\n // Turn zero or more --env options into an array\n // ...then split --env NAME=value and put into process.env.\n _.concat(this.options.env || []).forEach(itm => {\n const splitItm = _.split(itm, '=');\n process.env[splitItm[0]] = splitItm[1] || '';\n });\n\n return BbPromise.resolve();\n }",
"async loadDefaults () {\n // No default config files for seeded assets right now.\n const walletDef = app().walletDefinition(this.currentAsset.id, this.currentWalletType)\n if (walletDef.seeded) return\n const loaded = app().loading(this.form)\n const res = await postJSON('/api/defaultwalletcfg', {\n assetID: this.currentAsset.id,\n type: this.currentWalletType\n })\n loaded()\n if (!app().checkResponse(res)) {\n this.setError(res.msg)\n return\n }\n this.subform.setLoadedConfig(res.config)\n }",
"function attemptTlsSync(dev, func) {\n dev.taskCount = 1;\n dev.taskCompleted = func;\n // TODO: We only deal with certificates starting with Intel AMT 6 and beyond\n dev.amtstack.BatchEnum(null, ['AMT_PublicKeyCertificate', 'AMT_PublicPrivateKeyPair', 'AMT_TLSSettingData', 'AMT_TLSCredentialContext'], attemptTlsSyncEx);\n }",
"static async fetch(region, secrets) {\n if (this.stubs) {\n // find any unstubbed secrets\n const unstubbedSecrets = secrets.filter(secret => {\n return !Object.keys(this.stubs).includes(secret);\n });\n if (unstubbedSecrets.length) {\n // if there are any secrets that do not have equivalent stubs\n // raise an informative error.\n throw {\n message: `.fetch() errored. You have unstubbed secrets: [${unstubbedSecrets}]`\n };\n }\n } else {\n // Use AWS Secrets Manager if stubs haven't been set.\n await this._fetchAWSSecrets(region, secrets);\n }\n this.fetched = true;\n return;\n }",
"function waitForAuth(cb) {\n if (!self.authenticating) return cb();\n // Wait for a milisecond and try again\n setTimeout(function () {\n waitForAuth(cb);\n }, 1);\n }",
"async function initKvConnect() {\n const dcCore = require( 'dc-core' );\n const kvconnect = dcCore.config.load( process.cwd() + '/kvconnect.json' ) || {};\n if( !kvconnect ) {\n throw new Error( 'kvconnect: config not there!' );\n }\n\n Y.log( '*** kv_connect init ***', 'debug', NAME );\n if( kvconnect && kvconnect.activate === true ) {\n if( Y.doccirrus.auth.isVPRC() || Y.doccirrus.auth.isPRC() ) {\n globalConfig = kvconnect;\n activated = true;\n await Y.doccirrus.kvconnectRestClient.init();\n Y.log( 'kvconnect activated, read global config: ' + JSON.stringify( globalConfig ), 'debug', NAME );\n } else {\n Y.log( 'kvconnect activated but ignored', 'warn', NAME );\n }\n } else {\n Y.log( 'kvconnect not activated', 'warn', NAME );\n }\n\n }",
"authenticate() {\n this.set('hasResponseMessage', null);\n const {\n formatUsername,\n password,\n api,\n selectedEnvironemnt\n } = this.getProperties('formatUsername', 'password', 'api', 'selectedEnvironemnt');\n return this.get('session').authenticate('authenticator:application', formatUsername, password, api, selectedEnvironemnt)\n .catch(() => {\n this.set('hasResponseMessage', \"Invalid login. Please try again.\");\n });\n }",
"function runSample(demoCallback) {\n var resourceClient;\n var kvManagementClient;\n \n msRestAzure.loginWithServicePrincipalSecret(clientId, secret, tenantId)\n .then( (credentials) => {\n resourceClient = new ResourceManagementClient(credentials, subscriptionId);\n kvManagementClient = new KeyVaultManagementClient(credentials, subscriptionId);\n \n // Create sample resource group. \n console.log(\"Creating resource group: \" + groupName);\n return resourceClient.resourceGroups.createOrUpdate(groupName, { location: azureLocation });\n }).then( () => {\n const kvParams = {\n location: azureLocation,\n properties: {\n sku: { \n name: 'standard'\n },\n accessPolicies: [\n {\n tenantId: tenantId,\n objectId: objectId,\n permissions: {\n secrets: ['all'],\n }\n }\n ],\n enabledForDeployment: false,\n tenantId: tenantId\n },\n tags: {}\n };\n \n console.log(\"Creating key vault: \" + kvName);\n \n // Create the sample key vault using the KV management client.\n return kvManagementClient.vaults.createOrUpdate(groupName, kvName, kvParams);\n }).then( (result) => {\n console.log(\"Vault created with URI '\" + result.properties.vaultUri + \"'\");\n demoCallback(result.properties.vaultUri);\n })\n .catch( (err) => { \n console.log(err); \n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
when the user wants to switch between route options for cars/bikes/pedestrians and clicks the button to switch views | function switchRouteOptionsPane(e) {
// hide options
$('#optionsContainer').hide();
var parent = $('.ORS-routePreferenceBtns').get(0);
var optionType = e.currentTarget.id;
//switch the buttons above
var allBtn = parent.querySelectorAll('button');
for (var i = 0; i < allBtn.length; i++) {
var btn = allBtn[i];
if (btn == e.currentTarget) {
btn.addClassName('active');
//set the selected entry as currently selected route option
var options = $('#' + btn.id + 'Options').get(0).querySelector('input[checked="checked"]');
/* adapt global settings information */
updateGlobalSettings(optionType, options.id);
theInterface.emit('ui:routingParamsChanged');
} else {
btn.removeClassName('active');
}
}
// update options
updateProfileOptions(e.currentTarget.id);
} | [
"function navigateTo() {\n let viewName = $(this).attr('data-target');\n showView(viewName)\n }",
"function setRouteOption(routeOption) {\n //set radioButton with $('#' + routeOption) active\n var el = $('#' + routeOption);\n if (el) {\n el.attr('checked', true);\n }\n // set parent div (with all available options for car/bike/pedestrian/truck/wheelchair visible\n var parentOptions = list.routePreferences.keys();\n var parent;\n for (var i = 0; i < parentOptions.length; i++) {\n if (list.routePreferences.get(parentOptions[i]).indexOf(routeOption) != -1) {\n //activate corresponding option panel\n switchRouteOptionsButton(parentOptions[i]);\n }\n }\n }",
"function switchToView(view) {\n // Hide all views before displaying the one its switching to\n welcome ? welcome.$el.hide() : false;\n setupAssistance ? setupAssistance.$el.hide() : false;\n customUrl ? customUrl.$el.hide() : false;\n marketingConfig ? marketingConfig.$el.hide() : false;\n firstPlan ? firstPlan.$el.hide() : false;\n createPlan ? createPlan.$el.hide() : false;\n planList ? planList.$el.hide() : false;\n storefrontIndex ? storefrontIndex.$el.hide() : false;\n storefrontContent ? storefrontContent.$el.hide() : false;\n storefrontServiceArea ? storefrontServiceArea.$el.hide(): false;\n storefrontFullfilmentAssistance ? storefrontFullfilmentAssistance.$el.hide() : false;\n reviewSettings ? reviewSettings.$el.hide() : false;\n view ? view.$el.show() : false;\n }",
"function displayView(view) {\n console.log(view);\n // hämta alla sidor/get all views\n const pageView = document.getElementById(\"page1\") \n const loginView = document.getElementById(\"logIn\") \n const varningView = document.getElementById(\"varning\") \n \n \n // dölj alla sidor/hide all views\n pageView.style.display = \"none\"\n loginView.style.display = \"none\"\n varningView.style.display = \"none\" \n \n\n // visa den specifika sidan/display specified view\n if (view === 'pageView') {\n pageView.style.display = \"block\"\n }\n \n if (view === 'loginView') {\n loginView.style.display = \"block\"\n }\n\n if (view === 'varningView') {\n varningView.style.display = \"block\"\n } \n \n}",
"function toggleDirections() {\n $(\"#toggleDirections\").on(\"click\", (event) => {\n event.preventDefault();\n if (STORE.nav !== true) {\n addNav();\n STORE.nav = true;\n } else {\n removeNav();\n STORE.nav = false;\n }\n });\n}",
"function setupViewSwitcher(currentView) {\n var elements = document.getElementsByClassName(\"view-switch\");\n\n for (var i=0; i<elements.length; i++) {\n var element = elements[i];\n\n // Click handler to switch view\n element.addEventListener(\"click\", function(evt) {\n switchView(evt.target.getAttribute(\"data-view\"));\n });\n\n // Disable currently used view\n if (element.getAttribute(\"data-view\") === currentView) {\n element.disabled = true;\n }\n }\n}",
"handleVNAVPressed() {\n if (this.currentLateralActiveState !== LateralNavModeState.APPR) {\n this.isVNAVOn = !this.isVNAVOn;\n SimVar.SetSimVarValue(\"L:WT_CJ4_VNAV_ON\", \"number\", this.isVNAVOn ? 1 : 0);\n\n if (this.isVNAVOn) {\n this.handleVPathChanged();\n }\n else {\n SimVar.SetSimVarValue(\"K:ALTITUDE_SLOT_INDEX_SET\", \"number\", 1);\n SimVar.SetSimVarValue(\"K:VS_SLOT_INDEX_SET\", \"number\", 1);\n \n if (this.currentVerticalActiveState === VerticalNavModeState.PATH) { \n SimVar.SetSimVarValue(\"K:AP_PANEL_VS_HOLD\", \"number\", 0);\n this.currentVerticalActiveState = VerticalNavModeState.PTCH;\n }\n }\n }\n }",
"async function booking_nav() {\n console.log(selectedPark);\n if (selectedParkCAP > 0) {\n navigate('/booking', false, {selectedPark: selectedPark});\n }\n else {\n toast.error(\"Oops!!! No space available in this parking lot!\");\n }\n }",
"goToCardIntake() {\n let url;\n if (Auth.get(this).user.role === 'corporate-admin') {\n url = 'main.corporate.customer.intake-revised';\n } else {\n url = 'main.employee.customer.intake-revised';\n }\n if (this.displayData.rejectionTotal) {\n url = url + '.denials';\n }\n state.get(this).go(url, {customerId: this.displayData.selectedCustomer._id});\n }",
"viewWasClicked (view) {\n\t\t\n\t}",
"changeStep() {\n window.location.assign('#/eventmgmt/shop');\n }",
"function changeLes8OefPage() {\n $.mobile.navigate( \"#les8home\", { transition: 'slide'} );\n }// End function changeLes8OefPage()",
"function changeLes5Oef2Page() {\n $.mobile.navigate( \"#les5Oef2\", { transition: 'slide'} );\n }// End function changeLes5Oef2Page()",
"handleClicVerPromociones() {\n this[NavigationMixin.Navigate]({\n type: \"standard__objectPage\",\n attributes: {\n objectApiName: \"Promocion__c\",\n actionName: \"list\"\n }\n });\n }",
"function goToRoute(name){\n let route = Routes.find((route)=>route.name == name)\n Router.push(route);\n window.location.hash = name;\n fillContent(name,route);\n actionNavButton(route);\n recheckBottomNavActiveState(route);\n \n if(document.getElementById(\"navigation-drawer\").classList[0] == \"show-drawer\"){\n toggleDrawer();\n }\n \n}",
"function goToChangeSensitivity(){\n clientValuesFactory.setActiveWindow(windowViews.changeSensitivity);\n }",
"function setupBtnsSensorSelect() {\n\n //add a click action listener to the select buttons\n $(\"#sidebar button.sensorNavBtn\").click(function () {\n var button = $(this);\n\n //check if this is already the current page loaded \n if (!button.hasClass(\"current\")) { //if not then\n loadContent(button.attr(\"data-graph-sensor\")); //load new page\n $(\"#sidebar button.current\").removeClass(\"current\"); //remove current from the previous button\n button.addClass(\"current\"); //add current to the button pressed\n }\n });\n}",
"function watchRouteChange( ) {\n\t\tmyscope.$on('$routeChangeSuccess', function(current) {\n\t\t\t//console.log(\"routeChangeSuccess current route: %o\", current);\n\t\t\t//TODO: need to learn how to get a route name, ok?\n\t\t\t// if its a detail page for citation only, remove any previous hack\n\t\t\tif (window.location.hash.substring(1).indexOf('FETCHMERGED-LOGICAL') != -1) {\n\t\t\t\t\t$('#dnlClickHere').remove();\n\t\t\t\t\t$('#dnlCustom856').remove();\n\t\t\t\t\t$('#dnlMillRequest').remove();\n\t\t\t}\n\t\t\t//if its catalog details page - add all the hacks\n\t\t\tif (window.location.hash.substring(1).indexOf('FETCHMERGED-fairfield_catalog') != -1) {\n\t\t\t//if (myscope.docDetail.visible) {\n\t\t\t\tconsole.log(\"catalog details page open\");\n\t\t\t\tmillBibMatch = window.location.hash.match(/fairfield_catalog_b(\\d{7})/);\n\t\t\t\tconsole.log(\"Mill bib num is \" + millBibMatch[1]);\n\t\t\t\tdnlItemLoc = $('strong:contains(\"Library Location\")').next().html();\n\t\t\t\t//remove any previously added click here to view button\n\t\t\t\tif($('#dnlClickHere').size() > 0){\n\t\t\t\t\t$('#dnlClickHere').remove();\n\t\t\t\t}\n\t\t\t\tif (dnlItemLoc && dnlItemLoc.indexOf(\"Online\") !== -1) {\n\t\t\t\t\tconsole.log(\"this item is e-resourece\");\n\t\t\t\t\t//add click here to view button\n\t\t\t\t\t$('div.documentActionsContainer div.documentActions').prepend('<a id=\"dnlClickHere\" class=\"primary btn ng-binding\" href=\"https://libraryapps.fairfield.edu/summon/js/mill856link.php?bibnum=' + millBibMatch[1] + '\" target=\"_blank\" style=\"display: block;\">Click Here to View</a>');\n\t\t\t\t}\n\n\t\t\t\t//console.log($('strong:contains(\"Library Location\")').next().html());\n\t\t\t\t//remove previously added custom 856\n\t\t\t\tif($('#dnlCustom856').size() > 0){\n\t\t\t\t\t$('#dnlCustom856').remove();\n\t\t\t\t}\n\t\t\t\t//remove previously added request it button\n\t\t\t\tif($('#dnlMillRequest').size() > 0){\n\t\t\t\t\t$('#dnlMillRequest').remove();\n\t\t\t\t}\n\t\t\t\t//get 856 links from WebPac - this is JSONP\n\t\t\t\t$.getJSON(\n\t\t\t\t\t\t'https://libraryapps.fairfield.edu/summon/js/get856json.php?bibnum=' + millBibMatch[1] +'&callback=?',\n\t\t\t\t\t\tfunction(data){\n\t\t\t\t\t\t\ttry{\n\t\t\t\t\t\t\t\tvar Status = data.status;\n\t\t\t\t\t\t\t\tvar BibInfo = data.bibinfo;\n\t\t\t\t\t\t\t\tvar requestAble = data.requestable;\n\t\t\t\t\t\t\t\t//console.log(Status);\n\t\t\t\t\t\t\t\t//console.log(BibInfo);\n\t\t\t\t\t\t\t\tif(Status && Status == \"hasLink\") {\n\t\t\t\t\t\t\t\t\t$('div.fixed.fullDialog.detailPage div.detailSummary div.summary').append('<div id=\"dnlCustom856\"><ul>' + BibInfo + '</ul></div>');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t//add request it button\n\t\t\t\t\t\t\t\tif(requestAble) {\n\t\t\t\t\t\t\t\t\t//console.log(\"this item is requestable: \" + data.requestable);\n\t\t\t\t\t\t\t\t\t$('.documentActions a:contains(\"Request\")').remove();\n\t\t\t\t\t\t\t\t\t$('div.documentActionsContainer div.documentActions').prepend('<a id=\"dnlMillRequest\" class=\"primary btn ng-binding\" href=\"https://libraryapps.fairfield.edu/summon/js/millrequest.php?bibnum=' + millBibMatch[1] + '\" target=\"_blank\" style=\"display: block;\">Request It!</a>');\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} catch(err){\n\t\t\t\t\t\t\t\tconsole.log(err);\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}\n\t\t});\n\t}",
"function goToTeamSelection(){\n clientValuesFactory.setActiveWindow(windowViews.selectTeam);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
an internal function that will add/remove a hidden element called "addl_query" to the participant search form. The element will contain filtering information that will be used by lunr in the participant search to filter out the found results based on the additional filter items. | function updateSearchFormFields(ev) {
let searchForm = document.getElementById("participant_search_form");
let form = ev.target.closest("[data-js-search-filter]");
let checked = [...form.querySelectorAll(":checked")];
let queries = {};
for (let i = 0; i < checked.length; i++) {
if (!queries[checked[i].name]) {
queries[checked[i].name] = [];
}
queries[checked[i].name].push(`${checked[i].name}:${checked[i].value}`);
}
newQueries = Object.values(queries).map((q) => q.join(" "));
searchForm
.querySelectorAll("input[type='hidden']")
.forEach((e) => e.remove());
for (let i = 0; i < newQueries.length; i++) {
let input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", "addl_query");
input.setAttribute("value", newQueries[i]);
searchForm.append(input);
}
searchForm.querySelector("[type='submit']").click();
} | [
"function setupSearchFilter() {\n // an internal function that will add/remove a hidden element called \"addl_query\" to the\n // participant search form. The element will contain filtering information that will be used by\n // lunr in the participant search to filter out the found results based on the additional filter\n // items.\n function updateSearchFormFields(ev) {\n let searchForm = document.getElementById(\"participant_search_form\");\n let form = ev.target.closest(\"[data-js-search-filter]\");\n let checked = [...form.querySelectorAll(\":checked\")];\n let queries = {};\n for (let i = 0; i < checked.length; i++) {\n if (!queries[checked[i].name]) {\n queries[checked[i].name] = [];\n }\n queries[checked[i].name].push(`${checked[i].name}:${checked[i].value}`);\n }\n newQueries = Object.values(queries).map((q) => q.join(\" \"));\n searchForm\n .querySelectorAll(\"input[type='hidden']\")\n .forEach((e) => e.remove());\n for (let i = 0; i < newQueries.length; i++) {\n let input = document.createElement(\"input\");\n input.setAttribute(\"type\", \"hidden\");\n input.setAttribute(\"name\", \"addl_query\");\n input.setAttribute(\"value\", newQueries[i]);\n searchForm.append(input);\n }\n searchForm.querySelector(\"[type='submit']\").click();\n }\n\n // when the search filter items are changed, update the search fields\n on(\"change\", \"[data-js-search-filter]\", updateSearchFormFields);\n\n // when the search filter items are reset, update the search fields once the call stack clears (\n // setTimeout with timeout of 0)\n on(\"reset\", \"[data-js-search-filter]\", function (ev) {\n setTimeout(function () {\n updateSearchFormFields(ev);\n }, 0);\n });\n}",
"function setupParticipantSearch() {\n var searchIndex;\n\n // test for the presence of the participant search form; if present, fetch the \"all people\" index\n // data from the server, and initialize the lunr index with the data.\n document.getElementById(\"participant_search_form\") &&\n fetch(\"/assets/json/all-people-index.json\")\n .then((res) => res.json())\n .then((data) => {\n searchIndex = lunr.Index.load(data);\n });\n\n // submit handler for the participant search form; assumes that the lunr index has been loaded and\n // indexed already per above\n on(\"submit\", \"#participant_search_form\", function (ev) {\n ev.preventDefault();\n var searchResultsCont = document.getElementById(\n \"people_search_results_container\"\n );\n searchResultsCont.classList.remove(\"d-none\");\n var searchResultsEl = document.getElementById(\"people_search_results\");\n if (searchIndex) {\n let queries = [\n ...ev.target.querySelectorAll(\n \"input[name=q], input[name='addl_query']\"\n ),\n ].map((i) => i.value);\n let allResults = queries.map((q) => searchIndex.search(q));\n\n // create hash of result ref and number of queries it shows up in\n let resultCountByRef = {};\n for (let i = 0; i < allResults.length; i++) {\n for (let j = 0; j < allResults[i].length; j++) {\n let ref = allResults[i][j].ref;\n if (!resultCountByRef[ref]) {\n resultCountByRef[ref] = 0;\n }\n resultCountByRef[ref] += 1;\n }\n }\n\n // While looping through the first result set, only add items to results\n // that in are in all result sets.\n let results = [];\n for (let i = 0; i < allResults[0].length; i++) {\n let ref = allResults[0][i].ref;\n if (resultCountByRef[ref] === queries.length) {\n results.push(allResults[0][i]);\n }\n }\n var mostRecentPeopleByName = {};\n var names = results.map((result) => {\n var person = window.allPeople.find((p) => p.id === result.ref);\n if (\n !mostRecentPeopleByName[person.name] ||\n mostRecentPeopleByName[person.name].year < person.year\n ) {\n mostRecentPeopleByName[person.name] = person;\n }\n return person.name;\n });\n var displayedNames = {};\n var resultHtml = names.map((personName) => {\n if (!personName) {\n return \"\";\n }\n var person = mostRecentPeopleByName[personName];\n if (!person || displayedNames[personName]) {\n return \"\";\n }\n displayedNames[personName] = true;\n let website =\n person.website ||\n person.webpage ||\n person.twitter ||\n person.linkedin ||\n person.google_scholar;\n let image = '<div style=\"width: 150px\" class=\"mr-5\"></div>';\n if (person.image) {\n image = `<img loading=\"lazy\" src=\"${person.image}\" alt=\"Image of ${person.name}\" class=\"mr-5 rounded\" width=\"150\">`;\n }\n let name = person.name;\n if (website) {\n name = `<a href=\"${website}\" target=\"_blank\" rel=\"noopener noreferrer\">${name}</a>`;\n }\n return `<div class=\"media mb-5\">\n ${image}\n <div class=\"media-body\">\n <h5 class=\"mt-0 font-weight-bold\">${name}${person.category\n ? ` <span class=\"badge badge-secondary\">${person.category}</span>`\n : \"\"\n }</h5>\n ${person.bio}\n </div>\n </div>`;\n });\n searchResultsEl.innerHTML = resultHtml.join(\" \");\n let zeroResultsEl = document.getElementById(\n \"zero_searches_results_found\"\n );\n let someResultsEl = document.getElementById(\"search_results_listing\");\n if (results.length === 0) {\n zeroResultsEl.classList.remove(\"d-none\");\n someResultsEl.classList.add(\"d-none\");\n } else {\n zeroResultsEl.classList.add(\"d-none\");\n someResultsEl.classList.remove(\"d-none\");\n }\n }\n });\n}",
"function datagrid_add_filter() {\n var jq_afs = $('.datagrid .filters .add-filter select');\n var filter_key = jq_afs.val();\n if( filter_key != '') {\n datagrid_activate_filter(filter_key);\n jq_afs.val('');\n }\n}",
"function addKeywordFilter() {\n var div = document.getElementById(\"keyword-filter\");\n filterId = \"kwfilter\"\n + (parseInt(div.getElementsByTagName(\"span\").length) + 1);\n label = document.createElement('label');\n span = document.createElement('span');\n keywordFilter = document.createElement('select');\n label.id = filterId;\n span.onclick = function () {\n this.parentNode.outerHTML = \"\";\n };\n span.innerHTML = \"- Remove\";\n keywordFilter.innerHTML = document.getElementById(\"options\").innerHTML;\n label.appendChild(span);\n label.appendChild(keywordFilter);\n div.appendChild(label);\n}",
"function addLinearBrowseControls(){\n\n\tvar position = jQuery(document).getUrlParam(\"p\");\n\tvar total = jQuery(document).getUrlParam(\"t\");\n\tvar rows = jQuery(document).getUrlParam(\"rows\");\n\tvar qs = buildSolrQueryString();\n\tif(qs == \"\") return false;\n\tquerySolrServer(qs, position, total, rows, qs);\n\t\n}",
"function appendSearchBar() {\n const header = document.querySelector('.page-header');\n const searchDiv = document.createElement('form');\n searchDiv.innerHTML = `<input placeholder=\"Search for students...\"><button>Search</button>`;\n searchDiv.className = 'student-search';\n header.appendChild(searchDiv);\n\n searchDiv.addEventListener('submit', (e) => {\n e.preventDefault();\n let searchValue = e.target[0].value;\n searchItem(listItems, searchValue);\n e.target[0].value = '';\n });\n}",
"function lc_update_filter_in_page (_param, _colFilters)\n{\n\tvar filter_string = _colFilters.join ('_');\n\n\t// In case all collapsed columns have now been expanded, making filter_string\n\t// empty, make it non-empty so that the server will parse the changes.\n\tif (!filter_string)\n\t\tfilter_string = '_';\n\n\tlc_update_filter_in_links (document.getElementsByTagName ('A'), _param, filter_string);\n\tlc_update_filter_in_links (document.getElementsByTagName ('AREA'), _param, filter_string);\n\n\t// Update the hidden field\n\tvar hidden = document.getElementById (_param);\n\n\tif (hidden)\n\t\thidden.value = filter_string;\n}",
"function createFilterArea() {\n div.className = \"filterArea\";\n filterLabel.textContent = htmlTxt['filterLabelText'];\n filterCheckbox.type = 'checkbox';\n filterLabel.appendChild(filterCheckbox);\n div.appendChild(filterLabel);\n const listInfo = document.querySelector('#listInfo');\n listInfo.parentNode.insertBefore(div, listInfo.nextSibling);\n}",
"function createSearchElement() {\n appendSearchElementToDOM();\n addDynamicSearchFunctionality();\n}",
"function addSearchField(event, searchtext, connector, section) {\n // Get the current number of search fields on the page\n // REMEMBER this includes the element inside of .addsearchfieldcopy!!\n var numfields = $('.searchword').length;\n if (!searchtext || typeof searchtext == 'undefined')\n searchtext = '';\n if (!connector || typeof connector == 'undefined')\n connector = '';\n if (!section || typeof section == 'undefined')\n section = '';\n\n // Display error message when we reach limit\n if (numfields == 10) {\n showSearchFieldError();\n return false;\n }\n\n var nextNumfields = Number(numfields) + 1;\n var addsearchfieldcopy = $('.addsearchfieldcopy').clone(true);\n addsearchfieldcopy.toggleClass('addsearchfieldcopy addsearchfielddiv').show();\n addsearchfieldcopy.find(\".searchwordcopy\").toggleClass(\"searchwordcopy searchword\").val(searchtext);\n addsearchfieldcopy.find(\".section option[value='\" + section + \"']\").attr(\"selected\", \"true\");\n addsearchfieldcopy.find(\".boolean option[value='\" + connector + \"']\").attr(\"selected\", \"true\");\n addsearchfieldcopy.find(\".boolean\").attr(\"title\", \"boolean operator for combining textbox \" + numfields + \" and textbox \" + nextNumfields);\n $(\"#searchfields\").append(addsearchfieldcopy);\n $(addsearchfieldcopy).on(\"input change\", enableSearchButton);\n $(\"#resetsearch_tool\").show();\n\n // Re-init jquery handlers.\n $(\".removesearchlink\").click(removeSearchField);\n\n if (typeof AUTOSUGGEST != 'undefined' && AUTOSUGGEST != null\n && AUTOSUGGEST.enabled) {\n AUTOSUGGEST.checkACFields();\n }\n return false;\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 addFormElem(moduleChosen){\n\tclearForm();\n\tvar moduleCode = moduleChosen.split(' ')[0];\n\taddLecture(moduleCode);\n\taddRest(moduleCode);\n\taddButton();\n\tselectize();\n\tprepareInfoDisplay();\n\taddEventForFormElem(moduleCode);\n}",
"function updateFromFilters(){\n\n //$(\"input\").prop('disabled', true);\n\n var newList = _(elements)\n .forEach(function(d){ map.removeLayer(d.marker) })\n .filter(computeFilter)\n .forEach(function(d){ d.marker.addTo(map) })\n .value();\n\n updateList(newList);\n updateFromMap();\n }",
"function setGenerateSearchElement(elt,config){if(config.logLevel>0)alert(\"running setGenerateSearchElement\");\nvar dynamicHTML=false;\nif(dynamicHTML){ // this kind of code may be needed for IE; \nvar A=[[\"form\",\"action\",\"javascript:void(0)\",\"name\",\"searchForm\",\"id\",\"searchForm\",\n \"onsubmit\",\n \"thePlayerManager.lookup(document.forms.searchForm.searchfield.value,document.forms.searchForm)\"],\n [\"input\",\"id\",\"searchfield\",\"name\",\"searchfield\",\"type\",\"text\",\"size\",\"35\",\n \"title\",\"search text; word for dict, can be reg exp for script or commentary\"],\n [\"input\",\"id\",\"searchbutton\",\"value\",\"Search\",\"type\",\"button\",\n \"onclick\",\"thePlayerManager.lookup(this.form.searchfield.value,this.form,event)\",\n \"title\",\"search for word in dict, or for text in page or (with ctrl key down) repository\"],\n [\"br\"],\n [[\"div\",\"id\",\"boxes\"],\n [\"input\",\"onchange\",\"checkChanger.change(this)\",\"type\",\"checkbox\",\n \"checked\",\"checked\", \"name\",\"dict\", \"id\",\"dictCheckbox\"],\n [null,\"dictionary\\u00A0\\u00A0\"],\n [\"input\",\"onchange\",\"checkChanger.change(this)\",\"type\",\"checkbox\",\n \"checked\",\"checked\", \"name\",\"script\", \"id\",\"scriptCheckbox\"],\n [null,\"script\\u00A0\\u00A0\"],\n [\"input\",\"onchange\",\"checkChanger.change(this)\",\"type\",\"checkbox\",\n \"checked\",\"checked\", \"name\",\"comm\", \"id\",\"commCheckbox\"] ,\n [null,\"commentary\\u00A0\\u00A0\"]\n ]\n ];\n var X=newElt(A); elt.appendChild(X);\n} else {\n\nvar S= // ' <div id=\"search\">\\n'+\n' <form action=\"javascript:void(0)\" name=\"searchForm\"\\n'+\n' onsubmit=\"thePlayerManager.lookup(document.forms.searchForm.searchfield.value,document.forms.searchForm)\">\\n'+\n' <input id=\"searchfield\" type=\"text\" size=\"35\" \\n'+\n' title=\"search text; word for dict, can be reg exp for script or commentary\" />\\n'+\n' \\n'+\n' <input id=\"searchbutton\" type=\"button\" value=\"Search\" \\n'+\n' onclick=\"thePlayerManager.lookup(this.form.searchfield.value,this.form,event)\" \\n'+\n' title=\"search for word in dict, or for text in page or (with ctrl key down) repository\" /> <br/> \\n'+\n' <div id=\"boxes\">\\n'+\n' <input onchange=\"checkChanger.change(this)\" type=\"checkbox\" \\n'+\n' checked=\"checked\" name=\"dict\" id=\"dictCheckbox\" />dictionary\\u00A0\\u00A0\\n'+\n' <input onchange=\"checkChanger.change(this)\" type=\"checkbox\" \\n'+\n' name=\"script\" id=\"scriptCheckbox\" />script\\u00A0\\u00A0\\n'+\n' <input onchange=\"checkChanger.change(this)\" type=\"checkbox\" \\n'+\n' name=\"comm\" id=\"commCheckbox\" />commentary\\u00A0\\u00A0</div>\\n'+\n' </form>\\n';\n// '</div>';\nelt.innerHTML=S;\n}\nif(config.logLevel>0)alert(\"done setGenerateSearchElement\");\n}",
"function addPart(){\n var panel = View.panels.get('wo_upd_wr_form');\n var wrId = panel.getFieldValue(\"wr.wr_id\");\n \n var rest = new Ab.view.Restriction();\n rest.addClause(\"wrpt.wr_id\", wrId, \"=\");\n rest.addClause(\"wrpt.part_id\", '', \"=\");\n View.openDialog(\"ab-helpdesk-workrequest-newpart.axvw\", rest, true);\n}",
"function resourcePageAlter(){\n\t\t//added a div in search box of resource filter\n\t\t$('.resource-filter-block .views-exposed-widgets>div:nth-child(1)').append(\"<div class='resource-search-icon'></div>\");\n\t\t//fields of search form wrapped with a div and make the wrapper hide and show on click\n\t\t$('.resource-filter-block .views-exposed-widgets>div:nth-child(2) , .resource-filter-block .views-exposed-widgets>div:nth-child(3) , .resource-filter-block .views-exposed-widgets>div:nth-child(4) , .resource-filter-block .views-exposed-widgets>div:nth-child(5),.resource-filter-block .views-exposed-widget.views-submit-button').wrapAll(\"<div class='filter-wrapper'> </div>\");\n\t\t//$('body').delegate(\".resource-filter-advanced\", \"click\",function(){\n\t\t$('.resource-filter-advanced').on(\"click\",function(){\n\t\t\t$('.page-resources .main-container>.row>aside').css({\"height\":\"auto\"});\n\t\t\t$('.page-resources .main-container>.row>.col-sm-9 ').css(\"height\",\"auto\");\n\t\t\tif($('.resource-filter-block').hasClass(\"show\")){\n\t\t\t\t$('.resource-filter-block').removeClass(\"show\");\n\t\t\t\t$('.resource-filter-advanced .show-hide').text('+');\n\t\t\t}\n\t\t\telse{\n\t\t\t\t$('.resource-filter-block').addClass(\"show\");\n\t\t\t\t$('.resource-filter-advanced .show-hide').text('-');\n\t\t\t}\n\t\t\t$(\".page-resources .main-container>.row>aside , .page-resources .main-container>.row>.col-sm-9 \").equalHeights();\n\t\t\tvar h1= $('.page-resources .main-container>.row>aside').height();\n\t\t\tvar h2= $('.page-resources .main-container>.row>.col-sm-9 ').height();\n\t\t});\n\t\t//triggered the click event of apply button when search icon in resource search box is clicked\n\t\t$('body').delegate(\".resource-search-icon\", \"click\",function(){\n\t\t\t$('.resource-filter-block .views-exposed-widgets button').trigger('click');\n\t\t});\n\t\t\n\t}",
"function filterDataSetItems() {\n // Declare variables\n var input, filter, ul, li, a, i;\n input = document.getElementById('searchFilter');\n filter = input.value.toUpperCase();\n ul = document.getElementById(\"data-set-list-ul\");\n li = ul.getElementsByClassName('data-set-item');\n // Loop through all list items, and hide those who don't match the search query\n for (i = 0; i < li.length; i++) {\n a = li[i];\n if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {\n li[i].style.display = \"\";\n } else {\n li[i].style.display = \"none\";\n }\n }\n}",
"function addOnResults(element) {\n\tresultsDiv.appendChild(element);\n}",
"function addFilter(filter) {\n var filterRow = filterTable\n .append(\"tr\")\n .attr(\"class\", \"filter-row\")\n .attr(\"id\", filter.id); //Give the filter rows id that is the name of the filter\n\n //The text saying which variable is filtered\n filterRow\n .append(\"td\")\n .append(\"text\")\n .attr(\"class\", \"filter-text\")\n .text(filter.label + \": \");\n\n //Add the scale\n var scaleContainer = filterRow.append(\"td\");\n createD3Scaler(scaleContainer, filter);\n var buttonContainer = filterRow.append(\"td\");\n createRemoveButton(buttonContainer, filter);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A UI method to revert a draft document to the last published version or, if the document has never been published, delete the draft entirely. The user is advised of the difference. Returns an object if a change was made, or false if an error was reported to the user. If the draft document still exists the returned object will have a `doc` property containing its newly reverted contents. | async discardDraft(doc) {
const isPublished = !!doc.lastPublishedAt;
try {
if (await apos.confirm({
heading: isPublished
? 'apostrophe:discardDraft'
: 'apostrophe:deleteDraft',
description: isPublished
? 'apostrophe:discardDraftDescription'
: 'apostrophe:deleteDraftDescription',
affirmativeLabel: isPublished
? 'apostrophe:discardDraftAffirmativeLabel'
: 'apostrophe:deleteDraftAffirmativeLabel',
interpolate: {
title: doc.title
}
})) {
const action = window.apos.modules[doc.type].action;
if (isPublished) {
const newDoc = await apos.http.post(`${action}/${doc._id}/revert-draft-to-published`, {
body: {},
busy: true
});
apos.notify('apostrophe:draftDiscarded', {
type: 'success',
dismiss: true,
icon: 'text-box-remove-icon'
});
apos.bus.$emit('content-changed', {
doc: newDoc,
action: 'revert-draft-to-published'
});
return {
doc: newDoc
};
} else {
await apos.http.delete(`${action}/${doc._id}`, {
body: {},
busy: true
});
apos.notify('apostrophe:draftDeleted', {
type: 'success',
dismiss: true
});
apos.bus.$emit('content-changed', {
doc,
action: 'delete'
});
return {};
}
}
} catch (e) {
await apos.alert({
heading: this.$t('apostrophe:error'),
description: e.message || this.$t('apostrophe:errorWhileRestoringPrevious'),
localize: false
});
}
} | [
"async revert(_cancellation) {\r\n const diskContent = await vscode.workspace.fs.readFile(this.uri);\r\n this._bytesize = diskContent.length;\r\n this._documentData = diskContent;\r\n this._unsavedEdits = [];\r\n this._edits = [];\r\n // // If we revert then the edits are exactly what's on the disk\r\n // this._edits.flat().forEach(e => e.sameOnDisk = true);\r\n this._onDidChangeDocument.fire({\r\n fileSize: this.filesize,\r\n type: \"revert\",\r\n edits: []\r\n });\r\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 }",
"async delete(draftLinks) {\n return this.apiClient.deleteDraft(draftLinks);\n }",
"async deleteReview(draftLinks) {\n return this.apiClient.deleteReview(draftLinks);\n }",
"function isDocumentUnsaved(doc){\n\t\t// assumes doc is the activeDocument\n\t\tcTID = function(s) { return app.charIDToTypeID(s); }\n\t\tvar ref = new ActionReference();\n\t\tref.putEnumerated( cTID(\"Dcmn\"),\n\t\tcTID(\"Ordn\"),\n\t\tcTID(\"Trgt\") ); //activeDoc\n\t\tvar desc = executeActionGet(ref);\n\t\tvar rc = true;\n\t\t\tif (desc.hasKey(cTID(\"FilR\"))) { //FileReference\n\t\t\tvar path = desc.getPath(cTID(\"FilR\"));\n\t\t\t\n\t\t\tif (path) {\n\t\t\t\trc = (path.absoluteURI.length == 0);\n\t\t\t}\n\t\t}\n\t\treturn rc;\n\t}",
"workflowTemplateDraft(id) {\n return this.draft(id);\n }",
"async publish(doc) {\n const previouslyPublished = !!doc.lastPublishedAt;\n const action = window.apos.modules[doc.type].action;\n try {\n doc = await apos.http.post(`${action}/${doc._id}/publish`, {\n body: {},\n busy: true\n });\n apos.notify('apostrophe:changesPublished', {\n type: 'success',\n dismiss: true,\n icon: 'check-all-icon',\n buttons: [\n {\n type: 'event',\n label: 'apostrophe:undoPublish',\n name: previouslyPublished ? 'revert-published-to-previous' : 'unpublish',\n data: {\n action,\n _id: doc._id\n }\n }\n ]\n });\n apos.bus.$emit('content-changed', {\n doc,\n action: 'publish'\n });\n return doc;\n } catch (e) {\n if ((e.name === 'invalid') && e.body && e.body.data && e.body.data.unpublishedAncestors) {\n if (await apos.confirm({\n heading: 'apostrophe:unpublishedParent',\n description: 'apostrophe:unpublishedParentDescription'\n }, {\n interpolate: {\n unpublishedParents: e.body.data.unpublishedAncestors.map(page => page.title).join(this.$t('apostrophe:listJoiner'))\n }\n })) {\n try {\n for (const page of e.body.data.unpublishedAncestors) {\n await apos.http.post(`${action}/${page._id}/publish`, {\n body: {},\n busy: true\n });\n }\n // Retry now that ancestors are published\n return this.publish(doc);\n } catch (e) {\n await apos.alert({\n heading: this.$t('apostrophe:errorWhilePublishing'),\n description: e.message || this.$t('apostrophe:errorWhilePublishingParentPage'),\n localize: false\n });\n }\n }\n } else {\n await apos.alert({\n heading: this.$t('apostrophe:errorWhilePublishing'),\n description: e.message || this.$t('apostrophe:errorWhilePublishingDocument'),\n localize: false\n });\n }\n return false;\n }\n }",
"function createDraftsObject() {\n return {\n text: null,\n replies: {}\n }\n}",
"remove({ Meteor }, { _id }) {\n Meteor.call(\n 'documents.remove',\n {\n _id,\n }, (error) => {\n if (error) {\n Bert.alert(error.reason, 'danger');\n } else {\n Bert.alert('Document removed!', 'success');\n }\n },\n );\n }",
"async unpublish(req, doc) {\n const m = self.getManager(doc.type);\n return m.unpublish(req, doc);\n }",
"async create(draft) {\n return this.apiClient.createDraft(draft);\n }",
"get newDoc() {\n return (\n this._doc || (this._doc = this.changes.apply(this.startState.doc))\n )\n }",
"revert() {\n this.innerHTML = this.__canceledEdits;\n }",
"function unlinkDocument( user, document, res ) {\n var docIndex = arrayIdIndex( document._id, user.docList );\n if( docIndex === -1 ) return handleError( res, \"Document Unlink Error: Document not in User's Document List\" );\n user.docList.splice( docIndex, 1 );\n user.save()\n .catch( updateUserError => handleError( res, \"Update User Error: \" + updateUserError ) )\n .then( updatedUser => {\n var userIndex = arrayIdIndex( user._id, document.collaboratorList );\n if( userIndex === -1 ) return handleError( res, \"User Unlink Error: User not in Document's Collaborator List\" );\n document.collaboratorList.splice( userIndex, 1 );\n return document.save();\n })\n .catch( documentUpdateError => handleError( res, \"Document Update Error: \" + documentUpdateError ) )\n .then( updatedDocument => {\n res.json({ success: true, action: \"unlink\" });\n });\n}",
"function deleteSyncDoc(service, SyncDoc) {\n service\n .documents(SyncDoc)\n .remove()\n .then(response => {\n // console.log(response);\n console.log(\"== deleteSyncDoc ==\");\n})\n .catch(error => {\n console.log(error);\n });\n}",
"function extPart_queueDocEditsForDelete(partObj)\n{\n var partName = partObj.getName();\n var nodeSeg = partObj.getNodeSegment();\n var version = partObj.getVersion();\n\n var optionFlags = 0;\n if (version < 5.0)\n {\n optionFlags = docEdits.QUEUE_DONT_MERGE;\n }\n\n if (extPart.DEBUG) alert(\"deleting \" + partName + \":\\n\" + nodeSeg.toString());\n\n // TODO: This is a HACK. It is here to fix up the node offset\n // ranges for certain found nodes. For some reason,\n // these ranges can be off by a few characters.\n if (nodeSeg.matchRangeMin == null || nodeSeg.matchRangeMin == 0)\n {\n var outerLength = dwscripts.getOuterHTML(nodeSeg.node).length;\n var matchRange = nodeSeg.matchRangeMax - nodeSeg.matchRangeMin;\n if (Math.abs(outerLength - matchRange) <= 3)\n {\n nodeSeg.matchRangeMax = outerLength;\n }\n }\n\n // Check if other SBs depend on this node\n if (!extUtils.isDependentNodeSegment(nodeSeg, false))\n {\n var deleteType = extPart.getDeleteType(partName);\n var weight = extPart.getWeight(partName);\n\n if (deleteType == \"none\")\n {\n // do nothing\n if (extPart.DEBUG) alert(\"delete type set to none. nothing will be removed\");\n }\n else if (deleteType == \"tagOnly\" ||\n (!deleteType && weight == \"wrapSelection\"))\n {\n if (extUtils.isBlockTag(nodeSeg.node))\n {\n // preserve the innerHTML\n\n // The old call to dwscipts.getInnerHTML() didn't work for\n // parts that inserted nested tags like\n // <ASP:Repeater><ItemTemplate> because it only looks\n // for the first begin/end tag pair. Now, we call\n // extPart.getInnerHTML(), which knows exactly how\n // many tags were inserted.\n\n var newInnerHTML = extPart.getInnerHTML(partName, nodeSeg.node);\n\n // change the whole node\n nodeSeg = new NodeSegment(nodeSeg.node);\n\n if (extPart.DEBUG) alert(\"replacing:\\n\" + nodeSeg.toString() + \"\\n\\nwith:\\n\" + newInnerHTML);\n\n docEdits.queue(newInnerHTML, nodeSeg, null, null, optionFlags);\n }\n else\n {\n // do nothing, tagOnly delete type specified for non-block tag\n }\n }\n else if (deleteType == \"innerOnly\")\n {\n if (weight.indexOf(\"nodeAttribute\") != -1)\n {\n // just remove the value, leave the attribute\n var delInfo = weight.substring(weight.indexOf(\"+\")+1);\n var delRange = extUtils.findAttributePosition(nodeSeg.node,delInfo,false, true);\n\n // set the node relative segment range\n nodeSeg.matchRangeMin = delRange[0];\n nodeSeg.matchRangeMax = delRange[1];\n\n if (extPart.DEBUG) alert(\"deleting:\\n\" + nodeSeg.toString());\n\n extPart.queueDocEdit(partName, \"\", nodeSeg, null, null, optionFlags);\n }\n else\n {\n // remove the innerHTML of this node\n\n //has a child, so use that to add back all before the child,\n // and after the innerHTML\n var node = nodeSeg.node;\n if (node.hasChildNodes() && node.childNodes.length)\n {\n var outerHTML = dwscripts.getOuterHTML(node);\n var offsets = extPart_getInnerHTMLOffsets(partName, node);\n var newOuterHTML = outerHTML.substring(0, offsets.begin - 1) +\n outerHTML.substring(offsets.end + 1);\n\n if (extPart.DEBUG) alert(\"replacing:\\n\" + nodeSeg.toString() + \"\\n\\nwith:\\n\" + newOuterHTML);\n\n extPart.queueDocEdit(partName, newOuterHTML, nodeSeg, null, null, optionFlags);\n }\n else\n {\n //nothing in it, so don't delete anything\n }\n }\n }\n else if (deleteType.indexOf(\"attribute+\") == 0)\n {\n var delInfo = deleteType.substring(deleteType.indexOf(\"+\")+1);\n // check if a parameter was passed\n if (delInfo.indexOf(\"@@\") == 0)\n {\n var paramName = delInfo.replace(/@/g, \"\");\n var parameters = partObj.getParameters();\n delInfo = parameters[paramName];\n }\n var delRange = extUtils.findAttributePosition(nodeSeg.node,delInfo,true, true);\n\n // set the node relative segment range\n nodeSeg.matchRangeMin = delRange[0];\n nodeSeg.matchRangeMax = delRange[1];\n\n if (extPart.DEBUG) alert(\"deleting:\\n\" + nodeSeg.toString());\n\n extPart.queueDocEdit(partName, \"\", nodeSeg, null, null, optionFlags);\n }\n else\n {\n if (weight.indexOf(\"nodeAttribute+\") != -1)\n {\n var delInfo = weight.substring(weight.indexOf(\"+\")+1);\n\n var delRange = extUtils.findAttributePosition(nodeSeg.node,delInfo,true, true);\n\n // set the node relative segment range\n nodeSeg.matchRangeMin = delRange[0];\n nodeSeg.matchRangeMax = delRange[1];\n }\n\n if (extPart.DEBUG) alert(\"deleting:\\n\" + nodeSeg.toString());\n\n extPart.queueDocEdit(partName, \"\", nodeSeg, null, null, optionFlags);\n }\n }\n}",
"function forwardDraft(id) {\n try {\n \n //Logger.log(\"\\n\"+\"Pre Get draft\"+\"\\n\");\n var message = GmailApp.getDraft(id);\n //Logger.log(\"\\n\"+\"Got draft\"+\"\\n\");\n message.send();\n //Logger.log(\"\\n\"+\"Sent draft\"+\"\\n\");\n\n } catch (e) {\n return e.toString();\n }\n}",
"deleteDoc(doc) {\n this.docs.delete(doc.getIdentifier());\n }",
"function stateReverted() {\n var FlowState = w2ui.propertyForm.record.FlowState;\n var si = getCurrentStateInfo();\n if (si == null) {\n console.log('Could not determine the current stateInfo object');\n return;\n }\n si.Reason = \"\";\n var x = document.getElementById(\"smRevertReason\");\n if (x != null) {\n si.Reason = x.value;\n }\n if (si.Reason.length < 2) {\n w2ui.stateChangeForm.error('ERROR: You must supply a reason');\n return;\n }\n finishStateChange(si,\"revert\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
TODO: Do we need both validateWire and trySelectWire? | function validateWire () {
if (wire.requests.length) return
var i = self._selections.length
while (i--) {
var next = self._selections[i]
var piece
if (self.strategy === 'rarest') {
var start = next.from + next.offset
var end = next.to
var len = end - start + 1
var tried = {}
var tries = 0
var filter = genPieceFilterFunc(start, end, tried)
while (tries < len) {
piece = self._rarityMap.getRarestPiece(filter)
if (piece < 0) break
if (self._request(wire, piece, false)) return
tried[piece] = true
tries += 1
}
} else {
for (piece = next.to; piece >= next.from + next.offset; --piece) {
if (!wire.peerPieces.get(piece)) continue
if (self._request(wire, piece, false)) return
}
}
}
// TODO: wire failed to validate as useful; should we close it?
// probably not, since 'have' and 'bitfield' messages might be coming
} | [
"selectInputSourceNet() {\n this._selectInputSource(\"i_net\");\n }",
"checkValidity() {\n this.select.checkValidity();\n }",
"async _validateAndConnectDevice(rethrowErrors) {\r\n this.epIn = null;\r\n this.epOut = null;\r\n\r\n let ife = this.device.configurations[0].interfaces[0].alternates[0];\r\n for (let endpoint of ife.endpoints) {\r\n console.debug(\"Checking endpoint:\", endpoint);\r\n if (endpoint.type !== \"bulk\") {\r\n console.debug(\"Endpoint type not bulk. Ignoring...\")\r\n continue;\r\n }\r\n\r\n if (endpoint.direction === \"in\") {\r\n if (this.epIn !== null) {\r\n throw new UsbError(\"Interface has multiple IN endpoints\");\r\n }\r\n this.epIn = endpoint.endpointNumber;\r\n } else if (endpoint.direction === \"out\") {\r\n if (this.epOut !== null) {\r\n throw new UsbError(\"Interface has multiple OUT endpoints\");\r\n }\r\n this.epOut = endpoint.endpointNumber;\r\n }\r\n }\r\n if (this.epIn == null || this.epOut == null) {\r\n throw new UsbError(\"Could not find the required IN and OUT endpoints\")\r\n }\r\n\r\n console.debug(\"Endpoints: in =\", this.epIn, \", out =\", this.epOut);\r\n\r\n try {\r\n await this.device.open();\r\n // Opportunistically reset to fix issues on some platforms\r\n try {\r\n await this.device.reset();\r\n } catch (error) {\r\n /* Failed = doesn't support reset */\r\n }\r\n\r\n await this.device.selectConfiguration(1);\r\n await this.device.claimInterface(0);\r\n } catch (error) {\r\n if (rethrowErrors) {\r\n throw error;\r\n }\r\n }\r\n }",
"selectInputSourceBluetooth() {\n this._selectInputSource(\"i_bt\");\n }",
"checkClosed() {\n check(this.isClosed, \"Use Wire.close() to close the wire\");\n }",
"function startWireGame() {\n\t\tdecrement(time);\n\t\tvar colors = ['red', 'yellow', 'green', 'blue', 'black'];\n\n\t\tvar $wireSelect = $('.wireS');\n\t\tchangeMouse($wireSelect);\n\n\t\t// Random colors for top row\n\t\tcolors = shuffleArray(colors);\n\t\tfor (var i = 0; i < $wireSelect.length; i++) {\n\t\t\t$wireSelect.eq(i).css('background-color', colors[i]);\n\n\t\t}\n\n\t\tvar $wireSlot = $('.wireSlot');\n\t\tchangeMouse($wireSlot);\n\t\tvar $wirePlace = $('.wire');\n\n\t\t// Random colors for bottom row\n\t\tcolors = shuffleArray(colors);\n\t\tfor (var i = 0; i < $wirePlace.length; i++) {\n\t\t\t$wirePlace.eq(i).css('background-color', colors[i]);\n\n\t\t}\n\n\t\tvar wireSelected = null;\n\n\t\t//Countdown\n\n\t\t$wireSelect.on('click', function (event) {\n\t\t\twireSelected = $(this);\n\t\t\twireSelected.css('border', 'solid gold 4px');\n\t\t});\n\n\t\t$wireSlot.on('click', function (event) {\n\t\t\tif (wireSelected !== null) {\n\t\t\t\twireSelected.css('border', 'solid black 2px');\n\t\t\t\t$(this).css('background-color', wireSelected.css('background-color'));\n\t\t\t\tcheckWin($wirePlace, $wireSlot);\n\t\t\t}\n\n\t\t});\n\t}",
"selectInputSourceInetUsb() {\n this._selectInputSource(\"i_net_usb\");\n }",
"function syncValidity(realSelect) {\n // voodoo to go from the 'real' select to its select2 imitation input-field.\n const s2 = $(realSelect).data('select2').$selection;\n if (realSelect.checkValidity()) {\n s2.removeClass('select-2-otp-error');\n } else {\n s2.addClass('select-2-otp-error');\n }\n }",
"_getAVRInputSelection() {\n this._selectInputSource(\"i_request\");\n }",
"selectInputSourceAux4() {\n this._selectInputSource(\"i_aux4\");\n }",
"checkNetwork(network){}",
"function checkPortTypeMatch(selIndex,leftDevType, leftObjPath){\n\tvar conReturn = false;\n\tvar\tpRightObjPath = $('#deviceRight li').eq(selIndex).attr('data-name');\n\tvar devRightType = $('#deviceRight li').eq(selIndex).attr('portType');\n\tif (leftDevType.toLowerCase() == \"l2\"){\n\t\tconReturn = true;\n\t}\n\tif (leftDevType.toLowerCase() == \"l1\" && devRightType.toLowerCase() == \"l1\"){\n\t\tconReturn = checkPortSpeedIfMatch(leftObjPath,pRightObjPath)\t\n\t}\t\n\tif ((leftDevType.toLowerCase() == \"open\" && devRightType.toLowerCase() == \"l1\") ||(leftDevType.toLowerCase() == \"l1\" && devRightType.toLowerCase() == \"open\")) {\n\t\tconfirmation(\"Are you sure you want to connect \"+leftDevType+\" port to \"+devRightType+\"?\",Notification,\"conReturn = true;\");\n\t}\t\n\treturn conReturn;\n}",
"function validateSelection() {\n let length = false;\n let type = false;\n let local = false;\n let inst;\n //check length\n if (selection.length === 1) {\n length = true;\n }\n //check type\n if (selection[0].type === 'INSTANCE') {\n type = true;\n inst = selection[0];\n }\n //check if remote\n if (type) {\n if (inst.masterComponent.remote === false) {\n local = true;\n }\n }\n //put it all together\n if (length && type && local) {\n return true;\n }\n else {\n if (!length) {\n errorMsg = 'Please select a single instance';\n return false;\n }\n else if (!type) {\n errorMsg = 'Selection must be an instance.';\n return false;\n }\n else if (!local) {\n errorMsg = 'Instance is from a library. Please select a local component.';\n return false;\n }\n }\n}",
"function handleWMSelect(obj){\n\n // sure it's ghetto or whatever, but basically we just dispatch all of 'em from here\n switch (obj.id){\n case \"midiInput\":\n ipcRenderer.send('selectPort', {\n portId: obj.value.trim(),\n portType: 'input'\n });\n break;\n case \"midiOutput\":\n ipcRenderer.send('selectPort', {\n portId: obj.value.trim(),\n portType: 'output'\n });\n break;\n }\n}",
"scan_() {\n const fxElements = this.root_.querySelectorAll('[amp-fx]');\n iterateCursor(fxElements, fxElement => {\n if (this.seen_.includes(fxElement)) {\n return;\n }\n\n // Don't break for all components if only a subset are misconfigured.\n try {\n this.register_(fxElement);\n this.seen_.push(fxElement);\n } catch (e) {\n rethrowAsync(e);\n }\n });\n }",
"function focusMouseOnErrorElement(fieldname){\n\t\t\t\t//[ catchFirstError_element ] This would save after catching the first error element\n\t\t\t\tif( catchFirstError_element === undefined){\n\t\t\t\t\tcatchFirstError_element = fieldname;\n\t\t\t\t\t//We select form element by it's name attribute value\n\t\t\t\t\t$('[name=\"'+catchFirstError_element+'\"]').trigger('focus');\n\t\t\t\t}\n\t\t\t}",
"next_select(select) {\n const next = select.closest('div').next().find('select');\n return ((next.length > 0) && next) || false;\n }",
"[kMaybeBind]() {\n if (this.#state !== kSocketUnbound)\n return;\n this.#state = kSocketPending;\n this.#lookup(this.#address, QuicEndpoint.#afterLookup.bind(this));\n }",
"validateDmacMask() {\n let regex = /^[a-fA-F0-9]{4}\\.[a-fA-F0-9]{4}\\.[a-fA-F0-9]{4}$/;\n if (regex.test(this.state.dmacMask.replace(/^\\s+|\\s+$/g, \"\"))) {\n let mask = this.state.dmacMask.toString().replace(/^\\s+|\\s+$/g, \"\");\n let mask1 = mask.replace(/\\./g, \"\");\n let mask2 = mask1.replace(/^0+/, \"\");\n let mask3 = mask2.replace(/0+$/, \"\");\n if (mask3.length > 8){\n this.setState(\n {\n dmacMaxOctetError: true,\n },\n () => {\n return false;\n }\n );\n }\n if (mask3.length <= 8) return true;\n }\n else {\n this.setState(\n {\n dmacMaskError: true,\n },\n () => {\n return false;\n }\n );\n }\n }",
"selectInputSourceUsbIpod() {\n this._selectInputSource(\"i_usb_ipod\");\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
TODO: Implement the logic to check if the user is still supposed to be waiting (now < TTL for waitingRoomCookieTTL) | function isUserStillWaiting(request) {
return false; //Allow user to return the pool for selection.
} | [
"function C101_KinbakuClub_RopeGroup_WaitingForFriend() {\n\tif (C101_KinbakuClub_RopeGroup_FriendWaitCount == 0) C101_KinbakuClub_RopeGroup_FriendWaitCount = CurrentTime + 300000;\n\tC101_KinbakuClub_RopeGroup_FriendWaitCount++\n\tif (CurrentTime >= C101_KinbakuClub_RopeGroup_FriendWaitCount && !C101_KinbakuClub_RopeGroup_CassiVistied) {\n\t\tC101_KinbakuClub_RopeGroup_CurrentStage = 662;\n\t\tC101_KinbakuClub_RopeGroup_LoadCassi();\n\t\tC101_KinbakuClub_RopeGroup_CassiVistied = true;\n\t\tif (GameLogQuery(CurrentChapter, CurrentActor, \"MetCassi\")) {\n\t\t\tOverridenIntroText = GetText(\"CassiAppears\");\n\t\t} else OverridenIntroText = GetText(\"NewGirlAppears\");\n\t} else {\n\t\tCurrentTime = CurrentTime + 60000;\n\t\tif (CurrentTime >= C101_KinbakuClub_RopeGroup_FriendWaitCount) CurrentTime = CurrentTime + 60000;\n\t}\n}",
"_onCheckSessionTimer() {\n const { sessionId } = getProperties(this, 'sessionId');\n\n if (!sessionId) { return; }\n\n // debounce: do not run if destroyed\n if (this.isDestroyed) { return; }\n\n debounce(this, this._onCheckSessionTimer, ROOTCAUSE_SESSION_TIMER_INTERVAL);\n\n if (!sessionId) { return; }\n\n this._checkSession();\n }",
"hasRemainingUsers() {\n return this.remainingUsers !== 0\n }",
"function timeCheck(finishCallback, waitingCallback) {\n var d,\n h,\n m,\n s;\n condition = false;\n var interval = setInterval(function () {\n d = new Date();\n h = d.getHours();\n m = d.getMinutes();\n s = d.getSeconds();\n if (condition) {\n clearInterval(interval);\n finishCallback();\n } else {\n if (h === 23 & m >= 57 & s >= 13) {\n condition = true;\n } else {\n waitingCallback();\n }\n }\n }, 250);\n}",
"function checkUserNotfication(){\n clearInterval(getNotificationInterval);\n getNotificationInterval =\"\";\n\tgetUserNotificationSession();\n\tgetNotificationInterval = setInterval(function(){\n\t\tgetUserNotificationSession();\n\t},60000);\n}",
"static needPlayers() {\n\t\talert('There\\'s not enough players in the room');\n\t}",
"function _canPromote() {\n return (remainingSeconds <= 0);\n }",
"unlockMessage() {\n // if message is over a day old (10 seconds for testing), unlock it and allow deletion\n if(Date.now() - this.posted > 10000) {\n this.isLocked = false;\n }\n }",
"function CheckIdleTime() {\n _idleSecondsCounter++;\n var oPanel = document.getElementById(\"SecondsUntilExpire\");\n if (oPanel)\n oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + \"\";\n if (_idleSecondsCounter >= IDLE_TIMEOUT) {\n\t\tExt.getCmp('loginWindow').center();\n\t\t$(\"#loading\").fadeOut();\n\t\t$(\"#overlay\").fadeIn();\n\t\tExt.getCmp('loginWindow').show();\n\t\ttop.loginframe.document.getElementById(\"login_message\").style.display=\"block\";\n }\n}",
"function extendTTL(cond, by) {\n\t\t\t\tredis = openRedis();\n\t\t\t\tredis.TTL(\"session:\" + req.sess, function(err, reply) {\n\t\t\t\t\tif(!isNaN(parseInt(reply)) && parseInt(reply) < opts.expiry) {\n\t\t\t\t\t\tredis.expire(\"session:\" + req.sess, opts.expireExtend, function(err, reply) {\n\t\t\t\t\t\t\tredis.end();\n\t\t\t\t\t\t\tdebug(\"session:\" + req.sess + \" was \" + Number(reply)===0 ? \"not \" : \"\" +\n\t\t\t\t\t\t\t\t\"allowed to exist for another \" + opts.expireExtend + \" seconds.\");\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}",
"function findAvailableChallenges() {\n vm.availableChallenges = false;\n if (vm.currentUserIsOnCompetition && !vm.hasActiveChallenge) {\n var levelAbove = vm.currentUserPlayer.level > 1 ? vm.currentUserPlayer.level - 1 : null;\n _.forEach(vm.competition.players, function (player) {\n var waitingForPlayer = null;\n if (player.level === levelAbove && player.position !== 99 && player.class !== 'unavailable' && player.available !== false && !player.hold) {\n // Check if there is a waiting period for this player\n waitingForPlayer = _.find(vm.currentUserPlayer.waitingPeriods, { 'player': player._id });\n // If there is a waiting period for this user don't make them available\n if (waitingForPlayer && moment().isBefore(waitingForPlayer.expires)) {\n player.class = 'waiting';\n player.waitUntil = moment(waitingForPlayer.expires).format('MMM Do @ LT');\n } else {\n vm.availableChallenges = true;\n player.available = true;\n player.class = 'available';\n }\n }\n });\n }\n }",
"isFreshPeer (announceObj) {\n try {\n // Ignore announcements that do not have a broadcastedAt timestamp.\n if (!announceObj.data.broadcastedAt) return false\n\n // Ignore items that are older than 10 minutes.\n const now = new Date()\n const broadcastTime = new Date(announceObj.data.broadcastedAt)\n const tenMinutes = 60000 * 10\n const timeDiff = now.getTime() - broadcastTime.getTime()\n if (timeDiff > tenMinutes) return false\n\n return true\n } catch (err) {\n console.error('Error in stalePeer()')\n throw err\n }\n }",
"has_life_expired() {\n if ((this.lifetime !== null) && (this.age >= this.lifetime)) {\n return true;\n } else {\n return false;\n }\n }",
"function roomJoinResultListener (e) {\n // If there are already two people playing, wait 5 seconds, then\n // attempt to join the game again (hoping that someone has left)\n if (e.getStatus() == Status.ROOM_FULL) {\n hud.setStatus(\"Game full. Next join attempt in 5 seconds.\");\n joinTimer.start();\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}",
"TimeToLeave(key, callback) {\n client.ttl(key, (err, data) => {\n return callback(err, data);\n });\n }",
"function startActivityMonitor() {\n\tclearInterval(activityLoop);\n\tlastActive = Math.ceil((new Date()).getTime() / 1000); //unix time in seconds\n\tactivityLoop = setInterval(timerIncrement, 31000); // Check user active every 31 seconds \n\n}",
"function check_timer(req, res, next) {\n if (timerExpired) {\n complete(req, res);\n }else {\n next();\n }\n}",
"async function sync_meetings(){\n log(\"Beginning sync of active meeting rooms\");\n var fetched_rooms = (await active_meetings.once('value'));\n if(fetched_rooms.exists()){\n fetched_rooms = fetched_rooms.val();\n log(\"Found room:\" + fetched_rooms);\n for(var room_name in fetched_rooms){\n //Add rooms to fetched_rooms\n var room = fetched_rooms[room_name];\n \n var voice_channel = get_channel(room.voice);\n\n if(voice_channel == null){\n return;\n }\n\n meeting_rooms[room_name] = room;\n if(voice_channel.members.size == 0){\n meeting_rooms[room_name][\"timeout\"] = setTimeout(function(){\n delete_room(room_name);\n }, server.MEETING_TIMEOUT_TIME * 1000);\n var owner = get_member(room.owner_id);\n owner.send(\"Your meeting room \" + room_name + \" will delete in \" + server.MEETING_TIMEOUT_TIME + \" seconds unless the voice chat becomes active in this time period\");\n } \n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
determines if a cell contains a valid station name. | function isValidStation(s) {
return s.match(/^\s*\S+\s*$/)
} | [
"function checkName(str) {\n for (var i=0; i < trains.length; i++) {\n if (trains[i]===str) {\n return false;\n }\n }\n return true;\n}",
"function validName(input) {\n return input.length > 0\n }",
"function fn_CheckLoginName ( strLogin )\n\t{\n\t\tstrLogin = trimString( strLogin ) ;\n\n\t\tvar checkOK = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._@\";\n\t\tvar checkStr = strLogin ;\n\t\tvar allValid = true;\n\t\tfor (i = 0; i < checkStr.length; i++)\n\t\t{\n\t\t\tch = checkStr.charAt(i);\n\t\t\tfor (j = 0; j < checkOK.length; j++)\n\t\t\t if (ch == checkOK.charAt(j))\n\t\t\t\tbreak;\n\t\t\tif (j == checkOK.length)\n\t\t\t{\n\t\t\t allValid = false;\n\t\t\t break;\n\t\t\t}\n\t\t}\n\t\tif ( ! allValid )\n\t\t{\n\t\t\treturn (false);\n\t\t}\n\n\t\tif ( checkStr.charAt(0) == '-' || checkStr.charAt(0) == '.' || checkStr.charAt(0) == '_' )\n\t\t{\n\t\t\treturn (false);\n\t\t}\n\n\t\treturn (true);\n\t}",
"function isValidCell(cell) {\n var scell = cell.split(\" \");\n //console.log(scell);\n if (isNumericArray(scell)) {\n return !(scell.length !== 6); // return True if 6 values\n } else {\n return false;\n }\n }",
"isTickerValid(str) {\n str.trim();\n if (/^[a-zA-Z]+$/.test(str) && str.length <= 4) {\n return true;\n }\n return false;\n }",
"function hasValidNameField(manifest) {\n return misc_utils_1.isTruthyString(manifest[ManifestFieldNames.Name]);\n}",
"function isDialIdentifier (s)\n{\n var i;\n\n if (isEmpty(s))\n if (isDialIdentifier.arguments.length == 1) return defaultEmptyOK;\n else return (isDialIdentifier.arguments[1] == true);\n\n for (i = 0; i < s.length; i++) {\n var c = s.charAt(i);\n if ( !isDialDigitChar(c) && (c != \"w\") && (c != \"W\") ) return false;\n }\n\n return true;\n}",
"function customerHasValidLastName (cust) {\n return typeof cust === 'string' && cust !== '' && cust.length < 501;\n}",
"function isIdentifier (s) {\n \treturn /^[a-z]+$/.test(s);\n}",
"function LocationNameValidation(e) {\n\tvar ret\n\tvar keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;\n\tif (document.getElementById('locNameText').value.length == 0) {\n\t\tret = ((keyCode >= 65 && keyCode <= 90)\n\t\t\t\t|| (keyCode >= 97 && keyCode <= 122) || (specialKeys\n\t\t\t\t.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));\n\t} else if ((preLocVal == 32 || preLocVal == 46) && (keyCode == 32 || keyCode == 46)) {\n\t\tret = false;\n\t} else {\n\t\tret = ((keyCode == 32) || (keyCode == 46)\n\t\t\t\t|| (keyCode >= 65 && keyCode <= 90)\n\t\t\t\t|| (keyCode >= 97 && keyCode <= 122) || (keyCode >= 48 && keyCode <= 57)|| (specialKeys\n\t\t\t\t.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));\n\t\tpreLocVal = keyCode\n\n\t}\n\tdocument.getElementById(\"error\").style.display = ret ? \"none\" : \"inline\";\n\treturn ret;\n}",
"function nameValidation() {\n // Name validation\n const nameValue = name.value;\n const nameValidator = /[a-zA-z]+/.test(nameValue);\n\n return nameValidator;\n}",
"isRegisterName(str) {\n return this.architecture.hasRegisterName(str);\n }",
"function isLocalStation(stationIp, adviseLaunchInfo){\n\ttry {\n\t\tvar ipArr = stationIp.split(',');\n\t\t\n\t\tif (ipArr.indexOf(adviseLaunchInfo.localIP) > -1)\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t\t\n\t} catch(ex){\n\t\treturn false;\n\t}\n}",
"function checkLetterInWordTree(wordTreeNode, tileLetter, strWorkString, wordLen)\n{\n var isLetterPartOfWord = false;\n\n // Is the current letter present at the current location in the word tree?\n if ( wordTreeNode.hasOwnProperty( tileLetter ) )\n {\n // Append current tile letter to the working string\n strWorkString = strWorkString + tileLetter;\n\n // indicate success, letter at this location is part of a valid word\n isLetterPartOfWord = true;\n\n // Check to see if the current string of letters is the last letter which completes a valid word\n if ( wordTreeNode[ tileLetter ]['iw'] )\n addWordToFoundList(strWorkString, wordLen);\n }\n\n return (isLetterPartOfWord);\n}",
"function extPart_getIsIdentifier(groupName, partName)\n{\n var partType = extPart.getPartType(groupName, partName);\n return (!partType || partType == \"identifier\");\n}",
"isValid(string) {\n\t\tvar words = string.match(/\\w+/g);\n\t\tif (!words) {\n\t\t\treturn false;\n\t\t}\n\t\tfor (let w of words) {\n\t\t\tif (!this.isMember(w)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}",
"function isError(str){\n if(str.startsWith(\"Error: \")){\n return true;\n }\n return false;\n}",
"function invalid_char(val) {\n if (val.match('^[a-zA-z0-9_]+$') == null) {\n return true\n } else {\n return false\n }\n}",
"function isStringType(columnname, metadata){\n\t\n\t\tvar retVal = false;\n\t\tfor (var i = 0; i < metadata.length; i++) {\n\t\t\tvar element = metadata[i];\n\t\t\tif(element.column_name\t == columnname){\n\t\t\t\tretVal = element.validator==\"org.apache.cassandra.db.marshal.UTF8Type\"?true:false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn retVal;\n\t\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
apply a width value, possibly adjusting the height value along with it, depending on the size/options chosen This is triggered by user editing 'input_width' and may or may not end up updating 'height' and 'width' depending on whether input_height and input_width seem acceptable. This is also called manually with the existing width value when changing major options in order to use this logic to select a nice default height. | function _applyWidth(width) {
if(self._applying_dimensions) return;
if(self.layout() == "video") {
// for video, a given width implies a specific height, so just set it and done
if(width < VIDEO_MIN_WIDTH || width > VIDEO_MAX_WIDTH) {
// width invalid, don't apply it
return;
}
var height = _videoHeight(width);
self.height(height);
self.width(width);
self._applying_dimensions = true;
self.input_height(height);
self._applying_dimensions = false;
return;
}
var sizekey = self.sizekey();
var defaults = DEFAULT_SIZES[sizekey];
if(width < defaults.min_width || width > defaults.max_width) {
return;
}
// extra special min width for smallart players
if(self.size() == "large" && self.artwork_option() != "large" && width < STANDARD_SMALLART_WIDTH_MIN) {
return;
}
// passed the check, so use this width in the embed
self.width(width);
if ( width == "100%" ) {
// if the width is set to "100%", continue as if the width
// was set to defaults.min_width, since you can't do a height
// calculation with the string "100%"
width = defaults.min_width;
}
// calculate range of allowable heights
var range = self.heightRange(width);
var inp_height = self.input_height();
// by default, update input_height to the closest value in its allowed range
var new_height = pin(inp_height, range);
// however, if we are showing a tracklist, default the height to
// show exactly DEFAULT_NUM_LIST_ITEMS list items by default (unless there are fewer tracks
// than that, in which case, default to the number of tracks).
// Calculate this by knowing that range.min shows MIN_LIST_ITEMS, so add
// enough height for an additional 1 or 2 if appropriate
if(self.size() == "large" && self.layout() != "minimal" && self.show_tracklist()) {
var nitems = Math.min(DEFAULT_NUM_LIST_ITEMS, opts.num_tracks || 0);
if(nitems > MIN_LIST_ITEMS) {
Log.debug("showing " + nitems + " tracks by default");
new_height = range.min + LIST_ITEM_HEIGHT * (nitems - MIN_LIST_ITEMS);
}
}
if(new_height != inp_height) {
self.height(new_height);
self._applying_dimensions = true;
self.input_height(new_height);
self._applying_dimensions = false;
}
} | [
"set requestedWidth(value) {}",
"set width(aValue) {\n this._logService.debug(\"gsDiggThumbnailDTO.width[set]\");\n this._width = aValue;\n }",
"onWidthChange(width) {\n // Set new breakpoint\n var newState = {width: width};\n newState.breakpoint = this.getBreakpointFromWidth(newState.width);\n newState.cols = this.getColsFromBreakpoint(newState.breakpoint);\n \n if (newState.cols !== this.state.cols) {\n // Store the current layout\n newState.layouts = this.state.layouts;\n newState.layouts[this.state.breakpoint] = JSON.parse(JSON.stringify(this.state.layout));\n\n // Find or generate the next layout\n newState.layout = this.state.layouts[newState.breakpoint];\n if (!newState.layout) {\n newState.layout = utils.compact(utils.correctBounds(this.state.layout, {cols: newState.cols}));\n }\n }\n this.setState(newState);\n }",
"set originalWidth(aValue) {\n this._logService.debug(\"gsDiggThumbnailDTO.originalWidth[set]\");\n this._originalWidth = aValue;\n }",
"function _applyHeight(height) {\n if(self._applying_dimensions) return;\n\n var range = self.widthRange(height);\n var inp_width = self.input_width();\n var new_width = pin(inp_width, range);\n\n var hrange = self.heightRange(new_width);\n if(pin(height, hrange) == height) {\n self.height(height);\n self.width(new_width);\n\n if(new_width != inp_width) {\n self._applying_dimensions = true;\n self.input_width(new_width);\n self._applying_dimensions = false;\n }\n }\n }",
"set requestedHeight(value) {}",
"function widthHeightInputValidation(inputWH){\n inputWH.on('keyup', function(){\n if((inputWH.val() > maxWidthHeight) || (inputWH.val() < minWidthHeight) || (!($.isNumeric(inputWH.val())))){\n inputWH.css({\"border\":\"1px solid red\"});\n }else{\n inputWH.css({\"border\":\"none\"});\n }\n });\n }",
"set width( w ) {\n if ( !this.el ) return;\n\n if ( w === 'default' ) {\n this.parent.style.width = this.opts.cols * this.charWidth + 'px';\n return;\n }\n\n this.parent.style.width = w + 'px';\n }",
"function calculateNewSize(query, callback){\n\n\t//Raw param\n\tvar widthOrHeight = query.size;\n\t// Set to true if user passed in width by height\n\tvar nSizeHandW = false;\n\t// Set to default raw query\n\tvar nWidth = nHeight = widthOrHeight;\n\t//Split by 'x' (times char) and seperate the size\n\tif(widthOrHeight.indexOf(\"x\") != -1){\n\t\t var whArr = widthOrHeight.split(\"x\");\n\t\t nWidth = whArr[0];\n\t\t nHeight = whArr[1];\n\t\t nSizeHandW = true;\n\t}\n\t// Empty object to populate\n\tvar imageSize = {};\n\n\teasyimg.info(getImagePath(query.source)).then(function(stdout){\n\t\t//Get current size\n\t\tvar cWidth, cHeight;\n\t\tconsole.log(stdout);\n\t\tcWidth = stdout.width;\n\t\tcHeight = stdout.height;\n\t\tif(cWidth === undefined || cHeight === undefined){\n\t\t\timageSize =\t{ width : roundSize(nWidth) };\n\t\t}else if(nSizeHandW){\n\t\t\t// If new height and width make sure they are smaller than the current image.\n\t\t\tnWidth = Math.min(nWidth,cWidth);\n\t\t\tnHeight = Math.min(nHeight,cHeight);\n\t\t\t//Set new file path\n\t\t\timageSize =\t{\n\t\t\t\theight : roundSize(nHeight),\n\t\t\t \twidth : roundSize(nWidth)\n\t\t\t };\n\t\t}else{\n\t\t\t// resize to to the smallest size\n\t\t\tif(cWidth >= cHeight){\n\t\t\t\timageSize =\t{ width : roundSize(Math.min(nWidth,cWidth)) };\n\t\t\t}else{\n\t\t\t\tvar ratio = cHeight/cWidth;\n\t\t\t\timageSize = { width : roundSize(ratio * nHeight) };\n\t\t\t}\n\t\t}\n\t\tcallback(null, imageSize);\n\t}).catch((err)=>{\n\t\tconsole.log(\"error while getting info\", err);\n\t\tcallback(false, null);\n\t\treturn;\n\t});\n}",
"function setSize(target, param){ \n\t\tvar opts = $.data(target, 'slider').options; \n\t\tvar slider = $.data(target, 'slider').slider; \n\t\t \n\t\tif (param){ \n\t\t\tif (param.width) opts.width = param.width; \n\t\t\tif (param.height) opts.height = param.height; \n\t\t} \n\t\tif (opts.mode == 'h'){ \n\t\t\tslider.css('height', ''); \n\t\t\tslider.children('div').css('height', ''); \n\t\t\tif (!isNaN(opts.width)){ \n\t\t\t\tslider.width(opts.width); \n\t\t\t} \n\t\t} else { \n\t\t\tslider.css('width', ''); \n\t\t\tslider.children('div').css('width', ''); \n\t\t\tif (!isNaN(opts.height)){ \n\t\t\t\tslider.height(opts.height); \n\t\t\t\tslider.find('div.slider-rule').height(opts.height); \n\t\t\t\tslider.find('div.slider-rulelabel').height(opts.height); \n\t\t\t\tslider.find('div.slider-inner')._outerHeight(opts.height); \n\t\t\t} \n\t\t} \n\t\tinitValue(target); \n\t}",
"function airsliderSetSlidesEditingAreaSizes() {\n var width = parseInt($('.air-admin #air-slider-settings .air-slider-settings-list #air-slider-startWidth').val());\n var height = parseInt($('.air-admin #air-slider-settings .air-slider-settings-list #air-slider-startHeight').val());\n\n $('.air-admin #air-slides .air-slide .air-slide-editing-area').css({\n 'width' : width,\n 'height' : height,\n });\n\n// $('.air-admin').css({\n// 'width' : width,\n// });\n }",
"configure(width, height)\n {\n // use the width passed by the user\n // but check the height, each team should have at least 200 px of space\n this.width = width\n let len = Object.keys(this.teams).length;\n if (len * 200 > height)\n {\n this.height = len * 200 + 100;\n }\n else\n {\n this.height = height;\n }\n\n this.app.renderer.autoResize = true;\n this.app.renderer.resize(this.width, this.height);\n }",
"function resizeActivePictureAndScaleStyles(newWidth)\n{\n\tvar idImgS = charIDToTypeID( \"ImgS\" );\n\tvar desc2 = new ActionDescriptor();\n\tvar idWdth = charIDToTypeID( \"Wdth\" );\n\tvar idPxl = charIDToTypeID( \"#Pxl\" );\n\tdesc2.putUnitDouble( idWdth, idPxl, newWidth);\n\tvar idscaleStyles = stringIDToTypeID( \"scaleStyles\" );\n\tdesc2.putBoolean( idscaleStyles, true );\n\tvar idCnsP = charIDToTypeID( \"CnsP\" );\n\tdesc2.putBoolean( idCnsP, true );\n\tvar idIntr = charIDToTypeID( \"Intr\" );\n\tvar idIntp = charIDToTypeID( \"Intp\" );\n\tvar idBcbc = charIDToTypeID( \"Bcbc\" );\n\tdesc2.putEnumerated( idIntr, idIntp, idBcbc );\n\texecuteAction( idImgS, desc2, DialogModes.NO );\n}",
"function f_refectSpEditWidthHeight(){\n var w = $('#sp-taginfo-width');\n var h = $('#sp-taginfo-height');\n // set .spEdit css\n fdoc.find('.spEdit').css('width',w.val()+'px').css('height',h.val()+'px');\n }",
"maxWidth(els, val) {\r\n return this._updateAttr(els, val, 'data-gs-max-width', 'maxWidth');\r\n }",
"function scaleToFit(x, scaleW, scaleH, type) {\n\tif (type == \"h\") {\n\t\t// x : res = scaleW : scaleH\n\t\treturn Math.round((x * scaleH) / scaleW)\n\t} else {\n\t\t// res : x = scaleW : scaleH\n\t\treturn Math.round((x * scaleW) / scaleH)\n\t}\n}",
"changeSize() {\n // Calculate the distance between the mouse and the center of the shape\n this.distanceFromCenterX = mouseX - this.x;\n this.distanceFromCenterY = mouseY - this.y;\n // Change width and height according to the mouse position\n this.width = 2 * (this.distanceFromCenterX);\n this.height = 2 * (this.distanceFromCenterY);\n }",
"updateWidth() {\n if (this.setupComplete) {\n let width = this.headerData.getWidth();\n this.width = '' + width;\n this.widthVal = width;\n $(`#rbro_el_table${this.id}`).css('width', (this.widthVal + 1) + 'px');\n }\n }",
"function applyTemplateProperty(targetHTMLBlock_mainWrapper, targetHTMLBlock, dimensionSaver)\n { \n var newWidth = $('#t_width').val();//+' !important';\n var newHeight = $('#t_height').val(); //+' !important'; alert(newWidth);\n $(targetHTMLBlock_mainWrapper).css({'width':newWidth});\n\n $(targetHTMLBlock).css({'width':newWidth ,\n 'height': newHeight});\n $(dimensionSaver).val(newWidth+'-'+newHeight);\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if saving to redis is enabled and performs save if it is | function saveToRedis(redisKey, redisValue, isEnabled) {
if (typeof isEnabled === "undefined") {
isEnabled = config.redis.enableRedisInsert;
}
if (isEnabled) {
redisClient.setAsync(redisKey, redisValue);
}
} | [
"function syncRedis() {\n // if memStore has changed...\n if(JSON.stringify(memCache) !== JSON.stringify(memStore)) {\n return when.promise((resolve, reject) => {\n var serializedStore = JSON.stringify(memStore);\n redis.set(name, serializedStore, err => {\n if(err) {\n reject(err);\n } else {\n resolve(true);\n }\n });\n })\n .delay(syncInterval)\n .catch(err => {\n console.log(err.stack);\n return when(true);\n })\n .finally(() => {\n memCache = _.cloneDeep(memStore);\n if(active) syncRedis(memStore);\n return when(true);\n });\n }\n\n // else memStore has not changed...\n else {\n return when(true)\n .delay(syncInterval)\n .then(() => {\n if(active) syncRedis(memStore);\n return when(true);\n });\n }\n }",
"async doSaveCacheTriggers() {\n\t\tlet theUnsaved = this.triggerCache.getUnSaved({});\n\t\tif (!$.isEmptyObject(theUnsaved)) {\n\t\t\tlet doSaves = {'options':{'updates':[], 'keys':[]}, 'rules':{'updates':[], 'keys':[]}, 'data':{'updates':[], 'keys':[]}};\n\t\t\tfor (const dbId of Object.keys(theUnsaved)) {\n\t\t\t\tfor (const theName of Object.keys(theUnsaved[dbId])) {\n\t\t\t\t\tdoSaves[theName].updates.push(theUnsaved[dbId][theName].update); doSaves[theName].keys.push(theUnsaved[dbId][theName].key);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const storeName of Object.keys(doSaves)) {\n\t\t\t\tlet theName = (storeName === 'data') ? _ : storeName, theData = doSaves[storeName].updates, theKey = doSaves[storeName].keys;\n\t\t\t\tif (theData.length > 0) await this.doAddToDB('searching', theName, theData, theKey);\n\t\t\t}\n\t\t}\n\t}",
"function MEX_Save() {\n if (mod_MEX_dict.is_permit_admin){\n MEXQ_Save();\n }\n } // MEX_Save",
"save() {\n if (this.properties.saveCallback) {\n this.properties.saveCallback();\n } else if (this.properties.localStorageReportKey) {\n if ('localStorage' in window && window['localStorage'] !== null) {\n try {\n let report = this.getReport();\n // console.log(JSON.stringify(report));\n window.localStorage.setItem(this.properties.localStorageReportKey, JSON.stringify(report));\n this.modified = false;\n } catch (e) {}\n }\n }\n this.updateMenuButtons();\n }",
"async doSaveCacheHistory() {\n\t\tlet theUnsaved = this.historyCache.getUnSaved();\n\t\tif (!$.isEmptyObject(theUnsaved)) { await this.doAddToDB('searching', 'history', Object.values(theUnsaved)); }\n\t}",
"@action\n async save() {\n await this.rdfaCommunicator.persist();\n this.owner.lookup(SAVE_RESET_KEY).handleClose(this.args.info, null);\n }",
"function saveChanges() {\n let outcome = true;\n let data = JSON.stringify(itemsJsonObject, null, 2);\n fs.writeFile('items.json', data, function(err){\n if(err) outcome = false;\n });\n return outcome;\n}",
"saveStatus() {\n let componentName = this.get('componentName');\n if (!isPresent(componentName)) {\n return;\n }\n\n let userSettings = this.get('userSettingsService');\n let settingName = this.get('settingName');\n let currentStatus = userSettings.getTogglerStatus(componentName, settingName);\n let expanded = this.get('expanded');\n\n if (expanded !== currentStatus) {\n userSettings.setTogglerStatus(componentName, settingName, expanded);\n }\n }",
"saveGameConfig() {\n this.store.set('gameConfig', this.gameConfig);\n }",
"function updateIsEnabled() {\n browserAPI.api.storage.local.get({ isEnabled: true }, (data) => {\n isEnabled = data.isEnabled;\n });\n }",
"function saveNewSettings(settings, f=null){\n\tfor(let key of Object.keys(settings)){\n\t\tlet obj = {[key]: settings[key]};\n\t\tchrome.storage.sync.set(obj, function(e){console.log(e);});\n\t}\n\tif(f) f();\n}",
"loadSave(saveData) {\n // Note we run update active entry first to avoid issues of current active entry being undefined after loading save\n this.updateActiveEntry(0, () => {\n this.setState({ scenarioData: saveData.scenarioData, colorData: saveData.colorData, pluginData: saveData.pluginData }, () => {\n this.initUndefinedPluginData(() => this.updateActiveEntry(0));\n });\n })\n\n // Running plugin methods\n this.runPluginFunc(\"onLoadSave\", [saveData]);\n }",
"function saveSettings(){\n localStorage[\"pweGameServerStatus\"] = gameselection;\n //console.log('saved: ' + gameselection);\n}",
"isPersistent ()\n\t{\n\t\treturn tryPersistWithoutPromtingUser ();\n\t}",
"function saveSettings() {\n // Update the sources variable.\n $('.js-social-media-source', modal).each(function () {\n var source = $(this).val();\n\n if (sources.hasOwnProperty(source)) {\n sources[source] = $(this).is(':checked');\n }\n });\n\n // Save settings in cookie.\n if (Drupal.eu_cookie_compliance.hasAgreed()) {\n cookieSaveSettings();\n }\n\n // Apply new settings.\n $('.js-social-media-wrapper').each(function () {\n applySettings($(this));\n });\n }",
"persistStore () {\n const { driver } = this.options;\n\n this.prevStore = JSON.parse(driver.getItem(this.key)) || {};\n driver.setItem(this.key, JSON.stringify(this.store));\n\n this.notifySubscribers();\n this.notifyListeners();\n }",
"async save() {\n // Use replace instead of has been fully updated in any way\n if (this.__fullUpdate) {\n return await this.replace();\n }\n\n // Ensure model is registered before saving model data\n assert.instanceOf(this.constructor.__db, DbApi, 'Model must be registered.');\n\n // Call internal DB API to save changes to this Model instance\n const id = await this.constructor.__db.save(this, this.__updates, this.__id);\n\n // Set ID if ID returned\n if (id != null) {\n this.__id = id;\n }\n\n // Reset internally stored updates\n this.__updates = new Set();\n this.__fullUpdate = false;\n }",
"function save() {\n\twriteFile(config, CONFIG_NAME);\n\tglobal.store.dispatch({\n\t\ttype: StateActions.UPDATE_CONFIGURATION,\n\t\tpayload: {\n\t\t\t...config\n\t\t}\n\t})\n}",
"save(data) {\r\n console.log('MigratableLocalStorage.save', data);\r\n data = this.migrate(data);\r\n localStorage.setItem(this.key, JSON.stringify(data));\r\n return data;\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Allows you to add an audit trail object and audit trail content associated with Kaltura object. | static add(auditTrail){
let kparams = {};
kparams.auditTrail = auditTrail;
return new kaltura.RequestBuilder('audit_audittrail', 'add', kparams);
} | [
"static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('audit_audittrail', 'get', kparams);\n\t}",
"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}",
"static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('audit_audittrail', 'list', kparams);\n\t}",
"function newObject() {\r\n let journalObject = {\r\n // dateObjectProperty: creationDate,\r\n date: creationDate,\r\n // confidenceObjectProperty: confidenceLevel,\r\n confidence: confidenceLevel,\r\n // journalObjectProperty: journalEnt\r\n journal: journalEnt,\r\n // makeObject() {\r\n // return journalObjectArray.push(journalObject);\r\n // }\r\n }\r\n // return journalObjectArray.push(journalObject);\r\n return journalEntries.push(journalObject);\r\n}",
"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}",
"static add(dataEntry){\n\t\tlet kparams = {};\n\t\tkparams.dataEntry = dataEntry;\n\t\treturn new kaltura.RequestBuilder('data', 'add', kparams);\n\t}",
"function extendWithAndListen(name, object) {\n var oldObj = this[name];\n\n //if it already exists under the same structure, don't readd, do it only when we have a different object structure\n if (oldObj != undefined && angular.equals(Object.keys(oldObj), Object.keys(object)))\n return;\n\n this[name] = {};\n var obj = object[name];\n \n angular.extend(this[name], obj);\n\n console.log(\"Watching child object, \" + name);\n\n $scope = this;\n\n //deregister listener\n if ($scope.objectWatchers[name] != undefined && $scope.objectWatchers[name].constructor == Function)\n $scope.objectWatchers[name]();\n\n //watch a whole object\n var listener = this.$watch(name, function (newval, oldval) {\n if (newval == oldval || newval == undefined || oldval == undefined || angular.equals(newval, oldval))\n return;\n\n console.log(\"Child object changed... \");\n\n doPageParametersPost($scope);\n }, true);\n\n $scope.objectWatchers[name] = listener;\n \n if ($scope.httpPostParameters.indexOf(name) == -1)\n $scope.httpPostParameters.push(name);\n}",
"static addFromUploadedFile(entry, uploadTokenId, type = null){\n\t\tlet kparams = {};\n\t\tkparams.entry = entry;\n\t\tkparams.uploadTokenId = uploadTokenId;\n\t\tkparams.type = type;\n\t\treturn new kaltura.RequestBuilder('baseentry', 'addFromUploadedFile', kparams);\n\t}",
"static add(entry){\n\t\tlet kparams = {};\n\t\tkparams.entry = entry;\n\t\treturn new kaltura.RequestBuilder('externalmedia_externalmedia', 'add', kparams);\n\t}",
"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 addEntry(events, didITurnIntoASquirrel){\n journal.push({\n events: events,\n squirrel: didITurnIntoASquirrel\n })\n}",
"function logAndWrite(entry){\n console.log(entry);\n writeHistoryEntry(entry);\n}",
"function addRisk(event) {\n // Capture which category to add criteria too\n var categoryId = parseInt($(event.currentTarget).attr('data-id'));\n console.log(\"categoryId: \" + categoryId);\n // Add criteria to data model\n console.log('category name: ' + projectManager.getCategory(0));\n projectManager.addRiskTo(projectManager.getCategory(categoryId), '',0);\n // Update interface\n update();\n}",
"addRecord(record) {\n let _recordType = t.object();\n\n t.param('record', _recordType).assert(record);\n\n const { handlers, processors } = this.getHandlersAndProcessors(record.level);\n\n if (handlers.length === 0) {\n if (record.level > levels.ERROR) {\n // eslint-disable-next-line no-console\n console.log('[nightingale] no logger for > error level.', {\n key: record.key,\n message: record.message\n });\n }\n return;\n }\n\n if (processors) {\n processors.forEach(process => process(record, record.context));\n }\n\n handlers.some(handler => handler.handle(record) === false);\n }",
"function addExistingContentToVenerability(vulnerabilityId) {\n newNotes.forEach(function (note) {\n Meteor.call('addVulnerabilityNote', projectId, vulnerabilityId, note.title, note.content);\n });\n newHostList.forEach(function (host) {\n Meteor.call('addHostToVulnerability', projectId, vulnerabilityId, host.string_addr, host.port, host.protocol);\n });\n newCVEs.forEach(function (cve) {\n Meteor.call('addCve', projectId, vulnerabilityId, cve);\n });\n removeVulnerabilities();\n }",
"addCard(obj) {\n let card = new RenderableCard(obj, this, client);\n app.stage.table.addChild(card.container);\n this.interactiveObjects.set(obj.id, card);\n }",
"function addFields(object, fields, successFn, errorFn) {\n var realm = getRealmController();\n\n realm.addFields(\n object\n , fields\n , function(description) {\n successFn();\n }\n , function(error) {\n errorFn(error);\n }\n );\n}",
"static add(metadataProfileId, objectType, objectId, xmlData){\n\t\tlet kparams = {};\n\t\tkparams.metadataProfileId = metadataProfileId;\n\t\tkparams.objectType = objectType;\n\t\tkparams.objectId = objectId;\n\t\tkparams.xmlData = xmlData;\n\t\treturn new kaltura.RequestBuilder('metadata_metadata', 'add', kparams);\n\t}",
"function getAuditLogEntry(params, cb) {\n params.resourcePath = config.addURIParams(constants.FORMS_BASE_PATH + \"/data_sources/audit_logs/:id\", params);\n params.method = \"GET\";\n params.data = {};\n\n mbaasRequest.admin(params, cb);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get all notes for a lesson: returns [note, ...] | static async getAll(lessonId) {
const result = await db.query(
`SELECT * FROM notes WHERE lesson_id = $1`, [lessonId]);
if (result.rows.length === 0) {
throw new ExpressError(`No notes`, 404);
};
return result.rows.map(n => new Note(n.id, n.lesson_id, n.note));
} | [
"async getAllLessons() {\n const lessonCollection = await lessons();\n const lessonList = await lessonCollection.find({}).toArray();\n return lessonList;\n }",
"async getNotes() {\n\t\ttry {\n\t\t\tconst notes = await readFileAsync(\"db/db.json\", \"utf8\");\n\t\t\treturn JSON.parse(notes);\n\t\t} catch (err) {\n\t\t\tthrow err;\n\t\t}\n\t}",
"function getNoteByID(id) {\n let db = note.notes\n for (let i = 0; i < db.length; i++) {\n let nte = db[i]\n if (nte._id == id) {\n return nte\n }\n }\n}",
"function getNotes(req,res,next){\n Note.find()\n .then(notes=>{\n let head;\n let i = notes.length-1;\n let temp = [];\n let j = -1;\n while(i>=0){ \n let note = notes[i];\n\n let next;\n if(i!==notes.length-1){\n next = temp[j];\n } else {\n next = null;\n }\n let tempNote = {\n note: note.note,\n image: note.image,\n mScore: 1,\n correct: 0,\n incorrect: 0,\n next: next\n };\n temp.push(tempNote); //[note.next = null, note.next = ]\n j++;\n i--;\n }\n head = temp[j];\n req.head = head;\n next();\n });\n}",
"async function getNotes(){\n try{\n let arr=[];\n let value=await AsyncStorage.getItem('noteList');\n JSON.parse(value).map((n)=>{\n if(n.category===route.params.name){\n arr.push(n);}\n });\n if(arr.length!==notes.length){\n setNotes(arr);\n }\n }\n catch(error){\n console.log(error);\n }\n }",
"function getAllTextNotes(){\n\tvar count = 0;\n\ttext_noteRef.once(\"value\")\n\t .then(function(snapshot) {\n\t\t snapshot.forEach(function(childSnapshot) {\n\t\t \tcount += 1;\n\t\t var eachNote = childSnapshot.val();\n\t\t showTextNote(childSnapshot.key, eachNote.note);\n\t\t });\n\t });\n}",
"getJournals() {\n console.log(\"fetching journals\")\n API.getJournalEntries().then(parsedJournals => {\n displayJournals(parsedJournals);\n })\n }",
"async findAll() {\n return await Tutorial.findAll({\n include: [\"comments\"],\n }).then((tutorials) => {\n return tutorials;\n });\n }",
"function allNotesSortedByChanged(): Array<TNote> {\n const projectNotes = DataStore.projectNotes.slice()\n const calendarNotes = DataStore.calendarNotes.slice()\n const allNotes = projectNotes.concat(calendarNotes)\n const allNotesSortedByDate = allNotes.sort(\n (first, second) => second.changedDate - first.changedDate,\n ) // most recent first\n return allNotesSortedByDate\n}",
"getNote(index) {\r\n return this.notes[index % (this.notes.length - 1)];\r\n }",
"function assignNotes() {\n// console.log($scope.notes);\n ng.forEach($scope.topics, function (topic) {\n topic.note = getNoteFor($scope.notes, topic);\n });\n }",
"async index () {\n const lectures = await Lecture.all();\n return lectures;\n }",
"function loadNotes(hash){\n\n console.log(\"Retrieving the current library...\");\n chrome.storage.local.get({'library': []}, function(lib){\n raw_notes = lib.library;\n\n /* If the user has no notes, create a default new one and open it for them */\n if (raw_notes.length == 0) {\n createNote(\"Welcome to Notility!\", HTMLDocumentation, \"\");\n openNote(-1);\n return;\n }\n\n renderNotes();\n /* If the notes are being loaded from a hash search, filter the appropriate notes */\n if (hash) {\n chooseFilter(hash);\n document.getElementById(\"searcher\").value = hash;\n }\n\n /* Open a note for editing */\n chrome.storage.local.get({'activeNote':-1},function(activeID){\n openNote(activeID.activeNote);\n changeNoteHighlight(activeID.activeNote);\n });\n\n });\n \n}",
"function get_notes() {\n const numOfNotes = document.getElementById('todo-list').childNodes.length\n document.getElementById('stats').innerHTML = ` <p><strong>Num. of notes: </strong>${numOfNotes}</p>`\n}",
"loadNotesFromDB (context) {\n return db.notes.orderBy('dateModified').reverse().toArray().then((notes) => {\n console.log(`${notes.length} notes loaded from db`)\n return context.commit({\n type: 'setNotes',\n options: notes\n })\n })\n }",
"async function getLyrics(array) {\n let allRequests = [];\n array.forEach((trackEntry) => {\n allRequests.push(\n axios(\n `${baseURL}${lyricsSearch}track_id=${trackEntry.trackId}&${apiKey}`\n ).then((response) => {\n return {\n artist: joinedArtistNameForFileName,\n trackName: trackEntry.trackName,\n trackId: trackEntry.trackId,\n lyrics: response.data.message.body.lyrics.lyrics_body,\n };\n })\n );\n });\n let lyricsArray = Promise.all(allRequests);\n return lyricsArray;\n}",
"async getList() {\n const data = await this.getData();\n return data.map(tour => {\n return {\n title: tour.title,\n shortname: tour.shortname,\n summary: tour.summary,\n card: tour.card\n };\n });\n }",
"function loadAllLessons(){\n\tconsole.log(\"========Loading All Lessons==========\");\n\n\t// Query the database for all the lessons \n\tAjax(\"../Lux/Assets/query.php\", {query:{type:\"lesson\"}}, \n\tfunction(data){\n\t\tvar obj = data[1];\n\t\t// loop all the lessons\n\t\tif(obj.length != 0){\n\t\t\tfor(var key in obj){\n\t\t\t\tappendLesson(obj[key], key, true);\n\t\t\t}\n\t\t}\n\t\taddNewLesson();\n\t});\n}",
"async function populateNotes(videoId) {\n\n\tif (areNotesAvailable(videoId)) {\n\t\tvar response = await getVideoNotes(videoId);\n\t\tresponse.json().then((data) => {\n\t\t\tif (!data.error) {\n\t\t\t\t// console.log(data);\n\t\t\t\tdata.note.note_content.sort(noteCompareByTime);\n\t\t\t\tfor(var i = 0; i < data.note.note_content.length; i++) {\n\t\t\t\t\t// console.log(data.note.note_content[i]);\n\t\t\t\t\tappendNewNote(data.note.note_content[i].note_text);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get the minimum distance vertex | getMinVertex() {
let minVertex = -1;
for (let i = 0; i < this.graph.length; i++) {
if (
!this.visited[i] &&
(minVertex === -1 || this.dist[i] < this.dist[minVertex])
) {
minVertex = i;
}
}
return minVertex;
} | [
"function findMinDist() {\n let smallestV;\n let smallestDist = Number.MAX_VALUE;\n\n for (let v in Q) {\n v = +v; // Convert to int\n if (dist[v] <= smallestDist) {\n smallestDist = dist[v];\n smallestV = v;\n }\n }\n\n return smallestV;\n }",
"selectMinDFromVS(){\n var minVex = null;\n\n for (var i in this.VS){\n if (minVex == null){\n minVex = i;\n }\n \n else{\n if (typeof this.D[i] != \"number\") {\n this.D[i] = parseInt(this.D[i]);\n }\n if (typeof this.D[minVex] != \"number\") {\n this.D[minVex] = parseInt(this.D[minVex]);\n }\n if (this.D[i] < this.D[minVex]) {\n minVex = i;\n }\n }\n }\n return minVex;\n\n // MINE GETMIN() \n // var min = undefined;\n\n // for (var i in this.vid) {\n // if (min == undefined) {\n // min = i;\n // }\n // else {\n // if(Number(this.D[i]) != NaN) {\n // this.D[i] = Number(this.D[i])\n // }\n // if(Number(this.D[min]) != NaN) {\n // this.D[min] = Number(this.D[min])\n // }\n // if (this.D[i] < this.D[min]) {\n // min = i;\n // }\n // }\n // }\n // // console.log(min)\n // return min;\n }",
"function maxDijkstra(adjmat, weight, start) {\n var nvertices = adjmat.length;\n var intree = new Array(nvertices);\n var distance = new Array(nvertices);\n var v;\n\n for(var i = 0; i < nvertices; i++){\n intree[i] = false;\n distance[i] = MININT;\n }\n\n distance[start] = weight[start];\n var u; // Candidate vertex\n for(var c = 0; c <= nvertices; c++){\n u = maxDistance(distance, intree);\n console.log(\"u = \" + u);\n intree[u] = true;\n\n writeArray(distance);\n for (var v = 0; v < nvertices; v++){\n //If\n //1. vertex v is not in the SP tree yet\n //2. there is an edge between u and v\n //3. distance of u is not MININT\n //4. distance of v is less than the distance of u + weight of edge uv\n if (!intree[v] && \n adjmat[u][v] && \n distance[u] != MININT && \n distance[v] < distance[u] + weight[v]){\n // Here we are using vertex weight instead of edge weight\n distance[v] = distance[u] + weight[v];\n }\n }\n }\n\n return distance;\n}",
"min() {\n const values = this.$checkAndCleanValues(this.values, \"min\");\n let smallestValue = values[0];\n for (let i = 0; i < values.length; i++) {\n smallestValue = smallestValue < values[i] ? smallestValue : values[i];\n }\n return smallestValue;\n }",
"findMinimumSpanningTree(debug = true) {\n let currentVertexIndex = 0,\n result = [];\n while (this.nTree < this.currentVertices - 1) {\n debug &&\n console.log(\n `currentVertexIndex is : ${currentVertexIndex}, this is ${this.vertexList[\n currentVertexIndex\n ].getData()}`\n );\n this.vertexList[currentVertexIndex].inTree = true;\n this.nTree++;\n\n for (let j = 0; j < this.currentVertices; j++) {\n if (j === currentVertexIndex || this.vertexList[j].inTree) {\n // debug &&\n // console.log(`vertex is already in Tree : `, this.vertexList[j]);\n continue;\n }\n let distance = this.adjacencyMatrix[currentVertexIndex][j];\n if (distance === this.maxLimit) {\n // debug &&\n // console.log(`vertex is @${this.maxLimit} : `, this.vertexList[j]);\n continue;\n }\n debug &&\n console.log(\n `using vertex to Proceed :`,\n this.vertexList[j],\n \"with distance \",\n distance\n );\n\n /**\n * for current vertex insert all the edges in Queue\n * this queue will be doing sorting of the edges based on\n * the weights placed.\n */\n this.PQ.putInPriorityQueue(currentVertexIndex, j, distance);\n debug && console.log(this.PQ);\n }\n // debug && console.log(this.PQ);\n debug && console.log(`number of nodes in Tree ${this.nTree}`);\n\n if (this.PQ.getSize() === 0) {\n console.log(`GRAPH is not connected `);\n return;\n }\n let currentMinimumEdge = this.PQ.removeMin();\n\n let sourceVertex = currentMinimumEdge.source;\n currentVertexIndex = currentMinimumEdge.destination;\n\n result.push(\n `${this.vertexList[sourceVertex].getData()}${this.vertexList[\n currentVertexIndex\n ].getData()}(${currentMinimumEdge.weight})`\n );\n }\n return result.length > 0 ? result.join(\"-->\") : \"Some Error happened\";\n }",
"getMincosts() {\n\t\tlet mincost = new Float32Array(this.n+1);\n\t\tlet q = new List(this.n);\n\t\tfor (let r = 1; r <= this.n; r++) {\n\t\t\tif (this.p(r)) continue;\n\t\t\tq.enq(r);\n\t\t\twhile (!q.empty()) {\n\t\t\t\tlet u = q.deq();\n\t\t\t\tmincost[u] = (this.p(u) ? mincost[this.p(u)] : 0)\n\t\t\t\t\t\t\t + this.#dmin[u];\n\t\t\t\tif (this.left(u)) q.enq(this.left(u));\n\t\t\t\tif (this.right(u)) q.enq(this.right(u));\n\t\t\t}\n\t\t}\n\t\treturn mincost;\n\t}",
"getCenter() {\n const vertices = this.vertices;\n let areaSum = 0;\n let x = 0;\n let y = 0;\n\n vertices.forEach((currVertex, currIndex) => {\n const nextIndex = (currIndex + 1) % vertices.length;\n const nextVertex = vertices[nextIndex];\n\n const areaDiff = currVertex.x * nextVertex.y - nextVertex.x * currVertex.y;\n areaSum += areaDiff;\n\n x += (currVertex.x + nextVertex.x) * areaDiff;\n y += (currVertex.y + nextVertex.y) * areaDiff;\n });\n\n // If this is a straight line\n if (!areaSum) {\n return vertices.reduce((sumVertex, currVertex) => ({\n x: sumVertex.x + (currVertex.x / this.vertices.length),\n y: sumVertex.y + (currVertex.y / this.vertices.length)\n }), {\n x: 0,\n y: 0\n });\n }\n\n const factor = areaSum * 3;\n\n return new Vertex({\n x: x / factor,\n y: y / factor\n });\n }",
"function minDistance(objectTag, targetTag, maxDistance) {\r\n return gl5.filter(objectTag, targetTag, function (object, target) {\r\n return object.distanceTo(target) > maxDistance;\r\n });\r\n}",
"getSmallestNode() {\n let current = this;\n while (current.left) {\n current = current.left;\n }\n return current.value;\n }",
"function search_min_matrix(rows, places){\n var min = Number.MAX_VALUE;\n var ret = {i: -1, j: -1};\n\n for(k = 0; k < places.length; k++){\n var i = places[k].i, j = places[k].j;\n\n if(rows[i].elements[j].distance.value < min){\n min = rows[i].elements[j].distance.value;\n ret.i = i;\n ret.j = j;\n }\n }\n\n return ret;\n}",
"function getClosestNonWallTile(target){\r\n let min = 1000;\r\n let minIndexj = 0;\r\n let minIndexi = 0;\r\n for(let i=0; i<28; i++){//goes through each tile\r\n for(let j=0; j<31; j++){\r\n if(!originalTiles[j][i].wall){//if it is the current closest target\r\n if(dist(i, j, target.x, target.y)<min){\r\n min = dist(i, j, target.x, target.y);\r\n minIndexj = j;\r\n minIndexi = i;\r\n }\r\n }\r\n }\r\n }return createVector(minIndexi, minIndexj);//returns a PVector to the tile\r\n}",
"setDistanceMin(distance_min) {\n this.distance_min = Math.max(distance_min, this.distance_min_limit);\n this.zoom(0); // update, to ensure new minimum\n }",
"function getNearestGridPoint(x1, y1) {\n var current_x = parseInt(x1, 10);\n var current_y = parseInt(y1, 10);\n var i = 0;\n var minDist = Math.sqrt(Math.pow(points[i].x - current_x, 2) + Math.pow(points[i].y-current_y, 2));\n var ans = points[0];\n for(var i = 0 ; i < points.length; i ++) {\n var dist = Math.sqrt(Math.pow(points[i].x - current_x, 2) + Math.pow(points[i].y-current_y, 2));\n if(dist < minDist) {\n minDist = dist;\n ans = points[i];\n }\n }\n return ans;\n}",
"function maxDistance(dist, intree)\n{\n var max = 0;\n var maxV = -1;\n\n // For all vertices, if v is not in the dijkstra MST\n // and max distance sofar is less than or equal to dist[v]\n for (var v = 0; v < dist.length; v++){\n if (intree[v] === false && max <= dist[v]){\n max = dist[v];\n maxV = v; \n }\n }\n return maxV;\n}",
"function GetMin( data, column ) {\n\n // min gets the minimum data value from a range\n var min = d3.min( data, function( done ) {\n return done[column]; // same as done.year\n })\n\n return min;\n}",
"function primMST(graph) {\n if (!graph) return []\n const vertices = graph.getVerticeCount()\n const edges = Array(vertices).fill(Number.POSITIVE_INFINITY)\n const mstSet = Array(vertices).fill(false)\n const result = []\n edges[0] = 0 // we pick vertex 0 to start\n for (let i = 0; i < vertices; i++) {\n // we choose the the vertex with minimum edge weight to be included in the mst set\n let minVertex = -1\n for (let j = 0; j < vertices; j++) {\n if (!mstSet[j] && (minVertex === -1 || edges[j] < edges[minVertex])) {\n minVertex = j\n }\n }\n // add minVertex to mst set\n mstSet[minVertex] = true\n result.push(edges[minVertex])\n // update the remaining vertices min edges \n for (let k = 0; k < vertices; k++) {\n if (!mstSet[k]) {\n let neighbour = graph.getEdges(k)\n while (neighbour !== null) {\n if (neighbour.weight < edges[k]) {\n edges[k] = neighbour.weight\n }\n neighbour = neighbour.next\n }\n }\n }\n }\n return result\n}",
"getFirst(lane)\n {\n var vehicle;\n var result = null;\n var pos = Number.MAX_SAFE_INTEGER;\n\n for (let iVehicle = 0; iVehicle < this._aVehicles.length; iVehicle ++)\n {\n vehicle = this._aVehicles[iVehicle];\n\n if (vehicle.lane != lane)\n continue;\n \n if (vehicle.pos < pos)\n {\n pos = vehicle.pos;\n result = vehicle;\n }\n }\n\n return(result);\n }",
"getPreceding(refVehicle, offLane)\n {\n var vehicle, dist;\n var result = null;\n var distMin = Number.MAX_SAFE_INTEGER;\n var pos = refVehicle.pos;\n var lane = refVehicle.lane + offLane;\n\n for (let iVehicle = 0; iVehicle < this._aVehicles.length; iVehicle ++)\n {\n vehicle = this._aVehicles[iVehicle];\n\n if (vehicle === refVehicle) // ignore ourself\n continue;\n\n if (vehicle.lane != lane)\n continue;\n\n dist = vehicle.pos - pos;\n if (dist < 0)\n continue;\n\n if (dist < distMin)\n {\n distMin = dist;\n result = vehicle;\n }\n }\n\n return(result)\n }",
"distanceTo (x, y) { return this.get(x, y).dist }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
endregion region twilio handlers | function incomingTwilioHandler(connection) {
twilioConnection = connection;
connection.on("accept", function () {
socket.emit('status', 1);
callGoing();
Teamlab.saveVoipCall({}, currentCall.id,
{
answeredBy: Teamlab.profile.id
},
{
async: true,
success: function (params, call) {
currentCall = call;
renderView();
}
});
});
connection.on("disconnect", function () {
if (!pause) {
socket.emit('status', 0);
}
callCompleted();
});
connection.accept();
} | [
"function webhook(req, res, next) {\n\n console.log(\"Made it to the webhook!\")\n\n switch(req.body.type) {\n case \"message-created\":\n messageCreated(req.body);\n console.log(\"Message created!\")\n break;\n case \"space-members-added\":\n spaceMembersAdded(req.body);\n break;\n case \"space-members-removed\":\n spaceMembersRemoved(req.body);\n break;\n case \"message-annotation-added\":\n messageAnnotationAdded(req.body);\n break;\n case \"message-annotation-edited\":\n messageAnnotationEdited(req.body);\n break;\n case \"message-annotation-removed\":\n messageAnnotationRemoved(req.body);\n break;\n }\n\n // you can acknowledge here or later; if later, uncomment next()\n // but you MUST respond or watsonwork will keep sending the message\n res.status(200).send().end();\n // next();\n}",
"async function handleMessage (message) {\n try {\n // sms from\n const from = message.From\n // sms to\n const to = message.To\n // sms body\n const body = message.Body\n console.log(`Twilio - SMS received from ${from} on ${to}`)\n let session\n // find session, if exists\n session = await getSession(to, from)\n // did session expire?\n if (session) {\n const expired = await session.checkExpiration()\n if (expired) {\n // session has expired. unset session var\n session = undefined\n }\n }\n\n // if session doesn't exist, create one\n if (!session) {\n console.log('new Twilio SMS chat session')\n // get the appropriate part of the phone number to use for lookups\n const phone = getLookupNumber(from, to)\n\n let dcloudSession = {}\n try {\n dcloudSession = await getDcloudSession(from, to)\n console.log('got dCloud session information:', dcloudSession)\n } catch (e) {\n console.error('Error getting dCloud phone number registration info', e.message)\n }\n\n // find app info in database\n const app = await findApp(to)\n // validate app\n if (app === null || !app.token || !app.sid) {\n throw `Twilio app ${to} not registered. Please register this Twilio app with a id, sid, and token.`\n }\n\n let answers = {}\n let firstName = undefined\n let lastName = undefined\n let email = undefined\n let userId = undefined\n try {\n // get mobile app answers information that user submitted (hopefully)\n answers = await getAnswers(phone)\n // did we find mobile app info for this phone number in the answers db?\n if (answers) {\n // get instant demo username from the POD ID that user entered into the\n // settings screen of the mobile app\n console.log('found mobile app answers for', phone, '- it has podId', answers.podId)\n userId = answers.podId\n email = answers.emailAddress\n // first name is the string of non-space characters before the first space\n firstName = answers.userName.split(' ')[0]\n // last name is the rest of the userName value, after firstName\n lastName = answers.userName.substring(firstName.length)\n } else {\n // no mobile app answers found\n console.log('failed to find mobile app answers for', phone)\n }\n } catch (e) {\n console.error('Error getting dCloud session info', e)\n }\n // create session and store in sessions global\n // try to set the user ID using info from phones db info\n session = new Session('twilio', {\n to,\n from,\n app,\n phone,\n // set user ID from dcloud session info or from mobile app answers\n userId: dcloudSession.userId || userId,\n email: email || phone,\n firstName: firstName || phone,\n lastName: lastName || '',\n // apiAiToken: botConfig.aiToken,\n // entryPointId: brandConfig.entryPointId,\n dcloudSession: dcloudSession.session,\n dcloudDatacenter: dcloudSession.datacenter,\n botEnabled: true,\n survey: true\n }, onAddMessage, onTypingStart, onTypingStop)\n // add session to global sessions\n await addSession(session)\n // wait for the checkSessionInfo method to finish, so that any custom config\n // is applied before we start the chat bot\n await session.checkSessionPromise\n // check if session is an instant demo\n if (session.isInstantDemo) {\n // make sure customer is registered, then send sparky message to AI\n session.checkInstantDemoCustomer('sparky')\n // don't do anything else\n return\n } else {\n // set first message to AI as sparky, to trigger dialog with customer\n session.addCustomerMessage('sparky')\n // don't do anything else\n return\n }\n } else {\n console.log(session.id, `- existing SMS chat session with ${from}`)\n }\n // was there text in the message?\n if (body) {\n // add message to session data\n session.addCustomerMessage(body)\n }\n } catch (e) {\n console.error('error during twilio handleMessage:', e)\n // throw e\n }\n}",
"async listen() {\n const contract = await this.getContract();\n contract.on('Claimed', async (vendor, phone, amount) => {\n try {\n const otp = Math.floor(1000 + Math.random() * 9000);\n const data = await this.setHashToChain(contract, vendor, phone.toString(), otp.toString());\n\n const message = `A vendor is requesting ${amount} token from your account. If you agree, please provide this OTP to vendor: ${otp}`;\n // eslint-disable-next-line global-require\n const sms = require(`./plugins/sms/${config.get('plugins.sms.service')}`);\n\n // call SMS function from plugins to send SMS to beneficiary\n sms(phone.toString(), message);\n } catch (e) {\n console.log(e);\n }\n });\n console.log('--- Listening to Blockchain Events ----');\n }",
"function buttonAction1(res, tTime, rTime, uName, dTime){\n console.log(\"running test function\")\n const accountSid = 'ACc1bcb5b9402e67ef201df3937f522ebe';\n const authToken = 'ad0278c4e2c2c787cc44616f5b3d9c25';\n const client = require('twilio')(accountSid, authToken);\n client.messages\n .create({\n body: 'Hi ' + uName + ', your journey is going to take about ' + tTime + \" and you want to be there at \" + dTime + \". You will recieve a text when it is time to go.\",\n from: '+12766334501',\n to: '+13053047050'\n })\n .then(message => console.log(message.sid));\n \n \n \n}",
"function buttonAction1(res, tTime){\r\n console.log(\"running test function\")\r\n const accountSid = 'ACc1bcb5b9402e67ef201df3937f522ebe';\r\n const authToken = 'ad0278c4e2c2c787cc44616f5b3d9c25';\r\n const client = require('twilio')(accountSid, authToken);\r\n client.messages\r\n .create({\r\n body: 'Your journey is going to take about '+tTime,\r\n from: '+12766334501',\r\n to: '+13053047050'\r\n })\r\n .then(message => console.log(message.sid));\r\n}",
"function _handleMemberIO(member) {\n\n\tvar\n\t\tself = this;\n\n\t// Received a message\n\tmember.mstream.on('message',function(m){\n\t\tself._debug(9,\"[\"+member.id+\"] Got a llmsg from \"+(member.name || member.id)+\": \",m);\n\t\tmember.lastContact = new Date().getTime();\n\t\tif ( m.c == \"ping\" ) {\n\t\t\treturn self.__send(member,{a:\"ping\"});\n\t\t}\n\t\telse if ( m.a == \"ping\" ) {\n\t\t\tif ( !member.pingTimeout )\n\t\t\t\treturn;\n\t\t\tclearTimeout(member.pingTimeout);\n\t\t\tmember.pingTimeout = null;\n\t\t\treturn;\n\t\t}\n\t\telse if ( member.type == \"client\" && m.c == \"hi!\" ) {\n\t\t\tif ( m.mynameis != null ) {\n\t\t\t\tvar iknow = Object.keys(self._membersIKnow);\n\t\t\t\tiknow.forEach(function(name){ member.toldHimAbout[name] = true; });\n\t\t\t\tself._identifyMember(member,m.mynameis,m.iknow);\n\t\t\t\treturn self.__send(member,{a:\"hi!\",mynameis:self.name,iknow:iknow});\n\t\t\t}\n\t\t}\n\t\telse if ( member.type == \"server\" && m.a == \"hi!\" ) {\n\t\t\tif ( m.mynameis != null ) {\n\t\t\t\tif ( self.directMember(m.mynameis) ) {\n\t\t\t\t\tself._debug(7,\"I am already connected with '\"+m.mynameis+\"', dropping connection..\");\n\t\t\t\t\treturn member.disconnect();\n\t\t\t\t}\n\t\t\t\treturn self._identifyMember(member,m.mynameis,m.iknow);\n\t\t\t}\n\t\t}\n\t\telse if ( m.c == \"imcon4\" ) {\n\t\t\tif ( m.who && m.who instanceof Array ) {\n\t\t\t\tself._debug(4,\"Registering connection \"+m.who.join(',')+\" via \"+member.name);\n\t\t\t\tvar met = self._registerMembers(m.who,member.name);\n\t\t\t\tif ( met.length > 0 ) {\n\t\t\t\t\tself._debug(5,\"JUST MET: \",met);\n\t\t\t\t\tself._debug(5,\"Now i knoW: \",Object.keys(self._membersIKnow));\n\t\t\t\t\tmet.forEach(function(memberIJustMet){\n\t\t\t\t\t\tself.emit('meet',memberIJustMet);\n\t\t\t\t\t});\n\t\t\t\t\tself._checkMessagesFor(met);\n\t\t\t\t}\n\t\t\t\treturn self._tellThatIamConnectionFor(m.who,[member.name]);\n\t\t\t}\n\t\t}\n\t\telse if ( m.c == \"im!con4\" ) {\n\t\t\tif ( m.who && m.who instanceof Array ) {\n\t\t\t\tself._debug(4,\"Removing connection \"+m.who.join(',')+\" via \"+member.name);\n\t\t\t\tvar lostOrAlmost = self._unregisterMembers(m.who,member.name);\n\t\t\t\tif ( lostOrAlmost.lost.length > 0 ) {\n\t\t\t\t\tself._debug(6,\"JUST LOST: \",lostOrAlmost.lost);\n\t\t\t\t\tlostOrAlmost.lost.forEach(function(memberIJustLost){\n\t\t\t\t\t\tself.emit('loose',memberIJustLost);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif ( lostOrAlmost.almost.length > 0 ) {\n\t\t\t\t\tself._debug(6,\"Almost lost: \",lostOrAlmost.almost);\n\t\t\t\t}\n\t\t\t\tself._debug(6,\"Now i knoW: \",Object.keys(self._membersIKnow));\n\t\t\t\treturn self._tellThatIamNotConnectionFor(m.who,[member.name]);\n\t\t\t}\n\t\t}\n\t\telse if ( m.c == \"msg\" ) {\n\t\t\tif ( m.f && m.t && m.m )\n\t\t\t\treturn self._receiveMessage(m.f,m.t,m.m,member.name);\n\t\t}\n\t\tself._debug(9,\"[\"+member.id+\"] Misunderstood message: \",m);\n\t});\n\t// Error\n\tmember.mstream.on('error',function(err){\n\t\tself._debug(7,\"[\"+member.id+\"] Got an error from \"+(member.name || member.id)+\": \",err);\n\t});\n\t// Disconnected\n\tmember.mstream.on('end',function(){\n\t\tself._debug(7,\"[\"+member.id+\"] \"+member.type.toUpperCase()+\" \"+(member.name || member.id)+\" (\"+member.type+\") disconnected\");\n\t\tif ( member.type == \"server\" && !member.dropped && self.opts.autoReconnect ) {\n\t\t\tprocess.nextTick(function(){\n\t\t\t\tself._debug(7,\"Reconnecting with member \"+(member.name || member.id)+\" (\"+member.host+\":\"+member.port+\") ...\");\n\t\t\t\tself.connect(member.port,member.host);\n\t\t\t});\n\t\t}\n\t\treturn self._destroyMember(member);\n\t});\n\n\treturn member;\n\n}",
"_initializeRadio()\n {\n Radio.channel('rodan').on(RODAN_EVENTS.EVENT__USER_SAVED, (options) => this._handleEventGeneric(options));\n Radio.channel('rodan').on(RODAN_EVENTS.EVENT__USER_CHANGED_PASSWORD, (options) => this._handleEventGeneric(options));\n Radio.channel('rodan').reply(RODAN_EVENTS.REQUEST__USER_CHANGE_PASSWORD, (options) => this._handleRequestChangePassword(options));\n Radio.channel('rodan').reply(RODAN_EVENTS.REQUEST__USER_SAVE, (options) => this._handleRequestSaveUser(options));\n\n Radio.channel('rodan').reply(RODAN_EVENTS.REQUEST__AUTHENTICATION_USER, () => this._handleRequestUser());\n Radio.channel('rodan').reply(RODAN_EVENTS.REQUEST__AUTHENTICATION_LOGIN, options => this._login(options));\n Radio.channel('rodan').reply(RODAN_EVENTS.REQUEST__AUTHENTICATION_CHECK, () => this._checkAuthenticationStatus());\n Radio.channel('rodan').reply(RODAN_EVENTS.REQUEST__AUTHENTICATION_LOGOUT, () => this._logout());\n }",
"function getMessages(phoneNumber, twilioNumber) {\n $(\"#messages\").html(\"\");\n $.getJSON(\"/api/admin/get_messages\", {\"phone_number\": phoneNumber, \"twilio_number\": twilioNumber}, \n function(messages) {\n for (i in messages) {\n var message = messages[i];\n messageDiv = makeElement(\"message\");\n messageDiv.find(\".to\").text(message.outbound == 0 ? \"Me: \" : \"Them: \");\n messageDiv.find(\".body\").text(message.body);\n $(\"#messages\").append(messageDiv);\n }\n });\n}",
"function sendTwilioMessage (client,from,to,body){\n client.messages\n .create({\n body: \"your passowrd is:\"+body,\n /*from: '+12074075156',*/\n from:from,\n to:to \n })\n .then(message => console.log(\"here the message id:\"+message.sid));\n}",
"function respond(message, gateway, request, response, number) {\n console.log('[' + number + '] sending ' + message.length + 'c: ' + message);\n if (gateway === 'telerivet') {\n // Telerivet requires JSON response\n var res = {\n messages: [ { content: message } ]\n };\n response.send(res);\n } else {\n // Render Twilio-style response \n var twiml = new twilio.TwimlResponse();\n twiml.message(message);\n response.type('text/xml');\n response.send(twiml.toString());\n }\n}",
"function receiveCallback(data) {\n receiveWhois(session,data);\n }",
"function respond() {\n response.type('text/xml');\n response.send(twiml.toString());\n console.log(twiml.toString());\n }",
"respond (...args) {\n return this.listen('respond', ...args)\n }",
"function handle_bp_account_lite(req, startTime, apiName) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\n}",
"function listening_handler() {\n\tconsole.log(`Now Listening on Port ${port}`);\n}",
"_setupRoutes() {\n // For requests to webhook handler path, make the webhook handler take care\n // of the requests.\n this.server.post(this.webhookOptions.path, (req, res, next) => {\n this.handler(req, res, error => {\n res.send(400, 'Error processing hook');\n this.logger.error({err: error}, 'Error processing hook');\n\n next();\n });\n });\n\n this.server.post('/builds/:bid/status/:context', restify.plugins.jsonBodyParser(), this.buildStatusController.bind(this));\n this.server.post('/update', restify.plugins.jsonBodyParser(), this.buildStatusController.bind(this));\n\n this.server.get('/pull-request/:owner/:repo/:pullRequestNumber', this.getPullRequest.bind(this));\n }",
"function handleRequest(req, res, urn){\n if(!isRequestValid(req)){\n return res.status(500).json({\n status: 'error',\n message: \"Fields required: \" + activityFields + \" and incorrect type required: Create, Update or Delete\"\n });\n }else return forwardRequest(req, res, urn);\n}",
"setOnMessageHandler(handler) {\n this.wsSocket.on('data', handler);\n this.wsSocket.on('message', handler);\n }",
"function forwardRequest(req, res, urn){\n let identifier = req.body.actor.split(\"/\").pop()+'_'+Date.now();\n req.body.id = noteQueryUrl +''+identifier;\n return inboxApi.sendActivity(req,urn)\n .then((data) => {\n res.status(201).json({\n status: 'success',\n data\n })\n })\n .catch((err) => {\n console.log(err);\n res.status(500).json({\n status: 'error',\n message: String(err)\n })\n })\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Refresh the transformation matrix on the page with the current matrix values | function updateTransformationMatrixDisplay () {
// Divide by 1 to remove trailing zeroes
$('#matrixElemA').val(matrix.a.toFixed(decimalPlaces) / 1)
$('#matrixElemB').val(matrix.b.toFixed(decimalPlaces) / 1)
$('#matrixElemC').val(matrix.c.toFixed(decimalPlaces) / 1)
$('#matrixElemD').val(matrix.d.toFixed(decimalPlaces) / 1)
} | [
"function mResetMatrix() {\n resetMatrix();\n mPage.resetMatrix();\n}",
"function updateTransform() {\n scope.style.transform = 'translate(0,' + current + 'px)';\n }",
"identity() { \n this.internal.gridTransformationList = [];\n this.internal.linearTransformation.identity();\n }",
"UpdateViewDependentData()\n {\n if (!this.display || this._state === EveMissileWarhead.State.DEAD) return;\n mat4.transpose(this._perObjectData.vs.Get(\"WorldMat\"), this._transform);\n mat4.transpose(this._perObjectData.vs.Get(\"WorldMatLast\"), this._transform);\n }",
"toggleProjectionMatrixHandInPlace() {\n const m = this._m;\n m[8] *= -1;\n m[9] *= -1;\n m[10] *= -1;\n m[11] *= -1;\n this._markAsUpdated();\n }",
"resetTransform() {\n _wl_object_reset_translation_rotation(this.objectId);\n _wl_object_reset_scaling(this.objectId);\n }",
"function gPush() {\r\n MVS.push(modelViewMatrix) ;\r\n}",
"function editresult()\n{\n matrix = savematriz(2,matrizResultante);\n dom(\"mresult\").hidden=true;\n escreveMatriz(math.size(matrizResultante)._data,0,matrix,false);\n \n}",
"setTransformDirty () {\n this._transformDirty = true;\n }",
"function gPop() {\r\n modelViewMatrix = MVS.pop() ;\r\n}",
"_refresh(){\n this._refreshSize();\n this._refreshPosition();\n }",
"setSurroundModeToMatrix() {\n this._setSurroundMode(\"s_matrix\");\n }",
"function update() {\n $(\".counter\").text(\"\" + grid.nb); //update tous les counter avec le nouveau grid.nb\n\n let xy = grid.genRand(); //genere une nouvelle tuile aux coordonnees x, y\n\n for (let key in grid.stateChanges) { //pour chaque changement\n const tile = $(\"#\" + key); //on prend le div de la tuile\n\n const arr = grid.stateChanges[key];\n const val = grid.grid[arr[0]][arr[1]].value;\n\n tile.attr(\"style\", \"\"); //on reset son style pour annuler ses animations\n tile.attr(\"class\", \"tile \" + \"v\" + val); //on lui donne les bonnes classes pour sa nouvelle valeur\n //on lui donne le bon texte pour sa valeur\n tile.html('<div class=\"v\">' + (val === null ? \"\" : \"\" + val) + '</div>');\n }\n\n /*\n On anime la nouvelle tuile generee par genRand.\n\n Pas besoin de reset ce style puisqu'on specifie que l'animation ne se fait qu'une fois\n */\n if (xy !== false) $(\"#x\" + xy[0] + \"y\" + xy[1]).css({\n \"animation-name\": \"rotate\",\n \"animation-duration\": \"\" + duration + \"ms\",\n \"animation-timing-function\": \"linear\"\n });\n}",
"setTransform(t) {\n this._transform = t.copy();\n this.markTransformed();\n }",
"_invalidatePositionCache() {\n this._rowPos = [];\n this._columnPos = [];\n }",
"function transformations () {\n ctx.fillRect(0, 0, w, h)\n function drawTransformations() {\n for (let i = 0; i < 100; i++) {\n const x = Math.random() * w\n const y = Math.random() * h\n ctx.fillRect(x, y, 50, 50)\n }\n }\n\n ctx.fillStyle = \"black\"\n drawTransformations()\n ctx.save()\n ctx.fillStyle = \"red\"\n drawTransformations()\n ctx.restore()\n drawTransformations()\n}",
"resetTranslationRotation() {\n _wl_object_reset_translation_rotation(this.objectId);\n }",
"function resetScaleTransform() {\n Data.Edit.Transform.Scale = 1;\n updateTransform();\n}",
"function animate() {\n illustration.updateRenderGraph();\n requestAnimationFrame(animate);\n\n hook.rotate.y -= 0.01;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses a single line of ABC notes (i.e., not a header line). We process an ABC song stream by dividing it into tokens, each of which is a pitch, duration, or special decoration symbol; then we process each decoration individually, and we process each stem as a group using parseStem. The structure of a single ABC note is something like this: NOTE > STACCATO? PITCH DURATION? TIE? I.e., it always has a pitch, and it is prefixed by some optional decorations such as a (.) staccato marking, and it is suffixed by an optional duration and an optional tie () marking. A stem is either a note or a bracketed series of notes, followed by duration and tie. STEM > NOTE OR '[' NOTE ']' DURAITON? TIE? Then a song is just a sequence of stems interleaved with other decorations such as dynamics markings and measure delimiters. | function parseABCNotes(str) {
var tokens = str.match(ABCtoken), parsed = null,
index = 0, dotted = 0, beatlet = null, t;
if (!tokens) {
return null;
}
while (index < tokens.length) {
// Ignore %comments and !markings!
if (/^[\s%]/.test(tokens[index])) { index++; continue; }
// Handle inline [X:...] information fields
if (/^\[[A-Za-z]:[^\]]*\]$/.test(tokens[index])) {
handleInformation(
tokens[index].substring(1, 2),
tokens[index].substring(3, tokens[index].length - 1).trim()
);
index++;
continue;
}
// Handled dotted notation abbreviations.
if (/</.test(tokens[index])) {
dotted = -tokens[index++].length;
continue;
}
if (/>/.test(tokens[index])) {
dotted = tokens[index++].length;
continue;
}
if (/^\(\d+(?::\d+)*/.test(tokens[index])) {
beatlet = parseBeatlet(tokens[index++]);
continue;
}
if (/^[!+].*[!+]$/.test(tokens[index])) {
parseDecoration(tokens[index++], accent);
continue;
}
if (/^.?".*"$/.test(tokens[index])) {
// Ignore double-quoted tokens (chords and general text annotations).
index++;
continue;
}
if (/^[()]$/.test(tokens[index])) {
if (tokens[index++] == '(') {
accent.slurred += 1;
} else {
accent.slurred -= 1;
if (accent.slurred <= 0) {
accent.slurred = 0;
if (context.stems && context.stems.length >= 1) {
// The last notes in a slur are not slurred.
slurStem(context.stems[context.stems.length - 1], false);
}
}
}
continue;
}
// Handle measure markings by clearing accidentals.
if (/\|/.test(tokens[index])) {
for (t in accent) {
if (t.length == 1) {
// Single-letter accent properties are note accidentals.
delete accent[t];
}
}
index++;
continue;
}
parsed = parseStem(tokens, index, key, accent);
// Skip unparsable bits
if (parsed === null) {
index++;
continue;
}
// Process a parsed stem.
if (beatlet) {
scaleStem(parsed.stem, beatlet.time);
beatlet.count -= 1;
if (!beatlet.count) {
beatlet = null;
}
}
// If syncopated with > or < notation, shift part of a beat
// between this stem and the previous one.
if (dotted && context.stems && context.stems.length) {
if (dotted > 0) {
t = (1 - Math.pow(0.5, dotted)) * parsed.stem.time;
} else {
t = (Math.pow(0.5, -dotted) - 1) *
context.stems[context.stems.length - 1].time;
}
syncopateStem(context.stems[context.stems.length - 1], t);
syncopateStem(parsed.stem, -t);
}
dotted = 0;
// Slur all the notes contained within a strem.
if (accent.slurred) {
slurStem(parsed.stem, true);
}
// Start a default voice if we're not in a voice yet.
if (context === result) {
startVoiceContext(firstVoiceName());
}
if (!('stems' in context)) { context.stems = []; }
// Add the stem to the sequence of stems for this voice.
context.stems.push(parsed.stem);
// Advance the parsing index since a stem is multiple tokens.
index = parsed.index;
}
} | [
"function parseStem(tokens, index, key, accent) {\n var notes = [],\n duration = '', staccato = false,\n noteDuration, noteTime, velocity,\n lastNote = null, minStemTime = Infinity, j;\n // A single staccato marking applies to the entire stem.\n if (index < tokens.length && '.' == tokens[index]) {\n staccato = true;\n index++;\n }\n if (index < tokens.length && tokens[index] == '[') {\n // Deal with [CEG] chorded notation.\n index++;\n // Scan notes within the chord.\n while (index < tokens.length) {\n // Ignore and space and %comments.\n if (/^[\\s%]/.test(tokens[index])) {\n index++;\n continue;\n }\n if (/[A-Ga-g]/.test(tokens[index])) {\n // Grab a pitch.\n lastNote = {\n pitch: applyAccent(tokens[index++], key, accent),\n tie: false\n }\n lastNote.frequency = pitchToFrequency(lastNote.pitch);\n notes.push(lastNote);\n } else if (/[xzXZ]/.test(tokens[index])) {\n // Grab a rest.\n lastNote = null;\n index++;\n } else if ('.' == tokens[index]) {\n // A staccato mark applies to the entire stem.\n staccato = true;\n index++;\n continue;\n } else {\n // Stop parsing the stem if something is unrecognized.\n break;\n }\n // After a pitch or rest, look for a duration.\n if (index < tokens.length &&\n /^(?![\\s%!]).*[\\d\\/]/.test(tokens[index])) {\n noteDuration = tokens[index++];\n noteTime = durationToTime(noteDuration);\n } else {\n noteDuration = '';\n noteTime = 1;\n }\n // If it's a note (not a rest), store the duration\n if (lastNote) {\n lastNote.duration = noteDuration;\n lastNote.time = noteTime;\n }\n // When a stem has more than one duration, use the shortest\n // one for timing. The standard says to pick the first one,\n // but in practice, transcribed music online seems to\n // follow the rule that the stem's duration is determined\n // by the shortest contained duration.\n if (noteTime && noteTime < minStemTime) {\n duration = noteDuration;\n minStemTime = noteTime;\n }\n // After a duration, look for a tie mark. Individual notes\n // within a stem can be tied.\n if (index < tokens.length && '-' == tokens[index]) {\n if (lastNote) {\n notes[notes.length - 1].tie = true;\n }\n index++;\n }\n }\n // The last thing in a chord should be a ]. If it isn't, then\n // this doesn't look like a stem after all, and return null.\n if (tokens[index] != ']') {\n return null;\n }\n index++;\n } else if (index < tokens.length && /[A-Ga-g]/.test(tokens[index])) {\n // Grab a single note.\n lastNote = {\n pitch: applyAccent(tokens[index++], key, accent),\n tie: false,\n duration: '',\n time: 1\n }\n lastNote.frequency = pitchToFrequency(lastNote.pitch);\n notes.push(lastNote);\n } else if (index < tokens.length && /^[xzXZ]$/.test(tokens[index])) {\n // Grab a rest - no pitch.\n index++;\n } else {\n // Something we don't recognize - not a stem.\n return null;\n }\n // Right after a [chord], note, or rest, look for a duration marking.\n if (index < tokens.length && /^(?![\\s%!]).*[\\d\\/]/.test(tokens[index])) {\n duration = tokens[index++];\n noteTime = durationToTime(duration);\n // Apply the duration to all the ntoes in the stem.\n // NOTE: spec suggests multiplying this duration, but that\n // idiom is not seen (so far) in practice.\n for (j = 0; j < notes.length; ++j) {\n notes[j].duration = duration;\n notes[j].time = noteTime;\n }\n }\n // Then look for a trailing tie marking. Will tie every note in a chord.\n if (index < tokens.length && '-' == tokens[index]) {\n index++;\n for (j = 0; j < notes.length; ++j) {\n notes[j].tie = true;\n }\n }\n if (accent.dynamics) {\n velocity = accent.dynamics;\n for (j = 0; j < notes.length; ++j) {\n notes[j].velocity = velocity;\n }\n }\n return {\n index: index,\n stem: {\n notes: notes,\n duration: duration,\n staccato: staccato,\n time: durationToTime(duration)\n }\n };\n }",
"parse() {\n\t\t// console.log('Started parsing');\n\t\tthis.parseHeader();\n\t\tif (this.error !== null) {\n\t\t\tif (this.error.code <= 2 && this.error.code !== 0) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tthis.trks = new Array(this.ntrks);\n\t\tlet t0 = (new Date()).getTime();\n\t\tlet i;\n\t\tfor (i = 0; i < this.ntrks; i++) {\n\t\t\tthis.trks[i] = new MIDItrack();\n\t\t}\n\t\tfor (tpos = 0; tpos < this.ntrks; tpos++) {\n\t\t\tisNewTrack = true;\n\t\t\tthis.trks[tpos].usedInstruments.push();\n\t\t\tthis.parseTrack();\n\t\t\t// console.log(this.trks[tpos].events);\n\t\t}\n\t\tlet lowestQuantizeError = Infinity;\n\t\tlet bestBPB = 0;\n\t\tfor (i = 0; i < 16; i++) {\n\t\t\tlet total = 0;\n\t\t\tfor (let j = 0; j < this.trks.length; j++) {\n\t\t\t\ttotal += this.trks[j].quantizeErrors[i];\n\t\t\t}\n\t\t\t// console.log('BPB: ' + (i+1) + ', error: ' + total);\n\t\t\tif (total < lowestQuantizeError && i < 8) {\n\t\t\t\tlowestQuantizeError = total;\n\t\t\t\tbestBPB = i + 1;\n\t\t\t}\n\t\t}\n\t\tthis.blocksPerBeat = bestBPB;\n\t\t// console.log(this);\n\t\t// console.log(this.noteCount+' notes');\n\t\t// console.log('MIDI data loaded in '+((new Date).getTime() - t0)+' ms');\n\t}",
"function emphasis(state, silent) {\n var i, scanned, token,\n start = state.pos,\n marker = state.src.charCodeAt(start);\n\n if (silent) { return false; }\n\n if (marker !== 0x5F && marker !== 0x2A) { return false; } // '_' or '*'\n\n scanned = scanDelims(state.src, state.posMax, state.pos);\n\n for (i = 0; i < scanned.length; i++) {\n token = state.push('text', '', 0);\n token.content = String.fromCharCode(marker);\n\n state.delimiters.push({\n // Char code of the starting marker (number).\n //\n marker: marker,\n\n // An amount of characters before this one that's equivalent to\n // current one. In plain English: if this delimiter does not open\n // an emphasis, neither do previous `jump` characters.\n //\n // Used to skip sequences like \"*****\" in one step, for 1st asterisk\n // value will be 0, for 2nd it's 1 and so on.\n //\n jump: i,\n\n // A position of the token this delimiter corresponds to.\n //\n token: state.tokens.length - 1,\n\n // Token level.\n //\n level: state.level,\n\n // If this delimiter is matched as a valid opener, `end` will be\n // equal to its position, otherwise it's `-1`.\n //\n end: -1,\n\n // Boolean flags that determine if this delimiter could open or close\n // an emphasis.\n //\n open: scanned.can_open,\n close: scanned.can_close\n });\n }\n\n state.pos += scanned.length;\n\n return true;\n }",
"function getMomentStrs(str) {\n let result = []\n //1. split by line breaker into note segments, each segments containing notes to be played at the same moment\n let _arr = str.split(/\\n/)\n // console.log(_arr)\n if (_arr) {\n \n _arr.forEach((d, i) => {\n if (d !== null && d.trim().length > 0){\n let tmp={}\n tmp.line = i+1\n tmp.data=d\n result.push(tmp)\n } \n })\n }\n return result\n} // getMomentStrs",
"function renderMeas(\n chunks, abcList, currNoteGp, keySigSharpMap, timeSigDenom,\n showNotesCursor, showSpelling, abcNoteDuration, chordLocs,\n prevProximateChordIdx, measureEndTime, cursorTime) {\n if (chunks.length === 0) {\n return prevProximateChordIdx;\n }\n\n // TODO think about moving this block to where chunking happens\n let proximateChordIdx = prevProximateChordIdx;\n let sharpMap = {};\n chunks.forEach((chunk, chunkIdx) => {\n const noteGpsArr = chunk.getNoteGps();\n noteGpsArr.forEach((noteGp, idx) => {\n proximateChordIdx = _getProximateChordIdx(proximateChordIdx, noteGp, chordLocs);\n const proximateChord = chordLocs.length < 1 ? null : chordLocs[proximateChordIdx].chord;\n\n if (!noteGp.isGraceNote()) {\n // Display cursor at the unique non-grace noteGp that currNoteGp is associated with.\n if (showNotesCursor) {_displayCursor(abcList, noteGp, currNoteGp, cursorTime);}\n if (showSpelling) {_displaySpelling(abcList, noteGp, proximateChord);}\n }\n\n // TODO think of how to make the grace note rendering cleaner.\n if (noteGp.isGraceNote()) {\n // No need to handle grace note within a tuplet chunk. Not possible currently.\n // Start of grace note in a singleton chunk\n if (chunkIdx - 1 < 0 ||\n !(chunks[chunkIdx - 1] instanceof chunking.SingletonChunk) ||\n !chunks[chunkIdx - 1].getNoteGps()[0].isGraceNote()) {\n abcList.push('{');\n }\n }\n\n const alteredNoteGps = chunk.getAlteredNoteGps()[idx];\n _displayNoteGp(\n abcList, alteredNoteGps, sharpMap, keySigSharpMap, proximateChord,\n abcNoteDuration, timeSigDenom, chunk, idx);\n\n // TODO think of how to make the grace note rendering cleaner.\n if (noteGp.isGraceNote()) {\n // End of grace note in a singleton chunk\n if (chunkIdx + 1 > chunks.length ||\n !(chunks[chunkIdx + 1] instanceof chunking.SingletonChunk) ||\n !chunks[chunkIdx + 1].getNoteGps()[0].isGraceNote()) {\n abcList.push('}');\n }\n }\n });\n });\n\n _padFinalMeasure(abcList, measureEndTime, chunks, abcNoteDuration);\n return proximateChordIdx;\n}",
"parseTrack() {\n\t\tlet done = false;\n\t\tif (this.fetchString(4) !== 'MTrk') {\n\t\t\tconsole.log('ERROR: No MTrk');\n\t\t\tthis.error = { code: 4, pos: ppos, msg: 'Failed to find MIDI track.' };\n\t\t\treturn;\n\t\t}\n\t\t// this.trks.push(new MIDItrack());\n\t\tlet len = this.fetchBytes(4);\n\t\t// console.log('len = '+len);\n\t\twhile (!done) {\n\t\t\tdone = this.parseEvent();\n\t\t}\n\t\tthis.labelCurrentTrack();\n\t\t// console.log('Track '+tpos);\n\t\t// console.log(this.trks[tpos].events);\n\t\t// console.log(trackDuration);\n\t\tif (trackDuration > this.duration) {\n\t\t\tthis.duration = trackDuration;\n\t\t}\n\t\ttrackDuration = 0;\n\t\tnoteDelta.fill(0);\n\t}",
"notesNotation() {\r\n let actual = this.octaveGenerator();\r\n let notes = [];\r\n\r\n for (let i = 0; i < actual.length; i++) {\r\n if (actual[i].indexOf(\"#\") !== -1 || actual[i].indexOf(\"b\") !== -1) {\r\n notes.push(new VF.StaveNote({ clef: \"treble\", keys: [actual[i]], duration: \"w\" }).addAccidental(0, new VF.Accidental(actual[i][1]))); //index1 is always an accidantal in this case\r\n }\r\n else if (actual[i].indexOf(\"#\") === -1 || actual[i].indexOf(\"b\") === -1) {\r\n notes.push(new VF.StaveNote({ clef: \"treble\", keys: [actual[i]], duration: \"w\" }));\r\n\r\n }\r\n }\r\n\r\n for (let i = 0; i < notes.length - 1; i++) {\r\n //Checks if there is appearence of \"natural - accidental\" \r\n if (notes[i].keys[0][0] === notes[i + 1].keys[0][0] && this.keySigns.lastIndexOf(\"B\") === -1) {\r\n\r\n notes[i + 1] = notes[i + 1].addAccidental(0, new VF.Accidental(\"n\"));\r\n }\r\n else if (notes[i].keys[0][0] === notes[i + 1].keys[0][0] && notes[0].keys[0][0] === notes[notes.length - 1].keys[0][0]) {\r\n notes[notes.length - 1] = notes[notes.length - 1].addAccidental(0, new VF.Accidental(\"n\"));\r\n break;\r\n }\r\n\r\n }\r\n\r\n return notes;\r\n }",
"function setABCNote(note, duration = \"\"){\n\tmusicalElements += note + duration + \" \";\n}",
"function parse(lrc)\n{\n str=lrc.split(\"[\");\n //str[0]=\"\"\n //str[1]=\"xx:xx.xx]lyrics1\"\n //str[2]=\"yy:yy.yy]lyrics2\"\n //Skip str[0]\n for(var i=1;i<str.length;i++)\n {\n //str[i] format is 00:11.22]x\n //time format is 00:11.22\n var time=str[i].split(']')[0];\n //lyrics format is \"x\"\n var lyrics=str[i].split(']')[1];\n var minute=time.split(\":\")[0];\n var second=time.split(\":\")[1];\n //xx:xx.xx is converted into total seconds\n var sec=parseInt(minute)*60+parseInt(second);\n //save total seconds\n timeArray[i-1]=sec-sessionStorage.time;\n //save lyrics\n lyricsArray[i-1]=lyrics;\n }\n var allLyrics=document.getElementById(\"poemContent\");\n var counter = 0;\n for(var i=0;i<timeArray.length;i++) {\n allLyrics.innerHTML += '<p class=\"sentence\" id=\"' + i + '\">' + lyricsArray[i] + '</p>';\n\n }\n\n\n}",
"function freqNoteMatch(freqArray,minFrequency,maxFrequency,C_0){\n\n // freqArray: an array of constituent FFT frequencies. (Fmax = samplingRate / 2 ... Nyquist Theorem)\n\n // minFrequency: the lower bound of the frequency range we seek to analyze. \n\n // maxFrequency: the upper bound of the frequency rage under analysis. \n\n // centralFreq; The central frequency. Aka A0. The frequncy about which our musical alphabet is constructed. \n\n // Trim down freqArray to the frequency range under analysis. \n var minFftIndex = freqArray.findIndex(x => x >= minFrequency);\n var maxFftIndex = freqArray.findIndex(x => x > maxFrequency) - 1; \n freqArray = freqArray.slice(minFftIndex,maxFftIndex+1); \n\n // Frequencies which correspond to 'Notes': \n var toneArray = freqToNotes(C_0,maxFrequency); \n\n // Variables for subsequent iterative calculation: \n var toneIndex = 0; \n var zeroCount = 0; \n var precision = 10; // precision , in cents. There are 1200 cents in an octave. Adjacent tones are buffered by 100 'cents'. \n // With a precision of 10 cents, we ensure at minimum and 80 'cent' gap Between tones. \n\n\n // Determine the 'tonal range' within a given precision: \n var tMin = toneArray[toneIndex] * Math.pow( 2, (-precision)/1200 ); // THESE ARE FREQUENCIES. \n var tMax = toneArray[toneIndex] * Math.pow( 2, precision/1200 );\n\n\n // Ouptut bins: \n var freq2Tone = [],\n freqHues = [], \n octaveStarts = []; \n\n // Performing calculations: \n for( let i = 0; i < freqArray.length; i ++){\n\n // Convert the frequency to a 'step number', n, which used to convert frequency to color. \n // It is also used ot match frequency to 'Note' (e.g. 440 --> A). Consider the following: \n \n /**\n Our frequency array is linearly spaced. And the relationship between frequency and steps is\n and exponential one, of base a. (exponential is based on sequentual mutiplication; linear is \n sequential addition). \n\n fn = f0 * (a)n \n \n where n is step distnace away from the 'central frequency', f0, which corresponds to our \n middle A, a note that belts out at 440 Hz. Oh, and: \n\n a = 2 ** (1/12)\n\n In non-math terms, each octave is a 2 ** x Hz wide, consisting of 12 'bins' of increasing width width\n x being an integer.\n\n Oh, and on a similar note. If we wish to make all the octaves of equal length, we need to space our frequency \n axis logarithmically, which sort-of 'compensates' for the exponential spacing of notes WRT frequency. \n **/\n\n // Accordingly, we can convert frequencies into n's for a given a 'central frequency' (i.e. f0)\n // via the freqToTone() function. \n\n var n = freqToTone (freqArray[i],C_0); \n\n // Once we have an n, slap it on the freqHues array. \n // I call them hues here because we can think in terms of color. the remainder of the 'hue', or n, value\n // with respect to 12 will yield a color corresponding to one our of 12 (western chromatic tones). \n freqHues.push(n); \n\n // This is updated everytime we switch to another tone: \n if(freqArray[i] >= tMax && toneIndex < toneArray.length-1){\n toneIndex += 1;\n let f = toneArray[toneIndex]; \n tMin = f * Math.pow( 2, (-precision)/1200 );\n tMax = f * Math.pow( 2, precision/1200 );\n }\n\n // See if the given interative frequency, freqArray[i], is within our current 'tonal range': \n if(freqArray[i] >= tMin && freqArray[i] < tMax){\n // If this is being executed, freqArray[i], corresponds to a tone of interest, a note! \n var remainder = Math.round(n) % 12; \n if(remainder < 0){\n remainder = remainder + 12; \n }\n else if((remainder == 0 && i == 0) || (remainder == 0 && freq2Tone[i-1] == -1)){\n octaveStarts.push(i); \n }\n freq2Tone.push(remainder);\n }\n else{\n freq2Tone.push(-1)\n zeroCount += 1; \n }\n }\n\n // Loop through frequency array is done; prepare output!\n var freqObj = {}; \n\n // Below is an array of frequencies, the trimmed freqArray!\n freqObj.freqs = freqArray; \n\n // Below is an array of integers, the integers corresponding to notes, e.g. 1 -> A.\n freqObj.tones = freq2Tone; \n\n //Below is the frequency array mapped to 'intervalic steps', or n-values. \n freqObj.hues = freqHues; \n\n // Determine the octave start points. \n\n // THIS ARRAY IS SLICED BECAUSE? _____________! (WE THIS NEEDS A RESOLUTION)\n octaveStarts = octaveStarts.slice(2);\n freqObj.octaveStarts = octaveStarts; \n\n // And the pure tone array: \n freqObj.pureToneArray = toneArray; \n\n // And attach the min and max indices: \n freqObj.minFftIndex = minFftIndex; \n freqObj.maxFftIndex = maxFftIndex; \n\n // OUT: \n return freqObj; \n}",
"function MidiFile(data) {\n function readChunk(stream) {\n var id = stream.read(4);\n var length = stream.readInt32();\n return {\n 'id': id,\n 'length': length,\n 'data': stream.read(length)\n };\n }\n \n var lastEventTypeByte;\n \n function readEvent(stream) {\n var event = {};\n event.deltaTime = stream.readVarInt();\n var eventTypeByte = stream.readInt8();\n if ((eventTypeByte & 0xf0) == 0xf0) {\n /* system / meta event */\n if (eventTypeByte == 0xff) {\n /* meta event */\n event.type = 'meta';\n var subtypeByte = stream.readInt8();\n var length = stream.readVarInt();\n switch(subtypeByte) {\n case 0x00:\n event.subtype = 'sequenceNumber';\n if (length != 2) throw \"Expected length for sequenceNumber event is 2, got \" + length;\n event.number = stream.readInt16();\n return event;\n case 0x01:\n event.subtype = 'text';\n event.text = stream.read(length);\n return event;\n case 0x02:\n event.subtype = 'copyrightNotice';\n event.text = stream.read(length);\n return event;\n case 0x03:\n event.subtype = 'trackName';\n event.text = stream.read(length);\n return event;\n case 0x04:\n event.subtype = 'instrumentName';\n event.text = stream.read(length);\n return event;\n case 0x05:\n event.subtype = 'lyrics';\n event.text = stream.read(length);\n return event;\n case 0x06:\n event.subtype = 'marker';\n event.text = stream.read(length);\n return event;\n case 0x07:\n event.subtype = 'cuePoint';\n event.text = stream.read(length);\n return event;\n case 0x20:\n event.subtype = 'midiChannelPrefix';\n if (length != 1) throw \"Expected length for midiChannelPrefix event is 1, got \" + length;\n event.channel = stream.readInt8();\n return event;\n case 0x2f:\n event.subtype = 'endOfTrack';\n if (length != 0) throw \"Expected length for endOfTrack event is 0, got \" + length;\n return event;\n case 0x51:\n event.subtype = 'setTempo';\n if (length != 3) throw \"Expected length for setTempo event is 3, got \" + length;\n event.microsecondsPerBeat = (\n (stream.readInt8() << 16)\n + (stream.readInt8() << 8)\n + stream.readInt8()\n )\n return event;\n case 0x54:\n event.subtype = 'smpteOffset';\n if (length != 5) throw \"Expected length for smpteOffset event is 5, got \" + length;\n var hourByte = stream.readInt8();\n event.frameRate = {\n 0x00: 24, 0x20: 25, 0x40: 29, 0x60: 30\n }[hourByte & 0x60];\n event.hour = hourByte & 0x1f;\n event.min = stream.readInt8();\n event.sec = stream.readInt8();\n event.frame = stream.readInt8();\n event.subframe = stream.readInt8();\n return event;\n case 0x58:\n event.subtype = 'timeSignature';\n if (length != 4) throw \"Expected length for timeSignature event is 4, got \" + length;\n event.numerator = stream.readInt8();\n event.denominator = Math.pow(2, stream.readInt8());\n event.metronome = stream.readInt8();\n event.thirtyseconds = stream.readInt8();\n return event;\n case 0x59:\n event.subtype = 'keySignature';\n if (length != 2) throw \"Expected length for keySignature event is 2, got \" + length;\n event.key = stream.readInt8(true);\n event.scale = stream.readInt8();\n return event;\n case 0x7f:\n event.subtype = 'sequencerSpecific';\n event.data = stream.read(length);\n return event;\n default:\n // console.log(\"Unrecognised meta event subtype: \" + subtypeByte);\n event.subtype = 'unknown'\n event.data = stream.read(length);\n return event;\n }\n event.data = stream.read(length);\n return event;\n } else if (eventTypeByte == 0xf0) {\n event.type = 'sysEx';\n var length = stream.readVarInt();\n event.data = stream.read(length);\n return event;\n } else if (eventTypeByte == 0xf7) {\n event.type = 'dividedSysEx';\n var length = stream.readVarInt();\n event.data = stream.read(length);\n return event;\n } else {\n throw \"Unrecognised MIDI event type byte: \" + eventTypeByte;\n }\n } else {\n /* channel event */\n var param1;\n if ((eventTypeByte & 0x80) == 0) {\n /* running status - reuse lastEventTypeByte as the event type.\n eventTypeByte is actually the first parameter\n */\n param1 = eventTypeByte;\n eventTypeByte = lastEventTypeByte;\n } else {\n param1 = stream.readInt8();\n lastEventTypeByte = eventTypeByte;\n }\n var eventType = eventTypeByte >> 4;\n event.channel = eventTypeByte & 0x0f;\n event.type = 'channel';\n switch (eventType) {\n case 0x08:\n event.subtype = 'noteOff';\n event.noteNumber = param1;\n event.velocity = stream.readInt8();\n return event;\n case 0x09:\n event.noteNumber = param1;\n event.velocity = stream.readInt8();\n if (event.velocity == 0) {\n event.subtype = 'noteOff';\n } else {\n event.subtype = 'noteOn';\n }\n return event;\n case 0x0a:\n event.subtype = 'noteAftertouch';\n event.noteNumber = param1;\n event.amount = stream.readInt8();\n return event;\n case 0x0b:\n event.subtype = 'controller';\n event.controllerType = param1;\n event.value = stream.readInt8();\n return event;\n case 0x0c:\n event.subtype = 'programChange';\n event.programNumber = param1;\n return event;\n case 0x0d:\n event.subtype = 'channelAftertouch';\n event.amount = param1;\n return event;\n case 0x0e:\n event.subtype = 'pitchBend';\n event.value = param1 + (stream.readInt8() << 7);\n return event;\n default:\n throw \"Unrecognised MIDI event type: \" + eventType\n /* \n console.log(\"Unrecognised MIDI event type: \" + eventType);\n stream.readInt8();\n event.subtype = 'unknown';\n return event;\n */\n }\n }\n }\n \n stream = Stream(data);\n var headerChunk = readChunk(stream);\n if (headerChunk.id != 'MThd' || headerChunk.length != 6) {\n throw \"Bad .mid file - header not found\";\n }\n var headerStream = Stream(headerChunk.data);\n var formatType = headerStream.readInt16();\n var trackCount = headerStream.readInt16();\n var timeDivision = headerStream.readInt16();\n \n if (timeDivision & 0x8000) {\n throw \"Expressing time division in SMTPE frames is not supported yet\"\n } else {\n ticksPerBeat = timeDivision;\n }\n \n var header = {\n 'formatType': formatType,\n 'trackCount': trackCount,\n 'ticksPerBeat': ticksPerBeat\n }\n var tracks = [];\n for (var i = 0; i < header.trackCount; i++) {\n tracks[i] = [];\n var trackChunk = readChunk(stream);\n if (trackChunk.id != 'MTrk') {\n throw \"Unexpected chunk - expected MTrk, got \"+ trackChunk.id;\n }\n var trackStream = Stream(trackChunk.data);\n while (!trackStream.eof()) {\n var event = readEvent(trackStream);\n tracks[i].push(event);\n //console.log(event);\n }\n }\n \n return {\n 'header': header,\n 'tracks': tracks\n }\n}",
"function normalizeMeasures(part) {\n const measuresLengths = part.measures.map(a => a.beat.length);\n console.log(\"12121212121212122\", measuresLengths);\n const lcmOfBeatLength = Util.lcm(...measuresLengths);\n // 1.转换成对0 2.把track内所有小节beat统一长度\n\n // 不能用foreach,foreach会直接bypass掉empty的(稀疏数组遍历)\n // part.measures.forEach((measure, measureIndex) => {});\n for (\n let measureIndex = 0;\n measureIndex <= part.measures.length - 1;\n measureIndex += 1\n ) {\n // console.log(\"measure::::::::::\", part.measures[measureIndex]);\n if (!part.measures[measureIndex]) {\n //建一个空小节\n //potential bug here\n part.measures[measureIndex] = {\n measure: measureIndex + 1,\n sequence: \"\",\n beat: Util.createUnderScores(lcmOfBeatLength),\n matchZero: true\n };\n } else {\n // 对位处理成对0\n if (!part.measures[measureIndex].matchZero) {\n // 对位转成对0,抽出对应的音//potential bug here, super mario....seemingly solved\n // const sequenceArray = JSON.parse(\n // `[${part.measures[measureIndex].sequence}]`.replace(\n // /([ABCDEFG]#*b*[1-9])/g,\n // '\"$1\"'\n // )\n // );\n let newSeqArray = part.measures[measureIndex].beat\n .split(\"\")\n .map((beatDigit, index) => {\n if (beatDigit.match(/\\d/g)) {\n return part.measures[measureIndex].sequence[index];\n } else {\n return \"\";\n }\n });\n newSeqArray = newSeqArray.filter(seq => !!seq); // 排掉空的\n console.log(\"bbbbbbbbbbb\", newSeqArray);\n\n // TO FIX HERE!!!\n // let s = JSON.stringify(newSeqArray.filter(note => note != \"\")).replace(\n // /\"/g,\n // \"\"\n // );\n // s = s.substring(1, s.length - 1); // 去掉数组的前后方括号\n // part.measures[measureIndex].sequence = s;\n part.measures[measureIndex].sequence = newSeqArray;\n part.measures[measureIndex].matchZero = true;\n }\n // console.log(\"jjjjjjjjjjjjjj\", part.measures[measureIndex].sequence);\n //对0的,beat延展就行了,原来000的可能变成0--0--0-- (根据最小公倍数)\n if (part.measures[measureIndex].beat.length < lcmOfBeatLength) {\n const ratio = lcmOfBeatLength / part.measures[measureIndex].beat.length;\n // console.log(\"[][][]\");\n // console.log(lcmOfBeatLength);\n // console.log(part.measures[measureIndex].beat.length);\n const append = Util.createScores(ratio - 1);\n part.measures[measureIndex].beat = part.measures[measureIndex].beat\n .split(\"\")\n .join(append);\n part.measures[measureIndex].beat += append;\n }\n }\n }\n\n console.log(\"=== measure after normalization===\");\n console.log(part.measures);\n\n //把所有measure合成一大段 应了老话「不要看小节线」\n part.tonepart = part.measures.reduce((a, b) => {\n // console.log(\"?\", a.sequence);\n return {\n // potential bug: if a/b is empty string, no comma here, seemingly solved\n // sequence: `${a.sequence}${a.sequence && b.sequence ? \",\" : \"\"}${\n // b.sequence\n // }`,\n sequence: a.sequence.concat(b.sequence),\n beat: `${a.beat}${b.beat}`\n };\n });\n console.log(\"=== final part in this part ===\");\n console.log(part.tonepart);\n}",
"function Note(o) {\n if (!(this instanceof Note)) {\n throw Error(\"Use new Note()\");\n }\n var pos = o.pos;\n if (pos === undefined) {\n var octave = validateRange(o.octave, 0, 8);\n var note = validateRange(o.note, 0, 7);\n pos = octave * 7 + note;\n }\n this._pos = validateRange(pos, 0, 56); // C8\n if (o.mod !== undefined) {\n this._mod = validateRange(o.mod, Note.FLAT, Note.SHARP);\n }\n else {\n // Figure the mod based on the pitch\n var pitch = validateRange(o.pitch, 0, 96); // C8\n var naturalPitch = new Note({pos: this._pos, mod: Note.NATURAL}).pitch();\n this._mod = validateRante(pitch - naturalPitch, Note.FLAT, Note.SHARP);\n }\n}",
"function InlineParser() {\n this.preEmphasis = \" \\t\\\\('\\\"\";\n this.postEmphasis = \"- \\t.,:!?;'\\\"\\\\)\";\n this.borderForbidden = \" \\t\\r\\n,\\\"'\";\n this.bodyRegexp = \"[\\\\s\\\\S]*?\";\n this.markers = \"*/_=~+\";\n\n this.emphasisPattern = this.buildEmphasisPattern();\n this.linkPattern = /\\[\\[([^\\]]*)\\](?:\\[([^\\]]*)\\])?\\]/g; // \\1 => link, \\2 => text\n\n // this.clockLinePattern =/^\\s*CLOCK:\\s*\\[[-0-9]+\\s+.*\\d:\\d\\d\\]/;\n // NOTE: this is a weak pattern. does not enforce lookahead of opening bracket type!\n this.timestampPattern =/([\\[<])(\\d{4}-\\d{2}-\\d{2})(?:\\s*([A-Za-z]+)\\s*)(\\d{2}:\\d{2})?([\\]>])/g;\n this.macroPattern = /{{{([A-Za-z]\\w*)\\(([^})]*?)\\)}}}/g;\n }",
"parseHeader() {\n\t\tif (this.fetchString(4) === 'MThd') { /* console.log('MThd'); */\n\t\t} else {\n\t\t\tconsole.log('ERROR: No MThd');\n\t\t\tthis.error = { code: 1, pos: ppos, msg: 'No MIDI header detected.' };\n\t\t\treturn;\n\t\t}\n\t\tif (this.fetchBytes(4) !== 6) {\n\t\t\tconsole.log('ERROR: File header is not 6 bytes long.');\n\t\t\tthis.error = { code: 2, pos: ppos, msg: 'Unrecognized MIDI header length.' };\n\t\t\treturn;\n\t\t}\n\t\tthis.fmt = this.fetchBytes(2);\n\t\tif (this.fmt > 2) {\n\t\t\tconsole.log('ERROR: Unrecognized format number.');\n\t\t\tthis.error = { code: 3, pos: ppos, msg: 'Unrecognized MIDI format number.' };\n\t\t}\n\t\tthis.ntrks = this.fetchBytes(2);\n\t\t// console.log('Format '+this.fmt+', '+this.ntrks+' tracks');\n\n\t\t// Parse timing division\n\t\tlet tdiv = this.fetchBytes(2);\n\t\tif (!(tdiv >> 16)) {\n\t\t\t// console.log(tdiv+' ticks per quarter note');\n\t\t\tthis.timing = tdiv;\n\t\t} else {\n\t\t\tconsole.log('SMPTE timing format is unsupported.');\n\t\t\talert('SMPTE timing format is currently unsupported. Please give feedback if you see this message.');\n\t\t\tthis.timingFormat = 1;\n\t\t}\n\t}",
"function processMostUniqueWords(songs) {\n // we will need to process lyric sections in the same way as part II \n // next we will need to process lyric sections for unique words \n // we will need two additional fields in our store for this section: \n // we will need to store the lyric sections\n // we will also need to store the unique words count \n const artistAttributions = [];\n const artistLyrics = [];\n songs.map(song => {\n // go through the lyrics_text and break out into lyric sections \n const lyricText = song.lyrics_text.split('\\n\\n');\n // go through each item in the array of lyric sections and sanitize the data for more artist attributions \n lyricText.map(section => {\n // now we are at the lyric section level for each song\n // we want to properly attribute a section to the artist or artists who sing it\n // we need to sanitize the string and return an array of artist(s)\n const regex = /\\[(.*?)\\]/g;\n const sectionAttribution = section.match(/\\[(.*?)\\]/g);\n const sectionLyricsSeparated = section.replace(regex, '');\n // console.log({sectionLyricsSeparated});\n // console.log({sectionAttribution});\n \n const attributionsHeadersSeparated = sectionAttribution[0].split(':');\n if (attributionsHeadersSeparated.length == 1) {\n // if length equals 1 it means there is no additional attribution on this section and we can attribute it to the primary_artist \n artistAttributions.push(song.primary_artist);\n artistLyrics.push({\n artistName: song.primary_artist,\n artistLyrics: sectionLyricsSeparated\n });\n\n \n } else {\n // else continue to find artists in headers \n const artistStr = attributionsHeadersSeparated[1].replace(/]/i, '');\n const artistStr2 = artistStr.replace(/Both/i, '');\n // noticed there were occurrences of the word Both throughout some of the data \n\n const headersStripped = artistStr2\n .split(',').join('').split('+').join('').split('&')\n // TODO: super ugly ^ go back and fix this \n headersStripped.map(artist => {\n artistAttributions.push(artist.trim())\n const trimmedName = artist.trim();\n let obj = {\n artistName: trimmedName,\n artistLyrics: sectionLyricsSeparated\n }\n artistLyrics.push(obj);\n \n });\n\n\n }\n\n\n });\n });\n // console.log(artistAttributions);\n console.log(artistLyrics);\n\n // assignLyricSectionToArtist(artistAttributions);\n // assignLyricTextToArtist(artistLyrics);\n\n}",
"function AbcParseHeader(tokenizer, warn, multilineVars, tune) {\n var key1sharp = {\n acc: 'sharp',\n note: 'f'\n };\n var key2sharp = {\n acc: 'sharp',\n note: 'c'\n };\n var key3sharp = {\n acc: 'sharp',\n note: 'g'\n };\n var key4sharp = {\n acc: 'sharp',\n note: 'd'\n };\n var key5sharp = {\n acc: 'sharp',\n note: 'A'\n };\n var key6sharp = {\n acc: 'sharp',\n note: 'e'\n };\n var key7sharp = {\n acc: 'sharp',\n note: 'B'\n };\n var key1flat = {\n acc: 'flat',\n note: 'B'\n };\n var key2flat = {\n acc: 'flat',\n note: 'e'\n };\n var key3flat = {\n acc: 'flat',\n note: 'A'\n };\n var key4flat = {\n acc: 'flat',\n note: 'd'\n };\n var key5flat = {\n acc: 'flat',\n note: 'G'\n };\n var key6flat = {\n acc: 'flat',\n note: 'c'\n };\n var key7flat = {\n acc: 'flat',\n note: 'f'\n };\n\n key_signatures = {\n 'C#': [key1sharp, key2sharp, key3sharp, key4sharp, key5sharp, key6sharp, key7sharp],\n 'A#m': [key1sharp, key2sharp, key3sharp, key4sharp, key5sharp, key6sharp, key7sharp],\n 'G#Mix': [key1sharp, key2sharp, key3sharp, key4sharp, key5sharp, key6sharp, key7sharp],\n 'D#Dor': [key1sharp, key2sharp, key3sharp, key4sharp, key5sharp, key6sharp, key7sharp],\n 'E#Phr': [key1sharp, key2sharp, key3sharp, key4sharp, key5sharp, key6sharp, key7sharp],\n 'F#Lyd': [key1sharp, key2sharp, key3sharp, key4sharp, key5sharp, key6sharp, key7sharp],\n 'B#Loc': [key1sharp, key2sharp, key3sharp, key4sharp, key5sharp, key6sharp, key7sharp],\n\n 'F#': [key1sharp, key2sharp, key3sharp, key4sharp, key5sharp, key6sharp],\n 'D#m': [key1sharp, key2sharp, key3sharp, key4sharp, key5sharp, key6sharp],\n 'C#Mix': [key1sharp, key2sharp, key3sharp, key4sharp, key5sharp, key6sharp],\n 'G#Dor': [key1sharp, key2sharp, key3sharp, key4sharp, key5sharp, key6sharp],\n 'A#Phr': [key1sharp, key2sharp, key3sharp, key4sharp, key5sharp, key6sharp],\n 'BLyd': [key1sharp, key2sharp, key3sharp, key4sharp, key5sharp, key6sharp],\n 'E#Loc': [key1sharp, key2sharp, key3sharp, key4sharp, key5sharp, key6sharp],\n\n 'B': [key1sharp, key2sharp, key3sharp, key4sharp, key5sharp],\n 'G#m': [key1sharp, key2sharp, key3sharp, key4sharp, key5sharp],\n 'F#Mix': [key1sharp, key2sharp, key3sharp, key4sharp, key5sharp],\n 'C#Dor': [key1sharp, key2sharp, key3sharp, key4sharp, key5sharp],\n 'D#Phr': [key1sharp, key2sharp, key3sharp, key4sharp, key5sharp],\n 'ELyd': [key1sharp, key2sharp, key3sharp, key4sharp, key5sharp],\n 'A#Loc': [key1sharp, key2sharp, key3sharp, key4sharp, key5sharp],\n\n 'E': [key1sharp, key2sharp, key3sharp, key4sharp],\n 'C#m': [key1sharp, key2sharp, key3sharp, key4sharp],\n 'BMix': [key1sharp, key2sharp, key3sharp, key4sharp],\n 'F#Dor': [key1sharp, key2sharp, key3sharp, key4sharp],\n 'G#Phr': [key1sharp, key2sharp, key3sharp, key4sharp],\n 'ALyd': [key1sharp, key2sharp, key3sharp, key4sharp],\n 'D#Loc': [key1sharp, key2sharp, key3sharp, key4sharp],\n\n 'A': [key1sharp, key2sharp, key3sharp],\n 'F#m': [key1sharp, key2sharp, key3sharp],\n 'EMix': [key1sharp, key2sharp, key3sharp],\n 'BDor': [key1sharp, key2sharp, key3sharp],\n 'C#Phr': [key1sharp, key2sharp, key3sharp],\n 'DLyd': [key1sharp, key2sharp, key3sharp],\n 'G#Loc': [key1sharp, key2sharp, key3sharp],\n\n 'D': [key1sharp, key2sharp],\n 'Bm': [key1sharp, key2sharp],\n 'AMix': [key1sharp, key2sharp],\n 'EDor': [key1sharp, key2sharp],\n 'F#Phr': [key1sharp, key2sharp],\n 'GLyd': [key1sharp, key2sharp],\n 'C#Loc': [key1sharp, key2sharp],\n\n 'G': [key1sharp],\n 'Em': [key1sharp],\n 'DMix': [key1sharp],\n 'ADor': [key1sharp],\n 'BPhr': [key1sharp],\n 'CLyd': [key1sharp],\n 'F#Loc': [key1sharp],\n\n 'C': [],\n 'Am': [],\n 'GMix': [],\n 'DDor': [],\n 'EPhr': [],\n 'FLyd': [],\n 'BLoc': [],\n\n 'F': [key1flat],\n 'Dm': [key1flat],\n 'CMix': [key1flat],\n 'GDor': [key1flat],\n 'APhr': [key1flat],\n 'BbLyd': [key1flat],\n 'ELoc': [key1flat],\n\n 'Bb': [key1flat, key2flat],\n 'Gm': [key1flat, key2flat],\n 'FMix': [key1flat, key2flat],\n 'CDor': [key1flat, key2flat],\n 'DPhr': [key1flat, key2flat],\n 'EbLyd': [key1flat, key2flat],\n 'ALoc': [key1flat, key2flat],\n\n 'Eb': [key1flat, key2flat, key3flat],\n 'Cm': [key1flat, key2flat, key3flat],\n 'BbMix': [key1flat, key2flat, key3flat],\n 'FDor': [key1flat, key2flat, key3flat],\n 'GPhr': [key1flat, key2flat, key3flat],\n 'AbLyd': [key1flat, key2flat, key3flat],\n 'DLoc': [key1flat, key2flat, key3flat],\n\n 'Ab': [key1flat, key2flat, key3flat, key4flat],\n 'Fm': [key1flat, key2flat, key3flat, key4flat],\n 'EbMix': [key1flat, key2flat, key3flat, key4flat],\n 'BbDor': [key1flat, key2flat, key3flat, key4flat],\n 'CPhr': [key1flat, key2flat, key3flat, key4flat],\n 'DbLyd': [key1flat, key2flat, key3flat, key4flat],\n 'GLoc': [key1flat, key2flat, key3flat, key4flat],\n\n 'Db': [key1flat, key2flat, key3flat, key4flat, key5flat],\n 'Bbm': [key1flat, key2flat, key3flat, key4flat, key5flat],\n 'AbMix': [key1flat, key2flat, key3flat, key4flat, key5flat],\n 'EbDor': [key1flat, key2flat, key3flat, key4flat, key5flat],\n 'FPhr': [key1flat, key2flat, key3flat, key4flat, key5flat],\n 'GgLyd': [key1flat, key2flat, key3flat, key4flat, key5flat],\n 'CLoc': [key1flat, key2flat, key3flat, key4flat, key5flat],\n\n 'Gb': [key1flat, key2flat, key3flat, key4flat, key5flat, key6flat],\n 'Ebm': [key1flat, key2flat, key3flat, key4flat, key5flat, key6flat],\n 'DbMix': [key1flat, key2flat, key3flat, key4flat, key5flat, key6flat],\n 'AbDor': [key1flat, key2flat, key3flat, key4flat, key5flat, key6flat],\n 'BbPhr': [key1flat, key2flat, key3flat, key4flat, key5flat, key6flat],\n 'CbLyd': [key1flat, key2flat, key3flat, key4flat, key5flat, key6flat],\n 'FLoc': [key1flat, key2flat, key3flat, key4flat, key5flat, key6flat],\n\n 'Cb': [key1flat, key2flat, key3flat, key4flat, key5flat, key6flat, key7flat],\n 'Abm': [key1flat, key2flat, key3flat, key4flat, key5flat, key6flat, key7flat],\n 'GbMix': [key1flat, key2flat, key3flat, key4flat, key5flat, key6flat, key7flat],\n 'DbDor': [key1flat, key2flat, key3flat, key4flat, key5flat, key6flat, key7flat],\n 'EbPhr': [key1flat, key2flat, key3flat, key4flat, key5flat, key6flat, key7flat],\n 'FbLyd': [key1flat, key2flat, key3flat, key4flat, key5flat, key6flat, key7flat],\n 'BbLoc': [key1flat, key2flat, key3flat, key4flat, key5flat, key6flat, key7flat],\n\n // The following are not in the 2.0 spec, but seem normal enough.\n // TODO-PER: These SOUND the same as what's written, but they aren't right\n 'A#': [key1flat, key2flat],\n 'B#': [],\n 'D#': [key1flat, key2flat, key3flat],\n 'E#': [key1flat],\n 'G#': [key1flat, key2flat, key3flat, key4flat]\n };\n\n var calcMiddle = function(clef, oct) {\n var mid = 0;\n switch (clef) {\n case 'treble':\n case 'none':\n case 'treble+8':\n case 'treble-8':\n break;\n case 'bass3':\n case 'bass':\n case 'bass+8':\n case 'bass-8':\n case 'bass+16':\n case 'bass-16':\n mid = -12;\n break;\n case 'tenor':\n mid = -8;\n break;\n case 'alto2':\n case 'alto1':\n case 'alto':\n case 'alto+8':\n case 'alto-8':\n mid = -6;\n break;\n }\n return mid + oct;\n };\n\n this.deepCopyKey = function(key) {\n var ret = {\n accidentals: []\n };\n key.each(function(k) {\n ret.accidentals.push(Object.clone(k));\n });\n return ret;\n };\n\n var pitches = {\n A: 5,\n B: 6,\n C: 0,\n D: 1,\n E: 2,\n F: 3,\n G: 4,\n a: 12,\n b: 13,\n c: 7,\n d: 8,\n e: 9,\n f: 10,\n g: 11\n };\n\n this.addPosToKey = function(clef, key) {\n // Shift the key signature from the treble positions to whatever position is needed for the clef.\n // This may put the key signature unnaturally high or low, so if it does, then shift it.\n var mid = clef.verticalPos;\n key.accidentals.each(function(acc) {\n var pitch = pitches[acc.note];\n pitch = pitch - mid;\n acc.verticalPos = pitch;\n });\n if (mid < -10) {\n key.accidentals.each(function(acc) {\n acc.verticalPos -= 14;\n });\n } else if (mid < -4) {\n key.accidentals.each(function(acc) {\n acc.verticalPos -= 7;\n });\n }\n };\n\n this.fixKey = function(clef, key) {\n var fixedKey = Object.clone(key);\n this.addPosToKey(clef, fixedKey);\n return fixedKey;\n };\n\n var parseMiddle = function(str) {\n var mid = pitches[str.charAt(0)];\n for (var i = 1; i < str.length; i++) {\n if (str.charAt(i) === ',') mid -= 7;\n else if (str.charAt(i) === ',') mid += 7;\n }\n return mid - 6; // We get the note in the middle of the staff. We want the note that appears as the first ledger line below the staff.\n };\n\n this.parseKey = function(str) // (and clef)\n {\n str = tokenizer.stripComment(str);\n var origStr = str;\n if (str.length === 0) {\n // an empty K: field is the same as K:none\n str = 'none';\n }\n // The format is:\n // [space][tonic[#|b][ ][3-letter-mode][ignored-chars][space]][ accidentals...][ clef=treble|bass|bass3|tenor|alto|alto2|alto1|none [+8|-8]]\n // -- or -- the key can be \"none\"\n // First get the key letter: turn that into a index into the key array (0-11)\n // Then see if there is a sharp or flat. Increment or decrement.\n // Then see if there is a mode modifier. Add or subtract to the index.\n // Then do a mod 12 on the index and return the key.\n // TODO: This may leave unparsed characters at the end after something reasonable was found.\n\n var setMiddle = function(str) {\n var i = tokenizer.skipWhiteSpace(str);\n str = str.substring(i);\n if (str.startsWith('m=') || str.startsWith('middle=')) {\n str = str.substring(str.indexOf('=') + 1);\n multilineVars.clef.verticalPos = parseMiddle(str);\n }\n };\n // check first to see if there is only a clef. If so, just take that, but ignore an error after that.\n var retClef = tokenizer.getClef(str);\n if (retClef.token !== undefined && (retClef.explicit === true || retClef.token !== 'none')) { // none is the only ambiguous marking. We need to assume that's a key\n multilineVars.clef = {\n type: retClef.token,\n verticalPos: calcMiddle(retClef.token, 0)\n };\n str = str.substring(retClef.len);\n setMiddle(str);\n return {\n foundClef: true\n };\n }\n\n var ret = {};\n\n var retPitch = tokenizer.getKeyPitch(str);\n if (retPitch.len > 0) {\n var key = retPitch.token;\n str = str.substring(retPitch.len);\n // We got a pitch to start with, so we might also have an accidental and a mode\n var retAcc = tokenizer.getSharpFlat(str);\n if (retAcc.len > 0) {\n key += retAcc.token;\n str = str.substring(retAcc.len);\n }\n var retMode = tokenizer.getMode(str);\n if (retMode.len > 0) {\n key += retMode.token;\n str = str.substring(retMode.len);\n }\n // We need to do a deep copy because we are going to modify it\n ret = this.deepCopyKey(key_signatures[key]);\n } else if (str.startsWith('HP')) {\n this.addDirective(\"bagpipes\");\n ret.accidentals = [];\n multilineVars.key = ret;\n return {\n foundKey: true\n };\n } else if (str.startsWith('Hp')) {\n ret.accidentals = [{\n acc: 'natural',\n note: 'g'\n }, {\n acc: 'sharp',\n note: 'f'\n }, {\n acc: 'sharp',\n note: 'c'\n }];\n this.addDirective(\"bagpipes\");\n multilineVars.key = ret;\n return {\n foundKey: true\n };\n } else {\n var retNone = tokenizer.isMatch(str, 'none');\n if (retNone > 0) {\n // we got the none key - that's the same as C to us\n ret.accidentals = [];\n str = str.substring(retNone);\n }\n }\n // There are two special cases of deprecated syntax. Ignore them if they occur\n var j = tokenizer.skipWhiteSpace(str);\n str = str.substring(j);\n if (str.startsWith('exp') || str.startsWith('oct'))\n str = str.substring(3);\n\n // now see if there are extra accidentals\n var done = false;\n while (!done) {\n var retExtra = tokenizer.getKeyAccidental(str);\n if (retExtra.len === 0)\n done = true;\n else {\n str = str.substring(retExtra.len);\n if (retExtra.warn)\n warn(\"error parsing extra accidentals:\", origStr, 0);\n else {\n if (!ret.accidentals)\n ret.accidentals = [];\n ret.accidentals.push(retExtra.token);\n }\n }\n }\n\n // now see if there is a clef\n retClef = tokenizer.getClef(str);\n if (retClef.len > 0) {\n if (retClef.warn)\n warn(\"error parsing clef:\" + retClef.warn, origStr, 0);\n else {\n //ret.clef = retClef.token;\n multilineVars.clef = {\n type: retClef.token,\n verticalPos: calcMiddle(retClef.token, 0)\n };\n str = str.substring(retClef.len);\n setMiddle(str);\n }\n }\n\n if (ret.accidentals === undefined && retClef.token === undefined) {\n warn(\"error parsing key: \", origStr, 0);\n return {};\n }\n var result = {};\n if (retClef.token !== undefined)\n result.foundClef = true;\n if (ret.accidentals !== undefined) {\n // Adjust the octave of the accidentals, if necessary\n ret.accidentals.each(function(acc) {\n if (retClef.token === 'bass') {\n //if (acc.note === 'A') acc.note = 'a';\n //if (acc.note === 'B') acc.note = 'b';\n if (acc.note === 'C') acc.note = 'c';\n if (acc.note === 'D' && acc.acc !== 'flat') acc.note = 'd';\n if (acc.note === 'E' && acc.acc !== 'flat') acc.note = 'e';\n if (acc.note === 'F' && acc.acc !== 'flat') acc.note = 'f';\n if (acc.note === 'G' && acc.acc !== 'flat') acc.note = 'g';\n } else {\n if (acc.note === 'a') acc.note = 'A';\n if (acc.note === 'b') acc.note = 'B';\n if (acc.note === 'C') acc.note = 'c';\n }\n });\n multilineVars.key = ret;\n result.foundKey = true;\n }\n return result;\n };\n\n this.addDirective = function(str) {\n var oneParameterMeasurement = function(cmd, tokens) {\n var points = tokenizer.getMeasurement(tokens);\n if (points.used === 0 || tokens.length !== 0)\n return \"Directive \\\"\" + cmd + \"\\\" requires a measurement as a parameter.\";\n tune.formatting[cmd] = points.value;\n return null;\n };\n var getFontParameter = function(tokens) {\n var font = {};\n var token = tokens.last();\n if (token.type === 'number') {\n font.size = parseInt(token.token);\n tokens.pop();\n }\n if (tokens.length > 0) {\n var scratch = \"\";\n tokens.each(function(tok) {\n if (tok.token !== '-') {\n if (scratch.length > 0) scratch += ' ';\n scratch += tok.token;\n }\n });\n font.font = scratch;\n }\n return font;\n };\n var getChangingFont = function(cmd, tokens) {\n if (tokens.length === 0)\n return \"Directive \\\"\" + cmd + \"\\\" requires a font as a parameter.\";\n multilineVars[cmd] = getFontParameter(tokens);\n return null;\n };\n var getGlobalFont = function(cmd, tokens) {\n if (tokens.length === 0)\n return \"Directive \\\"\" + cmd + \"\\\" requires a font as a parameter.\";\n tune.formatting[cmd] = getFontParameter(tokens);\n return null;\n };\n\n var tokens = tokenizer.tokenize(str, 0, str.length); // 3 or more % in a row, or just spaces after %% is just a comment\n if (tokens.length === 0 || tokens[0].type !== 'alpha') return null;\n var restOfString = str.substring(str.indexOf(tokens[0].token) + tokens[0].token.length);\n restOfString = tokenizer.stripComment(restOfString);\n var cmd = tokens.shift().token.toLowerCase();\n var num;\n var scratch = \"\";\n switch (cmd) {\n // The following directives were added to abc_parser_lint, but haven't been implemented here.\n // Most of them are direct translations from the directives that will be parsed in. See abcm2ps's format.txt for info on each of these.\n //\t\t\t\t\talignbars: { type: \"number\", optional: true },\n //\t\t\t\t\taligncomposer: { type: \"string\", Enum: [ 'left', 'center','right' ], optional: true },\n //\t\t\t\t\tannotationfont: fontType,\n //\t\t\t\t\tbarsperstaff: { type: \"number\", optional: true },\n //\t\t\t\t\tbstemdown: { type: \"boolean\", optional: true },\n //\t\t\t\t\tcontinueall: { type: \"boolean\", optional: true },\n //\t\t\t\t\tdynalign: { type: \"boolean\", optional: true },\n //\t\t\t\t\texprabove: { type: \"boolean\", optional: true },\n //\t\t\t\t\texprbelow: { type: \"boolean\", optional: true },\n //\t\t\t\t\tflatbeams: { type: \"boolean\", optional: true },\n //\t\t\t\t\tfooter: { type: \"string\", optional: true },\n //\t\t\t\t\tfooterfont: fontType,\n //\t\t\t\t\tgchordbox: { type: \"boolean\", optional: true },\n //\t\t\t\t\tgraceslurs: { type: \"boolean\", optional: true },\n //\t\t\t\t\tgracespacebefore: { type: \"number\", optional: true },\n //\t\t\t\t\tgracespaceinside: { type: \"number\", optional: true },\n //\t\t\t\t\tgracespaceafter: { type: \"number\", optional: true },\n //\t\t\t\t\theader: { type: \"string\", optional: true },\n //\t\t\t\t\theaderfont: fontType,\n //\t\t\t\t\thistoryfont: fontType,\n //\t\t\t\t\tinfofont: fontType,\n //\t\t\t\t\tinfospace: { type: \"number\", optional: true },\n //\t\t\t\t\tlineskipfac: { type: \"number\", optional: true },\n //\t\t\t\t\tmaxshrink: { type: \"number\", optional: true },\n //\t\t\t\t\tmaxstaffsep: { type: \"number\", optional: true },\n //\t\t\t\t\tmaxsysstaffsep: { type: \"number\", optional: true },\n //\t\t\t\t\tmeasurebox: { type: \"boolean\", optional: true },\n //\t\t\t\t\tmeasurefont: fontType,\n //\t\t\t\t\tnotespacingfactor: { type: \"number\", optional: true },\n //\t\t\t\t\tpageheight: { type: \"number\", optional: true },\n //\t\t\t\t\tpagewidth: { type: \"number\", optional: true },\n //\t\t\t\t\tparskipfac: { type: \"number\", optional: true },\n //\t\t\t\t\tpartsbox: { type: \"boolean\", optional: true },\n //\t\t\t\t\trepeatfont: fontType,\n //\t\t\t\t\trightmargin: { type: \"number\", optional: true },\n //\t\t\t\t\tslurheight: { type: \"number\", optional: true },\n //\t\t\t\t\tsplittune: { type: \"boolean\", optional: true },\n //\t\t\t\t\tsquarebreve: { type: \"boolean\", optional: true },\n //\t\t\t\t\tstemheight: { type: \"number\", optional: true },\n //\t\t\t\t\tstraightflags: { type: \"boolean\", optional: true },\n //\t\t\t\t\tstretchstaff: { type: \"boolean\", optional: true },\n //\t\t\t\t\ttextfont: fontType,\n //\t\t\t\t\ttitleformat: { type: \"string\", optional: true },\n //\t\t\t\t\tvocalabove: { type: \"boolean\", optional: true },\n //\t\t\t\t\tvocalfont: fontType,\n //\t\t\t\t\twordsfont: fontType,\n case \"bagpipes\":\n tune.formatting.bagpipes = true;\n break;\n case \"landscape\":\n tune.formatting.landscape = true;\n break;\n case \"slurgraces\":\n tune.formatting.slurgraces = true;\n break;\n case \"stretchlast\":\n tune.formatting.stretchlast = true;\n break;\n case \"titlecaps\":\n multilineVars.titlecaps = true;\n break;\n case \"titleleft\":\n tune.formatting.titleleft = true;\n break;\n\n case \"botmargin\":\n case \"botspace\":\n case \"composerspace\":\n case \"indent\":\n case \"leftmargin\":\n case \"linesep\":\n case \"musicspace\":\n case \"partsspace\":\n case \"staffsep\":\n case \"staffwidth\":\n case \"subtitlespace\":\n case \"sysstaffsep\":\n case \"systemsep\":\n case \"textspace\":\n case \"titlespace\":\n case \"topmargin\":\n case \"topspace\":\n case \"vocalspace\":\n case \"wordsspace\":\n return oneParameterMeasurement(cmd, tokens);\n case \"scale\":\n scratch = \"\";\n tokens.each(function(tok) {\n scratch += tok.token;\n });\n num = parseFloat(scratch);\n if (isNaN(num) || num === 0)\n return \"Directive \\\"\" + cmd + \"\\\" requires a number as a parameter.\";\n tune.formatting.scale = num;\n break;\n case \"sep\":\n if (tokens.length === 0)\n tune.addSeparator();\n else {\n if (tokens.length !== 3 || tokens[0].type !== 'number' || tokens[1].type !== 'number' || tokens[2].type !== 'number')\n return \"Directive \\\"\" + cmd + \"\\\" requires 3 numbers: space above, space below, length of line\";\n tune.addSeparator(parseInt(tokens[0].token), parseInt(tokens[1].token), parseInt(tokens[2].token));\n }\n break;\n case \"barnumbers\":\n if (tokens.length !== 1 || tokens[0].type !== 'number')\n return \"Directive \\\"\" + cmd + \"\\\" requires a number as a parameter.\";\n multilineVars.barNumbers = parseInt(tokens[0].token);\n break;\n case \"begintext\":\n multilineVars.inTextBlock = true;\n break;\n case \"text\":\n tune.addText(tokenizer.translateString(restOfString)); // display secondary title\n break;\n case \"gchordfont\":\n case \"partsfont\":\n case \"vocalfont\":\n return getChangingFont(cmd, tokens);\n case \"barlabelfont\":\n case \"barnumberfont\":\n case \"composerfont\":\n case \"subtitlefont\":\n case \"tempofont\":\n case \"titlefont\":\n case \"voicefont\":\n return getGlobalFont(cmd, tokens);\n case \"barnumfont\":\n return getGlobalFont(\"barnumberfont\", tokens);\n case \"staves\":\n case \"score\":\n multilineVars.score_is_present = true;\n var addVoice = function(id, newStaff, bracket, brace, continueBar) {\n if (newStaff || multilineVars.staves.length === 0) {\n multilineVars.staves.push({\n index: multilineVars.staves.length,\n numVoices: 0\n });\n }\n var staff = multilineVars.staves.last();\n if (bracket !== undefined) staff.bracket = bracket;\n if (brace !== undefined) staff.brace = brace;\n if (continueBar) staff.connectBarLines = 'end';\n if (multilineVars.voices[id] === undefined) {\n multilineVars.voices[id] = {\n staffNum: staff.index,\n index: staff.numVoices\n };\n staff.numVoices++;\n }\n };\n\n var openParen = false;\n var openBracket = false;\n var openBrace = false;\n var justOpenParen = false;\n var justOpenBracket = false;\n var justOpenBrace = false;\n var continueBar = false;\n var lastVoice = undefined;\n var addContinueBar = function() {\n continueBar = true;\n if (lastVoice) {\n var ty = 'start';\n if (lastVoice.staffNum > 0) {\n if (multilineVars.staves[lastVoice.staffNum - 1].connectBarLines === 'start' ||\n multilineVars.staves[lastVoice.staffNum - 1].connectBarLines === 'continue')\n ty = 'continue';\n }\n multilineVars.staves[lastVoice.staffNum].connectBarLines = ty;\n }\n };\n while (tokens.length) {\n var t = tokens.shift();\n switch (t.token) {\n case '(':\n if (openParen) warn(\"Can't nest parenthesis in %%score\", str, t.start);\n else {\n openParen = true;\n justOpenParen = true;\n }\n break;\n case ')':\n if (!openParen || justOpenParen) warn(\"Unexpected close parenthesis in %%score\", str, t.start);\n else openParen = false;\n break;\n case '[':\n if (openBracket) warn(\"Can't nest brackets in %%score\", str, t.start);\n else {\n openBracket = true;\n justOpenBracket = true;\n }\n break;\n case ']':\n if (!openBracket || justOpenBracket) warn(\"Unexpected close bracket in %%score\", str, t.start);\n else {\n openBracket = false;\n multilineVars.staves[lastVoice.staffNum].bracket = 'end';\n }\n break;\n case '{':\n if (openBrace) warn(\"Can't nest braces in %%score\", str, t.start);\n else {\n openBrace = true;\n justOpenBrace = true;\n }\n break;\n case '}':\n if (!openBrace || justOpenBrace) warn(\"Unexpected close brace in %%score\", str, t.start);\n else {\n openBrace = false;\n multilineVars.staves[lastVoice.staffNum].brace = 'end';\n }\n break;\n case '|':\n addContinueBar();\n break;\n default:\n var vc = \"\";\n while (t.type === 'alpha' || t.type === 'number') {\n vc += t.token;\n if (t.continueId)\n t = tokens.shift();\n else\n break;\n }\n var newStaff = !openParen || justOpenParen;\n var bracket = justOpenBracket ? 'start' : openBracket ? 'continue' : undefined;\n var brace = justOpenBrace ? 'start' : openBrace ? 'continue' : undefined;\n addVoice(vc, newStaff, bracket, brace, continueBar);\n justOpenParen = false;\n justOpenBracket = false;\n justOpenBrace = false;\n continueBar = false;\n lastVoice = multilineVars.voices[vc];\n if (cmd === 'staves')\n addContinueBar();\n break;\n }\n }\n break;\n\n case \"midi\":\n case \"indent\":\n case \"playtempo\":\n case \"auquality\":\n case \"continuous\":\n case \"nobarcheck\":\n // TODO-PER: Actually handle the parameters of these\n tune.formatting[cmd] = restOfString;\n break;\n default:\n return \"Unknown directive: \" + cmd;\n }\n return null;\n };\n\n this.setCurrentVoice = function(id) {\n multilineVars.currentVoice = multilineVars.voices[id];\n tune.setCurrentVoice(multilineVars.currentVoice.staffNum, multilineVars.currentVoice.index);\n };\n\n this.parseVoice = function(line, i, e) {\n //First truncate the string to the first non-space character after V: through either the\n //end of the line or a % character. Then remove trailing spaces, too.\n var ret = tokenizer.getMeat(line, i, e);\n var start = ret.start;\n var end = ret.end;\n //The first thing on the line is the ID. It can be any non-space string and terminates at the\n //first space.\n var id = tokenizer.getToken(line, start, end);\n if (id.length === 0) {\n warn(\"Expected a voice id\", line, start);\n return;\n }\n var isNew = false;\n if (multilineVars.voices[id] === undefined) {\n multilineVars.voices[id] = {};\n isNew = true;\n if (multilineVars.score_is_present)\n warn(\"Can't have an unknown V: id when the %score directive is present\", line, i);\n }\n start += id.length;\n start += tokenizer.eatWhiteSpace(line, start);\n\n var staffInfo = {\n startStaff: isNew\n };\n var addNextTokenToStaffInfo = function(name) {\n var attr = tokenizer.getVoiceToken(line, start, end);\n if (attr.warn !== undefined)\n warn(\"Expected value for \" + name + \" in voice: \" + attr.warn, line, start);\n else if (attr.token.length === 0 && line.charAt(start) !== '\"')\n warn(\"Expected value for \" + name + \" in voice\", line, start);\n else\n staffInfo[name] = attr.token;\n start += attr.len;\n };\n\n //Then the following items can occur in any order:\n while (start < end) {\n var token = tokenizer.getVoiceToken(line, start, end);\n start += token.len;\n\n if (token.warn) {\n warn(\"Error parsing voice: \" + token.warn, line, start);\n } else {\n var attr = null;\n switch (token.token) {\n case 'clef':\n case 'cl':\n addNextTokenToStaffInfo('clef');\n // TODO-PER: check for a legal clef; do octavizing\n var oct = 0;\n //\t\t\t\t\t\t\tfor (var ii = 0; ii < staffInfo.clef.length; ii++) {\n //\t\t\t\t\t\t\t\tif (staffInfo.clef[ii] === ',') oct -= 7;\n //\t\t\t\t\t\t\t\telse if (staffInfo.clef[ii] === \"'\") oct += 7;\n //\t\t\t\t\t\t\t}\n if (staffInfo.clef !== undefined) {\n staffInfo.clef = staffInfo.clef.replace(/[',]/g, \"\"); //'//comment for emacs formatting of regexp\n if (staffInfo.clef.indexOf('+16') !== -1) {\n oct += 14;\n staffInfo.clef = staffInfo.clef.replace('+16', '');\n }\n staffInfo.verticalPos = calcMiddle(staffInfo.clef, oct);\n }\n break;\n case 'treble':\n case 'bass':\n case 'tenor':\n case 'alto':\n case 'none':\n case 'treble\\'':\n case 'bass\\'':\n case 'tenor\\'':\n case 'alto\\'':\n case 'none\\'':\n case 'treble\\'\\'':\n case 'bass\\'\\'':\n case 'tenor\\'\\'':\n case 'alto\\'\\'':\n case 'none\\'\\'':\n case 'treble,':\n case 'bass,':\n case 'tenor,':\n case 'alto,':\n case 'none,':\n case 'treble,,':\n case 'bass,,':\n case 'tenor,,':\n case 'alto,,':\n case 'none,,':\n // TODO-PER: handle the octave indicators on the clef by changing the middle property\n var oct2 = 0;\n //\t\t\t\t\t\t\tfor (var iii = 0; iii < token.token.length; iii++) {\n //\t\t\t\t\t\t\t\tif (token.token[iii] === ',') oct2 -= 7;\n //\t\t\t\t\t\t\t\telse if (token.token[iii] === \"'\") oct2 += 7;\n //\t\t\t\t\t\t\t}\n staffInfo.clef = token.token.replace(/[',]/g, \"\"); //'//comment for emacs formatting of regexp\n staffInfo.verticalPos = calcMiddle(staffInfo.clef, oct2);\n break;\n case 'staves':\n case 'stave':\n case 'stv':\n addNextTokenToStaffInfo('staves');\n break;\n case 'brace':\n case 'brc':\n addNextTokenToStaffInfo('brace');\n break;\n case 'bracket':\n case 'brk':\n addNextTokenToStaffInfo('bracket');\n break;\n case 'name':\n case 'nm':\n addNextTokenToStaffInfo('name');\n break;\n case 'subname':\n case 'sname':\n case 'snm':\n addNextTokenToStaffInfo('subname');\n break;\n case 'merge':\n staffInfo.startStaff = false;\n break;\n case 'stems':\n attr = tokenizer.getVoiceToken(line, start, end);\n if (attr.warn !== undefined)\n warn(\"Expected value for stems in voice: \" + attr.warn, line, start);\n else if (attr.token === 'up' || attr.token === 'down')\n multilineVars.voices[id].stem = attr.token;\n else\n warn(\"Expected up or down for voice stem\", line, start);\n start += attr.len;\n break;\n case 'up':\n case 'down':\n multilineVars.voices[id].stem = token.token;\n break;\n case 'middle':\n case 'm':\n addNextTokenToStaffInfo('verticalPos');\n staffInfo.verticalPos = parseMiddle(staffInfo.verticalPos);\n break;\n case 'gchords':\n case 'gch':\n multilineVars.voices[id].suppressChords = true;\n break;\n case 'space':\n case 'spc':\n addNextTokenToStaffInfo('spacing');\n break;\n }\n }\n start += tokenizer.eatWhiteSpace(line, start);\n }\n\n // now we've filled up staffInfo, figure out what to do with this voice\n // TODO-PER: It is unclear from the standard and the examples what to do with brace, bracket, and staves, so they are ignored for now.\n if (staffInfo.startStaff || multilineVars.staves.length === 0) {\n multilineVars.staves.push({\n index: multilineVars.staves.length,\n meter: multilineVars.origMeter\n });\n if (!multilineVars.score_is_present)\n multilineVars.staves[multilineVars.staves.length - 1].numVoices = 0;\n }\n if (multilineVars.voices[id].staffNum === undefined) {\n // store where to write this for quick access later.\n multilineVars.voices[id].staffNum = multilineVars.staves.length - 1;\n var vi = 0;\n for (var v in multilineVars.voices) {\n if (multilineVars.voices.hasOwnProperty(v)) {\n if (multilineVars.voices[v].staffNum === multilineVars.voices[id].staffNum)\n vi++;\n }\n }\n multilineVars.voices[id].index = vi - 1;\n }\n var s = multilineVars.staves[multilineVars.voices[id].staffNum];\n if (!multilineVars.score_is_present)\n s.numVoices++;\n if (staffInfo.clef) s.clef = {\n type: staffInfo.clef,\n verticalPos: staffInfo.verticalPos\n };\n if (staffInfo.spacing) s.spacing_below_offset = staffInfo.spacing;\n if (staffInfo.verticalPos) s.verticalPos = staffInfo.verticalPos;\n\n if (staffInfo.name) {\n if (s.name) s.name.push(staffInfo.name);\n else s.name = [staffInfo.name];\n }\n if (staffInfo.subname) {\n if (s.subname) s.subname.push(staffInfo.subname);\n else s.subname = [staffInfo.subname];\n }\n\n this.setCurrentVoice(id);\n };\n\n this.setTitle = function(title) {\n if (multilineVars.hasMainTitle)\n tune.addSubtitle(tokenizer.translateString(tokenizer.stripComment(title))); // display secondary title\n else {\n tune.addMetaText(\"title\", tokenizer.translateString(tokenizer.theReverser(tokenizer.stripComment(title))));\n multilineVars.hasMainTitle = true;\n }\n };\n\n this.setMeter = function(line) {\n line = tokenizer.stripComment(line);\n if (line === 'C') {\n if (multilineVars.havent_set_length === true)\n multilineVars.default_length = 0.125;\n return {\n type: 'common_time'\n };\n } else if (line === 'C|') {\n if (multilineVars.havent_set_length === true)\n multilineVars.default_length = 0.125;\n return {\n type: 'cut_time'\n };\n } else if (line.length === 0 || line.toLowerCase() === 'none') {\n if (multilineVars.havent_set_length === true)\n multilineVars.default_length = 0.125;\n return null;\n } else {\n var tokens = tokenizer.tokenize(line, 0, line.length);\n // the form is [open_paren] decimal [ plus|dot decimal ]... [close_paren] slash decimal [plus same_as_before]\n try {\n var parseNum = function() {\n // handles this much: [open_paren] decimal [ plus|dot decimal ]... [close_paren]\n var ret = {\n value: 0,\n num: \"\"\n };\n\n var tok = tokens.shift();\n if (tok.token === '(')\n tok = tokens.shift();\n while (1) {\n if (tok.type !== 'number') throw \"Expected top number of meter\";\n ret.value += parseInt(tok.token);\n ret.num += tok.token;\n if (tokens.length === 0 || tokens[0].token === '/') return ret;\n tok = tokens.shift();\n if (tok.token === ')') {\n if (tokens.length === 0 || tokens[0].token === '/') return ret;\n throw \"Unexpected paren in meter\";\n }\n if (tok.token !== '.' && tok.token !== '+') throw \"Expected top number of meter\";\n ret.num += tok.token;\n if (tokens.length === 0) throw \"Expected top number of meter\";\n tok = tokens.shift();\n }\n return ret; // just to suppress warning\n };\n\n var parseFraction = function() {\n // handles this much: parseNum slash decimal\n var ret = parseNum();\n if (tokens.length === 0) throw \"Expected slash in meter\";\n var tok = tokens.shift();\n if (tok.token !== '/') throw \"Expected slash in meter\";\n tok = tokens.shift();\n if (tok.type !== 'number') throw \"Expected bottom number of meter\";\n ret.den = tok.token;\n ret.value = ret.value / parseInt(ret.den);\n return ret;\n };\n\n if (tokens.length === 0) throw \"Expected meter definition in M: line\";\n var meter = {\n type: 'specified',\n value: []\n };\n var totalLength = 0;\n while (1) {\n var ret = parseFraction();\n totalLength += ret.value;\n meter.value.push({\n num: ret.num,\n den: ret.den\n });\n if (tokens.length === 0) break;\n var tok = tokens.shift();\n if (tok.token !== '+') throw \"Extra characters in M: line\";\n }\n\n if (multilineVars.havent_set_length === true) {\n multilineVars.default_length = totalLength < 0.75 ? 0.0625 : 0.125;\n }\n return meter;\n } catch (e) {\n warn(e, line, 0);\n }\n }\n return null;\n };\n\n this.calcTempo = function(relTempo) {\n var dur = multilineVars.default_length ? multilineVars.default_length : 1;\n for (var i = 0; i < relTempo.duration; i++)\n relTempo.duration[i] = dur * relTempo.duration[i];\n return relTempo;\n };\n\n this.resolveTempo = function() {\n if (multilineVars.tempo) { // If there's a tempo waiting to be resolved\n this.calcTempo(multilineVars.tempo);\n tune.metaText.tempo = multilineVars.tempo;\n delete multilineVars.tempo;\n }\n };\n\n this.addUserDefinition = function(line, start, end) {\n var equals = line.indexOf('=', start);\n if (equals === -1) {\n warn(\"Need an = in a macro definition\", line, start);\n return;\n }\n\n var before = line.substring(start, equals).strip();\n var after = line.substring(equals + 1).strip();\n\n if (before.length !== 1) {\n warn(\"Macro definitions can only be one character\", line, start);\n return;\n }\n var legalChars = \"HIJKLMNOPQRSTUVWhijklmnopqrstuvw~\";\n if (legalChars.indexOf(before) === -1) {\n warn(\"Macro definitions must be H-W, h-w, or tilde\", line, start);\n return;\n }\n if (after.length === 0) {\n warn(\"Missing macro definition\", line, start);\n return;\n }\n if (multilineVars.macros === undefined)\n multilineVars.macros = {};\n multilineVars.macros[before] = after;\n };\n\n this.setDefaultLength = function(line, start, end) {\n var len = line.substring(start, end).gsub(\" \", \"\");\n var len_arr = len.split('/');\n if (len_arr.length === 2) {\n var n = parseInt(len_arr[0]);\n var d = parseInt(len_arr[1]);\n if (d > 0) {\n var q = n / d;\n multilineVars.default_length = q; // a whole note is 1\n multilineVars.havent_set_length = false;\n }\n }\n };\n\n this.setTempo = function(line, start, end) {\n //Q - tempo; can be used to specify the notes per minute, e.g. if\n //the default note length is an eighth note then Q:120 or Q:C=120\n //is 120 eighth notes per minute. Similarly Q:C3=40 would be 40\n //dotted quarter notes per minute. An absolute tempo may also be\n //set, e.g. Q:1/8=120 is also 120 eighth notes per minute,\n //irrespective of the default note length.\n //\n // This is either a number, \"C=number\", \"Cnumber=number\", or fraction [fraction...]=number\n // It depends on the L: field, which may either not be present, or may appear after this.\n // If L: is not present, an eighth note is used.\n // That means that this field can't be calculated until the end, if it is the first three types, since we don't know if we'll see an L: field.\n // So, if it is the fourth type, set it here, otherwise, save the info in the multilineVars.\n // The temporary variables we keep are the duration and the bpm. In the first two forms, the duration is 1.\n // In addition, a quoted string may both precede and follow. If a quoted string is present, then the duration part is optional.\n try {\n var tokens = tokenizer.tokenize(line, start, end);\n\n if (tokens.length === 0) throw \"Missing parameter in Q: field\";\n\n var tempo = {};\n var delaySet = true;\n var token = tokens.shift();\n if (token.type === 'quote') {\n tempo.preString = token.token;\n token = tokens.shift();\n if (tokens.length === 0) { // It's ok to just get a string for the tempo\n return {\n type: 'immediate',\n tempo: tempo\n };\n }\n }\n if (token.type === 'alpha' && token.token === 'C') { // either type 2 or type 3\n if (tokens.length === 0) throw \"Missing tempo after C in Q: field\";\n token = tokens.shift();\n if (token.type === 'punct' && token.token === '=') {\n // This is a type 2 format. The duration is an implied 1\n if (tokens.length === 0) throw \"Missing tempo after = in Q: field\";\n token = tokens.shift();\n if (token.type !== 'number') throw \"Expected number after = in Q: field\";\n tempo.duration = [1];\n tempo.bpm = parseInt(token.token);\n } else if (token.type === 'number') {\n // This is a type 3 format.\n tempo.duration = [parseInt(token.token)];\n if (tokens.length === 0) throw \"Missing = after duration in Q: field\";\n token = tokens.shift();\n if (token.type !== 'punct' || token.token !== '=') throw \"Expected = after duration in Q: field\";\n if (tokens.length === 0) throw \"Missing tempo after = in Q: field\";\n token = tokens.shift();\n if (token.type !== 'number') throw \"Expected number after = in Q: field\";\n tempo.bpm = parseInt(token.token);\n } else throw \"Expected number or equal after C in Q: field\";\n\n } else if (token.type === 'number') { // either type 1 or type 4\n var num = parseInt(token.token);\n if (tokens.length === 0 || tokens[0].type === 'quote') {\n // This is type 1\n tempo.duration = [1];\n tempo.bpm = num;\n } else { // This is type 4\n delaySet = false;\n token = tokens.shift();\n if (token.type !== 'punct' && token.token !== '/') throw \"Expected fraction in Q: field\";\n token = tokens.shift();\n if (token.type !== 'number') throw \"Expected fraction in Q: field\";\n var den = parseInt(token.token);\n tempo.duration = [num / den];\n // We got the first fraction, keep getting more as long as we find them.\n while (tokens.length > 0 && tokens[0].token !== '=' && tokens[0].type !== 'quote') {\n token = tokens.shift();\n if (token.type !== 'number') throw \"Expected fraction in Q: field\";\n num = parseInt(token.token);\n token = tokens.shift();\n if (token.type !== 'punct' && token.token !== '/') throw \"Expected fraction in Q: field\";\n token = tokens.shift();\n if (token.type !== 'number') throw \"Expected fraction in Q: field\";\n den = parseInt(token.token);\n tempo.duration.push(num / den);\n }\n token = tokens.shift();\n if (token.type !== 'punct' && token.token !== '=') throw \"Expected = in Q: field\";\n token = tokens.shift();\n if (token.type !== 'number') throw \"Expected tempo in Q: field\";\n tempo.bpm = parseInt(token.token);\n }\n } else throw \"Unknown value in Q: field\";\n if (tokens.length !== 0) {\n token = tokens.shift();\n if (token.type === 'quote') {\n tempo.postString = token.token;\n token = tokens.shift();\n }\n if (tokens.length !== 0) throw \"Unexpected string at end of Q: field\";\n }\n return {\n type: delaySet ? 'delaySet' : 'immediate',\n tempo: tempo\n };\n } catch (msg) {\n warn(msg, line, start);\n return {\n type: 'none'\n };\n }\n };\n\n this.letter_to_inline_header = function(line, i) {\n var ws = tokenizer.eatWhiteSpace(line, i);\n i += ws;\n if (line.length >= i + 5 && line.charAt(i) === '[' && line.charAt(i + 2) === ':') {\n var e = line.indexOf(']', i);\n switch (line.substring(i, i + 3)) {\n case \"[I:\":\n var err = this.addDirective(line.substring(i + 3, e));\n if (err) warn(err, line, i);\n return [e - i + 1 + ws];\n case \"[M:\":\n var meter = this.setMeter(line.substring(i + 3, e));\n if (tune.hasBeginMusic() && meter)\n tune.appendStartingElement('meter', -1, -1, meter);\n return [e - i + 1 + ws];\n case \"[K:\":\n var result = this.parseKey(line.substring(i + 3, e));\n if (result.foundClef && tune.hasBeginMusic())\n tune.appendStartingElement('clef', -1, -1, multilineVars.clef);\n if (result.foundKey && tune.hasBeginMusic())\n tune.appendStartingElement('key', -1, -1, this.fixKey(multilineVars.clef, multilineVars.key));\n return [e - i + 1 + ws];\n case \"[P:\":\n tune.appendElement('part', -1, -1, {\n title: line.substring(i + 3, e)\n });\n return [e - i + 1 + ws];\n case \"[L:\":\n this.setDefaultLength(line, i + 3, e);\n return [e - i + 1 + ws];\n case \"[Q:\":\n if (e > 0) {\n var tempo = this.setTempo(line, i + 3, e);\n if (tempo.type === 'delaySet') tune.appendElement('tempo', -1, -1, this.calcTempo(tempo.tempo));\n else if (tempo.type === 'immediate') tune.appendElement('tempo', -1, -1, tempo.tempo);\n return [e - i + 1 + ws, line.charAt(i + 1), line.substring(i + 3, e)];\n }\n break;\n case \"[V:\":\n if (e > 0) {\n this.parseVoice(line, i + 3, e);\n //startNewLine();\n return [e - i + 1 + ws, line.charAt(i + 1), line.substring(i + 3, e)];\n }\n break;\n\n default:\n // TODO: complain about unhandled header\n }\n }\n return [0];\n };\n\n this.letter_to_body_header = function(line, i) {\n if (line.length >= i + 3) {\n switch (line.substring(i, i + 2)) {\n case \"I:\":\n var err = this.addDirective(line.substring(i + 2));\n if (err) warn(err, line, i);\n return [line.length];\n case \"M:\":\n var meter = this.setMeter(line.substring(i + 2));\n if (tune.hasBeginMusic() && meter)\n tune.appendStartingElement('meter', -1, -1, meter);\n return [line.length];\n case \"K:\":\n var result = this.parseKey(line.substring(i + 2));\n if (result.foundClef && tune.hasBeginMusic())\n tune.appendStartingElement('clef', -1, -1, multilineVars.clef);\n if (result.foundKey && tune.hasBeginMusic())\n tune.appendStartingElement('key', -1, -1, this.fixKey(multilineVars.clef, multilineVars.key));\n return [line.length];\n case \"P:\":\n if (tune.hasBeginMusic())\n tune.appendElement('part', -1, -1, {\n title: line.substring(i + 2)\n });\n return [line.length];\n case \"L:\":\n this.setDefaultLength(line, i + 2, line.length);\n return [line.length];\n case \"Q:\":\n var e = line.indexOf('\\x12', i + 2);\n if (e === -1) e = line.length;\n var tempo = this.setTempo(line, i + 2, e);\n if (tempo.type === 'delaySet') tune.appendElement('tempo', -1, -1, this.calcTempo(tempo.tempo));\n else if (tempo.type === 'immediate') tune.appendElement('tempo', -1, -1, tempo.tempo);\n return [e, line.charAt(i), line.substring(i + 2).strip()];\n case \"V:\":\n this.parseVoice(line, 2, line.length);\n //\t\t\t\t\t\tstartNewLine();\n return [line.length, line.charAt(i), line.substring(i + 2).strip()];\n default:\n // TODO: complain about unhandled header\n }\n }\n return [0];\n };\n\n var metaTextHeaders = {\n A: 'author',\n B: 'book',\n C: 'composer',\n D: 'discography',\n F: 'url',\n G: 'group',\n I: 'instruction',\n N: 'notes',\n O: 'origin',\n R: 'rhythm',\n S: 'source',\n W: 'unalignedWords',\n Z: 'transcription'\n };\n\n this.parseHeader = function(line) {\n if (line.startsWith('%%')) {\n var err = this.addDirective(line.substring(2));\n if (err) warn(err, line, 2);\n return {};\n }\n line = tokenizer.stripComment(line);\n if (line.length === 0)\n return {};\n\n if (line.length >= 2) {\n if (line.charAt(1) === ':') {\n var nextLine = \"\";\n if (line.indexOf('\\x12') >= 0 && line.charAt(0) !== 'w') { // w: is the only header field that can have a continuation.\n nextLine = line.substring(line.indexOf('\\x12') + 1);\n line = line.substring(0, line.indexOf('\\x12')); //This handles a continuation mark on a header field\n }\n var field = metaTextHeaders[line.charAt(0)];\n if (field !== undefined) {\n tune.addMetaText(field, tokenizer.translateString(tokenizer.stripComment(line.substring(2))));\n return {};\n } else {\n switch (line.charAt(0)) {\n case 'H':\n tune.addMetaText(\"history\", tokenizer.translateString(tokenizer.stripComment(line.substring(2))));\n multilineVars.is_in_history = true;\n break;\n case 'K':\n // since the key is the last thing that can happen in the header, we can resolve the tempo now\n this.resolveTempo();\n var result = this.parseKey(line.substring(2));\n if (!multilineVars.is_in_header && tune.hasBeginMusic()) {\n if (result.foundClef)\n tune.appendStartingElement('clef', -1, -1, multilineVars.clef);\n if (result.foundKey)\n tune.appendStartingElement('key', -1, -1, this.fixKey(multilineVars.clef, multilineVars.key));\n }\n multilineVars.is_in_header = false; // The first key signifies the end of the header.\n break;\n case 'L':\n this.setDefaultLength(line, 2, line.length);\n break;\n case 'M':\n multilineVars.origMeter = multilineVars.meter = this.setMeter(line.substring(2));\n break;\n case 'P':\n // TODO-PER: There is more to do with parts, but the writer doesn't care.\n if (multilineVars.is_in_header)\n tune.addMetaText(\"partOrder\", tokenizer.translateString(tokenizer.stripComment(line.substring(2))));\n else\n multilineVars.partForNextLine = tokenizer.translateString(tokenizer.stripComment(line.substring(2)));\n break;\n case 'Q':\n var tempo = this.setTempo(line, 2, line.length);\n if (tempo.type === 'delaySet') multilineVars.tempo = tempo.tempo;\n else if (tempo.type === 'immediate') tune.metaText.tempo = tempo.tempo;\n break;\n case 'T':\n this.setTitle(line.substring(2));\n break;\n case 'U':\n this.addUserDefinition(line, 2, line.length);\n break;\n case 'V':\n this.parseVoice(line, 2, line.length);\n if (!multilineVars.is_in_header)\n return {\n newline: true\n };\n break;\n case 'w':\n return {\n words: true\n };\n case 'X':\n break;\n case 'E':\n case 'm':\n warn(\"Ignored header\", line, 0);\n break;\n default:\n // It wasn't a recognized header value, so parse it as music.\n if (nextLine.length)\n nextLine = \"\\x12\" + nextLine;\n //parseRegularMusicLine(line+nextLine);\n //nextLine = \"\";\n return {\n regular: true,\n str: line + nextLine\n };\n }\n }\n if (nextLine.length > 0)\n return {\n recurse: true,\n str: nextLine\n };\n return {};\n }\n }\n\n // If we got this far, we have a regular line of mulsic\n return {\n regular: true,\n str: line\n };\n };\n}",
"function readAndPlayNote(array, index, currentInstrument){ \n\t// when to stop playing \n\tif(index === array.length){\n\t\t currentInstrument.gain.gain.value = 0;\n\t}else{\n\t\t currentInstrument.oscillator.type = currentInstrument.waveType;\n\t\t\n\t\t// tip! by setting value at a certain time, this prevents the 'gliding' from one freq. to the next \n\t\t// pick either one of the two below based on a certain condition \n\t\t// by default, use this one \n\t\tif(array[index].block.style !== \"glide\"){\n\t\t\tcurrentInstrument.oscillator.frequency.setValueAtTime(array[index].freq, 0);\n\t\t}else if(array[index].block.style === \"glide\"){\n\t\t\tcurrentInstrument.oscillator.frequency.value = array[index].freq;\n\t\t}\n\t\t \n\t\t// by setting gain value here according to the two conditions, this allows for the 'articulation' of notes without \n\t\t// the 'helicopter' sound when a certain note frequency is 0. \n\t\t// previously, the gain would have been .3 even for notes with 0 frequency,\n\t\t// which causes some increase in volume in background sound.\n\t\t// it was only detectable when I added the setTimeout below where I set gain to 0.\n\t\t// this is fixed by always setting gain to 0 if a note's frequency is 0.\n\t\t currentInstrument.gain.gain.value = array[index].freq > 0 ? parseFloat(array[index].block.volume) : 0.0;\n\t\t \n\t\tif(index < array.length){\n\t\t\t// hold the current note for whatever duration was specified\n\t\t\t// in other words, hold this current note for array[index].duration, then move on to the next note.\n\t\t\t// note that index is pre-incremented for the next note, but we also need the duration for this current index!\n\t\t\t// therefore, currIndex will hold the current note's index.\n\t\t\tvar currIndex = index;\n\t\t\t\n\t\t\t// change gain to 0 after a really small amount of time to give the impression of articulation\n\t\t\t// this amount of time will vary with the bpm \n\t\t\t// so far it seems that for bpm 120 (500 ms) and below, 95 ms is a good amount of space (not staccato)\n\t\t\t// for bpm 150 - 185, 70 ms is good, and past that, 50 ms\n\t\t\t// remember: currentTempo variable is in milliseconds\n\t\t\tvar spacer;\n\t\t\tif(currentTempo >= 500){\n\t\t\t\tspacer = 95;\n\t\t\t}else if(currentTempo >= 324 && currentTempo < 500){\n\t\t\t\t// bpm: 150 - 185\n\t\t\t\tspacer = 70;\n\t\t\t}else{\n\t\t\t\tspacer = 50;\n\t\t\t}\n\t\t\t\n\t\t\t// but, if a certain note's style is staccato or legato, spacer will\n\t\t\t// have to change accordingly as well\n\t\t\tif(array[index].block.style === \"legato\"){\n\t\t\t\tif(currentTempo >= 500){\n\t\t\t\t\tspacer = 200;\n\t\t\t\t}else if(currentTempo >= 324 && currentTempo < 500){\n\t\t\t\t\tspacer = 180;\n\t\t\t\t}else{\n\t\t\t\t\tspacer = 160;\n\t\t\t\t}\n\t\t\t}else if(array[index].block.style === \"staccato\"){\n\t\t\t\tif(currentTempo >= 500){\n\t\t\t\t\tspacer = 70;\n\t\t\t\t}else if(currentTempo >= 324 && currentTempo < 500){\n\t\t\t\t\tspacer = 50;\n\t\t\t\t}else{\n\t\t\t\t\tspacer = 30;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tsetTimeout(function(){ currentInstrument.gain.gain.value = 0.0; }, spacer); \n\t\t\t\n\t\t\t// create a new timer and push to timers array \n\t\t\ttimers.push( setTimeout(function(){readAndPlayNote(array, ++index, currentInstrument)}, array[currIndex].duration) ); \n\t\t}\n\t}\n}",
"function _createSoundNote(step, alter, octave, duration, lyricText, syllabicState) {\n var pitchElm = xml.createElement('pitch'); // pitch {step, alter, octave}\n var stepElm = xml.createElement('step');\n stepElm.textContent = step;\n pitchElm.appendChild(stepElm);\n if (alter != 0) {\n var alterElm = xml.createElement('alter');\n alterElm.textContent = alter;\n pitchElm.appendChild(alterElm);\n }\n var octaveElm = xml.createElement('octave');\n octaveElm.textContent = octave;\n pitchElm.appendChild(octaveElm);\n\n var durationElm = xml.createElement('duration'); // duration\n durationElm.textContent = duration;\n\n var lyricElm = xml.createElement('lyric'); // lyric {text, syllabic}\n var textElm = xml.createElement('text');\n textElm.textContent = lyricText;\n lyricElm.appendChild(textElm);\n var syllabicElm = xml.createElement('syllabic');\n syllabicElm.textContent = syllabicState;\n lyricElm.appendChild(syllabicElm);\n\n var noteElm = xml.createElement('note'); // note {pitch, duration, lyric}\n noteElm.appendChild(pitchElm);\n noteElm.appendChild(durationElm);\n noteElm.appendChild(lyricElm);\n\n return noteElm;\n }",
"withInclinata(notes) {\n var staffPosition = notes[0].staffPosition,\n prevStaffPosition = notes[0].staffPosition;\n\n // it is important to advance by the width of the inclinatum glyph itself\n // rather than by individual note widths, so that any liquescents are spaced\n // the same as non-liquscents\n var advanceWidth =\n Glyphs.PunctumInclinatum.bounds.width * this.ctxt.glyphScaling;\n\n // now add all the punctum inclinatum\n for (var i = 0; i < notes.length; i++, prevStaffPosition = staffPosition) {\n var note = notes[i];\n\n if (note.liquescent & LiquescentType.Small)\n note.setGlyph(this.ctxt, GlyphCode.PunctumInclinatumLiquescent);\n else if (note.liquescent & LiquescentType.Large)\n // fixme: is the large inclinatum liquescent the same as the apostropha?\n note.setGlyph(this.ctxt, GlyphCode.Stropha);\n // fixme: some climaci in the new chant books end with a punctum quadratum\n // (see, for example, the antiphon \"Sancta Maria\" for October 7).\n else note.setGlyph(this.ctxt, GlyphCode.PunctumInclinatum);\n\n staffPosition = note.staffPosition;\n\n var multiple = Math.abs(prevStaffPosition - staffPosition);\n switch (multiple) {\n case 0:\n multiple = 1.1;\n break;\n default:\n multiple *= 2 / 3;\n break;\n }\n\n if (i > 0) this.x += advanceWidth * multiple;\n\n note.bounds.x = this.x;\n\n this.neume.addVisualizer(note);\n }\n\n return this;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a CloudFormation stack artifact from this assembly. | getStackArtifact(artifactId) {
const artifact = this.tryGetArtifactRecursively(artifactId);
if (!artifact) {
throw new Error(`Unable to find artifact with id "${artifactId}"`);
}
if (!(artifact instanceof cloudformation_artifact_1.CloudFormationStackArtifact)) {
throw new Error(`Artifact ${artifactId} is not a CloudFormation stack`);
}
return artifact;
} | [
"getStackByName(stackName) {\n const artifacts = this.artifacts.filter(a => a instanceof cloudformation_artifact_1.CloudFormationStackArtifact && a.stackName === stackName);\n if (!artifacts || artifacts.length === 0) {\n throw new Error(`Unable to find stack with stack name \"${stackName}\"`);\n }\n if (artifacts.length > 1) {\n // eslint-disable-next-line max-len\n throw new Error(`There are multiple stacks with the stack name \"${stackName}\" (${artifacts.map(a => a.id).join(',')}). Use \"getStackArtifact(id)\" instead`);\n }\n return artifacts[0];\n }",
"getNestedAssemblyArtifact(artifactId) {\n const artifact = this.tryGetArtifact(artifactId);\n if (!artifact) {\n throw new Error(`Unable to find artifact with id \"${artifactId}\"`);\n }\n if (!(artifact instanceof nested_cloud_assembly_artifact_1.NestedCloudAssemblyArtifact)) {\n throw new Error(`Found artifact '${artifactId}' but it's not a nested cloud assembly`);\n }\n return artifact;\n }",
"function getStackResource() {\n const { stackResource } = exports.getStore();\n return stackResource;\n}",
"get resourceStack() {\n const actionResource = this.actionProperties.resource;\n if (!actionResource) {\n return undefined;\n }\n const actionResourceStack = core_1.Stack.of(actionResource);\n const actionResourceStackEnv = {\n region: actionResourceStack.region,\n account: actionResourceStack.account,\n };\n return sameEnv(actionResource.env, actionResourceStackEnv) ? actionResourceStack : undefined;\n }",
"function Stack(props) {\n return __assign({ Type: 'AWS::CloudFormation::Stack' }, props);\n }",
"getNestedAssembly(artifactId) {\n return this.getNestedAssemblyArtifact(artifactId).nestedAssembly;\n }",
"function Stack(props) {\n return __assign({ Type: 'AWS::OpsWorks::Stack' }, props);\n }",
"function getStack() {\n return settings.getStack();\n}",
"exportStack() {\n return this.stack.exportStack();\n }",
"function Stack(props) {\n return __assign({ Type: 'AWS::AppStream::Stack' }, props);\n }",
"static async getStackInfo(stackName) {\n var client = new AWS.CloudFormation();\n var stacks = await client.describeStacks({ StackName: stackName }).promise();\n return stacks['Stacks'][0];\n }",
"get stacksRecursively() {\n function search(stackArtifacts, assemblies) {\n if (assemblies.length === 0) {\n return stackArtifacts;\n }\n const [head, ...tail] = assemblies;\n const nestedAssemblies = head.nestedAssemblies.map(asm => asm.nestedAssembly);\n return search(stackArtifacts.concat(head.stacks), tail.concat(nestedAssemblies));\n }\n ;\n return search([], [this]);\n }",
"importStack(state) {\n return this.stack.importStack(state);\n }",
"async function getResourceStackAssociation() {\n templates = {};\n\n await sdkcall(\"CloudFormation\", \"listStacks\", {\n StackStatusFilter: [\"CREATE_COMPLETE\", \"ROLLBACK_IN_PROGRESS\", \"ROLLBACK_FAILED\", \"ROLLBACK_COMPLETE\", \"DELETE_FAILED\", \"UPDATE_IN_PROGRESS\", \"UPDATE_COMPLETE_CLEANUP_IN_PROGRESS\", \"UPDATE_COMPLETE\", \"UPDATE_ROLLBACK_IN_PROGRESS\", \"UPDATE_ROLLBACK_FAILED\", \"UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS\", \"UPDATE_ROLLBACK_COMPLETE\"]\n }, true).then(async (data) => {\n await Promise.all(data.StackSummaries.map(async (stack) => {\n await sdkcall(\"CloudFormation\", \"getTemplate\", {\n StackName: stack.StackId,\n TemplateStage: \"Processed\"\n }, true).then((data) => {\n template = null;\n try {\n template = JSON.parse(data.TemplateBody);\n templates[stack.StackName] = template;\n } catch(err) {\n console.log(\"Couldn't parse\"); // TODO: yaml 2 json\n }\n });\n }));\n });\n\n console.log(templates);\n}",
"static async deployStack(templateFilePath, stackName, bucketName) {\n await this.createBucketIfNotExists(bucketName);\n await KelchCommon.exec('aws cloudformation package --template-file ' + templateFilePath + ' --output-template-file ' + templateFilePath + ' --s3-bucket ' + bucketName + ' --use-json');\n await KelchCommon.exec('aws cloudformation deploy --template-file ' + templateFilePath + ' --stack-name ' + stackName + ' --capabilities CAPABILITY_IAM');\n }",
"tree() {\n const trees = this.artifacts.filter(a => a.manifest.type === cxschema.ArtifactType.CDK_TREE);\n if (trees.length === 0) {\n return undefined;\n }\n else if (trees.length > 1) {\n throw new Error(`Multiple artifacts of type ${cxschema.ArtifactType.CDK_TREE} found in manifest`);\n }\n const tree = trees[0];\n if (!(tree instanceof tree_cloud_artifact_1.TreeCloudArtifact)) {\n throw new Error('\"Tree\" artifact is not of expected type');\n }\n return tree;\n }",
"get nestedAssemblies() {\n return this.artifacts.filter(isNestedCloudAssemblyArtifact);\n function isNestedCloudAssemblyArtifact(x) {\n return x instanceof nested_cloud_assembly_artifact_1.NestedCloudAssemblyArtifact;\n }\n }",
"createNestedAssembly(artifactId, displayName) {\n const directoryName = artifactId;\n const innerAsmDir = path.join(this.outdir, directoryName);\n this.addArtifact(artifactId, {\n type: cxschema.ArtifactType.NESTED_CLOUD_ASSEMBLY,\n properties: {\n directoryName,\n displayName,\n },\n });\n return new CloudAssemblyBuilder(innerAsmDir, {\n // Reuse the same asset output directory as the current Casm builder\n assetOutdir: this.assetOutdir,\n parentBuilder: this,\n });\n }",
"buildAssembly(options = {}) {\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_cx_api_AssemblyBuildOptions(options);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, this.buildAssembly);\n }\n throw error;\n }\n // explicitly initializing this type will help us detect\n // breaking changes. (For example adding a required property will break compilation).\n let manifest = {\n version: cxschema.Manifest.version(),\n artifacts: this.artifacts,\n runtime: options.runtimeInfo,\n missing: this.missing.length > 0 ? this.missing : undefined,\n };\n // now we can filter\n manifest = filterUndefined(manifest);\n const manifestFilePath = path.join(this.outdir, MANIFEST_FILE);\n cxschema.Manifest.saveAssemblyManifest(manifest, manifestFilePath);\n // \"backwards compatibility\": in order for the old CLI to tell the user they\n // need a new version, we'll emit the legacy manifest with only \"version\".\n // this will result in an error \"CDK Toolkit >= CLOUD_ASSEMBLY_VERSION is required in order to interact with this program.\"\n fs.writeFileSync(path.join(this.outdir, 'cdk.out'), JSON.stringify({ version: manifest.version }));\n return new CloudAssembly(this.outdir);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cursor / Layout IMGUI_API void Separator(); // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator. | function Separator() { bind.Separator(); } | [
"function VERTICAL_SEPARATOR_ELEMENT_ITEM$static_(){SeparatorBEMEntities.VERTICAL_SEPARATOR_ELEMENT_ITEM=( SeparatorBEMEntities.VERTICAL_SEPARATOR_BLOCK.createElement(\"item\"));}",
"_containsSeparator() {\n return this.separator ? 'container-items-with-separator' : '';\n }",
"get seperator() { return this._seperator }",
"function detectSeparator(a, b, step, isNum, isDescending) {\r\n var isChar = isCharClass(a, b, step, isNum, isDescending);\r\n if (!isChar) {\r\n return '|';\r\n }\r\n return '~';\r\n}",
"function get_separator_tokens(cm, line) {\n var currentLine,\n separators,\n token,\n p,\n lastSeparator;\n\n separators = [];\n currentLine = cm.getLine(line);\n p = {line: line, ch: 0};\n while (p.ch < currentLine.length) {\n token = cm.getTokenAt(p)\n if (token.type == \"cell-separator\") {\n separators.push(token);\n }\n p.ch = token.end + 1;\n }\n\n if (separators.length > 0) {\n if (separators[0].start > 0) {\n // first separator is not the first character on a \n // line. This should probably never happen, but we'll\n // insert a virtual separator at the start.\n token = {start: 0, end: separators[0].start-1, type: null};\n separators.unshift(token);\n }\n\n lastSeparator = separators[separators.length-1];\n if (lastSeparator.start < currentLine.length) {\n // last separator is not at eol; append a pseudo-separator\n // in the results\n token = {start: currentLine.length, end: currentLine.length, type: null};\n separators.push(token);\n }\n }\n return separators;\n }",
"function borderSep() {\n table.style.borderCollapse = 'separate';\n}",
"function Divider(text)\n {\n console.log(\"\\r\\n--------------------\");\n console.log(text);\n }",
"set surround_seperator(string){ \n this.seperator_prefix = string\n this.seperator_suffix = string\n }",
"function getDelimiter (){\n\t\treturn prompt.delimiter;\n\t}",
"function getPoplistSepLine(x,y,s){\n\tvar result=\"M\"+(x-s/2)+\" \"+y+\",\";\n\tresult=result+\"L\"+(x+s/2)+\" \"+y;\n\t\n\treturn result;\n}",
"function SplitterHandle(orientation) {\n this._m_hidden = false;\n this._m_node = this.createNode();\n this.orientation = orientation;\n }",
"function render_bottom_border() {\n context.setLineDash([5, 15]);\n\n context.lineWidth = 1;\n context.strokeStyle = '#00ff00';\n context.beginPath();\n context.moveTo(0, (canvas.height - 155));\n context.lineTo(canvas.width, (canvas.height - 155));\n context.stroke();\n }",
"function blank() {\n putstr(padding_left(seperator, seperator, sndWidth));\n putstr(\"\\n\");\n }",
"function DDLightbarMenu_DrawBorder()\n{\n\tif (!this.borderEnabled)\n\t\treturn;\n\n\t// Draw the border around the menu options\n\tconsole.print(\"\\1n\" + this.colors.borderColor);\n\t// Upper border\n\tconsole.gotoxy(this.pos.x, this.pos.y);\n\tif (this.borderChars.hasOwnProperty(\"upperLeft\") && (typeof(this.borderChars.upperLeft) == \"string\"))\n\t\tconsole.print(this.borderChars.upperLeft);\n\telse\n\t\tconsole.print(\" \");\n\tvar lineLen = this.size.width - 2;\n\tif (this.borderChars.hasOwnProperty(\"top\") && (typeof(this.borderChars.top) == \"string\"))\n\t{\n\t\t// Display the top border text (if any) in the top border. Ensure the text\n\t\t// length is no longer than the maximum possible length (lineLen).\n\t\tvar borderText = shortenStrWithAttrCodes(this.topBorderText, lineLen);\n\t\tconsole.print(\"\\1n\" + borderText + \"\\1n\" + this.colors.borderColor);\n\t\tvar remainingLineLen = lineLen - console.strlen(borderText);\n\t\tfor (var i = 0; i < remainingLineLen; ++i)\n\t\t\tconsole.print(this.borderChars.top);\n\t}\n\telse\n\t{\n\t\tfor (var i = 0; i < lineLen; ++i)\n\t\t\tconsole.print(\" \");\n\t}\n\tif (this.borderChars.hasOwnProperty(\"upperRight\") && (typeof(this.borderChars.upperRight) == \"string\"))\n\t\tconsole.print(this.borderChars.upperRight);\n\telse\n\t\tconsole.print(\" \");\n\t// Lower border\n\tconsole.gotoxy(this.pos.x, this.pos.y+this.size.height-1);\n\tif (this.borderChars.hasOwnProperty(\"lowerLeft\") && (typeof(this.borderChars.lowerLeft) == \"string\"))\n\t\tconsole.print(this.borderChars.lowerLeft);\n\telse\n\t\tconsole.print(\" \");\n\tvar lineLen = this.size.width - 2;\n\tif (this.borderChars.hasOwnProperty(\"bottom\") && (typeof(this.borderChars.bottom) == \"string\"))\n\t{\n\t\t// Display the bottom border text (if any) in the bottom border. Ensure the text\n\t\t// length is no longer than the maximum possible length (lineLen).\n\t\tvar borderText = shortenStrWithAttrCodes(this.bottomBorderText, lineLen);\n\t\tconsole.print(\"\\1n\" + borderText + \"\\1n\" + this.colors.borderColor);\n\t\tvar remainingLineLen = lineLen - console.strlen(borderText);\n\t\tfor (var i = 0; i < remainingLineLen; ++i)\n\t\t\tconsole.print(this.borderChars.bottom);\n\t}\n\telse\n\t{\n\t\tfor (var i = 0; i < lineLen; ++i)\n\t\t\tconsole.print(\" \");\n\t}\n\tif (this.borderChars.hasOwnProperty(\"lowerRight\") && (typeof(this.borderChars.lowerRight) == \"string\"))\n\t\tconsole.print(this.borderChars.lowerRight);\n\telse\n\t\tconsole.print(\" \");\n\t// Side borders\n\tvar leftSideChar = \" \";\n\tvar rightSideChar = \" \";\n\tif (this.borderChars.hasOwnProperty(\"left\") && (typeof(this.borderChars.left) == \"string\"))\n\t\tleftSideChar = this.borderChars.left;\n\tif (this.borderChars.hasOwnProperty(\"right\") && (typeof(this.borderChars.right) == \"string\"))\n\t\trightSideChar = this.borderChars.right;\n\tlineLen = this.size.height - 2;\n\tvar lineNum = 1;\n\tfor (var lineNum = 1; lineNum <= lineLen; ++lineNum)\n\t{\n\t\tconsole.gotoxy(this.pos.x, this.pos.y+lineNum);\n\t\tconsole.print(leftSideChar);\n\t\tconsole.gotoxy(this.pos.x+this.size.width-1, this.pos.y+lineNum);\n\t\tconsole.print(rightSideChar);\n\t}\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 FormDivider() {\n const t = useTranslation();\n\n return (\n <Box\n sx={{\n display: 'flex',\n alignItems: 'center',\n }}\n >\n <Box sx={{ flex: 1 }} clone>\n <Divider />\n </Box>\n <Box\n component=\"span\"\n sx={{\n color: 'text.secondary',\n px: 1,\n textTransform: 'uppercase',\n }}\n >\n {t('or')}\n </Box>\n <Box sx={{ flex: 1 }} clone>\n <Divider />\n </Box>\n </Box>\n );\n}",
"get lineBreak() {\n return this.facet(EditorState.lineSeparator) || '\\n'\n }",
"function SplitterItem(widget, handle, alignment) {\n if (alignment === void 0) { alignment = 0; }\n _super.call(this, widget, alignment);\n this._m_handle = handle;\n }",
"function SRAOS_Divider(div, container, min, max, horz, comp1, comp2, hide, hideBuffer, hideThreshold) {\r\n div.dividerContainer = container;\r\n div.dividerHorz = horz;\r\n div.dividerComp1 = comp1;\r\n div.dividerComp2 = comp2;\r\n div.dividerHide = hide;\r\n div.dividerHideBuffer = hideBuffer;\r\n div.dividerVisibility = div.style.visibility ? div.style.visibility : 'inherit';\r\n div.hideThreshold = hideThreshold ? hideThreshold : 5;\r\n \r\n div.onDragStartDivider = div.onDragStart ? div.onDragStart : null;\r\n div.onDragStart = function(x, y) {\r\n this.baseDividerPos = this.dividerHorz ? y : x;\r\n for(var i=0; i<this.dividerComp1.length; i++) {\r\n var div = typeof this.dividerComp1[i] == 'string' ? document.getElementById(this.dividerComp1[i]) : this.dividerComp1[i];\r\n if (div) {\r\n div.baseDividerLen = this.dividerHorz ? parseInt(div.style.height) : parseInt(div.style.width);\r\n }\r\n //alert(this.dividerComp1[i].id + ' base: ' + this.dividerComp1[i].baseDividerLen);\r\n }\r\n for(var i=0; i<this.dividerComp2.length; i++) {\r\n var div = typeof this.dividerComp2[i] == 'string' ? document.getElementById(this.dividerComp2[i]) : this.dividerComp2[i];\r\n if (div) {\r\n div.baseDividerLen = this.dividerHorz ? parseInt(div.style.height) : parseInt(div.style.width);\r\n div.baseDividerPos = this.dividerHorz ? parseInt(div.style.top) : parseInt(div.style.left);\r\n }\r\n //alert(this.dividerComp2[i].id + ' base len/pos: ' + this.dividerComp2[i].baseDividerLen + '/' + this.dividerComp2[i].baseDividerPos);\r\n }\r\n if (this.onDragStartDivider) { this.onDragStartDivider(); }\r\n };\r\n \r\n div.onDragDivider = div.onDrag ? div.onDrag : null;\r\n div.onDrag = function(x, y) {\r\n var pos = this.dividerHorz ? y : x;\r\n for(var i=0; i<this.dividerComp1.length; i++) {\r\n var div = typeof this.dividerComp1[i] == 'string' ? document.getElementById(this.dividerComp1[i]) : this.dividerComp1[i];\r\n if (div) {\r\n if (this.dividerHide == 1 && this.noDrag) {\r\n if (div.style.visibility != 'hidden') {\r\n div.style.visibility = 'hidden';\r\n div._dividerShow = true;\r\n }\r\n }\r\n else {\r\n if (this.dividerHide == 1 && div._dividerShow) {\r\n div.style.visibility = 'inherit';\r\n div._dividerShow = false;\r\n }\r\n else {\r\n var newLen = div.baseDividerLen + (pos - this.baseDividerPos);\r\n newLen = newLen < 0 ? 0 : newLen;\r\n div.style[this.dividerHorz ? 'height' : 'width'] = newLen + \"px\";\r\n div.style.visibility = newLen > this.hideThreshold ? this.dividerVisibility : \"hidden\";\r\n //alert(div.id + ' base: ' + div.baseDividerLen + ' new ' + (this.dividerHorz ? 'height' : 'width') + ': ' + newLen + \" visible: \" + div.style.visibility);\r\n }\r\n }\r\n }\r\n }\r\n for(var i=0; i<this.dividerComp2.length; i++) {\r\n var div = typeof this.dividerComp2[i] == 'string' ? document.getElementById(this.dividerComp2[i]) : this.dividerComp2[i];\r\n if (div) {\r\n if (this.dividerHide == 2 && this.noDrag) {\r\n if (div.style.visibility != 'hidden') {\r\n div.style.visibility = 'hidden';\r\n div._dividerShow = true;\r\n }\r\n }\r\n else {\r\n var newPos = div.baseDividerPos + (pos - this.baseDividerPos);\r\n newPos = newPos < 0 ? 0 : newPos;\r\n div.style[this.dividerHorz ? 'top' : 'left'] = newPos + \"px\";\r\n if (div.canDrag) {\r\n if (this.dividerHorz) {\r\n var diff = newPos - div.baseY;\r\n div.baseY = newPos;\r\n if (div.minY) {\r\n div.minY = div.minY + diff;\r\n div.maxY = div.maxY + diff;\r\n }\r\n }\r\n else {\r\n var diff = newPos - div.baseX;\r\n div.baseX = newPos;\r\n if (div.minX) {\r\n div.minX = div.minX + diff;\r\n div.maxX = div.maxX + diff;\r\n }\r\n }\r\n }\r\n \r\n if (this.dividerHide == 2 && div._dividerShow) {\r\n div.style.visibility = 'inherit';\r\n div._dividerShow = false;\r\n }\r\n else {\r\n var newLen = div.baseDividerLen - (pos - this.baseDividerPos);\r\n newLen = newLen < 0 ? 0 : newLen;\r\n div.style[this.dividerHorz ? 'height' : 'width'] = newLen + \"px\";\r\n div.style.visibility = newLen > this.hideThreshold ? this.dividerVisibility : \"hidden\";\r\n }\r\n }\r\n \r\n //alert(div.id + ' base len/pos: ' + div.baseDividerLen + '/' + div.baseDividerPos + ' new ' + (this.dividerHorz ? 'height' : 'width') + '/' + (this.dividerHorz ? 'top' : 'left') + ': ' + newLen + '/' + newPos + \" visible: \" + div.style.visibility);\r\n }\r\n }\r\n if (this.onDragDivider) { this.onDragDivider(); }\r\n };\r\n \r\n if (hide == 1 || hide == 2) {\r\n div.onDragResetStartDivider = div.onDragResetStart ? div.onDragResetStart : null;\r\n div.onDragResetStart = function(x, y) {\r\n this.noDrag = false;\r\n \r\n // hide components\r\n if (parseInt(this.dividerHorz ? this.style.top : this.style.left) == (this.dividerHorz ? this.baseY : this.baseX)) {\r\n this.noDrag = true;\r\n }\r\n \r\n // show components\r\n else if ((this.dividerHorz ? this.style.top : this.style.left) == (this.dividerHide == 1 ? \"0px\" : this.dividerContainer.offsetWidth)) {\r\n this.style[this.dividerHorz ? 'top' : 'left'] = (this.dividerHorz ? this.baseY : this.baseX) + \"px\";\r\n }\r\n this.onDragStart(parseInt(this.style.left), parseInt(this.style.top));\r\n if (this.onDragResetStartDivider) { this.onDragResetStartDivider(); }\r\n };\r\n div.hide = function() {\r\n this.ondblclick();\r\n if (!this.noDrag) { this.ondblclick(); }\r\n };\r\n div.show = function() {\r\n if (this.noDrag) { this.ondblclick(); }\r\n };\r\n div.toggleShowHide = function() {\r\n this.noDrag ? this.show() : this.hide();\r\n };\r\n \r\n div.onDragResetEndDivider = div.onDragResetEnd ? div.onDragResetEnd : null;\r\n div.onDragResetEnd = function(x, y) {\r\n if (this.noDrag) {\r\n var newPos = parseInt(this.dividerHide == 1 ? 0 : parseInt(this.dividerHide ? this.dividerContainer.offsetHeight : this.dividerContainer.offsetWidth));\r\n var eqZero = newPos == 0;\r\n newPos = eqZero ? 0 : newPos - parseInt(this.dividerHorz ? this.offsetHeight : this.offsetWidth);\r\n if (this.dividerHideBuffer) {\r\n newPos = eqZero ? newPos + this.dividerHideBuffer : newPos - this.dividerHideBuffer;\r\n }\r\n this.style[this.dividerHorz ? 'top' : 'left'] = newPos + \"px\";\r\n }\r\n this.onDrag(parseInt(this.style.left), parseInt(this.style.top));\r\n if (this.onDragResetEndDivider) { this.onDragResetEndDivider(); }\r\n };\r\n }\r\n else {\r\n div.onDragResetStart = div.onDragResetStart ? div.onDragResetStart : div.onDragStart;\r\n div.onDragResetEnd = div.onDragResetEnd ? div.onDragResetEnd : div.onDrag;\r\n }\r\n \r\n Drag.init(div, div, horz ? parseInt(div.style.left) : min, horz ? parseInt(div.style.left) : max, horz ? min : parseInt(div.style.top), horz ? max : parseInt(div.style.top));\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check whether the specified guest is invited to the specified event. If so it returns the answer, otherwise it returns false. | function is_in_guest_list(event, guest){
var guests = event.getGuestList();
for (var j=0; j<guests.length; j++) {
//Logger.log("Check guest "+guests[j].getEmail());
if(guests[j].getEmail()==guest){
var answer = guests[j].getGuestStatus();
//Logger.log("Answer of "+guest+": "+answer)
return answer;
}
}
return false;
} | [
"function responseGameInvitation(e){\n\tvar recipientName = $(this).data(\"name\");\n\tif(recipientName == undefined || localStorage.gameTurn != undefined){\n\t\treturn false;\n\t}\n\tif(userNameChecker(recipientName)){\n\t\tvar recipientGameObject = getGameObject(recipientName);\n\t\tvar data = {\n\t\t\t\"recipientName\": recipientName,\n\t\t\t\"session\" : localStorage.sessionId,\n\t\t\t\"gameNum\" : recipientGameObject.gameNum\n\t\t};\n\t\tlocalStorage.setItem(\"gameTurn\", 0);\n\t\tperformPostRequest(\"invitation-response.php\", data, function(data){\n\t\t\tswitch(data.status) {\n\t\t\t\tcase 470:\n\t\t\t\t\tlocalStorage.removeItem('gameTurn');\n\t\t\t\t\tlogOut();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 200:\n\t\t\t\t\tlocalStorage.setItem(\"gameAreaClickCounter\", 0);\n\t\t\t\t\tlocalStorage.setItem(\"currentGameNum\", recipientGameObject.gameNum);\n\t\t\t\t\tbeginGame(recipientName);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 400:\n\t\t\t\t\tlocalStorage.removeItem('gameTurn');\n\t\t\t\t\tshowErrorMessage(\"Този потребител вече играе с друг играч!\", 1);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tlocalStorage.removeItem('gameTurn');\n\t\t\t}\n\t\t});\n\t}\n\telse\n\t{\n\t\tshowErrorMessage(\"Възникна проблем при опита за отговор на тази покана за игра!\");\n\t}\n}",
"async getInvitationsByEventId(req, res) {\n const userAuth = jwt_decode(req.token);\n const { event_id } = req.params;\n\n try {\n const user = await User.findOne({ cognito_id: userAuth.sub });\n\n // Check if user exist\n if (!user) {\n return res.status(400).json({\n errMessage: 'User Not Found',\n });\n }\n\n const event = await Event.findById(event_id);\n\n if (!event) {\n return res.status(400).json({\n errMessage: 'Event Not Found',\n });\n }\n\n const invitations = await Invitation.find({\n event_id: event._id,\n is_going: null,\n })\n .populate('user_id')\n .exec();\n\n return res.status(200).json({\n invitations,\n });\n } catch (error) {\n throw Error(`Error while getting invitation: ${error}`);\n }\n }",
"isUserEvent(event) {\n let e = this.annotation(Transaction.userEvent)\n return !!(\n e &&\n (e == event ||\n (e.length > event.length &&\n e.slice(0, event.length) == event &&\n e[event.length] == '.'))\n )\n }",
"function checkUserToInvite(current_user, invite_user, element) {\n if(!isBlank(invite_user)) {\n\tif(current_user !== invite_user) {\n\t if(checkUserExistence(invite_user)) {\n\t\treturn true;\n\t } else {\n\t\tsetElementBackgroundColor(element, 'red');\n\t\talert('The user you are trying to invite,\\ndoes not exist!\\nPlease, try again ...');\n\t\treturn false;\n\t }\n\t} else {\n\t setElementBackgroundColor(element, 'red');\n\t alert('You cannot invite yourself!\\nPlease, try again ...')\n\t return false;\n\t}\n } else {\n\tsetElementBackgroundColor(element, 'red');\n }\n}",
"invite(userId, invitedId) {\n // use date for sorted set ordering\n return new Promise((resolve, reject) => {\n this.client.zadd(\n `${this.namespace}:user:${invitedId}:${STATE_KEY.invited}`,\n Date.now(),\n userId,\n (err, res) => {\n if (err) { reject(err); }\n debug(`${userId} invited ${invitedId}`);\n return resolve(res);\n });\n });\n }",
"function isEventEditable(event) {\n if (!event || !event.calendarId) {\n return;\n }\n\n findEventOrganizer(event);\n\n var calendarsManager = enyo.application.calendarsManager,\n isWriteable = !calendarsManager.isCalendarReadOnly(event.calendarId),\n attendees = getActiveAttendees(event),\n numAttendees = attendees && attendees.length,\n organizer = numAttendees && event.organizer,\n accountUserName = numAttendees && calendarsManager.getCalAccountUser(event.calendarId),\n organizerEmail = organizer && organizer.email && organizer.email.toLowerCase(),\n youAreOrganizer = organizerEmail && accountUserName && organizerEmail == accountUserName.toLowerCase();\n\n return isWriteable && (!numAttendees || youAreOrganizer);\n }",
"function acceptMeetingRequest() {\n return confirm(\"Are you sure you want to accept a meeting request from this mentee?\");\n}",
"function isMessageFromOpponent(data)\n{\n // Is it from our opponent and is it intended for us?\n return (data.payload.sender == g_remote_uuid && data.payload.target == g_local_uuid);\n}",
"function checkForInvites() {\n debug('Checking for repository invites');\n github.users.getRepoInvites({}).then(invites => {\n invites.forEach(invite => {\n debug('Accepting repository invite', invite.full_name);\n github.users.acceptRepoInvite(invite);\n });\n });\n\n debug('Checking for organization invites');\n github.orgs.getOrganizationMemberships({state: 'pending'}).then(invites => {\n invites.forEach(invite => {\n debug('Accepting organization invite', invite.organization.login);\n github.users.editOrganizationMembership({\n org: invite.organization.login,\n state: 'active'\n });\n });\n });\n}",
"function shouldShowEvent(event) {\n\n // Hack to remove canceled Office 365 events.\n if (event.title.startsWith(\"Canceled:\")) {\n return false\n }\n\n // If it's an all-day event, only show if the setting is active.\n if (event.isAllDay) {\n return showAllDay\n }\n\n // Otherwise, return the event if it's in the future.\n return (event.startDate.getTime() > date.getTime())\n}",
"function hasEvent(eventsNames, oneEvent){\n\t\t for (var i=0; i<eventsNames.length; i++) {\n\t\t if ( eventsNames[i] == oneEvent ) {\n\t\t return true;\n\t\t }\n\t\t }\n\t\t return false;\n\t\t}",
"function checkEngage(cell, opponent) {\n if (cell === opponent) {\n // TODO: basic support for eating power-ball (which is not in the game yet)\n if (gPacman.isSuper) {\n console.log('Ghost is dead');\n } else {\n clearInterval(gIntervalGhosts);\n gIntervalGhosts = undefined;\n gState.isGameDone = true;\n // TODO: GameOver popup with a play again button\n console.log('Game Over!');\n return true;\n }\n }\n return false;\n}",
"function acceptMentorshipRequest() {\n return confirm(\"Are you sure you want to accept a mentorship request from this mentee?\");\n}",
"function hasMoveEnergy(unit)\n\t\t{\n\t\t\tvar index = serverUtility.getUnitIndex(boardgameserver.userID);\n\t\t\tvar actualUnit = units[index][unit];\n\t\t\tconsole.log(\"Player: \" + boardgameserver.userID);\n\t\t\tconsole.log(\"Get unit index: \" + serverUtility.getUnitIndex(boardgameserver.userID));\n\t\t\tconsole.log(\"Test Position: \" + actualUnit.position); \n\t\t\tconsole.log(\"Energy: \" + actualUnit.energy);\n\t\t\tconsole.log(\"Move Cost: \" + actualUnit.movecost); \n\n\t\t\tif (actualUnit.energy >= actualUnit.movecost)\n\t\t\t{\n\t\t\t\tconsole.log(\"Movement granted\");\n\t\t\t\t//actualUnit.energy = actualUnit.energy - actualUnit.movecost;\n\t\t\t\treturn true; \n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tconsole.log(\"You don't have enough energy to move!\");\n\t\t\t\treturn false; \n\t\t\t}\n\t\t}",
"function hasHitEnemy(abuser, victim) {\n let result = false;\n if(abuser.hurtbox && abuser.hurtbox.isActive && victim.hitbox && victim.hitbox.isActive) {\n result = abuser.hurtbox.x < victim.hitbox.x + victim.hitbox.width\n && abuser.hurtbox.x + abuser.hurtbox.width > victim.hitbox.x\n && abuser.hurtbox.y < victim.hitbox.y + victim.hitbox.height\n && abuser.hurtbox.y + abuser.hurtbox.height > victim.hitbox.y;\n }\n // if(result) console.log(result);\n return result;\n}",
"_hasTrackOrFail (agentId, dnaAddress, requestId) {\n // Check if receiver is known\n if (this._ipcHasTrack(agentId, dnaAddress)) {\n log.t(' oooo HasTrack() CHECK OK for (agent) \"' + agentId + '\" -> (DNA) \"' + dnaAddress + '\"')\n return true\n }\n // Send FailureResult back to IPC\n log.e(' #### HasTrack() CHECK FAILED for (agent) \"' + agentId + '\" -> (DNA) \"' + dnaAddress + '\"')\n this._ipcSend('json', {\n method: 'failureResult',\n dnaAddress: dnaAddress,\n _id: requestId,\n toAgentId: agentId,\n errorInfo: 'This agent is not tracking DNA: \"' + dnaAddress + '\"'\n })\n // Done\n return false\n }",
"function hasEvent(event, entry){\n return entry.events.indexOf(event) != -1;\n}",
"function checkIfEvent(redditData, db, r) {\n if (redditData.title.toLowerCase().includes(eventMentioned)) {\n sendModMailAlert(redditData, db, r);\n replyToEventHost(redditData);\n r.getSubmission(redditData.name).remove({\n spam: true\n }).then(function (error) {\n console.log(error);\n });\n } else {\n db.run(\"INSERT INTO redditPost (name, processed) VALUES ('\" + redditData.name + \"', '1')\");\n }\n}",
"function enterPressed(event) {\n event = event || window.event;\n if(event.which) { return(event.which == 13); }\n else { return(event.keyCode == 13); }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load transactions for the main chart graph. | loadGraph(){
var current = this;
var servicePathAPI = baseURL+'/api/transactions/all/'+ this.dataToken;
$.getJSON(servicePathAPI, function (data) {
var result = data;
if(result){
var series = [];
var categories = [];
for(var i=0;i < result.length;i++){
var item = result[i];
var transDate = new Date(item[0]);
var transAmount = item[1];
categories.push( moment( transDate.getTime() ).format("MM/DD/YYYY") );
current._chartData.push( [ transDate, transAmount] );
}
}
// Create the transactions chart
this._transactionChart = Highcharts.chart('mainChart', {
rangeSelector : {
selected : 1,
allButtonsEnabled: true
},
chart: {
zoomType: 'x',
alignTicks: false
},
title : {
text : 'Transaction Volume'
},
xAxis: {
type: 'datetime',
categories: categories
},
yAxis: {
title: {
text: 'USD'
}
},
tooltip: {
formatter: function() {
return 'Date: <b>' + moment(this.x).format("MM/DD/YYYY") + '</b> <br/> Amount: <b>$' + accounting.format(this.y) + '</b>';
}
},
series : [{
name : 'Transactions',
fillColor : {
linearGradient : {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops : [
[0, Highcharts.getOptions().colors[0]],
[1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
]
},
data : current._chartData
}]
});
});
} | [
"async function OnLoadTransactions() {\n const write_key = JSON.parse(localStorage.getItem('microprediction_key_current'))[0];\n const url = base_url+write_key+\"/\";\n resp = await get(url);\n await LoadTransactions();\n document.getElementById(\"box-href\").href = \"transactions/\" + write_key + \"/\";\n document.getElementById(\"box-info-loaded-from\").style.display = \"inline-block\"; \n}",
"function initCharts() {\n xmlHttpReq('GET', '/storages_data', '', function(responseText) {\n var response = JSON.parse(responseText);\n if (response.success) {\n drawCharts(response.data);\n } else {\n snackbar(response.message);\n }\n });\n}",
"function prepare_data() {\n nodes = [];\n links = [];\n\n var txn_nodes = [];\n // Each transaction will be a link.\n // Every source and target will have one link with sum of transactions between them\n\n //aggregate all transactions between same addresses\n var sender_receiver = {};\n var accounts_aggregates = {};\n chart_data.forEach(function (d) {\n var receivers = null;\n\n d.amount = parseFloat(d.amount)\n d.sender_balance = parseFloat(d.sender_balance)\n d.receiver_balance = parseFloat(d.receiver_balance)\n \n if (d.sender in sender_receiver) {\n receivers = sender_receiver[d.sender];\n //If sender and receiver are already in just add them up\n if (d.receiver in receivers) {\n receivers[d.receiver] = receivers[d.receiver] + d.amount;\n }\n // Only sender is in so create new receiver for sender\n else {\n receivers[d.receiver] = d.amount;\n }\n }\n // If receiver was a sender before then check if sender was a receiver and add those up\n else if (d.receiver in sender_receiver) {\n receivers = sender_receiver[d.receiver];\n if (d.sender in receivers) {\n receivers[d.sender] = receivers[d.sender] + d.amount;\n }\n }\n // else create new sender and receiver\n else {\n sender_receiver[d.sender] = {};\n sender_receiver[d.sender][d.receiver] = d.amount;\n }\n\n // Now also put in account aggregates\n var total_payments = 0;\n var total_receipts = 0;\n if (d.sender in accounts_aggregates) {\n total_payments = accounts_aggregates[d.sender].payments;\n } else {\n accounts_aggregates[d.sender] = { payments: 0, receipts: 0 };\n }\n\n if (d.receiver in accounts_aggregates) {\n total_receipts = accounts_aggregates[d.receiver].receipts;\n } else {\n accounts_aggregates[d.receiver] = { payments: 0, receipts: 0 };\n }\n\n accounts_aggregates[d.sender].payments = total_payments + d.amount;\n accounts_aggregates[d.receiver].receipts = total_receipts + d.amount;\n });\n\n // Get all addresses which will be nodes\n // Start with senders then go to receivers\n d3_nest()\n .key(function (d) {\n return d.sender;\n })\n .rollup(function (values) {\n var txn = values[0];\n txn_nodes.push({ id: txn.sender, account_type: txn.sender_type });\n })\n .entries(chart_data);\n\n // Now get receivers\n d3_nest()\n .key(function (d) {\n return d.receiver;\n })\n .rollup(function (values) {\n var txn = values[0];\n txn_nodes.push({ id: txn.receiver, account_type: txn.receiver_type });\n })\n .entries(chart_data);\n\n // Reduce to unique set of nodes\n d3_nest()\n .key(function (d) {\n return d.id;\n })\n .rollup(function (values) {\n var node = values[0];\n nodes.push({\n id: node.id,\n account_type: node.account_type,\n payments: accounts_aggregates[node.id].payments,\n receipts: accounts_aggregates[node.id].receipts,\n });\n })\n .entries(txn_nodes);\n\n var nodes_keys = d3_nest()\n .key(function (d) {\n return d.id;\n })\n .map(nodes)\n .keys();\n\n for (var sender in sender_receiver) {\n var receivers = sender_receiver[sender];\n\n for (var receiver in receivers) {\n links.push({\n source: nodes_keys.indexOf(sender),\n target: nodes_keys.indexOf(receiver),\n value: receivers[receiver],\n });\n }\n }\n\n linkWidthScale.domain(\n d3.extent(links, function (d) {\n return d.value;\n })\n );\n\n linkStrengthScale.domain(\n d3.extent(links, function (d) {\n return d.value;\n })\n );\n }",
"function loadWeeklyCharts () {\n\tchartsCurrentLevel = chartsLevel.weekly;\n\tchartsCurrentDays = 7;\n\tchartsDateFormat = '%b %e';\n\n\t// reset the charts monthly period\n\tchartsMonthlyPeriod = 0;\n\n\t// taking care of weird situations when the period might be out of bounds\n\tif (chartsWeeklyPeriod < chartsMinWeeklyPeriod) {\n\t\tchartsWeeklyPeriod = chartsMinWeeklyPeriod;\n\t} else if (chartsWeeklyPeriod > chartsMaxWeeklyPeriod) {\n\t\tchartsWeeklyPeriod = chartsMaxWeeklyPeriod;\n\t}\n\n\tvar todayStr = Util.getDateStr(Util.today());\n\tfor (var i = 0; i < chartsData.days.length; i++) {\n\t\tif (chartsData.days[i] == todayStr) {\n\t\t\tvar sliceStart = i - 1; // start from yesterday\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tvar sliceEnd = sliceStart + 7;\n\n\t// if the slice end is 0 then we need to make it (-1 for the above day in the past)\n\tif (sliceEnd === 0) {\n\t\tsliceEnd = chartsData.days.length - 1;\n\t}\n\n\t//console.log(\"Start: %d End: %d\", sliceStart, sliceEnd);\n\t// set the categories and series for all charts\n\tchartsData.currentAxisCategories = chartsData.days.slice(sliceStart, sliceEnd);\n\tchartsData.maxt.currentSeries = chartsData.maxt.data.slice(sliceStart, sliceEnd);\n\tchartsData.mint.currentSeries = chartsData.mint.data.slice(sliceStart, sliceEnd);\n\tchartsData.temperature.currentSeries = chartsData.temperature.data.slice(sliceStart, sliceEnd);\n\tchartsData.qpf.currentSeries = chartsData.qpf.data.slice(sliceStart, sliceEnd);\n\tchartsData.rain.currentSeries = chartsData.rain.data.slice(sliceStart, sliceEnd);\n\tchartsData.et0.currentSeries = chartsData.et0.data.slice(sliceStart, sliceEnd);\n\n\tfor (var programIndex = 0; programIndex < chartsData.programs.length; programIndex++) {\n\t\tchartsData.programs[programIndex].currentSeries = chartsData.programs[programIndex].data.slice(sliceStart, sliceEnd);\n\t\tchartsData.programsFlags[programIndex].currentSeries = chartsData.programsFlags[programIndex].data.slice(sliceStart, sliceEnd);\n\t}\n\n\t// render all charts with the currentAxisCategories and currentSeries\n\tgenerateCharts();\n\n\t//For water gauge show only last week (today - 7)\n\tsetWaterSavedValueForDays(chartsCurrentDays);\n\tgenerateWaterSavedGauge();\n}",
"function loadMonthlyCharts () {\n\tchartsCurrentLevel = chartsLevel.monthly;\n\tchartsCurrentDays = 30;\n\tchartsDateFormat = '%b %e';\n\n\t// reset the charts weekly period\n\tchartsWeeklyPeriod = 0;\n\n\t// taking care of weird situations when the period might be out of bounds\n\tif (chartsMonthlyPeriod < chartsMinMonthlyPeriod) {\n\t\tchartsMonthlyPeriod = chartsMinMonthlyPeriod;\n\t} else if (chartsMonthlyPeriod > chartsMaxMonthlyPeriod) {\n\t\tchartsMonthlyPeriod = chartsMaxMonthlyPeriod;\n\t}\n\n\tvar todayStr = Util.getDateStr(Util.today());\n\tfor (var i = 0; i < chartsData.days.length; i++) {\n\t\tif (chartsData.days[i] == todayStr) {\n\t\t\tvar sliceStart = i - 30;\n\t\t\tvar sliceEnd = i + 1; //including today\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// if the slice end is 0 then we need to make it\n\tif (sliceEnd === 0) {\n\t\tsliceEnd = chartsData.days.length;\n\t}\n\n\t//console.log(\"Monthly start %s : %d end: %d\", todayStr, sliceStart, sliceEnd);\n\n\t// set the categories and series for all charts\n\tchartsData.currentAxisCategories = chartsData.days.slice(sliceStart, sliceEnd);\n\tchartsData.maxt.currentSeries = chartsData.maxt.data.slice(sliceStart, sliceEnd);\n\tchartsData.mint.currentSeries = chartsData.mint.data.slice(sliceStart, sliceEnd);\n\tchartsData.temperature.currentSeries = chartsData.temperature.data.slice(sliceStart, sliceEnd);\n\tchartsData.qpf.currentSeries = chartsData.qpf.data.slice(sliceStart, sliceEnd);\n\tchartsData.rain.currentSeries = chartsData.rain.data.slice(sliceStart, sliceEnd);\n\tchartsData.et0.currentSeries = chartsData.et0.data.slice(sliceStart, sliceEnd);\n\n\tfor (var programIndex = 0; programIndex < chartsData.programs.length; programIndex++) {\n\t\tchartsData.programs[programIndex].currentSeries = chartsData.programs[programIndex].data.slice(sliceStart, sliceEnd);\n\t\tchartsData.programsFlags[programIndex].currentSeries = chartsData.programsFlags[programIndex].data.slice(sliceStart, sliceEnd);\n\t}\n\n\t// render all charts with the currentAxisCategories and currentSeries\n\tgenerateCharts();\n\t//For water gauge show only last month\n setWaterSavedValueForDays(chartsCurrentDays);\n generateWaterSavedGauge();\n}",
"function fundsPrices() {\n loadTable();\n loadShowAll_btn();\n }",
"function addPendingTransactions() {\n blockchain.pendingTransactions.forEach(transaction => {\n const pendingTransactionsTable = document.getElementById(\"newPendingTransactionTable\");\n\n if (!document.getElementById(\"transactionId\") || transaction.transactionId !== document.getElementById(\"transactionId\").innerHTML) {\n let row = pendingTransactionsTable.insertRow();\n let transactionId = row.insertCell(0);\n transactionId.innerHTML = transaction.transactionId;\n transactionId.id = \"transactionId\";\n let txTimestamp = row.insertCell(1);\n txTimestamp.innerHTML = (new Date(transaction.txTimestamp)).toLocaleTimeString();\n let sender = row.insertCell(2);\n sender.innerHTML = transaction.sender;\n let recipient = row.insertCell(3);\n recipient.innerHTML = transaction.recipient;\n let amount = row.insertCell(4);\n amount.innerHTML = transaction.amount;\n } else {\n return;\n };\n });\n }",
"function loadBalances() {\n\tfor (var k = 0; k < form.length; k++) {\n\t\tif (form[k][\"gr\"]){\n\t\t\tform[k][\"amount\"] = calculateGr1Balance(form[k][\"gr\"], form[k][\"vatClass\"], param[\"grColumn\"], param[\"startDate\"], param[\"endDate\"]);\n\t\t}\n\t}\n}",
"function loadDashboard() {\n loadReservations();\n loadTables();\n }",
"static async getEthTransactions() {\n const walletAddress = await this.getWallet().then(wallet =>\n wallet.getAddressString(),\n );\n\n return fetch(\n `https://api.ethplorer.io/getAddressTransactions/${walletAddress}?apiKey=freekey`,\n )\n .then(response => response.json())\n .then(transactions =>\n transactions.map(t => ({\n from: t.from,\n timestamp: t.timestamp,\n transactionHash: t.hash,\n value: t.value.toFixed(2),\n })),\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}",
"transaction() {\n let today = new Date();\n let day = today.getDate();\n let month = today.getMonth() + 1;\n let year = today.getFullYear();\n let time = today.getHours();\n let minutes = today.getMinutes();\n if (day < 10) day = '0' + day;\n if (month < 10) month = '0' + month;\n\n let orderType = 1;\n\n let todaysDate = year + '-' + month + '-' + day + ' ' + time + ':' + minutes + ':00';\n\n if (this.state.inBasket[0].dayRent == true) {\n orderType = 2;\n }\n\n orderService.makeOrder(\n this.state.activeC[0].id,\n orderType,\n todaysDate,\n this.state.inBasket[0].startDate,\n this.state.inBasket[0].endDate,\n this.discPrice,\n employeeID\n );\n\n for (let i = 0; i < this.state.inBasket.length; i++) {\n orderService.makeBikeOrder(this.state.activeC[0].id, todaysDate, this.state.inBasket[i].id);\n }\n\n if (equipmentBasket.length > 0) {\n for (let i = 0; i < equipmentBasket.length; i++) {\n orderService.makeEquipOrder(this.state.activeC[0].id, todaysDate, equipmentBasket[i].id);\n }\n }\n\n basket.length = 0;\n equipmentBasket.length = 0;\n this.totalPrice = 0;\n this.discPrice = 0;\n this.removeCustomer();\n this.updateBasket();\n this.handleClose();\n history.push('/overview/');\n }",
"function loadYearlyCharts () {\n\n\t//TODO: Temporary. Downloads 365 days data when user clicks on year tab\n\tif (!downloadedYearlyData) {\n\t\tmakeHidden($('#dashboard'));\n\t\tmakeVisible($('#pageLoadSpinner'));\n\t\tloadCharts(true, YEARDAYS);\n\t\tdownloadedYearlyData = true;\n\t}\n\n\n\tchartsCurrentLevel = chartsLevel.yearly;\n\tchartsCurrentDays = YEARDAYS;\n\tchartsDateFormat = '%b';\n\n\t// reset the charts weekly and monthly periods\n\tchartsWeeklyPeriod = 0;\n\tchartsMonthlyPeriod = 0;\n\n\t// set the categories and series for all charts\n\tchartsData.currentAxisCategories = chartsData.months;\n\tchartsData.maxt.currentSeries = chartsData.maxt.monthsData;\n\tchartsData.mint.currentSeries = chartsData.mint.monthsData;\n\tchartsData.temperature.currentSeries = chartsData.temperature.monthsData;\n\tchartsData.qpf.currentSeries = chartsData.qpf.monthsData;\n\tchartsData.rain.currentSeries = chartsData.rain.monthsData;\n\tchartsData.et0.currentSeries = chartsData.et0.monthsData;\n\n\tfor (var programIndex = 0; programIndex < chartsData.programs.length; programIndex++) {\n\t\tchartsData.programs[programIndex].currentSeries = chartsData.programs[programIndex].monthsData;\n\t}\n\n\t// render all charts with the currentAxisCategories and currentSeries\n\tgenerateCharts();\n\t//For water gauge show only last year\n setWaterSavedValueForDays(chartsCurrentDays);\n generateWaterSavedGauge();\n}",
"function chartsLoaded() {\n chartLibraryLoaded = true; // Global var which can be checked before attempting to draw chart\n drawChart() // try to draw chart\n}",
"function noOfTransactions() {\n document.getElementById(\"transactions\").textContent = newBlock.transactions.length;\n }",
"function draw_barchart(caso) {\n\n //'Migration Flow' mode\n if (caso==\"splom\") {\n d3.select(\"#chart-container\").selectAll(\".chartjs-size-monitor\").remove();\n d3.select(\"#chart-container\").select(\"canvas\").remove();\n var name_prov_selected = splom_data.find(element => element[\"Codigo\"]==selected_id)[\"Provincia\"];\n if (type==\"flow\") {\n d3.select(\"#chart-container\")\n .style(\"width\",+svg1Width/3+\"px\")\n .style(\"height\",+(25/269)*svg1Height+20650/269+\"px\")\n .style(\"top\",+(86/273)*svg1Height+86.5+\"px\")\n .append(\"canvas\")\n .attr(\"id\",\"myChart\");\n var ctx = $('#myChart');\n window.myHorizontalBar = new Chart(ctx, {\n type: 'horizontalBar',\n data: {\n labels: ylabels,\n datasets: [{\n data: barchar_data,\n label: '# emmigrants',\n backgroundColor: \"#008000\",\n borderColor: '#000000',\n borderWidth: 1\n }]\n },\n options: {\n responsive: true,\n maintainAspectRatio: false,\n scales: {\n yAxes: [{\n ticks: {\n beginAtZero: true\n }\n }]\n },\n legend: {\n display: false\n },\n title: {\n display: true,\n text: '# emmigrants from '+ name_prov_selected\n }\n }\n });\n }\n } \n\n //Variable comparison\n if (caso==\"comp\") {\n Chart.defaults.global.defaultFontFamily = 'Quattrocento Sans';\n Chart.defaults.global.defaultFontSize = 15,\n id_province_select_ant = [];\n var ctx = $('#compChart');\n window.myBar = new Chart(ctx, {\n type: 'bar',\n data: {\n labels: province_select,\n datasets: [{\n data: comp_data,\n barPercentage: 0.7,\n borderColor: '#000000',\n borderWidth: 1\n }]\n },\n options: {\n responsive: true,\n maintainAspectRatio: false,\n scales: {\n yAxes: [{\n ticks: {\n beginAtZero: true\n }\n }]\n },\n legend: {\n display: false,\n },\n title: {\n display: true,\n text: \"\",\n }\n }\n });\n draw_legend_barchart();\n }\n \n}",
"loadStocks() {\n stockService.get((err, data) => {\n if (err) return this.handleError(err);\n\n // the latest list of stocks on database\n const stocks = JSON.parse(data);\n\n // the list of stock symbols's currently on chart\n const chartedStockSymbols = this.stockChart.series.map((series) => {\n return series.name;\n });\n\n stocks.forEach((stock) => {\n // only get the pricing data of not-charted stock symbols\n if (chartedStockSymbols.indexOf(stock) == -1) {\n this.getStock(stock.symbol);\n }\n });\n\n this.stockSocket.start();\n });\n }",
"function init() {\n history = [];\n allTransactionsLoaded = false;\n\n account = StellarNetwork.remote.account(session.get('address'));\n account.on('transaction', function(data) {\n var transaction = {\n tx: data.transaction,\n meta: data.meta\n };\n\n history.unshift(transaction);\n\n $rootScope.$broadcast('transaction-history:new', transaction);\n });\n }",
"function syncBarChart(callback){\n barChartQuery(barChartParams,callback);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
HTML get element's HTML | get html() {
return this.element.innerHTML;
} | [
"get html() {\n return (this._htmlElement || this._element).innerHTML;\n }",
"elementFromHTML(html) {\n const div = document.createElement('div');\n div.innerHTML = html.trim();\n return div.firstChild;\n }",
"function getHtmlContent(){\n \n }",
"function getHtml(element) {\n var html = element.innerHTML;\n html = html.replace(/ class=\"ng-scope\"/g, '');\n html = html.replace(/<span>\\s*<\\/span>/g, '');\n html = html.replace(/\\n/g, '');\n html = html.replace(/<span>\\s+/g, '<span> ');\n html = html.replace(/\\s+<\\/span>/g, ' </span>');\n return html.trim();\n }",
"getHTML() {\n return getHTMLFromFragment(this.state.doc.content, this.schema);\n }",
"function getAllHtml(elements) {\n\n\tvar retArr = jQuery.map(elements, function(item, index) {\n\t\treturn objectOrEmptyString($(item).html())\n\t})\n\n\treturn retArr\n\n}",
"function extPart_getInnerHTML(partName, node)\n{\n var ret = \"\";\n var offsets = extPart_getInnerHTMLOffsets(partName, node);\n\n if ((offsets.begin >= 0) && (offsets.end >= 0))\n {\n ret = dwscripts.getOuterHTML(node).substring(offsets.begin, offsets.end);\n }\n\n return ret;\n}",
"function getInnerContent() {\n if (curOpt.url) {\n return '<iframe src=\\'' + curOpt.url + '\\' horizontalscrolling=\\'no\\' verticalscrolling=\\'no\\' width=\\'' + curOpt.width + '\\' height=\\'' + curOpt.height + '\\' frameBorder=\\'0\\'></iframe>';\n } else if (curOpt.selector) {\n var html = $(curOpt.selector).html();\n return html;\n }\n }",
"getElement(el) {\n return document.getElementsByClassName(el)[0];\n }",
"function get_elem(target) {\n return document.querySelector(target);\n }",
"function getElement(el) {\r\n if (typeof jQuery === 'function' && el instanceof jQuery) {\r\n return el[0];\r\n }\r\n return el;\r\n}",
"function getTextContent(element) {\r\n\r\n if (window.mozilla) {\r\n return element.textContent;\r\n }\r\n else {\r\n return element.innerText\r\n }\r\n}",
"function getElement(type) {\n switch(type) {\n case 'textarea':\n return '<textarea></textarea>';\n case 'button':\n return '<button></button>';\n default:\n return '<input />';\n }\n }",
"get element() {\n return this.dom;\n }",
"adaptarHTML(){\r\n debugger;\r\n //let boddy = '<div><form><input type=\"search\"/><input type=\"search\" id=\"BBB\"/></form></div>'; DUMMY\r\n let boddy = this.state.boddy;\r\n \r\n let processedHTML = '';\r\n \r\n let counter = 1;\r\n let $div = $('<div>').html(boddy);\r\n \r\n //busca los input y les agrega un id (si no lo tienen) y el evento onchange\r\n $div.find('input').attr({\"onChange\":\"window.cambioInput(this)\",'id':function(){\r\n if (this.id === null || this.id ===\"\"){\r\n this.id = \"ID-GENERADO-\" + counter;\r\n counter++;\r\n }\r\n }});\r\n processedHTML = $div.html();\r\n if (boddy !== \"\" && this.modificado === false){\r\n \r\n if (counter> 1){\r\n logger.info(\"El HTML fue modificado correctamente.\");\r\n }else{\r\n logger.info(\"El HTML no contiene inputs.\");\r\n }\r\n this.modificado = true;\r\n \r\n }\r\n return processedHTML;\r\n }",
"function $Html(id, value){\n\n if (typeof value != 'undefined'){\n $O(id).innerHTML = value\n }\n return $O(id).innerHTML\n}",
"function _loadHTML(object, element)\n\t{\n\t\tvar xhttp=_loadHTTP();\n\t\tvar receiver=document.getElementById(element); // elemento recebe\n\t\treceiver.innerHTML='<div id=\"ajaxLoad\"><h1>'+object.title+'</h1><p> </p><p><img src=\"ajax-loader.gif\" /> carregando ...</p></div>'; // animacao carregando\n\t\txhttp.open(\"get\", object.href, true); // carrega a pagina\n\t\t// executada quando o navegador obter codigo\n\t\txhttp.onreadystatechange=function()\n\t\t\t{\n\t\t\t\tif(xhttp.readyState==4)\n\t\t\t\t\t{\n\t\t\t\t\t\tvar content=xhttp.responseText; // le o texto\n\t\t\t\t\t\tvar receiver=document.getElementById(element); // exibe conteudo\n\t\t\t\t\t\treceiver.innerHTML=content; // elemento recebe conteudo\n\t\t\t\t\t}\n\t\t\t}\n\t\txhttp.send(null);\n\t\treturn(false);\n\t}",
"setHtml(element, html){\n element.html(html);\n }",
"function getHTMLTag(tagName) {\n const a = '<'+tagName+'></'+tagName+'>';\n return a;\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a position, calculate the best move using Stockfish Returns a deffered variable | function calcBestMove(game) {
var engine = new UCI(STOCK_PATH);
var deferred = Q.defer();
engine.runProcess().then(function () {
return engine.uciCommand();
}).then(function (idAndOptions) {
return engine.isReadyCommand();
}).then(function () {
return engine.uciNewGameCommand();
}).then(function () {
return engine.positionCommand(game.fen());
}).then(function () {
return engine.goInfiniteCommand(console.log);
}).delay(500).then(function () {
return engine.stopCommand();
}).then(function (bestMove) {
//TODO: Maybe need to translate this to a correct {to, from} dictionary. Maybe not
deferred.resolve(bestMove);
return engine.quitCommand();
}).then(function () {
console.log('Stopped');
}).fail(function (error) {
console.log(error);
deferred.reject(error);
process.exit();
}).done();
return deferred.promise;
} | [
"function makeBestMove() {\n\t\t\t// look for winning move\n\t\t\t//then findBestCorner();\n\t}",
"function computer_move(state) {\n // sends the state to the alphabeta() function to look 4 moves ahead and\n // determine the best move to make\n var moves = alphabeta(state, 4, 'red', Number.MIN_VALUE, Number.MAX_VALUE);\n var max_score = undefined;\n var move = undefined;\n // loops over all of the moves, identifying the move with the highest score,\n // which would be the best to play\n for (var idx = 0; idx < moves.length; idx++) {\n if (max_score === undefined || moves[idx].score > max_score) {\n max_score = moves[idx].score;\n move = {\n x: moves[idx].x,\n y: moves[idx].y\n };\n }\n }\n return move;\n }",
"function makeBestMove(game, color) {\n if (color === 'b')\n {\n var move = getBestMove(game, color, globalSum)[0];\n }\n else\n {\n var move = getBestMove(game, color, -globalSum)[0];\n }\n\n globalSum = evaluateBoard(move, globalSum, 'b');\n\n return move;\n}",
"function findBestMove(board){\n\tconst centerPos = 4;\n\n\tvar sideX = 'x';\n\tvar sideO = 'o';\n\n var boardsToConsider1 = getNextBoards(board, sideO);\n var boardsToConsider2 = getNextBoards(board, sideX);\n\tvar numBoards = boardsToConsider1.length;\n\n\t// first try to see if we can do a move that\n\t// flat out wins the game\n for (var i=0; i<numBoards; i++){\n\t\tvar currOBoard = boardsToConsider1[i];\n\t\tif (determineWinner(currOBoard, sideO)){\n\t\t\treturn currOBoard;\n\t\t}\n\t}\n\n\t// next try to see if we can do a move that\n\t// blocks opponent from winning\n\tfor (var i=0; i<numBoards; i++){\n\t\tvar currXBoard = boardsToConsider2[i];\n\t\tif (determineWinner(currXBoard, sideX)){\n\t\t\tvar blockingBoard = boardsToConsider1[i];\n\t\t\treturn blockingBoard\n\t\t}\n\t}\n\n\tvar nextBoard;\n\t//otherwise, see if we can place it in the center\n\tif (board[centerPos] == ' '){\n\t\tnextBoard = getNextBoard(board, centerPos, sideO);\n\t}\n\t// if center is taken, then just take an arbitrary slot\n\telse{\n\t\tnextBoard = boardsToConsider1[0];\n\t}\n\treturn nextBoard;\n}",
"function computer_move(state) {\n var moves = minimax(state, 4, 'Yellow');\n var max_score = undefined;\n var move = undefined;\n //Loop over list of potential moves picking the one with the highest score.\n for(var idx = 0; idx < moves.length; idx++) {\n if(max_score === undefined || moves[idx].score > max_score) {\n createjs.Sound.play('computer-click');\n //Assign move to the object\n max_score = moves[idx].score;\n move = {\n x: moves[idx].x,\n y: moves[idx].y\n\n }\n }\n }\n //Move returned by the function\n return move;\n}",
"function aiFindBestMove(board) {\n let bestMove = {\n value: -Infinity,\n index: -1\n }\n\n // iterate over empty spots\n for (let i = 0; i < 9; i++) {\n if (!board[i]) {\n // have the ai make a move on the empty spot\n board[i] = game.aiTeam;\n\n // get the value of the move\n const moveValue = minimax(board.slice(), 0, false, -Infinity, Infinity);\n if (moveValue > bestMove.value) {\n bestMove.value = moveValue;\n bestMove.index = i;\n }\n // undo the move\n board[i] = null;\n }\n }\n return bestMove.index;\n}",
"getBestMove(game, allPossbileMoves, exploreChance)\n\t{\n\t\t// find if we go on optimization or exploration\n\t\tif (Math.random() < exploreChance)\n\t\t{\n\t\t\t// explore - TODO: make it chance relative to the performance and not from things we did not see until now\n\t\t\treturn allPossbileMoves[Math.floor(Math.random() * allPossbileMoves.length)];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvar nextStepState = {};\n\t\t\tfor (var i = 0; i < allPossbileMoves.length; i++)\n\t\t\t{\n\t\t\t\tvar nextState = game.get_state_after_move(allPossbileMoves[i]);\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tvar score = this.stateScores[this._convert_state_format(nextState)];\n\t\t\t\t\tif (score == null)\n\t\t\t\t\t{\n\t\t\t\t\t\tthrow \"State not found\";\n\t\t\t\t\t}\n\t\t\t\t\tnextStepState[allPossbileMoves[i].dict_encode()] = score;\n\t\t\t\t}\n\t\t\t\tcatch (error)\n\t\t\t\t{\n\t\t\t\t\tnextStepState[allPossbileMoves[i].dict_encode()] = 0; // new - we did not see it yet \n\t\t\t\t}\n\t\t\t}\n\t\t\t// optimize - get the state with the biggest score \n\t\t\treturn AiMove.dict_decode(Object.keys(nextStepState).reduce((a, b) => nextStepState[a] > nextStepState[b] ? a : b));\n\t\t}\n\t}",
"minimax(newBoard, player) {\n let unvisitedCells = newBoard.unvisitedCells();\n\n if (this.checkWinner(newBoard, this.humanPlayer.identifier)) {\n return { score: -10 };\n } else if (this.checkWinner(newBoard, this.computerPlayer.identifier)) {\n return { score: 10 };\n } else if (unvisitedCells.length === 0) {\n return { score: 0 };\n }\n\n let moves = [];\n for (let i = 0; i < unvisitedCells.length; i++) {\n let move = {};\n move.index = newBoard.board[unvisitedCells[i]];\n newBoard.board[unvisitedCells[i]] = player;\n\n if (player === this.computerPlayer.identifier) {\n let result = this.minimax(newBoard, this.humanPlayer.identifier);\n move.score = result.score;\n } else {\n let result = this.minimax(newBoard, this.computerPlayer.identifier);\n move.score = result.score;\n }\n\n newBoard.board[unvisitedCells[i]] = move.index;\n\n moves.push(move);\n }\n\n let bestMove;\n if (player === this.computerPlayer.identifier) {\n let bestScore = -Infinity;\n for (let i = 0; i < moves.length; i++) {\n if (moves[i].score > bestScore) {\n bestScore = moves[i].score;\n bestMove = i;\n }\n }\n } else {\n let bestScore = Infinity;\n for (let i = 0; i < moves.length; i++) {\n if (moves[i].score < bestScore) {\n bestScore = moves[i].score;\n bestMove = i;\n }\n }\n }\n\n return moves[bestMove];\n }",
"function MiniGameChessStart(Depth) {\n\t\n\tvar MinMaxDepth = Depth;\n\t\t\n\t/**\n\t * Finds a random move to make\n\t * @return {string} move to make\n\t */\n\tvar randomMove = function() {\n\t var possibleMoves = game.moves();\n\t var randomIndex = Math.floor(Math.random() * possibleMoves.length);\n\t return possibleMoves[randomIndex];\n\t};\n\n\t/**\n\t * Evaluates current chess board relative to player\n\t * @param {string} color - Players color, either 'b' or 'w'\n\t * @return {Number} board value relative to player\n\t */\n\tvar evaluateBoard = function(board, color) {\n\t // Sets the value for each piece using standard piece value\n\t var pieceValue = {\n\t\t'p': 100,\n\t\t'n': 350,\n\t\t'b': 350,\n\t\t'r': 525,\n\t\t'q': 1000,\n\t\t'k': 10000\n\t };\n\n\t // Loop through all pieces on the board and sum up total\n\t var value = 0;\n\t board.forEach(function(row) {\n\t\trow.forEach(function(piece) {\n\t\t if (piece) {\n\t\t\t// Subtract piece value if it is opponent's piece\n\t\t\tvalue += pieceValue[piece['type']]\n\t\t\t\t\t * (piece['color'] === color ? 1 : -1);\n\t\t }\n\t\t});\n\t });\n\n\t return value;\n\t};\n\n\t/**\n\t * Calculates the best move looking one move ahead\n\t * @param {string} playerColor - Players color, either 'b' or 'w'\n\t * @return {string} the best move\n\t */\n\tvar calcBestMoveOne = function(playerColor) {\n\t // List all possible moves\n\t var possibleMoves = game.moves();\n\t // Sort moves randomly, so the same move isn't always picked on ties\n\t possibleMoves.sort(function(a, b){return 0.5 - Math.random()});\n\n\t // exit if the game is over\n\t if (game.game_over() === true || possibleMoves.length === 0) return;\n\n\t // Search for move with highest value\n\t var bestMoveSoFar = null;\n\t var bestMoveValue = Number.NEGATIVE_INFINITY;\n\t possibleMoves.forEach(function(move) {\n\t\tgame.move(move);\n\t\tvar moveValue = evaluateBoard(game.board(), playerColor);\n\t\tif (moveValue > bestMoveValue) {\n\t\t bestMoveSoFar = move;\n\t\t bestMoveValue = moveValue;\n\t\t}\n\t\tgame.undo();\n\t });\n\n\t return bestMoveSoFar;\n\t}\n\n\t/**\n\t * Calculates the best move using Minimax without Alpha Beta Pruning.\n\t * @param {Number} depth - How many moves ahead to evaluate\n\t * @param {Object} game - The game to evaluate\n\t * @param {string} playerColor - Players color, either 'b' or 'w'\n\t * @param {Boolean} isMaximizingPlayer - If current turn is maximizing or minimizing player\n\t * @return {Array} The best move value, and the best move\n\t */\n\tvar calcBestMoveNoAB = function(depth, game, playerColor,\n\t\t\t\t\t\t\t\t\tisMaximizingPlayer=true) {\n\t // Base case: evaluate board\n\t if (depth === 0) {\n\t\tvalue = evaluateBoard(game.board(), playerColor);\n\t\treturn [value, null]\n\t }\n\n\t // Recursive case: search possible moves\n\t var bestMove = null; // best move not set yet\n\t var possibleMoves = game.moves();\n\t // Set random order for possible moves\n\t possibleMoves.sort(function(a, b){return 0.5 - Math.random()});\n\t // Set a default best move value\n\t var bestMoveValue = isMaximizingPlayer ? Number.NEGATIVE_INFINITY\n\t\t\t\t\t\t\t\t\t\t\t : Number.POSITIVE_INFINITY;\n\t // Search through all possible moves\n\t for (var i = 0; i < possibleMoves.length; i++) {\n\t\tvar move = possibleMoves[i];\n\t\t// Make the move, but undo before exiting loop\n\t\tgame.move(move);\n\t\t// Recursively get the value of this move\n\t\tvalue = calcBestMoveNoAB(depth-1, game, playerColor, !isMaximizingPlayer)[0];\n\t\t// Log the value of this move\n\t\t//console.log(isMaximizingPlayer ? 'Max: ' : 'Min: ', depth, move, value, bestMove, bestMoveValue);\n\n\t\tif (isMaximizingPlayer) {\n\t\t // Look for moves that maximize position\n\t\t if (value > bestMoveValue) {\n\t\t\tbestMoveValue = value;\n\t\t\tbestMove = move;\n\t\t }\n\t\t} else {\n\t\t // Look for moves that minimize position\n\t\t if (value < bestMoveValue) {\n\t\t\tbestMoveValue = value;\n\t\t\tbestMove = move;\n\t\t }\n\t\t}\n\t\t// Undo previous move\n\t\tgame.undo();\n\t }\n\t // Log the best move at the current depth\n\t //console.log('Depth: ' + depth + ' | Best Move: ' + bestMove + ' | ' + bestMoveValue);\n\t // Return the best move, or the only move\n\t return [bestMoveValue, bestMove || possibleMoves[0]];\n\t}\n\n\t/**\n\t * Calculates the best move using Minimax with Alpha Beta Pruning.\n\t * @param {Number} depth - How many moves ahead to evaluate\n\t * @param {Object} game - The game to evaluate\n\t * @param {string} playerColor - Players color, either 'b' or 'w'\n\t * @param {Number} alpha\n\t * @param {Number} beta\n\t * @param {Boolean} isMaximizingPlayer - If current turn is maximizing or minimizing player\n\t * @return {Array} The best move value, and the best move\n\t */\n\tvar calcBestMove = function(depth, game, playerColor,\n\t\t\t\t\t\t\t\talpha=Number.NEGATIVE_INFINITY,\n\t\t\t\t\t\t\t\tbeta=Number.POSITIVE_INFINITY,\n\t\t\t\t\t\t\t\tisMaximizingPlayer=true) {\n\t // Base case: evaluate board\n\t if (depth === 0) {\n\t\tvalue = evaluateBoard(game.board(), playerColor);\n\t\treturn [value, null]\n\t }\n\n\t // Recursive case: search possible moves\n\t var bestMove = null; // best move not set yet\n\t var possibleMoves = game.moves();\n\t // Set random order for possible moves\n\t possibleMoves.sort(function(a, b){return 0.5 - Math.random()});\n\t // Set a default best move value\n\t var bestMoveValue = isMaximizingPlayer ? Number.NEGATIVE_INFINITY\n\t\t\t\t\t\t\t\t\t\t\t : Number.POSITIVE_INFINITY;\n\t // Search through all possible moves\n\t for (var i = 0; i < possibleMoves.length; i++) {\n\t\tvar move = possibleMoves[i];\n\t\t// Make the move, but undo before exiting loop\n\t\tgame.move(move);\n\t\t// Recursively get the value from this move\n\t\tvalue = calcBestMove(depth-1, game, playerColor, alpha, beta, !isMaximizingPlayer)[0];\n\t\t// Log the value of this move\n\t\t//console.log(isMaximizingPlayer ? 'Max: ' : 'Min: ', depth, move, value, bestMove, bestMoveValue);\n\n\t\tif (isMaximizingPlayer) {\n\t\t // Look for moves that maximize position\n\t\t if (value > bestMoveValue) {\n\t\t\tbestMoveValue = value;\n\t\t\tbestMove = move;\n\t\t }\n\t\t alpha = Math.max(alpha, value);\n\t\t} else {\n\t\t // Look for moves that minimize position\n\t\t if (value < bestMoveValue) {\n\t\t\tbestMoveValue = value;\n\t\t\tbestMove = move;\n\t\t }\n\t\t beta = Math.min(beta, value);\n\t\t}\n\t\t// Undo previous move\n\t\tgame.undo();\n\t\t// Check for alpha beta pruning\n\t\tif (beta <= alpha) {\n\t\t //console.log('Prune', alpha, beta);\n\t\t break;\n\t\t}\n\t }\n\t // Log the best move at the current depth\n\t //console.log('Depth: ' + depth + ' | Best Move: ' + bestMove + ' | ' + bestMoveValue + ' | A: ' + alpha + ' | B: ' + beta);\n\t // Return the best move, or the only move\n\t return [bestMoveValue, bestMove || possibleMoves[0]];\n\t}\n\n\t// Computer makes a move with algorithm choice and skill/depth level\n\tvar makeMove = function(algo, skill=3) {\n\t // exit if the game is over\n\t if (game.game_over() === true) {\n\t\t//console.log('game over');\n\t\treturn;\n\t }\n\t // Calculate the best move, using chosen algorithm\n\t if (algo === 1) {\n\t\tvar move = randomMove();\n\t } else if (algo === 2) {\n\t\tvar move = calcBestMoveOne(game.turn());\n\t } else if (algo === 3) {\n\t\tvar move = calcBestMoveNoAB(skill, game, game.turn())[1];\n\t } else {\n\t\tvar move = calcBestMove(skill, game, game.turn())[1];\n\t }\n\t // Make the calculated move\n\t game.move(move);\n\t // Update board positions\n\t board.position(game.fen());\n\t}\n\n\t// Computer vs Computer\n\tvar playGame = function(algo=4, skillW=2, skillB=2) {\n\t if (game.game_over() === true) {\n\t\t//console.log('game over');\n\t\treturn;\n\t }\n\t var skill = game.turn() === 'w' ? skillW : skillB;\n\t makeMove(algo, skill);\n\t window.setTimeout(function() {\n\t\tplayGame(algo, skillW, skillB);\n\t }, 250);\n\t};\n\n\t// Handles what to do after human makes move.\n\t// Computer automatically makes next move\n\tvar onDrop = function(source, target) {\n\t // see if the move is legal\n\t var move = game.move({\n\t\tfrom: source,\n\t\tto: target,\n\t\tpromotion: 'q' // NOTE: always promote to a queen for example simplicity\n\t });\n\n\t // If illegal move, snapback\n\t if (move === null) return 'snapback';\n\n\t // Log the move\n\t //console.log(move)\n\n\t // make move for black\n\t window.setTimeout(function() {\n\t\tmakeMove(4, MinMaxDepth);\n\t }, 200);\n\t};\n\n\tvar board,\n\t\tgame = new Chess();\n\n\t// Actions after any move\n\tvar onMoveEnd = function(oldPos, newPos) {\n\t // Alert if game is over\n\t if (game.game_over() === true) {\n\t\t//alert('Game Over');\n\t\t//console.log('Game Over');\n\t }\n\n\t // Log the current game position\n\t //console.log(game.fen());\n\t};\n\n\t// Check before pick pieces that it is white and game is not over\n\tvar onDragStart = function(source, piece, position, orientation) {\n\t if (game.game_over() === true || piece.search(/^b/) !== -1) {\n\t\treturn false;\n\t }\n\t};\n\n\t// Update the board position after the piece snap\n\t// for castling, en passant, pawn promotion\n\tvar onSnapEnd = function() {\n\t board.position(game.fen());\n\t};\n\n\t// Creates the board div\n\tif (document.getElementById(\"DivChessBoard\") == null) {\n\t\tvar div = document.createElement(\"div\");\n\t\tdiv.setAttribute(\"ID\", \"DivChessBoard\");\n\t\tdiv.className = \"HideOnDisconnect\";\n\t\tdiv.style.width = \"600px\";\n\t\tdiv.style.height = \"600px\";\n\t\tdocument.body.appendChild(div);\n\t}\n\n\t// Configure the board\n\tvar cfg = {\n\t draggable: true,\n\t position: 'start',\n\t // Handlers for user actions\n\t onMoveEnd: onMoveEnd,\n\t onDragStart: onDragStart,\n\t onDrop: onDrop,\n\t onSnapEnd: onSnapEnd\n\t}\n\tboard = ChessBoard('DivChessBoard', cfg);\n\n\t// Resets the board and shows it\n\tboard.clear();\n\tboard.start();\n\tgame.reset();\n\tMiniGameChessResize();\n\tMiniGameChessBoard = board;\n\tMiniGameChessGame = game;\n\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}",
"function getClosestFood(){\n if (foodList.length == 0){\n return 0;\n } else {\n var curClosest = -1;\n var curDistance = -1;\n for (var i = 0; i < foodList.length; i++){\n var curFood = foodList[i];\n var distance = Math.sqrt(Math.pow(curFood.xLoc - this.xLoc, 2) + Math.pow(curFood.yLoc - this.yLoc, 2));\n if (curClosest == -1){\n curClosest = curFood;\n curDistance = distance;\n } else if (distance < curDistance) {\n curClosest = curFood;\n curDistance = distance;\n }\n }\n return curClosest;\n }\n}",
"function getBestMove(initialBoard, player, levels) {\n\t\tvar initialMoves = getAllMoves(initialBoard, player);\n\t\tvar opponent = (player == 'C') ? 'P' : 'C';\n\t\t// for each move, determine the opponent's best next move (only looking one move ahead)\n\t\t// then determine our best single move given that opponent move and attach that score as the ultimate score of the initial move\n\t\tfor (var i=0; i<initialMoves.length; i++) {\n\t\t\tvar move = initialMoves[i];\n\t\t\tmove.nextMove = getBestBoard(getAllMoves(move.newBoard, opponent));\n\t\t\tif (null == move.nextMove) return;\n\t\t\tif (levels == 0) {\n\t\t\t\t// TODO: try optimizing by not actually computing whole boards here, just score deltas. Is that faster?\n\t\t\t\tmove.mySecondMove = getBestBoard(getAllMoves(move.nextMove.newBoard, player));\n\t\t\t} else {\n\t\t\t\tmove.mySecondMove = getBestMove(move.nextMove.newBoard, player, levels-1);\n\t\t\t}\n\t\t}\n\n\t\t// Get the best initial move based on the ultimate final score resulting from that move\n\t\t// Inject some randomness while we're at it\n\t\tvar best = null;\n\t\tfor (var i=0; i<initialMoves.length; i++) {\n\t\t\tvar move = initialMoves[i];\n\t\t\tif (best == null) best = move;\n\t\t\tif (!best.mySecondMove) {\n\t\t\t\tbest = move\n\t\t\t} else if (!move.mySecondMove) {\n\t\t\t\t// do nothing\n\t\t\t} else if (move.mySecondMove.score > best.mySecondMove.score && Math.random() < 0.8) {\n\t\t\t\tbest = move;\n\t\t\t} else if (move.mySecondMove.score == best.mySecondMove.score && Math.random() < 0.5) {\n\t\t\t\tbest = move;\n\t\t\t}\n\t\t}\n\t\treturn best;\n\t}",
"function checkDesiredPosition(move){\r\n\r\n var checkPosition = document.getElementById(move).value\r\n checkPosition = checkPosition.toLowerCase();\r\n\r\n switch(checkPosition){\r\n case \"5\":\r\n if (playerTurn){\r\n fuel = fuel + 5;\r\n userScore = userScore + 5;\r\n }\r\n else{\r\n computerScore = computerScore + 5;\r\n }\r\n break;\r\n case \"6\":\r\n if (playerTurn){\r\n fuel = fuel + 6;\r\n userScore = userScore + 6;\r\n }\r\n else{\r\n computerScore = computerScore + 6;\r\n }\r\n break;\r\n case \"7\":\r\n if (playerTurn){\r\n fuel = fuel + 7;\r\n userScore = userScore + 7;\r\n }\r\n else{\r\n computerScore = computerScore + 7;\r\n }\r\n break;\r\n case \"8\":\r\n if (playerTurn){\r\n fuel = fuel + 8;\r\n userScore = userScore + 8;\r\n }\r\n else{\r\n computerScore = computerScore + 8;\r\n }\r\n break;\r\n case \"9\":\r\n if (playerTurn){\r\n fuel = fuel + 9;\r\n userScore = userScore + 9;\r\n }\r\n else{\r\n computerScore = computerScore + 9;\r\n }\r\n break;\r\n case \"o\":\r\n if (playerTurn){\r\n document.getElementById(\"outcome\").innerHTML = \"Invalid move, you can't move out of bounds or onto obostacles.\";\r\n userOutOfBounds = true;\r\n round--;\r\n fuel++;\r\n }\r\n else{\r\n killOutOfBounds = true;\r\n }\r\n break;\r\n case \"u\":\r\n userKilled = true;\r\n break;\r\n case \"k\":\r\n if (playerTurn){\r\n userKilled = true;\r\n }\r\n else{\r\n killOutOfBounds = true;\r\n }\r\n break;\r\n }\r\n}",
"function player_max(current_board, player, other_player) {\n // Check if the game is over using the \"game_over\" function above.\n // If the current player wins, returns a high score (say 1000).\n // If the current player loses (other player wins), returns a low score (say -1000).\n // If it is a tie return a neutral score (say 0).\n // If the game is on going continue to the remaining part of the function.\n\n // Get all available moves.\n\n // Loop over available moves to find the move with maximum score.\n // 1. For every move, copy the board and apply the move to the copied board.\n // This is because the code here uses the board as a draft. It tried all\n // possible moves before picking the one it likes best. If we dont copy\n // the board before modifying it, then we effectively commit to the move (choose it)\n // before trying the other moves.\n // 2. After applying the move, call player_min with the new copied board and new player. \n // use the returned score and move to find the maximum.\n\n // Return the maximum score and its corresponding move.\n\n}",
"function hCost(position) {\n return Math.abs(position.x - end_position.x) + Math.abs(position.y - end_position.y);\n }",
"function pickUpNearestCoin() {\n var coin = hero.findNearestItem();\n if (coin)\n hero.move(coin.pos);\n}",
"function maxMove(game){\n return possMoves.reduce(function(maxSoFar, current){\n return evalMove(game, current) > evalMove(game, maxSoFar) ? current : maxSoFar;\n });\n }",
"function findComputerMove(move, state) {\r\n aiService.originalState = move.stateAfterMove;\r\n var tmpMove = {\r\n endMatchScores: move.endMatchScores,\r\n turnIndexAfterMove: move.turnIndexAfterMove,\r\n stateAfterMove: { board: angular.copy(state.board), delta: null } // {board: originalState.board, delta: null} haven't rolled dices yet!!!\r\n };\r\n return createComputerMove(tmpMove);\r\n }",
"function makeMove( state, move ) {\n\tlet player = state.currentPlayer;\n\t// Make sure move is an object with unit# and direction\n\tif ( typeof move != \"object\" ) {\n\t\tstate.players[player].errors++;\n\t\treturn state;\n\t}\n\tif ( typeof move.unit != \"number\" ) {\n\t\tstate.players[player].errors++;\n\t\treturn state;\n\t}\n\tif ( move.unit >= state.players[player].units.length ) {\n\t\tstate.players[player].errors++;\n\t\treturn state;\n\t}\n\tif ( typeof move.direction != \"string\" || move.direction.length != 1 ) {\n\t\tstate.players[player].errors++;\n\t\treturn state;\n\t}\n\tif ( !state.players[player].units[move.unit].canMove ) {\n\t\tstate.players[player].errors++;\n\t\treturn state;\n\t}\n\n\t// Calculate newX and newY\n\tvar newX = state.players[player].units[move.unit].x;\n\tvar newY = state.players[player].units[move.unit].y;\n\tswitch( move.direction ) {\n\t\tcase \"N\":\n\t\t\tnewY -= 1;\n\t\t\tbreak;\n\t\tcase \"E\":\n\t\t\tnewX += 1;\n\t\t\tbreak;\n\t\tcase \"S\":\n\t\t\tnewY += 1;\n\t\t\tbreak;\n\t\tcase \"W\":\n\t\t\tnewX -= 1;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tstate.players[player].errors++;\n\t\t\treturn state;\n\t}\n\n\t// Check for obstacles\n\tif ( obstructed( state, newX, newY ) ) {\n\t\tstate.players[player].errors++;\n\t\treturn state;\n\t}\n\n\t// Make move\n\tstate.players[player].units[move.unit].x = newX;\n\tstate.players[player].units[move.unit].y = newY;\n\n\t// Check to see if farmer is by a farm or the keep\n\tif ( state.players[player].units[move.unit].class == \"farmer\" ) {\n\t\tif ( !state.players[player].units[move.unit].hasFood \n\t\t && state.map[newY][newX].type == \"farm\" ) {\n\t\t\tstate.players[player].units[move.unit].hasFood = true;\n\t\t} else if ( state.players[player].units[move.unit].hasFood\n\t\t && byKeep( state, newX, newY ) ) {\n\t\t\tstate.players[player].units[move.unit].hasFood = false;\n\t\t\tstate.players[player].food += 200;\n\t\t}\n\t}\n\n\t// Disable future moves\n\tstate.players[player].units[move.unit].canMove = false;\n\n\treturn state;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates an OSS session. Providing aliyun access, secret keys and bucket are mandatory Region will use sane defaults if omitted | function OSSAdapter() {
var options = optionsFromArguments(arguments);
this._region = options.region;
this._internal = options.internal;
this._bucket = options.bucket;
this._bucketPrefix = options.bucketPrefix;
this._directAccess = options.directAccess;
this._baseUrl = options.baseUrl;
this._baseUrlDirect = options.baseUrlDirect;
let ossOptions = {
accessKeyId: options.accessKey,
accessKeySecret: options.secretKey,
bucket: this._bucket,
region: this._region,
internal: this._internal
};
this._ossClient = new OSS(ossOptions);
this._ossClient.listBuckets().then((val)=> {
var bucket = val.buckets.filter((bucket)=> {
return bucket.name == this._bucket
}).pop();
this._hasBucket = !!bucket;
});
} | [
"function create(accessKeyId, secretAccessKey) {\n config.accessKeyId = accessKeyId;\n config.secretAccessKey = secretAccessKey;\n\n AWS.config.update(config);\n AWS.config.region = window.AWS_EC2_REGION;\n AWS.config.apiVersions = {\n cloudwatch: '2010-08-01',\n sqs: '2012-11-05'\n };\n\n cloudWatch = new AWS.CloudWatch();\n autoScaling = new AWS.AutoScaling();\n sqs = new AWS.SQS();\n }",
"function genericAWSClient(obj) {\n var securityToken = obj.token;\n var signHeader = obj.signHeader;\n var host = obj.host;\n var accessKeyId = obj.accessKeyId;\n var path = obj.path;\n var agent = obj.agent;\n var secretAccessKey = obj.secretAccessKey;\n var secure = obj.secure == null ? true : false;\n var connection = secure ? https : http;\n\n return {call: call};\n\n function call(action, query, callback) {\n // Wrap the callback to prevent it from being called multiple times.\n callback = (function(next) {\n var isCalled = false;\n return function() {\n if (isCalled) return;\n isCalled = true;\n next.apply(null, arguments);\n }\n })(callback)\n \n // Try to set credentials with metadata API if no credentials provided\n metadata.readCredentials(obj, function(err) {\n if (err) return callback(err);\n var date = new Date();\n\n query = addQueryProperties(query, securityToken, accessKeyId, date);\n var body = qs.stringify(query);\n var headers = createHeaders(host, body.length, date, securityToken, accessKeyId, secretAccessKey);\n sendRequest();\n return;\n\n function sendRequest() {\n var options = {\n host: host,\n path: path,\n agent: agent,\n method: 'POST',\n headers: headers\n };\n var req = connection.request(options, function (res) {\n var data = '';\n //the listener that handles the response chunks\n res.addListener('data', function (chunk) {\n data += chunk.toString()\n })\n res.addListener('end', function() {\n var parser = new xml2js.Parser();\n parser.addListener('end', function(result) {\n if (typeof result != \"undefined\") {\n var err = result.Error || (result.Errors ? result.Errors.Error : null)\n if (err) {\n callback(new Error(err.Message), result)\n } else {\n callback(null, result)\n }\n } else {\n callback(new Error('Unable to parse XML from AWS.'))\n }\n });\n parser.parseString(data);\n })\n res.addListener('error', callback)\n });\n req.write(body)\n req.addListener('error', callback)\n req.end()\n }\n });\n }\n\n function addQueryProperties(query, securityToken, accessKeyId, date) {\n var extendedQuery = _.clone(query);\n if (securityToken) extendedQuery[\"SecurityToken\"] = securityToken;\n extendedQuery[\"Timestamp\"] = date.toISOString();\n extendedQuery[\"AWSAccessKeyId\"] = accessKeyId;\n extendedQuery[\"Signature\"] = signQuery(extendedQuery);\n return extendedQuery;\n }\n\n function createHeaders(host, bodyLength, date, securityToken, accessKeyId, secretAccessKey) {\n var headers = {\n \"Host\": host,\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=utf-8\",\n \"Content-Length\": bodyLength\n };\n\n if (signHeader) {\n headers[\"Date\"] = date.toUTCString();\n if (securityToken !== undefined) headers[\"x-amz-security-token\"] = securityToken;\n headers[\"x-amzn-authorization\"] =\n \"AWS3-HTTPS \" +\n \"AWSAccessKeyId=\" + accessKeyId + \", \" +\n \"Algorithm=HmacSHA256, \" +\n \"Signature=\" + utils.hmacSha256(secretAccessKey, date.toUTCString());\n }\n return headers;\n }\n\n function signQuery(query) {\n var keys = []\n var sorted = {}\n\n for(var key in query)\n keys.push(key)\n\n keys = keys.sort()\n\n for(var n in keys) {\n var key = keys[n]\n sorted[key] = query[key]\n }\n var stringToSign = [\"POST\", host, path, qs.stringify(sorted)].join(\"\\n\");\n\n // Amazon signature algorithm seems to require this\n stringToSign = stringToSign.replace(/!/g,\"%21\");\n stringToSign = stringToSign.replace(/'/g,\"%27\");\n stringToSign = stringToSign.replace(/\\*/g,\"%2A\");\n stringToSign = stringToSign.replace(/\\(/g,\"%28\");\n stringToSign = stringToSign.replace(/\\)/g,\"%29\");\n\n return utils.hmacSha256(secretAccessKey, stringToSign);\n }\n}",
"constructor(accessKey, secretKey, region, bucket, callback) {\n\t\tthis._s3 = null;\n\t\tthis._bucket = bucket;\n\t\tlet scriptTag = document.createElement('script');\n\t\tscriptTag.src = 'aws-sdk.min.js';\n\t\tscriptTag.onload = function () {\n\t\t\tAWS.config.update({\n\t\t\t\taccessKeyId: accessKey,\n\t\t\t\tsecretAccessKey: secretKey,\n\t\t\t\tregion: region\n\t\t\t});\n\t\t\tthis._s3 = new AWS.S3();\n\t\t\tcallback();\n\t\t}.bind(this);\n\t\tdocument.body.appendChild(scriptTag);\n\t}",
"async function createSession() {\n const idvClient = new IDVClient(config.YOTI_CLIENT_SDK_ID, config.YOTI_PEM);\n\n const sessionSpec = new SessionSpecificationBuilder()\n .withClientSessionTokenTtl(600)\n .withResourcesTtl(90000)\n .withUserTrackingId('some-user-tracking-id')\n // For zoom liveness check [only one type of liveness check to be enabled at a time]\n .withRequestedCheck(new RequestedLivenessCheckBuilder()\n .forZoomLiveness()\n .build())\n // For static liveness check\n // .withRequestedCheck(\n // new RequestedLivenessCheckBuilder()\n // .forStaticLiveness()\n // .build()\n // )\n .withRequestedCheck(new RequestedFaceComparisonCheckBuilder()\n .withManualCheckNever()\n .build())\n .withSdkConfig(new SdkConfigBuilder()\n .withSuccessUrl(`${config.YOTI_APP_BASE_URL}/success`)\n .withErrorUrl(`${config.YOTI_APP_BASE_URL}/error`)\n .withPrivacyPolicyUrl(`${config.YOTI_APP_BASE_URL}/privacy-policy`)\n .withJustInTimeBiometricConsentFlow() // or withEarlyBiometricConsentFlow()\n .build())\n .build();\n\n return idvClient.createSession(sessionSpec);\n}",
"async function configAWS(){\n aws.config.update({\n region: 'us-east-1', // Put your aws region here\n accessKeyId: config.AWSAccessKeyId,\n secretAccessKey: config.AWSSecretKey\n })\n}",
"function createS3(){\n\treturn s3.createBucket({\n\t\tBucket: CONFIG.s3_image_bucket,\n\t}).promise().catch(err => {\n\t\tif (err.code !== \"BucketAlreadyOwnedByYou\") throw err\n\t})\n}",
"function init_sdk() {\n\tvar branch = get_url_parameter(\"b\",\"master\");\n\tvar url = get_url_parameter(\"baseUrl\",(branch==\"develop\"?\"https://dev-api.wialon.com\":\"https://hst-api.wialon.com\"));\n\tif (!url)\n\t\turl = get_url_parameter(\"hostUrl\",\"https://hosting.wialon.com\");\n\tif (!url)\n\t\treturn;\n\n\tvar user = get_url_parameter(\"user\") || \"\";\n\tvar sid = get_url_parameter(\"sid\");\n\tvar authHash = get_url_parameter(\"authHash\");\n\n\twialon.core.Session.getInstance().initSession(url, \"gapp_eco_driving\");\n\tif (authHash) {\n\t\twialon.core.Session.getInstance().loginAuthHash(authHash, login);\n\t} else if (sid) {\n\t\twialon.core.Session.getInstance().duplicate(sid, user, true, login);\n\t}\n}",
"async function cognitoLogin({userPoolId, clientId, username, password, region, identityPoolId} ) {\n const poolData = {\n UserPoolId: userPoolId,\n ClientId: clientId\n };\n\n const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);\n\n return new Promise((resolve, reject) => {\n const authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails({\n Username: username,\n Password: password,\n });\n\n const userData = {\n Username: username,\n Pool: userPool,\n };\n\n const cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);\n \n cognitoUser.authenticateUser(authenticationDetails, {\n onSuccess(result) {\n if(region && identityPoolId) {\n AWS.config.region = region;\n AWS.config.credentials = new AWS.CognitoIdentityCredentials({\n IdentityPoolId : identityPoolId,\n Logins : { [`cognito-idp.ap-southeast-2.amazonaws.com/${userPoolId}`] : result.getIdToken().getJwtToken()}\n });\n \n AWS.config.credentials.refresh((error) => {\n if (error) {\n console.error(error);\n } else {\n // example: var s3 = new AWS.S3();\n console.log('Successfully logged! Now could using your aws servers example s3 buckets');\n result.getRefreshToken().getToken();\n resolve(result.getAccessToken().getJwtToken());\n }\n });\n\n } else {\n resolve(result.getAccessToken().getJwtToken());\n }\n },\n onFailure(err) {\n reject(err);\n },\n });\n });\n}",
"function KnoxS3ClientProvider(_config) {\n\t_config = _config || config;\n\n\tthis._cache = LRUCache(_config.lru);\n\tthis._awsOptions = _config.aws;\n}",
"function getS3Bucket(awsConfig) {\n // set the Amazon Cognito region\n AWS.config.region = awsConfig.awsCognitoRegion;\n // initialize the Credentials object with our parameters\n AWS.config.credentials = new AWS.CognitoIdentityCredentials({\n IdentityPoolId: awsConfig.cognitoIdentityPoolId\n });\n\n // get identity ID and update credentials\n AWS.config.credentials.get(function(err) {\n if (err) {\n console.log(\"Error: \" + err);\n return;\n } else {\n console.log(\"Cognito Identity Id: \" + AWS.config.credentials.identityId);\n AWS.config.update({\n credentials: AWS.config.credentials.identityId\n });\n }\n });\n\n // create the s3 bucket locally\n var s3 = new AWS.S3();\n var bucketName = awsConfig.awsBucketName;\n var bucket = new AWS.S3({\n params: {\n Bucket: bucketName\n }\n });\n\n return bucket;\n}",
"get awsRegion() { return this.env.AWS_REGION }",
"async function createEOSToken () {\n const TOKEN_ABI_PATH = './tests/testing-contracts/compiled/eosio.token.abi';\n const TOKEN_WASM_PATH = './tests/testing-contracts/compiled/eosio.token.wasm';\n const TOTAL_SUPPLY = '1000000000.0000 SYS';\n\n // Creates eosio.token account if you don't have it\n try {\n const tokenAccount = await Account.createFromName('eosio.token');\n const tokenContract = await eoslimeTool.Contract.deployOnAccount(TOKEN_WASM_PATH, TOKEN_ABI_PATH, tokenAccount);\n await tokenContract.actions.create([tokenAccount.name, TOTAL_SUPPLY]);\n await tokenContract.actions.issue([ACCOUNT_NAME, TOTAL_SUPPLY, 'memo']);\n } catch (error) {\n }\n }",
"function createReadStream(url, headers, retainMetadata) {\n return require('./client').createClient(url, headers, retainMetadata);\n}",
"function connect(options, fn) {\n var ec2 = require('tower-ec2-adapter');\n\n if (!options.key && !options.secret) {\n // try to load from databag.\n var path = require('path');\n\n var data = require(path.join(process.env.HOME, '.tower/config/data.json'));\n //recipe.exec('ec2:credentials', 'show', [], function(data){\n // console.log('here', data)\n //});\n ec2().connect(data['aws'], fn);\n } else {\n // XXX: make `connect` top-level\n ec2().connect({ key: options.key, secret: options.secret }, fn);\n }\n}",
"constructor(hostname, stage, origin, apikey)\n {\n if (!hostname && !(\"INOMIAL_HOSTNAME\" in process.env))\n throw new Error(\"No hostname given (INOMIAL_HOSTNAME is unset)\");\n\n hostname = hostname || process.env.INOMIAL_HOSTNAME;\n stage = stage || process.env.INOMIAL_STAGE || \"live\";\n apikey = apikey || process.env.INOMIAL_APIKEY;\n\n this.clientConfig = websocketClientConfig;\n\n // If the connection is down, queries are added to this queue.\n // When the connection comes back up, the queries are executed.\n this.requestQueue = [];\n\n // Set of outstanding queries, indexed by request ID.\n this.responseQueue = {};\n\n // Request ID generator.\n this.nextRequestId = 1000000;\n\n // URL We'll be connecting to.\n this.url = \"wss://\" + hostname + \"/\" + stage + \"/api/events\";\n\n // WSS Origin header, for non-browser clients.\n this.origin = origin;\n\n // API key, for non-browser clients. Browser clients will inherit the\n // HTTP session credentials.\n this.apikey = apikey;\n\n // The connection will be set once we connect.\n this.connection = null;\n\n // USN caches for accounts and subscriptions\n this.accountUuidCache = {};\n this.subscriptionUuidCache = {};\n\n this.reconnectPolicy = false;\n }",
"function initClient() {\n \n const keys = {\n // fill\n };\n\n return new Gdax.AuthenticatedClient(\n keys[\"API-key\"],\n keys[\"API-secret\"],\n keys[\"Passphrase\"],\n keys[\"Exchange-url\"]\n );\n}",
"static startSession(id, tokenHash, userId = null, type = null, expiry = null, sessionPrivileges = null){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.tokenHash = tokenHash;\n\t\tkparams.userId = userId;\n\t\tkparams.type = type;\n\t\tkparams.expiry = expiry;\n\t\tkparams.sessionPrivileges = sessionPrivileges;\n\t\treturn new kaltura.RequestBuilder('apptoken', 'startSession', kparams);\n\t}",
"static impersonateByKs(session, type = null, expiry = null, privileges = null){\n\t\tlet kparams = {};\n\t\tkparams.session = session;\n\t\tkparams.type = type;\n\t\tkparams.expiry = expiry;\n\t\tkparams.privileges = privileges;\n\t\treturn new kaltura.RequestBuilder('session', 'impersonateByKs', kparams);\n\t}",
"function initializeTokboxSession() {\n session = OT.initSession(projectAPIKey, sessionID);\n session.on('sessionDisconnected', (event) => {\n console.log('You were disconnected from the session.', event.reason);\n });\n\n // Connect to the session\n session.connect(token, (error) => {\n if (error) {\n handleError(error);\n }\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mark an assignment as missing. | function missingAssignment(axios$$1, token) {
return restAuthPost(axios$$1, '/assignments/' + token + '/missing', null);
} | [
"function createNewAssignment(assignmentName,totalPointValue,assignmentData,gradebookData){\n var assignment = new Assignment(assignmentName,totalPointValue,assignmentData);\n assignmentData.push(assignment);//update the assignmentData array\n //task 9: set the default assignment score\n for (var i=0 ;i< gradebookData.length;i++){\n gradebookData[i].grades[assignment.id]=0;\n }\n}",
"function fillInMissingProperties(event) {\n for (var attr in attributes) {\n if (event[attributes[attr]] === undefined) {\n event[attributes[attr]] = null;\n }\n }\n}",
"function resetFailFountain(){\n runFail = false;\n failFountain.reset(failParticle);\n coordinates = [];\n}",
"function removeTempAssignments() {\n jQuery(\"#assignmentsWrapper\").children(\"p\").filter(function(){\n return jQuery(this).find(\"input[id$='id']\").length < 1;\n }).remove();\n }",
"markDead()\n\t{\n\t\tif ( this.m_bAlive )\n\t\t{\n\t\t\tthis.m_bAlive = false;\n\t\t\tthis.emit( 'peer_failed' );\n\t\t}\n\t}",
"function clearOrgunitAssignment() {\n\tfor (var i = 0; metaData.dataSets && i < metaData.dataSets.length; i++) {\n\t\tmetaData.dataSets[i].organisationUnits = [];\n\t}\n\n\tfor (var i = 0; metaData.programs && i < metaData.programs.length; i++) {\n\t\tmetaData.programs[i].organisationUnits = [];\n\t}\n\n\tfor (var i = 0; metaData.users && i < metaData.users.length; i++) {\n\t\tmetaData.users[i].organisationUnits = [];\n\t\tmetaData.users[i].dataViewOrganisationUnits = [];\n\t\tmetaData.users[i].teiSearchOrganisationUnits = [];\n\t}\n\n\n\tfor (var i = 0; metaData.hasOwnProperty(\"predictors\") && i < metaData.predictors.length; i++) {\n\t\tmetaData.predictors[i].organisationUnitLevels = [];\n\t}\n\t\n}",
"isNotReadOnly(lvalue) {\n doCheck(!lvalue.isReadOnly, \"Assignment to read-only variable\");\n }",
"function propertyNull() {\n\t delete this[name];\n\t }",
"function needToSave(b) {\n unsavedAnnotations = b;\n }",
"_checkValidAssignmentTarget(node) {\n if (node.type === \"Identifier\" || node.type === \"MemberExpression\") {\n return node;\n }\n throw new SyntaxError(\"Invalid left-hand side in assignment expression\");\n }",
"clear_marks () {\n this.set_marks(null);\n }",
"function removeDeactivatedAssignements() {\n var i, j, k, assignments = new Array(), assignment, resourceInstance,\n listResources = Variable.findByName(gm, 'resources'),\n listTasksObjects = this.getTasksAndAbsences(), taskObjectInstance;\n for (i = 0; i < listResources.items.size(); i++) {\n assignments.length = 0;\n resourceInstance = listResources.items.get(i).getInstance(self);\n for (j = 0; j < resourceInstance.getAssignments().size(); j++) {\n assignment = resourceInstance.getAssignments().get(j);\n for (k = 0; k < listTasksObjects.length; k++) {\n taskObjectInstance = listTasksObjects[k].getInstance(self);\n if (assignment.getTaskDescriptorId() == taskObjectInstance.getDescriptorId() && taskObjectInstance.getActive() == false) {\n assignments.push(assignment);\n }\n }\n }\n for (j = 0; j < assignments.length; j++) {\n resourceInstance.getAssignments().remove(assignments[j]);\n }\n }\n}",
"function isKeepAssigned(o) {\n return keepAssignedPrototype.isPrototypeOf(o);\n}",
"function assignSkipCurrentEmail() {\n actionableEmails.shift();\n assignDisplayNextEmail();\n}",
"function assertNever(theValue) {\n throw new Error(\"Unhandled case for value: '\".concat(theValue, \"'\"));\n }",
"function markBadLocalLinks (document, element) {\n\t\telement.querySelectorAll('a[href^=\"#\"]').forEach(function (localRef) {\n\t\t\tif (!document.getElementById(localRef.getAttribute('href').substring(1))) {\n\t\t\t\tlocalRef.innerHTML = \"<span class=Undefined>\" + localRef.innerHTML + \"</span>\"\n\t\t\t\tconsole.error(errorMessage(['Undefined local link in', localRef.outerHTML]))\n\t\t\t}\n\t\t})\n\t} // markBadLocalLinks (document, element)",
"no_card() {\n this._card = null\n this.prepare_state('no-card')\n }",
"reset() {\n\tthis.progress = new Progress(0);\n\tthis.question = [];\n\tthis.setChanged();\n\tthis.notifyObservers(this.progress);\n\tthis.clearChanged();\n }",
"reset() {\n /**\n * The overall error.\n */\n this.globalError = 0;\n /**\n * The size of a set.\n */\n this.setSize = 0;\n\n this.sum = 0;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find an macro argument without expanding tokens and append the array of tokens to the token stack. Uses Token as a container for the result. | scanArgument(isOptional: boolean): ?Token {
let start;
let end;
let tokens;
if (isOptional) {
this.consumeSpaces(); // \@ifnextchar gobbles any space following it
if (this.future().text !== "[") {
return null;
}
start = this.popToken(); // don't include [ in tokens
({tokens, end} = this.consumeArg(["]"]));
} else {
({tokens, start, end} = this.consumeArg());
}
// indicate the end of an argument
this.pushToken(new Token("EOF", end.loc));
this.pushTokens(tokens);
return start.range(end, "");
} | [
"expandMacro(name) {\n if (!this.macros.get(name)) {\n return undefined;\n }\n\n const output = [];\n const oldStackLength = this.stack.length;\n this.pushToken(new Token(name));\n\n while (this.stack.length > oldStackLength) {\n const expanded = this.expandOnce(); // expandOnce returns Token if and only if it's fully expanded.\n\n if (expanded instanceof Token) {\n output.push(this.stack.pop());\n }\n }\n\n return output;\n }",
"consumeArgs(numArgs) {\n const args = []; // obtain arguments, either single token or balanced {…} group\n\n for (let i = 0; i < numArgs; ++i) {\n this.consumeSpaces(); // ignore spaces before each argument\n\n const startOfArg = this.popToken();\n\n if (startOfArg.text === \"{\") {\n const arg = [];\n let depth = 1;\n\n while (depth !== 0) {\n const tok = this.popToken();\n arg.push(tok);\n\n if (tok.text === \"{\") {\n ++depth;\n } else if (tok.text === \"}\") {\n --depth;\n } else if (tok.text === \"EOF\") {\n throw new ParseError(\"End of input in macro argument\", startOfArg);\n }\n }\n\n arg.pop(); // remove last }\n\n arg.reverse(); // like above, to fit in with stack order\n\n args[i] = arg;\n } else if (startOfArg.text === \"EOF\") {\n throw new ParseError(\"End of input expecting macro argument\");\n } else {\n args[i] = [startOfArg];\n }\n }\n\n return args;\n }",
"_getExpansion(name) {\n const definition = this.macros.get(name);\n\n if (definition == null) {\n // mainly checking for undefined here\n return definition;\n }\n\n const expansion = typeof definition === \"function\" ? definition(this) : definition;\n\n if (typeof expansion === \"string\") {\n let numArgs = 0;\n\n if (expansion.indexOf(\"#\") !== -1) {\n const stripped = expansion.replace(/##/g, \"\");\n\n while (stripped.indexOf(\"#\" + (numArgs + 1)) !== -1) {\n ++numArgs;\n }\n }\n\n const bodyLexer = new Lexer(expansion, this.settings);\n const tokens = [];\n let tok = bodyLexer.lex();\n\n while (tok.text !== \"EOF\") {\n tokens.push(tok);\n tok = bodyLexer.lex();\n }\n\n tokens.reverse(); // to fit in with stack using push and pop\n\n const expanded = {\n tokens,\n numArgs\n };\n return expanded;\n }\n\n return expansion;\n }",
"expandMacroAsText(name) {\n const tokens = this.expandMacro(name);\n\n if (tokens) {\n return tokens.map(token => token.text).join(\"\");\n } else {\n return tokens;\n }\n }",
"getMacro(name) {\n const len = this.stack.length - 1;\n for (let i = len; i >= 0; i--) {\n const inst = this.stack[i]._getMacro(name);\n if (inst !== null) {\n return inst;\n }\n }\n return null;\n }",
"makeToken() {\n if ( this.pattern === '*' ) {\n if ( this.modifyType !== this.parser.OPTTokenQueryprune ) {\n return;\n }\n return this.extractTokenFromQuerypruneValue();\n }\n if ( this.isRegex ) {\n return this.extractTokenFromRegex(this.pattern);\n }\n this.extractTokenFromPattern(this.pattern);\n }",
"consoleParseMacros(input) { return Parser.parse(input, { startRule: 'MACROS' }); }",
"function scanAndSetArgName( argz, fmt, p ) {\n var q = fmt.indexOf(')', ++p);\n if (q < 0) throw new Error(\"unterminated %(named) argument at offset \" + p);\n var argName = fmt.slice(p, q);\n setargM(argz, argName, p);\n return p = q + 1;\n}",
"function decodeMacroChain(featureMacro, dataMatrix, index){\n\tvar macroList = featureMacro.match(/%x\\[[-]?\\d+,\\d+\\]/g);\n\tvar featurePrefix = featureMacro.substring(0,featureMacro.indexOf(':')+1);\n\tvar decodedMacroSequence = '';\n\n\tfor(var j=0; j<macroList.length;j++){\n\t\tvar columnStartIndex = macroList[j].indexOf(',')+1;\n\t\tvar columnEndIndex = macroList[j].indexOf(']');\n\t\tvar rowStartIndex = macroList[j].indexOf('[')+1;\n\t\tvar rowEndIndex = macroList[j].indexOf(',');\n\t\tvar currentMacroColumn = parseInt(macroList[j].substring(columnStartIndex, columnEndIndex), 10);\n\t\tvar currentMacroRow = parseInt(macroList[j].substring(rowStartIndex, rowEndIndex), 10);\n\t\tvar relativePositionInSample;\n\t\tvar sampleNumber = 0;\n\t\tvar decodedMacroValue = '';\n\n\t\tif(!dataMatrix[index-1] || dataMatrix[index-1][0] === '' || index === 0)\n\t\t\trelativePositionInSample = 0;\n\t\telse\n\t\t\trelativePositionInSample++;\n\n\t\t// check for boundry conditions for macro (i.e. for first word in training doc with template entry %x[-1,0])\n\t\tif(currentMacroRow+relativePositionInSample < 0){\n\t\t\tdecodedMacroValue = '_B'+(relativePositionInSample+currentMacroRow); // will result in value of the form e.g. _B-1 (where _B-1 is the token before the start of a sample)\n\t\t}\n\t\t// check for boundry condition when currentMacroRow is looking past last word in document\n\t\telse if(currentMacroRow+index >= dataMatrix.length){\n\t\t\tdecodedMacroValue = '_B+'+(currentMacroRow+index-dataMatrix.length+1); // will result in value of the form e.g. _B+1 (where _B+1 is the token after the end of a sample)\n\t\t}\n\t\t// check for boundry condition when currentMacroRow is looking past last word in sample\n\t\telse if(macroOvershootOfSampleLength(dataMatrix, index, currentMacroRow) > 0){\n\t\t\tvar endOfSamplePosition = macroOvershootOfSampleLength(dataMatrix, index, currentMacroRow);\n\t\t\tdecodedMacroValue = '_B+'+(currentMacroRow+index-endOfSamplePosition); // will result in value of the form e.g. _B+1 (where _B+1 is the token after the end of a sample)\n\t\t}\n\t\telse if (!dataMatrix[index+currentMacroRow]){\n\t\t\treturn null;\n\t\t}\n\t\t// throw away conditions\n\t\telse if(!dataMatrix[index]\n\t\t\t\t|| dataMatrix[index][0] === '' \t// an empty value shouldn't have any features\n\t\t\t\t|| dataMatrix[index+currentMacroRow][0] === '' \t// features should not be created using the boundry spaces between samples\n\t\t\t\t|| (featurePrefix.match(/^B/) && currentMacroRow+relativePositionInSample < 0)) // bigram features shouldn't be created for words on the edge of the sample.\n\t\t{ \n\t\t\t//keep track of sample number for labeling compound featueres\n\t\t\tif(dataMatrix[index] === ''){\n\t\t\t\tsampleNumber++; \n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\t//else the standard case\n\t\telse{ \n\t\t\tdecodedMacroValue = dataMatrix[index+currentMacroRow][currentMacroColumn];\n\t\t}\n\n\t\tif(j === 0){\n\t\t\tdecodedMacroSequence = featurePrefix + decodedMacroValue;\n\t\t}\n\t\telse{\n\t\t\tdecodedMacroSequence += '/' + decodedMacroValue;\n\t\t}\n\t}\n\treturn decodedMacroSequence;\n}",
"tokenBefore(types) {\n let token = this.state.tree.resolve(this.pos, -1);\n while (token && types.indexOf(token.name) < 0)\n token = token.parent;\n return token ? { from: token.from, to: this.pos,\n text: this.state.sliceDoc(token.from, this.pos),\n type: token.type } : null;\n }",
"tokenBefore(types) {\n let token = this.state.tree.resolve(this.pos, -1);\n while (token && types.indexOf(token.name) < 0)\n token = token.parent;\n return token ? { from: token.start, to: this.pos,\n text: this.state.sliceDoc(token.start, this.pos),\n type: token.type } : null;\n }",
"unget(token) {\n this.stack.push(token);\n\n while (this.discardedWhiteSpace.length !== 0) {\n this.stack.push(this.discardedWhiteSpace.pop());\n }\n }",
"function addMacroExpand(){\n\tvar target = document.getElementById(\"macroexpandwordtxt\").value;\n\tvar replacement = document.getElementById(\"macroexpandreplacetxt\").value;\n\t// error check\n\tif ((target==\"\") || (replacement==\"\")){\n\t\talert(\"Must have word + replacement\");\n\t\treturn\n\t}\n\t\n\t// add it to the array\n\tg_expansions.push(target);\n\texpansions_replacements.push(replacement);\n\tvar ss=\"Failed to write \" + s;\n\t// if checkbox is checked, save to file\n\tif (document.getElementById(\"macroexpandcheckbox\").checked) {\n\t\tvar s = \"\\n\" + target + \"|\" + replacement;\n\t\t$.post('append_expansion.php', {\n\t\t\tnewline: s,\n\t\t\tasync: false,\n\t\t\tsuccess: ss=\"Success writing new macro expansion\",\n\t\t\terror: function(){\n\t\t\t\talert('Error writing link file');\n\t\t\t}\n\t\t})\n\talert(ss);\n\t}\n\t \n return;\n}",
"visitFunction_argument(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitVarargslist(ctx) {\r\n console.log(\"visitVarargslist\");\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: \"VarArgument\",\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: \"VarArgument\",\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 parseFuncInstrArguments(signature) {\n var args = [];\n var namedArgs = {};\n var signaturePtr = 0;\n\n while (token.type === _tokenizer.tokens.name || isKeyword(token, _tokenizer.keywords.offset)) {\n var key = token.value;\n eatToken();\n eatTokenOfType(_tokenizer.tokens.equal);\n var value = void 0;\n\n if (token.type === _tokenizer.tokens.number) {\n value = t.numberLiteralFromRaw(token.value);\n } else {\n throw new Error(\"Unexpected type for argument: \" + token.type);\n }\n\n namedArgs[key] = value;\n eatToken();\n } // $FlowIgnore\n\n\n var signatureLength = signature.vector ? Infinity : signature.length;\n\n while (token.type !== _tokenizer.tokens.closeParen && ( // $FlowIgnore\n token.type === _tokenizer.tokens.openParen || signaturePtr < signatureLength)) {\n if (token.type === _tokenizer.tokens.identifier) {\n args.push(t.identifier(token.value));\n eatToken();\n } else if (token.type === _tokenizer.tokens.valtype) {\n // Handle locals\n args.push(t.valtypeLiteral(token.value));\n eatToken();\n } else if (token.type === _tokenizer.tokens.string) {\n args.push(t.stringLiteral(token.value));\n eatToken();\n } else if (token.type === _tokenizer.tokens.number) {\n args.push( // TODO(sven): refactor the type signature handling\n // https://github.com/xtuc/webassemblyjs/pull/129 is a good start\n t.numberLiteralFromRaw(token.value, // $FlowIgnore\n signature[signaturePtr] || \"f64\")); // $FlowIgnore\n\n if (!signature.vector) {\n ++signaturePtr;\n }\n\n eatToken();\n } else if (token.type === _tokenizer.tokens.openParen) {\n /**\n * Maybe some nested instructions\n */\n eatToken(); // Instruction\n\n if (lookaheadAndCheck(_tokenizer.tokens.name) === true || lookaheadAndCheck(_tokenizer.tokens.valtype) === true || token.type === \"keyword\" // is any keyword\n ) {\n // $FlowIgnore\n args.push(parseFuncInstr());\n } else {\n throw function () {\n return new Error(\"\\n\" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + \"\\n\" + \"Unexpected token in nested instruction\" + \", given \" + tokenToString(token));\n }();\n }\n\n if (token.type === _tokenizer.tokens.closeParen) {\n eatToken();\n }\n } else {\n throw function () {\n return new Error(\"\\n\" + (0, _helperCodeFrame.codeFrameFromSource)(source, token.loc) + \"\\n\" + \"Unexpected token in instruction argument\" + \", given \" + tokenToString(token));\n }();\n }\n }\n\n return {\n args: args,\n namedArgs: namedArgs\n };\n }",
"function insertFuncArg(fcallexpr, arg) {\r\n\r\n var ind = getFuncIdByName(CurModObj, fcallexpr.str);\r\n var fO = CurModObj.allFuncs[ind]; // change CurFuncObj\r\n var sO = CurStepObj;\r\n\r\n assert((arg < fcallexpr.exprArr.length), \"invalid arg position \" +\r\n arg);\r\n\r\n // Particular argument expr in the function *call*\r\n //\r\n var argexpr = fcallexpr.exprArr[arg];\r\n assert(argexpr, \"ERROR: argexpr cannot be null\");\r\n\r\n // arg pos in the header. We add 1 because the first expr is the return\r\n // expression\r\n //\r\n var arggrid = arg + 1;\r\n\r\n // Point the default functionCallExpr in function to this function call\r\n // because updateOtherFuncCalls() depend on this \r\n //\r\n fO.funcCallExpr = fcallexpr;\r\n\r\n // STEP:\r\n //\r\n // Process arg expr in the func *call* and add the corresponding grid\r\n // to function grids (and header step) \r\n //\r\n if (argexpr.isScalarExpr() || argexpr.isGridCell() || argexpr.isLetName()) {\r\n\r\n // SCALAR args\r\n // if this is a number. Create a scalar grid and add push\r\n // to arg list\r\n //\r\n var newGId = fO.allGrids.length; // grid id at the end\r\n\r\n var newgO = new GridObj(newGId, \"param\" + arg, 1, 1,\r\n 1, 1, false, false, false, false);\r\n\r\n // Add the new grid to new function\r\n // Note: newGId is for adding at the end (for pushing)\r\n //\r\n fO.allGrids.push(newgO);\r\n fO.argsAdded += 1;\r\n newgO.inArgNum = arg;\r\n newgO.isConst = true; // incoming arg const by default\r\n\r\n // Record this grid in function header\r\n //\r\n fO.allSteps[FuncHeaderStepId].allGridIds.splice(arggrid, 0,\r\n newGId);\r\n\r\n // If this is a grid cell AND user needs a reference (Don't know\r\n // how to detect this yet), create an *additional* reference\r\n // grid object and record it in newgO (scalar grid). \r\n // We do this to enable an arg to be used as either a scalar\r\n // value or a reference\r\n //\r\n if (0 && argexpr.isGridCell()) { // <--- NOTE 0 \r\n\r\n alert(\"TODO: Handle this case if necessary\");\r\n\r\n /*\r\n\t // TODO: Currently we don't use this 'hidden' reference\r\n\t // grid. Allow switching to this.\r\n\r\n\t // If we pass a grid cell as a *reference* \r\n\t // (not as a sclar val)\r\n\t // it is similar to passing a whole grid reference plus\r\n\t // a set of indices to point to the correct cell\r\n\t // So, this case is similar to isGridRef case.\r\n\t //\r\n\t // NOTE: We use the same 'newGId' as the scalar because\r\n\t // this represents the same grid as scalar arg\r\n\t //\r\n\t var refgO = new cloneGridObj(newGId, argexpr.gO);\r\n\t refgO.caption = \"param\" + arg; // same name as salar\r\n\r\n\r\n\t // This is a grid cell reference. Which will indicate to \r\n\t // draw index values in the arg like Src[arg1,arg2,arg3]\r\n\t //\r\n\t refgO.isGridCellRef = true;\r\n\t \r\n\t // record this reference grid obj in the scalar grid\r\n\t //\r\n\t newgO.refgO = refgO;\r\n\r\n\t // Add the global data type to newgO\r\n\t //\r\n\t newgO.dataTypes.push(findDataTypeOfGridCellExpr(argexpr));\r\n\t */\r\n\r\n } else if (argexpr.isGridCell()) {\r\n\r\n // scalar grid cell (passed by value)\r\n //\r\n newgO.dataTypes.push(findDataTypeOfGridCellExpr(argexpr));\r\n\r\n } else if (argexpr.isLetName()) {\r\n\r\n // alert(\"ARGUMENT IS LET\");\r\n // Here do what needs to be done w.r.t. finding type of new grid\r\n\r\n var letType = findLetType(argexpr, CurModObj);\r\n newgO.dataTypes.push(letType);\r\n\r\n } else {\r\n\r\n // Add the global data type to newgO\r\n // NOTE: For all scalar types (even for a Number), we add type \r\n // integer. For a number, updateFuncArgType() is called\r\n // just after this so it's type will be updated correctly\r\n // \r\n newgO.dataTypes.push(DataTypes.Integer);\r\n }\r\n\r\n // Mark that scalar grid arg has globla data type\r\n //\r\n assert((newgO.dataTypes.length == 1),\r\n \"must have only global type\");\r\n newgO.typesInDim = -1;\r\n\r\n\r\n } else if (argexpr.isGridRef()) {\r\n\r\n // This is a grid reference. So, make a cloned grid \r\n // and insert it to arg list and step\r\n // NOTE: When we genrate code for this new function, the caller\r\n // generates something like func( _out), where \r\n // _out = out.data. So, on the caller side, just introduce\r\n // an argumnet called argX. JavaScript will make\r\n // argX = _out = out.data automatically. There is nothing\r\n // more to do. Within the argument, we can refer to \r\n // the grid cells as argX[i][j] and it will point to \r\n // proper caller's data[]. \r\n //\r\n var newGId = fO.allGrids.length;\r\n var newgO = new cloneGridObj(newGId, argexpr.gO);\r\n newgO.caption = \"param\" + arg;\r\n newgO.isGridRef = true; // mark this as a ref arg\r\n\r\n // Add the new grid to new function\r\n // Note: newGId is for adding at the end (for pushing)\r\n //\r\n fO.allGrids.push(newgO);\r\n fO.argsAdded += 1;\r\n newgO.inArgNum = arg;\r\n newgO.isConst = true; // a ref grid is constat by default\r\n\r\n // Record this grid in function header\r\n //\r\n fO.allSteps[FuncHeaderStepId].allGridIds.splice(arggrid, 0,\r\n newGId);\r\n\r\n } else {\r\n\r\n alert(\"TODO: Create grid for other ... arg\");\r\n }\r\n\r\n // if there are any other function call expressions that call the same\r\n // function update them -- i.e., insert a NeedUpdate argument, or \r\n // replace corresponding arg with a NeedUpdate arg\r\n //\r\n updateOtherFuncCalls(fO, arg, false);\r\n\r\n}",
"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 tokenize(templ) {\n return (function (arr) {\n var tokens = [];\n for (i = 0; i < arr.length; i++) {\n (function (token) {\n return token === \"\" ?\n null :\n tokens.push(token);\n }(arr[i]));\n }\n return tokens;\n }(split(templ, new RegExp(\"(\" + VAR_TAG.source + \"|\" +\n BLOCK_TAG.source + \"|\" +\n END_BLOCK_TAG.source + \")\"))));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
replace a pattern in a word. if a replacement occurs an optional callback can be called to postprocess the result. if no match is made NULL is returned. | function attemptReplace(token, pattern, replacement, callback) {
var result = null;
if((typeof pattern == 'string') && token.substr(0 - pattern.length) == pattern)
result = token.replace(new RegExp(pattern + '$'), replacement);
else if((pattern instanceof RegExp) && token.match(pattern))
result = token.replace(pattern, replacement);
if(result && callback)
return callback(result);
else
return result;
} | [
"function attemptReplace(token, pattern, replacement, callback) {\n\tvar result = null;\n\n\tif((typeof pattern == 'string') && token.substr(0 - pattern.length) == pattern)\n\t\tresult = token.replace(new RegExp(pattern + '$'), replacement);\n\telse if((pattern instanceof RegExp) && token.match(pattern))\n\t\tresult = token.replace(pattern, replacement);\n\n\tif(result && callback)\n\t\treturn callback(result);\n\telse\n return result;\n}",
"function _replacement() {\n if (!arguments[0]) return \"\";\n var i = 1, j = 0, $pattern;\n // loop through the patterns\n while ($pattern = _patterns[j++]) {\n // do we have a result?\n if (arguments[i]) {\n var $replacement = $pattern[$REPLACEMENT];\n switch (typeof $replacement) {\n case \"function\": return $replacement(arguments, i);\n case \"number\": return arguments[$replacement + i];\n }\n var $delete = (arguments[i].indexOf(self.escapeChar) == -1) ? \"\" :\n \"\\x01\" + arguments[i] + \"\\x01\";\n return $delete + $replacement;\n // skip over references to sub-expressions\n } else i += $pattern[$LENGTH];\n }\n }",
"function ReplaceParams() {\n var result = arguments[0];\n for (var iArg = 1; iArg < arguments.length; iArg++) { // Start at second arg (first arg is the pattern)\n var pattern = new RegExp('%' + iArg + '\\\\w*%');\n result = result.replace(pattern, arguments[iArg]);\n }\n return result;\n}",
"function replaceAll(str, term, replacement) {\n return str.replace(new RegExp(escapeRegExp(term), 'g'), replacement);\n }",
"function replaceWord(word, thisChar){\r\n\tthisChar.dialogue[thisChar.diaCounter]=thisChar.dialogue[thisChar.diaCounter].replace(\"[\"+word+\"]\", eval(\"player.\"+word));\r\n}",
"match(word) {\n if (this.pattern.length == 0)\n return [0];\n if (word.length < this.pattern.length)\n return null;\n let { chars, folded, any, precise, byWord } = this;\n // For single-character queries, only match when they occur right\n // at the start\n if (chars.length == 1) {\n let first = codePointAt(word, 0);\n return first == chars[0] ? [0, 0, codePointSize(first)]\n : first == folded[0] ? [-200 /* CaseFold */, 0, codePointSize(first)] : null;\n }\n let direct = word.indexOf(this.pattern);\n if (direct == 0)\n return [0, 0, this.pattern.length];\n let len = chars.length, anyTo = 0;\n if (direct < 0) {\n for (let i = 0, e = Math.min(word.length, 200); i < e && anyTo < len;) {\n let next = codePointAt(word, i);\n if (next == chars[anyTo] || next == folded[anyTo])\n any[anyTo++] = i;\n i += codePointSize(next);\n }\n // No match, exit immediately\n if (anyTo < len)\n return null;\n }\n let preciseTo = 0;\n let byWordTo = 0, byWordFolded = false;\n let adjacentTo = 0, adjacentStart = -1, adjacentEnd = -1;\n for (let i = 0, e = Math.min(word.length, 200), prevType = 0 /* NonWord */; i < e && byWordTo < len;) {\n let next = codePointAt(word, i);\n if (direct < 0) {\n if (preciseTo < len && next == chars[preciseTo])\n precise[preciseTo++] = i;\n if (adjacentTo < len) {\n if (next == chars[adjacentTo] || next == folded[adjacentTo]) {\n if (adjacentTo == 0)\n adjacentStart = i;\n adjacentEnd = i;\n adjacentTo++;\n }\n else {\n adjacentTo = 0;\n }\n }\n }\n let ch, type = next < 0xff\n ? (next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 /* Lower */ : next >= 65 && next <= 90 ? 1 /* Upper */ : 0 /* NonWord */)\n : ((ch = fromCodePoint(next)) != ch.toLowerCase() ? 1 /* Upper */ : ch != ch.toUpperCase() ? 2 /* Lower */ : 0 /* NonWord */);\n if (type == 1 /* Upper */ || prevType == 0 /* NonWord */ && type != 0 /* NonWord */ &&\n (this.chars[byWordTo] == next || (this.folded[byWordTo] == next && (byWordFolded = true))))\n byWord[byWordTo++] = i;\n prevType = type;\n i += codePointSize(next);\n }\n if (byWordTo == len && byWord[0] == 0)\n return this.result(-100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0), byWord, word);\n if (adjacentTo == len && adjacentStart == 0)\n return [-200 /* CaseFold */, 0, adjacentEnd];\n if (direct > -1)\n return [-700 /* NotStart */, direct, direct + this.pattern.length];\n if (adjacentTo == len)\n return [-200 /* CaseFold */ + -700 /* NotStart */, adjacentStart, adjacentEnd];\n if (byWordTo == len)\n return this.result(-100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0) + -700 /* NotStart */, byWord, word);\n return chars.length == 2 ? null : this.result((any[0] ? -700 /* NotStart */ : 0) + -200 /* CaseFold */ + -1100 /* Gap */, any, word);\n }",
"async function replaceAsync(str, regex, replacerAsync) {\n const promises = [];\n str.replace(regex, (match, ...args) => {\n const promise = replacerAsync(match, ...args);\n promises.push(promise);\n return \"\";\n });\n const data = await Promise.all(promises);\n return str.replace(regex, () => data.shift());\n}",
"function highlight_word(searchpara) {\n\tlet text=document.getElementById(\"search_text\").value;\n\tif (text) {\n\t\tlet pattern = new RegExp(\"(\"+text+\")\", \"gi\");\n\t\tlet new_text = searchpara.replace(pattern, \"<span class='highlight'>\"+text+\"</span>\");\n\t\tdocument.getElementById(\"search_para\").innerHTML=new_text;\n\t}\n}",
"function replacer(match, type, offset) {\r\n\t\r\n\t\t// Find start position (all positions here are relative to the matched substring,\r\n\t\t// not the entire original document (which is available as a 4th parameter btw))\r\n\t\tvar start = type.length;\r\n\t\t\r\n\t\t// Ensure we haven't already parsed this line\r\n\t\tif ( match.substr(start, 5) == 'parse' ) {\r\n\t\t\treturn match;\r\n\t\t}\r\n\r\n\t\t// And end position\r\n\t\tvar end = analyze_js(match, start);\r\n\t\t\r\n\t\t// Determine the wrapper to use. First clear any whitespace.\r\n\t\ttype = type.replace(/\\s/g, '');\r\n\t\t\r\n\t\t// If .innerHTML, parse HTML. Otherwise, it's a URL.\r\n\t\tvar wrapperFunc = ( type == '.innerHTML=' ) ? 'parseHTML' : 'parseURL';\r\n\r\n\t\t// Create the wrapped statement\r\n\t\tvar wrapped = wrapperFunc + '(' + match.substring(start, end) + ')';\r\n\r\n\t\t// And make the starting replacement \r\n\t\treturn substr_replace(match, wrapped, start, end-start);\r\n\r\n\t}",
"function SearchAndReplace(arr,oldWord,newWord) {\n var t = '';\n var text = arr.split(' ');\n for (let i = 0; i < text.length; i++) {\n if (text[i] == oldWord) {\n t = text[i].charAt(0);\n if (t == text[i].charAt(0).toUpperCase()) {\n t = newWord.charAt(0).toUpperCase()\n t += newWord.slice(1)\n }else{\n t = newWord.charAt(0).toLowerCase()\n t += newWord.slice(1)\n }\n text[i] = t\n }\n }\n return text.join(' ')\n}",
"function declineSingleCase(caseNumberIndex, patternIndex, word) {\n\tif (patternIndex < 0 || patternIndex >= pattern.length || caseNumberIndex < 1 || caseNumberIndex > 14) {\n\t\treturn \"???\";\n\t}\n\n\tvar word3 = palatalize(word);\n\tvar placeholders = [];\n\tvar suffixIndex = isPattern(pattern[patternIndex][1], word3, placeholders)\n\tif (suffixIndex < 0) {\n\t\treturn \"???\";\n\t}\n\n\tvar patternForCase = pattern[patternIndex][caseNumberIndex];\n\tif (patternForCase == \"?\") {\n\t\treturn \"?\";\n\t}\n\n\tvar rv = (!debugModeEnabled && caseNumberIndex == 1) ? /* 1. pad nemenime */\n\tunpalatalize(word3) : leftStr(suffixIndex, word3) + '-' + replacePlaceholders(patternForCase, placeholders);\n\n\tif (debugModeEnabled) {\n\t\t// preskoceni filtrovani\n\t\treturn rv;\n\t}\n\n\t// Formatovani zivotneho sklonovani\n\n\tvar hyphenIndex = rv.indexOf(\"-\");\n\tvar slashIndex = rv.indexOf(\"/\");\n\n\tif (hyphenIndex != -1 && slashIndex != -1) {\n\t\tif (isMasculineGenderAnimate()) {\n\t\t\t// \"text-xxx/yyy\" -> \"textyyy\"\n\t\t\trv = leftStr(hyphenIndex, rv) + rightStr(slashIndex + 1, rv);\n\t\t} else {\n\t\t\t// \"text-xxx/yyy\" -> \"text-xxx\"\n\t\t\trv = leftStr(slashIndex, rv);\n\t\t}\n\t}\n\n\t// vypusteni pomocnych znaku\n\trv = rv.replace(/[\\/\\-]/, \"\");\n\trv = unpalatalize(rv);\n\n\treturn rv;\n}",
"function wordPattern(word) {\n\t\t\tlet wcCombined = wcCombine(new Array(totalWC(word)).fill(wcPattern(4)));\n\t\t\treturn wcCombined.map(combine => {\n\t\t\t\tlet chars = word.split(\"*\");\n\t\t\t\tfor(let i = 1, j = 0; i < chars.length; i += 2) {\n\t\t\t\t\tchars.splice(i, 0, combine[j++]);\n\t\t\t\t}\n\t\t\t\treturn chars.join(\"\");\n\t\t\t});\n\t\t}",
"function replace(string,text,by) {\n // Replaces text with by in string\n\t var i = string.indexOf(text);\n\t var newstr = '';\n\t if ((!i) || (i == -1)) return string;\n\t newstr += string.substring(0,i) + by;\n\n\t if (i+text.length < string.length)\n\t\t newstr += replace(string.substring(i+text.length,string.length),text,by);\n\t \n\t return newstr;\n }",
"match(word) {\n if (this.pattern.length == 0) return [-100 /* NotFull */]\n if (word.length < this.pattern.length) return null\n let { chars, folded, any, precise, byWord } = this\n // For single-character queries, only match when they occur right\n // at the start\n if (chars.length == 1) {\n let first = codePointAt(word, 0),\n firstSize = codePointSize(first)\n let score = firstSize == word.length ? 0 : -100 /* NotFull */\n if (first == chars[0]);\n else if (first == folded[0]) score += -200 /* CaseFold */\n else return null\n return [score, 0, firstSize]\n }\n let direct = word.indexOf(this.pattern)\n if (direct == 0)\n return [\n word.length == this.pattern.length ? 0 : -100 /* NotFull */,\n 0,\n this.pattern.length\n ]\n let len = chars.length,\n anyTo = 0\n if (direct < 0) {\n for (\n let i = 0, e = Math.min(word.length, 200);\n i < e && anyTo < len;\n\n ) {\n let next = codePointAt(word, i)\n if (next == chars[anyTo] || next == folded[anyTo]) any[anyTo++] = i\n i += codePointSize(next)\n }\n // No match, exit immediately\n if (anyTo < len) return null\n }\n // This tracks the extent of the precise (non-folded, not\n // necessarily adjacent) match\n let preciseTo = 0\n // Tracks whether there is a match that hits only characters that\n // appear to be starting words. `byWordFolded` is set to true when\n // a case folded character is encountered in such a match\n let byWordTo = 0,\n byWordFolded = false\n // If we've found a partial adjacent match, these track its state\n let adjacentTo = 0,\n adjacentStart = -1,\n adjacentEnd = -1\n let hasLower = /[a-z]/.test(word),\n wordAdjacent = true\n // Go over the option's text, scanning for the various kinds of matches\n for (\n let i = 0, e = Math.min(word.length, 200), prevType = 0 /* NonWord */;\n i < e && byWordTo < len;\n\n ) {\n let next = codePointAt(word, i)\n if (direct < 0) {\n if (preciseTo < len && next == chars[preciseTo])\n precise[preciseTo++] = i\n if (adjacentTo < len) {\n if (next == chars[adjacentTo] || next == folded[adjacentTo]) {\n if (adjacentTo == 0) adjacentStart = i\n adjacentEnd = i + 1\n adjacentTo++\n } else {\n adjacentTo = 0\n }\n }\n }\n let ch,\n type =\n next < 0xff\n ? (next >= 48 && next <= 57) || (next >= 97 && next <= 122)\n ? 2 /* Lower */\n : next >= 65 && next <= 90\n ? 1 /* Upper */\n : 0 /* NonWord */\n : (ch = fromCodePoint(next)) != ch.toLowerCase()\n ? 1 /* Upper */\n : ch != ch.toUpperCase()\n ? 2 /* Lower */\n : 0 /* NonWord */\n if (\n !i ||\n (type == 1 /* Upper */ && hasLower) ||\n (prevType == 0 /* NonWord */ && type != 0) /* NonWord */\n ) {\n if (\n chars[byWordTo] == next ||\n (folded[byWordTo] == next && (byWordFolded = true))\n )\n byWord[byWordTo++] = i\n else if (byWord.length) wordAdjacent = false\n }\n prevType = type\n i += codePointSize(next)\n }\n if (byWordTo == len && byWord[0] == 0 && wordAdjacent)\n return this.result(\n -100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0),\n byWord,\n word\n )\n if (adjacentTo == len && adjacentStart == 0)\n return [\n -200 /* CaseFold */ -\n word.length +\n (adjacentEnd == word.length ? 0 : -100) /* NotFull */,\n 0,\n adjacentEnd\n ]\n if (direct > -1)\n return [\n -700 /* NotStart */ - word.length,\n direct,\n direct + this.pattern.length\n ]\n if (adjacentTo == len)\n return [\n -200 /* CaseFold */ + -700 /* NotStart */ - word.length,\n adjacentStart,\n adjacentEnd\n ]\n if (byWordTo == len)\n return this.result(\n -100 /* ByWord */ +\n (byWordFolded ? -200 /* CaseFold */ : 0) +\n -700 /* NotStart */ +\n (wordAdjacent ? 0 : -1100) /* Gap */,\n byWord,\n word\n )\n return chars.length == 2\n ? null\n : this.result(\n (any[0] ? -700 /* NotStart */ : 0) +\n -200 /* CaseFold */ +\n -1100 /* Gap */,\n any,\n word\n )\n }",
"function replaceInString(data, search, replace) {\n if (Array.isArray(search)) {\n for (var i=0; i<search.length; i++) {\n data = data.replaceAll(search[i], replace[i]);\n }\n return data;\n } else {\n return data.replaceAll(search, replace);\n }\n}",
"function str_replace(haystack, needle, replacement) {var temp = haystack.split(needle);return temp.join(replacement);}",
"makeSubstitutions (callback) {\n\t\tthis.emailData = this.emailData.replace(/@@@from@@@/g, this.userData[0].user.email);\n\t\tthis.emailData = this.emailData.replace(/@@@sender@@@/g, this.config.email.senderEmail);\n\t\tlet to = `${this.parentPost.id}.${this.teamStream.id}.${this.team.id}@${this.config.email.replyToDomain}`;\n\t\t['to', 'cc', 'bcc', 'x-original-to', 'delivered-to'].forEach(field => {\n\t\t\tlet regEx = new RegExp(`@@@${field}@@@`, 'g');\n\t\t\tthis.emailData = this.emailData.replace(regEx, to);\n\t\t});\n\t\tcallback();\n\t}",
"function replace(pString, pText, by) {\n try {\n var strLength = pString.length,\n txtLength = pText.length;\n if ((strLength == 0) || (txtLength == 0)) return pString;\n var vIndex = pString.indexOf(pText);\n while (vIndex >= 0) {\n pString = pString.replace(pText, by);\n vIndex = pString.indexOf(pText);\n } //End While\n } catch (e) {}\n return pString;\n}",
"function extUtils_replaceValuesInNodeSegment(nodeSeg, updatePatterns, paramObj)\n{\n var retVal = '';\n var theNode = nodeSeg.node;\n var theStr = extUtils.convertNodeToString(theNode);\n\n if (typeof theStr == \"string\" && theStr.length && theNode.outerHTML)\n {\n var innerLength = dwscripts.getInnerHTML(theNode).length;\n var closeTagPos = dwscripts.getOuterHTML(theNode).lastIndexOf(\"</\");\n var innerStart = closeTagPos - innerLength;\n var tagStart = theStr.substring(0,innerStart);\n var tagInner = theStr.substring(innerStart,closeTagPos);\n var tagEnd = theStr.substring(closeTagPos);\n for (var i=0; i < updatePatterns.length; i++)\n {\n var limitSearch = updatePatterns[i].limitSearch;\n var newParamValue = paramObj[updatePatterns[i].paramName];\n if (updatePatterns[i].pattern) //if there is a pattern, use it to update\n {\n var pattern = eval(updatePatterns[i].pattern);\n if (!limitSearch || limitSearch == \"tagOnly\")\n {\n tagStart = extUtils.safeReplaceBetweenSubExpressions(tagStart, pattern, newParamValue);\n }\n if (!limitSearch || limitSearch == \"innerOnly\")\n {\n var localBeginOffset = nodeSeg.matchRangeMin - innerStart;\n var localEndOffset = nodeSeg.matchRangeMax - innerStart;\n if (localBeginOffset >= 0 && localBeginOffset < localEndOffset && localEndOffset < innerLength)\n {\n var tinyString = tagInner.substring(localBeginOffset, localEndOffset);\n tinyString = extUtils.safeReplaceBetweenSubExpressions(tinyString, pattern, newParamValue);\n tagInner = tagInner.substring(0,localBeginOffset) + tinyString + tagInner.substring(localEndOffset);\n }\n else\n {\n tagInner = extUtils.safeReplaceBetweenSubExpressions(tagInner, pattern, newParamValue);\n }\n }\n if (!limitSearch)\n {\n tagEnd = extUtils.safeReplaceBetweenSubExpressions(tagEnd , pattern, newParamValue);\n }\n }\n else\n {\n if (limitSearch == \"innerOnly\") //innerOnly update pattern, so blow away inner\n {\n tagInner = newParamValue;\n }\n else if (limitSearch == \"tagOnly\") //tag update pattern, so blow away inner\n {\n tagStart = newParamValue;\n }\n else if (!limitSearch) //no update pattern, so blow away whole thing\n {\n tagStart = newParamValue;\n tagInner = \"\";\n tagEnd = \"\";\n }\n }\n }\n retVal = tagStart + tagInner + tagEnd;\n }\n\n return retVal;\n}",
"function replaceString(str, findTok, replaceTok, isOne) {\n\n pos = str.indexOf(findTok);\n valueRet = \"\";\n if (pos == -1) {\n return str;\n }\n valueRet += str.substring(0,pos) + replaceTok;\n if (!isOne && ( pos + findTok.length < str.length)) {\n valueRet += replaceString(str.substring(pos + findTok.length, str.length), findTok, replaceTok);\n } else {\n\t\tvalueRet += str.substring(pos + findTok.length, str.length)\n\t}\n\n return valueRet;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove last row if state matches | removeRow(state) {
if (this._rows.length > 0 &&
this._rows[this._rows.length - 1].state === state) {
this._rows = this._rows.slice(0, -1);
}
} | [
"function removeLastRow() {\n let rows = $('#table tr');\n if (rows.length > 1) {\n rows.last().remove();\n }\n rowIndex--;\n}",
"disposeRows() {\n // keep rows still in use, remove the others\n const keepers = [];\n this.rows.forEach((row) => {\n if (row.updateReference === this.updateReference) {\n keepers.push(row);\n } else {\n this.sceneGraph.root.removeChild(row);\n }\n });\n this.rows = keepers;\n }",
"isLastRow(): boolean {\n return this.getRowIndex() === this.getHeight() - 1;\n }",
"clearSelectedRow() {\n var $row = this.$table.find('tr.active');\n $row.removeClass('active');\n this.removeEditable($row);\n }",
"onAfterRemoveRow() {\n this.bindStrategy.removeRow(this.removedRows);\n }",
"function removeQuery(state, queryId) {\n const new_order = [];\n for(const id of state.order) {\n if(id !== queryId) {\n new_order.push(id);\n }\n }\n\n const new_state = Object.assign({}, state, {order: new_order});\n delete new_state[queryId];\n return new_state;\n}",
"function onlyOneChangeFromLastState(){\n\tvar constraints = [];\n\tfor(var i = 1; i <= 9; i++){\n\t\tvar name = \"cell-\"+i;\n\n\t\tconstraints.push(\n\t\t\t// Cell changed from un-marked to marked\n\t\t\tLogic.and(\n\t\t\t\t// was empty\n\t\t\t\tLogic.equiv(Logic.TRUE, (lastState[name+\"$0\"] ? Logic.TRUE : Logic.FALSE) ),\n\t\t\t\t// now marked\n\t\t\t\tLogic.equiv(Logic.FALSE, name+\"$0\")\n\t\t\t)\n\t\t);\n\t}\n\n\tvar constraint = Logic.exactlyOne.apply(Logic.exactlyOne, constraints);\n\tbp.addConstraint(constraint);\n}",
"function delete_prev_grid() {\n var table = document.getElementById(\"pixel_canvas\");\n var rowCount = table.rows.length;\n while (table.rows.length > 0) {\n table.deleteRow(0);\n }\n }",
"restoreRowPosition() {\n\t\t\tthis.swoosh.restore();\n\t\t}",
"function clear_old_state() {\n\t\t// Clear any existing matches\n\t\tdb.client.del(week_key, function(err,reply) {\n\t\t\tif (err) return _error(err);\n\t\t\treturn create_this_weeks_matches();\n\t\t});\n\t}",
"removeBack() {\n this._taskArr.pop();\n /*\n if(this._taskArr.length === 1) {\n this._taskArr.pop();\n } else if(this._taskArr.length > 1) {\n let curr = this._taskArr[this._taskArr.length - 1];\n let prev = this._taskArr[this._taskArr.length - 2];\n prev.setEndTime(curr.endTime);\n }\n */\n }",
"handleEraseClick() {\n const history = this.state.history.slice(0, this.state.currStep + 1);\n const currBoard = this.state.history[this.state.currStep].board.slice();\n const currNotes = JSON.parse(JSON.stringify(this.state.history[this.state.currStep].notes.slice()));\n const startingBoard = this.state.history[0].board;\n\n if (this.state.selectedCell && !startingBoard[this.state.selectedCell] && (!this.checkNotesEmpty(currNotes[this.state.selectedCell]) || currBoard[this.state.selectedCell])) {\n currBoard[this.state.selectedCell] = null;\n for (let i = 0; i < 9; i++) {\n currNotes[this.state.selectedCell][i] = false;\n }\n\n let numCount = this.countNums(currBoard);\n this.setState({\n history: history.concat([{\n board: currBoard,\n notes: currNotes,\n }]),\n currStep: this.state.currStep + 1,\n numCount: numCount,\n });\n }\n }",
"deleteWeight(){\n //If they only have one weight logged, they're current weight is set to zero\n if(this.weightLog.length == 1){\n this.weight = () => -1;\n }else{\n this.weight = () => this.weightLog[this.weightLog.length - 1].weight;\n }\n return this.weightLog.splice(this.weightLog.length -1,1);\n\n }",
"function rememberRemoval( tab ) {\n lastRemoved.unshift(tab);\n\n if (lastRemoved.length > MAX_HISTORY) {\n lastRemoved.pop();\n }\n}",
"deleteRuleset() {\n var rulesets = this.state.rulesets\n\n rulesets.splice(this.state.currentRuleset, 1) // Deletes the ruleset at the currentRuleset index\n\n if (rulesets.length > 0) { // If there is still more rulesets, just set currentRuleset to one less than before\n this.setState({rulesets: rulesets, currentRuleset: this.state.currentRuleset-1}, () => {\n this.updateData()\n })\n } else { // If there are no more rulesets, add an empty one and set currentRuleset to 0\n rulesets.push([\"placeholder\"])\n this.setState({rulesets: rulesets, currentRuleset: 0}, () => {\n this.updateData()\n })\n }\n }",
"function removeTableData() {\r\n hideTable();\r\n d3.selectAll(\".row_info\").remove();\r\n }",
"eraseEvent(state, num) {\n state.events.splice(num, 1);\n\n }",
"function removeRow (grid, i) {\n\n //console.log(\"REMOVING ROW: \", i);\n\n // remove the row at index i \n grid.splice(i,1);\n\n // create new empty row \n let newRow = newEmptyRow();\n\n // insert new row into grid at the top\n grid.splice(grid.length - 1, 0, newRow);\n \n //console.log(\"NEW GRID: \", grid);\n\n return;\n}",
"handleRightShiftUpdate($row){\n const node = $row.children(':last')\n node.detach();\n $row.prepend(node); \n }",
"function clearSelectedRows() {\n var tblRows = contentTbl.fnGetNodes(),\n\t\ttblRow,\n\t\tnumRows = tblRows.length;\n for (var i = 0; i < numRows; i++) {\n\t\ttblRow = $(tblRows[i]);\n if ($(tblRow).hasClass('selected')) {\n $(tblRow).removeClass('selected');\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the end index of the excerpt for the specified mention. | function excerptEnd(mention) {
var i = mention.section.j, match;
sentenceRe.lastIndex = mention.j + 40;
match = sentenceRe.exec(mention.section.speech.text);
return match ? Math.min(match.index + match[1].length, i) : i;
} | [
"endIndex()\n\t{\n\t\tlet endIndex=0;\n\t\tlet startIndex=this.startIndex();\n\t\tif(this.pageCount()===this.props.currentPage)\n\t\t\tendIndex=this.pageCount();\n\t\telse if(startIndex+(this.props.buttonsCount-1)<=this.pageCount())\n\t\t\tendIndex=startIndex+(this.props.buttonsCount-1);\n\t\telse\n\t\t\treturn this.pageCount();\n\n\t\treturn endIndex;\n\t}",
"function last(){\n\tvar isi = \"saya beajar di rumah beajar\";\n\tconsole.log(isi.lastIndexOf(\"beajar\",5)); //nilai angka berfungsi sebagai startnya di index\n}",
"function getLastClosedOffset(referenceSIM, tags) {\n for (var i = tags.length - 1; i >= 0; i--) {\n var ctag = tags[i];\n if (ctag.sim === referenceSIM && ctag.end !== undefined) {\n return ctag.offset;\n }\n }\n return 0;\n }",
"get end() {\n return this.endMarker;\n }",
"_lookRight(end, contextWords) {\n let charToToken = this._charToToken;\n let tokenOffsets = this._tokenOffsets;\n if (tokenOffsets.length === 0) {\n return end;\n };\n\n // If we landed between tokens, look right for token number.\n let lastToken = tokenOffsets.length - 1;\n let onToken = lastToken;\n let correct_for_start = 0;\n // end always points one character past the selection, but we want to\n // start our check on the actual last character of the selection\n end--;\n while ((end > 0) && (end < charToToken.length)\n && (onToken = charToToken[end]) < 0) {\n end++;\n correct_for_start = 1;\n };\n if (onToken === -1) {\n onToken = lastToken;\n }\n let goalToken = Math.min(lastToken, onToken + contextWords - correct_for_start);\n return tokenOffsets[goalToken].end;\n }",
"function getInsertionIndex() {\n var _select3 = select('core/block-editor'),\n getBlockIndex = _select3.getBlockIndex,\n getBlockSelectionEnd = _select3.getBlockSelectionEnd,\n getBlockOrder = _select3.getBlockOrder;\n\n var clientId = ownProps.clientId,\n destinationRootClientId = ownProps.destinationRootClientId,\n isAppender = ownProps.isAppender; // If the clientId is defined, we insert at the position of the block.\n\n if (clientId) {\n return getBlockIndex(clientId, destinationRootClientId);\n } // If there a selected block, we insert after the selected block.\n\n\n var end = getBlockSelectionEnd();\n\n if (!isAppender && end) {\n return getBlockIndex(end, destinationRootClientId) + 1;\n } // Otherwise, we insert at the end of the current rootClientId\n\n\n return getBlockOrder(destinationRootClientId).length;\n }",
"function DDLightbarMenu_GetTopItemIdxOfLastPage()\n{\n\tvar numItemsPerPage = this.size.height;\n\tif (this.borderEnabled)\n\t\tnumItemsPerPage -= 2;\n\tvar topItemIndex = this.NumItems() - numItemsPerPage;\n\tif (topItemIndex < 0)\n\t\ttopItemIndex = 0;\n\treturn topItemIndex;\n}",
"_getLastTriggeredIndex() {\n const index = this.options.toArray().indexOf(this._lastTriggered);\n return index === -1 ? null : index;\n }",
"function FindMotif(targetMotif, dnaString){\n\tvar indexLoc = '';\n\tvar notDone = true;\n\tvar counter = 0;\n\tvar lastFound = 0;\n\twhile(notDone && counter <10000){\n\t\tvar pos = dnaString.toString().indexOf(targetMotif,lastFound);\n\t\tif(pos == -1)\n\t\t\tnotDone = false;\n\t\telse{\n\t\t\tpos++\n\t\t\tindexLoc += (pos-1) + ' ';\n\t\t\tlastFound = pos;\n\t\t}\n\t\tconsole.log(pos);\n\t\tcounter++;\n\t}//end while\n\n\tconsole.log(indexLoc);\n\treturn indexLoc;\n}",
"function 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}",
"function findLastNumber(str) {\n for (let i = str.length - 1; i >= 0; --i) {\n const code = str.charCodeAt(i);\n if (code >= _ZERO && code <= _NINE) {\n return i;\n }\n }\n return -1;\n}",
"function getPosition(str,start,needle){\n\tvar index = str.substr(start).indexOf(needle);\n\tif (index==-1) {\n\t\treturn index;\n\t}\n\treturn index+start;\n}",
"function findLastIndex(arr, fn) {\n\tfor (let i = arr.length - 1; i >= 0; --i) {\n\t\tif (fn(arr[i])) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn -1;\n}",
"function pullEnemyIndex(y) {\n let eindex = findInArray(enemylist, y);\n return eindex;\n }",
"get end_results(){\n let resultsOnPage = (this.page_number + 1) * this.size;\n\n if (resultsOnPage <= this.total) {\n return resultsOnPage;\n }\n\n return this.total;\n }",
"function extractExcerpt(article) {\n if (!article.hasOwnProperty('templateContent')) {\n console.warn(\n 'Failed to extract excerpt: Document has no property \"templateContent\".'\n )\n return null\n }\n\n let excerpt = null\n const content = article.templateContent\n\n // The start and end separators to try and match to extract the excerpt\n const separatorsList = [\n { start: '<!-- Excerpt Start -->', end: '<!-- Excerpt End -->' },\n { start: '<p>', end: '</p>' },\n ]\n\n separatorsList.some((separators) => {\n const startPosition = content.indexOf(separators.start)\n const endPosition = content.indexOf(separators.end)\n\n if (startPosition !== -1 && endPosition !== -1) {\n excerpt = content\n .substring(startPosition + separators.start.length, endPosition)\n .trim()\n return true // Exit out of array loop on first match\n }\n })\n\n return excerpt\n}",
"function indexOf(distance) {\n flushPendingChanges.call(this);\n var index = indexOfInternal.call(this, distance);\n return index >= this._length ? -1 : index;\n }",
"function lastTime(arr, num) {\n // for (let i = arr.length - 1; i >= 0; i--) {\n // let num = arr[i];\n // if (num == target) {\n // return i;\n // }\n // }\n let targetIndex;\n for (let i = 0; i < arr.length; i++) {\n let num = arr[i];\n if (num == target) {\n targetIndex = i;\n }\n }\n}",
"function indexoff(){\n\tvar isi = \"saya beajar di rumah\";\n\tconsole.log(isi.indexOf(\"beajar\"));\n}",
"isEnd(editor, point, at) {\n var end = Editor.end(editor, at);\n return Point.equals(point, end);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
13. Write a program to take user input and store username in a variable. If the username contains any special symbol | function validUsername() {
var userName = prompt("Enter username");
var len = userName.split("");
for(i = 0; i < len.length; i++) {
if( (userName.slice(i,i+1) == "@") || (userName.slice(i,i+1) == ".") || (userName.slice(i,i+1) == "!") ) {
document.write("Invalid");
break;
}
}
} | [
"function getUsername() {\n let userName = document.getElementById('username_input_field').value;\n\n // if username supplied is invalid, alert user, and return null\n const validUsernameRegExp = new RegExp('^([a-zA-Z0-9_-]{3,16})$');\n if (!validUsernameRegExp.test(userName)) {\n alert('Your username can only contain alphanumeric, '\n + ' underscore, and hyphen characters (a-z A-Z 0-9 _ -). '\n + 'It should be at least 3 characters long.');\n return null;\n }\n\n // store username for next time\n setToLocalStorage(userNameKey, userName);\n\n return userName;\n}",
"function resolveUsername(username){\n if (username === \"\"){\n return \"\";\n } else {\n return \" by \" + username;\n }\n}",
"function validUsername(username) {\n return (username.trim().length) >= 3;\n}",
"function checkUsernameChange(data){\n data.toLowerCase();\n var result = data.match(/\\/nick/i);\n if(result === null || result.length!=1)\n return false;\n else\n return true;\n}",
"function handleUsername() {\r\n\r\n // we extract the last.fm username from the form\r\n const username = document.forms.enterUsername.elements.username.value;\r\n\r\n // we first check if the username field is empty\r\n if (username === '') {\r\n alert('Please enter a last.fm username');\r\n // if not, we can begin the search\r\n } else {\r\n\r\n // we first remove the search settings form from the screen\r\n document.getElementById('enterUsername').style.display = 'none';\r\n\r\n // and now retrieve this user's last.fm friends' names\r\n getFriends(username);\r\n }\r\n}",
"function usernameValidation(str) {\n const regex = /[^A-Za-z0-9\\_]/;\n return (\n str.length >= 4 &&\n str.length <= 25 &&\n str[0].match(/[A-z]/) &&\n !regex.test(str) &&\n str[str.length - 1] !== \"_\"\n );\n}",
"function promptUsername() {\n setInputFlow(submitUsername, true);\n\n print('Please enter your username in the box below');\n}",
"function findUsername(bookshelf, username) {\n let name = Object.keys(bookshelf.users).filter((e) => e === `${username}`);\n return !name ? errorMessage() : name;\n}",
"function getUserToSearch(name = \"giusetega\"){\n var user = document.getElementById(\"username\").value;\n return (user == null || user == \"\") ? name : user;\n}",
"function IndivisualLog() {\n\n \n var inFieldU = document.getElementById(\"in-userf\");\n var inFieldP = document.getElementById(\"in-passf\");\n \n var inLabelU = document.getElementById(\"in-user\");\n var inLabelP = document.getElementById(\"in-pass\");\nusernameRegex .exec(inFieldU);//regular expression\n const vaild=!!usernameRegex;\n if(!vaild){\nalert(\"user name is invaild\");\nreturn false\n }\n\n //if already shown from previous submit to hide it\n if (inLabelU.style.display === \"inline\" || \n inLabelP.style.display === \"inline\" \n \n \n ) {\n\n inLabelU.style.display = \"none\";\n inLabelP.style.display = \"none\";\n \n \n \n }\n if( inFieldU.value[0].match(RegexFirstchar) != null ){\n inLabelU.innerHTML=\"user name should not start with number or Literal Characters\";\n inLabelU.style.display=\"inline\"\n return false\n }\n\n \n }",
"function getUserPassword(username) {\n return username;\n}",
"function makeMyUsername(email){\n let username = email.slice(0,email.indexOf(\"@\"))\n return username;\n}",
"function fn_CheckLoginName ( strLogin )\n\t{\n\t\tstrLogin = trimString( strLogin ) ;\n\n\t\tvar checkOK = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._@\";\n\t\tvar checkStr = strLogin ;\n\t\tvar allValid = true;\n\t\tfor (i = 0; i < checkStr.length; i++)\n\t\t{\n\t\t\tch = checkStr.charAt(i);\n\t\t\tfor (j = 0; j < checkOK.length; j++)\n\t\t\t if (ch == checkOK.charAt(j))\n\t\t\t\tbreak;\n\t\t\tif (j == checkOK.length)\n\t\t\t{\n\t\t\t allValid = false;\n\t\t\t break;\n\t\t\t}\n\t\t}\n\t\tif ( ! allValid )\n\t\t{\n\t\t\treturn (false);\n\t\t}\n\n\t\tif ( checkStr.charAt(0) == '-' || checkStr.charAt(0) == '.' || checkStr.charAt(0) == '_' )\n\t\t{\n\t\t\treturn (false);\n\t\t}\n\n\t\treturn (true);\n\t}",
"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}",
"function getNickName() {\r\n \r\n return $(\"#loggedin\").text().substring(9);\r\n \r\n \r\n }",
"requestUsername() {\n var ui = SpreadsheetApp.getUi();\n var result = ui.prompt('Connect to ReadWorks', 'Please enter your ReadWorks username (email):', ui.ButtonSet.OK_CANCEL);\n var button = result.getSelectedButton();\n var text = result.getResponseText();\n if (button == ui.Button.CANCEL) {\n throw new Error('No username provided, cancelling assignment import.');\n } else if (button == ui.Button.CLOSE) {\n throw new Error('No username provided, cancelling assignment import.');\n }\n this.username = text;\n return this.username;\n }",
"function procAlias(username) {\n if (Object.keys(userData.alias).indexOf(username) > -1)\n return userData.alias[username];\n\n return username;\n}",
"function askForName() {\n var name = \"\";\n\n // Ensure name is valid\n while(name === \"\" || name === null) {\n name = window.prompt(\"Please enter a display name.\", \"\");\n }\n\n console.log(\"Player name set to \" +name+ \".\");\n return name;\n }",
"function takeUserInput(value){\n if(value !== 'Submit' && value !== '<' && value !== 'C' && userInput.length < 4){\n userInput += value;\n print();\n }\n else{\n switch(value){\n case 'Submit': // if the submit button is pressed then call the isValid() function\n // to check whether the userInput is valid or not.\n tries--;\n isValid();\n break;\n case '<': // backspace statement.\n if(userInput.length > 0){\n userInput = userInput.substr(0, userInput.length -1); \n print();\n }\n break;\n case 'C': // delets all the userInput\n reset();\n }\n }\n\n function print(){ // prints the real time userInput value.\n userText.value = userInput;\n }\n\n } // end function registerInput();"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates document title to flag current spent time | _updateTitle()
{
document.head.querySelector('title').innerText = `[${this._toString('HH:mm:ss')}] @amjs/working-on`;
} | [
"_updateTitle() {\n let ttl = '';\n if (this._curPage) {\n ttl = this._curPage.title();\n }\n document.title = this._rootArea.title(ttl);\n }",
"function modify_title()\n{\n if( title != undefined ) document.title = \"Scheduler - \" + title;\n\n var title_state;\n \n if( document.readyState == \"interactive\" ) title_state = \"(running)\";\n else\n if( document.readyState == \"complete\" ) title_state = \"(terminated)\";\n\n if( title_state ) document.title = document.title.replace( / *(\\(.*\\))|$/, \" \" + title_state );\n}",
"function changeTitle() {\n\t$currenttitle.text($currenttitle.text().replace(/Currently Playing:/, TitleBarDescription_Caption));\n}",
"function saveTitle() {\n\n var id = $(\"#current-note-display\")[0].getAttribute(\"data-id\");\n var title = $(\"#current-note-title\").text();\n editNote(id=id, title=title);\n\n //Replace title of note block in notes display with new title\n var curNote = findNoteElement(id);\n if (curNote != null) {\n curNote.innerHTML = trimTitle(title, titleDisplayLen);\n }\n\n}",
"function drawTitle(title, color, expTime) {\n width = svgPath.attr(\"width\");\n height = svgPath.attr(\"height\");\n removeTitle();\n svgPath.append(\"text\").attr(\"class\", \"title\").attr(\"x\", width / 2).attr(\n \"y\", ph_h).attr(\"text-anchor\", \"middle\").style(\"font-size\", \"18px\")\n .style(\"text-weight\", \"bold\").style(\"fill\", color).text(title);\n\n if (expTime) {\n remain = (expTime * 1000) - Date.now();\n var days = Math.floor(remain / yearMs);\n var hours = Math.floor((remain % yearMs) / hourMs);\n var minutes = Math.floor((remain % hourMs) / minuteMs);\n var seconds = Math.floor((remain % minuteMs) / secondMs);\n var clock = [];\n clock.push(('00' + hours).substr(-2), ('00' + minutes).substr(-2),\n ('00' + seconds).substr(-2));\n clockStr = (days > 0 ? days + \"d \" : \"\") + clock.join(\":\");\n remainStr = remain > 0 ? clockStr : \"Expired.\";\n svgPath.append(\"text\").attr(\"class\", \"clock\").attr(\"x\", width - ph_m)\n .attr(\"y\", ph_h).attr(\"text-anchor\", \"end\").style(\"font-size\",\n \"14px\").style(\"fill\", color).text(remainStr);\n if (remain > 0) {\n expClock = setTimeout(function() {\n drawTitle(title, color, expTime)\n }, secondMs)\n }\n }\n}",
"function editableTitle(){\n var postTitle = document.getElementById('postTitle');\n var titleText = postTitle.innerText;\n if(titleText.startsWith(\"UPDATED: \"))\n titleText = titleText.replace(\"UPDATED: \",\"\");\n postTitle.innerHTML = titleText;\n postTitle.contentEditable = \"true\";\n postTitle.classList.add(\"edit\");\n}",
"function addCountToDocumentTitle(countMessage) {\n\n if (document.title.indexOf(getMessage(kradVariables.MESSAGE_TOTAL_ERROR, null, null) > 0)\n || document.title.indexOf(getMessage(kradVariables.MESSAGE_TOTAL_WARNING, null, null) > 0)\n || document.title.indexOf(getMessage(kradVariables.MESSAGE_TOTAL_MESSAGE, null, null) > 0)) {\n\n var tokenIndex = document.title.lastIndexOf(\" - \");\n if (tokenIndex > -1) {\n document.title = document.title.substr(0, tokenIndex) + \" - \" + countMessage;\n return;\n }\n }\n\n document.title = document.title + \" - \" + countMessage;\n}",
"function updateTimeElapsed() {\n var time = formatTime(Math.round(video.currentTime));\n timeElapsed.innerText = formatTimeHumanize(time);\n timeElapsed.setAttribute('datetime', `${time.hours}h ${time.minutes}m ${time.seconds}s`);\n }",
"function updatedTitle(){\n var postTitle = document.getElementById('postTitle');\n var editedText = postTitle.innerText;\n postTitle.innerHTML = \"UPDATED: \"+editedText;\n postTitle.classList.remove(\"edit\");\n postTitle.contentEditable = \"false\";\n}",
"_updateTitleTab() {\n var self = this;\n super._updateTitleTab();\n if (_.isUndefined(self.m_sceneMime))\n return;\n $(Elements.BLOCK_SUBPROPERTIES_TITLE).text(self.m_config[self.m_sceneMime].tabTitle);\n }",
"function rewriteTitle() {\n\tif( typeof( SKIP_TITLE_REWRITE ) != 'undefined' && SKIP_TITLE_REWRITE ) {\n\t\treturn;\n\t}\n\n\tvar titleDiv = document.getElementById( 'title-meta' );\n\n\tif( titleDiv == null || titleDiv == undefined ) {\n\t\treturn;\n\t}\n\n\tvar cloneNode = titleDiv.cloneNode( true );\n\tvar firstHeading = document.getElementById( 'firstHeading' );\n\tvar node = firstHeading.childNodes[0];\n\n\t// new, then old!\n\tfirstHeading.replaceChild( cloneNode, node );\n\tcloneNode.style.display = 'inline';\n\tif ( titleDiv.childNodes[0].nodeValue.toLowerCase() == wgPageName.replace( /_/g, ' ' ).toLowerCase() ) {\n\t\tdocument.title = titleDiv.childNodes[0].nodeValue;\n\t}\n\n\tvar titleAlign = document.getElementById( 'title-align' );\n\tfirstHeading.style.textAlign = titleAlign.childNodes[0].nodeValue;\n}",
"get title()\n\t{\n\t\t//dump(\"get title: title:\"+this._calEvent.title);\n\t\tif (this._newTitle) {\n\t\t\treturn this._newTitle;\n\t\t}\n\n\t\tif (this._title) {\n\t\t\treturn this._title;\n\t\t}\n\n\t\treturn this._calEvent.title;\n\t}",
"set title(title) {\n if (Lang.isNull(title)) {\n this._study.title = null;\n return;\n }\n let titleObj = new Title();\n titleObj.value = title;\n this._study.title = titleObj;\n }",
"monitorTitle( mutations ) {\n\t\tif ( ! mutations[0].target.textContent.match( this.mentionCounterRegExp ) && this.mentionCount > 0 ) {\n\t\t\tthis.insertTitleCounter();\n\t\t}\n\t}",
"function updateTime() {\n let label = moment().format(timeFormat);\n\n trayIcon.setTitle(label);\n}",
"function UpdateDVDTitle() {\n\n\tif (g_bFirstPlaying) {\n\t\tTitleFull.Text = L_DVDPlayer_TEXT;\n\t\tTitle.Text = L_DVDPlayer_TEXT;\n\t}\n\n\telse {\n\t\ttry { \n\t\t\tnTitle = DVD.CurrentTitle;\n\t\t\tnChap = DVD.CurrentChapter;\n\n var tempstr = L_DVDPlayerTitleChapter_TEXT.replace(/%1/i, nTitle).replace(/%2/i, nChap);\n\t\t\tTitleFull.Text = tempstr;\n\t\t\tTitle.Text = tempstr;\n\t\t}\n\t\tcatch(e) {\n\t\t\tTitleFull.Text = L_DVDPlayer_TEXT;\n\t\t\tTitle.Text = L_DVDPlayer_TEXT;\n\t\t}\n\t}\n\n\tif (g_bFullScreen && !g_bActivityDeclined) \n {\n if (g_LTRReading)\n {\n xCoord = g_nButPosFull[g_nIndexTitle][0];\n }\n else\n {\n xCoord = g_ConWidth - g_nButPosFull[g_nIndexTitle][0] - TitleFull.TextWidth;\n }\n yCoord = g_nButPosFull[g_nIndexTitle][1];\n \n\t\tMFBar.SetObjectPosition(\"TitleFull\", xCoord, yCoord,\n\t\t\tTitleFull.TextWidth, g_nButPos[g_nIndexTitle][3]);\n\n\t\tMFBar.SetObjectPosition(\"Title\", xCoord, yCoord - 1000,\n\t\t\tTitle.TextWidth, g_nButPos[g_nIndexTitle][3]);\n\t}\n\telse if (!g_bFullScreen) \n {\n if (g_LTRReading)\n {\n xCoord = g_nButPos[g_nIndexTitle][0];\n }\n else\n {\n xCoord = g_ConWidth - g_nButPos[g_nIndexTitle][0] - Title.TextWidth;\n }\n yCoord = g_nButPos[g_nIndexTitle][1];\n\n\t\tMFBar.SetObjectPosition(\"Title\", xCoord, yCoord,\n\t\t\tTitle.TextWidth, g_nButPos[g_nIndexTitle][3]);\n\n\t\tMFBar.SetObjectPosition(\"TitleFull\", xCoord, yCoord - 1000,\n\t\t\tTitleFull.TextWidth, g_nButPos[g_nIndexTitle][3]);\n\t}\n\n\tUpdateDVDMessage();\n}",
"function musicAppHeading() {\n $(\"#header #appTitle\").text(\"Music Quiz\");\n $(\"#header #currentDay\").text(moment().format('dddd, MMMM Do'));\n}",
"function setupTitle() {\n var alarmRichlist = document.getElementById(\"alarm-richlist\");\n var reminders = alarmRichlist.childNodes.length;\n\n let title = PluralForm.get(reminders, calGetString(\"calendar\", \"alarmWindowTitle.label\"));\n document.title = title.replace(\"#1\", reminders);\n}",
"increaseTime() {\r\n this.duration += 1;\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sends a command to the server to power off the stb | function powerOff() {
sendPowerCommand('off');
} | [
"function reboot() {\n sendPowerCommand('reboot');\n}",
"function powerOn() {\n sendPowerCommand('on');\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 powerOff() {\n setVisible(powerOffButton, false);\n setVisible(powerOnButton, true);\n if (fmRadio.isPlaying()) {\n fmRadio.stop();\n }\n saveCurrentStation();\n saveVolume();\n }",
"function sustainOff() {\n echo = \"regular\";\n console.log('sustain off');\n }",
"function sendIdle() {\r\n sendStatus(status = \"idle\");\r\n}",
"stopShooting() {\n this.shooting = false;\n this.sentAddShooterPacket = false;\n\n var msg = {\n type: \"RemoveShooter\",\n entityType: \"Player\",\n };\n\n game.getNetwork.sendMessage(JSON.stringify(msg));\n }",
"sendReset() {\n this.sendMessage('reset');\n }",
"stop_midi_clock() {\n this.midi_clock.send([0xfc]);\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 systemOff (req, res) {\n\t\t// Here we will have calls to public controller functions to switch on/off a boolean\n\t\t// within each controller that lets it know whether it has permission to run\n\t}",
"async stop () {\n if (this.status !== ServerStatus.OFFLINE &&\n this.status !== ServerStatus.STOPPING) {\n await this.container.stop();\n }\n }",
"turnOff(){\n this._vehicleEngineStatus = false;\n const vehicleEngineStatus = \"The engine is not running\";\n return vehicleEngineStatus;\n }",
"function DriveStop() {\n wheels.both.stop();\n driveCmds = {};\n cmdCount = 0;\n}",
"lightsOff() {\n console.log('[johnny-five] Lights are off.');\n this.lights.stop().off();\n }",
"disable() {\n BluetoothSerial.disable()\n .then(res => {\n BluetoothActions.setIsEnabled(false);\n })\n .catch(err => console.log(err.message));\n }",
"function sendCmd(cmd) {\n return sendJson(ip+\"/cmd/{'c':\"+cmd+\"}\");\n}",
"stopRobotSimulation() {\n\t\tthis.status = false;\n\t}",
"function wakeUpServer() {\n\tvar h = require(\"http\");\n\th.get(SERVER_URL);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
When function is called, fn executes 2 things 1. Puts info together so that User is able to view the module added 2. Stores info in an array so that info can be send over to server 3. Removes selected option This event is not only binded to the button, it is also binded to the main form element. Currently, solving this problem unelegantly (LOOK AT THE IF STATEMENT) | function addEventForButton(button){
// Event Number 4 - Adds Module chosen
// along with tut/lab/etc.. info
button.on('click',function(){
var content = ''; //content holds info to be printed on the page for the user to see
//module-info
var moduleInfo;
content += $('.control-group:first select').select2('val');
moduleInfo = $('.control-group:first select').select2('val').split(' ')[0];
$('#mod-code option').each(function(){
if($(this).text() === content){
$(this).remove();
}
});
//Lecture Info
var lec = [];
$('.mod-info').find('div.lecture').each(function(){
var l = {
type: $(this).find('label').text(),
group: $(this).find('span').text()
};
lec.push(l);
});
// Other Info
var tut = [];
$('.mod-info').find('div.non-lecture').each(function(){
var t = {
type:$(this).find('label').text(),
group: $(this).find('span').text()
};
tut.push(t);
});
var allInfo = {
label : moduleInfo,
lectures: lec,
tutorials: tut,
};
$('.mod-pane').addClass('well');
addModuleButton();
$('.mod-pane table').append('<tr><td>' + content + '</td></tr>');
$('.mod-pane table tbody tr:last td').append('<button>×</button>');
$('.mod-pane table tbody tr:last td').find('button').addClass('close');
addEventForModuleTags();
allocModList.push(allInfo);
$('#mod-code').trigger('select2-removed');
$("#mod-code").select2("val", "");
});
} | [
"function toggleTeam()\n{\n var pickedTeam = $('#teamNum').val() + \" \" + $('#event option:selected').text();\n if($('#list').hasClass('btn-success'))\n {\n userData.teamList.push(pickedTeam)\n changeToRemove();\n }\n else\n {\n removeFromTeamList(pickedTeam);\n changeToAdd();\n } \n setUserData();\n}",
"function handleAddProgramPanel() {\n let addProgramContainer = $(this).parents('.add_program_container')[0]\n let selectedProgram = $(addProgramContainer).siblings('.selected_program')[0]\n let dataId = $(this).attr('data-id')\n console.log(dataId)\n if (!selectedPrograms.includes(dataId)) {\n addProgramPanel(this)\n $(addProgramContainer).find('.add_program_input').val('')\n }\n}",
"function updateDialogUI() {\n // if (count > MAX) {\n // addButton.attr('disabled', 'disabled');\n // } else {\n // addButton.removeAttr('disabled');\n // }\n\n showHideAddButton();\n }",
"triggerRemove(value) {\n const selectedOptions = uniq(without(this.state.selected, value));\n this.triggerChange(selectedOptions);\n }",
"function removeServer(btnClicked){\n\tif(btnClicked){\n\t\tserverCountToDelete++;\n\t}\n\tif(totalServerCount == 1){\n\t\t$('.message-text').html('Minimum 1 server required');\n\t\t$('.message-text').removeClass('success-msg');\n\t}\n\telse if(totalServerCount && idleServerArr.length){\n\t\tvar x = idleServerArr[0];\n\t\t$('.task-execution-view .server-task-wrapper'+x+'').remove();\n\t\t$('#addServerBtn').removeAttr('disabled');\n\t\tidleServerArr.shift();\n\t\t$('.message-text').html('Server successfully deleted');\n\t\t$('.message-text').addClass('success-msg');\n\t\ttotalServerCount--;\n\t\tserverCountToDelete--;\n\t}\n\tif(pendingTaskCount && idleServerArr.length){\n\t\tisPendingTaskAv();\n\t}\n}",
"function clickRemoveB() {\n removePrefect(prefectB);\n makePrefect(selectedStudent);\n buildList();\n closeDialog();\n }",
"function OptionPanel(Opc) {\n\n Campo = Opc;\n\n switch (Opc) {\n\n case \"C\":\n $(\"#block_search_GA\").css(\"display\", \"none\");\n $(\"#Block_Insert_GA\").css(\"display\", \"block\");\n $(\"#Bloque_estado\").css(\"display\", \"none\");\n $(\"#BtnSave\").attr(\"value\", \"Crear\");\n $(\"#TxtGrupo_ID\").removeAttr(\"disabled\");\n $(\"#Select_Pais\").parent().find(\"input.ui-autocomplete-input\").autocomplete(\"option\", \"disabled\", false).prop(\"disabled\", false);\n $(\"#Select_Pais\").parent().find(\"a.ui-button\").button(\"enable\");\n $('#Select_Pais').siblings('.ui-combobox').find('.ui-autocomplete-input').val('Seleccione...');\n\n Estado_Process = \"C\";\n $(\"#Tab_GrupoActividad\").tabs({ disabled: false });\n Clear();\n break;\n\n case \"R\":\n $(\"#block_search_GA\").css(\"display\", \"block\");\n $(\"#Block_Insert_GA\").css(\"display\", \"none\");\n Estado_Process = \"R\";\n break;\n\n case \"U\":\n $(\"#block_search_GA\").css(\"display\", \"block\");\n $(\"#Block_Insert_GA\").css(\"display\", \"none\");\n Estado_Process = \"U\";\n break;\n\n case \"D\":\n $(\"#block_search_GA\").css(\"display\", \"block\");\n $(\"#Block_Insert_GA\").css(\"display\", \"none\");\n Estado_Process = \"D\";\n break;\n\n }\n}",
"function getAutoDSelectedPartnerAdd(opt,type){\n var optAdd = \"<option value=''>Select</option>\";\n switch(opt) {\n case \"Select\":\n if(type==\"device\"){\n $('#autoDPartnerInfoTable > tbody').empty();\n $('#autoDPartnerInfoTableCont').hide();\n $('#autoDPartInfo1').hide();\n \t\t$('#newDevPartnerDevModel').empty().append(\"<input id='newDevPartnerDevModelS' type='text' value='' disabled='disabled'/>\");\n\t\t\t\t$('#newDevPartnerDevHost').empty().append(\"<input id='newDevPartnerDevHostS' type='text' value='' disabled='disabled'/>\");\n\t\t\t\t$('#newDevPartnerDevManu').empty().append(\"<input id='newDevPartnerDevManuS' type='text' value='' disabled='disabled'/>\");\n $('#autoDPartInfo2').hide();\n\t\t\t\t$(\"#autoDPartAddOpt > option:contains('Select')\").prop('selected',true);\n $('#autoDOptIncMappChk').hide();\n $('#autoDPartPortsSrchLblCont').hide();\n $('#autoDDevSlotsIncCont').hide();\n $('#autoDDevSlotsIncCountCont').hide()\n\t\t\t\t$('#autoDDevSlotInfoTableCont').hide();\n\t\t\t\t$('#autoDDevSlotInfoTbody').empty();\n\t\t\t\t$('#autoDDevSlotsIncCount').val('');\n\t\t\t\t$('#autoDDevSlotsIncChk').prop('checked',false);\n\t\t\t\t$('#addNewDevAuxIpTR').hide();\n\n }else if(type==\"testtool\"){\n $('#autoDTestTPartnerInfoTable > tbody').empty();\n $('#autoDTestTPartnerInfoTableCont').hide();\n $('#autoDTestTPartInfo1').hide();\n\t\t $('#newTestTPartnerDevHost').empty().append(\"<input id='newTestTPartnerDevHostS' type='text' value='' disabled='disabled'/>\");\n \t \t$('#newTestTPartnerDevManu').empty().append(\"<input id='newTestTPartnerDevManuS' type='text' value='' disabled='disabled'/>\");\n \t \t$('#newTestTPartnerDevModel').empty().append(\"<input id='newTestTPartnerDevModelS' type='text' value='' disabled='disabled'/>\");\n $('#autoDTestTPartInfo2').hide();\n $('#autoDTestTPartAddOpt-button > span').empty().append(\"Select\");\n $('#autoDTestTOptIncMappChk').hide();\n $('#autoDTestTPartPortsSrchLblCont').hide();\n $('#autoDTestTSlotsIncCont').hide();\n $('#autoDTestTSlotsIncCountCont').hide();\n\t\t\t\t$('#autoDTestTSlotInfoTableCont').hide();\n\t\t\t\t$('#autoDTestTSlotInfoTbody').empty();\n\t\t\t\t$('#autoDTestTSlotsIncChk').prop('checked',false);\n\t\t\t\t$('#autoDTestTSlotsIncCount').val(\"\");\n\t\t }\n break;\n case \"Networking Device\":\n var dataS = autoDDevLists[0].NetworkingDevices;\n for(var i=0; i<dataS.length; i++){\n optAdd += dataS[i].opt;\n }\n\t\t break;\n case \"L1 Switch\":\n var dataS = autoDDevLists[0].L1Switch;\n for(var i=0; i<dataS.length; i++){\n optAdd += dataS[i].opt;\n }\n\t\t break;\n case \"L2 Switch\":\n var dataS = autoDDevLists[0].L2Switch;\n for(var i=0; i<dataS.length; i++){\n optAdd += dataS[i].opt;\n }\n\t\t break;\n }\n if(type==\"device\"){$('#autoDPartAddOpt').empty().append(optAdd);}\n if(type==\"testtool\"){$('#autoDTestTPartAddOpt').empty().append(optAdd);}\n\tif(type==\"admin\"){$('#partipadd').empty().append(optAdd);}\n\n}",
"function removeadduser(level){\n\tif(level == \"add\"){\n\t\t$('.usernotexist').each(function(){\n\t\t\tif($(this).is(':checked')){\n\t\t\t\tvar did = $(this).attr('did');\n\t\t\t\tif (checkArray(did,userNotExistArray)){\n\t\t\t\t\tvar indx = userNotExistArray.indexOf(did);\n\t\t\t\t\tuserNotExistArray.splice(indx,1);\n\t\t\t\t}\n\t\t\t\tif (!checkArray(did,userExistArray)){\n\t\t\t\t\tuserExistArray.push(did);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}else{\n\t\t$('.userexist').each(function(){\n\t\t\tif($(this).is(':checked')){\n\t\t\t\tvar did = $(this).attr('did');\n\t\t\t\tif (checkArray(did,userExistArray)){\n\t\t\t\t\tvar indx = userExistArray.indexOf(did);\n\t\t\t\t\tuserExistArray.splice(indx,1);\n\t\t\t\t}\n\t\t\t\tif (!checkArray(did,userNotExistArray)){\n\t\t\t\t\tuserNotExistArray.push(did);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t}\n\tcreatetableforinvitation();\n}",
"function addFormElem(moduleChosen){\n\tclearForm();\n\tvar moduleCode = moduleChosen.split(' ')[0];\n\taddLecture(moduleCode);\n\taddRest(moduleCode);\n\taddButton();\n\tselectize();\n\tprepareInfoDisplay();\n\taddEventForFormElem(moduleCode);\n}",
"function moduleappend_response(req)\n{\n appending = false;\n if (!req.isSuccess()) {\n Zikula.showajaxerror(req.getMessage());\n return;\n }\n var data = req.getData();\n\n // copy new module li from module_1.\n var newmodule = $('module_'+firstmodule).cloneNode(true);\n\n // update the ids. We use the getElementsByTagName function from\n // protoype for this. The 6 tags here cover everything in a single li\n // that has a unique id\n newmodule.id = 'module_' + data.id;\n $A(newmodule.getElementsByTagName('a')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; });\n $A(newmodule.getElementsByTagName('div')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; });\n $A(newmodule.getElementsByTagName('span')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; });\n $A(newmodule.getElementsByTagName('input')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; node.value = ''; });\n $A(newmodule.getElementsByTagName('select')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; });\n $A(newmodule.getElementsByTagName('button')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; });\n $A(newmodule.getElementsByTagName('textarea')).each(function(node){ node.id = node.id.split('_')[0] + '_' + data.id; });\n\n // append new module to the module list\n $('modulelist').appendChild(newmodule);\n\n // set initial values in input, hidden and select\n //$('modname_' + data.id).value = data.modname;\n //$('description_' + data.id).value = data.description;\n //$('members_' + data.id).href = data.membersurl;\n\n// Zikula.setselectoption('modulenavtype_' + data.id, data.navtype_disp);\n// Zikula.setselectoption('moduleenablelang_' + data.id, data.enablelang);\n\n // hide cancel icon for new modules\n// Element.addClassName('moduleeditcancel_' + data.id, 'z-hide');\n // update delete icon to show cancel icon\n// Element.update('moduleeditdelete_' + data.id, canceliconhtml);\n\n // update some innerHTML\n// Element.update('moduleid_' + data.id, data.id);\n// Element.update('modulemodname_' + data.id, data.modname);\n// Element.update('modulenavtype_' + data.id, data.navtype_disp);\n// Element.update('moduleenablelang_' + data.id, data.enablelang);\n //Element.update('members_' + data.id, data.membersurl);\n\n // add events\n Event.observe('modifyajax_' + data.id, 'click', function(){modulemodifyinit(data.id)}, false);\n Event.observe('moduleeditsave_' + data.id, 'click', function(){modulemodify(data.id)}, false);\n Event.observe('moduleeditdelete_' + data.id, 'click', function(){moduledelete(data.id)}, false);\n Event.observe('moduleeditcancel_' + data.id, 'click', function(){modulemodifycancel(data.id)}, false);\n\n // remove class to make edit button visible\n Element.removeClassName('modifyajax_' + data.id, 'z-hide');\n Event.observe('modifyajax_' + data.id, 'click', function(){modulemodifyinit(data.id)}, false);\n\n // turn on edit mode\n allownameedit[data.id] = true;\n enableeditfields(data.id);\n\n // we are ready now, make it visible\n Element.removeClassName('module_' + data.id, 'z-hide');\n new Effect.Highlight('module_' + data.id, { startcolor: '#99ff66', endcolor: '#ffffff' });\n\n\n // set flag: we are adding a new module\n adding[data.id] = 1;\n}",
"function testbedOptionSave(){\n\tif(globalInfoType == \"JSON\"){\n devicesArr = getDevicesNodeJSON();\n deviceArr = getDevicesNodeJSON();\n\t}\n\n $(\"#deviceMenuPopUp\").dialog({\n modal: true,\n width: \"auto\",\n autoResize: true,\n maxHeight: 500,\n open: function(event, ui){\n $(this).parent().css('position', 'fixed');\n },\n\t\topen: function(event, ui) { $(\".ui-dialog-titlebar-close\").show(); }\n });\n $(\"#deviceMenuPopUp\").empty().load(\"pages/ConfigEditor/testbedOption.html\", function(){\n window['variable' + DeviceSanity[pageCanvas] ] = \"true\";\n for(var a=0; a<devicesArr.length; a++){\n if(devicesArr[a].DeviceName == \"\" || devicesArr[a].Status.toLowerCase() != \"\"){\n $(\"#bothTbID\").remove();\n $(\"#staticTbID\").remove();\n tbSelectOption();\n }else{\n $(\"#bothTbID\").remove();\n $(\"#staticTbID\").remove();\n $(\"#fileTypeSelectID\").prepend(\"<option value='both' id='bothTbID'>Both</option> <option value='static' id='staticTbID'>Static</option>\");\n tbSelectOption();\n }\n }\n for(var b=0; b<window['variable' + dynamicLineConnected[pageCanvas]].length; b++){\n if(window['variable' + dynamicLineConnected[pageCanvas]][b].DestinationDeviceObjectPath != \"\" || window['variable' + dynamicLineConnected[pageCanvas]][b].SourceDeviceObjectPath != \"\"){\n $(\"#checkenableint\").attr(\"disabled\", false);\n $(\"#checkconnectivity\").attr(\"disabled\", false);\n $(\"#checklinksanity\").attr(\"disabled\", false);\n $(\"#checkportmapping\").attr(\"disabled\", false);\n $(\"#checktgenconfig\").attr(\"disabled\", false)\n\n }else{\n $(\"#checkenableint\").attr(\"disabled\", true);\n $(\"#checkconnectivity\").attr(\"disabled\", true);\n $(\"#checklinksanity\").attr(\"disabled\", true);\n $(\"#checkportmapping\").attr(\"disabled\", true);\n $(\"#checktgenconfig\").attr(\"disabled\", true)\n }\n }\n/*\t\tif(lineConnected==[] || lineConnected.length==0){\n $(\"#checkenableint\").attr(\"disabled\", true);\n $(\"#checkconnectivity\").attr(\"disabled\", true);\n $(\"#checklinksanity\").attr(\"disabled\", true);\n $(\"#checkportmapping\").attr(\"disabled\", true);\n $(\"#checktgenconfig\").attr(\"disabled\", true)\n }*/\n if(window['variable' + DeviceSanity[pageCanvas] ].toString()==\"true\")$(\"#checkdevsanity\").prop('checked', true);\n if(Commit==\"true\")$(\"#checkcommit\").prop('checked',true);\n\n\n $(\".ui-dialog\").position({\n my: \"center\",\n at: \"center\",\n of: window\n });\n });\n return;\n\n\n}",
"function disable_button() {\n allow_add = false;\n}",
"function screenConfirmed(isConfirmed) { \n document.getElementById(\"selects\").innerHTML = \"\";\n if (isConfirmed === true){\n onAccessApproved(currentScreensharePickID);\n }\n togglePage();\n}",
"function HTL_removeIssues() {\n var selectedLocalIDs = [];\n for (var i = 0; i < issueRefs.length; i++) {\n issueRef = issueRefs[i]['project_name']+':'+issueRefs[i]['id'];\n var checkbox = document.getElementById('cb_' + issueRef);\n if (checkbox && checkbox.checked) {\n selectedLocalIDs.push(issueRef);\n }\n }\n\n if (selectedLocalIDs.length > 0) {\n if (!confirm('Remove all selected issues?')) {\n return;\n }\n var selectedLocalIDString = selectedLocalIDs.join(',');\n $('bulk_remove_local_ids').value = selectedLocalIDString;\n $('bulk_remove_value').value = 'true';\n setCurrentColSpec();\n\n var form = $('bulkremoveissues');\n form.submit();\n } else {\n alert('Please select some issues to remove');\n }\n}",
"function addClicked() {\n addStudent();\n updateData();\n clearAddStudentForm();\n}",
"function strategy_clicked(){\n var slected = $('#TradingStrategiesList').find('.selected'); // Which row was selected?\n if(slected.length===0){ // This means, the user de-selected an option, disabling buttons\n\n $(\"#runStrategy\").attr(\"disabled\",true);\n $(\"#run-str-fnt\").attr(\"class\",\"fas fa-fighter-jet mt-0\")\n \n $(\"#editStrategy\").attr(\"disabled\",true);\n $(\"#edt-str-fnt\").attr(\"class\",\"fas fa-pencil-alt mt-0\")\n \n $(\"#deleteStrategy\").attr(\"disabled\",true);\n $(\"#dlt-str-fnt\").attr(\"class\",\"far fa-trash-alt mt-0\")\n return; // Goes back to main\n }; \n\n // enables buttons, makes them bigger\n $(\"#runStrategy\").attr(\"disabled\",false);\n $(\"#run-str-fnt\").attr(\"class\",\"fas fa-2x fa-fighter-jet mt-0\")\n\n $(\"#editStrategy\").attr(\"disabled\",false);\n $(\"#edt-str-fnt\").attr(\"class\",\"fas fa-2x fa-pencil-alt mt-0\")\n\n $(\"#deleteStrategy\").attr(\"disabled\",false);\n $(\"#dlt-str-fnt\").attr(\"class\",\"far fa-2x fa-trash-alt mt-0\")\n\n // saves name of selected strategy to local storage\n localStorage.setItem(\"selectedStrategy\",slected[0].cells[1].textContent);\n }",
"function clear_control_panel_options() {\n\tvar control_panel_options_buttons = document.querySelectorAll(\".control_panel .options .button\");\n\tvar control_panel_options_buttons_length = control_panel_options_buttons.length;\n\tfor(var i=0; i<control_panel_options_buttons_length; i++) {\n\t\tcontrol_panel_options_buttons[i].parentNode.removeChild(control_panel_options_buttons[i]);\n\t}\n\tpart+=1;\n\tdeactivate_continue_button()\n\tselect_part();\n}",
"function removeFrom() {\n form.style.display = 'none';\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the dimension that is the largest | function largestAxisVec(dimensions) {
var dimensionArray = [];
for (var key in dimensions) {
dimensionArray.push(dimensions[key]);
}
return Math.max.apply(null, dimensionArray);
} | [
"findMax() { \n if(this.isEmpty()) return Number.MIN_VALUE;\n return this.heap[0];\n }",
"_getMaxPointSize() {\n const e = this.encoders.size;\n if (e.constant) {\n return e(null);\n } else {\n return /** @type {number[]} */ (e.scale.range()).reduce((a, b) =>\n Math.max(a, b)\n );\n }\n }",
"static getMaxHeight() { \n var result = Math.max(MainUtil.findAllRooms().map(room => (room.memory.console && room.memory.console.height)));\n return result || 10;\n }",
"get maxHeight() {\n\t\tlet maxHeight = 0, height;\n\n\t\tfor (let i = 0; i < this.count; i++) {\n\t\t\tif (this.cache[i]) {\n\t\t\t\theight = this.cache[i];\n\t\t\t} else {\n\t\t\t\theight = this.traverse(i);\n\t\t\t\t\n\t\t\t\tthis.cache[i] = height;\n\t\t\t\tthis.cache[this.tree[i]] = height - 1;\n\t\t\t}\n\n\t\t\tmaxHeight = Math.max(maxHeight, height);\n\t\t}\n\n\t\treturn maxHeight;\n\t}",
"function find_largest_array(array)\n{\n\tvar index = 0;\n\tfor (var i = 0; i < array.length; i++)\n\t{\n\t\tif (array[i].length > array[0].length)\n\t\t{\n\t\t\tindex = i;\n\t\t}\n\t}\n\treturn index;\n}",
"function largestRectangle(h) {\n\n let stack = [];\n let mx = -1;\n stack.push(0);\n for (let i = 1; i < h.length; i++) {\n let last_index = stack.slice(-1)[0];\n let stack_h = h[last_index];\n let curr_h = h[i];\n if (curr_h > stack_h || stack.length == 0) {\n stack.push(i);\n }\n else {\n let anchor = i;\n while (curr_h <= stack_h && stack.length > 0) {\n last_index = stack.pop();\n let area = stack_h * (anchor - last_index);\n mx = Math.max(area, mx);\n stack_h = h[last_index];\n }\n }\n }\n\n let anchor = h.length;\n let curr_h = h[h.length - 1];\n let stack_h = h[stack.slice(-1)[0]];\n while (curr_h >= stack_h && stack.length > 0) {\n let last_index = stack.pop();\n stack_h = h[last_index];\n let area = stack_h * (anchor - last_index);\n mx = Math.max(area, mx);\n\n }\n\n return mx;\n}",
"findMaxEdgeValue(){\n let heaviestEdgeWeight = 0;\n for (let edge of this.props.edges) {\n if (edge.weight > heaviestEdgeWeight) {\n heaviestEdgeWeight = edge.weight;\n }\n }\n return heaviestEdgeWeight;\n }",
"max() {\n for(let i = this.array.length - 1; i >= 0; i--){\n const bits = this.array[i];\n if (bits) {\n return BitSet.highBit(bits) + i * bitsPerWord;\n }\n }\n return 0;\n }",
"function findMaxArea(heights) {\n //0, 1, \n let max = 0;\n \n for (let i = 0; i <= heights.length; i++){//x=0 \n for (let j = i; j < heights.length; j++){\n let height = height[j] < height[i] ? height[j] :height[i] ;//8 \n \n let width = Math.abs(j - i); //1\n \n \n if (max < height * width){ \n max = height * width;//8\n }\n \n }\n }\n \n return max;\n \n }",
"function findMaximumValue(array) {\n\n}",
"@computed\n get maxDistancePx() {\n return Math.sqrt(\n Math.pow(this.windowDimensions.width / 2, 2) +\n Math.pow(this.windowDimensions.height / 2, 2),\n );\n }",
"function largestNumberOfLanes(segment) {\n var biggest;\n if (segment.listOfFeatures.length != 0) {\n for (var i = 0; i < segment.listOfFeatures.length; i++) {\n if (segment.listOfFeatures[i].type == 'laneAdd') {\n if (segment.listOfFeatures[i].numberOfLane > biggest) {\n biggest = segment.listOfFeatures[i].numberOfLane;\n }\n }\n }\n }\n return biggest;\n}",
"function getMaxWidth(element) {\n var maxWidth = Math.max.apply(null, element.map(function () {\n return jQuery(this).outerWidth(false);\n }).get());\n //console.log(maxWidth);\n return maxWidth;\n }",
"function largestMult(x,y,grid,directions){\n let largest = 0\n directions.forEach((e)=>{\n let localRes = mult(x,y,grid,e[0],e[1])\n // console.log(localRes)\n if (localRes>largest){\n largest = localRes\n }\n })\n return largest\n}",
"function find_dimensions()\n{\n numColsToCut= parseInt(NumberofColumns);\n numRowsToCut= parseInt(NumberofRows);\n \n widthOfOnePiece=Target_width/numColsToCut;\n heightOfOnePiece=Target_height/numRowsToCut; \n}",
"function getLastSize()\n {\n var newSize;\n\n // get last known ui sizes and dimensions or defaults\n if ( typeof lastState.size !== \"undefined\" )\n {\n newSize = {\n uiWidth: lastState.size.uiWidth,\n uiHeight: lastState.size.uiHeight\n }\n }\n\n // if no previous size, use defaults\n else\n {\n newSize = {\n uiWidth: settings.dockableWidth,\n uiHeight: settings.dockableHeight\n }\n }\n\n return newSize;\n }",
"function getBiggest(x, y) {\n if ( x > y) {\n return x;\n } else if ( x < y ) {\n return y;\n } else if ( x === y ) {\n return x;\n } else {\n return NaN;\n }\n}",
"function findMax() {\n var max = dog.data[0].count;\n var winner = dog.data[0];\n for (var i = 0; i < dog.data.length; i++) {\n if (dog.data[i].count > max) {\n max = dog.data[i].count\n winner = dog.data[i]\n }\n }\n return winner;\n }",
"getMaxLevel(capLevelIndex) {\r\n let result = 0,\r\n i,\r\n level,\r\n mWidth = this.mediaWidth,\r\n mHeight = this.mediaHeight,\r\n lWidth = 0,\r\n lHeight = 0;\r\n\r\n for (i = 0; i <= capLevelIndex; i++) {\r\n level = this.levels[i];\r\n if (this.isLevelRestricted(i)) {\r\n break;\r\n }\r\n result = i;\r\n lWidth = level.width;\r\n lHeight = level.height;\r\n if (mWidth <= lWidth || mHeight <= lHeight) {\r\n break;\r\n }\r\n }\r\n return result;\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
the below functions create the different sized grid boards by adding new li DOM elements and then resizing them as a percentage of their container so create the correct grid shape. | function create8X8 () {
for (i=0;i<64;i++){
var newSquare = "<li id="+parseInt(i)+"></li>";
$(".grid").append(newSquare);
}
$tileArray = $("li");
row_length = Math.sqrt($tileArray.length);
$tileArray.css("height", "10%").css("width", "10%");
} | [
"function createGrid() {\n for (let i = 0; i < width * height; i++) {\n const cell = document.createElement('div')\n grid.appendChild(cell)\n cells.push(cell)\n }\n for (let i = 2; i < 22; i++) {\n rowArray.push(cells.slice(i * 10, ((i * 10) + 10)))\n }\n for (let i = 0; i < 20; i++) {\n cells[i].classList.remove('div')\n cells[i].classList.add('top')\n }\n for (let i = 10; i < 20; i++) {\n cells[i].classList.remove('top')\n cells[i].classList.add('topline')\n }\n for (let i = 220; i < 230; i++) {\n cells[i].classList.remove('div')\n cells[i].classList.add('bottom')\n }\n }",
"function makeGrid() {\n for (let i = 0; i < 64; i++) {\n const div = document.createElement('div');\n div.className = 'square';\n state.container.appendChild(div);\n state.squares.push(div);\n }\n}",
"function makeGrid() {\n\tlet cellSize = 0;\n\tif ($(window).width() < $(window).height()) {\n\t\tcellSize = $(window).width()*0.8*(1/(level + 0.5));\n\t} else {\n\t\tcellSize = $(window).height()*0.8*(1/(level + 0.5));\n\t}\n\tmakeRows(cellSize);\n\tfillRows(cellSize);\n}",
"function createGrid() {\n // set CSS properties\n document.documentElement.style.setProperty('--grid_size', gridSize);\n document.documentElement.style\n .setProperty('--font_size_tile_adaptable', `${6 - gridSize/3}vh`);\n\n // get grid HTML element and empty its content from previous grid\n const grid = document.getElementById('grid');\n grid.innerHTML = '';\n\n for (let iRow = 0; iRow < gridSize; iRow += 1) {\n const row = document.createElement('div');\n row.className = 'row';\n\n for (let iCol = 0; iCol < gridSize; iCol += 1) {\n const tile = document.createElement('button');\n tile.disabled = true;\n tile.className = 'tile';\n tile.id = `tileR${iRow}C${iCol}`;\n tile.addEventListener('click', () => newMove([iRow, iCol]));\n row.appendChild(tile);\n }\n\n grid.appendChild(row);\n }\n\n // make 2D array that holds tile objects\n tiles = new Array(gridSize);\n for (let iRow = 0; iRow < gridSize; iRow++) {\n tiles[iRow] = new Array(gridSize);\n }\n}",
"function buildBoard() {\n container.style.gridTemplateColumns = `repeat(${dim}, 1fr)`;\n container.style.gridTemplateRows = `repeat(${dim}, 1fr)`;\n for (let i = 0; i < dim * dim; i++) {\n let n = 0.1;\n let item = document.createElement(\"div\");\n item.classList.add(\"grid-item\");\n item.addEventListener(\"mouseover\", () => {\n if (n <= 1) {\n n += 0.1;\n }\n if (random === true) {\n red = Math.floor(Math.random() * 255) + 1;\n blue = Math.floor(Math.random() * 255) + 1;\n green = Math.floor(Math.random() * 255) + 1;\n } else {\n (red = 0), (green = 0), (blue = 0);\n }\n item.style.backgroundColor = `rgba(${red}, ${green}, ${blue}, ${n})`;\n });\n container.appendChild(item);\n }\n}",
"function newGrid(x) {\n for (var rows = 0; rows < x; rows++) {\n for (var cols = 0; cols < x; cols++) {\n $(\"<div class= 'grid' ></div>\").appendTo(\".scetchpad\");\n }\n }\n}",
"function newGrid (newSize) {\n $('.row').remove();\n createGrid(newSize);\n // $('.column').outerHeight(oldSize*oldPixel/newSize);\n // $('.column').outerWidth(oldSize*oldPixel/newSize);\n}",
"function createBoard() {\n\tfor (let i = 0; i < layout.length; i++ ) {\n\t\n\t\tconst square = document.createElement(\"div\");\n\t\tgrid.appendChild(square);\n\t\tsquares.push(square);\n\t\n\n\t\n\tif (layout[i] === 0 ) {\n\t\tsquares[i].classList.add('pac-dot')\n\t} else if (layout[i] === 1 ) {\n\t\tsquares[i].classList.add('wall')\n\t} else if (layout[i] === 2 ) {\n\t\tsquares[i].classList.add('ghosthome')\n\t} else if (layout[i] === 3 ) {\n\t\tsquares[i].classList.add('power-pellet')\n\t}\n\n\t\t\t}\n} // end of createBoard function",
"function createGrid() {\n for (i = 1; i < 1090; i++) {\n var thisDiv = document.createElement('div');\n thisDiv.id = i;\n thisDiv.className = \"col-1-25\";\n container.appendChild(thisDiv);\n }\n createColumns();\n colourGrid();\n }",
"function createGrid(x) {\n\tfor (var rows=0; rows<x; rows++) {\n\t\tfor (var columns=0; columns<x; columns++) {\n\t\t\t$(\"#container\").append(\"<div class='grid'></div>\");\n\t\t};\n\t};\n\t$(\".grid\").width(960/x);\n\t$(\".grid\").height(960/x);\n}",
"function drawPanels(num) {\r\n\tvar rowCount = 0;\r\n\tvar wrapperWidth = $('#wrapper').css('width');\r\n\tvar panelSize = Math.floor(800/gridCount) + 'px';\r\n\tvar panels = $('#sketchpad');\r\n\r\n\tdo {\r\n\t\tfor ( var i = 0; i < num; i++ ) {\r\n\t\t\tpanels.append('<div class=\"gridPanel\"></div>');\r\n\t\t};\r\n\t\trowCount++;\r\n\t} while (rowCount < num );\r\n\r\n\t$('.gridPanel').css({\"width\": panelSize, \"height\":panelSize});\r\n}",
"function createGrid() {\n\t\t$(\"#grid\").html(\"\");\n\t\tvar x = shuffleArray(boxes);\n\t\tfor (var i = 0; i < x.length; i++) {\n\t\t\tvar box = \"<div id='box\" + i + \"' class='box open'>\" + x[i] + \"</div>\";\n\t\t\t$(\"#grid\").append(box);\n\t\t}\n\t}",
"function createBoxes(num){\n// creates the boxes in html depending on number\n var size = (parseInt(100/num) -.4) + \"%\";\n\n for(var row = 0; row < num; row++){\n for(var col = 0; col < num; col++){\n// creates a box element with an id equal to its row and column in the board array;\n var box = $(\"<div>\",{\n class: \"box\",\n id: row + \"\" + col\n });\n //add backboard to top row\n if(row == 0){\n $(box).addClass(\"backboard backboardBox\");\n }\n //check box dimensions\n box.css({\"width\":size,\"height\":size});\n $(box).appendTo(\".board\");\n }\n }\n}",
"function changeGridSize() {\n value = sizeSlider.value;\n container.innerHTML = \"\";\n makeRows(value, value);\n displayGridSlider.innerHTML = value.toString() + \"x\" + value.toString();\n}",
"function initTiles() {\n let body = document.getElementsByTagName(\"body\")[0];\n const dimension = (1 / GRID_SIZE) * 100;\n for (let i = 1; i <= noTiles; i++) {\n let newTile = document.createElement(\"div\");\n newTile.classList.add(\"tile\");\n newTile.classList.add(\"tile\" + i);\n newTile.setAttribute(\"style\", \"width: \" + dimension + \"%; height: \" + dimension + \"%; top: \" + (Math.trunc((i - 1) / GRID_SIZE) * dimension + \"%\") + \"; left: \" + (((i - 1) % GRID_SIZE) * dimension + \"%;\"));\n body.appendChild(newTile);\n }\n}",
"function drawGrid() {\n for(let i = 0; i < HEIGHT; i++) {\n // create a new raw\n let raw = $('<div class=\"raw\"></div>');\n // fill the raw with squares\n for(let j = 0; j < WIDTH; j++) {\n raw.append('<div class=\"block\"></div>');\n }\n // append the raw to the grid container to create the grid\n $('#grid-container').append(raw);\n } \n console.log('[GRID] drawn');\n addGridListeners();\n }",
"function createGrid(gridSize) {\n // create grid element and set default background color for canvas\n let grid1 = $('<div></div>').addClass('tiles-container');\n grid1.addClass(getGridBackgroundColorClass());\n grid1.hide();\n $('#js-gridContainer').append(grid1);\n /*set css variables for number of rows and columns*/\n document.documentElement.style.setProperty(\"--numRows\", gridSize);\n document.documentElement.style.setProperty(\"--numColumns\", gridSize);\n /*create the grid of tiles*/\n let numTiles = gridSize * gridSize;\n let initialBGColor = getGridBackgroundColor();\n let newTile = $('<div></div>').addClass('tile');\n newTile.data('tilecolor', initialBGColor);\n newTile.data('opacity', '100');\n addColorClass(newTile, initialBGColor);\n addOpacityClass(newTile);\n for (let i = 0; i < numTiles; i++) {\n grid1.append(newTile.clone(true)); /*'true' clones data AND eventHandlers*/\n }\n grid1.fadeIn(1000);\n }",
"function createChessGrid() {\n var color = \"w\";\n for (var j = 0; j < 8; j++) {\n let line = [];\n for (var i = 0; i < 8; i++) {\n var tile = createTile(j * WIDTH + 20, i * HEIGHT + 20, color);\n tile.placedPiece = \"\";\n line.push(tile);\n if (color == \"w\")\n color = \"b\";\n else {\n color = \"w\";\n }\n }\n if (color == \"w\")\n color = \"b\";\n else {\n color = \"w\";\n }\n grid.push(line);\n }\n}",
"function createAbstractGrid(){\n for(var i = 0;i < width; i++){\n BoardMethods.grid.push([]);\n BoardMethods.grid2.push([]);\n\n for(var i2 = 0;i2 < height; i2++){\n BoardMethods.grid[i].push(false);\n BoardMethods.grid2[i].push(false);\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Indicates if the filter is cached (via the cache method). | get isCached() {
return this._cached
} | [
"hasCache(identifier) {\n validation_1.CacheValidation.validateIdentifier(identifier);\n return this._resources.has(identifier);\n }",
"function isCachedMIMEType(mimeType) {\n\t\tswitch (mimeType) {\n\t\t\tcase 'application/pdf':\n\t\t\t\treturn true;}\n\n\t\treturn false;\n\t}",
"isCachedInMemory(keypath) {\n // See if we have it already in the first level of cache\n var found = this.getFromMemory(keypath)\n\n if (found === undefined || found === null || (typeof found == 'object' && found.constructor.name != 'BigNumber')) {\n return false\n }\n return true\n }",
"function isDomainCachable(req, res) {\n var finalUrlHeader = res.getHeader('x-final-url');\n if (finalUrlHeader != null) {\n var finalUrl = url.parse(res.getHeader('x-final-url'));\n\n // is the host in the list of domains we should not cache?\n var dontCacheHosts = require('./dont-cache')\n\n if (dontCacheHosts.indexOf(finalUrl.host) >= 0) {\n // in the list of domains to not cache - so don't cache the response\n return false\n } else {\n return true\n }\n } else {\n // cache by default - we know that if the header is not included then this is a cached response from a previous request\n return true;\n }\n}",
"createCache_() {\n if (this.activeLayer_ && this.layer.getSource() instanceof TileWMS) {\n // hide the active layer and disable any events that would update it\n this.activeLayer_.show = false;\n events.unlistenEach(this.layer, STYLE_KEYS, this.onStyleChange_, this);\n olEvents.unlisten(this.layer, 'change', this.onChange_, this);\n\n // create the cache\n this.updateAnimationCache_();\n\n // update the layer cache when the style changes, or a change event is fired (ie, params/url changed). in the\n // future we may have to clear the cache if something other than the TIME param changes (like user changes to\n // the url) but currently there isn't a way to do that.\n events.listenEach(this.layer, STYLE_KEYS, this.updateAnimationCache_,\n this);\n olEvents.listen(this.layer, 'change', this.updateAnimationCache_, this);\n }\n }",
"isInUse() {\n const { items, filters = {} } = this.props;\n let inUse = false;\n items.forEach(item => {\n if (item.key in filters && Array.isArray(filters[item.key]) && filters[item.key].length) {\n inUse = true;\n this.hasBeenUsed = true;\n }\n });\n return inUse;\n }",
"function cached(fn) {\n\t var cache = new Map();\n\t return function cachedFn() {\n\t var key = arguments.length <= 0 ? undefined : arguments[0];\n\t if (!cache.has(key)) cache.set(key, fn.apply(void 0, arguments));\n\t return cache.get(key);\n\t };\n\t }",
"function getCacheStatuses() {\n\tgetCacheCount();\n\tgetCacheAvailableCount();\n\tgetCacheDownCount();\n\tgetCacheStates();\n}",
"function getCachedImage(path){\n\n\tif(!io.fileExistsSync(path)){\n\t\t// File does not exist so.. doenst really matter\n\t\treturn false;\n\t}else{\n\t\t// Should exist\n\t\treturn true;\n\t}\n}",
"function checkForCache(req, res, next) {\r\n const { country } = req.params;\r\n client.get(country, (err, website) => {\r\n if (err) throw err;\r\n if (website != null) res.send(forwardData(country, website));\r\n else next();\r\n })\r\n}",
"function getRequireCache(req = require) {\n return req.cache;\n}",
"function cacheFn(fn) {\n var cache = {};\n return function(arg) {\n if (cache[arg]) {\n return cache[arg];\n } else {\n cache[arg] = fn(arg);\n return cache[arg];\n }\n };\n}",
"visitCache_or_nocache(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function differentApproach(event) {\n console.log(\"service worker fetching - approach with first checking cache (version is important!!)\")\n\n //check cache and respond form cache\n event.respondWith(\n caches.match(event.request)\n .then(cacheRequest => {\n console.log('response is here');\n return cacheRequest || fetch(event.request);\n })\n )\n}",
"async enforce(...rvals) {\n if (!this.enableCache) {\n return super.enforce(...rvals);\n }\n let key = '';\n const cache = CachedEnforcer.canCache(...rvals);\n if (cache) {\n key = CachedEnforcer.getCacheKey(...rvals);\n const res = this.getCache(key);\n if (res !== undefined) {\n return res;\n }\n }\n const res = await super.enforce(...rvals);\n if (cache) {\n this.setCache(key, res);\n }\n return res;\n }",
"infoResponseIsInStore() {\n const responses = this.currentInfoResponses();\n if (responses.length === this.imageServiceIds().length) {\n return true;\n }\n return false;\n }",
"function byCache(key, fn) {\n\n\t// the timestamp key\n\tvar timestamp_key = key + '.timestamp';\n\n\t// get by the key\n\tchrome.storage.local.get([ key, timestamp_key ], function(result) {\n\n\t\t// did we find anything\n\t\tif(result) {\n\n\t\t\t// current time\n\t\t\tvar current_timestamp = new Date().getTime();\n\n\t\t\t// check the timestamp\n\t\t\tif( result[timestamp_key] &&\n\t\t\t\t( current_timestamp - result[timestamp_key] ) <= 1000 * 60 * CONSTANTS.CACHE ) {\n\n\t\t\t\t// output our item ..\n\t\t\t\tfn( JSON.parse(result[key]) )\n\n\t\t\t} else {\n\n\t\t\t\t// remove it\n\t\t\t\tchrome.storage.local.remove([ key, timestamp_key ], function() {\n\n\t\t\t\t\t// signal done and that nothing was found from cache ...\n\t\t\t\t\tfn(null);\n\n\t\t\t\t});\n\n\t\t\t}\n\n\t\t} else fn(null);\n\n\t});\n\n}",
"checkForCachedResponse(request, cacheDuration, freshDataGetter) {\n\t\tconst key = 'service.league.request:' + JSON.stringify(request)\n\n\t\treturn this.core.cache.remember(key, cacheDuration, () => {\n\t\t\tdebug('cache miss', key)\n\n\t\t\treturn freshDataGetter()\n\t\t}).then(response => {\n\t\t\t// Make a copy of response to avoid mucking with cache with mutations (esp. memory based ones)\n\t\t\treturn _.cloneDeep(response)\n\t\t})\n\t}",
"function hasActionChanged() {\r\n\r\n return( action !== previousAction );\r\n\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loops an array replacing one char w/ another | function charReplacer(array, oldChar, newChar) {
for (let i = 0; i < array.length; i++) {
array[i] = array[i].replace(oldChar, newChar);
};
} | [
"function censorString(str, arr, char) {\n\treturn str.split(\" \").map(x => x.replace(new RegExp(arr.join('|'), 'g'), char.repeat(x.length))).join(\" \");\n}",
"function replaceArray(original, replacement, av)\n {\n\tfor (var i = 0; i < original.size(); i++)\n\t{\n\t\toriginal.value(i, replacement.value(i));\n\t\tif (replacement.isHighlight(i))\n\t\t{\n\t\t\toriginal.highlight(i);\n\t\t} else {\n\t\t\toriginal.unhighlight(i);\n\t\t}\n\t}\n }",
"function SearchAndReplace(arr,oldWord,newWord) {\n var t = '';\n var text = arr.split(' ');\n for (let i = 0; i < text.length; i++) {\n if (text[i] == oldWord) {\n t = text[i].charAt(0);\n if (t == text[i].charAt(0).toUpperCase()) {\n t = newWord.charAt(0).toUpperCase()\n t += newWord.slice(1)\n }else{\n t = newWord.charAt(0).toLowerCase()\n t += newWord.slice(1)\n }\n text[i] = t\n }\n }\n return text.join(' ')\n}",
"function encrpytIt(encodeString, codeArray) {\n var a = encodeString.replace(/[^A-Za-z ]/g, '');\n a = a.toLowerCase();\n var tilt = Array.from(a);\n var newArray = [];\n var i = 0;\n var x = 0;\n while (i < tilt.length) {\n if (tilt[i] == codeArray[x][0]) {\n newArray.push(codeArray[x][1]);\n x = 0;\n i++;\n } else if (tilt[i] != codeArray[x][0]) {\n x++;\n }\n \n } \n var newString = newArray.join('');\n return newString;\n}",
"flip(input){\n // Set a temp string\n let output = \"\";\n // Look at each character in the string\n for(let i = 0; i < input.length; i++) {\n // If character is a \"A\", change it to a \"Z\" and save in a new string\n if (input[i] === \"A\") {\n output += \"Z\";\n // If charachter is a \"Z\", change it to an \"A\" and save in new string\n } else {\n output += \"A\";\n }\n }\n // Output the new string\n return output;\n }",
"function shoutGreetings(array) {\nreturn array.map(elem => \n elem.toUpperCase() + `!`\n)\n}",
"function weave(strings) {\n let phrase = ('coding iz hard')\n let string = phrase.split('')\n let nth = 4;\n let replace = 'x';\n for (i = nth - 1; i < string.length; i += nth) {\n string[i] = replace;\n }\n return string.join('');\n}",
"function replace(arr, target, source) {\n\t return arr.map(function (v) {\n\t return v === target ? source : v;\n\t });\n\t}",
"buildReplacement(character, length) {\n let replacement = '';\n for (let i = 0; i < length; i++) {\n replacement += character;\n }\n return replacement;\n }",
"function new_array(curr_array, full_word, new_char) {\n\tlet pre_add_row = curr_array[0].length - 1;\n\tcurr_array[0].push(pre_add_row + 1);\n\tfor (let x = 1; x < full_word.length + 1; x++)\n\t\tcurr_array[x].push((full_word[x - 1] == new_char ? 0 : 1) + min([curr_array[x - 1][pre_add_row], curr_array[x][pre_add_row],\n\t\t\tcurr_array[x - 1][pre_add_row + 1], (curr_array[x - 2] && curr_array[x - 2][pre_add_row - 1]) ? curr_array[x - 2][pre_add_row - 1] : 100000]));\n\n\treturn curr_array;\n}",
"function jumbleWord(wordArr, mapArray) {\n var textArr = [];\n for (var i in wordArr) {\n textArr[i] = wordArr[mapArray[i]];\n }\n return textArr;\n}",
"function replaceAt(str, index, char) {\n var arr = str.split(\"\");\n arr[index] = char;\n return arr.join(\"\");\n}",
"function replaceN() {\n numbers[numbers.indexOf(12)] = 1221;\n numbers[numbers.indexOf(18)] = 1881;\n}",
"complementStrand() {\n let complementArray = []\n let counter = 0\n for(let i=0; i < this.dna.length; i++) {\n if (this.dna[i] === 'A') {\n complementArray[i] = 'T';\n } else if (this.dna[i] === 'T') {\n complementArray[i] = 'A';\n } else if (this.dna[i] === 'C') {\n complementArray[i] = 'G';\n } else {\n complementArray[i] = 'C';\n }\n }\n return complementArray;\n }",
"function makeHappy(arr){\n let result = arr.map(word => \"Happy \" + word)\n return result\n}",
"function initPlayerWord() {\n for (var i = 0; i < currentWord.length; i++) {\n if (currentWord[i] == ' ')\n playerWord[i] = \"-\";\n else {\n playerWord[i] = \" _ \";\n lettersLeft++;\n }\n }\n}",
"function swap(text) {\n let words = [];\n text.split(\" \").forEach(word => words.push(switchLetters(word)));\n console.log(words.join(\" \"));\n}",
"function modifyStrings(strings, modify) {\n // YOUR CODE BELOW HERE //\n // I = array of strings and modify function\n // O = modified array\n // init empty array as modArray\n // use for loop to loop through entire array of strings\n // push strings into modArray array and into modify function\n var modArray = [ ];\n for (var i = 0; i < strings.length; i++) {\n modArray.push(modify(strings[i]));\n } \n \n return modArray;\n\n \n \n // YOUR CODE ABOVE HERE //\n}",
"regexAll (text, array) {\n for (const i in array) {\n let regex = array[i][0]\n const flags = (typeof regex === 'string') ? 'g' : undefined\n regex = new RegExp (regex, flags)\n text = text.replace (regex, array[i][1])\n }\n return text\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
react to sensor update | on_sensor_update(sensor){
// sensor.pitch
// sensor.roll
} | [
"notify_speed_update() {\n this.speed_update = true;\n }",
"update_drone_stats(){\n this.update_location(new_location);\n this.update_sensor();\n this.update_battery(); // send drone info to remote maybe\n }",
"function onStartSensor(sensor){\n\t\tconsole.log(\"Sensor\" + sensor + \"start\");\n\t}",
"function updateRobotStatus (updatedData) {\n updatedData['Time'] = new Date();\n updatedData['Arduino Attached'] = serverStatus.hasArduino;\n\n socket.broadcast.emit('robot status', { 'data': updatedData });\n}",
"update() {\n for (let device of this.devices) {\n device.update();\n }\n }",
"_emitServiceStreamDataUpdateEvent ( dataUpdate ) {\n\n super.emit(\n EMITABLE_EVENTS.serviceStreamDataUpdate\n , dataUpdate\n );\n }",
"function update() {\n // populate the analyser buffer with frequency bytes\n analyser.getByteFrequencyData(buffer);\n // look for trigger signal\n for (var i = 0; i < analyser.frequencyBinCount; i++) {\n var percent = buffer[i] / 256;\n // TODO very basic / naive implementation where we only look\n // for one bar with amplitude > threshold\n // proper way will be to find the fundamental frequence of the square wave\n if (percent > config.threshold) {\n events.dispatch('signal');\n return;\n }\n }\n}",
"function update() {\n\tvar out;\n\n\tconfig.motors.forEach(function (motor) {\n\t\t// update motor.gpio with value from rawMotorValues[motor.key]\n\t\t// todo: constrain motor output values to range in configuration\n\t\t//out = ((rawMotorValues[motor.position.key] || 1000) - 1000) / 1000;\n\t\t//out = (out < 0 ? 0 : (out > 1 ? 1 : out)); \n\t\t// rawMotorValues[motor.position.key] is within config.conroller.ranges.throttle\n\t\t//var constrainedValue = ((rawMotorValues[motor.position.key] ||\n\t\t// config.controller.ranges.throttle.min) / config.controller.ranges.throttle.max);\n\t\t//constrainedValue = (constrainedValue > 1 ? 1 : constrainedValue);\n\t\t//console.log(constrainedValue);\n\t\t//b.analogWrite(motor.gpio, constrainedValue, 500, function (er) {});\n\t\t//console.log('setting ' + motor.gpio + ' to '+ rawMotorValues[motor.position.key]);\n\t\tpru.setSharedRAMInt(motor.gpio, rawMotorValues[motor.position.key]);\n\t});\n}",
"update() {\n var text = this.buildText(os.uptime());\n\n //update output\n this.output.full_text = text;\n this.output.short_text = text;\n\n //emit updated event to i3Status\n this.emit('updated', this, this.output);\n }",
"boardUpdate() {\n io.emit('boardUpdate', {\n board: this._gameBoard.sendableBoard(),\n yellow: this._yellowScore,\n green: this._greenScore\n })\n }",
"loop () {\n if (!this.shouldLoop) {\n return\n }\n\n window.requestAnimationFrame(this.loop.bind(this))\n\n // When not clicking the orientation values can be rounded more, so that\n // less messages are sent.\n const rounding = this.isClicking ? 100 : 25\n const orientation = this.gyroscope.getOrientation(rounding)\n\n this.gyroplane.updateOrientation(orientation)\n\n try {\n const coordinates = this.gyroplane.getScreenCoordinates()\n this.lazy.update(coordinates)\n } catch (e) {\n this.gyroplane.init()\n }\n\n // Get the lazy coordinates.\n const { x, y } = this.lazy.getBrushCoordinates()\n\n // Set the new values to the array.\n this.intArray.set([\n Math.round(x),\n Math.round(y),\n this.isClicking ? 1 : 0,\n Math.round(this.touch.y)\n ], 0)\n\n // Only send the data if it actually has changed.\n if (\n this.prevArray[0] !== this.intArray[0] ||\n this.prevArray[1] !== this.intArray[1] ||\n this.prevArray[2] !== this.intArray[2] ||\n this.prevArray[3] !== this.intArray[3]\n ) {\n this._onDataChange(this.buffer)\n this.prevArray.set(this.intArray, 0)\n }\n }",
"function stateSampler() {\n // Determine if the user is active\n const timestamp = Date.now();\n const timeElapsed = timestamp - state.lastTimestamp;\n state.userActive = timeElapsed < config.userActiveTimeout;\n\n // Create message for transmission to server\n const packet = {\n source: 'client',\n type: 'periodic-event',\n id,\n state,\n startTime,\n };\n\n // Send to server\n if (socketOpen) {\n socket.send(JSON.stringify(packet));\n }\n\n // Update the UI\n update();\n}",
"updateSampleDataArray () {\n\n // Update the state with the new array.\n this.setState({\n sampleFrequencyDataArray: this.updateSampleFrequencyDataArray(),\n sampleTimeDataArray: this.updateSampleTimeDataArray(),\n });\n\n // Recurse when available.\n requestAnimationFrame(() => this.updateSampleDataArray());\n\n }",
"function refresh() {\n $.get(\"/api?drone_uid=\" + droneUID + \"&subset=state\")\n .done(function(result) {\n // Available: result.command, result.voltage, result.status, result.error\n $(\"#current-command\").text(result.command);\n var status = result.status;\n if (status == \"disarmed\") {\n switchOff(\"#arm-switch\");\n switchOff(\"#motor-switch\");\n } else if (status == \"armed\") {\n switchOn(\"#arm-switch\");\n switchOff(\"#motor-switch\");\n } else if (status == \"throttled\") {\n switchOn(\"#arm-switch\");\n enableSwitch(\"#motor-switch\");\n switchOn(\"#motor-switch\");\n }\n });\n}",
"function update_navigator_data() {\n getNavigators().then(devices => {\n var temperature = devices[0].RoomAnalytics.AmbientTemperature;\n var humidity = devices[0].RoomAnalytics.RelativeHumidity;\n console.log(temperature, humidity);\n xapi.Command.UserInterface.Extensions.Widget.SetValue({\n Value: temperature + \" °C\",\n WidgetId: 'widget_actual_temp'\n });\n xapi.Command.UserInterface.Extensions.Widget.SetValue({\n Value: humidity + \" %\",\n WidgetId: 'widget_actual_humidity'\n });\n });\n}",
"_registerUpdates() {\n const update = this.updateCachedBalances.bind(this);\n this.accountTracker.store.subscribe(update);\n }",
"updateValue() {\n [...this.template.querySelectorAll('lightning-input')].forEach(\n (element) => {\n element.value = this._value;\n }\n );\n\n this._updateProxyInputAttributes('value');\n\n /**\n * @event\n * @name change\n * @description The event fired when the value changes.\n * @param {number} value\n */\n this.dispatchEvent(\n new CustomEvent('change', {\n detail: {\n value: this._value\n }\n })\n );\n this.showHelpMessageIfInvalid();\n }",
"watch() {\n if (this.shouldUpdate()) {\n this.trigger('change', this.rect);\n }\n\n if(!this.shouldStop){\n window.requestAnimationFrame(() => this.watch());\n }\n }",
"function emitUpdatedUnits()\n\t{\n\t\tboardgameserver.liveSockets[boardgameserver.p1].emit('update', {'units': units});\n\t\tboardgameserver.liveSockets[boardgameserver.p2].emit('update', {'units': units});\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds the tree navigation content | function buildTreeNavigation() {
var html = '';
html += '<div class="tree_roles">';
for (var i = 0; i < roles.length; i++) {
var role = roles[i];
html += '<div class="tree_role">';
html += '<a href="' + i + '" class="tree_role_link"><img src="' + role.headshot + '" class="tree_role_img"/></a>';
html += ' <a href="' + i + '" class="tree_role_link tree_link_text">' + role.shortTitle + '</a>';
html += '</div>';
html += '<div class="tree_lessons">';
for (var j = 0; j < role.lessons.length; j++) {
var lesson = role.lessons[j];
html += '<div class="tree_lesson">';
html += '<a href="' + j + '" class="tree_lesson_link"><img src="' + lesson.icon + '" class="tree_lesson_img"/></a>';
html += ' <a href="' + j + '" class="tree_lesson_link tree_link_text">' + lesson.title + '</a>';
html += '</div>';
}
html += '</div>';
}
html += '</div>';
$('#tree').html(html);
$('#tree a.tree_role_link').bind('click', function(event) {
event.preventDefault();
showLessons(getRole($(this).attr('href')));
});
$('#tree a.tree_lesson_link').bind('click', function(event) {
event.preventDefault();
showLesson(getLesson(
$(this).parent().parent().prevAll('.tree_role:first').children('a.tree_role_link').attr('href'),
$(this).attr('href')
));
});
} | [
"function buildNav() {\n for (section of sections) {\n target = section.id;\n sectionTitle = section.dataset.nav;\n createMenuItem(target, sectionTitle);\n }\n}",
"function build_child_links(data) {\n // FIXME this code is disgusting, rewrite it\n var nav = $.map(data, function(item, i){\n // data will contain all pages in the site. Child links should contain\n // all children nodes of the current node. That is, all nodes of the\n // form:\n // (blah)/something/index.html\n // where window.location.pathname is of the form\n // (blah)/ or\n // (blah)/index.html\n \n // Skip the dummy object marking the end of the array\n if (!item.title) return;\n\n // Throw out anything that's not this directory or sub/index.html\n var current = window.location.pathname;\n var path = site_root + item.path.substr(1);\n if (current.substr(-10) == \"index.html\") {\n current = current.slice(0,-10);\n }\n \n if (path.substr(0,current.length) != current) return;\n if (path.substr(current.length).split('/').length != 2) return;\n\n // Build up the HTML for the object.\n return (\n \"<li><a href=\\'\"+\n path +\n \"\\'>\" +\n (item.short_title || item.title) +\n \"</a></li>\");\n\n }).join(\"\");\n nav = $(\"<ul>\" + nav + \"</ul>\");\n $(document).ready(function(){\n var target = $('h2:contains(Child pages)');\n if (!target.length) return;\n target.after(nav);\n });\n}",
"build() {\n\t\tconst self = this;\n\n\t\tself.buildTags();\n\t\tself.buildTree();\n\t}",
"function build_header_nav(data) {\n // FIXME this code is disgusting, rewrite it\n var nav = $.map(data, function(item, i){\n // data will contain all pages in the site. Toplevel nav header should\n // contain all children nodes of the root node. That is, all nodes of\n // the form:\n // (root)/something/index.html\n // but not\n // (root)/index.html\n \n // Skip the dummy object marking the end of the array\n if (!item.title) return;\n\n // Throw out anything that's not sub/index.html\n var path = item.path.substr(1).split('/');\n if (path.length > 2) return;\n if (path.length == 2 && path[1] != \"index.html\") return;\n if (path.length < 1) return;\n if (path[0] == \"index.html\") return;\n\n var target = site_root + path.join('/');\n // If the current item is the page we're on, set a class so it can\n // be displayed differently.\n var current = '';\n if (window.location.pathname == target ||\n (window.location.pathname.substr(-1) == '/' && \n window.location.pathname + \"index.html\" == target)) {\n current = 'active'; \n }\n\n // Build up the HTML for the object.\n return (\n \"<li class='\" +\n current +\n \"'><a href=\\'\"+\n target +\n \"\\'>\" +\n (item.short_title || item.title) +\n \"</a></li>\");\n\n }).join(\"\");\n nav = $(nav)\n $(document).ready(function(){\n $('ul.nav').append(nav);\n });\n}",
"buildTree() {\n this.clear();\n\n const columnsCount = this.#sourceSettings.getColumnsCount();\n let columnIndex = 0;\n\n while (columnIndex < columnsCount) {\n const columnSettings = this.#sourceSettings.getHeaderSettings(0, columnIndex);\n const rootNode = new TreeNode();\n\n this.#rootNodes.set(columnIndex, rootNode);\n this.buildLeaves(rootNode, columnIndex, 0, columnSettings.origColspan);\n\n columnIndex += columnSettings.origColspan;\n }\n\n this.rebuildTreeIndex();\n }",
"function buildUlTree(tree)\n{\n\tvar unordered_list = '';\n\tfor (node in tree)\n\t{\n\t\tnode = tree[node];\n\t\t\n\t\tunordered_list += '<ul style=\"margin-bottom: 0\">';\n\t\tunordered_list += println(node['title']);\n\t\tif(node['children'])\n\t\t{\n\t\t\tunordered_list += buildUlTree(node['children']);\n\t\t}\n\t\tunordered_list += '</ul>';\n\t}\n\treturn unordered_list;\n}",
"function populateNavigation(clicky, parent, list, counter, parent_id) {\n // Each nav list is givin a unique id\n // Each Child has the class of their parnets id\n \n var nav_id = 'nav_menu_' + counter++;\n\n // Add nav list to parent\n $(parent).prepend(\"<nav id='\" + nav_id + \"' class='\" + parent_id + \" b_white c_dark' >\");\n\n // Create new nav item list to the new nav list \n $('#' + nav_id).append(\"<ul class='font_med ulNavigation '>\");\n\n // Create on click listener for the navigation item\n $(clicky).on('click', function() {\n \n // If its submenue is not open, open it, and close its neighbors\n if ($('#' + nav_id)[0].classList.contains('navigation_list--active') == false) {\n // Get neighbours, and close them\n \n //console.log( '.' + parent_id.replace(' ','.') );\n var paren_class_list = parent_id;\n paren_class_list ='.' + paren_class_list.replace(' ','.')\n //console.log( paren_class_list);\n \n $(paren_class_list ).each(function(index) {\n this.classList.remove('navigation_list--active');\n });\n //$('#' + nav_id).parent().add('navigation_list--active');\n $('#' + nav_id)[0].classList. add('navigation_list--active');\n \n \n\n }\n else {\n // If the submenye is open, close it and its children\n $('#' + nav_id)[0].classList.remove('navigation_list--active');\n \n $('.' + nav_id).parent().children().each(function(index) {\n this.classList.remove('navigation_list--active');\n });\n\n }\n });\n\n // Submenue generation\n for (var x in list) {\n $('#' + nav_id + ' ul').append(\"<li class='navigation_item '><a href='\" + list[x].link + \"' class='navigation_link fa \" + list[x].icon + \" c_dark'> <h5 class='font_small font_tight'>\" + list[x].name + \"</h5></a></li>\");\n\n if (list[x].submenu.length > 0) {\n //console.log($('#' + nav_id + ' ul li a').last()[0]);\n populateNavigation($('#' + nav_id + ' ul li a').last()[0], parent , list[x].submenu, (counter++) * 100, parent_id + ' ' + nav_id);\n }\n\n }\n\n }",
"function MgnlNavigation (id, title, action, icon, parent, depth) {\r\n // holds all top-level navigation nodes\r\n var nodes = new Array ();\r\n // holds all open nodes, i.e. where the children are shown\r\n var openNodes = new Array ();\r\n // holds all nodes where mouse is moved over\r\n var hoverNodes = new Array ();\r\n // holds the currently selected/clicked node\r\n var activeNode = null;\r\n // background: the table-element in the dom-tree, this holds the background color/image that reacts on mouse-events\r\n var background = null;\r\n // whether the menu is opened or not, i.e. children visible or hidden.\r\n var isOpen = false;\r\n\r\n // obvious getters and setters\r\n this.getDepth = function () {\r\n if (depth) return depth;\r\n else return 0;\r\n }\r\n this.getId = function () { return id; }\r\n this.getTitle = function () { return title; }\r\n this.getIcon = function () { return icon; }\r\n this.hasIcon = function () { return (icon ? true : false); }\r\n this.getParent = function () { return parent; }\r\n\r\n /**\r\n * adds a navigation node\r\n * Parameters:\r\n * id: the nodes id (must be unique!)\r\n * title: the txt to display\r\n * action: javascript function as string\r\n * icon: path to the icon shown on the left\r\n */\r\n this.addNode = function (id, title, action, icon) {\r\n // only add node if there is no such id yet\r\n if (!this.getNavigation ().getNode (id)) nodes[nodes.length] = new MgnlNavigation (id, title, action, icon, this, this.getDepth () + 1);\r\n }\r\n this.hasNodes = function () { return (nodes.length > 0); }\r\n this.getNodes = function () { return nodes; }\r\n this.getNode = function (id) {\r\n var n = this.getNodes ();\r\n if (this.getId () == id) return this;\r\n for (var i = 0; i < n.length; i++) {\r\n var ret = n[i].getNode (id);\r\n if (ret) return ret;\r\n }\r\n return null;\r\n }\r\n\r\n // open the menu tree\r\n this.showChildren = function () {\r\n // nothing to do on top-level\r\n if (this.getDepth () > 0) {\r\n this.closeOpenNodes (this);\r\n if (!isOpen) {\r\n if (this.hasNodes ()) {\r\n // hide all children\r\n // and set show timeout for animation\r\n if (MgnlNavigation.navTimeoutOpen && 1 * MgnlNavigation.navTimeoutOpen > 0) {\r\n if (c = this.background.parentNode.nextSibling.firstChild) {\r\n var n = this.getNodes ();\r\n var i = 0;\r\n do {\r\n c.style.display = 'none';\r\n window.setTimeout ('document.mgnlNavigationSelf.showChild (\\'' + n[i++].getId () + '\\')', i * MgnlNavigation.navTimeoutOpen);\r\n } while (c = c.nextSibling);\r\n }\r\n }\r\n // display wrapper\r\n this.background.parentNode.nextSibling.style.display = 'block';\r\n }\r\n this.addOpenNode (this);\r\n isOpen = true;\r\n }\r\n }\r\n }\r\n\r\n // close the menu tree\r\n this.hideChildren = function () {\r\n // nothing to do on top-level\r\n if (this.getDepth () > 0) {\r\n if (isOpen) {\r\n if (MgnlNavigation.navTimeoutClose && 1 * MgnlNavigation.navTimeoutClose > 0) {\r\n var n = this.getNodes ();\r\n for (var i = 0; i < n.length; i++) {\r\n // pretty animation...\r\n window.setTimeout ('document.mgnlNavigationSelf.hideChild (\\'' + n[i].getId () + '\\')', (i + 1) * MgnlNavigation.navTimeoutClose);\r\n }\r\n }\r\n // display wrapper\r\n else this.background.parentNode.nextSibling.style.display = 'none';\r\n }\r\n isOpen = false;\r\n }\r\n }\r\n\r\n // open/close menus\r\n // these two functions are used in animation, they get called asynchronously\r\n this.showChild = function (idShow) {\r\n if (n = this.getNode (idShow)) n.background.parentNode.parentNode.style.display = 'block';\r\n }\r\n this.hideChild = function (idHide) {\r\n if (n = this.getNode (idHide)) {\r\n n.background.parentNode.parentNode.style.display = 'none';\r\n // if this is the last child hide the wrapper too\r\n if (!n.background.parentNode.parentNode.nextSibling) {\r\n n.background.parentNode.parentNode.parentNode.style.display = 'none';\r\n }\r\n }\r\n }\r\n\r\n // changes the css-styles of the node\r\n this.setStyle = function (style) {\r\n // nothing to do on top-level\r\n if (style.length > 0) {\r\n style = style.charAt (0).toUpperCase () + style.substring (1, style.length);\r\n if (this.getDepth () > 0) {\r\n // apply styles\r\n if (this.background) this.background.className = 'mgnlNavigation' + this.getDepth () + style;\r\n \r\n if (this.hasNodes ()) {\r\n var n = this.getNodes ();\r\n if (n[0].background) n[0].background.parentNode.parentNode.parentNode.className = 'mgnlNavigationWrapper' + (this.getDepth () + 1) + style;\r\n }\r\n }\r\n }\r\n }\r\n\r\n // returns the navigationobject itself\r\n this.getNavigation = function () {\r\n // only do it on top-level-parent\r\n if (parent) return parent.getNavigation ();\r\n else return this;\r\n }\r\n\r\n // adds the node to the hoverNodes array\r\n this.addHoverNode = function (n) {\r\n // only do it on top-level-parent\r\n if (parent) parent.addHoverNode (n);\r\n else {\r\n var exists = false\r\n for (var i = 0; i < hoverNodes.length; i++) if (hoverNodes[i] == n) exists = true;\r\n if (!exists) hoverNodes.push (n);\r\n }\r\n }\r\n\r\n // used to reset the hover css style\r\n // loops through the hoverNodes array and calls mouseout if it's not the active node\r\n this.removeHoverNodes = function () {\r\n // only do it on top-level-parent\r\n if (parent) parent.removeHoverNodes ();\r\n else {\r\n for (var i = 0; i < hoverNodes.length; i++) {\r\n if (this.getActiveNode () == null || this.activeNode != hoverNodes[i]) {\r\n hoverNodes[i].mouseOut ();\r\n hoverNodes.splice (i, 1);\r\n }\r\n }\r\n }\r\n }\r\n\r\n // adds a node to the openNodes array\r\n this.addOpenNode = function (n) {\r\n // only do it on top-level-parent\r\n if (parent) parent.addOpenNode (n);\r\n else {\r\n var exists = false\r\n for (var i = 0; i < openNodes.length; i++) if (openNodes[i] == n) exists = true;\r\n if (!exists) openNodes.push (n);\r\n }\r\n }\r\n\r\n // loops through the openNodes array and closes all nodes with greater depth expect for the given one\r\n this.closeOpenNodes = function (n) {\r\n // only do it on top-level-parent\r\n if (parent) parent.closeOpenNodes (n);\r\n else {\r\n for (var i = 0; i < openNodes.length; i++) {\r\n // close them if they are less deep or a child\r\n if (openNodes[i].getDepth () >= n.getDepth () || n.getNode (openNodes[i].getId ())) {\r\n // only close it if it's NOT a parent of the active node\r\n if (openNodes[i].getNode (n.getId ()) == null) {\r\n openNodes[i].hideChildren ();\r\n openNodes.splice (i);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n // the node that was clicked\r\n this.setActiveNode = function (n) {\r\n // only do it on top-level-parent\r\n if (parent) parent.setActiveNode (n);\r\n else this.activeNode = n;\r\n }\r\n this.getActiveNode = function () {\r\n // only do it on top-level-parent\r\n if (parent) return parent.activeNode;\r\n else return this.activeNode;\r\n }\r\n\r\n // set active style and show children\r\n // if it get's called with id set it's an external call\r\n // and we need to make sure the parents are open!\r\n this.activate = function (idActivate, execute) {\r\n if (idActivate) {\r\n var n = this.getNode (idActivate);\r\n if (n) {\r\n var p = n.getParent ();\r\n while (p && p.getDepth () > 0) {\r\n if (!p.isOpen) p.showChildren ();\r\n p = p.parent;\r\n }\r\n }\r\n this.addHoverNode (n);\r\n n.activate ();\r\n if (execute) n.execute ();\r\n }\r\n if (this.getDepth () > 0) {\r\n this.setActiveNode (this);\r\n this.removeHoverNodes ();\r\n if (!isOpen) this.showChildren ();\r\n this.setStyle ('active');\r\n }\r\n }\r\n\r\n // call the action that was given to the constructor\r\n this.execute = function () {\r\n if (action.length > 0) {\r\n var f = new Function ('a ', action + '');\r\n f ();\r\n }\r\n }\r\n \r\n this.mouseOver = function (idOver) {\r\n if (n = this.getNode (idOver)) {\r\n if (this.getActiveNode () == null || this.getActiveNode () != n) {\r\n this.addHoverNode (n);\r\n n.setStyle ('hover');\r\n }\r\n }\r\n }\r\n \r\n this.mouseOut = function (idOut) {\r\n if (idOut && this.getDepth () == 0) this.removeHoverNodes ();\r\n else {\r\n if (this.getActiveNode () == null || this.getActiveNode () != this) {\r\n this.setStyle ('inactive');\r\n }\r\n }\r\n }\r\n \r\n this.mouseClick = function (idClick) {\r\n var n = this.getNode (idClick);\r\n if (n) {\r\n n.activate ();\r\n n.execute ();\r\n }\r\n }\r\n}",
"function createNavigation() {\n \n // If a mobile device is detected, remove initial navigation list\n if (!isMobileDevice) {\n navigation.children(TAG_UL).html(CHAR_EMPTY);\n }\n \n // Iterate all available commands\n $.each(commands, function(key, value) {\n \n // Add command to mobile navigation\n navigation.children(TAG_UL).append(\n htmlTag(\n TAG_LI,\n htmlTag(\n TAG_I,\n htmlTag(\n TAG_SPAN,\n value[0]\n )\n )\n )\n );\n });\n }",
"function createWebsiteTree() {\n let finalListUI = '';\n websiteList.reverse().forEach(website => {\n if(website.url.length > 40)\n website.displayURL = website.url.substring(0, 40) + \"....\";\n else\n website.displayURL = website.url;\n const listItem = `\n <div class=\"list__item\">\n <h3>${website.displayURL}</h3>\n <svg id=\"${hashCode(website.url)}\" width=\"14\" height=\"18\" viewBox=\"0 0 14 18\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M1 16C1 17.1 1.9 18 3 18H11C12.1 18 13 17.1 13 16V4H1V16ZM3 6H11V16H3V6ZM10.5 1L9.5 0H4.5L3.5 1H0V3H14V1H10.5Z\" fill=\"#C18888\"/>\n </svg>\n </div>`;\n finalListUI += listItem\n });\n websiteListUI.innerHTML = finalListUI;\n websiteList.forEach(website => {\n getElement('#' + hashCode(website.url)+'').addEventListener('click', () => removeFromList(website.url));\n })\n }",
"function buildMenu(subtree, currentPath) {\n var menu = {\n id: subtree.id,\n items: [],\n submenus: [],\n path: currentPath,\n title: subtree.title,\n hasIndex: subtree.hasIndex\n };\n\n var i;\n\n //sub menus\n for(i = 0; i < subtree.subtrees.length; i++) {\n var sub = subtree.subtrees[i];\n var menuPath = currentPath + makeUrlSafeName(sub.name) + '/';\n menu.submenus.push(buildMenu(sub, menuPath));\n }\n\n //documents\n for(i = 0; i < subtree.documents.length; i++) {\n var document = subtree.documents[i];\n if(document.name == 'index') continue; //exclude index pages from menu\n var documentName = getDocumentName(document);\n var documentPath = currentPath + documentName;\n menu.items.push({\n title: ('title' in document.meta) ? document.meta.title : document.name,\n path: documentPath,\n id: document.id\n });\n }\n\n return menu;\n}",
"function itemTree(leftId, leftPatch, rightId, rightPatch) {\n var innerHtml = '<a href=\"ItemTrees#leftId=' + leftId + '&leftPatch=' + leftPatch + '&rightId=' + rightId + '&rightPatch=' + rightPatch + '\">Item Trees: ';\n innerHtml += champHtml(leftId);\n innerHtml += ' (' + leftPatch + ') vs ';\n innerHtml += champHtml(rightId);\n innerHtml += ' (' + rightPatch + ')</a>';\n return innerHtml;\n}",
"function drawMenu() {\n\t\n\tvar menu_html = '';\n\tvar current_menu = CURRENT_PAGE.menu;\n\n\tmenu_html += \t'<div id=\"navigation\" class=\"' +\n\t\t\t\t\tcurrent_menu.class + ' ' +\n\t\t\t\t\tcurrent_menu.name +\n\t\t\t\t\t' left\">';\n\n\t// REQUIRE that one page be titled \"Homepage\"\n\tmenu_html +=\t'<h1> <a href=\"index.html\">' +\n\t\t\t\t\tcurrent_menu.title +\n\t\t\t\t\t'</a> </h1>';\n\n\tmenu_html += \"<ul>\";\n\tfor (var i=0; i<current_menu.content.length; i++) {\n\t\n\t\titem = current_menu.content[i];\n\t\tif ( item instanceof block ) {\n\t\t\tmenu_html += item.html;\n\t\t}\n\t\telse if (item instanceof menu_item) {\n\t\t\tmenu_html += '<li>' + item.html + '</li>';\n\t\t\tif ( currentlySelected(item) ) {\n\t\t\t\tfor (var j=0; j<item.content.length; j++) {\n\t\t\t\t\tmenu_html += '<li class=\"subcategory\">';\n\t\t\t\t\tmenu_html += item.content[j].html + '</li>';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tmenu_html += '<li>' + item.html + '</li>';\n\t\t}\n\t}\n\tmenu_html += '</ul></div>';\n\tdocument.getElementById(\"menu_contents\").innerHTML = menu_html;\n\n}",
"function makeBranches(treeNode, nestedList) {\r\n // 12. Each time the makeBranches() function is called, it is because a new node has been discovered in the source article. Increase the value of the nodeCount variable by 1.\r\n nodeCount++;\r\n\r\n// 13. Create the following list item HTML fragment, storing the list item element in the lielem variable and the span element node in the spanelem variable:\r\n// <li> \r\n// +--<span></span>\r\n// </li>\r\nvar liElem = document.createElement(\"li\");\r\nliElem.innerHTML = \"+--\";\r\nvar spanElem = document.createElement(\"span\");\r\nliElem.appendChild(spanElem);\r\nnestedList.appendChild(liElem);\r\n\r\nif (treeNode.nodeType === 1) {\r\n elemCount++;\r\n spanElem.setAttribute(\"class\", \"elementNode\");\r\n spanElem.textContent = \"<\" + treeNode.nodeName + \">\";\r\n} else if (treeNode.nodeType === 3) {\r\n textCount++;\r\n var textString = treeNode.nodeValue;\r\n\r\n\r\n if (isWhiteSpaceNode(textString)) {\r\n wsCount++;\r\n spanElem.setAttribute(\"class\", \"whiteSpaceNode\");\r\n spanElem.textContent = \"#text\";\r\n } else {\r\n spanElem.setAttribute(\"class\", \"textNode\")\r\n spanElem.textContent = textString;\r\n }\r\n}\r\nif (treeNode.childNodes.length > 0) {\r\n var newList = document.createElement(\"ol\");\r\n newList.innerHTML = \"|\";\r\n nestedList.appendChild(newList);\r\n for (var n = treeNode.firstChild; n !== null; n = n.nextSibling) {\r\n makeBranches(n, newList);\r\n }\r\n }\r\n}",
"function updateBuildingPath() {\n\n // clean DOM\n var $breadCrumb = $(\".breadcrumb\").empty();\n\n for (var i = 0; i < navbar.length - 1; i++) {\n $breadCrumb.append(\"<li><a class=\\\"nave\\\" name=\\\"\" + navbar[i] + \"\\\" style=\\\"cursor : pointer;\\\">\" + navbar[i] + \"</a></li>\");\n }\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 itemTree() {\n return col('col-12 col-xl-3', \n div('itemTree', itemTreeTitle() + '<hr>' + itemTreeChange() + '<hr>' + itemTreeTree() + '<hr>' + itemTreeAdd())\n )\n}",
"function buildTree(P, arg, path)\n{\n if (!path)\n path = \"/\";\n report(\"buildTree \"+arg);\n if (Number.isInteger(arg)) {\n report(\"atomic case \"+arg);\n var tree = getTree(P, {n: arg});\n tree.name = path+\"A\";\n return tree;\n }\n else {\n report(\"list case case \"+arg);\n path = path+\"H\";\n var children = arg;\n var nodes = [];\n for (var i=0; i<children.length; i++) {\n nodes.push(buildTree(P, children[i], path+\"/\"+i));\n }\n var tree = getTree(P, {children: nodes});\n tree.name = path;\n return tree;\n }\n}",
"function makeTree() {\r\n // fragments for the aside on the right\r\n var aside = document.createElement(\"aside\");\r\n aside.id = \"treeBox\";\r\n aside.innerHTML = \"<h1>Node Tree</h1>\";\r\n\r\n // inserts the aside into the document inside the main article\r\n var sectionMain = document.getElementById(\"main\");\r\n sectionMain.appendChild(aside);\r\n\r\n // creates the list for the aside\r\n var nodeList = document.createElement(\"ol\")\r\n aside.appendChild(nodeList);\r\n\r\n // sets the article that will be used as a source (the book says to use querySelectorAll() but that breaks everything)\r\n var sourceArticle = document.querySelector(\"#main article\");\r\n\r\n // runs the make branches function for the aside\r\n makeBranches(sourceArticle, nodeList);\r\n\r\n // displays the number of differenet types of nodes within the page\r\n document.getElementById(\"totalNodes\").textContent = nodeCount;\r\n document.getElementById(\"elemNodes\").textContent = elemCount;\r\n document.getElementById(\"textNodes\").textContent = textCount;\r\n document.getElementById(\"wsNodes\").textContent = wsCount;\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get own property names from Node prototype, but only the first time `Node` is instantiated | function lazyKeys() {
if (!ownNames) {
ownNames = Object.getOwnPropertyNames(Node.prototype);
}
} | [
"getProps(){\n let properties = new ValueMap();\n let propWalker = this;\n\n while(propWalker.__type<0x10){\n for(let [k,v] of propWalker.__props){\n properties.set(k,v);\n }\n propWalker = propWalker.getProp(\"__proto__\");\n };\n return properties;\n }",
"visitObject_properties(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"static get observedAttributes() {\n // note: piggy backing on this to ensure we're finalized.\n this.finalize();\n const attributes = [];\n // Use forEach so this works even if for/of loops are compiled to for loops\n // expecting arrays\n this._classProperties.forEach((v, p) => {\n const attr = this._attributeNameForProperty(p, v);\n if (attr !== undefined) {\n this._attributeToPropertyMap.set(attr, p);\n attributes.push(attr);\n }\n });\n return attributes;\n }",
"extractProps(node) {\n if (Element$1.isAncestor(node)) {\n var properties = _objectWithoutProperties(node, [\"children\"]);\n\n return properties;\n } else {\n var properties = _objectWithoutProperties(node, [\"text\"]);\n\n return properties;\n }\n }",
"function listAllProperties(o){ \n\tvar objectToInspect; \n\tvar result = [];\n\t\n\tfor(objectToInspect = o; objectToInspect !== null; objectToInspect = Object.getPrototypeOf(objectToInspect)){ \n\t\tresult = result.concat(Object.getOwnPropertyNames(objectToInspect)); \n\t}\n\t\n\treturn result; \n}",
"function propertyDescriptors() {\r\n console.log('--------------------- Property Descriptors ---------------------');\r\n\r\n var enber = {\r\n name: {christian: 'Christian', family: 'Bale'},\r\n age: 50\r\n };\r\n\r\n Object.defineProperty(enber, 'fullName', {\r\n get: function getFullName() {\r\n return this.name.family + '; ' + this.name.christian;\r\n },\r\n set: function setFullName(fullName) {\r\n var object = this;\r\n\r\n var names = fullName.split(' '); // ['John', 'Martin', 'Doe'] <<<< 'John Martin Doe'\r\n this.name.family = names.splice(names.length - 1, 1); // 'Doe' <-- ['John', 'Martin', ]\r\n\r\n this.name.christian = names.splice(0, 1);\r\n names.map(function (name) {\r\n object.name.christian = object.name.christian + ' ' + name;\r\n });\r\n }\r\n });\r\n\r\n console.log('enber object\\'s keys:', Object.keys(enber));\r\n console.log('enber object\\'s own property names:', Object.getOwnPropertyNames(enber));\r\n\r\n console.log('full name:', enber.fullName);\r\n console.log('set name...');\r\n enber.fullName = 'Johanns Chrisostomus Wolfgangus Amadeus Mozart';\r\n console.log('full name:', enber.fullName);\r\n }",
"onOwnPropertyNamesGet(room, identifier) {\n return Object.getOwnPropertyNames(room);\n }",
"function getChildNames(node) {\n var allKeys = Object.keys(node);\n var childNames = [];\n\n for (var i = 0, l = allKeys.length; i < l; ++i) {\n var key = allKeys[i];\n\n if (key[0] !== '$') {\n childNames.push(key);\n }\n }\n\n return childNames;\n}",
"function getNodeNamesFromCustomPreset(currPreset){\n //console.log(currPreset);\n let nodes = [...Object.keys(currPreset)];\n let oscNodes = nodes.filter((nodeName) => {\n return nodeName.indexOf(\"Osc\") >= 0 || nodeName.indexOf(\"AudioBuffer\") >= 0;\n });\n \n let gainNodes = nodes.filter((nodeName) => {\n return nodeName.indexOf(\"Gain\") >= 0;\n });\n \n return {\n \"gainNodes\": gainNodes, \n \"oscNodes\": oscNodes\n };\n}",
"get propertyName() {}",
"get nodelist() {\n\t\treturn this.nodes.values();\n\t}",
"visitPhysical_properties(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function ensurePropertyFunctions (Ctor) {\n const props = Ctor.props;\n\n return keys(props).reduce((descriptors, descriptorName) => {\n descriptors[descriptorName] = props[descriptorName];\n if (typeof descriptors[descriptorName] !== 'function') {\n descriptors[descriptorName] = initProps(descriptors[descriptorName]);\n }\n return descriptors;\n }, {});\n}",
"getPropertyKeys() {\n let properties = this.getProperties();\n let propertyKeys = [];\n if (properties) {\n for (var key in properties) {\n if (Object.prototype.hasOwnProperty.call(properties, key)) {\n propertyKeys.push(key);\n }\n }\n }\n propertyKeys = propertyKeys.sort();\n return propertyKeys;\n }",
"function testcase() {\n var obj = { \"a\": \"a\" };\n\n var result = Object.getOwnPropertyNames(obj);\n\n try {\n var beforeOverride = (result[0] === \"a\");\n result[0] = \"b\";\n var afterOverride = (result[0] === \"b\");\n\n return beforeOverride && afterOverride;\n } catch (ex) {\n return false;\n }\n }",
"visitColumn_properties(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitIndex_properties(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function findNodeProperty(prop, contact) {\n\t\n\tif (prop.indexOf(getClassName(contact.m_node1.other)) != -1) {\n\t\t\n\t\treturn [contact.m_node1.other, contact.m_node2.other]\n\t\t\n\t}\n\t\n\telse if (prop.indexOf(getClassName(contact.m_node2.other)) != -1) {\n\t\t\n\t\treturn [contact.m_node2.other, contact.m_node1.other]\n\t\t\n\t}\n\t\n\telse return false;\n\t\n}",
"getTrackedElements() {\n const sourceTrackedKeys = Object.keys(this.getSourceMembers());\n return sourceTrackedKeys.map((key) => this.getTrackedElement(key));\n }",
"inherit(property) {\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.