query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Retrieve a list of all alarms | getAlarms(where = { id: undefined, addresses: [] }) {
const internalWhere = {
enabled: 1,
};
if (where.addresses && where.addresses.length) {
internalWhere.address = {
[Op.in]: where.addresses,
};
}
if (where.id) {
internalWhere.id = where.id;
}
return this.alarmModel
.findAll({
where: internalWhere,
})
.map(function (alarm) {
alarm.dataValues.abi = JSON.parse(alarm.dataValues.abi);
alarm.dataValues.eventNames = alarm.dataValues.eventNames.split(";");
return alarm.dataValues;
});
} | [
"async function listAlarms () {\n return devices[0].alarmClockService().ListAlarms().then(alarms => {\n log.debug('Got alarms %j', alarms)\n mqttClient.publish(config.name + '/alarms', JSON.stringify(alarms), { retain: false })\n })\n}",
"function getAlarms() {\n DataSourceDwr.getAlarms(currentDsId,writeAlarms);\n }",
"async function listAlarms () {\n return devices[0].AlarmList().then(alarms => {\n log.debug('Got alarms %j', alarms)\n mqttClient.publish(config.name + '/alarms', JSON.stringify(alarms), { retain: false })\n return true\n })\n}",
"function logAllAlarms() {\n let getAlarms = browser.alarms.getAll();\n getAlarms.then(function() {\n console.log('All active alarms: ');\n for (let alarm of alarms) {\n console.log(alarm.name);\n }\n });\n}",
"static getAlarms(params = {}) {\n return HttpClient.get(`${ENDPOINT}alarms?${stringify(params)}`)\n .map(toAlarmsModel)\n }",
"function getAllAlarms() {\n var AlarmObject = Parse.Object.extend(\"Alarm\");\n\n /* this says that for results that are coming back\n\t you can treate all the items as alarm objects\n\t as seen below with '.time' and '.alarmName' */\n\n\n var query = new Parse.Query(AlarmObject);\n FB.getLoginStatus(function(response) {\n if (response.status === 'connected') {\n query.equalTo(\"fb_user_id\", response['authResponse']['userID']);\n query.find({\n success: function(results) {\n alarm_results = results;\n for (var i = 0; i < results.length; i++) {\n insertAlarm(results[i].get('time'), results[i].get(\n 'alarmName'));\n }\n setDelete();\n fireAlarm();\n },\n error: function() {\n //fireAlarm();\n }\n });\n }\n });\n\n}",
"getAlarms() {\n return Object.assign( {}, this._alarms );\n }",
"function gotAll(alarms) {\n\t\t\n\t\t// If there are active alarms\n\t\tif (alarms.length > 0) {\n\n\t\t\t// Get these alarms\n\t\t\tfor (var alarm of alarms) {\n\t\t\t\t// Push alarm object properties into activeAlarms array\n\t\t\t\tactiveAlarms.push([alarm.name, alarm.scheduledTime]);\n\t\t\t}\n\n\t\t\t// Show list of active alarms\n\t\t\t$('.activeAlarms').show();\n\t\t\t$('h3').text('Alarmes actives :');\n\n\t\t\t// Get current DateTime\n\t\t\tvar dateActuelle = new Date(Date.now());\n\n\t\t\t// Create the <li> list elements\n\t\t\tfor (var i = 0; i < activeAlarms.length; i++) {\n\n\t\t\t\t// TODO : Format this into a proper date to render inside the list !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\t\t\t\tvar alarmDateTime = activeAlarms[i][1];\n\n\t\t\t\t// Calcule timezone offset delay in minutes\n\t\t\t\tvar delay = Math.round((alarmDateTime - Date.now())/60000);\n\n\t\t\t\t// Create list element with active alarms info :\n\t\t\t\t$('ul.activeAlarms').append('<li id=\"alarm_' + i + '\">\"' + activeAlarms[i][0] +'\" dans ' + delay + ' minutes</li>');\n\n\t\t\t\t// TODO : Create a button alongside each <li> which clear the alarm if clicked !!!!!!!!!!!!!!!\n\t\t\t\n\t\t\t}\n\n\t\t} else {\n\n\t\t\t$('h3').text(\"Pas d'alarmes actives.\");\n\t\t\n\t\t}\n\n\t}",
"getAlarms() {\n let alarms;\n if (localStorage.getItem('alarms') === null) {\n alarms = [];\n } else {\n alarms = JSON.parse(localStorage.getItem('alarms'));\n }\n return alarms;\n }",
"function getAllAlarms(userid) {\n clearAlarmDisplay();\n\n // Parse DB query to get all alarms\n var AlarmObject = Parse.Object.extend(\"Alarm\");\n var query = new Parse.Query(AlarmObject);\n query.equalTo('userid', userid);\n\n query.find({\n success: function(results) {\n if (results.length == 0) { // If no alarms set\n $(\"#alarms\").html(\"No Alarms Set\");\n }\n for (var i = 0; i < results.length; i++) { \n insertAlarm(results[i].get(\"time\"), results[i].get(\"alarmName\"));\n }\n }\n });\n}",
"static getActiveAlarms(params = {}) {\n return HttpClient.get(`${ENDPOINT}alarmsbyrule?${stringify(params)}`)\n .map(toActiveAlarmsModel);\n }",
"function loadAlarms() {\r\n // TBD: read alarms\r\n\r\n // for now, just generate some random alarms\r\n for (var i = 0; i < 3; i++) {\r\n alarms.push(newAlarm());\r\n }\r\n alarms[2][\"Once\"] = true;\r\n alarms[0][\"enabled\"] = true;\r\n alarms[0][\"name\"] = \"Test\";\r\n}",
"function fetchAlarm() {\n const alarms = checkAlarams();\n\n alarms.forEach((time) => {\n setAlarm(time, true);\n });\n}",
"loadAlarms() {\n let alarms = store.getData( this._options.storeKey );\n this._alarms = Object.assign( {}, alarms );\n }",
"function showAlarms() {\n\tclearDisplay();\n\tchrome.storage.sync.get(null, function(items){\n\t\tvar ks = Object.keys(items);\n\t\tvar showAlms = document.createElement(\"div\");\n\t\tshowAlms.id = \"all-alarms\";\n\t\tshowAlms.style.textAlign = \"center\";\n\t\tdocument.body.appendChild(showAlms);\n\t\tfor(i=0; i<ks.length; i++){\n\t\t\tvar item = document.createElement('span');\n\t\t\titem.id = ks[i];\n\t\t\tshowAlms.appendChild(item);\n\t\t\taddAlarmView(ks[i]);\n\t\t}\n\t\tif (ks.length == 0) {\n\t\t\tvar txt = document.createElement('h4');\n\t\t\tvar error = document.createTextNode(\"Sorry, you don't have anything saved!\");\n\t\t\ttxt.appendChild(error);\n\t\t\ttxt.className = \"text\";\n\t\t\tshowAlms.appendChild(txt);\n\t\t}\n\t});\n}",
"async makeAlarms(alarm_array){\n // console.log(\"makeAlarms\")\n alarm_array.forEach(async(list_item) => {\n if (list_item.switch == true){\n promise = (await Notifications.scheduleNotificationAsync({\n identifier: list_item.name,\n content: {\n title: list_item.name,\n // Add feature: custom subtitle\n // subtitle: 'Its ' + list_item.alarm_hour + ':' + list_item.alarm_minute + '!',\n },\n // DailyTriggerInput\n trigger: {\n hour: list_item.alarm_hour,\n minute: list_item.alarm_minute,\n repeats: false\n }\n }));\n }\n });\n\n // list is the promise return\n list = (await Notifications.getAllScheduledNotificationsAsync());\n return list;\n }",
"function printAlarms(data){\n\n var alarmJSON;\n var toReturn = '';\n\n //For all alarms add to string\n for(i = 0; i<data.length; i++){\n alarmJSON = data[i];\n toReturn += ('<h6>   Alarm ' + (i+1) + ': Action: ' + alarmJSON.action + ', Trigger: ' + alarmJSON.trigger + ', numProps: ' + alarmJSON.numProps + '<br></h6>');\n }\n\n return toReturn;\n\n}",
"function displayAlarms() {\n $(\"#alarmsModalBody\").empty();\n alarms = getAlarms();\n var html = '';\n for (var i=0; i < alarms.length; i++) {\n var a=alarms[i];\n html = html + renderAlarm(a.id,a.name,a.genres, a.time,a.snooze_time);\n }\n $(\"#alarmsModalBody\").append(html);\n}",
"function displayAlarms() {\r\n setInterval(myTimer, 100);\r\n function myTimer() {\r\n chrome.alarms.getAll(function (alarms) {\r\n var output = \"\";\r\n if (!alarms.length)\r\n output = \"No alarms set.\";\r\n else\r\n for (var i = 0; i < alarms.length; i++) {\r\n var time_left = minutesLeft(alarms[i].scheduledTime);\r\n output += \"Alarm \" + (i + 1) + \" - \" + time_left + \" min remaining<br>\";\r\n }\r\n document.getElementById(\"allAlarms\").innerHTML = output;\r\n });\r\n }\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
readonly attribute boolean canDeleteMessages; // can't delete from imap readonly | get canDeleteMessages()
{
return true;
} | [
"get isDeleted() {\r\n return this.hasFlag(MessageFlag.DELЕTЕD);\r\n }",
"get isDelete() {\r\n return this.subTypes.includes('dialog_messages_delete');\r\n }",
"markMessagesDeletedByIDs(aMessageIDs) {\n // When marking deleted clear the folderID and messageKey so that the\n // indexing process can reuse it without any location constraints.\n let sqlString =\n \"UPDATE messages SET folderID = NULL, messageKey = NULL, \" +\n \"deleted = 1 WHERE id IN (\" +\n aMessageIDs.join(\",\") +\n \")\";\n\n let statement = this._createAsyncStatement(sqlString, true);\n statement.executeAsync(this.trackAsync());\n statement.finalize();\n\n GlodaCollectionManager.itemsDeleted(\n GlodaMessage.prototype.NOUN_ID,\n aMessageIDs\n );\n }",
"function CanMarkMsgAsRead(read) {\n return SelectedMessagesAreRead() != read;\n}",
"set canDeleteItems(value) {\n this.canDeleteItems_ = value;\n }",
"function flagToDelete() {\n _this.canDelete = true;\n }",
"deleteMessage(state, input) {\n state.messages = state.messages.filter(m => m.id !== input)\n }",
"get showDeletedMessages()\n\t{\n\t\treturn true;\n\t}",
"get isCanDelete() {\r\n if (!this.$filled) {\r\n return undefined;\r\n }\r\n return Boolean(this.payload.can_delete);\r\n }",
"function toggleReceivedMessagesButton() {\n if (checkedCount > 0) {\n $('#subReceivedMessagesDelete').attr({disabled: false});\n } else {\n $('#subReceivedMessagesDelete').attr({disabled: true});\n }\n }",
"isCanDelete() {\n return this.canDelete;\n }",
"get deleted() {\n return (this.delInfo & DEL_SIDE) > 0;\n }",
"get allowPrivateMessages() {\n return !DiscordAPI.UserSettings.restrictedGuildIds.includes(this.id);\n }",
"function test_del_collapsed_thread() {\n press_delete(msgc);\n if (folder.getTotalMessages(false) != 4)\n throw new Error(\"should have only deleted one message\");\n\n}",
"get isDeletedForAll() {\r\n return this.hasFlag(MessageFlag.DELETED_FOR_ALL);\r\n }",
"get isUnread() {\r\n return this.hasFlag(MessageFlag.UNREAD);\r\n }",
"async markNeedactionMessagesAsRead() {\n await this.async(() =>\n this.env.models['mail.message'].markAsRead(this.needactionMessages)\n );\n }",
"async deleteMessage (message) {\n return this.updateMessage('(message deleted)', message, true)\n }",
"function deleteCommandMessage(serverDocument, channelDocument, msg) {\n\tif(serverDocument.config.delete_command_messages && msg.channel.permissionsOf(msg._client.user.id).has(\"manageMessages\")) {\n\t\tchannelDocument.isMessageDeletedDisabled = true;\n\t\tmsg.delete().then(() => {\n\t\t\tchannelDocument.isMessageDeletedDisabled = false;\n\t\t\tserverDocument.save(err => {});\n\t\t});\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function `Play`(print all block) from `top` block to some condition(reach some `height` or `limit`) | async function play (options) {
let { height, limit, json } = options
limit = parseInt(limit)
height = parseInt(height)
try {
const client = await initChain(options)
await handleApiError(async () => {
// Get top block from `node`. It is a start point for play.
const top = await client.topBlock()
if (height && height > parseInt(top.height)) {
printError('Height is bigger then height of top block')
process.exit(1)
}
printBlock(top, json)
// Play by `height` or by `limit` using `top` block as start point
height
? await playWithHeight(height, top.prevHash)(client, json)
: await playWithLimit(--limit, top.prevHash)(client, json)
})
} catch (e) {
printError(e.message)
process.exit(1)
}
} | [
"function printTopBlock() {\n printLine('<span class=\"green\">==================</span>');\n printLine('<span class=\"cyan\"> dhruv bhanushali</span>');\n printLine('<span class=\"green\">==================</span>');\n printLine(`<strong>software developer and technical writer</strong>`);\n printLine(`<strong>undergraduate, IIT Roorkee</strong>`);\n printLine('<br>');\n help();\n printLine('<br>');\n printTree();\n printLine('<br>');\n}",
"function print() {\n console.log(blocks);\n }",
"function choose_next_block(){\n block_no=Random_no();\n from_top=0;\n from_left=4;\n rotation_no=1;\n}",
"function globalBlockScanner() {\n var testHit2 = setInterval(function() {\n if (globalBlockCount > 0) { \n for (i = 0; i < globalBlockCount; i++) { \n if (blockOfBlocks[i].hitsMe(mario, $('.' + blockOfBlocks[i].generalType + ':eq(' + i + ')'))) {\n blockEffects(blockOfBlocks[i], i);\n clearInterval(testHit2);\n } else if ((blockOfBlocks[i].enterVSpace(mario, $('.ground:eq(' + i + ')'))) && (blockOfBlocks[i].onTop(mario, $('.ground:eq(' + i + ')')))) {\n currentPlane = $('.ground:eq(' + i + ')').offset().top - mario.height();\n mario.css({\n 'top': currentPlane\n });\n clearInterval(testHit2);\n } else {\n clearInterval(testHit2);\n }\n }\n }\n }, 10);\n }",
"newBlocks() {\n let lastBlock = this.topArray[this.topArray.length - 1]\n // new block will generate with 200px gap between it and last block\n if (lastBlock.x === 500) {\n this.createBlocks();\n }\n }",
"function drawNextBlock(){\n nextBlock.forEach(index => {\n if(index < 3){\n nextSquare[index].classList.add('block');\n }\n else if((index >= width) && (index < 2*width)){\n nextSquare[index - width+3].classList.add('block');\n }\n else {\n nextSquare[index - (width -3)*2].classList.add('block');\n }\n });\n }",
"function show_block(scene, rectangle, items, algo = pivot_algo) {\n let height = 1;\n let y = -5;\n\n base = show_box(scene, rectangle, height, y, 'red');\n child_rectangles = algo(rectangle, {x:0, z:0}, items);\n let current_col = 0;\n child_rectangles.map(function (rect) {\n current_col = (current_col + 1) % colors.length;\n show_box(base, rect, height, 1, colors[current_col]);\n });\n}",
"function showBlocks() {\n\tconsole.log(blocks)\n}",
"function draw () {\n background('city')\n changeLava(road)\n blockArray[0].createBlk()\n heli(0, blueHeli, 45)\n // for loop to draw subsequent blocks if previous block reaches a certain height\n for (var i = 1; i < blockArray.length; i++) {\n if (blockArray[i - 1].y > canvas.height / 3) {\n blockArray[i].createBlk()\n if (i < 10) {\n heli(i, blueHeli, 45)\n } else if (i < 30) {\n level = '2: Chimp'\n heli(i, redHeli, 45)\n } else if (i < 80) {\n background('mountain')\n changeLava(lavaImage)\n heli(i, blackHeli, 45)\n level = '3: Gorilla'\n } else if (i < 200) {\n background('sky')\n changeLava(cloud)\n heli(i, bigHeli, 45)\n level = '4: King Kong'\n } else {\n background('space')\n changeLava(earth)\n heli(i, ufo, 65)\n level = '5: Wu Kong'\n }\n }\n }\n startBlock.draw(c)\n lava.draw(c)\n ball.draw(c)\n canvasText()\n }",
"function block(day, min1, min2, color, text){\n\tvar out = isidiot ? divclass(\"block idiot\") : divclass(\"block\");\n\tout.style.backgroundColor = color;\n\tvar tempHeight = (100 * (min2 - min1) / (end_time - start_time));\n\ttempHeight = isidiot ? tempHeight - 1.5 : tempHeight;\n\tout.style.height = tempHeight.toString() + \"%\";\n\tout.style.top = (100 * (min1 - start_time) / (end_time - start_time)).toString() + \"%\";\n\tout.innerHTML = text + \"<br>\" + toclock(min1) + \"-\" + toclock(min2);\n\tgrab(day).appendChild(out);\n\tblocks.push(out);\n\treturn out;\n}",
"function playBlocks() {\n clearInterval(intervalId);\n compTurn = true;\n turn++;\n turnCount.innerText = turn;\n addNewIndex(compSequence);\n\n if (theme !== \"farm\" && compSequence.length > 5 && compSequence.length < 11) {\n delay = 900;\n } else if (\n theme !== \"farm\" &&\n compSequence.length > 11 &&\n compSequence.length < 16\n ) {\n delay = 800;\n } else if (theme !== \"farm\" && compSequence.length > 16) {\n delay = 700;\n } else {\n delay = 1000;\n }\n\n playCompSequence();\n}",
"standingBlock() {\n\t\tthis.updateState(RYU_SPRITE_POSITION.standingBlock, RYU_IDLE_ANIMATION_TIME, false);\n\t}",
"function showtargetblock(){\n\n\tvar bloc = $$(\".block\");\n\n\tif(targetBlocks.length > 4){\n\t\talert(\"you lose\");\n\t\tstopGame();\n\t}\n\telse{\n\t\tvar temp = Math.floor(Math.random() * 9);\n\t\t\n\t\twhile (bloc[temp].hasClassName(\"target\") || temp == trapBlock) {\n\t\t\ttemp = Math.floor(Math.random() * 9);\n\t\t}\n\n\t\ttargetBlocks.push(temp);\n\t\t\n\t\tbloc[temp].addClassName(\"target\");\n\t}\n\t\n}",
"function printBox(width, height) {\n var top_bottom = 0;\n var inner_rows = 0;\n star = \"*\";\n gap = \" \";\n while (top_bottom < 2) {\n console.log(star.repeat(width));\n while (inner_rows <= (height - 2)) {\n console.log(\"*\" + (gap.repeat(width - 2)) + \"*\");\n inner_rows++;\n }\n top_bottom++;\n }\n}",
"function printBox(width, height) {\n for (let i = 1; i <=height; i++) {\n if (i === 1 || i === height) {\n console.log('*'.repeat(width));\n } else {\n console.log('*' + ' '.repeat(width - 2) + '*');\n }\n }\n}",
"function showNumbers() {\n\t\n lightupGrid();\n scene.stop();\n var blocks = getBlocks();\n\n for (var i = 0; i < blocks.length; i++) {\n\t\n var block = blocks[i];\n showBlockNumber(block.get(\"id\"));\n\n }\n scene.start();\n\n}",
"function pictureBehavior() {\n\n\tif (currentStep == 0 && !blocksDropped && experimentRunning) {\n\t\ty *= 1.06;\n\t\tblockHeight -= y;\n\n\n\t\t$(\".sit1block\").css(\"bottom\", blockHeight + \"%\");\n\t\t$(\".sit2block\").css(\"bottom\", blockHeight + \"%\");\n\n\t\tif (blockHeight <= fallDist) {blocksDropped = true; y = 0.75;} else {blocksDropped = false;}\n\n\t} else if (experimentRunning) {\n\n\t\tcurrentIceHeight1 = Math.max(0, iceMaxHeight1 * (maxIce - sit1IceArray[currentStep][1]) / maxIce);\n\t\tlet cssHeight1 = currentIceHeight1 + \"%\";\n\t\tcurrentIceWidth1 = Math.max(0, iceMaxWidth1 * (maxIce - sit1IceArray[currentStep][1]) / maxIce);\n\t\tlet cssWidth1 = currentIceWidth1 + \"%\";\n\n\t\t// Calculate the new height and width values for the ice cubes of situation 2\n\t\tcurrentIceHeight2 = Math.max(0, iceMaxHeight2 * (maxIce - sit2IceArray[currentStep][1]) / maxIce);\n\t\tlet cssHeight2 = currentIceHeight2 + \"%\";\n\t\tcurrentIceWidth2 = Math.max(0, iceMaxWidth2 * (maxIce - sit2IceArray[currentStep][1]) / maxIce);\n\t\tlet cssWidth2 = currentIceWidth2 + \"%\";\n\n\t\tif ((blockHeight) > 3) // If the blocks are already at the bottom of the beaker, don't move them\n\t\t\tblockHeight -= 0.3;\n\t\t$(\".sit1block\").css(\"bottom\", blockHeight + \"%\");\n\t\t$(\".sit2block\").css(\"bottom\", blockHeight + \"%\");\n\n\t\t// Shrink the ice cubes\n\t\t$(\".sit1Ice\").css({\n\t\t\theight: cssHeight1,\n\t\t\twidth: cssWidth1,\n\t\t});\n\t\t$(\".sit2Ice\").css({\n\t\t\theight: cssHeight2,\n\t\t\twidth: cssWidth2,\n\t\t});\n\t}\n}",
"function ShowCatBoardOnly()\n{\n\t//while ( canShowCatBoard == false )\n\t//{\n\t//\tif ( Wizards.Utils.DEBUG ) Debug.Log(\"Waiting for can show catboard\");\n\t//\tyield;\n\t//}\n\t//canScroll = false;\n\t//canZoom = false;\n\t//canScale = false;\n\t//if ( Wizards.Utils.DEBUG ) Debug.Log(\"Showing Catboard\");\n\tgm.HideChainCount();\n\tcatBoard=true;\n\tSetCheckPoint();\n\t\n\tlm.PauseFireworks();\n\twizard.freeze=true;\n\taudienceBar.Hide();\n\taudienceBar.isLock=true;\n\t//if ( Wizards.Utils.DEBUG ) Debug.Log(\"About to show ratings notice\");\n\tpanelController.ShowRatingsNotice();\n\t//if ( Wizards.Utils.DEBUG ) Debug.Log(\"About to yield for 10 seconds\");\n\tyield WaitForSeconds(10);\n\t//if ( Wizards.Utils.DEBUG ) Debug.Log(\"Finished yielding\");\n\tstageIndex++;\n\t\n\tHideCatBoard();\n\t\n\t\t\n\tcanPauseFireWorks = false;\n\t//canShowCatBoard = false;\n\t\n\t//yield WaitForSeconds(10.0);\n\t//canShowTitleWithName = true;\n\t//ShowTitle();\n\t\n\tem.NextStage();\n}",
"function showtarpblock(){\n\n\tvar bloc = $$(\".block\");\n\tvar temp = Math.floor(Math.random() * 9);\n\n\twhile (bloc[temp].hasClassName(\"target\")) {\n\t\ttemp = Math.floor(Math.random() * 9);\n\t}\n\n\ttrapBlock = temp;\n\n\tbloc[temp].addClassName(\"trap\");\n\n\tinstantTimer = setTimeout(function() {\n\t\ttrapBlock = null;\n\t\tbloc[temp].removeClassName(\"trap\");\n\t}, 2000);\n\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
generates noise/static visual towards the end of the song/row | function noiseAfterSong(songNum, songDuration) {
for (var currX = songDuration; currX < width; currX++) {
for (var currY = songNum*colHeight; currY < (songNum*colHeight)+colHeight; currY++) {
var currIndex = (currX + currY * width) * 4;
var r = pixels[currIndex + 0];
var g = pixels[currIndex + 1];
var b = pixels[currIndex + 2];
var a = pixels[currIndex + 3];
//adds static
var col= random(255);
pixels[currIndex+0] = col+20;
pixels[currIndex+1] = col;
pixels[currIndex+2] = col+20;
pixels[currIndex+3] = 200;
}
}
} | [
"function onRandom() {\r\n paintNoise();\r\n}",
"function four() {\n if (noise) {\n let audio = document.getElementById(\"clip4\");\n audio.play();\n }\n noise = true;\n bottomRight.style.backgroundColor = \"lightskyblue\";\n}",
"function draw() {\n\tif (rowRemoved && soundIsOn) {\n\t\trowPopAudio.play()\n\t\trowRemoved = false\n\t}\n\tfor (let y = 0; y < playField.length; y++) {\n\t\tfor (let x = 0; x < playField[y].length; x++) {\n\t\t\tif (playField[y][x] === 1) {\n\t\t\t\tmainCellArr[y][x].style.opacity = '1'\n\t\t\t} else if (playField[y][x] === 2) {\n\t\t\t\tmainCellArr[y][x].style.opacity = '1'\n\t\t\t} else {\n\t\t\t\tmainCellArr[y][x].style.opacity = '0.25'\n\t\t\t}\n\t\t}\n\t}\n}",
"function generateNoise() {\n\tvar texData = this._texData,\n\t\tw = this._width,\n\t\th = this._height,\n\t\tdimPixel = this._config.dimPixel;\n\tfor (var i = 0, l = texData.length; i < l; i++) {\n\t\tif (Math.random() > 0.996) {\n\t\t\tvar x = i % w,\n\t\t\t\ty = (i / w) >> 0;\n\n\t\t\tif (x < w - dimPixel && y < h - dimPixel) {\n\t\t\t\tfor (var k = 0; k < dimPixel; k++) {\n\t\t\t\t\tfor (var j = 0; j < dimPixel; j++)\n\t\t\t\t\t\ttexData[(x + k) + (y + j) * w] = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}",
"function play() {\n ////// draw radial lines of cells /////\n for (let i = 0; i < nodePositions.length; i++) {\n setIntervalOnNode(radialLines, 100, 120, nodePositions[i])\n }\n\n let cells = nodePositions.map(nodePos => {\n return getCell(nodePos, canvasWidth, canvasHeight)\n })\n cells.forEach(cell => {\n playRepeat(`${cell.y * numOfCols + cell.x + 1}ogg`)\n })\n }",
"function rain() {\n // remove al if there is a change\n\tif (isChange) {\n\t\t$('.rainContianer').empty();\n\t\t$('.rainContainer div').removeAttr('style');\n\t\tisChange = false;\n\t}\n \n // generate raindrops\n\tfor(i = 0 ; i < val; i++) {\n\t\tvar left = (Math.floor(Math.random() * (getWidth() - 0 + 1)));\n\t\tvar top = (Math.floor(Math.random() * (getHeight() + 1000 + 1)) - 1000);\n\n\n\t\t$('.rainContainer').append('<div class=\"drop\" id=\"drop' + i + '\"></div>');\n\t\t$('#drop' + i).css('left', left);\n\t\t$('#drop' + i).css('top', top);\n\t}\n}",
"rain(density, power = 2500) {\n for (let i = 0; i <= density; i++) {\n let delay = Math.ceil((Math.random() * 5000));\n let drop = Dom.createElement('span', null, 'rain-drop');\n drop.style.left = Math.ceil((Math.random() * 99)) + \"%\";\n drop.style.top = '-30px';\n drop.style.opacity = Math.random();\n\n drop.animate([\n {top: drop.style.top, opacity: drop.style.opacity}, \n {top: window.screen.height + 'px', opacity: '0'}], \n {duration: power, iterations: Infinity, delay: delay});\n \n this.app.appendChild(drop);\n }\n }",
"function three() {\n if (noise) {\n let audio = document.getElementById(\"clip3\");\n audio.play();\n }\n noise = true;\n bottomLeft.style.backgroundColor = \"rgb(255, 255, 102)\";\n}",
"function Visualiser(x, y, w, h) {\n\n this.x = x;\n this.y = y;\n this.width = w;\n this.height = h;\n\n\n this.display = function() {\n noFill();\n noStroke();\n rect(this.x, this.y, this.width, this.height);\n }\n\n this.isOn = function() { //function that returns a boolean//\n for(var i=0; i<rows; i++) {\n for(var j=0; j<cols; j++) {\n while(samples[i][j].on) {\n return true;\n }\n }\n }\n while(sineInstrumentPlaying === true || triangleInstrumentPlaying === true || sawInstrumentPlaying === true || squareInstrumentPlaying === true) {\n return true;\n }\n }\n\n\n this.visualiserSetup = function() {\n fft = new p5.FFT();\n\n //add 255 elements to colourList//\n for(var i=0; i<255; i++) {\n append(colourList, i);\n }\n }\n\n //display spectrum and waveform//\n this.visualiserDisplay = function() {\n\n spectrum = fft.analyze();\n\n if(this.isOn()) {\n if(clicked === true) {\n fill(pickAColour(), pickAColour(), pickAColour());\n } else {\n fill(0, 255, 0);\n }\n } else {\n noFill();\n }\n\n var i=0;\n while(i<spectrum.length) {\n var x = map(i, 0, spectrum.length, this.x, width);\n var h = -this.height + map(spectrum[i], 0, 255, this.height, this.y);\n rect(x, this.height, width / spectrum.length, h);\n i++;\n }\n\n waveform = fft.waveform();\n noFill();\n beginShape();\n if(this.isOn()) {\n stroke(255, 0, 0);\n strokeWeight(1);\n } else {\n noStroke();\n }\n var i=0;\n while(i<waveform.length) {\n var x = map(i, 0, waveform.length, this.x, width);\n var y = map(waveform[i], -1, 1, 0, this.height/3);\n vertex(x,y);\n i++;\n }\n endShape();\n }\n\n this.visualiserSetupLeft = function() {\n analyzer = new p5.Amplitude();\n for(var i=0; i<soundFiles.length; i++) {\n analyzer.setInput(soundFiles[i]);\n }\n\n fft = new p5.FFT();\n }\n\n //display amplitude for left//\n this.visualiserDisplayLeft = function() {\n //determine root mean square of amplitude values//\n var rms = analyzer.getLevel();\n\n if(this.isOn() || recordingStates[0] === 2 || recordingStates[1] === 2 || recordingStates[2] === 2 || recordingStates[3] === 2) {\n if(clicked === true) {\n fill(pickAColour(), pickAColour(), pickAColour());\n stroke(0);\n } else {\n fill(0, 255, 0);\n stroke(0);\n }\n } else {\n noFill();\n noStroke();\n }\n // Draw an ellipse with size based on volume\n var ellipseX = this.width/2;\n var ellipseY = this.height/2;\n if(this.isOn()) {\n ellipseX += random(-1, 1);\n ellipseY += random(-1, 1);\n }\n ellipse(ellipseX, ellipseY, 20+rms*1500, 20+rms*1500);\n\n waveform = fft.waveform();\n noFill();\n beginShape();\n if(this.isOn()) {\n stroke(255, 0, 0);\n strokeWeight(1);\n } else {\n noStroke();\n }\n var i=0;\n while(i<waveform.length) {\n var x = map(i, 0, waveform.length, this.x, this.width);\n var y = map(waveform[i], -1, 1, 0, this.height/3);\n vertex(x,y);\n i++;\n }\n endShape();\n\n //360 degree FFT analiser visualisation//\n spectrum = fft.analyze();\n noStroke();\n translate(this.width/2, this.height/2);\n if(this.isOn()) {\n beginShape();\n for(var i=0; i<spectrum.length; i++) {\n var angle = map(i, 0, spectrum.length, 0, 360);\n var amp = spectrum[i];\n var r = map(amp, 0, 256, 0, 170);\n var x = r * cos(angle);\n var y = r * sin(angle);\n vertex(x,y);\n }\n stroke(0, 255, 0);\n noFill();\n endShape();\n } else {\n noStroke();\n }\n }\n}",
"function Worm() {\n\n//create all the worm variables\n this.zoff = 0;\n this.xpos= 0;\n this.ypos = height;\n this.red = 255;\n this.g = 255;\n this.b = 255;\n\n\n// this function is for the colour of the worm\n this.colour = function() {\n\n this.red = map(this.xpos, 0, width, 0, 255);\n this.g = map(this.ypos, 0, width, 255, 0);\n // this.b = map(this.ypos, 0, width, 255, 0);\n }\n\n// this is the function that displays all the things related in the worms\n// such as creating the worm itself, it is created by using ,ultiple points and connecting them\n// with some perlin noise involved\n this.display = function() {\n let noiseMax = slider.value();\n\n let yy = map(noise(this.ypos), 0, 1, 0, height);\n this.ypos += 0.005;\n translate(this.xpos, yy);\n stroke(this.red, this.g, this.b, 200);\n noFill();\n beginShape();\n\n for (let a = 0; a < TWO_PI; a += 0.1) {\n\n let xoff = map(cos(a), -1, 1, 0, noiseMax);\n let yoff = map(sin(a), -1, 1, 0, noiseMax);\n // let xSize = map(mouseX,0,width,0,100);\n // let ySize = map(mouseY,0,height,0,300);\n let xSize = 100\n let ySize = 300\n let r = map(noise(xoff, yoff, this.zoff), 0, 1, xSize, ySize);\n let x = r * cos(a);\n let y = r * sin(a);\n\n vertex(x, y);\n }\n\n endShape(CLOSE);\n\n\n //this.xpos += random(1,1.1);\n //this.zoff += random(0.01,0.015);\n\n this.xpos +=1.5\n this.zoff += 0.01;\n\n }\n\n\n\n// this funciton allows you to click the screen and it will restartt tthe page\n this.restart = function(){\n if (mouseIsPressed) {\n background(0);\n this.xpos = 0;\n this.ypos = random(height);\n\n }\n\n\n }\n }",
"function generateSound() {\n var cols = Object.keys(colors);\n var random = cols[Math.floor(Math.random() * cols.length)];\n sequence.push(random);\n // console.log('Sequence: ' + sequence);\n playSequence();\n }",
"function drawMusicLines() {\n\t// non-moving line parts\n\tstroke(redPalette[0]);\n\tstrokeWeight(3);\n\tlet xLeftEnd = 388;\n\tlet xRightEnd = 1412;\n\tlet yAltitude = 360;\n\tlet headLimitPoint = 1050;\n\n\t// left (before head)\n\tline(0, yAltitude, xLeftEnd, yAltitude);\n\n\t// right (after head)\n\tstroke(backgroundBluesPalette[0]);\n\tline(xRightEnd, yAltitude, 1800, yAltitude);\n\n\t// moving line parts (variates with sound amplitude)\n\tlet currentX = xLeftEnd + 1;\n\tlet currentY = yAltitude;\n\tlet previousX = xLeftEnd;\n\tlet previousY = yAltitude;\n\n\tlet soundWave = fft.waveform(1024);\n\tlet counter = 0;\n\tlet lerpProgress = 0;\n\tlet afterHead = false;\n\n\tlet colorList = [0, 1, 1, 2, 2, 3, 3, 2, 2, 1, 1, 0];\n\tlet currentTargetColor = 1;\n\tlet previousColor = redPalette[colorList[0]];\n\tlet currentColor = redPalette[colorList[currentTargetColor]];\n\n\twhile (currentX < xRightEnd) {\n\t\tif (mainMusicPlaying) {\n\t\t\tif (afterHead === false) {\n\t\t\t\t//lerp color handling\n\t\t\t\tlet colorRegionLength = (headLimitPoint - xLeftEnd) / 6;\n\t\t\t\tlet lerpProgressFactor = (100 / colorRegionLength) / 100;\n\n\t\t\t\t/*if (currentX <= xLeftEnd + colorRegionLength) {\n\t\t\t\t\tstroke(lerpColor(redPalette[0], redPalette[1], lerpProgress));\n\t\t\t\t} else if (currentX <= xLeftEnd + 2 * colorRegionLength) {\n\t\t\t\t\tstroke(lerpColor(redPalette[1], redPalette[2], lerpProgress));\n\t\t\t\t} else if (currentX <= xLeftEnd + 3 * colorRegionLength) {\n\t\t\t\t\tstroke(lerpColor(redPalette[2], redPalette[3], lerpProgress));\n\t\t\t\t} else if (currentX <= xLeftEnd + 4 * colorRegionLength) {\n\t\t\t\t\tstroke(lerpColor(redPalette[3], redPalette[2], lerpProgress));\n\t\t\t\t} else if (currentX <= xLeftEnd + 5 * colorRegionLength) {\n\t\t\t\t\tstroke(lerpColor(redPalette[2], redPalette[1], lerpProgress));\n\t\t\t\t} else if (currentX <= xLeftEnd + 6 * colorRegionLength) {\n\t\t\t\t\tstroke(lerpColor(redPalette[1], redPalette[0], lerpProgress));\n\t\t\t\t} else {\n\t\t\t\t\tafterHead = true;\n\t\t\t\t\tlerpProgress = 0;\n\t\t\t\t}*/\n\n\t\t\t\tlerpProgress += lerpProgressFactor;\n\t\t\t\tif (lerpProgress > 1) {\n\t\t\t\t\tlerpProgress = 0;\n\t\t\t\t\tcurrentTargetColor++;\n\t\t\t\t\tpreviousColor = currentColor;\n\t\t\t\t\tcurrentColor = redPalette[colorList[currentTargetColor]];\n\t\t\t\t} else {\n\t\t\t\t\tstroke(lerpColor(previousColor, currentColor, lerpProgress));\n\t\t\t\t}\n\n\t\t\t\tif (currentX > xLeftEnd + 6 * colorRegionLength){ // moving after head\n\t\t\t\t\tafterHead = true;\n\t\t\t\t\tlerpProgress = 0;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlet colorRegionLength = (xRightEnd - headLimitPoint) / 3;\n\t\t\t\tlet lerpProgressFactor = (100 / colorRegionLength) / 100;\n\t\t\t\tif (currentX <= headLimitPoint + colorRegionLength) {\n\t\t\t\t\tstroke(lerpColor(redPalette[0], redPalette[1], lerpProgress));\n\t\t\t\t} else if (currentX < headLimitPoint + 2 * colorRegionLength) {\n\t\t\t\t\tstroke(lerpColor(redPalette[1], backgroundBluesPalette[1], lerpProgress));\n\t\t\t\t} else if (currentX < headLimitPoint + 3 * colorRegionLength) {\n\t\t\t\t\tstroke(lerpColor(backgroundBluesPalette[1], backgroundBluesPalette[0], lerpProgress));\n\t\t\t\t} else {\n\t\t\t\t\tstroke(backgroundBluesPalette[0]);\n\t\t\t\t}\n\n\t\t\t\tlerpProgress = lerpProgress + lerpProgressFactor;\n\t\t\t\tif (lerpProgress >= 1) {\n\t\t\t\t\tlerpProgress = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// music: use soundwave\n\t\t\tlet amplitudeMultiplier = getMusicAmplitudeMultiplierForXPosition(currentX);\n\t\t\tlet waveCoordinate = soundWave[counter];\n\t\t\tcurrentY = (Math.trunc(waveCoordinate * 100) * amplitudeMultiplier) + yAltitude;\n\t\t\tcurrentX++;\n\t\t} else {\n\t\t\t// no music: random noise\n\t\t\tif (currentX < 1050) {\n\t\t\t\tstroke(redPalette[0]);\n\t\t\t} else {\n\t\t\t\tstroke(backgroundBluesPalette[0]);\n\t\t\t}\n\t\t\tlet noiseFactor = noise(getRandomInt(10, 210) + frameCount);\n\t\t\tcurrentY = Math.trunc(noiseFactor * 100) + (yAltitude - 50);\n\t\t\tcurrentX = currentX + 10;\n\t\t}\n\n\t\tline(previousX, previousY, currentX, currentY);\n\n\t\tpreviousX = currentX;\n\t\tpreviousY = currentY;\n\t\tcounter++;\n\t}\n\n\t// close moving line\n\tstroke(backgroundBluesPalette[0]);\n\tline(previousX, previousY, Math.min(currentX, xRightEnd), yAltitude);\n}",
"function updateVisuals() {\n //add a light flicker to past command text\n let lines = document.getElementsByClassName('line');\n for (i=0; i < lines.length; i++) {\n if (Math.random() > 0.85) {\n let newOpacity = 1 - (Math.random() / 6);\n lines[i].style.opacity = newOpacity;\n }\n }\n //toggle the cursor char every interval\n cursorState = !cursorState;\n //and also the page title because why not\n if (cursorState) {\n document.title = document.title.slice(0, document.title.length-1);\n } else {\n document.title += '_';\n } \n updateLine();\n}",
"function draw() {\n let sequence = [];\n let n = i;\n do {\n sequence.push(n);\n n = collatz(n);\n } while (n != 1);\n sequence.push(1);\n sequence.reverse();\n\n\n //Visualize the reversed List\n let len = 10; // 10\n let angle = PI/randomGaussian(3, gaussian);; // PI/3\n resetMatrix(); // without it, it could be pretty cool\n translate(width/2, height/2);//width/2\n\n for (let j = 0; j < sequence.length; j++) {\n let value = sequence[j];\n\n if (value % 2 == 0) {\n rotate(angle);\n } else {\n rotate(-angle);\n }\n stroke(random(200,250), random(100, 255), random(100, 150), 50); // 50 alpha normally\n\n line(0, 0, 0, -len);\n translate(0, -len);\n\n }\n i += random(10);\n if (i > loops) {\n i = 1;\n //noLoop();\n background(0);\n gaussian = .01;\n }\n}",
"noise (width, height) {\n let data = helpers.mnArray(width, height);\n this.source = data.map((col, x) => {\n return col.map((elem, y) => {\n return this.random.frac(x, y);\n });\n });\n }",
"function draw(params)\n{\n for (var i = 0; i < params.nb_recursions; i++) {\n\n if(params.noise_type == 'linear')\n {\n array[i] = interp_noise(width, height, Math.ceil(params.lattice_size/(i+1)), bilin_mix);\n }\n else if (params.noise_type == 'cubic')\n {\n array[i] = interp_noise(width, height, Math.ceil(params.lattice_size/(i+1)), cubic_mix);\n }\n else if(params.noise_type == 'perlin')\n {\n array[i] = perlin_noise(width, height, Math.ceil(params.lattice_size/(i+1)));\n }\n else if(params.noise_type == 'improved_perlin')\n {\n array[i] = improved_perlin_noise(width, height, Math.ceil(params.lattice_size/(i+1)));\n }\n else if(params.noise_type == 'voronoi')\n {\n array[i] = voronoi_noise(width, height, Math.ceil(params.lattice_size/(i+1)));\n }\n else if(params.noise_type == 'wood')\n {\n array[i] = improved_perlin_noise(width, height, Math.ceil(params.lattice_size/(i+1)));\n }\n else if(params.noise_type == 'diamond-square')\n {\n array[i] = diamond_square(width, height, params.roughness);\n }\n }\n\n if(params.noise_type == 'wood'){\n for (var x = 0; x < width; x++) {\n for (var y = 0; y < height; y++) {\n var noise_value = 0\n for (var i = 0; i < params.nb_recursions; i++) {\n noise_value += 1/(i+1)*(array[i][x][y]*2-1);\n }\n var wood_value = Math.sin(Math.sqrt((x-width/2)*(x-width/2)+(y-height/2)*(y-height/2))/5+noise_value*8 )*0.5+0.5;\n var idx = (y*width+x)*4;\n var light_wood_colour = [0xb6, 0x9b, 0x4c];\n var dark_wood_colour = [0x82, 0x52, 0x01];\n imagedata.data[idx] = cubic_mix(light_wood_colour[0], dark_wood_colour[0], wood_value); //red\n imagedata.data[idx+1] = cubic_mix(light_wood_colour[1], dark_wood_colour[1], wood_value); //green\n imagedata.data[idx+2] = cubic_mix(light_wood_colour[2], dark_wood_colour[2], wood_value); //blue\n imagedata.data[idx+3] = 255; //alpha\n }\n }\n }\n else{ //simply draw the noise\n for (var x = 0; x < width; x++) {\n for (var y = 0; y < height; y++) {\n var value = 0;\n for (var i = 0; i < params.nb_recursions; i++) {\n value += 1/(i+1)*(array[i][x][y]*2-1);\n }\n value = value*0.5+0.5;\n var idx = (y*width+x)*4;\n imagedata.data[idx] = 255*value; //red\n imagedata.data[idx+1] = 255*value; //green\n imagedata.data[idx+2] = 255*value; //blue\n imagedata.data[idx+3] = 255; //alpha\n }\n }\n }\n\n ctx.putImageData(imagedata, 0, 0);\n}",
"function vizualizer() {\n // var vol = amply.getLevel(); // Receiving the volume of the song\n var spectrum = fft.analyze(); // Getting the audio frequensies from the song\n\n noStroke();\n translate(width/2, height/3+50); // The placement for the vizualizer\n\n // Originally, it spun when playing, which is what this line of code was for\n //rotate(n * 0.5);\n\n for (var i = 0; i < spectrum.length; i++) {\n var angle = map(i, 0, spectrum.length, 0, 1138); // Places the lines around the vizualizer's center\n var amp = spectrum[i];\n var r = map(amp, 0, 100, 0, 150);\n var x = r * cos(angle);\n var y = r * sin(angle);\n\n var hue = sin(start + i * 1);\n hue = map(hue, -1, 1, 10, 360); // The rotating colors\n //ellipse(100, 100, 10, 10);\n\n stroke(hue, 255, 100); // The straight lines' color coming from the vizualizer's center\n strokeWeight(6);\n line(0, 0, x, y);\n\n }\n\n fill(0);\n noStroke();\n\n start -= 0.5; // The speed of the color rotation is static to simulate the \"loading\"\n\n // Originally, it spun when playing, which is what this line of code was for\n //n += 0.5;\n}",
"handleWrapping() {\n // When the snow goes off screen, more will come down\n if (this.y > height) {\n this.x = random(0, width);\n this.y -= height;\n }\n }",
"function nextSong() {\n // Set up drawing state.\n background(50);\n textSize(32);\n fill(255);\n\n // Pick a seed.\n var songSeed = floor(random(100000));\n\n // Pass seed to song generator.\n var song = generateSong(songSeed);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rescales the paper. Parameters: amount: The ratio between the rescaled and current paper (e.g. '2.0' makes everything appear two times bigger) x, y: Coordinates of the point that shall remain stable, given by pixel coordinates relative to the top left corner of the viewport. | function paper_scale(amount, x, y) {
var scale = V(paper.viewport).scale().sx;
var newScale = scale*amount;
paper.scale(newScale, newScale);
var ox = paper.options.origin.x;
var oy = paper.options.origin.y;
var dx = (newScale - scale)/scale * (x - ox);
var dy = (newScale - scale)/scale * (y - oy);
paper.setOrigin(ox - dx, oy - dy);
} | [
"scale(scaleAmount) {\n\n this.w *= scaleAmount;\n this.h *= scaleAmount;\n this.x = this.center.x - this.w / 2;\n this.y = this.center.y - this.h / 2;\n\n this.calculateVectorsAndSetShape();\n this.resetFixture();\n }",
"function zoom(amount) {\n\tif (blockSize + amount <= 0)\n\t\treturn;\n\n\tblockSize += amount;\n\tresetDimensions();\n\tresizeBlockArray(false);\n\tdrawBlocks();\n\tdrawGrid();\n}",
"changeZoom(amount){\n\n this.zoomFactor += amount;\n this.zoomFactor = clampNumber(this.zoomFactor, this.minZoomFactor, this.maxZoomFactor);\n }",
"function changeResin(amount) {\n if (amount >= 0) {\n currentResin = Math.min(amount, 160);\n update();\n }\n}",
"scale(_factor) {\n this.x *= _factor;\n this.y *= _factor;\n }",
"scaleRelativeToBody(multiplyAmount) {\n this.x *= multiplyAmount;\n this.y *= multiplyAmount;\n this.w *= multiplyAmount;\n this.h *= multiplyAmount;\n this.calculateVectorsAndSetShape();\n this.resetFixture();\n }",
"function onScale(factor, ref) {\n var olds = transformation.s;\n transformation.s *= factor;\n var news = transformation.s;\n transformation.t.x += ref.x * (olds-news);\n transformation.t.y += ref.y * (olds-news);\n repaint();\n}",
"function transcale (x, y, sc) {\n drawspace.css('margin-top', topHeight);\n drawspace.css('transform', \"scale(\" + sc + \")\");\n if (sc === 0.5) {\n $('div[data-role=\"main\"]').height(2490);\n $('div[data-role=\"main\"]').width(2490);\n } else {\n $('div[data-role=\"main\"]').height(4980);\n $('div[data-role=\"main\"]').width(4980);\n }\n // document.querySelector('meta[name=viewport]').setAttribute('content', \"width=device-width, height=device-height, initial-scale=1, user-scalable=no\");\n $('body').scrollLeft(x);\n $('body').scrollTop(y);\n}",
"function scalePage(page, scaleFactor) {\r\n if (!page.isValid || scaleFactor === NaN) return;\r\n\r\n var graphics = page.allGraphics;\r\n for (var i = 0; i < graphics.length; i++) {\r\n var gr = graphics[i];\r\n if (isFramePastMargin(page, gr.parent)) {\r\n gr.absoluteHorizontalScale = scaleFactor;\r\n gr.absoluteVerticalScale = scaleFactor;\r\n }\r\n }\r\n}",
"function pult_scaling (direction) \n\t{\n\t\tvar pos = \n\t\t{\n\t\t\tx: pano.pos.px, \n\t\t\ty: pano.pos.py, \n\t\t};\n\t\tif (direction == 'p') delta = 1;\n\t\tif (direction == 'm') delta = -1;\n\t\tscaling(delta, pos);\n\t}",
"function scaleBy(point, value) {\r\n point.x *= value;\r\n point.y *= value;\r\n }",
"_scale(degree, point) {\n const paper = this._paper;\n point = point || g.rect(paper.viewport.getBoundingClientRect()).center();\n const delta = Math.pow(this._mult, degree);\n this._currDeg += degree;\n\n const scale = Math.pow(this._mult, this._currDeg);\n const oldX = paper.options.origin.x;\n const oldY = paper.options.origin.y;\n const paperPoint = convertToLocal(paper, point);\n paper.setOrigin(0, 0);\n paper.scale(scale, scale);\n paper.setOrigin(((oldX - paperPoint.x) * delta) + paperPoint.x,\n ((oldY - paperPoint.y) * delta) + paperPoint.y);\n }",
"scaleInPlace(factor) {\n this.fontInfo.size = SmoScoreText.fontPointSize(this.fontInfo.size) * factor;\n }",
"function transcale (x, y, sc) {\n drawspace.css('margin-top', topHeight);\n drawspace.css('transform', \"scale(\" + sc + \")\");\n if (sc === 0.5) {\n $('div[data-role=\"main\"]').height(2490);\n $('div[data-role=\"main\"]').width(2490);\n document.querySelector('meta[name=viewport]').setAttribute('content', \"width=device-width, height=device-height, initial-scale=1, user-scalable=no\");\n $('body').scrollLeft(x);\n $('body').scrollTop(y);\n } else {\n $('div[data-role=\"main\"]').height(4980);\n $('div[data-role=\"main\"]').width(4980);\n document.querySelector('meta[name=viewport]').setAttribute('content', \"width=device-width, height=device-height, initial-scale=1, user-scalable=no\");\n $('body').scrollLeft(x);\n $('body').scrollTop(y);\n }\n}",
"fitToScreen() {\n var rect = this.getRectofPoints(this.points);\n var rateX = 0, rateY = 0;\n this.wx = 0;\n this.wy = 0;\n rateX = (this.canvas.width-20)/(rect.xMax-rect.xMin);\n rateY = (this.canvas.height-20)/(rect.yMax-rect.yMin);\n if(rateX > rateY) {\n this.scale = 1 * rateY;\n }\n else {\n this.scale = 1 * rateX;\n }\n this.wx = (this.zoomedX(rect.xMin)-(this.canvas.width-this.zoomedX(rect.xMax)+this.zoomedX(rect.xMin))/2)/this.scale; // world zoom origin\n this.wy = (this.zoomedY(rect.yMin)-(this.canvas.height-this.zoomedY(rect.yMax)+this.zoomedY(rect.yMin))/2)/this.scale;\n this.drawLine();\n }",
"function scaleBy(point, value) {\n point.x *= value;\n point.y *= value;\n }",
"function rescale() {\n console.info(\"zqh: Rescaling...\");\n var cparent = $(\"canvas\").parent();\n $(\"canvas\").width(cparent.width());\n $(\"canvas\").height(cparent.width() * 0.8);\n }",
"scaleRow(row, amount)\r\n {\r\n for (var c = 0; c < this.n; c++)\r\n this.matrix[row][c] = math.multiply(this.matrix[row][c], amount);\r\n }",
"updateScale() {\n this.scale = this.getDrawingScale();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds code to run in the machine right after the docker daemon has been started. | _setAfterDaemonStarted () {
const code = this._opts.AfterDaemonStarted;
if (!code || !code.length) {
return;
}
this
._getLaunchConfigCode()
.push(code.join(''));
} | [
"function AfterSelfExec() {\n}",
"async function setupDocker(name = 'Docker') {}",
"function setupDockerSwarm() {\n\n const doDockerSwarmSetup = require('./setup_docker_swarm.js');\n doDockerSwarmSetup(lapi, linode_servers, ssh_connector, hosts_to_build, (err) => {\n if (err) {\n hardFail(err);\n }\n else {\n completedScript();\n }\n });\n\n }",
"function setDockerInformation () {\n if (window_reference && docker_list) {\n window_reference.webContents.send('docker_data', docker_list);\n }\n}",
"start(machineName) {\n if (!machineName) {\n machineName = this.configs['docker']['machineName'];\n }\n if (!this.hasMachine(machineName)) {\n console.warn(chalk\n .yellow('Docker machine doesn\\'t exist, creating machine.'));\n this.createMachine(machineName);\n }\n if (this.isMachineRunning(machineName)) {\n console.warn(chalk.yellow('Docker machine already running.'), \n machineName);\n return;\n }\n try {\n execSync(`docker-machine start ${machineName}`, {\n stdio: 'inherit'\n });\n console.log(chalk.green('Success starting Docker machine.'), \n machineName);\n } catch(e) {\n console.error(chalk.red('Error starting Docker machine.'), \n machineName, e);\n }\n }",
"function initializeSwarm() {\n\twriteDockerCompose(_imagename, _ninstances, _ncpus, _memory, _ports);\n\n\tlet command = 'docker swarm init';\n\t// exec(command, err, stdout, stdin) {\n\t// \tif (err) {\n\t// \t\tconsole.log('An error occured executing ', command);\n\t// \t\tconsole.log(err);\n\t// \t}\n //\n\t// \tconsole.log('Swarm initialized');\n\t// \tgetSwarmCommandToken(stdout);\n\t// });\n}",
"afterLaunch() {}",
"async start () {\n await this.container.start();\n }",
"_addedHook() {}",
"function setContainerEvents() {\n containers.forEach((container) => {\n workingContainer(container);\n });\n}",
"createContainer() {\n if (document.getElementById('newcontainer-image').value == '')\n return;\n let options = {\n Image: document.getElementById('newcontainer-image').value,\n // Cmd: document.getElementById('newcontainer-cmd').value.split(' '),\n\n HostConfig: {}\n };\n if (document.getElementById('newcontainer-name').value != '') {\n options.name = document.getElementById('newcontainer-name').value;\n }\n if (document.getElementById('newcontainer-cmd').value != '')\n options.Cmd = document.getElementById('newcontainer-cmd').value.split(' ');\n if (document.getElementById('newcontainer-workdir').value != '')\n options.WorkingDir = document.getElementById('newcontainer-workdir').value;\n if (document.getElementById('newcontainer-ports').value != '') {\n let ports = document.getElementById('newcontainer-ports').value.split(',');\n let PortBindings = {};\n for (const port of ports) {\n let splitPorts = port.split(':')\n PortBindings[splitPorts[1] + '/tcp'] = [{ \"HostPort\": splitPorts[0] }];\n }\n options.HostConfig.PortBindings = PortBindings;\n }\n if (document.getElementById('newcontainer-autoremove').checked) {\n options.HostConfig.AutoRemove = true;\n }\n\n window.Lemonade.Mirror.send('docker-create', CookieManager.getCookie('loggedIn_user', undefined), CookieManager.getCookie('loggedIn_session', undefined), options,\n document.getElementById('newcontainer-autostart').checked, document.getElementById('newcontainer-groupcontainer').checked);\n\n }",
"function init() {\n\n copyFile( 'Dockerfile' )\n copyFile( '.dockerignore' )\n\n}",
"apply(compiler) {\n compiler.hooks.done.tap('Run Electron', (\n stats /* stats is passed as argument when done hook is tapped. */\n ) => {\n console.log('electronStarted: ', electronStarted)\n if (!electronStarted) {\n electronStarted = true;\n childProcess\n .spawn(electron, ['.'], { stdio: 'inherit' })\n .on('close', () => {\n process.exit(0);\n });\n }\n });\n }",
"function main() {\r\n startMicroservice()\r\n registerWithCommMgr()\r\n}",
"onBoot() {}",
"function ExecuteOnStartup() {\r\n\r\n}",
"afterNightSetup() {}",
"function main() {\n startMicroservice()\n registerWithCommMgr()\n}",
"async init() {\n this.runner = new Runner(this.containerId, {\n trexCount: this.trexCount,\n onRunning: this.handleRunning.bind(this),\n title: this.title,\n level: this.level\n });\n this.runner.on('running', this.handleRunning.bind(this));\n this.runner.on('reset', this.handleReset.bind(this));\n this.runner.on('crash', this.handleCrash.bind(this));\n this.runner.on('gameover', this.handleGameOver.bind(this));\n await this.runner.init();\n this.runner.restart();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start the recursive build process with a clone of the points array and null points filtered out (3873) | function startRecursive() {
var points = grep(series.points || [], function (point) { // #4390
return point.y !== null;
});
series.kdTree = _kdtree(points, dimensions, dimensions);
} | [
"getEmptyBorderPoints() {\n\n let empties = [];\n let emptiesPlayer0 = [];\n let emptiesPlayer1 = [];\n let piecesVisited = [];\n this.cachedPiecePointsTouchingEmpty = {};\n this.cachedPiecesThatArentBridges = [];\n this.cachedPiecesThatAreBridges = [];\n\n if (this.pieces.length > 0) {\n // Just need any piece to start from (but not the comment below)\n let seedPieceString = this.pieces[0];\n\n // Make sure we start with the TOP piece at this point, since this algorithm should only visit top pieces.\n seedPieceString = this.getTopPieceAt(Piece.getPointString(seedPieceString));\n\n // console.log(\"Starting algorithm with these pieces:\");\n // console.log(this.pieces);\n\n this.getEmptyBorderPointsKernel(seedPieceString, empties, emptiesPlayer0,\n emptiesPlayer1, piecesVisited, Hive.PRACTICALLY_INFINITY);\n }\n\n // Make sure any pieces flagged as definite bridges are removed from the cached of piece's that aren't\n // console.log(\"Finally, removing these definite bridge pieces\");\n // console.log(this.cachedPiecesThatAreBridges);\n for (let i = this.cachedPiecesThatAreBridges.length - 1; i >= 0; i--) {\n this.listDelete(this.cachedPiecesThatArentBridges, this.cachedPiecesThatAreBridges[i]);\n }\n\n // console.log(\"Ending algorithm with these non-bridges\");\n // console.log(this.cachedPiecesThatArentBridges);\n\n return [empties, emptiesPlayer0, emptiesPlayer1, piecesVisited.length];\n\n }",
"function startRecursive() {\n\t\t\t\tvar points = grep(series.points || [], function (point) { // #4390\n\t\t\t\t\treturn point.y !== null;\n\t\t\t\t});\n\n\t\t\t\tseries.kdTree = _kdtree(points, dimensions, dimensions);\n\t\t\t}",
"function startRecursive() {\n\t\t\tvar points = grep(series.points || [], function (point) { // #4390\n\t\t\t\treturn point.y !== null;\n\t\t\t});\n\n\t\t\tseries.kdTree = _kdtree(points, dimensions, dimensions);\n\t\t}",
"function startRecursive() {\n\t\t\tseries.kdTree = _kdtree(series.points.slice(), dimensions, dimensions);\t\t\n\t\t}",
"function startRecursive() {\n series.kdTree = _kdtree(series.points.slice(), dimensions, dimensions);\n }",
"function buildTree(root, points) {\n for (var i = 0; i < points.length; i++) {\n var point = points[i];\n var leaf = findLeaf(point, root);\n leaf.children.push(point);\n\n if (leaf.children.length > 1) {\n var temp = leaf.children;\n leaf.children = [];\n divide(leaf);\n buildTree(leaf, temp);\n }\n }\n}",
"function grindObjectGrid(focusArray){\n //console.log(objectGrid);\n //console.log(focusArray);\n for(var y=0; y<15 ; y++){\n for(var x=0; x<17 ; x++){\n if( focusArray[y][x] != null && focusArray[y][x].exploding == false){\n var newBlock = new destructibleBlock(x,y);\n objectGrid[y][x] = newBlock;\n //console.log(newBlock);\n }\n }\n }\n}",
"merge() {\n\n\t\tconst children = this.children;\n\n\t\tlet i, l;\n\t\tlet child;\n\n\t\tif(children !== null) {\n\n\t\t\tthis.points = [];\n\t\t\tthis.data = [];\n\n\t\t\tfor(i = 0, l = children.length; i < l; ++i) {\n\n\t\t\t\tchild = children[i];\n\n\t\t\t\tif(child.points !== null) {\n\n\t\t\t\t\tthis.points.push(...child.points);\n\t\t\t\t\tthis.data.push(...child.data);\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tthis.children = null;\n\n\t\t}\n\n\t}",
"buildPrimalSpanningTree() {\n\t\t// TODO\n\t\t// initialize all vertices\n\t\tfor (let v of this.mesh.vertices) {\n\t\t\tthis.vertexParent[v] = v;\n\t\t}\n\n\t\t// build spanning tree\n\t\tlet root = this.mesh.vertices[0];\n\t\tlet queue = [root];\n\t\twhile (queue.length > 0) {\n\t\t\tlet u = queue.shift();\n\n\t\t\tfor (let v of u.adjacentVertices()) {\n\t\t\t\tif (this.vertexParent[v] === v && v !== root) {\n\t\t\t\t\tthis.vertexParent[v] = u;\n\t\t\t\t\tqueue.push(v);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"_generate(allRoadPoints, seedPoints) {\n class Vine {\n constructor( seedPOI, potentialPoints ) {\n this.isGrowing = true\n this.seed = seedPOI\n this.lastBud = seedPOI\n this.livingNodes = [seedPOI]\n\n // nodes the vine can grow into (remove seed since we've already started there)\n this.potentialNodes = potentialPoints.filter((e)=> { \n return e != seedPOI })\n }\n }\n\n let vines = []\n // use each capital as a starting seed\n for (let i=0; i< seedPoints.length; i++) {\n vines.push(new Vine(seedPoints[i], allRoadPoints))\n }\n\n let numGrowing = vines.length\n while (numGrowing > 0) {\n numGrowing = 0\n for (let v=0; v< vines.length; v++) {\n let vine = vines[v]\n if (!vine.isGrowing) {\n continue\n } else {\n numGrowing += 1\n }\n\n // 0) if we have exhausted potential nodes, we are done\n if (vine.potentialNodes.length == 0) {\n // do this first in case config_findALLPoints is true and we looped without setting isGrowing = false\n vine.isGrowing = false\n continue\n }\n\n // 1) find closest city to vine.lastBud\n let i = this._getPointClosest(vine.potentialNodes, vine.lastBud)\n let growTarget = vine.potentialNodes.splice(i, 1)[0]\n // 2) find closest existing node to new node\n let f = this._getPointClosest(vine.livingNodes, growTarget)\n let fromTarget = vine.livingNodes[f]\n\n if (fromTarget == growTarget) {\n if (!this.config_findALLPoints) {\n vine.isGrowing = false\n }\n \n continue\n }\n\n // 2) if road doesnt already exist, create it\n let road = this._createRoad(fromTarget, growTarget)\n if (this.roads.includes(road)) {\n vine.isGrowing = false\n continue\n } \n\n // and add it to the vine\n this.roads.push(road)\n vine.lastBud = growTarget\n vine.livingNodes.push(growTarget)\n \n }\n }\n }",
"buildSourceFeatures(){\n let points = [...this.state.points]\n // BEGIN SOURCE PARENT CODE\n // parent geoJSON\n var geojsonObjectParentSource = {\n 'type': 'FeatureCollection',\n 'features': [ ]\n };\n var styleFunctionParentSource = this.buildStyle(\n this.props.sourceFeaturesParentStyles.fillColor, \n this.props.sourceFeaturesParentStyles.borderColor, \n this.props.sourceFeaturesParentStyles.borderWidth,\n 4,\n true\n );\n\n // creating the parent feature\n let featureObjParentSource = this.buildFeature(\n this.props.sourceFeaturesParent.lat, \n this.props.sourceFeaturesParent.lng,\n this.props.sourceFeaturesParentStyles.label,\n this.props.sourceFeaturesParent.deviceName,\n false\n )\n points.push([this.props.sourceFeaturesParent.lng, this.props.sourceFeaturesParent.lat])\n geojsonObjectParentSource.features.push(featureObjParentSource)\n\n // building the vector source with geojson and feature\n var vectorSourceParentSource = new VectorSource({\n features: (new GeoJSON()).readFeatures(geojsonObjectParentSource)\n });\n // creating a vector layer with the source and style\n var vectorLayerParentSource = new VectorLayer({\n source: vectorSourceParentSource,\n style: styleFunctionParentSource,\n key: \"parentSource\"\n });\n\n // BEGIN SOURCE CHILD CODE\n var geojsonObjectChildrenSource = {\n 'type': 'FeatureCollection',\n 'features': [ ]\n };\n \n var styleFunctionChildrenSource = this.buildStyle(\n this.props.sourceFeaturesChildrenStyles.fillColor, \n this.props.sourceFeaturesChildrenStyles.borderColor, \n this.props.sourceFeaturesChildrenStyles.borderWidth,\n 4,\n true\n );\n \n // creating features for the geojson\n this.props.sourceFeaturesChildren.forEach( feature => {\n let featureObj = this.buildFeature(\n feature.lat, \n feature.lng, \n this.props.sourceFeaturesChildrenStyles.label,\n feature.deviceName,\n true,\n this.props.sourceFeaturesParent.deviceName\n );\n if(this.state.thoroughTest === true){\n let featureObjDupe = this.buildFeature(\n feature.lat +0.00007, \n feature.lng, \n this.props.sourceFeaturesChildrenStyles.label+\"_d\",\n feature.deviceName+\"_d\",\n true,\n this.props.sourceFeaturesParent.deviceName\n );\n geojsonObjectChildrenSource.features.push(featureObjDupe)\n }\n geojsonObjectChildrenSource.features.push(featureObj)\n })\n // creating the source with the features and geojson\n var vectorSourceChildrenSource = new VectorSource({\n features: (new GeoJSON()).readFeatures(geojsonObjectChildrenSource)\n });\n // creating a vector layer with the source and style\n var vectorLayerChildrenSource = new VectorLayer({\n source: vectorSourceChildrenSource,\n style: styleFunctionChildrenSource,\n key: \"childSource\"\n });\n // returning an object for both child and parent layers to be accessed via\n let tmpParentStyle = {\n deviceName : this.props.sourceFeaturesParent.deviceName,\n borderColor : this.props.sourceFeaturesChildrenStyles.borderColor\n }\n return {parent: vectorLayerParentSource, child:vectorLayerChildrenSource, points:points, parentForSwap: tmpParentStyle}\n }",
"function buildsControlPoints()\n {\n // control points\n var ctrlPts = dr.ctrlPts;\n for (var i=0, len=sconf.ctrlPtXYs_js.length; i < len; i++) {\n\t dr.ctrlPts.push( constructCtrlPt( i ) );\n }\n }",
"_rebuildIndex() {\n this._wp = whichPolygon({ features: [...this._resolved.values()] });\n }",
"function rebuildIndex() {\n _wp = whichPolygon({ features: Object.values(_resolvedFeatures) });\n }",
"function closestUtil(points, length){\n console.log(points);\n\n //when points in the array points is less then 3 brute force distance calculations are made\n if(length <= 3){\n console.log(\"less than or equal to 3\");\n return bruteForce(points,points.length);\n }\n\n //getting mid point of array for creating tree\n mid = Math.round(length/2);\n middlePoint = points[mid];\n\n console.log(\"mid\",mid);\n console.log(\"dL\",points.slice(0,mid));\n console.log(\"dR\",points.slice(mid,length));\n\n //creating two new arrays split at the midpoints of the points array\n let dlArr = points.slice(0,mid);\n let dRArr = points.slice(mid,length)\n\n //getting the closest pair amoungst the left and right child of the current node \n let dL = closestUtil(dlArr,dlArr.length);\n let dR = closestUtil(dRArr,dRArr.length);\n\n console.log(\"dLMin\",dL);\n console.log(\"dRMin\",dR);\n\n //the pair of points with the closest distance\n let bestD = minimum(dL[0],dR[0]);\n\n let closest = null;\n \n if(bestD == dL[0]){\n closest = dL;\n }else{\n closest = dR;\n }\n\n strip = new Array(length);\n let j = 0;\n\n //getting all points that are closer to the midpoint line then the distance of the best distance\n for(var i = 0;i < length;i++){\n if(Math.abs(points[i].x - middlePoint.x) < bestD){\n strip[j] = points[i],\n j++;\n }\n }\n\n //returns closest point passing in the best distance, and the strip array, and the size of it.\n return minimum(bestD, stripClosest(strip,closest,j));\n}",
"initNeighbors() {\n this.hashmap = new HashPoints(this.pieces);\n this.pieces.forEach((row, i) => {\n row.forEach((piece, j) => {\n //if (piece instanceof Dock) piece.calcDir(j, i, this);\n this.findNeighbors(i, j);\n })\n });\n }",
"drawWaypoints() {\n Object.keys(this.grid).forEach((x) => {\n Object.keys(this.grid[x]).forEach((y) => {\n this.grid[x][y] = this.grid[x][y].filter((aWaypoint) => {\n if (!aWaypoint.isDestroyed) {\n this.drawWaypoint(aWaypoint);\n return true;\n }\n return false;\n });\n });\n });\n }",
"generate_coordinates(points) {\n // new array\n var new_array = [];\n for (let index = 0; index < points.length; index++) {\n new_array.push( points[index].coordinates.slice() ); \n }\n // return new array\n return new_array;\n }",
"function prepForPath(points){\n let arr = points.slice();\n return arr.push(arr[arr.length - 1]);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
helper for generating default HTML | function defaultHtml (incomingData) {
var data = assign({
charset: 'utf-8',
metaViewport: true,
html: '',
relative: false
}, incomingData)
var sep = data.relative ? '' : '/'
var result = ['<!doctype html>']
var add = function () {
result.push.apply(result, arguments)
}
add('<head>')
add('<meta charset="' + data.charset + '"/>')
if (data.metaViewport !== false) {
add('<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"/>')
}
if (data.metaTags) {
for (var key in data.metaTags) {
add('<meta name="' + key + '" content="' + data.metaTags[key] + '"/>')
}
}
if (data.title) {
add('<title>' + data.title + '</title>')
}
if (data.css) {
add('<link rel="stylesheet" href="' + sep + data.css + '"/>')
}
if (data.head) {
add(data.head)
}
add('</head>')
add('<body>')
add('<div id="root">')
add('</div>')
add('</body>')
add('<script src="' + sep + data.main + '"></script>')
return result.join('')
} | [
"function generateAndAppendHTML() {\n\n }",
"function buildHTML() {\r\n\t\treturn;\r\n\t}",
"get markup() {}",
"function defaultTemplate(context) {\n function el(name, attrs, children) {\n var element = document.createElement(name);\n Object.keys(attrs).forEach(function(attr) {\n element.setAttribute(attr, attrs[attr]);\n });\n (children || []).forEach(function(child) {\n if (typeof(child) == \"undefined\")\n child = \"undefined\";\n if (typeof(child) == \"string\") {\n var temp = document.createElement(\"div\");\n temp.innerHTML = child;\n for (var i = 0; i < temp.childNodes.length; i++)\n element.appendChild(temp.childNodes[i]);\n } else\n element.appendChild(child);\n });\n return element;\n }\n\n return el(\"div\", {}, [\n el(\"div\", {id: \"container\"}, [\n el(\"div\", {id: \"background\"}),\n el(\"table\", {cellpadding: 0, cellspacing: 0}, [\n el(\"thead\", {}, [\n el(\"tr\", {}, [\n el(\"th\", {\"class\": \"docs\"}, [el(\"h1\", {}, [context.title])]),\n el(\"th\", {\"class\": \"code\"})\n ])\n ]),\n el(\"tbody\", {}, context.sections.map(function(section, i) {\n return el(\"tr\", {id: \"section-\" + (i+1)}, [\n el(\"td\", {\"class\": \"docs\"}, [\n el(\"div\", {\"class\": \"pilwrap\"}, [\n el(\"a\", {\n \"class\": \"pilcrow\",\n \"href\": \"#section-\" + (i+1)\n }, [\"¶\"])\n ]),\n section.docsHtml\n ]),\n el(\"td\", {\"class\": \"code\"}, [section.codeHtml])\n ]);\n }))\n ])\n ])\n ]).innerHTML;\n}",
"function HtmlGenerator() {\n\t\tthis.resultValues = ['Not Tested','Not Testable','Not Applicable','Not OK','OK'];\n\t\tthis.resultColors = ['darkorange','yellow','violet','red','limegreen']\n\t\tthis.selectValues = ['No','Yes'];\n\t\tthis.responsibility = ['NGE-Tunisia','NGE-China'];\n }",
"function HTMLGen () {\n this.p = function(s){return '<p>'+s+'</p>';}\n this.div = function(s){return '<div>'+s+'</div>';}\n this.b = function(s){return '<b>'+s+'</b>';}\n this.a = function(s){return '<a>'+s+'</a>';}\n this.body = function(s){return '<body>'+s+'</body>';}\n this.span = function(s){return '<span>'+s+'</span>';}\n this.title = function(s){return '<title>'+s+'</title>';}\n this.comment = function(s){return '<!--'+s+'-->';}\n }",
"get _HTML() {\n return `\n<a href=\"./nyhet.html#${this._nyhet.tittel}\">\n<div class=\"boks boks-link boks-horisontal\">\n <div class=\"boksetekst\">\n <header>\n <h2 class=\"boks-overskrift\">${this._nyhet.tittel}</h2>\n <h3 class=\"boks-underoverskrift\">Dato publisert: <time datetime=\"${this._dato.toISOString()}\" >${this._dato.toLocaleDateString()}</time></h3>\n </header>\n <p>${this._tekst}</p>\n </div>\n <div class=\"boksebilde nyhetsbilde\">\n <img src=\"${this._nyhet.bilde}\" alt=\"${this._nyhet.tittel}\">\n </div>\n</div>\n</a>`;\n }",
"renderHTML() {\n \n }",
"generateHTML() {\n let HTML = '';\n HTML += `<img class=\"headerLogo\" src=\"${this.logoPath + this.data.logoHeader}\" alt=\"${this.data.logoalt}\">`;\n return HTML;\n }",
"get template() {\n // You can use the html helper like so to render HTML:\n return html`<b>Hello, world!</b>`;\n }",
"toHtml() {\n return this.templEngine.renderMain(this.response);\n }",
"function generateHTML(node) {\n \n if (node.name === 'h1') {\n\n html = h1(lib, node)\n\n }\n else if (node.name === 'h2') {\n\n html = h2(lib, node)\n\n } else if (node.name === 'div') {\n\n html = div(lib, node)\n\n } else if (node.name === 'a') {\n\n html = a(lib, node)\n\n } else {\n\n html = '<' + node.name + ' not-yet-supported/>'\n }\n\n debug('generate <%s> --> %s', node.name, html)\n\n return html\n}",
"get miniTemplate() {\n return html` <div id=\"container\">${super.toolbarTemplate}</div> `;\n }",
"function generateHTML(node) {\n\n if (node.name === 'h4') {\n\n html = h4(lib, node)\n\n } else if (node.name === 'h5') {\n\n html = h5(lib, node)\n\n } else if (node.name === 'img') {\n\n html = img(lib, node)\n\n } else {\n\n html = '<' + node.name + ' not-yet-supported/>'\n }\n\n debug('generate <%s> --> %s', node.name, html)\n\n return html\n}",
"function widgetHTML() {\n var html = '';\n html += '<div class=\"widget-wrapper\">';\n html += ' <div class=\"widget-controls\"><h3 class=\"widget-header\">' + widget.title + '</h3></div>';\n //html += ' <div class=\"widget-header\">' + widget.title + '</div>';\n html += ' <div class=\"widget-content\">' + widget.content + '</div>';\n html += '</div>';\n return html;\n }",
"html() {\n console.log(\"Rendering\");\n const html = ` <h2>${this.name}</h2>\n <div class=\"image\"><img src=\"${this.imgSrc}\" alt=\"${this.imgAlt}\"></div>\n <div>\n <div>\n <h3>Distance</h3>\n <p>${this.distance}</p>\n </div>\n <div>\n <h3>Difficulty</h3>\n <p>${this.difficulty}</p>\n </div>\n </div>`;\n return html;\n }",
"function htmlWriter() {\n \n //writes the html for introduction\n htmlIntro();\n \n //creates the event functionality for example 1 and example 2\n exampleSetEvents();\n \n //writes the html for the game\n htmlGame();\n }",
"getHTML() {\n if (this.html) return this.html;\n else return this.html = [\n `<li class=\"stack\">`,\n `<a href=\"/archive/${this.fileName}\" class=\"title\">${this.title}</a>`,\n `<pre class=\"content\">${this.content}</pre>`,\n `<span class=\"footnote\">${new Date(this.date).toLocaleString('chinese', {timeZone: 'Asia/Shanghai',hour12:false})}</span>`,\n `</li>`\n ].join('');\n }",
"function helpTextHTMLGenerator ( name ) {\n\n if(name == \"ba\") {\n \n return \"<div class=\\\"text-one\\\"><p>Este é o menu de bedidas alcoólicas, aqui pode pedir bebidas para si ou para os seus amigos clicando em pedir. Poderá também, no entanto sugerir uma bebida clicando em sugerir.</p></div>\";\n \n } else if (name == \"bna\") {\n \n return \"<div class=\\\"text-one\\\"><p>Este é o menu de bedidas não alcoólicas, aqui pode pedir bebidas para si ou para os seus amigos clicando em pedir. Poderá também, no entanto sugerir uma bebida clicando em sugerir.</p></div>\";\n \n } else if (name == \"food\") {\n \n return \"<p><div class=\\\"text-one\\\">Este é o menu de snacks, aqui pode pedir snacks para si ou para os seus amigos clicando em pedir. Poderá também, no entanto sugerir um snack clicando em sugerir.</p></div>\";\n \n } else if (name == \"paint\") {\n \n return \"<div class=\\\"text-two\\\"><p>Acrescente um toque pessoal à mesa desenhando nesta. Para seleccionar uma cor use a paleta de cores que se encontra no canto inferior esquerdo e depois é só desenhar dentro do espaço disponibilizado. Se ficar satisfeito com o seu trabalho basta clicar em 'Guardar' e o seu fundo fica personalizado. Caso contrário poderá limpar a mesa no botão de 'Limpar'.</p></div>\";\n \n } else if (name == \"snooker\") {\n \n return \"<div class=\\\"text-one\\\"><p>Neste menu pode divertir-se sozinho ou com um amigo, basta apenas escolher se quer jogar em janela ou em ecran inteiro e o número de jogadores. Após escolher as hipóteses pretendidas seleccione 'Iniciar' e o seu jogo começará.</p></div>\";\n \n } else {\n \n var content = \"\";\n \n content += \"<table>\";\n content += \"<tr>\";\n content += \"<th><img class=\\\"help-icons\\\" src=\\\"../images/ba.png\\\" /></th>\";\n content += \"<th><p>Menu de bebidas alcoólicas</p></th>\";\n content += \"</tr>\";\n \n content += \"<tr>\";\n content += \"<th><img class=\\\"help-icons\\\" src=\\\"../images/bna.png\\\" /></th>\";\n content += \"<th><p>Menu de bebidas não alcoólicas</p></th>\";\n content += \"</tr>\";\n \n content += \"<tr>\";\n content += \"<th><img class=\\\"help-icons\\\" src=\\\"../images/food.png\\\" /></th>\";\n content += \"<th><p>Menu de snacks</p></th>\";\n content += \"</tr>\";\n \n content += \"<tr>\";\n content += \"<th><img class=\\\"help-icons\\\" src=\\\"../images/paint.png\\\" /></th>\";\n content += \"<th><p>Personalização do Fundo</p></th>\";\n content += \"</tr>\";\n \n content += \"<tr>\";\n content += \"<th><img class=\\\"help-icons\\\" src=\\\"../images/snooker.png\\\" /></th>\";\n content += \"<th><p>Snooker</p></th>\";\n content += \"</tr>\";\n content += \"</table>\";\n \n return content;\n \n }\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
isValidBoard returns true if the board satisfies sudoku constraints | isValidBoard() {
for (let row = 0; row < 9; row++) {
for (let column = 0; column < 9; column++) {
const cellValue = this.getCell(row, column);
const validValues = this.getValidPossibleValues(row, column, true);
if (cellValue && !validValues.has(cellValue)) {
return false;
}
}
}
return true;
} | [
"function IsValid(board) {\n\t\n\t// Check each column\n\tfor(var i = 0; i < board.length; i++) {\n\t\tvar column = board[i];\t\n\t\tvar table = {};\n\t\tfor(var j = 0; j < column.length; j++) {\n\t\t\tvar num = column[j];\n\t\t\t\n\t\t\tif(num != \" \" && table[num])\n\t\t\t\treturn false;\n\t\t\ttable[num] = 1;\n\t\t}\n\t}\n\t\t\n\t// Check each row\n\tfor(var j = 0; j < board.length; j++) {\n\t\ttable = {}\n\t\tfor(var i = 0; i < board.length; i++) {\n\t\t\tvar column = board[i];\n\t\t\tvar num = column[j];\n\t\t\n\t\t\tif(num != \" \" && table[num])\n\t\t\t\treturn false;\n\t\t\ttable[num] = 1;\n\t\t}\n\t}\t\n\t\n\ttable = {}\n\t// Check each square\n\t/*\n\tsquareSize = Math.floor(Math.sqrt(board.length));\n\tfor(var i = 1; i < 8; i += 3) {\n\t\tfor(var j = 1; j < 8 += 3) {\n\t\t\tif(!ValidGrid(board, i, j))\n\t\t\t\treturn false;\n\t\t}\n\t}\n\t*/\n\t\n\treturn true;\n}",
"isCompleteAndValid(board){\n if (!this.isFullBoard(board)) {\n this.lastMessage = \"The board contains one or more empty slots.\";\n return false;\n }\n\n return this.isValidSudoku(board);\n }",
"function boardValid () {\r\n if (typeof board !== 'object') {\r\n displayMessage('Remember to define your <code>board</code> object!')\r\n return false\r\n }\r\n if (!board.hasOwnProperty('cells')) {\r\n displayMessage('Your <code>board</code> object needs a property named <code>cells</code>.')\r\n return false\r\n }\r\n if (!isArray(board.cells)) {\r\n displayMessage('<code>board.cells</code> should be an array.')\r\n return false\r\n }\r\n if (board.cells.length === 0) {\r\n displayMessage(\"This board doesn\\'t seem to have any cells in it... try adding some elements to your array.\")\r\n return false\r\n }\r\n if (board.cells.length > 36) {\r\n displayMessage('The game can only cope with total number of cells up to 36! Try again with fewer cells.')\r\n return false\r\n }\r\n if (!isSquare(board.cells.length)) {\r\n displayMessage(\"<p>The number of cells in your object must be able to form a square: same number on each side:</p><pre>0 | 1\\n--+--\\n2 | 3\\n</pre><p>Some examples that pass this test are:<pre><code>cells: ['a', 'b', 'c', 'd']\\n\\ncells: [0, 1, 2, 3, 4, 5, 6, 7, 8]\\n\\ncells: [{}, {}, {}, {}]</code></pre>\")\r\n return false\r\n }\r\n return true\r\n}",
"function validateBoard() {\n var puzzleString = initPuzzle();\n sudokuSolver.solve(puzzleString, 1);\n }",
"function isValid(board, row, col) {\n let num = board[row][col];\n // check if row / column / block already has current number\n return !(\n boardHasNumberInSection(board, num, {\n rowStart: 0, rowEnd: 9, rowInc: 1,\n colStart: col, colEnd: col + 1, colInc: 1,\n }, {row, col})\n || boardHasNumberInSection(board, num, {\n rowStart: row, rowEnd: row + 1, rowInc: 1,\n colStart: 0, colEnd: 9, colInc: 1\n }, {row, col})\n || boardHasNumberInSection(board, num, {\n rowStart: Math.floor(row / 3) * 3, rowEnd: Math.floor(row / 3) * 3 + 3, rowInc: 1,\n colStart: Math.floor(col / 3) * 3, colEnd: Math.floor(col / 3) * 3 + 3, colInc: 1\n }, {row, col})\n );\n }",
"function isValid(board, row, col) {\n let num = board[row][col];\n // check if row / column / block already has current number\n return !(\n boardHasNumberInSection(board, num, {\n rowStart: 0, rowEnd: 9, rowInc: 1,\n colStart: col, colEnd: col + 1, colInc: 1,\n }, {row, col})\n || boardHasNumberInSection(board, num, {\n rowStart: row, rowEnd: row + 1, rowInc: 1,\n colStart: 0, colEnd: 9, colInc: 1\n }, {row, col})\n || boardHasNumberInSection(board, num, {\n rowStart: Math.floor(row / 3) * 3, rowEnd: Math.floor(row / 3) * 3 + 3, rowInc: 1,\n colStart: Math.floor(col / 3) * 3, colEnd: Math.floor(col / 3) * 3 + 3, colInc: 1\n }, {row, col})\n );\n }",
"isBoardSolved() {\n const diff = symmetricDifference(this.sudokuBoard.flat(), completedSet);\n return this.isValidBoard() && diff.size === 0;\n }",
"function isBoardValid (board) {\n let wrongLength = false\n for (let i = 0; i < 9; i++) {\n if (board[i].length != 9) {\n wrongLength = true\n break\n }\n }\n if (9 !== 9 || wrongLength) {\n return false\n }\n for (let row = 0; row < 9; row++) {\n for (let col = 0; col < 9; col++) {\n if (board[row][col] != EMPTY_SPOT) {\n if (!canPlace(row, col, board[row][col], board)) {\n return false\n }\n }\n }\n }\n return true\n}",
"checkIfValidCellOnBoard()\r\n {\r\n for (let i = 0; i < NumOfRows; i++)\r\n {\r\n for (let j = 0; j < NumOfCols; j++)\r\n {\r\n if(this.state.playBoard[i][j].isValid==='valid')\r\n {\r\n return true;\r\n }\r\n }\r\n }\r\n\r\n return false;\r\n\r\n }",
"isValidBoard(board, x, y, value) {\n for(let i=0 ; i<BOARD_SIZE ; i++) {\n if(board[x][i] === value) {\n return false;\n }\n if(board[i][y] === value) {\n return false;\n }\n }\n\n let squareBlockStartX = x - (x%3);\n let squareBlockStartY = y - (y%3);\n for(let i=squareBlockStartX ; i<squareBlockStartX+3 ; i++) {\n for(let j=squareBlockStartY ; j<squareBlockStartY+3 ; j++) {\n if(board[i][j] === value) {\n return false;\n }\n }\n }\n\n return true;\n }",
"function validSolution(board){\n\n let boardValue = true;\n\n const checkRows = (array) => {\n array.forEach(row => checkNumbers(row));\n }\n\n const checkColumns = (array) => {\n for (let i = 0; i < array.length; i++) {\n let colArray = [];\n array.forEach(row => {\n colArray.push(row[i]);\n });\n checkNumbers(colArray);\n }\n }\n\n const checkSubGrids = (array) => {\n const getSubGridIndexes = (num) => {\n if (num === 1) {\n return [0,1,2];\n } else if (num === 2) {\n return [3,4,5];\n } else {\n return [6,7,8];\n }\n }\n\n const getSubGridValues = (x, y, array) => {\n let values = [];\n\n rows = getSubGridIndexes(x);\n columns = getSubGridIndexes(y);\n\n rows.forEach(row => {\n columns.forEach(column => {\n values.push(board[row][column]);\n });\n });\n\n return values;\n };\n\n const squareSections = [1,2,3];\n return squareSections.every(squareX => {\n return squareSections.every(squareY => checkNumbers(getSubGridValues(squareX, squareY, array)));\n });\n }\n\n const checkNumbers = (array) => {\n let checkArray = [];\n array.forEach(num => {\n if (checkArray.indexOf(num) === -1 && num > 0 && num < 10) {\n checkArray.push(num);\n }\n });\n\n if (checkArray.length !== 9) {\n boardValue = false;\n }\n }\n\n checkRows(board);\n\n checkColumns(board)\n\n checkSubGrids(board);\n\n return boardValue;\n}",
"function sudokuIsValid(puzzle) {\n let checksArr = []\n for (let i = 0; i < 9; i++) {\n checksArr.push(getRow(puzzle, i))\n checksArr.push(getColumn(puzzle, i))\n }\n for (let i = 0; i < 3; i++) {\n for (let j = 0; j < 3; j++) {\n checksArr.push(getSection(puzzle, i, j))\n }\n }\n for (let i = 0; i < checksArr.length; i++) {\n if (!includes1to9(checksArr[i])) {\n return false\n }\n }\n return true\n}",
"isBoardValid(idx)\n {\n // board is complete, no move is valid.\n if (this.state.winner)\n return false;\n\n const lastRow = this.state.lastMoveLocation.row;\n const lastCol = this.state.lastMoveLocation.col;\n\n // Not initialised. Valid.\n if (lastRow === null || lastCol === null)\n {\n return true;\n }\n else\n {\n const currentBoard = lastRow * this.props.size + lastCol;\n if (this.state.localWinners[currentBoard])\n {\n // If local board is complete, next move\n // is available in any non-complete board.\n return this.state.localWinners[idx] === null;\n }\n else\n {\n return idx === currentBoard;\n }\n }\n }",
"function sudokuIsValid(puzzle){\n for(let i = 0; i < 9; i++){\n if(includes1to9(getRow(puzzle, i))===false){ //test every row\n return false;\n } \n if(includes1to9(getColumn(puzzle, i))===false){ //test every column\n return false;\n }\n }\n for(let i = 0; i<=2; i++){\n for(let j = 0; j<=2; j++){\n if(includes1to9(getSection(puzzle, i, j))===false){ //test every section\n return false;\n }\n }\n }\n return true;\n}",
"isValidSudoku(board) {\n // Set up lists of empty Sets for storing found values in the 'board'.\n const rows = []; // Rows in board\n const cols = []; // Columns in board\n const subBs = []; // Sub-boxes in board \n\n for (let x=0; x<9; ++x) {\n rows.push(new Set());\n cols.push(new Set());\n subBs.push(new Set());\n }\n \n // Iterate through all values in board and verify they meet constraints.\n for (let r=0; r<9; ++r) {\n for (let c=0; c<9; ++c) {\n let val = board[r][c];\n\n if (val==\".\") continue; // Skip over empty slots.\n \n if (rows[r].has(val)) {\n this.lastMessage = `Row ${r+1} has duplicate ${val}.`;\n return false;\n }\n\n rows[r].add(val);\n \n if (cols[c].has(val)) {\n this.lastMessage = `Column ${c+1} has duplicate ${val}.`;\n return false;\n }\n\n cols[c].add(val);\n \n let BoxNum =(Math.floor(r/3) * 3) + Math.floor(c/3);\n if (subBs[BoxNum].has(val)) {\n this.lastMessage = `Sub-Box ${BoxNum + 1} has duplicate ${val}.`;\n return false;\n }\n\n subBs[BoxNum].add(val);\n }\n }\n\n this.lastMessage = \"This board is valid.\";\n return true;\n }",
"function checkSudokuBoard() {\n\t\trows.forEach(function (row, rowindex, rowarray) {\n\t\t\tvar values = [];\n\t\t\tcolumns.forEach(function (column, columnindex, columnarray) {\n\t\t\t\t\n\t\t\t\tvar currentValue = board[row][column].getValue();\n\t\t\t\t\t\t\t\t\n\t\t\t\tif (currentValue) {\n\t\t\t\t\t// Check if a value is already included in the row\n\t\t\t\t\tif (values.indexOf(currentValue) !== -1) {\n\t\t\t\t\t\tthrow {\n\t\t\t\t\t\t\tname: \"ImpossibleBoardError\"\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvalues.push(currentValue);\n\t\t\t\t\t}\n\t\t\t\t} \n\t\t\t});\n\t\t});\n\t\t\n\t\tcolumns.forEach(function (column, columnindex, columnarray) {\n\t\t\tvar values = [];\n\t\t\tcolumns.forEach(function (row, rowindex, rowarray) {\n\t\t\t\t\n\t\t\t\tvar currentValue = board[row][column].getValue();\n\t\t\t\t\t\t\t\t\n\t\t\t\tif (currentValue) {\n\t\t\t\t\t// Check if a value is already included in the column\n\t\t\t\t\tif (values.indexOf(currentValue) !== -1) {\n\t\t\t\t\t\tthrow {\n\t\t\t\t\t\t\tname: \"ImpossibleBoardError\"\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvalues.push(currentValue);\n\t\t\t\t\t}\n\t\t\t\t} \n\t\t\t});\n\t\t});\n\t\t\n\t\tvar boxes = [0,1,2,3,4,5,6,7,8];\n\t\t\n\t\tboxes.forEach(function (box, boxindex, boxarray) {\n\t\t\tvar columns = board.getBoxColumns(box);\n\t\t\tvar rows = board.getBoxRows(box);\n\t\t\tvar values = [];\n\t\t\trows.forEach(function (row, rowindex, rowarray) {\n\t\t\t\tcolumns.forEach(function (column, columnindex, columnarray) {\n\t\t\t\t\t\n\t\t\t\t\tvar currentValue = board[row][column].getValue();\n\t\t\t\t\t// Check if a value is already included in the box\t\t\t\t\n\t\t\t\t\tif (currentValue) {\n\t\t\t\t\t\tif (values.indexOf(currentValue) !== -1) {\n\t\t\t\t\t\t\tthrow {\n\t\t\t\t\t\t\t\tname: \"ImpossibleBoardError\"\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tvalues.push(currentValue);\n\t\t\t\t\t\t}\n\t\t\t\t\t} \n\t\t\t\t});\n\t\t\t});\n\t\t});\n\n\t}",
"function validSolution(board){\n // Check rows\n for (let i = 0; i < 9; i++) {\n if (board[i].reduce((a, n) => a + n) !== 45) return false\n }\n \n // Check columns\n for (let i = 0; i < 9; i++) {\n const col = board.map(row => row[i])\n if (col.reduce((a, n) => a + n) !== 45) return false\n }\n \n // Check blocks (TODO: this is clunky, fix it)\n const b = board.reduce((acc, c) => acc.concat(c));\n let flag45 = true;\n [0, 3, 6, 27, 30, 33, 54, 57, 60].forEach(i => {\n if (b[i] + b[i+1] + b[i+2] + b[i+9] + b[i+10] + b[i+11] + b[i+18] + b[i+19] + b[i+20] !== 45) {\n flag45 = false\n return\n }\n })\n if (!flag45) return false\n \n return true\n}",
"function CheckValidPuzzle(){\r\n\tvar isValid = true;\r\n\t\r\n\tfor(let x = 0; x < allSquares.length; x++){\r\n\t\tfor(let y = 0; y < allSquares[x].length; y++){\r\n\t\t\tif(isValid == false){\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tisValid = CheckValidCell(x, y);\r\n\t\t}\r\n\t}\r\n\t\r\n\treturn isValid;\r\n}",
"moveIsValid(row, col) {\n return !this.game_over &&\n this.board.exists(row, col) &&\n this.board.get(row, col) == null\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns Slack user id from Youtrack user id by matching on email. | getSlackIdFromYoutrackId(youtrackId) {
// Try to find slack user with email that starts with youtrack id
let slackUser = _.find(
this.slackUsers,
user => _.startsWith(user.profile.email, `${youtrackId}@`) && !user.deleted,
);
// If not found, also try to find email with only first name
if (!slackUser) {
slackUser = _.find(
this.slackUsers,
user => _.startsWith(user.profile.email, `${youtrackId.split('.')[0]}@`) && !user.deleted,
);
}
if (slackUser) {
return slackUser.id;
}
return null;
} | [
"function getUserID(email) {\n for (let id in users) {\n if (users[id].email === email) {\n return users[id].id;\n }\n }\n}",
"function findUserId(email) {\n for (let userId in users) {\n if (email === users[userId].email) {\n return userId;\n }\n }\n return null;\n}",
"static getUserIdByEmail(email) {\n for (let i = 0; i < users.length; i++) {\n if (users[i].userEmail == email) {\n return users[i].id\n }\n }\n }",
"function findUserId(email) {\n for (let key in users) {\n if (users[key].userEmail === email) {\n return key;\n }\n }\n}",
"function getId(email) {\n for(let user in users) {\n if(users[user][\"email\"] === email)\n return users[user][\"id\"];\n }\n}",
"function findUserIdByEmail(emailInput) {\n\tfor (user_id in userDB) {\n\t\tif (userDB[user_id].email === emailInput) {\n\t\t\treturn userDB[user_id].id;\n\t\t}\n\t}\n\treturn false;\n}",
"function getID() {\n const existingUsers = users.filter(user => (user.email === email && user.password === password))\n return existingUsers[0].id\n }",
"function emailLookup(email) {\n for (let id in users) {\n if (users[id].email === email) {\n return users[id];\n }\n }\n return null;\n}",
"function generateUserId(email) {\n 'use stirct';\n /**\n * @see http://stackoverflow.com/q/7616461/940217\n * @return {number}\n */\n String.prototype.hashCode = function() {\n if (Array.prototype.reduce) {\n return this.split('').reduce(function(a, b) {\n a = ((a << 5) - a) + b.charCodeAt(0);\n return a & a\n }, 0);\n }\n var hash = 0;\n if (this.length === 0) return hash;\n for (var i = 0; i < this.length; i++) {\n var character = this.charCodeAt(i);\n hash = ((hash << 5) - hash) + character;\n hash = hash & hash; // Convert to 32bit integer\n }\n return hash;\n }\n\n var hashids = new Hashids(),\n id = email.hashCode();\n id = Math.abs(id);\n\n\n return hashids.encode(id);\n}",
"function matchingUser(email) {\n for (let key in users) {\n if(users[key].email === email) {\n return users[key];\n }\n }\n}",
"function findUser(email) {\n for (user in users) {\n if (email === users[user].email) {\n return users[user]\n }\n }\n}",
"function findSlackUser(slackId) {\n return new Promise((resolve, reject) => {\n poolConnect(function (err, client, done) {\n if (err !== undefined && err !== null) {\n reject(new Error(err));\n return;\n }\n\n client.query(\n 'SELECT _auth.id FROM _auth LEFT JOIN \"user\" ON \"user\"._id = _auth.id WHERE \"user\".username = $1;',\n [slackId],\n function (queryErr, result) {\n done();\n\n if (queryErr !== undefined && queryErr !== null) {\n console.error('Unable to execute query for finding user', queryErr);\n reject(queryErr);\n return;\n }\n\n if (result.rows.length === 0) {\n resolve(null);\n return;\n }\n\n resolve({\n id: result.rows[0].id,\n slackId: slackId\n });\n }\n );\n });\n });\n}",
"function getUserId (){\n let user = parseToken();\n return user._id;\n}",
"function getUserID(data){\n\treturn data['user']['id_str'];\n}",
"getUserByEmail(email) {\n\t\treturn instance.get('/api/user/' + email)\n\t}",
"getUserIdFromEmail(email, successCallback) {\n return firebase.database().ref('users/').orderByChild('email').equalTo(email).once('value').then(function(snapshot) {\n var userId = (snapshot.val() && snapshot.val().uid) || '';\n successCallback(userId);\n });\n }",
"function retrieveUserID(inputMessage) {\n\tlet userID = inputMessage.slice(2, -1);\n\t// Users with nickname\n\tif (userID.startsWith('!')) userID = userID.slice(1);\n\treturn userID;\n}",
"function getUserId(name) {\n\n var whiteSpace = name.replace(/\\s/g, '');\n // check for an empty field\n if (name == '' || whiteSpace == '') {\n return ''; // pass through the empty name\n }\n for (var i=0; i < scope.users.length; i++) {\n var nameSplit = name.split(\" \");\n // match on username?\n if (scope.users[i].username == name) {\n return scope.users[i].id;\n }\n // match on first and last name\n else if ( scope.users[i].firstName == nameSplit[0] && scope.users[i].lastName == nameSplit[1] ) {\n return scope.users[i].id;\n }\n }\n return -1;\n }",
"static async getUserFromEmail(email) {\n try {\n return await User.query().findOne({ email });\n } catch (err) {\n return null;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function called when the client submits the sensortype reference removal | async function submitRemoveSensorTypeReference() {
let returnMessage = await UC.jsonFetch(
"https://dat2c1-3.p2datsw.cs.aau.dk/node0/admin/removesensortypereference", [
new UC.FetchArg("username", sessionStorage.getItem("username")),
new UC.FetchArg("password", sessionStorage.getItem("password")),
new UC.FetchArg("sensorType", sensorTypeSelect.value),
new UC.FetchArg("sensorID", removeSensorTypeReferenceSensorSelect.value)
]);
checkReturnCode(returnMessage, "Sensortype reference succesfully removed!");
await initialLoad();
} | [
"async function removeSensorType() {\n let returnMessage = await UC.jsonFetch(\n \"https://dat2c1-3.p2datsw.cs.aau.dk/node0/admin/removesensortype\", [\n new UC.FetchArg(\"username\", sessionStorage.getItem(\"username\")),\n new UC.FetchArg(\"password\", sessionStorage.getItem(\"password\")),\n new UC.FetchArg(\"sensorType\", sensorTypeSelect.value)\n ]);\n checkReturnCode(returnMessage, \"Sensortype succesfully removed!\");\n\n await initialLoad();\n}",
"function refbrowser_delReference(fieldname, uid) {\n var selector = 'input[value=\"' + uid + '\"][name=\"' + fieldname + ':list\"]',\n inputs = jq(selector);\n inputs.closest('li').remove();\n }",
"function refbrowser_delReference(fieldname, uid) {\n var selector = 'input[value=\"' + uid + '\"][name=\"' + fieldname + ':list\"]',\n inputs = jq(selector);\n inputs.closest('li').remove();\n }",
"removedFromEntity() { }",
"sendDocRemove(ref, data) {\n this.streamHelper.write({\n documentChange: {\n document: {\n name: ref.formattedName,\n fields: this.serializer.encodeFields(data),\n },\n removedTargetIds: [this.targetId],\n },\n });\n }",
"sendDocRemove(ref, data) {\n this.streamHelper.write({\n documentChange: {\n document: {\n name: ref.formattedName,\n fields: this.serializer.encodeFields(data),\n },\n removedTargetIds: [this.targetId],\n },\n });\n }",
"function deregister() {\n if (Object.prototype.typeOf === boundTypeOf) {\n Object.prototype.typeOf = otypeof;\n otypeof = undefined;\n }\n }",
"function deleteRemovedType(){\n\t//Delete every single item from the removedMember list\n\tfor(i in $removedType){\n\t\tdelete $removedType[i];\n\t}\n}",
"function removeReferenceInput(){\n\t\t$('.remove_reference').click(function(e){\n\t\t\tif ( $('.c_curriculum_references').children().length > 1 ) {\n\t\t\t\t$(this).parent('div').parent('div').remove();\n\t\t\t}\n\t\t});\n\t}",
"function deleteServerBehavior(sbObj)\r\n{\r\n dwscripts.deleteSB(sbObj);\r\n}",
"onReferenceUnbound(entity) {\n this.observable.send(\"referenceUnbound\", entity);\n }",
"function remove_experiment_type() {\n vocab_server(\"remove_experiment_type\", $(\"#exptype-vocab\").val());\n }",
"handleRemove(event) {\n event.preventDefault();\n this.asset = undefined;\n this.assetSearchResultList = undefined;\n this.checkSaAvailability();\n }",
"function deleteServerBehavior(sbObj)\r\n{\r\n dwscripts.deleteSB(sbObj);\r\n return true;\r\n}",
"function deleteServerBehavior(sbObj)\n{\n dwscripts.deleteSB(sbObj);\n}",
"onUserDataRemove({ data, type }) {\n SavedDataHandler.remove(data, () => {\n this.client.send(type);\n });\n }",
"_handleReferenceRemovalForVirtualLinks() {\n this.mainCollection.after.remove((userId, doc) => {\n // this problem may occur when you do a .remove() before Meteor.startup()\n if (!this.linkConfig.relatedLinker) {\n console.warn(\n `There was an error finding the link for removal for collection: \"${\n this.mainCollection._name\n }\" with link: \"${\n this.linkName\n }\". This may occur when you do a .remove() before Meteor.startup()`\n );\n return;\n }\n\n const accessor = this.createLink(doc);\n\n _.each(accessor.fetchAsArray(), linkedObj => {\n const { relatedLinker } = this.linkConfig;\n // We do this check, to avoid self-referencing hell when defining virtual links\n // Virtual links if not found \"compile-time\", we will try again to reprocess them on Meteor.startup\n // if a removal happens before Meteor.startup this may fail\n if (relatedLinker) {\n let link = relatedLinker.createLink(linkedObj);\n\n if (relatedLinker.isSingle()) {\n link.unset();\n } else {\n link.remove(doc);\n }\n }\n });\n });\n }",
"function deleteType(response, request, pool) {\n\tvar sql = 'delete from tbl_book_type where t_no = ?';\n\tvar postData = '';\n\trequest.addListener(\"data\",function(postDataChunk){\n\t\tpostData += postDataChunk;\n\t\tconsole.log('Received postData: '+postDataChunk);\n });\n request.addListener(\"end\",function(){\n \tpool.getConnection(function(err, conn){\n\t\t\tif(err) util.returnError(response, 500, err);\n\t\t\tvar param = qs.parse(postData);\n\t\t\tconn.query(sql,\n\t\t\t\t[param.id],\n\t\t\t\tfunction(err, rows) {\n\t\t\t\t\tif(err) util.returnError(response, 500, err);\n\t\t\t\t\tsetting(response, request, pool);\n\t\t\t\t}\n\t\t\t);\n\t\t\tconn.release();\n\t\t});\n });\n}",
"removeType() {\n this.selectedTypes.addEventListener('click', (event) => {\n if(event.target.classList.contains('remove')) {\n let updatedTypes = [...this.displayTypes]\n updatedTypes.splice(event.target, 1)\n let updatedId = [...this.types]\n updatedId.splice(event, 1)\n this.displayTypes = updatedTypes\n this.types = updatedId\n this.types.length === 0 && this.selected.classList.add('hidden');\n this.displaySelectedTypes()\n }\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a link suitable for sharing | getShareLink(kind = SharingLinkKind.OrganizationView, expiration = null) {
const dependency = this.addBatchDependency();
return this.getShareable().then(shareable => {
dependency();
return shareable.getShareLink(kind, expiration);
});
} | [
"getShareLink(kind, expiration = null) {\r\n // date needs to be an ISO string or null\r\n const expString = expiration !== null ? expiration.toISOString() : null;\r\n // clone using the factory and send the request\r\n return this.clone(SharePointQueryableShareable, \"shareLink\").postCore({\r\n body: jsS({\r\n request: {\r\n createLink: true,\r\n emailData: null,\r\n settings: {\r\n expiration: expString,\r\n linkKind: kind,\r\n },\r\n },\r\n }),\r\n });\r\n }",
"function getShareLink(calId) {\n var link = null;\n jQuery.ajax({\n url: \"/api/share/encrypt?calendarId=\" + calId,\n type: \"GET\",\n dataType:\"json\",\n beforeSend: function (xhr) {\n xhr.setRequestHeader (\"Authorization\", token);\n },\n contentType: \"application/json; charset=utf-8\",\n async: false\n }).done(function(data){\n link = \"http://127.0.0.1:8080/sharedcalendar/share.html?calendar=\" + data.content;\n });\n return link;\n }",
"function getLink( link ) {\n\tvar content = 'Shareable link for your form: ' + link;\n\talert(content);\n}",
"function getShareUrl() {\n return url_1.URLExt.normalize(getOption('shareUrl') || getBaseUrl());\n }",
"function linkShare () {\r\n\tvar data = JSON.stringify(localStorage);\r\n\tvar url = location.protocol + '//' + location.host + location.pathname + '?ls=' + btoa(data);\r\n\r\n\r\n\tvar outputElement = getElem('textShareOutput');\r\n\toutputElement.style.display = 'unset';\r\n\toutputElement.value = url;\r\n\toutputElement.select();\r\n\toutputElement.focus();\r\n\tdocument.execCommand(\"copy\");\r\n}",
"function GetLink() {\n // Serialize global parameters\n let serializedData = [];\n serializedData.push(Number(document.getElementById(\"volumeSlider\").value));\n serializedData.push(Number(document.getElementById(\"speedSlider\").value));\n\n // Serialize each grid\n serializedData.push([]);\n for (let gridTune of currentGridTuneObjects) {\n serializedData[2].push(gridTune.Serialize());\n }\n\n // Convert the serialized object to a base64 string so it can be put in a URL\n let serializedString = btoa(JSON.stringify(serializedData));\n let shareableLink = window.location + \"?\" + serializedString;\n\n // Copy and display the shareable link\n navigator.clipboard.writeText(shareableLink);\n document.getElementById(\"shareLink\").textContent = shareableLink;\n document.getElementById(\"shareLink\").style.display = \"block\";\n}",
"function getLinkURL(sharedLinkObj) {\n let urlString;\n\n if (sharedLinkObj == null) {\n urlString = \"\"\n } else {\n urlString = sharedLinkObj.url\n }\n\n return urlString\n}",
"function getURL(){\n\tvar html = document.getElementById(\"report\")\n\tvar share = document.getElementById(\"share\")\n\tvar url = window.location.href\n\thtml.innerHTML += \"<a href=\\\"mailto:photosectNL@gmail.com?subject=Reported%20Image&body=\"+ encodeURIComponent(url) +\"\\\">Report offensive image here</a>\"\n\tshare.innerHTML += \"<a href=\\\"mailto:?subject=Check%20out%20this%20image%20on%20PhotoSect!&body=\"+ encodeURIComponent(url) +\"\\\">Share with friends!</a>\"\n}",
"function shareLink(req, res) {\n var link = req.query.link;\n var text = req.query.text || 'Check out this post. ';\n var via = req.query.via || 'dropshape';\n if (link) {\n res.apiMessage(Status.OK, 'redirect to', {redirect: createTwitterRedirect(req, link, text, via)});\n } else {\n res.apiMessage(Status.BAD_REQUEST, 'you must provide a link');\n }\n }",
"function linkURL(photo) {\t\n \treturn \"http://www.flickr.com/photos/\" + photo.owner + \"/\" + photo.id;\n}",
"function renderSharingLink() {\n var $shareLink = $('#sharing-link');\n $shareLink.attr('href', document.location.href);\n $shareLink.html(document.location.href);\n}",
"function discoverShare(e) {\r\n var link = e.target, \r\n cachedLinks = eval(GM_getValue('cachedLinks', '({})')),\r\n sid;\r\n if (!link.href) return;\r\n if (sid=link.href.match(/sid=(.*?)&/i)) \r\n sid = sid[1];\r\n else\r\n return;\r\n if (cachedLinks[sid]) {\r\n link.href = cachedLinks[sid];\r\n link.setAttribute('unmasked', '');\r\n } else\r\n GM_xmlhttpRequest({\r\n method: 'HEAD',\r\n\t url: link.href,\r\n\t headers: {\r\n\t 'User-agent':window.navigator.userAgent,\r\n\t 'Accept': 'application/atom+xml,application/xml,text/xml',\r\n\t },\r\n\t onload: function(res) {\r\n\t var url;\r\n\t if (res.status == 200 && (url = res.finalUrl)) {\r\n\t link.href = url;\r\n\t cachedLinks[sid] = url;\r\n\t GM_setValue('cachedLinks', cachedLinks.toSource());\r\n\t link.setAttribute('unmasked', '');\r\n\t }\r\n }\r\n });\r\n}",
"function getPublicShareUrl({ creative }) {\n let url =\n `${window.location.protocol}//` +\n `${window.location.host}/` +\n `public/creative/` +\n `${creative.accountId}/` +\n `${creative.id}` +\n `&email=${creative.sharedWithEmail}`;\n return url;\n}",
"createSharingUrl (network) {\n const ua = navigator.userAgent.toLowerCase();\n\n /**\n * On IOS, SMS sharing link need a special formating\n * Source: https://weblog.west-wind.com/posts/2013/Oct/09/Prefilling-an-SMS-on-Mobile-Devices-with-the-sms-Uri-Scheme#Body-only\n */\n if (network === 'sms' && (ua.indexOf('iphone') > -1 || ua.indexOf('ipad') > -1)) {\n network += '_ios';\n }\n\n let url = this.baseNetworks[network].sharer;\n\n /**\n * On IOS, Twitter sharing shouldn't include a hashtag parameter if the hashtag value is empty\n * Source: https://github.com/nicolasbeauvais/vue-social-sharing/issues/143\n */\n if (network === 'twitter' && this.hashtags.length === 0) {\n url = url.replace('&hashtags=@hashtags', '');\n }\n\n return url\n .replace(/@url/g, encodeURIComponent(this.url))\n .replace(/@title/g, encodeURIComponent(this.title))\n .replace(/@description/g, encodeURIComponent(this.description))\n .replace(/@quote/g, encodeURIComponent(this.quote))\n .replace(/@hashtags/g, this.generateHashtags(network, this.hashtags))\n .replace(/@media/g, this.media)\n .replace(/@twitteruser/g, this.twitterUser ? '&via=' + this.twitterUser : '');\n }",
"function linkURL(photo) {\t\n\t \treturn \"http://www.flickr.com/photos/\" + photo.owner + \"/\" + photo.id;\n\t}",
"get link() {\n this._logService.debug(\"gsDiggStoryDTO.link[get]\");\n return this._link;\n }",
"get link() { return this._link; }",
"function generateLink(){\n let link = \"ts=\"+ time() + \"&apikey=\" + publicKey + \"&hash=\" + MD5(time() + privateKey + publicKey);\n return link.toString();\n}",
"function getFullShareUrl(deal, ito) {\n if (!deal || !deal.shareUrl) {\n return makeUrlAbsolute('/');\n }\n return encodeURI(`${makeUrlAbsolute(deal.shareUrl)}?ito=${ito}${deal.id}`);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function akan mereturn jarak spasi antar karakter 'o' dengan karakter 'x' yang terdekat. Contoh, jika arr adalah ['x', ' ', 'o', ' ', ' ', 'x'], maka jarak terdekat dari 'o' ke 'x' adalah 2. Jika tidak ditemukan 'x' sama sekali, function akan mereturn nilai 0. | function targetTerdekat(arr) {
// you can only write your code here!
let a = 0;
let b = 0;
let tampung = 0;
let arrX = [];
if(arr.indexOf('x') === -1){
return 0;
}
else{
for(var i = 0; i < arr.length; i++){
if(arr[i] === 'x'){
a = i;
arrX.push(a);
}
else if(arr[i] === 'o'){
b = i;
}
var hasil = [];
for(var j = 0; j < arr.length; j++){
tampung = Math.abs(b - arrX[j]);
hasil.push(tampung);
hasil.sort();
}
}
return hasil[0];
}
} | [
"function targetTerdekat(arr) {\n var posisiO = 0;\n var posisiX = 0;\n var jarak_terdekat_sementara = arr.length;\n for(var i =0 ; i < arr.length ; i++){\n if(arr[i] === \"o\"){\n posisiO = posisiO + i;\n }\n }\n for(var j = 0 ; j < arr.length ; j++){\n if(arr[j] === \"x\"){\n posisiX = posisiX + j;\n var jarak = Math.abs(posisiO - posisiX);\n posisiX = 0;\n }\n if (jarak_terdekat_sementara > jarak) {\n jarak_terdekat_sementara = jarak;\n } \n }\n if(arr.indexOf(\"x\")<0){\n return jarak_terdekat_sementara = 0;\n }\n return jarak_terdekat_sementara;\n}",
"function targetTerdekat(arr) {\n // you can only write your code here!\n var indexO;\n var indexX = [];\n\n // mencari index o dan x\n for(var i = 0; i < arr.length; i++){\n if(arr[i] === 'o'){\n indexO = i;\n } else if(arr[i] === 'x'){\n indexX.push(i);\n }\n }\n // console.log(indexO, indexX);\n if(indexX.length === 0){\n return 0; // tidak ada x\n } else {\n if(indexX[0] > indexO){\n var jarakSpasi = indexX[0] - indexO;\n } else {\n var jarakSpasi = indexO - indexX[0];\n }\n var jarakTerkecil = 0;\n // console.log('Jarak spasi awal', jarakSpasi);\n for(var i = 1; i < indexX.length; i++){\n if(indexO < indexX[i]){\n if((indexX[i] - indexO) < jarakSpasi){\n jarakTerkecil = indexX[i] - indexO;\n } else {\n jarakTerkecil = jarakSpasi;\n }\n } else {\n if((indexO - indexX[i]) < jarakSpasi)\n jarakSpasi = indexO - indexX[i];\n }\n }\n return jarakSpasi;\n }\n }",
"function targetTerdekat(arr) {\n\n var indexO = arr.indexOf('o')\n // console.log(indexO)=2\n var jarak = 0\n var jarakTerdekat =arr.length\n // console.log (jarakTerdekat)=8\n\n if (arr.indexOf('x') === -1){\n return 0\n }\n // Mengembalikan nilai 0 jika tidak ada array 'x' didalam index\n\n for (var i = 0; i < arr.length; i++){\n if (arr[i] === 'x'){\n jarak = Math.abs(i-indexO)\n // console.log (jarak+' iterasi ke-'+i)\n // Nilai jarak adalah nilai absolute dari pengurangan antara i dengan nilai index O\n if (jarak < jarakTerdekat){\n jarakTerdekat = jarak\n }\n // jika nilai jarak kurang dari nilai jarak terdekat maka set nilai jarak dengan nilai jarakTerdekat\n }\n }\n return jarakTerdekat\n}",
"function targetTerdekat(arr) {\n var o = -1\n var x = -1\n var a = 0\n while(o === -1) {\n if(arr[a] === 'o') {\n o = a\n }\n else a++\n }\n a = 0\n while(x === -1) {\n if(arr[o + a] === 'x') {\n x = a\n }\n else if(arr[o - a] === 'x') {\n x = a\n }\n else if(a === arr.length * 2) {\n x = \"Blank\"\n }\n else a++\n }\n\n if(x === \"Blank\") {\n return 0\n }\n\n if(x < o) {\n return o - x\n }\n else if(o < x) {\n return x - o\n }\n}",
"function targetTerdekat(arr) {\n // you can only write your code here!\n let o = 0\n let x = 0\n\n let foundO = false\n let foundX = false\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] == 'o') {\n o = i\n foundO = true\n } else if (arr[i] == 'x') {\n x = i\n foundX = true\n }\n if (foundO && foundX) {\n break\n }\n }\n if (!foundX) {\n return 0\n } else {\n return Math.abs(o - x)\n }\n}",
"function returnReverso(x) {\n arreglo = [];\n ultimo = x.length;\n for (i = 0; i < x.length; i++) {\n x[i] = ultimo - i;\n\n arreglo.push(x[i]);\n }\n return arreglo;\n}",
"function buscarIndiceLetra(op, letra) {\n let i;\n \n abc.map((letraArr, indice) => {\n if(op == \"sumar\") {\n if(letra.toLowerCase() == letraArr) {\n i = indice + posiciones;\n };\n }else if(op == \"restar\") {\n if(letra.toLowerCase() == letraArr) {\n i = indice - posiciones;\n };\n }\n });\n \n // Si i es mas grande que el numero de letras en el abecedario empezara desde el comienzo.\n // Si i es mas bajo que el numero de letras en el abecedario empezara desde el final.\n if(i > abc.length - 1) {\n i = i - abc.length\n }else if(i < 0) {\n i = abc.length - Math.abs(i);\n };\n \n return abc[i];\n}",
"function cariModus(arr) {\n\tvar temp = arr[0];\n\tvar modus_count = 0;\n\tvar fixModus_count = 0;\n\tvar transition_modus = [];\n\tvar temp_modus = [];\n\tvar fix_modus = [];\n\tvar modus = 0;\n\n\t// Simpan setiap variasi angka yang ada dalam array input.\n\tfor (var i = 0; i < arr.length; i++) {\n\t\tif (transition_modus.indexOf(arr[i]) === -1) {\n\t\t\ttransition_modus.push(arr[i]);\n\t\t}\n\t}\n\n\tfor (var i = 0; i < arr.length; i++) {\n\t\tif (arr[i] === temp) {\n\t\t\tmodus_count = modus_count + 1;\n\t\t}\n\t}\n\n\tif (modus_count === arr.length) {\n\t\tmodus = -1;\n\t} else if ((modus_count === 1) && (transition_modus.length === arr.length)) {\n\t\tmodus = -1;\n\t} else if (modus_count > 0 && modus_count < arr.length) {\n\t\t// Pisahkan variasi angka yang didapatkan sebelumnya ke dalam array khusus angka tersebut (temp), lalu array temp dipush ke dalam array fix_modus.\n\t\t// Jika misal array input = [1,2,2,3,4,5],\n\t\t// Maka tampilan fix modus adalah [[1], [2,2], [3], [4], [5]] (Sama seperti tampilan array result tugas mengelompokkan hewan).\n\t\tfor (var i = 0; i < transition_modus.length; i++) {\n\t\t\tfor (var j = 0; j < arr.length; j++) {\n\t\t\t\tif (arr[j] === transition_modus[i]) {\n\t\t\t\t\ttemp_modus.push(arr[j]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfix_modus.push(temp_modus);\n\t\t\ttemp_modus = [];\n\t\t}\n\t\t\n\t\t// Loop array fix_modus dan cari array di dalamnya yang memiliki length paling tinggi, lalu assign nilai length tsb ke fixModus_count.\n\t\t// Metode ini juga memenuhi syarat \"Apabila ditemukan lebih dari dua nilai modus, maka tampilkan nilai modus yang paling pertama muncul (dihitung dari kiri ke kanan)\".\n\t\t// Assign modus dengan nilai dari array yang memiliki length paling tinggi.\n\t\tfor (var i = 0; i < fix_modus.length; i++) {\n\t\t\tif (fix_modus[i].length > fixModus_count) {\n\t\t\t\tfixModus_count = fix_modus[i].length;\n\t\t\t\tmodus = fix_modus[i][0];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn modus;\n}",
"function mengelompokkanAngka(arr) {\n \n // Buat variabel penampung hasil akhir\n \n var res = [];\n \n // Buat variabel penampung masing-masing kelompok angka\n\n var genap = [];\n var ganjil = [];\n var kelipatan3 = [];\n\n // Loop untuk mengecek semua elemen di argumen\n\n for (i = 0; i < arr.length; i++) {\n\n // Jika elemen habis dibagi 3 maka masukkan ke kelompok 'kelipatan3'\n\n if (arr[i] % 3 == 0) {\n kelipatan3.push (arr[i]);\n }\n\n // Jika elemen habis dibagi 2 maka masukkan ke kelompok 'kelipatan2'\n\n else if (arr[i] % 2 == 0) {\n genap.push (arr [i]);\n }\n\n // Selain itu berarti bilangan ganjil, yang dimasukkan ke kelompok bilangan ganjil\n \n else {\n ganjil.push (arr [i]);\n }\n }\n\n res = [genap, ganjil, kelipatan3];\n return (res);\n}",
"function controllo(campo, mossa) {\n \n \n var QX = 0; /* Conta il num di X allineate */\n var QO = 0; /* Conta il num di O allineate */\n \n for (var i = 0; i < 3; i++) { /* Controllo allineamenti verticali */\n QX = 0;\n QO = 0;\n for (var j = 0; j < 3; j++) {\n if ( campo[i][j] == 'X' ) QX++;\n if ( campo[i][j] == 'O' ) QO++;\n }\n \n if (QX == 3) return 'VX';\n if (QO == 3) return 'VO';\n }\n \n \n \n for (var j = 0; j < 3; j++) { /* Controllo allineamenti orizzontali */\n QX = 0;\n QO = 0;\n for (var i = 0; i < 3; i++) {\n if ( campo[i][j] == 'X' ) QX++;\n if ( campo[i][j] == 'O' ) QO++;\n }\n if (QX == 3) return 'VX';\n if (QO == 3) return 'VO';\n }\n \n \n \n QX = 0; /* Controllo allineamenti obliqui da alto sx a basso dx */\n QO = 0;\n var j = 0;\n for (var i = 0; i < 3; i++) {\n if ( campo[i][j] == 'X' ) QX++;\n if ( campo[i][j] == 'O' ) QO++;\n j++;\n } \n \n if (QX == 3) return 'VX';\n if (QO == 3) return 'VO';\n \n QX = 0; /* Controllo allineamenti obliqui da basso sx a alto dx */\n QO = 0;\n var j = 0;\n for (var i = 2; i >= 0 ; i--) {\n if ( campo[i][j] == 'X' ) QX++;\n if ( campo[i][j] == 'O' ) QO++;\n j++;\n } \n \n if (QX == 3) return 'VX';\n if (QO == 3) return 'VO';\n \n if (mossa == 10) return 'PA';\n \n return 'IC';\n\n }",
"function mengelompokkanAngka(arr) {\n var arrGenap = []\n var arrGanjil = []\n var arrKelipatan = []\n var arrResult = []\n for (var i=0; i < arr.length; i++ ){\n // console.log (arr[i])\n if (arr[i]%2 === 0 && arr[i]%3 !==0 ){\n arrGenap.push(arr[i])\n // jika genap\n }\n else if (arr[i]%2 !== 0 && arr[i]%3 !=0){\n arrGanjil.push(arr[i])\n // jika ganjil\n }\n else if (arr[i]%3 === 0){\n arrKelipatan.push(arr[i])\n }\n // jika kelipatan 3\n // arrResult = arrGenap + arrGanjil + arrKelipatan\n }\narrResult=[arrGenap,arrGanjil,arrKelipatan]\nreturn arrResult\n// console.log(arrGenap)\n// console.log(arrGanjil)\n// console.log(arrKelipatan)\n\n}",
"function sequence(x,y){\n \n // jika x lebih kecil dari y, maka\n if (x < y){\n // tampilkan pesan Parameter x harus lebih besar dibanding y\n return 'Parameter x harus lebih besar dibanding y'\n }\n\n // jika x lebih besar dari y, maka\n if (x > y){\n // assign var hasil = [y], dan var i = 0\n var hasil = [y];\n var i = 0;\n\n // jika hasil terakhir lebih besar dari 1, maka ulangi terus proses nya\n while(hasil[hasil.length -1] > 1){\n // jika hasil akhir belum 1 atau 0, maka tambahkan 1 nilai ke index paling belakang\n hasil.push((hasil[i]**2) % (x+i));\n // jumlahkan i tambah 1\n i += 1;\n }\n // tampilkan hasil dengan format ini.\n return('array: [' + hasil + ']\\n' + 'count: ' + hasil.length);\n }\n}",
"function mengelompokkanAngka(arr) {\r\n // you can only write your code here!\r\n var newArr = [];\r\n\r\n for (var index = 0; index < 3; index++) {\r\n newArr.push([]);\r\n }\r\n\r\n for (var i = 0; i < arr.length; i++) {\r\n if (arr[i] % 3 === 0) {\r\n newArr[2].push(arr[i]);\r\n } else {\r\n if (arr[i] % 2 !== 0) {\r\n newArr[1].push(arr[i]);\r\n } else {\r\n if (arr[i] % 2 === 0) {\r\n newArr[0].push(arr[i]);\r\n }\r\n }\r\n }\r\n }\r\n return newArr;\r\n}",
"function cariModus(arr) {\n // you can only write your code here!\n let temp = []\n for (let i = 0; i < arr.length; i++) {\n // Validasi apakah temp kosong atau tidak\n if (temp.length === 0) {\n // jika kosong push data\n temp.push([arr[i], 1])\n } else {\n // jika tidak\n // Buat variable flag untuk mengecek nilai dalam temp\n let flag = false\n // loop temp\n for (let j = 0; j < temp.length; j++) {\n // cek apakah nilai dalam arr[i] sama dengan temp[j][0]\n if (arr[i] === temp[j][0]) {\n // jika ya, tambahkan frekuensi value / temp[j][1] dengan 1\n // set nilai flag menjadi true\n temp[j][1] += 1\n flag = true\n }\n }\n // cek apakah nilai flag true atau false\n if (!flag) {\n // jika false, push nilai arr[i] dengan frekuesnsi 1\n temp.push([arr[i], 1])\n }\n }\n }\n\n // variable modus untuk menampung frekuensi dari setiap nilai didalam temp\n let modus = []\n\n // looping untuk menambahkan setiap frekuensi dari temp\n for (let i = 0; i < temp.length; i++) {\n modus.push(temp[i][1])\n }\n // sort nilai tertinggi ke terendah\n modus.sort(function(a, b) { return b - a })\n\n // cek panjang temp\n // jika panjang temp == 1 maka nilai yang ada dalam temp adalah sama\n // jika panjang temp == panjang arr, maka nilai dalam temp tidak memiliki modus\n if (temp.length === 1 || temp.length === arr.length) {\n // jika ya, return -1\n return -1\n } else {\n // jika tidak, looping temp untuk mengecek frekuensi dalam temp dengan nilai terbesar pada modus\n for (let i = 0; i < temp.length; i++) {\n // cek apakah frekuensi terbesar sama dengan frekuensi yang ada pada temp\n if (modus[0] === temp[i][1]) {\n // jika ya, return value temp\n return temp[i][0]\n }\n }\n }\n // console.log(temp)\n}",
"function cariModus(arr) {\n var indexTampung =0;\n var simpanIndex, tampung=[];\n\n //Memfilter sekaligus menghitung jumlah angka yang sama yang akan di simpan pada array\"tampung\"\n for(var i=0; i<arr.length; i++) {\n var counter = 1;\n for(var j=i+1; j<arr.length; j++) {\n if(arr[i] === arr[j] && arr[i] !== '') {\n counter++;\n arr[j] = ''; //jika ada nilai yang sama maka arr[j] di hilangkan agar tidak ada duplikasi lagi\n }\n }\n if(arr[i] !== '') {\n tampung.push([arr[i], counter]) // array \"tampung\" menyimpan nilai dan jumah duplikatnya\n }\n }\n\n //mencari Modus\n var indexMax = 0;\n var MAX = tampung[indexMax][0];\n for(var i=0; i<tampung.length; i++) {\n if(tampung[i][1] > tampung[indexMax][1]) {\n indexMax = i;\n MAX = tampung[indexMax][0];\n }\n }\n\n // console.log(tampung)\n if(tampung.length === 1 || tampung[indexMax][1] === 1){ //untuk jika modus hanya ada 1 nilai atau tidak ada modus\n return -1 ; \n }else{\n return MAX;\n }\n}",
"function mengelompokkanAngka(arr) { \n let even = [];\n let odd = [];\n let three = [];\n let total = [];\n for (let i=0; i<arr.length; i++){\n if(arr[i]%2 === 0 && arr[i]%3 !==0){\n even.push(arr[i])\n } else if(arr[i]%3 ===0 || arr[i]%2 === 0){\n three.push(arr[i])\n } else {\n odd.push(arr[i])\n }\n }\n total.push(even, odd, three);\n return total;\n }",
"function DrOrdenaDoble(arr,valor) {\n //Array, true/false según queramos de mayor a menor o viceversa\n if (valor==null)\n valor=true;\n //Ordeno por burbuja\n //Mejora: implementar quickshort\n if (arr.length<2)\n return arr;\n var i,j,im1,im2;\n if (valor)\n for (i=arr.length-1;i>0;i--) {\n for (j=0;j<i;j++) {\n if (arr[j][0]>arr[j+1][0]) {\n im1=arr[j][0];\n im2=arr[j][1];\n arr[j][0]=arr[j+1][0];\n arr[j][1]=arr[j+1][1];\n arr[j+1][0]=im1;\n arr[j+1][1]=im2;\n }\n }\n }\n else\n for (i=arr.length-1;i>0;i--) {\n for (j=0;j<i;j++) {\n if (arr[j][0]<arr[j+1][0]) {\n im1=arr[j][0];\n im2=arr[j][1];\n arr[j][0]=arr[j+1][0];\n arr[j][1]=arr[j+1][1];\n arr[j+1][0]=im1;\n arr[j+1][1]=im2;\n }\n }\n }\n return arr;\n }",
"function sukeistiMasayvoElementus(nr1, nr2) {\nlet y = prekiautojai[nr1];\nprekiautojai[nr1] = prekiautojai[nr2];\nprekiautojai[nr2] = y;\n\n}",
"function sukeistiMasEl(x, y) {\n var temp = prekiautojai[x]; // issisaugau x reiksme i temp\n prekiautojai[x] = prekiautojai[y]; // x reiksme pakeiciu i y reiksme;\n prekiautojai[y] = temp; // y reiksme pakeiciu i issaugota temp\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Executes all the hooks in the `hook` stack, an returns whether they allow the command to continue (used in pre hooks). | function hook (hook, args) {
var allows = true;
for (var i = 0; i < Hooks[hook].length; i++) {
if (Hooks[hook][i].callback(game, args) === false) {
allows = false;
}
}
return allows;
} | [
"function _runHook(type, hook, args) {\n var handlers = STORAGE[type][hook];\n if (!handlers) {\n return type === 'filters' ? args[0] : false;\n }\n var i = 0,\n len = handlers.length;\n if (type === 'filters') {\n for (; i < len; i++) {\n args[0] = handlers[i].callback.apply(handlers[i].context, args);\n }\n } else {\n for (; i < len; i++) {\n handlers[i].callback.apply(handlers[i].context, args);\n }\n }\n return type === 'filters' ? args[0] : true;\n }",
"function executeHooks(self, eventName, context, args){\n\t\tfor(var i=0; self.state && self.state.eventHooks[eventName] && i<self.state.eventHooks[eventName].length; i++){\n\t\t\tif(typeof self.state.eventHooks[eventName][i] === \"function\")\n\t\t\t\tself.state.eventHooks[eventName][i].apply(context, args);\n\t\t\telse\n\t\t\t\tlog(self, \"A hook was not executed because it is not a function\", \"WARNING\");\n\t\t}\n\n\t\tfor(var i=0; clazz.eventHooks[eventName] && i<clazz.eventHooks[eventName].length; i++){\n\t\t\tif(typeof clazz.eventHooks[eventName][i] === \"function\")\n\t\t\t\tclazz.eventHooks[eventName][i].apply(context, args);\n\t\t\telse\n\t\t\t\tlog(self, \"A hook was not executed because it is not a function\", \"WARNING\");\n\t\t}\n\n\t\tif(clazz.filteredEventHooks[self.state.instanceName] !== undefined){\n\t\t\tfor(var i=0; clazz.filteredEventHooks[self.state.instanceName][eventName] && i<clazz.filteredEventHooks[self.state.instanceName][eventName].length; i++){\n\t\t\t\tif(typeof clazz.filteredEventHooks[self.state.instanceName][eventName][i] === \"function\")\n\t\t\t\t\tclazz.filteredEventHooks[self.state.instanceName][eventName][i].apply(context, args);\n\t\t\t\telse\n\t\t\t\t\tlog(self, \"A hook was not executed because it is not a function\", \"WARNING\");\n\t\t\t}\n\t\t}\n\t}",
"function _runHook( type, hook, args ) {\n\n // Allow glob pattern * in hook - how?\n\n var handlers = STORAGE[ type ][ hook ];\n\n \n if ( !handlers ) {\n return (type === 'filters') ? args[0] : false;\n }\n\n var i = 0, len = handlers.length;\n if ( type === 'filters' ) {\n for ( ; i < len; i++ ) {\n args[ 0 ] = handlers[ i ].callback.apply( handlers[ i ].context, args );\n }\n } else {\n for ( ; i < len; i++ ) {\n handlers[ i ].callback.apply( handlers[ i ].context, args );\n }\n }\n\n return ( type === 'filters' ) ? args[ 0 ] : true;\n }",
"function _runHook(type, hook, args) {\n var handlers = STORAGE[type][hook],\n i,\n len;\n\n if (!handlers) {\n return 'filters' === type ? args[0] : false;\n }\n\n len = handlers.length;\n\n if ('filters' === type) {\n for (i = 0; i < len; i++) {\n args[0] = handlers[i].callback.apply(handlers[i].context, args);\n }\n } else {\n for (i = 0; i < len; i++) {\n handlers[i].callback.apply(handlers[i].context, args);\n }\n }\n\n return 'filters' === type ? args[0] : true;\n }",
"async function run(context, hook, ...args) {\n if (!hook) { return; }\n hook = [].concat(hook);\n\n for (const f of hook) {\n await f.call(context, ...args);\n }\n}",
"function call_hooks_callback(hook) {\n var callback=arguments[arguments.length-1];\n\n // no hooks defined? call callback directly\n if((!hooks_intern[hook])||(hooks_intern[hook].length==0)) {\n callback([]);\n return;\n }\n\n var count=hooks_intern[hook].length;\n var ret=[];\n\n // pass all arguments save the first\n var args=Array.prototype.slice.call(arguments);\n args=args.slice(1);\n\n // replace callback by own callback\n args[args.length-1]=function(v) {\n // add value to return values\n if(v)\n ret.push(v);\n\n // if this was the last hook to answer, call final callback function\n if(--count==0)\n callback(ret);\n };\n\n\n // call all hooks\n for(var i=0; i<hooks_intern[hook].length; i++) {\n hooks_intern[hook][i].apply(this, args);\n }\n}",
"_runTransitionHooks(nextState) {\n var hooks = this._getTransitionHooks(nextState);\n var nextLocation = this.nextLocation;\n\n try {\n for (var i = 0, len = hooks.length; i < len; ++i) {\n hooks[i]();\n\n if (this.nextLocation !== nextLocation)\n break; // No need to proceed further.\n }\n } catch (error) {\n this.handleError(error);\n return false;\n }\n\n // Allow the transition if nextLocation hasn't changed.\n return this.nextLocation === nextLocation;\n }",
"continues() {\n // Return without a flag test.\n if (this.mnemonic === \"ret\" && this.args.length === 0) {\n return false;\n }\n // Return from interrupt.\n if (this.mnemonic === \"reti\" || this.mnemonic === \"retn\") {\n return false;\n }\n // Jump without a flag test.\n if ((this.mnemonic === \"jp\" || this.mnemonic === \"jr\") && this.args.length === 1) {\n return false;\n }\n // All else might continue.\n return true;\n }",
"function runHooks(hooks, callback) {\n var promise;\n try {\n promise = hooks.reduce(function (promise, hook) {\n // The first hook to use transition.wait makes the rest\n // of the transition async from that point forward.\n return promise ? promise.then(hook) : hook();\n }, null);\n } catch (error) {\n return callback(error); // Sync error.\n }\n\n if (promise) {\n // Use setTimeout to break the promise chain.\n promise.then(function () {\n setTimeout(callback);\n }, function (error) {\n setTimeout(function () {\n callback(error);\n });\n });\n } else {\n callback();\n }\n}",
"function runHookFunctions (i, hooksList, data, doneAll){\n hooksList[i](data, function afterRunHookFN (err){\n if (err) return doneAll(err);\n // next hook indice\n i++;\n\n if (i < hooksList.length) {\n // run hook if have hooks\n runHookFunctions(i, hooksList, data, doneAll);\n } else {\n // done all\n doneAll();\n }\n });\n}",
"function runHooks(hooks, callback) {\n try {\n var promise = hooks.reduce(function (promise, hook) {\n // The first hook to use transition.wait makes the rest\n // of the transition async from that point forward.\n return promise ? promise.then(hook) : hook();\n }, null);\n } catch (error) {\n return callback(error); // Sync error.\n }\n\n if (promise) {\n // Use setTimeout to break the promise chain.\n promise.then(function () {\n setTimeout(callback);\n }, function (error) {\n setTimeout(function () {\n callback(error);\n });\n });\n } else {\n callback();\n }\n}",
"function runHooks(hooks, callback) {\n\t var promise;\n\t try {\n\t promise = hooks.reduce(function (promise, hook) {\n\t // The first hook to use transition.wait makes the rest\n\t // of the transition async from that point forward.\n\t return promise ? promise.then(hook) : hook();\n\t }, null);\n\t } catch (error) {\n\t return callback(error); // Sync error.\n\t }\n\n\t if (promise) {\n\t // Use setTimeout to break the promise chain.\n\t promise.then(function () {\n\t setTimeout(callback);\n\t }, function (error) {\n\t setTimeout(function () {\n\t callback(error);\n\t });\n\t });\n\t } else {\n\t callback();\n\t }\n\t}",
"function invokeHook(hook, handler, msg) {\r\n var result = true;\r\n try {\r\n if (typeof hook === 'function') {\r\n result = hook(handler, msg);\r\n }\r\n else {\r\n result = hook.messageHook(handler, msg);\r\n }\r\n }\r\n catch (err) {\r\n exceptionHandler(err);\r\n }\r\n return result;\r\n }",
"function isHook(node: Node): boolean {\n if (node.type === AST_NODE_TYPES.IDENTIFIER) {\n return isHookName(node.name);\n } else if (\n node.type === AST_NODE_TYPES.MEMBER_EXPRESSION &&\n !node.computed &&\n isHook(node.property)\n ) {\n const obj = node.object;\n const isPascalCaseNameSpace = /^[A-Z].*/;\n return (\n obj.type === AST_NODE_TYPES.IDENTIFIER &&\n isPascalCaseNameSpace.test(obj.name)\n );\n } else {\n // TODO Possibly handle inline require statements e.g. require(\"useStable\")(...)\n // This does not seem like a high priority, since inline requires are probably\n // not common and are also typically in compiled code rather than source code.\n\n return false;\n }\n}",
"function invokeHook(hook, handler, msg) {\r\n\t var result;\r\n\t try {\r\n\t if (typeof hook === 'function') {\r\n\t result = hook(handler, msg);\r\n\t }\r\n\t else {\r\n\t result = hook.messageHook(handler, msg);\r\n\t }\r\n\t }\r\n\t catch (err) {\r\n\t result = true;\r\n\t console.error(err);\r\n\t }\r\n\t return result;\r\n\t }",
"function invokeHook(hook, handler, msg) {\n var result = true;\n\n try {\n if (typeof hook === 'function') {\n result = hook(handler, msg);\n } else {\n result = hook.messageHook(handler, msg);\n }\n } catch (err) {\n exceptionHandler(err);\n }\n\n return result;\n }",
"_runNextHook() {\n var itr = this._iterator;\n if (itr.hasNext()) {\n var hook = itr.next();\n hook(this);\n } else {\n this.emit(Events.RUNNER_COMPLETED, this.data);\n // Call the complete handler if one was provided to the `.run()` call.\n this._completeHandler && this._completeHandler(this.data.failure, this.data);\n }\n }",
"function invokeHook(hook, handler, msg) {\n var result = true;\n try {\n if (typeof hook === 'function') {\n result = hook(handler, msg);\n }\n else {\n result = hook.messageHook(handler, msg);\n }\n }\n catch (err) {\n exceptionHandler(err);\n }\n return result;\n }",
"function call_hooks(hook, vars, param1, param2, param3, param4) {\n if(hooks_intern[hook])\n for(var i=0; i<hooks_intern[hook].length; i++) {\n hooks_intern[hook][i](vars, param1, param2, param3, param4);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clear the Result Section | function clearResultSec() {
resultSec.html("");
searchMsg.html("");
} | [
"function clear() {\n\t // reset current state for next data\n\t _result = {};\n\t _errors = {};\n\t _summary = true;\n\t }",
"function clearResult() {\n showResult('');\n }",
"function clearResult() {\n $(\"#resultEl\").html(\"\");\n }",
"function clearResultTable() {\n resultTable.html(\"\");\n}",
"function clearResultDisplay() {\n resultDisplay().text('');\n }",
"function clearResults() {\n $results.children().remove();\n }",
"function clearResultarea() {\n resultarea.innerHTML = \"\";\n }",
"function clear() {\n\t\t\t//jQuery('div.results').html('');\n\t\t}",
"function clearResults(){\n $(settings.results).children().remove();\n }",
"function clearAreaResultSearch(){\n retrDocs.innerHTML = \"\";\n docsInformation = [];\n indexSnippet = 0;\n }",
"clearResults() {\r\n this.results.testStat = 0;\r\n this.results.terms = [];\r\n }",
"function clearResults() {\n\t\t// Re-display loading icons\n\t\tdocument.getElementById(\"loadingmeaning\").style.display = \"inline\";\n\t\tdocument.getElementById(\"loadinggraph\").style.display = \"inline\";\n\t\tdocument.getElementById(\"loadingcelebs\").style.display = \"inline\";\n\t\t\n\t\t// Clear old results\n\t\tdocument.getElementById(\"meaning\").innerHTML = \"\";\n\t\tdocument.getElementById(\"graph\").innerHTML = \"\";\n\t\tdocument.getElementById(\"celebs\").innerHTML = \"\";\n\t\t\n\t\t// Hide \"no results\" error message\n\t\tdocument.getElementById(\"norankdata\").style.display = \"none\";\n\t}",
"clearResultDisplay() {\n this.resultDisplay.text('');\n }",
"function clearResults() {\n\t$('.results').text('');\n}",
"function clearResults() {\n\t\t$(\"#results\").empty();\n\n\t}",
"function clearResults() {\n triggerError(false);\n document.querySelector(\"#results\").innerHTML = \"\";\n}",
"function clearResults()\r\n{\r\n\t// Stop any existing search.\r\n\tsearchControl.cancelSearch();\r\n\t\r\n\t// Clear the results.\r\n\tresults = new Array();\r\n\tresultProgress = new Array();\r\n\tresultCounter = 0;\r\n\twriteDiv('results', null, \"\");\r\n\tshowProgress(0);\r\n\t\r\n\t// Clear the input box.\r\n\tsetControlValue(\"searchInput\", \"\");\r\n}",
"clearResults() {\n for (const id of this.failed.keys()) {\n this.failed.set(id, null);\n }\n for (const id of this.finished.keys()) {\n this.finished.set(id, null);\n }\n }",
"function clearOutResults(){\n\t\t$(\"#resultsTable\").find(\"td\").each(function() { \n\t\t\t$(this).html(\"\");\n\t\t});\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create sprint details window | function createSprintInfoWindow(name, sprint_data) {
if(windows.get(name) == undefined) {
let window = new BrowserWindow({
width : 400,
height : 700,
parent : win,
center : true,
title : 'Sprint Details'
})
window.webContents.on('did-finish-load', () => {
window.webContents.send('load-table', sprint_data);
})
window.on('closed', () => {
window = null;
windows.set(name, undefined);
})
windows.set(name, window);
window.loadFile('./sprintDetails.html');
}
} | [
"function storeIssuePrintPreview(issueId)\n{\n window.open(\"procurement/print/storeIssueDialog.jsp?operationType=find&output=HTML&issueId=\" + issueId,\n \"Store Issue Print Preview\",\n \"menubar=no,location=no,resizable=yes,scrollbars=yes,status=yes\");\n} //End of function storeIssuePrintPreview",
"function PrintPreview() {\n var toPrint = document.getElementById('printSection');\n var popupWin = window.open('', '_blank', 'width=550,height=350,location=no,left=200px');\n popupWin.document.open();\n popupWin.document.write('<html><title>::Print Preview::</title></head><body\">')\n popupWin.document.write(toPrint.innerHTML);\n popupWin.document.write('</html>');\n popupWin.document.close();\n }",
"function openPrintDlg() {\n createDnRDlg({w:350, h:280, l:200, t:200}, {resizeable:true, newsize:true}, 'pmDlgContainer', localeList['Print_Settings'], 'printdlg.phtml?'+SID);\n}",
"function openNutritionPrintGrid()\n{\n\tvar url = makeURL(\"NutritionDetail\", \"ShowItemNutritionPrintGrid\");\n\tvar w = window.open(url, 'NutritionPrintGrid', 'left=20,top=20,width=850,height=600,toolbar=1,resizable=1,menubar=1,scrollbars=1');\n\tif (!w)\n\t{\n\t\talert(\"could not open: \" + url);\n\t\treturn;\n\t}\n\tw.focus();\n}",
"function openPrintable(sTitle, sURL)\r\n{\r\n\tvar win = null;\r\n\twin = window.open(sURL, sTitle, \"width=620,height=460,status=no,toolbar=no,scrollbars=yes\");\r\n}",
"function onReportPreview() \r\n{\r\n if (hasCurrentAppValidCriteria())\r\n {\r\n // currentApp with criteria will be pulled by print.html when document ready\r\n var printWin = window.open('print.html?menu=menuReportShow', \"Print Report\", 'width = 900, height = 800, scrollbars=yes');\r\n } \r\n}",
"function OnCmdPrintPrayerPlan()\r\n{\r\n window.openDialog(\"chrome://kneemail/content/print_prayer_plan.xul\", \"print_prayer_plan\", \"modal,centerscreen\", intPlans[intPlan]);\r\n}",
"function buildPage() {\n\tvar navOutput = '<select id=\"sprintSelector\" style=\"width:100px;\" onchange=\"changeCurrentSprint()\">';\n\tvar contentOutput = '<table cellspacing=\"0\" width=\"100%\" class=\"ms-rteTable-0\"><tbody><tr class=\"ms-rteTableEvenRow-0\">';\n\tvar sProgress;\n\t\n\t//Build navigation output.\n\tfor (var i = 0; i < sprintsData.sprints.length; i++) {\n\t\tvar sprintId = sprintsData.sprints[i].id;\n\t\tvar sprintNumber = sprintsData.sprints[i].data.sprint;\n\t\t\n\t\tif (currentSprintId === sprintId) {\n\t\t\tsProgress = sprintsData.sprints[i].data;\n\t\t\tnavOutput += '<option value=\"'+ sprintId +'\" selected>Sprint '+ sprintNumber +'</option>';\n\t\t\n\t\t} else {\n\t\t\tnavOutput += '<option value=\"'+ sprintId +'\">Sprint '+ sprintNumber +'</option>';\n\t\t}\n\t}\n\tnavOutput += '</select>   ' + \n\t\t\t\t\t'<a href=\"javascript:buildNewSprintTemplate();\">'+\n\t\t\t\t\t'<font size=\"2\">+ Add new sprint</font>'+\n\t\t\t\t\t'</a> | '+\n\t\t\t\t\t'<a href=\"/regression/SitePages/Notes.aspx?s='+ currentSprintId +'\">'+\n\t\t\t\t\t'<font size=\"2\">View sprint notes</font>'+\n\t\t\t\t\t'</a>';\n\t\n\t//Build sprint progress output.\n\tfor (var i = 0; i < sProgress.tools.length; i++) {\n\t\t\tcontentOutput += '<td class=\"ms-rteTableEvenCol-0\" style=\"width: 14.2857%;\">' +\n\t\t\t\t\t\t\t\t'<h1>' + sProgress.tools[i].name + '</h1>' +\n\t\t\t\t\t\t\t\t'<ul>';\n \n\t\t\tfor (var j = 0; j < sProgress.tools[i].features.length; j++) {\n\t\t\t\tvar featureStatusHtml;\n\t\t\t\tvar urlVariables = '?s=' + currentSprintId + '&t=' + i + '&f=' + j;\n\t\t\t\tvar featureUrl = sProgress.tools[i].features[j].url + urlVariables;\n\t\t\t\t\n\t\t\t\tswitch(sProgress.tools[i].features[j].status) {\n\t\t\t\t\tcase 0:\n\t\t\t\t\t\tfeatureStatusHtml = ' - <font color=\"#C0C0C0\" size=\"1\"><b>?</b></font>';\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\tfeatureStatusHtml = ' - <font color=\"#008000\" size=\"3\"><b>v</b></font>';\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\tfeatureStatusHtml = ' - <font color=\"#ff0000\" size=\"3\"><b>x</b></font>';\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcontentOutput += '<li>'+\n\t\t\t\t\t\t\t\t\t'<a href=\"' + featureUrl + '\">'+\n\t\t\t\t\t\t\t\t\tsProgress.tools[i].features[j].name+\n\t\t\t\t\t\t\t\t\t'</a>' + featureStatusHtml+\n\t\t\t\t\t\t\t\t\t'</li>';\n\t\t\t}\n\t\t\t\n\t\t\tcontentOutput += '</ul>'+\n\t\t\t\t\t\t\t\t'<a href=\"javascript:openNewFeatureDialog(' + i + ');\">'+\n\t\t\t\t\t\t\t\t'<font size=\"1\">+ Add feature</font>'+\n\t\t\t\t\t\t\t\t'</a></td>';\n\t\t\t\t\t\t\t\t\n\t\t}\n\t\t\n\t\tcontentOutput += '</tr></tbody></table>';\t\n\t\n\t\n\tdocument.getElementById(\"SprintOptions\").innerHTML = navOutput;\n\tdocument.getElementById(\"innerContent\").innerHTML = contentOutput;\n\tdocument.getElementById(\"DeltaPlaceHolderPageTitleInTitleArea\").innerHTML = 'Regression - Sprint ' + sProgress.sprint;\n}",
"function openPrintPreview(type, id, child_id, revision, print_action) \n{\n // configure window size using cookies or default values if there are no cookies\n var width = getCookie(\"ReqPopupWidth\");\n var height = getCookie(\"ReqPopupHeight\");\n var windowCfg='';\n var feature_url = print_action;\n\n if (width == null) {\n width = \"800\";\n }\n if (height == null) {\n height = \"600\";\n }\n \n switch(type)\n {\n\n case 'req':\n feature_url += \"?req_id=\" + id + \"&req_version_id=\" + child_id + \"&req_revision=\" + revision;\n break;\n\n case 'reqSpec':\n feature_url += \"?reqspec_id=\" + id + \"&reqspec_revision_id=\" + child_id;\n break;\n \n case 'tc':\n feature_url += \"&testcase_id=\" + id + \"&tcversion_id=\" + child_id;\n break;\n \n }\n windowCfg = \"width=\"+width+\",height=\"+height+\",resizable=yes,scrollbars=yes,toolbar=yes,dependent=yes,menubar=yes\";\n window.open(fRoot+feature_url,\"_blank\",windowCfg); // TODO localize \"Print Preview\"!\n}",
"function printCollection(id, colname) {\r\n var img = \"http://smile.abdn.ac.uk:8081/smile-server/api-1.1/qrcode?data=http://smile.abdn.ac.uk/smile-server/api-1.1/collections/\"+id; \r\n var mname = colname;\r\n var printWindow = window.open();\r\n printWindow.document.write(\"<html><head><title>\"+mname+\"</title><style>@media screen{body{width:150px;height:150px;}p{margin:-10px -10px -10px -35px;}} @media print{body{width:58mm;height:58mm;margin:0;}img{display:block;width:50mm;height:50mm;margin-left:auto;margin-right:auto;padding:0px;}#bord{width:58mm; margin:0 auto;}p{margin-top:-20px;font-size:14pt;}}</style></head><body><div id=\\\"bord\\\"><img src=\"+img+\" /><br/><p align=\\\"center\\\">\"+mname+\"</p></div></body></html>\");\r\n printWindow.window.print();\r\n}",
"function seatPopup(id, student)\n{\n\tif (student.name != \"NULL\")\n\t{\n\tpreurl = 'student_stats.html?id=';\n\turl = preurl + id;\n\twindow.open(url,'popUpWindow','height=500,width=800,left=300,top=100,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=0, directories=no, status=no');\n\t}\n\n}",
"function setupPrintDialog() {\n window.print();\n }",
"function createPasteDetail(){\n \n bookTplMarkup = [\n '<div>{title}</div><br/>',\n '<div>by author: {nickname} published: {pub_time} expires: {exp_time} </div><br/>',\n ];\n bookTpl = new Ext.Template(bookTplMarkup);\n\n // basic more detailed panel\n detailWindow = new Ext.Panel({\n id: 'detail',\n width: 750,\n title:'Paste basic overview', \n plain:true,\n layout: 'fit', \n closable:true,\n closeAction:'hide',\n renderTo: 'detail',\n items:[{\n id: 'detailPanel',\n region: 'center',\n autoHeight:true,\n bodyStyle: {\n background: '#ffffff',\n padding: '7px'\n },\n html: 'Choose a weblink to be shown.' \n }] ,\n tbar: [{\n // show more details of Paste\n text: 'More details',\n handler: function(){\n detailMoreWindow.show();\n }\n \n }]\n });\n detailWindow.hide();\n}",
"function printList(){\n var win = window.open();\n win.document.write('<html><head><title>Grocery List</title><link rel=\"stylesheet\" type=\"text/css\" href=\"/public/stylesheets/style.css\"><link rel=\"stylesheet\" type=\"text/css\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\"></head><body>');\n var printedCoverPage = \"<div id='print-cover-page'><h2>Weekly Menu Plan</h2>\" + printCoverPage(selectedRecipes, recipeListData) + \"</div>\";\n var printedRecipePages = \"<div id='print-recipe-pages'><h2>Recipes and Instructions</h2>\" + printRecipePages(selectedRecipes, recipeListData) + \"</div>\";\n var printedGroceryList = \"<div id='print-grocery-list'><h2>Grocery List</h2>\" + \"<br>\" + printGroceryList(selectedRecipes, recipeListData) + \"</div>\";\n win.document.write(printedCoverPage);\n win.document.write(printedRecipePages);\n win.document.write(printedGroceryList);\n win.document.write('<script src=\"/public/javascripts/print.js\"></script></body></html>');\n}",
"function createSystemDetailsPanel(details, panel) {\n\t\tvar content = '<h2>System Details</h2>';\n\t\tcontent += '<h3>Memory Details</h3>';\n\t\tcontent += '<table>';\n\t\tcontent += '<tr><td>current heap</td><td>'+details.currentHeap+' MB</td></tr>';\n\t\tcontent += '<tr><td>max heap</td><td>'+details.maxHeap+' MB</td></tr>';\n\t\tcontent += '<tr><td>free heap</td><td>'+details.freeHeap+' MB</td></tr>';\n\t\tcontent += '</table>';\n\t\tif (details.environment) {\n\t\t\tcontent += '<h3>System Properties</h3>';\n\t\t\tcontent += '<table>';\n\t\t\tcontent += '<tr><td class=\"termgenie-module-table-header\">Name</td><td class=\"termgenie-module-table-header\">Value</td></tr>';\n\t\t\t\n\t\t\tvar names = [];\n\t\t\tjQuery.each(details.environment, function(name){\n\t\t\t\tnames.push(name);\n\t\t\t});\n\t\t\tnames.sort();\n\t\t\t\n\t\t\tjQuery.each(names, function(index, name){\n\t\t\t\tvar value = details.environment[name];\n\t\t\t\tcontent += '<tr><td>'+name+'</td><td>'+value+'</td></tr>';\n\t\t\t});\n\t\t\tcontent += '</table>';\n\t\t}\n\t\tpanel.append(content);\n\t}",
"function ui_popupPrintableWin(str_url,str_windowname, str_winsize) {\n\t\tstr_winsize = str_winsize.toUpperCase();\n\t\tvar ht = screen.availHeight;\n\t\tvar wd = screen.availWidth;\n\t\tvar left = 0;\n\t\tvar top = 10;\n\t\tif (str_winsize == \"S\") scalar = 0.33;\n\t\t else if (str_winsize == \"M\") scalar = 0.50;\n\t\t else scalar = 0.75;\n\t\tw_ht = Math.round(scalar * ht);\n\t\tw_wd = Math.round(scalar * wd);\n\t\tleft = (wd - w_wd) - 20;\n\t\tvar windowparms = \"menubar,scrollbars,resizable,status\";\n\t\twindowparms += \"left=\" + left + \",top=\" + top + \",screenX=\" + left + \",screenY=\" + top + \",\";\n\t\twindowparms += \"height=\" + w_ht + \",width=\" + w_wd;\n\t\tif (window.NewWindow) {\n\t\t if (!NewWindow.closed) NewWindow.close();\n\t\t }\n\t\tNewWindow = window.open(str_url,str_windowname,windowparms);\n\t\tNewWindow.window.focus();\n }",
"function showPrintingToolsTab() {\n }",
"function printMovieDetail() {\n if (movie.bkgimage != null) {\n bkgImageElt.css('background-image', `url(${movie.bkgimage})`);\n }\n else {\n bkgImageElt.css('background-image', `linear-gradient(rgb(81, 85, 115), rgb(21, 47, 123))`);\n }\n\n titleElt.text(movie.title);\n modalTitle.text(movie.title);\n originaltitleElt.text(movie.originaltitle);\n resumeElt.text(movie.resume);\n dateElt.text(printDateFr(movie.date));\n durationElt.text(printDuration(movie.duration));\n imgElt.attr('src', movie.image);\n iframe.attr('src', movie.traileryt + \"?version=3&enablejsapi=1\");\n // Afficher la liste des acteurs\n var actorsStr = '';\n for (var actor of movie.actors) {\n actorsStr += actor + ' | ';\n }\n actorsElt.text(actorsStr);\n // afficher le réalisteur\n directorElt.text(movie.director);\n}",
"function showInfo(caller) {\n\tconsole.log(caller.id);\n\tvar db = fbladata.getDB();\n\tvar workshop;\n\tvar description;\n\tvar date;\n\tvar time;\n\tvar conference;\n\tvar w = window.open(\"workshop_info.html\", \"w\", \"width=500,height=300\");\n\tdb.serialize(function() {\n\t\tdb.each(\"SELECT name,description,date,time,conference FROM workshops WHERE id = \" + caller.id, function(err,row) {\n\t\t\tconsole.log(row);\n\t\t\tworkshop = row.name;\n\t\t\tdescription = row.description;\n\t\t\tdate = row.date;\n\t\t\ttime = row.time;\n\t\t\tif (row.conference == \"WASH\") conference = \"Washington, D.C.\";\n\t\t\tif (row.conference == \"NEWO\") conference = \"New Orleans, LA\";\n\t\t\tif (row.conference == \"MINN\") conference = \"Minneapolis, MN\";\n\t\t}, function() {\n\t\t\tw.document.write(\"<link href='css/bootstrap.min.css' rel='stylesheet'><h1 style='padding:10px'>\"+workshop+\"</h1>\"+\n\t\t\t\"<p style='padding-left:10px;'>\"+description+\"<br/><b>Date:</b> \"+date+\"<br/><b>Time:</b> \"+time+\"<br/><b>Location:</b> \"+conference+\"</p>\");\n\t\t\tw.document.title = workshop;\n\t\t});\n\t});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes the model specified by modelHandle. | function removeModel(modelHandle) {
if (allModels[modelHandle]) {
var entryToRemove = document.querySelector('option[value="' + modelHandle + '"]');
currentModelSelect.remove(entryToRemove.index);
scene.remove( allModels[modelHandle] );
delete allModels[modelHandle];
}
} | [
"removeModel(model){\n let index = this._models.indexOf(model);\n if(index > -1){\n this._models.splice(index, 1);\n }\n }",
"removeModel(model){\n const index = this.findModel(model);\n //removing model number\n this.removeIndex(index);\n }",
"onDelete(model) {\n this.ApplicationModel.removeModel(model);\n }",
"removeModelReferences(model) {\n this.removeSelectedFeaturesForModel(model);\n this.workbench.remove(model);\n if (model.uniqueId) {\n this.models.delete(model.uniqueId);\n }\n }",
"remove (modelName) { this.models.delete(modelName) }",
"remove(modelName) {\n this.models.delete(modelName);\n }",
"remove(model) {\n // TODO: this assumes that all objects are children of the root node!\n // We should call something like model.parent.removeChild(model);\n scene.removeChild(model);\n\n delete updateHandlers[model.id];\n delete eventHandlers[model.id];\n }",
"remove(model) {\n let match = this.models.find(m => isEqual(m.attrs, model.attrs));\n\n if (match) {\n let i = this.models.indexOf(match);\n this.models.splice(i, 1);\n }\n\n return this;\n }",
"removeModel() {\n this.log('removeModel', {\n sourceModel: this.sourceModel,\n dragIndex: this.dragIndex\n })\n this.sourceModel.removeAt(this.dragIndex)\n }",
"function removeModel(){\r\n scene.remove(modelOBJ, wireframeOBJ); \r\n}",
"async removeModel() {\n if (await this.checkStoredModelStatus() == null) {\n throw new Error(\n 'Cannot remove locally saved model because it does not exist.');\n }\n return await tf.io.removeModel(this.modelSavePath_);\n }",
"function deleteModel(vModel) {\n window.localStorage.removeItem(vModel);\n }",
"@action\n remove(models) {\n // Handle single model\n if (!Array.isArray(models)) models = [models];\n\n const ids = models.map(model => {\n return model.uniqueId;\n });\n\n this.spliceModels(ids);\n }",
"_removeFromCache( model ) {\n var index = this._findCacheIndex( model );\n\n if ( !index && index !== 0 ) {\n throw new Error( '[Wrangler] can not remove model from cache' );\n }\n\n this.cache.splice( index, 1 );\n }",
"async remove() {\n // Reject removals of unsaved models\n if (this.isNew()) {\n throw new Error('cannot remove unsaved model')\n }\n\n // Run before remove hook\n await this.beforeRemove()\n\n // Remove the record from mongo\n await this.collection.remove(fixId({\n _id: this._id\n }))\n\n // Delete the id, making it a new model\n delete this._id\n\n // Run after remove hook\n await this.afterRemove()\n }",
"async removeById(Model, id) {\n // Get collection ID of provided Model\n const collectionId = modelCollectionId(Model);\n\n // Remove stored Model instance matching provided ID\n await this._plug.removeById(collectionId, id);\n }",
"function deleteModel(modelName){\n if(!modelMap[modelName]) return false;\n delete modelMap[modelName];\n return true;\n }",
"function deleteModel(model) {\n if (model.tag == \"asteroid\") {\n for (var a in asteroids) {\n if (asteroids[a] == model) {\n asteroids.splice(a, 1);\n }\n }\n }\n for (var e in inputEllipsoids) {\n if (inputEllipsoids[e] == model) {\n inputEllipsoids.splice(e, 1);\n }\n }\n}",
"async drop(model) {\n throw new Error('not implemented');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the user's scopes from the JWT payload. | function userScopes(jwtPayload) {
if (!(jwtPayload.scope instanceof Array && jwtPayload.scope.length)) {
return [];
}
return jwtPayload.scope
.map(function (s) { return (s.includes('.') ? s.substr(s.indexOf('.') + 1, s.length) : s); })
.map(function (s) { return ({ name: s }); });
} | [
"getGrantedScopes() {\r\n const scopes = this._storage.getItem('granted_scopes');\r\n if (!scopes) {\r\n return null;\r\n }\r\n return JSON.parse(scopes);\r\n }",
"getRequestedScopes() {\n const scopesStr = sessionStorage.getItem(this.sessionStorageRequestedScopesKey);\n return scopesStr ? JSON.parse(scopesStr) : null;\n }",
"function userScopes(decodedToken) {\n if (!(decodedToken.scope instanceof Array && decodedToken.scope.length)) {\n return [];\n }\n return decodedToken.scope\n .map(function (s) { return (s.includes('.') ? s.substr(s.indexOf('.') + 1, s.length) : s); })\n .map(function (s) { return ({ name: s }); });\n}",
"function retrieveScopes() {\n if (localStorage.getItem(swaggerId) === null) {\n authManager.loadSwaggerJson(false); //synchronous call\n }\n return extractScopesFromSwagger();\n}",
"function getScope() {\n var token = getToken();\n var payload = jwtHelper.decodeToken(token);\n var scope = payload.scope;\n return scope;\n }",
"function catchScopes(userScopes, endpointScopes) {\n const scopes = [];\n\n for (const scope of endpointScopes) {\n if (userScopes.indexOf(scope) > -1) scopes.push(scope);\n }\n\n return scopes;\n}",
"function getAuthorizedScopes (req, res, next) {\n // Get the scopes authorized for the verified and decoded token\n const scopeNames = req.claims.scope && req.claims.scope.split(' ')\n\n Scope.get(scopeNames, function (err, scopes) {\n if (err) { return next(err) }\n req.scopes = scopes\n next()\n })\n}",
"fetchScopes(context) {\n return new Promise((resolve, reject) => {\n service\n .getUser()\n .then(function(user) {\n if (user == null) {\n context.dispatch('signIn');\n context.commit('setScopes', null);\n return resolve(null);\n } else {\n context.commit('setScopes', user.scopes);\n return resolve(user.scopes);\n }\n })\n .catch(function(err) {\n context.commit('setError', err);\n return reject(err);\n });\n });\n }",
"getDeniedScopes() {\n const scopesStr = sessionStorage.getItem(this.sessionStorageDeniedScopesKey);\n return scopesStr ? JSON.parse(scopesStr) : null;\n }",
"getScopes() {\n const self = this\n return new Promise((resolve, reject) => {\n mgr.getUser().then(function(user) {\n if (user == null) {\n self.signIn()\n return resolve(null)\n } else {\n return resolve(user.scopes)\n }\n }).catch(function(err) {\n console.log(err)\n return reject(err)\n })\n })\n }",
"getScopes(){\n let self = this\n return new Promise((resolve, reject) => {\n self.mgr.getUser().then(function (user) {\n if (user == null) {\n self.signIn()\n return resolve(null)\n } else{\n return resolve(user.scopes)\n }\n }).catch(function (err) {\n console.log(err)\n return reject(err)\n });\n })\n }",
"function determineScope (req, res, next) {\n var params = req.connectParams;\n\n Scope.get(params.scope.split(' '), function (err, scopes) {\n if (err) { return next(err); }\n\n // remove null results\n var knownScope = scopes.reduce(function (list, scope) {\n if (scope instanceof Scope) {\n list.push(scope);\n }\n return list;\n }, []);\n\n // get authorized scope for user\n req.user.authorizedScope(function (err, authorizedScope) {\n if (err) { return callback(err); }\n\n // filter unauthorized scope\n req.scopes = knownScope.filter(function (scope) {\n return authorizedScope.indexOf(scope.name) !== -1;\n });\n\n // extract scope names\n req.scope = req.scopes.map(function (scope) {\n return scope.name;\n }).join(' ');\n\n next();\n });\n });\n}",
"normalizeScope() {\n let scope;\n // Set to empty string if the scope if not set\n if (typeof this._userConfig.oauth.scope === 'undefined') {\n scope = '';\n }\n // convert an array into a string\n else if (util.isArray(this._userConfig.oauth.scope)) {\n scope = this._userConfig.oauth.scope.join(',');\n }\n return scope;\n }",
"ensureScope(...scopes) {\n return function(req, res, next) {\n\n //Get claims\n const claims = req.claims;\n if (!claims) {\n return next(new NotAuthenticatedError());\n }\n\n //Must have scope\n if (!claims.scope) {\n return next(new NotAuthorizedError('No scope'));\n }\n\n //Get user scopes and check scopes\n //Combine and split given scopes in case provided as string or params\n const claimed = claims.scope.split(' ');\n const checked = scopes.join(' ').split(' ');\n\n //Check if we have a match\n const match = checked.some(scope => claimed.includes(scope));\n if (!match) {\n return next(new NotAuthorizedError('Insufficient scope'));\n }\n\n //All good\n next();\n };\n }",
"function getScopes(val){\n if (Immutable.Iterable.isIterable(val)){\n return val.flatMap(getScopes).toJS();\n } else if (val && val.getScopes){\n return val.getScopes();\n } else {\n return [];\n }\n }",
"getScopes() {\r\n return this.builder.scopes;\r\n }",
"static get scopes() {\n return [\n 'https://www.googleapis.com/auth/cloud-platform',\n 'https://www.googleapis.com/auth/dialogflow',\n ];\n }",
"get scopesAllowed(){\n\t\treturn this._scopesAllowed;\n\t}",
"static get scopes() {\n return [\n 'https://www.googleapis.com/auth/cloud-platform',\n 'https://www.googleapis.com/auth/monitoring',\n 'https://www.googleapis.com/auth/monitoring.read',\n 'https://www.googleapis.com/auth/monitoring.write',\n ];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
You can create a humanizer, which returns a function with defaults parameters. | function humanizer(passedOptions) {
var result = function humanizer(ms, humanizerOptions) {
var options = extend({}, result, humanizerOptions || {});
return doHumanization(ms, options);
};
return extend(result, {
language: "en",
delimiter: ", ",
spacer: " ",
units: ["year", "month", "week", "day", "hour", "minute", "second"],
languages: {},
halfUnit: true,
round: false
}, passedOptions);
} | [
"function humanizer(passedOptions) {\n\n var result = function humanizer(ms, passedOptions) {\n var options = extend({}, result, passedOptions || {});\n return doHumanization(ms, options);\n };\n\n extend(result, {\n language: \"en\",\n delimiter: \", \",\n units: [\n \"year\",\n \"month\",\n \"week\",\n \"day\",\n \"hour\",\n \"minute\",\n \"second\"\n ],\n languages: {}\n }, passedOptions);\n\n return result;\n\n }",
"function humanizer(passedOptions) {\n\n var result = function humanizer(ms, humanizerOptions) {\n var options = extend({}, result, humanizerOptions || {});\n return doHumanization(ms, options);\n };\n\n return extend(result, {\n language: \"en\",\n delimiter: \", \",\n spacer: \" \",\n units: [\"year\", \"month\", \"week\", \"day\", \"hour\", \"minute\", \"second\"],\n languages: {},\n halfUnit: true,\n round: false\n }, passedOptions);\n\n}",
"function humanizer(passedOptions) {\n\n var result = function humanizer(ms, passedOptions) {\n var options = extend({}, result, passedOptions || {});\n return doHumanization(ms, options);\n };\n\n return extend(result, {\n language: \"en\",\n delimiter: \", \",\n spacer: \" \",\n units: [\"year\", \"month\", \"week\", \"day\", \"hour\", \"minute\", \"second\"],\n languages: {},\n halfUnit: true\n }, passedOptions);\n\n }",
"function humanizer (passedOptions) {\n\t var result = function humanizer (ms, humanizerOptions) {\n\t var options = extend({}, result, humanizerOptions || {})\n\t return doHumanization(ms, options)\n\t }\n\t\n\t return extend(result, {\n\t language: 'en',\n\t delimiter: ', ',\n\t spacer: ' ',\n\t units: ['y', 'mo', 'w', 'd', 'h', 'm', 's'],\n\t languages: {},\n\t round: false,\n\t unitMeasures: {\n\t y: 31557600000,\n\t mo: 2629800000,\n\t w: 604800000,\n\t d: 86400000,\n\t h: 3600000,\n\t m: 60000,\n\t s: 1000,\n\t ms: 1\n\t }\n\t }, passedOptions)\n\t }",
"function humanizer (passedOptions) {\n var result = function humanizer (ms, humanizerOptions) {\n var options = extend({}, result, humanizerOptions || {})\n return doHumanization(ms, options)\n }\n\n return extend(result, {\n language: 'en',\n delimiter: ', ',\n spacer: ' ',\n conjunction: '',\n serialComma: true,\n units: ['y', 'mo', 'w', 'd', 'h', 'm', 's'],\n languages: {},\n round: false,\n unitMeasures: {\n y: 31557600000,\n mo: 2629800000,\n w: 604800000,\n d: 86400000,\n h: 3600000,\n m: 60000,\n s: 1000,\n ms: 1\n }\n }, passedOptions)\n }",
"function humanizer(passedOptions) {\n var result = function humanizer(ms, humanizerOptions) {\n const options = extend({}, result, humanizerOptions || {});\n return doHumanization(ms, options);\n };\n\n return extend(result, {\n language: 'en',\n delimiter: ', ',\n spacer: ' ',\n conjunction: '',\n serialComma: true,\n units: ['y', 'mo', 'w', 'd', 'h', 'm', 's'],\n languages: {},\n round: false,\n unitMeasures: {\n y: 31557600000,\n mo: 2629800000,\n w: 604800000,\n d: 86400000,\n h: 3600000,\n m: 60000,\n s: 1000,\n ms: 1,\n },\n }, passedOptions);\n }",
"function defaultScoreFn(x) {\n return x;\n }",
"function defaultFormatter(text){\n return text;\n}",
"function mk_getkw(kw,defaults){\n return function(l){\n return obj.choice(kw,l,defaults[l]);\n };\n}",
"function meaningOfLife(defval = 42) {\n return 'The meaning of life is ' + defval;\n}",
"function humanize(str) {\n\tif (str == null || str === '') return '';\n\tstr = (`${str}`).replace(/[-_\\s]+(.)?/g, (match, c) => (c ? c.toUpperCase() : ''));\n\treturn str.slice(0, 1).toUpperCase() + str.slice(1).replace(/([A-Z])/g, ' $1');\n}",
"function defaultFirst(a = 1, b) { //It is usually recommended to put all default parameters at the end of a list of parameters,\n return a + b\n}",
"function meaningOfLife(test = 42) {\n return \"The meaning of life is \" + test;\n }",
"function defaultParams() {\n var defaultFunction = function defaultFunction() {\n console.log(\"Repeater.js error: No function specified.\");\n };\n\n var defaults = {\n functionToRepeat: defaultFunction,\n delay: 0,\n argsArray: [],\n maxRepeats: null,\n timeLimit: null,\n runFirst: false\n };\n\n return defaults;\n }",
"function foo( { a = 10, b = 20 } = {} ) {\n console.log( `[defaults for function arguments] a = ${a}, b = ${b}` );\n}",
"function defaultFor(arg, val) { \n\t\treturn typeof arg !== 'undefined' ? arg : val; \n\t}",
"function meaningOfLife(x = 42) {\n return \"The meaning of life is \" + x;\n}",
"function defaultFor(arg, val) { \n\treturn typeof arg !== 'undefined' ? arg : val; \n}",
"function applyDefaultNamesData() {\n // name, method, min length, max length, letters to allow dublication, multi-word name rate\n nameBases = [ // min; max; mean; common\n {name: \"German\", method: \"let-to-syl\", min: 4, max: 11, d: \"lt\", m: 0.1}, // real: 3; 17; 8.6; 8\n {name: \"English\", method: \"let-to-syl\", min: 5, max: 10, d: \"\", m: 0.3}, // real: 4; 13; 7.9; 8\n {name: \"French\", method: \"let-to-syl\", min: 4, max: 10, d: \"lns\", m: 0.3}, // real: 3; 15; 7.6; 6\n {name: \"Italian\", method: \"let-to-syl\", min: 4, max: 11, d: \"clrt\", m: 0.2}, // real: 4; 14; 7.7; 7\n {name: \"Castillian\", method: \"let-to-syl\", min: 4, max: 10, d: \"lr\", m: 0}, // real: 2; 13; 7.5; 8\n {name: \"Ruthenian\", method: \"let-to-syl\", min: 4, max: 9, d: \"\", m: 0}, // real: 3; 12; 7.1; 7\n {name: \"Nordic\", method: \"let-to-syl\", min: 5, max: 9, d: \"kln\", m: 0.1}, // real: 3; 12; 7.5; 6\n {name: \"Greek\", method: \"let-to-syl\", min: 4, max: 10, d: \"ls\", m: 0.2}, // real: 3; 14; 7.1; 6\n {name: \"Roman\", method: \"let-to-syl\", min: 5, max: 10, d: \"\", m: 1}, // real: 3; 15; 8.0; 7\n {name: \"Finnic\", method: \"let-to-syl\", min: 3, max: 10, d: \"aktu\", m: 0}, // real: 3; 13; 7.5; 6\n {name: \"Korean\", method: \"let-to-syl\", min: 5, max: 10, d: \"\", m: 0}, // real: 3; 13; 6.8; 7\n {name: \"Chinese\", method: \"let-to-syl\", min: 5, max: 9, d: \"\", m: 0}, // real: 4; 11; 6.9; 6\n {name: \"Japanese\", method: \"let-to-syl\", min: 3, max: 9, d: \"\", m: 0}, // real: 2; 15; 6.8; 6\n {name: \"Portuguese\", method: \"let-to-syl\", min: 4, max: 10, d: \"r\", m: 0.1}, // real: 3; 16; 7.5; 8\n {name: \"Nahuatl\", method: \"let-to-syl\", min: 5, max: 12, d: \"l\", m: 0} // real: 5; 18; 9.2; 8\n ];\n nameBase = [\n [\"Achern\",\"Aichhalden\",\"Aitern\",\"Albbruck\",\"Alpirsbach\",\"Altensteig\",\"Althengstett\",\"Appenweier\",\"Auggen\",\"Wildbad\",\"Badenen\",\"Badenweiler\",\"Baiersbronn\",\"Ballrechten\",\"Bellingen\",\"Berghaupten\",\"Bernau\",\"Biberach\",\"Biederbach\",\"Binzen\",\"Birkendorf\",\"Birkenfeld\",\"Bischweier\",\"Blumberg\",\"Bollen\",\"Bollschweil\",\"Bonndorf\",\"Bosingen\",\"Braunlingen\",\"Breisach\",\"Breisgau\",\"Breitnau\",\"Brigachtal\",\"Buchenbach\",\"Buggingen\",\"Buhl\",\"Buhlertal\",\"Calw\",\"Dachsberg\",\"Dobel\",\"Donaueschingen\",\"Dornhan\",\"Dornstetten\",\"Dottingen\",\"Dunningen\",\"Durbach\",\"Durrheim\",\"Ebhausen\",\"Ebringen\",\"Efringen\",\"Egenhausen\",\"Ehrenkirchen\",\"Ehrsberg\",\"Eimeldingen\",\"Eisenbach\",\"Elzach\",\"Elztal\",\"Emmendingen\",\"Endingen\",\"Engelsbrand\",\"Enz\",\"Enzklosterle\",\"Eschbronn\",\"Ettenheim\",\"Ettlingen\",\"Feldberg\",\"Fischerbach\",\"Fischingen\",\"Fluorn\",\"Forbach\",\"Freiamt\",\"Freiburg\",\"Freudenstadt\",\"Friedenweiler\",\"Friesenheim\",\"Frohnd\",\"Furtwangen\",\"Gaggenau\",\"Geisingen\",\"Gengenbach\",\"Gernsbach\",\"Glatt\",\"Glatten\",\"Glottertal\",\"Gorwihl\",\"Gottenheim\",\"Grafenhausen\",\"Grenzach\",\"Griesbach\",\"Gutach\",\"Gutenbach\",\"Hag\",\"Haiterbach\",\"Hardt\",\"Harmersbach\",\"Hasel\",\"Haslach\",\"Hausach\",\"Hausen\",\"Hausern\",\"Heitersheim\",\"Herbolzheim\",\"Herrenalb\",\"Herrischried\",\"Hinterzarten\",\"Hochenschwand\",\"Hofen\",\"Hofstetten\",\"Hohberg\",\"Horb\",\"Horben\",\"Hornberg\",\"Hufingen\",\"Ibach\",\"Ihringen\",\"Inzlingen\",\"Kandern\",\"Kappel\",\"Kappelrodeck\",\"Karlsbad\",\"Karlsruhe\",\"Kehl\",\"Keltern\",\"Kippenheim\",\"Kirchzarten\",\"Konigsfeld\",\"Krozingen\",\"Kuppenheim\",\"Kussaberg\",\"Lahr\",\"Lauchringen\",\"Lauf\",\"Laufenburg\",\"Lautenbach\",\"Lauterbach\",\"Lenzkirch\",\"Liebenzell\",\"Loffenau\",\"Loffingen\",\"Lorrach\",\"Lossburg\",\"Mahlberg\",\"Malsburg\",\"Malsch\",\"March\",\"Marxzell\",\"Marzell\",\"Maulburg\",\"Monchweiler\",\"Muhlenbach\",\"Mullheim\",\"Munstertal\",\"Murg\",\"Nagold\",\"Neubulach\",\"Neuenburg\",\"Neuhausen\",\"Neuried\",\"Neuweiler\",\"Niedereschach\",\"Nordrach\",\"Oberharmersbach\",\"Oberkirch\",\"Oberndorf\",\"Oberbach\",\"Oberried\",\"Oberwolfach\",\"Offenburg\",\"Ohlsbach\",\"Oppenau\",\"Ortenberg\",\"otigheim\",\"Ottenhofen\",\"Ottersweier\",\"Peterstal\",\"Pfaffenweiler\",\"Pfalzgrafenweiler\",\"Pforzheim\",\"Rastatt\",\"Renchen\",\"Rheinau\",\"Rheinfelden\",\"Rheinmunster\",\"Rickenbach\",\"Rippoldsau\",\"Rohrdorf\",\"Rottweil\",\"Rummingen\",\"Rust\",\"Sackingen\",\"Sasbach\",\"Sasbachwalden\",\"Schallbach\",\"Schallstadt\",\"Schapbach\",\"Schenkenzell\",\"Schiltach\",\"Schliengen\",\"Schluchsee\",\"Schomberg\",\"Schonach\",\"Schonau\",\"Schonenberg\",\"Schonwald\",\"Schopfheim\",\"Schopfloch\",\"Schramberg\",\"Schuttertal\",\"Schwenningen\",\"Schworstadt\",\"Seebach\",\"Seelbach\",\"Seewald\",\"Sexau\",\"Simmersfeld\",\"Simonswald\",\"Sinzheim\",\"Solden\",\"Staufen\",\"Stegen\",\"Steinach\",\"Steinen\",\"Steinmauern\",\"Straubenhardt\",\"Stuhlingen\",\"Sulz\",\"Sulzburg\",\"Teinach\",\"Tiefenbronn\",\"Tiengen\",\"Titisee\",\"Todtmoos\",\"Todtnau\",\"Todtnauberg\",\"Triberg\",\"Tunau\",\"Tuningen\",\"uhlingen\",\"Unterkirnach\",\"Reichenbach\",\"Utzenfeld\",\"Villingen\",\"Villingendorf\",\"Vogtsburg\",\"Vohrenbach\",\"Waldachtal\",\"Waldbronn\",\"Waldkirch\",\"Waldshut\",\"Wehr\",\"Weil\",\"Weilheim\",\"Weisenbach\",\"Wembach\",\"Wieden\",\"Wiesental\",\"Wildberg\",\"Winzeln\",\"Wittlingen\",\"Wittnau\",\"Wolfach\",\"Wutach\",\"Wutoschingen\",\"Wyhlen\",\"Zavelstein\"],\n [\"Abingdon\",\"Albrighton\",\"Alcester\",\"Almondbury\",\"Altrincham\",\"Amersham\",\"Andover\",\"Appleby\",\"Ashboume\",\"Atherstone\",\"Aveton\",\"Axbridge\",\"Aylesbury\",\"Baldock\",\"Bamburgh\",\"Barton\",\"Basingstoke\",\"Berden\",\"Bere\",\"Berkeley\",\"Berwick\",\"Betley\",\"Bideford\",\"Bingley\",\"Birmingham\",\"Blandford\",\"Blechingley\",\"Bodmin\",\"Bolton\",\"Bootham\",\"Boroughbridge\",\"Boscastle\",\"Bossinney\",\"Bramber\",\"Brampton\",\"Brasted\",\"Bretford\",\"Bridgetown\",\"Bridlington\",\"Bromyard\",\"Bruton\",\"Buckingham\",\"Bungay\",\"Burton\",\"Calne\",\"Cambridge\",\"Canterbury\",\"Carlisle\",\"Castleton\",\"Caus\",\"Charmouth\",\"Chawleigh\",\"Chichester\",\"Chillington\",\"Chinnor\",\"Chipping\",\"Chisbury\",\"Cleobury\",\"Clifford\",\"Clifton\",\"Clitheroe\",\"Cockermouth\",\"Coleshill\",\"Combe\",\"Congleton\",\"Crafthole\",\"Crediton\",\"Cuddenbeck\",\"Dalton\",\"Darlington\",\"Dodbrooke\",\"Drax\",\"Dudley\",\"Dunstable\",\"Dunster\",\"Dunwich\",\"Durham\",\"Dymock\",\"Exeter\",\"Exning\",\"Faringdon\",\"Felton\",\"Fenny\",\"Finedon\",\"Flookburgh\",\"Fowey\",\"Frampton\",\"Gateshead\",\"Gatton\",\"Godmanchester\",\"Grampound\",\"Grantham\",\"Guildford\",\"Halesowen\",\"Halton\",\"Harbottle\",\"Harlow\",\"Hatfield\",\"Hatherleigh\",\"Haydon\",\"Helston\",\"Henley\",\"Hertford\",\"Heytesbury\",\"Hinckley\",\"Hitchin\",\"Holme\",\"Hornby\",\"Horsham\",\"Kendal\",\"Kenilworth\",\"Kilkhampton\",\"Kineton\",\"Kington\",\"Kinver\",\"Kirby\",\"Knaresborough\",\"Knutsford\",\"Launceston\",\"Leighton\",\"Lewes\",\"Linton\",\"Louth\",\"Luton\",\"Lyme\",\"Lympstone\",\"Macclesfield\",\"Madeley\",\"Malborough\",\"Maldon\",\"Manchester\",\"Manningtree\",\"Marazion\",\"Marlborough\",\"Marshfield\",\"Mere\",\"Merryfield\",\"Middlewich\",\"Midhurst\",\"Milborne\",\"Mitford\",\"Modbury\",\"Montacute\",\"Mousehole\",\"Newbiggin\",\"Newborough\",\"Newbury\",\"Newenden\",\"Newent\",\"Norham\",\"Northleach\",\"Noss\",\"Oakham\",\"Olney\",\"Orford\",\"Ormskirk\",\"Oswestry\",\"Padstow\",\"Paignton\",\"Penkneth\",\"Penrith\",\"Penzance\",\"Pershore\",\"Petersfield\",\"Pevensey\",\"Pickering\",\"Pilton\",\"Pontefract\",\"Portsmouth\",\"Preston\",\"Quatford\",\"Reading\",\"Redcliff\",\"Retford\",\"Rockingham\",\"Romney\",\"Rothbury\",\"Rothwell\",\"Salisbury\",\"Saltash\",\"Seaford\",\"Seasalter\",\"Sherston\",\"Shifnal\",\"Shoreham\",\"Sidmouth\",\"Skipsea\",\"Skipton\",\"Solihull\",\"Somerton\",\"Southam\",\"Southwark\",\"Standon\",\"Stansted\",\"Stapleton\",\"Stottesdon\",\"Sudbury\",\"Swavesey\",\"Tamerton\",\"Tarporley\",\"Tetbury\",\"Thatcham\",\"Thaxted\",\"Thetford\",\"Thornbury\",\"Tintagel\",\"Tiverton\",\"Torksey\",\"Totnes\",\"Towcester\",\"Tregoney\",\"Trematon\",\"Tutbury\",\"Uxbridge\",\"Wallingford\",\"Wareham\",\"Warenmouth\",\"Wargrave\",\"Warton\",\"Watchet\",\"Watford\",\"Wendover\",\"Westbury\",\"Westcheap\",\"Weymouth\",\"Whitford\",\"Wickwar\",\"Wigan\",\"Wigmore\",\"Winchelsea\",\"Winkleigh\",\"Wiscombe\",\"Witham\",\"Witheridge\",\"Wiveliscombe\",\"Woodbury\",\"Yeovil\"],\n [\"Adon\",\"Aillant\",\"Amilly\",\"Andonville\",\"Ardon\",\"Artenay\",\"Ascheres\",\"Ascoux\",\"Attray\",\"Aubin\",\"Audeville\",\"Aulnay\",\"Autruy\",\"Auvilliers\",\"Auxy\",\"Aveyron\",\"Baccon\",\"Bardon\",\"Barville\",\"Batilly\",\"Baule\",\"Bazoches\",\"Beauchamps\",\"Beaugency\",\"Beaulieu\",\"Beaune\",\"Bellegarde\",\"Boesses\",\"Boigny\",\"Boiscommun\",\"Boismorand\",\"Boisseaux\",\"Bondaroy\",\"Bonnee\",\"Bonny\",\"Bordes\",\"Bou\",\"Bougy\",\"Bouilly\",\"Boulay\",\"Bouzonville\",\"Bouzy\",\"Boynes\",\"Bray\",\"Breteau\",\"Briare\",\"Briarres\",\"Bricy\",\"Bromeilles\",\"Bucy\",\"Cepoy\",\"Cercottes\",\"Cerdon\",\"Cernoy\",\"Cesarville\",\"Chailly\",\"Chaingy\",\"Chalette\",\"Chambon\",\"Champoulet\",\"Chanteau\",\"Chantecoq\",\"Chapell\",\"Charme\",\"Charmont\",\"Charsonville\",\"Chateau\",\"Chateauneuf\",\"Chatel\",\"Chatenoy\",\"Chatillon\",\"Chaussy\",\"Checy\",\"Chevannes\",\"Chevillon\",\"Chevilly\",\"Chevry\",\"Chilleurs\",\"Choux\",\"Chuelles\",\"Clery\",\"Coinces\",\"Coligny\",\"Combleux\",\"Combreux\",\"Conflans\",\"Corbeilles\",\"Corquilleroy\",\"Cortrat\",\"Coudroy\",\"Coullons\",\"Coulmiers\",\"Courcelles\",\"Courcy\",\"Courtemaux\",\"Courtempierre\",\"Courtenay\",\"Cravant\",\"Crottes\",\"Dadonville\",\"Dammarie\",\"Dampierre\",\"Darvoy\",\"Desmonts\",\"Dimancheville\",\"Donnery\",\"Dordives\",\"Dossainville\",\"Douchy\",\"Dry\",\"Echilleuses\",\"Egry\",\"Engenville\",\"Epieds\",\"Erceville\",\"Ervauville\",\"Escrennes\",\"Escrignelles\",\"Estouy\",\"Faverelles\",\"Fay\",\"Feins\",\"Ferolles\",\"Ferrieres\",\"Fleury\",\"Fontenay\",\"Foret\",\"Foucherolles\",\"Freville\",\"Gatinais\",\"Gaubertin\",\"Gemigny\",\"Germigny\",\"Gidy\",\"Gien\",\"Girolles\",\"Givraines\",\"Gondreville\",\"Grangermont\",\"Greneville\",\"Griselles\",\"Guigneville\",\"Guilly\",\"Gyleslonains\",\"Huetre\",\"Huisseau\",\"Ingrannes\",\"Ingre\",\"Intville\",\"Isdes\",\"Jargeau\",\"Jouy\",\"Juranville\",\"Bussiere\",\"Laas\",\"Ladon\",\"Lailly\",\"Langesse\",\"Leouville\",\"Ligny\",\"Lombreuil\",\"Lorcy\",\"Lorris\",\"Loury\",\"Louzouer\",\"Malesherbois\",\"Marcilly\",\"Mardie\",\"Mareau\",\"Marigny\",\"Marsainvilliers\",\"Melleroy\",\"Menestreau\",\"Merinville\",\"Messas\",\"Meung\",\"Mezieres\",\"Migneres\",\"Mignerette\",\"Mirabeau\",\"Montargis\",\"Montbarrois\",\"Montbouy\",\"Montcresson\",\"Montereau\",\"Montigny\",\"Montliard\",\"Mormant\",\"Morville\",\"Moulinet\",\"Moulon\",\"Nancray\",\"Nargis\",\"Nesploy\",\"Neuville\",\"Neuvy\",\"Nevoy\",\"Nibelle\",\"Nogent\",\"Noyers\",\"Ocre\",\"Oison\",\"Olivet\",\"Ondreville\",\"Onzerain\",\"Orleans\",\"Ormes\",\"Orville\",\"Oussoy\",\"Outarville\",\"Ouzouer\",\"Pannecieres\",\"Pannes\",\"Patay\",\"Paucourt\",\"Pers\",\"Pierrefitte\",\"Pithiverais\",\"Pithiviers\",\"Poilly\",\"Potier\",\"Prefontaines\",\"Presnoy\",\"Pressigny\",\"Puiseaux\",\"Quiers\",\"Ramoulu\",\"Rebrechien\",\"Rouvray\",\"Rozieres\",\"Rozoy\",\"Ruan\",\"Sandillon\",\"Santeau\",\"Saran\",\"Sceaux\",\"Seichebrieres\",\"Semoy\",\"Sennely\",\"Sermaises\",\"Sigloy\",\"Solterre\",\"Sougy\",\"Sully\",\"Sury\",\"Tavers\",\"Thignonville\",\"Thimory\",\"Thorailles\",\"Thou\",\"Tigy\",\"Tivernon\",\"Tournoisis\",\"Trainou\",\"Treilles\",\"Trigueres\",\"Trinay\",\"Vannes\",\"Varennes\",\"Vennecy\",\"Vieilles\",\"Vienne\",\"Viglain\",\"Vignes\",\"Villamblain\",\"Villemandeur\",\"Villemoutiers\",\"Villemurlin\",\"Villeneuve\",\"Villereau\",\"Villevoques\",\"Villorceau\",\"Vimory\",\"Vitry\",\"Vrigny\",\"Ivre\"],\n [\"Accumoli\",\"Acquafondata\",\"Acquapendente\",\"Acuto\",\"Affile\",\"Agosta\",\"Alatri\",\"Albano\",\"Allumiere\",\"Alvito\",\"Amaseno\",\"Amatrice\",\"Anagni\",\"Anguillara\",\"Anticoli\",\"Antrodoco\",\"Anzio\",\"Aprilia\",\"Aquino\",\"Arce\",\"Arcinazzo\",\"Ardea\",\"Ariccia\",\"Arlena\",\"Arnara\",\"Arpino\",\"Arsoli\",\"Artena\",\"Ascrea\",\"Atina\",\"Ausonia\",\"Bagnoregio\",\"Barbarano\",\"Bassano\",\"Bassiano\",\"Bellegra\",\"Belmonte\",\"Blera\",\"Bolsena\",\"Bomarzo\",\"Borbona\",\"Borgo\",\"Borgorose\",\"Boville\",\"Bracciano\",\"Broccostella\",\"Calcata\",\"Camerata\",\"Campagnano\",\"Campodimele\",\"Campoli\",\"Canale\",\"Canepina\",\"Canino\",\"Cantalice\",\"Cantalupo\",\"Canterano\",\"Capena\",\"Capodimonte\",\"Capranica\",\"Caprarola\",\"Carbognano\",\"Casalattico\",\"Casalvieri\",\"Casape\",\"Casaprota\",\"Casperia\",\"Cassino\",\"Castelforte\",\"Castelliri\",\"Castello\",\"Castelnuovo\",\"Castiglione\",\"Castro\",\"Castrocielo\",\"Cave\",\"Ceccano\",\"Celleno\",\"Cellere\",\"Ceprano\",\"Cerreto\",\"Cervara\",\"Cervaro\",\"Cerveteri\",\"Ciampino\",\"Ciciliano\",\"Cineto\",\"Cisterna\",\"Cittaducale\",\"Cittareale\",\"Civita\",\"Civitavecchia\",\"Civitella\",\"Colfelice\",\"Collalto\",\"Colle\",\"Colleferro\",\"Collegiove\",\"Collepardo\",\"Collevecchio\",\"Colli\",\"Colonna\",\"Concerviano\",\"Configni\",\"Contigliano\",\"Corchiano\",\"Coreno\",\"Cori\",\"Cottanello\",\"Esperia\",\"Fabrica\",\"Faleria\",\"Falvaterra\",\"Fara\",\"Farnese\",\"Ferentino\",\"Fiamignano\",\"Fiano\",\"Filacciano\",\"Filettino\",\"Fiuggi\",\"Fiumicino\",\"Fondi\",\"Fontana\",\"Fonte\",\"Fontechiari\",\"Forano\",\"Formello\",\"Formia\",\"Frascati\",\"Frasso\",\"Frosinone\",\"Fumone\",\"Gaeta\",\"Gallese\",\"Gallicano\",\"Gallinaro\",\"Gavignano\",\"Genazzano\",\"Genzano\",\"Gerano\",\"Giuliano\",\"Gorga\",\"Gradoli\",\"Graffignano\",\"Greccio\",\"Grottaferrata\",\"Grotte\",\"Guarcino\",\"Guidonia\",\"Ischia\",\"Isola\",\"Itri\",\"Jenne\",\"Labico\",\"Labro\",\"Ladispoli\",\"Lanuvio\",\"Lariano\",\"Latera\",\"Lenola\",\"Leonessa\",\"Licenza\",\"Longone\",\"Lubriano\",\"Maenza\",\"Magliano\",\"Mandela\",\"Manziana\",\"Marano\",\"Marcellina\",\"Marcetelli\",\"Marino\",\"Marta\",\"Mazzano\",\"Mentana\",\"Micigliano\",\"Minturno\",\"Mompeo\",\"Montalto\",\"Montasola\",\"Monte\",\"Montebuono\",\"Montefiascone\",\"Monteflavio\",\"Montelanico\",\"Monteleone\",\"Montelibretti\",\"Montenero\",\"Monterosi\",\"Monterotondo\",\"Montopoli\",\"Montorio\",\"Moricone\",\"Morlupo\",\"Morolo\",\"Morro\",\"Nazzano\",\"Nemi\",\"Nepi\",\"Nerola\",\"Nespolo\",\"Nettuno\",\"Norma\",\"Olevano\",\"Onano\",\"Oriolo\",\"Orte\",\"Orvinio\",\"Paganico\",\"Palestrina\",\"Paliano\",\"Palombara\",\"Pastena\",\"Patrica\",\"Percile\",\"Pescorocchiano\",\"Pescosolido\",\"Petrella\",\"Piansano\",\"Picinisco\",\"Pico\",\"Piedimonte\",\"Piglio\",\"Pignataro\",\"Pisoniano\",\"Pofi\",\"Poggio\",\"Poli\",\"Pomezia\",\"Pontecorvo\",\"Pontinia\",\"Ponza\",\"Ponzano\",\"Posta\",\"Pozzaglia\",\"Priverno\",\"Proceno\",\"Prossedi\",\"Riano\",\"Rieti\",\"Rignano\",\"Riofreddo\",\"Ripi\",\"Rivodutri\",\"Rocca\",\"Roccagiovine\",\"Roccagorga\",\"Roccantica\",\"Roccasecca\",\"Roiate\",\"Ronciglione\",\"Roviano\",\"Sabaudia\",\"Sacrofano\",\"Salisano\",\"Sambuci\",\"Santa\",\"Santi\",\"Santopadre\",\"Saracinesco\",\"Scandriglia\",\"Segni\",\"Selci\",\"Sermoneta\",\"Serrone\",\"Settefrati\",\"Sezze\",\"Sgurgola\",\"Sonnino\",\"Sora\",\"Soriano\",\"Sperlonga\",\"Spigno\",\"Stimigliano\",\"Strangolagalli\",\"Subiaco\",\"Supino\",\"Sutri\",\"Tarano\",\"Tarquinia\",\"Terelle\",\"Terracina\",\"Tessennano\",\"Tivoli\",\"Toffia\",\"Tolfa\",\"Torre\",\"Torri\",\"Torrice\",\"Torricella\",\"Torrita\",\"Trevi\",\"Trevignano\",\"Trivigliano\",\"Turania\",\"Tuscania\",\"Vacone\",\"Valentano\",\"Vallecorsa\",\"Vallemaio\",\"Vallepietra\",\"Vallerano\",\"Vallerotonda\",\"Vallinfreda\",\"Valmontone\",\"Varco\",\"Vasanello\",\"Vejano\",\"Velletri\",\"Ventotene\",\"Veroli\",\"Vetralla\",\"Vicalvi\",\"Vico\",\"Vicovaro\",\"Vignanello\",\"Viterbo\",\"Viticuso\",\"Vitorchiano\",\"Vivaro\",\"Zagarolo\"],\n [\"Abanades\",\"Ablanque\",\"Adobes\",\"Ajofrin\",\"Alameda\",\"Alaminos\",\"Alarilla\",\"Albalate\",\"Albares\",\"Albarreal\",\"Albendiego\",\"Alcabon\",\"Alcanizo\",\"Alcaudete\",\"Alcocer\",\"Alcolea\",\"Alcoroches\",\"Aldea\",\"Aldeanueva\",\"Algar\",\"Algora\",\"Alhondiga\",\"Alique\",\"Almadrones\",\"Almendral\",\"Almoguera\",\"Almonacid\",\"Almorox\",\"Alocen\",\"Alovera\",\"Alustante\",\"Angon\",\"Anguita\",\"Anover\",\"Anquela\",\"Arbancon\",\"Arbeteta\",\"Arcicollar\",\"Argecilla\",\"Arges\",\"Armallones\",\"Armuna\",\"Arroyo\",\"Atanzon\",\"Atienza\",\"Aunon\",\"Azuqueca\",\"Azutan\",\"Baides\",\"Banos\",\"Banuelos\",\"Barcience\",\"Bargas\",\"Barriopedro\",\"Belvis\",\"Berninches\",\"Borox\",\"Brihuega\",\"Budia\",\"Buenaventura\",\"Bujalaro\",\"Burguillos\",\"Burujon\",\"Bustares\",\"Cabanas\",\"Cabanillas\",\"Calera\",\"Caleruela\",\"Calzada\",\"Camarena\",\"Campillo\",\"Camunas\",\"Canizar\",\"Canredondo\",\"Cantalojas\",\"Cardiel\",\"Carmena\",\"Carranque\",\"Carriches\",\"Casa\",\"Casarrubios\",\"Casas\",\"Casasbuenas\",\"Caspuenas\",\"Castejon\",\"Castellar\",\"Castilforte\",\"Castillo\",\"Castilnuevo\",\"Cazalegas\",\"Cebolla\",\"Cedillo\",\"Cendejas\",\"Centenera\",\"Cervera\",\"Checa\",\"Chequilla\",\"Chillaron\",\"Chiloeches\",\"Chozas\",\"Chueca\",\"Cifuentes\",\"Cincovillas\",\"Ciruelas\",\"Ciruelos\",\"Cobeja\",\"Cobeta\",\"Cobisa\",\"Cogollor\",\"Cogolludo\",\"Condemios\",\"Congostrina\",\"Consuegra\",\"Copernal\",\"Corduente\",\"Corral\",\"Cuerva\",\"Domingo\",\"Dosbarrios\",\"Driebes\",\"Duron\",\"El\",\"Embid\",\"Erustes\",\"Escalona\",\"Escalonilla\",\"Escamilla\",\"Escariche\",\"Escopete\",\"Espinosa\",\"Espinoso\",\"Esplegares\",\"Esquivias\",\"Estables\",\"Estriegana\",\"Fontanar\",\"Fuembellida\",\"Fuensalida\",\"Fuentelsaz\",\"Gajanejos\",\"Galve\",\"Galvez\",\"Garciotum\",\"Gascuena\",\"Gerindote\",\"Guadamur\",\"Henche\",\"Heras\",\"Herreria\",\"Herreruela\",\"Hijes\",\"Hinojosa\",\"Hita\",\"Hombrados\",\"Hontanar\",\"Hontoba\",\"Horche\",\"Hormigos\",\"Huecas\",\"Huermeces\",\"Huerta\",\"Hueva\",\"Humanes\",\"Illan\",\"Illana\",\"Illescas\",\"Iniestola\",\"Irueste\",\"Jadraque\",\"Jirueque\",\"Lagartera\",\"Las\",\"Layos\",\"Ledanca\",\"Lillo\",\"Lominchar\",\"Loranca\",\"Los\",\"Lucillos\",\"Lupiana\",\"Luzaga\",\"Luzon\",\"Madridejos\",\"Magan\",\"Majaelrayo\",\"Malaga\",\"Malaguilla\",\"Malpica\",\"Mandayona\",\"Mantiel\",\"Manzaneque\",\"Maqueda\",\"Maranchon\",\"Marchamalo\",\"Marjaliza\",\"Marrupe\",\"Mascaraque\",\"Masegoso\",\"Matarrubia\",\"Matillas\",\"Mazarete\",\"Mazuecos\",\"Medranda\",\"Megina\",\"Mejorada\",\"Mentrida\",\"Mesegar\",\"Miedes\",\"Miguel\",\"Millana\",\"Milmarcos\",\"Mirabueno\",\"Miralrio\",\"Mocejon\",\"Mochales\",\"Mohedas\",\"Molina\",\"Monasterio\",\"Mondejar\",\"Montarron\",\"Mora\",\"Moratilla\",\"Morenilla\",\"Muduex\",\"Nambroca\",\"Navalcan\",\"Negredo\",\"Noblejas\",\"Noez\",\"Nombela\",\"Noves\",\"Numancia\",\"Nuno\",\"Ocana\",\"Ocentejo\",\"Olias\",\"Olmeda\",\"Ontigola\",\"Orea\",\"Orgaz\",\"Oropesa\",\"Otero\",\"Palmaces\",\"Palomeque\",\"Pantoja\",\"Pardos\",\"Paredes\",\"Pareja\",\"Parrillas\",\"Pastrana\",\"Pelahustan\",\"Penalen\",\"Penalver\",\"Pepino\",\"Peralejos\",\"Peralveche\",\"Pinilla\",\"Pioz\",\"Piqueras\",\"Polan\",\"Portillo\",\"Poveda\",\"Pozo\",\"Pradena\",\"Prados\",\"Puebla\",\"Puerto\",\"Pulgar\",\"Quer\",\"Quero\",\"Quintanar\",\"Quismondo\",\"Rebollosa\",\"Recas\",\"Renera\",\"Retamoso\",\"Retiendas\",\"Riba\",\"Rielves\",\"Rillo\",\"Riofrio\",\"Robledillo\",\"Robledo\",\"Romanillos\",\"Romanones\",\"Rueda\",\"Sacecorbo\",\"Sacedon\",\"Saelices\",\"Salmeron\",\"San\",\"Santa\",\"Santiuste\",\"Santo\",\"Sartajada\",\"Sauca\",\"Sayaton\",\"Segurilla\",\"Selas\",\"Semillas\",\"Sesena\",\"Setiles\",\"Sevilleja\",\"Sienes\",\"Siguenza\",\"Solanillos\",\"Somolinos\",\"Sonseca\",\"Sotillo\",\"Sotodosos\",\"Talavera\",\"Tamajon\",\"Taragudo\",\"Taravilla\",\"Tartanedo\",\"Tembleque\",\"Tendilla\",\"Terzaga\",\"Tierzo\",\"Tordellego\",\"Tordelrabano\",\"Tordesilos\",\"Torija\",\"Torralba\",\"Torre\",\"Torrecilla\",\"Torrecuadrada\",\"Torrejon\",\"Torremocha\",\"Torrico\",\"Torrijos\",\"Torrubia\",\"Tortola\",\"Tortuera\",\"Tortuero\",\"Totanes\",\"Traid\",\"Trijueque\",\"Trillo\",\"Turleque\",\"Uceda\",\"Ugena\",\"Ujados\",\"Urda\",\"Utande\",\"Valdarachas\",\"Valdesotos\",\"Valhermoso\",\"Valtablado\",\"Valverde\",\"Velada\",\"Viana\",\"Vinuelas\",\"Yebes\",\"Yebra\",\"Yelamos\",\"Yeles\",\"Yepes\",\"Yuncler\",\"Yunclillos\",\"Yuncos\",\"Yunquera\",\"Zaorejas\",\"Zarzuela\",\"Zorita\"],\n [\"Belgorod\",\"Beloberezhye\",\"Belyi\",\"Belz\",\"Berestiy\",\"Berezhets\",\"Berezovets\",\"Berezutsk\",\"Bobruisk\",\"Bolonets\",\"Borisov\",\"Borovsk\",\"Bozhesk\",\"Bratslav\",\"Bryansk\",\"Brynsk\",\"Buryn\",\"Byhov\",\"Chechersk\",\"Chemesov\",\"Cheremosh\",\"Cherlen\",\"Chern\",\"Chernigov\",\"Chernitsa\",\"Chernobyl\",\"Chernogorod\",\"Chertoryesk\",\"Chetvertnia\",\"Demyansk\",\"Derevesk\",\"Devyagoresk\",\"Dichin\",\"Dmitrov\",\"Dorogobuch\",\"Dorogobuzh\",\"Drestvin\",\"Drokov\",\"Drutsk\",\"Dubechin\",\"Dubichi\",\"Dubki\",\"Dubkov\",\"Dveren\",\"Galich\",\"Glebovo\",\"Glinsk\",\"Goloty\",\"Gomiy\",\"Gorodets\",\"Gorodische\",\"Gorodno\",\"Gorohovets\",\"Goroshin\",\"Gorval\",\"Goryshon\",\"Holm\",\"Horobor\",\"Hoten\",\"Hotin\",\"Hotmyzhsk\",\"Ilovech\",\"Ivan\",\"Izborsk\",\"Izheslavl\",\"Kamenets\",\"Kanev\",\"Karachev\",\"Karna\",\"Kavarna\",\"Klechesk\",\"Klyapech\",\"Kolomyya\",\"Kolyvan\",\"Kopyl\",\"Korec\",\"Kornik\",\"Korochunov\",\"Korshev\",\"Korsun\",\"Koshkin\",\"Kotelno\",\"Kovyla\",\"Kozelsk\",\"Kozelsk\",\"Kremenets\",\"Krichev\",\"Krylatsk\",\"Ksniatin\",\"Kulatsk\",\"Kursk\",\"Kursk\",\"Lebedev\",\"Lida\",\"Logosko\",\"Lomihvost\",\"Loshesk\",\"Loshichi\",\"Lubech\",\"Lubno\",\"Lubutsk\",\"Lutsk\",\"Luchin\",\"Luki\",\"Lukoml\",\"Luzha\",\"Lvov\",\"Mtsensk\",\"Mdin\",\"Medniki\",\"Melecha\",\"Merech\",\"Meretsk\",\"Mescherskoe\",\"Meshkovsk\",\"Metlitsk\",\"Mezetsk\",\"Mglin\",\"Mihailov\",\"Mikitin\",\"Mikulino\",\"Miloslavichi\",\"Mogilev\",\"Mologa\",\"Moreva\",\"Mosalsk\",\"Moschiny\",\"Mozyr\",\"Mstislav\",\"Mstislavets\",\"Muravin\",\"Nemech\",\"Nemiza\",\"Nerinsk\",\"Nichan\",\"Novgorod\",\"Novogorodok\",\"Obolichi\",\"Obolensk\",\"Obolensk\",\"Oleshsk\",\"Olgov\",\"Omelnik\",\"Opoka\",\"Opoki\",\"Oreshek\",\"Orlets\",\"Osechen\",\"Oster\",\"Ostrog\",\"Ostrov\",\"Perelai\",\"Peremil\",\"Peremyshl\",\"Pererov\",\"Peresechen\",\"Perevitsk\",\"Pereyaslav\",\"Pinsk\",\"Ples\",\"Polotsk\",\"Pronsk\",\"Proposhesk\",\"Punia\",\"Putivl\",\"Rechitsa\",\"Rodno\",\"Rogachev\",\"Romanov\",\"Romny\",\"Roslavl\",\"Rostislavl\",\"Rostovets\",\"Rsha\",\"Ruza\",\"Rybchesk\",\"Rylsk\",\"Rzhavesk\",\"Rzhev\",\"Rzhischev\",\"Sambor\",\"Serensk\",\"Serensk\",\"Serpeysk\",\"Shilov\",\"Shuya\",\"Sinech\",\"Sizhka\",\"Skala\",\"Slovensk\",\"Slutsk\",\"Smedin\",\"Sneporod\",\"Snitin\",\"Snovsk\",\"Sochevo\",\"Sokolec\",\"Starica\",\"Starodub\",\"Stepan\",\"Sterzh\",\"Streshin\",\"Sutesk\",\"Svinetsk\",\"Svisloch\",\"Terebovl\",\"Ternov\",\"Teshilov\",\"Teterin\",\"Tiversk\",\"Torchevsk\",\"Toropets\",\"Torzhok\",\"Tripolye\",\"Trubchevsk\",\"Tur\",\"Turov\",\"Usvyaty\",\"Uteshkov\",\"Vasilkov\",\"Velil\",\"Velye\",\"Venev\",\"Venicha\",\"Verderev\",\"Vereya\",\"Veveresk\",\"Viazma\",\"Vidbesk\",\"Vidychev\",\"Voino\",\"Volodimer\",\"Volok\",\"Volyn\",\"Vorobesk\",\"Voronich\",\"Voronok\",\"Vorotynsk\",\"Vrev\",\"Vruchiy\",\"Vselug\",\"Vyatichsk\",\"Vyatka\",\"Vyshegorod\",\"Vyshgorod\",\"Vysokoe\",\"Yagniatin\",\"Yaropolch\",\"Yasenets\",\"Yuryev\",\"Yuryevets\",\"Zaraysk\",\"Zhitomel\",\"Zholvazh\",\"Zizhech\",\"Zubkov\",\"Zudechev\",\"Zvenigorod\"],\n [\"Akureyri\",\"Aldra\",\"Alftanes\",\"Andenes\",\"Austbo\",\"Auvog\",\"Bakkafjordur\",\"Ballangen\",\"Bardal\",\"Beisfjord\",\"Bifrost\",\"Bildudalur\",\"Bjerka\",\"Bjerkvik\",\"Bjorkosen\",\"Bliksvaer\",\"Blokken\",\"Blonduos\",\"Bolga\",\"Bolungarvik\",\"Borg\",\"Borgarnes\",\"Bosmoen\",\"Bostad\",\"Bostrand\",\"Botsvika\",\"Brautarholt\",\"Breiddalsvik\",\"Bringsli\",\"Brunahlid\",\"Budardalur\",\"Byggdakjarni\",\"Dalvik\",\"Djupivogur\",\"Donnes\",\"Drageid\",\"Drangsnes\",\"Egilsstadir\",\"Eiteroga\",\"Elvenes\",\"Engavogen\",\"Ertenvog\",\"Eskifjordur\",\"Evenes\",\"Eyrarbakki\",\"Fagernes\",\"Fallmoen\",\"Fellabaer\",\"Fenes\",\"Finnoya\",\"Fjaer\",\"Fjelldal\",\"Flakstad\",\"Flateyri\",\"Flostrand\",\"Fludir\",\"Gardabær\",\"Gardur\",\"Gimstad\",\"Givaer\",\"Gjeroy\",\"Gladstad\",\"Godoya\",\"Godoynes\",\"Granmoen\",\"Gravdal\",\"Grenivik\",\"Grimsey\",\"Grindavik\",\"Grytting\",\"Hafnir\",\"Halsa\",\"Hauganes\",\"Haugland\",\"Hauknes\",\"Hella\",\"Helland\",\"Hellissandur\",\"Hestad\",\"Higrav\",\"Hnifsdalur\",\"Hofn\",\"Hofsos\",\"Holand\",\"Holar\",\"Holen\",\"Holkestad\",\"Holmavik\",\"Hopen\",\"Hovden\",\"Hrafnagil\",\"Hrisey\",\"Husavik\",\"Husvik\",\"Hvammstangi\",\"Hvanneyri\",\"Hveragerdi\",\"Hvolsvollur\",\"Igeroy\",\"Indre\",\"Inndyr\",\"Innhavet\",\"Innes\",\"Isafjordur\",\"Jarklaustur\",\"Jarnsreykir\",\"Junkerdal\",\"Kaldvog\",\"Kanstad\",\"Karlsoy\",\"Kavosen\",\"Keflavik\",\"Kjelde\",\"Kjerstad\",\"Klakk\",\"Kopasker\",\"Kopavogur\",\"Korgen\",\"Kristnes\",\"Krutoga\",\"Krystad\",\"Kvina\",\"Lande\",\"Laugar\",\"Laugaras\",\"Laugarbakki\",\"Laugarvatn\",\"Laupstad\",\"Leines\",\"Leira\",\"Leiren\",\"Leland\",\"Lenvika\",\"Loding\",\"Lodingen\",\"Lonsbakki\",\"Lopsmarka\",\"Lovund\",\"Luroy\",\"Maela\",\"Melahverfi\",\"Meloy\",\"Mevik\",\"Misvaer\",\"Mornes\",\"Mosfellsbær\",\"Moskenes\",\"Myken\",\"Naurstad\",\"Nesberg\",\"Nesjahverfi\",\"Nesset\",\"Nevernes\",\"Obygda\",\"Ofoten\",\"Ogskardet\",\"Okervika\",\"Oknes\",\"Olafsfjordur\",\"Oldervika\",\"Olstad\",\"Onstad\",\"Oppeid\",\"Oresvika\",\"Orsnes\",\"Orsvog\",\"Osmyra\",\"Overdal\",\"Prestoya\",\"Raudalaekur\",\"Raufarhofn\",\"Reipo\",\"Reykholar\",\"Reykholt\",\"Reykjahlid\",\"Rif\",\"Rinoya\",\"Rodoy\",\"Rognan\",\"Rosvika\",\"Rovika\",\"Salhus\",\"Sanden\",\"Sandgerdi\",\"Sandoker\",\"Sandset\",\"Sandvika\",\"Saudarkrokur\",\"Selfoss\",\"Selsoya\",\"Sennesvik\",\"Setso\",\"Siglufjordur\",\"Silvalen\",\"Skagastrond\",\"Skjerstad\",\"Skonland\",\"Skorvogen\",\"Skrova\",\"Sleneset\",\"Snubba\",\"Softing\",\"Solheim\",\"Solheimar\",\"Sorarnoy\",\"Sorfugloy\",\"Sorland\",\"Sormela\",\"Sorvaer\",\"Sovika\",\"Stamsund\",\"Stamsvika\",\"Stave\",\"Stokka\",\"Stokkseyri\",\"Storjord\",\"Storo\",\"Storvika\",\"Strand\",\"Straumen\",\"Strendene\",\"Sudavik\",\"Sudureyri\",\"Sundoya\",\"Sydalen\",\"Thingeyri\",\"Thorlakshofn\",\"Thorshofn\",\"Tjarnabyggd\",\"Tjotta\",\"Tosbotn\",\"Traelnes\",\"Trofors\",\"Trones\",\"Tverro\",\"Ulvsvog\",\"Unnstad\",\"Utskor\",\"Valla\",\"Vandved\",\"Varmahlid\",\"Vassos\",\"Vevelstad\",\"Vidrek\",\"Vik\",\"Vikholmen\",\"Vogar\",\"Vogehamn\",\"Vopnafjordur\"],\n [\"Abdera\",\"Abila\",\"Abydos\",\"Acanthus\",\"Acharnae\",\"Actium\",\"Adramyttium\",\"Aegae\",\"Aegina\",\"Aegium\",\"Aenus\",\"Agrinion\",\"Aigosthena\",\"Akragas\",\"Akrai\",\"Akrillai\",\"Akroinon\",\"Akrotiri\",\"Alalia\",\"Alexandreia\",\"Alexandretta\",\"Alexandria\",\"Alinda\",\"Amarynthos\",\"Amaseia\",\"Ambracia\",\"Amida\",\"Amisos\",\"Amnisos\",\"Amphicaea\",\"Amphigeneia\",\"Amphipolis\",\"Amphissa\",\"Ankon\",\"Antigona\",\"Antipatrea\",\"Antioch\",\"Antioch\",\"Antiochia\",\"Andros\",\"Apamea\",\"Aphidnae\",\"Apollonia\",\"Argos\",\"Arsuf\",\"Artanes\",\"Artemita\",\"Argyroupoli\",\"Asine\",\"Asklepios\",\"Aspendos\",\"Assus\",\"Astacus\",\"Athenai\",\"Athmonia\",\"Aytos\",\"Ancient\",\"Baris\",\"Bhrytos\",\"Borysthenes\",\"Berge\",\"Boura\",\"Bouthroton\",\"Brauron\",\"Byblos\",\"Byllis\",\"Byzantium\",\"Bythinion\",\"Callipolis\",\"Cebrene\",\"Chalcedon\",\"Calydon\",\"Carystus\",\"Chamaizi\",\"Chalcis\",\"Chersonesos\",\"Chios\",\"Chytri\",\"Clazomenae\",\"Cleonae\",\"Cnidus\",\"Colosse\",\"Corcyra\",\"Croton\",\"Cyme\",\"Cyrene\",\"Cythera\",\"Decelea\",\"Delos\",\"Delphi\",\"Demetrias\",\"Dicaearchia\",\"Dimale\",\"Didyma\",\"Dion\",\"Dioscurias\",\"Dodona\",\"Dorylaion\",\"Dyme\",\"Edessa\",\"Elateia\",\"Eleusis\",\"Eleutherna\",\"Emporion\",\"Ephesus\",\"Ephyra\",\"Epidamnos\",\"Epidauros\",\"Eresos\",\"Eretria\",\"Erythrae\",\"Eubea\",\"Gangra\",\"Gaza\",\"Gela\",\"Golgi\",\"Gonnos\",\"Gorgippia\",\"Gournia\",\"Gortyn\",\"Gythium\",\"Hagios\",\"Hagia\",\"Halicarnassus\",\"Halieis\",\"Helike\",\"Heliopolis\",\"Hellespontos\",\"Helorus\",\"Hemeroskopeion\",\"Heraclea\",\"Hermione\",\"Hermonassa\",\"Hierapetra\",\"Hierapolis\",\"Himera\",\"Histria\",\"Hubla\",\"Hyele\",\"Ialysos\",\"Iasus\",\"Idalium\",\"Imbros\",\"Iolcus\",\"Itanos\",\"Ithaca\",\"Juktas\",\"Kallipolis\",\"Kamares\",\"Kameiros\",\"Kannia\",\"Kamarina\",\"Kasmenai\",\"Katane\",\"Kerkinitida\",\"Kepoi\",\"Kimmerikon\",\"Kios\",\"Klazomenai\",\"Knidos\",\"Knossos\",\"Korinthos\",\"Kos\",\"Kourion\",\"Kume\",\"Kydonia\",\"Kynos\",\"Kyrenia\",\"Lamia\",\"Lampsacus\",\"Laodicea\",\"Lapithos\",\"Larissa\",\"Lato\",\"Laus\",\"Lebena\",\"Lefkada\",\"Lekhaion\",\"Leibethra\",\"Leontinoi\",\"Lepreum\",\"Lessa\",\"Lilaea\",\"Lindus\",\"Lissus\",\"Epizephyrian\",\"Madytos\",\"Magnesia\",\"Mallia\",\"Mantineia\",\"Marathon\",\"Marmara\",\"Maroneia\",\"Masis\",\"Massalia\",\"Megalopolis\",\"Megara\",\"Mesembria\",\"Messene\",\"Metapontum\",\"Methana\",\"Methone\",\"Methumna\",\"Miletos\",\"Misenum\",\"Mochlos\",\"Monastiraki\",\"Morgantina\",\"Mulai\",\"Mukenai\",\"Mylasa\",\"Myndus\",\"Myonia\",\"Myra\",\"Myrmekion\",\"Mutilene\",\"Myos\",\"Nauplios\",\"Naucratis\",\"Naupactus\",\"Naxos\",\"Neapoli\",\"Neapolis\",\"Nemea\",\"Nicaea\",\"Nicopolis\",\"Nirou\",\"Nymphaion\",\"Nysa\",\"Oenoe\",\"Oenus\",\"Odessos\",\"Olbia\",\"Olous\",\"Olympia\",\"Olynthus\",\"Opus\",\"Orchomenus\",\"Oricos\",\"Orestias\",\"Oreus\",\"Oropus\",\"Onchesmos\",\"Pactye\",\"Pagasae\",\"Palaikastro\",\"Pandosia\",\"Panticapaeum\",\"Paphos\",\"Parium\",\"Paros\",\"Parthenope\",\"Patrae\",\"Pavlopetri\",\"Pegai\",\"Pelion\",\"Peiraieús\",\"Pella\",\"Percote\",\"Pergamum\",\"Petsofa\",\"Phaistos\",\"Phaleron\",\"Phanagoria\",\"Pharae\",\"Pharnacia\",\"Pharos\",\"Phaselis\",\"Philippi\",\"Pithekussa\",\"Philippopolis\",\"Platanos\",\"Phlius\",\"Pherae\",\"Phocaea\",\"Pinara\",\"Pisa\",\"Pitane\",\"Pitiunt\",\"Pixous\",\"Plataea\",\"Poseidonia\",\"Potidaea\",\"Priapus\",\"Priene\",\"Prousa\",\"Pseira\",\"Psychro\",\"Pteleum\",\"Pydna\",\"Pylos\",\"Pyrgos\",\"Rhamnus\",\"Rhegion\",\"Rhithymna\",\"Rhodes\",\"Rhypes\",\"Rizinia\",\"Salamis\",\"Same\",\"Samos\",\"Scyllaeum\",\"Selinus\",\"Seleucia\",\"Semasus\",\"Sestos\",\"Scidrus\",\"Sicyon\",\"Side\",\"Sidon\",\"Siteia\",\"Sinope\",\"Siris\",\"Sklavokampos\",\"Smyrna\",\"Soli\",\"Sozopolis\",\"Sparta\",\"Stagirus\",\"Stratos\",\"Stymphalos\",\"Sybaris\",\"Surakousai\",\"Taras\",\"Tanagra\",\"Tanais\",\"Tauromenion\",\"Tegea\",\"Temnos\",\"Tenedos\",\"Tenea\",\"Teos\",\"Thapsos\",\"Thassos\",\"Thebai\",\"Theodosia\",\"Therma\",\"Thespiae\",\"Thronion\",\"Thoricus\",\"Thurii\",\"Thyreum\",\"Thyria\",\"Tiruns\",\"Tithoraea\",\"Tomis\",\"Tragurion\",\"Trapeze\",\"Trapezus\",\"Tripolis\",\"Troizen\",\"Troliton\",\"Troy\",\"Tylissos\",\"Tyras\",\"Tyros\",\"Tyritake\",\"Vasiliki\",\"Vathypetros\",\"Zakynthos\",\"Zakros\",\"Zankle\"],\n [\"Abila\",\"Adflexum\",\"Adnicrem\",\"Aelia\",\"Aelius\",\"Aeminium\",\"Aequum\",\"Agrippina\",\"Agrippinae\",\"Ala\",\"Albanianis\",\"Ambianum\",\"Andautonia\",\"Apulum\",\"Aquae\",\"Aquaegranni\",\"Aquensis\",\"Aquileia\",\"Aquincum\",\"Arae\",\"Argentoratum\",\"Ariminum\",\"Ascrivium\",\"Atrebatum\",\"Atuatuca\",\"Augusta\",\"Aurelia\",\"Aurelianorum\",\"Batavar\",\"Batavorum\",\"Belum\",\"Biriciana\",\"Blestium\",\"Bonames\",\"Bonna\",\"Bononia\",\"Borbetomagus\",\"Bovium\",\"Bracara\",\"Brigantium\",\"Burgodunum\",\"Caesaraugusta\",\"Caesarea\",\"Caesaromagus\",\"Calleva\",\"Camulodunum\",\"Cannstatt\",\"Cantiacorum\",\"Capitolina\",\"Castellum\",\"Castra\",\"Castrum\",\"Cibalae\",\"Clausentum\",\"Colonia\",\"Concangis\",\"Condate\",\"Confluentes\",\"Conimbriga\",\"Corduba\",\"Coria\",\"Corieltauvorum\",\"Corinium\",\"Coriovallum\",\"Cornoviorum\",\"Danum\",\"Deva\",\"Divodurum\",\"Dobunnorum\",\"Drusi\",\"Dubris\",\"Dumnoniorum\",\"Durnovaria\",\"Durocobrivis\",\"Durocornovium\",\"Duroliponte\",\"Durovernum\",\"Durovigutum\",\"Eboracum\",\"Edetanorum\",\"Emerita\",\"Emona\",\"Euracini\",\"Faventia\",\"Flaviae\",\"Florentia\",\"Forum\",\"Gerulata\",\"Gerunda\",\"Glevensium\",\"Hadriani\",\"Herculanea\",\"Isca\",\"Italica\",\"Iulia\",\"Iuliobrigensium\",\"Iuvavum\",\"Lactodurum\",\"Lagentium\",\"Lauri\",\"Legionis\",\"Lemanis\",\"Lentia\",\"Lepidi\",\"Letocetum\",\"Lindinis\",\"Lindum\",\"Londinium\",\"Lopodunum\",\"Lousonna\",\"Lucus\",\"Lugdunum\",\"Luguvalium\",\"Lutetia\",\"Mancunium\",\"Marsonia\",\"Martius\",\"Massa\",\"Matilo\",\"Mattiacorum\",\"Mediolanum\",\"Mod\",\"Mogontiacum\",\"Moridunum\",\"Mursa\",\"Naissus\",\"Nervia\",\"Nida\",\"Nigrum\",\"Novaesium\",\"Noviomagus\",\"Olicana\",\"Ovilava\",\"Parisiorum\",\"Partiscum\",\"Paterna\",\"Pistoria\",\"Placentia\",\"Pollentia\",\"Pomaria\",\"Pons\",\"Portus\",\"Praetoria\",\"Praetorium\",\"Pullum\",\"Ragusium\",\"Ratae\",\"Raurica\",\"Regina\",\"Regium\",\"Regulbium\",\"Rigomagus\",\"Roma\",\"Romula\",\"Rutupiae\",\"Salassorum\",\"Salernum\",\"Salona\",\"Scalabis\",\"Segovia\",\"Silurum\",\"Sirmium\",\"Siscia\",\"Sorviodurum\",\"Sumelocenna\",\"Tarraco\",\"Taurinorum\",\"Theranda\",\"Traiectum\",\"Treverorum\",\"Tungrorum\",\"Turicum\",\"Ulpia\",\"Valentia\",\"Venetiae\",\"Venta\",\"Verulamium\",\"Vesontio\",\"Vetera\",\"Victoriae\",\"Victrix\",\"Villa\",\"Viminacium\",\"Vindelicorum\",\"Vindobona\",\"Vinovia\",\"Viroconium\"],\n [\"Aanekoski\",\"Abjapaluoja\",\"Ahlainen\",\"Aholanvaara\",\"Ahtari\",\"Aijala\",\"Aimala\",\"Akaa\",\"Alajarvi\",\"Alatornio\",\"Alavus\",\"Antsla\",\"Aspo\",\"Bennas\",\"Bjorkoby\",\"Elva\",\"Emasalo\",\"Espoo\",\"Esse\",\"Evitskog\",\"Forssa\",\"Haapajarvi\",\"Haapamaki\",\"Haapavesi\",\"Haapsalu\",\"Haavisto\",\"Hameenlinna\",\"Hameenmaki\",\"Hamina\",\"Hanko\",\"Harjavalta\",\"Hattuvaara\",\"Haukipudas\",\"Hautajarvi\",\"Havumaki\",\"Heinola\",\"Hetta\",\"Hinkabole\",\"Hirmula\",\"Hossa\",\"Huittinen\",\"Husula\",\"Hyryla\",\"Hyvinkaa\",\"Iisalmi\",\"Ikaalinen\",\"Ilmola\",\"Imatra\",\"Inari\",\"Iskmo\",\"Itakoski\",\"Jamsa\",\"Jarvenpaa\",\"Jeppo\",\"Jioesuu\",\"Jiogeva\",\"Joensuu\",\"Jokela\",\"Jokikyla\",\"Jokisuu\",\"Jormua\",\"Juankoski\",\"Jungsund\",\"Jyvaskyla\",\"Kaamasmukka\",\"Kaarina\",\"Kajaani\",\"Kalajoki\",\"Kallaste\",\"Kankaanpaa\",\"Kannus\",\"Kardla\",\"Karesuvanto\",\"Karigasniemi\",\"Karkkila\",\"Karkku\",\"Karksinuia\",\"Karpankyla\",\"Kaskinen\",\"Kasnas\",\"Kauhajoki\",\"Kauhava\",\"Kauniainen\",\"Kauvatsa\",\"Kehra\",\"Keila\",\"Kellokoski\",\"Kelottijarvi\",\"Kemi\",\"Kemijarvi\",\"Kerava\",\"Keuruu\",\"Kiikka\",\"Kiipu\",\"Kilinginiomme\",\"Kiljava\",\"Kilpisjarvi\",\"Kitee\",\"Kiuruvesi\",\"Kivesjarvi\",\"Kiviioli\",\"Kivisuo\",\"Klaukkala\",\"Klovskog\",\"Kohtlajarve\",\"Kokemaki\",\"Kokkola\",\"Kolho\",\"Koria\",\"Koskue\",\"Kotka\",\"Kouva\",\"Kouvola\",\"Kristiina\",\"Kaupunki\",\"Kuhmo\",\"Kunda\",\"Kuopio\",\"Kuressaare\",\"Kurikka\",\"Kusans\",\"Kuusamo\",\"Kylmalankyla\",\"Lahti\",\"Laitila\",\"Lankipohja\",\"Lansikyla\",\"Lappeenranta\",\"Lapua\",\"Laurila\",\"Lautiosaari\",\"Lepsama\",\"Liedakkala\",\"Lieksa\",\"Lihula\",\"Littoinen\",\"Lohja\",\"Loimaa\",\"Loksa\",\"Loviisa\",\"Luohuanylipaa\",\"Lusi\",\"Maardu\",\"Maarianhamina\",\"Malmi\",\"Mantta\",\"Masaby\",\"Masala\",\"Matasvaara\",\"Maula\",\"Miiluranta\",\"Mikkeli\",\"Mioisakula\",\"Munapirtti\",\"Mustvee\",\"Muurahainen\",\"Naantali\",\"Nappa\",\"Narpio\",\"Nickby\",\"Niinimaa\",\"Niinisalo\",\"Nikkila\",\"Nilsia\",\"Nivala\",\"Nokia\",\"Nummela\",\"Nuorgam\",\"Nurmes\",\"Nuvvus\",\"Obbnas\",\"Oitti\",\"Ojakkala\",\"Ollola\",\"onningeby\",\"Orimattila\",\"Orivesi\",\"Otanmaki\",\"Otava\",\"Otepaa\",\"Oulainen\",\"Oulu\",\"Outokumpu\",\"Paavola\",\"Paide\",\"Paimio\",\"Pakankyla\",\"Paldiski\",\"Parainen\",\"Parkano\",\"Parkumaki\",\"Parola\",\"Perttula\",\"Pieksamaki\",\"Pietarsaari\",\"Pioltsamaa\",\"Piolva\",\"Pohjavaara\",\"Porhola\",\"Pori\",\"Porrasa\",\"Porvoo\",\"Pudasjarvi\",\"Purmo\",\"Pussi\",\"Pyhajarvi\",\"Raahe\",\"Raasepori\",\"Raisio\",\"Rajamaki\",\"Rakvere\",\"Rapina\",\"Rapla\",\"Rauma\",\"Rautio\",\"Reposaari\",\"Riihimaki\",\"Rovaniemi\",\"Roykka\",\"Ruonala\",\"Ruottala\",\"Rutalahti\",\"Saarijarvi\",\"Salo\",\"Sastamala\",\"Saue\",\"Savonlinna\",\"Seinajoki\",\"Sillamae\",\"Sindi\",\"Siuntio\",\"Somero\",\"Sompujarvi\",\"Suonenjoki\",\"Suurejaani\",\"Syrjantaka\",\"Tampere\",\"Tamsalu\",\"Tapa\",\"Temmes\",\"Tiorva\",\"Tormasenvaara\",\"Tornio\",\"Tottijarvi\",\"Tulppio\",\"Turenki\",\"Turi\",\"Tuukkala\",\"Tuurala\",\"Tuuri\",\"Tuuski\",\"Ulvila\",\"Unari\",\"Upinniemi\",\"Utti\",\"Uusikaarlepyy\",\"Uusikaupunki\",\"Vaaksy\",\"Vaalimaa\",\"Vaarinmaja\",\"Vaasa\",\"Vainikkala\",\"Valga\",\"Valkeakoski\",\"Vantaa\",\"Varkaus\",\"Vehkapera\",\"Vehmasmaki\",\"Vieki\",\"Vierumaki\",\"Viitasaari\",\"Viljandi\",\"Vilppula\",\"Viohma\",\"Vioru\",\"Virrat\",\"Ylike\",\"Ylivieska\",\"Ylojarvi\"],\n [\"Sabi\",\"Wiryeseong\",\"Hwando\",\"Gungnae\",\"Ungjin\",\"Wanggeomseong\",\"Ganggyeong\",\"Jochiwon\",\"Cheorwon\",\"Beolgyo\",\"Gangjin\",\"Gampo\",\"Yecheon\",\"Geochang\",\"Janghang\",\"Hadong\",\"Goseong\",\"Yeongdong\",\"Yesan\",\"Sintaein\",\"Geumsan\",\"Boseong\",\"Jangheung\",\"Uiseong\",\"Jumunjin\",\"Janghowon\",\"Hongseong\",\"Gimhwa\",\"Gwangcheon\",\"Guryongpo\",\"Jinyeong\",\"Buan\",\"Damyang\",\"Jangseong\",\"Wando\",\"Angang\",\"Okcheon\",\"Jeungpyeong\",\"Waegwan\",\"Cheongdo\",\"Gwangyang\",\"Gochang\",\"Haenam\",\"Yeonggwang\",\"Hanam\",\"Eumseong\",\"Daejeong\",\"Hanrim\",\"Samrye\",\"Yongjin\",\"Hamyang\",\"Buyeo\",\"Changnyeong\",\"Yeongwol\",\"Yeonmu\",\"Gurye\",\"Hwasun\",\"Hampyeong\",\"Namji\",\"Samnangjin\",\"Dogye\",\"Hongcheon\",\"Munsan\",\"Gapyeong\",\"Ganghwa\",\"Geojin\",\"Sangdong\",\"Jeongseon\",\"Sabuk\",\"Seonghwan\",\"Heunghae\",\"Hapdeok\",\"Sapgyo\",\"Taean\",\"Boeun\",\"Geumwang\",\"Jincheon\",\"Bongdong\",\"Doyang\",\"Geoncheon\",\"Pungsan\",\"Punggi\",\"Geumho\",\"Wonju\",\"Gaun\",\"Hayang\",\"Yeoju\",\"Paengseong\",\"Yeoncheon\",\"Yangpyeong\",\"Ganseong\",\"Yanggu\",\"Yangyang\",\"Inje\",\"Galmal\",\"Pyeongchang\",\"Hwacheon\",\"Hoengseong\",\"Seocheon\",\"Cheongyang\",\"Goesan\",\"Danyang\",\"Hamyeol\",\"Muju\",\"Sunchang\",\"Imsil\",\"Jangsu\",\"Jinan\",\"Goheung\",\"Gokseong\",\"Muan\",\"Yeongam\",\"Jindo\",\"Seonsan\",\"Daegaya\",\"Gunwi\",\"Bonghwa\",\"Seongju\",\"Yeongdeok\",\"Yeongyang\",\"Ulleung\",\"Uljin\",\"Cheongsong\",\"wayang\",\"Namhae\",\"Sancheong\",\"Uiryeong\",\"Gaya\",\"Hapcheon\",\"Wabu\",\"Dongsong\",\"Sindong\",\"Wondeok\",\"Maepo\",\"Anmyeon\",\"Okgu\",\"Sariwon\",\"Dolsan\",\"Daedeok\",\"Gwansan\",\"Geumil\",\"Nohwa\",\"Baeksu\",\"Illo\",\"Jido\",\"Oedong\",\"Ocheon\",\"Yeonil\",\"Hamchang\",\"Pyeonghae\",\"Gijang\",\"Jeonggwan\",\"Aewor\",\"Gujwa\",\"Seongsan\",\"Jeongok\",\"Seonggeo\",\"Seungju\",\"Hongnong\",\"Jangan\",\"Jocheon\",\"Gohan\",\"Jinjeop\",\"Bubal\",\"Beobwon\",\"Yeomchi\",\"Hwado\",\"Daesan\",\"Hwawon\",\"Apo\",\"Nampyeong\",\"Munsan\",\"Sinbuk\",\"Munmak\",\"Judeok\",\"Bongyang\",\"Ungcheon\",\"Yugu\",\"Unbong\",\"Mangyeong\",\"Dong\",\"Naeseo\",\"Sanyang\",\"Soheul\",\"Onsan\",\"Eonyang\",\"Nongong\",\"Dasa\",\"Goa\",\"Jillyang\",\"Bongdam\",\"Naesu\",\"Beomseo\",\"Opo\",\"Gongdo\",\"Jingeon\",\"Onam\",\"Baekseok\",\"Jiksan\",\"Mokcheon\",\"Jori\",\"Anjung\",\"Samho\",\"Ujeong\",\"Buksam\",\"Tongjin\",\"Chowol\",\"Gonjiam\",\"Pogok\",\"Seokjeok\",\"Poseung\",\"Ochang\",\"Hyangnam\",\"Baebang\",\"Gochon\",\"Songak\",\"Samhyang\",\"Yangchon\",\"Osong\",\"Aphae\",\"Ganam\",\"Namyang\",\"Chirwon\",\"Andong\",\"Ansan\",\"Anseong\",\"Anyang\",\"Asan\",\"Boryeong\",\"Bucheon\",\"Busan\",\"Changwon\",\"Cheonan\",\"Cheongju\",\"Chuncheon\",\"Chungju\",\"Daegu\",\"Daejeon\",\"Dangjin\",\"Dongducheon\",\"Donghae\",\"Gangneung\",\"Geoje\",\"Gimcheon\",\"Gimhae\",\"Gimje\",\"Gimpo\",\"Gongju\",\"Goyang\",\"Gumi\",\"Gunpo\",\"Gunsan\",\"Guri\",\"Gwacheon\",\"Gwangju\",\"Gwangju\",\"Gwangmyeong\",\"Gyeongju\",\"Gyeongsan\",\"Gyeryong\",\"Hwaseong\",\"Icheon\",\"Iksan\",\"Incheon\",\"Jecheon\",\"Jeongeup\",\"Jeonju\",\"Jeju\",\"Jinju\",\"Naju\",\"Namyangju\",\"Namwon\",\"Nonsan\",\"Miryang\",\"Mokpo\",\"Mungyeong\",\"Osan\",\"Paju\",\"Pocheon\",\"Pohang\",\"Pyeongtaek\",\"Sacheon\",\"Sangju\",\"Samcheok\",\"Sejong\",\"Seogwipo\",\"Seongnam\",\"Seosan\",\"Seoul\",\"Siheung\",\"Sokcho\",\"Suncheon\",\"Suwon\",\"Taebaek\",\"Tongyeong\",\"Uijeongbu\",\"Uiwang\",\"Ulsan\",\"Yangju\",\"Yangsan\",\"Yeongcheon\",\"Yeongju\",\"Yeosu\",\"Yongin\",\"Chungmu\",\"Daecheon\",\"Donggwangyang\",\"Geumseong\",\"Gyeongseong\",\"Iri\",\"Jangseungpo\",\"Jeomchon\",\"Jeongju\",\"Migeum\",\"Onyang\",\"Samcheonpo\",\"Busan\",\"Busan\",\"Cheongju\",\"Chuncheon\",\"Daegu\",\"Daegu\",\"Daejeon\",\"Daejeon\",\"Gunsan\",\"Gwangju\",\"Gwangju\",\"Gyeongseong\",\"Incheon\",\"Incheon\",\"Iri\",\"Jeonju\",\"Jinhae\",\"Jinju\",\"Masan\",\"Masan\",\"Mokpo\",\"Songjeong\",\"Songtan\",\"Ulsan\",\"Yeocheon\",\"Cheongjin\",\"Gaeseong\",\"Haeju\",\"Hamheung\",\"Heungnam\",\"Jinnampo\",\"Najin\",\"Pyeongyang\",\"Seongjin\",\"Sineuiju\",\"Songnim\",\"Wonsan\"],\n [\"Anding\",\"Anlu\",\"Anqing\",\"Anshun\",\"Baan\",\"Baixing\",\"Banyang\",\"Baoding\",\"Baoqing\",\"Binzhou\",\"Caozhou\",\"Changbai\",\"Changchun\",\"Changde\",\"Changling\",\"Changsha\",\"Changtu\",\"Changzhou\",\"Chaozhou\",\"Cheli\",\"Chengde\",\"Chengdu\",\"Chenzhou\",\"Chizhou\",\"Chongqing\",\"Chuxiong\",\"Chuzhou\",\"Dading\",\"Dali\",\"Daming\",\"Datong\",\"Daxing\",\"Dean\",\"Dengke\",\"Dengzhou\",\"Deqing\",\"Dexing\",\"Dihua\",\"Dingli\",\"Dongan\",\"Dongchang\",\"Dongchuan\",\"Dongping\",\"Duyun\",\"Fengtian\",\"Fengxiang\",\"Fengyang\",\"Fenzhou\",\"Funing\",\"Fuzhou\",\"Ganzhou\",\"Gaoyao\",\"Gaozhou\",\"Gongchang\",\"Guangnan\",\"Guangning\",\"Guangping\",\"Guangxin\",\"Guangzhou\",\"Guide\",\"Guilin\",\"Guiyang\",\"Hailong\",\"Hailun\",\"Hangzhou\",\"Hanyang\",\"Hanzhong\",\"Heihe\",\"Hejian\",\"Henan\",\"Hengzhou\",\"Hezhong\",\"Huaian\",\"Huaide\",\"Huaiqing\",\"Huanglong\",\"Huangzhou\",\"Huining\",\"Huizhou\",\"Hulan\",\"Huzhou\",\"Jiading\",\"Jian\",\"Jianchang\",\"Jiande\",\"Jiangning\",\"Jiankang\",\"Jianning\",\"Jiaxing\",\"Jiayang\",\"Jilin\",\"Jinan\",\"Jingjiang\",\"Jingzhao\",\"Jingzhou\",\"Jinhua\",\"Jinzhou\",\"Jiujiang\",\"Kaifeng\",\"Kaihua\",\"Kangding\",\"Kuizhou\",\"Laizhou\",\"Lanzhou\",\"Leizhou\",\"Liangzhou\",\"Lianzhou\",\"Liaoyang\",\"Lijiang\",\"Linan\",\"Linhuang\",\"Linjiang\",\"Lintao\",\"Liping\",\"Liuzhou\",\"Longan\",\"Longjiang\",\"Longqing\",\"Longxing\",\"Luan\",\"Lubin\",\"Lubin\",\"Luzhou\",\"Mishan\",\"Nanan\",\"Nanchang\",\"Nandian\",\"Nankang\",\"Nanning\",\"Nanyang\",\"Nenjiang\",\"Ningan\",\"Ningbo\",\"Ningguo\",\"Ninguo\",\"Ningwu\",\"Ningxia\",\"Ningyuan\",\"Pingjiang\",\"Pingle\",\"Pingliang\",\"Pingyang\",\"Puer\",\"Puzhou\",\"Qianzhou\",\"Qingyang\",\"Qingyuan\",\"Qingzhou\",\"Qiongzhou\",\"Qujing\",\"Quzhou\",\"Raozhou\",\"Rende\",\"Ruian\",\"Ruizhou\",\"Runing\",\"Shafeng\",\"Shajing\",\"Shaoqing\",\"Shaowu\",\"Shaoxing\",\"Shaozhou\",\"Shinan\",\"Shiqian\",\"Shouchun\",\"Shuangcheng\",\"Shulei\",\"Shunde\",\"Shunqing\",\"Shuntian\",\"Shuoping\",\"Sicheng\",\"Sien\",\"Sinan\",\"Sizhou\",\"Songjiang\",\"Suiding\",\"Suihua\",\"Suining\",\"Suzhou\",\"Taian\",\"Taibei\",\"Tainan\",\"Taiping\",\"Taiwan\",\"Taiyuan\",\"Taizhou\",\"Taonan\",\"Tengchong\",\"Tieli\",\"Tingzhou\",\"Tongchuan\",\"Tongqing\",\"Tongren\",\"Tongzhou\",\"Weihui\",\"Wensu\",\"Wenzhou\",\"Wuchang\",\"Wuding\",\"Wuzhou\",\"Xian\",\"Xianchun\",\"Xianping\",\"Xijin\",\"Xiliang\",\"Xincheng\",\"Xingan\",\"Xingde\",\"Xinghua\",\"Xingjing\",\"Xingqing\",\"Xingyi\",\"Xingyuan\",\"Xingzhong\",\"Xining\",\"Xinmen\",\"Xiping\",\"Xuanhua\",\"Xunzhou\",\"Xuzhou\",\"Yanan\",\"Yangzhou\",\"Yanji\",\"Yanping\",\"Yanqi\",\"Yanzhou\",\"Yazhou\",\"Yichang\",\"Yidu\",\"Yilan\",\"Yili\",\"Yingchang\",\"Yingde\",\"Yingtian\",\"Yingzhou\",\"Yizhou\",\"Yongchang\",\"Yongping\",\"Yongshun\",\"Yongzhou\",\"Yuanzhou\",\"Yuezhou\",\"Yulin\",\"Yunnan\",\"Yunyang\",\"Zezhou\",\"Zhangde\",\"Zhangzhou\",\"Zhaoqing\",\"Zhaotong\",\"Zhenan\",\"Zhending\",\"Zhengding\",\"Zhenhai\",\"Zhenjiang\",\"Zhenxi\",\"Zhenyun\",\"Zhongshan\",\"Zunyi\"],\n [\"Nanporo\",\"Naie\",\"Kamisunagawa\",\"Yuni\",\"Naganuma\",\"Kuriyama\",\"Tsukigata\",\"Urausu\",\"Shintotsukawa\",\"Moseushi\",\"Chippubetsu\",\"Uryu\",\"Hokuryu\",\"Numata\",\"Tobetsu\",\"Suttsu\",\"Kuromatsunai\",\"Rankoshi\",\"Niseko\",\"Kimobetsu\",\"Kyogoku\",\"Kutchan\",\"Kyowa\",\"Iwanai\",\"Shakotan\",\"Furubira\",\"Niki\",\"Yoichi\",\"Toyoura\",\"Toyako\",\"Sobetsu\",\"Shiraoi\",\"Atsuma\",\"Abira\",\"Mukawa\",\"Hidaka\",\"Biratori\",\"Niikappu\",\"Urakawa\",\"Samani\",\"Erimo\",\"Shinhidaka\",\"Matsumae\",\"Fukushima\",\"Shiriuchi\",\"Kikonai\",\"Nanae\",\"Shikabe\",\"Mori\",\"Yakumo\",\"Oshamambe\",\"Esashi\",\"Kaminokuni\",\"Assabu\",\"Otobe\",\"Okushiri\",\"Imakane\",\"Setana\",\"Takasu\",\"Higashikagura\",\"Toma\",\"Pippu\",\"Aibetsu\",\"Kamikawa\",\"Higashikawa\",\"Biei\",\"Kamifurano\",\"Nakafurano\",\"Minamifurano\",\"Horokanai\",\"Wassamu\",\"Kenbuchi\",\"Shimokawa\",\"Bifuka\",\"Nakagawa\",\"Mashike\",\"Obira\",\"Tomamae\",\"Haboro\",\"Enbetsu\",\"Teshio\",\"Hamatonbetsu\",\"Nakatonbetsu\",\"Esashi\",\"Toyotomi\",\"Horonobe\",\"Rebun\",\"Rishiri\",\"Rishirifuji\",\"Bihoro\",\"Tsubetsu\",\"Ozora\",\"Shari\",\"Kiyosato\",\"Koshimizu\",\"Kunneppu\",\"Oketo\",\"Saroma\",\"Engaru\",\"Yubetsu\",\"Takinoue\",\"Okoppe\",\"Omu\",\"Otofuke\",\"Shihoro\",\"Kamishihoro\",\"Shikaoi\",\"Shintoku\",\"Shimizu\",\"Memuro\",\"Taiki\",\"Hiroo\",\"Makubetsu\",\"Ikeda\",\"Toyokoro\",\"Honbetsu\",\"Ashoro\",\"Rikubetsu\",\"Urahoro\",\"Kushiro\",\"Akkeshi\",\"Hamanaka\",\"Shibecha\",\"Teshikaga\",\"Shiranuka\",\"Betsukai\",\"Nakashibetsu\",\"Shibetsu\",\"Rausu\",\"Hiranai\",\"Imabetsu\",\"Sotogahama\",\"Ajigasawa\",\"Fukaura\",\"Fujisaki\",\"Owani\",\"Itayanagi\",\"Tsuruta\",\"Nakadomari\",\"Noheji\",\"Shichinohe\",\"Rokunohe\",\"Yokohama\",\"Tohoku\",\"Oirase\",\"Oma\",\"Sannohe\",\"Gonohe\",\"Takko\",\"Nanbu\",\"Hashikami\",\"Shizukuishi\",\"Kuzumaki\",\"Iwate\",\"Shiwa\",\"Yahaba\",\"Nishiwaga\",\"Kanegasaki\",\"Hiraizumi\",\"Sumita\",\"Otsuchi\",\"Yamada\",\"Iwaizumi\",\"Karumai\",\"Hirono\",\"Ichinohe\",\"Zao\",\"Shichikashuku\",\"Ogawara\",\"Murata\",\"Shibata\",\"Kawasaki\",\"Marumori\",\"Watari\",\"Yamamoto\",\"Matsushima\",\"Shichigahama\",\"Rifu\",\"Taiwa\",\"Osato\",\"Shikama\",\"Kami\",\"Wakuya\",\"Misato\",\"Onagawa\",\"Minamisanriku\",\"Kosaka\",\"Fujisato\",\"Mitane\",\"Happo\",\"Gojome\",\"Hachirogata\",\"Ikawa\",\"Misato\",\"Ugo\",\"Yamanobe\",\"Nakayama\",\"Kahoku\",\"Nishikawa\",\"Asahi\",\"Oe\",\"Oishida\",\"Kaneyama\",\"Mogami\",\"Funagata\",\"Mamurogawa\",\"Takahata\",\"Kawanishi\",\"Oguni\",\"Shirataka\",\"Iide\",\"Mikawa\",\"Shonai\",\"Yuza\",\"Koori\",\"Kunimi\",\"Kawamata\",\"Kagamiishi\",\"Shimogo\",\"Tadami\",\"Minamiaizu\",\"Nishiaizu\",\"Bandai\",\"Inawashiro\",\"Aizubange\",\"Yanaizu\",\"Mishima\",\"Kaneyama\",\"Aizumisato\",\"Yabuki\",\"Tanagura\",\"Yamatsuri\",\"Hanawa\",\"Ishikawa\",\"Asakawa\",\"Furudono\",\"Miharu\",\"Ono\",\"Hirono\",\"Naraha\",\"Tomioka\",\"Okuma\",\"Futaba\",\"Namie\",\"Shinchi\",\"Ibaraki\",\"Oarai\",\"Shirosato\",\"Daigo\",\"Ami\",\"Kawachi\",\"Yachiyo\",\"Goka\",\"Sakai\",\"Tone\",\"Kaminokawa\",\"Mashiko\",\"Motegi\",\"Ichikai\",\"Haga\",\"Mibu\",\"Nogi\",\"Shioya\",\"Takanezawa\",\"Nasu\",\"Nakagawa\",\"Yoshioka\",\"Kanna\",\"Shimonita\",\"Kanra\",\"Nakanojo\",\"Naganohara\",\"Kusatsu\",\"Higashiagatsuma\",\"Minakami\",\"Tamamura\",\"Itakura\",\"Meiwa\",\"Chiyoda\",\"Oizumi\",\"Ora\",\"Ina\",\"Miyoshi\",\"Moroyama\",\"Ogose\",\"Namegawa\",\"Ranzan\",\"Ogawa\",\"Kawajima\",\"Yoshimi\",\"Hatoyama\",\"Tokigawa\",\"Yokoze\",\"Minano\",\"Nagatoro\",\"Ogano\",\"Misato\",\"Kamikawa\",\"Kamisato\",\"Yorii\",\"Miyashiro\",\"Sugito\",\"Matsubushi\",\"Shisui\",\"Sakae\",\"Kozaki\",\"Tako\",\"Tonosho\",\"Kujukuri\",\"Shibayama\",\"Yokoshibahikari\",\"Ichinomiya\",\"Mutsuzawa\",\"Shirako\",\"Nagara\",\"Chonan\",\"Otaki\",\"Onjuku\",\"Kyonan\",\"Mizuho\",\"Hinode\",\"Okutama\",\"Oshima\",\"Hachijo\",\"Aikawa\",\"Hayama\",\"Samukawa\",\"Oiso\",\"Ninomiya\",\"Nakai\",\"Oi\",\"Matsuda\",\"Yamakita\",\"Kaisei\",\"Hakone\",\"Manazuru\",\"Yugawara\",\"Seiro\",\"Tagami\",\"Aga\",\"Izumozaki\",\"Yuzawa\",\"Tsunan\",\"Kamiichi\",\"Tateyama\",\"Nyuzen\",\"Asahi\",\"Kawakita\",\"Tsubata\",\"Uchinada\",\"Shika\",\"Hodatsushimizu\",\"Nakanoto\",\"Anamizu\",\"Noto\",\"Eiheiji\",\"Ikeda\",\"Minamiechizen\",\"Echizen\",\"Mihama\",\"Takahama\",\"Oi\",\"Wakasa\",\"Ichikawamisato\",\"Hayakawa\",\"Minobu\",\"Nanbu\",\"Fujikawa\",\"Showa\",\"Nishikatsura\",\"Fujikawaguchiko\",\"Koumi\",\"Sakuho\",\"Karuizawa\",\"Miyota\",\"Tateshina\",\"Nagawa\",\"Shimosuwa\",\"Fujimi\",\"Tatsuno\",\"Minowa\",\"Iijima\",\"Matsukawa\",\"Takamori\",\"Anan\",\"Agematsu\",\"Nagiso\",\"Kiso\",\"Ikeda\",\"Sakaki\",\"Obuse\",\"Yamanouchi\",\"Shinano\",\"Iizuna\",\"Ginan\",\"Kasamatsu\",\"Yoro\",\"Tarui\",\"Sekigahara\",\"Godo\",\"Wanouchi\",\"Anpachi\",\"Ibigawa\",\"Ono\",\"Ikeda\",\"Kitagata\",\"Sakahogi\",\"Tomika\",\"Kawabe\",\"Hichiso\",\"Yaotsu\",\"Shirakawa\",\"Mitake\",\"Higashiizu\",\"Kawazu\",\"Minamiizu\",\"Matsuzaki\",\"Nishiizu\",\"Kannami\",\"Shimizu\",\"Nagaizumi\",\"Oyama\",\"Yoshida\",\"Kawanehon\",\"Mori\",\"Togo\",\"Toyoyama\",\"Oguchi\",\"Fuso\",\"Oharu\",\"Kanie\",\"Agui\",\"Higashiura\",\"Minamichita\",\"Mihama\",\"Taketoyo\",\"Mihama\",\"Kota\",\"Shitara\",\"Toei\",\"Kisosaki\",\"Toin\",\"Komono\",\"Asahi\",\"Kawagoe\",\"Taki\",\"Meiwa\",\"Odai\",\"Tamaki\",\"Watarai\",\"Taiki\",\"Minamiise\",\"Kihoku\",\"Mihama\",\"Kiho\",\"Hino\",\"Ryuo\",\"Aisho\",\"Toyosato\",\"Kora\",\"Taga\",\"Oyamazaki\",\"Kumiyama\",\"Ide\",\"Ujitawara\",\"Kasagi\",\"Wazuka\",\"Seika\",\"Kyotamba\",\"Ine\",\"Yosano\",\"Shimamoto\",\"Toyono\",\"Nose\",\"Tadaoka\",\"Kumatori\",\"Tajiri\",\"Misaki\",\"Taishi\",\"Kanan\",\"Inagawa\",\"Taka\",\"Inami\",\"Harima\",\"Ichikawa\",\"Fukusaki\",\"Kamikawa\",\"Taishi\",\"Kamigori\",\"Sayo\",\"Kami\",\"Shinonsen\",\"Heguri\",\"Sango\",\"Ikaruga\",\"Ando\",\"Kawanishi\",\"Miyake\",\"Tawaramoto\",\"Takatori\",\"Kanmaki\",\"Oji\",\"Koryo\",\"Kawai\",\"Yoshino\",\"Oyodo\",\"Shimoichi\",\"Kushimoto\",\"Kimino\",\"Katsuragi\",\"Kudoyama\",\"Koya\",\"Yuasa\",\"Hirogawa\",\"Aridagawa\",\"Mihama\",\"Hidaka\",\"Yura\",\"Inami\",\"Minabe\",\"Hidakagawa\",\"Shirahama\",\"Kamitonda\",\"Susami\",\"Nachikatsuura\",\"Taiji\",\"Kozagawa\",\"Iwami\",\"Wakasa\",\"Chizu\",\"Yazu\",\"Misasa\",\"Yurihama\",\"Kotoura\",\"Hokuei\",\"Daisen\",\"Nanbu\",\"Hoki\",\"Nichinan\",\"Hino\",\"Kofu\",\"Okuizumo\",\"Iinan\",\"Kawamoto\",\"Misato\",\"Onan\",\"Tsuwano\",\"Yoshika\",\"Ama\",\"Nishinoshima\",\"Okinoshima\",\"Wake\",\"Hayashima\",\"Satosho\",\"Yakage\",\"Kagamino\",\"Shoo\",\"Nagi\",\"Kumenan\",\"Misaki\",\"Kibichuo\",\"Fuchu\",\"Kaita\",\"Kumano\",\"Saka\",\"Kitahiroshima\",\"Akiota\",\"Osakikamijima\",\"Sera\",\"Jinsekikogen\",\"Suooshima\",\"Waki\",\"Kaminoseki\",\"Tabuse\",\"Hirao\",\"Abu\",\"Katsuura\",\"Kamikatsu\",\"Ishii\",\"Kamiyama\",\"Naka\",\"Mugi\",\"Minami\",\"Kaiyo\",\"Matsushige\",\"Kitajima\",\"Aizumi\",\"Itano\",\"Kamiita\",\"Tsurugi\",\"Higashimiyoshi\",\"Tonosho\",\"Shodoshima\",\"Miki\",\"Naoshima\",\"Utazu\",\"Ayagawa\",\"Kotohira\",\"Tadotsu\",\"Manno\",\"Kamijima\",\"Kumakogen\",\"Masaki\",\"Tobe\",\"Uchiko\",\"Ikata\",\"Kihoku\",\"Matsuno\",\"Ainan\",\"Toyo\",\"Nahari\",\"Tano\",\"Yasuda\",\"Motoyama\",\"Otoyo\",\"Tosa\",\"Ino\",\"Niyodogawa\",\"Nakatosa\",\"Sakawa\",\"Ochi\",\"Yusuhara\",\"Tsuno\",\"Shimanto\",\"Otsuki\",\"Kuroshio\",\"Nakagawa\",\"Umi\",\"Sasaguri\",\"Shime\",\"Sue\",\"Shingu\",\"Hisayama\",\"Kasuya\",\"Ashiya\",\"Mizumaki\",\"Okagaki\",\"Onga\",\"Kotake\",\"Kurate\",\"Keisen\",\"Chikuzen\",\"Tachiarai\",\"Oki\",\"Hirokawa\",\"Kawara\",\"Soeda\",\"Itoda\",\"Kawasaki\",\"Oto\",\"Fukuchi\",\"Kanda\",\"Miyako\",\"Yoshitomi\",\"Koge\",\"Chikujo\",\"Yoshinogari\",\"Kiyama\",\"Kamimine\",\"Miyaki\",\"Genkai\",\"Arita\",\"Omachi\",\"Kohoku\",\"Shiroishi\",\"Tara\",\"Nagayo\",\"Togitsu\",\"Higashisonogi\",\"Kawatana\",\"Hasami\",\"Ojika\",\"Saza\",\"Shinkamigoto\",\"Misato\",\"Gyokuto\",\"Nankan\",\"Nagasu\",\"Nagomi\",\"Ozu\",\"Kikuyo\",\"Minamioguni\",\"Oguni\",\"Takamori\",\"Mifune\",\"Kashima\",\"Mashiki\",\"Kosa\",\"Yamato\",\"Hikawa\",\"Ashikita\",\"Tsunagi\",\"Nishiki\",\"Taragi\",\"Yunomae\",\"Asagiri\",\"Reihoku\",\"Hiji\",\"Kusu\",\"Kokonoe\",\"Mimata\",\"Takaharu\",\"Kunitomi\",\"Aya\",\"Takanabe\",\"Shintomi\",\"Kijo\",\"Kawaminami\",\"Tsuno\",\"Kadogawa\",\"Misato\",\"Takachiho\",\"Hinokage\",\"Gokase\",\"Satsuma\",\"Nagashima\",\"Yusui\",\"Osaki\",\"Higashikushira\",\"Kinko\",\"Minamiosumi\",\"Kimotsuki\",\"Nakatane\",\"Minamitane\",\"Yakushima\",\"Setouchi\",\"Tatsugo\",\"Kikai\",\"Tokunoshima\",\"Amagi\",\"Isen\",\"Wadomari\",\"China\",\"Yoron\",\"Motobu\",\"Kin\",\"Kadena\",\"Chatan\",\"Nishihara\",\"Yonabaru\",\"Haebaru\",\"Kumejima\",\"Yaese\",\"Taketomi\",\"Yonaguni\"],\n [\"Abrigada\",\"Afonsoeiro\",\"Agueda\",\"Aguiar\",\"Aguilada\",\"Alagoas\",\"Alagoinhas\",\"Albufeira\",\"Alcacovas\",\"Alcanhoes\",\"Alcobaca\",\"Alcochete\",\"Alcoutim\",\"Aldoar\",\"Alexania\",\"Alfeizerao\",\"Algarve\",\"Alenquer\",\"Almada\",\"Almagreira\",\"Almeirim\",\"Alpalhao\",\"Alpedrinha\",\"Alvalade\",\"Alverca\",\"Alvor\",\"Alvorada\",\"Amadora\",\"Amapa\",\"Amieira\",\"Anapolis\",\"Anhangueira\",\"Ansiaes\",\"Apelacao\",\"Aracaju\",\"Aranhas\",\"Arega\",\"Areira\",\"Araguaina\",\"Araruama\",\"Arganil\",\"Armacao\",\"Arouca\",\"Asfontes\",\"Assenceira\",\"Avelar\",\"Aveiro\",\"Azambuja\",\"Azinheira\",\"Azueira\",\"Bahia\",\"Bairros\",\"Balsas\",\"Barcarena\",\"Barreiras\",\"Barreiro\",\"Barretos\",\"Batalha\",\"Beira\",\"Beja\",\"Benavente\",\"Betim\",\"Boticas\",\"Braga\",\"Braganca\",\"Brasilia\",\"Brejo\",\"Cabecao\",\"Cabeceiras\",\"Cabedelo\",\"Cabofrio\",\"Cachoeiras\",\"Cadafais\",\"Calheta\",\"Calihandriz\",\"Calvao\",\"Camacha\",\"Caminha\",\"Campinas\",\"Canidelo\",\"Canha\",\"Canoas\",\"Capinha\",\"Carmoes\",\"Cartaxo\",\"Carvalhal\",\"Carvoeiro\",\"Cascavel\",\"Castanhal\",\"Castelobranco\",\"Caueira\",\"Caxias\",\"Chapadinha\",\"Chaves\",\"Celheiras\",\"Cocais\",\"Coimbra\",\"Comporta\",\"Coentral\",\"Conde\",\"Copacabana\",\"Coqueirinho\",\"Coruche\",\"Corumba\",\"Couco\",\"Cubatao\",\"Curitiba\",\"Damaia\",\"Doisportos\",\"Douradilho\",\"Dourados\",\"Enxames\",\"Enxara\",\"Erada\",\"Erechim\",\"Ericeira\",\"Ermidasdosado\",\"Ervidel\",\"Escalhao\",\"Escariz\",\"Esmoriz\",\"Estombar\",\"Espinhal\",\"Espinho\",\"Esposende\",\"Esquerdinha\",\"Estela\",\"Estoril\",\"Eunapolis\",\"Evora\",\"Famalicao\",\"Famoes\",\"Fanhoes\",\"Fanzeres\",\"Fatela\",\"Fatima\",\"Faro\",\"Felgueiras\",\"Ferreira\",\"Figueira\",\"Flecheiras\",\"Florianopolis\",\"Fornalhas\",\"Fortaleza\",\"Freiria\",\"Freixeira\",\"Frielas\",\"Fronteira\",\"Funchal\",\"Fundao\",\"Gaeiras\",\"Gafanhadaboahora\",\"Goa\",\"Goiania\",\"Gracas\",\"Gradil\",\"Grainho\",\"Gralheira\",\"Guarulhos\",\"Guetim\",\"Guimaraes\",\"Horta\",\"Iguacu\",\"Igrejanova\",\"Ilhavo\",\"Ilheus\",\"Ipanema\",\"Iraja\",\"Itaboral\",\"Itacuruca\",\"Itaguai\",\"Itanhaem\",\"Itapevi\",\"Juazeiro\",\"Lagos\",\"Lavacolchos\",\"Laies\",\"Lamego\",\"Laranjeiras\",\"Leiria\",\"Limoeiro\",\"Linhares\",\"Lisboa\",\"Lomba\",\"Lorvao\",\"Lourencomarques\",\"Lourical\",\"Lourinha\",\"Luziania\",\"Macao\",\"Macapa\",\"Macedo\",\"Machava\",\"Malveira\",\"Manaus\",\"Mangabeira\",\"Mangaratiba\",\"Marambaia\",\"Maranhao\",\"Maringue\",\"Marinhais\",\"Matacaes\",\"Matosinhos\",\"Maxial\",\"Maxias\",\"Mealhada\",\"Meimoa\",\"Meires\",\"Milharado\",\"Mira\",\"Miranda\",\"Mirandela\",\"Mogadouro\",\"Montalegre\",\"Montesinho\",\"Moura\",\"Mourao\",\"Mozelos\",\"Negroes\",\"Neiva\",\"Nespereira\",\"Nilopolis\",\"Niteroi\",\"Nordeste\",\"Obidos\",\"Odemira\",\"Odivelas\",\"Oeiras\",\"Oleiros\",\"Olhao\",\"Olhalvo\",\"Olhomarinho\",\"Olinda\",\"Olival\",\"Oliveira\",\"Oliveirinha\",\"Oporto\",\"Ourem\",\"Ovar\",\"Palhais\",\"Palheiros\",\"Palmeira\",\"Palmela\",\"Palmital\",\"Pampilhosa\",\"Pantanal\",\"Paradinha\",\"Parelheiros\",\"Paripueira\",\"Paudalho\",\"Pedrosinho\",\"Penafiel\",\"Peniche\",\"Pedrogao\",\"Pegoes\",\"Pinhao\",\"Pinheiro\",\"Pinhel\",\"Pombal\",\"Pontal\",\"Pontinha\",\"Portel\",\"Portimao\",\"Poxim\",\"Quarteira\",\"Queijas\",\"Queluz\",\"Quiaios\",\"Ramalhal\",\"Reboleira\",\"Recife\",\"Redinha\",\"Ribadouro\",\"Ribeira\",\"Ribeirao\",\"Rosais\",\"Roteiro\",\"Sabugal\",\"Sacavem\",\"Sagres\",\"Sandim\",\"Sangalhos\",\"Santarem\",\"Santos\",\"Sarilhos\",\"Sarzedas\",\"Satao\",\"Satuba\",\"Seixal\",\"Seixas\",\"Seixezelo\",\"Seixo\",\"Selmes\",\"Sepetiba\",\"Serta\",\"Setubal\",\"Silvares\",\"Silveira\",\"Sinhaem\",\"Sintra\",\"Sobral\",\"Sobralinho\",\"Sorocaba\",\"Tabuacotavir\",\"Tabuleiro\",\"Taveiro\",\"Teixoso\",\"Telhado\",\"Telheiro\",\"Tomar\",\"Torrao\",\"Torreira\",\"Torresvedras\",\"Tramagal\",\"Trancoso\",\"Troviscal\",\"Vagos\",\"Valpacos\",\"Varzea\",\"Vassouras\",\"Velas\",\"Viana\",\"Vidigal\",\"Vidigueira\",\"Vidual\",\"Viladerei\",\"Vilamar\",\"Vimeiro\",\"Vinhais\",\"Vinhos\",\"Viseu\",\"Vitoria\",\"Vlamao\",\"Vouzela\"],\n [\"Acaltepec\",\"Acaltepecatl\",\"Acapulco\",\"Acatlan\",\"Acaxochitlan\",\"Ajuchitlan\",\"Atotonilco\",\"Azcapotzalco\",\"Camotlan\",\"Campeche\",\"Chalco\",\"Chapultepec\",\"Chiapan\",\"Chiapas\",\"Chihuahua\",\"Cihuatlan\",\"Cihuatlancihuatl\",\"Coahuila\",\"Coatepec\",\"Coatlan\",\"Coatzacoalcos\",\"Colima\",\"Colotlan\",\"Coyoacan\",\"Cuauhillan\",\"Cuauhnahuac\",\"Cuauhtemoc\",\"Cuernavaca\",\"Ecatepec\",\"Epatlan\",\"Guanajuato\",\"Huaxacac\",\"Huehuetlan\",\"Hueyapan\",\"Ixtapa\",\"Iztaccihuatl\",\"Iztapalapa\",\"Jalisco\",\"Jocotepec\",\"Jocotepecxocotl\",\"Matixco\",\"Mazatlan\",\"Michhuahcan\",\"Michoacan\",\"Michoacanmichin\",\"Minatitlan\",\"Naucalpan\",\"Nayarit\",\"Nezahualcoyotl\",\"Oaxaca\",\"Ocotepec\",\"Ocotlan\",\"Olinalan\",\"Otompan\",\"Popocatepetl\",\"Queretaro\",\"Sonora\",\"Tabasco\",\"Tamaulipas\",\"Tecolotlan\",\"Tenochtitlan\",\"Teocuitlatlan\",\"Teocuitlatlanteotl\",\"Teotlalco\",\"Teotlalcoteotl\",\"Tepotzotlan\",\"Tepoztlantepoztli\",\"Texcoco\",\"Tlachco\",\"Tlalocan\",\"Tlaxcala\",\"Tlaxcallan\",\"Tollocan\",\"Tolutepetl\",\"Tonanytlan\",\"Tototlan\",\"Tuchtlan\",\"Tuxpan\",\"Uaxacac\",\"Xalapa\",\"Xochimilco\",\"Xolotlan\",\"Yaotlan\",\"Yopico\",\"Yucatan\",\"Yztac\",\"Zacatecas\",\"Zacualco\"]\n ];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
rooter.findAndRequire(...$patterns) Method that first finds all the files matching the `glob` patterns provided from the `rooter.ROOT` path, and then imports them (using the usual cache of `node`). It works the same as `find` and `require` combined. So, it returns a list (with what modules returned). | findAndRequire(...patterns) {
return this.find(...patterns).map(pattern => require(pattern));
} | [
"find(...patterns) {\n\t\treturn globby.sync(flatten(patterns).map(pattern => this.resolve(pattern)));\n\t}",
"function loadModulesFromPattern(pattern) {\n\n\t\tlib.glob.sync(pattern).forEach(function(path) {\n\t\t\tloadModuleFromPath(path);\n\t\t});\n\n\t}",
"function find(pattern, rootDir, cb) {\n var files = glob.sync(pattern, { cwd: rootDir, mark: true });\n files = files.filter(function (name) { return name.slice(-1) !== \"/\"; });\n cb(null, files);\n }",
"_findAssets(root, pattern) {\n var options = {\n root: root,\n nodir: true\n }\n return glob(pattern, options)\n }",
"async function findFiles(globPatterns, options) {\n const globPats = globPatterns.filter((filename) => filename !== STDIN);\n const stdin = globPats.length < globPatterns.length ? [STDIN] : [];\n const globResults = globPats.length ? await (0, glob_1.globP)(globPats, options) : [];\n const cwd = options.cwd || process.cwd();\n return stdin.concat(globResults.map((filename) => path.resolve(cwd, filename)));\n}",
"async function findFiles(globPatterns, options) {\n const globPats = globPatterns.filter((filename) => filename !== STDIN);\n const stdin = globPats.length < globPatterns.length ? [STDIN] : [];\n const globResults = globPats.length ? await globP(globPats, options) : [];\n const cwd = options.cwd || process.cwd();\n return stdin.concat(globResults.map((filename) => path.resolve(cwd, filename)));\n}",
"async function globWithinWorkspace(patterns, options) {\n const { ignore, relative } = options || {};\n\n const relativePaths = await glob(patterns, { ignore, dot: true, cwd: ROOT });\n if (relative) return relativePaths;\n return relativePaths.map((relativePath) => path.join(ROOT, relativePath));\n}",
"function lookupAllFiles(options) {\n return options.files\n .map(pattern => Mocha.utils.lookupFiles(pattern, ['js'], options.recursive))\n .reduce((arr, pathOrArr) => arr.concat(pathOrArr), []);\n}",
"async globAll(patterns, options) {\n return new Promise((resolve, reject) => {\n globAll(patterns, options, (error, matches) => {\n if (error) {\n reject(error);\n }\n else {\n resolve(matches);\n }\n });\n });\n }",
"findAndExecute(...patterns) {\n\t\treturn this.find(...patterns).map(pattern => importFresh(pattern));\n\t}",
"async function glob(pattern) {\n const paths = await tiny_glob_1.default(normalize_path_1.default(pattern), { absolute: true });\n return paths.map((path) => normalize_path_1.default(path));\n}",
"function glob(/* patterns... */) {\n return glob.pattern.apply(null, arguments);\n }",
"function getGlobbedFiles(...globPatterns) {\n\n return globPatterns\n .reduce(function(allFiles, globPattern) {\n Array.prototype.push.apply( allFiles, glob(globPattern, { sync: true }) );\n return allFiles;\n }, [])\n .map( path => Path.resolve(path) );\n}",
"function find(path, ignore = [], filter = [], levelsDeep = 2) {\n return __awaiter(this, void 0, void 0, function* () {\n const found = [];\n // ensure we ignore find against node_modules path.\n if (path.endsWith('node_modules')) {\n return found;\n }\n // ensure node_modules is always ignored\n if (!ignore.includes('node_modules')) {\n ignore.push('node_modules');\n }\n try {\n if (levelsDeep < 0) {\n return found;\n }\n else {\n levelsDeep--;\n }\n const fileStats = yield getStats(path);\n if (fileStats.isDirectory()) {\n const files = yield findInDirectory(path, ignore, filter, levelsDeep);\n found.push(...files);\n }\n else if (fileStats.isFile()) {\n const fileFound = findFile(path, filter);\n if (fileFound) {\n found.push(fileFound);\n }\n }\n return found;\n }\n catch (err) {\n throw new Error(`Error finding files in path '${path}'.\\n${err.message}`);\n }\n });\n}",
"function findJSFiles(root_path) {\n return new Promise(function(resolve, reject) {\n var js_files = [];\n var formats_finder = new FindFiles({\n rootFolder: root_path,\n filterFunction: function(path, stat) {\n return path.match(/\\.js$/, path) && stat.isFile();\n },\n });\n formats_finder.on('match', function(path, stat) {\n js_files.push(path);\n });\n formats_finder.on('patherror', function(err, path) {\n reject('Failed on path ' + path + ' with err = ', err);\n });\n formats_finder.on('complete', function() {\n resolve(js_files);\n });\n formats_finder.startSearch();\n });\n}",
"parseAllFiles(pattern, callback) {\n glob(pattern, (err, filepaths) => {\n if (err) throw err;\n\n async.map(filepaths, this.parseFile, callback);\n });\n }",
"match(pattern) {\n const base = this.dirPath.base;\n const files = fast_glob_1.default.sync(path_1.default.join(this.dirPath.fragment, pattern), {\n cwd: base,\n onlyFiles: true,\n globstar: true,\n });\n return new TaskArray_1.TaskArray(files.map(file => {\n const task = new SourceFileTask_1.SourceFileTask(new Paths_1.Path(file, base));\n sourceInternal_1.addSource(task);\n return task;\n }), this.dirPath);\n }",
"globP(pattern, options) {\r\n return new Promise((resolve, reject) => {\r\n glob_1.default(pattern, options, (err, files) => {\r\n if (err) {\r\n reject(err);\r\n }\r\n else {\r\n resolve(files);\r\n }\r\n });\r\n });\r\n }",
"function readFiles(path, pattern) {\n return readdir(path).then(function (children) {\n children = children.filter(function (child) {\n return pattern.test(child);\n });\n var fileChildren = children.map(function (child) {\n return fileExistsWithResult(paths.join(path, child), child);\n });\n return winjs_base_1.TPromise.join(fileChildren).then(function (subdirs) {\n return removeNull(subdirs);\n });\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate that the feedSlug matches \w | function validateFeedSlug(feedSlug) {
if (!validFeedSlugRe.test(feedSlug)) {
throw new _errors__WEBPACK_IMPORTED_MODULE_1__/* .FeedError */ .IY("Invalid feedSlug, please use letters, numbers or _: ".concat(feedSlug));
}
return feedSlug;
} | [
"function validateFeedSlug(feedSlug) {\n if (!validFeedSlugRe.test(feedSlug)) {\n throw new _errors.FeedError(\"Invalid feedSlug, please use letters, numbers or _: \".concat(feedSlug));\n }\n\n return feedSlug;\n}",
"judgeSlug () {\n\t\tif (!this.SEO.snippetFields.slug)\n\t\t\treturn;\n\t\t\n\t\tconst slug = this.SEO.snippetFields.slug.textContent.toLowerCase();\n\t\tconst keyword = this.keywordLower.replace(/[\\t\\s]+/g, '-');\n\t\tconst keywoerd = normalizeDiacritics(keyword);\n\n\t\tif (slug.indexOf(keyword) > -1 || slug.indexOf(keywoerd) > -1) {\n\t\t\tthis.addRating(\n\t\t\t\tSEO_RATING.GOOD,\n\t\t\t\tSEO_REASONS.slugSuccess\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tthis.addRating(\n\t\t\tSEO_RATING.POOR,\n\t\t\tSEO_REASONS.slugFail\n\t\t);\n\t}",
"function isSlugInvalid(slugstring) {\n //(only a-z, A-Z, 0-9 and \"_\" are allowed as characters!)\n var forbiddenCharRegex = /^\\w+$/;\n if (!forbiddenCharRegex.test(slugstring)) {return 1;}\n else {return 0;}\n}",
"function validateTitle(title){\n if(title.match(/^[A-Za-z0-9 _-]+$/))\n return true;\n else\n return false;\n}",
"function validateTitle(title){\n pattern = /^[A-Za-z_-]+$/g;\n if(pattern.test(title))\n return true;\n else\n return false;\n}",
"function urlSlug(title) {\n return title.split(/\\W/).filter( (e) => e != '').join('-').toLowerCase(); \n}",
"function isSlug (field) {\n const regex = /^[a-z0-9-]*$/i\n if (!regex.test(newDoc[field])) {\n throw new Error(field + ' must consist of [a-z0-9-]')\n }\n\n if (newDoc[field].length > 32) {\n throw new Error(field + ' cannot be longer then 32 characters')\n }\n }",
"function urlSlug(title) {\n\n let toLower = title.toLowerCase();\n let sluggish = toLower.split(/\\W/);\n sluggish = sluggish.filter(ele => ele != \"\");\n sluggish = sluggish.join('-');\n return sluggish;\n\n}",
"static slug(value) {\n if (value.endsWith(\"-\") === true) {\n return {\n valid: false,\n message: \"Slug can not end with a hyphen.\"\n }\n } else if ((new RegExp(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)).test(value) !== true) {\n return {\n valid: false,\n message: \"Slug can only contain lowercase letters, numbers, and hyphens.\"\n }\n } else {\n return {\n valid: true\n }\n }\n }",
"validateIntentName(name){\n var regex = /[a-zA-Z\\-0-9]+([_]|[-]|[a-zA-Z\\-0-9])*$/;\n return regex.test(name);\n }",
"function checkSlug(slug, callbackFunction) {\n checkSlug(slug, null, callbackFunction);\n}",
"function checkSiteName() {\n siteNameregex = /^[A-z0-9]{3,10}$/;\n let result = siteNameregex.test($('#site-name').val())\n return result\n}",
"isValid(word) {\n if (typeof word !== 'string') {\n return false;\n }\n\n if ( /^[a-zA-Z]+$/.test(word) ) {\n return true;\n }\n }",
"function stringIsWord(value) {\n\treturn value.length <=50 && /^[a-z\\-\\s]+$/i.test(value) && !/^[\\-\\s]+$/.test(value);\n}",
"function validate_name(name) {\n return /^[A-Za-z\\s-]+$/.test(name.value) || /^[a-zA-Z ]+$/.test(name.value);\n\n}",
"function urlSlugNoUnderscore(title) {\n \n let slug = title.split(/[\\W_]+/g);\n\n // if let slug = title.split(/\\W/); --> slug is an array has no punctuation but the underscores still remain\n\n return slug.filter(element => element !== '').join('-').toLowerCase(); \n}",
"validate(token) {\n return /\\w{2,}/.test(token);\n }",
"function imageNameCheck(string)\n {\n //http://stackoverflow.com/questions/336210/regular-expression-for-alphanumeric-and-underscores\n var res = string.match(/^[a-z0-9._ -]+$/i);\n if(res==null)\n {\n swal(\"Oops...\", \"Only English alphabet, numbers, space, '.', '-' and '_' is allowed for image/video name\", \"error\");\n return false;\n }\n else\n return true;\n }",
"function legalWord(word){\n word = word.toLowerCase();\n if (word.length <= 2){ //means word is at least 3 characters\n return false\n }\n \n if (word == \"http\" ||word == \"www\" ||word == \"https\"){\n \n return false\n }\n return true\n \n \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
I. transmogrify Write a Javascript function called transmogrify. This function should accept three arguments, which you can assume will be numbers. Your function should return the "transmogrified" result. The transmogrified result of three numbers is the product of the first two numbers, raised to the power of the third number. For example, the transmogrified result of 5, 3, and 2 is (5 times 3) to the power of 2 is 225. console.log(transmogrify(5, 3, 2));=> 225 | function transmorgify(num1, num2, num3){
return Math.pow(num1 * num2, num3);
} | [
"function transmogrify(num1,num2,num3) {\n return (num1 * num2) ** num3\n}",
"function transmorgrify(num1, num2, num3) {\n return(num1 * num2) ** num3\n}",
"function transmogrifier(num1, num2, num3) {\n\t// multiply first two numbers\n\tvar base = num1 * num2;\n\t// raise first two numbers to the power of third number\n\tvar transmogrified = Math.pow(base, num3);\n\treturn transmogrified;\n}",
"function transmogrify(num1,num2,num3) {\n // Calculate num1 and num2 using the Math.pow() multiple the result by num3\n return Math.pow(num1 * num2, num3);\n \n }",
"function transmogrifier(one, two, three) {\n return Math.pow(one * two, three); \n}",
"function transmogrifier(num1=0, num2=0, num3=0) {\n\tvar sum = 0;\n\tsum = num1 * num2; \n\treturn Math.pow(sum, num3);\n}",
"function transmogrifier(number1, number2, number3) {\n return Math.pow(number1*number2, number3)\n}",
"function transmogrifier(num1, num2, num3) {\n return Math.pow((num1 * num2), num3);\n}",
"function transmogrifier(num1, num2, num3) {\n return Math.pow((num1*num2),num3);\n}",
"function multiplyTrio(a,b,c){\n\treturn a*b*c;\n}",
"function multiplizieren(a,b) {\r\n return a * b;\r\n}",
"function product(a) {\n\nreturn a * 3;\n\n}",
"function multiplizieren(a,b) {\n return a * b;\n}",
"function muliplizieren(a,b) {\r\n return a * b;\r\n}",
"function multiplcation (a,b) {return a*b}",
"function productNumbers(a, b, c) {\n return a * b * c;\n}",
"function multiplyTwoNumbers(a, b) {\nreturn a * b\n}",
"function transformNumbers(numbers2){\n\tfor(let i=0; i<numbers2.length; i++){\n\t\tnumbers[i] = Math.pow(numbers[i], 2)\n\t}\n}",
"function multiplyThree( numOne, numTwo, numThree ){\nreturn numOne * numTwo * numThree;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generator function. Returns a function which returns incrementing Fibonacci numbers with each call. | function Fibonacci() {
// Create a new fiber which yields sequential Fibonacci numbers
var fiber = Fiber(function() {
Fiber.yield(0); // F(0) -> 0
var prev = 0, curr = 1;
while (true) {
Fiber.yield(curr);
var tmp = prev + curr;
prev = curr;
curr = tmp;
}
});
// Return a bound handle to `run` on this fiber
return fiber.run.bind(fiber);
} | [
"function Fibonacci() {\n // Create a new fiber which yields sequential Fibonacci numbers\n var fiber = Fiber(function () {\n Fiber.yield(0); // F(0) -> 0\n var prev = 0, curr = 1;\n while (true) {\n Fiber.yield(curr);\n var tmp = prev + curr;\n prev = curr;\n curr = tmp;\n }\n });\n // Return a bound handle to `run` on this fiber\n return fiber.run.bind(fiber);\n}",
"function genfib(){\n let arr = [0, 1];\n let idx = 0;\n return function fib(){\n if(idx == 0){\n idx++;\n return 0;\n } else if(idx == 1){\n idx++;\n return 1;\n } else if(idx > 1){\n arr[idx] = arr[idx - 1] + arr[idx - 2];\n idx++;\n return arr[arr.length - 1];\n }\n }\n }",
"function fibonacciIterator(count) {\n let current =0 , next= 1;\n let total = 0;\n //Iterator is simply an object with a next() function\n // which returns the next value in the sequence\n let iterator = {\n next: function() {\n //If total number of elements in the series have been generated\n if(total < count ){ \n //Current value of the iterator done -> whether iteration has completed. \n let result = { value:current ,done:false};\n let temp = current;\n current = next;\n next = next + temp;\n total++;\n return result;\n } else {\n return { value:total,done:true}\n }\n\n }\n }\n return iterator;\n}",
"function fibonacci() {\r\n return defer(function* () {\r\n let prev = 1;\r\n let curr = 1;\r\n yield prev;\r\n yield curr;\r\n for (;;) {\r\n let temp = prev;\r\n prev = curr;\r\n curr = temp + curr;\r\n yield curr;\r\n }\r\n });\r\n}",
"function genfib(){\n var arr = [0, 1];\n var idx = -1;\n\n return function fib(){\n arr.push( arr[arr.length-1] + arr[arr.length-2] );\n return arr[++idx];\n }\n}",
"function fibonaccif(){\n let invocationCounter = -1;\n\n function fibonacci(x) {\n if (x === 0) return 0;\n if (x <= 1) return 1;\n \n return fibonacci(x - 1) + fibonacci(x - 2);\n };\n\n return function(){\n invocationCounter++;\n return fibonacci(invocationCounter)\n }\n\n}",
"function iFibonacci(num){\n var num1 = 0;\n var num2 = 1;\n var total = 0;\n if(num == 0){return 0};\n if(num == 1){return 1};\n for(var i = 2; i<=num; i++){\n total = num1 + num2;\n num1 = num2;\n num2 = total;\n };\n return total;\n}",
"function fibonacciGenerator (n) {\n \n var fibNumbers = [];\n for (var i = 0; i < n; i++){\n if (i <= 1) {\n fibNumbers.push(i);\n } else{\n fibNumbers.push(fibNumbers[i - 2] + fibNumbers[i - 1]); \n } \n }\n \n return fibNumbers;\n }",
"function iterativeFibonacci(n){\n var fibs= [0,1];\n\n for(i=0; i < n; i++){\n fibs.push(fibs[0] + fibs[1]);\n fibs.shift();\n }\n return fibs[0];\n}",
"function fibonacci(n) {\n\t// set a default limit\n\tif(!n) var n = 0;\n\t//start with 0 and 1\n\tvar a = 0,\n\t\tb = 1,\n\t\tx = a + b;\n\t// console.log(a + ' + ' + b + ' =', x);\n\t// start the sequence with a loop\n\tfor(a;x<n;) {\n\t\ta = b;\n\t\tb = x;\n\t\tx = a + b;\n\t\t// console.log(a + ' + ' + b + ' =', x);\n\t}\n\treturn x;\n}",
"function iFibonacci(num){\n var fib = [0, 1];\n for(var i = 0; i < num; i++){\n fib.push(fib[0] + fib[1]);\n fib.shift();\n }\n return fib[0];\n}",
"function getFibonacciNumber(index){\n\n if(index === null || index === undefined || index < 0)\n return null;\n\n var previous_first = 0, previous_second = 1, next = 1;\n\n for(var i = 2; i <= index; i++) {\n next = previous_first + previous_second;\n previous_first = previous_second;\n previous_second = next;\n }\n return next;\n}",
"function suiteFibonacci(nbr){\n\n let a = 0\n let b = 1\n let resu = 1\n\n for(i=2; i<=nbr; i++){\n resu = a + b;\n a = b;\n b = resu;\n}\n return resu\n\n }",
"function fibonacci(index) {\n if (index == 0) return 0;\n if (index == 1) return 1;\n var f1 = 0;\n var f2 = 1;\n var swapper;\n for (var i = 2; i <= index; i++) {\n swapper = f2;\n f2 = f1 + f2;\n f1 = swapper;\n }\n console.log(\"fibonacci at 3 index is: \", f2);\n}",
"function rFibonacci(num){\n if(num === 0){\n return 0;\n }else if(num === 1 || num === 2){\n return 1;\n }else{\n return rFibonacci(num - 2) + rFibonacci(num - 1);\n }\n}",
"function fibonnaci(f) {\n var ab = [1, 1];\n while (ab.length < ARGSMAX) {\n ab.push(ab[ab.length - 2] + ab[ab.length - 1]);\n }\n\n while (f.apply(null, ab)) {\n ab.shift();\n ab.push(ab[2] + ab[3]);\n }\n }",
"function febonacci(n){\n let febo = [0,1];\n for(let i = 2; i <= n; i++){\n febo[i] = febo[i - 1] + febo [i- 2];\n \n } \n return febo;\n}",
"function Fibonacci(n){\n if(n == 0){\n return 0;\n }\n if(n == 1){\n return 1;\n }\n return Fibonacci(n-1) + Fibonacci(n-2) ;\n}",
"function fibSeq () {\n let arr = [1,0];\n return function () {\n arr.push(arr[arr.length-2] + arr[arr.length-1])\n return arr[arr.length-1];\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runtime helper for merging vbind="object" into a VNode's data. | function bindObjectProps(data,tag,value,asProp,isSync){if(value){if(!isObject(value)){"development"!=='production'&&warn('v-bind without argument expects an Object or Array value',this);}else{if(Array.isArray(value)){value=toObject(value);}var hash;var loop=function loop(key){if(key==='class'||key==='style'||isReservedAttribute(key)){hash=data;}else{var type=data.attrs&&data.attrs.type;hash=asProp||config.mustUseProp(tag,type,key)?data.domProps||(data.domProps={}):data.attrs||(data.attrs={});}if(!(key in hash)){hash[key]=value[key];if(isSync){var on=data.on||(data.on={});on["update:"+key]=function($event){value[key]=$event;};}}};for(var key in value){loop(key);}}}return data;} | [
"function bindObjectProps(\ndata,\ntag,\nvalue,\nasProp,\nisSync)\n{\nif(value){\nif(!isObject(value)){\nwarn(\n'v-bind without argument expects an Object or Array value',\nthis);\n\n}else {\nif(Array.isArray(value)){\nvalue=toObject(value);\n}\nvar hash;\nvar loop=function loop(key){\nif(\nkey==='class'||\nkey==='style'||\nisReservedAttribute(key))\n{\nhash=data;\n}else {\nvar type=data.attrs&&data.attrs.type;\nhash=asProp||config.mustUseProp(tag,type,key)?\ndata.domProps||(data.domProps={}):\ndata.attrs||(data.attrs={});\n}\nvar camelizedKey=camelize(key);\nvar hyphenatedKey=hyphenate(key);\nif(!(camelizedKey in hash)&&!(hyphenatedKey in hash)){\nhash[key]=value[key];\n\nif(isSync){\nvar on=data.on||(data.on={});\non[\"update:\"+key]=function($event){\nvalue[key]=$event;\n};\n}\n}\n};\n\nfor(var key in value){loop(key);}\n}\n}\nreturn data;\n}",
"function bindObjectProps(data,tag,value,asProp,isSync){if(value){if(!isObject(value)){\"production\"!=='production'&&warn('v-bind without argument expects an Object or Array value',this);}else{if(Array.isArray(value)){value=toObject(value);}var hash;var loop=function loop(key){if(key==='class'||key==='style'||isReservedAttribute(key)){hash=data;}else{var type=data.attrs&&data.attrs.type;hash=asProp||config.mustUseProp(tag,type,key)?data.domProps||(data.domProps={}):data.attrs||(data.attrs={});}if(!(key in hash)){hash[key]=value[key];if(isSync){var on=data.on||(data.on={});on[\"update:\"+key]=function($event){value[key]=$event;};}}};for(var key in value){loop(key);}}}return data;}",
"function bindObjectProps(data, tag, value, asProp) {\n\t if (value) {\n\t if (!isObject(value)) {\n\t (\"production\") !== 'production' && warn('v-bind without argument expects an Object or Array value', this);\n\t } else {\n\t if (Array.isArray(value)) {\n\t value = toObject(value);\n\t }\n\t var hash;\n\t for (var key in value) {\n\t if (key === 'class' || key === 'style') {\n\t hash = data;\n\t } else {\n\t var type = data.attrs && data.attrs.type;\n\t hash = asProp || config.mustUseProp(tag, type, key) ? data.domProps || (data.domProps = {}) : data.attrs || (data.attrs = {});\n\t }\n\t if (!(key in hash)) {\n\t hash[key] = value[key];\n\t }\n\t }\n\t }\n\t }\n\t return data;\n\t}",
"function bindObjectProps(data,tag,value,asProp,isSync){if(value){if(!isObject(value)){\"development\"!=='production'&&warn('v-bind without argument expects an Object or Array value',this);}else{if(Array.isArray(value)){value=toObject(value);}var hash;var loop=function(key){if(key==='class'||key==='style'||isReservedAttribute(key)){hash=data;}else{var type=data.attrs&&data.attrs.type;hash=asProp||config.mustUseProp(tag,type,key)?data.domProps||(data.domProps={}):data.attrs||(data.attrs={});}if(!(key in hash)){hash[key]=value[key];if(isSync){var on=data.on||(data.on={});on[\"update:\"+key]=function($event){value[key]=$event;};}}};for(var key in value)loop(key);}}return data;}",
"function rtdbBindAsObject({ target, document, resolve, reject, ops }, extraOptions = DEFAULT_OPTIONS) {\r\n const key = 'value';\r\n const options = Object.assign({}, DEFAULT_OPTIONS, extraOptions);\r\n const listener = document.on('value', (snapshot) => {\r\n ops.set(target, key, options.serialize(snapshot));\r\n }\r\n // TODO: allow passing a cancel callback\r\n // cancelCallback\r\n );\r\n document.once('value', resolve, reject);\r\n return (reset) => {\r\n document.off('value', listener);\r\n if (reset !== false) {\r\n const value = typeof reset === 'function' ? reset() : null;\r\n ops.set(target, key, value);\r\n }\r\n };\r\n }",
"function bindObjectProps(data,tag,value,asProp,isSync){if(value){if(!isObject(value)){warn('v-bind without argument expects an Object or Array value',this);}else{if(Array.isArray(value)){value=toObject(value);}var hash;var loop=function loop(key){if(key==='class'||key==='style'||isReservedAttribute(key)){hash=data;}else{var type=data.attrs&&data.attrs.type;hash=asProp||config.mustUseProp(tag,type,key)?data.domProps||(data.domProps={}):data.attrs||(data.attrs={});}var camelizedKey=camelize(key);var hyphenatedKey=hyphenate(key);if(!(camelizedKey in hash)&&!(hyphenatedKey in hash)){hash[key]=value[key];if(isSync){var on=data.on||(data.on={});on[\"update:\"+key]=function($event){value[key]=$event;};}}};for(var key in value){loop(key);}}}return data;}",
"function bindObjectProps(data, tag, value, asProp) {\n if (value) {\n if (!isObject(value)) {\n \"development\" !== 'production' && warn('v-bind without argument expects an Object or Array value', this);\n } else {\n if (Array.isArray(value)) {\n value = toObject(value);\n }\n var hash;\n for (var key in value) {\n if (key === 'class' || key === 'style') {\n hash = data;\n } else {\n var type = data.attrs && data.attrs.type;\n hash = asProp || config.mustUseProp(tag, type, key) ? data.domProps || (data.domProps = {}) : data.attrs || (data.attrs = {});\n }\n if (!(key in hash)) {\n hash[key] = value[key];\n }\n }\n }\n }\n return data;\n }",
"function attach(obj){\n attachData = obj;\n }",
"function rtdbBindAsObject(_a, extraOptions) {\r\n var vm = _a.vm, key = _a.key, document = _a.document, resolve = _a.resolve, reject = _a.reject, ops = _a.ops;\r\n if (extraOptions === void 0) { extraOptions = DEFAULT_OPTIONS; }\r\n var options = Object.assign({}, DEFAULT_OPTIONS, extraOptions);\r\n var listener = document.on('value', function (snapshot) {\r\n ops.set(vm, key, options.serialize(snapshot));\r\n }, reject);\r\n document.once('value', resolve);\r\n return function (reset) {\r\n document.off('value', listener);\r\n if (reset !== false) {\r\n var value = typeof reset === 'function' ? reset() : null;\r\n ops.set(vm, key, value);\r\n }\r\n };\r\n}",
"function bindElement(element, object) {\n setPropertyOnElement(element, DATA_BINDING_ID, object);\n }",
"function extendsObjectWithObject(object, model) {\n\t\t\t// (if you want tools that do that nicely for you (and manymore) you should try deep-compiler)\n\t\t\tfor (var i in model)\n\t\t\t\tobject[i] = decompose.up(object[i], model[i]);\n\t\t}",
"function TinyBind(object, parent) {\n /** \n * a Element->Variable dict\n * \n * @example [{ ele: Element, var: \"profile.name\" }]\n */\n this.bindDict = [];\n this.object = object;\n \n /** a callback when data updated */\n this.onUpdate = null;\n\n /** \n * update a element or a field value\n * \n * @param {bindItem} item from this.bindDict\n * @param {boolean} v2m true if want to update module's field\n */\n this.exec = function(item, v2m) {\n if (v2m) {\n this.ptr(item.var, this.eleVal(item.ele));\n (typeof this.onUpdate === \"function\") && this.onUpdate(this)\n }\n else this.eleVal(item.ele, this.ptr(item.var));\n }\n\n /** \n * get or set a value of Module\n * \n * @param {string} name varname\n * @param {any?} val the new value. if is `undefined`, the value will not apply.\n */\n this.ptr = function(name, val) {\n var p = this.object;\n var fieldList = name.split(\".\");\n var lastField = fieldList.pop();\n fieldList.forEach(function(name) {\n if (typeof(p[name]) === \"undefined\") p[name] = {}\n p = p[name]\n });\n if (typeof(val) !== \"undefined\") p[lastField] = val;\n return p[lastField];\n }\n\n /**\n * get value from an element, or set a element\n * \n * @param {Element} ele\n * @param {any?} val the new value for the ele. if `undefined`, do not change the element\n * @param {any} the best field value for this.object\n */\n this.eleVal = function(ele, val) {\n var valDefined = typeof(val) !== \"undefined\";\n var nodeName = ele.nodeName;\n if (nodeName === \"INPUT\") {\n //this is a input \n var type = (ele.getAttribute(\"type\") || \"text\").toLowerCase();\n if (type === \"checkbox\") {\n if (valDefined) ele.checked = val;\n return ele.checked;\n }\n if (valDefined) ele.value = val;\n return ele.value;\n }\n if (nodeName === \"SELECT\") {\n //a select box\n if (valDefined) {\n var options = ele.children;\n var i = options.length;\n while (--i !== -1) {\n var option = options[i];\n if (option.value === val) {\n option.selected = true;\n break;\n }\n }\n }\n return ele.value;\n }\n }\n\n this.changeHandler = function(ev) {\n var d = this.bindDict;\n var i = d.length;\n while (--i !== -1) {\n if (d[i].ele !== ev.target) continue;\n this.exec(d[i], true);\n break;\n }\n }\n\n var inputs = parent.querySelectorAll(\"[t-bind]\");\n var i = inputs.length;\n var h = this.changeHandler.bind(this);\n while (--i !== -1) {\n var ele = inputs[i],\n x = {\n ele: ele,\n var: ele.getAttribute('t-bind')\n };\n this.bindDict.push(x);\n this.exec(x, false);\n ele.addEventListener('change', h, false);\n }\n}",
"function createBinding(obj, template) {\n if (!TEMPLATEPROCESSEDMAP.get(template)) {\n processTemplate(template);\n };\n var clone = TEMPLATEPROCESSEDMAP.get(template).cloneNode(true);\n var target = { };\n var proxy = new Proxy(target, PROXYOBJECT);\n var context = createContext(clone, template);\n var startNode = createAnchor(0, 'proxy');\n var endNode = createAnchor(1, 'proxy');\n var nodes = [startNode, endNode];\n var mount = obj[SYMBOLMOUNT];\n var unmount = obj[SYMBOLUNMOUNT];\n var move = obj[SYMBOLMOVE];\n var fragment = document.createDocumentFragment();\n if (unmount) {\n PROXYUNMOUNTMAP.set(proxy, unmount);\n };\n if (move) {\n PROXYMOVEMAP.set(proxy, move);\n };\n TARGETCONTEXTMAP.set(target, context);\n TARGETEVENTMAP.set(target, { });\n TARGETDELIMITERMAP.set(target, { });\n for (var key in obj) {\n if (key in context) {\n continue;\n };\n target[key] = obj[key];\n };\n for (var key in context) {\n setProperty(target, key, obj[key], proxy, true);\n };\n if (mount) {\n mount.call(proxy, clone);\n };\n fragment.appendChild(startNode);\n fragment.appendChild(clone);\n fragment.appendChild(endNode);\n PROXYDELIMITERMAP.set(proxy, nodes);\n __PS_MV_REG = [];\n return [proxy, fragment];\n}",
"function extendVm(vm, key) {\r\n\tvar ctx = vm._vuebackbone[key],\r\n\t\tdataKey = getDataKey(key);\r\n\r\n\tvm.$bb = vm.$bb || {};\r\n\tObject.defineProperty(vm.$bb, key, {\r\n\t\tget() {\r\n\t\t\tlet access = vm.$data[dataKey]; // eslint-disable-line no-unused-vars\r\n\t\t\treturn ctx.bb;\r\n\t\t},\r\n\t\tset(bb) {\r\n\t\t\tunbindBBFromVue(vm, key);\r\n\t\t\tctx.bb = bb;\r\n\t\t\tvm.$data[dataKey] = rawSrc(bb);\r\n\t\t\tbindBBToVue(vm, key);\r\n\t\t}\r\n\t});\r\n}",
"async _processBindValue(bindInfo, value, options) {\n const transformed = transformer.transformValueIn(bindInfo, value, options);\n if (bindInfo.isArray) {\n bindInfo.values = transformed.concat(bindInfo.values.slice(transformed.length));\n } else {\n bindInfo.values[options.pos] = transformed;\n }\n if (bindInfo.type === types.DB_TYPE_OBJECT &&\n bindInfo.typeClass === undefined) {\n bindInfo.typeClass = await this._getDbObjectClass(value._objType);\n bindInfo.objType = bindInfo.typeClass._objType;\n }\n }",
"function objExtend(data) {\n\tvar i, j;\n\tfor (i in data) {\n\t\tif (!bobj[i]) bobj[i] = {};\n\t\tfor (j in data[i]) {\n\t\t\tif (!bobj[i][j]) bobj[i][j] = 0;\n\t\t\tbobj[i][j] += data[i][j];\n\t\t}\n\t}\n}",
"function setDataRoot(obj) { data = obj }",
"function overlay(base, object) {\n for (var key in object) {\n if (!object.hasOwnProperty(key)) {\n continue;\n }\n if (typeof object[key] === 'object' && typeof base[key] === 'object') {\n overlay(base[key], object[key]);\n } else {\n base[key] = object[key];\n }\n }\n}",
"_bindRootQueriesAndMutations(obj) {\n const out = {};\n for (const key in obj)\n if (key === 'RootMutation' || key === 'RootQuery') {\n out[key] = {};\n for (const key2 in obj[key])\n out[key][key2] = obj[key][key2].bind(this);\n } else {\n out[key] = obj[key];\n }\n return out;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrain NN with new training data | function retrain() {
trainingData = _.shuffle(trainingData);
train();
} | [
"function retrain() {\r\n percept.reset();\r\n train();\r\n}",
"reset() {\n let input = tf.input({shape: [this._inputSize]});\n let last = input;\n for (let i=0; i < this._numLayers; i++) {\n \tlast = tf.layers.dense({units: this._layout[i], activation: this._activation}).apply(last);\n }\n let output = tf.layers.dense({units: 1, activation: 'linear'}).apply(last);\n let model = tf.model({inputs: input, outputs: output});\n model.compile({loss: this._loss, optimizer: this._optimizer, metrics: ['mae']});\n this._model = model;\n\n this._training_x = [];\n this._training_y = [];\n }",
"function train() { \n for (var i = 0; i < trainingData.length; i++) { \n input.activate(trainingData[i][\"input\"]); \n output.activate(); \n output.propagate(learningRate, trainingData[i][\"output\"]); \n }\n}",
"async retrainModel() {\n ui.status(\n 'Please wait and do NOT click anything while the model retrains...',\n 'blue');\n\n const trainingMode = ui.getTrainingMode();\n if (trainingMode === 'freeze-feature-layers') {\n console.log('Freezing feature layers of the model.');\n for (let i = 0; i < 7; ++i) {\n this.model.layers[i].trainable = false;\n }\n } else if (trainingMode === 'reinitialize-weights') {\n // Make a model with the same topology as before, but with re-initialized\n // weight values.\n const returnString = false;\n this.model = await tf.models.modelFromJSON({\n modelTopology: this.model.toJSON(null, returnString)\n });\n }\n this.model.compile({\n loss: 'categoricalCrossentropy',\n optimizer: tf.train.adam(0.01),\n metrics: ['acc'],\n });\n\n // Print model summary again after compile(). You should see a number\n // of the model's weights have become non-trainable.\n this.model.summary();\n\n const batchSize = 128;\n const epochs = ui.getEpochs();\n\n const surfaceInfo = {name: trainingMode, tab: 'Transfer Learning'};\n console.log('Calling model.fit()');\n await this.model.fit(this.gte5TrainData.x, this.gte5TrainData.y, {\n batchSize: batchSize,\n epochs: epochs,\n validationData: [this.gte5TestData.x, this.gte5TestData.y],\n callbacks: [\n ui.getProgressBarCallbackConfig(epochs),\n tfVis.show.fitCallbacks(surfaceInfo, ['val_loss', 'val_acc'], {\n zoomToFit: true,\n zoomToFitAccuracy: true,\n height: 200,\n callbacks: ['onEpochEnd'],\n }),\n ]\n });\n console.log('DONE Calling model.fit()');\n }",
"train(data) {\n this.x = transpose(data.x);\n this.y = new NN_vec1D(data.y);\n \n this.noCategories = data.no_classes();\n this.noInputs = data.no_attr();\n this.training_done = false;\n this.current_iter = 0;\n \n //Initializes weights and biases\n this.init();\n }",
"function train() {\n // gets net and training data\n var net = new brain.NeuralNetwork();\n var trainingDataRaw = fs.readFileSync('./excerpts.js');\n var trainingData = JSON.parse(trainingDataRaw);\n \n // gets a few excerpts\n var selectData = [];\n for (i = 0; i < 20; i++) {\n var next = trainingData[Math.floor((Math.random() * trainingData.length))];\n selectData.push(next);\n }\n // maps encoded training data\n selectData = compute(selectData);\n \n // trains network and returns it\n net.train(selectData, {\n log: true\n });\n \n return net;\n}",
"function train(data) {\n let net = new brain.NeuralNetwork();\n net.train(processTrainingData(data, {\n errorThresh: 0.005, // error threshold to reach\n iterations: 20000, // maximum training iterations\n log: true, // console.log() progress periodically\n logPeriod: 10, // number of iterations between logging\n learningRate: 0.1 // learning rate\n}));\n trainedNet = net.toFunction();\n\tdocument.getElementById(\"rslts\").innerHTML = \"Training complete.\";\n\t\n}",
"function train(data) {\n let net = new brain.NeuralNetwork();\n net.train(processTrainingData(data));\n trainedNet = net.toFunction();\n console.log(\"Netzwerk trainiert\");\n}",
"function trainModelnflx() {\r\n const trainingOptionsnflx = {\r\n epochs: 50, // 50 times\r\n batchSize: 10\r\n }\r\n nnetnflx.train(trainingOptionsnflx, whileTrainingnflx, finishedTrainingnflx);\r\n}",
"train() {\n\t\tif (!this.model) {\n\t\t\tthis.model = this.buildModel();\n\t\t\tthis.targetModel = this.buildModel();\n\t\t\tthis.targetModel.trainable = false;\n\t\t\tthis.copyWeights(this.model, this.targetModel);\n\t\t}\n\t\tlet [states, actions, rewards, dones] = this.rollout(this.replayBuffer.maxSize);\n\t\tthis.replayBuffer.pushEpisode(states, actions, rewards, dones);\n\t\tfor (let i = 0; i < this.trainSteps; i++) {\n\t\t\tthis.epsilon = this.getEpsilon(i);\n\t\t\t[states, actions, rewards, dones] = this.rollout(64);\n\t\t\tthis.replayBuffer.pushEpisode(states, actions, rewards, dones);\n\t\t\tlet loss = this.update();\n\t\t\tif (i != 0 && i % this.copyPeriod == 0) {\n\t\t\t\tthis.copyWeights(this.model, this.targetModel);\n\t\t\t}\n\t\t\tif (i != 0 && i % this.loggingPeriod == 0) {\n\t\t\t\tthis.log(loss);\n\t\t\t}\n\t\t}\n\t}",
"function dataLoadednflx() {\r\n nnetnflx.normalizeData(); //normalize\r\n trainModelnflx();\r\n}",
"function trainModelamzn() {\r\n const trainingOptionsamzn = {\r\n epochs: 50, // 50 times\r\n batchSize: 10\r\n }\r\n nnetamzn.train(trainingOptionsamzn, whileTrainingamzn, finishedTrainingamzn);\r\n}",
"function train(data){\r\n initInputAndObjective(data);\r\n propagate();\r\n backpropagate();\r\n}",
"function trainNetwork() {\n let trainData = inputGridToMatrix();\n NETWORK.train(trainData);\n}",
"train() {\n let output = new Object();\n if (this.dataPos > this.trainingData.length - 1) {\n return output;\n }\n let result = this.processData(this.trainingData[this.dataPos]);\n for(let i = 0; i < this.weights.length; i++){\n let error = this.expectedResults[this.dataPos] - result;\n console.log('Error: ' + error);\n console.log('Old weight: ' + this.weights[i]);\n this.weights[i] += error * this.trainingData[this.dataPos][i] * this.learningRate;\n console.log('training data value: ' + this.trainingData[this.dataPos][i]);\n console.log('New weight: ' + this.weights[i]);\n }\n \n output.x = this.trainingData[this.dataPos][0];\n output.y = this.trainingData[this.dataPos][1];\n output.success = result == this.expectedResults[this.dataPos];\n this.dataPos++;\n return output;\n }",
"train(input, target) {\r\n this.feedForward(input);\r\n this.backPropagation(input, target);\r\n }",
"function train(perceptron,trainData) {\n let label1 = convertLetterToNumber(perceptron.label1);\n let label2 = convertLetterToNumber(perceptron.label2);\n for (let index = 0 ; index < trainData.length ; index++){\n let yLabel = trainData[index][0];\n if(yLabel === label1 || yLabel === label2) {\n let isPassTrashold = prediction(perceptron, trainData[index]);\n let isLabel1 = (isPassTrashold && label1 === yLabel);\n let isLabel2 = (!isPassTrashold && label1 !== yLabel);\n if (!(isLabel1 || isLabel2)) {\n if (label1 === yLabel) {\n for (let i = 0, j = 1; i < trainData.length; i++ , j++) {\n perceptron.weights[i] += trainData[index][j];\n }\n } else {\n for (let i = 0, j = 1; i < trainData.length; i++ , j++) {\n perceptron.weights[i] -= trainData[index][j] ;\n }\n }\n }\n }\n }\n}",
"train(inputs, target){\n let guess = this.feedforward(inputs);\n let error = target - guess;\n \n for(let i = 0 ; i < this.weights.length; i++){\n this.weights[i] += error * inputs[i] * this.learning_rate;\n }\n \n }",
"function train() {\n const learningRate = 0.005;\n const optimizer = tf.train.sgd(learningRate);\n \n optimizer.minimize(function() {\n const predsYs = predict(tf.tensor1d(trainX));\n console.log(predsYs);\n stepLoss = loss(predsYs, tf.tensor1d(trainY));\n console.log(stepLoss.dataSync()[0]);\n return stepLoss;\n });\n plot();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to evaluate 'compareHtml' property instead of 'html' for DocumentFragments | evaluate(property, a, b) {
if (property === 'html' && typeof a.value !== 'string') {
// DocumentFragment, compare separately supplied html
return a.object.compareHtml === b.object.compareHtml;
}
} | [
"evaluate(property, a, b) {\n if (property === 'html' && typeof a.value !== 'string' && `compareHtml` in a.object) {\n // DocumentFragment, compare separately supplied html\n return a.object.compareHtml === b.object.compareHtml;\n }\n }",
"function samehtml(a,b) {\n\treturn (unhtml(a)==unhtml(b));\n}",
"function checkHtml(html1, html2){\n expect(html1).to.be.equal(html2); // just check if the two strings are equal\n}",
"function getDOMDiff(leftHTML, rightHTML, config = {}) {\r\n const leftTree = getAST(leftHTML);\r\n const rightTree = getAST(rightHTML);\r\n normalizeAST(leftTree, config.ignoredTags);\r\n normalizeAST(rightTree, config.ignoredTags);\r\n // parentNode causes a circular reference, so ignore them.\r\n const ignore = (path, key) => key === 'parentNode';\r\n const diffs = deepDiff(leftTree, rightTree, ignore);\r\n if (!diffs || !diffs.length) {\r\n return undefined;\r\n }\r\n return createDiffResult(leftTree, rightTree, diffs[0]);\r\n}",
"function compareElementsContent(firstElement, secondElement) {\n // Gets the contents\n var firstContent = $.trim($(firstElement).prop(\"innerHTML\"));\n var secondContent = $.trim($(secondElement).prop(\"innerHTML\"));\n return firstContent.localeCompare(secondContent);\n}",
"function assertHTMLEquals() {\n \n //Snegopat.\n JsUnit.error(\"assertHTMLEquals() не поддерживается в Снегопате.\");\n \n //JsUnit._validateArguments(2, arguments);\n //var var1 = JsUnit._nonCommentArg(1, 2, arguments);\n //var var2 = JsUnit._nonCommentArg(2, 2, arguments);\n //var var1Standardized = JsUnit.Util.standardizeHTML(var1);\n //var var2Standardized = JsUnit.Util.standardizeHTML(var2);\n\n //JsUnit._assert(JsUnit._commentArg(2, arguments), var1Standardized === var2Standardized, 'Expected ' + JsUnit._displayStringForValue(var1Standardized) + ' but was ' + JsUnit._displayStringForValue(var2Standardized));\n /////Snegopat.\n}",
"function assertHTMLEquals() {\r\n JsUnit._validateArguments(2, arguments);\r\n var var1 = JsUnit._nonCommentArg(1, 2, arguments);\r\n var var2 = JsUnit._nonCommentArg(2, 2, arguments);\r\n var var1Standardized = JsUnit.Util.standardizeHTML(var1);\r\n var var2Standardized = JsUnit.Util.standardizeHTML(var2);\r\n\r\n JsUnit._assert(JsUnit._commentArg(2, arguments), var1Standardized === var2Standardized, 'Expected ' + JsUnit._displayStringForValue(var1Standardized) + ' but was ' + JsUnit._displayStringForValue(var2Standardized));\r\n}",
"checkHtmlText() {\n this.innerHtmlText = null;\n if (startsWith(this.text, '<html>', true)) {\n const htmlText = this.text.trim();\n const s = htmlText.toLocaleLowerCase();\n if (s.indexOf('<body') === -1) {\n const s2 = s.indexOf('</html>');\n if (s2 >= 0)\n this.innerHtmlText = htmlText.substr(6, s2);\n }\n }\n }",
"function assertDOMEquals(leftHTML, rightHTML, config = {}) {\r\n const result = getDOMDiff(leftHTML, rightHTML, config);\r\n if (result) {\r\n throw new Error(`${result.message}, at path: ${result.path}`);\r\n }\r\n}",
"function diff1(prevKey, html2) {\n\t\tvar html1 = doTA.H[prevKey];\n\t\tvar prevPos1 = 0, pos1 = html1.indexOf('<');\n\t\tvar prevPos2 = 0, pos2 = html2.indexOf('<');\n\t\tvar tagId = '', elem, part1, part2;\n\t\tvar posx, endPosx;\n\n\t\tdo {\n\t\t\tif (html1[pos1] === \"<\") {\n\t\t\t\tpos1++;\n\t\t\t\tpos2++;\n\t\t\t\tif (html1[pos1] === \"/\" || html1[pos1] === \"!\") {\n\t\t\t\t\t//don't patch comment node and close tag.\n\t\t\t\t\tpos1 = html1.indexOf('>', pos1);\n\t\t\t\t\tpos2 = html2.indexOf('>', pos2);\n\t\t\t\t} else {\n\t\t\t\t\tprevPos1 = pos1;\n\t\t\t\t\tprevPos2 = pos2;\n\t\t\t\t\tpos1 = html1.indexOf('>', prevPos1);\n\t\t\t\t\tpos2 = html2.indexOf('>', prevPos2);\n\t\t\t\t\tpart1 = html1.substring(prevPos1, pos1);\n\t\t\t\t\tpart2 = html2.substring(prevPos2, pos2);\n\t\t\t\t\t//attributes\n\t\t\t\t\tif (part1 !== part2) {\n\t\t\t\t\t\t// console.log('openTag', [part1, part2])\n\t\t\t\t\t\ttagId = parsePatchAttr(part1, part2);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//record id\n\t\t\t\t\t\t//tagId = getTagId(part1);\n\t\t\t\t\t\tposx = part1.indexOf(' id=\"');\n\t\t\t\t\t\t0 <= posx && (posx += 5, endPosx = part1.indexOf('\"', posx), tagId = part1.substring(posx, endPosx)); //jshint ignore: line\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t//text node\n\t\t\t} else if (html1[pos1] === '>') {\n\t\t\t\tprevPos1 = ++pos1;\n\t\t\t\tprevPos2 = ++pos2;\n\n\t\t\t\tpos1 = html1.indexOf('<', prevPos1);\n\t\t\t\tpos2 = html2.indexOf('<', prevPos2);\n\t\t\t\t//textNode, only support firstChild here\n\t\t\t\tif (pos2 > prevPos2) {\n\t\t\t\t\tvar text1 = html1.substring(prevPos1, pos1);\n\t\t\t\t\tvar text2 = html2.substring(prevPos2, pos2);\n\t\t\t\t\tif (text1 !== text2) {\n\t\t\t\t\t\telem = document.getElementById(tagId);\n\t\t\t\t\t\tif (elem) {\n\t\t\t\t\t\t\tif (elem.firstChild && elem.firstChild.nodeType === 3) {\n\t\t\t\t\t\t\t\t// console.log('textApplied', [text1, text2]);\n\t\t\t\t\t\t\t\telem.firstChild.nodeValue = text2;\n\t\t\t\t\t\t\t} //else to log something?\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tconsole.log('tag not found', [tagId]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} while(pos1 > 0);\n\t}",
"function is_html_1(msg) {\n msg = msg.toLowerCase()\n let numhits = 0\n if(msg.indexOf('<html') != -1) numhits++\n if(msg.indexOf('</html>') != -1) numhits++\n if(msg.indexOf('<head ') != -1) numhits++\n if(msg.indexOf('</head>') != -1) numhits++\n if(msg.indexOf('<body') != -1) numhits++\n if(msg.indexOf('</body>') != -1) numhits++\n if(msg.indexOf('<pre') != -1) numhits++\n if(msg.indexOf('</pre>') != -1) numhits++\n if(msg.indexOf('<span>') != -1) numhits++\n if(msg.indexOf('</span>') != -1) numhits++\n if(msg.indexOf('<div>') != -1) numhits++\n if(msg.indexOf('</div>') != -1) numhits++\n\n return numhits > 2\n }",
"static isSameElement(a, b) {\n return Promise.all([\n a.getAttribute('outerHTML'),\n b.getAttribute('outerHTML')\n ]).then((results) => {\n return Promise.resolve(results[0] === results[1]);\n });\n }",
"function expectedHtml(htmlFile) {\n return new jsdom.JSDOM(htmlFile).window.document.body.outerHTML;\n}",
"sameMarkup(other) {\n return this.hasMarkup(other.type, other.attrs, other.marks);\n }",
"getHTML() {\n return getHTMLFromFragment(this.state.doc.content, this.schema);\n }",
"getHTML() {\r\n return getHTMLFromFragment(this.state.doc.content, this.schema);\r\n }",
"parseTable() {\n if (!this.data.types.includes('text/html') || !this.data.types.includes('text/plain')) {\n return false;\n }\n\n const htmlData = this.data.getData('text/html');\n this.doc = new DOMParser().parseFromString(htmlData, 'text/html');\n // Avoid formatting lines that were copied from a diff\n const tables = this.doc.querySelectorAll('table:not(.diff-wrap-lines)');\n\n // We're only looking for exactly one table. If there happens to be\n // multiple tables, it's possible an application copied data into\n // the clipboard that is not related to a simple table. It may also be\n // complicated converting multiple tables into Markdown.\n if (tables.length !== 1) {\n return false;\n }\n\n const text = this.data.getData('text/plain').trim();\n const splitRows = text.split(/[\\n\\u0085\\u2028\\u2029]|\\r\\n?/g);\n\n // Now check that the number of rows matches between HTML and text\n if (this.doc.querySelectorAll('tr').length !== splitRows.length) {\n return false;\n }\n\n this.rows = splitRows.map((row) => row.split('\\t'));\n this.normalizeRows();\n\n // Check that the max number of columns in the HTML matches the number of\n // columns in the text. GitHub, for example, copies a line number and the\n // line itself into the HTML data.\n if (!this.columnCountsMatch()) {\n return false;\n }\n\n return true;\n }",
"function assertGuestHtmlCorrect(frame, div, opt_containerDoc) {\n var containerDoc = opt_containerDoc || document;\n assertStringContains('static html', div.innerHTML);\n assertStringContains('edited html', div.innerHTML);\n assertStringContains('dynamic html', div.innerHTML);\n assertStringContains('external script', div.innerHTML);\n assertEquals('small-caps',\n containerDoc.defaultView.getComputedStyle(\n containerDoc.getElementById('foo-' + frame.idSuffix),\n null).fontVariant);\n assertEquals('inline',\n containerDoc.defaultView.getComputedStyle(\n containerDoc.getElementById('hello-' + frame.idSuffix),\n null).display);\n }",
"function assertGuestHtmlCorrect(frame, div) {\n assertStringContains('static html', div.innerHTML);\n assertStringContains('edited html', div.innerHTML);\n assertStringContains('dynamic html', div.innerHTML);\n if (inES5Mode) {\n assertStringContains('external script', div.innerHTML);\n }\n assertEquals('small-caps',\n document.defaultView.getComputedStyle(\n document.getElementById('foo-' + frame.idSuffix),\n null).fontVariant);\n if (inES5Mode) {\n assertEquals('inline',\n document.defaultView.getComputedStyle(\n document.getElementById('hello-' + frame.idSuffix),\n null).display);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle autocomplete for survey for "Location" with the searchText | handleSurveyLocAutoComplete(searchText) {
var surveyData = this.state.surveyData;
surveyData["location"] = searchText;
this.setState({ surveyData });
this.handleLocationAutoComplete(searchText);
} | [
"function initLocationAutoComplete(view) {\n\n\t// TODO: ignore punctuation in matching and consider both abbreviated and full state names\n\n\t// TODO: automatically select first item in list on enter pressed if nothing highlighted using arrow keys\n\n\t// create autocomplete instance on search field\n\tview.$search.autocomplete({\n\t\tminLength: 3,\n\t\tselect: function(evt, ui) {\n\t\t\tvar itm = ui.item;\n\t\t\t$('input[name=\"lat\"]', view.$el).val(itm.lat);\n\t\t\t$('input[name=\"lng\"]', view.$el).val(itm.lng);\n\t\t\tview.currLocationLabel = itm.label;\n\t\t\tview.$form.submit();\n\t\t},\n\t\tsource: []\n\t});\n}",
"function searchAutoComplete() {\n if(self.selectedChoice() == 'name') {\n autoCompleteSource(nameArr);\n } else {\n autoCompleteSource(addrArr);\n }\n}",
"function setupLocationAutocomplete() {\n\n if (!window.google) {\n // Google Places API not loaded\n return;\n }\n\n var form = $(\"#change-location-form\");\n\n var input = form.find('[name=\"place\"]');\n if (!input.length) {\n return;\n }\n var autocomplete = createPlaceAutocompleteSelectFirst(input[0]);\n\n input.tooltip();\n\n input.keypress(function(event) {\n return event.keyCode !== 13;\n });\n\n // When user selects an entry in the list kick in the magic\n google.maps.event.addListener(autocomplete, 'place_changed', function() {\n var place = autocomplete.getPlace();\n if (!place.geometry) {\n return;\n }\n\n var address = window.splitLocation(place);\n\n // Pure country code lookup, quick jump to country listing\n if (address.countryCode && !address.city && !address.streetAddress) {\n\n // Store the location for the server-side processing\n storeLocation(address);\n window.location = \"/country/\" + address.countryCode.toUpperCase();\n return;\n }\n\n if (window.customLocationGoToHandler) {\n window.customLocationGoToHandler(place, address);\n return;\n }\n\n submitChangeLocation(address);\n });\n }",
"handleFormLocAutoComplete(searchText) {\r\n this.setState({location: searchText});\r\n this.handleLocationAutoComplete(searchText);\r\n this.handleLocationAutoCompleteSelect(searchText);\r\n }",
"function searchForLocation(){\n searchManager.geoCode({\n\t\tsearchTerm: document.getElementById('txtSearchField').value,\n\t\tonComplete: processSearchResults\n\t});\n hideSearch();\n}",
"function autoSuggestSearch (searchbox){ \n showSuggestSearchList(searchbox); \n}",
"function parseLocationResults() {\n\tthis.$search.autocomplete('option', 'source', this.locations.map(function(loc) {\n\t\treturn {\n\t\t\tlabel: loc.get('city') + ', ' + l(loc.get('state')) + ' ' + loc.get('postal'),\n\t\t\tcity: loc.get('city'),\n\t\t\tstate: loc.get('state'),\n\t\t\tzip: loc.get('postal'),\n\t\t\tlat: loc.get('latitude'),\n\t\t\tlng: loc.get('longitude')\n\t\t};\n\t}));\n\tthis.$search.removeClass('loading');\t\n\t\n\t// hack to force open autocomplete list when locations are ready. from https://community.oracle.com/thread/2451338\n\t//preserve the minLength option\n\tvar lMinLength = this.$search.autocomplete(\"option\",\"minLength\");\n\t//set minLength to 0 so a search can trigger\n\tthis.$search.autocomplete(\"option\",\"minLength\", 0); \n\tthis.$search.autocomplete(\"search\",'');\n\t//reset the minlength option\n\tthis.$search.autocomplete(\"option\",\"minLength\", lMinLength);\n}",
"function autocomplete()\n{\n\tvar locationInformation = collectDetailsAboutTheCurrentSelection();\n\t//showObject(locationInformation);\n\n\t// If first in a line, complete unfinished environment.\n\tif(locationInformation.firstPlaceInLine)\n\t{\n\t\tcloseEnvironment(locationInformation.unclosedEnvironment);\n\t\treturn;\n\t}\n\n\t// If in primary argument to input, include, includegraphics or similar, \n\t// complete filename.\n\tif(shouldCompleteFilename(locationInformation.commandName)) {\n\t\tvar words = locateMatchingFilenames(locationInformation.extractedWord);\n\t} else if(locationInformation.wordToComplete.length == 0) {\n\t\t\treturn;\n\t} else if (locationInformation.isCommandName) {\n\t\tvar words = locateMatchingCommandNames(locationInformation.extractedWord);\n\t} else {\n\t\tvar words = locateMatchingWordsAwareOfContext(locationInformation.commandName, locationInformation.extractedWord);\n\t}\n\t\n\t// Sort the found matches to avoid problems when the ordering is changed \n\t// due to the current suggested completion.\n\twords = words.sort();\n\n\tinsertSuggestion(words, locationInformation);\n}",
"function doSearchWith(location) {\n state = 1;\n locations = [];\n errorMessage = '';\n searchTerm = location;\n\n $$('#search-text').val(searchTerm);\n\n doSearchByTerm();\n }",
"function getYelpLocations() {\n $.ajax({\n url: 'http://vncling.github.io/Projects/cities.json',\n dataType: 'json',\n success: function(data) {\n yelpLocations = data;\n for(var i = 0; i < 171; i++) {\n var readableName = data.divisions[i].name;\n yelpReadableNames.push(readableName);\n }\n\t\t\n $('#autocomplete').autocomplete({\n lookup: yelpReadableNames,\n showNoSuggestionNotice: true,\n noSuggestionNotice: 'Sorry, no matching results',\n onSelect: function (suggestion) {\n self.searchLocation(suggestion.value);\n }\n });\n },\n error: function() {\n self.dealStatus('Oops, something went wrong, please reload the page and try again.');\n self.loadImg('');\n }\n });\n\t\n }",
"function autocomplete() {\n\n // Autocomplete for search location\n let autocompleteSearch = $(\"#search-location\")[0];\n var autocompletedSearch = new google.maps.places.Autocomplete(autocompleteSearch);\n\n}",
"function autocomplete()\n{\n\tvar locationInformation = collectDetailsAboutTheCurrentSelection();\n\t//showObject(locationInformation);\n\n\t// If first in a line, complete unfinished environment.\n\tif(locationInformation.firstPlaceInLine)\n\t{\n\t\tstack = locationInformation.environmentStack;\n\t\tif(stack.length > 0)\n\t\t{\n\t\t\tcloseEnvironment(stack[stack.length-1]);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif(suggestCommandOrEnvironment(locationInformation))\n\t{\n\t\treturn;\n\t}\n\n\t// Suggest labels to section and subsection\n\tif(addLabelBelow(locationInformation))\n\t{\n\t\treturn;\n\t}\n\n\t// If in primary argument to input, include, includegraphics or similar, \n\t// complete filename.\n\tvar words;\n\tif(shouldCompleteFilename(locationInformation.commandName)) {\n\t\twords = locateMatchingFilenames(locationInformation.extractedWord);\n\t} else if (locationInformation.isCommandName) {\n\t\twords = locateMatchingCommandNames(locationInformation.extractedWord);\n\t} else if(locationInformation.wordToComplete.length === 0) {\n\t\treturn;\n\t} else {\n\t\twords = locateMatchingWordsAwareOfContext(locationInformation.commandName, locationInformation.extractedWord);\n\t}\n\n\tif(words.length == 0)\n\t{\n\t\tsuggestCommandOrEnvironment(locationInformation);\n\t\treturn;\n\t}\n\n\t// Sort the found matches to avoid problems when the ordering is changed \n\t// due to the current suggested completion.\n\twords = words.sort();\n\n\tinsertSuggestion(words, locationInformation);\n}",
"onSuggestSelect({ label, location }) {\n this.props.onSuggest(label, location);\n this._geoSuggest.clear();\n }",
"function searchSelectCity() {\n\tvar restrictionSet = {\n\t\ttypes: [\"(cities)\"],\n\t};\n\n\tvar typeCity = document.getElementById(\"locationName\");\n\tvar autocomplete = new google.maps.places.Autocomplete(\n\t\ttypeCity,\n\t\trestrictionSet\n\t);\n\tvar updateLatLng;\n\n\t\n\tgoogle.maps.event.addListener(autocomplete, \"place_changed\", function () {\n\t\tplace = autocomplete.getPlace();\n\t});\n\n\t// when submit button is clicked - the map center is changed to the new location\n\n\tsearchForm.addEventListener(\"submit\", function (event) {\n\t\tevent.preventDefault();\n\t\tif (place !== \"\") {\n\t\t\tupdateLatLng = new google.maps.LatLng(\n\t\t\t\tplace.geometry.location.lat(),\n\t\t\t\tplace.geometry.location.lng()\n\t\t\t);\n\t\t\tmap.setZoom(13);\n\t\t\tcenter = updateLatLng;\n\t\t\tmap.setCenter(center);\n\t\t\tdocument.getElementById(\"textLocation\").innerHTML = place.adr_address;\n\t\t} else {\n\t\t\talert(\"Please enter location\");\n\t\t}\n\t});\n}",
"autosuggest() {}",
"function searchVenue(){\n\t\t$(\"#query\").click(function(){\n\t\t\t$(this).val(\"\");\n\t\t});\n\n\t\t$(\"#query\").blur(function(){\n\t\t\tif ($(this).val() == \"\") {\n\t\t\t\t$(this).val(\"Example: Ninja Japanese Restaurant\");\n\t\t\t}\n\t\t\n\t\t\tif ($(this).val() != \"Example: Ninja Japanese Restaurant\") {\n\t\t\t\t$(this).addClass(\"focus\");\n\t\t\t} else {\n\t\t\t\t$(this).removeClass(\"focus\");\n\t\t\t}\n\t\t});\n\n\t\t//Submit search query and call to getVenues\n\t\t$(\"#searchform\").submit(function(event){\n\t\t\tevent.preventDefault();\n\t\t\tif (!lat) {\n\t\t\t\tnavigator.geolocation.getCurrentPosition(getLocation);\n\t\t\t} else {\n\t\t\t\tgetVenues();\n\t\t\t}\t\t\n\t\t});\n\n\t}",
"function initLocationSearchField(view) {\n\n\tview.$search = $('.location input', view.$el);\n\n\t// remember original text to be able to conditionally style input \n\tview._origSearchPrompt = view.$search.val();\n\n\t// restore location text if previously set\n\tif(view.currLocationLabel) {\n\t\tview.$search.val(view.currLocationLabel);\n\t}\n\n\t// handle search field gain focus\n\tview.$search.focus(function() {\n\t\t// remove original search prompt on focus\n\t\tif(this.value === view._origSearchPrompt) {\n\t\t\tthis.value = \"\";\n\t\t\tstyleLocationSearchInput(view);\n\t\t}\n\n\t\thideInvalidLocationMessage(view);\n\n\t\t// TODO: Fix having to tap on search field twice on iPhones (and other mobiles?)\n\n\t});\n\n\t// handle search field lose focus\n\tview.$search.blur(function() {\n\n\t\t// restore any current location to search field on blur\n\t\tview.$search.val(view.currLocationLabel);\n\n\t\t// restore original prompt if field is empty\n\t\tif(this.value.replace(/\\s/g, '') === \"\") {\n\t\t\tthis.value = view._origSearchPrompt;\n\t\t}\n\t\tstyleLocationSearchInput(view);\n\n\t});\n\n\tinitLocationAutoComplete(view);\n\tinitLocationKeyup(view);\n\n\tstyleLocationSearchInput(view);\n\n}",
"function autoComplete() {\r\n search = document.createElement(\"input\");\r\n search.id = \"locationField\";\r\n var auto = new google.maps.places.Autocomplete(search);\r\n result.appendChild(search);\r\n //Check for manually input location and display map\r\n google.maps.event.addListener(auto, 'place_changed',\r\n function () {\r\n var place = auto.getPlace();\r\n var lat = place.geometry.location.lat();\r\n var long = place.geometry.location.lng();\r\n getPostcode(lat, long);\r\n }\r\n );\r\n }",
"function mapSearch() {\n\tvar test = app.map_search.split(\",\");\n\tif (test.length > 1 && isNaN(test[0]) == false && isNaN(test[1]) == false) {\n\t\tchangeCenter();\n\t} else {\n\t\tvar settings = {\n\t\t\t\"async\": true,\n\t\t\t\"crossDomain\": true,\n\t\t\t\"url\": \"https://api.locationiq.com/v1/autocomplete.php?key=960b659c86dc12&q=\" + app.map_search,\n\t\t\t\"method\": \"GET\"\n\t\t}\n\n\t\t$.ajax(settings).done(function (response) {\n\t\t\t//console.log(response);\n\t\t\tmyMap.setView([response[0].lat, response[0].lon], 7);\n\t\t\trequestUpdate(); // table update after search of location \n\t\t});\n\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Programa que calcula si un numero es par o impar y muestra el resultado en consola. function calculaQueES | function calculaQueES(num) {
return num % 2
} | [
"function esPar(numerito) { \n //Si se hace una division para dos se recibe un entero o decimal\n if (numerito % 2 === 0) { //=== 0 quiere decir que no da reciduo\n return true;\n } else {\n return false;\n }\n}",
"function numPrimos()\n\t{\n\t\tvar valor=parseInt(document.getElementById(\"valor\").value); //aca convierto la cadena de caracteres en num entero y tomo su valor, el ingresado\n\t\tvar NumeroPrimo=true; //aca defino que numrpimo es true, para que despues con el for se corte el bucle.\n \n\t\tfor(i=1;i<valor;i++)\n\t\t{\n\t\t\tif(valor/i == Math.round(valor/i) && i!=1 && i!=valor) // para saber si es primo o no y redondeo\n\t\t\t{\n\t\t\t\tNumeroPrimo=false; //aca hago break para que si no es primo se termine el bucle.\n\t\t\t\tbreak;\n\t\t\t};\n\t\t};\n \n\t\tif(NumeroPrimo){\n\t\t\tdocument.getElementById(\"resultado\").innerHTML=\"El numero ingresado es \"+valor+\" y es Primo\";\n }else{\n\t\t\tdocument.getElementById(\"resultado\").innerHTML=\"El numero ingresado es \"+valor+\" y no es Primo\";\n }\n}",
"function somaPrimos (num) {\n let soma = [];\n for (i=0; i <= num; i++) {\n if(ePrimo(i)) soma.push(i); \n }\n soma.forEach(\n (a) => res += parseFloat(a)\n )\n return res\n}",
"function agregaNumerosArreglo(cadenaNumeros){//Recibe nuestra cadena de numeros\n let contador = 0;\n let par_num = \"\";\n let longuitud_cadena = 0;\n const lengthC = cadenaNumeros.length;//longuitud de nuestra cadena recibida\n \n for (let numero of cadenaNumeros) {//recorremos nuestro mensaje \n if(contador === 2){//si mi contador es === 2 ya tenemos un par de numeros asi que lo agregamos a nuestro arreglo\n contador = 1;//inicializamos el contador en 1 porque si no se salta 1 numero\n arr_numeros.push(par_num);//agregamos el par de numeros que tenemos a nuestro arreglo\n par_num = \"\" + numero; //le damos a nuestra variable el valor de la letra actual \n longuitud_cadena ++;\n }else{//contador menor a 2\n longuitud_cadena++\n par_num = par_num + numero;//concatenamos lo que tenemos en par_num con nuestro numero actual\n contador++;\n //para evitar que no agregue el ultimo par de numeros nos apoyamos de longuitud_cadena\n //al final de todo el recorrido tendremos longuitudes iguales por lo que el ultimo numero se agregara\n if (longuitud_cadena === lengthC) {\n arr_numeros.push(par_num);\n }\n }\n }\n \n return arr_numeros;//regresamso nuestro arreglo de numeros\n}",
"function somaPrimos(num) {\n return 0\n}",
"function censura(paroleProibite, testoSostitutivo, testoIniziale) {\n var contatoreCensurate = 0;\n for (var i = 0; i < paroleProibite.length; i++) {\n while (esisteRegolareOConPrimaMaiuscolaMinuscola(paroleProibite[i], testoIniziale)) {\n\n var tuttaMinuscola = paroleProibite[i].toLowerCase();\n var conPrimaMaiuscola = conPrimaLetteraMaiuscola(paroleProibite[i]);\n\n //Processerà in tutte le sue occorrenze prima solo...\n if (testoIniziale.includes(paroleProibite[i])) {//la parola regolare\n testoIniziale = testoIniziale.replace(paroleProibite[i], testoSostitutivo);\n } else if (testoIniziale.includes(tuttaMinuscola)) {//la parola minuscola\n testoIniziale = testoIniziale.replace(tuttaMinuscola, testoSostitutivo);\n } else if (testoIniziale.includes(conPrimaMaiuscola)) {//la parola con prima lettera Maiuscola\n testoIniziale = testoIniziale.replace(conPrimaMaiuscola, testoSostitutivo);\n }\n\n //..un ciclo alla volta incrementando il contatore\n contatoreCensurate = contatoreCensurate + 1;\n }\n }\n\n document.writeln('<br>Parole censurate totali: ' + contatoreCensurate + '<br>Il testo censurato è:<br>' + testoIniziale);\n console.log('testo censurato ok\\nParole censurate ' + contatoreCensurate);\n return testoIniziale;\n}",
"function adivinarSexoEstudiante(estudiantes) {\n //valor que se utilizará para comparar\n var resultado = 100000;\n //tupla que almacenará la posición más cercana \n var numeroTupla = 0;\n //for que recorre todos los datos como parámetro de la consulta \n //de la tabla de estudiantes\n for (var i = 0; i < estudiantes.length; i++) {\n var recintoTupla = 1;\n var estiloTupla = 0;\n \n \n //se le da valor a los recintos que pertenecen las personas en las\n //tuplas si es paraíso es 1 y turrialba es 2 \n if (estudiantes[i].recinto === 'Turrialba') {\n recintoTupla = 2;\n }\n //se elige el estilo de aprendizaje y se le asigna un valor\n //de 1 a 4\n switch (estudiantes[i].estilo) {\n case 'DIVERGENTE':\n estiloTupla = 1;\n break;\n case 'CONVERGENTE':\n estiloTupla = 2;\n break;\n case 'ASIMILADOR':\n estiloTupla = 3;\n break;\n case 'ACOMODADOR':\n estiloTupla = 4;\n break;\n }\n \n //distancia euclidiana aplicada a los valores de las tuplas para definir distancia\n var sumatoria = Math.pow((estiloTupla - (parseInt(document.getElementById('estilo').value))), 2) + Math.pow(recintoTupla - (parseInt(document.getElementById('recinto').value)), 2) + Math.pow((parseFloat(estudiantes[i].promedio)) - (parseFloat(document.getElementById('promedio').value)), 2);\n var distancia = Math.sqrt(sumatoria);\n \n //aquí comparan para mostrar el más cercano al que entra como parámetro\n //comparando los datos de la tupla y los ingresados\n if (resultado > distancia) {\n resultado = distancia;\n numeroTupla = i;\n } \n }\n \n //if para mostrar el sexo en la pantalla dependiendo de la tupla\n if(estudiantes[numeroTupla].sexo === 'M')\n document.getElementById('mensaje3').innerHTML = 'Su sexo es: Masculino y el número de tupla es: '+estudiantes[numeroTupla].id+'.';\n else\n document.getElementById('mensaje3').innerHTML = 'Su sexo es: Femenino y el número de tupla es: '+estudiantes[numeroTupla].id+'.';\n}",
"function calcularEscolha(jogador, computador) {\n if (jogador == 1 && computador == 1) {\n return 0;\n }\n else if (jogador == 1 && computador == 2) {\n return 2;\n } \n else if (jogador == 1 && computador == 3) {\n return 1;\n } \n else if (jogador == 2 && computador == 1) {\n return 1;\n } \n else if (jogador == 2 && computador == 2) {\n return 0;\n } \n else if (jogador == 2 && computador == 3) {\n return 2;\n } \n else if (jogador == 3 && computador == 1) {\n return 2;\n } \n else if (jogador == 3 && computador == 2) {\n return 1;\n } \n else if (jogador == 3 && computador == 3) {\n return 0;\n }\n\n}",
"emirps(n, option) {\n // Good luck!\n console.log(option);\n let primes = new Set();\n let emirps = [];\n let count = 0;\n let number = 11;\n if (typeof n == \"number\") {\n while (count < n) {\n let emirp = parseInt(\n number\n .toString()\n .split(\"\")\n .reverse()\n .join(\"\")\n );\n if (emirp !== number && isPrime(emirp) && isPrime(number)) {\n emirps.push(number);\n count++;\n }\n number += 2;\n }\n } else {\n number = n[0] % 2 == 0 ? n[0] + 1 : n[0];\n n = n[1];\n\n while (number < n) {\n let emirp = parseInt(\n number\n .toString()\n .split(\"\")\n .reverse()\n .join(\"\")\n );\n if (emirp !== number && isPrime(emirp) && isPrime(number)) {\n emirps.push(number);\n count++;\n }\n number += 2;\n }\n }\n\n if (option === undefined) {\n return number - 2;\n }\n if (option) {\n return emirps;\n } else {\n return count;\n }\n function isPrime(number) {\n if (primes.has(number)) return true;\n let root = Math.ceil(Math.sqrt(number));\n for (let i = 2; i <= root; i++) {\n if (number % i === 0) {\n return false;\n }\n }\n primes.add(number);\n\n return true;\n }\n }",
"function calcularEscolha(jogador, computador) {\n if (jogador == computador) {\n return 0\n }\n\n if (jogador == 1 && computador == 2) {\n return 2\n }\n\n if (jogador == 1 && computador == 3) {\n return 1\n }\n\n if (jogador == 2 && computador == 1) {\n return 1\n }\n\n if (jogador == 2 && computador == 3) {\n return 2\n }\n\n if (jogador == 3 && computador == 1) {\n return 2\n }\n\n if (jogador == 3 && computador == 1) {\n return 1\n }\n}",
"function calcularEscolha(jogador, computador){\n//pedra\nif(jogador==1 && computador==1){ return 0; }\nelse if (jogador==1 && computador==2) { return 2; }\nelse if (jogador==1 && computador==3) { return 1; }\n//papel\nelse if (jogador==2 && computador==1) { return 1; }\nelse if (jogador==2 && computador==2) { return 0; }\nelse if (jogador==2 && computador==3) { return 2; }\n//tesoura\nelse if (jogador==3 && computador==1) { return 2; }\nelse if (jogador==3 && computador==2) {\treturn 1; }\nelse if (jogador==3 && computador==3) { return 0; }\n}",
"function peorVendedorMes(mes) {\n let ventaMes = 999999999999;\n let vendedor = \"\";\n let semanaMax = mes * 4 - 1; //Por ejemplo, el mes 1 seria el intervalo de semanas de 0 a 3.\n let semanaMin = semanaMax - 3;\n let ventaSubtotal = 0;\n for (let i = semanaMin; i < semanaMax; i++) {\n ventaSubtotal += vendedor1[i];\n }\n if (ventaSubtotal < ventaMes) {\n ventaMes = ventaSubtotal;\n vendedor = vendedores[0];\n }\n ventaSubtotal = 0;\n for (let i = semanaMin; i < semanaMax; i++) {\n ventaSubtotal += vendedor2[i];\n }\n if (ventaSubtotal < ventaMes) {\n ventaMes = ventaSubtotal;\n vendedor = vendedores[1];\n }\n ventaSubtotal = 0;\n for (let i = semanaMin; i < semanaMax; i++) {\n ventaSubtotal += vendedor3[i];\n }\n if (ventaSubtotal < ventaMes) {\n ventaMes = ventaSubtotal;\n vendedor = vendedores[2];\n }\n ventaSubtotal = 0; for (let i = semanaMin; i < semanaMax; i++) {\n ventaSubtotal += vendedor4[i];\n }\n if (ventaSubtotal < ventaMes) {\n ventaMes = ventaSubtotal;\n vendedor = vendedores[3];\n }\n ventaSubtotal = 0;\n for (let i = semanaMin; i < semanaMax; i++) {\n ventaSubtotal += vendedor5[i];\n }\n if (ventaSubtotal < ventaMes) {\n ventaMes = ventaSubtotal;\n vendedor = vendedores[4];\n }\n console.log(\"El peor vendedor del mes\", mes, \"es\", vendedor, \" con\", ventaMes);\n}",
"function exe9(){\n var numero = Number(prompt(\"Informe um número\"))\n var soma = 0\n for (var i = numero; i >= 1; i--){ // é i -- pq vai diminuindo\n if (numero % i == 0){\n soma = soma + i //soma dos divisores\n }\n }\n console.log(`Soma dos divisores é ${soma}`)\n}",
"function fatorial(numero) {\n return 0\n}",
"function C2E3() {\n let limite = 10;\n let LimiteDeNumerosPares = 6;\n let MultiplosDeTres = 0;\n let NumerosPares = 0;\n let SumaNumeros = 0;\n\n let i = 0;\n while (i <= limite || NumerosPares > LimiteDeNumerosPares) {\n i++\n SumaNumeros = SumaNumeros + i\n if (i % 3 == 0) {\n MultiplosDeTres++\n }\n if (i % 2 == 0) {\n NumerosPares++\n }\n\n }\n\n console.log(`La suma de los numeros: ${SumaNumeros}`);\n console.log(`Los multiplos de tres: ${MultiplosDeTres}`);\n}",
"function calcularPromedio() {\n const notas = [];\n let suma = 0;\n const notaParcial1 = prompt('Ingrese nota del primer parcial');\n const notaParcial2 = prompt('Ingrese nota del segundo parcial');\n const notaProyectoFinal = prompt('Ingrese nota del proyecto final');\n\n notas.push(notaParcial1);\n notas.push(notaParcial2);\n notas.push(notaProyectoFinal);\n\n for (let indice = 0; indice < notas.length; indice++) {\n // const element = notas[indice];\n suma = suma + parseInt(notas[indice]);\n }\n\n const promedio = suma / notas.length;\n\n if (promedio >= 6) {\n console.log('Aprobó la materia');\n } else {\n console.log('Desaprobó la materia 😣');\n }\n\n console.log(notas);\n\n}",
"function verificarMultiplo100(eleccion) {\n if (eleccion % 100 === 0) {\n //Continua sin problemas\n return true;\n } else {\n alert('Solo puede extraer billetes de $100.');\n return false;\n };\n}",
"function main(payasos, munecas)\n{\n let pesoT=pesoPaquete(payasos,munecas);\n let numPaquetes=(pesoPaquete(payasos,munecas))/1000;\n if((numPaquetes*1000)%1000 !=0)\n {\n numPaquetes=parseInt(numPaquetes)+1;\n }\n console.log(numPaquetes);\n console.log(pesoT/1000);\n}",
"async retorna_notas(valor_saque) \n {\n var soma_notas = 0;\n var array_notas = [];\n const notas = await this.getNotas();\n\n var notasOrdenadas = notas.sort((a, b) => {\n return b - a\n });\n\n if(notasOrdenadas.includes(valor_saque)) {\n soma_notas = valor_saque;\n array_notas[array_notas.length] = valor_saque;\n \n return [{ notas: array_notas, operacao: true }];\n } \n else {\n notasOrdenadas.forEach(function(nota, i) {\n var continuaLaco = true;\n while(continuaLaco) {\n if(nota <= valor_saque) {\n soma_notas = soma_notas + nota;\n valor_saque = valor_saque - nota;\n array_notas[array_notas.length] = nota;\n continuaLaco = true;\n } \n else {\n continuaLaco = false;\n }\n }\n });\n\n if(valor_saque == 0) {\n return [{ notas: array_notas, operacao: true }];\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
if this.state.month is 1 then year 1 and this month change 12 | prevMonth() {
let month = this.state.month;
let year = this.state.year;
if (month === 1) {
month = 12;
year = year - 1;
}
else
month -= 1;
this.setState({
year: year,
month: month
})
} | [
"_decreaseMonthYear() {\n let newMonth;\n let newYear;\n if (this.state.month === 0) {\n newMonth = 11;\n newYear = this.state.year - 1;\n } else {\n newMonth = this.state.month - 1;\n newYear = this.state.year;\n }\n\n this.setState({\n month: newMonth,\n year: newYear,\n focusedDateKey: undefined,\n lastHoveredDay: undefined,\n });\n if (this.props.onMonthUpdate) {\n this.props.onMonthUpdate(newMonth + 1, newYear);\n }\n }",
"_increaseMonthYear() {\n let newMonth;\n let newYear;\n if (this.state.month === 11) {\n newMonth = 0;\n newYear = this.state.year + 1;\n } else {\n newMonth = this.state.month + 1;\n newYear = this.state.year;\n }\n\n this.setState({\n month: newMonth,\n year: newYear,\n focusedDateKey: undefined,\n lastHoveredDay: undefined,\n });\n if (this.props.onMonthUpdate) {\n this.props.onMonthUpdate(newMonth + 1, newYear);\n }\n }",
"incrementMonth() {\n if(parseInt(this.state.currMonth, 10) < 12) {\n this.setState({ currMonth: String(parseInt(this.state.currMonth, 10)+1) });\n // Special case: increment to next year\n } else {\n this.setState({\n currMonth: String(1), \n currYear: String(parseInt(this.state.currYear, 10)+1)\n });\n }\n }",
"setMonth(month) {\n let newDate = new Date(this.state.year, this.state.month, this.state.day);\n newDate.setDate(1);\n newDate.setMonth(month);\n this.setState(\n {\n dow: newDate.getDay(),\n day: newDate.getDate(),\n month: newDate.getMonth()\n }\n );\n }",
"resetMonth() {\n this.year = this.today.getFullYear()\n this.month = this.today.getMonth() + 1\n return this.getMonth()\n }",
"onMonthChange(yearMonth) {\n\n this.setState({yearMonth: yearMonth}, this.reload)\n\n }",
"function checkMonth() {\n if (CUR_MONTH < 1) {\n CUR_MONTH = 12;\n CUR_YEAR -= 1;\n } else if (CUR_MONTH > 12) {\n CUR_MONTH = 1;\n CUR_YEAR += 1;\n }\n}",
"function setDate(){\r\n if (day > monthDays[month]) {\r\n day = day % monthDays[month];\r\n if (month == 11) {\r\n month = 0;\r\n year++;\r\n }\r\n else month++;\r\n }\r\n}",
"function updateMonth() {\n updateCal(30);\n}",
"function update(month,year) {\n currentMonth = month;\n currentYear = year;\n}",
"setMonth(month) {\n return new CandyDate(Object(date_fns__WEBPACK_IMPORTED_MODULE_0__[\"setMonth\"])(this.nativeDate, month));\n }",
"decrementMonth() {\n if(parseInt(this.state.currMonth, 10) > 1) {\n this.setState({ currMonth: String(parseInt(this.state.currMonth, 10)-1) });\n // Special case: decrement to previous year\n } else {\n this.setState({\n currMonth: String(12), \n currYear: String(parseInt(this.state.currYear, 10)-1)\n });\n }\n }",
"function incrementCurrentMonth() {\n if(currentMonth === 11) { incrementCurrentYear(); currentMonth = 0; }\n else { currentMonth++; }\n }",
"gotoMonth(month) {\n if (!isNaN(month)) {\n this.calendars[0].month = parseInt(month, 10);\n this.adjustCalendars();\n }\n }",
"updateDateStrings() {\n this.setState({\n currMonth: String((this.state.date).getMonth()+1),\n currYear: String(this.state.date.getFullYear())\n });\n }",
"function setYearInterval() {\n if (month === 0) {\n month = 12;\n year -= 1;\n }\n else if (month === 13) {\n month = 1;\n year += 1;\n }\n}",
"function onMonthChange(ev){\n setMonth(ev.target.value);\n }",
"function next_month(){\r\n if (current_month==\"December\"){\r\n current_month=\"January\";\r\n current_year=(parseInt(current_year)+1).toString();\r\n }\r\n else{\r\n current_month=list_of_months[list_of_months.indexOf(current_month)+1];\r\n }\r\n set_days();\r\n }",
"_setInfo() {\n let { year: currentYear, month: currentMonth } = this.currentMonthInfo; \n \n this.prevMonthInfo = { \n year: currentMonth == 0 ? currentYear - 1 : currentYear,\n month: currentMonth == 0 ? 11 : currentMonth - 1,\n day: null\n };\n \n this.nextMonthInfo = {\n year: currentMonth == 11 ? currentYear + 1 : currentYear,\n month: currentMonth == 11 ? 0 : currentMonth + 1,\n day: null\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test Matrix3.mul() with identity matrix | testMulIdentity() {
console.info("Test: Matrix3.mul() -- Identity matrix")
const firstMatrix = [
1, 4, 8,
6, 4, 2,
7, 8, 0,
]
const secondMatrix = [
1, 0, 0,
0, 1, 0,
0, 0, 1,
]
const expected = [
1, 4, 8,
6, 4, 2,
7, 8, 0,
]
const m = new Matrix3(firstMatrix)
m.mul(secondMatrix)
const actual = m.items
this.assertIdentical(actual, expected)
} | [
"testMul() {\n console.info('test Matrix3.mul()')\n const a = [\n 1,1,1,\n 1,1,1,\n 1,1,1,\n ]\n const b = [\n 2,2,2,\n 2,2,2,\n 2,2,2,\n ]\n const expected = [\n 6,6,6,\n 6,6,6,\n 6,6,6,\n ]\n const m = new Matrix3(a)\n m.multiplyM3(b)\n const actual = m.items\n this.assertIdentical(actual, expected)\n }",
"testMulIdentity() {\n console.info('test Matrix2.mul() by identity matrix')\n const firstMatrix = [\n 1, 2,\n 3, 4,\n ]\n const i = [\n 1, 0,\n 0, 1,\n ]\n const expected = [\n 1, 2,\n 3, 4,\n ]\n const m = new Matrix2(firstMatrix)\n m.mul(i)\n const actual = m.elements\n this.assertIdentical(actual, expected)\n }",
"testMulIdentity() {\n console.info('test Matrix4.mul() by identity matrix')\n const a = [\n 1, 2, 3, 4, \n 5, 6, 7, 8,\n 9, 10, 11, 12,\n 13, 14, 15, 16\n ]\n const i = [\n 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n 0, 0, 0, 1,\n ]\n const expected = a\n const m = new Matrix4(a)\n m.mul(i)\n const actual = m.elements\n this.assertIdentical(actual, expected)\n }",
"testMulIdentity() {\r\n console.info('test Matrix4.mul() by identity matrix')\r\n const a = [\r\n 1, 2, 3, 4, \r\n 5, 6, 7, 8,\r\n 9, 10, 11, 12,\r\n 13, 14, 15, 16,\r\n ]\r\n const i = [\r\n 1, 0, 0, 0,\r\n 0, 1, 0, 0,\r\n 0, 0, 1, 0,\r\n 0, 0, 0, 1,\r\n ]\r\n const expected = [\r\n 1, 2, 3, 4, \r\n 5, 6, 7, 8,\r\n 9, 10, 11, 12,\r\n 13, 14, 15, 16,\r\n ]\r\n const m = new Matrix4(a)\r\n m.mul(i)\r\n const actual = m.elements\r\n this.assertIdentical(actual, expected)\r\n }",
"testMul() {\n console.info('test Matrix2.mul()')\n const a = [\n 1, 1,\n 4, 3,\n ]\n const b = [\n 1, 6,\n 2, 2,\n ]\n const expected = [\n 3, 8,\n 10, 30,\n ]\n const m = new Matrix2(a)\n m.multiplyM2(b)\n const actual = m.items\n this.assertIdentical(actual, expected)\n }",
"multiplyMatrixBySingle(m) {\n const res = new Matrix();\n\n res.setSize(this.getRows(), this.getColumns());\n\n let i, j;\n\n for (i=0;i<this.getRows();i++) {\n for (j=0;j<this.getColumns();j++) {\n res.setValue(i, j, this.getValue(i, j) * m);\n }\n }\n\n return res;\n }",
"mul(b)\n\t{\n\t\tif(b instanceof Matrix4) //A\n\t\t{\n\t\t\tvar val = this.val;\n\t\t\tb = b.val;\n\t\t\t\n\t\t\t__mjs_tmpMat1.val[M00] = val[M00] * b[M00] + val[M01] * b[M10] + val[M02] * b[M20] + val[M03] * b[M30];\n\t\t\t__mjs_tmpMat1.val[M01] = val[M00] * b[M01] + val[M01] * b[M11] + val[M02] * b[M21] + val[M03] * b[M31];\n\t\t\t__mjs_tmpMat1.val[M02] = val[M00] * b[M02] + val[M01] * b[M12] + val[M02] * b[M22] + val[M03] * b[M32];\n\t\t\t__mjs_tmpMat1.val[M03] = val[M00] * b[M03] + val[M01] * b[M13] + val[M02] * b[M23] + val[M03] * b[M33];\n\t\t\t__mjs_tmpMat1.val[M10] = val[M10] * b[M00] + val[M11] * b[M10] + val[M12] * b[M20] + val[M13] * b[M30];\n\t\t\t__mjs_tmpMat1.val[M11] = val[M10] * b[M01] + val[M11] * b[M11] + val[M12] * b[M21] + val[M13] * b[M31];\n\t\t\t__mjs_tmpMat1.val[M12] = val[M10] * b[M02] + val[M11] * b[M12] + val[M12] * b[M22] + val[M13] * b[M32];\n\t\t\t__mjs_tmpMat1.val[M13] = val[M10] * b[M03] + val[M11] * b[M13] + val[M12] * b[M23] + val[M13] * b[M33];\n\t\t\t__mjs_tmpMat1.val[M20] = val[M20] * b[M00] + val[M21] * b[M10] + val[M22] * b[M20] + val[M23] * b[M30];\n\t\t\t__mjs_tmpMat1.val[M21] = val[M20] * b[M01] + val[M21] * b[M11] + val[M22] * b[M21] + val[M23] * b[M31];\n\t\t\t__mjs_tmpMat1.val[M22] = val[M20] * b[M02] + val[M21] * b[M12] + val[M22] * b[M22] + val[M23] * b[M32];\n\t\t\t__mjs_tmpMat1.val[M23] = val[M20] * b[M03] + val[M21] * b[M13] + val[M22] * b[M23] + val[M23] * b[M33];\n\t\t\t__mjs_tmpMat1.val[M30] = val[M30] * b[M00] + val[M31] * b[M10] + val[M32] * b[M20] + val[M33] * b[M30];\n\t\t\t__mjs_tmpMat1.val[M31] = val[M30] * b[M01] + val[M31] * b[M11] + val[M32] * b[M21] + val[M33] * b[M31];\n\t\t\t__mjs_tmpMat1.val[M32] = val[M30] * b[M02] + val[M31] * b[M12] + val[M32] * b[M22] + val[M33] * b[M32];\n\t\t\t__mjs_tmpMat1.val[M33] = val[M30] * b[M03] + val[M31] * b[M13] + val[M32] * b[M23] + val[M33] * b[M33];\n\t\t\t\n\t\t\tthis.set(__mjs_tmpMat1);\n\t\t}\n\t\telse if(b instanceof Quaternion || b instanceof SimpleTransform) //B\n\t\t{\n\t\t\tthis.mul(__mjs_tmpMat2.set(b));\n\t\t}\n\t\telse if(b instanceof Vector3) //C\n\t\t{\n\t\t\tthis.mul(__mjs_tmpMat2.setScale(b));\n\t\t}\n\t\t\n\t\treturn this;\n\t}",
"function matrix_multiply_3(A,B,C) {\n\treturn matrix_multiply(A, matrix_multiply(B,C));\n}",
"static multiply(m0, m1) {\n Matrix.checkDimensions(m0, m1);\n let m = new Matrix(m0.rows, m0.cols);\n for (let i = 0; i < m.rows; i++) {\n for (let j = 0; j < m.cols; j++) {\n m.data[i][j] = m0.data[i][j] * m1.data[i][j];\n }\n }\n return m;\n }",
"static multiply(m0,m1){\n Matrix.checkDimensions(m0,m1);\n let m = new Matrix(m0.rows,m0.columns);\n for(let i = 0; i < m.rows; i++){\n for(let j = 0; j < m.columns; j++){\n m.data[i][j] = m0.data[i][j] * m1.data[i][j];\n }\n }\n return m;\n }",
"function betterMult() {\n result = mat4();\n for(i = 0; i < arguments.length; i++) {\n result = mult(result, arguments[i]);\n }\n return result;\n}",
"mult(m) {\n\t\treturn new LMat3([\n\t\t\tthis.arr[0] * m.arr[0] + this.arr[1] * m.arr[3] + this.arr[2] * m.arr[6],\n\t\t\tthis.arr[0] * m.arr[1] + this.arr[1] * m.arr[4] + this.arr[2] * m.arr[7],\n\t\t\tthis.arr[0] * m.arr[2] + this.arr[1] * m.arr[5] + this.arr[2] * m.arr[8],\n\t\n\t\t\tthis.arr[3] * m.arr[0] + this.arr[4] * m.arr[3] + this.arr[5] * m.arr[6],\n\t\t\tthis.arr[3] * m.arr[1] + this.arr[4] * m.arr[4] + this.arr[5] * m.arr[7],\n\t\t\tthis.arr[3] * m.arr[2] + this.arr[4] * m.arr[5] + this.arr[5] * m.arr[8],\n\t\n\t\t\tthis.arr[6] * m.arr[0] + this.arr[7] * m.arr[3] + this.arr[8] * m.arr[6],\n\t\t\tthis.arr[6] * m.arr[1] + this.arr[7] * m.arr[4] + this.arr[8] * m.arr[7],\n\t\t\tthis.arr[6] * m.arr[2] + this.arr[7] * m.arr[5] + this.arr[8] * m.arr[8], \n\t\t]);\t\n\t}",
"static multiply(A, B) {\n let R = new Matrix3D;\n let T1 = new Matrix3D;\n let T2 = new Matrix3D;\n if (A instanceof Matrix3D && B instanceof Matrix3D) {\n // A and B can't change during the operation.\n // If R is the same as A and/or B, Make copies of A and B\n // The comparison must use ==, not ===. We are comparing for identical\n // objects, not if two objects might have the same values.\n if (A._matrix == R._matrix) {\n A = Matrix3D.copy(T1, A);\n }\n if (B == R._matrix) {\n B = Matrix3D.copy(T2, B);\n }\n\n R._matrix[0] = A._matrix[0] * B._matrix[0] + A._matrix[3] * B._matrix[1] + A._matrix[6] * B._matrix[2];\n R._matrix[1] = A._matrix[1] * B._matrix[0] + A._matrix[4] * B._matrix[1] + A._matrix[7] * B._matrix[2];\n R._matrix[2] = A._matrix[2] * B._matrix[0] + A._matrix[5] * B._matrix[1] + A._matrix[8] * B._matrix[2];\n\n R._matrix[3] = A._matrix[0] * B._matrix[3] + A._matrix[3] * B._matrix[4] + A._matrix[6] * B._matrix[5];\n R._matrix[4] = A._matrix[1] * B._matrix[3] + A._matrix[4] * B._matrix[4] + A._matrix[7] * B._matrix[5];\n R._matrix[5] = A._matrix[2] * B._matrix[3] + A._matrix[5] * B._matrix[4] + A._matrix[8] * B._matrix[5];\n\n R._matrix[6] = A._matrix[0] * B._matrix[6] + A._matrix[3] * B._matrix[7] + A._matrix[6] * B._matrix[8];\n R._matrix[7] = A._matrix[1] * B._matrix[6] + A._matrix[4] * B._matrix[7] + A._matrix[7] * B._matrix[8];\n R._matrix[8] = A._matrix[2] * B._matrix[6] + A._matrix[5] * B._matrix[7] + A._matrix[8] * B._matrix[8];\n return R;\n }\n }",
"multiply(outMatrix, matrix1, matrix2) {\r\n // @todo\r\n }",
"multiply(matrix)\n\t{\n\t\tif (matrix != null && matrix instanceof ThreeMatrix)\n\t\t{\n\t\t\tvar ret = new ThreeMatrix();\n\n\t\t\tvar TcI,TcJ;\n\t\t\tfor (TcI = 0; TcI < 3; TcI++)\n\t\t\t{\n\t\t\t\tfor (TcJ = 0; TcJ < 3; TcJ++)\n\t\t\t\t{\n\t\t\t\t\tret.setat(TcI,TcJ,this.row(TcI).dot(matrix.column(TcJ)));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\t\telse\n\t\t\treturn null;\n\t}",
"multiply(matrix) {\r\n return this.mulOp(matrix, (x, y) => {\r\n return x * y;\r\n });\r\n }",
"multiply(matrix) {\n return this.clone().multiplyO(matrix)\n }",
"static multiply(m1, m2) {\n //matrix product\n if (m1.cols !== m2.rows) {\n print(\"Multiplication error\");\n return undefined;\n }\n let result = new Matrix(m1.rows, m2.cols);\n\n let a = m1.data;\n let b = m2.data;\n\n //multiply\n for (let i = 0; i < result.rows; i++) {\n for (let j = 0; j < result.cols; j++) {\n //dot product\n let sum = 0;\n for (let k = 0; k < m1.cols; k++) {\n sum += a[i][k] * b[k][j];\n }\n result.data[i][j] = sum;\n }\n }\n\n return result;\n }",
"multiply(matrix) {\n return this.clone().multiplyO(matrix);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get Friend List, if fully loaded, globalSignGFL should be [true, true, ...] | function getFriendList(uid){
update_status('开始获取好友列表...');
pageNo = 0;
URL = 'http://friend.renren.com/GetFriendList.do?curpage='+pageNo.toString()+'&id='+uid;
$.get(URL, {}, function(data){
Group = $('div.page > a', data);
var min_pageNo = 1;
var max_pageNo = 0;
for (var i=0; i<Group.length; i++){
var string = Group[i].href;
var selection = /curpage=\d+/g.exec(string);
var integer = 0;
if (selection){
integer = parseInt(selection[0].slice(8));
if (integer > max_pageNo){
max_pageNo = integer;
}
}
}
console.log('min:'+min_pageNo.toString()+' max:'+max_pageNo.toString());
idList = $('div#list-results div.info a',data);
for (var j=0; j<idList.length; j++){
selection = /profile\.do\?id=\d+/g.exec(idList[j].href);
if (selection) {
friendid = /\d+/g.exec(selection[0])[0];
globalFriendList.push(friendid)
}
}
if (max_pageNo >= min_pageNo) {
globalSignGFL = new Array(max_pageNo - min_pageNo + 2);
globalSignGFL[0] = true;
}
for (var i=min_pageNo; i<=max_pageNo; i++){
URL = 'http://friend.renren.com/GetFriendList.do?curpage='+i.toString()+'&id='+uid;
getFriendPage(URL, i);
}
if (max_pageNo < min_pageNo){
globalOkWithFriendList = true;
getAllFriendStatus(globalUserId);
}
}, 'html');
} | [
"function fetchFriendList() {\n chrome.tabs.sendRequest(bkg.facebook_id, {retrieveFriendsMap: 1});\n}",
"function get_fb_friends() {\n \n if (! fb_friends) {\n ds = { };\n fb_friends = ajax_call('/playdates/get_fb_friends/', ds);\n for (pdi in fb_friends) {\n key_list[fb_friends[pdi][\"key\"]] = fb_friends[pdi];\n }\n }\n return fb_friends;\n }",
"function getFriends() {\n\t\ttrace(\"Get Friends of logged in user\");\n\t\t\n\t\t_api.friends_get(null, function(result, ex) {\t\t\t\t\t\n\t\t\ttrace(_s.FRIENDS_GET);\n\t\t\t\n\t\t\ttrace(result);\n\t\t\tinspect(result);\n\t\t\t\n\t\t\tif(!$.isArray(result))\n\t\t\t\tresult = [];\n\t\t\t\n\t\t\tdispatchEvent(_s.FRIENDS_GET, result);\n\t\t});\t\t\n\t}",
"function obtainFriendList(){\n\tjQuery.get(CONTACT_URL, function(res){\n\t\tvar data = JSON.parse(res);\n\t\tvar member_count=data['MemberCount'];\n\t\tvar member_list=data['MemberList'];\n\t\tif (member_count==0) {\n\t\t\thint(\"Please login to continue.\");\n\t\t} else {\n\t\t\tfor(var i=0;i<member_list.length;i++){\n\t\t\t\tvar member=member_list[i];\n\t\t\t\tvar member_username=member[\"UserName\"];\n\t\t\t\tvar member_name=member[\"NickName\"];\n\t\t\t\tvar member_location=member[\"City\"];\n\t\t\t\tquery_db(member_location, member_name);\n\t\t\t\tif(i==member_list.length-1){\n\t\t\t\t\tquery_db(EOF__FLAG__, EOF__FLAG__);\n\t\t\t\t}\n\t\t\t\tvar data_nick={action:\"username\", nick:member_name, username:member_username, host:host};\n\t\t\t\tchrome.runtime.sendMessage({sendBack:true, data:data_nick});\n\t\t\t\tif(i==member_list.length-1){\n\t\t\t\t\tchrome.runtime.sendMessage({sendBack:true, data:{action:\"username\", nick:EOF__FLAG__, username:EOF__FLAG__}});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t});\n}",
"get friendList(){\n return this._friendList;\n }",
"get friends() {\n this._logger.debug(\"friends[get]\");\n return this._friends;\n }",
"function listFriends() {\n const people = loadFile()\n const friends = []\n\n const filteredPeople = people.filter((person) => {\n return person.isActive === false && currency(person.balance).value <= 2000\n })\n\n filteredPeople.forEach((person) => {\n person.friends.forEach((friend) => {\n friends.push(friend.name)\n })\n });\n\n return friends\n}",
"function friendsAvailable() {\n friendsLoaded = true;\n\n if (contactsLoaded) {\n disableExisting(existingFbContacts);\n }\n }",
"function loadFriends() {\n\n\tFB.api('/me/friends', function(response) {\n\n\t\taddFriend(me().name, me().id);\n\n\t\tfor (var i = 0; i < response.data.length; i++) {\n\t\t\taddFriend(response.data[i].name, response.data[i].id);\n\t\t}\n\n\t\tsetTypeahead();\n\t\t//getPhotos([\"Brad Girardeau\",\"Ben Girardeau\"]);\n\n\t});\n\n}",
"function getFriendsList(){\n\tconsole.log(\"Attempting to fetch the friends list from the data stored earlier...\");\n\tdocument.querySelector('.footer__console-status').innerHTML = consoleLogDefaultText + \" \" + \"Friends List: \" + sceneData.friendsListTab[0].firstName + \", \" + sceneData.friendsListTab[1].firstName + \", \" + sceneData.friendsListTab[2].firstName + inputField;\n}",
"function check_friend_lists () {\n var pgm = service + '.check_friend_lists: ' ;\n var no_friends = get_oauth(), provider ;\n for (provider in no_friends) if (no_friends.hasOwnProperty(provider)) no_friends[provider] = 0 ;\n var i, friend ;\n for (i=0 ; i<friends.length ; i++) {\n friend = friends[i] ;\n if (!no_friends.hasOwnProperty(friend.provider)) no_friends[friend.provider] = -1 ; // not logged in with this provider\n else if (no_friends[friend.provider] >= 0) no_friends[friend.provider] += 1 ; // logged in\n else no_friends[friend.provider] -= 1 ; // not logged in\n }\n // todo: add notification if logged in and no friends for one or more providers. there must be a friend list download problem\n for (provider in no_friends) if (no_friends.hasOwnProperty(provider)) {\n if (no_friends[provider] == 0) console.log(pgm + 'Warning. No friend list was found for ' + provider) ;\n else if ((no_friends[provider] < 0) && (providers.indexOf(provider) == -1)) console.log(pgm + 'Error. Found friend list for unknown provider ' + provider) ;\n }\n } // check_friend_lists",
"function fetchFriends(){\n friends = [];\n T.get('friends/list', { screen_name: myScreenName, count: NB_EL_TO_DISPLAY }, function (err, data, response) {\n if(err){\n setError(err)\n }else{\n for (var i = 0; i < data.users.length; i++) {\n let { id_str, name, screen_name, profile_image_url_https, following} = data.users[i];\n friends.push({id_str, name, screen_name, profile_image_url_https, following})\n }\n }\n\n })\n}",
"function getFriendLists() {\r\n friendLists = [];\r\n\r\n $('.dropdown-menu').empty();\r\n $(\".dropdown-menu\").append('<li><a href=\"#\">All</a></li>');\r\n\r\n FB.api('/me/?fields=friendlists.fields(members,name)', function(response) {\r\n for (var i=0; i < response.friendlists.data.length; i++) {\r\n var list = response.friendlists.data[i];\r\n\r\n if(list.members != undefined) {\r\n friendLists[list.name] = []\r\n\r\n for(var j=0; j < list.members.data.length; j++) {\r\n friendLists[list.name].push(list.members.data[j].id)\r\n }\r\n\r\n $(\".dropdown-menu\").append('<li><a href=\"#\">' + list.name + '</a></li>');\r\n }\r\n }\r\n });\r\n}",
"function getFriends_FB() {\r\n\t// if the person has not pressed login button\r\n\r\n\tif (!loggedIn) {\r\n\t\tloginFacebook();\r\n\t}\r\n\r\n\tdocument.getElementById(\"status\").innerHTML = \"Please wait...\";\r\n\r\n\t// if the person is loggedIn\r\n\tif (loggedIn) {\r\n\r\n\t\tFB\r\n\t\t\t\t.api(\r\n\t\t\t\t\t\t\"/me/friends?fields=id,name,gender,languages,picture,location,birthday,work,education,email\",\r\n\t\t\t\t\t\tfunction(response) {\r\n\t\t\t\t\t\t\tfriends = response[\"data\"];\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\ttotalToBeLoaded = friends.length;\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tloadLocation(0);\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t});\r\n\r\n\t}\r\n\r\n}",
"function FriendsList() {\n //***NEEDS IMPLEMENTATION***\n}",
"getFriends() {\n return this.sendRequest(\n 'GET',\n 'https://api.fitbit.com/1/user/-/friends.json',\n this.constructHeaders(),\n );\n }",
"function friendsAvailable() {\n Curtain.hide(sendReadyEvent);\n\n friendsLoaded = true;\n\n if (contactsLoaded) {\n window.setTimeout(startSync, 0);\n\n markExisting(existingFbContacts);\n }\n }",
"async getFriends() {\n\n\t\treturn( await this._apiClient.get( \"/friends/index.json\" ) );\n\n\t}",
"function loadFriends(friends, allFriends, callback) {\n\n friend = friends.shift();\n\n if (friend) {\n\n queries.findUser(friend.xid, function(user) {\n if (user) {\n allFriends.push(user);\n }\n loadFriends(friends, allFriends, callback);\n });\n }\n else {\n callback(allFriends);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the boundary edge lengths of the input mesh. | computeBoundaryLengths() {
this.l = DenseMatrix.zeros(this.nB, 1);
for (let he of this.boundary.adjacentHalfedges()) {
let i = this.bVertexIndex[he.vertex];
this.l.set(geometry.length(he.edge), i, 0);
}
} | [
"function LengthofEdges() {\r\n\tvar length = l.value;\r\n\tvar width = w.value;\r\n\tvar height = h.value;\r\n\treturn ((4*height)+(2*length)+(2*width));\r\n}",
"idealEdgeLength(edge) { return 32 }",
"edgeLength() {\n return this.getFace().sideLength();\n }",
"idealEdgeLength(edge) { return 32; }",
"getTotalLength() {\n let totalLength = 0;\n\n for (let i = 1; i < this.polygon.length; i++) {\n totalLength += Vec2(\n this.polygon[i][0] * this.scale,\n this.polygon[i][1] * this.scale\n ).distance(\n Vec2(\n this.polygon[i - 1][0] * this.scale,\n this.polygon[i - 1][1] * this.scale\n )\n );\n }\n\n return totalLength;\n }",
"static edgeLen(edge) {\n return edge[0].dist(edge[1])\n }",
"function getWidth(mesh) {\n mesh?.geometry?.computeBoundingBox()\n const meshSize = new Vector3();\n mesh?.geometry?.boundingBox?.getSize(meshSize)\n return meshSize.x\n}",
"function getEdgeLength(num){\n length = Math.ceil(Math.sqrt(num));\n return length % 2 == 0 ? length + 1 : length;\n}",
"getNumOfEdges() {\n let numOfRelations = 0;\n for (let node of this.nodes) {\n numOfRelations += node.adjacent.size;\n }\n return numOfRelations / 2;\n }",
"function getDimensions () {\n for (var i = 0; i < vertices.length; i += 1) {\n var v = vertices[i];\n\n if (typeof self.minX === 'undefined' || v.x < self.minX) {\n self.minX = v.x;\n }\n\n if (typeof self.minY === 'undefined' || v.y < self.minY) {\n self.minY = v.y;\n }\n\n if (typeof self.minZ === 'undefined' || v.z < self.minZ) {\n self.minZ = v.z;\n }\n\n if (typeof self.maxX === 'undefined' || v.x > self.maxX) {\n self.maxX = v.x;\n }\n\n if (typeof self.maxY === 'undefined' || v.y > self.maxY) {\n self.maxY = v.y;\n }\n\n if (typeof self.maxZ === 'undefined' || v.z > self.maxZ) {\n self.maxZ = v.z;\n }\n }\n\n self.lengthX = Math.abs(self.maxX - self.minX);\n self.lengthY = Math.abs(self.maxY - self.minY);\n self.lengthZ = Math.abs(self.maxZ - self.minZ);\n }",
"edgeCount() {\n return this.vertices()\n .reduce((sum, v) => this.adjacencyList[v].size + sum, 0) / 2;\n }",
"realLength(){\n let length = 0;\n let A = this.getPoint(0);\n for(let i = 1; i<this.size(); i++){\n const B = this.getPoint(i);\n if(B.getGroundElevation() === 0){\n return 0;\n }\n const dEle = A.getGroundElevation()-B.getGroundElevation();\n length +=Math.sqrt(Math.pow(B.groundDistance(A),2) + Math.pow(dEle,2));\n A = B;\n\n }\n return Math.round(length*10)/10;\n }",
"getDiagLength() {\n let dX = this.XLen()/2;\n let dY = this.YLen()/2;\n let dZ = this.ZLen()/2;\n return Math.sqrt(dX*dX + dY*dY + dZ*dZ);\n }",
"triangulate ( bound, isReal ) {\n\n if(bound.length < 2) {\n Log(\"BREAK ! the hole has less than 2 edges\");\n return;\n // if the hole is a 2 edges polygon, we have a big problem\n } else if(bound.length === 2) {\n Log(\"BREAK ! the hole has only 2 edges\");\n // DDLS.Debug.trace(\" - edge0: \" + bound[0].originVertex.id + \" -> \" + bound[0].destinationVertex.id,{ fileName : \"Mesh.hx\", lineNumber : 1404, className : \"DDLS.Mesh\", methodName : \"triangulate\"});\n // DDLS.Debug.trace(\" - edge1: \" + bound[1].originVertex.id + \" -> \" + bound[1].destinationVertex.id,{ fileName : \"Mesh.hx\", lineNumber : 1405, className : \"DDLS.Mesh\", methodName : \"triangulate\"});\n return;\n // if the hole is a 3 edges polygon:\n } else if(bound.length === 3) {\n\n let f = new Face();\n f.setDatas(bound[0], isReal);\n this._faces.push(f);\n bound[0].leftFace = f;\n bound[1].leftFace = f;\n bound[2].leftFace = f;\n bound[0].nextLeftEdge = bound[1];\n bound[1].nextLeftEdge = bound[2];\n bound[2].nextLeftEdge = bound[0];\n // if more than 3 edges, we process recursively:\n } else {\n let baseEdge = bound[0];\n let vertexA = baseEdge.originVertex;\n let vertexB = baseEdge.destinationVertex;\n let vertexC;\n let vertexCheck;\n let circumcenter = new Point();\n let radiusSquared = 0;\n let distanceSquared = 0;\n let isDelaunay = false;\n let index = 0;\n let _g1 = 2;\n let _g = bound.length;\n while(_g1 < _g) {\n let i1 = _g1++;\n vertexC = bound[i1].originVertex;\n if(Geom2D.getRelativePosition2(vertexC.pos,baseEdge) == 1) {\n index = i1;\n isDelaunay = true;\n //DDLS.Geom2D.getCircumcenter(vertexA.pos.x,vertexA.pos.y,vertexB.pos.x,vertexB.pos.y,vertexC.pos.x,vertexC.pos.y,circumcenter);\n Geom2D.getCircumcenter(vertexA.pos, vertexB.pos, vertexC.pos, circumcenter);\n radiusSquared = Squared(vertexA.pos.x - circumcenter.x, vertexA.pos.y - circumcenter.y);\n // for perfect regular n-sides polygons, checking strict delaunay circumcircle condition is not possible, so we substract EPSILON to circumcircle radius:\n radiusSquared -= EPSILON_SQUARED;\n let _g3 = 2;\n let _g2 = bound.length;\n while(_g3 < _g2) {\n let j = _g3++;\n if(j != i1) {\n vertexCheck = bound[j].originVertex;\n distanceSquared = Squared(vertexCheck.pos.x - circumcenter.x, vertexCheck.pos.y - circumcenter.y);\n if(distanceSquared < radiusSquared) {\n isDelaunay = false;\n break;\n }\n }\n }\n if(isDelaunay) break;\n }\n }\n \n if(!isDelaunay) {\n // for perfect regular n-sides polygons, checking delaunay circumcircle condition is not possible\n Log(\"NO DELAUNAY FOUND\");\n /*let s = \"\";\n let _g11 = 0;\n let _g4 = bound.length;\n while(_g11 < _g4) {\n let i2 = _g11++;\n s += bound[i2].originVertex.pos.x + \" , \";\n s += bound[i2].originVertex.pos.y + \" , \";\n s += bound[i2].destinationVertex.pos.x + \" , \";\n s += bound[i2].destinationVertex.pos.y + \" , \";\n }*/\n index = 2;\n }\n\n let edgeA, edgeAopp, edgeB, edgeBopp, boundA, boundB, boundM = [];\n\n if(index < (bound.length - 1)) {\n edgeA = new Edge();\n edgeAopp = new Edge();\n this._edges.push( edgeA, edgeAopp );\n //this._edges.push(edgeAopp);\n edgeA.setDatas(vertexA,edgeAopp,null,null,isReal,false);\n edgeAopp.setDatas(bound[index].originVertex,edgeA,null,null,isReal,false);\n boundA = bound.slice(index);\n boundA.push(edgeA);\n this.triangulate(boundA,isReal);\n }\n if(index > 2) {\n edgeB = new Edge();\n edgeBopp = new Edge();\n this._edges.push(edgeB, edgeBopp);\n //this._edges.push(edgeBopp);\n edgeB.setDatas(bound[1].originVertex,edgeBopp,null,null,isReal,false);\n edgeBopp.setDatas(bound[index].originVertex,edgeB,null,null,isReal,false);\n boundB = bound.slice(1,index);\n boundB.push(edgeBopp);\n this.triangulate(boundB,isReal);\n }\n \n if( index === 2 ) boundM.push( baseEdge, bound[1], edgeAopp ); \n else if( index === (bound.length - 1) ) boundM.push(baseEdge, edgeB, bound[index]); \n else boundM.push(baseEdge, edgeB, edgeAopp );\n \n this.triangulate( boundM, isReal );\n\n }\n\n // test\n //this.deDuplicEdge();\n\n }",
"function edgeLength(n, p) {\n return p / n;\n}",
"GetPathLength(path) {\n let path_distance = 0;\n for (let j = 0; j < path.length - 1; j++) {\n let edge_start = path[j];\n let edge_end = path[j + 1];\n path_distance += this.GetEdgeWeight(edge_start, edge_end);\n }\n return path_distance;\n }",
"triangulate ( bound, isReal ) {\n\n if(bound.length < 2) {\n Log(\"BREAK ! the hole has less than 2 edges\");\n return;\n // if the hole is a 2 edges polygon, we have a big problem\n } else if(bound.length === 2) {\n Log(\"BREAK ! the hole has only 2 edges\");\n // DDLS.Debug.trace(\" - edge0: \" + bound[0].originVertex.id + \" -> \" + bound[0].destinationVertex.id,{ fileName : \"Mesh.hx\", lineNumber : 1404, className : \"DDLS.Mesh\", methodName : \"triangulate\"});\n // DDLS.Debug.trace(\" - edge1: \" + bound[1].originVertex.id + \" -> \" + bound[1].destinationVertex.id,{ fileName : \"Mesh.hx\", lineNumber : 1405, className : \"DDLS.Mesh\", methodName : \"triangulate\"});\n return;\n // if the hole is a 3 edges polygon:\n } else if(bound.length === 3) {\n\n let f = new Face();\n f.setDatas(bound[0], isReal);\n this._faces.push(f);\n bound[0].leftFace = f;\n bound[1].leftFace = f;\n bound[2].leftFace = f;\n bound[0].nextLeftEdge = bound[1];\n bound[1].nextLeftEdge = bound[2];\n bound[2].nextLeftEdge = bound[0];\n // if more than 3 edges, we process recursively:\n } else {\n let baseEdge = bound[0];\n let vertexA = baseEdge.originVertex;\n let vertexB = baseEdge.destinationVertex;\n let vertexC;\n let vertexCheck;\n let circumcenter = new Point();\n let radiusSquared = 0;\n let distanceSquared = 0;\n let isDelaunay = false;\n let index = 0;\n let i;\n let _g1 = 2;\n let _g = bound.length;\n while(_g1 < _g) {\n let i1 = _g1++;\n vertexC = bound[i1].originVertex;\n if(Geom2D.getRelativePosition2(vertexC.pos,baseEdge) == 1) {\n index = i1;\n isDelaunay = true;\n //DDLS.Geom2D.getCircumcenter(vertexA.pos.x,vertexA.pos.y,vertexB.pos.x,vertexB.pos.y,vertexC.pos.x,vertexC.pos.y,circumcenter);\n Geom2D.getCircumcenter(vertexA.pos, vertexB.pos, vertexC.pos, circumcenter);\n radiusSquared = Squared(vertexA.pos.x - circumcenter.x, vertexA.pos.y - circumcenter.y);\n // for perfect regular n-sides polygons, checking strict delaunay circumcircle condition is not possible, so we substract EPSILON to circumcircle radius:\n radiusSquared -= EPSILON_SQUARED;\n let _g3 = 2;\n let _g2 = bound.length;\n while(_g3 < _g2) {\n let j = _g3++;\n if(j != i1) {\n vertexCheck = bound[j].originVertex;\n distanceSquared = Squared(vertexCheck.pos.x - circumcenter.x, vertexCheck.pos.y - circumcenter.y);\n if(distanceSquared < radiusSquared) {\n isDelaunay = false;\n break;\n }\n }\n }\n if(isDelaunay) break;\n }\n }\n \n if(!isDelaunay) {\n // for perfect regular n-sides polygons, checking delaunay circumcircle condition is not possible\n Log(\"NO DELAUNAY FOUND\");\n /*let s = \"\";\n let _g11 = 0;\n let _g4 = bound.length;\n while(_g11 < _g4) {\n let i2 = _g11++;\n s += bound[i2].originVertex.pos.x + \" , \";\n s += bound[i2].originVertex.pos.y + \" , \";\n s += bound[i2].destinationVertex.pos.x + \" , \";\n s += bound[i2].destinationVertex.pos.y + \" , \";\n }*/\n index = 2;\n }\n\n let edgeA, edgeAopp, edgeB, edgeBopp, boundA, boundB, boundM = [];\n\n if(index < (bound.length - 1)) {\n edgeA = new Edge();\n edgeAopp = new Edge();\n this._edges.push( edgeA, edgeAopp );\n //this._edges.push(edgeAopp);\n edgeA.setDatas(vertexA,edgeAopp,null,null,isReal,false);\n edgeAopp.setDatas(bound[index].originVertex,edgeA,null,null,isReal,false);\n boundA = bound.slice(index);\n boundA.push(edgeA);\n this.triangulate(boundA,isReal);\n }\n if(index > 2) {\n edgeB = new Edge();\n edgeBopp = new Edge();\n this._edges.push(edgeB, edgeBopp);\n //this._edges.push(edgeBopp);\n edgeB.setDatas(bound[1].originVertex,edgeBopp,null,null,isReal,false);\n edgeBopp.setDatas(bound[index].originVertex,edgeB,null,null,isReal,false);\n boundB = bound.slice(1,index);\n boundB.push(edgeBopp);\n this.triangulate(boundB,isReal);\n }\n \n if( index === 2 ) boundM.push( baseEdge, bound[1], edgeAopp ); \n else if( index === (bound.length - 1) ) boundM.push(baseEdge, edgeB, bound[index]); \n else boundM.push(baseEdge, edgeB, edgeAopp );\n \n this.triangulate( boundM, isReal );\n\n }\n\n // test\n //this.deDuplicEdge();\n\n }",
"function polygonLength(vertices){\n var i = -1,\n n = vertices.length,\n b = vertices[n - 1],\n xa,\n ya,\n xb = b[0],\n yb = b[1],\n perimeter = 0;\n\n while (++i < n) {\n xa = xb;\n ya = yb;\n b = vertices[i];\n xb = b[0];\n yb = b[1];\n xa -= xb;\n ya -= yb;\n perimeter += Math.sqrt(xa * xa + ya * ya);\n }\n\n return perimeter;\n }",
"function edgeLengthInMiles(e) {\n\n if (!e.hasOwnProperty(\"length\")) {\n\tlet len = 0.0;\n\tif (e.via == null) {\n\t // no intermediate points: easy case\n\t len = distanceInMiles(waypoints[e.v1].lat, waypoints[e.v1].lon,\n\t\t\t\t waypoints[e.v2].lat, waypoints[e.v2].lon);\n\t}\n\telse {\n\t // account for intermediate points in \"via\" array\n\t len = distanceInMiles(waypoints[e.v1].lat, waypoints[e.v1].lon,\n\t\t\t\t parseFloat(e.via[0]), parseFloat(e.via[1]));\n\t for (var pos = 0; pos < e.via.length - 2; pos += 2) {\n\t\tlen += distanceInMiles(parseFloat(e.via[pos]),\n\t\t\t\t parseFloat(e.via[pos+1]),\n\t\t\t\t parseFloat(e.via[pos+2]),\n\t\t\t\t parseFloat(e.via[pos+3]));\n\t }\n\t len += distanceInMiles(parseFloat(e.via[e.via.length-2]),\n\t\t\t\t parseFloat(e.via[e.via.length-1]),\n\t\t\t\t waypoints[e.v2].lat, waypoints[e.v2].lon);\n\t}\n\te.length = len;\n }\n return e.length;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function enables/disables correct pages in the pagination | function togglePagination() {
if (App.CurrentPage) {
//reset pagination
$('.pagination li').removeClass("active").removeClass("disabled");
$('.pagination').find(".page" + App.CurrentPage).addClass("active");
if (App.CurrentPage === 1) {
$('.prev').addClass("disabled");
} else if (App.CurrentPage === (App.TotalEntries / App.NumEntriesPerPage)) {
$('.next').addClass("disabled");
}
}
} | [
"function enableButtons() {\n $next = $paginator.find(\".next-page\");\n $prev = $paginator.find(\".previous-page\");\n \n if( self.currentPage === 0 ) { // is first page\n $prev.addClass('disabled').removeData(\"page\");\n } else {\n $prev.removeClass('disabled').data(\"page\", self.currentPage);\n }\n \n if( self.currentPage === $pages.length-1 ) { // is last page\n $next.addClass('disabled').removeData(\"page\");\n } else {\n $next.removeClass('disabled').data(\"page\", self.currentPage+2);\n }\n \n $paginator.find(\".page-number-container:first a\").removeClass(\"current-page\");\n $paginator.find(\".page-number-container:first a:eq(\"+self.currentPage+\")\").addClass('current-page');\n }",
"function updatePagination(page) {\r\n if (page >= 1) {\r\n $(\".next\").attr(\"disabled\", false);\r\n }\r\n\r\n if (page <= 1) {\r\n $(\".previous\").attr(\"disabled\", true);\r\n } else {\r\n $(\".previous\").attr(\"disabled\", false);\r\n }\r\n}",
"function setPagination(){\n\t\tvar currPage=grid.getGridParam(\"page\"),lastPage=grid.getGridParam(\"lastpage\"),\n\t\t\tnavId='_'+ grid.getGridParam('pager').slice(1);\n\t\tif(currPage=== 1){\n\t\t\tjQuery(\"#first\"+navId+\", #prev\"+navId).addClass('ui-state-disabled');\n\t\t}else{\n\t\t\tjQuery(\"#first\"+navId+\", #prev\"+navId).removeClass('ui-state-disabled');\n\t\t}\n\t\tif(currPage== lastPage || lastPage===0){\n\t\t\tjQuery(\"#next\"+navId+\", #last\"+navId).addClass('ui-state-disabled');\n\t\t}else{\n\t\t\tjQuery(\"#next\"+navId+\", #last\"+navId).removeClass('ui-state-disabled');\n\t\t}\t\n\t}",
"function check() {\n document.getElementById(\"next\").disabled = currentPage == numberOfPages ? true : false;\n document.getElementById(\"previous\").disabled = currentPage == 1 ? true : false;\n document.getElementById(\"first\").disabled = currentPage == 1 ? true : false;\n document.getElementById(\"last\").disabled = currentPage == numberOfPages ? true : false;\n }",
"function check() {\n document.getElementById(\"next\").disabled = currentPage == numberOfPages ? true : false;\n document.getElementById(\"previous\").disabled = currentPage == 1 ? true : false;\n document.getElementById(\"first\").disabled = currentPage == 1 ? true : false;\n document.getElementById(\"last\").disabled = currentPage == numberOfPages ? true : false;\n }",
"function check() {\n document.getElementById(\"next\").disabled =\n currentPage == numberOfPages ? true : false;\n document.getElementById(\"previous\").disabled =\n currentPage == 1 ? true : false;\n}",
"function enable_next( )\n{\n $( \"#paging-last\" ).prop( 'disabled', 'false' );\n $( \"#paging-next\" ).prop( 'disabled', 'false' );\n}",
"function check() {\n document.getElementById(\"next\").disabled = currentPage == numberOfPages ? true : false;\n document.getElementById(\"previous\").disabled = currentPage == 1 ? true : false;\n document.getElementById(\"first\").disabled = currentPage == 1 ? true : false;\n document.getElementById(\"last\").disabled = currentPage == numberOfPages ? true : false;\n}",
"function _updatePageButtons() {\n var nextButton = document.querySelector('.next-page');\n var prevButton = document.querySelector('.prev-page');\n\n prevButton.disabled = (leftPageNo == -1);\n nextButton.disabled = (rightPageNo >= maxPageNo);\n}",
"function setPaginationButtonStatus(that) {\n that.model.pagination.disableNextBtn =\n that.model.pagination.currentPage + 1 >=\n that.model.pagination.totalPages;\n\n that.model.pagination.disablePrevBtn =\n that.model.pagination.currentPage === 0;\n }",
"function updatePagination () {\n ctrl.shouldPaginate = shouldPaginate();\n }",
"function updatePager() {\n if (isNext) {\n nextButton.removeClass('disable');\n } else {\n nextButton.addClass('disable');\n }\n if (isPrevious) {\n prevButton.removeClass('disable');\n } else {\n prevButton.addClass('disable');\n }\n //Setting the Page Number\n if (prevButton.siblings('.pageno').length == 1) {\n prevButton.siblings('.pageno').html(pageNo);\n } else if (nextButton.siblings('.pageno').length == 1) {\n nextButton.siblings('.pageno').html(pageNo);\n }\n }",
"checkPaginationEnabled() {\n if (this.disablePagination || this.vertical) {\n this.showPaginationControls = false;\n }\n else {\n const isEnabled = this.tabList.nativeElement.scrollWidth > this.elementRef.nativeElement.offsetWidth;\n if (!isEnabled) {\n this.scrollDistance = 0;\n }\n if (isEnabled !== this.showPaginationControls) {\n this.changeDetectorRef.markForCheck();\n }\n this.showPaginationControls = isEnabled;\n }\n }",
"function setPrevNext() {\n prevDisable();\n prevBtn.addEventListener(\"click\", function() {\n page--;\n if(page == 1)\n prevDisable();\n getList(page);\n });\n nextBtn.addEventListener(\"click\", function() {\n page++;\n prevEnable();\n getList(page);\n //need to add some restriction!!!!!!!!!!!!!!!!!for page > limit\n });\n}",
"function setupPagingNavigationButtons(p_name, p_tpages, p_page) {\r\n var l_next_obj = jQuery('#status_report_pager_' + id + '_center').find('td[id=\"next_status_report_pager_' + id + '\"]');\r\n var l_first_obj = jQuery('#status_report_pager_' + id + '_center').find('td[id=\"first_status_report_pager_' + id + '\"]');\r\n var l_last_obj = jQuery('#status_report_pager_' + id + '_center').find('td[id=\"last_status_report_pager_' + id + '\"]');\r\n var l_prev_obj = jQuery('#status_report_pager_' + id + '_center').find('td[id=\"prev_status_report_pager_' + id + '\"]');\r\n if (p_tpages > 1) {\r\n if (p_page !== p_tpages) {\r\n l_next_obj.removeClass('ui-state-disabled');\r\n l_last_obj.removeClass('ui-state-disabled');\r\n }\r\n if (p_page > 1) {\r\n l_prev_obj.removeClass('ui-state-disabled');\r\n l_first_obj.removeClass('ui-state-disabled');\r\n }\r\n }\r\n }",
"function disable_next( )\n{\n $( \"#paging-last\" ).prop( 'disabled', 'true' );\n $( \"#paging-next\" ).prop( 'disabled', 'true' );\n}",
"function updatePageControls() {\r\n\t// Loop through and count the active document pages.\r\n\tvar pageCounter = 0;\r\n\tvar lastPageIndex = 0;\t\t//Get the last pages index position for a document\r\n\tfor (var i = 0; i < objCase.pages.length; i++) { \r\n\t\tif (objCase.pages[i].subDocumentOrder == objPage.subDocumentOrder && objPage.subDocumentOrder != 9999 && objPage.subDocumentOrder != '9999') {\r\n\t\t\tpageCounter++;\r\n\t\t\tlastPageIndex = i;\r\n\t\t} \r\n\t}\r\n\t\r\n\tvar lastPageNumber = objCase.pages[lastPageIndex].subDocumentPageNumber;\r\n\t\r\n\tif (pageCounter == 1 || pageCounter == 0) {\r\n\t\t// #Only\r\n\t\t$(\"#nav_prev_page\").attr('disabled','disabled');\r\n\t\t$(\"#nav_next_page\").attr('disabled','disabled');\r\n\t} else if (objPage.subDocumentPageNumber == 1) {\r\n\t\t// #First\r\n\t\t$(\"#nav_prev_page\").attr('disabled','disabled');\r\n\t\t$(\"#nav_next_page\").removeAttr('disabled');\r\n\t} else if (objPage.subDocumentPageNumber == lastPageNumber) {\r\n\t\t// #Last\r\n\t\t$(\"#nav_prev_page\").removeAttr('disabled');\r\n\t\t$(\"#nav_next_page\").attr('disabled','disabled');\r\n\t} else if (objPage.subDocumentOrder == 9999 || objPage.subDocumentOrder == '9999') {\r\n\t\t$(\"#nav_prev_document\").attr('disabled','disabled');\r\n\t\t$(\"#nav_next_document\").attr('disabled','disabled');\t\t\t\r\n\t} else {\r\n\t\t// #Middle\r\n\t\t$(\"#nav_prev_page\").removeAttr('disabled');\r\n\t\t$(\"#nav_next_page\").removeAttr('disabled');\r\n\t}\r\n}",
"function updateButtonState() {\n if (window.activePage == undefined){\n return\n }\n var previousLi = $('li.page-item.previous');\n var firstLi = $('li.page-item.first');\n var nextLi = $('li.page-item.next');\n var lastLi = $('li.page-item.last');\n if (window.activePage == 1){\n if (!firstLi.hasClass('disabled')){\n firstLi.addClass('disabled');\n }\n if (!previousLi.hasClass('disabled')) {\n previousLi.addClass('disabled');\n }\n if (nextLi.hasClass('disabled')) {\n nextLi.removeClass('disabled');\n }\n if (lastLi.hasClass('disabled')) {\n lastLi.removeClass('disabled');\n }\n } else if (window.activePage == window.maxPage) {\n if (firstLi.hasClass('disabled')) {\n firstLi.removeClass('disabled');\n }\n if (previousLi.hasClass('disabled')) {\n previousLi.removeClass('disabled');\n }\n if (!nextLi.hasClass('disabled')) {\n nextLi.addClass('disabled');\n }\n if (!lastLi.hasClass('disabled')) {\n lastLi.addClass('disabled');\n }\n } else {\n if (firstLi.hasClass('disabled')) {\n firstLi.removeClass('disabled');\n }\n if (previousLi.hasClass('disabled')) {\n previousLi.removeClass('disabled');\n }\n if (nextLi.hasClass('disabled')) {\n nextLi.removeClass('disabled');\n }\n if (lastLi.hasClass('disabled')) {\n lastLi.removeClass('disabled');\n }\n }\n}",
"_checkPaginationEnabled() {\n if (this.disablePagination) {\n this._showPaginationControls = false;\n }\n else {\n const isEnabled = this._tabList.nativeElement.scrollWidth > this._elementRef.nativeElement.offsetWidth;\n if (!isEnabled) {\n this.scrollDistance = 0;\n }\n if (isEnabled !== this._showPaginationControls) {\n this._changeDetectorRef.markForCheck();\n }\n this._showPaginationControls = isEnabled;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Formats date and time If only a date is recived back from Google Calendar API: Date Format Given By Google Calandar API yyyymmdd ie 20181220 Formated to monthName dd, yyyy If date and time is recieve back from Google Calendar API: Date Format given by google calendar API is 20180615T18:00:0005:00 Formatted to monthName dd, yyyy tt:tt (am/pm) | function formatDate(when) {
if (when !== "") {
const monthNames = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];
// Splits 2018-06-15T18:00:00-05:00 or 2018-12-20 into an array
// of numbers
let dateArray = when.split(/(?:-|T)+/);
const year = dateArray[0];
let month;
if (dateArray[1].indexOf("10") === -1) {
month = dateArray[1].replace("0", ""); //Replace the 05:00 with 5:00
} else {
month = dateArray[1]; //Replace the 05:00 with 5:00
}
const day = dateArray[2];
// If only date given return just the date else return time as well
if (dateArray.length <= 3) {
return `${monthNames[month - 1]} ${day}, ${year}`;
} else {
// Get the time array from 2018-06-15T18:00:00-05:00
// splits time into [hh, mm, ss] ie [18,00,00]
const time = dateArray[3].split(":");
let hour = parseInt(time[0], 10);
// if the time is after noon 12pm subtract 12 from it 18 becomes 6pm
if (hour > 12) {
hour = hour - 12;
}
let ampm = "pm";
// if the 24 hour time doesn't contain a 0 as the first element ie 17:00
// it it pm
dateArray[3][0] == "0" ? (ampm = "am") : (ampm = "pm");
return `${monthNames[month - 1]} ${day}, ${year} at ${hour} ${ampm}`;
}
}
return "";
} | [
"function setFormatDateAndTime(dateAndTime) {\n return Utilities.formatDate(dateAndTime, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), \"dd-MMM-yyyy | HH:mm:ss\")\n}",
"convertGoogleDateTime(date) {\n let yyyy = date.substring(0, 4);\n let mm = date.substring(5, 7);\n let dd = date.substring(8, 10);\n let converted = mm + \"/\" + dd + \"/\" + yyyy;\n return converted;\n }",
"function formatDate(data) {\n data.startdatetime = data.startdatetime.split(\"-\").join(\"\");\n data.startdatetime += \"T07:00-0000\"\n data.enddatetime = data.enddatetime.split(\"-\").join(\"\");\n data.enddatetime += \"T07:00-0000\"\n return data;\n }",
"function formatTime_fullCalendar(time){\r\n var timePattern = /[0-9-]{10}T[0-9:]{5} [APM]{2}/;\r\n if (timePattern.test(time)){\r\n var timePart = time.substr(time.indexOf('T')+1);\r\n var hourPart = timePart.substr(0, 2);\r\n var hour = parseInt(hourPart);\r\n var minutePart = timePart.substr(timePart.indexOf(':')+1, 2);\r\n if (timePart.indexOf('PM') != -1){\r\n if (hour < 12){\r\n timePart = (hour + 12) + ':' + minutePart + ':00';\r\n }else{ //hourPart is 12 and it's PM\r\n timePart = hourPart + ':' + minutePart + ':00';\r\n }\r\n }else { // time is AM\r\n timePart = hourPart + ':' + minutePart + ':00';\r\n }\r\n return time.substr(0, time.indexOf('T')+1) + timePart;\r\n }else{\r\n return time;\r\n }\r\n\r\n}",
"function reformatDate(date) {\n\tif (!date || date == null) {\n\t\treturn \"\";\n\t}\n\t\n\t// split up the date and time components to make easier to change.\n\tvar datetime = date.split(' ');\n\t\n\t// reformat the calendar-date components.\n\tvar oldDate = datetime[0];\n\tvar oldDateComponents = oldDate.split('/');\n\tvar YYYY = oldDateComponents[2];\n\tvar MM = oldDateComponents[0].length === 1 ? '0' + oldDateComponents[0] : oldDateComponents[0]; // month should be in the form 'MM'.\n\tvar DD = oldDateComponents[1];\n\t\n\t// reformat the clock-time components.\n\tvar oldTime = datetime[1];\n\tvar oldTimeComponents = oldTime.split(':');\n\tvar hh = oldTimeComponents[0].length === 1 ? '0' + oldTimeComponents[0] : oldTimeComponents[0]; // hours should be in the form 'hh'.\n\tvar mm = oldTimeComponents[1];\n\tvar ss = '00'; // seconds aren't preserved in formatDate() from the original TimeStamp, so here just hardcoding 0...\n\tvar sss = '000'; // same situation as seconds, so here just hardcoding 0 for milliseconds...\n\t\n\t// assemble the iso date from the reformatted date and time components.\n\tvar isoDate = YYYY + '-' + MM + '-' + DD + 'T' + // add the date components.\n\t\thh + ':' + mm + ':' + ss + '.' + sss + 'Z'; // add the time components.\n\t\n\t// return the iso-formatted version of the date.\n\treturn isoDate;\n}",
"function WindowsDateFormat2DatePickerDateFormat(sample, notime) {\n var result;\n var ampm = sample.match(/AM|PM/);\n var hasTime = sample.match(/:/);\n var sampleNoTime = sample.replace(/[0-9]+:[0-9]+( (A|P)M)*$/, '');\n var longFormat = sample && sampleNoTime.match(/[^: /.\\-0-9]/); // induce from content\n var isSpecialDateFormat = sample && sample.match(/[0-9]+-[a-zA-Z]{3}-[0-9]{4}/); // induce from content of the form of 01-Nov-1990 specifically\n try {\n if (isSpecialDateFormat) result = 'd-M-yy'\n else if (longFormat) {\n result = ServerDateFormat.longFormat;\n if (result.match(/MMMM/)) result = result.replace(/MMMM/, \"MM\");\n else if (result.match(/MMM/)) result = result.replace(/MMM/, \"M\");\n else if (result.match(/MM/)) result = result.replace(/MM/, \"mm\");\n else if (result.match(/M/)) result = result.replace(/M/, \"m\");\n\n if (result.match(/yyyy/)) result = result.replace(/yyyy/, \"yy\");\n else if (result.match(/yy/)) result = result.replace(/yy/, \"y\");\n\n if (result.match(/dddd/)) result = result.replace(/dddd/, \"DD\");\n else if (result.match(/ddd/)) result = result.replace(/ddd/, \"D\");\n\n } else {\n result = ServerDateFormat.shortFormat;\n if (result.match(/MMMM/)) result = result.replace(/MMMM/, \"MM\");\n else if (result.match(/MMM/)) result = result.replace(/MMM/, \"M\");\n else if (result.match(/MM/)) result = result.replace(/MM/, \"mm\");\n else if (result.match(/M/)) result = result.replace(/M/, \"m\");\n\n if (result.match(/yyyy/)) result = result.replace(/yyyy/, \"yy\");\n else if (result.match(/yy/)) result = result.replace(/yy/, \"y\");\n\n if (result.match(/dddd/)) result = result.replace(/dddd/, \"DD\");\n else if (result.match(/ddd/)) result = result.replace(/ddd/, \"D\");\n }\n } catch (e) {\n result = 'yy/mm/dd' // this would make sure it is parsable by C# as it is actually yyyy/mm/dd\n }\n if (sample) {\n try {\n if (!hasTime) var date = $.datepicker.parseDate(result, sample);\n } catch (e) {\n result = 'yy/mm/dd' // if it cannot be parsed, fallback to this\n }\n }\n return hasTime ? ((longFormat ? ServerDateFormat.shortFormat : result.replace(/yy/, 'Y').replace(/mm/, 'm').replace(/dd/, 'd')) + (notime ? '' : ' H:i' + (ampm ? ' A' : ''))) : result;\n}",
"function getFormattedDate(text) {\n\tvar tokenizedText = text.split(\",\");\n\tvar month = tokenizedText[1].split(\" \")[1]; // \"March\"\n\tvar day = tokenizedText[1].split(\" \")[2]; // \"5\"\n\tvar year = tokenizedText[2].split(\" \")[1]; // \"2014\"\n\tvar time = tokenizedText[2].split(\" \")[3]; // \"2:20\"\n\tvar ampm = tokenizedText[2].split(\" \")[4]; // \"PM\"\n\t/* format month in numerals */\n\tswitch(month) {\n\t\tcase \"January\": \tmonth = \"01\"; break;\n\t\tcase \"February\": month = \"02\"; break;\n\t\tcase \"March\": month = \"03\"; break;\n\t\tcase \"April\": month = \"04\"; break;\n\t\tcase \"May\": month = \"05\"; break;\n\t\tcase \"June\": month = \"06\"; break;\n\t\tcase \"July\": month = \"07\"; break;\n\t\tcase \"August\": month = \"08\"; break;\n\t\tcase \"September\": month = \"09\"; break;\n\t\tcase \"October\": month = \"10\"; break;\n\t\tcase \"November\": month = \"11\"; break;\n\t\tcase \"December\": month = \"12\"; break;\n\t}\n\t/* prepend 0 to day if necessary */\n\tif (day.length == 1)\n\t\tday = \"0\" + day;\n\n\t/* convert to 24 hour format */\n\tif (ampm == \"PM\") {\n\t\tvar timeTokenized = time.split(\":\");\n\t\tvar hours = +timeTokenized[0] + 12;\n\t\ttime = hours + \":\" + timeTokenized[1];\n\t}\n\t/* prepend 0 to time if necessary */\n\tif (time.length == 4)\n\t\ttime = \"0\" + time;\n\n\treturn (year + \"-\" + month + \"-\" + day + \"T\" + time);\n}",
"function DataTimeFormatting(inputdate)\n{\n var date=inputdate.split('T')[0]\n date=date.split('-')[1]+\"/\"+date.split('-')[2]+\"/\"+date.split('-')[0]\n if(inputdate.split('T')[1].includes('+'))\n {\n var time=inputdate.split('T')[1].split('+')[0]\n time=time.split(':')[0]+\":\"+time.split(':')[1]\n }\n else\n {\n var time=inputdate.split('T')[1].split('-')[0]\n time=time.split(':')[0]+\":\"+time.split(':')[1]\n }\n\n return date;\n //return date+\" \"+time;\n}",
"function fmtDate(date){\n var res = \"\";\n res = date.substring(0,4)+\"/\"+date.substring(4,6)+\"/\"+date.substring(6,8);\n res = res + \" 06:00:00\";\n return res;\n }",
"function stfrtimeFormat(date, mask, gmt = false) {\n date = date ? new Date(date) : new Date;\n if (isNaN(date)) return false;\n\n mask = String(mask);\n\n let token = /(%A)|(%a)|(%D)|(%d)|(%e)|(%j)|(%u)|(%w)|(%U)|(%V)|(%W)|(%b)|(%h)|(%B)|(%m)|(%C)|(%g)|(%G)|(%y)|(%Y)|(%H)|(%k)|(%I)|(%l)|(%M)|(%p)|(%P)|(%r)|(%R)|(%S)|(%T)|(%X)|(%z)|(%Z)|(%c)|(%F)|(%s)|(%x)/g;\n let timezone = /\\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\\d{4})?)\\b/g;\n let timezoneClip = /[^-+\\dA-Z]/g;\n\n let day_label = [\n \"dim.\", \"lun.\", \"mar.\", \"mer.\", \"jeu.\", \"ven.\", \"sam.\",\n \"dimanche\", \"lundi\", \"mardi\", \"mercredi\", \"jeudi\", \"vendredi\", \"samedi\"\n ];\n let month_label = [\n \"jan.\", \"févr.\", \"mars\", \"avril\", \"mai\", \"juin\", \"juil.\", \"août\", \"sept.\", \"oct.\", \"nov.\", \"dec.\",\n \"Janvier\", \"Février\", \"Mars\", \"Avril\", \"Mai\", \"Juin\", \"Juillet\", \"Août\", \"Septembre\", \"Octobre\", \"Novembre\", \"Décembre\"\n ];\n\n let get = gmt ? \"get\" : \"getUTC\";\n let d = date[ get + \"Date\"](),\n day = date[ get + \"Day\"](),\n month = date[ get + \"Month\"](),\n year = date[ get + \"FullYear\"](),\n hour = date[ get + \"Hours\"](),\n min = date[ get + \"Minutes\"](),\n sec = date[ get + \"Seconds\"](),\n offset = gmt ? 0 : date.getTimezoneOffset();\n\n let flags = {\n '%a': day_label[day], // day of the week (short)\n '%A': day_label[day + 7], // day of the week\n '%d': pad(d), // day in two digits\n '%e': d, // day\n '%j': '', // day of the year in third digits\n '%u': day, // day of the week (0 to 6, 0 for sunday)\n '%w': (day === 0 ? 7 : day+1), // day of the week with ISO-8601 norm (1 to 7, 1 for monday)\n '%U': '', // number of the week (1 = first complet week)\n '%V': '', // day of the week with ISO-8601 norm (0 to 6, 10for monday)\n '%W': '', // number of the week (1 = first monday)\n '%b': month_label[month], // month (short)\n '%h': month_label[month], // month (short)\n '%B': month_label[month + 12], // month\n '%m': pad(month + 1), // number of the month (in two digits)\n '%C': parseInt(year*100), // century\n '%g': String(year).slice(2), // year in two digits\n '%y': String(year).slice(0, 2), // year in two digits\n '%Y': year, // year in four digits\n '%H': pad(hour), // 24h formatted hour in two digits\n '%k': hour, // 24 formatted hour\n '%I': pad(hour % 12 || 12), // 12h formatted hour in two digits\n '%l': hour % 12 || 12, // 12h formatted hour\n '%M': pad(min), // minuts in two digits\n '%p': hour < 12 ? \"AM\" : \"PM\", // upper case ante and post meridian\n '%P': hour < 12 ? \"am\" : \"pm\", // lower case ante and post meridian\n '%R': pad(hour)+\":\"+pad(min), // same as \"%H:%M\"\n '%S': pad(sec), // seconds in two digits\n '%T': pad(hour)+\":\"+pad(min)+\":\"+pad(sec), // same as \"%H:%M:%S\"\n '%X': '', // hour in local format\n '%z': (offset > 0 ? \"-\" : \"+\") + pad(Math.floor(Math.abs(offset) / 60) * 100 + Math.abs(offset) % 60, 4), // time difference with greenwich time ( ex : +0200 )\n '%Z': gmt ? (String(date).match(timezone) || [\"\"]).pop().replace(timezoneClip, \"\") : \"UTC\", // time zone identifier\n '%c': '', // date and hour in local format\n '%D': pad(month + 1)+\"/\"+pad(d)+\"/\"+String(year).slice(0, 2), // same as \"%m/%d/%y\"\n '%F': String(year).slice(0, 2)+\"-\"+pad(month + 1)+\"-\"+pad(d), // same as \"%y-%m-%d\"\n '%s': '', // second in UNIX format\n '%x': '' // date in local format\n };\n\n function pad(value, length) {\n value = String(value);\n length = length || 2;\n while (value.length < length) value = \"0\" + value;\n return value;\n }\n\n return mask.replace(token, function (flag) {\n return flag in flags ? flags[flag] : flag.slice(1, flag.length - 1);\n });\n}",
"function date2str(xDate, xFormat) {\r\n //use this map to find parts of date/time string value\r\n\tvar dMap = {\r\n\t\tM: xDate.getMonth() + 1,\r\n\t\tMMM: xDate.toString().split(\" \")[1].slice(0,3),\r\n\t\td: xDate.getDate(),\r\n\t\tddd: xDate.toString().split(\" \")[0].slice(0,3),\r\n\t\tH: xDate.getHours(), //24-hr\r\n\t\th: xDate.getHours()>12 ? xDate.getHours()-12 : ( xDate.getHours()==0 ? 12 : xDate.getHours() ), //12-Hr\r\n\t\ta: xDate.getHours()>=12 ? \"PM\" : \"AM\",\r\n\t\tm: xDate.getMinutes(),\r\n\t\ts: xDate.getSeconds(),\r\n\t\ty: xDate.getFullYear()\r\n\t};\r\n\t//replace any uppercase format letters to lowercase (excluding case sensitive ones like H/h and M/m)\r\n\txFormat = xFormat.replace(/Y/g, 'y'); //change to lowercase 'y' for year\r\n\txFormat = xFormat.replace(/D/g, 'd'); //change to lowercase 'd' for day\r\n\txFormat = xFormat.replace(/S/g, 's'); //change to lowercase 's' for second\r\n\txFormat = xFormat.replace(/A/g, 'a'); //change to lowercase 'a' for am/pm\r\n\r\n\tlet xDateOut = xFormat.replace(/(M+|d+|h+|H+|m+|s+|a+|y+)/g, function(v) {\r\n\t\t//Check for string output for Month or Day with length >= 3\r\n\t\tif (v.length>=3 && (v.slice(-1)==\"M\" || v.slice(-1)==\"d\")) {\r\n\t\t\treturn dMap[v.slice(0,3)];\r\n\t\t} else { //all numeric output\r\n\t\t\treturn ((v.length > 1 ? \"0\" : \"\") + dMap[v.slice(-1)]).slice( v.slice(-1)==\"y\" ? -v.length : -2 );\r\n\t\t}\r\n\t});\r\n\treturn xDateOut;\r\n}",
"function formatTimeAndDate(time) {\n var data = time.split('T');\n return {\n date: data[0],\n time: data[1]\n }\n\n}",
"function getFormattedDate() {\n return \"[\" + new Date().toISOString().replace(/T/, ' ').replace(/\\..+/, '') + \"] \";\n}",
"function getFormattedDateTimedddMMMddYYYYhhmmssTT(dateObj) {\n var d = new Date(dateObj);\n return d.toDateString().replaceNth(' ', ', ', 3) + ' ' + getFormattedTimeSSAmPm(d);\n}",
"function dateAndTimeFormatConversionFunction(dateAndTime, timezone, wishedDateAndTimeFormat = \"timestamp\") {\n\n // Declaration of the 'convertedDateAndTime' variable which will contain the date and time (datetime) converted in the wished format...\n var convertedDateAndTime;\n\n // Adding the number of seconds contained in the 'timezone' variable (which corresponds to the indicated timezone) to the 'dateAndTime' variable...\n dateAndTime = (dateAndTime + timezone) * 1000;\n\n // If the wished date and time is \"timestamp\"... \n if(wishedDateAndTimeFormat != \"timestamp\") {\n\n // Conversion of 'dateAndTime' timestamp as a JS Date object...\n var dateAndTimeASJSDate = new Date(dateAndTime);\n\n // If the number of date is less than 9 or equal to 9, so...\n if(dateAndTimeASJSDate.getUTCDate() <= 9) {\n\n // A '0' is added to the final value of date...\n var date = \"0\" + dateAndTimeASJSDate.getUTCDate();\n\n // Else...\n } else {\n\n // The final value of date is ready...\n var date = dateAndTimeASJSDate.getUTCDate();\n }\n\n // Getting the exactly issue of month...\n var month = dateAndTimeASJSDate.getUTCMonth() + 1;\n\n // If the number of month is less than 9 or equal to 9, so...\n if(month <= 9) {\n\n // A '0' is added to the final value of month...\n month = \"0\" + month;\n }\n\n // The final value of year is ready...\n var year = dateAndTimeASJSDate.getUTCFullYear();\n\n // If the number of hours is less than 9 or equal to 9, so...\n if(dateAndTimeASJSDate.getUTCHours() <= 9) {\n\n // A '0' is added to the final value of hours...\n var hours = \"0\" + dateAndTimeASJSDate.getUTCHours();\n\n // Else...\n } else {\n\n // The final value of hours is ready...\n var hours = dateAndTimeASJSDate.getUTCHours();\n }\n\n // If the number of minutes is less than 9 or equal to 9, so...\n if(dateAndTimeASJSDate.getUTCMinutes() <= 9) {\n\n // A '0' is added to the final value of minutes...\n var minutes = \"0\" + dateAndTimeASJSDate.getUTCMinutes();\n\n // Else...\n } else {\n\n // The final value of minutes is ready...\n var minutes = dateAndTimeASJSDate.getUTCMinutes();\n }\n\n // If the number of seconds is less than 9 or equal to 9, so...\n if(dateAndTimeASJSDate.getUTCSeconds() <= 9) {\n\n // A '0' is added to the final value of seconds...\n var secondes = \"0\" + dateAndTimeASJSDate.getUTCSeconds();\n\n // Else...\n } else {\n\n // The final value of seconds is ready...\n var secondes = dateAndTimeASJSDate.getUTCSeconds();\n }\n\n // In the case \"DD/MM/YYYY HH:mm:ss\" is choosen as wished date and time format...\n if(wishedDateAndTimeFormat === \"DD/MM/YYYY HH:mm:ss\") {\n\n // Affectation of 'dateAndTime''s time to 'convertedDateAndTime'...\n convertedDateAndTime = date + \"/\" + month + \"/\" + year + \" \" + hours + \":\" + minutes + \":\" + secondes;\n\n // In the case \"YYYY/MM/DD HH:mm:ss\" is choosen as wished date and time format...\n } else if(wishedDateAndTimeFormat === \"YYYY/MM/DD HH:mm:ss\") {\n\n // Affectation of 'dateAndTime''s time to 'convertedDateAndTime'...\n convertedDateAndTime = year + \"/\" + month + \"/\" + date + \" \" + hours + \":\" + minutes + \":\" + secondes;\n\n // In the case \"MM/DD/YYYY HH:mm:ss\" is choosen as wished date and time format...\n } else if(wishedDateAndTimeFormat === \"MM/DD/YYYY HH:mm:ss\") {\n\n // Affectation of 'dateAndTime''s time to 'convertedDateAndTime'...\n convertedDateAndTime = month + \"/\" + date + \"/\" + year + \" \" + hours + \":\" + minutes + \":\" + secondes;\n\n // In the case \"HH:mm:ss\" is choosen as wished date and time format...\n } else if(wishedDateAndTimeFormat === \"HH:mm:ss\") {\n\n // Affectation of 'dateAndTime''s time to 'convertedDateAndTime'...\n convertedDateAndTime = hours + \":\" + minutes + \":\" + secondes;\n\n // Else...\n } else {\n\n // Message to tell some things in the console...\n console.log(\"\\x1b[31m\" + \"Unknown format, so the date and the time are kept as timestamp...\" + \"\\x1b[0m\");\n\n // Affectation of 'dateAndTime' to 'convertedDateAndTime'...\n convertedDateAndTime = dateAndTime;\n }\n\n // Else...\n } else {\n\n // Message to tell some things in the console...\n console.log(\"\\x1b[31m\" + \"Date and time already in timestamp...\" + \"\\x1b[0m\");\n\n // Affectation of 'dateAndTime' to 'convertedDateAndTime'...\n convertedDateAndTime = dateAndTime;\n }\n\n // Returning the converted date and time (datetime) in the variable 'convertedDateAndTime'...\n return convertedDateAndTime;\n}",
"function formatDateTime(d)\n {\n var result = d.getFullYear()+'-'+Expand(d.getMonth()+1,2)+'-'+Expand(d.getDate(),2)+'--'+\n Expand(d.getHours(),2)+'-'+Expand(d.getMinutes(), 2)+'-'+Expand(d.getSeconds(),2);\n return result;\n }",
"function formatDateTime(value, format) {\n var index = 0;\n var output = \"\";\n var ampm = format.contains(\"AM/PM\");\n var hours = 0;\n var date;\n if (!(value instanceof Date)) {\n date = new Date(value);\n }\n else {\n date = value;\n }\n while (index < format.length) {\n var fmt = format.substr(index);\n if (fmt.startsWith(\"mmmm\")) {\n //---- full month name ----\n var str = monthNames[date.getMonth()];\n output += str;\n index += 4;\n }\n else if (fmt.startsWith(\"mmm\")) {\n //---- 3 letter month abbreviaton ----\n var str = monthAbbrevs[date.getMonth()];\n output += str;\n index += 3;\n }\n else if (fmt.startsWith(\"mm\")) {\n //---- 2 digit minutes ----\n var str = N2(date.getMinutes());\n output += str;\n index += 2;\n }\n else if (fmt.startsWith(\"m\")) {\n //---- 1-2 digit day month number (1-relative) ----\n var str = (date.getMonth() + 1) + \"\";\n output += str;\n index += 1;\n }\n else if (fmt.startsWith(\"q\")) {\n //---- 1 digit QUARTER number (1-relative) ----\n var str = (Math.floor(date.getMonth() / 3) + 1) + \"\";\n output += str;\n index += 1;\n }\n else if (fmt.startsWith(\"dddd\")) {\n //---- full day of week ----\n var str = dayNames[date.getDay()];\n output += str;\n index += 4;\n }\n else if (fmt.startsWith(\"ddd\")) {\n //---- 3 letter day abbreviaton ----\n var str = dayAbbrevs[date.getDay()];\n output += str;\n index += 3;\n }\n else if (fmt.startsWith(\"dd\")) {\n //---- 2 digit day-of-month ----\n var str = N2(date.getDate());\n output += str;\n index += 2;\n }\n else if (fmt.startsWith(\"d\")) {\n //---- 1-2 digit day of month ----\n var str = date.getDate() + \"\";\n output += str;\n index += 1;\n }\n else if (fmt.startsWith(\"yyyy\")) {\n //---- 4 digit year ----\n var str = date.getFullYear() + \"\";\n output += str;\n index += 4;\n }\n else if (fmt.startsWith(\"yy\")) {\n //---- 2 digit year----\n var str = (date.getFullYear() + \"\").substr(2); // drop first 2 chars\n output += str;\n index += 3;\n }\n else if (fmt.startsWith(\".0\")) {\n //---- milliseconds as fraction ----\n var str = (date.getMilliseconds() / 1000) + \"\";\n output += str;\n index += 2;\n }\n else if (fmt.startsWith(\"ss\")) {\n //---- 2 digit seconds ----\n var str = N2(date.getSeconds());\n output += str;\n index += 2;\n }\n else if (fmt.startsWith(\"s\")) {\n //---- 1-2 digit seconds ----\n var str = date.getSeconds() + \"\";\n output += str;\n index += 1;\n }\n else if (fmt.startsWith(\"hh\")) {\n //---- 2 digit hours ----\n hours = date.getHours();\n var hrs = getHours(hours, ampm);\n var str = N2(hrs);\n output += str;\n index += 2;\n }\n else if (fmt.startsWith(\"h\")) {\n //---- 1-2 digit hours ----\n hours = date.getHours();\n var hrs = getHours(hours, ampm);\n var str = hrs + \"\";\n output += str;\n index += 1;\n }\n else if (fmt.startsWith(\"AM/PM\")) {\n //---- AM/PM indicator ----\n var str = (hours > 11) ? \"PM\" : \"AM\";\n output += str;\n index += 5;\n }\n else {\n //---- copy a literal char ----\n output += fmt[0];\n index += 1;\n }\n }\n return output;\n }",
"getFormattedDate(event) {\n console.log(event[\"startDate\"]);\n let arr = event[\"startDate\"].split(' ');\n let arr2 = arr[0].split('-');\n let arr3 = arr[1].split(':');\n let date = new Date(arr2[0] + '-' + arr2[1] + '-' + arr2[2] + 'T' + arr3[0] + ':' + arr3[1] + '-05:00');\n return date;\n }",
"function getFormattedDateTimedddMMMddYYYYhhmmTT(dateObj) {\n var d = new Date(dateObj);\n return d.toDateString().replaceNth(' ', ', ', 3) + ' ' + getFormattedTimeAmPm(d);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
verifies if password passes comp8 requirements, Boolean return | function comp8(str) {
const len_req = 8;
if (str.length != len_req) {
if (debug_on) {
console.log("Password len " + str.length + " != " + len_req);
}
return false;
}
let has_upper = false, has_lower = false, has_symbol = false, has_number = false;
for (let i = 0; i < str.length; i++) {
let c = str.charCodeAt(i);
if (c >= 48 && c <= 57) {
has_number = true;
}
else if (c >= 65 && c <= 90) {
has_upper = true;
}
else if (c >= 97 && c <= 122) {
has_lower = true;
}
// the rest in this range are symbols
else if (c >= 32 && c <= 127) {
has_symbol = true;
}
}
if (has_upper && has_lower && has_symbol && has_number ) {
if (debug_on) { console.log("Password is valid comprehensive8."); }
return true;
}
if (debug_on) { console.log("Password is not valid comprehensive8."); }
return false;
} | [
"function isValidPassword(password) {\n if (password.length >= 8) {\n return true;\n }\n return false;\n }",
"function isValidPassword(pwd) {\r\n return pwd.length >= 8;\r\n}",
"function validatePassword() {\n var _password = getPassword();\n var _confirmPassword = getConfirmPassword();\n var _pwd = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])/;\n\n if (_password === \"\" || _confirmPassword === \"\") {\n return false;\n }\n\n if (_password !== _confirmPassword) {\n return false;\n }\n\n if (_password.length < 8) {\n return false;\n }\n\n if (_pwd.test(_password) == false) {\n return false;\n }\n\n return true;\n}",
"function goodPassword(password) {return (password.includes(\"#\") || password.includes(\"!\") || password.includes(\"$\")) && !(password.includes(\"password\")) && password.length > 5 && hasNumber(password) && pwCaps(password)}",
"function checkPassword(str)\r\n{\r\n\tif (str.length >= 8)\r\n\t return true\r\n\telse\r\n\t return false\r\n}",
"function checkPassword() {\n if (this.value.length >= 8) {\n setAccepted('password-validated');\n } else {\n setUnaccepted('password-validated');\n }\n}",
"function isStrongPwd(password) {\n\n var uppercase = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n var lowercase = \"abcdefghijklmnopqrstuvwxyz\";\n\n var digits = \"0123456789\";\n\n var splChars = \"!@#$%&*()\";\n\n var ucaseFlag = contains(password, uppercase);\n\n var lcaseFlag = contains(password, lowercase);\n\n var digitsFlag = contains(password, digits);\n\n var splCharsFlag = contains(password, splChars);\n\n if (password.length >= 8 && ucaseFlag && lcaseFlag && digitsFlag && splCharsFlag)\n return true;\n else\n return false;\n\n }",
"checkLength(password)\n {\n var minimumLength = 8; //Change this variable to change password length requirement\n return password.length >= minimumLength;\n }",
"function isValidPassword(password) {\n var passLength = password.length;\n var passcontainWord = password.includes('password');\n \n // if (passLength > 8 && !passcontainWord) {\n // return true\n // } else {\n // return false;\n // }\n\n return passLength > 8 && !passcontainWord;\n}",
"isCorrectPassword(passwd) {\n return this.password === encrypt(passwd);\n }",
"function isValidPassword(pass){\n return pass.length >= 8 && !pass.includes('password');\n}",
"function passwordLongEnough(password){\n\n\tif (password.length>8){return true}\n\t\treturn false\n\n\tif(password.length>8){\n\t\treturn true\n\t}\n\n\n}",
"function validPassword(d) {return (d.includes(\"!\") || d.includes(\"#\") || d.includes(\"&\")) && (!d.includes(\"password\") && !d.includes(\"PASSWORD\") && !d.includes(\"password!\") && !d.includes(\"password#\") && !d.includes(\"password$\")) && checkCase(d) && digit(d) && d.length > 5;}",
"function validar_password(password){\r\n\tvar regex2 = /(?=.*[A-Z])+(?=.*[0-9])+(?=.{8,})/;\r\n\treturn regex2.test(password) ? true : false;\r\n}",
"function validatePassword(password) {\n var re = /^((?=.*[A-Z])(?=.*\\d)\\S{8,})$/i;\n return re.test(password);\n}",
"function passwordLongEnough(password){\n\tif(password.length >=8){\n\t\treturn true\n\t}\n}",
"function pwLongEnough(password){\n\tif(password.length >= 8){\n\t\treturn true;\n\t}\n\treturn false;\n}",
"function passwordValidity(password)\n{\n //regex untuk memvalidasi passwword\n let regex = /([0-9]{1}[A-Z]{5}[-@!$%#^&*()_+|~=`{}\\[\\]:\";'<>?,.\\/]{1})/;\n\n//untuk mengembalikan true/false\n return regex.test(password)\n}",
"function areValidCredentials(name, password) {\n // your code here\n if(name.length > 3 && password.length >= 8 ) {\n return true;\n }\n return false;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
if on last image, disable next button | function disableNext() {
if (img_counter == images.length - 1) {
next_btn.disabled = true;
} else {
next_btn.disabled = false;
}
} | [
"handleNextClick() {\n this.nextButton.current.disabled = true;\n this.setNextPhotoActive();\n }",
"showPrevImage(e) {\n this.index--;\n this.img.src = this.imgArr[this.index];\n this.nextButton.disabled = false;\n\n if (this.index === 0) {\n this.prevButton.disabled = true;\n }\n }",
"function disable_next( )\n{\n $( \"#paging-last\" ).prop( 'disabled', 'true' );\n $( \"#paging-next\" ).prop( 'disabled', 'true' );\n}",
"function disablePrev() {\n if (img_counter == 0) {\n prev_btn.disabled = true;\n } else {\n prev_btn.disabled = false;\n }\n}",
"function next() {\n count++; // next e click korle index 1 kore barbe \n\n if (count >= photos.length) { // total length index[3] hole bha soman hole abr zero thake count hbe\n count = 0;\n imgTag.src = photos[count];\n }else{\n imgTag.src = photos[count];\n }\n \n}",
"function next() {\n\t\t\tgoToImage((curImage+1 > numImages-1 ? 0 : curImage+1), next, true);\n\t\t}",
"function nextImage() {\n\tIMAGE_CURRENT++;\n\tif(IMAGE_CURRENT > image.length - 1){\n\t\tIMAGE_CURRENT = 0;\n\t}\n\tshowImage();\n}",
"function nextPic(){\n\n var el={}, id={};\n\n // last pic in the shown pics\n el.lastPic = $('.image_carousel .carousel-content *[class$=showPic]').last();\n id.pic = el.lastPic.attr('id');\n\n var onlyId = id.pic.split('_')[1];\n showPic_details(onlyId);\n // alert('nextPic-details = '+onlyId +' id.pic = '+id.pic+' lastid.pic = '+lastPic_id);\n\n if(id.pic != lastPic_id)\n {\n first_pozPic +=3;\n\n /*=============================[ show next pics]==============================================*/\n\n el.lastPic.prevAll().removeClass('showPic');\n\n el.nextall = el.lastPic.nextAll().slice(0,3);\n el.nextall.addClass('showPic');\n\n /*=============================[ prev - next buttons]==============================================*/\n id.set_lastpic = el.nextall.last().attr('id');\n if(id.set_lastpic == lastPic_id)\n $('.image_carousel #cars_next').addClass('disabled');\n\n $('.image_carousel #cars_prev').removeClass('disabled');\n\n }\n\n\n}",
"_nextImg() {\n this._index = (this._index + 1) % this._imgs.length\n this._showImg()\n }",
"function nextImage() {\n if (imageIndex < 2) {\n setImageIndex(imageIndex + 1);\n } else {\n setImageIndex(0);\n }\n }",
"function enable_next( )\n{\n $( \"#paging-last\" ).prop( 'disabled', 'false' );\n $( \"#paging-next\" ).prop( 'disabled', 'false' );\n}",
"function thumb_next() {\n\tremove_watermark();\n\tif ($('#container').find('.thumb_current').length > 0) {\n\t\t$nb_thumb = $('#container').find('.thumb').length;\n\t\t$index = $('.thumb_current').index();\n\t\t$index++;\n\t\tif ($index < $nb_thumb) { //Goto next\n\t\t\t$item_next = $('#container').children()[$index];\n\t\t\t$('.thumb_current').removeClass('thumb_current');\n\t\t\t$item_next.className += ' thumb_current';\n\t\t\tthumb_adjust_container_position();\n\t\t\treturn true; //We have move\n\t\t} else {\n\t\t\treturn false; //We do not move\n\t\t}\n\t}\n }",
"function disableNextButton() {\n $(\"#next-button\").prop(\"disabled\", true);\n }",
"function myNext(){\r\n for (var i = 0; i < buttons.length; i++) { \r\n if (buttons[i].className == \"on\") {\r\n buttons[i].className = \"\";\r\n break;\r\n }\r\n }\r\n\r\n if (index < gallery.length - 1) {\r\n buttons[index + 1].className = \"on\";\r\n index += 1;\r\n apple_festival.src = 'images/' + gallery[index];\r\n }else{\r\n index = 0;\r\n apple_festival.src = 'images/' + gallery[index];\r\n buttons[0].className = \"on\";\r\n }\r\n}",
"setNextPhotoActive() {\n let newIndex;\n if (this.state.activeIndex === images.length - 1) {\n newIndex = 0;\n } else {\n newIndex = this.state.activeIndex + 1;\n }\n\n // Update the currently active photo and enable the next button\n this.setState(\n {\n activeIndex: newIndex\n },\n () => {\n this.nextButton.current.disabled = false;\n }\n );\n }",
"renderNextButton() {\n if (this.props.currentImage === this.props.images.length - 1) return;\n return (\n <button onClick={this.props.onNext} className=\"lightbox--arrow next\">\n <i className=\"fa fa-angle-right\"></i>\n </button>\n )\n }",
"function gallery_next() {\n\tif ($('#container').find('.thumb_current').length > 0) {\n\t\tvar nb_thumb = $('#container').find('.thumb').length;\n\t\tvar index = $('.thumb_current').index();\n\t\tindex++;\n\t\tif (index < nb_thumb) { //Goto next\n\t\t\titem_next = $('#container').children()[index];\n\t\t\t$('.thumb_current').removeClass('thumb_current');\n\t\t\titem_next.className += ' thumb_current';\n\t\t\tgallery_adjust_container_position();\n\t\t\treturn true; //We have move\n\t\t} else {\n\t\t\treturn false; //We do not move\n\t\t}\n\t}\n }",
"function disablePrevNextButton() {\n let lastElement = $('.pagination a:nth-child(6)');\n let firstElement = $('.pagination a:nth-child(2)');\n\n lastElement.hasClass('active') ?\n $('.nextButton').addClass('disable') :\n $('.nextButton').removeClass('disable');\n firstElement.hasClass('active') ?\n $('.previousButton').addClass('disable') :\n $('.previousButton').removeClass('disable');\n}",
"function enableNextButton() {\n $(\"#next-button\").prop(\"disabled\", false);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
release the select dom object | function __releaseSelects($dom) {
if (_floatGFrame!=null) {
_floatGFrame.style.display = "none";
}
} | [
"function releaseMapSelection() {\n\t\tif (this.selectedNetworkElements != null) {\n\t\t\tfor (var i = 0; i < this.selectedNetworkElements.getLength(); i++) {\n\t\t\t\tthis.selectedNetworkElements.get(i).unselect();\n\t\t\t}\n\t\t}\n\t\tif (this.dottedSelection != null) {\n\t\t\tthis.dottedSelection.release();\n\t\t}\n\t\tthis.selectedNetworkElements = null;\n\t\tthis.selection.release();\n\t\tthis.dottedSelection = null;\n\t}",
"function releaseDottedSelection() {\n\t\tdocument.body.removeChild(document.getElementById(this.id));\n\t}",
"exitSelectElement(ctx) {\n\t}",
"unselect(domEl) {\n if ( !domEl ) return;\n domEl.removeClass('selected');\n }",
"visualUnselect() {\n if (!this.domSelected)\n return;\n this.domSelected.removeAttribute('selected');\n this.domSelected.tabIndex = -1;\n this.domSelected = undefined;\n }",
"exitSelectElements(ctx) {\n\t}",
"function deselectAll() {\n lastSelectedElement(true, null);\n}",
"unselect(){\n this.selected = null;\n }",
"unselect() {\n if (this.selected) {\n this.selected = false;\n this.fontColor = this.fontColorUnselected;\n if (this.cursor) {\n this.removeChild(this.cursor);\n this.cursor = false;\n }\n }\n }",
"function destroySelectMode(display) {\n// clear selected stuff\n\t$(\".ui-selected\", display).removeClass(\"ui-selected\")\n\tdisplay.selectable('destroy');\t\n}",
"function clearSelectOptionsFast(id) {\n var select = document.getElementById('idtoClean')\n var selectParentNode = select.parentNode\n var newSelectObj = select.cloneNode(false)\n selectParentNode.replaceChild(newSelectObj, select)\n //Use this line if you don't want use a return reference function \n //select = newSelectObj\n return newSelectObj\n}",
"function encerrarAreaSelect() {\n\tareaSelect.off(\"change\");\n\tremoverConsultas();\n\tareaSelect.remove();\n\tareaSelect = null;\n}",
"function depopulateGroups(){\n $('#group_select').html('');\n }",
"function closeSelect(){\n $(\".elementSelect\").select2(\"close\");\n $(\".supplierSelect\").select2(\"close\")\n}",
"static removeSelect(element){\n\t\tdelete objectPrimary.store[element.hammerObject.element.id];\n\t\telement.hammerObject.element.classList.remove(\"animationSelected\");\n\t }",
"function del_select_next(){\n\tcurrent=$(\".select\");\n\tselect_next();\n\tcurrent.hide();\n\tcurrent.remove();\n}",
"@action\n resultsBoxDestroy() {\n this.resultsElement = null;\n this.hasSelected = false;\n }",
"unselect() {\n this.selected = false;\n }",
"function deselect() {\n\n\t\tvar filter = document.getElementsByClassName('filter')[0];\n\n\t\tif (filter.childNodes.length > 0) {\n\t\t\t// delete selected month\n\t\t\tfilter.removeChild(filter.childNodes[0]);\n\n\t\t\t// update all other visualizations\n\t\t\tupdatedSpending();\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
generate a path by following the grid | function createPath({ start, grid, stepCount }) {
const path = [start];
let current = start;
let next = null;
const findNext = ({ current, grid }) => {
const { x, y } = current;
const candidates = grid.filter(
(pt) =>
(pt.x === x && Math.abs(pt.y - y) === config.dotSpacing) ||
(pt.y === y &&
Math.abs(pt.x - x) === config.dotSpacing &&
!path.includes(pt))
);
return pickFromGrid(candidates);
};
for (let i = 0; i < stepCount; i++) {
next = findNext({ current, grid });
if (next) {
path.push(next);
current = next;
} else {
return null;
}
}
return path;
} | [
"function drawDjikstraPath()\n {\n for(let i = 1; i < path.length; i++)\n {\n let gridIndex = rcToIndex(path[i].first, path[i].second , gridRowSize);\n $('.cell').eq(gridIndex).html('<div class=\"marker_path bg-dark\"></div>'); \n }\n\n }",
"function draw_grid() \n {\n var hLines = new Path();\n for(var i=0; i<GRID_SIZE; i = i+2)\n {\n hLines.add(new Point(0, i*CELL_SIZE));\n hLines.add(new Point(GRID_SIZE*CELL_SIZE, i*CELL_SIZE));\n hLines.add(new Point(GRID_SIZE*CELL_SIZE, i*CELL_SIZE+CELL_SIZE));\n hLines.add(new Point(0, i*CELL_SIZE+CELL_SIZE));\n }\n hLines.style = {\n strokeColor: 'black'\n };\n\n var vLines = new Path();\n for(var i=0; i<GRID_SIZE; i = i+2)\n {\n vLines.add(new Point(i*CELL_SIZE, 0));\n vLines.add(new Point(i*CELL_SIZE, GRID_SIZE*CELL_SIZE));\n vLines.add(new Point(i*CELL_SIZE+CELL_SIZE, GRID_SIZE*CELL_SIZE));\n vLines.add(new Point(i*CELL_SIZE+CELL_SIZE, 0));\n }\n vLines.style = {\n strokeColor: 'black'\n };\n \n }",
"function tracePath(grid, j, i) {\n var maxj = grid.length;\n var p = [];\n var dxContour = [0, 0, 1, 1, 0, 0, 0, 0, -1, 0, 1, 1, -1, 0, -1, 0];\n var dyContour = [0, -1, 0, 0, 1, 1, 1, 1, 0, -1, 0, 0, 0, -1, 0, 0];\n var dx, dy;\n var startEdge = ['none', 'left', 'bottom', 'left', 'right', 'none', 'bottom', 'left', 'top', 'top', 'none', 'top', 'right', 'right', 'bottom', 'none'];\n var nextEdge = ['none', 'bottom', 'right', 'right', 'top', 'top', 'top', 'top', 'left', 'bottom', 'right', 'right', 'left', 'bottom', 'left', 'none'];\n var edge;\n\n var startCell = grid[j][i];\n var currentCell = grid[j][i];\n\n var cval = currentCell.cval;\n var edge = startEdge[cval];\n\n var pt = getXY(currentCell, edge);\n\n /* push initial segment */\n p.push([i + pt[0], j + pt[1]]);\n edge = nextEdge[cval];\n pt = getXY(currentCell, edge);\n p.push([i + pt[0], j + pt[1]]);\n clearCell(currentCell);\n\n /* now walk arround the enclosed area in clockwise-direction */\n var k = i + dxContour[cval];\n var l = j + dyContour[cval];\n var prev_cval = cval;\n\n while ((k >= 0) && (l >= 0) && (l < maxj) && ((k != i) || (l != j))) {\n currentCell = grid[l][k];\n if (typeof currentCell === 'undefined') { /* path ends here */\n //console.log(k + \" \" + l + \" is undefined, stopping path!\");\n break;\n }\n cval = currentCell.cval;\n if ((cval === 0) || (cval === 15)) {\n return { path: p, info: 'mergeable' };\n }\n edge = nextEdge[cval];\n dx = dxContour[cval];\n dy = dyContour[cval];\n if ((cval === 5) || (cval === 10)) {\n /* select upper or lower band, depending on previous cells cval */\n if (cval === 5) {\n if (currentCell.flipped) { /* this is actually a flipped case 10 */\n if (dyContour[prev_cval] === -1) {\n edge = 'left';\n dx = -1;\n dy = 0;\n } else {\n edge = 'right';\n dx = 1;\n dy = 0;\n }\n } else { /* real case 5 */\n if (dxContour[prev_cval] === -1) {\n edge = 'bottom';\n dx = 0;\n dy = -1;\n }\n }\n } else if (cval === 10) {\n if (currentCell.flipped) { /* this is actually a flipped case 5 */\n if (dxContour[prev_cval] === -1) {\n edge = 'top';\n dx = 0;\n dy = 1;\n } else {\n edge = 'bottom';\n dx = 0;\n dy = -1;\n }\n } else { /* real case 10 */\n if (dyContour[prev_cval] === 1) {\n edge = 'left';\n dx = -1;\n dy = 0;\n }\n }\n }\n }\n pt = getXY(currentCell, edge);\n p.push([k + pt[0], l + pt[1]]);\n clearCell(currentCell);\n k += dx;\n l += dy;\n prev_cval = cval;\n }\n\n return { path: p, info: 'closed' };\n}",
"function tracePath(grid, j, i){\n var maxj = grid.length;\n var p = [];\n var dxContour = [0, 0, 1, 1, 0, 0, 0, 0, -1, 0, 1, 1, -1, 0, -1, 0];\n var dyContour = [0, -1, 0, 0, 1, 1, 1, 1, 0, -1, 0, 0, 0, -1, 0, 0];\n var dx, dy;\n var startEdge = [\"none\", \"left\", \"bottom\", \"left\", \"right\", \"none\", \"bottom\", \"left\", \"top\", \"top\", \"none\", \"top\", \"right\", \"right\", \"bottom\", \"none\"];\n var nextEdge = [\"none\", \"bottom\", \"right\", \"right\", \"top\", \"top\", \"top\", \"top\", \"left\", \"bottom\", \"right\", \"right\", \"left\", \"bottom\", \"left\", \"none\"];\n var edge;\n\n var startCell = grid[j][i];\n var currentCell = grid[j][i];\n\n var cval = currentCell.cval;\n var edge = startEdge[cval];\n\n var pt = getXY(currentCell, edge);\n\n /* push initial segment */\n p.push([i + pt[0], j + pt[1]]);\n edge = nextEdge[cval];\n pt = getXY(currentCell, edge);\n p.push([i + pt[0], j + pt[1]]);\n clearCell(currentCell);\n\n /* now walk arround the enclosed area in clockwise-direction */\n var k = i + dxContour[cval];\n var l = j + dyContour[cval];\n var prev_cval = cval;\n\n while((k >= 0) && (l >= 0) && (l < maxj) && ((k != i) || (l != j))){\n currentCell = grid[l][k];\n if(typeof currentCell === 'undefined'){ /* path ends here */\n //console.log(k + \" \" + l + \" is undefined, stopping path!\");\n break;\n }\n cval = currentCell.cval;\n if((cval === 0) || (cval === 15)){\n return { path: p, info: \"mergeable\" };\n }\n edge = nextEdge[cval];\n dx = dxContour[cval];\n dy = dyContour[cval];\n if((cval === 5) || (cval === 10)){\n /* select upper or lower band, depending on previous cells cval */\n if(cval === 5){\n if(currentCell.flipped){ /* this is actually a flipped case 10 */\n if(dyContour[prev_cval] === -1){\n edge = \"left\";\n dx = -1;\n dy = 0;\n } else {\n edge = \"right\";\n dx = 1;\n dy = 0;\n }\n } else { /* real case 5 */\n if(dxContour[prev_cval] === -1){\n edge = \"bottom\";\n dx = 0;\n dy = -1;\n }\n }\n } else if(cval === 10){\n if(currentCell.flipped){ /* this is actually a flipped case 5 */\n if(dxContour[prev_cval] === -1){\n edge = \"top\";\n dx = 0;\n dy = 1;\n } else {\n edge = \"bottom\";\n dx = 0;\n dy = -1;\n }\n } else { /* real case 10 */\n if(dyContour[prev_cval] === 1){\n edge = \"left\";\n dx = -1;\n dy = 0;\n }\n }\n }\n }\n pt = getXY(currentCell, edge);\n p.push([k + pt[0], l + pt[1]]);\n clearCell(currentCell);\n k += dx;\n l += dy;\n prev_cval = cval;\n }\n\n return { path: p, info: \"closed\" };\n }",
"function solvePath(){\n var grid = cGrid;\n stepCount = 0; //resetStep\n startRow = 0;\n exitRow = grid.length-1;\n var point = {\n row: 0,\n col: 0\n };\n\n //1. Loop start row , find the start col and mark\n let startCol = point.col;\n for ( ;startCol < grid[startRow].length; startCol++){\n noEntry = true;\n if (grid[startRow][startCol] == colValues.OPEN){\n point.row = startRow;\n point.col = startCol;\n noEntry = false;\n break;\n }\n }\n if(noEntry){\n writeResults();\n return;\n }\n \n //2. loop and find open path and mark as walked\n do {\n let step = {};\n for( var direct in directions){\n step = movable(point, grid, direct);\n if(step.canMove && step.colValue == colValues.OPEN){\n //mark current step as walked , move and add step count\n grid[point.row][point.col] = colValues.PATH;\n document.getElementById(`${point.row}:${point.col}`).setAttribute(\"blockValue\", \"step\");\n point = getNextPoint(point, direct);\n stepCount ++;\n break;\n }\n }\n //3. Test exit condition\n if ( point.row == exitRow){\n exitReached = true;\n grid[point.row][point.col] = colValues.PATH;\n document.getElementById(`${point.row}:${point.col}`).setAttribute(\"blockValue\", \"step\");\n break;\n }\n } while(true);\n\n writeResults();\n}",
"_getLinePath() {\n const graph = this.graph;\n const width = graph.getWidth();\n const height = graph.getHeight();\n const tl = graph.getPoint({\n x: 0,\n y: 0\n });\n const br = graph.getPoint({\n x: width,\n y: height\n });\n const cell = this.cell;\n const flooX = Math.ceil(tl.x / cell) * cell;\n const flooY = Math.ceil(tl.y / cell) * cell;\n const path = [];\n for (let i = 0; i <= br.x - tl.x; i += cell) {\n const x = flooX + i;\n path.push([ 'M', x, tl.y ]);\n path.push([ 'L', x, br.y ]);\n }\n for (let j = 0; j <= br.y - tl.y; j += cell) {\n const y = flooY + j;\n path.push([ 'M', tl.x, y ]);\n path.push([ 'L', br.x, y ]);\n }\n return path;\n }",
"getPath(width = 100, height = 75) {\n const outletY = this.outletY(false);\n const path = ['M4,1']; // start top-left, after corner\n path.push(`L${width - 2},1`); // line to top-right\n path.push(`C${width - 0.3431},1 ${width + 1},2.34314575 ${width + 1},4`); // top-right corner\n path.push(\n `L${width + 1},${outletY - 8.5} L${width + 1},${outletY - 8.5} L${width +\n arrowWidth +\n 1},${outletY} L${width + 1},${outletY + 8.5} L${width + 1},${height -\n 2}`,\n ); // right side\n path.push(\n `C${width + 1},${height - 0.3431} ${width - 0.3431},${height +\n 1} ${width - 2},${height + 1}`,\n ); // bottom-right corner\n path.push(`L4,${height + 1}`); // line to bottom left\n\n path.push(`C2.34314575,${height + 1} 1,${height - 0.3431} 1,${height - 2}`); // bottom-left corner\n path.push(\n `L1,${outletY + 8.5} L1,${outletY + 8.5} L${arrowWidth +\n 1},${outletY} L1,${outletY - 8.5} L1,4`,\n ); // left side\n path.push('C1,2.34314575 2.34314575,1 4,1'); // top-left corner\n path.push('Z'); // end\n\n return path.join(' ');\n }",
"function robotPaths (grid) {\n var resultPath = [];\n var columnLength = grid.length - 1;\n var rowLength = grid[0].length - 1;\n\n function innerTraverseHelper(column, row, currentPath){\n \n if (column === columnLength && row === rowLength) {\n resultPath = currentPath;\n }\n\n if(column <= columnLength && row <= rowLength) {\n if(column < columnLength && grid[column+1][row] !== 'x') {\n innerTraverseHelper(column+1, row, currentPath.concat([[column, row]]));\n }\n if(row < rowLength && grid[column][row+1] !== 'x') {\n innerTraverseHelper(column, row+1, currentPath.concat([[column, row]]));\n }\n }\n }\n\n innerTraverseHelper(0,0,[[0,0]]);\n\n return resultPath;\n}",
"findPaths(){\n gridArray.forEach(function(yValue, yCoord){\n yValue.forEach(function(xValue, xCoord){\n BadBoggle.searchPath([[yCoord, xCoord]], yCoord, xCoord);\n });\n });\n }",
"pathFinder(position, length) {\n\t\tconst { x, y } = position\n\t\tconst path = {\n\t\t\tup: [],\n\t\t\tdown: [],\n\t\t\tleft: [],\n\t\t\tright: []\n\t\t}\n\n\t\tObject.entries(path).forEach(([direction, value]) => {\n\t\t\tlet newY = y\n\t\t\tlet newX = x\n\t\t\tlet blocked = false\n\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\tswitch (direction) {\n\t\t\t\t\tcase 'up':\n\t\t\t\t\t\t--newY\n\t\t\t\t\t\tif (newY >= 0 && newY < this.grid.length && !blocked) {\n\t\t\t\t\t\t\tconst cellBlocked = this.grid[newY][x].blocked\n\t\t\t\t\t\t\tif (!cellBlocked) {\n\t\t\t\t\t\t\t\tvalue.push({ y: newY, x: x })\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tblocked = true\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'down':\n\t\t\t\t\t\t++newY\n\t\t\t\t\t\tif (newY >= 0 && newY < this.grid.length && !blocked) {\n\t\t\t\t\t\t\tconst cellBlocked = this.grid[newY][x].blocked\n\t\t\t\t\t\t\tif (!cellBlocked) {\n\t\t\t\t\t\t\t\tvalue.push({ y: newY, x })\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tblocked = true\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'right':\n\t\t\t\t\t\t++newX\n\t\t\t\t\t\tif (newX >= 0 && newX < this.grid[y].length && !blocked) {\n\t\t\t\t\t\t\tconst cellBlocked = this.grid[y][newX].blocked\n\t\t\t\t\t\t\tif (!cellBlocked) {\n\t\t\t\t\t\t\t\tvalue.push({ y, x: newX })\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tblocked = true\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'left':\n\t\t\t\t\t\t--newX\n\t\t\t\t\t\tif (newX >= 0 && newX < this.grid[y].length && !blocked) {\n\t\t\t\t\t\t\tconst cellBlocked = this.grid[y][newX].blocked\n\t\t\t\t\t\t\tif (!cellBlocked) {\n\t\t\t\t\t\t\t\tvalue.push({ y, x: newX })\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tblocked = true\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\treturn path\n\t}",
"transformMatrixIntoPath () {\n const matrix = this._matrix\n const cellSize = this._cellSize\n // adjust origin\n let d = ''\n matrix.forEach((row, i) => {\n let needDraw = false\n row.forEach((column, j) => {\n if (column) {\n if (!needDraw) {\n d += `M${cellSize * j} ${cellSize / 2 + cellSize * i} `\n needDraw = true\n }\n if (needDraw && j === matrix.length - 1) {\n d += `L${cellSize * (j + 1)} ${cellSize / 2 + cellSize * i} `\n }\n } else {\n if (needDraw) {\n d += `L${cellSize * j} ${cellSize / 2 + cellSize * i} `\n needDraw = false\n }\n }\n })\n })\n return d\n }",
"function findPath(grid, pathStart, pathEnd)\n{\n // shortcuts for speed\n\tvar\tabs = Math.abs;\n\tvar\tmax = Math.max;\n\tvar\tpow = Math.pow;\n\tvar\tsqrt = Math.sqrt;\n\n\tif(!grid) return;\n\t// keep track of the grid dimensions\n\t// Note that this A-star implementation expects the grid array to be square:\n\t// it must have equal height and width. If your game grid is rectangular,\n\t// just fill the array with dummy values to pad the empty space.\n\tvar gridWidth = grid[0].length;\n\tvar gridHeight = grid.length;\n\tvar gridSize =\tgridWidth * gridHeight;\n\n\n function ManhattanDistance(Point, Goal)\n {\t// linear movement - no diagonals - just cardinal directions (NSEW)\n return abs(Point.x - Goal.x) + abs(Point.y - Goal.y);\n }\n\n function Neighbours(x, y)\n {\n var\tN = y - 1,\n S = y + 1,\n E = x + 1,\n\t\t\t\tW = x - 1,\n myN = N > -1 && canWalkHere(x, N, 'd'),\n myS = S < gridHeight && canWalkHere(x, S, 'u'),\n myE = E < gridWidth && canWalkHere(E, y, 'l'),\n myW = W > -1 && canWalkHere(W, y, 'r'),\n result = [];\n if(myN)\n result.push({x:x, y:N});\n if(myE)\n result.push({x:E, y:y});\n if(myS)\n result.push({x:x, y:S});\n if(myW)\n result.push({x:W, y:y});\n //findNeighbours(myN, myS, myE, myW, N, S, E, W, result);\n return result;\n }\n // returns boolean value (grid cell is available and open)\n function canWalkHere(x, y, direction)\n {\n return ((grid[x] != null) &&\n (grid[x][y] != null) &&\n (grid[x][y].IsDug(direction)));\n\t}\n\n\t// which heuristic should we use?\n\t// default: no diagonals (Manhattan)\n\tvar distanceFunction = ManhattanDistance;\n\tvar findNeighbours = function(){}; // empty\n\n // Node function, returns a new object with Node properties\n\t// Used in the calculatePath function to store route costs, etc.\n\tfunction Node(Parent, Point)\n\t{\n\t\tvar newNode = {\n\t\t\t// pointer to another Node object\n\t\t\tParent:Parent,\n\t\t\t// array index of this Node in the grid linear array\n\t\t\tvalue:Point.x + (Point.y * gridWidth),\n\t\t\t// the location coordinates of this Node\n\t\t\tx:Point.x,\n\t\t\ty:Point.y,\n\t\t\t// the distanceFunction cost to get\n\t\t\t// TO this Node from the START\n\t\t\tf:0,\n\t\t\t// the distanceFunction cost to get\n\t\t\t// from this Node to the GOAL\n\t\t\tg:0\n\t\t};\n\n\t\treturn newNode;\n\t}\n\n\t// Path function, executes AStar algorithm operations\n\tfunction calculatePath()\n\t{\n\t\t// create Nodes from the Start and End x,y coordinates\n\t\tvar\tmypathStart = Node(null, {x:pathStart[0], y:pathStart[1]});\n\t\tvar mypathEnd = Node(null, {x:pathEnd[0], y:pathEnd[1]});\n\t\t// create an array that will contain all grid cells\n\t\tvar AStar = new Array(gridSize);\n\t\t// list of currently open Nodes\n\t\tvar Open = [mypathStart];\n\t\t// list of closed Nodes\n\t\tvar Closed = [];\n\t\t// list of the final output array\n\t\tvar result = [];\n\t\t// reference to a Node (that is nearby)\n\t\tvar myNeighbours;\n\t\t// reference to a Node (that we are considering now)\n\t\tvar myNode;\n\t\t// reference to a Node (that starts a path in question)\n\t\tvar myPath;\n\t\t// temp integer variables used in the calculations\n\t\tvar length, max, min, i, j;\n\t\t// iterate through the open list until none are left\n\t\twhile(length = Open.length)\n\t\t{\n\t\t\tmax = gridSize;\n\t\t\tmin = -1;\n\t\t\tfor(i = 0; i < length; i++)\n\t\t\t{\n\t\t\t\tif(Open[i].f < max)\n\t\t\t\t{\n\t\t\t\t\tmax = Open[i].f;\n\t\t\t\t\tmin = i;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// grab the next node and remove it from Open array\n\t\t\tmyNode = Open.splice(min, 1)[0];\n\t\t\t// is it the destination node?\n\t\t\tif(myNode.value === mypathEnd.value)\n\t\t\t{\n\t\t\t\tmyPath = Closed[Closed.push(myNode) - 1];\n\t\t\t\tdo\n\t\t\t\t{\n\t\t\t\t\tresult.push([myPath.x, myPath.y]);\n\t\t\t\t}\n\t\t\t\twhile (myPath = myPath.Parent);\n\t\t\t\t// clear the working arrays\n\t\t\t\tAStar = Closed = Open = [];\n\t\t\t\t// we want to return start to finish\n\t\t\t\tresult.reverse();\n\t\t\t}\n\t\t\telse // not the destination\n\t\t\t{\n\t\t\t\t// find which nearby nodes are walkable\n\t\t\t\tmyNeighbours = Neighbours(myNode.x, myNode.y);\n\t\t\t\t// test each one that hasn't been tried already\n\t\t\t\tfor(i = 0, j = myNeighbours.length; i < j; i++)\n\t\t\t\t{\n\t\t\t\t\tmyPath = Node(myNode, myNeighbours[i]);\n\t\t\t\t\tif (!AStar[myPath.value])\n\t\t\t\t\t{\n\t\t\t\t\t\t// estimated cost of this particular route so far\n\t\t\t\t\t\tmyPath.g = myNode.g + distanceFunction(myNeighbours[i], myNode);\n\t\t\t\t\t\t// estimated cost of entire guessed route to the destination\n\t\t\t\t\t\tmyPath.f = myPath.g + distanceFunction(myNeighbours[i], mypathEnd);\n\t\t\t\t\t\t// remember this new path for testing above\n\t\t\t\t\t\tOpen.push(myPath);\n\t\t\t\t\t\t// mark this node in the grid graph as visited\n\t\t\t\t\t\tAStar[myPath.value] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// remember this route as having no more untested options\n\t\t\t\tClosed.push(myNode);\n\t\t\t}\n\t\t} // keep iterating until until the Open list is empty\n\t\treturn result;\n }\n\n return calculatePath();\n}",
"function draw() {\n for(var i = 0; i < N; i++){\n for(var j = 0; j < N; j++){\n grid[i][j].display();\n }\n }\n \n if(foundPath){\n if(curr != curr.parrent){\n curr.col = color(60,125,190);\n curr = curr.parent;\n }\n }\n}",
"function calculatePath(){\n //MAKE SURE WE HAVE WHAT WE NEED TO CALCULATE PATH\n if (start !== undefined && finish !== undefined && linesDrawn.length === 0)\n {\n //GET THE START FOR PATH\n var startCoordinates = [start.x,start.y];\n //GET THE END FOR PATH\n var finishCoordinates = [finish.x,finish.y];\n //FOR FINDING THE PATH\n var nearestStartArrayCoordinates = [Math.round(startCoordinates[0]/10)*10,Math.round(startCoordinates[1]/10)*10];\n //FOR FINDING THE PATH WE WILL USE THIS AND PREVIOUS IN THE MAP TO FIND PATH SINCE THEY ARE ALL ROUDED TO NEAREST 10\n var nearestFinishArrayCoordinates = [Math.round(finishCoordinates[0]/10)*10,Math.round(finishCoordinates[1]/10)*10];\n //CREATE POSSIBLE NODES BASED ON SQUARE PLACEMENT\n var nodesArray = generateNodeArray();\n //CREATE MAP BASED ON THAT\n var map = generateMap(nodesArray);\n //GENERATE PATH\n var pathToFinish = generatePath(startCoordinates,nearestStartArrayCoordinates,nearestFinishArrayCoordinates,map);\n //PUSH THE FINAL COORDINATES SO IT IS COMPLETE\n pathToFinish.push(finishCoordinates);\n //DRAW LINES\n drawLine(pathToFinish);\n\n\n\n }\n}",
"function findPath(currentPosition) {\r\n var i = 0,\r\n x = currentPosition[0], \r\n y = currentPosition[1],\r\n s = currentPosition[2];\r\n if (x < 3) {\r\n var s1 = grid[x+1][y].status;\r\n }\r\n if (y < 3) {\r\n var s2 = grid[x][y+1].status;\r\n }\r\n if (y >= 1) {\r\n var s3 = grid[x][y-1].status;\r\n }\r\n var nextMoves = [[x+1,y,s1],[x,y+1,s2],[x,y-1,s3]];\r\n \r\n path.push(currentPosition);\r\n\r\n if (x == 3 && s != \"X\") {\r\n var solution = path.slice(0);\r\n solutions.push(solution);\r\n pathCount++;\r\n \r\n for (i = 0;i < solution.length; i++) {\r\n if (solution[i][0] == 3) {\r\n $('#paths').append('<span>('+solution[i][0]+','+solution[i][1]+')</span><br>'); \r\n } else {\r\n $('#paths').append('<span>('+solution[i][0]+','+solution[i][1]+')-></span>');\r\n }\r\n }\r\n \r\n }\r\n else {\r\n for (i = 0; i < nextMoves.length; i++) {\r\n if (nextMoves[i][0] < 0 || nextMoves[i][0] > 3 || nextMoves[i][1] < 0 || nextMoves[i][1] > 3 || nextMoves[i][2] == \"X\") {\r\n }\r\n else {\r\n if (checkPosition(nextMoves[i], path)) {\r\n } else {\r\n findPath(nextMoves[i]);\r\n }\r\n }\r\n }\r\n }\r\n path.pop();\r\n}",
"squarePath (x, y, l) {\n return \"M\" + x + \",\" + y + \" \" +\n \"m\" + -l/2 + \",0 \" +\n \"m\" + \"0,\" + -l/2 + \" \" +\n \"h\" + \"0,\" + l + \" \" +\n \"v\" + l + \",0 \" + // l + \" \" +\n \"h 0,\" + -l + \" \" + //,0 \" +\n \"v0,0Z\";\n }",
"function connection_path_generator(d) {\n\t\t\tvar x1 = _layout.zoom_plot.x+scale_position_by_chromosome(d.chrom1,d.pos1,\"top\"), // top\n\t\t\t\t\ty1 = y_coordinate_for_connection(\"top\"),\n\t\t\t\t\tx2 = _layout.zoom_plot.x+scale_position_by_chromosome(d.chrom2,d.pos2,\"bottom\"), // bottom\n\t\t\t\t\ty2 = y_coordinate_for_connection(\"bottom\")\n\t\t\t\t\tdirection1 = Number(d.strand1==\"-\")*2-1, // negative strands means the read is mappping to the right of the breakpoint\n\t\t\t\t\tdirection2 = Number(d.strand2==\"-\")*2-1;\n\n\t\t\treturn (\n\t\t\t\t\t \"M \" + (x1+_static.foot_length*direction1) + \" \" + y1\n\t\t\t + \" L \" + x1 + \" \" + y1 \n\t\t\t + \" L \" + x2 + \" \" + y2\n\t\t\t + \" L \" + (x2+_static.foot_length*direction2) + \" \" + y2)\n\t}",
"makePath() {\n const vector = this.visited;\n let end = vector.length-1;\n let parent = vector[end].pai;\n \n // Ultima posicao de vector eh o destino entao ele ja entra no path\n this.path.push(vector[end].info);\n \n // O for a seguir percore o vetor de tras pra frente, basicamente ele percorre \n // todos os vertices 'pais' que foram visitados pelo algoritmo do A*, quando \n // encontra o filho, o pai deste filho vira o 'parent' e continua buscando por parent.\n // Resumidamente ele realiza o backtracking do destino para origem, passando sempre no\n // vertice pai daquele que esta sendo buscado\n for(let i = end; i >= 0; i--) {\n if(vector[i].info.lin == parent.lin &&\n vector[i].info.col == parent.col) {\n this.path.push(vector[i].info);\n parent = vector[i].pai;\n }\n }\n\n // Insere a origem no path, já que ela eh nenhum vertice possui ela como filho\n this.path.push(vector[0].pai);\n\n // Inverte o vetor pois ele foi gerado do destino para a origem e nao da origem para o destino\n this.reverseVector();\n}",
"function draw_knight_path(path_array){\n\tfor (var i=0; i<path_array.length-1; i++){\n\t\tvar start_cell= path_array[i];\n\t\tvar end_cell= path_array[i+1];\n\t\tc.strokeStyle= 'grey';\n\t\tc.lineWidth=1;\n\t\tdraw_circle_at_coordinate(start_cell[0], start_cell[1]);\n\t\tdraw_line(start_cell[0],start_cell[1], end_cell[0], end_cell[1]);\n\t}\n\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
viewRoster AJAX call to load Group Roster list. | function viewRoster(){
$('#viewGroupRoster').live('click', function() {
//call .ajax to call server.
$.ajax({
method: "get", url: "quicktools/viewgrouproster.php", data: "groupid=" + $(this).attr("title"),
beforeSend: function(xhr){
$("#smloading").show();
},
complete: function(xhr, tStat){
$("#smloading").hide();
},
success: function(html){
$("#groupRoster").show();
$("#groupRoster").html(html).removeClass("ui-state-error");
},
error: function(xhr, tStat, err){
var msg = lang.jsError + ": ";
$("#groupRoster").html(msg + xhr.status + " " + xhr.statusText).addClass("ui-state-error");
}
}); //END $.ajax(
}); //END .live
} | [
"function renderRoster() {\n submitAJAX(\"getroster\", null, buildroster);\n}",
"function getRoster() {\n $.ajax({\n url: 'http://devjana.net/support/tau_students.json',\n dataType: 'JSON',\n success: function(data) {\n if (debug) {\n console.log('Data standing by!');\n }\n roster = data.tau;\n console.log(roster);\n displayStudent();\n displayNav();\n }\n });\n }",
"function loadRoster(TeamID) {\n $.ajax({\n url: '/api/TeamAPI/GetFullRoster?TeamID=' + TeamID,\n type: 'GET',\n success: function(data, status, xhr) {\n $('#teamRoster').empty();\n\n $.each(data, function(index, player) {\n $(createTableDataPlayer(player, index)).appendTo($('#teamRoster'));\n });\n }\n });\n}",
"function displayRoster(data) {\n // capture the parameter, store it as rawData\n var rawData = data;\n // console.log(rawData.length);\n\n // select the roster-display hook\n var rosterDislay = $(\"#roster-list\");\n\n // for loop that's going to build the roster\n for (var i = 0; i < rawData.length; i++) {\n var id = rawData[i].id;\n var name = rawData[i].ownername;\n var initPos = rawData[i].position;\n var modPos = rawData[i].modifiedPos;\n var selecting = rawData[i].selecting;\n var email = rawData[i].email;\n // console.log(id + \" \" + name + \" \" + modPos + \" \" + selecting);\n\n // builds the individual list item and gives it a class\n var temp = $(\"<li>\" + \" \" + name + \" \" + \"</li>\");\n temp.addClass(\"list-item\");\n\n // builds the button and gives it some data attributes\n var button = $(\"<button id='roster-submit'>Submit</button>\");\n button.attr(\"data-id\", id);\n button.attr(\"data-modpos\", modPos);\n button.attr(\"data-selecting\", selecting);\n button.attr(\"data-name\", name);\n button.attr(\"data-email\", email);\n button.attr(\"data-initpos\", initPos);\n\n // if the selecting is true, the button will appear next to the name\n if (selecting === true) {\n temp.append(button);\n }\n\n // puts the temp onto the page\n rosterDislay.append(temp);\n }\n}",
"function show_my_groups()\n{\n\tvar study_groups = [];\n\n\t$.ajax({\n\t\turl: '/studygroups/myGroups',\n\t\tmethod: 'GET',\n\t\tdataType: 'json',\n\t\tsuccess: function(data)\n\t\t{\n\t\t\tstudy_groups = data;\n\t\t\tjQuery(\".uos_my_study_groups\").empty();\n\t\t\tjQuery(\".uos_my_study_groups\").html(\"<h1>My Study Groups</h1>\");\n\n\t\t\tfor (var i = 0; i < study_groups.length; i++)\n\t\t\t{\n\t\t\t\tvar data = \"<div class = 'uos_sg'>\" +\n\t\t\t\t\t\t\t\t\"<div class = 'uos_study_group_img'>\" +\n\t\t\t\t\t\t\t\t\t\"<img src = '\" + study_groups[i]['img'] + \"'>\" +\n\t\t\t\t\t\t\t\t\"</div>\" +\n\t\t\t\t\t\t\t\t\"<div class = 'uos_study_group_text'>\" +\n\t\t\t\t\t\t\t\t\t\"<h3>\" + study_groups[i]['group_name'] + \"</h3>\" +\n\t\t\t\t\t\t\t\t\t\"<a href = '/group?id=\" + study_groups[i]['group_id'] + \"' id = 'uos_open_group'>View profile</a>\" +\n\t\t\t\t\t\t\t\t\"</div>\" +\n\t\t\t\t\t\t\t\"</div>\";\n\n\t\t\t\tjQuery(\".uos_my_study_groups\").append(data);\n\t\t\t}\n\t\t}\n\t});\n}",
"function getGroups() {\n $.get(\"/api/groups\", renderGroupList);\n }",
"function getPlayerRoster(team) {\n var queryURL =\n \"https://nba-players.herokuapp.com/players-stats-teams/\" +\n team.substring(0, 3);\n $.ajax({\n url: queryURL,\n method: \"GET\"\n }).then(function(response) {\n $(\"#back-btn-roster\").show();\n\n for (i in response) {\n var player =\n \"<a class='player'\" +\n \"data-name='\" +\n response[i].name +\n \"' data-team=\" +\n team +\n \" data-id='\" +\n i +\n \"' width='100px'\" +\n \">\" +\n response[i].name +\n \"<a><br>\";\n console.log(player);\n $(\"#roster-holder\").append(player);\n }\n });\n }",
"function getData() {\n document.getElementById('widgetBody').innerHTML = 'Requesting groups...';\n var req = opensocial.newDataRequest();\n req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');\n req.add(socialsite.newFetchUsersGroupsRequest(opensocial.IdSpec.PersonId.VIEWER), 'mygroups');\n req.add(socialsite.newFetchPublicGroupsRequest(opensocial.IdSpec.PersonId.VIEWER), 'publicgroups');\n req.send(onLoadGroups);\n }",
"function request_google_roster() {\n\tvar roster_elem = new xmpp.Element('iq', { from: conn.jid, type: 'get', id: 'google-roster'})\n\t\t\t\t\t\t.c('query', { xmlns: 'jabber:iq:roster', 'xmlns:gr': 'google:roster', 'gr:ext': '2' });\n\tconn.send(roster_elem);\n}",
"function request_google_roster() {\n var roster_elem = new xmpp.Element('iq', { from: conn.jid, type: 'get', id: 'google-roster'})\n .c('query', { xmlns: 'jabber:iq:roster', 'xmlns:gr': 'google:roster', 'gr:ext': '2' });\n conn.send(roster_elem);\n }",
"function getGroceries() {\n $.ajax( {\n type: 'GET',\n url: '/api/groceries'\n }).then(function(resp) {\n appendHTML(resp);\n });\n }",
"function onSearchGroup(data, textStatus, jqXHR) {\n if (data.meta.code == 200) {\n var group = data.response;\n $(\"#searchGroupResults\").append(\"<div id='foundgroup'></div>\");\n $(\"#foundgroup\").append(\"<h2>\" + group.name + \"</h2>\");\n if (group.users.indexOf(user.citylife.id) == -1) {\n if (group.requestingUsers.indexOf(user.citylife.id) == -1) {\n $(\"#foundgroup\").append('<tr><td><input type=\"button\" value=\"Request membership\" onclick=\"requestMembership(\\'' + group._id + '\\')\"/></td></tr>');\n } else {\n $(\"#foundgroup\").append('<tr><td><input type=\"button\" value=\"Cancel membership request\" onclick=\"cancelMembershipRequest(\\'' + group._id + '\\')\"/></td></tr>');\n }\n } else {\n $(\"#foundgroup\").append(renderLeaveOrDeleteButton(group));\n }\n $(\"#foundgroup\").append(\"<h3>The members of \" + group.name + \": </h3>\");\n for (var i = 0; i < group.users.length; i++) {\n var searchdata = { \n id: group.users[i],\n token: user.citylife.token\n };\n var url = config.server.address + \"/users/profile\";\n $.ajax({\n url: url,\n data: searchdata,\n dataType: \"json\",\n type: \"POST\",\n success: onProfileFoundForSearch,\n error: function(jqXHR, errorstatus, errorthrown) {\n console.log(\"Error: \" + errorstatus + \" -- \" + jqXHR.responseText);\n }\n }); \n };\n $(\"#searchGroupResults\").append(\"<div id='foundgroup'></div>\");\n } else {\n alertAPIError(data.meta.message);\n }\n}",
"function getTeamRoster(callback) {\r\n\tif(player == null) {\r\n\t\tgetFromServer(\"/teams/\"+$_GET(\"team\")+\"/roster\", function(data) {\r\n\t\t\tplayer = data;\r\n\t\t\tcallback(data);\r\n\t\t});\r\n\t} else {\r\n\t\tcallback(player);\r\n\t}\r\n}",
"function user_groups_list(){\n\tfunction_to_use=\"user_groups\";\n\t$.ajax({\n\t\ttype: \"POST\",\n\t\turl: \"website_code/php/management/user_groups.php\",\n\t\tdata: {\n\t\t\tno_id: 1\n\t\t},\n\t})\n\t.done(function (response) {\n\t\tmanagement_usergroupStateChanged(response);\n\t});\n}",
"function getScoutListFromRoster(unitID,pageid,leaderapprv) {\t//tested used\r\n\r\n//nbconsole.log(2,leaderapprv);\r\n\tvar utype=\"unit\";\r\n\r\n\tvar xhttp = new XMLHttpRequest();\r\n\txhttp.onreadystatechange = function() {\r\n\t\tif (this.readyState == 4 && this.status > 399 && this.status < 500) {\r\n\t\t\t$.mobile.loading('hide');\r\n\t\t\talert('Error: '+ this.status); //page not found etc. This is unrecoverable\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tif (this.readyState == 4 && this.status > 499) {\r\n\t\t\terrHandle( getScoutListFromRoster,unitID,pageid,leaderapprv,'','','','');\t//server side error - maybe next try will work\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tif (this.readyState == 4 && this.status == 200) {\r\n\t\t\tresetLogoutTimer(url);\r\n\t\t\tservErrCnt=0;\r\n\t\t\t//get scoutlist\r\n\t\t\t// These are not going thru the name filter because they never show\r\n\r\n//\t\t\tvar startIndex= this.responseText.indexOf('Add Leader',1); //<div class=\"ui-block-b\"> on a line by itself\r\n//\t\t\tvar endIndex=this.responseText.indexOf('Add Scout',startIndex); //<div id=\"footer\" align=\"center\">\r\n\t\t\t\r\n\t\t\tvar startIndex= this.responseText.indexOf('<div class=\"ui-block-b\">',1); //<div class=\"ui-block-b\"> on a line by itself\r\n\t\t\tvar endIndex=this.responseText.indexOf('<div id=\"footer\" align=\"center\">',startIndex); //<div id=\"footer\" align=\"center\">\t\t\t\r\n\t\t\t\r\n\t\t\tvar scoutlistresp=this.responseText.slice(startIndex,endIndex+7);\r\n\r\n\t\t\t//first Scout ID is\r\n\t\t\t//var scoutIDs = this.responseText.match(/id=\\\"scoutUserID\\d+/);\r\n\t\t\t//var scoutIDn = scoutIDs[0].match(/\\d+/);\r\n\t\t\t//var scoutID=scoutIDn[0];\r\n\t\t\t//var unitID= /UnitID\\=\\d+/.exec($('base')[0].href);\r\n\r\n\t\t\tfillScoutRosterArr(scoutlistresp);\r\n\t\t\taddScoutToList();\t// add scout names to mobiscroll\r\n\r\n\t\t\t//$('#footer').append('<a href=\"#importScoutName\" data-rel=\"popup\" data-transition=\"slideup\" style=\"hidden\"></a>');\r\n\t//\t\t$('#importBPMenu').popup('close');\r\n\t\t\t//$('#importScoutName').popup('open');\r\n\r\n\t\t\t//var noNameMatch=[];\r\n\t\t\tmatchNames();\r\n\t\t\tif (noNameMatch.length != 0) {\r\n\t\t\t\tpopupNameMatch(unitID,pageid,leaderapprv);\r\n\t\t\t\t//we have names that didn't match. So we need to handle them\r\n\t\t\t} else {\r\n\t\t\t\t// All names matched!\r\n\r\n\t\t\t\tgetMBfromQE(unitID,pageid,leaderapprv);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (this.readyState == 4 && this.status != 200 && this.status == 500) {\r\n\t\t\t //console.log('Server Error ' +servErrCnt);\r\n\t\t\t if (servErrCnt > maxErr) {\r\n\t\t\t\t $.mobile.loading('hide');\r\n\t\t\t\talert('Halted due to excessive Server errors');\r\n\t\t\t\treturn;\r\n\t\t\t }\r\n\t\t\t servErrCnt++;\r\n\t\t\t// mbArrPtr=errmbArrPtr;\r\n\t\t\tsetTimeout(function() {getScoutListFromRoster(unitID,pageid,leaderapprv);},1000);\t//reset \r\n\t\t}\r\n\r\n\t};\r\n\tvar url = 'https://' + host + 'scoutbook.com/mobile/dashboard/admin/roster.asp?UnitID=' + unitID;\r\n\r\n\t//console.log('Getting Roster ' +url);\r\n\txhttp.open(\"GET\",url , true);\r\n\txhttp.responseType=\"text\";\r\n\r\n\txhttp.send();\r\n\txhttp.onerror = function() {\r\n\t\terrHandle( getScoutListFromRoster,unitID,pageid,leaderapprv,'','','','');\r\n\t};\r\n}",
"function viewUsersgroupsResult(data) {\n _pendingAjaxRequest = null; // requ�te ajax termin�e\n\n if (data.length < 1) {\n // Affiche un message si on n'a r�cup�r� aucune donn�e\n var textMessage = \"Il n'y a pas de groupe d'utilisateurs pour le moment\";\n showMessage(textMessage, \"error\");\n stopLoadingAnimationCustomPlace(\"#usersgroups-panel .categorie-panel-content\");\n return;\n }\n\n // R�cup�re l'objet o� on va ins�rer le contenu\n var content = $(\"#usersgroups-panel .categorie-panel-content .usersgroups\");\n\n // Traitement des donn�es\n for (var i = 0; i < data.length; i++) {\n // Cr�e la carte de groupe\n var card = $(\"<div>\", {\n class : \"group-card\",\n groupid : data[i].id\n }).appendTo(content);\n\n // Cr�e le header\n var header = $(\"<div>\", {\n class:\"group-card-header\"\n });\n\n // Cr�e le contenu\n var groupid = $(\"<span>\", { class: 'group-id', html: data[i].id });\n var grouptitle = $(\"<span>\", { class: 'group-title', html: data[i].title });\n\n // Tronque le titre s'il est trop long\n if (grouptitle.html().length > 15) {\n addTooltipJquery(grouptitle, grouptitle.html(), \"bottom center\", \"top center\");\n grouptitle.html(grouptitle.html().substring(0, 12) + \"...\");\n }\n\n // Attache les �l�ments au DOM (Document Object Model)\n card.append(header); // attache l'objet header au parent card\n card.append(groupid); // attache l'objet groupid au parent card\n header.append(grouptitle); // attache l'objet grouptitle au parent header\n\n\n // Cr�e un bouton text (pour l'�dition)\n var edit = $(\"<div>\", {\n class: \"text-button\",\n func : \"edit-usergroup\",\n groupid: data[i].id,\n html: \"edit\"\n });\n\n // Cr�e un second bouton text (pour la suppression)\n var del = $(\"<div>\", {\n class: \"text-button\",\n func : \"delete-usergroup\",\n groupid: data[i].id,\n html: \"delete\"\n });\n\n header.append(edit);\n header.append(del);\n }\n\n // Ajoute les toolitps de description\n addTooltip(\".group-id\", \"group id\");\n // addTooltip(\".user-groupid\", \"id du group de l'utilisateur\");\n // addTooltip(\".icon-button[func='edit-user']\", \"editer\");\n // addTooltip(\".icon-button[func='delete-user']\", \"supprimer\");\n\n // Ev�nements\n clickDeleteUsergroup();\n clickEditUsergroup();\n\n // Stop l'animation de chargement\n stopLoadingAnimationCustomPlace(\"#usersgroups-panel .categorie-panel-content\");\n}",
"function participantList(id) {\n window.location.href = base_url + '/group-manager/session/list/participants/' + id;\n}",
"function showTeamRoster(data) {\r\n\t$('#teaminfobox').empty();\r\n\t//Build Table\r\n\tvar table = jQuery('<table/>', {\r\n\t\tid: \"teamplayertable\",\r\n\t\tclass: \"table\"\r\n\t}).appendTo('#teaminfobox');\r\n\tvar tr = jQuery('<tr/>', {\r\n\t}).appendTo(table);\r\n\tjQuery('<th/>', {\r\n\t\ttext: \"Vorname\"\r\n\t}).appendTo(tr);\r\n\tjQuery('<th/>', {\r\n\t\ttext: \"Nachname\"\r\n\t}).appendTo(tr);\r\n\tjQuery('<th/>', {\r\n\t\ttext: \"#\"\r\n\t}).appendTo(tr);\r\n\tjQuery('<th/>', {\r\n\t\ttext: \"Position\"\r\n\t}).appendTo(tr);\r\n\tjQuery('<th/>', {\r\n\t\ttext: \"Tore\"\r\n\t}).appendTo(tr);\r\n\t\t\r\n\t//Show Players\r\n\t$.each(data, function(index, value) {\r\n\t\tvar tr = jQuery('<tr/>', {\r\n\t\t}).appendTo(table);\r\n\t\t\r\n\t\tjQuery('<td/>', {\r\n\t\t\ttext: value.firstname\r\n\t\t}).appendTo(tr);\r\n\t\tjQuery('<td/>', {\r\n\t\t\ttext: value.surname\r\n\t\t}).appendTo(tr);\r\n\t\tjQuery('<td/>', {\r\n\t\t\ttext: value.number\r\n\t\t}).appendTo(tr);\r\n\t\tjQuery('<td/>', {\r\n\t\t\ttext: value.position\r\n\t\t}).appendTo(tr);\r\n\t\tjQuery('<td/>', {\r\n\t\t\ttext: value.goals\r\n\t\t}).appendTo(tr);\r\n\t});\r\n}",
"function openMyRoster() {\n\tvar my_Roster = Alloy.createController('my_Roster').getView();\n\tmy_Roster.open();\n\t$.explore.close();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This returns the id of the insert code event | function getEvent(row, col, allInsertEventsByPos) {
//default error message
retVal = "ERROR ON ID";
//if the row and column are good
if((row >= 0 && row < allInsertEventsByPos.length) &&
(col >= 0 && col < allInsertEventsByPos[row].length)) {
//return the id of the code
retVal = allInsertEventsByPos[row][col];
}
return retVal;
} | [
"function eventid(e){\n return parse_id(e.target.get('id'));\n }",
"get insertedId() {\n return this._lastResults.insertId;\n }",
"function getAddEventID() {\n return $window.addevent_id;\n }",
"function idEvent() {\n return crypto.randomBytes(3).toString(\"hex\");\n}",
"get callbackId(): ?string {\n if (this.isInteractiveMessage) {\n return ((this._rawEvent: any): InteractiveMessageEvent).callback_id;\n }\n return null;\n }",
"get id () {\n return this.constructor.name.replace(/(\\w+)Event/, '$1').toLowerCase()\n }",
"get id()\n\t{\n\t\tif (!this._id) {\n\t\t\tthis._id = this.getAttributeByTag(\"t:ItemId\", \"Id\", null);\n\t\t\tif (this._id) {\n\t\t\t\tthis._calEvent.id = this._id;\n\t\t\t}\n\t\t}\n\t\treturn this._calEvent.id;\n\t}",
"function addCodeToEvent(request, response, next) {\n Event.findOne({\"_id\": request.params.eventId}, function (err, event) {\n if (err) throw err;\n event.codes.push(request.params.codeId);\n event.save(function (err) {\n if (err) throw err;\n response.send();\n next();\n });\n });\n }",
"function getCallbackId() {\n var newUUID = uuid.new();\n return newUUID;\n }",
"insert(insertEvent) {\n //if there is not a file marker for this file\n if (!this.newCodeFileMarkers[insertEvent.fileId]) {\n //create a new file marker\n this.newCodeFileMarkers[insertEvent.fileId] = new NewCodeFileMarker();\n }\n\n let insertEventCharacter = insertEvent.character;\n if (insertEvent.character === 'NEWLINE' || insertEvent.character === 'CR-LF') {\n insertEventCharacter = '\\n';\n }\n\n //handle the insert\n this.newCodeFileMarkers[insertEvent.fileId].insert(insertEvent.lineNumber - 1, insertEvent.column - 1, insertEventCharacter);\n }",
"function createEventId() {\n let randomId = require('random-id');\n let len = 8;\n let pattern = 'aA0';\n let id = randomId(len, pattern);\n return String(id);\n}",
"function handleInsert(_e) {\n console.log(\"Database insertion returned -> \" + _e);\n}",
"function add_event(connection, event_code) {\n console.log(event_code);\n connection.query('INSERT INTO frc_event (event_code) VALUES(?) ON DUPLICATE KEY UPDATE event_code = event_code',\n\t\t [event_code],\n\t\t function (error, results, fields) {\n\t\t\t if (error) {\n\t\t\t throw error;\n\t\t\t }\n\t\t });\n}",
"function createEventId(){\n\tvar timestamp = new Date();\n\tevent_timestamp = Math.floor(timestamp.getTime());\n\treturn event_timestamp;\n}",
"function createID() {\r\n return s_lastID++;\r\n }",
"static get commitId() {\n return events.EventField.fromPath('$.detail.commitId');\n }",
"function _getNewID(){\n \n // Rendiamo il nostro id univoco\n var now = new Date().getTime();\n \n return signature + now;\n \n }",
"generateId() { return this._get_uid() }",
"generateId() {\n return cuid();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
transfer_marble selected ball to user | function transfer_marble(marbleId, to_owner_id) {
show_tx_step({ state: 'building_proposal' }, function () {
var obj = {
type: 'transfer_marble',
id: marbleId,
owner_id: to_owner_id,
v: 1
};
console.log(wsTxt + ' sending transfer marble msg', obj);
ws.send(JSON.stringify(obj));
refreshHomePanel();
});
} | [
"function transfer_marble(marbleName, to_username, to_company){\n\tshow_tx_step({state: 'building_proposal'}, function(){\n\t\tvar obj = \t{\n\t\t\t\t\t\ttype: 'transfer_marble',\n\t\t\t\t\t\tname: marbleName,\n\t\t\t\t\t\tusername: to_username,\n\t\t\t\t\t\tcompany: to_company,\n\t\t\t\t\t\tv: 1\n\t\t\t\t\t};\n\t\tconsole.log('[ws] sending transfer marble msg', obj);\n\t\tws.send(JSON.stringify(obj));\n\t\trefreshHomePanel();\n\t});\n}",
"goalAchieved(ball) {\n let d = dist(this.x, this.y, ball.x, ball.y);\n if (d < this.size / 2) {\n if (this.targetId === 1 && this.targetIdTrue === 0) {\n this.sound.setVolume(0.05);\n this.sound.play();\n this.targetIdTrue = 1;\n } else if (this.targetId === 3 && this.targetIdTrue === 0) {\n this.sound.setVolume(0.05);\n this.sound.play();\n this.targetIdTrue = 3;\n } else if (this.targetId === 5 && this.targetIdTrue === 0) {\n this.sound.setVolume(0.05);\n this.sound.play();\n this.targetIdTrue = 5;\n }\n }\n }",
"function renderSelectedBall() {\n for (var i = 0; i < level.columns; i++) {\n for (var j = 0; j < level.rows; j++) {\n if (level.selectedball.selected) {\n drawBall(level.balls[level.selectedball.column][level.selectedball.row].posX, level.balls[level.selectedball.column][level.selectedball.row].posY, 'red')\n }\n }\n }\n }",
"function grabBall() {\n\tvar playersThere = (distObj(me, ball) < 50 || distObj(opp, ball)<50);\n\tif (!ball.getPossessed() && !ball.isShooting() && playersThere) {\n\t\tif (distObj(me, ball) < distObj(opp, ball) && ball.getBallTo() != me) {\n\t\t\tball.posess(me);\n\t\t\tme.setHasBall(true);\n\t\t}\n\t\telse if (distObj(me, ball) >= distObj(opp, ball) && ball.getBallTo() != opp) {\n\t\t\tball.posess(opp);\n\t\t\topp.setHasBall(true);\n\t\t}\n\t}\n\telse if (distObj(me, ball) < 70 && !me.getHasBall() && ball.getPossessed) {\n\t\tme.inStealRange = true;\n\t}\n}",
"function addBall () {\n\t\tballs[balls.length] = new Ball(app.canvas.width/1,app.canvas.height/4);\n\t\tball = balls[balls.length-1];\n\t\tball.active = false;\n\t\tselected = true;\n\t}",
"goalAchieved(ball) {\n let d = dist(this.x, this.y, ball.x, ball.y);\n if (d < this.size + (ball.size / 2)) {\n if (this.targetId === 1 && this.targetIdTrue === 0) {\n this.fillColor = 0;\n this.targetIdTrue = 1;\n console.log(\"test\");\n } else if (this.targetId === 3 && this.targetIdTrue === 0) {\n this.fillColor = 0;\n this.targetIdTrue = 3;\n } else if (this.targetId === 5 && this.targetIdTrue === 0) {\n this.fillColor = 0;\n this.targetIdTrue = 5;\n }\n }\n}",
"function clickBall(x, y) {\n for (var i = 0; i < level.columns; i++) {\n for (var j = 0; j < level.rows; j++) {\n var maxX = Math.round(level.balls[i][j].posX + level.radius + 1)\n var maxY = Math.round(level.balls[i][j].posY + level.radius + 1)\n var minX = Math.round(level.balls[i][j].posX - level.radius - 1)\n var minY = Math.round(level.balls[i][j].posY - level.radius - 1)\n if (x > minX && x < maxX && y > minY && y < maxY && level.selectedball.selected != true) {\n level.selectedball.selected = true;\n level.selectedball.column = i;\n level.selectedball.row = j;\n } else if (x > minX && x < maxX && y > minY && y < maxY) {\n var c1 = level.selectedball.column\n var r1 = level.selectedball.row\n var c2 = i;\n var r2 = j;\n canMove(c1, r1, c2, r2);\n level.selectedball.selected = false;\n }\n }\n }\n }",
"kick(_position, _ball) {\n let dir = Abschlussarbeit.calculateDirection(this.position, _position);\n //let precision affect kick direction\n if (Math.random() < 0.5) // 50/50 chance\n dir.x *= this.precision; //x precision is affected\n else\n dir.y *= this.precision; //y precision is affected\n dir = Abschlussarbeit.normalizeVector(dir);\n _ball.direction = dir;\n _ball.speed = this.strength;\n _ball.free = true;\n let currentPlayer = document.getElementById(\"currentPlayer\");\n currentPlayer.textContent = \"\";\n }",
"function stroke() {\n click = click + 1;\n var random = Math.floor(Math.random() * (650 - 20) + 20);\n draw.clearRect(0, 0, ground.width, ground.height);\n const ball = new Ball(random, 150, 10, \"white\");\n score = checkPlayer_1_Ball(ball.x, click);\n document.getElementById(\"result\").innerHTML = \"score:\" + score;\n\n console.log(click);\n ball.drawBall();\n hole.drawHole();\n}",
"function dropBall() {\n // console.log('dropBall called')\n /* add a Ball at the top center of the canvas to the list of balls */\n balls.push(new Ball({\n x: CANVAS_WIDTH / 2,\n y: 3 * BALL_RADIUS,\n radius: BALL_RADIUS,\n mass: BALL_MASS,\n bounciness: 0.8,\n // color: COLORS[Math.floor(COLORS.length * Math.random())],\n color: \"red\",\n // color: \"red\",\n alpha: .5\n }))\n // console.log('balls length', balls.length)\n // console.log('balls', balls)\n stage.addChild(balls[balls.length-1])\n}",
"function drop() {\n var ballIndex = Math.floor(Math.random() * 9999) % balls.length,\n ball = sym.createChildSymbol(balls[ballIndex], \"RoundRect\");\n ball.play();\n }",
"function runMild(){\n this.ballMd.setActive();\n}",
"function nextBall() {\n \n if (batter_goal===\"achieved\" && bowler_goal===\"achieved\" && ball_goal===\"achieved\" && canv_ballcount<datasize) {\n canv_ballcount++;\n scoreupdate=0;\n\n //update the current runs\n setBallResult();\n resetMainStates();\n setBatterHelmet(1);\n setBatterHelmet(2); \n \n }\n //if innings balls completed. REDUNDANT?\n if (canv_ballcount>datasize && inningscount==1) { //Innings1.getMaxBalls()\n //canv_ballcount=0;\n inningscount++;\n }\n }",
"function ballPowerUpCollide() {\r\n powerUp.visible = false;\r\n ball.fill = powerUpColor;\r\n console.log(\"Power Up acquired! You can smash through bricks now.\");\r\n}",
"drawBall(){\n \tstroke(0);\n strokeWeight(2);\n \tfill(car, did, ele);\n\t\t rect(this.x,this.y,50,50);\n\t}",
"function changeBall(){\n\tvar x = Randomizer.nextInt(ball.getRadius(),\n\t\tgetWidth() - ball.getRadius());\n\tvar y = Randomizer.nextInt(ball.getRadius(), getHeight() - ball.getRadius());\n\t\n\tball.setPosition(x, y);\n\tchangeColor();\n}",
"function drawBall(){\n\t\t//Clear old ball\n\t\tclearBall(ball.left,ball.top);\n\t\t\n\t\t//Update ball location\n\t\tball.left += speed.x;\n\t\tball.right = ball.left + ball.size;\n\t\tball.top += speed.y;\n\t\tball.bottom = ball.top + ball.size;\n\t\t\n\t\t//Draw the new ball\n\t\tdrawCircle(ball.left, ball.top);\n\t\t\n\t\t//If darkness is true and nightmare is false, lightup ball and check if token should be lit\n\t\tif(mode.darkness && mode.nightmare == false){\n\t\t\tlightUp(ball.left, ball.top);\n\t\t\tif(token.lightOn && settings.mode == \"glowing\"){\n\t\t\t\ttokenLightUp();\n\t\t\t}\n\t\t}\n\t}",
"PillarBomba(player,bomba){\n if(!bomba.recogida && player.modifier !== 'bomba'){ // Si el player ya tiene una bomba la nueva bmba no se pilla\n bomba.PickMe();\n player.changeModifierBomba(bomba.index);\n }\n}",
"function setBallType(){ \n for (var i = 0; i < serverBalls.length; i++){\n var missingBallColor = null; // Hold the color of the server ball\n var check = balls.filter(function (obj) {\n missingBallColor = serverBalls[i].color\n return obj.color === serverBalls[i].color;\n });\n \n // If client ball is missing check if the ball isStripe\n if (check.length == 0){\n var findBall = serverBalls.filter(function (obj) { \n return obj.color === missingBallColor;\n });\n missingBalls.push(findBall[0]);\n }\n console.log(check);\n }\n \n // If client ball is missing check if the ball isStripe \n for (var i=0; i < missingBalls.length; i++){\n if (missingBalls[i].isStripe == false){\n console.log(\"ATENCION!!! La bola es: \"+missingBalls[i].isStripe);\n solidCount++; \n console.log(\"Cantidad solidas: \"+solidCount+\", anoto player: \"+player.number);\n } else {\n stripeCount++;\n console.log(\"Cantidad Stripes: \"+stripeCount);\n } \n console.log(\"Cantidad solidas: \"+solidCount);\n console.log(\"Cantidad Stripes: \"+stripeCount);\n console.log(\"Anotó player: \"+player.number);\n }\n\n // Stripe count or solid count is 0 assign isStripe to player \n if (solidCount > 0 & stripeCount == 0){\n // Emit isStripe = true to the player\n io.to(room).emit('solidstripe', player.number, 'solid');\n changePlayer = false;\n }\n if (stripeCount > 0 & solidCount == 0){\n // Emit isStripe = false to the player\n io.to(room).emit('solidstripe', player.number, 'stripe');\n changePlayer = false; \n }\n \n // If both solids and stripes made it into the pockets\n if (solidCount > 0 && stripeCount > 0){\n io.to(room).emit('solidstripe', player.number, 'solid');\n // Two balls fell so change player\n changePlayer = true;\n io.to(room).emit('changePlayer', player.number, serverGame[0].cueball);\n } \n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Used to create an empty directive. This is used to track flagdirectives whose children may have functionality based on them. Example: `mdnoink` will potentially be used by all child directives. | function attrNoDirective () {
return { controller: angular.noop };
} | [
"function attrNoDirective () {\n\t return { controller: angular.noop };\n\t}",
"function attrNoDirective() {\n return {\n controller: angular.noop\n };\n }",
"function attrNoDirective () {\n return { controller: angular.noop };\n}",
"function createDirectiveType(meta) {\n var typeParams = createBaseDirectiveTypeParams(meta); // Directives have no NgContentSelectors slot, but instead express a `never` type\n // so that future fields align.\n\n typeParams.push(NONE_TYPE);\n typeParams.push(expressionType(literal(meta.isStandalone)));\n return expressionType(importExpr(Identifiers.DirectiveDeclaration, typeParams));\n} // Define and update any view queries",
"function instantiateDirectivesDirectly() {\n var tNode = previousOrParentNode.tNode;\n var count = tNode.flags & 4095;\n if (count > 0) {\n var start = tNode.flags >> 13;\n var end = start + count;\n var tDirectives = currentView.tView.directives;\n for (var i = start; i < end; i++) {\n var def = tDirectives[i];\n directiveCreate(i, def.factory(), def);\n }\n }\n}",
"function instantiateDirectivesDirectly() {\n var tNode = (previousOrParentNode.tNode);\n var count = tNode.flags & 4095;\n if (count > 0) {\n var start = tNode.flags >> 13;\n var end = start + count;\n var tDirectives = (currentView.tView.directives);\n for (var i = start; i < end; i++) {\n var def = tDirectives[i];\n directiveCreate(i, def.factory(), def);\n }\n }\n}",
"visitEmptyDeclaration(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function instantiateDirectivesDirectly() {\n var tNode = previousOrParentNode.tNode;\n var count = tNode.flags & 4095 /* DirectiveCountMask */;\n if (count > 0) {\n var start = tNode.flags >> 14 /* DirectiveStartingIndexShift */;\n var end = start + count;\n var tDirectives = tView.directives;\n for (var i = start; i < end; i++) {\n var def = tDirectives[i];\n directiveCreate(i, def.factory(), def);\n }\n }\n}",
"function noDataFound() {\n return {\n restrict: 'A',\n scope: true,\n templateUrl: 'views/common/noDataFound.html',\n }\n}",
"function AbstractDirective() {\n\n\t// directives need the same foundation as viewable services\n\tAbstractViewableService.apply(this, arguments);\n\n\tif (this.isolated && !(this.scope instanceof Object)) {\n\t\tthis.scope = {};\n\t}\n\n}",
"function disableLayoutDirective() {\n // Return a 1x-only, first-match attribute directive\n config.enabled = false;\n\n return {\n restrict : 'A',\n priority : '900'\n };\n }",
"function DirectiveType(){}",
"function addNoCompileAttributes(tElement){angular.forEach(tElement,function(el){1===el.nodeType&&angular.element(el).attr(\"dir-paginate-no-compile\",!0)})}",
"function disableLayoutDirective(){return{restrict:'A',priority:'900',compile:function compile(element,attr){config.enabled=false;return angular.noop;}};}",
"function removeEmptyTargets() {\n var targets = element.find('[transclude-id]');\n\n angular.forEach(targets, removeIfEmpty);\n }",
"constructor ( ...children ) {\n super( ...children )\n this.setAttribute( 'declaration', 'none' )\n this.setAttribute( 'formula', false )\n }",
"function addNoCompileAttributes(tElement) {\n\t\t\tangular.forEach(tElement, function(el) {\n\t\t\t\tif (el.nodeType === 1) {\n\t\t\t\t\tangular.element(el).attr('dir-paginate-no-compile', true);\n\t\t\t\t}\n\t\t\t});\n\t\t}",
"_dummy() {\n return new XMLBuilderImpl(this._doc.createElement('dummy_node'));\n }",
"function none$1() {\n return {\n id: 'none',\n name: '',\n grammar: {\n main: []\n }\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine whether the given properties match those of a `RuleActionProperty` | function CfnRuleGroup_RuleActionPropertyValidator(properties) {
if (!cdk.canInspect(properties)) {
return cdk.VALIDATION_SUCCESS;
}
const errors = new cdk.ValidationResults();
if (typeof properties !== 'object') {
errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));
}
errors.collect(cdk.propertyValidator('allow', cdk.validateObject)(properties.allow));
errors.collect(cdk.propertyValidator('block', cdk.validateObject)(properties.block));
errors.collect(cdk.propertyValidator('captcha', cdk.validateObject)(properties.captcha));
errors.collect(cdk.propertyValidator('challenge', cdk.validateObject)(properties.challenge));
errors.collect(cdk.propertyValidator('count', cdk.validateObject)(properties.count));
return errors.wrap('supplied properties not correct for "RuleActionProperty"');
} | [
"function CfnWebACL_RuleActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('allow', CfnWebACL_AllowActionPropertyValidator)(properties.allow));\n errors.collect(cdk.propertyValidator('block', CfnWebACL_BlockActionPropertyValidator)(properties.block));\n errors.collect(cdk.propertyValidator('captcha', CfnWebACL_CaptchaActionPropertyValidator)(properties.captcha));\n errors.collect(cdk.propertyValidator('challenge', CfnWebACL_ChallengeActionPropertyValidator)(properties.challenge));\n errors.collect(cdk.propertyValidator('count', CfnWebACL_CountActionPropertyValidator)(properties.count));\n return errors.wrap('supplied properties not correct for \"RuleActionProperty\"');\n}",
"function CfnRule_ActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('forward', cdk.requiredValidator)(properties.forward));\n errors.collect(cdk.propertyValidator('forward', CfnRule_ForwardPropertyValidator)(properties.forward));\n return errors.wrap('supplied properties not correct for \"ActionProperty\"');\n}",
"function CfnRule_ActionsPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('assignContactCategoryActions', cdk.listValidator(cdk.validateObject))(properties.assignContactCategoryActions));\n errors.collect(cdk.propertyValidator('eventBridgeActions', cdk.listValidator(CfnRule_EventBridgeActionPropertyValidator))(properties.eventBridgeActions));\n errors.collect(cdk.propertyValidator('sendNotificationActions', cdk.listValidator(CfnRule_SendNotificationActionPropertyValidator))(properties.sendNotificationActions));\n errors.collect(cdk.propertyValidator('taskActions', cdk.listValidator(CfnRule_TaskActionPropertyValidator))(properties.taskActions));\n return errors.wrap('supplied properties not correct for \"ActionsProperty\"');\n}",
"function CfnTrigger_ActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('arguments', cdk.validateObject)(properties.arguments));\n errors.collect(cdk.propertyValidator('crawlerName', cdk.validateString)(properties.crawlerName));\n errors.collect(cdk.propertyValidator('jobName', cdk.validateString)(properties.jobName));\n errors.collect(cdk.propertyValidator('notificationProperty', CfnTrigger_NotificationPropertyPropertyValidator)(properties.notificationProperty));\n errors.collect(cdk.propertyValidator('securityConfiguration', cdk.validateString)(properties.securityConfiguration));\n errors.collect(cdk.propertyValidator('timeout', cdk.validateNumber)(properties.timeout));\n return errors.wrap('supplied properties not correct for \"ActionProperty\"');\n}",
"function CfnDataset_ActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('actionName', cdk.requiredValidator)(properties.actionName));\n errors.collect(cdk.propertyValidator('actionName', cdk.validateString)(properties.actionName));\n errors.collect(cdk.propertyValidator('containerAction', CfnDataset_ContainerActionPropertyValidator)(properties.containerAction));\n errors.collect(cdk.propertyValidator('queryAction', CfnDataset_QueryActionPropertyValidator)(properties.queryAction));\n return errors.wrap('supplied properties not correct for \"ActionProperty\"');\n}",
"matchesPropertyFilter(rules) {\n if (!rules) {\n return false\n }\n\n // If there is an operationType then that means we're AND'ing or OR'ing\n // the results of two sets of rules, a left and right\n if (rules.operationType) {\n switch (rules.operationType.toLowerCase()) {\n case AND:\n return this.matchesPropertyFilter(rules.left) && this.matchesPropertyFilter(rules.right)\n case OR:\n return this.matchesPropertyFilter(rules.left) || this.matchesPropertyFilter(rules.right)\n default:\n throw new Error(`Unrecognized filter rule operation type: ${rules.operationType}`)\n }\n }\n\n // Otherwise evaluate the filter based on the value type (data type)\n switch (rules.valueType.toLowerCase()) {\n case STRING:\n return this.matchesStringFilter(rules)\n case NUMBER:\n return this.matchesNumberFilter(rules)\n default:\n throw new Error(`Unsupported value type: ${rules.valueType}`)\n }\n }",
"function CfnLoggingConfiguration_ActionConditionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('action', cdk.requiredValidator)(properties.action));\n errors.collect(cdk.propertyValidator('action', cdk.validateString)(properties.action));\n return errors.wrap('supplied properties not correct for \"ActionConditionProperty\"');\n}",
"function CfnRule_TaskActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('contactFlowArn', cdk.requiredValidator)(properties.contactFlowArn));\n errors.collect(cdk.propertyValidator('contactFlowArn', cdk.validateString)(properties.contactFlowArn));\n errors.collect(cdk.propertyValidator('description', cdk.validateString)(properties.description));\n errors.collect(cdk.propertyValidator('name', cdk.requiredValidator)(properties.name));\n errors.collect(cdk.propertyValidator('name', cdk.validateString)(properties.name));\n errors.collect(cdk.propertyValidator('references', cdk.hashValidator(CfnRule_ReferencePropertyValidator))(properties.references));\n return errors.wrap('supplied properties not correct for \"TaskActionProperty\"');\n}",
"function CfnWebACL_WafActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('type', cdk.requiredValidator)(properties.type));\n errors.collect(cdk.propertyValidator('type', cdk.validateString)(properties.type));\n return errors.wrap('supplied properties not correct for \"WafActionProperty\"');\n}",
"function CfnWebACL_ChallengeActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('customRequestHandling', CfnWebACL_CustomRequestHandlingPropertyValidator)(properties.customRequestHandling));\n return errors.wrap('supplied properties not correct for \"ChallengeActionProperty\"');\n}",
"function CfnRule_MatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('httpMatch', cdk.requiredValidator)(properties.httpMatch));\n errors.collect(cdk.propertyValidator('httpMatch', CfnRule_HttpMatchPropertyValidator)(properties.httpMatch));\n return errors.wrap('supplied properties not correct for \"MatchProperty\"');\n}",
"function CfnWebACL_AllowActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('customRequestHandling', CfnWebACL_CustomRequestHandlingPropertyValidator)(properties.customRequestHandling));\n return errors.wrap('supplied properties not correct for \"AllowActionProperty\"');\n}",
"function CfnTopicRule_ElasticsearchActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('endpoint', cdk.requiredValidator)(properties.endpoint));\n errors.collect(cdk.propertyValidator('endpoint', cdk.validateString)(properties.endpoint));\n errors.collect(cdk.propertyValidator('id', cdk.requiredValidator)(properties.id));\n errors.collect(cdk.propertyValidator('id', cdk.validateString)(properties.id));\n errors.collect(cdk.propertyValidator('index', cdk.requiredValidator)(properties.index));\n errors.collect(cdk.propertyValidator('index', cdk.validateString)(properties.index));\n errors.collect(cdk.propertyValidator('roleArn', cdk.requiredValidator)(properties.roleArn));\n errors.collect(cdk.propertyValidator('roleArn', cdk.validateString)(properties.roleArn));\n errors.collect(cdk.propertyValidator('type', cdk.requiredValidator)(properties.type));\n errors.collect(cdk.propertyValidator('type', cdk.validateString)(properties.type));\n return errors.wrap('supplied properties not correct for \"ElasticsearchActionProperty\"');\n}",
"function CfnAlarmModel_AlarmActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('dynamoDb', CfnAlarmModel_DynamoDBPropertyValidator)(properties.dynamoDb));\n errors.collect(cdk.propertyValidator('dynamoDBv2', CfnAlarmModel_DynamoDBv2PropertyValidator)(properties.dynamoDBv2));\n errors.collect(cdk.propertyValidator('firehose', CfnAlarmModel_FirehosePropertyValidator)(properties.firehose));\n errors.collect(cdk.propertyValidator('iotEvents', CfnAlarmModel_IotEventsPropertyValidator)(properties.iotEvents));\n errors.collect(cdk.propertyValidator('iotSiteWise', CfnAlarmModel_IotSiteWisePropertyValidator)(properties.iotSiteWise));\n errors.collect(cdk.propertyValidator('iotTopicPublish', CfnAlarmModel_IotTopicPublishPropertyValidator)(properties.iotTopicPublish));\n errors.collect(cdk.propertyValidator('lambda', CfnAlarmModel_LambdaPropertyValidator)(properties.lambda));\n errors.collect(cdk.propertyValidator('sns', CfnAlarmModel_SnsPropertyValidator)(properties.sns));\n errors.collect(cdk.propertyValidator('sqs', CfnAlarmModel_SqsPropertyValidator)(properties.sqs));\n return errors.wrap('supplied properties not correct for \"AlarmActionProperty\"');\n}",
"function CfnMitigationAction_ActionParamsPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('addThingsToThingGroupParams', CfnMitigationAction_AddThingsToThingGroupParamsPropertyValidator)(properties.addThingsToThingGroupParams));\n errors.collect(cdk.propertyValidator('enableIoTLoggingParams', CfnMitigationAction_EnableIoTLoggingParamsPropertyValidator)(properties.enableIoTLoggingParams));\n errors.collect(cdk.propertyValidator('publishFindingToSnsParams', CfnMitigationAction_PublishFindingToSnsParamsPropertyValidator)(properties.publishFindingToSnsParams));\n errors.collect(cdk.propertyValidator('replaceDefaultPolicyVersionParams', CfnMitigationAction_ReplaceDefaultPolicyVersionParamsPropertyValidator)(properties.replaceDefaultPolicyVersionParams));\n errors.collect(cdk.propertyValidator('updateCaCertificateParams', CfnMitigationAction_UpdateCACertificateParamsPropertyValidator)(properties.updateCaCertificateParams));\n errors.collect(cdk.propertyValidator('updateDeviceCertificateParams', CfnMitigationAction_UpdateDeviceCertificateParamsPropertyValidator)(properties.updateDeviceCertificateParams));\n return errors.wrap('supplied properties not correct for \"ActionParamsProperty\"');\n}",
"function CfnTopicRule_CloudwatchAlarmActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('alarmName', cdk.requiredValidator)(properties.alarmName));\n errors.collect(cdk.propertyValidator('alarmName', cdk.validateString)(properties.alarmName));\n errors.collect(cdk.propertyValidator('roleArn', cdk.requiredValidator)(properties.roleArn));\n errors.collect(cdk.propertyValidator('roleArn', cdk.validateString)(properties.roleArn));\n errors.collect(cdk.propertyValidator('stateReason', cdk.requiredValidator)(properties.stateReason));\n errors.collect(cdk.propertyValidator('stateReason', cdk.validateString)(properties.stateReason));\n errors.collect(cdk.propertyValidator('stateValue', cdk.requiredValidator)(properties.stateValue));\n errors.collect(cdk.propertyValidator('stateValue', cdk.validateString)(properties.stateValue));\n return errors.wrap('supplied properties not correct for \"CloudwatchAlarmActionProperty\"');\n}",
"function CfnRuleGroup_ActionDefinitionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('publishMetricAction', CfnRuleGroup_PublishMetricActionPropertyValidator)(properties.publishMetricAction));\n return errors.wrap('supplied properties not correct for \"ActionDefinitionProperty\"');\n}",
"function CfnTrigger_PredicatePropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n errors.collect(cdk.propertyValidator('conditions', cdk.listValidator(CfnTrigger_ConditionPropertyValidator))(properties.conditions));\n errors.collect(cdk.propertyValidator('logical', cdk.validateString)(properties.logical));\n return errors.wrap('supplied properties not correct for \"PredicateProperty\"');\n}",
"function CfnWebACL_CaptchaActionPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('customRequestHandling', CfnWebACL_CustomRequestHandlingPropertyValidator)(properties.customRequestHandling));\n return errors.wrap('supplied properties not correct for \"CaptchaActionProperty\"');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete team member from team list, JSON, diagram, and events | function deleteMember(pillId) {
$('#confirmAction').modal('hide');
// remove from members array
var indexOfJSON = getMemberJSONIndex(pillId);
var members = flashTeamsJSON["members"];
var memberId = members[indexOfJSON].id;
//console.log("deleting member " + memberId);
//console.log("clicked #mPill_", pillId);
$("#mPill_" + memberId).popover('destroy');
members.splice(indexOfJSON, 1);
renderPills(members);
renderMemberPopovers(members);
// remove from members array with event object
for(var i=0; i<flashTeamsJSON["events"].length; i++){
var ev = flashTeamsJSON["events"][i];
var member_event_index = ev.members.indexOf(memberId);
// remove member
if(member_event_index != -1){ // found member in the event
removeAllMemberCircles(ev);
ev.members.splice(member_event_index,1);
drawEvent(ev,false);
}
//remove dri if the member was a dri
if (ev.dri == String(memberId)){
ev.dri = "";
}
}
// update event popovers
drawAllPopovers();
updateStatus(false);
} | [
"function deleteTeam(req, res) {\n Team.deleteMany({_id: req.params.id}, (err, result) => {\n if (err) {\n res.json({\n message: 'Test - No teams were found with given Id. Try again.',\n });\n } else {\n switch (result.n) {\n case 1:\n res.json({\n message: 'Team successfully deleted!',\n result\n });\n break;\n case 0:\n res.json({\n message: 'Postmam - No teams were found with given Id. Try again.',\n result\n });\n break;\n default:\n res.json({\n message: 'Something gone wrong. Check the result.',\n result\n });\n break;\n };\n };\n });\n}",
"function deleteTeam(req, res) {\n \n Team.findByIdAndRemove(req.params.teamId)\n .exec()\n .then(() => \n res.status(200).send('Team removed')\n )\n .catch(error => { throw error })\n}",
"function delete_team()\n{\n\tif (confirm(\"Are you sure that you want to delete team \" + G_selected_team) == true) \n\t{\n\t\tif (confirm(\"Are you ABSOLUTELY sure that you want to delete team \" + G_selected_team) == true) \n\t\t{\n\t\t\tclear_and_display_modal();\n\t\t\twrite_modal (\"Deleting team \" + G_selected_team + \"...\");\n \t \t// construct the SQL Delete command\n \t\tvar mysql = \"DELETE FROM RRM_2018_Data WHERE Team_Code='\" + G_selected_team + \"';\"; \n \t\n \t\tadd_event (EVENT_TYPE_DELETE_FROM_DB, G_selected_team, \"\");\n\t\t\tdo_sql (mysql, proceed_delete_team1,\"\")\n\t\t\twrite_modal (\"Please wait for operation to complete\");\n\t\t\treturn; \t\n\t\t} \n\t}\n}",
"function deleteEventMember(eventId, memberNum, memberName) {\n //Delete the line\n $(\"#event_\" + eventId + \"_eventMemLine_\" + memberNum).remove();\n\n //Update the JSON\n var indexOfJSON = getEventJSONIndex(eventId);\n for (i = 0; i < flashTeamsJSON[\"events\"][indexOfJSON].members.length; i++) {\n if (flashTeamsJSON[\"events\"][indexOfJSON].members[i] == memberName) {\n flashTeamsJSON[\"events\"][indexOfJSON].members.splice(i, 1);\n //START HERE IF YOU WANT TO SHIFT UP MEMBER LINES AFTER DELETION\n break;\n }\n }\n}",
"function deleteTeam(id){\n\t$.ajax({\n\t type : \"DELETE\",\n\t url : url + '/' + id,\n\t\terror: function(xhr, status, error) {\n\t\t\ttoastr.error('DELETE error');\n\t\t}\n\t});\n}",
"async function dropFromTeam( req, res, next ){\n const teamId = req.params.id;\n const user = {\n userId : res.claims.userId,\n email : res.claims.email\n }\n //console.log(user);\n\n try{\n //console.log(user);\n const team = await Team.findByIdAndUpdate( teamId, { $pull: { \"members\" : user } } );\n\n // OPTIONAL - after dropping from team drop from the team meetings as well\n res.json(team);\n\n }catch( error ){\n error.status = 500;\n next( error );\n }\n\n}",
"function deleteEventMember(eventId, memberNum) {\n if (memberNum == current){\n $(\"#rect_\" + eventId).attr(\"fill\", TASK_NOT_START_COLOR)\n }\n\n //Update the JSON then redraw the event\n var indexOfJSON = getEventJSONIndex(eventId);\n var event = flashTeamsJSON[\"events\"][indexOfJSON];\n var indexInEvent = event.members.indexOf(memberNum);\n if(indexInEvent != -1) {\n event.members.splice(indexInEvent, 1);\n drawEvent(event);\n }\n}",
"function removeMember(teamId, memberId) {\n $.ajax({\n type: \"DELETE\",\n url: `/api/teams/${teamId}/members/${memberId}`\n })\n .done(function() {\n //alert(\"Deleted successfully!\");\n location.reload();\n })\n .fail(function() {\n //alert(\"There was a problem, please try again.\");\n });\n\n return false;\n}",
"async deleteTeamByID(ctx) {\n await Model.team\n .deleteOne({ _id: ctx.params.id })\n .then(result => {\n if(result.deletedCount > 0) { ctx.body = \"Delete Successful\"; }\n else { throw \"Error deleting team\"; }\n })\n .catch(error => {\n throw new Error(error);\n });\n }",
"function deleteEventMember(eventId, memberNum) {\n if (memberNum == current){\n $(\"#rect_\" + eventId).attr(\"fill\", TASK_NOT_START_COLOR)\n }\n\n logActivity(\"deleteEventMember(eventId, memberNum)\",'Delete Event Member - Before', new Date().getTime(), current_user, chat_name, team_id, flashTeamsJSON[\"events\"][getEventJSONIndex(eventId)]);\n\n //Update the JSON then redraw the event\n var indexOfJSON = getEventJSONIndex(eventId);\n var event = flashTeamsJSON[\"events\"][indexOfJSON];\n var indexInEvent = event.members.indexOf(memberNum);\n if(indexInEvent != -1) {\n event.members.splice(indexInEvent, 1);\n drawEvent(event);\n }\n\n logActivity(\"deleteEventMember(eventId, memberNum)\",'Delete Event Member - After', new Date().getTime(), current_user, chat_name, team_id, flashTeamsJSON[\"events\"][getEventJSONIndex(eventId)]);\n\n}",
"function removeTeamFromDivision(team) {\n //log object\n let logObj = {};\n logObj.actor = 'SYSTEM SUBROUTINE removeTeamFromDivision';\n logObj.action = ' remove team from division ';\n logObj.target = team;\n logObj.logLevel = 'STD';\n logObj.timeStamp = new Date().getTime();\n\n //find division the team belongs to\n Division.findOne({\n teams: team\n }).then(\n (foundDiv) => {\n if (foundDiv) {\n logObj.target += ' ' + foundDiv.displayName;\n //get index of the team in the array\n let ind = foundDiv.teams.indexOf(team);\n //remove team from array\n foundDiv.teams.splice(ind, 1);\n //save the div\n foundDiv.save().then(saved => {\n logger(logObj);\n }, err => {\n logObj.logLevel = 'ERROR';\n logObj.error = err;\n logger(logObj);\n })\n } else {\n logObj.logLevel = 'ERROR';\n logObj.error = 'Error finding div';\n logger(logObj);\n\n }\n },\n (err) => {\n logObj.logLevel = 'ERROR';\n logObj.error = err;\n logger(logObj);\n }\n )\n}",
"function removeTeam(state, id) {\n //TBC\n}",
"function memberDelete(i,j){\n self.projectList[i].memberList.splice(j,1);\n self.oneIndex = i;\n projectUpdate(self.projectList[i]);\n $state.go('home');\n }",
"deleteMember(event) {\n groupPopMessage.textContent = 'Deleting Member';\n groupPopUp();\n const id = event.target.dataset.userid;\n const groupId = event.target.dataset.groupid;\n const url = `https://epic-mail-2018.herokuapp.com/api/v1/groups/${groupId}/users/${id}`;\n return setTimeout(() => fetchDeleteMember(url), 1000);\n }",
"function remove_team(player1, team) {\n const index = player1.teams.indexOf(team)\n if(index > -1) {\n array.splice(index, 1)\n }\n}",
"urlForDeleting() {\n return `/settings/${Spark.pluralTeamString}/${this.team.id}/members/${this.deletingTeamMember.id}`;\n }",
"\"teams.remove\"(_id) {\n\t\tif (!this.userId) {\n\t\t\tthrow new Meteor.Error(\"not-authorized\");\n\t\t}\n\n\t\tnew SimpleSchema({\n\t\t\t_id: { type: String, min: 1 }\n\t\t}).validate({ _id });\n\n\t\tTeams.remove({ _id, userId: this.userId });\n\t}",
"function participant_modal_detail_remove_from_member(id_member, id_participant){\n $.ajax({\n url : \"/api/members/\"+id_member+\"/participants/\"+id_participant,\n type : \"DELETE\",\n success : function(json) {\n },\n error : function(xhr,errmsg,err) {\n console.log(xhr.status + \": \" + xhr.responseText);\n }\n });\n}",
"function deleteEvent(eventId){\n\n $('#confirmAction').modal('hide');\n\n var indexOfJSON = getEventJSONIndex(eventId);\n var events = flashTeamsJSON[\"events\"];\n \n events.splice(indexOfJSON, 1);\n //console.log(\"event deleted from json\");\n \n //stores the ids of all of the interactions to erase\n var intersToDel = [];\n \n for (var i = 0; i < flashTeamsJSON[\"interactions\"].length; i++) {\n var inter = flashTeamsJSON[\"interactions\"][i];\n if (inter.event1 == eventId || inter.event2 == eventId) {\n intersToDel.push(inter.id);\n }\n }\n \n for (var i = 0; i < intersToDel.length; i++) {\n // remove from timeline\n var intId = intersToDel[i];\n deleteInteraction(intId);\n }\n\n removeTask(eventId);\n \n updateStatus(false);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check if Accuser is alive | function checkAccuserStatus(accuser, gameid) {
return new Promise((resolve, reject) => {
db.findOne({ player: accuser,gameid:gameid }, { status: 1, _id: 0 }, (err, docs) => {
if (err) console.error("There's a problem with the database: ", err);
else if (docs) console.log("accuser life check queried");
resolve(docs.status);
});
});
} | [
"function isAlive(user) {\n return Db.shared.get('users', user, 'isAlive');\n }",
"function isAlive() {\n\treturn (health > 0);\n}",
"function CheckAlive() {\n\tif(this.currentHealth <= 0) {\n\t\tDie();\n\t}\n}",
"function checkUserActive() {\n\t\t\tif (checking) {\n\t\t\t\tnewStatus = self.isUserActive();\n\t\t\t\tif (userStatus != newStatus && newStatus == true) {\n\t\t\t\t\t$(self).triggerHandler($.Acheta.UserActivityChecker.EVENT_USER_BECAME_ACTIVE);\n\t\t\t\t} else if(userStatus != newStatus && newStatus == false) {\n\t\t\t\t\t$(self).triggerHandler($.Acheta.UserActivityChecker.EVENT_USER_BECAME_INACTIVE);\n\t\t\t\t}\n\t\t\t\tuserStatus = newStatus;\n\t\t\t\tsetTimeout(function(){checkUserActive();}, interval);\n\t\t\t}\n\t\t}",
"function isSessionAlive() {\n\n console.log('Starting session listening');\n\n function testIsSession() {\n fetchAuthenticatedUser().then(function(user) {\n console.log('Still authenticated');\n }).fail(function(error) {\n console.log('Not authenticated', error);\n Communicator.mediator.trigger('app:user:sessionended');\n });\n }\n\n //Every 5 minutes\n setInterval(testIsSession, 5 * 60 * 1000);\n }",
"idleChecker() {\n this.idleTime += 1\n if (this.idleTime > MAX_IDLE_TIME && !this.idle) {\n this.idle = true\n this.ws.send(\n JSON.stringify({\n type: 'event',\n event: 'userEnterIdle',\n dataType: 'text',\n data: this.user.userId,\n })\n )\n }\n }",
"function isUserConnected() {\n\tif (userExist()) {\n\t\tshowContent();\n\t\tloadPage();\n\t\tredirectLogOff();\n\t} else {\n\t\thideContent();\n\t}\n}",
"alive (currentUser) {\r\n new Result().emit(currentUser.socket, '/v1/alive', '200', { 'status': 200, 'message': 'Ok' })\r\n }",
"function checklogin () {\n\t//TODO make a boolean checking if you have an active session on the server.\n}",
"function checkAlive (health) {\n if (health > 0) {\n return true;\n } else {\n return false;\n }\n}",
"function isPlayerAlive(){\n if(app.player.health < 1){\n app.playerAlive = false;\n } else{\n app.playerAlive = true;\n }\n}",
"checkIfAlive() {\n if (this.health < 0.1 && this.health > 0) { //check if its alive or not\n this.spyGone = true;\n }\n }",
"function checkUserActivity() {\n\t\t\tvar lastActive = settings.userActivity ? time() - settings.userActivity : 0;\n\n\t\t\t// Throttle down when no mouse or keyboard activity for 5 min.\n\t\t\tif ( lastActive > 300000 && settings.hasFocus ) {\n\t\t\t\tblurred();\n\t\t\t}\n\n\t\t\t// Suspend after 10 min. of inactivity when suspending is enabled.\n\t\t\t// Always suspend after 60 min. of inactivity. This will release the post lock, etc.\n\t\t\tif ( ( settings.suspendEnabled && lastActive > 600000 ) || lastActive > 3600000 ) {\n\t\t\t\tsettings.suspend = true;\n\t\t\t}\n\n\t\t\tif ( ! settings.userActivityEvents ) {\n\t\t\t\t$document.on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active touchend.wp-heartbeat-active', function() {\n\t\t\t\t\tuserIsActive();\n\t\t\t\t});\n\n\t\t\t\t$('iframe').each( function( i, frame ) {\n\t\t\t\t\tif ( isLocalFrame( frame ) ) {\n\t\t\t\t\t\t$( frame.contentWindow ).on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active touchend.wp-heartbeat-active', function() {\n\t\t\t\t\t\t\tuserIsActive();\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tsettings.userActivityEvents = true;\n\t\t\t}\n\t\t}",
"function checkActive() {\n var here;\n if (active === undefined) {\n return false;\n }\n \n function playerHere(player) {\n return _.any(here, function (uuid) {\n return player === uuid;\n });\n }\n \n // make sure a challenger hasn't left\n if (active.player1 !== '' && active.player2 !== '') {\n here = main.uuids();\n \n if (!playerHere(active.player1) || !playerHere(active.player2)) {\n return false;\n }\n }\n return true;\n }",
"function isUserActiveNow() {\n return isUserActive;\n}",
"isAlive() {\r\n return this.health > 0;\r\n }",
"function checkAlive (health) {\n return !(health <= 0)\n}",
"function isAlive(activePlayer) {\n if (activePlayer.health > 0) {\n return true;\n }\n return false ;\n}",
"checkAlive()\n { \n if(this.isAlive === false)\n {\n this.enemyLevel++;//increases what level enemy the player is on \n this.reset();//reset the enemy \n return false;//retrun that the enemy is dead\n }\n return true;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves a request token from Auth and calls the given callback with it. The request token is an object with the properties 'token', 'tokenSecret', 'consumerKey' and 'consumerSecret'. | function getRequestToken(accessor, callback) {
var message = {method: "post",
action: baseAuthUrl + "/request_token",
parameters: [["oauth_callback", "oob"]]};
OAuth.completeRequest(message, accessor);
var requestBody = OAuth.formEncode(message.parameters);
opera.postError("Trying to get a request token");
var requestTokenRequest = new XMLHttpRequest();
requestTokenRequest.onreadystatechange = function receiveRequestToken() {
if (requestTokenRequest.readyState == 4) {
var token = parseTokenFromText(requestTokenRequest.responseText);
token.consumerKey = accessor.consumerKey;
token.consumerSecret = accessor.consumerSecret;
callback(token);
}
}
requestTokenRequest.open(message.method, message.action, true);
requestTokenRequest.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
requestTokenRequest.send(requestBody);
} | [
"request(callback) {\n return strategy.requestToken((err, tok) => {\n //update our local knowledge of the token\n currentToken = tok && tok.accessToken;\n return callback(err, tok);\n });\n }",
"function requestCallback (method, url, token, callback) {\n const xhr = new XMLHttpRequest();\n xhr.open(method, url, true);\n xhr.setRequestHeader (\"Authorization\", token);\n xhr.onreadystatechange = function () {\n if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {\n callback(null, JSON.parse(xhr.response));\n } else {\n callback(xhr.status, xhr.response)\n }\n }\n xhr.send()\n}",
"function requestToken(next) {\n oauth.getOAuthRequestToken(function(error, oauthToken, oauthTokenSecret, results) {\n if (error) {\n next(error);\n } else {\n next(null, {requestToken:oauthToken, \n requestTokenSecret:oauthTokenSecret, \n redirectUrl:config.authorizeUrl + \"?oauth_token=\" + oauthToken});\n }\n });\n}",
"function get_request_token(callback) {\n\t\tvar url = 'https://api.twitter.com/oauth/request_token';\n\n\t\tvar params = (cfg.callback_url!=\"\")?'oauth_callback='+escape(cfg.callback_url):'';\n\n\t\tapi(url,'POST',params,function(resp){\n\t\t\tif (resp!=false) {\n\t\t\t\tvar responseParams = OAuth.getParameterMap(resp);\n\t\t\t\tcfg.request_token = responseParams['oauth_token'];\n\t\t\t\tcfg.request_token_secret = responseParams['oauth_token_secret'];\n\t\t\t\t\n\t\t\t\tTi.App.Properties.setString('oauth_token_tw',cfg.request_token);\n\t\t\t\tTi.App.Properties.setString('oauth_token_secret_tw',cfg.request_token_secret);\n\n\t\t\t\tTi.API.debug(\"fn-get_request_token: response was \"+resp);\n\t\t\t\tTi.API.debug(\"fn-get_request_token: config is now \"+JSON.stringify(cfg));\n\t\t\t\tTi.API.debug(\"fn-get_request_token: callback is \"+JSON.stringify(callback));\n\n\t\t\t\tget_request_verifier(callback);\n\t\t\t}\n\t\t},false,true,false);\n\t}",
"function authorize(callback) {\n if (!authorized) {\n get_request_token(callback);\n // get_request_token or a function it calls will call callback\n } else {\n // execute the callback function\n if ( typeof (callback) == 'function') {\n callback(authorized);\n }\n }\n return authorized;\n }",
"function getForgeToken(callback) {\n jQuery.ajax({\n url: '/forge/oauth/token',\n success: function (oauth) {\n if (callback)\n callback(oauth.access_token, oauth.expires_in);\n }\n });\n }",
"function getToken (callback){\n PythonShell.run('authorization.py', options, function(err){\n if (err) {\n console.log(err);\n return callback('Get Token start')\n }\n else {\n return callback(false)\n }\n });\n}",
"function auth(callback) {\n\toauth.getOAuthRequestToken(function(err, oauth_token, oauth_token_secret, results) {\n\t\t\tif (err) {\n\t\t\t\tconsole.log('error: ' + JSON.stringify(error));\n\t\t\t\tcallback(error, null);\n\t\t\t} else {\n\t\t\t\t// FIXME: store more than one token\n\t\t\t\toauthTokenSecert = oauth_token_secret;\n\t\t\t\tcallback(null, \"https://qa.test.powershop.co.nz/external_api/oauth/authorize?oauth_token=\" + oauth_token);\n\t\t\t}\n\t});\n}",
"function getForgeToken(callback) {\n jQuery.ajax({\n url: '/api/forge/oauth/public',\n success: function(res) {\n callback(res.access_token, res.expires_in);\n }\n });\n}",
"function fetchToken(code, callback) {\n\t//https request\n\taxios({\n\t\tmethod: 'post',\n\t\turl: TOKEN_URL,\n\t\theaders:{\n\t\t\t\"Authorization\": ENCODED_ID_SECRET,\n\t\t\t\"Content-Type\": CONTENT_TYPE\n\t\t},\n\t\tdata: querystring.stringify({\n\t\t\t\"grant_type\": GRANT_TYPE,\n\t\t\t\"redirect_uri\": REDIRECT_URI,\n\t\t\t\"code\":code\n\t\t})\n\t}).then(function(response){\n\t\tvar access_token = response.data['access_token'];\n\t\tcallback(null, access_token);\n\t}).catch(function(error){\n\t\t//pass error to async.waterfall\n\t\tcallback(error, null);\n\t});\n}",
"function authorize (callback) {\n console.log('authorize()')\n\n // Init OAuth\n var oauth = OAuth({\n consumer: {\n public: Homey.env.CLIENT_ID,\n secret: Homey.env.CLIENT_SECRET\n }\n })\n // Build request data\n var token_request_data = {\n url: 'https://api.twitter.com/oauth/request_token',\n method: 'POST',\n data: {\n oauth_callback: 'oob'// PIN based access\n }\n }\n\n // Send out the request\n request({\n url: token_request_data.url,\n method: token_request_data.method,\n json: true,\n form: oauth.authorize(token_request_data)\n }, function (error, response, body) {\n if (error) {\n console.error(error)\n }\n var jsonBody = qs.parse(body)\n\n // Check whether oauth has been confirmed\n if (jsonBody.oauth_callback_confirmed === 'true') {\n // Keep track of the requesttoken\n requestToken = {\n public: jsonBody.oauth_token,\n secret: jsonBody.oauth_secret\n }\n // Redirect the user to Twitter login\n callback(null, 'https://api.twitter.com/oauth/authenticate?oauth_token=' + jsonBody.oauth_token)\n } else {\n callback(__('pairing.authorized_error'))\n }\n })\n}",
"function oAuthCallback(res, req){\n\t//TODO: Automate token capture within application\n\tconsole.log(\"oAuth Callback called\");\n\tvar myURL = url.parse(req.url);\n\tvar code = myURL.searchParams.get('code');\n\tvar state = myURL.searchParams.get('state');\n\t\n\tconsole.log(\"Auth code is: \" + code);\n\tconsole.log(\"Auth state is: \" + state);\n}",
"function callAuthInfo(token, callback) {\n // Construct the payload to send to Janrain's auth_info endpoint.\n var post_data = querystring.stringify({\n 'token': token,\n 'apiKey': janrain_api_key,\n 'format': 'json'\n });\n\n var post_options = {\n host: 'rpxnow.com',\n path: '/api/v2/auth_info',\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Content-Length': post_data.length\n }\n };\n\n // Create the post request.\n var post_req = https.request(post_options, function(res) {\n var data = '';\n res.setEncoding('utf8');\n // Append data as we receive it from the Janrain server.\n res.on('data', function(d) {\n data += d;\n });\n // Once we have all the data, we can parse it and return the data we\n // want.\n res.on('end', function() {\n callback(JSON.parse(data));\n });\n });\n\n post_req.write(post_data);\n post_req.end();\n}",
"function get_access_token(callback) {\n\t\tvar url = 'https://api.twitter.com/oauth/access_token';\n\n\t\tapi(url,'POST','oauth_token='+cfg.request_token+'&oauth_verifier='+cfg.request_verifier,function(resp){\n\t\t\tif (resp!=false) {\n\t\t\t\tvar responseParams = OAuth.getParameterMap(resp);\n\t\t\t\tcfg.access_token = responseParams['oauth_token'];\n\t\t\t\tcfg.access_token_secret = responseParams['oauth_token_secret'];\n\t\t\t\tcfg.user_id = responseParams['user_id'];\n\t\t\t\tcfg.screen_name = responseParams['screen_name'];\n\t\t\t\taccessor.tokenSecret = cfg.access_token_secret;\n\t\t\t\tTitanium.App.Properties.setString('oauth_token',responseParams['oauth_token']);\n\t\t\t\tTitanium.App.Properties.setString('twt_user_id',responseParams['user_id']);\n\t\t\t\tTitanium.App.Properties.setString('screen_name',responseParams['screen_name']);\n\t\t\t\tTi.API.debug(\"fn-get_access_token: response was \"+resp);\n\n\t\t\t\tsave_access_token();\n\n\t\t\t\tauthorized = load_access_token();\n\n\t\t\t\tTi.API.debug(\"fn-get_access_token: the user is authorized is \"+authorized);\n\n\t\t\t\tTi.API.info('Authorization is complete. The callback fn is: '+JSON.stringify(callback));\n\n\t\t\t\t// execute the callback function\n\t\t\t\tif(typeof(callback)=='function'){\n\t\t\t\t\tTi.API.debug(\"fn-get_access_token: we are calling a callback function\");\n\t\t\t\t\tcallback(true);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tTi.API.info(\"Failed to get access token.\");\n\t\t\t\t// execute the callback function\n\t\t\t\tif(typeof(callback)=='function'){\n\t\t\t\t\tTi.API.debug(\"fn-get_access_token: we are calling a callback function\");\n\t\t\t\t\tcallback(false);\n\t\t\t\t}\n\t\t\t}\n\t\t},false,true,false);\n\t}",
"function exchangeToken(code, callback) {\n // make POST to /oauth/token with x-www-form-urlencoded client_id etc.\n request.post({\n url: oauth_config.host+'/oauth/token',\n form: {\n client_id: oauth_config.client_id,\n client_secret: oauth_config.client_secret,\n redirect_uri: oauth_config.redirect_uri,\n grant_type: 'authorization_code',\n code: code\n }\n }, function(error, response, body) {\n if (error) {\n // return any errors we got\n callback(error);\n return;\n }\n // log the response headers in case we need to debug issues\n console.log('\\n\\nexchange token response headers\\n', response.headers);\n console.log(body);\n\n const parsed = JSON.parse(body);\n if (parsed.access_token) {\n // success! return our token\n callback(null, parsed.access_token, parsed.created_at + parsed.expires_in);\n } else {\n // something weird happened so return the body as an error\n callback(parsed);\n }\n });\n}",
"function twitterAuth(callback) {\n var secretKey = `${twitterKey}:${twitterSecret}`;\n var b64SecretKey = Buffer.from(secretKey, 'utf8').toString('base64');\n console.log(secretKey + \" - \" + b64SecretKey);\n var headers = {\n 'Authorization': `Basic ${b64SecretKey}`,\n 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',\n }\n var options = {\n url: 'https://api.twitter.com/oauth2/token',\n method: 'POST',\n headers: headers,\n body: 'grant_type=client_credentials'\n }\n request(options, function (err, res, body) {\n if (!err && res.statusCode == 200) {\n callback(JSON.parse(body).access_token);\n } else {\n console.log(\"error getting twitter authentication token\");\n }\n })\n}",
"function fetchToken(auth_code, callback){\n let url = \"https://login.uber.com/oauth/v2/token?client_id=\"+client_id\n +\"&client_secret=\"+client_secret+\"&grant_type=authorization_code&redirect_uri=http://127.0.0.1&code=\" + auth_code;\n fetch(url,{\n method: \"POST\"\n }).then(response => response.json()).then(json => callback(json));\n}",
"function verifyTokenFn(req, res, next) {\n var bearer = \"\";\n const bearerHeader = req.headers[\"authorization\"];\n console.log(\" --beaderHeader --> \" + bearerHeader);\n if (bearerHeader != \"undefined\" || bearerHeader != \"\") {\n bearer = bearerHeader.split(\" \");\n } \n const bearerTkn = bearer[1];\n console.log(\" -- bearer Tokne --> \"+ bearerTkn);\n // Set the token in request\n req.token = bearerTkn;\n next();\n}",
"function processTokenCallback(kc, token) {\n if (kc.debug) {\n console.info('[SSI.KEYCLOAK] Processing Token');\n }\n try {\n setTokenIfValid(kc, token);\n } catch (e) {\n return kc.onAuthError(e);\n }\n return kc.onAuthSuccess();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Da update em um Contato | async update(request, response, next){
try{
const { name, email, whatsapp, city, uf } = request.body;
const { id } = request.params;
const contatoID = await connection('contatos').select('*').where({id: id});
if(contatoID != ""){
await connection('contatos')
.update({ name, email, whatsapp, city, uf })
.where({ id: id })
return response.json({ "Status": "Alterado com Sucesso!" });
}
return response.status(400).json({ "Status": "ID de Contato não encontrado!" });
}catch(error){
next(error)
}
} | [
"function update () {\n\t\t\tvar condicionventa = this.condicionventa ;\n\n\t\t\tif (this.enterprise !== undefined) { condicionventa.enterprise = this.enterprise._id } else { condicionventa.enterprise = condicionventa.enterprise._id };\n\n\t\t\tcondicionventa.$update(function() {\n\t\t\t\t$state.go('home.condicionVentas');\n\t\t\t}, function(errorResponse) {\n\t\t\t\tthis.error = errorResponse.data.message;\n\t\t\t});\n\t\t}",
"function update () {\n\t\t\t// console.log(this.comprobante.enterprise, 'ent');\n\t\t\t// console.log(this.comprobante, 'comp');\n\t\t\tvar transferencia = this.transferencia;\n\n\t\t\tif (this.enterprise !== undefined) { transferencia.enterprise = this.enterprise._id } else { transferencia.enterprise = transferencia.enterprise._id };\n\t\t\tif (this.modoFacturacion !== undefined) { transferencia.modoFacturacion = this.modoFacturacion } else { transferencia.modoFacturacion = comprobante.modoFacturacion };\n\n\t\t\t// comprobante.$update(function() {\n\t\t\t// \t$location.path('comprobantes/view/' + comprobante._id);\n\t\t\t// }, function(errorResponse) {\n\t\t\t// \tthis.error = errorResponse.data.message;\n\t\t\t// });\n\t\t}",
"static updateCama(req, res) {\n const { descripcion, numeroCama } = req.body\n return Camas\n .findByPk(req.params.id)\n .then((data) => {\n data.update({\n descripcion: descripcion || data.descripcion,\n numeroCama: numeroCama || data.numeroCama \n })\n .then(update => {\n res.status(200).send({\n message: 'Sala actualizado',\n data: {\n \n descripcion: descripcion || update.descripcion,\n numeroCama: numeroCama || update.numeroCama\n }\n })\n })\n .catch(error => res.status(400).send(error));\n })\n .catch(error => res.status(400).send(error));\n }",
"async update ({ params, request }) {\n const data = request.only(['ciclo_numero', 'ciclo_ano', 'ciclo_ativo']);\n const ciclo = await Ciclo.findOrFail(params.id);\n\n ciclo.merge(data);\n await ciclo.save();\n\n return ciclo;\n }",
"_atualiza( dados )\n {\n console.log( \"Model: Atualizando os meus dados\" );\n\n this._nome = dados.name.first + \" \" + dados.name.last;\n this._imagem = dados.picture.large;\n }",
"async function AtualizarDispositivo(res, data){\n try { \n var dispositivo = await Dispositivo.update({\n \"nome\": data.nome,\n \"descricao\": data.descricao,\n \"id_modelo\": data.id_modelo\n },{\n where:{ \"id\": data.id }\n });\n \n res.status(200);\n res.json(dispositivo);\n \n } catch (error) {\n res.status(404);\n res.json({'msg':\"Falha na requisição\", 'error': error});\n }\n}",
"function actualizarCinta(){\n //Obtenemos los datos de los elementos del formulario de edicion\n var titulo = document.getElementById('titulo'),\n fecha = document.getElementById('fecha'),\n comentario = document.getElementById('comentario'),\n genero = document.getElementById('genero'),\n puntos = $(\"#puntos\").attr('data-puntos'),\n id = idURL;\n\n\n //Formateamos los valores para enviarlos a la db\n var datosCintaEditada = [\n titulo.value,\n fecha.value,\n comentario.value,\n genero.value,\n puntos,\n id];\n\n //Conectamos a la base \n db.conectar();\n //Realizamos la actualizacion de los datos\n db.actualizar(datosCintaEditada);\n\n}",
"async update ({ params, request }) {\n const data = request.only(['transacao_data', 'nome', 'valor', 'executado'])\n const transacao = await Transacoes.findOrFail(params.id)\n transacao.merge(data)\n await transacao.save()\n return transacao\n }",
"update(codigo, nome, cidade) {\n try {\n\n let campus = this.get(codigo);\n if (!campus) return false;\n\n campus.nome = nome || campus.nome;\n campus.cidade = cidade || campus.cidade;\n\n db.push(`/campus/${codigo}`, campus, false);\n\n return true;\n\n } catch (error) {\n throw error;\n }\n }",
"async update ({ params, request, response }) {\n const produtocompra = await ProdutoCompra.findOrFail(params.id);\n const { data, status, valor, cliente, funcionario, cod_produto, quantidade } = request.body;\n\n await produtocompra.compras().update({ data, status, valor, cliente, funcionario, cartao });\n produtocompra.merge({cod_compra});\n await produtocompra.save();\n\n let compra = await produtocompra.compras().fetch();\n\n return{\n id: produtocompra.id,\n data: compras.data,\n status: compras.status,\n valor: compras.valor,\n cliente: compras.cliente,\n funcionario: compras.funcionario,\n cod_produto: produtocompra.cod_produto,\n quantidade: produtocompra.quantidade\n };\n }",
"async function actualizarCurso3(id){ \n const resultado = await Curso.findByIdAndUpdate(id,{ \n $set: { \n autor: 'Juan Solis',\n publicado: false\n }\n },/*Con este {new: true} se muestran los datos actualizados \n sin el se muestran los datos antes de actualizar*/ {new: true});\n console.log(resultado);\n}",
"update(req,res){\r\n res.status(200).json(\r\n {\r\n sucess: true,\r\n messages: 'Estructura base PUT',\r\n errors: null,\r\n data: [{}, {}, {}]\r\n }\r\n );\r\n }",
"update(req,res){\n res.status(200).json(\n {\n sucess: true,\n messages: 'Estructura base PUT',\n errors: null,\n data: [{}, {}, {}]\n }\n );\n }",
"function atualizarContatosResponsavel(responsavelUpdateContatos, usuario, res) {\n\t connection.acquire(function(err, con) {\n\t con.query(\"update Responsavel set telefoneResponsavel = ?, emailResponsavel = ? where idusuario = ?\", [responsavelUpdateContatos.telefoneResponsavel ,responsavelUpdateContatos.emailResponsavel, usuario.idusuario], function(err, result) {\n\t con.release();\n\t if (err) {\n\t res.send({status: 1, message: 'TODO update failed'});\n\t } else {\n\t res.send({status: 0, message: 'TODO updated successfully'});\n\t }\n\t });\n\t });\n\t}",
"async update ({ params, request }) {\n const data = request.only([ 'atv_dia_sigla', 'atv_dia_descricao' ]);\n const atividade = await AtividadeDoDia.findOrFail(params.id);\n \n atividade.merge(data);\n await atividade.save();\n \n return atividade;\n }",
"async function actualizarCurso2(id){ \n const curso = await Curso.findById(id);\n const resultado = await Curso.update({_id : id}, {\n $set: { \n autor: 'Emanuel',\n publicado: true\n }\n });\n console.log(resultado);\n}",
"updatePessoa() {\n const formData = app.toFormData(app.currentPessoa);\n axios.post(\"http://localhost/Projeto%20DG%20Solutions/system.php?action=update\", formData).then(function (response) {\n app.currentPessoa = {};\n if (response.data.error) {\n app.errorMsg = response.data.message;\n }\n else {\n app.successMsg = response.data.message;\n app.getAllPessoas();\n }\n });\n }",
"static updateMovilidad(Empleado_idEmpleado,Fecha_Asistencia,Movilidad_Dia){\n\n \n return db.execute('UPDATE Asistencia SET Movilidad_Dia=? where Empleado_idEmpleado =? and Fecha_Asistencia=?',[Movilidad_Dia,Empleado_idEmpleado,Fecha_Asistencia]);\n}",
"function update_capitulo_usuario_se(id_serie,temporada,capitulo_num,capitulo_name,id_capitulo) {\n db = window.openDatabase(shortName, version, displayName, maxSize);\n db.transaction(function(tx) {\n tx.executeSql('UPDATE usuario_se set temporada=?,capitulo_num=?,capitulo_name=?,id_capitulo=?,modificado=DateTime(\"now\") WHERE id_serie=?', [temporada,capitulo_num,capitulo_name,id_capitulo,id_serie], nullHandler(\"update ultimo epi\"), errorHandler);\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
firstToMaybe : First a > Maybe a firstToMaybe : (a > First b) > a > Maybe b | function firstToMaybe(first) {
if(isFunction(first)) {
return function(x) {
var m = first(x)
if(!isSameType(First, m)) {
throw new TypeError('firstToMaybe: First returing function required')
}
return applyTransform(m)
}
}
if(isSameType(First, first)) {
return applyTransform(first)
}
throw new TypeError('firstToMaybe: First or First returing function required')
} | [
"function maybeToFirst(maybe) {\n if(isFunction(maybe)) {\n return function(x) {\n var m = maybe(x)\n\n if(!isSameType(Maybe, m)) {\n throw new TypeError('maybeToFirst: Maybe returning function required')\n }\n\n return applyTransform(m)\n }\n }\n\n if(isSameType(Maybe, maybe)) {\n return applyTransform(maybe)\n }\n\n throw new TypeError('maybeToFirst: Maybe or Maybe returning function required')\n}",
"function coupleFirst(x) {\n\t return x.first;\n\t }",
"function lastToFirst(last) {\n if(isFunction(last)) {\n return function(x) {\n var m = last(x)\n\n if(!isSameType(Last, m)) {\n throw new TypeError('lastToFirst: Last returing function required')\n }\n\n return applyTransform(m)\n }\n }\n\n if(isSameType(Last, last)) {\n return applyTransform(last)\n }\n\n throw new TypeError('lastToFirst: Last or Last returing function required')\n}",
"function sortByFirstVal(a, b) {\n if (a[0] < b[0]) return -1;\n if (a[0] > b[0]) return 1;\n return 0;\n }",
"function andForMaybe(a, b) {\n if (Maybe_1.isNotNullAndUndefined(a)) {\n return b;\n }\n return a;\n}",
"function firstToAsync(left, first) {\n if(isFunction(first)) {\n return function(x) {\n var m = first(x)\n\n if(!isSameType(First, m)) {\n throw new TypeError('firstToAsync: First returning function required for second argument')\n }\n\n return applyTransform(left, m)\n }\n }\n\n if(isSameType(First, first)) {\n return applyTransform(left, first)\n }\n\n throw new TypeError('firstToAsync: First or First returning function required for second argument')\n}",
"function firstToAsync(left, first) {\n if(isFunction(first)) {\n return function(x) {\n var m = first(x)\n\n if(!isSameType(First, m)) {\n throw new TypeError('firstToAsync: First returing function required for second argument')\n }\n\n return applyTransform(left, m)\n }\n }\n\n if(isSameType(First, first)) {\n return applyTransform(left, first)\n }\n\n throw new TypeError('firstToAsync: First or First returing function required for second argument')\n}",
"function firstOrLast(arr, wantFirst) {\n if (wantFirst) {\n return arr.reduce((accum, elem) => typeof accum === 'undefined' ? elem : accum, undefined);\n } else {\n return arr.reduceRight((accum, elem) => typeof accum === 'undefined' ? elem : accum, undefined);\n }\n}",
"function maybe_2(xs) /* forall<a> (xs : list<a>) -> maybe<a> */ {\n return (xs == null) ? Nothing : Just(xs.head);\n}",
"function listToMaybe(xs){\n if (xs.length > 0) return new Just(xs[0]);\n else return Nothing;\n}",
"first(mtn, sort, includeSpecial) {\n if (sort == null) sort = (a) => a;\n const sortedValues = sort(mtn.values);\n\n let newStn = null;\n if (includeSpecial) {\n // Returns undefined if mtn is an empty array, rather than throwing\n newStn = sortedValues.find(() => true);\n } else {\n newStn = sortedValues.find((stn) => !isSpecialNode(stn));\n }\n\n if (newStn !== undefined) {\n return newStn; // Use the first 'real' value\n } else {\n return TraversalNode.NOT_PRESENT; // If no 'real' values found\n }\n }",
"function first(a) { return (a !== null && a.length > 0) ? a[0] : null; }",
"function toMaybe(x){\n if (x === undefined || x === null) return Nothing;\n else return new Just(x);\n}",
"function firstToEither(left, first) {\n if(isFunction(first)) {\n return function(x) {\n var m = first(x)\n\n if(!isSameType(First, m)) {\n throw new TypeError('firstToEither: First returing function required for second argument')\n }\n\n return applyTransform(left, m)\n }\n }\n\n if(isSameType(First, first)) {\n return applyTransform(left, first)\n }\n\n throw new TypeError('firstToEither: First or First returing function required for second argument')\n}",
"function first(value){\n return value[0];// returns first value sequence\n}",
"function findSmallest(first, second, third){\n if(first < second && first < third){\n return first;\n }\n else if(second < first && second < third){\n return second;\n } \n else{\n return third\n }\n}",
"function takeFirst(collection){\n if(!(collection.length >= 1)){\n return;\n }\n return collection[0];\n}",
"function toMaybe(x) {\n return x == null ? Nothing : Just (x);\n }",
"function first() {\n var clean = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : filter.ignoreMissing;\n\n return function (values) {\n var cleanValues = clean(values);\n if (!cleanValues) return null;\n return cleanValues.length ? cleanValues[0] : undefined;\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
view history panel key redispersed | function view_history_panel_solve_key_redispersed(number_saturation){
var str = "<h6 id='hist' style='display: none'>";
str = str + "<img src='imagenes/tag_info.png' title='Información sobre la última operación realizada'/>";
str_value = "";
end = sel_val['node_cap'] + 1;
for (i=1; i <= end; i++){
index = "dispersed_keys_"+number_saturation+'_'+i;
value = dispersed_keys[index];
str_value = str_value + "'"+value+"'";
if (i < end){
str_value = str_value + ", ";
}
}
str = str + "Se vuelven a dispersar las claves: "+str_value+".";//string_insert_solve_key_redispersed();
str = str + "</h6>";
$(str).insertBefore("#hist");
$("h6").slideDown("slow");
return false;
} | [
"history(lastKeyPressed) {\n this._keyHistory.push(lastKeyPressed);\n }",
"onHistoryShow (stamp) {\n this.getJobState('history', stamp, false, '')\n }",
"function save_history () {\n\tvar ds = currHds();\n\tedit_history [edit_history_index] = JSON.stringify(ds.toJSON());\n}",
"function view_history() {\n\tvar string_analyse_history = localStorage.getItem(\"analyse_history\");\n\n\tif (string_analyse_history) {\n\t\tanalyse_history = JSON.parse(string_analyse_history);\n\t\tfor (var to_add of analyse_history) appendLine(to_add.resultDate,\n\t\t\tto_add.url,\n\t\t\tto_add.nbRequest,\n\t\t\tto_add.responsesSize,\n\t\t\tto_add.domSize,\n\t\t\tto_add.greenhouseGasesEmission,\n\t\t\tto_add.waterConsumption,\n\t\t\tto_add.ecoIndex,\n\t\t\tto_add.grade);\n\t}\n\n}",
"_getHistory() {\n let history = this.kernel.getHistory();\n let historyRepr = \"\";\n for (let i=0; i<history.length-1; i++)\n historyRepr += history[i] + ((i < history.length-2) ? \"<br/>\" : \"\");\n return historyRepr;\n }",
"function showHistoryList() {\n\n let $history = $id(const_id_SRMhistorylist);\n if ($history) {\n // clean existing Tab History List\n $history.innerHTML = \"\";\n } else {\n // create new Tab History List\n let $List = $class(\"CodeMirror\").appendChild(document.createElement(\"DIV\"));\n $List.id = \"SRMHistory\";// used by CSS\n $List.innerHTML = `<b id=\"${const_id_SRMaddhistory}\">History +</b><div id=\"${const_id_SRMhistorylist}\"></div>`;\n addEvent({\n selector: \"#\" + const_id_SRMaddhistory,\n func: evt => {\n tabManager.saveHistory();\n showHistoryList();\n }\n });\n }\n\n // add History List Items\n (tabManager.currentTab.Historyentries).forEach(addHistoryItemHTML);\n }",
"getHistory(){\n }",
"async getHistory(ctx, key) {\n let iterator = await ctx.stub.getHistoryForKey(key);\n let result = [];\n let res = await iterator.next();\n while (!res.done) {\n if (res.value) {\n console.info(`found state update with value: ${res.value.value.toString('utf8')}`);\n const obj = JSON.parse(res.value.value.toString('utf8'));\n result.push(obj);\n }\n res = await iterator.next();\n }\n await iterator.close();\n return result; \n }",
"function rl_get_previous_history(count, key) {\n rl_history_seek(rl_history_index - count);\n}",
"function history() {\n var temp = \"\";\n for (var i=0; i<commandHistory.length; i++) {\n temp += commandHistory[i]+\"<br>\";\n }\n return temp;\n}",
"editEncryptionKeys() {\n return this.gotoState('dbaas-logs.detail.encryption-keys.home');\n }",
"function get_current_history() {\n return histories[get_current_grid_name()];\n}",
"function showLastHistorySearch() {\n\n var localData = localStorage.getItem('history');\n var searchObj = localData ? JSON.parse(localData) : [];\n\n searchObj.forEach(function(key) {\n var history = $('<li>').html(key);\n $('#weather-history-results').prepend(history);\n });\n}",
"function viewHandler() {\r\n if (current_viewType == \"MapView\" && current_tagType == \"Results\") {\r\n var hashValue = createHashValue();\r\n Sys.Application.addHistoryPoint({ param: hashValue }, siteTitle);\r\n }\r\n}",
"async getHistory(key) {\n\n let ledgerkey = this.ctx.stub.createCompositeKey(this.name, State.splitKey(key));\n const resultsIterator = await this.ctx.stub.getHistoryForKey(ledgerkey);\n let results = await this.getAllResults(resultsIterator, true);\n\n return results;\n }",
"function rl_beginning_of_history(count, key) {\n rl_history_seek(0);\n}",
"print_history() {\n\t\tthis.m_history.forEach(function(l_result){\n\t\t\tthis.f_print(l_result);\n\t\t})\n\t}",
"function getHistory(){\n\t\tvar oldHistoryStr = localStorage.getItem(\"actionHistory\");\n\t\tif(!oldHistoryStr || oldHistoryStr == \"\") {\n\t\t\tvar oldHistoryAry = [];\n\t\t} else {\n\t\t\tvar oldHistoryAry = JSON.parse(oldHistoryStr);\n\t\t}\n\t\t\n\t\tconsole.log([\"oldhistory\", oldHistoryAry]);\n\t\treturn oldHistoryAry.concat(laygoon.common.history);\n\t}",
"function show_history() {\n var macs = [];\n $(\".device.active\").each(function() {\n macs.push($(this).find(\".mac\").eq(0).text());\n });\n if(macs.length) {\n $.post(\"set_history.php\",\n {\n macs:macs\n },\n function(data) {\n window.location.hash = '#history';\n $(window).trigger('hashchange');\n });\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
! decodeUtf8ToCodePointsChunkAlgorithm.js Version 0.1.36 | function decodeUtf8ToCodePointsChunkAlgorithm(utf8Codes, i, l, codePoints, allowOverlongEncoding, events, cache, close) {
// XXX do documentation
// utf8Codes = [...]
// an array of utf8 codes (uint8)
// i XXX
// l XXX
// codePoints = []
// where the code points (uint32) are pushed
// allowOverlongEncoding = true
// allow overlong encoding error detection
// cache = [state, utf8Codes...x4]
// used by the algorithm
// events = []
// where the error events are pushed
// close = false
// tells the algorithm to close the stream
// returns codePoints
// events :
// error
// invalid start byte, errno 1
// invalid continuation byte, errno 2
// overlong encoding, errno 3
// reserved code point, errno 4
// invalid code point, errno 5
// unexpected end of data, errno 6
var code = 0, c = 0;
for (; i < l; i += 1) {
code = utf8Codes[i];
switch (cache[0]) {
case 2:
if ((0xC0 & code) !== 0x80) { events.push({type: "error", message: "invalid continuation byte", errno: 2, length: 2, index: i, requiredUtf8CodeAmount: 2, requiredUtf8CodeIndex: 1}); return codePoints; }
else { codePoints.push(((cache[1] << 6) | (code & 0x3F)) & 0x7FF); cache[0] = 0; } break;
case 3:
if ((0xC0 & code) !== 0x80) { events.push({type: "error", message: "invalid continuation byte", errno: 2, length: 2, index: i, requiredUtf8CodeAmount: 3, requiredUtf8CodeIndex: 1}); return codePoints; }
else if ((c = cache[1]) === 0xE0 && code <= 0x9F && !allowOverlongEncoding) { events.push({type: "error", message: "overlong encoding", errno: 3, length: 2, index: i, requiredUtf8CodeAmount: 3, requiredUtf8CodeIndex: 1}); return codePoints; }
else { cache[3] = code; cache[1] = (c << 6) | (code & 0x3F); cache[0] = 31; } break;
case 31:
if ((0xC0 & code) !== 0x80) { events.push({type: "error", message: "invalid continuation byte", errno: 2, length: 3, index: i, requiredUtf8CodeAmount: 3, requiredUtf8CodeIndex: 2}); return codePoints; }
else if (0xD800 <= (c = ((cache[1] << 6) | (code & 0x3F)) & 0xFFFF) && c <= 0xDFFF) { events.push({type: "error", message: "reserved code point", errno: 4, length: 3, index: i, requiredUtf8CodeAmount: 3, requiredUtf8CodeIndex: 2}); return codePoints; }
else { codePoints.push(c); cache[0] = 0; } break;
case 4:
if ((0xC0 & code) !== 0x80) { events.push({type: "error", message: "invalid continuation byte", errno: 2, length: 2, index: i, requiredUtf8CodeAmount: 4, requiredUtf8CodeIndex: 1}); return codePoints; }
else if ((c = cache[1]) === 0xF0 && code <= 0x8F && !allowOverlongEncoding) { events.push({type: "error", message: "overlong encoding", errno: 3, length: 2, index: i, requiredUtf8CodeAmount: 4, requiredUtf8CodeIndex: 1}); return codePoints; }
else { cache[3] = code; cache[1] = (c << 6) | (code & 0x3F); cache[0] = 41; } break;
case 41:
if ((0xC0 & code) !== 0x80) { events.push({type: "error", message: "invalid continuation byte", errno: 2, length: 3, index: i, requiredUtf8CodeAmount: 4, requiredUtf8CodeIndex: 2}); return codePoints; }
else { cache[4] = code; cache[1] = (cache[1] << 6) | (code & 0x3F); cache[0] = 42; } break;
case 42:
if ((0xC0 & code) !== 0x80) { events.push({type: "error", message: "invalid continuation byte", errno: 2, length: 4, index: i, requiredUtf8CodeAmount: 4, requiredUtf8CodeIndex: 3}); return codePoints; }
else if ((c = ((cache[1] << 6) | (code & 0x3F)) & 0x1FFFFF) > 0x10FFFF) { events.push({type: "error", message: "invalid code point", errno: 5, length: 4, index: i, requiredUtf8CodeAmount: 4, requiredUtf8CodeIndex: 3}); return codePoints; }
else { codePoints.push(c); cache[0] = 0; } break;
default:
if (code <= 0x7F) codePoints.push(code);
else if ((0xE0 & code) === 0xC0) {
if (code < 0xC2 && !allowOverlongEncoding) { events.push({type: "error", message: "overlong encoding", errno: 3, length: 1, index: i, requiredUtf8CodeAmount: 2, requiredUtf8CodeIndex: 0}); return codePoints; }
else { cache[2] = cache[1] = code; cache[0] = 2; }
} else if ((0xF0 & code) === 0xE0) { cache[2] = cache[1] = code; cache[0] = 3; }
else if ((0xF8 & code) === 0xF0) {
if (code >= 0xF5) { events.push({type: "error", message: "invalid start byte", errno: 1, length: 1, index: i, requiredUtf8CodeAmount: 4, requiredUtf8CodeIndex: 0}); return codePoints; }
else { cache[2] = cache[1] = code; cache[0] = 4; }
} else { events.push({type: "error", message: "invalid start byte", errno: 1, length: 1, index: i}); return codePoints; }
}
}
if (close) {
switch (cache[0]) {
case 2: events.push({type: "error", message: "unexpected end of data", errno: 6, length: 2, index: i, requiredUtf8CodeAmount: 2, requiredUtf8CodeIndex: 1}); break;
case 3: events.push({type: "error", message: "unexpected end of data", errno: 6, length: 2, index: i, requiredUtf8CodeAmount: 3, requiredUtf8CodeIndex: 1}); break;
case 31: events.push({type: "error", message: "unexpected end of data", errno: 6, length: 3, index: i, requiredUtf8CodeAmount: 3, requiredUtf8CodeIndex: 2}); break;
case 4: events.push({type: "error", message: "unexpected end of data", errno: 6, length: 2, index: i, requiredUtf8CodeAmount: 4, requiredUtf8CodeIndex: 1}); break;
case 41: events.push({type: "error", message: "unexpected end of data", errno: 6, length: 3, index: i, requiredUtf8CodeAmount: 4, requiredUtf8CodeIndex: 2}); break;
case 42: events.push({type: "error", message: "unexpected end of data", errno: 6, length: 4, index: i, requiredUtf8CodeAmount: 4, requiredUtf8CodeIndex: 3}); break;
}
}
return codePoints;
} | [
"function Utf8DecodeWorker() {\n GenericWorker.call(this, \"utf-8 decode\");\n // the last bytes if a chunk didn't end with a complete codepoint.\n this.leftOver = null;\n}",
"function cleanUtf8Split(chunk, runtime) {\n var idx = chunk.length - 1;\n /**\n * From Keyang:\n * The code below is to check if a single utf8 char (which could be multiple bytes) being split.\n * If the char being split, the buffer from two chunk needs to be concat\n * check how utf8 being encoded to understand the code below.\n * If anyone has any better way to do this, please let me know.\n */\n if ((chunk[idx] & 1 << 7) != 0) {\n while ((chunk[idx] & 3 << 6) === 128) {\n idx--;\n }\n idx--;\n }\n if (idx != chunk.length - 1) {\n runtime.csvLineBuffer = chunk.slice(idx + 1);\n return chunk.slice(0, idx + 1);\n // var _cb=cb;\n // var self=this;\n // cb=function(){\n // if (self._csvLineBuffer){\n // self._csvLineBuffer=Buffer.concat([bufFromString(self._csvLineBuffer,\"utf8\"),left]);\n // }else{\n // self._csvLineBuffer=left;\n // }\n // _cb();\n // }\n }\n else {\n return chunk;\n }\n}",
"function decodeImpl(bytes) {\n var pos = 0;\n var len = bytes.length;\n var out = [];\n var substrings = [];\n while (pos < len) {\n var byte1 = bytes[pos++];\n if (byte1 === 0) {\n break; // NULL\n }\n if ((byte1 & 0x80) === 0) { // 1-byte\n out.push(byte1);\n }\n else if ((byte1 & 0xe0) === 0xc0) { // 2-byte\n var byte2 = bytes[pos++] & 0x3f;\n out.push(((byte1 & 0x1f) << 6) | byte2);\n }\n else if ((byte1 & 0xf0) === 0xe0) {\n var byte2 = bytes[pos++] & 0x3f;\n var byte3 = bytes[pos++] & 0x3f;\n out.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);\n }\n else if ((byte1 & 0xf8) === 0xf0) {\n var byte2 = bytes[pos++] & 0x3f;\n var byte3 = bytes[pos++] & 0x3f;\n var byte4 = bytes[pos++] & 0x3f;\n // this can be > 0xffff, so possibly generate surrogates\n var codepoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;\n if (codepoint > 0xffff) {\n // codepoint &= ~0x10000;\n codepoint -= 0x10000;\n out.push((codepoint >>> 10) & 0x3ff | 0xd800);\n codepoint = 0xdc00 | codepoint & 0x3ff;\n }\n out.push(codepoint);\n }\n else {\n // FIXME: we're ignoring this\n }\n // As a workaround for https://github.com/samthor/fast-text-encoding/issues/1,\n // make sure the 'out' array never gets too long. When it reaches a limit, we\n // stringify what we have so far and append to a list of outputs.\n if (out.length > 1024) {\n substrings.push(String.fromCharCode.apply(null, out));\n out.length = 0;\n }\n }\n substrings.push(String.fromCharCode.apply(null, out));\n return substrings.join('');\n}",
"function decodingBlock(slice) {\n return slice.split('')\n .map((char, index) => {\n let decodedChar = null;\n\n if (index === 0) {\n decodedChar = encodeDictionary.indexOf(char) << 2;\n decodedChar += (encodeDictionary.indexOf(slice[index + 1]) & 0x30) >> 4;\n return String.fromCharCode(decodedChar);\n } else if (index === 1) {\n decodedChar = (encodeDictionary.indexOf(char) & 0xF) << 4;\n decodedChar += (encodeDictionary.indexOf(slice[index + 1]) & 0x3C) >> 2;\n return String.fromCharCode(decodedChar);\n } else if (index === 2) { // index === 2\n decodedChar = (encodeDictionary.indexOf(char) & 0x3) << 6;\n decodedChar += (encodeDictionary.indexOf(slice[index + 1]) & 0x3F);\n return String.fromCharCode(decodedChar);\n }\n })\n .join('');\n}",
"function h$decodeUtf8z(v,start) {\n// h$log(\"h$decodeUtf8z\");\n var n = start;\n var max = v.len;\n while(n < max) {\n// h$log(\"### \" + n + \" got char: \" + v.u8[n]);\n if(v.u8[n] === 0) { break; }\n n++;\n }\n return h$decodeUtf8(v,n,start);\n}",
"function processChunk(chunk) {\n console.log(chunk);\n let result = new TextDecoder('utf-8').decode(chunk);\n return result;\n}",
"readUtf8() {\n let n = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;\n const bString = this.readChars(n);\n return Object(utf8__WEBPACK_IMPORTED_MODULE_0__[\"decode\"])(bString);\n }",
"function decoder(contents)\n{\n var encry={};\n var initswaps=1000;\n var alpha=\"abcdefghijklmnopqrstuvwxyz\";\n\n\n encry.str=contents.slice(0,10000); /* the first 1000 incoded message */\n\n\n encry.key={};\n for (var i in alpha) {\n var c=alpha.charAt(i);\n encry.key[c]=c; /* building array key */\n\n }\n\n\n\n\n\n //create random starting key\n for (var i = 0; i < initswaps; i++) {\n encry.key=swapkeys(encry.key);\n }\n\n encry=deriveKey(encry);\n\n encry.str=contents.slice(10000,20000)\n encry=deriveKey(encry); // checks to confrim the key wasn't a local max found by trying on a different section of the message\n\n answer=applyKey(contents,encry.key);\n return;\n\n\n}",
"decode(buf) {\n function isHex(hex) {\n if ((hex >= 48 && hex <= 57) || (hex >= 65 && hex <= 70) || (hex >= 97 && hex <= 102)) {\n return true;\n }\n return false;\n }\n function getx(i, len, bufArg) {\n const ret = { char: null, nexti: i + 2, error: true };\n if (i + 1 < len) {\n if (isHex(bufArg[i]) && isHex(bufArg[i + 1])) {\n const str = String.fromCodePoint(bufArg[i], bufArg[i + 1]);\n ret.char = parseInt(str, 16);\n if (!Number.isNaN(ret.char)) {\n ret.error = false;\n }\n }\n }\n return ret;\n }\n function getu(i, len, bufArg) {\n const ret = { char: null, nexti: i + 4, error: true };\n if (i + 3 < len) {\n if (isHex(bufArg[i]) && isHex(bufArg[i + 1]) && isHex(bufArg[i + 2]) && isHex(bufArg[i + 3])) {\n const str = String.fromCodePoint(bufArg[i], bufArg[i + 1], bufArg[i + 2], bufArg[i + 3]);\n ret.char = parseInt(str, 16);\n if (!Number.isNaN(ret.char)) {\n ret.error = false;\n }\n }\n }\n return ret;\n }\n function getU(i, len, bufArg) {\n const ret = { char: null, nexti: i + 4, error: true };\n let str = '';\n while (i < len && isHex(bufArg[i])) {\n str += String.fromCodePoint(bufArg[i]);\n // eslint-disable-next-line no-param-reassign\n i += 1;\n }\n ret.char = parseInt(str, 16);\n if (bufArg[i] === 125 && !Number.isNaN(ret.char)) {\n ret.error = false;\n }\n ret.nexti = i + 1;\n return ret;\n }\n const chars = [];\n const len = buf.length;\n let i1;\n let ret;\n let error;\n let i = 0;\n while (i < len) {\n const TRUE = true;\n while (TRUE) {\n error = true;\n if (buf[i] !== 96) {\n /* unescaped character */\n chars.push(buf[i]);\n i += 1;\n error = false;\n break;\n }\n i1 = i + 1;\n if (i1 >= len) {\n break;\n }\n if (buf[i1] === 96) {\n /* escaped grave accent */\n chars.push(96);\n i += 2;\n error = false;\n break;\n }\n if (buf[i1] === 120) {\n ret = getx(i1 + 1, len, buf);\n if (ret.error) {\n break;\n }\n /* escaped hex */\n chars.push(ret.char);\n i = ret.nexti;\n error = false;\n break;\n }\n if (buf[i1] === 117) {\n if (buf[i1 + 1] === 123) {\n ret = getU(i1 + 2, len, buf);\n if (ret.error) {\n break;\n }\n /* escaped utf-32 */\n chars.push(ret.char);\n i = ret.nexti;\n error = false;\n break;\n }\n ret = getu(i1 + 1, len, buf);\n if (ret.error) {\n break;\n }\n /* escaped utf-16 */\n chars.push(ret.char);\n i = ret.nexti;\n error = false;\n break;\n }\n break;\n }\n if (error) {\n throw new Error(`escaped.decode: ill-formed escape sequence at buf[${i}]`);\n }\n }\n return chars;\n }",
"function decodeCodePointFromUtf8CodeArray(array, i, l) {\n // decodeCodePointFromUtf8CodeArray(bytes, 0, bytes.length) -> {result, length, error, warnings, requiredLength, expectedLength}\n // decodeCodePointFromUtf8CodeArray([0xc3, 0xa9, 0x61, 0x62], 0, 4) -> {.: 233, .: 2, .: \"\", .: \"\", .: 0, .: 2}\n\n // Unpacks the first UTF-8 encoding in array and returns the rune and its\n // width in bytes.\n\n // errors:\n // invalid start byte\n // invalid continuation byte\n // invalid code point\n // unexpected empty data\n // unexpected end of data\n // warnings:\n // overlong encoding\n // reserved code point\n\n // Return value:\n // {\n // result: 0xFFFD, // the resulting codepoint (default is runeError)\n // length: 0, // nb of utf8code read/used\n // error: \"\", // error code\n // warnings: \"\", // comma seperated warning codes\n // requiredLength: 0, // additional nb of utf8code required to possibly fix the error\n // expectedLength: 0, // the length of the expected code point size\n // };\n\n // \"reserved code point\" warning never happens at the same time as with \"overlong encoding\"\n\n // Benchmark shows that the speed is equal with old decodeUtf8XxxLikeChrome using decodeXxxAlgorithm.\n // XXX benchmark with return [runeError, 0, error, 1, 1]\n // XXX benchmark with decodeCodePointFromUtf8CodeArray.Result = makeStruct(\"result,length,error,warnings,requiredLength,expectedLength\");\n\n var code = 0,\n a = 0, c = 0,\n warnings = \"\",\n runeError = 0xFFFD;\n\n if (i >= l) { return {result: runeError|0, length: 0, error: \"unexpected empty data\", warnings: warnings, requiredLength: 1, expectedLength: 1}; }\n code = array[i];\n\n if (code <= 0x7F) { return {result: code|0, length: 1, error: \"\", warnings: warnings, requiredLength: 0, expectedLength: 1}; } // one byte required\n if ((0xE0 & code) === 0xC0) { // two bytes required\n if (code < 0xC2) { warnings = \"overlong encoding\"; }\n a = code;\n if (i + 1 >= l) { return {result: runeError|0, length: 1, error: \"unexpected end of data\", warnings: warnings, requiredLength: 1, expectedLength: 2}; }\n code = array[i + 1];\n if ((0xC0 & code) != 0x80) { return {result: runeError|0, length: 2, error: \"invalid continuation byte\", warnings: warnings, requiredLength: 0, expectedLength: 2}; }\n return {result: ((a << 6) | (code & 0x3F)) & 0x7FF, length: 2, error: \"\", warnings: warnings, requiredLength: 0, expectedLength: 2};\n }\n if ((0xF0 & code) === 0xE0) { // three bytes required\n a = code;\n if (i + 1 >= l) { return {result: runeError|0, length: 1, error: \"unexpected end of data\", warnings: warnings, requiredLength: 2, expectedLength: 3}; }\n code = array[i + 1];\n if ((0xC0 & code) != 0x80) { return {result: runeError|0, length: 2, error: \"invalid continuation byte\", warnings: warnings, requiredLength: 0, expectedLength: 3}; }\n if ((c = a) === 0xE0 && code <= 0x9F) { warnings = \"overlong encoding\"; }\n a = (c << 6) | (code & 0x3F);\n if (i + 2 >= l) { return {result: runeError|0, length: 2, error: \"unexpected end of data\", warnings: warnings, requiredLength: 1, expectedLength: 3}; }\n code = array[i + 2];\n if ((0xC0 & code) != 0x80) { return {result: runeError|0, length: 3, error: \"invalid continuation byte\", warnings: warnings, requiredLength: 0, expectedLength: 3}; }\n if (0xD800 <= (c = ((a << 6) | (code & 0x3F)) & 0xFFFF) && c <= 0xDFFF) { warnings = (warnings ? \",\" : \"\") + \"reserved code point\"; }\n return {result: c|0, length: 3, error: \"\", warnings: warnings, requiredLength: 0, expectedLength: 3};\n }\n if ((0xF8 & code) === 0xF0) { // four bytes required\n if (code >= 0xF5) { return {result: runeError|0, length: 1, error: \"invalid start byte\", warnings: warnings, requiredLength: 0, expectedLength: 4}; }\n a = code;\n if (i + 1 >= l) { return {result: runeError|0, length: 1, error: \"unexpected end of data\", warnings: warnings, requiredLength: 3, expectedLength: 4}; }\n code = array[i + 1];\n if ((0xC0 & code) != 0x80) { return {result: runeError|0, length: 2, error: \"invalid continuation byte\", warnings: warnings, requiredLength: 0, expectedLength: 4}; }\n if ((c = a) === 0xF0 && code <= 0x8F) { warnings = \"overlong encoding\"; }\n a = (c << 6) | (code & 0x3F);\n if (i + 2 >= l) { return {result: runeError|0, length: 2, error: \"unexpected end of data\", warnings: warnings, requiredLength: 2, expectedLength: 4}; }\n code = array[i + 2];\n if ((0xC0 & code) != 0x80) { return {result: runeError|0, length: 3, error: \"invalid continuation byte\", warnings: warnings, requiredLength: 0, expectedLength: 4}; }\n a = (a << 6) | (code & 0x3F);\n if (i + 3 >= l) { return {result: runeError|0, length: 3, error: \"unexpected end of data\", warnings: warnings, requiredLength: 1, expectedLength: 4}; }\n code = array[i + 3];\n if ((0xC0 & code) != 0x80) { return {result: runeError|0, length: 4, error: \"invalid continuation byte\", warnings: warnings, requiredLength: 0, expectedLength: 4}; }\n if ((c = ((a << 6) | (code & 0x3F)) & 0x1FFFFF) > 0x10FFFF) { return {result: runeError|0, length: 4, error: \"invalid code point\", warnings: warnings, requiredLength: 0, expectedLength: 4}; }\n return {result: c|0, length: 4, error: \"\", warnings: warnings, requiredLength: 0, expectedLength: 4};\n }\n return {result: runeError|0, length: 1, error: \"invalid start byte\", warnings: warnings, requiredLength: 0, expectedLength: 1};\n }",
"function decompressInner_(str, inputStart, inputEnd,\n output, outputStart, stride,\n decodeOffset, decodeScale) {\n var prev = 0;\n for (var j = inputStart; j < inputEnd; j++) {\n var code = str.charCodeAt(j);\n prev += (code >> 1) ^ (-(code & 1));\n output[outputStart] = decodeScale * (prev + decodeOffset);\n outputStart += stride;\n }\n }",
"decode(input, target) {\n const length = input.length;\n if (!length) {\n return 0;\n }\n let size = 0;\n let byte1;\n let byte2;\n let byte3;\n let byte4;\n let codepoint = 0;\n let startPos = 0;\n // handle leftover bytes\n if (this.interim[0]) {\n let discardInterim = false;\n let cp = this.interim[0];\n cp &= ((((cp & 0xE0) === 0xC0)) ? 0x1F : (((cp & 0xF0) === 0xE0)) ? 0x0F : 0x07);\n let pos = 0;\n let tmp;\n while ((tmp = this.interim[++pos] & 0x3F) && pos < 4) {\n cp <<= 6;\n cp |= tmp;\n }\n // missing bytes - read ahead from input\n const type = (((this.interim[0] & 0xE0) === 0xC0)) ? 2 : (((this.interim[0] & 0xF0) === 0xE0)) ? 3 : 4;\n const missing = type - pos;\n while (startPos < missing) {\n if (startPos >= length) {\n return 0;\n }\n tmp = input[startPos++];\n if ((tmp & 0xC0) !== 0x80) {\n // wrong continuation, discard interim bytes completely\n startPos--;\n discardInterim = true;\n break;\n }\n else {\n // need to save so we can continue short inputs in next call\n this.interim[pos++] = tmp;\n cp <<= 6;\n cp |= tmp & 0x3F;\n }\n }\n if (!discardInterim) {\n // final test is type dependent\n if (type === 2) {\n if (cp < 0x80) {\n // wrong starter byte\n startPos--;\n }\n else {\n target[size++] = cp;\n }\n }\n else if (type === 3) {\n if (cp < 0x0800 || (cp >= 0xD800 && cp <= 0xDFFF) || cp === 0xFEFF) ;\n else {\n target[size++] = cp;\n }\n }\n else {\n if (cp < 0x010000 || cp > 0x10FFFF) ;\n else {\n target[size++] = cp;\n }\n }\n }\n this.interim.fill(0);\n }\n // loop through input\n const fourStop = length - 4;\n let i = startPos;\n while (i < length) {\n /**\n * ASCII shortcut with loop unrolled to 4 consecutive ASCII chars.\n * This is a compromise between speed gain for ASCII\n * and penalty for non ASCII:\n * For best ASCII performance the char should be stored directly into target,\n * but even a single attempt to write to target and compare afterwards\n * penalizes non ASCII really bad (-50%), thus we load the char into byteX first,\n * which reduces ASCII performance by ~15%.\n * This trial for ASCII reduces non ASCII performance by ~10% which seems acceptible\n * compared to the gains.\n * Note that this optimization only takes place for 4 consecutive ASCII chars,\n * for any shorter it bails out. Worst case - all 4 bytes being read but\n * thrown away due to the last being a non ASCII char (-10% performance).\n */\n while (i < fourStop\n && !((byte1 = input[i]) & 0x80)\n && !((byte2 = input[i + 1]) & 0x80)\n && !((byte3 = input[i + 2]) & 0x80)\n && !((byte4 = input[i + 3]) & 0x80)) {\n target[size++] = byte1;\n target[size++] = byte2;\n target[size++] = byte3;\n target[size++] = byte4;\n i += 4;\n }\n // reread byte1\n byte1 = input[i++];\n // 1 byte\n if (byte1 < 0x80) {\n target[size++] = byte1;\n // 2 bytes\n }\n else if ((byte1 & 0xE0) === 0xC0) {\n if (i >= length) {\n this.interim[0] = byte1;\n return size;\n }\n byte2 = input[i++];\n if ((byte2 & 0xC0) !== 0x80) {\n // wrong continuation\n i--;\n continue;\n }\n codepoint = (byte1 & 0x1F) << 6 | (byte2 & 0x3F);\n if (codepoint < 0x80) {\n // wrong starter byte\n i--;\n continue;\n }\n target[size++] = codepoint;\n // 3 bytes\n }\n else if ((byte1 & 0xF0) === 0xE0) {\n if (i >= length) {\n this.interim[0] = byte1;\n return size;\n }\n byte2 = input[i++];\n if ((byte2 & 0xC0) !== 0x80) {\n // wrong continuation\n i--;\n continue;\n }\n if (i >= length) {\n this.interim[0] = byte1;\n this.interim[1] = byte2;\n return size;\n }\n byte3 = input[i++];\n if ((byte3 & 0xC0) !== 0x80) {\n // wrong continuation\n i--;\n continue;\n }\n codepoint = (byte1 & 0x0F) << 12 | (byte2 & 0x3F) << 6 | (byte3 & 0x3F);\n if (codepoint < 0x0800 || (codepoint >= 0xD800 && codepoint <= 0xDFFF) || codepoint === 0xFEFF) {\n // illegal codepoint or BOM, no i-- here\n continue;\n }\n target[size++] = codepoint;\n // 4 bytes\n }\n else if ((byte1 & 0xF8) === 0xF0) {\n if (i >= length) {\n this.interim[0] = byte1;\n return size;\n }\n byte2 = input[i++];\n if ((byte2 & 0xC0) !== 0x80) {\n // wrong continuation\n i--;\n continue;\n }\n if (i >= length) {\n this.interim[0] = byte1;\n this.interim[1] = byte2;\n return size;\n }\n byte3 = input[i++];\n if ((byte3 & 0xC0) !== 0x80) {\n // wrong continuation\n i--;\n continue;\n }\n if (i >= length) {\n this.interim[0] = byte1;\n this.interim[1] = byte2;\n this.interim[2] = byte3;\n return size;\n }\n byte4 = input[i++];\n if ((byte4 & 0xC0) !== 0x80) {\n // wrong continuation\n i--;\n continue;\n }\n codepoint = (byte1 & 0x07) << 18 | (byte2 & 0x3F) << 12 | (byte3 & 0x3F) << 6 | (byte4 & 0x3F);\n if (codepoint < 0x010000 || codepoint > 0x10FFFF) {\n // illegal codepoint, no i-- here\n continue;\n }\n target[size++] = codepoint;\n }\n else ;\n }\n return size;\n }",
"function decodingBlock(slice) {\n var decodeSlice = '',\n j,\n length,\n charNumberOne,\n charNumberTwo,\n charNumberThree;\n\n for (j = 0, length = slice.length; j < length; j++) {\n switch (j) {\n case 0:\n charNumberOne = encodeDictionary.indexOf(slice[j]) << 2;\n charNumberOne += (encodeDictionary.indexOf(slice[j + 1]) & 0x30) >> 4;\n decodeSlice += String.fromCharCode(charNumberOne);\n break;\n case 1:\n charNumberTwo = (encodeDictionary.indexOf(slice[j]) & 0xF) << 4;\n charNumberTwo += (encodeDictionary.indexOf(slice[j + 1]) & 0x3C) >> 2;\n decodeSlice += String.fromCharCode(charNumberTwo);\n break;\n case 2:\n charNumberThree = (encodeDictionary.indexOf(slice[j]) & 0x3) << 6;\n charNumberThree += (encodeDictionary.indexOf(slice[j + 1]) & 0x3F);\n decodeSlice += String.fromCharCode(charNumberThree);\n break;\n }\n }\n return decodeSlice;\n}",
"function runLengthDecodeString(data) {}",
"InitializeDecode(string, EncodingType) {\n\n }",
"DecodeBlob(string, EncodingType) {\n\n }",
"function main() {\n var chunkIndex\n var chunk\n\n while (point._index < chunks.length) {\n chunk = chunks[point._index] // If we’re in a buffer chunk, loop through it.\n\n if (typeof chunk === 'string') {\n chunkIndex = point._index\n\n if (point._bufferIndex < 0) {\n point._bufferIndex = 0\n }\n\n while (point._index === chunkIndex && point._bufferIndex < chunk.length) {\n go(chunk.charCodeAt(point._bufferIndex))\n }\n } else {\n go(chunk)\n }\n }\n } // Deal with one code.",
"_write(chunk, enc, done) {\n try {\n let buffer = chunk;\n\n if (this.firstBytes.length < 4) {\n this.firstBytes.push(...buffer);\n\n if (this.firstBytes.length >= 4) {\n buffer = this.sniff();\n } else {\n done();\n return;\n }\n }\n\n // It may seem odd that this is a writable stream and not a transform\n // stream. Originally it was a transform stream. But I ran into some\n // problems owing to peculiar needs of XML parsing. The short version is\n // just that we need to be able to get immediate ‘feedback’ at from the\n // parser upon hitting an encoding declaration. We also need to be able to\n // halt flow entirely, also at the codepoint level.\n //\n // The default implementation of ‘codepoint’ is to emit a ‘codepoint’\n // event. This is just for the sake of standalone usage, e.g., during\n // tests. In practice, Decoder will be subclassed by Processor, which will\n // provide its own ‘codepoint’ method. This ends up sparing us from having\n // a bunch of intermediary buffers.\n\n const codepoints = this.decode(buffer);\n\n // This first check is needed because cork() is like, ‘cork, please,\n // unless you don’t feel like it ... on second thought just do whatever\n // you think is best for me, it was just a suggestion, I’m so silly to be\n // bothing you, apologies.’\n\n if (this.__halted__) {\n this.__codepoints__ = codepoints;\n this.__done__ = done;\n return;\n }\n\n // We cannot use a for-of loop here because automatic iterator closing\n // breaks it. I’m not sure if this is maybe a V8 implementation bug or\n // correct behavior. IIRC, automatic iterator closing was only supposed\n // to happen if there weren’t other references to the iterator, but maybe\n // that was ultimately changed. Amazingly enough, it’s not simply a matter\n // of ‘the loop was exited, so the iterator was closed’. *Synchronously*,\n // I can still get more values. It is only when the continuation is\n // attempted asynchronously that the generator, by virtue of having once\n // been used in a for loop that was exited, becomes closed! Unintuitive\n // and really zalgo-y — I hope this is a bug and not a new Bad Part?\n\n let cp;\n\n while ((cp = codepoints.next().value) !== undefined) {\n this.codepoint(cp);\n\n // If we get halted ... wait to continue! This way the parser can truly\n // halt the stream and not just like, kind of. Follow up is above in\n // local wrapper for uncork().\n\n if (this.__halted__) {\n this.__codepoints__ = codepoints;\n this.__done__ = done;\n return;\n }\n }\n\n done();\n } catch (err) {\n done(err);\n }\n }",
"function h$decodePacked(s) {\n function f(o) {\n var c = s.charCodeAt(o);\n return c<34?c-32:c<92?c-33:c-34;\n }\n var r=[], i=0;\n while(i < s.length) {\n var c = s.charCodeAt(i);\n if(c < 124) r.push(f(i++));\n else if(c === 124) {\n i += 3; r.push(90+90*f(i-2)+f(i-1));\n } else if(c === 125) {\n i += 4;\n r.push(8190+8100*f(i-3)+90*f(i-2)+f(i-1));\n } else throw (\"h$decodePacked: invalid: \" + c);\n }\n return r;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
reset rhino position and current state | resetPosition(x, y) {
this.x = x;
this.y = y;
this.moving = false;
this.currentState = {
killing: false,
frames: 1,
};
this.setDirection(Constants.RHINO_DIRECTIONS.DEFAULT)
} | [
"function resetPos(){\n var molecule = Mol();\n var cys = OriCrystal();\n centerMolecule();\n drawMolecule();\n if(molecule[0].type == \"crystal\" && cys[0].cleave == 0){\n drawCube();\n }\n if(cys[0].preview == 1){\n drawCube();\n }\n drawAxis();\n if(cys[0].cleave == 1){\n drawsurface();\n }\n}",
"resetGameElements() {\n const rhinoPositions = [\n (Constants.GAME_WIDTH + 70),\n ((Constants.GAME_HEIGHT * 0.45) - 16)\n ];\n cancelAnimationFrame(this.currentAnimationFrame);\n this.currentAnimationFrame = null;\n this.skier = new Skier(0, 0);\n this.rhino.resetPosition(...rhinoPositions);\n this.framesCounter = 0;\n this.score = 0;\n this.scoreBoard.updateScore(this.score);\n this.rhinoAppeared = false;\n this.scoreBoard.setGameStatus(\"\");\n }",
"resetPos() {\n // Set x and y to starting x and y\n this.x = this.startX;\n this.y = this.startY;\n }",
"reset() {\n\t\tthis.position = 0;\n\t}",
"resetPos() {\n this.x = width / 2 - this.w / 2 ;\n this.y = height - this.h;\n }",
"function resetTurtle() {\n // reset coloring\n resetPlaybackStyle(document.firstChild);\n // reset tutle\n turtle= document.getElementById(\"turtle\");\n turtle.setAttribute(\"transform\",\"\");\n winList= [];\n // remove old path\n path= document.getElementById(\"plotpath\");\n path.setAttribute(\"d\",\"\");\n checkPosition();\n}",
"function reset(){\n turtle['ctr_x'] = 125;\n turtle['ctr_y'] = 130;\n turtle['x'] = 100;\n turtle['y'] = 100;\n visited = [];\n dr = 0;\n eggs = [];\n draw();\n }",
"function reset (){\n cursor = 0;\n }",
"reset() {\n this.pos.set(this.startPos);\n this.vel.set(this.startVel);\n }",
"reset(){\n this.x = this.Xmove * 2; //starts player at bottom middle of screen\n this.y = this.Ymove * 5 - 30;\n }",
"function reset_coords(){ NW = N = NE = CW = CE = SW = S = SE = 0;}",
"reset() {\n this.yPos = this.groundYPos;\n this.jumpVelocity = 0;\n this.jumping = false;\n this.ducking = false;\n this.update(0, Trex.status.RUNNING);\n this.midair = false;\n this.speedDrop = false;\n this.jumpCount = 0;\n this.crashed = false;\n }",
"reset() {\n this.sprite.x = settings.birdStartPosition.x;\n this.sprite.y = settings.birdStartPosition.y;\n this.velocity = 0;\n }",
"function resetMove() {\r\n selected = false;\r\n selectedID = \"\";\r\n lockout = false;\r\n endLoc = 0;\r\n unhighlightMoves();\r\n}",
"reset()\n {\n this.current = this.unknownFramebuffer;\n this.viewport = new Rectangle();\n }",
"function reset(){\n gravity.g = 0;\n cannonball.dx = 0;\n cannonball.dy = 0;\n cannonball.x = 25;\n cannonball.y = 590;\n cannonball.cmy = 0;\n cannonball.cmx = 0;\n cannonRotate.degree = -52;\n cannonRotate.add = 0.5;\n power.power = 0;\n powerSelect.y = 195;\n powerSelect.dy = 5;\n}",
"function resetMotion() {\n window.clearTimeout(timer);\n index = -1;\n time = 0.0;\n position.x = base.x;\n runable = true;\n\n drawMotionGraph();\n}",
"reset(){\n this.lastPosition = this.position\n this.position = this.startPosition\n }",
"reset() {\n\t\tthis.realPosition = null;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create conditional thunk. Options includes the algorithm and any algorithmspecific params. FIXME: do we need to return a thunk or an ERP (that knows how to score itself)? FIXME: finish | function conditional(computation, options) {
switch (options.algorithm) {
case "traceMH":
return mcmc_thunk(computation, new RandomWalkKernel(), options.lag, options.verbose, options.init)
case "traceST":
var rwkernel = new RandomWalkKernel(function(rec){return rec.structural || (typeof rec.erp.nextVal != 'function')})
var kernel = new mixKernel(new STKernel.STKernel(), rwkernel)
return mcmc_thunk(computation, kernel, options.lag, options.verbose, options.init)
case "LARJMH":
return mcmc_thunk(computation,
new LARJKernel(new RandomWalkKernel(function(rec){return !rec.structural}), annealSteps, jumpFreq),
options.lag, options.verbose)
case "enumerate":
var items = []
var probs = []
var enumeration = enumerateDist(computation)
for (key in enumeration) {
items.push(enumeration[key].val)
probs.push(enumeration[key].prob)
}
return function() {
return items[util.discreteChoice(probs)];
}
default: //rejection
return function() {
return rejectionSample(computation)
}
}
} | [
"function conditional(computation, options) {\n switch (options.algorithm) {\n case \"traceMH\":\n \n break\n \n case \"traceST\":\n \n break\n \n case \"LARJMH\":\n \n break\n \n default: //rejection\n return function() {\n return rejectionSample(computation)\n }\n \n }\n \n}",
"function prepareTagHeuristic(tagComparison) {\n if (typeof tagComparison === 'undefined') {\n return createTagHeuristic(); // default heuristic\n } else if (typeof tagComparison === 'function') {\n return tagComparison; // custom, user-provided function\n } else if (typeof tagComparison === 'object') {\n return createTagHeuristic(tagComparison); // options for the default heuristic\n } else {\n throw new Error(\"Invalid 'tagComparison' option provided: \" + tagComparison);\n }\n}",
"static with(options = {}) {\n return new HarnessPredicate(MatSortHarness, options);\n }",
"static with(options = {}) {\n return new HarnessPredicate(MatChipGridHarness, options);\n }",
"static with(options = {}) {\n return new HarnessPredicate(MatLegacyChipAvatarHarness, options);\n }",
"retrieveAlgorithm() {\n let highestOpt = this.higherOptimization();\n if (highestOpt > this.props.trip.options.optimization) {\n return this.restOfTheString(highestOpt);\n }\n\n if (this.props.trip.options.optimization === \"none\") {\n return this.restOfTheString(0);\n }\n let slider = parseFloat((this.props.trip).options.optimization);\n let breakPoint = 1.0 / (this.props.config.optimization + 1);\n\n if (slider < breakPoint) {\n return this.restOfTheString(0); // No optimization\n }\n else if (slider >= breakPoint && slider < 2*breakPoint) {\n return this.restOfTheString(1); // NN\n }\n else if (slider >= 2*breakPoint && slider < 3*breakPoint) {\n return this.restOfTheString(2); // 2 opt\n }\n else if (slider >= 3*breakPoint && slider < 4*breakPoint) {\n return this.restOfTheString(3); // 3 opt\n }\n }",
"static with(options = {}) {\n return new HarnessPredicate(MatLegacyChipListHarness, options);\n }",
"static with(options = {}) {\n return new HarnessPredicate(MatLegacyChipInputHarness, options)\n .addOption('value', options.value, async (harness, value) => {\n return (await harness.getValue()) === value;\n })\n .addOption('placeholder', options.placeholder, async (harness, placeholder) => {\n return (await harness.getPlaceholder()) === placeholder;\n });\n }",
"function runAlgoSelected() {\n let algo;\n for (let i = 0; i < algoTracker.length; i++) {\n if (algoTracker[i][1] === true) {\n algo = algoTracker[i][0]\n }\n }\n if (!algo) {\n alert('Select an Algorithm first')\n } else {\n if (algo === 'quick') {\n return main.quick();\n } else if (algo === 'bubble') {\n return main.bubble();\n } else if (algo === 'merge') {\n return main.merge();\n } else if (algo === 'heap') {\n return main.heap();\n }\n }\n}",
"static with(options = {}) {\n return new HarnessPredicate(MatLegacyChipListboxHarness, options);\n }",
"function decisionMaker ( hungry, tired){\n if ( hungry && !tired ){\n return eat()\n } else if ( !hungry && tired ){\n return sleep()\n } else {\n return \"undecided\"\n }\n }",
"branch(predicate, trueMiddleware, falseMiddleware) {\n return this.lazy(ctx => predicate(ctx) ? trueMiddleware : falseMiddleware);\n }",
"static with(options = {}) {\n return new HarnessPredicate(MatRowHarness, options);\n }",
"function createNodeEvaluator({ typeChecker, typescript, policy, logger, stack, reporting, nextNode }) {\n let ops = 0;\n const handleNewNode = (node, statementTraversalStack) => {\n nextNode(node);\n // Increment the amount of encountered ops\n ops++;\n // Throw an error if the maximum amount of operations has been exceeded\n if (ops >= policy.maxOps) {\n throw new MaxOpsExceededError({ ops, node });\n }\n // Update the statementTraversalStack with the node's kind\n statementTraversalStack.push(node.kind);\n if (reporting.reportTraversal != null) {\n reporting.reportTraversal({ node });\n }\n };\n /**\n * Wraps an evaluation action with error reporting\n */\n const wrapWithErrorReporting = (environment, node, action) => {\n // If we're already inside of a try-block, simply execute the action and do nothing else\n if (pathInLexicalEnvironmentEquals(node, environment, true, TRY_SYMBOL)) {\n return action();\n }\n try {\n return action();\n }\n catch (ex) {\n // Report the Error\n reportError(reporting, ex, node);\n // Re-throw the error\n throw ex;\n }\n };\n const nodeEvaluator = {\n expression: (node, environment, statementTraversalStack) => wrapWithErrorReporting(environment, node, () => {\n handleNewNode(node, statementTraversalStack);\n return evaluateExpression(getEvaluatorOptions(node, environment, statementTraversalStack));\n }),\n statement: (node, environment) => wrapWithErrorReporting(environment, node, () => {\n const statementTraversalStack = createStatementTraversalStack();\n handleNewNode(node, statementTraversalStack);\n return evaluateStatement(getEvaluatorOptions(node, environment, statementTraversalStack));\n }),\n declaration: (node, environment, statementTraversalStack) => wrapWithErrorReporting(environment, node, () => {\n handleNewNode(node, statementTraversalStack);\n return evaluateDeclaration(getEvaluatorOptions(node, environment, statementTraversalStack));\n }),\n nodeWithArgument: (node, environment, arg, statementTraversalStack) => wrapWithErrorReporting(environment, node, () => {\n handleNewNode(node, statementTraversalStack);\n return evaluateNodeWithArgument(getEvaluatorOptions(node, environment, statementTraversalStack), arg);\n }),\n nodeWithValue: (node, environment, statementTraversalStack) => wrapWithErrorReporting(environment, node, () => {\n handleNewNode(node, statementTraversalStack);\n return evaluateNodeWithValue(getEvaluatorOptions(node, environment, statementTraversalStack));\n })\n };\n /**\n * Gets an IEvaluatorOptions object ready for passing to one of the evaluation functions\n */\n function getEvaluatorOptions(node, environment, statementTraversalStack) {\n return {\n typeChecker,\n typescript,\n policy,\n reporting,\n node,\n evaluate: nodeEvaluator,\n environment,\n stack,\n logger,\n statementTraversalStack\n };\n }\n return nodeEvaluator;\n}",
"static with(options = {}) {\n return new HarnessPredicate(MatLegacyActionListHarness, options);\n }",
"static with(options = {}) {\n return new HarnessPredicate(MatSnackBarHarness, options);\n }",
"function buildStrategies() {\n var strategies = {};\n\n strategies.random = function() {\n return placePointsRandom(POINT_COUNT, width, height);\n }\n\n strategies.noise_high = function() {\n return placePointsNoise(POINT_COUNT, width, height, 1);\n }\n\n strategies.noise_low = function() {\n return placePointsNoise(POINT_COUNT, width, height, .02);\n }\n\n strategies.grid = function() {\n return placePointsGrid(sqrt(POINT_COUNT), width, height);\n }\n\n strategies.cull_close_before = function() {\n return placePointsCullRange(POINT_COUNT, width, height, 20, 1000);\n }\n\n strategies.cull_far_before = function() {\n return placePointsCullRange(POINT_COUNT, width, height, 0, 30);\n }\n\n strategies.cull_both_before = function() {\n return placePointsCullRange(POINT_COUNT, width, height, 10, 30);\n }\n\n strategies.tiles = function() {\n return placePointsTiles(width / 150, width, height);\n }\n\n\n strategies.relax = function() {\n return relaxPoints(placePointsRandom(POINT_COUNT, width, height), 10, 10, 1);\n }\n\n strategies.tighten = function() {\n return relaxPoints(placePointsRandom(POINT_COUNT, width, height), 5, 50, -.3);\n }\n\n strategies.tighten_relax = function() {\n var ps = placePointsRandom(POINT_COUNT, width, height);\n ps = relaxPoints(ps, 5, 50, -.3); // tighten\n ps = relaxPoints(ps, 10, 10, 1); // relax\n return ps;\n }\n\n strategies.tiles_plus = function() {\n var ps = placePointsTiles(width / 150, width, height);\n ps = addPoints(ps, placePointsRandom(POINT_COUNT, 12, 12));\n relaxPoints(ps, 5, 17, 4);\n\n return ps;\n }\n\n strategies.grid_random = function() {\n return addPoints(placePointsGrid(sqrt(POINT_COUNT), width, height), placePointsRandom(POINT_COUNT, 12, 12));\n }\n\n strategies.grid_distort = function() {\n return noiseDistort(placePointsGrid(sqrt(POINT_COUNT), width, height), .01, 40);\n }\n\n strategies.grid_cull = function() {\n return noiseCull(placePointsGrid(sqrt(POINT_COUNT), width, height), .01, .5, .0);\n }\n\n strategies.grid_cull_dithered = function() {\n return noiseCull(placePointsGrid(sqrt(POINT_COUNT), width, height), .01, .33, .33);\n }\n\n strategies.random_cull = function() {\n return noiseCull(placePointsRandom(POINT_COUNT, width, height), .01, .5, .0);\n }\n\n strategies.cull_close_noise = function() {\n var ps = placePointsCullRange(POINT_COUNT, width, height, 15, 1000);\n return noiseCull(ps, .01, .5, .0);\n }\n\n\n\n\n return strategies;\n\n}",
"function generateTrivialOpBoilerplate(fn,ctx) {\n\n var code = '';\n\n // NB: trivial functions don't rely on pc being set up, so we perform the op before updating the pc.\n code += fn;\n\n ctx.isTrivial = true;\n\n if (accurateCountUpdating) {\n code += 'c.control_signed[9] += 1;\\n';\n }\n\n // NB: do delay handler after executing op, so we can set pc directly\n if (ctx.needsDelayCheck) {\n code += 'if (c.delayPC) { c.pc = c.delayPC; c.delayPC = 0; } else { c.pc = ' + format.toString32(ctx.pc+4) + '; }\\n';\n // Might happen: delay op from previous instruction takes effect\n code += 'if (c.pc !== ' + format.toString32(ctx.post_pc) + ') { return ' + ctx.fragment.opsCompiled + '; }\\n';\n } else {\n code += ctx.genAssert('c.delayPC === 0', 'delay pc should be zero');\n\n // We can avoid off-branch checks in this case.\n if (ctx.post_pc !== ctx.pc+4) {\n n64js.assert(\"post_pc should always be pc+4 for trival ops?\");\n code += 'c.pc = ' + format.toString32(ctx.pc+4) + ';\\n';\n code += 'if (c.pc !== ' + format.toString32(ctx.post_pc) + ') { return ' + ctx.fragment.opsCompiled + '; }\\n';\n } else {\n //code += 'c.pc = ' + format.toString32(ctx.pc+4) + ';\\n';\n code += '/* delaying pc update */\\n';\n ctx.delayedPCUpdate = ctx.pc+4;\n }\n }\n\n\n // Trivial instructions never cause a branch delay\n code += ctx.genAssert('c.delayPC === 0', 'delay pc should be zero');\n ctx.needsDelayCheck = false;\n\n // Trivial instructions never cause stuffToDo to be set\n code += ctx.genAssert('c.stuffToDo === 0', 'stuffToDo should be zero');\n\n return code;\n }",
"function createConditionalEvaluator(conditionNode, trueNodes, falseNodes) {\n var $1 = createEvaluator(conditionNode)\n , $2 = createStatementsEvaluator(trueNodes)\n , $3 = createStatementsEvaluator(falseNodes);\n\n if ( typeof $1 !== 'function' ) {\n return $1 ? $2 : $3;\n }\n\n var type = getBinaryType($2, $3);\n return [condLiteral, condTrue, condFalse, condBoth][type];\n\n function condLiteral(c, w) { return $1(c, w) ? $2 : $3; }\n function condTrue(c, w) { return $1(c, w) ? $2(c, w) : $3; }\n function condFalse(c, w) { return $1(c, w) ? $2 : $3(c, w); }\n function condBoth(c, w) { return $1(c, w) ? $2(c, w) : $3(c, w); }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
console.log(tripleNumber([3, 1, 5, 10])); 2. Write a function that takes in an array of numbers and returns a new array of numbers less than 5. For example, given [4, 10, 8, 3], the function should return [4, 3]. | function numbersLessThanFive(inputArray) {
var outputArray = [];
for (var i = 0; i < inputArray.length; i++) {
if (inputArray[i] < 5) {
outputArray.push(inputArray[i]);
}
}
return outputArray;
} | [
"function tripleAndFilter(arr){\n return arr.map(function(value){\n return value * 3;\n }).filter(function(value){\n return value % 5 === 0;\n })\n }",
"function tripledPlusFive(arr){\n var onlyNums=arr.filter(function(val){\n return typeof val === 'number'\n })\n mappingOnlyNums = onlyNums.map(function(val){\n return ((val * 3) + 5) //[3, 6, 9, 12, 15]\n })\n return mappingOnlyNums\n}",
"function largerThanThree(array) {\n let newArray = [];\n\n for (const number of array) {\n if (number > 3) {\n newArray.push(number);\n }\n }\n\n return newArray;\n}",
"function elementsLessThanGiven(array, number) {\n var newArray = [];\n var index = 0;\n\n for (var i = 0; i < array.length; i++) {\n if (array[i] < number) {\n newArray[index] = array[i];\n index++;\n // newArray.push(array(i))\n }\n }\n return newArray;\n}",
"function tripler(array) {\n let newArray = [];\n\n for (let index = 0; index < array.length; index++) {\n const num = array[index];\n newArray.push(num * 3);\n }\n\n return newArray;\n}",
"function listFiveNumbers() {\n \n return [1,2,3,4,5];\n\n}",
"function filter(array) {\n newArray = []\n array.forEach((number) => {\n if (number > 5) {\n newArray.push(number)\n }\n })\n return newArray;\n}",
"function multiFour(array)\n{\n\tvar mulFour=array.filter(value=>value%4==0);\n\tconsole.log(mulFour);\n}",
"function doubleTrouble(array){\n var numbers2= []; \n for (var i = 0; i<array.length; i++){\n numbers2.push(array[i]*2) \n } return numbers2\n}",
"function get_larger_numbers(array, num){\n const result = []\n array.forEach(x => {\n if (x >= num){\n result.push(x)\n } else {\n result.push(num)\n }\n })\n return result\n}",
"function numbersTimesThree(array) {\n var outputArray = [];\n array.forEach(function (value) {\n outputArray.push(value * 3);\n });\n return outputArray;\n}",
"function fiveTo(number){\n var arrayIntegers = [];\n for (var i = 5; i < number; i++) {\n arrayIntegers.push(i);\n\n }\n return arrayIntegers;\n\n}",
"function doubleOddNumbers(arr) {}",
"function doubleNumbers(array) {\n return array.map(function(number) {\n return number * 2;\n }, []);\n}",
"function getMultiplesOfThree() {\n var A = [10, 5, 13, 18, 51];\n return A.filter(el => el % 3 == 0);\n}",
"function tripleEachElement(array) {\n return array.map(function (n) {return 3 * n});\n}",
"function lessThanAGivenElement(array, num) {\n var output = [];\n array.forEach(function (el) {\n if (el < num) {\n output[output.length] = el;\n }\n });\n \n return output;\n}",
"function higherThanThree(number){\n const newNumber = [];\n for (i = 0; i < number.length; i++) {\n if(number[i] >= 3){\n newNumber.push(number[i]);\n }\n }\n return newNumber;\n }",
"function triple(n){\n return n * 3;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get mapping by locale | getLocaleMapping(locale, group = 'default') {
locale = (0, utils_1.formatLocale)(locale);
const langMap = this.localeTextMap.get(locale);
if (langMap) {
return langMap.get(group);
}
} | [
"mapLocale(locale = this._defaultLocale) {\n let layout;\n const country = locale\n .split('-')\n .shift();\n // search for layout matching the\n // first part, the country code\n if (this.availableLocales[country]) {\n layout = this.availableLocales[locale];\n }\n // look if the detailed locale matches any layout\n if (this.availableLocales[locale]) {\n layout = this.availableLocales[locale];\n }\n if (!layout) {\n throw Error(`No layout found for locale ${locale}`);\n }\n return layout;\n }",
"function MapLocale() {\n this.localeID = 0;\n this.localeVisitCount = 0;\n this.localeName = \"localeName\";\n this.localeDesc = \"localeDesc\";\n this.localeDirBlocked = \"Erm... sorry, you can't go that way.\";\n }",
"normalize(locales, locale) {\n if (!locale) {\n return null;\n }\n\n // Transform Language-Country => Language_Country\n locale = locale.replace('-', '_');\n\n let search;\n\n if (api.collections.isArray(locales)) {\n search = isArrayElement;\n } else {\n search = isObjectKey;\n }\n\n if (search(locales, locale)) {\n return locale;\n }\n\n // Try to search by the language\n const parts = locale.split('_');\n const language = parts[0];\n if (search(locales, language)) {\n return language;\n }\n\n return null;\n }",
"function getLocale(localeString) {\n var loc = localeArray.filter(function (locale) {\n return locale.code == localeString;\n });\n return $.extend(true, {}, loc[0]); //important to use $.extend to clone the object (rather than create a reference)\n}",
"getStringForLocale(key, locale) {\n let strings = this.strings[locale];\n if (!strings) {\n strings = $5b160d28a433310d$var$getStringsForLocale(locale, this.strings, this.defaultLocale);\n this.strings[locale] = strings;\n }\n let string = strings[key];\n if (!string) throw new Error(`Could not find intl message ${key} in ${locale} locale`);\n return string;\n }",
"static get( locale ) {\n console.log( 'GetI18N: Locale is ' + locale );\n // alert( locale + ' from geti18nmessage..' );\n if ( locale == 'ja' ) {\n \n return jaMessages;\n\n } else {\n \n // default to en\n return enMessages;\n\n }\n\n \n }",
"locale(key) {\n //Open and read JSON file\n console.log(\"Locale OBJ: \", this.obj);\n let val = null;\n //Find and Return Value of specified Key\n return this.obj[key];\n }",
"function localize(key) {\n const language = l10n.locale.slice(0, 2);\n let result = '';\n // Attempt to find a match for the current locale\n if (l10n.strings[l10n.locale])\n result = l10n.strings[l10n.locale][key];\n // If none is found, attempt to find a match for the language\n if (!result && l10n.strings[language])\n result = l10n.strings[language][key];\n // If none is found, try english\n if (!result)\n result = l10n.strings.en[key];\n // If that didn't work, return undefined\n if (!result)\n return undefined;\n return result;\n}",
"function getLocaleId(locale){return findLocaleData(locale)[0/* LocaleId */];}",
"function mapLanguage(langCode) {\r\n\tif (languageMap[langCode]) return (languageMap[langCode]['name']);\r\n\telse return ('unknown');\r\n}",
"static getRegisteredLocales(){return Object.keys(TcHmi.System.config.languages)}",
"function getLocalizedString() {\n var namedKey = arguments[0];\n var result = '';// default the result to an empty string\n if (namedKey === undefined) {\n $log.error(\"LOCALIZE ERROR : attempted to read KEY UNDEFINED\");\n return result;\n }\n else if (namedKey === '') {\n $log.error(\"LOCALIZE ERROR : attempted to read KEY EMPTY STRING\");\n return result;\n }\n if (dictionary.length <= 0) {\n return result;\n }\n // make sure the dictionary has valid data\n if ((dictionary !== []) && (dictionary.length > 0)) {\n // use the filter service to only return those entries which match the value\n // and only take the first result\n var entry = $filter('filter')(dictionary, function (element) {\n return element.key === namedKey;\n }\n )[0];\n if (entry === undefined) {\n $log.error(\"LOCALIZE ERROR : Could not find KEY named \" + namedKey + \" for language \" + language + \". FORGOT TO DECLARE IT?\");\n return namedKey;\n } else {\n // set the result getting value for the current language\n result = entry[language];\n }\n }\n //replaces {0} , {1} and so on\n if (arguments.length > 1){\n for (var index = 1; index < arguments.length; index++) {\n var target = '{' + (index-1) + '}';\n result = result.replace(target, arguments[index]);\n }\n }\n //console.log(result+ \" FOR \"+localize.language);\n // return the value to the call\n return result;\n }",
"function getTranslation(keyPath, locale) {\n var translation = eval('_locales.' + locale + '.' + keyPath);\n if(!translation || (translation === undefined)) {\n return null;\n }\n return translation;\n }",
"function getLocale(lang) {\n\t//var lang = req.headers[\"accept-language\"];\n\tif (!lang) {\n\t\treturn;\n\t}\n\tlet arr;\n\tif (lang.indexOf(\";\") >= 0) {\n\t\tarr = lang.substring(0, lang.indexOf(\";\")).split(\",\");\n\t} else {\n\t\tarr = [lang];\n\t}\n\t//var arr = langparser.parse(lang);\n\t//if (!arr || arr.length < 1) {\n\t//\treturn;\n\t//}\n\t//var locale = arr[0].code;\n\n\tvar locale = arr[0].substring(0, arr[0].indexOf(\"-\"));\n\n\t//if (arr[0].region) {\n\t//\tlocale += \"_\" + arr[0].region;\n\t//}\n\n\tlocale += \"_\" + arr[0].substring(arr[0].indexOf(\"-\") + 1);\n\treturn locale;\n}",
"locale() {\n return settingsCache.get('default_locale');\n }",
"function getLocaleData(langCode) {\n\t\tvar f = moment.localeData || moment.langData;\n\t\treturn f.call(moment, langCode) ||\n\t\t\tf.call(moment, 'en'); // the newer localData could return null, so fall back to en\n\t}",
"function getText(key, locale) {\n var labels = locales[locale];\n\n return labels ? labels[key] : locales.en[key];\n }",
"function findFallbackLocale(locale) {\n const locales = getAvailableLocales();\n\n for (let i = locale.length - 1; i > 1; i -= 1) {\n const key = locale.substring(0, i);\n\n if (locales.includes(key)) {\n return key;\n }\n }\n\n return null;\n}",
"function getText(key, locale) {\r\n var labels = locales[locale];\r\n\r\n return labels ? labels[key] : locales.en[key];\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get current search options | function getSearchOptions() {
var serchOptions = {};
serchOptions[HOTEL_SEARCH_FILTER] = filterParams;
serchOptions[HOTEL_SEARCH_BODY] = filterBody;
serchOptions[HOTEL_SEARCH_ADVANCE] = filterAdvance;
serchOptions[HOTEL_SEARCH_FROM_CACHE] = filterFromCache;
return angular.copy(serchOptions);
} | [
"function getQuerySearchOptions() {\n\tvar offset = null,\n\t\tlocation = null,\n\t\tradius = null;\n\n\n\tvar options = {\n\t\tinput: document.searchForm.search.value\n\t};\n\n\t// set offset\n\toffset = document.querySelector('.settings-query-search input[name=\"offset\"]').value;\n\tif (/^\\d+$/.test(offset)) {\n\t\toptions.offset = parseInt(offset, 10);\n\t}\n\n\t// set location and radius\n\tlocation = document.querySelector('.settings-query-search input[name=\"location\"]').value;\n\tradius = document.querySelector('.settings-query-search input[name=\"radius\"]');\n\tif (location !== '' && radius !== '') {\n\t\toptions.location = new google.maps.LatLng({\n\t\t\tlat: parseFloat(location.split(',')[0]),\n\t\t\tlng: parseFloat(location.split(',')[1])\n\t\t});\n\n\t\toptions.radius = parseInt(radius, 10);\n\t}\n\n\treturn options;\n}",
"get options() {\n return this._results.options;\n }",
"function getOptions() {\n\t\tmodel.getSnapShot()\n\t\t.then(function(snapShot) {\n\t\t\tlet artists = [],\n\t\t\t albums = [];\n\t\t\tfor (let key in snapShot.val()) {\n\t\t\t\tartists.push(snapShot.val()[key].artist);\n\t\t\t\talbums.push(snapShot.val()[key].album);\n\t\t\t}\n\t\t\t// uses underscore to find unique values\n\t\t\t// and sort had to use lowercase to sort\n\t\t\t// alphabetically properly\n\t\t\tartists = _.uniq(artists).sort();\n\t\t\talbums = _.uniq(albums).sort();\n\t\t\t// displays the filter form\n\t\t\trender.filter(albums, artists);\n\t\t});\n\t}",
"function quickSearchOptions_GetUserDefinedValues() {\n\n //Gather Quick Search Options\n var searchText = $(\"#QuickSearchTextBox_helm\").igTextEditor(\"text\").trim();\n var stateAbbreviation = Compass.Utils.igCombo_GetByValue(\"QuickSearchStateCombo_helm\");\n var subStatusTypeSkey = Compass.Utils.igCombo_GetByValue(\"QuickSearchSubStatusCombo_helm\");\n\n //If the user has access to search all orgs then get their filter criteria from \n //the quick search all orgs drop down. Otherwise, do not search all orgs.\n var allOrgs = false;\n if (helm.QuickSearchOptionsData.ShowAllOrgsQuickSearchOption) {\n allOrgs = Compass.Utils.igCombo_GetByValue(\"QuickSearchOrgCombo_helm\");\n }\n /* */\n\n var searchAllOrgs = (allOrgs == null) ? false : allOrgs; //if null default to false\n\n return new helm.QuickSearch(searchText, stateAbbreviation, subStatusTypeSkey, searchAllOrgs);\n\n }",
"get findOptions() {\n return this._findOptions\n }",
"function getOptions(options) {\n\n // Extract the links option that specifies if the elements \n // should include link that takes it to the details page\n if (options.hasOwnProperty(\"links\")) {\n links = options.links;\n }\n\n // Extract the links option that specifies if the elements \n // should include link that takes it to the details page\n if (options.hasOwnProperty(\"selectable\")) {\n selectable = options.selectable;\n }\n\n // extract the strip option that tells Geo Display \n // wether it should generate the breadcrumbs strip\n if (options.hasOwnProperty(\"strip\")) {\n makeStrip = options.strip;\n }\n\n // extract the parrent option that tells Geo Display \n // if it should generate the parent placeholder and place \n // elements in the parent placeholder after expanding the,\n if (options.hasOwnProperty(\"parent\")) {\n makeParent = options.parent;\n }\n\n // extract the search option that tells Geo Display \n // if it should generate the search functionalirty \n // for locations\n if (options.hasOwnProperty(\"search\")) {\n makeSearch = options.search;\n }\n\n // extract the search option that tells Geo Display \n // if it the search functionality should include options for context\n // searching\n if (options.hasOwnProperty(\"contextSearch\")) {\n makeContextSearch = options.contextSearch;\n contextSearch = true;\n }\n\n // extract option that decides if search help should be generated.\n if (options.hasOwnProperty(\"searchHelp\")) {\n makeSerachHelp = options.searchHelp;\n }\n\n // extract option that decides if locations can be expanded if they have children.\n if (options.hasOwnProperty(\"expansion\")) {\n allowExpansion = options.expansion;\n }\n\n // extract option that decides if empty search string can happen\n if (options.hasOwnProperty(\"emptySearch\")) {\n allowEmptySearch = options.emptySearch;\n }\n\n // extract option that decides if empty search string can happen\n if (options.hasOwnProperty(\"allowCrumbs\")) {\n allowCrumbs = options.allowCrumbs;\n }\n\n\n }",
"function selectOptions() {\n\n let options = [];\n\n if (props.smallSearch) {\n availiableTokens.forEach((token, i) => {\n let symbol = token['symbol'];\n let address = token['address'];\n //let name = token['name'];\n let logo = token['logoURI'];\n options.push({\n \"value\": address,\n \"name\": symbol,\n \"key\": i,\n \"logo\": logo,\n \"symbol\": symbol\n });\n });\n }\n else {\n availiableTokens.forEach((token, i) => {\n let symbol = token['symbol'];\n let address = token['address'];\n let name = token['name'];\n let logo = token['logoURI'];\n options.push({\n \"value\": address,\n \"name\": name,\n \"key\": i,\n \"logo\": logo,\n \"symbol\": symbol\n });\n });\n }\n\n return options;\n }",
"getCurrentOptions() {\r\n return Object.keys(this.curr.val[this.getCurrentQuestion()]);\r\n }",
"function getPlaceSearchOptions() {\n\tvar componentRestrictions = null,\n\t\toffset = null,\n\t\tlocation = null,\n\t\tradius = null,\n\t\ttypes = [];\n\n\tdocument.querySelectorAll('.settings-place-search input[name=\"types\"]:checked').forEach(function(item) {\n\t\ttypes.push(item.value);\n\t});\n\n\tvar options = {\n\t\tinput: document.searchForm.search.value,\n\t\ttypes: types\n\t};\n\n\t// set componentRestrictions\n\tcomponentRestrictions = document.querySelector('.settings-place-search select[name=\"componentRestrictions\"]').value;\n\tif (componentRestrictions !== \"\") {\n\t\toptions.componentRestrictions = {\n\t\t\tcountry: componentRestrictions\n\t\t};\n\t}\n\n\t// set offset\n\toffset = document.querySelector('.settings-place-search input[name=\"offset\"]').value;\n\tif (/^\\d+$/.test()) {\n\t\toptions.offset = parseInt(offset, 10);\n\t}\n\n\t// set location and radius\n\tlocation = document.querySelector('.settings-place-search input[name=\"location\"]').value;\n\tradius = document.querySelector('.settings-place-search input[name=\"radius\"]').value;\n\n\tif (location !== '' && radius !== '') {\n\t\toptions.location = new google.maps.LatLng({\n\t\t\tlat: parseFloat(location.split(',')[0]),\n\t\t\tlng: parseFloat(location.split(',')[1])\n\t\t});\n\n\t\toptions.radius = parseInt(radius, 10);\n\t}\n\n\treturn options;\n}",
"@computed get searchOptions(): ?GetTransactionsRequesOptions {\n const wallet = this.stores.substores[environment.API].wallets.active;\n if (!wallet) return null;\n let options = this._searchOptionsForWallets[wallet.id];\n if (!options) {\n // Setup options for each requested wallet\n extendObservable(this._searchOptionsForWallets, {\n [wallet.id]: {\n limit: this.INITIAL_SEARCH_LIMIT,\n skip: this.SEARCH_SKIP\n }\n });\n options = this._searchOptionsForWallets[wallet.id];\n }\n return options;\n }",
"function getOptions() {\n\t\treturn defaultOptions;\n\t}",
"function getOptions() {\n return defaultOptions;\n }",
"function fvc_searchOptions(options) {\n /*****************************************\n * overrides must provide the following classes and ids\n *\n * class: facetview_startagain - reset the search parameters\n * class: facetview_pagesize - size of each result page\n * class: facetview_order - ordering direction of results\n * class: facetview_orderby - list of fields which can be ordered by\n * class: facetview_searchfield - list of fields which can be searched on\n * class: facetview_freetext - input field for freetext search\n *\n * should (not must) respect the following configs\n *\n * options.search_sortby - list of sort fields and directions\n * options.searchbox_fieldselect - list of fields search can be focussed on\n * options.sharesave_link - whether to provide a copy of a link which can be saved\n */\n \n // initial button group of search controls\n var thefacetview = '<div class=\"btn-group\" style=\"display:inline-block; margin-right:5px;\"> \\\n <button type=\"button\" class=\"btn btn-sm btn-default facetview_startagain\" title=\"clear all search settings and start again\" href=\"\"><span class=\"glyphicon glyphicon-remove\"></span></button> \\\n <button type=\"button\" class=\"btn btn-sm btn-default facetview_pagesize\" title=\"change result set size\" href=\"#\"></a>';\n \n if (options.search_sortby.length > 0) {\n thefacetview += '<button type=\"button\" class=\"btn btn-sm facetview_order\" title=\"current order descending. Click to change to ascending\" \\\n href=\"desc\"><span class=\"glyphicon glyphicon-arrow-down\"></span></a>';\n }\n thefacetview += '</div>';\n \n // selection for search ordering\n if (options.search_sortby.length > 0) {\n thefacetview += '<select class=\"facetview_orderby\" style=\"border-radius:5px; \\\n -moz-border-radius:5px; -webkit-border-radius:5px; width:100px; background:#eee; margin:0 5px 21px 0; padding: 3px;\"> \\\n <option value=\"\">order by ... relevance</option>';\n \n for (var each = 0; each < options.search_sortby.length; each++) {\n var obj = options.search_sortby[each];\n var sortoption = '';\n if ($.type(obj['field']) == 'array') {\n sortoption = sortoption + '[';\n sortoption = sortoption + \"'\" + obj['field'].join(\"','\") + \"'\";\n sortoption = sortoption + ']';\n } else {\n sortoption = obj['field'];\n }\n thefacetview += '<option value=\"' + sortoption + '\">' + obj['display'] + '</option>';\n };\n thefacetview += '</select>';\n }\n \n // select box for fields to search on\n if ( options.searchbox_fieldselect.length > 0 ) {\n thefacetview += '<select class=\"facetview_searchfield\" style=\"border-radius:5px 0px 0px 5px; \\\n -moz-border-radius:5px 0px 0px 5px; -webkit-border-radius:5px 0px 0px 5px; width:100px; margin:0 -2px 0px 0; background-color:inherit; \\\n padding:6px; width: 33%;\">';\n thefacetview += '<option value=\"\">search everywhere</option>';\n \n for (var each = 0; each < options.searchbox_fieldselect.length; each++) {\n var obj = options.searchbox_fieldselect[each];\n thefacetview += '<option value=\"' + obj['field'] + '\">' + obj['display'] + '</option>';\n };\n thefacetview += '</select>';\n };\n \n // text search box\n thefacetview += '<input type=\"text\" class=\"facetview_freetext\" style=\"border-radius:5px; \\\n -moz-border-radius:5px; -webkit-border-radius:5px; \\\n display:inline-block; width: 55%; margin:0 0 0 0; background-color:inherit; padding: 6px;\" \\\n name=\"q\" value=\"\" placeholder=\"search term\" />';\n \n // share and save link\n if (options.sharesave_link) {\n thefacetview += '<a class=\"btn facetview_sharesave\" title=\"share or save this search\" style=\"margin:0 0 21px 5px;\" href=\"\"><i class=\"icon-share-alt\"></i></a>';\n thefacetview += '<div class=\"facetview_sharesavebox alert alert-info\" style=\"display:none;\"> \\\n <button type=\"button\" class=\"facetview_sharesave close\">×</button> \\\n <p>Share or save this search:</p> \\\n <textarea class=\"facetview_sharesaveurl\" style=\"width:100%;height:100px;\">' + shareableUrl(options) + '</textarea> \\\n </div>';\n }\n return thefacetview\n}",
"function getOptions() {\n\toptions = datastore.getTable('options');\n\n\tif (options.query().length === 0) {\n\t\t_initializeOptions();\n\t}\n\telse {\n\t\t_setOptionsUI();\n\t}\n}",
"function getOptions() {\n var currentOptions = questions[questionIndex].options;\n return currentOptions;\n }",
"function getOptions() {\n return defaultOptions;\n }",
"get options() {\n return this._items;\n }",
"get searchExpr() {\n return this._getOption('searchExpr');\n }",
"function getOptions() {\n return ctrl.options;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The purpose of this function is to print the billing info informations in the correct position | function print_isrBankInfo(jsonInvoice, report, repStyleObj) {
var str = jsonInvoice["billing_info"]["bank_name"].split(',');
//Receipt
var billingInfo_REC = report.addSection("billingInfo_REC");
for (var i = 0; i < str.length; i++) {
billingInfo_REC.addParagraph(str[i].trim());
}
//Payment
var billingInfo_PAY = report.addSection("billingInfo_PAY");
for (var i = 0; i < str.length; i++) {
billingInfo_PAY.addParagraph(str[i].trim());
}
} | [
"printInfo() {\n // console.log('EXCHANGE: investor list:');\n // Object.values(this.investors).forEach(investor => void console.log(investor));\n // console.log(`EXCHANGE: chain length: ${this.chain.lastBlock().index}, total BTC: ${this.totalBtc}`);\n }",
"function paymentInfo() {\n shippingAddressInnerHTML();\n billingAddressInnerHTML();\n cardInfoInnerHTML();\n showPaymentPrice();\n shippingOptionInnerHTML();\n}",
"function print_billing_list(list) {\n var bil_list = document.querySelector(\".billing-list\");\n\n var list_container = document.createElement(\"ul\");\n list_container.classList.add(\"billing-list__list\");\n\n bil_list.appendChild(list_container);\n\n for (key in list.values) {\n\n if (list.values[key].result >= 0) {\n\n var list_item = document.createElement(\"li\");\n list_item.classList.add(\"billing-list__item\");\n\n var name_container = document.createElement(\"div\");\n name_container.classList.add(\"billing-list__item-container\");\n name_container.classList.add(\"billing-list__item-container_name\");\n\n list_item.appendChild(name_container); //add div into li\n\n var name_text = document.createElement(\"p\");\n name_text.classList.add(\"billing-list__name\");\n\n name_container.appendChild(name_text); //add p into div\n\n var values_container = document.createElement(\"div\");\n values_container.classList.add(\"billing-list__item-container\");\n values_container.classList.add(\"billing-list__item-container_values\");\n\n list_item.appendChild(values_container); //add div into li\n\n var value_text = document.createElement(\"span\");\n value_text.classList.add(\"billing-list__value\");\n\n values_container.appendChild(value_text); //add span into div\n\n var result_text = document.createElement(\"span\");\n result_text.classList.add(\"billing-list__result\");\n\n values_container.appendChild(result_text); //add span into div\n\n name_text.innerHTML = list.values[key].name;\n value_text.innerHTML = list.values[key].value;\n result_text.innerHTML = getRuNumberFormat(list.values[key].result);// + \" ₽\";\n\n list_container.append(list_item);\n }\n\n }\n}",
"function displayOrderInformation(id) {\n var data = [];\n\n /**\n * Iterates over the orders array and assigns an order to data if the given order ID is found.\n */\n for (var i = 0; i < orders.length; i++) {\n if (orders[i]['_id']['$oid'] === id) {\n data = orders[i];\n }\n }\n\n $('#orderModalTitle').text('Order #' + data['orderNumber'] + ' - ' + data['shipping']['firstName'] + ' ' + data['shipping']['lastName']);\n $('#dateOfPurchase').text(getDate(data['dateCreated']['$date']['$numberLong']));\n $('#status').text(data['status']);\n $('#shippingAddress').html(\n '<h6>Shipping Address:</h6>' +\n '<div>' + data['shipping']['firstName'] + ' ' + data['shipping']['lastName'] + '</div>' +\n '<div>' + data['shipping']['address1'] + '</div>' +\n ((data['shipping']['address2'] !== '') ? '<div>' + data['shipping']['address2'] + '</div>' : '') +\n '<div>' + data['shipping']['townOrCity'] + '</div>' +\n '<div>' + ((data['shipping']['county'] !== '') ? (data['shipping']['county'] + ', ') : '') + data['shipping']['postCode'] + '</div>' +\n '<div>' + data['shipping']['country'] + '</div>'\n );\n $('#billingAddress').html(\n '<h6>Billing Information:</h6>' +\n '<div class=\"mb-2\">Card ending in ' + data['billing']['cardNumber'] + '</div>' +\n '<h6>Billing Address:</h6>' +\n ((data['billing']['sameAsShipping'] === 'true') ? '<div>Same as shipping address</div>' :\n '<div>' + data['billing']['firstName'] + ' ' + data['billing']['lastName'] + '</div>' +\n '<div>' + data['billing']['address1'] + '</div>' +\n ((data['billing']['address2'] !== '') ? '<div>' + data['billing']['address2'] + '</div>' : '') +\n '<div>' + data['billing']['townOrCity'] + '</div>' +\n '<div>' + ((data['billing']['county'] !== '') ? (data['billing']['county'] + ', ') : '') + data['billing']['postCode'] + '</div>' +\n '<div>' + data['billing']['country'] + '</div>'\n )\n );\n $('#delivery').text(data['delivery']);\n\n var html = '';\n\n /**\n * Iterates over the order's package array and appends a row in HTML form for each product in the order's package.\n */\n for (var i = 0; i < data['package'].length; i++) {\n var product = data['package'][i];\n var productName = product['title'] + ' (' + product['year'] + ')';\n var quantity = {'DVD': product['dvdQuantity'], 'Blu-ray': product['bluRayQuantity']};\n var price = {'DVD': product['dvdPrice'], 'Blu-ray': product['bluRayPrice']};\n\n for (var key in quantity) {\n if (parseInt(quantity[key]) > 0) {\n html += '<li>' + quantity[key] + ' x ' + productName + ' [Format: ' + key + '] ' + '[Price: £' + price[key] + ']' + '</li>';\n }\n }\n }\n\n $('#package').html(html);\n $('#subTotal').text('£' + data['summary']['subTotal']);\n $('#vat').text('£' + data['summary']['vat']);\n $('#postAndPackaging').text((data['summary']['postAndPackaging'] !== 'Free') ?'£ ' + data['summary']['postAndPackaging'] : 'Free');\n $('#grandTotal').text('£' + data['summary']['grandTotal']);\n}",
"*getBillingInfo() {\n // TODO\n }",
"function displayInfo() {\n\t//get order summary cookie fields\n\tvar info = document.getElementById(\"custInfo\");\n\tvar fName = getField(\"order\", \"fName\");\n\tvar lName = getField(\"order\", \"lName\");\n\tvar phone = getField(\"order\", \"phone\");\n\tvar hours = getField(\"order\", \"hours\");\n\tvar minutes = getField(\"order\", \"minutes\");\n\tvar ampm = getField(\"order\", \"ampm\");\n\tvar month = getField(\"order\", \"month\");\n\tvar day = getField(\"order\", \"day\");\n\tvar card = getField(\"order\", \"card\");\n\t\n\t//display pickup and customer information\n\tinfo.innerHTML = \"The following order will be ready for pickup on \" + month + \" \" + day + \" at \" +\n\t\t\thours + \":\" + minutes + \" \" + ampm + \" for \" + fName + \" \" + lName + \", \" +\n\t\t\t\"with telephone number of \" + phone + \" and credit card ending in \" + card + \":\";\n}",
"function printAccountInfo(name, number, business) {\n\tconsole.log(`Account Holder Name: ${name}`);\n\tconsole.log(`Account Holder Number: ${number}`);\n\tconsole.log(`Business Name: ${business}`);\n}",
"function printOderDetail() {\r\n console.log('Order Information Detail : ');\r\n console.log('Họ Tên : ', gSelectedMenuStructure.hoTen);\r\n console.log('Email :', gSelectedMenuStructure.email);\r\n console.log('Số Điện Thoại :', gSelectedMenuStructure.soDienThoai);\r\n console.log('Địa chỉ : ', gSelectedMenuStructure.diaChi);\r\n console.log('Lời Nhắn :', gSelectedMenuStructure.loiNhan);\r\n console.log('Size Pizza : ', gSelectedMenuStructure.kichCo);\r\n console.log('Loại Pizza : ', gSelectedMenuStructure.loaiPizza);\r\n console.log('Giá Chưa Khuyến mại: ', gSelectedMenuStructure.priceCombo);\r\n console.log('% Giảm Giá : ', gSelectedMenuStructure.phanTramGiamGia);\r\n console.log('Phải Thanh Toán : ', gSelectedMenuStructure.thanhTien);\r\n }",
"function packageDetails() {\n let currentCustomer = vm.customers[vm.currentIndices.customer];\n let currentOrder = currentCustomer.orders[vm.currentIndices.order];\n let currentShipment = currentOrder.shipments[vm.currentIndices.shipment];\n if (currentShipment !== undefined) {\n let packageInfoElement = document.getElementById(\"PACKAGE_DETAILS\").children;\n packageInfoElement[1].innerText = currentShipment.ship_date;\n let contents = \"\";\n for(let i = 0; i < currentShipment.contents.length; i++){\n contents += currentShipment.contents[i];\n contents += \", \";\n }\n packageInfoElement[4].innerText = contents.substring(0,contents.length-2);\n }\n }",
"printAddressBook() {\n var j = 1;\n console.log('----------------------------------Address Book details-----------------------------------------\\n');\n\n console.log('Sr.No. First Name\\tLast Name\\t Mobile No.\\t City\\t State \\t ZIP code');\n for (let i = 0; i < this.addressbook.AddressBook.length; i++) {\n if (this.addressbook.AddressBook[i] == null) {\n continue;\n }\n console.log(j++ + '.\\t' + this.addressbook.AddressBook[i].FirstName\n + '\\t\\t ' + this.addressbook.AddressBook[i].LastName\n + '\\t\\t' + this.addressbook.AddressBook[i].MobileNo\n + '\\t ' + this.addressbook.AddressBook[i].City\n + '\\t ' + this.addressbook.AddressBook[i].State\n + '\\t ' + this.addressbook.AddressBook[i].ZipCode);\n }\n }",
"function printDetails(data) {\n data.forEach(item => {\n // console.log(item.name, item.capital, item.flag);\n })\n }",
"function displayInfo(accountHolder, accountNumber,businessName) {\n\tconsole.log(`Account Holder Name: ${accountHolder}`);\n\tconsole.log(`Account Number: ${accountNumber}`);\n\tconsole.log(`Business Name: ${businessName}`);\n}",
"function extractBillingData(obj) {\n obj = _.isDefined(obj) ? obj : $cart || {};\n\n return {\n fullName : (obj['billing_firstname'] + ' ' + obj['billing_lastname']).trim(),\n firstName : obj['billing_firstname'],\n lastName : obj['billing_lastname'],\n address : obj['billing_address'],\n address2 : obj['billing_address2'],\n city : obj['billing_city'],\n state : obj['billing_state'],\n zip : obj['billing_zip'],\n country : obj['billing_country']\n };\n }",
"function print_isrSupplierInfo(jsonInvoice, report, repStyleObj) {\n\n //Receipt\n var supplierInfo_REC = report.addSection(\"supplierInfo_REC\");\n supplierInfo_REC.addParagraph(jsonInvoice[\"billing_info\"][\"iban_number\"]);\n supplierInfo_REC.addParagraph(jsonInvoice[\"supplier_info\"][\"business_name\"]);\n supplierInfo_REC.addParagraph(jsonInvoice[\"supplier_info\"][\"address1\"]);\n supplierInfo_REC.addParagraph(jsonInvoice[\"supplier_info\"][\"postal_code\"] + \" \" + jsonInvoice[\"supplier_info\"][\"city\"]);\n\n //Payment\n var supplierInfo_PAY = report.addSection(\"supplierInfo_PAY\");\n supplierInfo_PAY.addParagraph(jsonInvoice[\"billing_info\"][\"iban_number\"]);\n supplierInfo_PAY.addParagraph(jsonInvoice[\"supplier_info\"][\"business_name\"]);\n supplierInfo_PAY.addParagraph(jsonInvoice[\"supplier_info\"][\"address1\"]);\n supplierInfo_PAY.addParagraph(jsonInvoice[\"supplier_info\"][\"postal_code\"] + \" \" + jsonInvoice[\"supplier_info\"][\"city\"]);\n}",
"display() {\n \t\tfor (let key in this.ticket) {\n \t\t\tconsole.log(key + ' : ' + this.ticket[key] + this.currency);\n \t\t}\n }",
"function printBill(cal,items){\n let message;\n let receiptItem = [];\n items.forEach((el,key) => {\n receiptItem.push({no: key, item: el.name, qty: el.quantity, cost: el.total_price});\n });\n const output = receipt.create([\n { type: 'text', value: [\n Bold()+' DesiChulhaa(Baner)'+Normal(),\n 'baner road, Balewadt Phata,Shrinath Complex',\n '27BAVPK2884A1ZF',\n '8087164638/8087164738'\n ], align: 'center' },\n { type: 'empty' },\n { type: 'properties', lines: [\n { name: 'Order Number', value: 'XXXXXXXXXXXX' },\n { name: 'Date', value: 'XX/XX/XXXX XX:XX' }\n ] },\n { type: 'table', lines: receiptItem },\n { type: 'customTable',lines:[\n {ltext:'',lvalue:'Total',rtext: cal.total_quantity,rvalue: cal.gtotal_price},\n {ltext:'',lvalue:'',rtext: 'CGST (2.5%)',rvalue: ''},\n {ltext:'',lvalue:'',rtext: 'SGST (2.5%)',rvalue: ''}\n ]},\n { type: 'customRuler' },\n { type: 'empty' },\n { type: 'properties', lines: [\n { name: 'Amount Received', value: 'AUD XX.XX' },\n { name: 'Amount Returned', value: 'AUD XX.XX' }\n ] },\n { type: 'empty' },\n { type: 'text', value: 'Final bits of text at the very base of a docket. This text wraps around as well!', align: 'center', padding: 5 },\n { type: 'text', value: ''+PAPER_PART_CUT}\n]);\n\nPrinter.printDirect({\n data: output,\n printer: 'Two Pilots Demo Printer',\n type: 'RAW',\n docname: 'Test',\n success: function (jobID) {\n message = 'sent to printer with ID: ' + jobID;\n },\n error: function (err) {\n message = err;\n }\n});\n return message;\n}",
"function displayInvoice() {\n console.log(\"========\");\n console.log(\"Invoice\");\n console.log(\"========\");\n}",
"function billingAddressInnerHTML() {\n document.getElementById(\"billing-address\").innerHTML = \"<h5>Billing address</h5><p>\" +\n \"Full Name: \" + billingAddress[\"name\"] +\n \"<br>Street: \" + billingAddress[\"street\"] +\n \"<br>City: \" + billingAddress[\"city\"] +\n \" State: \" + billingAddress[\"state\"] + \"<br>Zip: \" + billingAddress[\"zip\"] + \"</p>\";\n}",
"function printWalmart (orderId, shipDate, shipper, track, billingname, shiptoname , orderby, rcvdby, subtot, shipcost,\ntax, total, tc, asn, wmpo, items) {\n\tif (navigator.appName == 'Microsoft Internet Explorer') {\n\t\ttry {\n\t\t\tvar obNewAXComponent = new ActiveXObject(\"PMDPrint.PMDPrint\");\n\t\t\tif (obNewAXComponent.pluginVersion() < 2) {\n\t\t\t\talert(\"You have an outdated PMDPrint Plugin, please update.\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tobNewAXComponent.WalmartInitialize(\n\t\t\t\t\t orderId, // OrderId\n\t\t\t\t\t shipDate, // ShipDate\n\t\t\t\t\t shipper, // ShippedVia\n\t\t\t\t\t track, // Tracking\n\t\t\t\t\t billingname, // BillingName\n\t\t\t\t\t shiptoname, // Ship To Name\n\t\t\t\t\t orderby, // OrderedBy\n\t\t\t\t\t rcvdby, // RecievedBy\n\t\t\t\t\t subtot, // SubTotal\n\t\t\t\t\t shipcost, // Shipping\n\t\t\t\t\t tax, // Tax\n\t\t\t\t\t total, // Total\n\t\t\t\t\t tc, // TC\n\t\t\t\t\t asn, // ASN\n\t\t\t\t\t wmpo // Walmart PO# (Only used for Ship2Store)\n\t\t\t\t);\n\t\t\t\tfor (var i in items)\n\t\t\t\t{\n\t\t\t\t\tobNewAXComponent.WalmartAddItem(items[i][0], items[i][1], items[i][2], items[i][3], items[i][4]);\n\t\t\t\t}\n\t\t\t\tobNewAXComponent.WalmartPrint();\n\t\t\t\treturn true;\n\t\t\t} catch (e) {\n\t\t\t\talert(\"There was an error printing.\\nError Name:\" + e.name + \"\\nMessage: \"+e.message);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch(e) {\n\t\t\talert(\"You must install the PMDPrint plugin before you can print labels.\");\n\t\t\treturn false;\n\t\t}\n\t} else {\n\t\talert(\"This feature is currently Internet Explorer only.\\nPlease accept our apology for the inconvenience.\");\n\t\treturn false;\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Custom updater for the splitter. This one doesn't do much but the programmer could manipulate the hash here prior to splitting the output if they like. For example, they could add additional parameters or data to the hash values if desired. | function updater(vnid_hash) {
if (_.isUndefined(vnid_hash) || _.isEmpty(vnid_hash) || ! _.isObject(vnid_hash)) {
throw Error("Simple splitter component requires a vnid hash parameter!");
}
return vnid_hash;
} | [
"function _updateHash()\n{\n\tlet hash = [];\n\n\tif (viewModel.sortFilter)\n\t{\n\t\thash.push(HASH_LABELS.SORT + '=' + viewModel.sortFilter);\n\t}\n\tif (viewModel.statusFilter)\n\t{\n\t\thash.push(HASH_LABELS.STATUS + '=' + viewModel.statusFilter);\n\t}\n\n\tif (viewModel.companyFilter)\n\t{\n\t\thash.push(HASH_LABELS.COMPANY + '=' + viewModel.companyFilter);\n\t}\n\n\tif (viewModel.searchFilter)\n\t{\n\t\thash.push(HASH_LABELS.SEARCH + '=' + viewModel.searchFilter);\n\t}\n\n\t// Join the hash key/value pairs together \n\thash = hash.join('&');\n\n\t// Set the hash values into the URL\n\twindow.location.href = (window.location.href.split('#')[0]) + '#' + hash;\n}",
"function addPartsHashes(state, data) {\n for (var i = 0; i < data.length; i += hashChunkSize) {\n var chunk = data.slice(i, Math.min(i + hashChunkSize, data.length));\n var hash = crypto.createHash('sha256');\n hash.update(chunk);\n state.hashArr.push(hash.digest());\n }\n}",
"function parseHash(newHash, oldHash) {\n var eventData = {'oldHash' : oldHash, 'newHash' : newHash};\n $.Topic(PubSub.topicNames.UPDATE_HASH_CHANGES).publish(eventData);\n crossroads.parse(newHash);\n }",
"buildHashAndPreserve(newHash, oldHash, ...preservedKeys) {\n return this.buildHash(Object.assign(this.getSubsetOfHash(oldHash, preservedKeys), this.parseHash(newHash)));\n }",
"updateSelectionHash() {\n if (!this.trackedSelections) {\n return;\n }\n const ranges = this.trackedSelections.productSelections();\n const value = ranges.map((r) => r.toString()).join(';');\n AppContext.getInstance().hash.setProp(AppConstants.HASH_PROPS.SELECTION, value);\n }",
"function hashChunks(input) {\n let ondata = (evt, cb) => {\n crypto.subtle.digest(\"SHA-256\", evt.raw).then((digest) => {\n let mh = multihash.encode(Buffer.from(digest), \"sha2-256\")\n cb({multihash: mh, links: evt.links, data: evt.data})\n }).catch((err) => { cb(null, err) })\n }\n\n return asynchronous(input, ondata)\n}",
"setHash(term, hash) {\n // As a first step, term must be removed from the _hash_values, because\n // a new value will be added...\n this._hash_values = _.chain(this._hash_values)\n .map((tuple) => {\n // Remove the term if it is there\n tuple.terms = _.without(tuple.terms, term);\n if( tuple.terms.length === 0 ) {\n return undefined;\n } else {\n return tuple;\n }\n })\n .compact()\n .value();\n\n // Just store the hash values in a normal object\n this._term_to_hash[term] = hash;\n if( n3util.isBlank(term) ) this._bnode_to_hash[term] = hash;\n\n // Find whether that particular hash already exists, in which case the term is added,\n // otherwise just the full structure.\n let index = _.findIndex(this._hash_values, (tuple) => {\n if( HashValue.hashEqual(tuple.hash, hash) === true ) {\n if( !tuple.terms.includes(term) )\n tuple.terms.push(term);\n return true;\n } else {\n return false;\n }\n });\n if( index === -1 ) {\n // this is a new hash value for a new terms\n this._hash_values.push({\n hash: hash,\n terms: [term]\n })\n }\n }",
"calculateHash(){\n\t\t//it will take the properties of this function, run them through a hash function\n\t\t//and return the hash, used to identify the hash.\n\t\treturn SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data) + this.nonce).toString();\n\t}",
"_hashChanged() {\n\n\t\t// Re-parse the current location hash\n\t\tthis._parseHash();\n\n\t\t// If there's a callback\n\t\tif(this.change) {\n\t\t\tthis.change(this);\n\t\t}\n\t}",
"hash(){\n\t\tvar tmp = this.input;\n\t\tfor(var i = 0; i < 1000; i++){\n\t\t\ttmp = this.hashSHA( tmp );\n\t\t}\n\t\tthis.output = this.hashRMD( tmp );\n\t}",
"updateHash() {\n const parsedHash = queryString.parse(window.location.hash);\n this.setState({\n relativePath: parsedHash.relativePath || \"/\"\n }, () => {\n this.getData();\n });\n }",
"setHash(hash) {\n this.hash = hash;\n }",
"function setHasher(newHasher) {\n exports.hasher = newHasher;\n}",
"__split () {\n let regexp = new RegExp( '^' + this.__regexp.protocol + this.__regexp.host + this.__regexp.path + this.__regexp.parameters + this.__regexp.hash + '$', 'i' )\n let parts = this.__url.match( regexp )\n if ( parts ) {\n this.__parts.protocol = parts.groups[ 'protocol' ] || null\n this.__parts.path = parts.groups[ 'path' ] || null\n this.__parts.hash = ( parts.groups[ 'hash' ] ) ? parts.groups[ 'hash' ].substring( 1 ) : null\n\n this.__parts.host = parts.groups[ 'host' ] || null\n // Split host, username and password if needed\n if ( this.__parts.host ) {\n let hostParts = this.__parts.host.split( '@' )\n if ( hostParts[ 1 ] ) {\n // We have a username and password so we need to update those parts\n let authentication = hostParts[ 0 ].split( ':' )\n this.__parts.username = authentication[ 0 ]\n this.__parts.password = authentication[ 1 ]\n this.__parts.host = hostParts[ 1 ]\n } else {\n // We dont have a username and password so we need to update those parts\n this.__parts.username = null\n this.__parts.password = null\n this.__parts.host = hostParts[ 0 ]\n }\n }\n\n this.__parts.parameters = parts.groups[ 'parameters' ] || null\n // Split the parameters into an object\n if ( this.__parts.parameters ) {\n let parameters = {}\n let groups = this.__parts.parameters.split( '?' )[ 1 ].split( '&' )\n loop( groups, ( group ) => {\n let pair = group.split( '=' )\n if ( pair[ 0 ] !== '' ) {\n parameters[ pair[ 0 ] ] = ( pair[ 1 ] !== undefined ) ? pair[ 1 ] : true\n }\n } )\n this.__parts.parameters = parameters\n } else {\n this.__parts.parameters = {}\n }\n }\n }",
"function _updateHash( e ){\n var api = e.data.api,\n options = e.data.options,\n tableID = $( api.table().node() ).attr('id'),\n hash = {}, // End result hash (will be processed into URL hash)\n tableHash = [], // The conditions for THIS table\n urlHash = []; // Gets joined by &\n\n // Grab all the existing hashes - to carefuly not disturb any conditions NOT for this table\n $.each(_queryString(), function(table, cons){\n\n if ( ! table && ! cons ) return;\n\n // If this id isn't this table, store the hash and move on\n if ( table !== tableID ){\n hash[ table ] = cons || '';\n }\n // Were ignoring THIS table id because were going to re-create it\n });\n\n // Only set the order if the current order isn't the default order\n // (taking into account the possibility of a custom setting)\n if ( _isEnabled( 'order' )\n && api.order()[0]\n && JSON.stringify(api.order()) !== JSON.stringify($.fn.dataTable.defaults.aaSorting ) )\n tableHash.push( 'o' + api.order()[0][1].charAt( 0 ) + api.order()[0][0] );\n\n // Only set the search if something is searched for\n if ( _isEnabled( 'search' )\n && api.search() )\n tableHash.push( 's' + encodeURIComponent(api.search()) );\n\n // Only set the page if its not the default\n if ( _isEnabled( 'page' )\n && api.page.info()\n && api.page.info().page !== 0 )\n tableHash.push( 'p'+api.page.info().page );\n\n // Only set the length if its not the default\n if ( _isEnabled( 'length' )\n && api.page.len()\n && api.page.len() !== (options.pageLength || 10) )\n tableHash.push( 'l' + api.page.len() );\n\n // Only set the scroller position if the extension is included and the rounded scroller position isn't 0\n if ( _isEnabled( 'scroller' )\n && _dtSettings.oScroller !== undefined \n && Math.round(_dtSettings.oScroller.s.baseRowTop) !== 0)\n tableHash.push( 'c' + Math.round(_dtSettings.oScroller.s.baseRowTop) );\n tableHash.push( 'r' + api.colReorder.order().join('.') );\n\n // Only set column visibility if one or more columns are hidden, and only store the lesser value\n // in the hash (Visible vs Hidden)\n if ( _isEnabled( 'colvis' )\n && api.columns().visible().filter( function ( v ) { return ! v; } ).any() ) {\n var t = [], f = [];\n // Add the visible col indexes to t, and hidden to f\n api.columns().visible().each( function ( value, index ) {\n if ( value === true )\n t.push( index );\n else\n f.push( index );\n } );\n\n // If visible column count is greater, then use non-vis\n if( t.length >= f.length )\n tableHash.push( 'vf' + f.join('.') );\n // Otherwise, use visible count\n else\n tableHash.push( 'vt' + t.join('.') );\n }\n\n // Only set the column order if the column indexes are not in the default order\n if ( _isEnabled( 'colorder' )\n && JSON.stringify( api.colReorder.order() ) !== JSON.stringify( api.columns().indexes().toArray() ) )\n\n hash[ tableID ] = tableHash.join(':');\n\n $.each(hash, function(table,conditions){\n if ( ! conditions) return;\n\n urlHash.push(table +'='+conditions);\n });\n\n window.location.hash = urlHash.join('&');\n }",
"function updateHash() {\n window.location.hash = btoa( // base64 so url-safe\n RawDeflate.deflate( // gzip\n unescape(encodeURIComponent( // convert to utf8\n editor.getValue()\n ))\n )\n );\n}",
"setHash() {\n this.hash = this._hashBlock();\n return this;\n }",
"_secondaryInfoHash (infoHash) {\n var newInfoHash = infoHash + '_JS'\n return sha1(newInfoHash)\n }",
"resize() {\r\n this.length = 0; // set length 0\r\n this.size = this.size * 2; // double size\r\n const newBucket = new Array(this.size).fill(null);\r\n\r\n this.bucket.forEach((element) => {\r\n if (element) {\r\n element.forEach((item) => {\r\n const [key, value] = item;\r\n const hashIndex = hash(key, this.size);\r\n if (!newBucket[hashIndex]) {\r\n newBucket[hashIndex] = [[key, value]];\r\n } else {\r\n newBucket[hashIndex].push([key, value]);\r\n }\r\n this.length++;\r\n });\r\n }\r\n });\r\n this.bucket = newBucket;\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
for each API fucntions. when side menu clicks hide/show | function showAPIActionContent(obj_Id) {
$(".each_api_action").hide();
$("#"+obj_Id).show();
} | [
"function hideApiPanel() {\n $(\"#apiPanel.open\").removeClass(\"open\");\n $(\"#apiPanelDrawer.show\").removeClass(\"show\");\n}",
"function onSecondaryHeaderBtn() {\n toggleSideInfos();\n}",
"function showingActivitiesMenu() {\n showHidesubActivitiesButtons(-1500, 50, function () {\n showHideMainActivitiesButtons(20, 100, function () {\n });\n });\n }",
"function sideNavControl() {\n\n sideNavBlock.each((i, sideMenuTitleToggle) => {\n\n $(sideMenuTitleToggle).on('click', (e) => {\n\n const SIDE_MENU_LINK = $(sideMenuTitleToggle).siblings();\n\n // Toggle class of side menu title\n if (sideMenuTitleToggle) {\n toggleClass($(sideMenuTitleToggle), SIDE_MENU_BLOCK_OPEN);\n }\n\n // Switch view of side menu\n if (SIDE_MENU_LINK && SIDE_MENU_LINK.length === 1) {\n toggleClass($(SIDE_MENU_LINK), SIDE_MENU_BLOCK_CLOSE);\n }\n\n });\n\n });\n\n }",
"function toggleTopSideBar(){\n \n toggleTopbar();\n toggleSidebar();\n }",
"function sideNavControl() {\n\n sideNavBlock.each((i, sideMenuTitleToggle) => {\n\n $(sideMenuTitleToggle).on('click', (e) => {\n\n const SIDE_MENU_LINK = $(sideMenuTitleToggle).siblings();\n\n // Toggle class of side menu title\n if (sideMenuTitleToggle) {\n toggleClass($(sideMenuTitleToggle), SIDE_MENU_BLOCK_OPEN);\n }\n\n // Switch view of side menu\n if (SIDE_MENU_LINK && SIDE_MENU_LINK.length === 1) {\n toggleClass($(SIDE_MENU_LINK), SIDE_MENU_BLOCK_CLOSE);\n }\n\n });\n\n });\n\n }",
"function sidebarToggleVisibility() {\n this.hideSidebar();\n this.hideSidebarByCookieValue();\n}",
"function openSideBar(){\n loadSidebar('ConfigurationSelection','Select');\n}",
"function sideNavControl() {\n\n sideNavBlock.each((i, sideMenuTitleToggle) => {\n\n $(sideMenuTitleToggle).on('click', (e) => {\n\n const SIDE_MENU_LINK = $(sideMenuTitleToggle).siblings();\n\n // Toggle class of side menu title\n if (sideMenuTitleToggle) {\n toggleClass($(sideMenuTitleToggle), SIDE_MENU_BLOCK_OPEN);\n }\n\n // Switch view of side menu\n if (SIDE_MENU_LINK && SIDE_MENU_LINK.length === 1) {\n toggleClass($(SIDE_MENU_LINK), SIDE_MENU_BLOCK_CLOSE);\n }\n\n });\n\n });\n\n }",
"function setupDevMenu() {\n $('#top-carousel-toggle').click(function() {\n if($('#top-carousel-toggle').is(':checked'))\n $('.top-features').show();\n else \n $('.top-features').hide();\n });\n $('#pages-toggle').click(function() {\n if($('#pages-toggle').is(':checked')) {\n $('.page-controls').show();\n $('#results-meta').show();\n $('#search').unbind('click').click(function() {renderPages()});\n } else { \n $('.page-controls').hide();\n $('#results-meta').hide();\n $('#search').unbind('click').click(function() {renderTable()});\n }\n });\n $('#sort-toggle').click(function() {\n if($(this).is(':checked'))\n $('#sort-results').show();\n else \n $('#sort-results').hide();\n });\n $('#hover-comments').click(function() {\n $('.comment-tooltip').toggleClass('tooltip');\n $('.comment').toggle();\n });\n $('#self-led-toggle').click(function() {\n $('#self-led-button').toggle();\n $('#self-led-checkbox').toggle();\n });\n $('#features-toggle').click(function() {\n // switch carousel to 3 top features\n _swapFeaturesMarkup();\n renderPages();\n });\n}",
"function tycheesCommon_loadUI_sidebar() {\n\tvar placeObj = tycheesCommon_getCurrentPlaceObject();\n\t\n\tvar userPlaceRoleObj;\n\t$.each(placeObj.roleList, function(i, roleObj) {\n\t\tif ($.trim(roleObj.userId) == tycheesCommon_getCurrentUserId()) {\n\t\t\tuserPlaceRoleObj = roleObj;\n\t\t}\n\t});\n\t\n\tvar placeAccessObj;\n\t$.each(placeObj.accessList, function(i, accessObj) {\n\t\tif ($.trim(accessObj.roleName) == $.trim(userPlaceRoleObj.role)) {\n\t\t\tplaceAccessObj = accessObj;\n\t\t}\n\t});\n\n\t// Reset state\n\t$(\"#sidebar-dashboard\").hide();\n\t$(\"#sidebar-calendar\").hide();\n\t$(\"#sidebar-billing\").hide();\n\t$(\"#sidebar-inventory\").hide();\n\t$(\"#sidebar-relation\").hide();\n\t$(\"#sidebar-reports\").hide();\n\t$(\"#sidebar-humanResources\").hide();\n\t$(\"#sidebar-settings\").hide();\n\n\tvar functionDashboardAccessible = false;\n\tvar functionCalendarAccessible = false;\n\tvar functionBillingAccessible = false;\n\tvar functionInventoryAccessible = false;\n\tvar functionRelationAccessible = false;\n\tvar functionReportsAccessible = false;\n\tvar functionHumanResourcesAccessible = false;\n\tvar functionSettingsAccessible = false;\n\n\t$.each(placeAccessObj.propertiesList, function(i, accessPropObj) {\n\t\tif (accessPropObj.propKey == ModuleConstants.MODULE_DASHBOARD_PROP_KEY)\n\t\t\tif (accessPropObj.propValue == 'Readable' || accessPropObj.propValue == 'Writable')\n\t\t\t\tfunctionDashboardAccessible = tycheesCommon_isFunctionVisible(accessPropObj);\n\t\tif (accessPropObj.propKey == ModuleConstants.MODULE_CALENDAR_PROP_KEY)\n\t\t\tif (accessPropObj.propValue == 'Readable' || accessPropObj.propValue == 'Writable')\n\t\t\t\tfunctionCalendarAccessible = tycheesCommon_isFunctionVisible(accessPropObj);\n\t\tif (accessPropObj.propKey == ModuleConstants.MODULE_BILLING_PROP_KEY)\n\t\t\tif (accessPropObj.propValue == 'Readable' || accessPropObj.propValue == 'Writable')\n\t\t\t\tfunctionBillingAccessible = tycheesCommon_isFunctionVisible(accessPropObj);\n\t\tif (accessPropObj.propKey == ModuleConstants.MODULE_INVENTORY_PROP_KEY)\n\t\t\tif (accessPropObj.propValue == 'Readable' || accessPropObj.propValue == 'Writable')\n\t\t\t\tfunctionInventoryAccessible = tycheesCommon_isFunctionVisible(accessPropObj);\n\t\tif (accessPropObj.propKey == ModuleConstants.MODULE_RELATION_PROP_KEY)\n\t\t\tif (accessPropObj.propValue == 'Readable' || accessPropObj.propValue == 'Writable')\n\t\t\t\tfunctionRelationAccessible = tycheesCommon_isFunctionVisible(accessPropObj);\n\t\tif (accessPropObj.propKey == ModuleConstants.MODULE_REPORTS_PROP_KEY)\n\t\t\tif (accessPropObj.propValue == 'Readable' || accessPropObj.propValue == 'Writable')\n\t\t\t\tfunctionReportsAccessible = tycheesCommon_isFunctionVisible(accessPropObj);\n\t\tif (accessPropObj.propKey == ModuleConstants.MODULE_SETTINGS_PROP_KEY)\n\t\t\tif (accessPropObj.propValue == 'Readable' || accessPropObj.propValue == 'Writable')\n\t\t\t\tfunctionSettingsAccessible = tycheesCommon_isFunctionVisible(accessPropObj);\n\t});\n\t\n\t// Get current URL\n\tvar currentUrl = location.href;\n\n\tif (currentUrl.indexOf(\"/dashboard/\") != -1)\n\t\t$(\"#sidebar-dashboard\").addClass(\"active\");\n\tif (currentUrl.indexOf(\"/calendar/\") != -1)\n\t\t$(\"#sidebar-calendar\").addClass(\"active\");\n\tif (currentUrl.indexOf(\"/billing/\") != -1)\n\t\t$(\"#sidebar-billing\").addClass(\"active\");\n\tif (currentUrl.indexOf(\"/inventory/\") != -1)\n\t\t$(\"#sidebar-inventory\").addClass(\"active\");\n\tif (currentUrl.indexOf(\"/relation/\") != -1)\n\t\t$(\"#sidebar-relation\").addClass(\"active\");\n\tif (currentUrl.indexOf(\"/reports/\") != -1)\n\t\t$(\"#sidebar-reports\").addClass(\"active\");\n\tif (currentUrl.indexOf(\"/humanresources/\") != -1)\n\t\t$(\"#sidebar-humanResources\").addClass(\"active\");\n\tif (currentUrl.indexOf(\"/settings/\") != -1)\n\t\t$(\"#sidebar-settings\").addClass(\"active\");\n\n\t// Show whichever enable\n\tif (functionDashboardAccessible)\n\t\t$(\"#sidebar-dashboard\").show();\n\tif (functionCalendarAccessible)\n\t\t$(\"#sidebar-calendar\").show();\n\tif (functionBillingAccessible)\n\t\t$(\"#sidebar-billing\").show();\n\tif (functionInventoryAccessible)\n\t\t$(\"#sidebar-inventory\").show();\n\tif (functionRelationAccessible)\n\t\t$(\"#sidebar-relation\").show();\n\tif (functionReportsAccessible)\n\t\t$(\"#sidebar-reports\").show();\n\tif (functionHumanResourcesAccessible)\n\t\t$(\"#sidebar-humanResources\").show();\n\t//if (functionSettingsAccessible)\n\t\t$(\"#sidebar-settings\").show();\n\n\t$(\"#sidebar-profile\").show();\n}",
"function activateSidebarDisplayOptions() {\n\t $('.sidebar-display-buttons').click(function() {\n\t var selected = $(this);\n\t console.log(\"icon selected:\", selected.text().toUpperCase().trim());\n\t // disable all the buttons\n\t $('.sidebar-display-buttons').addClass(\"disabled\");\n\t $('.map-selection-row, .timeseries-row, .scatterplot-row').removeClass('active');\n\t // then toggle the selected disabled class\n\t selected.toggleClass(\"disabled\");\n\t // use the name of the icon to trigger sidebar\n\t if (selected.text().toUpperCase().trim() == \"MAP CONTROLS\") {\n\t $('.map-selection-row').toggleClass('active');\n\t } else if (selected.text().toUpperCase().trim() == \"TIME SERIES\") {\n\t $('.timeseries-row').toggleClass('active');\n\t } else if (selected.text().toUpperCase().trim() == \"CLIMATE NORMALS\"){\n\t $('.scatterplot-row').toggleClass('active');\n\t }\n\t });\n\t}",
"showNavigation(arrayOfArgu) {\n const toggleBtn = arrayOfArgu[0];\n const self = arrayOfArgu[1];\n if (!self) {\n self = this;\n }\n const verticalNav = document.getElementById('vertical-nav-bar');\n const classValue = verticalNav.getAttribute('class');\n if (classValue.indexOf('hide-item') >= 0) {\n self.changeClassValue (verticalNav, 'hide-item', 'show-item');\n } else if (classValue.indexOf('show-item') >= 0) {\n self.changeClassValue (verticalNav, 'show-item', 'hide-item');\n }\n }",
"function menuWebFeatures() {\n //hide rows\n var features = ['Access App',\n 'Announcement Tiles',\n 'Community Site Feature',\n 'Duet Enterprise - SAP Workflow',\n 'Duet Enterprise Reporting',\n 'Duet Enterprise Site Branding',\n 'External System Events',\n 'Getting Started with Project Web App',\n 'Hold',\n 'Minimal Download Strategy',\n 'Offline Synchronization for External Lists',\n 'Project Functionality',\n 'Project Proposal Workflow',\n 'Project Web App Connectivity',\n 'SAP Workflow Web Parts',\n 'Search Config Data Content Types',\n 'Search Config Data Site Columns',\n 'Search Config List Instance Feature',\n 'Search Config Template Feature',\n 'Site Feed',\n 'SharePoint Server Publishing'\n ];\n features.forEach(function(feature, i) {\n hideSPFeature(feature);\n });\n\n //hide row background color\n hideAltRowColor();\n }",
"function toggleSidebarOpen() {\n\n\n\n }",
"function toggleSideMenu() {\n setShowSide(!showSideMenu)\n }",
"function toggle(){\n toggleClass( nav, 'sidebar-show' );\n toggleClass( layer, 'sidebar-layer-show' );\n }",
"function sidemenuToggle() {\n if(isSideMenuOpen) {\n sidemenuClose();\n } else {\n sidemenuOpen();\n }\n}",
"function onPrimaryHeaderBtn() {\n if(status == 'home') {\n toggleSideMenu();\n } else {\n goBack();\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
+ add_tos :: Number > Number > String | function add_tos(n1,n2){
return (n1 + n2) + "";
} | [
"function add(firstNum, secondNum){\n return firstNum + secondNum\n }",
"function add(number) {\n return number + amount;\n }",
"function addNumbers() {\n\tlet addend1 = document.getElementById(\"addend1\").value;\n\tlet addend2 = document.getElementById(\"addend2\").value;\n\tlet addend1_parsed = parseInt(addend1);\n\tlet addend2_parsed = parseInt(addend2);\n\tconsole.log(addend1_parsed);\n\tconsole.log(addend2_parsed);\n\tlet addition = add(addend1_parsed, addend2_parsed);\n\tlet additionSt = addition.toString();\n\tconsole.log(addition);\n\tconsole.log(additionSt);\n\tsumHtml.value = additionSt;\n}",
"add(n){\n number += n;\n return number;\n }",
"function add(firstNum, secondNum) {\n return firstNum + secondNum\n}",
"function add (a, b) {\n console.log(Number(a) + Number(b));\n}",
"static add(a, b) {\n if (typeof b == \"number\") {\n for (let i = 0, len = a.length; i < len; i++)\n a[i] += b;\n }\n else {\n for (let i = 0, len = a.length; i < len; i++)\n a[i] += b[i] || 0;\n }\n return a;\n }",
"function addieren(a,b){\n return a + b;\n}",
"function AddNumber(num){\n \n numeroActual = numeroActual.toString() + num.toString(); \n actualizar();\n}",
"function add (firstNum, secondNum) {\n\n return firstNum + secondNum;\n\n}",
"function addieren(a,b) {\r\n return a + b;\r\n}",
"function addOnlyNums(...arg){\n var longitud=arg.length;\n var sumaTotal=0;\n for (i=0;i<longitud;i++){\n if (typeof(arg[i])=='number'){sumaTotal+=arg[i]};\n }\n return sumaTotal;\n}",
"function addTwoNumbers(num1,num2) {\n if (dataTypePrinter(num1) === 'number' && dataTypePrinter(num2) === 'number') {\n return num1 + num2\n} else { return \"please enter numbers\"\n}\n}",
"function addieren(a,b) {\n return a + b; \n}",
"function append(t) {\n carry = 0;\n if (t >= 10) {\n carry = 1;\n t -= 10;\n }\n sum += t; \n }",
"function callAddWithNonNumbers() {\n return add('foo', 'bar');\n }",
"function add(param1, param2) {\n return param1 + param2;\n}",
"function addNumbers(number1, number2) {\r\n return number1 + number2;\r\n}",
"add(value) {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
assigns a custom attribute to elements in the DOM hierarchy to indicate that they do/don't contain lvas used for hiding empty categories hides all categories containing hidden lvas either by datahiderow_date or datahiderow_semester or datahiderow_university showeverything should not be used with true unless it can safely be said that all occurrences of datahiderow_ are false | function propagateVisibility(showeverything) {
/*at first hide everything*/
var fachs = document.querySelectorAll('*[data-name~="fach"]');
for (var i=0; i < fachs.length; i++) {
fachs[i].setAttribute("data-nocontent","true");
}
var wholefachs = document.querySelectorAll('*[data-name~="wholefach"]');
for (var i=0; i < wholefachs.length; i++) {
wholefachs[i].setAttribute("data-nolvas","true");
}
var wholemodul2s = document.querySelectorAll('*[data-name~="wholemodul2"]');
for (var i=0; i < wholemodul2s.length; i++) {
wholemodul2s[i].setAttribute("data-nolvas","true");
}
var wholemodul1s = document.querySelectorAll('*[data-name~="wholemodul1"]');
for (var i=0; i < wholemodul1s.length; i++) {
wholemodul1s[i].setAttribute("data-nolvas","true");
}
var tables = document.querySelectorAll('*[data-name~="lvatable"]');
for (var i=0; i < tables.length; i++) {
if(showeverything) {
//TODO parentNode method not very change-proof (XPath?)
tables[i].parentNode.setAttribute("data-nocontent","false"); /*fach*/
tables[i].parentNode.parentNode.setAttribute("data-nolvas","false"); /*wholefach*/
tables[i].parentNode.parentNode.parentNode.parentNode.setAttribute("data-nolvas","false"); /*wholemodul2*/
tables[i].parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.setAttribute("data-nolvas","false"); /*wholemodul1*/
} else {
var subrows = tables[i].firstChild.childNodes; //firstChild is tbody
for (var j=0; j < subrows.length; j++) {
if( subrows[j].hasChildNodes() &&
subrows[j].getAttribute("data-hiderow_date") != "true" &&
subrows[j].getAttribute("data-hiderow_semester") != "true" &&
subrows[j].getAttribute("data-hiderow_university") != "true" &&
(document.getElementById("content").getAttribute("data-hideuni") != "true" || tables[i].parentNode.parentNode.getAttribute("data-multipleuniversities_static") != "true") ) {
//TODO parentNode method not very change-proof (XPath?)
tables[i].parentNode.setAttribute("data-nocontent","false"); /*fach*/
tables[i].parentNode.parentNode.setAttribute("data-nolvas","false"); /*wholefach*/
tables[i].parentNode.parentNode.parentNode.parentNode.setAttribute("data-nolvas","false"); /*wholemodul2*/
tables[i].parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.setAttribute("data-nolvas","false"); /*wholemodul1*/
break;
}
}
}
}
redrawFix();
} | [
"function MLINKSTUD_set_datatable_hidden() {\n\n console.log(\"===== MLINKSTUD_set_datatable_hidden =====\");\n\n add_or_remove_class(el_MLINKSTUD_loading, cls_hide, mod_MLINKSTUD_dict.mode !== \"loading\");\n add_or_remove_class(el_MLINKSTUD_no_data, cls_hide, mod_MLINKSTUD_dict.mode !== \"no_data\");\n add_or_remove_class(el_MLINKSTUD_has_data, cls_hide, mod_MLINKSTUD_dict.mode !== \"has_data\");\n\n const has_unlinked_data = mod_MLINKSTUD_dict.mode === \"has_data\" && mod_MLINKSTUD_dict.has_unlinked_rows;\n console.log(\" has_unlinked_data\", has_unlinked_data);\n add_or_remove_class(el_MLINKSTUD_has_unlinked_data, cls_hide, !has_unlinked_data);\n add_or_remove_class(el_MLINKSTUD_all_linked_data, cls_hide, has_unlinked_data);\n }",
"_hideLabelsFromAssistiveTech () {\n this.element\n .querySelectorAll('span')\n .forEach(span => span.setAttribute('aria-hidden', true))\n }",
"_unmarkInvisibleEls() {\n let all = Array.from(this.el.getElementsByTagName(\"[style-pirate-hidden=1]\"));\n all.forEach(el => el.removeAttribute('style-pirate-hidden'));\n }",
"checkVisibility(list, dataAttr) {\n /* Returns TRUE if list is empty or attribute is in list */\n if (list.length > 0) {\n for(var v = 0; v < list.length; v++){\n if(dataAttr){\n try{\n var arr = dataAttr.split(\" \")\n .filter(function(el){return el.length > 0});\n }\n catch{\n var arr = dataAttr.filter(function(el){return el.length > 0});\n }\n\n if(arr.indexOf(list[v]) >=0 ) {\n return true\n }\n }\n else\n return false\n }\n return false\n } else {\n return true\n }\n }",
"function showOldestDate(showeverything, date){\n\tvar rows = document.querySelectorAll('*[data-name~=\"lvarow\"]');\n\tfor (var i=0; i < rows.length; i++) {\n\t\tif(showeverything || rows[i].getAttribute(\"data-query_date\") >= date) {\n\t\t\trows[i].setAttribute(\"data-hiderow_date\",\"false\");\n\t\t} else {\n\t\t\trows[i].setAttribute(\"data-hiderow_date\",\"true\");\n\t\t}\n\t}\n\t\n\tpropagateVisibility(false);\n}",
"function article_lu_nonlu() {\n if ($(this).children().hasClass('icon-eye-open')) {\n $.post('/pokemon/rss/set_lu', {'article_id' : article_id, 'lu': 'false'});\n $(this).children().removeClass('icon-eye-open').addClass('icon-eye-close');\n } else {\n $.post('/pokemon/rss/set_lu', {'article_id' : article_id, 'lu' : 'true'});\n $(this).children().removeClass('icon-eye-close').addClass('icon-eye-open');\n }\n}",
"function dp_exclude(attrName)\r\n{\r\n\tif (!attrName) return true;\r\n\tif (dp_exclude[attrName]) return true;\r\n\treturn false;\r\n}",
"ignore(value) {\n var attr = this.attr;\n if (value === true) {\n attr.ignore = true;\n }\n }",
"hideUniformCategory(list, category) {\n list.set('hideCategory', category && !category.get(\"has_children\"));\n }",
"_markInvisibleEls() {\n let all = Array.from(this.el.getElementsByTagName(\"*\"));\n all.filter(e => !e.offsetParent).forEach(el => {\n el.setAttribute('style-pirate-hidden',1)\n });\n }",
"function setDataAttributeLiquidazione(tipoEvento) {\n return tipoEvento.codice === 'L' ? 'data-liquidazione=\"true\"' : '';\n }",
"function hideCacheDaysIfEmbedding()\n\t{\n\t\tif ($j(\".wpp-rendering-type-select\").val() == 'embedded') \n\t\t{ \n\t\t\t$j(\".wpp-cache-days-select\").closest('tr').hide();\n\t\t\t$j(\".wpp-fetch-method-select\").closest('tr').hide();\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$j(\".wpp-cache-days-select\").closest('tr').show();\n\t\t\t$j(\".wpp-fetch-method-select\").closest('tr').show();\n\t\t}\n\t}",
"calculateIsHidden() {\n const { columns } = this.state;\n let isHidden = [];\n for (var i = 0; i < columns.length; i++) {\n isHidden[columns[i].property] = false;\n }\n for (var j = 0; j < columns.length; j++) {\n var row = document.getElementById(columns[j].maxWidthRow);\n var cell = row && row.getElementsByClassName(columns[j].props.className)[0] && row.getElementsByClassName(columns[j].props.className)[0].getElementsByClassName('value_')[0];\n // Condition for truncation.\n // >2 is used as edge was giving some wrong value of clientwidth and scrollwidth\n if (cell && cell.scrollWidth - cell.clientWidth > 2) {\n // For LONGSTRING no expand icon is shown\n if (columns[j].dataType !== 'LONGSTRING' && columns[j].type !== 'PARAGRAPH') {\n isHidden[columns[j].property] = true;\n }\n }\n }\n this.props.isHidden(isHidden);\n }",
"function hideuni(hide) {\n\tif(hide){\n\t\tdocument.getElementById(\"content\").setAttribute(\"data-hideuni\",\"true\");\n\t}else{\n\t\tdocument.getElementById(\"content\").setAttribute(\"data-hideuni\",\"false\");\n\t}\n\n\tpropagateVisibility(false);\n}",
"function setupDataAttributes()\n {\n self.registerDataAttribute( 'list', function( attr, node, data, key, value )\n {\n return fillList( node, data, key, value );\n });\n self.registerDataAttribute( 'dump', function( attr, node, data, key, value )\n {\n return fillDump( node, data, key, value );\n });\n self.registerDataAttribute( 'remove-if', function( attr, node, data, key )\n {\n var value = markuper.evaluator.evalBooleanExpression( key, data );\n\n node.removeAttribute( 'data-remove-if' );\n if( value )\n {\n node.remove();\n return false; // don't process the contents of this node\n }\n });\n self.registerDataAttribute( 'keep-if', function( attr, node, data, key )\n {\n var value = markuper.evaluator.evalBooleanExpression( key, data );\n\n node.removeAttribute( 'data-keep-if' );\n if( !value )\n {\n node.remove();\n return false; // don't process the contents of this node\n }\n });\n self.registerDataAttribute( 'import', function( attr, node, data, filename )\n {\n node.removeAttribute( 'data-import' );\n extendElement( node ).importTemplate( filename );\n });\n self.registerDataAttribute( 'set-attribute', function( attr, node, data, key )\n {\n var args = key.split( ' ' );\n var attributeName = args[0];\n var expr = args.slice(1).join(' ');\n \n node.removeAttribute( 'data-set-attribute' );\n setAttribute( node, attributeName, expr, data );\n });\n \n self.registerDataAttribute( 'set-*-attribute', function( attr, node, data, key )\n {\n node.removeAttribute( 'data-'+attr );\n attr = attr.replace( /^set-/, '' ).replace( /-attribute$/, '' );\n setAttribute( node, attr, key, data );\n });\n }",
"function setBoolAttr(d) {\n // change the element's text\n let value = d3.select(this).node().textContent;\n $(this).parent().parent().find(\">button>span.boolVal\").text(value);\n let object = d3.select($(this).parents(\"li.attribute\").first().parent().get(0)).data()[0];\n let attrName = \"cim:\" + d.attributes[0].value.substring(1);\n // update the model\n self.model.setAttribute(object, attrName, value);\n }",
"function defineBooleanAttribute(key,handler){var attr=$attrs.$normalize('md-'+key);if(handler)defineProperty(key,handler);if($attrs.hasOwnProperty(attr))updateValue($attrs[attr]);$attrs.$observe(attr,updateValue);function updateValue(newValue){ctrl[key]=newValue!=='false';}}",
"function pruneMarkedAttrs(elem) {\n\t\tvar $elem = $(elem);\n\t\tvar data = $elem.attr('data-aloha-ephemera-attr');\n\t\tvar i;\n\t\tvar attrs;\n\t\t// Because IE7 crashes if we remove this attribute. If the\n\t\t// dom-to-xhtml plugin is turned on, it will handle the removal\n\t\t// of this attribute during serialization.\n\t\tif (!Browser.ie7) {\n\t\t\t$elem.removeAttr('data-aloha-ephemera-attr');\n\t\t}\n\t\tif (typeof data === 'string') {\n\t\t\tattrs = Strings.words(data);\n\t\t\tfor (i = 0; i < attrs.length; i++) {\n\t\t\t\t$elem.removeAttr(attrs[i]);\n\t\t\t}\n\t\t}\n\t}",
"function hasUnmodifiableSections() {\n return $('[data-modifiable=false]').length > 0;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Publishes a list of all available quizzes. Shows details of first quiz by default | function publish_all_quizzes() {
$(".quiz_list").empty();
$(".quiz_list").append("<div class = 'quiz_title'>Quizzes</div>")
/*Publish all questions*/
var num_quizzes = data.quizzes.length;
for(var i = 0; i < num_quizzes; i++)
$(".quiz_list").append("<div class = 'quiz_item' quiz_id = '"+i+"'> "+(i+1)+"</div>");
/*If many quizzes present, toggle scrolling*/
if($(".quiz_list").height() > $(".quiz_list_wrapper").height())
$(".quiz_list").css({"float": "none", "white-space": "nowrap", "-ms-overflow-style" : "-ms-autohiding-scrollbar;", "overflow-x": "auto"});
/*Displays data for the first quiz by default*/
$(".quiz_item").first().addClass("active");
publish_question_list(data.quizzes[0].questions);
/*On clicking a quiz, display question list of that quiz*/
$(".quiz_item").click(function() {
/*Update CSS styling*/
$(".quiz_item").removeClass("active");
$(this).addClass("active");
var quiz_id = $(this).attr("quiz_id");
publish_question_list(data.quizzes[quiz_id].questions);
});
// Button to add a new quiz
$(".quiz_list").append("<div id = 'add_quiz'>+</div>")
$("#add_quiz").click(function() {
// Add an empty quiz, and reload view
var new_empty_quiz = jQuery.extend(true, {}, empty_quiz); //Deep copy object
data.quizzes.push(new_empty_quiz);
publish_all_quizzes();
});
} | [
"function publish_all_quizzes() {\n\t$(\".quiz_list\").append(\"<div class = 'quiz_title'>Quizzes</div>\")\n\n\t/*Publish all questions*/\n\tvar num_quizzes = data.quizzes.length;\n\tfor(var i = 0, quiz_number = 0; i < num_quizzes; i++)\n\t\t//Display only published quizzes\n\t\tif(data.quizzes[i].isPublished) {\n\t\t\tquiz_number++;\n\t\t\t$(\".quiz_list\").append(\"<div class = 'quiz_item' quiz_id = '\"+i+\"'> \"+quiz_number+\"</div>\");\n\t\t}\n\n\t/*If many quizzes present, toggle scrolling*/\n\tif($(\".quiz_list\").height() > $(\".quiz_list_wrapper\").height())\n\t\t$(\".quiz_list\").css({\"float\": \"none\", \"white-space\": \"nowrap\", \"-ms-overflow-style\" : \"-ms-autohiding-scrollbar;\", \"overflow-x\": \"auto\"});\n\n\t/*Displays data for the first quiz by default*/\n\t$(\".quiz_item\").first().addClass(\"active\");\n\tpublish_question_list(data.quizzes[0].questions);\n\n\t/*On clicking a quiz, display question list of that quiz*/\n\t$(\".quiz_item\").click(function() {\n\t\t/*Update CSS styling*/\n\t\t$(\".quiz_item\").removeClass(\"active\");\n\t\t$(this).addClass(\"active\");\n\n\t\tvar quiz_id = $(this).attr(\"quiz_id\");\n\t\tpublish_question_list(data.quizzes[quiz_id].questions);\n\t});\n}",
"static async GetAllQuizzes() {\n const response = await fetch(`${this.URL}/quiz/getAllQuizzes`);\n const data = await response.json();\n return data;\n }",
"function displayQuizzes() {\n for(quizz of GLOBAL.serverQuizzes) {\n const quizzBanner = generateQuizzCardHtml(quizz, isThisAUsersQuizz(quizz.id));\n \n isThisAUsersQuizz(quizz.id)\n ? document.querySelector(\".user-quizzes-section .banners-container\").insertAdjacentHTML(\"beforeend\", quizzBanner)\n : document.querySelector(\".all-quizzes-section .banners-container\").insertAdjacentHTML(\"beforeend\", quizzBanner);\n }\n manageEmptyUsersQuizzInterface();\n}",
"async function getQuizzes(req, res, next) {\n res.send(Object.values(quizzes).map(({ title, id }) => ({ title, id })));\n}",
"getAdminQuizzes() {\n this.setMethod('GET');\n this.setAuth();\n delete this.options.body;\n return this.getApiResult(Config.QUIZ_API);\n }",
"getQuizList(){\n\t\tgetData(\"quizsubjectname/\",\n\t\t\t(() => {}),\n\t\t\t((res) => {\n\t\t\t\tconst quizes = res;\n\t\t\t\tthis.makeQuizObject(quizes);\n\t\t\t}),\n\t\t\t(() => {})\n\t\t);\n\t}",
"function displayAvailableQuizzes() {\n \"use strict\";\n\n var templateName = \"title\"; // name that dust uses to store the compiled template\n\n // Get the quiz div\n var source = $(QUIZ_CONFIG.get(\"AVAILABLE_QUIZZES_TEMPLATE\")).html();\n\n // update the template\n runDust(source, templateName, renderAvailableQuizzes, availableQuizzes);\n}",
"static getCollection() {\n return \"quizzes\";\n }",
"function publish_question_list(quiz_data) {\n\t$(\".question_list\").empty();\n\n\t$.each(quiz_data, function(i, question) {\n\t\t$(\".question_list\").append(\"<div class = 'question_list_item' question_id = '\"+i+\"'>\"+question.concept+\"</div>\");\n\t});\n\n\t/*Show first question by default*/\n\t$(\".question_list_item\").first().addClass(\"question_active\");\n\tpublish_question(quiz_data[0]);\n\n\t/*On clicking a question, display it*/\n\t$(\".question_list_item\").click(function() {\n\t\t/*Update CSS styling*/\n\t\t$(\".question_list_item\").removeClass(\"question_active\");\n\t\t$(this).addClass(\"question_active\")\n\t\t\n\t\tvar question_id = $(this).attr(\"question_id\");\n\t\tpublish_question(quiz_data[question_id]);\n\t});\n}",
"async getQuizList(callback) {\n return JSON.stringify(this.quizzes);\n }",
"function publish_question_list(quiz_data) {\n $(\".question_list\").empty();\n\n $.each(quiz_data, function(i, question) {\n $(\".question_list\").append(\"<div class = 'question_list_item' question_id = '\"+i+\"'>\"+question.concept+\"</div>\");\n });\n\n /*Show first question by default*/\n $(\".question_list_item\").first().addClass(\"question_active\");\n publish_question(quiz_data[0]);\n\n // Add option to create new question\n $(\".question_list\").append(\"<div id = 'add_question'>+</div>\")\n $(\"#add_question\").click(function() {\n var quiz_id = $(\".quiz_item.active\").attr(\"quiz_id\");\n\n // Add an empty question, and reload view\n var new_empty_question = jQuery.extend(true, {}, empty_question); //Create deep copy\n data.quizzes[quiz_id].questions.push(new_empty_question);\n publish_question_list(data.quizzes[quiz_id].questions);\n });\n\n // Add option to publish this quiz\n $(\"#publish_quiz\").remove();\n var quiz_id = $(\".quiz_item.active\").attr(\"quiz_id\");\n var label = data.quizzes[quiz_id].isPublished ? \"Hide Quiz\" : \"Publish Quiz\";\n $(\".buttons_container\").append(\"<div class = 'button' id = 'publish_quiz'>\"+label+\"</div>\")\n\n // If a quiz is being published, then toggle the published value\n $(\"#publish_quiz\").click(function() {\n $(\"#publish_quiz\").remove();\n var quiz_id = $(\".quiz_item.active\").attr(\"quiz_id\");\n\n // Toggle whether the quiz is published and reload\n data.quizzes[quiz_id].isPublished = !data.quizzes[quiz_id].isPublished;\n publish_question_list(data.quizzes[quiz_id].questions);\n });\n\n /*On clicking a question, display it*/\n $(\".question_list_item\").click(function() {\n /*Update CSS styling*/\n $(\".question_list_item\").removeClass(\"question_active\");\n $(this).addClass(\"question_active\")\n \n var question_id = $(this).attr(\"question_id\");\n publish_question(quiz_data[question_id]);\n });\n}",
"function getResults(quizzes, cb) {\n\t\t\t\tvar complete = Object.keys(quizzes).length;\n\t\t\t\t\n\t\t\t\tfor (var quiz in quizzes) {\n\t\t\t\t\tvar results = [];\n\n\t\t\t\t\tdb.results.find({quizName: quizzes[quiz].quizName, creator_username: localStorage.getItem('username')}, function(err, foundResult) {\n\t\t\t\t\t\tif (err||!foundResult) {console.log(err)}\n\t\t\t\t\t\t\telse { \n\t\t\t\t\t\t\t\tif (foundResult.length == 0) {\n\t\t\t\t\t\t\t\t\tres.render('Administrator/dashboard_routes/reports', {\n\t\t\t\t\t\t\t\t\tisAuthenticated: req.isAuthenticated(),\n\t\t\t\t\t\t\t\t\tdata: 'no results'});\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tresults.push(foundResult);\n\t\t\t\t\t\t\t\t\tcomplete--;\n\t\t\t\t\t\t\t\t\tif (complete == 0) {\n\t\t\t\t\t\t\t\t\t\tcb(quizzes, results);\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t};\n\t\t\t\t\t});\n\t\t\t\t};\n\t\t\t}",
"function getQuizzes(req, res, next) {\n const ret = Object.values(quizzes).map(quiz => {\n return {\n id: quiz.id,\n title: quiz.title\n };\n });\n return res.json(ret);\n}",
"function generateQuizzes(quizzes){\n\n // for each quiz in the quizzes object\n for (let quiz of quizzes) {\n\n // Admin DOM elements\n const adminQuestionDiv = document.createElement('div');\n const adminQuestionBody = document.createElement('div');\n adminQuestionBody.innerHTML = `<a href=\"./admin.html?id=${quiz.quizId}&quizName=${quiz.name}\"><h5 class=\"card-title\">Quiz ${questionNum} : ${quiz.name}</h5></a>`;\n adminSection.appendChild(adminQuestionDiv);\n adminQuestionDiv.appendChild(adminQuestionBody);\n adminQuestionDiv.classList.add('card');\n adminQuestionDiv.classList.add('col-10');\n adminQuestionDiv.classList.add('mt-1');\n adminQuestionBody.classList.add('card-body');\n\n // Student DOM elements\n const studentQuestionDiv = document.createElement('div');\n const studentQuestionBody = document.createElement('div');\n studentQuestionBody.innerHTML = `<a href=\"./student.html?id=${quiz.quizId}&quizName=${quiz.name}\"><h5 class=\"card-title\">Quiz ${questionNum++} : ${quiz.name}</h5></a>`;\n studentSection.appendChild(studentQuestionDiv);\n studentQuestionDiv.appendChild(studentQuestionBody);\n studentQuestionDiv.classList.add('card');\n studentQuestionDiv.classList.add('col-10');\n studentQuestionDiv.classList.add('mt-1');\n studentQuestionBody.classList.add('card-body');\n }\n}",
"function listOfQuestions() {\r\n client.query(`SELECT * from public.\"questionsDB\" ORDER BY id ASC`, function(err, result) {\r\n if(err) {\r\n return console.error('error running query', err);\r\n }\r\n else {\r\n console.log('List of questions-->', result.rows);\r\n }\r\n });\r\n }",
"function showQuizzes() {\n /* put 1/3 in each column inc to count, reset : inc colm */\n var count = Math.ceil(quizList.length/3);\n var col=0;\n var row=0;\n for (var i=0; i<quizList.length; i++) {\n content = '<div id='+quizList[i].quiz_id+' class=\"alert alert-info\">';// blue\n content += quizList[i].title;\n content += ': total questions: '+quizList[i].questions.length;//.question_count;\n //content += ' worth: '+quizList[i].points_possible;\n content += '</div>';\n $('#col_'+col).append(content);\n row++;\n if (row==count) { row=0; col++; }\n }\n //click quiz to view questions\n $('.alert').on('click', function(e) {\n e.preventDefault();\n selectedQuiz=e.target.id;// quiz_id\n orchidConfig.quiz_id = selectedQuiz;\n \n showQuizQuestions(selectedQuiz);\n });\n }",
"async function loadQuizList() {\n\tlet response;\n\tlet json;\n\ttry {\n\t\tresponse = await fetch( QUIZ_LIST_FILE );\n\t\tjson = await response.json();\n\t} catch ( e ) {\n\t\tSTORE.quizList = null;\n\t\treturn;\n\t}\n\tSTORE.quizList = json.quizzes;\n\tconsole.log( `loaded ${STORE.quizList.length} quizzes` );\n}",
"function setAvailableQuestions() {\r\n quizzes.forEach(quiz => {\r\n availableQuestions.push(quiz);\r\n });\r\n}",
"function getResponses(quizzes, cb) {\n\t\t\t\tvar complete = Object.keys(quizzes).length;\n\t\t\t\t\n\t\t\t\tfor (var quiz in quizzes) {\n\t\t\t\t\tvar responses = [];\n\t\t\t\t\tdb.responses.find({quizName: quizzes[quiz].quizName, creator_username: localStorage.getItem('username'), evaluated: false}, function(err, foundResponse) {\n\t\t\t\t\t\tif (err||!foundResponse) {console.log(err)}\n\t\t\t\t\t\t\telse { \n\t\t\t\t\t\t\t\tresponses.push(foundResponse);\n\t\t\t\t\t\t\t\tcomplete--;\n\t\t\t\t\t\t\t\tif (complete == 0) {\n\t\t\t\t\t\t\t\t\tcb(quizzes, responses);\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t};\n\t\t\t\t\t});\n\t\t\t\t};\n\t\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert `insertArr` inside `target` at `insertIndex`. Please don't touch unless you understand | function arrayInsert(target, insertIndex, insertArr) {
var before = target.slice(0, insertIndex);
var after = target.slice(insertIndex);
return before.concat(insertArr, after);
} | [
"function arrayInsert(target, insertIndex, insertArr) {\n const before = target.slice(0, insertIndex);\n const after = target.slice(insertIndex);\n return before.concat(insertArr, after);\n }",
"function arrayInsert(target, insertIndex, insertArr) {\n var before = target.slice(0, insertIndex);\n var after = target.slice(insertIndex);\n return before.concat(insertArr, after);\n }",
"function arrayInsert(target, insertIndex, insertArr) {\n var before = target.slice(0, insertIndex);\n var after = target.slice(insertIndex);\n return before.concat(insertArr, after);\n}",
"function insert(curr_index, target_index, arr) {\n var temp = arr[curr_index];\n\n for(var i = curr_index; i > target_index; i--) {\n arr[i] = arr[i-1];\n }\n\n arr[target_index] = temp;\n return arr; \n}",
"function insertIntoList(targetList, toInsert, offset) {\n\t if (offset === targetList.count()) {\n\t toInsert.forEach(function (c) {\n\t targetList = targetList.push(c);\n\t });\n\t } else if (offset === 0) {\n\t toInsert.reverse().forEach(function (c) {\n\t targetList = targetList.unshift(c);\n\t });\n\t } else {\n\t var head = targetList.slice(0, offset);\n\t var tail = targetList.slice(offset);\n\t targetList = head.concat(toInsert, tail).toList();\n\t }\n\t return targetList;\n\t}",
"InsertArrayElementAtIndex() {}",
"_insertAt(target, element, index) {\n let refNode = target.firstChild;\n let i = 0;\n while(refNode && i !== index) {\n ++i;\n refNode = refNode.nextSibling;\n }\n target.insertBefore(element, refNode);\n }",
"function insertArrayInto(toAdd, insertPoint, array){\n\t//\n\tvar kLimit = toAdd.length;\n\tvar iLimit = array.length;\n\n\tarray.length = iLimit+kLimit;\n\n\tvar k= insertPoint + kLimit;\n\tfor(var i=insertPoint; i < iLimit; i++){\n\t\tarray[k] = array[i];\n\t\tk++;\n\t}\n\ti=insertPoint;\n\tfor(k=0; k < kLimit; k++){\n\t\tarray[i] = toAdd[k];\n\t\ti++;\n\t}\n\treturn array;\n\n}",
"function insertIntoNewArray(arr, index, element) {\n // implementation\n}",
"function insertTo(ary, ele, pos) {\n // TODO\n}",
"function insert(array, idx, val) {\n return array.slice(0, idx).concat(Array.isArray(val) ? val : [val]).concat(array.slice(idx));\n}",
"function insert(arr, element, index) {\n insertAll(arr, [element], index);\n}",
"function insertValue (array, index, value) {\n\n}",
"function insertAt(arr, index, val) // ([], 0, 1)\n{\n for(var x = arr.length ; x > index; x--){\n // x has extra index place for the new value\n // move the items by one till the index we want\n arr[x] = arr[x-1]\n }\n // add thde value\n arr[index] = val\n return arr\n}",
"function insertAt(arr,givenIndex,val){\n for (var index = arr.length; index >= givenIndex; index--){\n var currentValue = arr[index-1];\n arr[index] = currentValue;\n }\n arr[givenIndex] = val;\n return arr;\n}",
"insertAt(index, data) {}",
"function insert(array, element, index) {\n //if (array) {\n index = _Math__WEBPACK_IMPORTED_MODULE_0__[\"fitToRange\"](index, 0, array.length);\n array.splice(index, 0, element);\n //}\n}",
"function insertList (a_obj, a_index, obj, index) {\r\n let len = a_index.length;\r\n if (len == 0) {\r\n\ta_obj.push(obj);\r\n\ta_index.push(index);\r\n }\r\n else if (len == 1) {\r\n\tif (a_index[0] >= index) {\r\n\t a_obj.unshift(obj);\r\n\t a_index.unshift(index);\r\n\t}\r\n\telse {\r\n\t a_obj.push(obj);\r\n\t a_index.push(index);\r\n\t}\r\n }\r\n else {\r\n\tif (a_index[0] >= index) {\r\n\t a_obj.unshift(obj);\r\n\t a_index.unshift(index);\r\n\t}\r\n\telse if (a_index[len-1] <= index) {\r\n\t a_obj.push(obj);\r\n\t a_index.push(index);\r\n\t}\r\n\telse { // Insert between the two by dichotomy\r\n\t let minPos = 0;\r\n\t let maxPos = len-1;\r\n\t let pos;\r\n\t while (maxPos - minPos > 1) {\r\n\t\tpos = (minPos + maxPos) >> 1; // Divide by 2 keeping an integer position => shift left by 1\r\n\t\tif (a_index[pos] > index) {\r\n\t\t maxPos = pos;\r\n\t\t}\r\n\t\telse {\r\n\t\t minPos = pos;\r\n\t\t}\r\n\t }\r\n\t // Insert the new element at maxPos (which is just before the maxPos element, and just after\r\n\t // the minPos one)\r\n\t a_obj.splice(maxPos, 0, obj);\r\n\t a_index.splice(maxPos, 0, index);\r\n\t}\r\n }\r\n}",
"function doInsertion(index,numToInsert){\n\tvar temp = (index >= myArray.length) ? numToInsert : myArray[index];\t\t\n\t\n\t// once index position is more or equal to total array length, \n\t// insert as new number in last position\n\tif(index >= myArray.length){ \n\t\tmyArray.push(temp);\n\t}else{\t\t\t\n\t\tmyArray[index] = numToInsert;\n\t\tindex++;\n\n\t\t// move the numbers ahead to next position\n\t\t// as if pushing to next position\n\t\tdoInsertion(index,temp);\t\n\t}\n\t\t\n} // end of doInsertion"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Processes message attachments and uploads them to the folder specified. | function processMessageAttachments(message, folderToUpload) {
var attachments = message.getAttachments();
if (attachments.length != 0) {
Logger.log('Message %s has %s attachments.', message.getId(), attachments.length);
Logger.log('Uploading blob to folder');
for (var i = 0; i < attachments.length; i++) {
var d = message.getDate();
var formattedDate = d.getFullYear() + '.' + d.getMonth() + '.' + d.getDate();
uploadBlobToFolder(attachments[i].copyBlob(), formattedDate + ' - ' + attachments[i].getName(), folderToUpload);
}
}
else {
Logger.log('Message %s has no attachments.', message.getId());
}
Logger.log('Adding label %s', processedLabel.getName());
message.getThread().addLabel(processedLabel);
} | [
"processAttachments(sender, attachments) {\n this.preProcess(sender);\n\n console.log(attachments);\n\n switch (this.users.get(sender).currentState) {\n\n case 'create-note':\n quill.addAttachments(this.users.get(sender).note, attachments)\n break;\n\n default:\n this.sendTextMessage(sender, \"Message with attachment received\");\n break;\n }\n\n }",
"async handleAttachments () {\n\t\t// not yet supported\n\t}",
"async function postFiles(conversation) {\n const path = config.filesPath;\n const files = [];\n const fileNames = fs.readdirSync(path);\n fileNames.forEach(name => {\n const file = new Circuit.File(path + name);\n files.push(file);\n });\n\n const item = await client1.addTextItem(conversation.convId, {\n content: 'test file upload',\n attachments: files\n });\n logger.info(`[APP]: Bot1 posted ${item.attachments.length} files to item ${item.itemId}`);\n }",
"function uploadAttachments(parsedMessage, callback){\n var attachmentCount = parsedMessage.attachments.length;\n var uploadedMessage = _.omit(parsedMessage, 'attachments');\n uploadedMessage.attachments = [];\n function done(error, url){\n if(error){\n callback(error);\n return;\n }\n uploadedMessage.attachments.push(url);\n //done with all uploads\n if(uploadedMessage.attachments.length == attachmentCount){\n callback(null, uploadedMessage);\n }\n }\n var timestamp = new Date().getTime() + '/';\n _.each(parsedMessage.attachments, function(attachment, index){\n var fileName = timestamp + index + '-' + attachment.fileName;\n s3.upload(fileName, attachment.contentType, attachment.buffer, done)\n });\n}",
"async handleAttachmentFile (/*attachment*/) {\n\t\t/*\n\t\tWHEN WE'RE READY TO DEAL WITH ATTACHMENTS\n\n\t\t// prepare to store on S3\n\t\tconst size = attachment.parseAttachment.size;\n\t\tconst basename = Path.basename(attachment.path);\n\t\tconst filename = FileStorageService.preEncodeFilename(basename);\n\t\tconst storageTopPath = ''; // When we deal with attachments: this.inboundEmailServer.config.s3.topPath ? (this.inboundEmailServer.config.s3.topPath + '/') : '';\n\t\tconst timestamp = Date.now();\n\t\tconst storagePath = `${storageTopPath}/email_files/${timestamp}_${basename}/${filename}`;\n\t\tconst options = {\n\t\t\tpath: attachment.path,\n\t\t\tfilename: storagePath\n\t\t};\n\n\t\tthis.log('Would have handled attachment: ' + JSON.stringify(options));\n\t\t// store on S3\n\t\tthis.FileStorageService.storeFile(\n\t\t\toptions,\n\t\t\t(error, storageUrl, downloadUrl, versionId, storagePath) => {\n\t\t\t\tif (error) {\n\t\t\t\t\tthis.warn(`Unable to handle attachment ${basename}/${filename} and store file to S3: ${JSON.stringify(error)}`);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// this is the data we'll pass on to the API server\n\t\t\t\t\tlet data = { storageUrl, downloadUrl, versionId, storagePath, size };\n\t\t\t\t\tdata.lastModified = Date.now();\n\t\t\t\t\tthis.attachmentData.push(data);\n\t\t\t\t}\n\t\t\t\tprocess.nextTick(callback);\n\t\t\t}\n\t\t);\n\t\t*/\n\t}",
"async handleAttachments () {\n\t\tthis.attachmentData = [];\n\t\tawait Promise.all(this.attachments.map(async attachment => {\n\t\t\tawait this.handleAttachmentFile(attachment);\n\t\t}));\n\t}",
"function uploadAttachment()\n {\n if (Office.context.mailbox.item.attachments == undefined)\n {\n app.showNotification(\"Sorry attachments are not supported by your Exchange server.\");\n }\n else if (Office.context.mailbox.item.attachments.length == 0)\n {\n app.showNotification(\"Oops there are no attachments on this email.\");\n }\n else\n {\n var apicall = \"https://api.workflowmax.com/job.api/document?apiKey=\"+ apiKey + \"&accountKey=\" + accountKey;\n\n var documentXML = \"<Document><Job>\" + cJobID + \"</Job><Title>Document Title</Title><Text>Note for document</Text><FileName>test.txt</FileName><Content>\" + string64 + \"</Content></Document>\";\n\n var xhr = new XMLHttpRequest();\n\n xhr.open('POST', apicall);\n\n xhr.send(documentXML);\n }\n }",
"async function replyForReceivedAttachments(localAttachmentData) {\n if (localAttachmentData) {\n\n // run an indexer\n azureSearchClient.resetIndexer(process.env.SearchServiceDocumentIndexer, function(err){\n // optional error\n });\n\n // run an indexer\n azureSearchClient.runIndexer(process.env.SearchServiceDocumentIndexer, function(err){\n // optional error\n });\n\n await turnContext.sendActivity({ attachments: [self.dialogHelper.createBotCard('... ' + localAttachmentData.fileName + ' is uploaded to azure','')] });\n\n } else {\n\n await turnContext.sendActivity({ attachments: [self.dialogHelper.createBotCard('...Attachment was NOT successfully saved to azure','')] });\n\n }\n }",
"process(e) {\n // get the file from the input field\n const files = this.$('input').prop('files');\n\n if (files.length === 0) {\n // We've got no files to upload, so trying\n // to begin an upload will show an error\n // to the user.\n return;\n }\n\n this.attrs.uploader.upload(files, !this.isMediaUploadButton);\n }",
"function addAttachments() {\n if (item.itemType === Office.MailboxEnums.ItemType.Message) {\n Office.cast.item.toMessageCompose(item).addFileAttachmentAsync(\"https://i.imgur.com/ucI9vyz.png\", \"image file\", { asyncContext: null },\n function (asyncResult) {\n if (asyncResult.status == Office.AsyncResultStatus.Failed) {\n app.showNotification(asyncResult.error.message);\n }\n else {\n app.showNotification('ID of added attachment: ' + asyncResult.value);\n }\n });\n } else if (item.itemType === Office.MailboxEnums.ItemType.Appointment) {\n Office.cast.item.toAppointmentCompose(item).addFileAttachmentAsync(\"https://i.imgur.com/ucI9vyz.png\", \"image file\");\n }\n }",
"function slackUpload(fname, channel, msg) {\n console.log(\"CHANNEL: \" + channel + \" \" + path.basename(channel));\n if (msg.includes('[[')) {\n console.log(\"*** POSTING ATTACHMENT\");\n var att=JSON.parse(msg);\n msg=''; // ATTACHMENT, NO MESSAGE FOR NOW\n }\n var token=bot.token;\n var options = {\n uri: 'https://slack.com/api/files.upload',\n method: 'POST',\n formData: { \n // channels: 'CEUDECU0Z',\n channels: path.basename(channel),\n file: fs.createReadStream(__dirname + '/downloads/' + fname),\n initial_comment: msg,\n attachments: ''\n },\n headers:{\n Authorization: ' Bearer ' + token \n }\n }\n // send as multipart/form-data\n console.log(\"SEND REQUEST \" + channel);\n // console.log(options);\n request(options)\n .on('finish', function() {\n console.log('Done uploading');\n });\n}",
"async _postMessage() {\n if (!this.composer.canPostMessage) {\n if (this.composer.hasUploadingAttachment) {\n this.env.services['notification'].notify({\n message: this.env._t(\"Please wait while the file is uploading.\"),\n type: 'warning',\n });\n }\n return;\n }\n await this.composer.postMessage();\n // TODO: we might need to remove trigger and use the store to wait for the post rpc to be done\n // task-2252858\n this.trigger('o-message-posted');\n }",
"function sendFileMessage(message) {\n\n}",
"async function finalizeUploads() {\n if (Array.isArray(attachments)) {\n for (const attachment of attachments) {\n const { buffer, originalname, mimetype } = attachment;\n if (Buffer.isBuffer(buffer)) { // Checking whether the file object has a buffer because some corrupt files don't have a valid buffer. Observed it in my testing.\n await requestHandler.request(`cards/${cardID}/attachments`, \"trello\", \"post\", {}, {}, {\n name: originalname,\n mimeType: mimetype,\n key: trelloKey,\n token: trelloToken\n }, {\n file: \"file\",\n buffer,\n details: {\n filename: originalname,\n contentType: mimetype\n }\n });\n }\n else {\n return res.status(400).send(`${originalname} seems to be a corrupted file`);\n }\n }\n\n return res.redirect(`https://trello.com/c/${cardID}`);\n }\n else if (linkAttachString !== undefined) {\n const linkArray = linkAttachString.split(\"||\");\n const linkArrayLength = linkArray.length;\n if (linkArrayLength <= 8) {\n let index = 0;\n\n for (const link of linkArray) {\n index = index + 1;\n const { body } = await superagent.get(link);\n\n if (Buffer.isBuffer(body)) {\n await requestHandler.request(`cards/${cardID}/attachments`, \"trello\", \"post\", {}, {}, {\n name: `Link - ${index}`,\n url: link.trim(),\n key: trelloKey,\n token: trelloToken\n });\n\n if (index === linkArrayLength) {\n return res.redirect(`https://trello.com/c/${cardID}`);\n }\n }\n else {\n return res.status(400).send(`Link \\`${link}\\` is an invalid file upload URL! Here is a link to the report you made: https://trello.com/c/${cardID}`);\n }\n }\n }\n else {\n return res.status(400).send(`Please contact the bug hunter if you want to upload more than 8 attachments. Here is a link to the report you made: https://trello.com/c/${cardID}`);\n }\n }\n else {\n return res.redirect(`https://trello.com/c/${cardID}`);\n }\n }",
"function updateMessagesForAttachments(data, status) {\n log(\"Method: updateMessagesForAttachments\");\n var messages = $(\"#Messages_Section\").html();\n if (data.indexOf(\"Documents found in folder\") > -1) {\n if (messages.indexOf(attachmentMessage) == -1) {\n messages += attachmentMessage;\n showErrorMessage(messages);\n }\n }\n else {\n var position = messages.indexOf(attachmentMessage);\n if (position > -1) {\n messages = messages.substr(0, position) + messages.substr(position + attachmentMessage.length, messages.length);\n if (messages.trim() == \"\") {\n hideErrorMessage();\n }\n else {\n showErrorMessage(messages);\n }\n }\n }\n attachmentSubmitWait = \"\";\n}",
"function addAttachments (channelUserId, message, primaryFBMessage, postDataItems) {\n\n\tif (!message.attachments || !message.attachments.length) { return; }\n\n\tconst fbAttachments = convertToFacebookAttachments(message.attachments);\n\n\tfbAttachments.map(fbAttachment => {\n\t\tlet shell;\n\t\tlet newShellMessage;\n\n\t\tif (primaryFBMessage.attachment) {\n\t\t\tshell = createFacebookMessageShell(channelUserId);\n\t\t\tnewShellMessage = true;\n\t\t}\n\t\telse {\n\t\t\tshell = primaryFBMessage;\n\t\t\tnewShellMessage = false;\n\t\t}\n\n\t\tshell.message.attachment = fbAttachment;\n\n\t\tif (newShellMessage) {\n\t\t\tpostDataItems.push(shell);\n\t\t}\n\t});\n\n}",
"async function processAllFiles() {\n let file;\n while ((file = await inbox.pop())) {\n console.log(`New file: ${file.name}`);\n let payload = await file.cbor();\n console.log(`file contents: ${JSON.stringify(payload)}`);\n websocket.send(encode({\n \"closing\": false,\n \"userId\": userEncodedId,\n \"token\": token,\n \"data\": payload,\n }));\n }\n}",
"function uploadFiles() {\n\n\t\t\t\t\t// Locate any mtc files that are already saved to the file system\n\t\t\t\t\tfunction listExistingMtcFiles() {\n\t\t\t\t\t\treturn fs.listFiles(domain.domInfo.outgoingDir(), \"*.mtc\");\n\t\t\t\t\t}\n\n\t\t\t\t\t// Load each file and upload it to the server\n\t\t\t\t\tfunction readFiles(files) {\n\t\t\t\t\t\tvar readPromise = AH.resolve();\n\t\t\t\t\t\tif (files && files.length) {\n\t\t\t\t\t\t\treadPromise = readPromise\n\t\t\t\t\t\t\t\t.then(syncEvent(\"uploadingXacts\"));\n\t\t\t\t\t\t\treadPromise = files.reduce(function (previous, fileInfo, idx) {\n\t\t\t\t\t\t\t\treturn previous.then(function () {\n\t\t\t\t\t\t\t\t\tvar filePromise = fs.readJsonFileContent(fileInfo.dir, fileInfo.name)\n\t\t\t\t\t\t\t\t\t\t.then(function (mtc) {\n\t\t\t\t\t\t\t\t\t\t\treturn server.putFile(mtc, options.timeout);\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t.then(function () {\n\t\t\t\t\t\t\t\t\t\t\treturn fs.deleteFile(domain.domInfo.outgoingDir(), fileInfo.name, false);\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tlogFileToUpload(fileInfo);\n\t\t\t\t\t\t\t\t\treturn AH.notify(Message.getMessage(Constants.messageCodes.uploadingFile, idx + 1, files.length), filePromise);\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}, readPromise);\n\n\t\t\t\t\t\t\treadPromise = readPromise\n\t\t\t\t\t\t\t\t.then(syncEvent(\"uploadedXacts\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn readPromise;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn listExistingMtcFiles()\n\t\t\t\t\t\t.then(readFiles);\n\t\t\t\t}",
"function CMU(channel, message, file) {\n bot.Channels.get(channel).uploadFile(file, file, message)\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
show clear button if transcript | function showClearButton() {
console.log('CHECKING SHOW CLEAR', transcript)
if (!transcript.length) {
clearButton.style.visibility = 'hidden'
} else {
clearButton.style.visibility = 'visible'
}
} | [
"function handleClearTranscript(event) {\r\n event.preventDefault();\r\n console.log(\"speech deleted\");\r\n\ttranscript.textContent = \"\";\r\n transcriptt.textContent = \"\";\r\n transcripttt.textContent = \"\";\r\n \r\n}",
"function clear(){\n $('#phrase-pane').html('')\n}",
"function clearText(text) {\n\ttext.text(\"\");\n\n\tif (text.id() == 'monologue') {\n\t\tspeech_bubble.hide();\n\t}\n\ttext_layer.draw();\n}",
"function clear() {\n var regions = document.getElementsByClassName('a11y-speak-region');\n var introText = document.getElementById('a11y-speak-intro-text');\n\n for (var i = 0; i < regions.length; i++) {\n regions[i].textContent = '';\n } // Make sure the explanatory text is hidden from assistive technologies.\n\n\n if (introText) {\n introText.setAttribute('hidden', 'hidden');\n }\n}",
"function ClearText() {\r\n $(\"#answer\").val(\"\");\r\n $('.translation').removeClass('show');\r\n $(\"#answer\").removeClass();\r\n //$(\"#status\").html(\"X\");\r\n }",
"removePhraseFromDisplay() {\r\n const container = document.getElementById('phrase').firstElementChild;\r\n container.innerHTML = null;\r\n }",
"function clear()\n {\n console.log(\"Clear previewSelection\");\n// previewedSelection = null;\n contentVeil.reset();\n contentVeil.hide();\n }",
"function clearPre() {\n var pre = document.getElementById('content');\n pre.innerHTML = '';\n}",
"function clear() {\n var regions = document.getElementsByClassName('a11y-speak-region');\n\n for (var i = 0; i < regions.length; i++) {\n regions[i].textContent = '';\n }\n}",
"clear() {\n this.text = '';\n }",
"function clearText() {\n\ttext.value = '';\n\ttetx.value = '';\n}",
"function clearTranslation() {\n var translateBox = document.getElementById('translatedBox');\n translateBox.textContent = '';\n}",
"function clearFormText() {\n tinyMCE.activeEditor.setContent('');\n}",
"_clearText(){\n /** default text is '...', _oldText is also reset*/\n this._oldText= \"...\";\n this.entry.set_text(\"...\");\n\n /** mark as unvalidated with no decoration */\n this._validated= false;\n this.entry.style_class= '';\n\n\n this.emit('dns-text-cleared');\n }",
"_showClearButton() {\n\t\tif (this.disableShowClear) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this._isClearButtonVisible) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.$.clear.style.display = 'inline-block';\n\t\tthis._isClearButtonVisible = true;\n\t}",
"clearText() {\n this.text = \"\";\n this.removeTextFromBlob(this)\n }",
"clear() {\n this.setLanguage('');\n this.setEditorCodeText('');\n }",
"clearResultDisplay() {\n this.resultDisplay.text('');\n }",
"function clearElementText(domElement) {\n\t\tdomElement.innerHTML = '';\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates valid disposition of usage values and updates all credit card sliders | function updateAll(idUpdated) {
const currentValues = [] // Credit cards sliders values
const saleTotal = saleInProgress.total // Sale total
const balance = Number($('#balance').val()) || 0 // Currently inserted balance usage
const ccMin = balance && balance != 0 ? 0 : 10 // Minimum credit card sliders value (10 if no balance, 0 otherwise)
// Get sliders values and credit card representatives
$('[data-id]', cardList).each((i, elem) => {
currentValues.push({
id: Number($(elem).attr('data-id')),
val: Number($(elem).val())
})
})
const ccMax = saleTotal - (balance && balance != 0 ? balance : currentValues.length * ccMin)
console.log('cc min max:', ccMin, ccMax)
console.log('log label:', 'getSumSliders()', 'balance', 'saleTotal', 'getTotalDifference()')
const getSumSliders = () => currentValues.reduce((a, b) => a + b.val, 0)
const getTotalDifference = () => Math.round((saleTotal - balance - getSumSliders()) * 100) / 100
console.log('values 1:', getSumSliders(), balance, saleTotal, getTotalDifference())
if (currentValues.length > 1) {
// Drag sliders that went past ccMin/ccMax
currentValues.forEach((v, i) => {
if (currentValues[i].val < ccMin) {
currentValues[i].val = ccMin;
} else if (currentValues[i].val > ccMax) {
currentValues[i].val = ccMax;
}
})
console.log('values 2:', getSumSliders(), balance, saleTotal, getTotalDifference())
if (getTotalDifference() > 0.01) { // total is higher than sum of usages, must increase sliders values
currentValues.forEach((v, i) => {
// Correct sliders without modifying the updated one
if (v.id != idUpdated && getTotalDifference() > 0.01) {
const maxSliderAddition = ccMax - v.val; // The maximum the slider can be increased
console.log(i, getTotalDifference(), maxSliderAddition)
currentValues[i].val += Math.min(maxSliderAddition, getTotalDifference())
}
})
console.log('values 3:', getSumSliders(), balance, saleTotal, getTotalDifference())
} else if (getTotalDifference() < -0.01) { // total is lower than sum of usages, must decrease sliders values
currentValues.forEach((v, i) => {
// Correct sliders without modifying the updated one
if (v.id != idUpdated && getTotalDifference() < -0.01) {
const maxSliderSubtraction = (v.val - ccMin) * -1; // The maximum the slider can be decreased
console.log(i, getTotalDifference(), maxSliderSubtraction)
currentValues[i].val += Math.max(maxSliderSubtraction, getTotalDifference())
}
})
console.log('values 4:', getSumSliders(), balance, saleTotal, getTotalDifference())
} else {
console.info("total difference is ~0!", getSumSliders(), balance, saleTotal, getTotalDifference())
}
// Update slider elements with new currentValues
console.log('updating with:', currentValues, getTotalDifference())
$('[data-id]', cardList).each((i, elem) => {
// if (Number($(elem).attr('data-id')) === idUpdated) {
// }
$(elem).data("ionRangeSlider").update({ from: Math.round(currentValues[i].val * 100) / 100 })
})
} else {
// If there's only one credit card it must be used to pay all the total (minus balance usage)
$('[data-id]', cardList).data("ionRangeSlider").update({ from: Math.round((total - balance) * 100) / 100 })
}
} | [
"function updateSrcValue() {\n destAmount = document.getElementById('dest-amount').value\n srcAmount = destAmount * (1 / (expectedRate / (10 ** 18)));\n displaySrcAmount();\n}",
"function adjustPaymentOptions_and_availableAmounts () {\n creditType = $(\"#creditType\").val()\n netIncome = $(\"#netIncome\").val()\n\n if (netIncome == \"-$30.0000\") {\n $(\"#amountErrorMessage\").attr(\"class\", \"displayNone\")\n $(\"#insuficientIncomeMessage\").attr(\"class\", \"displayBlock\")\n $(\"#btn-calculatePayments\").attr(\"class\", \"btn-disabled\")\n modifyAvailableAmounts(netIncome, personalCredit.minAmount, personalCredit.topAmount)\n $(\"#numberOfPayments\").attr(\"disabled\", true)\n $(\"#creditAmount\").attr(\"disabled\", true)\n }\n\n else if (creditType == \"Personal\" && netIncome == \"$30.000 - $50.000\") {\n cleanFormPaymentOptions()\n populatePaymentOptions (creditType)\n modifyAvailableAmounts(netIncome, personalCredit.minAmount, personalCredit.topAmount)\n } \n \n else if (creditType == \"Personal\" && netIncome == \"$50.000 - $75.000\") {\n cleanFormPaymentOptions()\n populatePaymentOptions (creditType)\n modifyAvailableAmounts(netIncome, personalCredit.minAmount, personalCredit.topAmount)\n }\n\n else if (creditType == \"Personal\" && netIncome == \"+$75.0000\") {\n cleanFormPaymentOptions()\n populatePaymentOptions (creditType)\n modifyAvailableAmounts(netIncome, personalCredit.minAmount, personalCredit.topAmount)\n }\n\n else if (creditType == \"Pledge\" && netIncome == \"$30.000 - $50.000\") {\n cleanFormPaymentOptions()\n populatePaymentOptions (creditType)\n modifyAvailableAmounts(netIncome, pledgeCredit.minAmount, pledgeCredit.topAmount)\n }\n\n else if (creditType == \"Pledge\" && netIncome == \"$50.000 - $75.000\") {\n cleanFormPaymentOptions()\n populatePaymentOptions (creditType)\n modifyAvailableAmounts(netIncome, pledgeCredit.minAmount, pledgeCredit.topAmount)\n }\n\n else if (creditType == \"Pledge\" && netIncome == \"+$75.0000\") {\n cleanFormPaymentOptions()\n populatePaymentOptions (creditType)\n modifyAvailableAmounts(netIncome, pledgeCredit.minAmount, pledgeCredit.topAmount)\n }\n\n else if (creditType == \"Mortgage\" && netIncome == \"$30.000 - $50.000\") {\n cleanFormPaymentOptions()\n populatePaymentOptions (creditType)\n modifyAvailableAmounts(netIncome, mortgageCredit.minAmount, mortgageCredit.topAmount)\n }\n\n else if (creditType == \"Mortgage\" && netIncome == \"$50.000 - $75.000\") {\n cleanFormPaymentOptions()\n populatePaymentOptions (creditType)\n modifyAvailableAmounts(netIncome, mortgageCredit.minAmount, mortgageCredit.topAmount)\n }\n\n else if (creditType == \"Mortgage\" && netIncome == \"+$75.0000\") {\n cleanFormPaymentOptions()\n populatePaymentOptions (creditType)\n modifyAvailableAmounts(netIncome, mortgageCredit.minAmount, mortgageCredit.topAmount)\n }\n\n else if (creditType == \"Business\" && netIncome == \"$30.000 - $50.000\") {\n cleanFormPaymentOptions()\n populatePaymentOptions (creditType)\n modifyAvailableAmounts(netIncome, businessCredit.minAmount, businessCredit.topAmount)\n }\n\n else if (creditType == \"Business\" && netIncome == \"$50.000 - $75.000\") {\n cleanFormPaymentOptions()\n populatePaymentOptions (creditType)\n modifyAvailableAmounts(netIncome, businessCredit.minAmount, businessCredit.topAmount)\n }\n\n else if (creditType == \"Business\" && netIncome == \"+$75.0000\") {\n cleanFormPaymentOptions()\n populatePaymentOptions (creditType)\n modifyAvailableAmounts(netIncome, businessCredit.minAmount, businessCredit.topAmount)\n }\n}",
"function updateDestValue() {\n srcAmount = document.getElementById('src-amount').value\n destAmount = (srcAmount * (expectedRate / 10 ** 18));\n displayDestAmount();\n}",
"function securityperchange(){\n\tvar secperamt=$(\"#securityPer\").val();\n\tif(secperamt==\"\"){\n\t\tsecperamt=0;\n\t}\n\tvar totalAamt=$(\"#totalCc\").val()==''?0:$(\"#totalCc\").val();\n\tvar secpervalamt=parseFloat(totalAamt)*(parseFloat(secperamt)/100);\n\tvar secpervalamtCC=parseFloat($(\"#secDepositPrevCerti\").val()==''?0:$(\"#secDepositPrevCerti\").val())+secpervalamt;\t\n\t\n\t$(\"#secDepositCurrentCerti\").val(secpervalamt.toFixed(2));\t\n\t$(\"#secDepositCumulative\").val(secpervalamtCC.toFixed(2));\n\t$(\"#secDepositCurrentCerti\").attr(\"readonly\", true);\n\tcaldeductionamt();\t\n}",
"function CalcAnalyticAssUnAss() {\n\n var sumAmountTblAnalyticDist = 0;\n $(\".SumAmountTblAnalyticDist\").each(function () {\n var value = parseFloat($(this).text().replace(regRemoveCurrFormate, \"\"));\n // add only if the value is number\n if (!isNaN(value) && value.length != 0) {\n sumAmountTblAnalyticDist += value;\n }\n });\n\n $(\"#TCGE-PUAAAssigned\").text(setSystemCurrFormate(+parseFloat(sumAmountTblAnalyticDist)));\n\n var originalAmount = $(\"#TCGE-PUAAOriginalAmount\").text().replace(regRemoveCurrFormate, \"\");\n\n //console.log(originalAmount);\n\n var unAssignedVal = parseFloat(originalAmount) - sumAmountTblAnalyticDist;\n\n $(\"#TCGE-PUAAUnassigned\").text(setSystemCurrFormate(+parseFloat(unAssignedVal)));\n ForceRefreshThisPicker(\"#TCGE-PUAAccDisID\");\n}",
"function calc(days, valid) {\n let day_count = $('#day_count');\n let apartment_amount = $('#apartment_amount');\n let services_amount = $('#services_amount');\n let final_amount = $('#final_amount');\n day_count.text('');\n apartment_amount.text('');\n services_amount.text('');\n final_amount.text('');\n let base_price;\n if (valid) {\n day_count.text(days);\n if ($('.apartment_sale_price').length) {\n base_price = $('.apartment_sale_price').data('apartment_sale_price');\n } else {\n base_price = $('.apartment_price').data('apartment_price');\n }\n apartment_amount.text(representAmount(base_price * days));\n let checked_services_amount = 0;\n $('.upgrade_service').each(function () {\n if ($(this).is(':checked')) {\n checked_services_amount += $(this).data('service_price');\n }\n });\n services_amount.text(representAmount(checked_services_amount * days));\n final_amount.text(representAmount((checked_services_amount + base_price) * days));\n }\n}",
"function checkValidPointsUsed() {\n const pointsAvailable = parseInt(document.querySelector(\".user-loyalty-points\").textContent);\n const userEnteredPoints = parseInt(pointsToUse.value);\n\n // Check if user enters a points value that is less than 0 or greater than loyalty points earned\n if (userEnteredPoints < 0) {\n pointsToUse.value = 0;\n }\n else if (userEnteredPoints > pointsAvailable) {\n // Check if user enters a points value greater than what is available\n if (pointsAvailable === 0) {\n pointsToUse.value = 0;\n }\n else {\n // Check if pointsAvailable is divisible by 50 and remove remainder to use a multiple of 50 if not\n const remainder = pointsAvailable % 50;\n if (remainder) {\n pointsToUse.value = pointsAvailable - remainder;\n }\n }\n }\n else if (userEnteredPoints % 50 != 0) {\n const excessPoints = userEnteredPoints % 50;\n pointsToUse.value = userEnteredPoints - excessPoints;\n }\n}",
"function calculateAnalogCardsPrice()\n{\n\tvar index = document.form.accessory_fxo_card.selectedIndex;\n\tvar fxo = parseInt(document.form.accessory_fxo_card.options[index].value);\n\tindex = document.form.accessory_fxs_card.selectedIndex;\n\tvar fxs = parseInt(document.form.accessory_fxs_card.options[index].value);\n\n\tvar dis_fxo = fxo;\n\tvar dis_fxs = fxs;\n\n\tindex = document.form.item_server_hardware.selectedIndex;\n\tindex = document.form.item_server_hardware.options[index].value;\n\tvar card_type = hashServerAnalogType[index];\n\n\tvar ec_type = document.form.accessory_analog_echo.checked ? 1 : 0;\n\tvar dis_ec = ec_type;\n\tec_type = \"echw\" + ec_type;\n\n\n\tvar total_cards = Math.ceil((fxo + fxs) / 4);\n\tvar total_price = 0;\n\tfor(var i = 1; i <= total_cards; i++)\n\t{\n\t\t//how many (4fxo, fxs) cards?\n\t\tif(parseInt(fxo/4))\n\t\t{\n\t\t\tindex = card_type + \"|\" + i + \"|\" + ec_type + \"|fxo4|fxs0\";\n\t\t\ttotal_price += parseFloat(hashAnalogPrice[index], 10);\n\t\t\tfxo -= 4;\n\t\t}\n\t\t// is there a mixed card (2,0), (2,2)\n\t\telse if(fxo % 4 && (fxo || fxs))\n\t\t{\n\t\t\tindex = fxs > 0 ? 2 : 0;\n\t\t\tfxs -= index;\n\n\t\t\tindex = \"fxo\" + fxo % 4 + \"|\" + \"fxs\" + index;\n\t\t\tindex = card_type + \"|\" + i + \"|\" + ec_type + \"|\" + index;\n\t\t\ttotal_price += parseFloat(hashAnalogPrice[index], 10);\n\n\t\t\tfxo -= (fxo % 4);\n\t\t}\n\n\t\telse if(parseInt(fxs/4))\n\t\t{\n\t\t\tindex = card_type + \"|\" + i + \"|\" + ec_type + \"|fxo0|fxs4\";\n\t\t\ttotal_price += parseFloat(hashAnalogPrice[index], 10);\n\t\t\tfxs -= 4;\n\t\t}\n\t\telse if(fxs % 4)\n\t\t{\n\t\t\tindex = card_type + \"|\" + i + \"|\" + ec_type + \"|fxo0|fxs2\";\n\t\t\ttotal_price += parseFloat(hashAnalogPrice[index], 10);\n\t\t\tfxs -= (fxs % 4);\n\t\t}\n\t}\n\n\treturn { price : total_price, fxo : dis_fxo, fxs : dis_fxs, ec : dis_ec };\n}",
"function bottomDischargeCalculations(){\r\n\t//1. Assign 0 if input left blank\r\n\tvar assign_zero = [$bottomSpoutDiameter, $bottomSpoutLength];\r\n\t$.each(assign_zero, (index, $item) => {\r\n\t\tassignDefaultIfNull($item, 0);\r\n\t});\r\n\t\r\n\t//2. Unit MF\r\n\tmultiplyAccordingToUnit[$bottomSpoutDiameter, $bottomSpoutLength];\r\n}",
"function update_view() {\n $rqt_form = $('#parametersForm');\n\n // get current RQT form values\n get_form_values();\n\n let $downpayment_value_slider = $rqt_form.find('.down_payment_amt').parents('label').find('.value-slider'),\n $purchase_price_lbl = $rqt_form.find('.purchase_price_lbl');\n\n // purchase calculation\n if ($rqt_form_values.loan_purpose == 0) {\n // don't show 1st time buyer options if the downpayment is above 5%\n let $first_time_buyer = $rqt_form.find('#first_time_buyer');\n if ($rqt_form_values.down_payment_pct > 5) {\n $first_time_buyer.parents('.extra-options').addClass('hidden');\n $first_time_buyer.removeAttr('checked');\n $first_time_buyer.prop('checked', false);\n } else {\n\n $first_time_buyer.parents('.extra-options').removeClass('hidden');\n }\n\n let $lpmi_check = $rqt_form.find('#lpmi_check');\n if ($rqt_form_values.down_payment_pct >= 20) {\n $lpmi_check.parents('.extra-options').addClass('hidden');\n $lpmi_check.prop('checked', false);\n $lpmi_check.removeAttr('checked');\n } else {\n $lpmi_check.parents('.extra-options').removeClass('hidden');\n }\n\n // refinance / cash out refinance\n $rqt_form.find('input.field-group:disabled, input.field-group.disabled').parents('.fields-group').removeClass('disabled');\n $rqt_form.find('.down_payment_amt, .down_payment_pct').removeAttr('disabled');\n\n $downpayment_value_slider.show();\n $purchase_price_lbl.find('span').text(\"Purchase Price\");\n } else {\n $rqt_form.find('.down_payment_amt, .down_payment_pct').prop('disabled', true);\n $rqt_form.find('input.field-group:disabled, input.field-group.disabled').parents('.fields-group').addClass('disabled');\n $downpayment_value_slider.hide();\n $purchase_price_lbl.find('span').text(\"Property Value\");\n }\n\n\n}",
"function sliderValueChange() {\n elemValue = document.getElementById('value');\n var porcessorValue = processorSlider.value;\n var memoryValue = memorySlider.value;\n var storageValue = storageSlider.value;\n //formula to calculate cloud price based on slider value\n finalValue = Number(((((porcessorValue * memoryValue) * 1000) + ((porcessorValue * memoryValue) * storageValue) + ((porcessorValue * memoryValue) * 100)) / 12).toFixed(2));\n if (document.getElementById('cPanel').ej2_instances[0].checked) {\n finalValue = Number((finalValue - 10).toFixed(2));\n }\n if (document.getElementById('discount').ej2_instances[0].checked) {\n finalValue = Number((finalValue - ((finalValue * 25) / 100)).toFixed(2));\n }\n elemValue.innerText = finalValue.toString();\n }",
"function updateBonusses(oldItem, newItem) {\n\n // Because we need the elements multiple times in the next bit we declare them here\n let RegExDigits = /(\\d+)/;\n let stabAcc = document.getElementById(\"stab-accuracy-bonus\");\n let slashAcc = document.getElementById(\"slash-accuracy-bonus\");\n let crushAcc = document.getElementById(\"crush-accuracy-bonus\");\n let magicAcc = document.getElementById(\"magic-accuracy-bonus\");\n let rangedAcc = document.getElementById(\"ranged-accuracy-bonus\");\n let stabDef = document.getElementById(\"stab-defence-bonus\");\n let slashDef = document.getElementById(\"slash-defence-bonus\");\n let crushDef = document.getElementById(\"crush-defence-bonus\");\n let magicDef = document.getElementById(\"magic-defence-bonus\");\n let rangedDef = document.getElementById(\"ranged-defence-bonus\");\n let meleeStrength = document.getElementById(\"melee-strength-bonus\");\n let rangedStrength = document.getElementById(\"ranged-strength-bonus\");\n let magicDamage = document.getElementById(\"magic-damage-bonus\");\n let prayerBonus = document.getElementById(\"prayer-bonus\");\n\n // Change the stats\n // This if must be first in line\n if (Object.keys(selectedItems[newItem.type.toLocaleLowerCase()]).length !== 0) { \n // There also exists a case where the user can switch between item slots and the oldItem and newItem will not be properly alligned.\n // For this we need to look at the selectedItems property.\n\n let type = newItem.type.toLocaleLowerCase();\n // Accuracy\n stabAcc.innerHTML = parseInt(stabAcc.innerHTML) + - selectedItems[type].stabAcc + newItem.stabAcc;\n\n slashAcc.innerHTML = parseInt(slashAcc.innerHTML) + - selectedItems[type].slashAcc + newItem.slashAcc;\n\n crushAcc.innerHTML = parseInt(crushAcc.innerHTML) + - selectedItems[type].crushAcc + newItem.crushAcc;\n\n magicAcc.innerHTML = parseInt(magicAcc.innerHTML) + - selectedItems[type].magicAcc + newItem.magicAcc;\n\n rangedAcc.innerHTML = parseInt(rangedAcc.innerHTML) + - selectedItems[type].rangedAcc + newItem.rangedAcc;\n\n // Defence \n stabDef.innerHTML = parseInt(stabDef.innerHTML) + - selectedItems[type].stabDef + newItem.stabDef;\n\n slashDef.innerHTML = parseInt(slashDef.innerHTML) + - selectedItems[type].slashDef + newItem.slashDef;\n\n crushDef.innerHTML = parseInt(crushDef.innerHTML) + - selectedItems[type].crushDef + newItem.crushDef;\n\n magicDef.innerHTML = parseInt(magicDef.innerHTML) + - selectedItems[type].magicDef + newItem.magicDef;\n\n rangedDef.innerHTML = parseInt(rangedDef.innerHTML) + - selectedItems[type].rangedDef + newItem.rangedDef;\n\n // Strength\n meleeStrength.innerHTML = parseInt(meleeStrength.innerHTML) + - selectedItems[type].strengthBonus + newItem.strengthBonus;\n\n rangedStrength.innerHTML = parseInt(rangedStrength.innerHTML) + - selectedItems[type].rangedStrength + newItem.rangedStrength;\n\n magicDamage.innerHTML = parseInt(magicDamage.innerHTML) + - selectedItems[type].magicStrength + newItem.magicStrength;\n\n prayerBonus.innerHTML = parseInt(prayerBonus.innerHTML) + - selectedItems[type].prayerBonus + newItem.prayerBonus;\n\n } else if (!oldItem) {\n // Stats can be increased by the new item stats without any other calculations\n // Replace the HTML by what was already there + the new stats\n stabAcc.innerHTML = parseInt(stabAcc.innerHTML.match(RegExDigits)) + newItem.stabAcc;\n slashAcc.innerHTML = parseInt(slashAcc.innerHTML.match(RegExDigits)) + newItem.slashAcc;\n crushAcc.innerHTML = parseInt(crushAcc.innerHTML.match(RegExDigits)) + newItem.crushAcc;\n magicAcc.innerHTML = parseInt(magicAcc.innerHTML.match(RegExDigits)) + newItem.magicAcc;\n rangedAcc.innerHTML = parseInt(rangedAcc.innerHTML.match(RegExDigits)) + newItem.rangedAcc;\n stabDef.innerHTML = parseInt(stabDef.innerHTML.match(RegExDigits)) + newItem.stabDef;\n slashDef.innerHTML = parseInt(slashDef.innerHTML.match(RegExDigits)) + newItem.slashDef;\n crushDef.innerHTML = parseInt(crushDef.innerHTML.match(RegExDigits)) + newItem.crushDef;\n magicDef.innerHTML = parseInt(magicDef.innerHTML.match(RegExDigits)) + newItem.magicDef;\n rangedDef.innerHTML = parseInt(rangedDef.innerHTML.match(RegExDigits)) + newItem.rangedDef;\n meleeStrength.innerHTML = parseInt(meleeStrength.innerHTML.match(RegExDigits)) + newItem.strengthBonus;\n rangedStrength.innerHTML = parseInt(rangedStrength.innerHTML.match(RegExDigits)) + newItem.rangedStrength;\n magicDamage.innerHTML = parseInt(magicDamage.innerHTML.match(RegExDigits)) + newItem.magicStrength;\n prayerBonus.innerHTML = parseInt(prayerBonus.innerHTML.match(RegExDigits)) + newItem.prayerBonus;\n\n } else {\n // There was an old item in the slot so have to remove those stats\n // Replace the HTML by what was already there - the old stats + the new stats\n\n // Look I won't be oblivious to the fact that this is a strange block of code, I will explain what one block does. The rest are all the same.\n // Because we try to update the stats to match what it would be with the new item. Therefore we need to remove the old item stats.\n // This can easily be done by doing a \"+ -\" because if the old item stabAcc was -5 and the new one is 0 the calculation would be \"-5 + - -5 + 0\" which results in 0\n // If the old stabAcc was instead 5 and the new one 0 the calculation would be \"5 + - 5 + 0\" which again would result in 0\n // This calculation works for both ends of the spectrum.\n\n // Accuracy\n stabAcc.innerHTML = parseInt(stabAcc.innerHTML) + - oldItem.stabAcc + newItem.stabAcc;\n\n slashAcc.innerHTML = parseInt(slashAcc.innerHTML) + - oldItem.slashAcc + newItem.slashAcc;\n\n crushAcc.innerHTML = parseInt(crushAcc.innerHTML) + - oldItem.crushAcc + newItem.crushAcc;\n\n magicAcc.innerHTML = parseInt(magicAcc.innerHTML) + - oldItem.magicAcc + newItem.magicAcc;\n\n rangedAcc.innerHTML = parseInt(rangedAcc.innerHTML) + - oldItem.rangedAcc + newItem.rangedAcc;\n\n // Defence \n stabDef.innerHTML = parseInt(stabDef.innerHTML) + - oldItem.stabDef + newItem.stabDef;\n\n slashDef.innerHTML = parseInt(slashDef.innerHTML) + - oldItem.slashDef + newItem.slashDef;\n\n crushDef.innerHTML = parseInt(crushDef.innerHTML) + - oldItem.crushDef + newItem.crushDef;\n\n magicDef.innerHTML = parseInt(magicDef.innerHTML) + - oldItem.magicDef + newItem.magicDef;\n\n rangedDef.innerHTML = parseInt(rangedDef.innerHTML) + - oldItem.rangedDef + newItem.rangedDef;\n\n // Strength\n meleeStrength.innerHTML = parseInt(meleeStrength.innerHTML) + - oldItem.strengthBonus + newItem.strengthBonus;\n\n rangedStrength.innerHTML = parseInt(rangedStrength.innerHTML) + - oldItem.rangedStrength + newItem.rangedStrength;\n\n magicDamage.innerHTML = parseInt(magicDamage.innerHTML) + - oldItem.magicStrength + newItem.magicStrength;\n\n prayerBonus.innerHTML = parseInt(prayerBonus.innerHTML) + - oldItem.prayerBonus + newItem.prayerBonus;\n }\n}",
"function onDigitalRunChange() {\n var prizeType = $('input[name=\"prizeRadio\"]:checked').val();\n if(prizeType != 'custom') {\n return;\n }\n\n var value = $('#swDigitalRun').val();\n if(!checkRequired(value) || !checkNumber(value)) {\n showErrors('digital run value is invalid.');\n return;\n }\n\n //fee object\n var projectCategoryId = mainWidget.softwareCompetition.projectHeader.projectCategory.id + \"\";\n var feeObject = softwareContestFees[projectCategoryId];\n\n //update custom cost data\n var contestCost = getContestCost(feeObject, 'custom');\n contestCost.drCost = parseFloat(value);\n fillPrizes();\n}",
"static updateCreditView(entries=[])\n {\n let total = totalDonated(entries);\n\n Pledges.setCreditEntries(entries);\n Pledges.setCreditTotal(total);\n Pledges.setCreditCount(entries.length);\n }",
"function calcRanges(){\n\t\n\n temp = document.forms[0].PDAEquipRange.value;\n //alert(temp);\n cycRange = document.forms[0].cycles.value.replace(\",\", \" - \");\n //alert(\"cyc Range \" +cycRange);\n document.forms[0].PDAEquipRange.value = temp.replace(\"makeupCycles\", cycRange);\n //Update all the makupCycles\n document.forms[0].parseRange.value = document.forms[0].parseRange.value.replace(/makeupCycles/g, cycRange);\n //alert(\"parseRange \"+document.forms[0].parseRange.value);\n //Conductivity Range\n //ConductivityRange = makeupConductivity * CyclesLow \"to\" makeupConductivity * CyclesHigh \n cyclesArray = document.forms[0].cycles.value.split(\",\");\n //alert( \"cycles array\" + cyclesArray[0] );\n // alert( \"cycles array\" + cyclesArray[1] );\n firstpart = cyclesArray[0] * document.forms[0].Conductivity.value;\n // alert(\"first part\"+ firstpart);\n secondpart = cyclesArray[1] * document.forms[0].Conductivity.value;\n //alert(\"second part\"+ secondpart);\n \n\t//12-13-12 trimmed to 2 decimals\n\tconductivityRange = firstpart.toFixed(2) + \" - \" + secondpart.toFixed(2);\n\t\n\t\n\t\n\t\n //alert(\"conductivity range \" + conductivityRange);\n temp = document.forms[0].PDAEquipRange.value;\n //alert(temp);\n document.forms[0].PDAEquipRange.value = temp.replace(\"makeupConductivity\", conductivityRange);\n //temp =document.forms[0].parseRange.value;\n document.forms[0].parseRange.value = document.forms[0].parseRange.value.replace(/makeupConductivity/g, conductivityRange);\n\n\n\n\n //Calcium Range\n CHvalue = document.forms[0].calciumHardness.value;\n firstpart = cyclesArray[0] * CHvalue;\n secondpart = cyclesArray[1] * CHvalue;\n CalHardness = firstpart + \" - \" + secondpart;\n //alert(conductivityRange);\n temp = document.forms[0].PDAEquipRange.value;\n //alert(temp);\n document.forms[0].PDAEquipRange.value = temp.replace(\"makeupCalcium\", CalHardness);\n document.forms[0].parseRange.value = document.forms[0].parseRange.value.replace(/makeupCalcium/g, CalHardness);\n\n\n //Alkalinity\n AlkValue = document.forms[0].alkalinity.value;\n firstpart = cyclesArray[0] * AlkValue;\n secondpart = cyclesArray[1] * AlkValue;\n AlkValue = firstpart.toFixed(2) + \" - \" + secondpart.toFixed(2);\n //alert(conductivityRange);\n temp = document.forms[0].PDAEquipRange.value;\n\n document.forms[0].PDAEquipRange.value = temp.replace(\"makeupM.Alkalinity\", AlkValue);\n document.forms[0].parseRange.value = document.forms[0].parseRange.value.replace(/makeupM.Alkalinity/g, AlkValue);\n\n //Chlorides\n Chlorides = document.forms[0].chlorides.value;\n firstpart = cyclesArray[0] * Chlorides;\n secondpart = cyclesArray[1] * Chlorides;\n Chlorides = firstpart.toFixed(2) + \" - \" + secondpart.toFixed(2);\n //alert(conductivityRange);\n temp = document.forms[0].PDAEquipRange.value;\n //alert(temp);\n document.forms[0].PDAEquipRange.value = temp.replace(\"makeupChloride\", Chlorides);\n document.forms[0].parseRange.value = document.forms[0].parseRange.value.replace(/makeupChloride/g, Chlorides);\n\n\n}",
"function makeThePercentage() {\n // first check if discount amount is visible,\n // if its not, the the rate is already in discount percentage\n // and will be calculated according to current amount\n if ($('#txtDiscountAmt').is(':visible')) {\n //$('#txtDiscountAmt').focusout();\n var _qty = $('#txtQty').val();\n // txtDiscountAmtKeyUpHandler.call(txtDiscountAmt);\n //$('#txtQty').val()\n var _disPerc = 100 * parseFloat($('#txtDiscountAmt').val()) / parseFloat($('#txtCurrentDue').val());\n _disPerc = _disPerc;\n if (isNaN(_disPerc)) {\n _disPerc = '0';\n }\n // set this perctage to text amount\n $('#txtDiscount').val(_disPerc);\n // set the label to current value\n $('#lblDisAmt').text(parseFloat($('#txtDiscountAmt').val()).toFixed(2));\n $('#hdnDiscountValue').text($('#txtDiscountAmt').val());\n // set the hidden recomp value to this\n $('#hdnDisAmtRecomp').val($('#txtDiscountAmt').val());\n }\n}",
"function ResidentialCalculate() {\n $prod_line = $(\"#product-line-cost\").find(\"input[type='radio'][name=OptCheck]:checked\");\n prod_line = $prod_line.val() || 0;\n\n var $NbOfApart = $(\"#AptForm\").find(\"[name=NbDoor_res]\");\n var NbOfApart = $NbOfApart.val();\n var $NbOfFloor = $(\"#AptForm\").find(\"[name=NbFloor_res]\");\n var raw_NbOfFloor = $NbOfFloor.val();\n var $NbBasements_res = $(\"#AptForm\").find(\"[name=NbBasements_res]\");\n var NbBasements_res = $NbBasements_res.val();\n var NbOfFloor = raw_NbOfFloor - NbBasements_res;\n var AvrgDoor = +NbOfApart / +NbOfFloor;\n var NbElev_res = Math.ceil(AvrgDoor) / 6; // Num of elevator\n var NbColumn_res = NbOfFloor / parseInt(\"20\", 10) ;\n var NbRealElev_res = Math.ceil(NbElev_res) * Math.ceil(NbColumn_res) || 0 ; // ceiling number and force but 0 instead of NaN \n var raw_total_Cost = NbRealElev_res * prod_line;\n var roundedCost = raw_total_Cost.toFixed(2); // fix 2 digits after comma\n var total_Cost = Number(roundedCost); // set to number\n var price = total_Cost, // format price to $ CAD \n locale = \"en-CA\",\n currency = \"CAD\";\n \n var formatter = new Intl.NumberFormat (locale, {\n style: \"currency\",\n currency: currency,\n });\n\n var formattedPrice = formatter.format(price);\n\n \n $(\"#elevator-needed\").text(NbRealElev_res);\n $(\"#cost-result\").text(formattedPrice);\n}",
"function checkInputValue() {\n if(!pageVariables.exchangeActive()) {\n if (retrieveElement(\"buy_fee\").isEmpty == 0 && retrieveElement(\"buy_fee\").value === 0 ) {\n changeFee();\n }\n }\n if( pageVariables.exchangeActive() ) {\n if (retrieveElement(\"sell_fee\").isEmpty == 0 && retrieveElement(\"sell_fee\").value === 0 ) {\n changeFee();\n }\n }\n if (retrieveElement(\"buy_fee\").isEmpty == 1) {\n changeFee(reset = 1);\n }\n if (!document.getElementById(\"earned\").value && !document.getElementById(\"earned_percentage\").value && (retrieveElement(\"buy_final_received\").isEmpty == 0 && retrieveElement(\"sell_final_usd\").isEmpty == 0)) {\n if (!pageVariables.exchangeActive()) {\n document.getElementById(\"earned\").value = formatOutput(\"earned\", 0, 1);\n document.getElementById(\"earned_percentage\").value = formatOutput(\"earned_percentage\", 0, 1);\n } else {\n document.getElementById(\"earned\").value = formatOutput(\"earned\", 0);\n document.getElementById(\"earned_percentage\").value = formatOutput(\"earned_percentage\", 0);\n }\n }\n}",
"function updateCSCReqs() {\n 'use strict';\n\n cscReqTotal = $('#cscReqs input:checkbox:checked').length / 2;\n $('#cscReqTotal').html(cscReqTotal.toFixed(1));\n cscReqSat = cscReqTotal >= 5;\n setIcon('cscReqs', cscReqSat);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
d2b.chartPie() returns a d2b pie chart generator | function pie () {
var $$ = {};
var chart = function chart(context) {
context.call($$.chartFrame); // make sure pie, arc, and legend accessors are defined properly
$$.pie.value($$.value).color($$.color).key($$.key);
$$.legend.html($$.label).key($$.key).color($$.color);
$$.tooltip.color(function (d) {
return d3Color.rgb($$.color(d.data)).darker(0.3);
});
var selection = context.selection ? context.selection() : context;
selection.each(function (datum) {
update.call(this, datum, context !== selection ? context : null);
});
selection.dispatch('chart-pie-updated', {
bubbles: true
});
selection.dispatch('chart-updated', {
bubbles: true
});
return chart;
}; // percent formater
var percent = d3Format.format('.0%'); // configure model properties
base(chart, $$).addProp('chartFrame', chartFrame().legendEnabled(true).breadcrumbsEnabled(false)).addProp('legend', legend().clickable(true).dblclickable(true)).addProp('key', function (d) {
return d.label;
}).addProp('pie', svgPie()).addProp('tooltip', tooltip().followMouse(true).html(function (d) {
return "<b>".concat($$.label(d.data), "</b>: ").concat($$.value(d.data), " (").concat(percent(d.__percent__), ")");
})).addPropFunctor('values', function (d) {
return d;
}).addPropFunctor('duration', 250).addPropFunctor('donutRatio', 0).addPropFunctor('at', 'center center').addPropFunctor('showPercent', function (d, total) {
return $$.value(d) / total > 0.03;
}).addPropFunctor('radius', function (d, w, h) {
return Math.min(w, h) / 2;
}).addPropFunctor('color', function (d) {
return color(d.label);
}).addPropFunctor('value', function (d) {
return d.value;
}).addPropFunctor('arcLabel', null).addPropFunctor('label', function (d) {
return d.label;
}).addAdvancedConfig(chartPieAdvanced); // // The advanced method is an alternative to calling the chart base method directly.
// // The method will provide additional chart configuration before rendering through
// // the `chartPieAdvanced` function.
// chart.advanced = function (context) {
// const selection = (context.selection)? context.selection() : context;
// const transition = selection !== context;
// selection.each(function (datum) {
// if (datum.onChartUpdated) d3.select(this).on('chart-updated', datum.onChartUpdated);
// let el = d3.select(this).selectAll('.d2b-chart-advanced').data([chartPieAdvanced(chart, datum)]);
// const elEnter = el.enter().append('div').attr('class', 'd2b-chart-advanced');
// el = elEnter.merge(el);
// const elTransition = transition ? el.transition(context) : el;
// elTransition.call(chart);
// });
// };
// update chart
function update(datum, transition) {
var el = d3Selection.select(this),
selection = el.select('.d2b-chart-container'),
size = selection.node().__size__,
radius = $$.radius(datum, size.width, size.height),
donutRatio = $$.donutRatio(datum),
legendEmpty = $$.legend.empty(),
values = $$.values(datum),
filtered = values.filter(function (d) {
return !legendEmpty(d);
});
$$.pie.values(filtered);
$$.legend.values(values); // legend functionality
var legend = el.select('.d2b-legend-container');
(transition ? legend.transition(transition) : legend).call($$.legend);
legend.on('change', function () {
return el.transition().duration($$.duration(datum)).call(chart);
}).selectAll('.d2b-legend-item').on('mouseover', function (d) {
arcGrow.call(this, el, d, 1.03);
}).on('mouseout', function (d) {
arcGrow.call(this, el, d);
}); // get pie total
var total = d3Array.sum(filtered, function (d) {
return $$.value(d);
}); // select and enter pie chart 'g' element.
var chartGroup = selection.selectAll('.d2b-pie-chart').data([filtered]);
var chartGroupEnter = chartGroup.enter().append('g').attr('class', 'd2b-pie-chart');
chartGroup = chartGroup.merge(chartGroupEnter);
if (transition) chartGroup = chartGroup.transition(transition);
$$.pie.arc().innerRadius(radius * donutRatio).outerRadius(radius);
chartGroup.call($$.pie);
var arcGroup = selection.selectAll('.d2b-pie-arc').each(function (d) {
// store inner and outer radii so that they can be used for hover
// transitions
d.__innerRadius__ = radius * donutRatio;
d.__outerRadius__ = radius; // store percent for use with the tooltip
d.__percent__ = d.value / total;
}).on('mouseover', function (d) {
arcGrow.call(this, el, d.data, 1.03);
}).on('mouseout', function (d) {
arcGrow.call(this, el, d.data);
}).call($$.tooltip);
var arcPercent = arcGroup.selectAll('.d2b-pie-arc-percent').data(function (d) {
return [d];
});
arcPercent.enter().append('g').attr('class', 'd2b-pie-arc-percent').append('text').attr('y', 6);
arcGroup.each(function () {
var elem = d3Selection.select(this),
current = elem.select('.d2b-pie-arc path').node().current,
percentGroup = elem.select('.d2b-pie-arc-percent'),
percentText = percentGroup.select('text').node();
percentGroup.node().current = current;
percentText.current = percentText.current || 0;
});
if (transition) {
arcGroup = arcGroup.each(function (d) {
d.transitioning = true;
}).transition(transition).on('end', function (d) {
d.transitioning = false;
});
}
var arcText = arcGroup.select('.d2b-pie-arc-percent').call(tweenCentroid, $$.pie.arc()).select('text');
arcText.each(function (d) {
var arcLabel = $$.arcLabel(d.data);
var text = d3Selection.select(this);
if (transition) text = text.transition(transition); // if arc label is non-null use percents
if (arcLabel) {
text.text(arcLabel);
} else {
text.call(tweenNumber, $$.value(d.data) / total, percent).style('opacity', function (d) {
return $$.showPercent.call(this, d.data, total) ? 1 : 0;
});
}
});
var coords = chartCoords(datum, radius, size);
if (isNaN(coords.x) || isNaN(coords.y)) return;
chartGroupEnter.attr('transform', "translate(".concat(coords.x, ", ").concat(coords.y, ")"));
chartGroup.attr('transform', "translate(".concat(coords.x, ", ").concat(coords.y, ")"));
} // Position the pie chart according to the 'at' string (e.g. 'center left',
// 'top center', ..). Unless at is an object like {x: , y:}, then position
// according to these coordinates.
function chartCoords(datum, radius, size) {
var coords = $$.at(datum, size.width, size.height, radius);
if (_typeof(coords) !== 'object') {
coords = coords.split(' ');
var at = {
x: coords[1],
y: coords[0]
};
coords = {};
switch (at.x) {
case 'left':
coords.x = radius;
break;
case 'center':
case 'middle':
coords.x = size.width / 2;
break;
case 'right':
default:
coords.x = size.width - radius;
}
switch (at.y) {
case 'bottom':
coords.y = size.height - radius;
break;
case 'center':
case 'middle':
coords.y = size.height / 2;
break;
case 'top':
default:
coords.y = radius;
}
}
return coords;
}
function arcGrow(el, d) {
var multiplier = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
var arc = $$.pie.arc();
var transitioning = false;
var arcSvg = el.selectAll('.d2b-pie-arc').filter(function (dd) {
return dd.data === d;
}).each(function (d) {
transitioning = transitioning || d.transitioning;
d.outerRadius = d.__outerRadius__ * multiplier;
d.innerRadius = d.__innerRadius__;
});
if (transitioning) return;
arcSvg.select('path').transition().duration(100).call(tweenArc, arc);
}
return chart;
} | [
"function generatePieChart() {\n var pieChartOutline = {\n \t\"header\": {\n \t\t\"title\": {\n \t\t\t\"text\": \"Inheritance\",\n \t\t\t\"fontSize\": 20,\n \t\t\t\"font\": \"Helvetica Neue\",\n // \"font-weight\": \"bold\",\n \t\t},\n \t\t\"subtitle\": {\n \"text\": \"\",\n \"color\": \"#ffffff\",\n \t\t\t\"fontSize\": 12,\n \t\t\t\"font\": \"open sans\"\n \t\t},\n \t\t\"titleSubtitlePadding\": 9\n \t},\n \t\"footer\": {\n \"color\": \"#999999\",\n \t\t\"fontSize\": 15,\n \t\t\"font\": \"open sans\",\n \t\t\"location\": \"\"\n \t},\n \t\"size\": {\n \"canvasHeight\": 350,\n \t\t\"canvasWidth\": 450,\n \t\t\"pieOuterRadius\": \"90%\"\n \t},\n \t\"data\": {\n \t\t\"sortOrder\": \"value-desc\",\n \t\t\"content\": [\n \t\t\t{\n \t\t\t\t\"label\": \"Inherited\",\n \t\t\t\t\"value\": $(\".source_data\").data(\"inherited\"),\n \t\t\t\t\"color\": \"#2484c1\"\n \t\t\t},\n \t\t\t{\n \t\t\t\t\"label\": \"De novo\",\n \t\t\t\t\"value\": $(\".source_data\").data(\"denovo\"),\n \t\t\t\t\"color\": \"#71afd7\"\n \t\t\t},\n \t\t\t{\n \t\t\t\t\"label\": \"Unknown\",\n \t\t\t\t\"value\": $(\".source_data\").data(\"unknown\"),\n \t\t\t\t\"color\": \"#4daa4b\"\n \t\t\t}\n \t\t]\n \t},\n \"labels\": {\n\t\t\"outer\": {\n\t\t\t\"pieDistance\": 32\n\t\t},\n\t\t\"inner\": {\n \"format\": \"value\",\n\t\t\t\"hideWhenLessThanPercentage\": 3\n\t\t},\n\t\t\"mainLabel\": {\n\t\t\t\"fontSize\": 16\n\t\t},\n\t\t\"percentage\": {\n\t\t\t\"color\": \"#ffffff\",\n\t\t\t\"decimalPlaces\": 0,\n \"fontSize\": 14\n\t\t},\n\t\t\"value\": {\n\t\t\t\"color\": \"#ffffff\",\n\t\t\t\"fontSize\": 14\n\t\t},\n\t\t\"lines\": {\n\t\t\t\"enabled\": true\n\t\t},\n\t\t\"truncation\": {\n\t\t\t\"enabled\": true\n\t\t}\n\t},\n\t\"effects\": {\n // Remove to re-enable effects\n \"load\": { //this\n\t\t\t\"effect\": \"none\" //this\n\t\t}, //this\n\t\t\"pullOutSegmentOnClick\": {\n\t\t\t// \"effect\": \"linear\", // put this back in\n \"effect\": \"none\", //this\n \"speed\": 400,\n\t\t\t\"size\": 8\n\t\t}, // this (only the comma)\n \"highlightSegmentOnMouseover\": false, //this\n\t\t\"highlightLuminosity\": -0.5 //this\n\t},\n\t\"misc\": {\n\t\t\"gradient\": {\n\t\t\t\"enabled\": true,\n\t\t\t\"percentage\": 100\n\t\t}\n\t}\n};\n\n // Scale down the pie chart, title, and labels if the screen is narrower than 580 pixels\n if (window.innerWidth <= 580) {\n pieChartOutline.size.canvasWidth = parseInt(225 * window.innerWidth / 580 + 225);\n pieChartOutline.size.canvasHeight = parseInt(175 * window.innerWidth / 580 + 175);\n pieChartOutline.header.title.fontSize = parseInt(10 * window.innerWidth / 580 + 10);\n pieChartOutline.labels.mainLabel.fontSize = parseInt(8 * window.innerWidth / 580 + 8);\n pieChartOutline.labels.value.fontSize = parseInt(7 * window.innerWidth / 580 + 7);\n }\n\n // Generate the pie chart using d3.pie\n var pie = new d3pie(\"pieChart\", pieChartOutline);\n }",
"function drawPie() {\n\t\tvar lastend = 0; \n\t\tvar myTotal = getTotal();\n\t\tmyData = arraySplittedYTwo;\n\t\tc.clearRect(0, 0, graph.width, graph.height); //set canvas to empty on start\n\t\tvar myColor = [\"#ECD078\",\"#D95B43\",\"#C02942\",\"#542437\",\"#53777A\"]; //color fills for the data\n\n\t\tfor (var i = 0; i < myData.length; i++) {\n\t\t\tc.fillStyle = myColor[i];\n\t\t\tc.beginPath();\n\t\t\tc.moveTo(200,150);\n\t\t\tc.arc(200,150,150,lastend,lastend+(Math.PI*2*(myData[i]/myTotal)),false);\n\t\t\t\n\t\t\tc.lineTo(200,150);\n\t\t\tc.fill();\n\t\t\tlastend += Math.PI*2*(myData[i]/myTotal);\n\t\t}\n\n\t\tdocument.getElementById('chartGenerator').disabled = true; //disabled chartGenerator button\n\t}",
"function generatePieGraph(canvas, chartobj, duration){\n\t\n\tif(canvas && canvas.tagName == 'CANVAS' && chartobj){\n\t\t\n\t\t\n\t\t//DEFINITIONS - local variables\n\t\t//canvas variables and timer definitions\n\t\tvar context = canvas.getContext('2d'),\n\t\t canvaswidth = canvas.getAttribute('width'),\n\t\t canvasheight = canvas.getAttribute('height'),\n\t\t stoploop = false,\n\t\t starttime = new Date().getTime();\n\t\t\t\t \n\t\t//define transition times to introduce chart, calculate 't' coefficient for each transition\n\t\tvar transtime1 = 1000,\n\t\t transtime2 = 500,\n\t\t t1 = (duration <= transtime1) ? EasingFunctions.easeOutQuart(duration/transtime1) : 1,\n\t\t t2 = 0,\n\t\t t3 = 0;\n\t\tif(t1 == 1){\n\t\t\tt2 = (duration >= transtime1 && duration <= transtime1+transtime2) ? EasingFunctions.easeInCubic((duration-transtime1)/transtime2) : 1;\n\t\t\tt3 = (duration >= transtime1 && duration <= transtime1+transtime2) ? EasingFunctions.easeOutCubic((duration-transtime1)/transtime2) : 1;\n\t\t}\n\t\t \n\t\t//determine general placement variables to draw pie chart\n\t\tvar radius = (chartobj.properties.size/2),\n\t\t growradius = radius*t1,\n\t\t cX = (chartobj.properties.offsetX == 'center') ? canvaswidth/2 : Number(chartobj.properties.offsetX)+radius || 0,\n\t\t cY = (chartobj.properties.offsetY == 'center') ? canvasheight/2 : Number(chartobj.properties.offsetY)+radius || 0,\n\t\t totalvalue = 0;\n\t\t \n\t\t \n\t\t \n\t\t//get total value count for the chart - execute immediately\n\t\t(function getTotalValue(){\n\t\t\tfor(var i=0; i<chartobj.data.length; i++){\n\t\t\t\ttotalvalue += parseFloat(chartobj.data[i].value);\n\t\t\t}\n\t\t}.call(this));\n\t\t \n\t\t \n\t\t \n\t\t//draw a wedge based on pre-calculated and predefined properties\n\t\tif(t1) renderWedges();\n\t\tif(t2) renderWedgeLabels();\n\t\t\n\t\t\n\t\t\n\t\t//iterates through all data objects in chartobj to draw each pie wedge based on that data\n\t\tfunction renderWedges(){\n\t\t\t\t\n\t\t\t//reset total degree count\n\t\t\tvar totaldegreesdrawn = 0;\n\t\t\t\n\t\t\t//loop through all wedges for rendering\n\t\t\tfor(var i=0; i<chartobj.data.length; i++){\n\t\t\t\t\n\t\t\t\t//calculate wedge variables\n\t\t\t\tvar degrees = chartobj.data[i].value/totalvalue * 360,\n\t\t\t\t rads = degrees * (Math.PI/180),\n\t\t\t\t sAngle = (chartobj.properties.startAngle*t1 + totaldegreesdrawn) * (Math.PI/180),\n\t\t\t\t eAngle = sAngle+rads*t1,\n\t\t\t\t wedgeradius = growradius * chartobj.data[i].sizemod || growradius;\n\t\t\t\t\n\t\t\t\t//define initial context styling, create new path\n\t\t\t\tcontext.globalAlpha = t1;\n\t\t\t\tcontext.fillStyle = chartobj.data[i].fillColor;\n\t\t\t\tcontext.strokeStyle = chartobj.data[i].strokeColor || 'rgba(0,0,0,0)';\n\t\t\t\tcontext.lineWidth = chartobj.data[i].strokeWidth || 0;\n\t\t\t\tcontext.lineCap = chartobj.data[i].strokeCap || 'round';\n\t\t\t\tcontext.lineJoin = 'miter';\n\t\t\t\t\n\t\t\t\t//draw wedge\n\t\t\t\tcontext.save();\n\t\t\t\tcontext.beginPath();\n\t\t\t\tcontext.moveTo(cX,cY);\n\t\t\t\tcontext.arc(cX, cY, wedgeradius, sAngle, eAngle, false);\n\t\t\t\tcontext.lineTo(cX,cY);\n\t\t\t\t\n\t\t\t\t//render order as defined by chartobj property setting\n\t\t\t\tif(chartobj.properties.renderPriority == 'fill'){\n\t\t\t\t\tcontext.stroke();\n\t\t\t\t\tcontext.fill();\n\t\t\t\t}else{\n\t\t\t\t\tcontext.fill();\n\t\t\t\t\tcontext.stroke();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//restore context\n\t\t\t\tcontext.restore();\n\t\t\t\t\n\t\t\t\t//increment counter keeping track of total degrees drawn\n\t\t\t\ttotaldegreesdrawn+=degrees;\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\t\n\t\t//iterates through all data objects in chartobj to draw each pie wedge's label based on that data\n\t\t//this has to go through a separate iteration in order to draw ontop of the wedge slices properly\n\t\tfunction renderWedgeLabels(){\n\t\t\t\n\t\t\tif(chartobj.properties.drawLabels){\n\t\t\t\t//reset total degree count\n\t\t\t\tvar totaldegreesdrawn = 0;\n\t\t\t\t\n\t\t\t\t//loop through all wedge data to render label information\n\t\t\t\tfor(var i=0; i<chartobj.data.length; i++){\n\t\t\t\t\t\n\t\t\t\t\tvar data = chartobj.data[i];\n\t\t\t\t\t//calculate wedge variables\n\t\t\t\t\tvar degrees = data.value/totalvalue * 360,\n\t\t\t\t\t rads = degrees * (Math.PI/180),\n\t\t\t\t\t sAngle = (chartobj.properties.startAngle*t1 + totaldegreesdrawn) * (Math.PI/180),\n\t\t\t\t\t eAngle = sAngle+rads*t1,\n\t\t\t\t\t mAngle = eAngle - ((eAngle-sAngle)/2),\n\t\t\t\t\t fontsize = chartobj.properties.fontSize || 16;\n\t\t\t\t\t weightedfontscale = (chartobj.properties.labelScale == 'relative') ? ( fontsize * ((((data.value/totalvalue) ) + .75)) * t3).toFixed(1) : fontsize,\n\t\t\t\t\t extendlabel = (chartobj.properties.extendSmallLabels && (data.value/totalvalue)*100 < 5) ? true : false,\n\t\t\t\t\t distance = (extendlabel) ? radius*1.4 : radius*.75,\n\t\t\t\t\t label = ((data.value/totalvalue)*100).toFixed(1) + '%';\n\t\t\t\t\t label = (data.displaylabel) ? data.label + ' ('+label+')' : label; \n\t\t\t\t\t \n\t\t\t\t\t \n\t\t\t\t\t//render label text\n\t\t\t\t\tcontext.save();\n\t\t\t\t\tcontext.fillStyle = data.labelColor || chartobj.properties.labelColor || 'black';\n\t\t\t\t\tcontext.strokeStyle = 'rgba(0,0,0,.66)';\n\t\t\t\t\tcontext.lineWidth = .5;\n\t\t\t\t\tcontext.globalAlpha = t2;\n\t\t\t\t\tcontext.font = weightedfontscale + 'pt Karbon-Light';\n\t\t\t\t\tcontext.textAlign = 'center';\n\t\t\t\t\tcontext.textBaseline = 'alphabetic';\n\t\t\t\t\tcontext.fillText(label, cX + Math.cos(mAngle)*distance, (weightedfontscale/2) + cY + Math.sin(mAngle)*distance);\n\t\t\t\t\t\n\t\t\t\t\tif(extendlabel){\n\t\t\t\t\t\t\n\t\t\t\t\t\tvar cX_label = cX + Math.cos(mAngle)*distance,\n\t\t\t\t\t\t cY_label = cY + Math.sin(mAngle)*distance,\n\t\t\t\t\t\t eX_label = cX + Math.cos(mAngle)*radius*.9,\n\t\t\t\t\t\t eY_label = cY + Math.sin(mAngle)*radius*.9,\n\t\t\t\t\t\t grad2 = context.createLinearGradient(cX_label,cY_label,eX_label,eY_label);\n\t\t\t\t\t\t grad2.addColorStop(0, 'rgba(0,0,0,0)');\n\t\t\t\t\t\t grad2.addColorStop(1, 'rgba(0,0,0,.75)');\n\t\t\t\t\t\t \n\t\t\t\t\t\tcontext.strokeStyle = grad2;\n\t\t\t\t\t\tcontext.beginPath();\n\t\t\t\t\t\tcontext.moveTo(cX_label, cY_label);\n\t\t\t\t\t\tcontext.lineTo(eX_label, eY_label);\n\t\t\t\t\t\tcontext.stroke();\n\t\t\t\t\t}\n\t\t\t\t\tcontext.restore();\n\t\t\t\t\t\n\t\t\t\t\t//increment counter keeping track of total degrees drawn\n\t\t\t\t\ttotaldegreesdrawn+=degrees;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\t\n\t\t\t\n\t\t//function will 'knockout' the center of the pie chart white/negative space.\n\t\tif(chartobj.properties.knockout) {(function knockoutPieCenter(){\n\t\t\t\n\t\t\tvar sizemod = chartobj.properties.knockoutScale || .5;\n\t\t\tcontext.fillStyle = 'white';\n\t\t\tcontext.globalAlpha = 1;\n\t\t\tcontext.beginPath();\n\t\t\tcontext.arc(cX, cY, growradius*sizemod, 0, 7, false);\n\t\t\tcontext.lineTo(cX,cY);\n\t\t\tcontext.fill();\n\t\t\tcontext.restore();\n\t\t\t\n\t\t}.call(this))};\n\t\t\n\t\t\n\t\t//return true or false based on whether all transitions have reported finished or not\n\t\tif(t1 == 1 && t2 == 1) return true;\n\t\telse return false;\n\t\t\t\n\t}\n\t\n}",
"function createPieChart(chartContainer, chartTitle, dataContent, canvasHeight, outerLabelsColor){\r\n\t$(chartContainer).css('height', canvasHeight + 'px');\r\n\tvar pie = new d3pie(chartContainer, {\r\n\t\t\"header\": {\r\n\t\t\t\"title\": {\r\n\t\t\t\t\"text\": chartTitle,\r\n\t\t\t\t\"fontSize\": 24,\r\n\t\t\t\t\"font\": \"open sans\"\r\n\t\t\t}\r\n\t\t},\r\n\t\t\"size\": {\r\n\t\t\t\"canvasWidth\": $(chartContainer).width()*0.9,\r\n\t\t\t\"canvasHeight\": canvasHeight * 0.8\r\n\t\t},\r\n\t\t\"data\": {\r\n\t\t\t\"sortOrder\": \"value-desc\",\r\n\t\t\t\"content\": dataContent\r\n\t\t},\r\n\t\t\"tooltips\": {\r\n\t\t\t\"enabled\": true,\r\n\t\t\t\"type\": \"placeholder\",\r\n\t\t\t\"string\": \"{label}, {value}, {percentage}%\",\r\n\t\t\t\"styles\": {\r\n\t\t\t\t\"fadeInSpeed\": 500,\r\n\t\t\t\t\"backgroundColor\": \"#00cc99\",\r\n\t\t\t\t\"backgroundOpacity\": 0.9,\r\n\t\t\t\t\"color\": \"#ffffcc\",\r\n\t\t\t\t\"borderRadius\": 0,\r\n\t\t\t\t\"font\": \"verdana\",\r\n\t\t\t\t\"fontSize\": 14,\r\n\t\t\t\t\"padding\": 20\r\n\t\t\t}\r\n\t\t},\r\n\t\t\"labels\": {\r\n\t\t\t\"outer\": {\r\n\t\t\t\t\"pieDistance\": 12,\r\n\t\t\t\t\"fill\": outerLabelsColor\r\n\t\t\t},\r\n\t\t\t\"inner\": {\r\n\t\t\t\t\"hideWhenLessThanPercentage\": 1\r\n\t\t\t},\r\n\t\t\t\"mainLabel\": {\r\n\t\t\t\t\"fontSize\": 12\r\n\t\t\t},\r\n\t\t\t\"percentage\": {\r\n\t\t\t\tfontSize: 11\r\n\t\t\t},\r\n\t\t\t\"percentage\": {\r\n\t\t\t\t\"color\": \"#ffffff\",\r\n\t\t\t\t\"decimalPlaces\": 0\r\n\t\t\t},\r\n\t\t\t\"value\": {\r\n\t\t\t\t\"color\": \"#adadad\",\r\n\t\t\t\t\"fontSize\": 11\r\n\t\t\t},\r\n\t\t\t\"lines\": {\r\n\t\t\t\t\"enabled\": true\r\n\t\t\t},\r\n\t\t},\r\n\t\t\"effects\": {\r\n\t\t\t\"pullOutSegmentOnClick\": {\r\n\t\t\t\t\"effect\": \"linear\",\r\n\t\t\t\t\"speed\": 400,\r\n\t\t\t\t\"size\": 8\r\n\t\t\t}\r\n\t\t},\r\n\t\t\"misc\": {\r\n\t\t\t\"gradient\": {\r\n\t\t\t\t\"enabled\": true,\r\n\t\t\t\t\"percentage\": 100\r\n\t\t\t}\r\n\t\t}\r\n\t});\r\n}",
"function generatePieChart(req, res) {\n //TODO: validations\n var graphData = {\n type:'pie',\n title : req.param('graph-title-pie'),\n xLabel : '',\n yLabel : '',\n xDataType : req.param('data-name-pie'),\n yDataType : req.param('data-value-pie')\n };\n populateGraphData(graphData,'', function (err, graphData) {\n return res.json(graphData);\n });\n}",
"function makePieChart(json) {\n var pie = new d3pie(\"#pieChart\", {\n data: {\n content: json\n },\n size: {\n canvasHeight: 400,\n canvasWidth: 400\n \t },\n labels: {\n outer: {\n pieDistance: 20\n },\n mainLabel: {\n fontSize: 13,\n font: \"verdana\"\n },\n percentage: {\n color: \"#ffffff\",\n decimalPlaces: 2, \n fontSize: 20\n\n\n },\n value: {\n color: \"#FFFFFF\",\n fontSize: 18\n },\n lines: {\n enabled: true\n },\n truncation: {\n enabled: false\n }\n }\n });\n}",
"function drawPieChart() {\n\n const data = google.visualization.arrayToDataTable([\n ['Receita', 'Valor'],\n ['Carro A', 8],\n ['Carro B', 4],\n ['Moto A', 3],\n ['Moto B', 3]\n ]);\n\n const options = {\n title: 'Receita (detalhamento)',\n fontSize: 12,\n fontName:'Helvetica, sans-serif',\n height: 250,\n width: 450,\n slices: {\n 0: { color: '#00796b' },\n 1: { color: '#009688' },\n 2: { color: '#4db6ac' },\n 3: { color: '#b2dfdb' }\n }\n };\n\n const chart = new google.visualization.PieChart(document.getElementById('piechart'));\n\n chart.draw(data, options);\n}",
"function make_pie_chart(percent, divContainerForChart, color1, color2){\r\n\r\n\t// Remoeves the pie charts created so tehy are not displayed next time. This\r\n\t// allow the user to see the current prie chart and not the previous one\r\n\t$(divContainerForChart).empty();\r\n\r\n\t// Create the Pie Chart\r\n\t(function(d3) {\r\n\r\n 'use strict';\r\n\r\n var dataset = [\r\n { label: 'Risk', count: percent },\r\n { label: 'Total', count: 100-percent },\r\n ];\r\n\r\n var width = 206;\r\n var height = 206;\r\n var radius = Math.min(width, height) / 2;\r\n\r\n var color = d3.scaleOrdinal().range([color1,color2]);\r\n\r\n var svg = d3.select(divContainerForChart)\r\n\t\t\t\t\t.append(\"svg\")\r\n .attr('width', width)\r\n .attr('height', height)\r\n\t \t\t\t.attr('viewBox', '0 0 ' + width + \" \" + height)\r\n .append('g')\r\n .attr('transform', 'translate(' + (width / 2) +\r\n ',' + (height / 2) + ')');\r\n\r\n var arc = d3.arc()\r\n .innerRadius(0)\r\n .outerRadius(radius);\r\n\r\n var pie = d3.pie()\r\n .value(function(d) { return d.count; })\r\n .sort(null);\r\n\r\n var path = svg.selectAll('path')\r\n .data(pie(dataset))\r\n .enter()\r\n .append('path')\r\n .attr('d', arc)\r\n .attr('fill', function(d) {\r\n return color(d.data.label);\r\n });\r\n\r\n })(window.d3);\r\n}",
"function createPieChart(chartContainer, chartTitle, dataContent, canvasHeight, outerLabelsColor){\n\t$(chartContainer).css('height', canvasHeight + 'px');\n\tvar pie = new d3pie(chartContainer, {\n\t\t\"header\": {\n\t\t\t\"title\": {\n\t\t\t\t\"text\": chartTitle,\n\t\t\t\t\"fontSize\": 24,\n\t\t\t\t\"font\": \"open sans\"\n\t\t\t}\n\t\t},\n\t\t\"size\": {\n\t\t\t\"canvasWidth\": $(chartContainer).width()*0.9,\n\t\t\t\"canvasHeight\": canvasHeight * 0.8\n\t\t},\n\t\t\"data\": {\n\t\t\t\"sortOrder\": \"value-desc\",\n\t\t\t\"content\": dataContent\n\t\t},\n\t\t\"tooltips\": {\n\t\t\t\"enabled\": true,\n\t\t\t\"type\": \"placeholder\",\n\t\t\t\"string\": \"{label}, {value}, {percentage}%\",\n\t\t\t\"styles\": {\n\t\t\t\t\"fadeInSpeed\": 500,\n\t\t\t\t\"backgroundColor\": \"#00cc99\",\n\t\t\t\t\"backgroundOpacity\": 0.9,\n\t\t\t\t\"color\": \"#ffffcc\",\n\t\t\t\t\"borderRadius\": 4, //Changed by Allan Clayton\n\t\t\t\t\"font\": \"verdana\",\n\t\t\t\t\"fontSize\": 14,\n\t\t\t\t\"padding\": 4 //Changed by Allan Clayton\n\t\t\t}\n\t\t},\n\t\t\"labels\": {\n\t\t\t\"outer\": {\n\t\t\t\t\"format\": \"none\",\n\t\t\t\t\"pieDistance\": 12,\n\t\t\t},\n\t\t\t\"inner\": {\n\t\t\t\t\"format\": \"percentage\",\n\t\t\t\t\"hideWhenLessThanPercentage\": 6 //Changed by Allan Clayton\n\t\t\t},\n\t\t\t\"mainLabel\": {\n\t\t\t\t\"fontSize\": 16\n\t\t\t},\n\t\t\t\"percentage\": {\n\t\t\t\t\"color\": \"#ffffff\",\n\t\t\t\t\"decimalPlaces\": 0,\n\t\t\t\t\"fontSize\": 11\n\t\t\t},\n\t\t\t\"value\": {\n\t\t\t\t\"color\": \"#adadad\",\n\t\t\t\t\"fontSize\": 11\n\t\t\t},\n\t\t\t\"lines\": {\n\t\t\t\t\"enabled\": true\n\t\t\t},\n\t\t},\n\t\t\"effects\": {\n\t\t\t\"pullOutSegmentOnClick\": {\n\t\t\t\t\"effect\": \"linear\",\n\t\t\t\t\"speed\": 400,\n\t\t\t\t\"size\": 8\n\t\t\t}\n\t\t},\n\t\t\"misc\": {\n\t\t\t\"gradient\": {\n\t\t\t\t\"enabled\": true,\n\t\t\t\t\"percentage\": 100\n\t\t\t}\n\t\t}\n\t});\n}",
"function drawPieChart(canvas) {\n\t// HACK TO INSERT COLOR - FIND A BETTER WAY\n\tvar hack_color = [\"#FF0000\", \"#00FF00\", \"#0000FF\", \"#FF00FF\", \"#FF9900\", \"#C0C0C0\"];\n\tfor (var i=0; i<this.data.length; i++) {\n\t\tthis.data[i].color = hack_color[i];\n\t}\n\t// END HACK TO INSERT COLOR\n\tvar ctx = canvas.getContext(\"2d\");\n var lastend = 0;\n\tvar total = 0;\n\n\tctx.clearRect(0, 0, canvas.width, canvas.height);\n\tfor (var i = 0; i < this.data.length; i++) {\n\t\ttotal += this.data[i].value;\n\t}\n\tif (total == 0) {\n\t\treturn;\n\t}\n\t\n\tfor (var i = 0; i < this.data.length; i++) {\n\t\tctx.fillStyle = this.data[i].color;\n\t\tctx.beginPath();\n\t\tctx.moveTo(canvas.width/2, canvas.height/2);\n\t\tctx.arc(canvas.width/2, canvas.height/2, canvas.height/2, lastend,lastend+\n\t \t\t(Math.PI*2*(this.data[i].value / total)),false);\n\t\tctx.lineTo(canvas.width/2, canvas.height/2);\n\t\tctx.fill();\n\t\tlastend += Math.PI*2*(this.data[i].value / total);\n\t}\n\t\n}",
"function drawChart() {\n\t\t// get the data from the table\n\t\t$(\".pie-chartify\").each( function(i,e){\n\t\t\tvar id = \"chart-\" + i,\n\t\t\t\tdt = dataTableFromTable( e ),\n\t\t\t\topt = {\n\t\t\t\t\t'pieSliceText': 'none',\n\t\t\t\t\t'tooltip': {\n\t\t\t\t\t\t'text': 'percentage'\n\t\t\t\t\t},\n\t\t\t\t\t'chartArea': {\n\t\t\t\t\t'width': '90%',\n\t\t\t\t\t\t'height': '90%'\n\t\t\t\t\t},\n\t\t\t\t\t'width': 600,\n\t\t\t\t\t'height': 400,\n\t\t\t\t\t'legend': {\n\t\t\t\t\t\tposition: 'labeled'\n\t\t\t\t\t},\n\t\t\t\t\t'fontName': 'Helvetica',\n\t\t\t\t\t'fontSize': 14,\n\t\t\t\t\t\"is3D\": true\n\t\t\t\t},\n\t\t\t\tc;\n\t\t\t$(this).after(\"<div class='piechart' id='\" + id + \"'></div>\");\n\n\t\t\tc = new google.visualization.PieChart(\n\t\t\t\tdocument.getElementById(id)\n\t\t\t);\n\t\t\tc.draw(dt, opt);\n\t\t});\n\t}",
"function drawpiecharts() {\n var iChart;\n var canvases = document.getElementsByClassName(\"piechart\");\n var ncanvases = Math.min(canvases.length, arguments.length);\n for (iChart = 0; iChart < ncanvases; iChart++) {\n var data = arguments[iChart];\n data.sort(function(a, b){return b-a});\n var total = 0;\n for (var point in data)\n total += data[point];\n\n var canvas = canvases[iChart];\n var context = canvas.getContext(\"2d\");\n var centerX = canvas.width/2;\n var centerY = canvas.height/2;\n var radius = Math.min(centerX, centerY) * total/(10 + total);\n var currangle = 0;\n\n var ndivisions = Math.min(colors.length, data.length);\n var iDivision;\n for (iDivision = 0; iDivision < ndivisions; iDivision++) {\n var nextangle = currangle + 2 * Math.PI * data[iDivision]/total;\n context.beginPath();\n context.arc(centerX, centerY, radius, currangle, nextangle);\n context.lineTo(centerX, centerY);\n context.fillStyle = colors[iDivision];\n context.fill();\n currangle = nextangle;\n }\n }\n}",
"function createCrashPerPieChart(){\n $scope.pieChart2 = {\n chart: {\n type: 'pieChart',\n height: 500,\n x: function(d){return d.key;},\n y: function(d){return d.y;},\n showLabels: true,\n duration: 500,\n labelThreshold: 0.01,\n labelSunbeamLayout: true,\n legend: {\n margin: {\n top: 5,\n right: 35,\n bottom: 5,\n left: 0\n }\n }\n }\n };\n\n $scope.pieChartData2 = computeCrashPerData();\n }",
"function renderPieChart() {\n var i, x, y, r, a1, a2, set, sum;\n\n x = width / 2;\n y = height / 2;\n r = Math.min(x, y) - 2;\n a1 = 1.5 * Math.PI;\n a2 = 0;\n set = sets[0];\n sum = sumSet(set);\n\n for (i = 0; i < set.length; i++) {\n ctx.fillStyle = colorOf(i);\n ctx.beginPath();\n a2 = a1 + (set[i] / sum) * (2 * Math.PI);\n\n // TODO opts.wedge\n ctx.arc(x, y, r, a1, a2, false);\n ctx.lineTo(x, y);\n ctx.fill();\n a1 = a2;\n }\n }",
"function pieData(d) {return [{'name':'CO2','value': d.CO2E},\n\t\t\t{'name':'methane','value':d.METH},\n\t\t\t{'name':'NO','value':d.NOXE},\n\t\t\t{'name':'other','value':d.GHGO}];}",
"function plotPieCh( data ) {\n\t\n\t\tvar chart, item, angle, offset, tot;\n\t\t\n\t\ttot = summation( data );\n\t\toffset = 0;\n\t\tchart = new THREE.Object3D();\n\t\t\n\t\t// in each iteration a portion is added\n\t\tfor (var i=0; i<data.length; i++) {\n\t\t\tangle = 2*Math.PI*data[i] / tot;\n\t\t\t\n\t\t\titem = pie( angle, getColor( i ) );\n\t\t\t\n\t\t\toffset += angle;\n\t\t\titem.rotation.y += offset;\n\t\t\t\n\t\t\tchart.add( item );\n\t\t}\n\t\t\n\t\treturn chart;\n\t}",
"function grafik_data_penjualanperiode_tjualpelanggan(x,y){\n var pieData = [\n {\n value: x,\n color:\"#CA0101\",\n highlight: \"#FF0000\",\n label: \"Umum\"\n },\n {\n value: y,\n color: \"#009933\",\n highlight: \"#3CD16E\",\n label: \"Pelanggan\"\n }\n ];\n \n \n\n var myPie = new Chart(document.getElementById(\"grafik_data_penjualanperiode_tjualpelanggan\").getContext(\"2d\")).Pie(pieData);\n}",
"function grafik_data_penjualanperiode_pelanggan(x,y){\n var pieData = [\n {\n value: x,\n color:\"#F7464A\",\n highlight: \"#FF5A5E\",\n label: \"Umum\"\n },\n {\n value: y,\n color: \"#46BFBD\",\n highlight: \"#5AD3D1\",\n label: \"Pelanggan\"\n }\n ];\n \n \n\n var myPie = new Chart(document.getElementById(\"grafik_data_penjualanperiode_pelanggan\").getContext(\"2d\")).Pie(pieData);\n}",
"function createPieCharts(type){\n\t\tvar dataContainer = document.getElementById(\"piedatadiv\");\n\t\tvar chartContainer = document.getElementById('piechartdiv');\n\t\tclearDiv(chartContainer);\n\t\t\n\t\tvar dataTable = getDataTable(document.frm.h_jsondata.value);\n\t\tif (!dataContainer){\n\t\t\talert(\"Data container not found, div 'piedatadiv'\");\n\t\t}\n\t\telse{\n\t\t\tvar lastSelectedDimension = parseInt(dataTable.ExtendedProperties[\"LastSelectedDimension\"]);\n\t\t\tvar table = document.createElement(\"table\");\n\t\t\tvar counter = 0;\n\t\t\tvar row = null;\n\n\t\t\tvar containerWidth = chartContainer.style.width.replace('px', '');\n\t\t\tvar containerHeight = chartContainer.style.height.replace('px', '');\n\t\t\tvar iLowerSize = containerHeight;\n\t\t\tif (containerHeight > containerWidth)\n\t\t\t\tiLowerSize = containerWidth;\n\t\t\t\n\t\t\tvar iMeasuresAggCount = dataTable.Columns.length - lastSelectedDimension - 1;\n\t\t\tm_PieHeight = (containerWidth / m_PiesPerRow) - 15;\n\t\t\tm_PieWidth = (containerWidth / m_PiesPerRow\t) - 15;\n\n\t\t\tfor (var jColumn = lastSelectedDimension + 1; jColumn < dataTable.Columns.length; jColumn++){\t\t\n\t\t\t\tvar cell = document.createElement(\"td\");\n\t\t\t\t\n\t\t\t\tcell.style.width = m_PieWidth;\n\t\t\t\tcell.style.height = m_PieHeight;\n\t\t\t\tcell.style.align = \"center\";\n\t\t\t\t\t\n\t\t\t\tvar div = document.createElement(\"div\");\n\t\t\t\tdiv.id = \"piediv\" + jColumn;\n\t\t\t\tcell.appendChild(div);\n\n\t\t\t\tif(m_UseGrid){\n\t\t\t\t\tvar divGrid = document.createElement(\"div\");\n\t\t\t\t\tdivGrid.id = \"gridpiediv\" + jColumn;\n\t\t\t\t\tcell.appendChild(divGrid);\n\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\n\t\t\t\tif (!row || counter % m_PiesPerRow == 0){\n\t\t\t\t\trow = document.createElement(\"tr\");\n\t\t\t\t\ttable.appendChild(row);\n\t\t\t\t}\n\t\t\t\trow.appendChild(cell);\n\t\t\t\tcounter++\n\t\t\t}\n\t\t\ttable.style.height = counter/m_PiesPerRow * m_PieHeight;\n\t\t\ttable.style.cellSpacing = \"10px\";\n\t\t\ttable.style.cellPadding = \"30px\";\n\t\t\ttable.style.width = \"100%\";\n\t\t\t\n\t\t\tif (document.all)\n\t\t\t\tchartContainer.innerHTML = table.outerHTML;\n\t\t\telse\n\t\t\t\tchartContainer.appendChild(table);\n\t\t\n\t\t\tfor (var jColumn = lastSelectedDimension + 1; jColumn < dataTable.Columns.length; jColumn++){\t\t\n\t\t\t\tvar idSWF = \"piediv\" + jColumn;\n\t\t\t\tvar pieChart = new FusionCharts(\"../../Charts/\" + type + \".swf\", idSWF, m_ChartWidth, m_ChartHeight, \"0\", \"0\");\n\t\t\t\tvar xmlData = document.getElementById(\"h_pie\" + jColumn).value;\n\t\t\t\tpieChart.setDataXML(xmlData);\n\t\t\t\tpieChart.render(idSWF);\n\n\t\t\t\tif (m_UseGrid){\n\t\t\t\t\tvar pieGrid = new FusionCharts(\"../../Charts/SSGrid.swf\", \"grid\" + idSWF, m_PieWidth, m_PieHeight, \"0\", \"0\");\n\t\t\t\t\tpieGrid.setDataXML(xmlData);\n\t\t\t\t\tpieGrid.render(\"grid\" + idSWF);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets this GregorianCalendar to the date given by the date specifiers weekYear, weekOfYear, and dayOfWeek. weekOfYear follows the WEEK_OF_YEAR numbering. The dayOfWeek value must be one of the DAY_OF_WEEK values: SUNDAY to SATURDAY. | setWeekDate(weekYear, weekOfYear, dayOfWeek) {
if (dayOfWeek < GregorianCalendar.SUNDAY || dayOfWeek > GregorianCalendar.SATURDAY) {
throw new Error('invalid dayOfWeek: ' + dayOfWeek);
}
const fields = this.fields;
// To avoid changing the time of day fields by date
// calculations, use a clone with the GMT time zone.
const gc = this.clone();
gc.clear();
gc.setTimezoneOffset(0);
gc.set(YEAR, weekYear);
gc.set(WEEK_OF_YEAR, 1);
gc.set(DAY_OF_WEEK, this.getFirstDayOfWeek());
let days = dayOfWeek - this.getFirstDayOfWeek();
if (days < 0) {
days += 7;
}
days += 7 * (weekOfYear - 1);
if (days !== 0) {
gc.add(DAY_OF_YEAR, days);
} else {
gc.complete();
}
fields[YEAR] = gc.get(YEAR);
fields[MONTH] = gc.get(MONTH);
fields[DAY_OF_MONTH] = gc.get(DAY_OF_MONTH);
this.complete();
} | [
"static ofWeekOfWeekBasedYearField(weekDef) {\n return new ComputedDayOfField('WeekOfWeekBasedYear', weekDef,\n ChronoUnit.WEEKS, IsoFields.WEEK_BASED_YEARS, WEEK_OF_WEEK_BASED_YEAR_RANGE);\n }",
"function weekOfYear(mom,firstDayOfWeek,firstDayOfWeekOfYear){var adjustedMoment,end=firstDayOfWeekOfYear-firstDayOfWeek,daysToDayOfWeek=firstDayOfWeekOfYear-mom.day();return daysToDayOfWeek>end&&(daysToDayOfWeek-=7),end-7>daysToDayOfWeek&&(daysToDayOfWeek+=7),adjustedMoment=moment(mom).add(\"d\",daysToDayOfWeek),{\"week\":Math.ceil(adjustedMoment.dayOfYear()/7),\"year\":adjustedMoment.year()}}//http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday",
"static fromWeekOfYear(year, weekOfYear, time) {\n time[0] = year;\n var day = TimeUtil.dayOfWeek(year, 1, 1);\n var doy;\n if (day < 4) {\n doy = (weekOfYear * 7 - 7 - day) + 1;\n if (doy < 1) {\n time[0] = time[0] - 1;\n if (TimeUtil.isLeapYear(time[0])) {\n // was doy= doy + ( isLeapYear(time[0]) ? 366 : 365 ); TODO: verify\n doy = doy + 366;\n } else {\n doy = doy + 365;\n }\n }\n } else {\n doy = weekOfYear * 7 - day + 1;\n }\n time[1] = 1;\n time[2] = doy;\n TimeUtil.normalizeTime(time);\n }",
"function CP_setWeekStartDay(day) { this.weekStartDay = day; }",
"static ofWeekBasedYearField(weekDef) {\n return new ComputedDayOfField('WeekBasedYear', weekDef,\n IsoFields.WEEK_BASED_YEARS, ChronoUnit.FOREVER, WEEK_BASED_YEAR_RANGE);\n }",
"function weekInYear(date, option) {\n if (!date) {\n return undefined;\n }\n\n var firstDayOfWeekArg = 1;\n\n if (_typeof(option) === 'object') {\n // DateFormat\n if (option.symbols !== undefined && option.symbols.firstDayOfWeek !== undefined) {\n firstDayOfWeekArg = option.symbols.firstDayOfWeek;\n } else if (option.decimalFormatSymbols !== undefined && option.decimalFormatSymbols.firstDayOfWeek !== undefined) {\n // Locale\n firstDayOfWeekArg = option.decimalFormatSymbols.firstDayOfWeek;\n }\n } else if (typeof option === 'number') {\n firstDayOfWeekArg = option;\n } // Thursday of current week decides the year\n\n\n var thursday = _thursdayOfWeek(date, firstDayOfWeekArg); // In ISO format, the week with January 4th is the first week\n\n\n var jan4 = new Date(thursday.getFullYear(), 0, 4); // If the date is before the beginning of the year, it belongs to the year before\n\n var startJan4 = firstDayOfWeek(jan4, firstDayOfWeekArg);\n\n if (date.getTime() < startJan4.getTime()) {\n jan4 = new Date(thursday.getFullYear() - 1, 0, 4);\n } // Get the Thursday of the first week, to be able to compare it to 'thursday'\n\n\n var thursdayFirstWeek = _thursdayOfWeek(jan4, firstDayOfWeekArg);\n\n var diffInDays = (thursday.getTime() - thursdayFirstWeek.getTime()) / 86400000;\n return 1 + Math.round(diffInDays / 7);\n} // private",
"dayOfWeek(value){\n if(!value) return this._dayOfWeek;\n\n if(value === this._dayOfWeek) return this;\n\n if(! /^[1-7]$/.test(value)) throw new Error(`Invalid input \"${value}\" for dayOfWeek.`);\n this._date += value - this._dayOfWeek;\n\n return this.reset();\n }",
"function updateWeek() {\n updateCal(7);\n}",
"addWeekday(wd) {\n\t\tfor(let i=0; i < this._date.length; i++) {\n\t\t\tthis._date[i].addWeekday(wd);\n\t\t}\n\t}",
"weekOfYear(){\n return Math.ceil(this.dayOfYear()/7);\n }",
"function WDateChooser_selectWeek( week, dismiss, aDoc ) {\n var era = parseInt( this.getElementById( this.makeId(\"hideEra\") ).value );\n var year = parseInt( this.getElementById( this.makeId(\"hideYear\") ).value );\n var month = parseInt( this.getElementById( this.makeId(\"hideMonth\") ).value );\n var date = parseInt( this.getElementById( this.makeId(\"hideDate\") ).value );\n var c = this.cal.clone();\n WDateChooser_initCalendarDate( c );\n c.set(\"ERA\", era);\n c.set(\"YEAR\", year);\n c.set(\"MONTH\", month);\n c.set(\"DATE\", date);\n\n // get the first day of week\n var firstDayOfWeek = c.firstDayOfWeek;\n // get weekdays\n weekdays = this.df.dateFormatSymbols.shortWeekdays.length;\n\n // get the start day of the month in the calendar\n var selDate = c.clone();\n selDate.set(\"DATE\", 1);\n while (selDate.get(\"DAY_OF_WEEK\") != firstDayOfWeek) {\n selDate.add(\"DATE\", -1);\n }\n\n // get the start date of the Nth week\n for (var i = 1; i < week; i++) {\n selDate.add(\"DATE\", weekdays);\n if (month != selDate.get(\"MONTH\")) {\n break;\n }\n }\n if (week > 1 && month != selDate.get(\"MONTH\")) {\n // rewind 1 week\n selDate.add(\"DATE\", -1 * weekdays);\n week--;\n }\n\n if ( dismiss ) {\n // change selection type to week\n this.selection = 1;\n this.updateSelectedDate( selDate, true );\n this.updateCurrentDate( c );\n this.setVisible( false );\n // set focus on the date button\n var dateButton = this.getElementById( this.buttonId );\n if (dateButton != null)\n dateButton.focus();\n }\n else {\n // Unhilight the last selection\n this.hilightSelection( aDoc, false );\n // change selection type to week\n this.selection = 1;\n // set new week number\n var weekNum = this.getElementById( this.makeId(\"smWeekNum\") );\n if (weekNum != null) {\n weekNum.value = week;\n }\n // update selection\n this.updateSelectedDate( selDate, true );\n this.updateCurrentDate( c );\n // Hilight the current selection\n this.hilightSelection( aDoc, true );\n }\n}",
"function convertWeekNumberToDate (intYear, intWeek, intMinusDays) {\n \n var objDate = new Date(intYear, 0, 1);\n var intdayNum = objDate.getDay();\n var intdiff = --intWeek * 7;\n\n // Add required number of days\n objDate.setDate(objDate.getDate() - objDate.getDay() + ++intdiff);\n \n if ( parseInt(intMinusDays) !== 0 ){\n\tobjDate.setDate\t( objDate.getDate() - parseInt( intMinusDays ) ); \n }\n \n return objDate;\n}",
"static set startOfWeek(day) {\n Samay._startOfWeek = day;\n }",
"function callDateSetWithWeek(d, method, value) {\n\t if(method === 'ISOWeek') {\n\t return setWeekNumber(d, value);\n\t } else {\n\t return callDateSet(d, method, value);\n\t }\n\t }",
"function w_SetWeekDate(evt)\n{\n\tvar m=\"\";\n\tvar g=\"\";\n\tvar mMonth;\n\tvar mDay;\n\tvar result = '';\n\tvar startW = '';\n\tvar endW = '';\n\n\n\tvar e_out;\n\tvar ie_var = \"srcElement\";\n\tvar moz_var = \"target\";\n\tvar prop_var = \"startweek\";\n var istartWeek, iendWeek;\n var rowWeek;\n \n\t// \"target\" for Mozilla, Netscape, Firefox et al. ; \"srcElement\" for IE\n\tevt[moz_var] ? e_out = evt[moz_var][prop_var] : e_out = evt[ie_var][prop_var];\n\tistartWeek = e_out;\n\tprop_var = \"endweek\";\n\tevt[moz_var] ? e_out = evt[moz_var][prop_var] : e_out = evt[ie_var][prop_var];\n\tiendWeek = e_out;\n\n\tprop_var = \"rowweek\";\n\tevt[moz_var] ? e_out = evt[moz_var][prop_var] : e_out = evt[ie_var][prop_var];\n\trowWeek = e_out;\n\n\n mMonth = (w_d.getMonth()+1);\n\n if(mMonth<10)\n m = \"0\" + mMonth\n else\n m = mMonth\n\n mDay = document.getElementById(\"w_c\"+rowWeek+istartWeek).innerHTML; \t\n if (mDay<10)\n\t g = \"0\" + mDay\n else\n\t g = mDay\t\n \t\t\n startW = g + \"/\" + m + \"/\" + w_d.getFullYear();\n\n mDay = document.getElementById(\"w_c\"+rowWeek+iendWeek).innerHTML; \t\n if (mDay<10)\n\t g = \"0\" + mDay\n else\n\t g = mDay\t\n\n endW = g + \"/\" + m + \"/\" + w_d.getFullYear();\n \n // set the selected date\n try\n {\n document.getElementById(w_linkedInputText_1).value = startW;\n document.getElementById(w_linkedInputText_2).value = endW;\n }\n catch(e)\n {};\n\t\n w_hiddenCalendar();\n\tdocument.getElementById(w_linkedInputText_2).focus();\n}",
"function weekOfTheYear(date, firstDayOfWeek){\n firstDayOfWeek = firstDayOfWeek == null? 0 : firstDayOfWeek;\n var doy = dayOfTheYear(date);\n var dow = (7 + date.getDay() - firstDayOfWeek) % 7;\n var relativeWeekDay = 6 - firstDayOfWeek - dow;\n return Math.floor((doy + relativeWeekDay) / 7);\n }",
"function callDateSetWithWeek(d, method, value, safe) {\n if (method === 'ISOWeek') {\n setISOWeekNumber(d, value);\n } else {\n callDateSet(d, method, value, safe);\n }\n }",
"w (date) {\n return getWeekOfYear(date)\n }",
"function CalendarWeek(jqyObj) {\n\t\t\n\t\t// jquery object that reference the week <div/>\n\t\tthis.jqyObj = jqyObj;\n\t\t\n\t\t// all CalendarDayCell objects in the week\n\t\tthis.days = new Array();\n\t\t\n\t\t// append a CalendarDayCell object\n\t\tthis.appendCalendarDayCell = function (calDayCell){\n\t\t\t// push is not supported by IE 5/Win with the JScript 5.0 engine\n\t\t\tthis.days.push(calDayCell);\n\t\t\tthis.jqyObj.append(calDayCell.jqyObj);\n\t\t};\n\t\t\n\t\t// returns an array of CalendarDayCell objects\n\t\tthis.getDays = function(){\n\t\t\treturn this.days;\n\t\t}\n\t\t\n\t\tthis.setHtml = function(htmlData){\n\t\t\tthis.jqyObj.html(htmlData);\n\t\t};\n\t\t\n\t\tthis.getHtml = function(){\n\t\t\treturn this.jqyObj.html();\n\t\t};\t\t\n\t\t\n\t\tthis.setCss = function(attr,value){\n\t\t\tthis.jqyObj.css(attr,value);\n\t\t};\n\t\t\n\t\tthis.getCss = function(attr){\n\t\t\treturn this.jqyObj.css(attr);\n\t\t};\t\t\n\t\t\n\t\tthis.setAttr = function(id,value){\n\t\t\tthis.jqyObj.attr(id,value);\n\t\t};\n\t\t\n\t\tthis.getAttr = function(id){\n\t\t\treturn this.jqyObj.attr(id);\n\t\t};\n\n\t\t// set width of the calendar header <div/>\n\t\tthis.setWidth = function(w){\n\t\t\tthis.jqyObj.width(w);\n\t\t}\t\t\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The market interval endpoint returns a summary of information about all markets based in a given currency over a configurable time interval. | marketInterval({ nomicsCurrencyID, hours, startISOString, endISOString }) {
return this.getMarketIntervalV1({ nomicsCurrencyID, hours, startISOString, endISOString })
.catch((err) => {
console.error("Error in 'marketInterval' method of nomics module\n" + err);
throw new Error(err);
});
} | [
"getMarketRates() {\n return this._request({\n fullURL: 'https://quote.coins.ph/v1/markets',\n responseField: 'markets'\n })\n }",
"async function markets() {\n try {\n const client = new CoinMarketCap(process.env.COINMARKETCAP_API_KEY)\n const currency = 'CAD';\n const cryptoCount = 5;\n\n const prices = await client.getTickers({limit: cryptoCount, convert: currency});\n\n console.log('Market Monday\\n');\n console.log(`Top ${cryptoCount} cryptocurrencies by market cap:\\n`);\n prices.data.forEach(d => {\n const price = new Big(d.quote[currency].price);\n const change = new Big(d.quote[currency].percent_change_7d);\n const upDown = change.lt(0) ? 'down' : 'up';\n const chart = change.lt(0) ? emoji.get(':chart_with_downwards_trend:') : emoji.get(':chart_with_upwards_trend:');\n const decimals = price.lt(1) ? 4 : 0;\n\n console.log(`${chart} ${d.name} (${d.symbol}) $${price.toFormat(decimals)} CAD - ${upDown} ${change.abs().toString()}% this week ${chart}`);\n });\n } catch (err) {\n console.error(err);\n }\n}",
"function getMarkets() {\n return new Promise(function(resolve, reject) {\n var date\n var max\n\n if (!params.live) {\n max = smoment()\n max.moment.subtract(2, 'days').startOf('day')\n\n // get the date at the end\n // of the provided interval\n date = smoment(params.start)\n date.moment.startOf(params.interval)\n\n // use max if the date\n // provided is later than that\n if (date.moment.diff(max.moment) > 0) {\n date = max\n }\n }\n\n hbase.getTopMarkets({date: date}, function(err, markets) {\n\n if (err) {\n reject(err)\n\n // format results\n } else {\n markets.forEach(function(market) {\n market.base = {\n currency: market.base_currency,\n issuer: market.base_issuer\n }\n market.counter = {\n currency: market.counter_currency,\n issuer: market.counter_issuer\n }\n })\n resolve(markets)\n }\n })\n })\n }",
"async markets() {\n if (this.data.markets != null) {\n return this.data.markets;\n }\n let results = await this.ccxt('fetch_markets');\n var raw_markets = results;\n this.data.markets = [];\n raw_markets\n .filter(raw_market => raw_market.active == true)\n .forEach(raw_market => {\n const id = raw_market.id;\n const symbol = raw_market.symbol;\n const type = raw_market.info.type;\n const base = raw_market.base;\n const quote = raw_market.quote;\n const bid = parseFloat(raw_market.info.bid);\n const ask = parseFloat(raw_market.info.ask);\n const expiration = (raw_market.expiration != null ? raw_market.expiration : null);\n const contract_size = (raw_market.info.contractSize != null ? raw_market.info.contractSize : 1);\n const precision = raw_market.precision;\n const raw = raw_market.info;\n const tvsymbol = 'FTX:' + symbol.replace('-','').replace('/','');\n const market = new this.classes.market(id, symbol, type, base, quote, bid, ask, expiration, contract_size, precision, tvsymbol, raw)\n this.data.markets.push(market);\n });\n await this.index_markets();\n await this.update_markets_usd_price();\n return this.data.markets;\n }",
"async markets() {\n if (this.data.markets != null) {\n return this.data.markets;\n }\n await this.fetch_tickers();\n this.data.markets = [];\n var raw_markets = await this.ccxt('fetch_markets');\n raw_markets\n .filter(raw_market => raw_market.active == true && ['spot', 'future'].includes(raw_market.type))\n .forEach(raw_market => {\n const id = raw_market.id;\n const symbol = raw_market.symbol;\n const tvsymbol = 'DERIBIT:' + raw_market.symbol.replace('-','').replace('PERPETUAL', 'PERP')\n const type = raw_market.type;\n if (type != undefined) {\n const base = raw_market.base;\n const quote = raw_market.quote;\n var ticker = this.data.tickers.hasOwnProperty(symbol) ? this.data.tickers[symbol] : null;\n const bid = ticker != null ? ticker.bid : null;\n const ask = ticker != null ? ticker.ask : null;\n const expiration = (raw_market.info.expiration_timestamp != null ? raw_market.info.expiration_timestamp : null);\n const contract_size = (raw_market.info.contract_size != null ? (symbol == 'BTC-PERPETUAL' ? 1 : raw_market.info.contract_size) : 1);\n const precision = raw_market.precision;\n const raw = raw_market.info;\n const market = new this.classes.market(id, symbol, type, base, quote, bid, ask, expiration, contract_size, precision, tvsymbol, raw)\n this.data.markets.push(market);\n }\n });\n await this.index_markets();\n await this.update_markets_usd_price();\n return this.data.markets;\n }",
"function marketOverview(cb){\n async.parallel({\n symbols: function(callback) {\n loadTrendingSymbols(callback);\n },\n\n marketSentiments: function(callback) {\n loadSentiments('Market', '2013-10-01', '2013-11-31', function(err, sentiments) {\n callback(null, {\n \"bullish\": _.last(sentiments.bullish).value,\n \"bearish\": _.last(sentiments.bearish).value,\n });\n });\n }\n\n }, function(err, results) {\n cb(err, results);\n });\n}",
"function getVolumes(markets) {\n\n\n markets.forEach(function(market) {\n var swap\n\n if (market.base.currency === 'XRP') {\n swap = market.base\n market.base = market.counter\n market.counter = swap\n }\n })\n\n return Promise.map(markets, function(market) {\n return new Promise(function(resolve, reject) {\n var start = smoment(params.start)\n var end\n var interval\n\n if (params.live &&\n ['3day', '7day', '30day'].indexOf(params.live) !== -1) {\n interval = '5minute'\n end = smoment(params.end)\n\n } else {\n end = smoment(params.start)\n end.moment.add(1, params.interval || 'day').subtract(1, 'second')\n }\n\n hbase.getExchanges({\n base: market.base,\n counter: market.counter,\n start: start,\n end: end,\n interval: interval,\n limit: Infinity,\n reduce: true\n }, function(err, resp) {\n\n var data = {}\n\n if (err) {\n reject(err)\n return\n }\n\n if (interval) {\n resp.reduced = reduce(resp.rows)\n }\n\n data.count = resp.reduced.count\n data.rate = resp.reduced.vwap\n data.amount = resp.reduced.base_volume\n data.base = market.base\n data.counter = market.counter\n\n if (data.counter.currency === 'XRP') {\n data.converted_amount = resp.reduced.counter_volume\n data.rate = resp.reduced.vwap ?\n 1 / resp.reduced.vwap : 0\n }\n\n resolve(data)\n })\n })\n })\n }",
"async markets() {\n if (this.data.markets != null) {\n return this.data.markets;\n }\n let results = await this.ccxt('fetch_markets');\n var raw_markets = this.utils.is_array(results) ? results : [];\n this.data.markets = [];\n raw_markets\n .filter(raw_market => raw_market.active == true)\n //.filter(raw_market => raw_market.info.typ == 'FFWCSX')\n .forEach(raw_market => {\n const id = raw_market.id;\n const symbol = raw_market.symbol;\n const tvsymbol = 'BITMEX:' + raw_market.id;\n const type = raw_market.info.type;\n const base = raw_market.base;\n const quote = raw_market.quote;\n const bid = raw_market.info.bidPrice;\n const ask = raw_market.info.askPrice;\n const expiration = (raw_market.info.expiry != null ? raw_market.info.expiry : null);\n const contract_size = (raw_market.info.contractSize != null ? raw_market.info.contractSize : 1);\n const precision = raw_market.precision;\n const raw = raw_market.info;\n const market = new this.classes.market(id, symbol, type, base, quote, bid, ask, expiration, contract_size, precision, tvsymbol, raw)\n this.data.markets.push(market);\n });\n await this.index_markets();\n await this.update_markets_usd_price();\n return this.data.markets;\n }",
"function getVolumes(markets) {\n\n markets.forEach(function(market) {\n var swap;\n\n if (market.base.currency === 'XRP') {\n swap = market.base;\n market.base = market.counter;\n market.counter = swap;\n }\n });\n\n return Promise.map(markets, function(market) {\n return new Promise(function(resolve, reject) {\n var start = smoment(params.start);\n var end = smoment(params.start);\n\n end.moment.add(1, params.interval || 'day').subtract(1, 'second');\n\n hbase.getExchanges({\n base: market.base,\n counter: market.counter,\n start: start,\n end: end,\n limit: Infinity,\n reduce: true\n }, function(err, resp) {\n var data = {};\n\n if (err) {\n reject(err);\n return;\n }\n\n resp = resp.reduced;\n\n data.count = resp.count;\n data.rate = resp.vwap;\n data.amount = resp.base_volume;\n data.base = market.base;\n data.counter = market.counter;\n\n if (data.counter.currency === 'XRP') {\n data.convertedAmount = resp.counter_volume;\n data.rate = resp.vwap ? 1 / resp.vwap : 0;\n }\n\n resolve(data);\n });\n });\n });\n }",
"function getMarkets() {\n return new Promise(function(resolve, reject) {\n var date;\n var max;\n\n if (options.top) {\n\n max = smoment();\n max.moment.subtract(2, 'days').startOf('day');\n\n // get the date at the end\n // of the provided interval\n date = smoment(params.start);\n date.moment.add(1, params.interval);\n\n // use T-2 if the date\n // provided is later than that\n if (date.moment.diff(max.moment) > 0) {\n date = max;\n }\n\n hbase.getTopMarkets({date: date}, function(err, markets) {\n if (err) {\n reject(err);\n\n // no markets found\n } else if (!markets.length) {\n reject('no markets found');\n\n // take top 50\n } else {\n resolve(markets.slice(0, 50));\n }\n });\n\n } else {\n resolve(marketPairs);\n }\n });\n }",
"function retrievePrices(exchange, instrument, timeframe, since, callback) {\n\n}",
"getExchangeRates() {\r\n return this.getUnsignedRequestPromise('GET', '/exchange/api/v2/info/prices', {});\r\n }",
"exchangeMarketInterval({ nomicsCurrencyID, exchange, startISOString, endISOString }) {\n return this.getExchangeMarketIntervalV1({ nomicsCurrencyID, exchange, startISOString, endISOString })\n .catch((err) => {\n console.error(\"Error in 'exchangeMarketInterval' method of nomics module\\n\" + err);\n throw new Error(err);\n });\n }",
"async function getHistoricalRates(event, timePeriod) {\n data = [];\n let today = timePeriods.today;\n event ? (timePeriod = timePeriods[event.target.id]) : (timePeriod = timePeriods.oneMonth);\n await fetch(\n `https://api.exchangeratesapi.io/history?start_at=${timePeriod}&end_at=${today}&base=${baseCurrency}&symbols=${exchangeCurrency}`,\n )\n .then(result => result.json())\n .then(result =>\n Object.keys(result.rates)\n .sort((first, second) => first.localeCompare(second))\n .map(key => {\n data.push({ date: moment.utc(key), rate: result.rates[key][exchangeCurrency] });\n }),\n );\n displayChart();\n}",
"getTimeSeriesUrl(symbol='', interval=1) {\n const intervalSet = new Set([1, 5, 15, 30, 60]);\n\n // The symbol has to be a non-empty string\n if (typeof symbol !== 'string' || !symbol) {\n console.error('getTimeSeriesUrl: The parameter <symbol> is invalid');\n\n return '';\n }\n\n // The interval has to be a valid number\n if (typeof interval !== 'number' || !intervalSet.has(interval)) {\n console.error('getTimeSeriesUrl: The parameter <interval> is invalid');\n\n return '';\n }\n\n return `https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=${symbol}&interval=${interval}min&apikey=${this.#apiKey}`;\n }",
"exchangeOHLCVCandles({ interval, exchange, market, startISOString, endISOString }) {\n return this.getExchangeOHLCVCandlesV1({ interval, exchange, market, startISOString, endISOString })\n .catch((err) => {\n console.error(\"Error in 'exchangeOHLCVCandles' method of nomics module\\n\" + err);\n throw new Error(err);\n });\n }",
"function getMarketDataForMarketInRange(marketData, callback) {\n $.ajax({\n url: GET_DATA_FOR_MARKET_IN_RANGE + marketData.marketname + \".\" + marketData.start + \".\" + marketData.end,\n async: true,\n success: (function(data) {\n // console.log(\"Got all market data for \" + marketData.marketname);\n\n var retVal = {};\n retVal[marketData.marketname] = [];\n var retValArr = retVal[marketData.marketname];\n\n data.Items.forEach(function(item) {\n retValArr.push({\n \"DataTimestamp\": item.DataTimestamp.S,\n \"LeftVal\": parseFloat(item.LeftVal.N),\n \"RightVal\": parseFloat(item.RightVal.N)\n });\n });\n\n callback(retVal);\n })\n });\n}",
"async function historicRatesForAcurrency() {\n let currencyService = new CurrencyService(process.env.MICRO_API_TOKEN);\n let rsp = await currencyService.history({\n code: \"USD\",\n date: \"2021-05-30\",\n });\n console.log(rsp);\n}",
"function getTopMarkets() {\n \n api.getTopMarkets(function(data){\n var volume = 0;\n for (var i=0; i<data.length; i++) {\n volume += data[i][3];\n }\n \n $scope.tradeVolume = volume ? \"$\"+commas(volume,2) : \"\";\n $scope.$apply();\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Xpath for Race Runner Toggle OFF | get raceRunnerToggleOFF() {return browser.element("//android.widget.ScrollView/android.view.ViewGroup/android.widget.ScrollView/android.view.ViewGroup/android.view.ViewGroup[1]/android.view.ViewGroup/android.view.ViewGroup[1]");} | [
"get raceRunnerToggleON() {return browser.element(\"//android.widget.ScrollView/android.view.ViewGroup/android.widget.ScrollView/android.view.ViewGroup/android.view.ViewGroup[1]/android.view.ViewGroup/android.view.ViewGroup[3]\");}",
"get raceRunnerToggleOFF() {return browser.element(\"//android.widget.ScrollView/android.view.ViewGroup/android.view.ViewGroup[13]/android.view.ViewGroup[2]/android.view.ViewGroup/android.widget.TextView\");}",
"clickRaceRunnerToggleOFF(){\n this.raceRunnerToggleOFF.waitForExist();\n this.raceRunnerToggleOFF.click();\n }",
"clickRaceRunnerToggleOFF(){\n this.raceRunnerToggleOFF.waitForExist();\n this.raceRunnerToggleOFF.click();\n }",
"get meetingRaceList_RaceRunnerToggle() {return browser.element(\"//android.widget.ScrollView/android.view.ViewGroup/android.widget.ScrollView/android.view.ViewGroup/android.view.ViewGroup[1]/android.view.ViewGroup\");}",
"clickRaceRunnerToggleON(){\n this.raceRunnerToggleON.waitForExist();\n this.raceRunnerToggleON.click();\n }",
"clickRaceRunnerToggleON(){\n this.raceRunnerToggleON.waitForExist();\n this.raceRunnerToggleON.click();\n }",
"get racingHub_2ndRace() {return browser.element(\"//android.widget.ScrollView/android.view.ViewGroup/android.view.ViewGroup[2]/android.widget.Button\");}",
"toggleRobotTrails() {\n // don't want to toggle active trails if this element is unchecked\n this.activeTrailCB.disabled = !this.toggleTrailsCB.checked;\n\n this.showHideTrails();\n }",
"get Homescreen_RaceResult() {return browser.element(\"//XCUIElementTypeOther[@name='z RACE RESULTS']\");}",
"async seeDisabledAttribute (xpath) {\n const helper = this.helpers['Puppeteer'] || this.helpers['WebDriver']\n return await helper.waitForElement(xpath + ':disabled')\n }",
"async seeDisabledAttribute (xpath) {\n const helper = this.helpers['Puppeteer'] || this.helpers['WebDriver']\n let res = await helper.grabAttributeFrom(xpath, 'disabled')\n return assert.ok(res !== null && res.toString().toLowerCase() === 'true', \"\\x1b[31mexpected element '\\x1b[91m\" + xpath + \"\\x1b[31m' to be disabled\")\n }",
"get horseCard_Race_ReplayButton() {return browser.element(\"//android.widget.ScrollView/android.view.ViewGroup/android.widget.ScrollView/android.view.ViewGroup/android.view.ViewGroup[1]/android.view.ViewGroup/android.view.ViewGroup[1]/android.view.ViewGroup\");}",
"get meetingRaceList_RaceStatus() {return browser.element(\"//android.view.ViewGroup[2]/android.view.ViewGroup/android.view.ViewGroup[2]\");}",
"function toggleGrd(e) {\n // alert(\"in toggleGrd(e=\"+e+\")\");\n\n // get the Tree Node\n var inode = e[\"target\"].id.substring(4);\n inode = inode.substring(0,inode.length-4);\n inode = Number(inode);\n\n // toggle the Grd property\n if (myTree.gprim[inode] != \"\") {\n if ((wv.sceneGraph[myTree.gprim[inode]].attrs & wv.plotAttrs.LINES) == 0) {\n myTree.prop(inode, 2, \"on\");\n } else {\n myTree.prop(inode, 2, \"off\");\n }\n\n // toggle the Grd property (on all Core/Tube in this Crystal)\n } else {\n var myElem = myTree.document.getElementById(\"node\"+inode+\"col4\");\n if (myElem.getAttribute(\"class\") == \"fakelinkoff\") {\n myTree.prop(inode, 2, \"on\");\n } else {\n myTree.prop(inode, 2, \"off\");\n }\n }\n\n myTree.update();\n}",
"get VideoHub_RaceReplayTab() { return browser.element('//XCUIElementTypeOther[@name=\"Race Replays\"]');}",
"function ukToggleAttr() {\n let tmToggleElements = document.querySelectorAll(\".tm-toggle\");\n if(tmToggleElements.length > 0) {\n tmToggleElements.forEach(function(e) {\n e.setAttribute(\"uk-toggle\", \"\");\n });\n }\n}",
"async dontSeeDisabledAttribute (xpath) {\n const helper = this.helpers['Puppeteer'] || this.helpers['WebDriver']\n return await helper.waitForInvisible(xpath + ':disabled')\n }",
"async dontSeeDisabledAttribute (xpath) {\n const helper = this.helpers['Puppeteer'] || this.helpers['WebDriver']\n let res = await helper.grabAttributeFrom(xpath, 'disabled')\n return assert.ok(!(res !== null && res.toString().toLowerCase() === 'true'), \"\\x1b[31mexpected element '\\x1b[91m\" + xpath + \"\\x1b[31m' NOT to be disabled\")\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
// // ChoroplethMap ChoroplethMap ChoroplethMap ChoroplethMap // | function qpChoroplethMapMaker() {
var width = 1000, height = 428;
var zoom = d3.behavior.zoom()
.scaleExtent([1, 5])
.on("zoom", moveAndZoom);
var svg = d3.select("div#qpCoreChoroplethMap").append("svg")
.attr({ width: width, height: height })
.call(zoom);
var projection = d3.geo.mercator();
var path = d3.geo.path().projection(projection);
var url = 'https://gist.githubusercontent.com/d3byex/65a128a9a499f7f0b37d/raw/176771c2f08dbd3431009ae27bef9b2f2fb56e36/world-110m.json';
d3.json(url, function (error, world) {
var countries = topojson.feature(world, world.objects.countries).features;
var neighbors = topojson.neighbors(world.objects.countries.geometries);
qpChoroplethMapMaker.mapButtonClick = mapButtonClick;
function mapButtonClick(datapoint) {
d3.select("div#ChoroplethMaplegend").selectAll("*").remove();//Removes prevoius ChoroplethMap svg canvas
svg.transition().duration(200);
var mainGroup = svg.append("g");
mainGroup.style({ stroke: "white", "stroke-width": "2px", "stroke-opacity": 0.0 });
var country_value_and_iso = {};
incomingData.forEach(function(d) {
country_value_and_iso[d["Iso3"]] = +d[datapoint];
country_value_and_iso[d.Country_Name] = +d.id;
});
var country_name_and_iso = {};
incomingData.forEach(function(d) {
country_name_and_iso[d["Iso3"]] = d.Country_Name;
});
var maxValue = d3.max(whole_data, function(d) {
return parseFloat(d[datapoint]);});
var color_domain = [0,maxValue];
var colorQuantize = d3.scale.quantize()
.domain(color_domain)
.range(["#2c7bb6", "#00a6ca","#00ccbc","#90eb9d","#ffff8c","#f9d057","#f29e2e","#e76818","#d7191c"]);
//////////////////////////////////////////////////////////////////
////
//// Legend Legend Legend Legend Legend Legend Legend Legend
////
//////////////////////////////////////////////////////////////////
var legendWidth = 140, legendHeight = 400;
var key = d3.select("div#ChoroplethMaplegend").append("svg")
.attr("width", legendWidth)
.attr("height", legendHeight);
//Append a linearGradient element to the defs
var legend = key.append("defs").append("svg:linearGradient")
.attr("id", "gradient")
.attr("x1", "100%")
.attr("y1", "0%")
.attr("x2", "100%")
.attr("y2", "100%")
.attr("spreadMethod", "pad");
//set the color for the beggining
legend.selectAll("stop")
.attr("offset", "0%")
.data([
{offset: "0%", color: "#d7191c"},
{offset: "12.5%", color: "#e76818"},
{offset: "25%", color: "#f29e2e"},
{offset: "37.5%", color: "#f9d057"},
{offset: "50%", color: "#ffff8c"},
{offset: "62.5%", color: "#90eb9d"},
{offset: "75%", color: "#00ccbc"},
{offset: "87.5%", color: "#00a6ca"},
{offset: "100%", color: "#2c7bb6"}
])
.enter().append("stop")
.attr("offset", function(d) { return d.offset; })
.attr("stop-color", function(d) { return d.color; })
.attr("stop-opacity", 1);
//Draw the rectangle and fill with gradient
key.append("rect")
.attr("id", "legendRect")
.attr("width", legendWidth - 100)
.attr("height", legendHeight -100)
.style("fill", "url(#gradient)")
.attr("transform", "translate(0,10)");
var legendY = d3.scale.linear()
.range([300, 0])
.domain([0,maxValue]);
var yAxis = d3.svg.axis()
.scale(legendY)
.orient("right");
key
.append("g")
.attr("class", "y axis")
.attr("transform", "translate(41,10)")
.call(yAxis).append("text")
.attr("transform", "rotate(-90)")
.attr("y", 30)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Colored Scale for " + datapoint);
///////////////////////////////////////////////////////////
///End Legend End Legend End Legend End Legend End Legend
///////////////////////////////////////////////////////////
//Coloring of the world
mainGroup.selectAll("path", "countries")
.data(countries)
.enter().append("path").transition().duration(1000)
.attr("d", path)
.style("fill", function (d) {
return colorQuantize(country_value_and_iso[d.id]);});
// Define the div for the tooltip
var div = d3.select("div#qpCoreChoroplethMap").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
mainGroup
.selectAll("path")
.data(countries)
.on("mouseover", function (p) {
div.transition()
.duration(200)
.style("opacity", .9);
div .html(country_value_and_iso[p.id])
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
div.html(country_name_and_iso[p.id] + ":" + "<br/>" + country_value_and_iso[p.id]);
d3.select(this).style("stroke-opacity", 1.0);
});
mainGroup.selectAll("path")
.on("mouseout", function () {
d3.select(this).style("stroke-opacity", 0.0);
});
}//ButtonClick
});//d3json
function moveAndZoom() {
var t = d3.event.translate;
var s = d3.event.scale;
var x = Math.min(
(width / height) * (s - 1),
Math.max(width * (1 - s), t[0]));
var h = height / 4;
var y = Math.min(
h * (s - 1) + h * s,
Math.max(height * (1 - s) - h * s, t[1]));
mainGroup.style("stroke-width", ((1 / s) * 2) + "px");
mainGroup.attr('transform', 'translate(' + x + ',' + y + ')scale(' + s + ')');
}//Move and zoom
}//ChoroplethMapMaker | [
"function qpChoroplethMapMaker() {\n\n var width = 850, height = 350;\n\n var zoom = d3.behavior.zoom()\n .scaleExtent([1, 5])\n .on(\"zoom\", moveAndZoom);\n\n var svg = d3.select(\"svg#ChoroplethMap\")\n .attr({ width: width, height: height })\n .call(zoom);\n\n var projection = d3.geo.mercator();\n var path = d3.geo.path().projection(projection);\n\n var url = 'https://gist.githubusercontent.com/d3byex/65a128a9a499f7f0b37d/raw/176771c2f08dbd3431009ae27bef9b2f2fb56e36/world-110m.json';\n\n d3.json(url, function (error, world) {\n var countries = topojson.feature(world, world.objects.countries).features;\n var neighbors = topojson.neighbors(world.objects.countries.geometries);\n\n qpChoroplethMapMaker.mapButtonClick = mapButtonClick;\n\n function mapButtonClick(datapoint) {\n d3.select(\"svg#ChoroplethMap\").selectAll(\"*\").remove();//Removes prevoius ChoroplethMap svg canvas\n d3.selectAll(\"div.tooltip\").remove();\n d3.selectAll(\"div.dropdownbox\").remove();\n d3.selectAll(\"databox\").remove();\n\n svg.transition().duration(200);\n\n var datapoint = d3.select('select.select').property('value');\n\n var mainGroup = svg.append(\"g\");\n mainGroup.style({ stroke: \"white\", \"stroke-width\": \"2px\", \"stroke-opacity\": 0.0 });\n\n var country_value_and_iso = {};\n incomingData.forEach(function(d) {\n country_value_and_iso[d[\"Iso3\"]] = +d[datapoint];\n country_value_and_iso[d.Country_Name] = +d.id;\n });\n var country_name_and_iso = {};\n incomingData.forEach(function(d) {\n country_name_and_iso[d[\"Iso3\"]] = d.Country_Name;\n });\n\n var maxValue = d3.max(all_data_for_map, function(d) {\n return parseFloat(d[datapoint]);});\n\n var minValue = d3.min(all_data_for_map, function(d) {\n return parseFloat(d[datapoint]);})\n\n var color_domain = [minValue,maxValue];\n var colorQuantize = d3.scale.quantize()\n .domain(color_domain)\n .range([\"#d7191c\", \"#d7411c\", \"#e76818\", \"#e79018\", \"#f29e2e\", \"#f9ad57\", \"#f9d057\", \"#f9dc8c\", \"#ffeb8c\",\n \"#ffeb8c\", \"#c7eb9d\", \"#90eb9d\", \"#00ccbc\", \"#00a6ca\", \"#0060ca\", \"#0006ca\"]);\n\n //////////////////////////////////////////////////////////////////\n ////\n //// Legend Legend Legend Legend Legend Legend Legend Legend\n ////\n //////////////////////////////////////////////////////////////////\n\n var legendWidth = 140, legendHeight = 400;\n var key = d3.select(\"svg#ChoroplethMap\").append(\"svg\")\n .attr(\"width\", legendWidth)\n .attr(\"height\", legendHeight);\n\n //Append a linearGradient element to the defs\n var legend = key.append(\"defs\").append(\"svg:linearGradient\")\n .attr(\"id\", \"gradient\")\n .attr(\"x1\", \"100%\")\n .attr(\"y1\", \"0%\")\n .attr(\"x2\", \"100%\")\n .attr(\"y2\", \"100%\")\n .attr(\"spreadMethod\", \"pad\");\n\n //set the color for the beggining\n legend.selectAll(\"stop\")\n .attr(\"offset\", \"0%\")\n .data([\n {offset: \"0%\", color: \"#0006ca\"},\n {offset: \"6.25%\", color: \"#0060ca\"},\n {offset: \"12.5%\", color: \"#00a6ca\"},\n {offset: \"18.75%\", color: \"#00ccbc\"},\n {offset: \"25%\", color: \"#23d7b1\"},\n {offset: \"32.25%\", color: \"#48eb9d\"},\n {offset: \"37.5%\", color: \"#90eb9d\"},\n {offset: \"43.75%\", color: \"#c7eb9d\"},\n {offset: \"50%\", color: \"#ffeb8c\"},\n {offset: \"56.25%\", color: \"#f9dc8c\"},\n {offset: \"62.5%\", color: \"#f9d057\"},\n {offset: \"68.75%\", color: \"#f9ad57\"},\n {offset: \"75%\", color: \"#f29e2e\"},\n {offset: \"82.25%\", color: \"#e79018\"},\n {offset: \"87.5%\", color: \"#e76818\"},\n {offset: \"93.75%\", color: \"#d7411c\"},\n {offset: \"100%\", color: \"#d7191c\"}\n ])\n .enter().append(\"stop\")\n .attr(\"offset\", function(d) { return d.offset; })\n .attr(\"stop-color\", function(d) { return d.color; })\n .attr(\"stop-opacity\", 1);\n\n //Draw the rectangle and fill with gradient\n key.append(\"rect\")\n .attr(\"id\", \"legendRect\")\n .attr(\"width\", legendWidth - 100)\n .attr(\"height\", legendHeight -100)\n .style(\"fill\", \"url(#gradient)\")\n .attr(\"transform\", \"translate(0,90)\");\n\n var legendY = d3.scale.linear()\n .range([300, 0])\n .domain([minValue,maxValue]);\n\n var yAxis = d3.svg.axis()\n .scale(legendY)\n .orient(\"right\");\n\n key\n .append(\"g\")\n .attr(\"class\", \"y axis\")\n .attr(\"transform\", \"translate(41,90)\")\n .call(yAxis).append(\"text\")\n .attr(\"transform\", \"rotate(-90)\")\n .attr(\"y\", 50)\n .attr(\"dy\", \".71em\")\n .style(\"text-anchor\", \"end\")\n .text(\"Colored Scale for \" + datapoint);\n\n ///////////////////////////////////////////////////////////\n ///End Legend End Legend End Legend End Legend End Legend\n ///////////////////////////////////////////////////////////\n\n //Coloring of the world\n mainGroup.selectAll(\"path\", \"countries\")\n .data(countries)\n .enter().append(\"path\").transition().duration(1000)\n .attr(\"d\", path)\n .style(\"fill\", function (d) {\n return colorQuantize(country_value_and_iso[d.id]);});\n\n // Define the div for the tooltip\n var div = d3.select(\"body\").append(\"div\")\n .attr(\"class\", \"tooltip\")\n .style(\"opacity\", .9);\n\n mainGroup\n .selectAll(\"path\")\n .data(countries)\n .on(\"mouseover\", function (p) {\n div.transition()\n .duration(200)\n .style(\"opacity\", .9);\n div\t.html(country_value_and_iso[p.id])\n .style(\"left\", (d3.event.pageX) + \"px\")\n .style(\"top\", (d3.event.pageY - 28) + \"px\");\n\n var num = country_value_and_iso[p.id];\n\n if (datapoint === 'Sec_of_State_2017') {\n meeting_list = []\n\n //API for json of who the sec of state met with\n d3.json(aPITOUSE + 'meetingjsonlist', function(error, incomingData) {\n for (var i in _.range(incomingData[0].length)) {\n if (incomingData[0][i][\"Country Name\"] === country_name_and_iso[p.id]) {\n var lowerCaseBlurb = incomingData[0][i][\"Date\"].slice(1).toLowerCase();\n var upperCaseBlub = incomingData[0][i][\"Date\"].slice(0,1);\n var formattedDate = upperCaseBlub + lowerCaseBlurb;\n meeting_list.push(\"Met With \" + country_name_and_iso[p.id] + \"'s \" + incomingData[0][i][\"Leader\"] + \"<br/>\" + \"On \" + formattedDate + \"<br/>\");\n }\n else if (incomingData[0][i][\"Country Name\"] !== country_name_and_iso[p.id]) {\n if (meeting_list.length > 0) {\n var whole_blurb = country_name_and_iso[p.id] + \"'s \" + datapoint + \"<br/>\" + num.toFixed(2) + \"<br/>\" + meeting_list.join(\"\");\n div.html(whole_blurb);\n }\n else {\n div.html(country_name_and_iso[p.id] + \"'s \" + datapoint + \"<br/>\" + num.toFixed(2))\n }}\n }});\n }\n else {div.html(country_name_and_iso[p.id] + \"'s \" + datapoint + \"<br/>\" + num.toFixed(2))}\n d3.select(this).style(\"stroke-opacity\", 1.0);\n div.style(\"visibility\", \"visible\");\n })\n .on(\"mouseout\", function () {\n d3.select(this).style(\"stroke-opacity\", 0.0);\n div.style(\"visibility\", \"hidden\");\n })\n .on(\"click\", function(p) { //This triggers the country data section\n var CountryName = country_name_and_iso[p.id];\n CountryDataDisplay(CountryName);\n });//ONCLick\n /* What i want in viz\n Country Name,\n QP Score\n Country Flag,\n Map,\n Quick Facts: Capital, Language, FreedomHouseRanking, Population, GDP, HDI, FDI\n Headline Scores for Each Section\n */\n\n }//ButtonClick\n });//d3json\n\n\n function moveAndZoom() {\n var t = d3.event.translate;\n var s = d3.event.scale;\n\n var x = Math.min(\n (width / height) * (s - 1),\n Math.max(width * (1 - s), t[0]));\n\n var h = height / 4;\n var y = Math.min(\n h * (s - 1) + h * s,\n Math.max(height * (1 - s) - h * s, t[1]));\n\n mainGroup.style(\"stroke-width\", ((1 / s) * 2) + \"px\");\n mainGroup.attr('transform', 'translate(' + x + ',' + y + ')scale(' + s + ')');\n }//Move and zoom\n }//ChoroplethMapMaker",
"function drawChoroplethPopulation() {\n\n //clear svg after switching a map\n d3.select(\"#map\")\n .selectAll(\"*\")\n .remove();\n d3.select(\"#pie\")\n .selectAll(\"*\")\n .remove();\n d3.select(\"#pie2\")\n .selectAll(\"*\")\n .remove();\n\n // Create Choropleth datamap using population\n var world = new Datamap({\n element: document.getElementById('map'),\n scope: 'world',\n geographyConfig: {\n popupTemplate: function(geo, data) {\n return data && data.Population_thousands && \"<div class='hoverinfo'><strong>\" + geo.properties.name + \"<br>Total Population(in thousands):\" + data.Population_thousands + \"</strong></div>\";\n },\n highlightOnHover: true,\n highlightFillColor: function(data) {\n if (data.fillKey) {\n return 'grey';\n }\n return 'blue';\n },\n highlightBorderColor: 'black',\n highlightBorderWidth: 1,\n popupOnHover: true,\n borderColor: '#fff',\n borderWidth: 0.5,\n borderOpacity: 1\n },\n dataUrl: 'data/data.csv',\n dataType: 'csv',\n data: {},\n fills: {\n 'Lowest': '#aed6f1',\n 'Low': '#5dade2',\n 'Medium': '#3498db',\n 'High': '#2874a6',\n 'Highest': ' #1b4f72',\n defaultFill: '#dddddd'\n },\n done: function(datamap) {\n datamap.svg.selectAll('.datamaps-subunit').on('click', function(geo) {\n\n //Get index of the country clicked to map data with dataset\n var index;\n for (var i = 0; i < data.length; i++) {\n if (data[i].id == geo.id)\n index = i;\n }\n\n //Array to store Economy and employment data from dataset\n var newDataEconomy = [];\n var newDataEmployment = [];\n newDataEconomy = [{\n \"Name\": \"Agriculture\",\n \"Value\": data[index].Economy_Agriculture\n },\n {\n \"Name\": \"Industry\",\n \"Value\": data[index].Economy_Industry\n },\n {\n \"Name\": \"Services\",\n \"Value\": data[index].Economy_Services\n }\n ];\n\n newDataEmployment = [{\n \"Name\": \"Agriculture\",\n \"Value\": data[index].Employment_Agriculture\n },\n {\n \"Name\": \"Industry\",\n \"Value\": data[index].Employment_Industry\n },\n {\n \"Name\": \"Services\",\n \"Value\": data[index].Employment_Services\n }\n ];\n\n //Define scale of the donut chart\n var width = 200;\n var height = 200;\n var outradius = Math.min(width, height) / 2;\n var inradius = 66;\n var legendSize = 11;\n var legendSpace = 3;\n\n //Define color scale\n var color = d3.scale.category10();\n\n d3.select(\"#pie\")\n .selectAll(\"*\")\n .remove();\n\n d3.select(\"#pie2\")\n .selectAll(\"*\")\n .remove();\n\n //Define svg elements\n var svg = d3.select('#pie')\n .append('svg')\n .attr('width', width)\n .attr('height', height)\n .append('g')\n .attr('transform', 'translate(' + (width / 2) + ',' + (height / 2) + ')');\n\n //Define radius for donut\n var arc = d3.svg.arc()\n .outerRadius(outradius)\n .innerRadius(inradius);\n\n //Divide donut with value of objects\n var pie = d3.layout.pie()\n .value(function(d, i) {\n return d.Value;\n })\n .sort(null)\n .padAngle(.02);\n\n //Fill donut with distinct colors of keys from object \n var path = svg.selectAll('path')\n .data(pie(newDataEconomy))\n .enter()\n .append('path')\n .attr('d', arc)\n .attr('fill', function(d, i) {\n return color(d.data.Name);\n })\n .each(function(d) {\n this._current = d;\n });\n\n //Donut animation on load\n path.transition()\n .duration(1000)\n .attrTween('d', function(d) {\n var interpolate = d3.interpolate({\n startAngle: 0,\n endAngle: 0\n }, d);\n return function(t) {\n return arc(interpolate(t));\n };\n });\n\n //Plot donut labels \n var text = svg.selectAll('text')\n .data(pie(newDataEconomy))\n .enter()\n .append(\"text\")\n .transition()\n .duration(200)\n .attr(\"transform\", function(d) {\n return \"translate(\" + arc.centroid(d) + \")\";\n })\n .attr(\"dy\", \".4em\")\n .attr(\"text-anchor\", \"middle\")\n .text(function(d) {\n return d.data.Value + \"%\";\n })\n .style({\n fill: '#fff',\n 'font-size': '10px'\n });\n\n //Display key legends for donut chart\n var legend = svg.selectAll('.legend')\n .data(color.domain())\n .enter()\n .append('g')\n .attr('class', 'legend')\n .attr('transform', function(d, i) {\n var height = legendSize + legendSpace;\n var offset = height * color.domain().length / 2;\n var horiz = -3 * legendSize;\n var vert = i * height - offset;\n return 'translate(' + horiz + ',' + vert + ')';\n });\n\n legend.append('rect')\n .attr('width', legendSize)\n .attr('height', legendSize)\n .style('fill', color)\n .style('stroke', color)\n .on('click', function(label) {\n var rect = d3.select(this);\n var enabled = true;\n var totalEnabled = d3.sum(newDataEconomy.map(function(d) {\n return (d.enabled) ? 1 : 0;\n }));\n });\n\n legend.append('text')\n .attr('x', legendSize + legendSpace)\n .attr('y', legendSize - legendSpace)\n .text(function(d) {\n return d;\n })\n\n var svg = d3.select('#pie2')\n .append('svg')\n .attr('width', width)\n .attr('height', height)\n .append('g')\n .attr('transform', 'translate(' + (width / 2) + ',' + (height / 2) + ')');\n\n\n var arc = d3.svg.arc()\n .outerRadius(outradius)\n .innerRadius(inradius);\n\n var pie = d3.layout.pie()\n .value(function(d, i) {\n return d.Value;\n })\n .sort(null)\n .padAngle(.02);\n\n var path = svg.selectAll('path')\n .data(pie(newDataEmployment))\n .enter()\n .append('path')\n .attr('d', arc)\n .attr('fill', function(d, i) {\n return color(d.data.Name);\n })\n .each(function(d) {\n this._current = d;\n });\n\n path.transition()\n .duration(1000)\n .attrTween('d', function(d) {\n var interpolate = d3.interpolate({\n startAngle: 0,\n endAngle: 0\n }, d);\n return function(t) {\n return arc(interpolate(t));\n };\n });\n\n var text = svg.selectAll('text')\n .data(pie(newDataEmployment))\n .enter()\n .append(\"text\")\n .transition()\n .duration(200)\n .attr(\"transform\", function(d) {\n return \"translate(\" + arc.centroid(d) + \")\";\n })\n .attr(\"dy\", \".4em\")\n .attr(\"text-anchor\", \"middle\")\n .text(function(d) {\n return d.data.Value + \"%\";\n })\n .style({\n fill: '#fff',\n 'font-size': '10px'\n });\n\n\n var legend = svg.selectAll('.legend')\n .data(color.domain())\n .enter()\n .append('g')\n .attr('class', 'legend')\n .attr('transform', function(d, i) {\n var height = legendSize + legendSpace;\n var offset = height * color.domain().length / 2;\n var horiz = -3 * legendSize;\n var vert = i * height - offset;\n return 'translate(' + horiz + ',' + vert + ')';\n });\n\n legend.append('rect')\n .attr('width', legendSize)\n .attr('height', legendSize)\n .style('fill', color)\n .style('stroke', color)\n .on('click', function(label) {\n var rect = d3.select(this);\n var enabled = true;\n var totalEnabled = d3.sum(newDataEmployment.map(function(d) {\n return (d.enabled) ? 1 : 0;\n }));\n });\n\n legend.append('text')\n .attr('x', legendSize + legendSpace)\n .attr('y', legendSize - legendSpace)\n .text(function(d) {\n return d;\n });\n });\n }\n });\n }",
"function makeChoroplethChart(id, tag, cf, geom, barchart) {\n var chart = dc.leafletChoroplethChart(id);\n var dimension = cf.dimension(function(d){ if(d[tag]==null){\n return 'No Data';\n } else {\n return d[tag]; \n }});\n var group = dimension.group();\n chart.width($(id).width()).height(300)\n .dimension(dimension)\n .group(group)\n .center([0,0])\n .zoom(0) \n .geojson(geom)\n .colors(['#dddddd','steelblue'])\n .colorDomain([0, 1])\n .colorAccessor(function (d) {\n if(d>0){\n return 1;\n } else {\n return 0;\n }\n }) \n .featureKeyAccessor(function(feature){\n return feature.properties['CODE'];\n }).popup(function(feature){\n return lookup[feature.properties['CODE']];\n })\n .renderPopup(true)\n .featureOptions({\n 'fillColor': 'black',\n 'color': 'black',\n 'opacity':1,\n 'fillOpacity': 0,\n 'weight': 3\n })\n .createLeaflet(function(){\n return map;\n })\n .on('filtered',function(chart,filter){\n // This is where we select on the map\n // filter = the ADM code\n var filters = chart.filters();\n if(newFilter == true){\n newFilter = false;\n barchart.filter(filter);\n } else {\n newFilter = true;\n } \n if(filters.length>0){\n if(admlevel==1){\n setGeometry({adm1: filter});\n } else if(admlevel==2){\n setGeometry({adm2: filter});\n }\n }\n });\n\n return chart;\n}",
"function choroplethMap() {\n d3.csv(\"data/mass_shootings2.csv\", function(err, rows){\n\n function filter_and_unpack(rows, key, year) {\n return rows.filter(row => row['Year'] == year).map(row => row[key])\n }\n\n var frames = []\n var slider_steps = []\n\n var n = 39;\n var num = 1982;\n for (var i = 0; i <= n; i++) {\n var z = filter_and_unpack(rows, 'Total_Victims', num)\n var locations = filter_and_unpack(rows, 'State', num)\n var incName = filter_and_unpack(rows, 'Name_of_Incident', num)\n frames[i] = {data: [{z: z, locations: locations, text: incName}], name: num}\n slider_steps.push ({\n label: num.toString(),\n method: \"animate\",\n args: [[num], {\n mode: \"immediate\",\n transition: {duration: 300},\n frame: {duration: 300}\n }\n ]\n })\n num = num + 1\n }\n\n var data = [{\n type: 'choropleth',\n locationmode: 'USA-states',\n locations: frames[0].data[0].locations,\n z: frames[0].data[0].z,\n text: frames[0].data[0].locations,\n zauto: false,\n zmin: 0,\n zmax: 604\n\n }];\n var layout = {\n title: 'Mass Shootings in America<br>1982 - 2021',\n geo:{\n scope: 'usa',\n color_continuous_scale : \"Inferno\",\n reversescale : true,\n showland: true,\n landcolor: 'rgb(217, 217, 217)',\n showlakes: true,\n lakecolor: 'rgb(255, 255, 255)',\n subunitcolor: 'rgb(255, 255, 255)',\n lonaxis: {},\n lataxis: {}\n },\n updatemenus: [{\n x: 0.1,\n y: 0,\n yanchor: \"top\",\n xanchor: \"right\",\n showactive: false,\n direction: \"left\",\n type: \"buttons\",\n pad: {\"t\": 87, \"r\": 10},\n buttons: [{\n method: \"animate\",\n args: [null, {\n fromcurrent: true,\n transition: {\n duration: 200,\n },\n frame: {\n duration: 500\n }\n }],\n label: \"Play\"\n }, {\n method: \"animate\",\n args: [\n [null],\n {\n mode: \"immediate\",\n transition: {\n duration: 0\n },\n frame: {\n duration: 0\n }\n }\n ],\n label: \"Pause\"\n }]\n }],\n sliders: [{\n active: 0,\n steps: slider_steps,\n x: 0.1,\n len: 0.9,\n xanchor: \"left\",\n y: 0,\n yanchor: \"top\",\n pad: {t: 50, b: 10},\n currentvalue: {\n visible: true,\n prefix: \"Year:\",\n xanchor: \"right\",\n font: {\n size: 20,\n color: \"#666\"\n }\n },\n transition: {\n duration: 300,\n easing: \"cubic-in-out\"\n }\n }]\n };\n // console.log(frames)\n Plotly.newPlot('myDiv2', data, layout).then(function() {\n Plotly.addFrames('myDiv2', frames);\n });\n })\n}",
"function initMap(){\n\tlet styles = [\n\t {\n\t \"elementType\": \"geometry\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#ebe3cd\"\n\t }\n\t ]\n\t },\n\t {\n\t \"elementType\": \"labels.text.fill\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#523735\"\n\t }\n\t ]\n\t },\n\t {\n\t \"elementType\": \"labels.text.stroke\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#f5f1e6\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"administrative\",\n\t \"elementType\": \"geometry.stroke\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#c9b2a6\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"administrative.land_parcel\",\n\t \"elementType\": \"geometry.stroke\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#dcd2be\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"administrative.land_parcel\",\n\t \"elementType\": \"labels\",\n\t \"stylers\": [\n\t {\n\t \"visibility\": \"off\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"administrative.land_parcel\",\n\t \"elementType\": \"labels.text.fill\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#ae9e90\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"landscape.natural\",\n\t \"elementType\": \"geometry\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#dfd2ae\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"poi\",\n\t \"elementType\": \"geometry\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#dfd2ae\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"poi\",\n\t \"elementType\": \"labels.text\",\n\t \"stylers\": [\n\t {\n\t \"visibility\": \"off\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"poi\",\n\t \"elementType\": \"labels.text.fill\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#93817c\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"poi.business\",\n\t \"stylers\": [\n\t {\n\t \"visibility\": \"off\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"poi.park\",\n\t \"elementType\": \"geometry.fill\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#a5b076\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"poi.park\",\n\t \"elementType\": \"labels.text.fill\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#447530\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"road\",\n\t \"elementType\": \"geometry\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#f5f1e6\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"road\",\n\t \"elementType\": \"labels.icon\",\n\t \"stylers\": [\n\t {\n\t \"visibility\": \"off\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"road.arterial\",\n\t \"elementType\": \"geometry\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#fdfcf8\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"road.arterial\",\n\t \"elementType\": \"labels\",\n\t \"stylers\": [\n\t {\n\t \"visibility\": \"off\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"road.highway\",\n\t \"elementType\": \"geometry\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#f8c967\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"road.highway\",\n\t \"elementType\": \"geometry.stroke\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#e92434\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"road.highway\",\n\t \"elementType\": \"labels\",\n\t \"stylers\": [\n\t {\n\t \"visibility\": \"off\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"road.highway.controlled_access\",\n\t \"elementType\": \"geometry\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#e98d58\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"road.highway.controlled_access\",\n\t \"elementType\": \"geometry.stroke\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#db8555\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"road.local\",\n\t \"stylers\": [\n\t {\n\t \"visibility\": \"off\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"road.local\",\n\t \"elementType\": \"labels\",\n\t \"stylers\": [\n\t {\n\t \"visibility\": \"off\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"road.local\",\n\t \"elementType\": \"labels.text.fill\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#806b63\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"transit\",\n\t \"stylers\": [\n\t {\n\t \"visibility\": \"off\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"transit.line\",\n\t \"elementType\": \"geometry\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#dfd2ae\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"transit.line\",\n\t \"elementType\": \"labels.text.fill\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#8f7d77\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"transit.line\",\n\t \"elementType\": \"labels.text.stroke\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#ebe3cd\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"transit.station\",\n\t \"elementType\": \"geometry\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#dfd2ae\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"water\",\n\t \"elementType\": \"geometry.fill\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#83d3c1\"\n\t }\n\t ]\n\t },\n\t {\n\t \"featureType\": \"water\",\n\t \"elementType\": \"labels.text.fill\",\n\t \"stylers\": [\n\t {\n\t \"color\": \"#92998d\"\n\t }\n\t ]\n\t }\n\t];\n\n\tmap = new google.maps.Map(document.getElementById(\"map\"), {\n\t\tcenter: {lat: 38.904722, lng: -77.016389},\n\t\tstyles: styles,\n\t\tzoom: 12,\n\t\tmapTypeControl: false\n\t});\n}",
"function mapOptions() {\n var mapStyles = [\n {\n \"elementType\": \"geometry\",\n \"stylers\": [\n {\n \"color\": \"#1d2c4d\"\n }\n ]\n },\n {\n \"elementType\": \"labels.text.fill\",\n \"stylers\": [\n {\n \"color\": \"#8ec3b9\"\n }\n ]\n },\n {\n \"elementType\": \"labels.text.stroke\",\n \"stylers\": [\n {\n \"color\": \"#1a3646\"\n }\n ]\n },\n {\n \"featureType\": \"administrative.country\",\n \"elementType\": \"geometry.stroke\",\n \"stylers\": [\n {\n \"color\": \"#4b6878\"\n }\n ]\n },\n {\n \"featureType\": \"administrative.land_parcel\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"administrative.land_parcel\",\n \"elementType\": \"labels.text.fill\",\n \"stylers\": [\n {\n \"color\": \"#64779e\"\n }\n ]\n },\n {\n \"featureType\": \"administrative.neighborhood\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"administrative.province\",\n \"elementType\": \"geometry.stroke\",\n \"stylers\": [\n {\n \"color\": \"#4b6878\"\n }\n ]\n },\n {\n \"featureType\": \"landscape.man_made\",\n \"elementType\": \"geometry.stroke\",\n \"stylers\": [\n {\n \"color\": \"#334e87\"\n }\n ]\n },\n {\n \"featureType\": \"landscape.natural\",\n \"elementType\": \"geometry\",\n \"stylers\": [\n {\n \"color\": \"#023e58\"\n }\n ]\n },\n {\n \"featureType\": \"poi\",\n \"elementType\": \"geometry\",\n \"stylers\": [\n {\n \"color\": \"#283d6a\"\n }\n ]\n },\n {\n \"featureType\": \"poi\",\n \"elementType\": \"labels.text\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"poi\",\n \"elementType\": \"labels.text.fill\",\n \"stylers\": [\n {\n \"color\": \"#6f9ba5\"\n }\n ]\n },\n {\n \"featureType\": \"poi\",\n \"elementType\": \"labels.text.stroke\",\n \"stylers\": [\n {\n \"color\": \"#1d2c4d\"\n }\n ]\n },\n {\n \"featureType\": \"poi.park\",\n \"elementType\": \"geometry.fill\",\n \"stylers\": [\n {\n \"color\": \"#023e58\"\n }\n ]\n },\n {\n \"featureType\": \"poi.park\",\n \"elementType\": \"labels.text.fill\",\n \"stylers\": [\n {\n \"color\": \"#3C7680\"\n }\n ]\n },\n {\n \"featureType\": \"road\",\n \"elementType\": \"geometry\",\n \"stylers\": [\n {\n \"color\": \"#304a7d\"\n }\n ]\n },\n {\n \"featureType\": \"road\",\n \"elementType\": \"labels\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"road\",\n \"elementType\": \"labels.text.fill\",\n \"stylers\": [\n {\n \"color\": \"#98a5be\"\n }\n ]\n },\n {\n \"featureType\": \"road\",\n \"elementType\": \"labels.text.stroke\",\n \"stylers\": [\n {\n \"color\": \"#1d2c4d\"\n }\n ]\n },\n {\n \"featureType\": \"road.arterial\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"road.highway\",\n \"elementType\": \"geometry\",\n \"stylers\": [\n {\n \"color\": \"#2c6675\"\n }\n ]\n },\n {\n \"featureType\": \"road.highway\",\n \"elementType\": \"geometry.stroke\",\n \"stylers\": [\n {\n \"color\": \"#255763\"\n }\n ]\n },\n {\n \"featureType\": \"road.highway\",\n \"elementType\": \"labels\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"road.highway\",\n \"elementType\": \"labels.text.fill\",\n \"stylers\": [\n {\n \"color\": \"#b0d5ce\"\n }\n ]\n },\n {\n \"featureType\": \"road.highway\",\n \"elementType\": \"labels.text.stroke\",\n \"stylers\": [\n {\n \"color\": \"#023e58\"\n }\n ]\n },\n {\n \"featureType\": \"road.local\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"transit\",\n \"elementType\": \"labels.text.fill\",\n \"stylers\": [\n {\n \"color\": \"#98a5be\"\n }\n ]\n },\n {\n \"featureType\": \"transit\",\n \"elementType\": \"labels.text.stroke\",\n \"stylers\": [\n {\n \"color\": \"#1d2c4d\"\n }\n ]\n },\n {\n \"featureType\": \"transit.line\",\n \"elementType\": \"geometry.fill\",\n \"stylers\": [\n {\n \"color\": \"#283d6a\"\n }\n ]\n },\n {\n \"featureType\": \"transit.station\",\n \"elementType\": \"geometry\",\n \"stylers\": [\n {\n \"color\": \"#3a4762\"\n }\n ]\n },\n {\n \"featureType\": \"water\",\n \"elementType\": \"geometry\",\n \"stylers\": [\n {\n \"color\": \"#0e1626\"\n }\n ]\n },\n {\n \"featureType\": \"water\",\n \"elementType\": \"labels.text\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"water\",\n \"elementType\": \"labels.text.fill\",\n \"stylers\": [\n {\n \"color\": \"#4e6d70\"\n }\n ]\n }\n ],\n mapOptions = {\n center: {\n lat: officeLatCoord,\n lng: officeLonCoord\n },\n disableDefaultUI: true,\n mapTypeId: 'roadmap',\n scrollwheel: false,\n styles: mapStyles\n },\n directionsOptions = {\n suppressMarkers: true,\n polylineOptions: {\n strokeColor: mapStroke,\n strokeOpacity: mapStrokeOpacity,\n strokeWeight: mapStrokeWeight\n }\n };\n\n buildMap(mapOptions, directionsOptions);\n}",
"function draw_choropleth_map() {\n fetch('/mysql/map')\n .then(response => response.json())\n .then(result => {\n\n let countries = result.map(a => a.name);\n let deaths = result.map(b => b.total_deaths);\n\n let data = [{\n type: 'choropleth',\n locationmode: 'country names',\n locations: countries,\n z: deaths,\n autocolorscale: true,\n colorbar: {\n autotic: true,\n title: 'Total Deaths'\n },\n }];\n\n let layout = {\n title: 'Covid-19 Deaths by Country',\n geo: {\n projection: {\n type: 'robinson'\n }\n }\n };\n\n Plotly.newPlot(\"myDiv\", data, layout, {showLink: false});\n\n }\n );\n\n}",
"function drawChoroplethDensity() {\n d3.select(\"#map\")\n .selectAll(\"*\")\n .remove();\n d3.select(\"#pie\")\n .selectAll(\"*\")\n .remove();\n d3.select(\"#pie2\")\n .selectAll(\"*\")\n .remove();\n\n\n var world = new Datamap({\n element: document.getElementById('map'),\n scope: 'world',\n geographyConfig: {\n popupTemplate: function(geo, data) {\n return data && data.Population_density && \"<div class='hoverinfo'><strong>\" + geo.properties.name + \"<br>Population Density(Per square km): \" + data.Population_density + \"</strong></div>\";\n },\n highlightOnHover: true,\n highlightFillColor: function(data) {\n if (data.fillKey) {\n return 'grey';\n }\n return 'blue';\n },\n highlightBorderColor: 'black',\n highlightBorderWidth: 1,\n popupOnHover: true,\n borderColor: '#fff',\n borderWidth: 0.5,\n borderOpacity: 1\n },\n dataUrl: 'data/data_density.csv',\n dataType: 'csv',\n data: {},\n fills: {\n 'Lowest': '#E59866',\n 'Low': '#DC7633',\n 'Medium': '#BA4A00',\n 'High': '#873600',\n 'Highest': '#6E2C00',\n defaultFill: '#dddddd'\n },\n done: function(datamap) {\n datamap.svg.selectAll('.datamaps-subunit').on('click', function(geo) {\n var index;\n for (var i = 0; i < data.length; i++) {\n if (data[i].id == geo.id)\n index = i;\n }\n console.log(data[index]);\n\n var newDataEconomy = [];\n var newDataEmployment = [];\n newDataEconomy = [{\n \"Name\": \"Agriculture\",\n \"Value\": data[index].Economy_Agriculture\n },\n {\n \"Name\": \"Industry\",\n \"Value\": data[index].Economy_Industry\n },\n {\n \"Name\": \"Services\",\n \"Value\": data[index].Economy_Services\n }\n ];\n\n newDataEmployment = [{\n \"Name\": \"Agriculture\",\n \"Value\": data[index].Employment_Agriculture\n },\n {\n \"Name\": \"Industry\",\n \"Value\": data[index].Employment_Industry\n },\n {\n \"Name\": \"Services\",\n \"Value\": data[index].Employment_Services\n }\n ];\n\n var width = 200;\n var height = 200;\n var outradius = Math.min(width, height) / 2;\n var inradius = 66;\n var legendSize = 11;\n var legendSpace = 3;\n\n var color = d3.scale.category10();\n\n d3.select(\"#pie\")\n .selectAll(\"*\")\n .remove();\n\n d3.select(\"#pie2\")\n .selectAll(\"*\")\n .remove();\n\n var svg = d3.select('#pie')\n .append('svg')\n .attr('width', width)\n .attr('height', height)\n .append('g')\n .attr('transform', 'translate(' + (width / 2) + ',' + (height / 2) + ')');\n\n\n var arc = d3.svg.arc()\n .outerRadius(outradius)\n .innerRadius(inradius);\n\n var pie = d3.layout.pie()\n .value(function(d, i) {\n return d.Value;\n })\n .sort(null)\n .padAngle(.02);\n\n var path = svg.selectAll('path')\n .data(pie(newDataEconomy))\n .enter()\n .append('path')\n .attr('d', arc)\n .attr('fill', function(d, i) {\n return color(d.data.Name);\n })\n .each(function(d) {\n this._current = d;\n });\n\n path.transition()\n .duration(1000)\n .attrTween('d', function(d) {\n var interpolate = d3.interpolate({\n startAngle: 0,\n endAngle: 0\n }, d);\n return function(t) {\n return arc(interpolate(t));\n };\n });\n\n var text = svg.selectAll('text')\n .data(pie(newDataEconomy))\n .enter()\n .append(\"text\")\n .transition()\n .duration(200)\n .attr(\"transform\", function(d) {\n return \"translate(\" + arc.centroid(d) + \")\";\n })\n .attr(\"dy\", \".4em\")\n .attr(\"text-anchor\", \"middle\")\n .text(function(d) {\n return d.data.Value + \"%\";\n })\n .style({\n fill: '#fff',\n 'font-size': '10px'\n });\n\n var legend = svg.selectAll('.legend')\n .data(color.domain())\n .enter()\n .append('g')\n .attr('class', 'legend')\n .attr('transform', function(d, i) {\n var height = legendSize + legendSpace;\n var offset = height * color.domain().length / 2;\n var horiz = -3 * legendSize;\n var vert = i * height - offset;\n return 'translate(' + horiz + ',' + vert + ')';\n });\n\n legend.append('rect')\n .attr('width', legendSize)\n .attr('height', legendSize)\n .style('fill', color)\n .style('stroke', color)\n .on('click', function(label) {\n var rect = d3.select(this);\n var enabled = true;\n var totalEnabled = d3.sum(newDataEconomy.map(function(d) {\n return (d.enabled) ? 1 : 0;\n }));\n });\n\n legend.append('text')\n .attr('x', legendSize + legendSpace)\n .attr('y', legendSize - legendSpace)\n .text(function(d) {\n return d;\n })\n\n var svg = d3.select('#pie2')\n .append('svg')\n .attr('width', width)\n .attr('height', height)\n .append('g')\n .attr('transform', 'translate(' + (width / 2) + ',' + (height / 2) + ')');\n\n\n var arc = d3.svg.arc()\n .outerRadius(outradius)\n .innerRadius(inradius);\n\n var pie = d3.layout.pie()\n .value(function(d, i) {\n return d.Value;\n })\n .sort(null)\n .padAngle(.02);\n\n var path = svg.selectAll('path')\n .data(pie(newDataEmployment))\n .enter()\n .append('path')\n .attr('d', arc)\n .attr('fill', function(d, i) {\n return color(d.data.Name);\n })\n .each(function(d) {\n this._current = d;\n });\n\n path.transition()\n .duration(1000)\n .attrTween('d', function(d) {\n var interpolate = d3.interpolate({\n startAngle: 0,\n endAngle: 0\n }, d);\n return function(t) {\n return arc(interpolate(t));\n };\n });\n\n var text = svg.selectAll('text')\n .data(pie(newDataEmployment))\n .enter()\n .append(\"text\")\n .transition()\n .duration(200)\n .attr(\"transform\", function(d) {\n return \"translate(\" + arc.centroid(d) + \")\";\n })\n .attr(\"dy\", \".4em\")\n .attr(\"text-anchor\", \"middle\")\n .text(function(d) {\n return d.data.Value + \"%\";\n })\n .style({\n fill: '#fff',\n 'font-size': '10px'\n });\n\n\n var legend = svg.selectAll('.legend')\n .data(color.domain())\n .enter()\n .append('g')\n .attr('class', 'legend')\n .attr('transform', function(d, i) {\n var height = legendSize + legendSpace;\n var offset = height * color.domain().length / 2;\n var horiz = -3 * legendSize;\n var vert = i * height - offset;\n return 'translate(' + horiz + ',' + vert + ')';\n });\n\n legend.append('rect')\n .attr('width', legendSize)\n .attr('height', legendSize)\n .style('fill', color)\n .style('stroke', color)\n .on('click', function(label) {\n var rect = d3.select(this);\n var enabled = true;\n var totalEnabled = d3.sum(newDataEmployment.map(function(d) {\n return (d.enabled) ? 1 : 0;\n }));\n });\n\n legend.append('text')\n .attr('x', legendSize + legendSpace)\n .attr('y', legendSize - legendSpace)\n .text(function(d) {\n return d;\n });\n });\n }\n });\n }",
"function createGLChoropleth() {\n return m_this.createChoropleth();\n }",
"function createGLChoropleth() {\n\t return m_this.createChoropleth();\n\t }",
"function initMap() {\n var styles = [\n {\n \"elementType\": \"geometry\",\n \"stylers\": [\n {\n \"color\": \"#ebe3cd\"\n }\n ]},\n {\n \"elementType\": \"labels.text.fill\",\n \"stylers\": [\n {\n \"color\": \"#523735\"\n }\n ]},\n {\n \"elementType\": \"labels.text.stroke\",\n \"stylers\": [\n {\n \"color\": \"#f5f1e6\"\n }\n ]},\n {\n \"featureType\": \"administrative\",\n \"elementType\": \"geometry.stroke\",\n \"stylers\": [\n {\n \"color\": \"#c9b2a6\"\n }\n ]\n },\n {\n \"featureType\": \"administrative.land_parcel\",\n \"elementType\": \"geometry.stroke\",\n \"stylers\": [\n {\n \"color\": \"#dcd2be\"\n }\n ]\n },\n {\n \"featureType\": \"administrative.land_parcel\",\n \"elementType\": \"labels.text.fill\",\n \"stylers\": [\n {\n \"color\": \"#ae9e90\"\n }\n ]\n },\n {\n \"featureType\": \"landscape.natural\",\n \"elementType\": \"geometry\",\n \"stylers\": [\n {\n \"color\": \"#dfd2ae\"\n }\n ]\n },\n {\n \"featureType\": \"poi\",\n \"elementType\": \"geometry\",\n \"stylers\": [\n {\n \"color\": \"#dfd2ae\"\n }\n ]\n },\n {\n \"featureType\": \"poi\",\n \"elementType\": \"labels.text.fill\",\n \"stylers\": [\n {\n \"color\": \"#93817c\"\n }\n ]\n },\n {\n \"featureType\": \"poi.attraction\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"poi.business\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"poi.government\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"poi.medical\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"poi.park\",\n \"elementType\": \"geometry.fill\",\n \"stylers\": [\n {\n \"color\": \"#a5b076\"\n }\n ]\n },\n {\n \"featureType\": \"poi.park\",\n \"elementType\": \"labels.text\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"poi.park\",\n \"elementType\": \"labels.text.fill\",\n \"stylers\": [\n {\n \"color\": \"#447530\"\n }\n ]\n },\n {\n \"featureType\": \"poi.place_of_worship\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"poi.school\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"poi.sports_complex\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"road\",\n \"elementType\": \"geometry\",\n \"stylers\": [\n {\n \"color\": \"#f5f1e6\"\n }\n ]\n },\n {\n \"featureType\": \"road.arterial\",\n \"elementType\": \"geometry\",\n \"stylers\": [\n {\n \"color\": \"#fdfcf8\"\n }\n ]\n },\n {\n \"featureType\": \"road.highway\",\n \"elementType\": \"geometry\",\n \"stylers\": [\n {\n \"color\": \"#f8c967\"\n }\n ]\n },\n {\n \"featureType\": \"road.highway\",\n \"elementType\": \"geometry.stroke\",\n \"stylers\": [\n {\n \"color\": \"#e9bc62\"\n }\n ]\n },\n {\n \"featureType\": \"road.highway.controlled_access\",\n \"elementType\": \"geometry\",\n \"stylers\": [\n {\n \"color\": \"#e98d58\"\n }\n ]\n },\n {\n \"featureType\": \"road.highway.controlled_access\",\n \"elementType\": \"geometry.stroke\",\n \"stylers\": [\n {\n \"color\": \"#db8555\"\n }\n ]\n },\n {\n \"featureType\": \"road.local\",\n \"elementType\": \"labels.text.fill\",\n \"stylers\": [\n {\n \"color\": \"#806b63\"\n }\n ]\n },\n {\n \"featureType\": \"transit.line\",\n \"elementType\": \"geometry\",\n \"stylers\": [\n {\n \"color\": \"#dfd2ae\"\n }\n ]\n },\n {\n \"featureType\": \"transit.line\",\n \"elementType\": \"labels.text.fill\",\n \"stylers\": [\n {\n \"color\": \"#8f7d77\"\n }\n ]\n },\n {\n \"featureType\": \"transit.line\",\n \"elementType\": \"labels.text.stroke\",\n \"stylers\": [\n {\n \"color\": \"#ebe3cd\"\n }\n ]\n },\n {\n \"featureType\": \"transit.station\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"transit.station\",\n \"elementType\": \"geometry\",\n \"stylers\": [\n {\n \"color\": \"#dfd2ae\"\n }\n ]\n },\n {\n \"featureType\": \"water\",\n \"elementType\": \"geometry.fill\",\n \"stylers\": [\n {\n \"color\": \"#b9d3c2\"\n }\n ]\n },\n {\n \"featureType\": \"water\",\n \"elementType\": \"labels.text.fill\",\n \"stylers\": [\n {\n \"color\": \"#92998d\"\n }\n ]\n }\n ];\n\n //cluster markers create var\n var cluster = [];\n //Styles for map\n var map = new google.maps.Map(document.getElementById('map'), {\n gestureHandling: 'cooperative',\n center: new google.maps.LatLng(37.089, -96.253),\n mapTypeControl: false,\n zoom: 6,\n styles: styles\n });\n\n //Create infowindow and select size\n var infoWindow = new google.maps.InfoWindow({\n maxWidth: 350\n });\n\n // check if geolocation is enabled if not map is set to go to US center.\n if (navigator.geolocation)\n {\n // Add handler to listen when user's position changes\n navigator.geolocation.watchPosition(function(position) {\n // If this is the first time, set the map's center to the user's location\n if (currentLocation === undefined)\n {\n map.setCenter({lat:position.coords.latitude, lng:position.coords.longitude}); \n } \n currentLocation = position;\n geozoom = 3;\n });\n }\n\n // Conect to the database trought php file and assign columns to different vars\n downloadUrl('data/data.xml', function(data) {\n //saving xml file in array xml?\n var xml = data.responseXML;\n var markers = xml.documentElement.getElementsByTagName('marker');\n\n //loop trought all the markers saving each attribute in vars name,address,etc..\n for (var i = 0; i < markers.length; i++) {\n var name = markers[i].getAttribute('name');\n var address = markers[i].getAttribute('address');\n var type = markers[i].getAttribute('type');\n var point = new google.maps.LatLng(\n parseFloat(markers[i].getAttribute('lat')),\n parseFloat(markers[i].getAttribute('lng')));\n var url = markers[i].getAttribute('url');\n //Maybe delete this var.. since I dont need to show emails\n var email = markers[i].getAttribute('email'); \n var html = '<div id=\"iw-container\">' +\n '<div class=\"iw-title\">' + name +'</div>' +\n '<div class=\"iw-content\">' +\n '<div class=\"iw-subTitle urlink\">' + '<a href=http://'+url+ ' ' +'target=\"_blank\">' + url + '</a>' +'</div>' + \n //I could insert a image here too.\n '<div class=\"iw-subTitle type\"><b>Type: </b> '+ type + '</div>' +\n '<div class=\"iw-subTitle address\"><b>Address: </b>' + address + '</div>' +\n //I added a inline block to fit the infowindow correctly\n '<span style=\"display:inline-block; width: 350px;\"></span>'\n '</div>' +\n '<div class=\"iw-bottom-gradient\"></div>' +\n '</div>';\n var icon = customIcon[type] || {};\n //Add current marker[i] to the map\n var marker = new google.maps.Marker({\n map: map,\n position: point,\n icon: icon.customI,\n });\n\n bindInfoWindow(marker, map, infoWindow, html);\n\n //code for markers clusterer CHECK ERROR: INITMAP: Cannot read property 'apply' of undefined\n google.maps.event.addListener(marker, 'click', (function(marker, i) {\n //return function() {\n //infowindow.setContent(\"Info on member here\");\n //infowindow.open(map, marker);\n //}\n })(marker, i));\n\n cluster.push(marker); \n //end of loop\n }\n\n //marker clusterer\n var mc = new MarkerClusterer(map,cluster);\n\n });\n}",
"function drawChoroplethMap(div,filenames,attributes_topojson,attribute_choropleth,attributes_tooltip,domain,range) {\n var tooltip_length = attributes_tooltip.length;\n var height = 900;\n var width = 800;\n var projection = d3.geo.mercator();\n var choropleth_var = void 0;\n var db = d3.map();\n var b, s, t;\n var map = void 0; // update global\n\n var geoID = function(d) {\n\tconsole.log(d.properties[attributes_topojson[1]]);\n return d.properties[attributes_topojson[1]];\n };\n\t\n var color = d3.scale.threshold().domain(domain)\n\t\t\t.range(range); //<-A\n\t\t\t\n var path = d3.geo.path().projection(projection);\n \n function click() {\n\t alert(\"Click!\");\n }\n\t//Modal:\n\t\t\t\t$('#myModal').on('show.bs.modal', function () {\n\t\t\t\t\t$(this).find('.modal-content').css({\n\t\t\t\t\t\twidth:'auto', //probably not needed\n\t\t\t\t\t\theight:'auto', //probably not needed \n\t\t\t\t\t\t'max-height':'100%'\n\t\t\t\t\t});\n\t\t\t\t});\n\n\t//Datasets for modal window:\n\tvar array_datasets = [\"data/single_states/bawu_stats.csv\",\"data/single_states/bayern_stats.csv\",\"data/single_states/berlin_stats.csv\",\"data/single_states/brandenburg_stats.csv\",\"data/single_states/bremen_stats.csv\",\"data/single_states/hamburg_stats.csv\",\"data/single_states/hessen_stats.csv\",\"data/single_states/meckvor_stats.csv\",\"data/single_states/niedersachsen_stats.csv\",\"data/single_states/nrw_stats.csv\",\"data/single_states/rlp_stats.csv\",\"data/single_states/saarland_stats.csv\",\"data/single_states/sachsen_anhalt_stats.csv\",\"data/single_states/sachsen_stats.csv\",\"data/single_states/schleswig_holstein_stats.csv\",\"data/single_states/thueringen_stats.csv\"]\n\t\t\t\t\n //Tooltip:\n var tip = d3.tip()\n\t.attr('class', 'd3-tip')\n\t.offset([-10, 0])\n\t.html(function(d) {\n\t\tvar tooltip = \"\";\n\t\tconsole.log(d.properties[\"id\"]);//attributes_tooltip[0]\n\t\tif (d.properties[attributes_tooltip[0]] != undefined) {\n\t\t\ttooltip += \"Name of state: \" + d.properties[attributes_tooltip[0]]; \n\t\t}\n if (d.properties[attributes_tooltip[1]] != undefined) {\n\t\t\ttooltip += \"<br>\" + \"Total number of institutions: \" + d.properties[attributes_tooltip[1]];\n\t\t}\n\t\tif (d.properties[attributes_tooltip[2]] != undefined) {\n\t\t\ttooltip += \"<br>\" + \"Total number of students: \" + d.properties[attributes_tooltip[2]];\n\t\t}\n\t\tif (d.properties[attributes_tooltip[3]] != undefined) {\n\t\t\ttooltip += \"<br>\" + \"Avergage number of students per institution: \" + d.properties[attributes_tooltip[3]];\n\t\t}\n\t\tif (d.properties[attributes_tooltip[4]] != undefined) {\n\t\t\ttooltip += \"<br>\" + \"Click here for more information!\" ;\n\t\t}\n\t\tif (d.properties[attributes_tooltip[5]] != undefined) {\n\t\t\ttooltip += \"<br>\" + attributes_tooltip[5] + \": \" + d.properties[attributes_tooltip[5]];\n\t\t}\n\t\ttooltip += \"<br>\" + \"Click here for more information!\" ;\n\t\treturn tooltip;\n });\n\n var svg = d3.select(div)\n .append(\"svg\")\n .attr(\"width\", width)\n .attr(\"height\", height);\n\t //.call(d3.behavior.zoom()\n\t //.on(\"zoom\", redraw));\n\t \n function redraw() {\n svg.attr(\"transform\", \"translate(\" + d3.event.translate + \")scale(\" + d3.event.scale + \")\");\n }\n \n svg.call(tip); \n\n d3.json(filenames[0], function(data) {\n\td3.csv(filenames[1], function(statistics) {\n\t\t\n\t\t//get color for choropleth map:\n\t\tvar rateByValue = {};\n\t\t\t\t\n statistics.forEach(function (d) { // <-B\n\t\t\t\t//console.log(d[attribute_choropleth[0]]);\n\t\t\t\tconsole.log(d[attribute_choropleth[0]]);\n rateByValue[d[attribute_choropleth[0]]] = Math.round( d[attribute_choropleth[1]] );\n\t\t});\t\n\t\t\n\t\tvar choropleth = topojson.feature(data, data.objects[attributes_topojson[0]]);\n\n \n\t\tprojection.scale(1).translate([0, 0]);\n\t\tvar b = path.bounds(choropleth);\n\t\tvar s = .9 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height);\n\t\tvar t = [(width - s * (b[1][0] + b[0][0])) / 2, (height - s * (b[1][1] + b[0][1])) / 2];\n\t\tprojection.scale(s).translate(t);\n\n\t\tmap = svg.append('g').attr('class', 'boundary');\n\t\n\t\tchoropleth_var = map.selectAll('path').data(choropleth.features);\n\n\t\tchoropleth_var.enter()\n\t\t\t.append('path')\n\t\t\t.attr('d', path)\t//;\n\t\t\t.on('mouseover', tip.show)\t\t\t// event for tooltip\n\t\t\t.on('mouseout', tip.hide)\n\t\t\t.on('click', function(d){ \n\t\t\t\tconsole.log(d.properties[attributes_tooltip[0]]);\n\t\t\t\tvar selected_dataset = array_datasets[d.properties[\"id\"]-753];\n\t\t\t\tdocument.getElementById(\"modal_header\").innerHTML = d.properties[attributes_tooltip[0]];\n\t\t\t\t\n\t\t\t\t//Clear div:\n\t\t\t\t$('#grouped').empty();\n\t\t\t\t$('#stacked').empty();\n\t\t\t\t$('#sortable_bar').empty();\n\t\t\t\t$('#dashboard').empty();\n\t\t\t\t\n\t\t\t\t//Grouped:\n\t\t\t\tvar grouped_div = \"#grouped\",\n\t\t\t\t//grouped_filename = \"data/single_states/bawu_stats.csv\",\n\t\t\t\tgrouped_filename = selected_dataset,\n\t\t\t\tgrouped_attributes = [\"Semester\",\"Uni\",\"FH\",\"PH\",\"VFH\"],\t//first: attribute for x-Axis, the following attributes: attribute for y-Axis (bars)\n\t\t\t\tgrouped_attributes_tooltip = [[\"Uni\",\"number of students at a university\", \"\"], [\"FH\",\"number of students at a university of applied sciences\", \"\"], [\"PH\",\"number of students at a university of education\", \"\"], [\"VFH\",\"number of students at a university of administration\", \"\"]],\n\t\t\t\tgrouped_range = [\"#006d2c\",\"#2ca25f\", \"#66c2a4\", \"#b2e2e2\"], //; //colors for bars\n\t\t\t\tgrouped_y_axis_annotation = \"Number of students\";\n\t\t\t\t\n\t\t\t\t//Stacked:\n\t\t\t\tvar stacked_div = \"#stacked\",\n\t\t\t\t//stacked_filename = \"data/single_states/bawu_stats.csv\",\n\t\t\t\tstacked_filename = selected_dataset,\n\t\t\t\tstacked_attributes = [\"Semester\",\"Uni\",\"FH\",\"PH\",\"VFH\"],\t//first: attribute for x-Axis, the following attributes: attribute for y-Axis (bars)\n\t\t\t\tstacked_attributes_tooltip = [[\"Uni\",\"number of students at a university\", \"\"], [\"FH\",\"number of students at a university of applied sciences\", \"\"], [\"PH\",\"number of students at a university of education\", \"\"], [\"VFH\",\"number of students at a university of administration\", \"\"]],\n\t\t\t\tstacked_range = [\"#006d2c\",\"#2ca25f\", \"#66c2a4\", \"#b2e2e2\"]; //; //colors for bars\n\t\t\t\tstacked_y_axis_annotation = \"Number of students\";\n\t\t\n\t\t\t\t//Sortable:\n\t\t\t\tvar sortable_div = \"#sortable_bar\",\n\t\t\t\t//sortable_filename = \"data/single_states/bawu_stats.csv\",\n\t\t\t\tsortable_filename = selected_dataset,\n\t\t\t\tsortable_attributes = [\"Semester\",\"Total\"],\n\t\t\t\tsortable_attributes_tooltip = [\"total number of students\", \"\"],\n\t\t\t\tsortable_y_axis_annotation = \"Number of students\";\n\t\t\n\t\t\t\t//draw charts:\n\t\t\t\tdrawDashboard_modal(\"#dashboard\", selected_dataset, [\"Semester\",\"Uni\",\"FH\",\"PH\",\"VFH\"],[\"#006d2c\",\"#2ca25f\", \"#66c2a4\", \"#b2e2e2\"]); \n\t\t\t\tdrawGroupedVerticalBar(grouped_div,grouped_filename,grouped_attributes,grouped_attributes_tooltip,grouped_range,grouped_y_axis_annotation);\n\t\t\t\tdrawStackedVerticalBar(stacked_div,stacked_filename,stacked_attributes,stacked_attributes_tooltip,stacked_range,stacked_y_axis_annotation);\n\t\t\t\tdrawSortableBarChart(sortable_div,sortable_filename,sortable_attributes,sortable_attributes_tooltip,sortable_y_axis_annotation);\n\t\n\t\t\t\t//button settings when loading the page:\n\t\t\t\tdocument.getElementById('button_grouped').disabled = true; \n\t\t\t\tdocument.getElementById('button_stacked').disabled = false;\n\t\t\t\tdocument.getElementById('button_sortable').disabled = false;\n\t\t\t\tdocument.getElementById('button_dashboard').disabled = false; \n\t\t\t\tdocument.getElementById('label_checkbox').style.visibility=\"hidden\";\n\t\t\t\tdocument.getElementById('checkbox').checked = false;\n\t\n\t\t\t\t$(document.getElementById('grouped')).show();\n\t\t\t\t$(document.getElementById('stacked')).hide();\n\t\t\t\t$(document.getElementById('sortable_bar')).hide();\n\t\t\t\t$(document.getElementById('dashboard')).hide();\n\t\t\t\t\n\t\t\t\t$('#myModal').modal('show');\n\t\t\t});\t\t\t// event for tooltip \n\n\t\tchoropleth_var.attr(\"fill\", function (d) {\n\t\t\t\t\t\tvar col = color(rateByValue[d.properties[attributes_topojson[1]]]);\n\t\t\t\t\t\tconsole.log(col);\n\t\t\t\t\t\treturn col; // <-C\n });\n\n\t\tchoropleth_var.exit().remove();\n\n\t\t\n\t\t//legend: \n\t\t/*var legend = svg.selectAll('g.legendEntry')\n\t\t\t.data(color.range())\n\t\t\t.enter()\n\t\t\t.append('g').attr('class', 'legendEntry');\n\n\t\tlegend\n\t\t\t.append('rect')\n\t\t\t.attr(\"x\", width - 75)\t\t\t\t\t//south-east: 165\n\t\t\t.attr(\"y\", function(d, i) {\n\t\t\t\treturn (height - 800) + (i * 20);\t//south-east: 350\n\t\t\t})\n\t\t\t//.attr(\"y\", height - 500)\n\t\t\t.attr(\"width\", 10)\n\t\t\t.attr(\"height\", 10)\n\t\t\t.style(\"stroke\", \"black\")\n\t\t\t.style(\"stroke-width\", 1)\n\t\t\t.style(\"fill\", function(d){return d;}); \n\n\t\tlegend\n\t\t\t.append('text')\n\t\t\t.attr(\"x\", width - 60) //leave space of about 5 pixel after the rectangles, south-east: 150\n\t\t\t.attr(\"y\", function(d, i) {\n\t\t\t\treturn (height - 800) + (i * 20);\t//south-east: 350\n\t\t\t})\n\t\t\t.attr(\"dy\", \"0.8em\") //place text one line \"below\" the x,y point\n\t\t\t.text(function(d,i) {\n\t\t\t\tvar extent = color.invertExtent(d);\n\t\t\t\t//extent will be a two-element array, format it however you want:\n\t\t\t\tvar format = d3.format(\"0.2f\");\n\t\t\t\tconsole.log(i);\n\t\t\t\tconsole.log(d);\n\t\t\t\tconsole.log(extent[0]);\n\t\t\t\tif (i == 0) {\n\t\t\t\t\treturn \"0 - <= \" + format(+extent[1]);\n\t\t\t\t}\n\t\t\t\telse if (i == domain.length) {\n\t\t\t\t\treturn \"> \" + format(+extent[0]);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn format(+extent[0]) + \" - <= \" + format(+extent[1]);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t});*/\n\t\n\t});\t\n\t\n });\n}",
"function drawMap(target) {\n var basic_choropleth = new Datamap({\n scope: 'world',\n element: document.getElementById(target),\n geographyConfig: {\n highlightBorderColor: '#bada55',\n popupTemplate: function(geography, data) {\n if (data) return '<div class=\"hoverinfo\">' + geography.properties.name +\n '<table><tr><td>Total population:</td><td align=right>' + data.total_population +\n '</td></tr>' + '<tr><td>Sample population:</td><td align=right>' + data.sample_population +\n '</td></tr>' + '<tr><td>Coverage index:</td><td align=right>' + data.coverage_index +\n '</td></tr></table></div>';\n else return '<div class=\"hoverinfo\">' + geography.properties.name + '</div>'\n },\n highlightBorderWidth: 3\n },\n projection: 'mercator',\n height: 600,\n fills: {\n defaultFill: \"#afafaf\",\n oecd: \"#7fcc66\",\n partner: \"#7f66cc\"\n },\n data: mapdata\n });\n basic_choropleth.legend();\n }",
"function mapData(stateData) {\n\n var selHtml = d3.select(\"#selDataset\");\n var yearSelected = selHtml.property(\"value\");\n\n var yrSelVal = stateData.filter(function (y) {\n return y.year === yearSelected;\n })\n // console.log(yrSelVal);\n var states = yrSelVal.map(st => st.state);\n var state_abbr = yrSelVal.map(st => st.abbr);\n var temp = yrSelVal.map(t => t.avg_temp);\n var years = stateData.map(yr => yr.year);\n \n var cmap = [{\n type: 'choropleth',\n locationmode: 'USA-states',\n locations: state_abbr,\n z: temp,\n text: states,\n zmin: 15,\n zmax: 80,\n colorscale: 'Electric',\n colorbar: {\n title: 'Avg Temp',\n thickness: 10\n },\n marker: {\n line:{\n color: 'rgb(255,255,255)',\n width: 0.5\n }\n }\n }];\n\n var layout = {\n title: 'Average Annual Temperatures - 1900 - 2012',\n geo:{\n scope: 'usa',\n } \n }\n \n Plotly.newPlot(\"usmap\", cmap, layout);\n}",
"function mapOptions() {\n var mapStyles = [\n {\n 'elementType': 'geometry',\n 'stylers': [\n {\n 'color': '#1d2c4d'\n }\n ]\n },\n {\n 'elementType': 'labels.text.fill',\n 'stylers': [\n {\n 'color': '#8ec3b9'\n }\n ]\n },\n {\n 'elementType': 'labels.text.stroke',\n 'stylers': [\n {\n 'color': '#1a3646'\n }\n ]\n },\n {\n 'featureType': 'administrative.country',\n 'elementType': 'geometry.stroke',\n 'stylers': [\n {\n 'color': '#4b6878'\n }\n ]\n },\n {\n 'featureType': 'administrative.land_parcel',\n 'stylers': [\n {\n 'visibility': 'off'\n }\n ]\n },\n {\n 'featureType': 'administrative.land_parcel',\n 'elementType': 'labels.text.fill',\n 'stylers': [\n {\n 'color': '#64779e'\n }\n ]\n },\n {\n 'featureType': 'administrative.neighborhood',\n 'stylers': [\n {\n 'visibility': 'off'\n }\n ]\n },\n {\n 'featureType': 'administrative.province',\n 'elementType': 'geometry.stroke',\n 'stylers': [\n {\n 'color': '#4b6878'\n }\n ]\n },\n {\n 'featureType': 'landscape.man_made',\n 'elementType': 'geometry.stroke',\n 'stylers': [\n {\n 'color': '#334e87'\n }\n ]\n },\n {\n 'featureType': 'landscape.natural',\n 'elementType': 'geometry',\n 'stylers': [\n {\n 'color': '#023e58'\n }\n ]\n },\n {\n 'featureType': 'poi',\n 'elementType': 'geometry',\n 'stylers': [\n {\n 'color': '#283d6a'\n }\n ]\n },\n {\n 'featureType': 'poi',\n 'elementType': 'labels.text',\n 'stylers': [\n {\n 'visibility': 'off'\n }\n ]\n },\n {\n 'featureType': 'poi',\n 'elementType': 'labels.text.fill',\n 'stylers': [\n {\n 'color': '#6f9ba5'\n }\n ]\n },\n {\n 'featureType': 'poi',\n 'elementType': 'labels.text.stroke',\n 'stylers': [\n {\n 'color': '#1d2c4d'\n }\n ]\n },\n {\n 'featureType': 'poi.park',\n 'elementType': 'geometry.fill',\n 'stylers': [\n {\n 'color': '#023e58'\n }\n ]\n },\n {\n 'featureType': 'poi.park',\n 'elementType': 'labels.text.fill',\n 'stylers': [\n {\n 'color': '#3C7680'\n }\n ]\n },\n {\n 'featureType': 'road',\n 'elementType': 'geometry',\n 'stylers': [\n {\n 'color': '#304a7d'\n }\n ]\n },\n {\n 'featureType': 'road',\n 'elementType': 'labels',\n 'stylers': [\n {\n 'visibility': 'off'\n }\n ]\n },\n {\n 'featureType': 'road',\n 'elementType': 'labels.text.fill',\n 'stylers': [\n {\n 'color': '#98a5be'\n }\n ]\n },\n {\n 'featureType': 'road',\n 'elementType': 'labels.text.stroke',\n 'stylers': [\n {\n 'color': '#1d2c4d'\n }\n ]\n },\n {\n 'featureType': 'road.arterial',\n 'stylers': [\n {\n 'visibility': 'off'\n }\n ]\n },\n {\n 'featureType': 'road.highway',\n 'elementType': 'geometry',\n 'stylers': [\n {\n 'color': '#2c6675'\n }\n ]\n },\n {\n 'featureType': 'road.highway',\n 'elementType': 'geometry.stroke',\n 'stylers': [\n {\n 'color': '#255763'\n }\n ]\n },\n {\n 'featureType': 'road.highway',\n 'elementType': 'labels',\n 'stylers': [\n {\n 'visibility': 'off'\n }\n ]\n },\n {\n 'featureType': 'road.highway',\n 'elementType': 'labels.text.fill',\n 'stylers': [\n {\n 'color': '#b0d5ce'\n }\n ]\n },\n {\n 'featureType': 'road.highway',\n 'elementType': 'labels.text.stroke',\n 'stylers': [\n {\n 'color': '#023e58'\n }\n ]\n },\n {\n 'featureType': 'road.local',\n 'stylers': [\n {\n 'visibility': 'off'\n }\n ]\n },\n {\n 'featureType': 'transit',\n 'elementType': 'labels.text.fill',\n 'stylers': [\n {\n 'color': '#98a5be'\n }\n ]\n },\n {\n 'featureType': 'transit',\n 'elementType': 'labels.text.stroke',\n 'stylers': [\n {\n 'color': '#1d2c4d'\n }\n ]\n },\n {\n 'featureType': 'transit.line',\n 'elementType': 'geometry.fill',\n 'stylers': [\n {\n 'color': '#283d6a'\n }\n ]\n },\n {\n 'featureType': 'transit.station',\n 'elementType': 'geometry',\n 'stylers': [\n {\n 'color': '#3a4762'\n }\n ]\n },\n {\n 'featureType': 'water',\n 'elementType': 'geometry',\n 'stylers': [\n {\n 'color': '#0e1626'\n }\n ]\n },\n {\n 'featureType': 'water',\n 'elementType': 'labels.text',\n 'stylers': [\n {\n 'visibility': 'off'\n }\n ]\n },\n {\n 'featureType': 'water',\n 'elementType': 'labels.text.fill',\n 'stylers': [\n {\n 'color': '#4e6d70'\n }\n ]\n }\n ],\n mapOptions = {\n backgroundColor: 'rgba(255, 255, 255, 0.3)',\n center: {\n lat: officeLatCoord,\n lng: officeLonCoord\n },\n disableDefaultUI: true,\n mapTypeId: 'roadmap',\n scrollwheel: false,\n styles: mapStyles\n },\n directionsOptions = {\n suppressMarkers: true,\n polylineOptions: {\n strokeColor: styleOptions.mapStroke,\n strokeOpacity: styleOptions.mapStrokeOpacity,\n strokeWeight: styleOptions.mapStrokeWeight\n }\n };\n\n buildMap(mapOptions, directionsOptions);\n }",
"function mapstyle (){\n var date = new Date();\n var day_map = [{\"featureType\":\"landscape.natural\",\"elementType\":\"geometry.fill\",\"stylers\":[{\"visibility\":\"on\"},{\"color\":\"#e0efef\"}]},{\"featureType\":\"poi\",\"elementType\":\"geometry.fill\",\"stylers\":[{\"visibility\":\"on\"},{\"hue\":\"#1900ff\"},{\"color\":\"#c0e8e8\"}]},{\"featureType\":\"road\",\"elementType\":\"geometry\",\"stylers\":[{\"lightness\":100},{\"visibility\":\"simplified\"}]},{\"featureType\":\"road\",\"elementType\":\"labels\",\"stylers\":[{\"visibility\":\"off\"}]},{\"featureType\":\"transit.line\",\"elementType\":\"geometry\",\"stylers\":[{\"visibility\":\"on\"},{\"lightness\":700}]},{\"featureType\":\"water\",\"elementType\":\"all\",\"stylers\":[{\"color\":\"#7dcdcd\"}]}];\n var night_map = [{\"featureType\":\"all\",\"elementType\":\"labels.text.fill\",\"stylers\":[{\"color\":\"#ffffff\"}]},{\"featureType\":\"all\",\"elementType\":\"labels.text.stroke\",\"stylers\":[{\"color\":\"#000000\"},{\"lightness\":13}]},{\"featureType\":\"administrative\",\"elementType\":\"geometry.fill\",\"stylers\":[{\"color\":\"#000000\"}]},{\"featureType\":\"administrative\",\"elementType\":\"geometry.stroke\",\"stylers\":[{\"color\":\"#144b53\"},{\"lightness\":14},{\"weight\":1.4}]},{\"featureType\":\"landscape\",\"elementType\":\"all\",\"stylers\":[{\"color\":\"#08304b\"}]},{\"featureType\":\"poi\",\"elementType\":\"geometry\",\"stylers\":[{\"color\":\"#0c4152\"},{\"lightness\":5}]},{\"featureType\":\"road.highway\",\"elementType\":\"geometry.fill\",\"stylers\":[{\"color\":\"#000000\"}]},{\"featureType\":\"road.highway\",\"elementType\":\"geometry.stroke\",\"stylers\":[{\"color\":\"#0b434f\"},{\"lightness\":25}]},{\"featureType\":\"road.arterial\",\"elementType\":\"geometry.fill\",\"stylers\":[{\"color\":\"#000000\"}]},{\"featureType\":\"road.arterial\",\"elementType\":\"geometry.stroke\",\"stylers\":[{\"color\":\"#0b3d51\"},{\"lightness\":16}]},{\"featureType\":\"road.local\",\"elementType\":\"geometry\",\"stylers\":[{\"color\":\"#000000\"}]},{\"featureType\":\"transit\",\"elementType\":\"all\",\"stylers\":[{\"color\":\"#146474\"}]},{\"featureType\":\"water\",\"elementType\":\"all\",\"stylers\":[{\"color\":\"#021019\"}]}];\n var breakout_map_2015 = [\n {\n \"featureType\": \"administrative\",\n \"elementType\": \"labels.text\",\n \"stylers\": [\n {\n \"visibility\": \"on\"\n }\n ]\n },\n {\n \"featureType\": \"administrative\",\n \"elementType\": \"labels.icon\",\n \"stylers\": [\n {\n \"visibility\": \"simplified\"\n }\n ]\n },\n {\n \"featureType\": \"administrative.country\",\n \"elementType\": \"geometry.stroke\",\n \"stylers\": [\n {\n \"color\": \"#ababab\"\n }\n ]\n },\n {\n \"featureType\": \"administrative.province\",\n \"elementType\": \"geometry.stroke\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"administrative.locality\",\n \"elementType\": \"all\",\n \"stylers\": [\n {\n \"visibility\": \"on\"\n }\n ]\n },\n {\n \"featureType\": \"administrative.locality\",\n \"elementType\": \"labels.text\",\n \"stylers\": [\n {\n \"visibility\": \"on\"\n }\n ]\n },\n {\n \"featureType\": \"administrative.locality\",\n \"elementType\": \"labels.text.fill\",\n \"stylers\": [\n {\n \"color\": \"#404041\"\n }\n ]\n },\n {\n \"featureType\": \"landscape\",\n \"elementType\": \"geometry\",\n \"stylers\": [\n {\n \"visibility\": \"on\"\n },\n {\n \"color\": \"#e3e3e3\"\n }\n ]\n },\n {\n \"featureType\": \"poi\",\n \"elementType\": \"all\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"road\",\n \"elementType\": \"geometry.fill\",\n \"stylers\": [\n {\n \"color\": \"#cccccc\"\n }\n ]\n },\n {\n \"featureType\": \"road\",\n \"elementType\": \"geometry.stroke\",\n \"stylers\": [\n {\n \"color\": \"#cccccc\"\n },\n {\n \"weight\": \"0.50\"\n }\n ]\n },\n {\n \"featureType\": \"road\",\n \"elementType\": \"labels.icon\",\n \"stylers\": [\n {\n \"saturation\": \"-100\"\n }\n ]\n },\n {\n \"featureType\": \"road.highway\",\n \"elementType\": \"all\",\n \"stylers\": [\n {\n \"visibility\": \"simplified\"\n }\n ]\n },\n {\n \"featureType\": \"road.highway\",\n \"elementType\": \"labels\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"road.arterial\",\n \"elementType\": \"all\",\n \"stylers\": [\n {\n \"visibility\": \"on\"\n }\n ]\n },\n {\n \"featureType\": \"road.local\",\n \"elementType\": \"all\",\n \"stylers\": [\n {\n \"visibility\": \"on\"\n }\n ]\n },\n {\n \"featureType\": \"transit\",\n \"elementType\": \"labels.icon\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"transit.line\",\n \"elementType\": \"geometry\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"transit.line\",\n \"elementType\": \"labels.text\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"transit.station.airport\",\n \"elementType\": \"geometry\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"transit.station.airport\",\n \"elementType\": \"labels\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n },\n {\n \"featureType\": \"water\",\n \"elementType\": \"geometry\",\n \"stylers\": [\n {\n \"color\": \"#b1b1b1\"\n }\n ]\n },\n {\n \"featureType\": \"water\",\n \"elementType\": \"labels\",\n \"stylers\": [\n {\n \"visibility\": \"off\"\n }\n ]\n }\n];\n // var hour = date.getHours();\n // if(6 < hour && hour < 21) {\n // return night_map;\n // } else { \n // return day_map; \n // }\n return breakout_map_2015;\n}",
"function createMapAndLegend(world, gameData, selectedGame){ \n\n d3.select(\"svg.choro\").remove();\n \n var svg = d3.select(\"div#choropleth\")\n .append(\"svg\")\n .attr(\"class\", \"choro\")\n .attr(\"width\", width + margin.left + margin.right)\n .attr(\"height\", height + margin.top + margin.bottom)\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");\n \n var tooltip = d3.tip()\n .attr(\"class\", \"country-tool-tip\")\n .direction(\"s\")\n .html(function(d) {\n for (let i = 0; i < gameData_g.length; i++) {\n if (gameData_g[i][\"Country\"] == d.properties.name) {\n return \"<p>Country: \" + d.properties.name + \"<br/>\" +\n \"Game: \" + gameData_g[i][\"Game\"] + \"<br/>\" +\n \"Avg Rating: \" + gameData_g[i][\"Average Rating\"] + \"<br/>\" +\n \"Number of Users: \" + gameData_g[i][\"Number of Users\"] + \"</p>\";\n }\n }\n return \"<p>Country: \" + d.properties.name + \"<br/>\" +\n \"Game: \" + gameData_g[0][\"Game\"] + \"<br/>\" +\n \"Avg Rating: N/A <br/>\" +\n \"Number of Users: N/A </p>\";\n });\n svg.call(tooltip);\n\n console.log(\"Selected game: \" + selectedGame);\n gameData = gameData.filter(function(g) { return g[\"Game\"] == selectedGame;});\n gameData_g = gameData;\n\n var projection = d3.geoMercator()\n .scale(width/10)\n .translate([width/2, height/2])\n var path = d3.geoPath().projection(projection);\n\n var quantile = d3.scaleQuantile()\n .domain(gameData.map(function(g) { return +g[\"Average Rating\"];}))\n .range([\"#eff3ff\", \"#bdd7e7\", \"#6baed6\", \"#2171b5\"])\n\n var getColorOfCountry = function(country) {\n for (let i = 0; i < gameData_g.length; i++) {\n if (gameData_g[i][\"Country\"] == country) {\n return quantile(gameData_g[i][\"Average Rating\"]);\n }\n }\n return \"gray\";\n }\n\n svg.selectAll(\"path\")\n .data(world.features)\n .enter()\n .append(\"path\")\n .attr(\"class\", \"continent\")\n .attr(\"d\", path)\n .attr(\"fill\", function(d) { return getColorOfCountry(d.properties.name); })\n .on(\"mouseover\", tooltip.show)\n .on(\"mouseout\", tooltip.hide);\n\n quantiles = [d3.min(quantile.domain()), ...quantile.quantiles(), d3.max(quantile.domain())]\n quantiles = [[quantiles[0], quantiles[1]],[quantiles[1],quantiles[2]],[quantiles[2],quantiles[3]],[quantiles[3],quantiles[4]]]\n var i = 0;\n var legend = svg.selectAll(\"legend\")\n .data(quantiles)\n .enter()\n .append(\"g\")\n .attr(\"class\", \"lenged\")\n .style(\"text-anchor\", \"left\")\n .attr(\"transform\", function(d) {\n i++;\n return \"translate(\" + width/1.15 + \",\" + i * 20 + \")\";\n })\n legend.append(\"text\")\n .text(function(d) { return d[0].toFixed(2) + \" to \" + d[1].toFixed(2); });\n \n legend.append(\"rect\")\n .attr(\"width\", 10)\n .attr(\"height\", 10)\n .attr(\"transform\", \"translate(\" + -15 + \",\" + -10 + \")\")\n .attr(\"stroke\", \"black\")\n .attr(\"fill\", function(d) { return quantile(d[0]); });\n \n d3.select(\"div#choropleth\")\n .append(\"text\")\n .text(\"byang301\")\n}",
"function drawMap(mapPlotData) {\n /** Clear anything currently on the map **/\n console.time(\"query_aql_draw\");\n var maxWeight = 10; \n var minWeight = 0;\n\n // find max/min weight\n $.each(mapPlotData, function (i, data) {\n if (data.count) {\n maxWeight = Math.max(data.count, maxWeight);\n //minWeight = Math.min(data.count, minWeight);\n }\n });\n\n var range = maxWeight - minWeight;\n if (range < 0) {\n range = 0\n maxWeight = 0\n minWeight = 0\n }\n if (range < 10){\n range = 10\n }\n\n colors = ['#053061', '#2166ac', '#4393c3', '#92c5de', '#d1e5f0', '#f7f7f7', '#fddbc7', '#f4a582', '#d6604d', '#b2182b', '#67001f'];\n // style function\n function getColor(d) {\n return d > minWeight + range * 0.9 ? colors[10] :\n d > minWeight + range * 0.8 ? colors[9] :\n d > minWeight + range * 0.7 ? colors[8] :\n d > minWeight + range * 0.6 ? colors[7] :\n d > minWeight + range * 0.5 ? colors[6] :\n d > minWeight + range * 0.4 ? colors[5] :\n d > minWeight + range * 0.3 ? colors[4] :\n d > minWeight + range * 0.2 ? colors[3] :\n d > minWeight + range * 0.1 ? colors[2] :\n d > minWeight ? colors[1] :\n colors[0];\n }\n\n function style(feature) {\n return {\n fillColor: getColor(feature.properties.count),\n weight: 2,\n opacity: 1,\n color: 'white',\n dashArray: '3',\n fillOpacity: 0.5\n };\n }\n\n // draw geojson polygons\n if (logicLevel == \"state\") {\n // transfer to geohash\n $.each(mapPlotData, function (m, data) {\n for (var hash in state_hash) {\n if (state_hash.hasOwnProperty(hash)) {\n if (hash == mapPlotData[m].cell) {\n var val = state_hash[hash];\n mapPlotData[m].cell = val;\n }\n }\n }\n });\n\n // update states count\n $.each(state.features, function (i, d) {\n if (d.properties.count)\n d.properties.count = 0;\n for (var m in mapPlotData) {\n if (mapPlotData[m].cell == d.properties.NAME)\n d.properties.count = mapPlotData[m].count;\n }\n });\n\n // draw state polygons\n statePolygons.setStyle(style);\n } else if (logicLevel == \"county\") {\n // update county's count\n $.each(county.features, function (i, d) {\n if (d.properties.count)\n d.properties.count = 0;\n for (var m in mapPlotData) {\n if (mapPlotData[m].cell && mapPlotData[m].cell.slice(3, mapPlotData[m].cell.length) == d.properties.NAME)\n d.properties.count = mapPlotData[m].count;\n }\n });\n\n // draw county polygons\n countyPolygons.setStyle(style);\n }\n // add legend\n if ($('.legend'))\n $('.legend').remove();\n\n var legend = L.control({\n position: 'topleft'\n });\n\n legend.onAdd = function (map) {\n var div = L.DomUtil.create('div', 'info legend'),\n grades = [0],\n labels = [];\n\n for (var i = 1; i < 10; i++) {\n var value = Math.floor((i * 1.0 / 10) * range + minWeight);\n if (value > grades[i-1]) {\n grades.push(value);\n }\n }\n\n // loop through our density intervals and generate a label with a colored square for each interval\n for (var i = 0; i < grades.length; i++) {\n div.innerHTML +=\n '<i style=\"background:' + getColor(grades[i]) + '\"></i> ' +\n grades[i] + (grades[i + 1] ? '–' + grades[i + 1] + '<br>' : '+');\n }\n\n return div;\n };\n\n legend.addTo(map);\n\n console.timeEnd(\"query_aql_draw\");\n}",
"function buildmap(yearmap){\n //Get data and filter by state\n d3.json('static/data/state_data.json').then(function(states){\n var year=yearmap;\n var tempfilteredyear=states.filter(states=>states.year==year);\n var filteredyear=tempfilteredyear.filter(tempfilteredyear=>tempfilteredyear.state!='US');\n var states=filteredyear.map(state=>state.state);\n var statenames=filteredyear.map(state=>state.state_name);\n var greenhousevalues=filteredyear.map(state=>state.greenhouse_emissions);\n var generationvalues=filteredyear.map(state=>state.generation_mwh_total);\n var coolingvalues=filteredyear.map(state=>state.cooling_degree_days);\n //Create year greenhouse emissions map plot\n var mapdata=[{\n type:'choropleth',\n locationmode:'USA-states',\n locations:states,\n z:greenhousevalues,\n text:statenames,\n autocolorscale:true}];\n var maplayout={\n title:`${year} State Greenhouse Emissions (metric tons of carbon dioxide)`,\n plot_bgcolor:'rgb(215,215,215)',\n paper_bgcolor:'rgb(215,215,215)',\n geo:{\n bgcolor:'rgb(215,215,215)',\n scope:'usa',\n countrycolor:'rgb(255,255,255)',\n showland:true,\n landcolor:'rgb(255,255,255)',\n showlakes:true,\n lakecolor:'rgb(52,177,242)',\n subunitcolor:'rgb(255,255,255)',\n lonaxis:{},\n lataxis:{}}};\n Plotly.newPlot('chart3',mapdata,maplayout);\n //Create year generation map plot\n var mapdata=[{\n type:'choropleth',\n locationmode:'USA-states',\n locations:states,\n z:generationvalues,\n text:statenames,\n autocolorscale:true}];\n var maplayout={\n title:`${year} State Power Generation (MWh)`,\n plot_bgcolor:'rgb(215,215,215)',\n paper_bgcolor:'rgb(215,215,215)',\n geo:{\n bgcolor:'rgb(215,215,215)',\n scope:'usa',\n countrycolor:'rgb(255,255,255)',\n showland:true,\n landcolor:'rgb(255,255,255)',\n showlakes:true,\n lakecolor:'rgb(52,177,242)',\n subunitcolor:'rgb(255,255,255)',\n lonaxis:{},\n lataxis:{}}};\n Plotly.newPlot('chart4',mapdata,maplayout);\n //Create year cooling degree days map plot\n var mapdata=[{\n type:'choropleth',\n locationmode:'USA-states',\n locations:states,\n z:coolingvalues,\n text:statenames,\n autocolorscale:true}];\n var maplayout={\n title:`${year} State Cooling Degree Days`,\n plot_bgcolor:'rgb(215,215,215)',\n paper_bgcolor:'rgb(215,215,215)',\n geo:{\n bgcolor:'rgb(215,215,215)',\n scope:'usa',\n countrycolor:'rgb(255,255,255)',\n showland:true,\n landcolor:'rgb(255,255,255)',\n showlakes:true,\n lakecolor:'rgb(52,177,242)',\n subunitcolor:'rgb(255,255,255)',\n lonaxis:{},\n lataxis:{}}};\n Plotly.newPlot('chart5',mapdata,maplayout);\n });}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
wrapper to publish message to redis channel | function publishMsg(channel, message) {
var redisClient = redis.createClient();
redisClient.publish(channel, message);
} | [
"publish (payload) {\n // get default Redis channel\n let channel = this.api.config.general.channel\n\n // publish redis message\n this.clients.client.publish(channel, JSON.stringify(payload))\n }",
"publish(payload) {\n // get default Redis channel\n let channel = this.api.config.general.channel;\n\n // publish redis message\n this.clients.client.publish(channel, JSON.stringify(payload));\n }",
"rawPublish(channel, message) {\n return new Promise((resolve, reject) => {\n if (channel) {\n this._redisPublisher.publish(channel, message).then(() => {\n resolve()\n }).catch(err => reject(err))\n } else {\n reject(new Error('channel missing'))\n }\n })\n }",
"publish(channel, message) {\n return new Promise((resolve, reject) => {\n if (channel) {\n this._redisPublisher.publish(channel, this.encoder.pack(message)).then(() => {\n resolve()\n }).catch(err => reject(err))\n } else {\n reject(new Error('channel missing'))\n }\n })\n }",
"publish (topic, message) {\n\n this.send({\n action: 'publish',\n payload: {\n topic: topic,\n message: message,\n },\n })\n\n }",
"function publishRedis (queue,tr) {\n msgout = { \"tr_id\": tr.id, \"tr_timestamp\": tr.timestamp, \"tr_price\": tr.price, \"tr_amount\": tr.amount, \"tr_side\": tr.side };\n client.publish(queue,JSON.stringify(msgout));\n}",
"publish (topic, message) {\n this.client.publish(topic, message)\n }",
"publish({ channel, message }) {\n // there is an unsubscribe function in pubnub\n // but it doesn't have a callback that fires after success\n // therefore, redundant publishes to the same local subscriber will be accepted as noisy no-ops\n this.pubnub.publish({ message, channel });\n }",
"function pub() {\n return redisSyncPub_.publish(ns.settings.redisSyncChannel, JSON.stringify({\n requestAt: new Date().getTime(),\n syncId: syncId,\n expire:ns.settings.redisSyncFrequency * 2\n }));\n }",
"function publishToChannel(channel, { routingKey, exchangeName, data }) {\n return new Promise((resolve, reject) => {\n channel.publish(exchangeName, routingKey, Buffer.from(JSON.stringify(data), 'utf-8'), { persistent: true }, function (err, ok) {\n if (err) {\n return reject(err);\n }\n\n resolve();\n })\n });\n}",
"function publish(pubnub, channel, data) {\n pubnub.publish({\n channel: channel,\n message: data\n }, (status, response) => {\n console.log(channel, status, response);\n });\n}",
"static async redisSave(message){\n\n try{\n // 0. generate a uuid for this message\n message.id = uuidv4();\n\n await Promise.all([\n // 1. create the hash entry\n Message.redisSaveMessageHash(message),\n\n // 2. create the zset entry\n Message.redisSaveChannelMessageZset(message),\n\n // 3. update the message count for the channel\n Message.redisUpdateChannelMessageCountRedis(message),\n\n // 4. update the last_updated timestamp\n Message.redisUpdateChannelLastUpdatedRedis(message),\n ]);\n\n return message\n }\n catch(err){\n throw err;\n }\n }",
"async function publish (nc, msg = '', enc) {\n console.log(`Publish message in the queue '${k.queueName}'`)\n assert(nc !== null)\n assert(enc !== null)\n nc.publish(k.queueName, enc.encode(msg))\n}",
"function publish (topic, data) {\n\n }",
"function pub(channel, message){\n\t\"use strict\";\n\tpubnub.publish({\n\t\tchannel: channel,\n\t\tmessage: message\n\t});\n}",
"static publish(queue, event, payload) {\n let q = io.connect(`${SERVER}`);\n let message = {queue,event,payload};\n q.emit('publish', message, (ret) => {\n q.disconnect();\n });\n }",
"_write(data, encoding, next) {\n const message = new Buffer(JSON.stringify({\n account: this.accountName,\n source: this.source,\n data,\n }));\n this.channel.publish(EXCHANGE_NAME, '', message, { persistent: true }, (err) => {\n next(err);\n });\n }",
"publish(channelName, ...args) {\n if (channelName && channelName !== '') {\n let channel = this.getChannel(channelName, true);\n if (channel && channel.namespace === channelName) {\n args.push(channel)\n channel.publish(args);\n }\n }\n }",
"async function publish (nc, msg = '', enc = fastify.NATS.StringCodec()) {\r\n console.log(`Publish message in the queue '${k.queueName}'`)\r\n assert(nc !== null)\r\n nc.publish(k.queueName, enc.encode(msg)) // simple publisher\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a promise for response headers from the mock data. | promiseHeaders() {
var _a;
const headers = (_a = this.data.headers) !== null && _a !== void 0 ? _a : TestTransport.defaultHeaders;
return headers instanceof RpcError
? Promise.reject(headers)
: Promise.resolve(headers);
} | [
"async resolveHeaders() {\n return {};\n }",
"async _getHeaders() {\n const authToken = await this.authService.getToken();\n return this._headers(authToken.access_token);\n }",
"getRequestHeaders() {}",
"get headers() {\n let headers = {};\n try {\n this._log.trace(\"Processing response headers.\");\n let channel = this.request.channel.QueryInterface(Ci.nsIHttpChannel);\n channel.visitResponseHeaders(function (header, value) {\n headers[header.toLowerCase()] = value;\n });\n } catch (ex) {\n this._log.debug(\"Caught exception processing response headers:\" +\n Utils.exceptionStr(ex));\n return null;\n }\n\n delete this.headers;\n return this.headers = headers;\n }",
"function getXHRRequestPromise(url, body, authToken, method, desiredHeader) {\n return new Promise(function(resolve, reject) {\n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n // so the session cookie is included\n xhr.withCredentials = true;\n xhr.setRequestHeader('content-type', 'application/json');\n xhr.setRequestHeader(\"Accept\", \"application/json\");\n if (authToken) {\n xhr.setRequestHeader(\"X-MSTR-AuthToken\", authToken);\n }\n xhr.onreadystatechange = function() {\n if (xhr.readyState != 2) {\n return reject({\n status: this.status,\n statusText: xhr.statusText\n });\n }\n\n console.log(\"getXHRRequestPromise response headers: \", xhr.getAllResponseHeaders());\n if (desiredHeader) {\n return resolve(xhr.getResponseHeader(desiredHeader));\n }\n\n return resolve(xhr.getAllResponseHeaders());\n };\n xhr.send(JSON.stringify(body));\n });\n}",
"function headers(){ return headers; }",
"get headers() {\n return new Headers(this._headers);\n }",
"getHeaderObject() {\n\n // create headers object\n const headers = {};\n\n for (const [header, value] of this._headers.entries()) {\n headers[header] = value;\n }\n\n return headers;\n }",
"getResponseHeaders () {\n return this.request('getResponseHeaders')\n }",
"function makeHeaders() {\n let headers = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n };\n if (token_real !== null) {\n headers.Authorization = 'Token ' + token_real;\n }\n return headers;\n}",
"function connectAndGetRequestHeadersFrom(server)\n{\n return new Promise(function(resolve, reject) {\n var header_ws = new WebSocket(server + '/echo-request-headers');\n header_ws.onmessage = function (evt) {\n try {\n var headers = JSON.parse(evt.data);\n resolve(headers);\n } catch (e) {\n reject(\"Unexpected exception from JSON.parse: \" + e);\n }\n // The stringify() call in header_ws.onclose can cause a\n // \"'WebSocket.URL' is deprecated.\" error as a side-effect even\n // though the reject() call itself does nothing. Clear out the\n // handlers to prevent unwanted side-effects.\n header_ws.onerror = undefined;\n header_ws.onclose = undefined;\n };\n header_ws.onerror = function () {\n reject('Unexpected error event');\n };\n header_ws.onclose = function (evt) {\n reject('Unexpected close event: ' + JSON.stringify(evt));\n };\n });\n}",
"function getHeaders() {\n if (typeof that.headers != 'undefined') {\n return that.headers;\n } else {\n load_pgn();\n return that.headers;\n }\n }",
"get headers(){\n\t\tvar result={};\n\t\ttry{\n\t\t\tvar headerNames = Myna.JavaUtils.enumToArray($server.request.getHeaderNames());\n\t\t\theaderNames.forEach(function(name){\n\t\t\t\t//try to detect date headers\n\t\t\t\ttry {\n\t\t\t\t\tresult[name] = new Date($server.request.getDateHeader(name));\n\t\t\t\t} catch (e){\n\t\t\t\t\tvar values =Myna.JavaUtils.enumToArray($server.request.getHeaders(name))\n\t\t\t\t\tif (values.length == 1){\n\t\t\t\t\t\tvalues = String(values[0]).split(/,/)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvalues = values.map(function(value){return String(value)})\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tresult[name] =values;\n\t\t\t\t\tresult[name.toLowerCase()]=result[name];\n\t\t\t\t\t/* result.hideProperty(name.toLowerCase()); */\n\t\t\t\t}\n\t\t\t});\n\t\t} catch(e){}\n\t\treturn result;\n\t}",
"_getFullHeadersHash(headers = {}) {\n return assign({}, this.headers, headers);\n }",
"static getResponseHeaders(headers) {\n const data = {};\n for (const pair of headers.entries()) {\n const [name, value] = pair;\n const entry = name.toLowerCase();\n const current = data[entry];\n if (current === void 0) {\n data[entry] = value;\n }\n else if (current instanceof Array) {\n current.push(value);\n }\n else {\n data[entry] = [current];\n }\n }\n return data;\n }",
"createHeaders() {\n\t\t// all requests for now are JSON\n\t\tconst header = {\n\t\t\tAccept: 'application/json',\n\t\t\t'Content-Type': 'application/json',\n\t\t};\n\t\t// if (this.sessionToken) header['Authorization'] = 'Bearer ' + this.sessionToken;\n\t\treturn header;\n\t}",
"function makeHeaders() {\n let headers = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n }\n if (sessionStorage.getItem('token'))\n headers['Authorization'] = 'Token ' + sessionStorage.getItem('token');\n\n return headers;\n}",
"static get responseHeaders() {\n\t\treturn this.response.headers;\n\t}",
"getHeaders() {\n\t\tlet headers = {\n\t\t\taccept: \"application/json\",\n\t\t\t\"x-ibm-client-id\": this.config.apiKey,\n\t\t\t\"x-ibm-client-secret\": this.config.apiSecret\n\t\t};\n\n\t\treturn headers;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates the cancel button, opens up the account entities section | function openAccountEntityAdd() {
if ($('#cancelEntityButton').length == 0) {
var cancelEntityButton = $("<input/>", {
"class" : "cancel btn btn-default",
"type" : "button",
"id" : "cancelEntityButton",
"click" : me.rosterCancelAction,
"value" : ap.core_prompts["action.Cancel"]
});
var accountEntitiesContainer = $('#accountEntitiesContainer');
accountEntitiesContainer.find('.btn-group').append(
cancelEntityButton);
$('#accountEntitiesContainer').css("display", 'block');
me.$mainButtonContainer.css("display", 'none');
$('#rosterDownFillEntitiesBtn').remove();
$('#rosterAddNewBtn').remove();
me.focusOnFirstField(true);
page.manageTabIndex();
forceIEtoRepaintFooter();
}
;
} | [
"function cancelButtonPressed() {\n \n // 0. Hide the buttons\n document.getElementById(\"button-group-2\").style.display = \"none\";\n \n // 0. Clear the checkboxes\n clearCheckboxes();\n \n // 1. Hide the New Application form and display the table with the selected application contents\n document.getElementById(\"prop-edit\").setAttribute(\"style\",\"display: none;\");\n document.getElementById(\"prop-table-full\").setAttribute(\"style\",\"\");\n \n }",
"function onCancelClick() {\n logger.info('cancel_button click event handler');\n clearAllErrors();\n closeKeyboards();\n $.edit_customer_profile.fireEvent('route', {\n page : 'profile',\n isCancel : true\n });\n}",
"function cancelOp() {\n\tshowButtons();\n\tdocument.getElementById(\"deleteShelf\").style.display=\"none\";\n\tdocument.getElementById(\"addShelf\").style.display=\"none\";\n\t\n}",
"cancel(){\n\t\t\tthis.sendAction('addColono')\n\t\t}",
"clickOnCancel(){\n logger.log(\"***** Clicking On Cancel *****\");\n browser.click(eval(applicationLocator.actions.btn_CancelPopUp));\n logger.log(\"***** Clicked On Cancel *****\");\n }",
"showCancel () {\n const order = this.order\n const page = this.page\n const remaining = order.qty - order.filled\n const asset = Order.isMarketBuy(order) ? app().assets[order.quoteID] : app().assets[order.baseID]\n page.cancelRemain.textContent = Doc.formatCoinValue(remaining, asset.info.unitinfo)\n page.cancelUnit.textContent = asset.info.unitinfo.conventional.unit.toUpperCase()\n this.showForm(page.cancelForm)\n }",
"function handleCancel() {\n var data = {sushiItems};\n var html = tableTemplate(data);\n $('#bodyContent').html(html);\n \n //hide the submit and cancel buttons for the form\n $('#newItemButton').css('display', 'inline-block');\n $('#clearTable').css('display', 'inline-block');\n $('#submit').css('display', 'none');\n $('#cancel').css('display', 'none');\n}",
"function btnCancel_onClick() {\n\t\t\tSP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.Cancel);\n\t\t}",
"function clickedCancel()\n{\n recordsetDialog.onClickCancel(window);\n}",
"function cancelButtonClicked() {\n setShowRecipePopup(!showRecipePopup);\n }",
"clickCancel() {\n return this\n .waitForElementVisible('@deleteListModalBtn')\n .assert.visible('@deleteListModalBtn')\n .click('@deleteListModalBtn');\n }",
"function cancel()\n {\n dirtyController.setDirty(false);\n hideWorkflowEditor();\n hideWorkflowUpdateEditor();\n selectWorflow(selectedWorkflow);\n }",
"function handleCancel() {\n console.log('clicked cancel');\n editMode = false;\n console.log('edit mode activated');\n $('#cancel-button-zone').empty();\n}",
"onRemoveAccountDialogCancelTap_() {\n this.actionMenuAccount_ = null;\n this.$.removeConfirmationDialog.cancel();\n this.shadowRoot.querySelector('#add-account-button').focus();\n }",
"function editzselex_cancel()\n{\n Element.update('zselex_modify', ' ');\n Element.show('zselex_articlecontent');\n editing = false;\n return;\n}",
"showCancel () {\n const order = this.order\n const page = this.page\n const remaining = order.qty - order.filled\n page.cancelRemain.textContent = Doc.formatCoinValue(remaining / 1e8)\n const symbol = Order.isMarketBuy(order) ? this.market.quote.symbol : this.market.base.symbol\n page.cancelUnit.textContent = symbol.toUpperCase()\n this.showForm(page.cancelForm)\n }",
"function cancelEmploymentType(){\n\tobjEmploymentType.form.ace('cancel');\n}",
"function cancelClicked() {\n clearAddStudentForm();\n}",
"handleDeleteAccountButtonClick() {\n this.openConfirmAccountDeletionDialog();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
update the selection list with all cameras available | function updateCameraList(cameras) {
try {
const listElement = document.querySelector('select#availableCameras');
listElement.innerHTML = '';
cameras
.map(camera => {
const cameraOption = document.createElement('option');
cameraOption.label = camera.label;
cameraOption.value = camera.deviceId;
return cameraOption;
})
.forEach(cameraOption => {
listElement.add(cameraOption);
});
} catch (error) {
console.error(error);
alert(`Unexpected error occured!`);
}
} | [
"function updateCameraList(cameras) {\n let listElement = document.querySelector('select#videoSelect');\n listElement.innerHTML = '';\n cameras.forEach(camera => {\n const cameraOption = document.createElement('option');\n cameraOption.label = camera.label;\n cameraOption.value = camera.deviceId;\n listElement.appendChild(cameraOption)\n })\n}",
"function updateCameraList(cameras) {\n const listElement = document.querySelector(\"select#availableCameras\");\n listElement.innerHTML = \"\";\n cameras\n .map((camera) => {\n const cameraOption = document.createElement(\"option\");\n cameraOption.label = camera.label;\n cameraOption.value = camera.deviceId;\n })\n .forEach((cameraOption) => listElement.add(cameraOption));\n}",
"function updateCameraList(cameras) {\n const listElement = document.querySelector('select#availableCameras');\n listElement.innerHTML = '';\n cameras.map(camera => {\n const cameraOption = document.createElement('option');\n cameraOption.label = camera.label;\n cameraOption.value = camera.deviceId;\n return cameraOption;\n }).forEach(cameraOption => {\n // listElement.add(cameraOption)\n listElement.appendChild(cameraOption)\n // console.log(cameraOption);\n });\n}",
"function updateVideoInput(cameras) {\n const listElement = document.getElementById('availableVideoInput');\n listElement.innerHTML = '';\n let count = 1;\n cameras.forEach(camera => {\n const option = document.createElement('option');\n option.value = camera.deviceId;\n const label = camera.label || `Video Input ${count++}`;\n const textNode = document.createTextNode(label);\n option.appendChild(textNode);\n listElement.appendChild(option);\n })\n}",
"function setCandidateDevices(videoDevices) {\n videoDevices.forEach(function(device, index) {\n let option = document.createElement('option');\n option.setAttribute('value', device.deviceId);\n let label = device.label !== \"\" ? device.label : (\"camera \" + index);\n option.innerHTML = label;\n camera_selector.appendChild(option);\n });\n}",
"function agora_get_camera_devices() {\r\n client.getCameras(function (cameras) {\r\n devices.cameras = cameras;\r\n cameras.forEach(function (camera, i) {\r\n var name = camera.label.split('(')[0];\r\n var optionId = 'camera_' + i;\r\n var deviceId = camera.deviceId;\r\n \r\n if(shouldFaceUser===true){\r\n if(i == 1){\r\n localStreams.camera.camId = deviceId;\r\n }\r\n\r\n }else{\r\n localStreams.camera.camId = deviceId;\r\n }\r\n /* update camera-list */\r\n $('#camera-list').append('<div class=\"dropdown-item pointer js_live-change-camera\" id=\"' + optionId + '\">' + name + '</div>');\r\n });\r\n });\r\n}",
"function build_cameras(rover) {\n\t\tif (rover !== \"curiosity\") {\n\t\t\trover = \"other\"\n\t\t}\n\n\t\t$camera.empty();\n\n\t\tfor(var prop in cameras[rover]) {\n\t\t\t$camera.append($('<option>').attr('value', cameras[rover][prop]).text(prop));\n\t\t}\n\t}",
"updateCamera() {\n this.camera = this.cameras[this.selectedCamera];\n this.interface.setActiveCamera(this.camera);\n }",
"function gotDevices(deviceInfos) {\r\n\tvar videoSelect = document.querySelector(\"#videosource\");\r\n\t for (var i = 0; i !== deviceInfos.length; ++i) {\r\n\t\tvar deviceInfo = deviceInfos[i];\r\n\t\tvar option = document.createElement('option');\r\n\t\toption.value = deviceInfo.deviceId;\r\n\t\t\r\n\t\t//if only back camera lens is needed, can add checking on the \"back\" keyword in the deviceInfo.label\r\n\t\tif (deviceInfo.kind === 'videoinput' ) {\r\n\t\t option.text = deviceInfo.label || 'Camera ' +\r\n\t\t\t(videoSelect.length + 1);\r\n\t\t videoSelect.appendChild(option);\r\n\t\t}\r\n\t}\r\n}",
"function updateVideoDevices(res) {\n assert(res.succeeded);\n var i, scmr, cams = [], cam;\n // build the current device list\n for (i = 1; i < res.length - 1; i++) {\n cam = Model({\n // the media plugin doesn't give a unique id for every\n // camera, so name is used as a reasonably unique id\n id: ConstProperty(res[i]),\n name: ConstProperty(res[i]),\n type: ConstProperty('Camera'),\n // TODO: this associates every camera with the same video channel,\n // while there should be multiple video channels\n localVideoChannel: localVideoChannel.channel\n });\n cams.push(cam);\n }\n // newly selected device (if there are no devices res = [0, -1])\n scmr = cams[res[res.length - 1]];\n // replace the device collection with the new device list\n updateDeviceCollection(cameras, cams);\n // TODO: note, that in some cases selectedCamera() != cameras(i) for any i\n selectedCamera(scmr || null, Property.sUpdated);\n }",
"drawCameras() {\n for (let i = 0; i < this.cameras.length; ++i) {\n const cam = this.cameras[i];\n cam.draw(this.ctx, i === this.selectedCamera);\n }\n }",
"initCameras() {\n this.cameras = new Map()\n\n // Loads defined cameras when scene is loaded\n for (let [id, camera] of this.camerasInfo) {\n this.createCamera(id, camera);\n }\n }",
"initCameras() {\n this.cameras = {};\n if ((Object.keys(this.graph.views)).length == 0) {\n this.cameras[\"default\"] = this.camera;\n this.selectedCamera = \"default\";\n }\n for (let key in this.graph.views) {\n const cam = this.graph.views[key];\n let newCam;\n if (cam.type == \"perspective\") {\n newCam = new CGFcamera(\n cam.angle * DEGREE_TO_RAD, cam.near, cam.far, Object.values(cam.from), Object.values(cam.to)\n );\n\n } else if (cam.type == \"ortho\") {\n newCam = new CGFcameraOrtho(\n cam.left, cam.right, cam.bottom, cam.top, cam.near, cam.far, Object.values(cam.from), Object.values(cam.to), vec3.fromValues(0, 1, 0)\n );\n }\n this.cameras[cam.id] = newCam;\n if (cam.id === this.graph.defaultViewId) {\n this.camera = newCam;\n this.interface.setActiveCamera(this.camera);\n this.selectedCamera = key;\n }\n }\n }",
"get cameras() {\n return this._cameras;\n }",
"onCameraChanged() {\r\n this.camera = this.cameras[this.selectedCamera];\r\n }",
"function updateCamBrandModel() {\n\n\t\t\t\n\t var camModels = {};\n\t\t\tvar bnd = editor.camBrandModelMaping[CameraBrand.getValue()];\n\t\t\tif(bnd == undefined){\n\n\t\t\t\t//toastr.info(editor.languageData.Thesecameraisremovedpleasetryanotherone)\n\t\t\t}\n\t\t\telse{\n\t\t\t\tvar len = bnd.length;\n\t\t\t\tfor (var i = 0; i < len; i++) {\n\n\t\t\t\t\tcamModels[bnd[i]] = bnd[i];\n\n\t\t\t\t}\n\t \tcamModelSelector.setOptions(camModels).setWidth('150px').setValue(bnd[0]);\n\t\t\t}\n\t \n\n\t }",
"updateCars(cars) {\n this.mini_cars = cars;\n if (this.selectedVideo == '') {\n this.selectedVideo = cars[0];\n }\n }",
"async Cameras_all() {\n let uri = \"type=cameras\";\n let response = await this.domoticzCall(uri);\n return response.result;\n }",
"function updateCamSliders() {\n camPhiSlider.value = toDegrees( camera.phi )\n camThetaSlider.value = toDegrees( camera.theta )\n camRadiusSlider.value = camera.radius\n camFovSlider.value = toDegrees( camera.getFov() )\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Nested pseudoclass if we are insideRule and the next special character found opens a new block | function foundNestedPseudoClass() {
var openParen = 0;
for (var i = pos + 1; i < source_text.length; i++) {
var ch = source_text.charAt(i);
if (ch === "{") {
return true;
} else if (ch === '(') {
// pseudoclasses can contain ()
openParen += 1;
} else if (ch === ')') {
if (openParen === 0) {
return false;
}
openParen -= 1;
} else if (ch === ";" || ch === "}") {
return false;
}
}
return false;
} | [
"function foundNestedPseudoClass() {\n for (var i = pos + 1; i < source_text.length; i++){\n var ch = source_text.charAt(i);\n if (ch === \"{\"){\n return true;\n } else if (ch === \";\" || ch === \"}\" || ch === \")\") {\n return false;\n }\n }\n return false;\n }",
"function foundNestedPseudoClass() {\n for (var i = pos + 1; i < source_text.length; i++) {\n var ch = source_text.charAt(i);\n if (ch === \"{\") {\n return true;\n } else if (ch === \";\" || ch === \"}\" || ch === \")\") {\n return false;\n }\n }\n return false;\n }",
"function foundNestedPseudoClass() {\n var openParen = 0;\n for (var i = pos + 1; i < source_text.length; i++) {\n var ch = source_text.charAt(i);\n if (ch === \"{\") {\n return true;\n } else if (ch === '(') {\n // pseudoclasses can contain ()\n openParen += 1;\n } else if (ch === ')') {\n if (openParen == 0) {\n return false;\n }\n openParen -= 1;\n } else if (ch === \";\" || ch === \"}\") {\n return false;\n }\n }\n return false;\n }",
"function foundNestedPseudoClass() {\n var openParen = 0;\n for (var i = pos + 1; i < source_text.length; i++) {\n var ch = source_text.charAt(i);\n if (ch === \"{\") {\n return true;\n } else if (ch === '(') {\n // pseudoclasses can contain ()\n openParen += 1;\n } else if (ch === ')') {\n if (openParen === 0) {\n return false;\n }\n openParen -= 1;\n } else if (ch === \";\" || ch === \"}\") {\n return false;\n }\n }\n return false;\n }",
"function foundNestedPseudoClass() {\n\t var openParen = 0;\n\t for (var i = pos + 1; i < source_text.length; i++) {\n\t var ch = source_text.charAt(i);\n\t if (ch === \"{\") {\n\t return true;\n\t } else if (ch === '(') {\n\t // pseudoclasses can contain ()\n\t openParen += 1;\n\t } else if (ch === ')') {\n\t if (openParen === 0) {\n\t return false;\n\t }\n\t openParen -= 1;\n\t } else if (ch === \";\" || ch === \"}\") {\n\t return false;\n\t }\n\t }\n\t return false;\n\t }",
"function beginWithBlock(expression){var startLabel=defineLabel();var endLabel=defineLabel();markLabel(startLabel);beginBlock({kind:1/* With */,expression:expression,startLabel:startLabel,endLabel:endLabel});}",
"openNode(node) {\n\t\t if (!emitsWrappingTags(node)) return;\n\t\t let className = node.kind;\n\t\t if (!node.sublanguage) {\n\t\t\t className = `${this.classPrefix}${className}`;\n\t\t }\n\t\t this.span(className);\n\t }",
"function beginWithBlock(expression) {\n var startLabel = defineLabel();\n var endLabel = defineLabel();\n markLabel(startLabel);\n beginBlock({\n kind: 1 /* With */\n , expression: expression,\n startLabel: startLabel,\n endLabel: endLabel\n });\n }",
"handle_part(block) {\n\n let part_name = this.syntaxReader.read_name();\n this.syntaxReader.skip_newlines_blankspace();\n\n //If a part is to redefined it will use the function in HandleRedefines.js\n if (part_name === \"redefines\") {\n this.syntaxReader.skip_newlines_blankspace();\n let part = block.get_or_create_part_by_name(this.syntaxReader.read_name());\n return this.handle_redefines_part_property(block, part);\n }\n\n var part = block.get_or_create_part_by_name(part_name);\n\n this.syntaxReader.skip_next_char(); // Skip the : between the part name and the block name\n\n this.syntaxReader.skip_newlines_blankspace();\n\n let block_name = this.syntaxReader.read_name();\n\n var c_n_char = this.syntaxReader.check_next_char();\n\n //If the block of the part contains an amount that amount is returned\n //if no value the amount is set to default 1\n if (c_n_char === \"[\") {\n var amount = this.syntaxReader.read_amount();\n if (amount.length === 2) {\n part.amount = amount[0];\n part.upper_amount = amount[1];\n } else {\n part.amount = amount;\n }\n this.syntaxReader.skip_newlines_blankspace();\n c_n_char = this.syntaxReader.check_next_char();\n } else {\n part.amount = 1;\n }\n\n this.syntaxReader.skip_newlines_blankspace();\n var next_action = this.syntaxReader.read_name();\n //this if statement is a mess\n if (c_n_char == \":\") {\n this.syntaxReader.skip_next_char();\n c_n_char = this.syntaxReader.read_next_char();\n // If the Block is defined in an other package\n\n if (c_n_char == \":\") {\n block_name += \"::\" + this.syntaxReader.read_name();\n part.amount = this.syntaxReader.read_amount();\n this.syntaxReader.skip_newlines_blankspace();\n c_n_char = this.syntaxReader.read_next_char();\n\n //checking if it's the shortcut of subsets or redefines\n } else if (c_n_char === \">\") {\n part.block = this.get_block_by_name(block_name);\n c_n_char = this.syntaxReader.check_next_char();\n\n //fetch the part that is to be redefine and add it to the current part redefines array\n if (c_n_char === \">\") {\n this.syntaxReader.skip_next_char();\n this.syntaxReader.skip_newlines_blankspace();\n let redefinition_part_name = this.syntaxReader.read_name();\n let redefinition_part = this.handle_redefines_part(redefinition_part_name, block)\n part.add_redefine(redefinition_part);\n return part\n }\n //uses the subset routine\n this.syntaxReader.skip_newlines_blankspace();\n let subset_part = this.handle_subsets_part(block);\n part.add_subset(subset_part);\n return part;\n } else {\n this.syntaxReader.error(\"Expected :: or :>>\");\n }\n }\n\n part.isPart_count = block.isPart_count;\n let ref_block = this.get_block_by_name(block_name);\n part.block = ref_block;\n\n if (c_n_char == \";\") {\n // Done\n this.syntaxReader.skip_next_char();\n return part;\n\n //if a part contains a part his function is used\n } else if (c_n_char == \"{\") {\n this.syntaxReader.skip_next_char();\n this.handle_part_content(part);\n return part;\n }\n\n //The same redefines routine as above but when the user writes redefines instead of :>>\n if (next_action === \"redefines\") {\n let redefinition_part_name = this.syntaxReader.read_name();\n let redefinition_part = this.handle_redefines_part(redefinition_part_name, block)\n part.add_redefine(redefinition_part);\n return part\n\n //The same subsets routine as above but when the user writes subsets instead of :>\n } else if (next_action === \"subsets\") {\n this.syntaxReader.skip_newlines_blankspace();\n let subset_part = this.handle_subsets_part(block);\n part.add_subset(subset_part);\n return part;\n } else {\n this.syntaxReader.error(\"The part is either not closed or keywords is missing\");\n }\n\n }",
"consumeAnAtRule() {\n var inputToken = this.consumeAToken();\n var atRule = {\n type: 'at-rule',\n name: inputToken.text,\n prelude: [],\n block: undefined\n };\n\n while (inputToken = this.consumeAToken()) {\n if (inputToken === ';') {\n return atRule;\n } else if (inputToken === '{') {\n atRule.block = this.consumeASimpleBlock(inputToken);\n return atRule;\n } else if (inputToken.type === 9\n /* simpleBlock */\n && inputToken.associatedToken === '{') {\n atRule.block = inputToken;\n return atRule;\n }\n\n this.reconsumeTheCurrentInputToken(inputToken);\n var component = this.consumeAComponentValue();\n\n if (component) {\n atRule.prelude.push(component);\n }\n }\n\n return atRule;\n }",
"parseNestedBlocks(parentTag) {\r\n var token = this.lexer.getNextToken();\r\n\r\n if(token.isKind('text')) {\r\n // Add this instructon to the list\r\n this.labProcedure.instructions.push(LabParser.sanatize(token.getDetails()));\r\n token = this.lexer.getNextToken();\r\n }\r\n\r\n token.errorCheck('langle');\r\n token = this.lexer.getNextToken();\r\n\r\n if(!token.isKind('lslash')) {\r\n // Then there is at least one sub-block to parse.\r\n const repatitionLimit = 1000 // Limit on the number of sequential sub-blocks of the same scope\r\n let i=1\r\n\r\n token.errorCheck('text');\r\n var newParent = LabParser.removeLabel(token.getDetails());\r\n token = this.lexer.getNextToken();\r\n token.errorCheck('rangle');\r\n\r\n var closingTag = ''\r\n\r\n while(closingTag!==parentTag) { // Parse any aditional sub-blocks of the same scope.\r\n if(i==repatitionLimit) {\r\n throw new Error(\"To many sequential sub-blocks of the same scope.\");\r\n }\r\n\r\n this.parseNestedBlocks(newParent);\r\n\r\n token = this.lexer.getNextToken();\r\n token.errorCheck('langle');\r\n token = this.lexer.getNextToken();\r\n newParent = LabParser.removeLabel(token.getDetails());\r\n closingTag = LabParser.removeLabel(this.lexer.getNextToken().getDetails());\r\n i++;\r\n }\r\n\r\n token = this.lexer.getNextToken();\r\n token.errorCheck('rangle');\r\n\r\n } else {\r\n // Otherwise, this is the end of this block.\r\n token = this.lexer.getNextToken();\r\n token.errorCheck('text', parentTag);\r\n token = this.lexer.getNextToken();\r\n token.errorCheck('rangle');\r\n }\r\n }",
"constructor(start, end, nestLevel, parent)\n {\n super(State.BlockQuote, start, end, parent);\n this.nestLevel = nestLevel;\n }",
"function beginWithBlock(expression) {\n var startLabel = defineLabel();\n var endLabel = defineLabel();\n markLabel(startLabel);\n beginBlock({\n kind: 1 /* With */,\n expression: expression,\n startLabel: startLabel,\n endLabel: endLabel\n });\n }",
"parseBlock() {\n\t\tvar program = this.delimited('{', '}', null, this.parseExpression.bind(this));\n\t\treturn {\n\t\t\ttype: 'block',\n\t\t\texpressions: program\n\t\t};\n\t}",
"parseAlternative() {\n let node = {\n type: 'Alternative',\n Term: undefined,\n Alternative: undefined,\n };\n while (this.position < this.source.length\n && !isClosingSyntaxCharacter(this.peek())) {\n node = {\n type: 'Alternative',\n Term: this.parseTerm(),\n Alternative: node,\n };\n }\n return node;\n }",
"function parentRuleBlock(id_string){\n\treturn '<div id=\"active_' + id_string + '\"><em><strong>Active ' + id_string + ':</strong></em></div>'\n}",
"function next() {\n return stashed()\n || whitespace()\n || comments()\n || parent()\n || prop()\n || rule()\n || open()\n || close();\n }",
"enterRulePart(ctx) {\n\t}",
"enterNestedParenthesesBlock(ctx) {\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate the css classes for the given reflection group and apply them to the [[ReflectionGroup.cssClasses]] property. | static applyGroupClasses(group) {
const classes = [];
if (group.allChildrenAreInherited) {
classes.push("tsd-is-inherited");
}
if (group.allChildrenArePrivate) {
classes.push("tsd-is-private");
}
if (group.allChildrenAreProtectedOrPrivate) {
classes.push("tsd-is-private-protected");
}
if (group.allChildrenAreExternal) {
classes.push("tsd-is-external");
}
group.cssClasses = classes.join(" ");
} | [
"static applyReflectionClasses(reflection) {\n const classes = [];\n let kind;\n if (reflection.kind === index_1.ReflectionKind.Accessor) {\n if (!reflection.getSignature) {\n classes.push(\"tsd-kind-set-signature\");\n }\n else if (!reflection.setSignature) {\n classes.push(\"tsd-kind-get-signature\");\n }\n else {\n classes.push(\"tsd-kind-accessor\");\n }\n }\n else {\n kind = index_1.ReflectionKind[reflection.kind];\n classes.push(DefaultTheme.toStyleClass(\"tsd-kind-\" + kind));\n }\n if (reflection.parent &&\n reflection.parent instanceof index_1.DeclarationReflection) {\n kind = index_1.ReflectionKind[reflection.parent.kind];\n classes.push(DefaultTheme.toStyleClass(`tsd-parent-kind-${kind}`));\n }\n let hasTypeParameters = !!reflection.typeParameters;\n reflection.getAllSignatures().forEach((signature) => {\n hasTypeParameters = hasTypeParameters || !!signature.typeParameters;\n });\n if (hasTypeParameters) {\n classes.push(\"tsd-has-type-parameter\");\n }\n if (reflection.overwrites) {\n classes.push(\"tsd-is-overwrite\");\n }\n if (reflection.inheritedFrom) {\n classes.push(\"tsd-is-inherited\");\n }\n if (reflection.flags.isPrivate) {\n classes.push(\"tsd-is-private\");\n }\n if (reflection.flags.isProtected) {\n classes.push(\"tsd-is-protected\");\n }\n if (reflection.flags.isStatic) {\n classes.push(\"tsd-is-static\");\n }\n if (reflection.flags.isExternal) {\n classes.push(\"tsd-is-external\");\n }\n reflection.cssClasses = classes.join(\" \");\n }",
"function setGroupCss(options) {\n for (var key in options) {\n if (options.hasOwnProperty(key)) {\n setCss.call(this, key, options[key]);\n }\n }\n }",
"function populateSpryCSSClasses()\n{\n var dom = dw.getDocumentDOM();\n\tvar allClasses = dom.getSelectorsDefinedInStylesheet('class');\n\tfor (i = 0; i < allClasses.length; i++)\n\t{\n\t\tif (allClasses[i][0] == '.')\n\t\t{\n\t\t\tallClasses[i] = allClasses[i].slice(1);\n\t\t}\n\t}\n\t_LIST_SPRY_HOVER_CLASSES.setAll(allClasses,allClasses);\n\t_LIST_SPRY_SELECT_CLASSES.setAll(allClasses,allClasses);\n\t_LIST_SPRY_ODD_CLASSES.setAll(allClasses,allClasses);\n\t_LIST_SPRY_EVEN_CLASSES.setAll(allClasses,allClasses);\n}",
"_setupClasses() {\n const customClasses = getWithDefault(this, 'customClasses', {});\n var newClasses = smartExtend(customClasses, defaultCssClasses);\n set(this, 'classes', O.create(newClasses));\n }",
"createColorClasses() {\n const existingStyles = document.head.getElementsByTagName('style');\n // style elements created by this plugin\n const fontColorStyles = [].filter.call(existingStyles, styleElement => styleElement.hasAttribute(FontColor.stylesDataAttribute));\n const colorsWithClassesAlreadyCreated = fontColorStyles\n .map(styleElement => styleElement.getAttribute(FontColor.stylesDataAttribute).split(FontColor.stylesDataAttributeColorSeparator))\n .flat();\n const colorsToCreateClasses = this.config.colors\n .filter(color => colorsWithClassesAlreadyCreated.indexOf(color) === -1);\n const css = colorsToCreateClasses\n .map(color => `.${FontColor.classFor(color)}{color:${color}}`)\n .join('')\n .trim();\n if (!css) {\n return;\n }\n const styles = document.createElement('style');\n styles.type = 'text/css';\n styles.innerHTML = css;\n const attrValue = this.config.colors.join(FontColor.stylesDataAttributeColorSeparator);\n styles.setAttribute(FontColor.stylesDataAttribute, attrValue);\n document.head.appendChild(styles);\n }",
"get styleClasses() {\n return `${this.defaultCssClass} ` + `${this.paddingIndentationCssClass}-` + this.groupRow.level +\n (this.isActive() ? ` ${this.defaultCssClass}--active` : '');\n }",
"stylesByGroup(group) {\n const widths = this.columnGroupWidths;\n const offsetX = this.offsetX;\n const styles = {\n width: `${widths[group]}px`\n };\n if (group === 'left') {\n translateXY(styles, offsetX, 0);\n }\n else if (group === 'right') {\n const bodyWidth = parseInt(this.innerWidth + '', 0);\n const totalDiff = widths.total - bodyWidth;\n const offsetDiff = totalDiff - offsetX;\n const offset = offsetDiff * -1;\n translateXY(styles, offset, 0);\n }\n return styles;\n }",
"function groups_to_docsets(groups, docset) {\n var results = [{\n \"tagname\": \"class\",\n \"type\": docset.type,\n \"comment\": groups.class,\n \"code\": docset.code,\n \"linenr\": docset.linenr\n }];\n\n _.each(groups.cfg, function(cfg) {\n results.push({\n \"tagname\": \"cfg\",\n \"type\": docset.type,\n \"comment\": cfg,\n \"code\": {},\n \"linenr\": docset.linenr\n });\n });\n\n if (groups.Constructor.length > 0) {\n // Remember that a constructor is already found and ignore if a\n // constructor is detected from code.\n var constructor_found = true\n\n results.push({\n \"tagname\": \"method\",\n \"type\": docset.type,\n \"comment\": groups.Constructor,\n \"code\": {},\n \"linenr\": docset.linenr\n });\n }\n\n return results;\n}",
"function ApplyEffectToElement(group, classes, duration) {\n group.each(function(index) {\n $(this).addClass(classes);\n });\n\n window.setTimeout(function() {\n group.each(function() {\n $(this).removeClass(classes);\n });\n }, duration);\n}",
"function getClasses(uid) {\n\t\tuid = (uid || Math.random())+\"\";\n\n\t\tvar courses = slice(document.querySelectorAll(\"div[id*=DERIVED_REGFRM1_DESCR]\")),\n\t\t classes = [];\n\n\t\tcourses.forEach(function (courseElem) {\n\t\t\tvar course = parseCourse(courseElem.getElementsByClassName(\"PAGROUPDIVIDER\")[0].textContent),\n\t\t\t nbr = \"0000\",\n\t\t\t comp = \"Unknown\",\n\t\t\t rows = slice(courseElem.querySelectorAll(\"tr[id*=CLASS_MTG_VW]\")),\n\t\t\t rowNum = 0;\n\n\t\t\trows.forEach(function (rowElem) {\n\t\t\t\tvar nbrElem = rowElem.querySelector(\"span[id^=DERIVED_CLS_DTL_CLASS_NBR]\"),\n\t\t\t\t compElem = rowElem.querySelector(\"span[id^=MTG_COMP]\"),\n\t\t\t\t sched = parseTimeRange(rowElem.querySelector(\"span[id^=MTG_SCHED]\").textContent),\n\t\t\t\t location = rowElem.querySelector(\"span[id^=MTG_LOC]\").textContent,\n\t\t\t\t dates = parseDateRange(rowElem.querySelector(\"span[id^=MTG_DATES]\").textContent);\n\n\t\t\t\t// These fields normally only appear once per course component\n\t\t\t\tif (nbrElem.textContent != \"\\u00a0\")\n\t\t\t\t\tnbr = nbrElem.textContent;\n\n\t\t\t\tif (compElem.textContent != \"\\u00a0\")\n\t\t\t\t\tcomp = compElem.textContent;\n\n\t\t\t\tvar first = snapFirstOccurence(dates, sched),\n\t\t\t\t except = [];\n\n\t\t\t\t// For each public holiday that occurs while the university is\n\t\t\t\t// open, check if a class can be snapped to that day and if so,\n\t\t\t\t// add its start time to the list of exceptions\n\t\t\t\tholidays.forEach(function(holiday) {\n\t\t\t\t\tvar times = snapToDay(dates, sched, holiday);\n\n\t\t\t\t\tif (times)\n\t\t\t\t\t\texcept.push(times.start);\n\t\t\t\t});\n\n\t\t\t\tclasses.push({\n\t\t\t\t\tuid: uid + \"::\" + nbr + \"::\" + rowNum,\n\t\t\t\t\tstart: first.start,\n\t\t\t\t\tend: first.end,\n\t\t\t\t\tuntil: dates.end,\n\t\t\t\t\tsummary: course.code + \" \" + comp,\n\t\t\t\t\tdescription: course.code + \" - \" + course.name,\n\t\t\t\t\tlocation: location,\n\t\t\t\t\texcept: except.length != 0 ? except : null,\n\t\t\t\t});\n\n\t\t\t\trowNum ++;\n\t\t\t});\n\t\t});\n\n\t\treturn classes;\n\t}",
"function colorClasses(colors) {\n var content = \"\";\n content += \"// Generated color classes\\n\";\n\n //Sass variables\n colors.forEach(color => {\n content += `\\$${color.name}: ${color.value};\\n`;\n });\n\n content += \"\\n\";\n\n //Materialize classes\n colors.forEach(color => {\n content += `.${color.name}{background-color: \\$${color.name} !important;}\\n`;\n content += `.${color.name}-text{color: \\$${color.name} !important;}\\n`;\n });\n\n return content;\n}",
"function generate_conversions(parsed, groups){\n var generated_output = [parsed]\n\n // for each group\n Object.values(groups).forEach(function(group){\n // map each group's conversions \n generated_output = group[\"conversions\"].map(function(conversion){\n // to the map of the generation\n return generated_output.map(function(generation){\n // for each style\n Object.values(group[\"styles\"]).forEach(function(style){\n // TODO: apply style to conversion before replace\n var styled_conversion = apply_style(style, conversion)\n\n // find and replace each occurrence of group/style in generation with the conversion\n generation = generation.replace(\n RegExp(`(${style[\"substituted\"]})`, \"gi\"), \n `<mark class=\"group${group[\"index\"]} marked\" data-sub=\"${style[\"substituted\"]}\">${styled_conversion}</mark>`\n )\n })\n\n return generation\n })\n }).flat()\n })\n\n return generated_output\n}",
"function rebuildClassList() {\n var s = 'wait-rotator-circle'; // base class\n\n s += _getRadioValue(sizes);\n s += _getRadioValue(slices);\n s += _getRadioValue(parts);\n s += _getRadioValue(speed);\n s += _getRadioValue(thick);\n s += _getRadioValue(colors);\n s += _getRadioValue(styles);\n s += _getRadioValue(shapes);\n\n example.className = '';\n example.offsetWidth = example.offsetWidth; // reflow magic\n var classes = s.split(' ');\n var t = '';\n for (var i = 0; i < classes.length; i++) {\n if (t != '') t += ' ';\n t += '<span>' + classes[i] + '</span>';\n }\n\n layout_example.innerHTML = '<div class=\"' + t + '\"></div>';\n\n example.className = s;\n example.offsetWidth = example.offsetWidth;\n}",
"function applyClassDecorators(classPath, state) {\n\t\t var decorators = classPath.node.decorators || [];\n\t\t classPath.node.decorators = null;\n\t\n\t\t if (decorators.length === 0) return;\n\t\n\t\t var name = classPath.scope.generateDeclaredUidIdentifier('class');\n\t\n\t\t return decorators.map(function (dec) {\n\t\t return dec.expression;\n\t\t }).reverse().reduce(function (acc, decorator) {\n\t\t return buildClassDecorator({\n\t\t CLASS_REF: name,\n\t\t DECORATOR: decorator,\n\t\t INNER: acc\n\t\t }).expression;\n\t\t }, classPath.node);\n\t\t }",
"_groupCustomClasses() {\n const result = [];\n if (this.options.customClasses && Array.isArray(this.options.customClasses)) {\n this.options.customClasses.forEach((customClass) => {\n if (typeof (customClass.targetXPathIndex) === 'number') {\n if (typeof (result[customClass.targetXPathIndex]) === 'undefined') {\n result[customClass.targetXPathIndex] = [customClass];\n } else {\n result[customClass.targetXPathIndex].push(customClass);\n }\n delete customClass.targetXPathIndex;\n }\n });\n }\n return result;\n }",
"function applyClassDecorators(classPath, state) {\n var decorators = classPath.node.decorators || [];\n classPath.node.decorators = null;\n if (decorators.length === 0) return;\n var name = classPath.scope.generateDeclaredUidIdentifier('class');\n return decorators.map(function (dec) {\n return dec.expression;\n }).reverse().reduce(function (acc, decorator) {\n return buildClassDecorator({\n CLASS_REF: name,\n DECORATOR: decorator,\n INNER: acc\n }).expression;\n }, classPath.node);\n }",
"function getCssClasses(colorScheme) {\n var cssClasses = [];\n\n if (!colorScheme) {\n return cssClasses;\n }\n\n colorScheme = ensureColorScheme(colorScheme);\n\n if (colorScheme.scheme === _index__WEBPACK_IMPORTED_MODULE_0__[\"colorSchemes\"].ColorSchemeId.ALTERNATIVE) {\n cssClasses.push('color-alternative');\n } else if (colorScheme.scheme === _index__WEBPACK_IMPORTED_MODULE_0__[\"colorSchemes\"].ColorSchemeId.RAINBOW) {\n cssClasses.push('color-rainbow');\n } else if (colorScheme.scheme) {\n cssClasses.push(colorScheme.scheme);\n }\n\n if (colorScheme.inverted) {\n cssClasses.push('inverted');\n }\n\n if (colorScheme.tile) {\n cssClasses.push('tile');\n }\n\n return cssClasses;\n}",
"function applyClassDecorators(classPath, state) {\n\t var decorators = classPath.node.decorators || [];\n\t classPath.node.decorators = null;\n\n\t if (decorators.length === 0) return;\n\n\t var name = classPath.scope.generateDeclaredUidIdentifier('class');\n\n\t return decorators.map(function (dec) {\n\t return dec.expression;\n\t }).reverse().reduce(function (acc, decorator) {\n\t return buildClassDecorator({\n\t CLASS_REF: name,\n\t DECORATOR: decorator,\n\t INNER: acc\n\t }).expression;\n\t }, classPath.node);\n\t }",
"function createCSSRules(){\n if(typeof KolabInReal != \"object\" || !KolabInReal.hasOwnProperty('currentSquareMembers')){\n return;\n }\n var lines = \"\";\n KolabInReal.currentSquareMembers.forEach(function (m){\n // if colorVisible (a custom property) is set and set to true\n // then turn that colour on\n if(m.hasOwnProperty('colorVisible') && m.colorVisible){\n lines += 'span[author=\"'+m.kolabID+'\"] {color:'+m.color+';}\\n';\n }\n // if the variable is not set (this is more likely)\n // then add the colour, and set it to black\n else{\n lines += 'span[author=\"'+m.kolabID+'\"] {color:#000000;}\\n';\n m.colorVisible = false;\n }\n });\n\n // add the lines to the dynamic css tag\n $dyncss().text(lines);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
createContentCell(content, parentDiv) creates a cell for either to word or page divs | function createContentCell(content, parentDiv) {
// Create main cell body
var mainDiv = document.createElement("DIV");
mainDiv.style.width = "90%";
mainDiv.style.padding = "10px";
mainDiv.style.marginRight = "auto";
mainDiv.style.marginLeft = "auto";
mainDiv.style.marginTop = "20px";
mainDiv.style.position = "relative";
mainDiv.style.backgroundColor = "white";
mainDiv.style.borderRadius = "5px";
// Create main title for cell
var titleElement = document.createElement("H2");
titleElement.style.marginLeft = "20px";
titleElement.style.width = "75%";
titleElement.style.wordWrap = "break-word";
titleElementText = document.createTextNode(content);
titleElement.appendChild(titleElementText);
// Add edit button
var editIcon = document.createElement("IMG");
editIcon.style.position = "absolute"
editIcon.style.right = "65px"
editIcon.style.top = "20px"
editIcon.style.height = "26";
editIcon.style.width = "30";
editIcon.src="images/edit.png";
// Add listener to edit icon click
editIcon.addEventListener('click', function() {
if (parentDiv == "wordListingDiv") {
//*******************************
// Edit button tapped was a word
//*******************************
// Get index of clicked item in the word
var index = wordArray.indexOf(titleElement.innerHTML)
// Prompt for the new word
var newWord = prompt("Word edit", wordArray[index]);
if (newWord != null && newWord.length > 0) {
// Change word
wordArray[index] = newWord;
titleElement.childNodes[0].nodeValue = wordArray[index];
}
} else {
//*******************************
// Edit button tapped was a page
//*******************************
// Get the index of the item in the page array
var index = pagesArray.indexOf(titleElement.innerHTML)
// Prompt for the new word
var newPage = prompt("Page edit", pagesArray[index]);
// Ensure word entered is a page
if (newPage != null && newPage.length > 0) {
// Change page
pagesArray[index] = newPage;
titleElement.childNodes[0].nodeValue = pagesArray[index];
}
}
// Save the settings
saveSettings();
});
// Add trash button
var trashIcon = document.createElement("IMG");
trashIcon.style.position = "absolute"
trashIcon.style.right = "20px"
trashIcon.style.top = "20px"
trashIcon.style.height = "26";
trashIcon.style.width = "30";
trashIcon.src="images/garbage.png";
// Add listener to the trash button
trashIcon.addEventListener('click', function() {
var index = wordArray.indexOf(content)
if (index >= 0) {
//********************************
// Trash button tapped was a word
//********************************
// Remove word
wordArray.splice(index, 1);
mainDiv.parentNode.removeChild(mainDiv);
} else {
//********************************
// Trash button tapped was a page
//********************************
// Remove page
pagesArray.splice(pagesArray.indexOf(content), 1);
mainDiv.parentNode.removeChild(mainDiv);
}
// Save settings
saveSettings();
});
// Add sub-elements to the cell
mainDiv.appendChild(titleElement);
mainDiv.appendChild(editIcon);
mainDiv.appendChild(trashIcon);
// Add cell
document.getElementById(parentDiv).appendChild(mainDiv);
} | [
"function createCell(cell, text) {\n var div = document.createElement('div'), \n txt = document.createTextNode(text); \n \tdiv.appendChild(txt); \n \tcell.appendChild(div); \n}",
"function createPageCell(word) {\n\n\tcreateContentCell(word, \"pageListingDiv\");\n\n}",
"function createCell(content){\n td = document.createElement(\"td\")\n td.innerHTML = content\n return td\n}",
"function createWordCell(word) {\n\n\tcreateContentCell(word, \"wordListingDiv\");\n\n}",
"function createCell(cell, text, style) {\n let div = document.createElement('div'), // create DIV element\n txt = document.createTextNode(text); // create text node\n div.appendChild(txt); // append text node to the DIV\n div.setAttribute('class', style); // set DIV class attribute\n cell.appendChild(div); // append DIV to the table cell\n}",
"function createCell(cell, text, style) {\n var div = document.createElement('div'), // create DIV element\n txt = document.createTextNode(text); // create text node\n div.appendChild(txt); // append text node to the DIV\n div.setAttribute('class', style); // set DIV class attribute\n cell.appendChild(div); // append DIV to the table cell\n}",
"function createCell(cell, text, style) {\n var div = document.createElement('div'), // create DIV element\n txt = document.createTextNode(text); // create text node\n div.appendChild(txt); // append text node to the DIV\n div.setAttribute('class', style); // set DIV class attribute\n div.setAttribute('className', style); // set DIV class attribute for IE (?!)\n cell.appendChild(div); // append DIV to the table cell\n}",
"function createCell(cell, text, style) {\n var div = document.createElement('div'), // create DIV element\n txt = document.createTextNode(text); // create text node\n div.appendChild(txt); // append text node to the DIV\n div.setAttribute('class', style); // set DIV class attribute\n div.setAttribute('className', style); // set DIV class attribute for IE (?!)\n cell.appendChild(div); // append DIV to the table cell\n\tcell.setAttribute('class', style); // set DIV class attribute\n cell.setAttribute('className', style); // set DIV class attribute for IE (?!)\n\tcell.appendChild(div); \n}",
"function newCell(content) {\n return $(\"<td></td>\").html(content);\n}",
"function parseCellContent(cell, cellContent) {\n var elements = cellContent.elements;\n elements.forEach(function (elem) {\n var domElement = createElement(elem);\n\n if (elem.innerElements !== undefined && elem.innerElements.length > 0) {\n elem.innerElements.forEach(function (innerElem) {\n var innerElement = createElement(innerElem);\n domElement.appendChild(innerElement);\n });\n }\n cell.appendChild(domElement);\n });\n }",
"function contentCell_generateGUI()\n{\n\tthis.tdElem = document.createElement(\"TD\");\n\n\tthis.tdElem.className = 'editor_td';\n\tthis.tdElem.align = this.align;\n\tthis.tdElem.vAlign = this.valign;\n\n\tif(this.width)\n\t{\n\t\tthis.tdElem.width = this.width;\n\t}\n\n\tthis.tdElem.contentCellId = this.id;\n\n\tthis.tdElem.onclick = this.mouseClicked;\n\tthis.tdElem.ondblclick = this.mouseDblClicked;\n\n\tif(this.component)\n\t{\n\t\tthis.tdElem.innerHTML = this.component.htmlText;\n\t}\n\telse if(this.input)\n\t{\n\t\tthis.tdElem.innerHTML = this.input.htmlText;\n\t}\n\telse\n\t{\n\t\tthis.tdElem.innerHTML = ' ';\n\t}\n}",
"function createCell(cell, text, style, id) {\n //cell.innerHTML = '<span id=\"' + id + '\" ></span>' + cell.innerHTML;\n \n var div = document.createElement('span'), // create DIV element\n txt = document.createTextNode(text); // create text node\n div.appendChild(txt); // append text node to the DIV\n div.setAttribute('class', style); // set DIV class attribute\n div.setAttribute('id', id); // set DIV id attribute\n div.setAttribute('className', style); // set DIV class attribute for IE (?!)\n //cell.appendChild(div); // append DIV to the table cell\n cell.insertBefore(div, cell.firstChild);\n}",
"function add_text_to_cell(params) {\n // get params\n var cell = params.cell;\n var id = params.id; if (!id) {_cell_id_++; id = 'Cell_'+_cell_id_;};\n var clss = params.clss || '';\n var content = params.text || console.log('error: please provide text');\n var css = params.css || {};\n\n // position new cell\n var pos = {position: 'relative'};\n for (var k in css) {\n pos[k] = css[k];\n }\n\n // add content\n $(cell.id).append(\n '<div style=\"display:table; width:100%; height:100%\"> \\\n <div style=\"display:table-cell;\" id=\"' + id + '\" class=\"'+clss+'\"> \\\n <div> ' + content + ' </div> \\\n </div> \\\n </div>'\n );\n\n // set style\n $('#'+id).css(pos);\n\n // return container\n return {id:'#'+id};\n}",
"function createCell(x, y, type) {\n //TODO: Check parameters\n var cell = document.createElement('div');\n\n cell.className = type;\n\n cell.style.top = (y * 25 - 12.5) + 'px';\n cell.style.left = (x * 25 - 12.5) + 'px';\n\n $('div#content').appendChild(cell);\n}",
"createMarkdownCell(options, parent) {\r\n if (!options.contentFactory) {\r\n options.contentFactory = this;\r\n }\r\n return new cells_1.MarkdownCell(options);\r\n }",
"function createContentDiv() {\n var contentDiv = document.createElement('div');\n contentDiv.id = 'content';\n return contentDiv;\n}",
"function addCell(content, whichRow, whichKind, array){\r\n\tvar cell = document.createElement(whichKind);\r\n\tcell.innerHTML = content;\r\n\twhichRow.appendChild(cell);\r\n\tarray.push(cell);\r\n\tcell.id = \"newCell\" + (array.length - 4);\r\n}",
"function CellContent() {\n this.type = 0;\n this.content = null;\n}",
"function create_cell_in_a_list(params) {\n // get positionning params\n var position = params.position || {};\n var grid = params.grid || {};\n var vspace = grid.vspace; if (vspace==null) vspace = 4;\n var hspace = grid.hspace; if (hspace==null) hspace = 4;\n var height = position.h; if (height==null) height = 100;\n var y = position.y; if (y==null) y = 0;\n params.css = params.css || {};\n\n // compute offsets\n var width = 100 - hspace;\n\n // position new cell\n var pos = {position: 'relative',\n width:''+width+'%', height:''+height+'px', \n 'margin-left':''+hspace/2+'%', 'margin-right':''+hspace/2+'%',\n 'margin-top':''+vspace/2+'px', 'margin-bottom':''+vspace/2+'px'};\n for (var k in pos) {\n params.css[k] = pos[k];\n }\n\n // force parent to be scrollable:\n if (params.parent) {\n $(params.parent.id).css({'overflow-y':'auto'});\n }\n\n // create new cell\n var cell = create_cell(params);\n\n // return new cell\n return cell;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rectangle lk intersects label li moving from pi with vector vi in positive time Compare centers of the labels they must be within li.height / 2 + lk.height / 2 in the vertical variable and li.width / 2 + lk.width / 2 in the horizontal variable, i.e solve |lk.x (pk.x + t v.x)| < d | function labelRectangleIntersection(lk, li, vi, pi) {
let min = 0;
let max = Number.POSITIVE_INFINITY;
if (vi.y !== 0) {
const firstIntersection = (lk.height / 2 + li.height / 2 - li.offsetY + (lk.top + lk.bottom) / 2 - pi.y) / vi.y;
const secondIntersection = (-lk.height / 2 - li.height / 2 - li.offsetY + (lk.top + lk.bottom) / 2 - pi.y) / vi.y;
// Multiplying by a negative sign reverses an inequality
if (vi.y > 0) {
max = Math.min(max, firstIntersection);
min = Math.max(min, secondIntersection);
} else {
min = Math.max(min, firstIntersection);
max = Math.min(max, secondIntersection);
}
} else {
// vector is vertical and they will never intersect
if (li.offsetY + pi.y - (lk.top + lk.bottom) / 2 > lk.height / 2 + li.height / 2) return interval.empty();
if (li.offsetY + pi.y - (lk.top + lk.bottom) / 2 < -lk.height / 2 - li.height / 2) return interval.empty();
}
if (vi.x !== 0) {
const thirdIntersection = (lk.width / 2 + li.width / 2 + (lk.right + lk.left) / 2 - pi.x - li.offsetX) / vi.x;
const fourthIntersection = (-lk.width / 2 - li.width / 2 + (lk.right + lk.left) / 2 - pi.x - li.offsetX) / vi.x;
if (vi.x > 0) {
max = Math.min(max, thirdIntersection);
min = Math.max(min, fourthIntersection);
} else {
min = Math.max(min, thirdIntersection);
max = Math.min(max, fourthIntersection);
}
} else {
if (pi.x + li.offsetX - (lk.right + lk.left) / 2 > lk.width / 2 + li.width / 2) return interval.empty();
if (pi.x + li.offsetX - (lk.right + lk.left) / 2 < -lk.width / 2 - li.width / 2) return interval.empty();
}
// Only interested in positive values
return interval(min, max);
} | [
"function labelRectangleIntersection (lk, li, vi, pi) {\n let min = 0\n let max = Number.POSITIVE_INFINITY\n if (vi.y !== 0) {\n const firstIntersection = (lk.height / 2 + li.height / 2 - li.offsetY + (lk.top + lk.bottom) / 2 - pi.y) / vi.y\n const secondIntersection = (-lk.height / 2 - li.height / 2 - li.offsetY + (lk.top + lk.bottom) / 2 - pi.y) / vi.y\n // Multiplying by a negative sign reverses an inequality\n if (vi.y > 0) {\n max = Math.min(max, firstIntersection)\n min = Math.max(min, secondIntersection)\n } else {\n min = Math.max(min, firstIntersection)\n max = Math.min(max, secondIntersection)\n }\n } else {\n // vector is vertical and they will never intersect\n if (li.offsetY + pi.y - (lk.top + lk.bottom) / 2 > lk.height / 2 + li.height / 2) return interval.empty()\n if (li.offsetY + pi.y - (lk.top + lk.bottom) / 2 < -lk.height / 2 - li.height / 2) return interval.empty()\n }\n if (vi.x !== 0) {\n const thirdIntersection = (lk.width / 2 + li.width / 2 + (lk.right + lk.left) / 2 - pi.x - li.offsetX) / vi.x\n const fourthIntersection = (-lk.width / 2 - li.width / 2 + (lk.right + lk.left) / 2 - pi.x - li.offsetX) / vi.x\n if (vi.x > 0) {\n max = Math.min(max, thirdIntersection)\n min = Math.max(min, fourthIntersection)\n } else {\n min = Math.max(min, thirdIntersection)\n max = Math.min(max, fourthIntersection)\n }\n } else {\n if (pi.x + li.offsetX - (lk.right + lk.left) / 2 > lk.width / 2 + li.width / 2) return interval.empty()\n if (pi.x + li.offsetX - (lk.right + lk.left) / 2 < -lk.width / 2 - li.width / 2) return interval.empty()\n }\n\n // Only interested in positive values\n return interval(min, max)\n}",
"function labelSegmentIntersection(pk, vk, li, vi, pi) {\n // translate so we can assume that point is in the centre\n pk = { x: pk.x - pi.x - li.offsetX, y: pk.y - pi.y - li.offsetY };\n // TODO handle parallel lines\n // The time interval where they meet is connected so it is enough to find the end points. This must occur when either the corners of the label intersect or when\n const intersections = [];\n // the end points of the segment intersect\n for (let x of [-li.width / 2, li.width / 2]) {\n for (let y of [-li.height / 2, li.height / 2]) {\n let intersection = segmentSegmentIntersection({ x, y }, vi, pk, vk);\n // Intersects inside the segment\n if (intersection && intersection.s >= 0 && intersection.s <= 1) {\n intersections.push(intersection.t);\n }\n\n // Given a point to we take the side coming from it in counter clockwise\n let side;\n if (x * y < 0) {\n side = { x: 0, y: -2 * y };\n } else {\n side = { x: -2 * x, y: 0 };\n }\n intersection = segmentSegmentIntersection({ x, y }, side, pk, vi);\n if (intersection && intersection.t >= 0 && intersection.t <= 1) {\n intersections.push(-intersection.s);\n //// The side covers the point in the future\n //if (intersection.s < 0) {\n // intersections.push(Number.POSITIVE_INFINITY)\n //}\n }\n intersection = segmentSegmentIntersection({ x, y }, side, { x: pk.x + vk.x, y: pk.y + vk.y }, vi);\n if (intersection && intersection.t >= 0 && intersection.t <= 1) {\n intersections.push(-intersection.s);\n }\n }\n }\n var min = intersections.reduce((a, b) => Math.min(a, b), Number.POSITIVE_INFINITY);\n var max = intersections.reduce((a, b) => Math.max(a, b), Number.NEGATIVE_INFINITY);\n min = Math.max(min, 0);\n return interval(min, max);\n}",
"function checkLabelBoundaries(object, rectWidth) {\n // if it detects that the box is outside of the width and height of the canvas, then translate the box to a different position\n if(mouseX + 10 + rectWidth >= width) {\n translate(mouseX - 10 - rectWidth, mouseY+10);\n } else {\n translate(mouseX+10, mouseY+10);\n }\n\n if(!object.compare) {\n var offset = height/15+textAscent();\n } else {\n var offset = height/15+textAscent()*3;\n }\n\n if(mouseY + 10 + offset >= height) {\n translate(0, -10 - offset);\n }\n}",
"function labelPosition(ctx, v) {\n\tctx.font=\"300 14px Open Sans, sans-serif\";\n\tvar l = new Object();\n\tl.x = [0,0,0];\n\tl.y = [];\n\tfor(var i=0, len=v.length; i<len; i++) {\n\t\tvar radPos = 0;\n\t\tif (i == 0) {\n\t\t\tradPos = 2-(v[0]/2);\n\t\t} else {\n\t\t\tradPos = 2-(v[i]/2+v[i-1]/2);\n\t\t}\n\t\tl.x[i] = (graphWidth/2+Math.cos(radPos*Math.PI)*70);\n\t\tl.x[i] -= ctx.measureText(yearCreated).width/2;\n\t\tl.y[i] = (graphWidth/2+Math.sin(radPos*Math.PI)*70);\n\t\tl.y[i] += 7; // Font height offset\n\n\t\tvar radPosTemp = 0;\n\t\t// Label offset\n\t\tl.x[i] += Math.cos(radPos*Math.PI) * 23;\n\t\tl.y[i] += Math.sin(radPos*Math.PI) * 23;\n\t}\n\treturn l;\n}",
"function boxIntersectLine(x, y, w, h, x1, y1, x2, y2) {\n return (\n intersectLine(x, y, x + w, y, x1, y1, x2, y2) || // top of label\n intersectLine(x + w, y, x + w, y + h, x1, y1, x2, y2) || // right of label\n intersectLine(x, y + h, x + w, y + h, x1, y1, x2, y2) || // bottom of label\n intersectLine(x, y, x, y + h, x1, y1, x2, y2) // left of label\n );\n }",
"determine_label(x, y) {\n if (x == 0) return [\"left\", 5, 5];\n if (x == scopeList[this.id].layout.width) return [\"right\", -5, 5];\n if (y == 0) return [\"center\", 0, 13];\n return [\"center\", 0, -6];\n }",
"function DectectAndShowVerticalLOS () {\r\n // check against surrounding flights\r\n for (let i=0; i<surroundingFlight; i++) {\r\n let los = VerticalConflictDetector(ownshipVerticalResTop, [ownshipPointLevel, ownshipNewPointLevel], commonSpeed, srdFlightTop[i], srdPointLevel[i], commonSpeed);\r\n surroundingLos[i].children[0].segments = [los[3], los[4]];\r\n if (los[0]) { \r\n surroundingLos[i].children[0].strokeColor = red;\r\n surroundingLos[i].children[0].dashArray = null;\r\n surroundingLos[i].children[0].visible = true;\r\n surroundingLos[i].children[1].position = los[3].add(los[4]).divide(2);\r\n surroundingLos[i].children[2].position = srdFlightSide[i].getPointAt(commonSpeed * los[2]);\r\n surroundingLos[i].children[3].visible = false;\r\n } else {\r\n surroundingLos[i].children[0].strokeColor = black;\r\n surroundingLos[i].children[0].dashArray = lineWidth.dashArray;\r\n surroundingLos[i].children[0].visible = showGoodCpa;\r\n surroundingLos[i].children[1].position = hidden;\r\n surroundingLos[i].children[2].position = hidden;\r\n surroundingLos[i].children[3].visible = true;\r\n }\r\n }\r\n // check against intruder\r\n los = VerticalConflictDetector(ownshipVerticalResTop, [ownshipPointLevel, ownshipNewPointLevel], commonSpeed, intruderTop, intruderPointLevel, commonSpeed);\r\n intruderLos.children[0].segments = [los[3], los[4]];\r\n if (los[0]) {\r\n intruderLos.children[0].strokeColor = red;\r\n intruderLos.children[0].dashArray = null;\r\n intruderLos.children[0].visible = true;\r\n intruderLos.children[1].position = los[3].add(los[4]).divide(2);\r\n intruderLos.children[2].position = intruderSide.getPointAt(commonSpeed * los[2]);\r\n intruderLos.children[3].visible = false;\r\n } else {\r\n intruderLos.children[0].strokeColor = black;\r\n intruderLos.children[0].dashArray = lineWidth.dashArray;\r\n intruderLos.children[0].visible = showGoodCpa;\r\n intruderLos.children[1].position = hidden;\r\n intruderLos.children[2].position = hidden;\r\n intruderLos.children[3].visible = true;\r\n }\r\n}",
"function centerRotation(triObj, key, p0) {\n var j, k, jCur, jNew, jx;\n var nK = key.length;\n var eps = 0.001;\n \n //console.log(triObj[19].vCur[0], triObj[19].vCur[1], triObj[19].vCur[2]);\n //console.log(triObj[19].vNew[0], triObj[19].vNew[1], triObj[19].vNew[2]);\n //console.log(triObj[19].vCur, triObj[19].vNew);\n //console.log(nK, p0, key);\n for (k = 0; k < nK; k++) {\n //console.log(triObj[key[k]].vCur[0], triObj[key[k]].vCur[1], triObj[key[k]].vCur[2]);\n //console.log(triObj[key[k]].vNew[0], triObj[key[k]].vNew[1], triObj[key[k]].vNew[2]);\n //console.log(triObj[key[k]].vCur, triObj[key[k]].vNew);\n //console.log(k, key[k], triObj[key[k]].vNew, triObj[key[k]].vCur);\n jCur = -1;\n jNew = -1;\n for (j = 0; j < 3; j++) {\n //console.log(k, j, rectD(triObj[key[k]].vCur[j], p0), triObj[key[k]].vCur[j], triObj[key[k]].vCur);\n if (rectD(triObj[key[k]].vCur[j], p0) < eps) {\n jCur = j;\n //console.log(j, jNew, jCur, rectD(triObj[key[k]].vCur[j], p0), triObj[key[k]].vCur[j], triObj[key[k]].vCur);\n }\n //console.log(triObj[key[k]].vCur[0], triObj[key[k]].vCur[1], triObj[key[k]].vCur[2]);\n //console.log(triObj[key[k]].vNew[0], triObj[key[k]].vNew[1], triObj[key[k]].vNew[2]);\n //console.log(k, j, key[k], p0, triObj[key[0]].vNew[j], triObj[key[k]].vNew[1], triObj[19].vNew[1], triObj[key[k]].vNew[j], triObj[key[k]].vNew);\n //console.log(k, j, rectD(triObj[key[k]].vNew[j], p0));\n \n if (rectD(triObj[key[k]].vNew[j], p0) < eps) {\n jNew = j;\n //console.log(j, jNew, jCur, rectD(triObj[key[k]].vNew[j], p0), triObj[key[k]].vNew[j], triObj[key[k]].vNew);\n }\n //console.log(triObj[key[k]].vCur[0], triObj[key[k]].vCur[1], triObj[key[k]].vCur[2]);\n //console.log(triObj[key[k]].vNew[0], triObj[key[k]].vNew[1], triObj[key[k]].vNew[2]);\n }\n //console.log(jNew, jCur);\n if ((jNew > 0) && (jCur > 0)) {\n jx = (3 + jNew - jCur) % 3;\n //console.log(jx);\n for (j = 0; j < jx; j++) {\n triObj[key[k]].vNew.push(triObj[key[k]].vNew.shift()); //rotate left\n }\n }\n //console.log(k, triObj[key[k]].vNew, triObj[key[k]].vCur);\n }\n\n}",
"function arrangeLabels() {\n\n var secondLabel = document.getElementsByClassName(\"actual-label\")[1];\n var thirdLabel = document.getElementsByClassName(\"actual-label\")[2];\n var secondLabelThirdLine = document.getElementsByClassName(\"labelThree\")[1];\n var thirdLabelThirdLine = document.getElementsByClassName(\"labelThree\")[2];\n\n var a = secondLabel.getBoundingClientRect();\n var b = thirdLabel.getBoundingClientRect();\n\n var secondX = d3.select(secondLabel).attr(\"dx\");\n var secondY = d3.select(secondLabel).attr(\"dy\");\n var secondThirdX = d3.select(secondLabelThirdLine).attr(\"x\");\n\n var thirdX = d3.select(thirdLabel).attr(\"dx\");\n var thirdY = d3.select(thirdLabel).attr(\"dy\");\n var thirdThirdX = d3.select(thirdLabelThirdLine).attr(\"x\");\n\n // detect overlap between second and third labels\n if((Math.abs(a.left - b.left) * 2 < (a.width + b.width)) && \n (Math.abs(a.top - b.top) * 2 < (a.height + b.height))) { \n\n d3.select(secondLabel)\n .attr(\"dx\", secondX-238)\n .attr(\"dy\", secondY-36);\n d3.select(secondLabelThirdLine)\n .attr(\"x\", secondThirdX-238);\n\n d3.select(thirdLabel)\n .attr(\"dx\", thirdX-104)\n .attr(\"dy\", thirdY-72);\n d3.select(thirdLabelThirdLine)\n .attr(\"x\", thirdThirdX-104);\n\n var thisLabel = secondLabel.getBBox();\n var thisRect = document.getElementsByClassName('actual-rect')[1].getBBox();\n var tspanWidth = document.getElementsByClassName('labelThree')[1].getComputedTextLength();\n\n // draw lines from 2nd label\n d3.select(\"svg.ok\") // horizontal\n .append(\"line\")\n .attr(\"id\", \"line-first\")\n .attr(\"x1\", thisLabel.x + tspanWidth+10) \n .attr(\"y1\", 90)\n .attr(\"x2\", thisRect.x + (thisRect.width / 2) + 2 ) \n .attr(\"y2\", 90) \n .style(\"opacity\", 0)\n .style(\"stroke-width\", 4)\n .style(\"stroke\", \"#231f20\")\n .style(\"fill\", \"none\");\n\n d3.select(\"svg.ok\") // vertical\n .append(\"line\")\n .attr(\"id\", \"line-first\")\n .attr(\"x1\", thisRect.x + (thisRect.width / 2) ) \n .attr(\"y1\", 90)\n .attr(\"x2\", thisRect.x + (thisRect.width / 2) ) \n .attr(\"y2\", 140) \n .style(\"opacity\", 0)\n .style(\"stroke-width\", 4)\n .style(\"stroke\", \"#231f20\")\n .style(\"fill\", \"none\");\n\n var thisLabel = thirdLabel.getBBox();\n var thisRect = document.getElementsByClassName('actual-rect')[2].getBBox();\n var tspanWidth = document.getElementsByClassName('labelThree')[2].getComputedTextLength();\n\n // draw lines from 3rd label\n d3.select(\"svg.ok\") // horizontal\n .append(\"line\")\n .attr(\"id\", \"line-second\")\n .attr(\"x1\", thisLabel.x + tspanWidth+10) \n .attr(\"y1\", 54)\n .attr(\"x2\", thisRect.x + (thisRect.width / 2) + 2) \n .attr(\"y2\", 54) \n .style(\"opacity\", 0)\n .style(\"stroke-width\", 4)\n .style(\"stroke\", \"#231f20\")\n .style(\"fill\", \"none\");\n\n d3.select(\"svg.ok\") // vertical\n .append(\"line\")\n .attr(\"id\", \"line-second\")\n .attr(\"x1\", thisRect.x + (thisRect.width / 2)) \n .attr(\"y1\", 54)\n .attr(\"x2\", thisRect.x + (thisRect.width / 2)) \n .attr(\"y2\", 140) \n .style(\"opacity\", 0)\n .style(\"stroke-width\", 4)\n .style(\"stroke\", \"#231f20\")\n .style(\"fill\", \"none\");\n }\n }",
"function improve_labelling()\n {\n if (debug) console.log('improve labelling');\n stat_improve++; // stat\n\n var delta = MSI;\n\n // for (var y=0; y<mat.nc+mat.nr; y++)\n // if (slack[y] < MSI && y_merge.indexOf(y) == -1) // && mat.cost(slackx[y], y) > 0)\n // console.log(y_merge + ' y ' + y + ' slack[y] ' + slack[y] + ' cost ' + mat.cost(slackx[y], y));\n\n // for (var y = 0; y < mat.nc+mat.nr; y++) {\n for (var i_y = 0; i_y < y_merge_back; i_y++) {\n var y = y_merge[i_y];\n if (!T[y] && slack[y] < delta)\n delta = slack[y];\n }\n\n if (debug && delta > 1000000000) alert('no minimal delta found');\n\n // adapt node labels: q holds all nodes in S\n lx[q[0]] -= delta;\n for (var i = 1; i < q_back; i++) {\n var x = q[i];\n lx[x] -= delta;\n ly[xy[x]] += delta;\n }\n\n slack0_pivot = -1;\n // for (var y = 0; y < mat.nc+mat.nr; y++) {\n for (var i_y = 0; i_y < y_merge_back; i_y++) {\n var y = y_merge[i_y];\n if (!T[y] && slack[y] < MSI) {\n slack[y] -= delta;\n if (slack[y] == 0) {\n // store the first with ![T[y] && slack[y]==0, it exists\n if (slack0_pivot == -1) slack0_pivot = y;\n // condition leads immediately to a match in grow_eq_subgraph\n if (yx[y] == -1) {\n slack0_pivot = y;\n break;\n }\n }\n }\n }\n }",
"getIntersectedLabel(x, y) {\n // debugger\n for (const label of this._.labelSet) {\n if (label.minimized) continue;\n if (Utils2D.coordsInElement(x, y, this.refs[getLabelRef(label.id, this._.componentId)])) {\n return label;\n }\n }\n return null;\n }",
"function updateLabelLinePoints(target, labelLineModel) {\n\t if (!target) {\n\t return;\n\t }\n\t\n\t var labelLine = target.getTextGuideLine();\n\t var label = target.getTextContent(); // Needs to create text guide in each charts.\n\t\n\t if (!(label && labelLine)) {\n\t return;\n\t }\n\t\n\t var labelGuideConfig = target.textGuideLineConfig || {};\n\t var points = [[0, 0], [0, 0], [0, 0]];\n\t var searchSpace = labelGuideConfig.candidates || DEFAULT_SEARCH_SPACE;\n\t var labelRect = label.getBoundingRect().clone();\n\t labelRect.applyTransform(label.getComputedTransform());\n\t var minDist = Infinity;\n\t var anchorPoint = labelGuideConfig.anchor;\n\t var targetTransform = target.getComputedTransform();\n\t var targetInversedTransform = targetTransform && invert([], targetTransform);\n\t var len = labelLineModel.get('length2') || 0;\n\t\n\t if (anchorPoint) {\n\t pt2.copy(anchorPoint);\n\t }\n\t\n\t for (var i = 0; i < searchSpace.length; i++) {\n\t var candidate = searchSpace[i];\n\t getCandidateAnchor(candidate, 0, labelRect, pt0, dir);\n\t Point.scaleAndAdd(pt1, pt0, dir, len); // Transform to target coord space.\n\t\n\t pt1.transform(targetInversedTransform); // Note: getBoundingRect will ensure the `path` being created.\n\t\n\t var boundingRect = target.getBoundingRect();\n\t var dist = anchorPoint ? anchorPoint.distance(pt1) : target instanceof Path ? nearestPointOnPath(pt1, target.path, pt2) : nearestPointOnRect(pt1, boundingRect, pt2); // TODO pt2 is in the path\n\t\n\t if (dist < minDist) {\n\t minDist = dist; // Transform back to global space.\n\t\n\t pt1.transform(targetTransform);\n\t pt2.transform(targetTransform);\n\t pt2.toArray(points[0]);\n\t pt1.toArray(points[1]);\n\t pt0.toArray(points[2]);\n\t }\n\t }\n\t\n\t limitTurnAngle(points, labelLineModel.get('minTurnAngle'));\n\t labelLine.setShape({\n\t points: points\n\t });\n\t } // Temporal variable for the limitTurnAngle function",
"function getXofLabel(d, t, y){\n\t\tvar a = nodesData[d.node.src];\n\t\tvar b = nodesData[d.node.tgt];\n\t\tvar ax = a.x - (a.x - b.x) / 3;\n\t\tvar by = b.y - (b.y - a.y) / 3;\n\t\tvar Ax = ((1 - t) * b.x) + (t * b.x);\n\t\tvar Ay = ((1 - t) * b.y) + (t * by);\n\t\tvar Bx = ((1 - t) * b.x) + (t * ax);\n\t\tvar By = ((1 - t) * by) + (t * a.y);\n\t\tvar Cx = ((1 - t) * ax) + (t * a.x);\n\t\tvar Cy = ((1 - t) * a.y) + (t * a.y);\n\t\tvar Dx = ((1 - t) * Ax ) + (t * Bx);\n\t var Dy = ((1 - t) * Ay ) + (t * By);\n\t var Ex = ((1 - t) * Bx ) + (t * Cx);\n\t var Ey = ((1 - t) * By ) + (t * Cy);\n\t var Px = ((1 - t) * Dx ) + (t * Ex);\n\t var Py = ((1 - t) * Dy ) + (t * Ey);\n\t d.x = Px;\n\t return Py < y;\n\t}",
"function labelRect (highlightNode, previousLabelRects) {\n const viewport = getViewportDimensions();\n const scroll = getScrollOffset();\n const highlightRect = getNodeRect(highlightNode);\n\n let current = {\n side: 0,\n rect: start(highlightRect)[sides[0]],\n };\n let lastOnScreen = current;\n\n while (!isFullyOnScreen(current.rect, viewport, scroll) || intersectsPreviousLabels(current.rect, previousLabelRects)) {\n current = next(current, highlightRect);\n if (!current) {\n // could not find a good position after going around once,\n // fallback to whatever fits on screen\n return lastOnScreen;\n }\n if (isFullyOnScreen(current.rect, viewport, scroll)) {\n lastOnScreen = current;\n }\n }\n return lastOnScreen;\n}",
"function label(d) {\n\n delete d.d3plus_label\n\n if (vars.g.edges.selectAll(\"line, path\").size() < vars.edges.large && vars.edges.label && d[vars.edges.label]) {\n\n if (\"spline\" in d.d3plus) {\n\n var length = this.getTotalLength(),\n center = this.getPointAtLength(length/2),\n prev = this.getPointAtLength((length/2)-(length*.1)),\n next = this.getPointAtLength((length/2)+(length*.1)),\n radians = Math.atan2(next.y-prev.y,next.x-prev.x),\n angle = radians*(180/Math.PI),\n bounding = this.parentNode.getBBox(),\n width = length*.8,\n x = d.d3plus.translate.x+center.x,\n y = d.d3plus.translate.y+center.y,\n translate = {\n \"x\": d.d3plus.translate.x+center.x,\n \"y\": d.d3plus.translate.y+center.y\n }\n\n }\n else {\n\n var bounds = this.getBBox()\n start = {\"x\": d[vars.edges.source].d3plus.dx, \"y\": d[vars.edges.source].d3plus.dy},\n end = {\"x\": d[vars.edges.target].d3plus.dx, \"y\": d[vars.edges.target].d3plus.dy},\n xdiff = end.x-start.x,\n ydiff = end.y-start.y,\n center = {\"x\": end.x-(xdiff)/2, \"y\": end.y-(ydiff)/2},\n radians = Math.atan2(ydiff,xdiff),\n angle = radians*(180/Math.PI),\n length = Math.sqrt((xdiff*xdiff)+(ydiff*ydiff)),\n width = length,\n x = center.x,\n y = center.y,\n translate = {\n \"x\": center.x,\n \"y\": center.y\n }\n\n }\n\n width += vars.labels.padding*2\n\n var m = 0\n if (vars.edges.arrows.value) {\n m = typeof vars.edges.arrows.value === \"number\"\n ? vars.edges.arrows.value : 8\n m = m/vars.zoom.behavior.scaleExtent()[1]\n width -= m*2\n }\n\n if (angle < -90 || angle > 90) {\n angle -= 180\n }\n\n if (width*vars.zoom.behavior.scaleExtent()[0] > 20) {\n\n d.d3plus_label = {\n \"x\": x,\n \"y\": y,\n \"translate\": translate,\n \"w\": width,\n \"h\": 15+vars.labels.padding*2,\n \"angle\": angle,\n \"anchor\": \"middle\",\n \"valign\": \"center\",\n \"color\": vars.edges.color,\n \"resize\": false,\n \"names\": [vars.format.value(d[vars.edges.label])],\n \"background\": 1\n }\n\n }\n\n }\n\n }",
"_overlapsLabel(label) {\n const that = this,\n labelRect = label.getBoundingClientRect();\n let headRect = that._headRect;\n\n if (headRect.height === 0) {\n headRect = that._headRect = that._head.getBoundingClientRect();\n }\n\n return !(labelRect.right - 10 < headRect.left ||\n labelRect.left + 10 > headRect.right ||\n labelRect.bottom - 10 < headRect.top ||\n labelRect.top + 10 > headRect.bottom);\n }",
"fit (size, line, layout, tolerance){\n let upp = layout.units_per_pixel;\n let flipped; // boolean indicating if orientation of line is changed\n\n // Make new copy of line, with consistent orientation\n [line, flipped] = LabelLineBase.splitLineByOrientation(line);\n\n // matches for \"left\" or \"right\" labels where the offset angle is dependent on the geometry\n if (typeof layout.orientation === 'number'){\n this.offset[1] += ORIENTED_LABEL_OFFSET_FACTOR * (size[1] - layout.vertical_buffer);\n\n // if line is flipped, or the orientation is \"left\" (-1), flip the offset's y-axis\n if (flipped){\n this.offset[1] *= -1;\n }\n\n if (layout.orientation === -1){\n this.offset[1] *= -1;\n }\n }\n\n let line_lengths = getLineLengths(line);\n let label_length = size[0] * upp;\n\n // loop through line looking for a placement for the label\n for (let i = 0; i < line.length - 1; i++){\n let curr = line[i];\n\n let curve_tolerance = 0;\n let length = 0;\n let ahead_index = i + 1;\n let prev_angle;\n\n // look ahead to further line segments within an angle tolerance\n while (ahead_index < line.length){\n let ahead_curr = line[ahead_index - 1];\n let ahead_next = line[ahead_index];\n\n let next_angle = getAngleForSegment(ahead_curr, ahead_next);\n\n if (ahead_index !== i + 1){\n curve_tolerance += getAbsAngleDiff(next_angle, prev_angle);\n }\n\n // if curve tolerance is exceeded, break out of loop\n if (Math.abs(curve_tolerance) > STRAIGHT_ANGLE_TOLERANCE){\n break;\n }\n\n length += line_lengths[ahead_index - 1];\n\n // check if label fits geometry\n if (calcFitness(length, label_length) < tolerance){\n let curr_midpt = Vector.mult(Vector.add(curr, ahead_next), 0.5);\n\n // TODO: modify angle if line chosen within curve_angle_tolerance\n // Currently line angle is the same as the starting angle, perhaps it should average across segments?\n this.angle = -next_angle;\n let angle_offset = this.angle;\n\n // if line is flipped, or the orientation is \"left\" (-1), rotate the angle of the offset 180 deg\n if (typeof layout.orientation === 'number'){\n if (flipped){\n angle_offset += Math.PI;\n }\n\n if (layout.orientation === -1){\n angle_offset += Math.PI;\n }\n }\n\n // ensure that all vertical labels point up (not down) by snapping angles close to pi/2 to -pi/2\n if (Math.abs(this.angle - Math.PI/2) < VERTICAL_ANGLE_TOLERANCE) {\n // flip angle and offset\n this.angle = -Math.PI/2;\n\n if (typeof layout.orientation === 'number'){\n this.offset[1] *= -1;\n }\n }\n\n this.position = curr_midpt;\n\n this.updateBBoxes(this.position, size, this.angle, this.angle, this.offset);\n\n if (this.inTileBounds()) {\n return true;\n }\n }\n\n prev_angle = next_angle;\n ahead_index++;\n }\n }\n\n return false;\n }",
"drawlabels() {\n \n if (this.internal.volume===null)\n return;\n \n var context=this.internal.layoutcontroller.context;\n var dw=context.canvas.width;\n var dh=context.canvas.height;\n context.clearRect(Math.floor(this.cleararea[0]*dw),0,Math.floor(this.cleararea[1]*dw),dh);\n let cdim=$(context.canvas).css(['width','height','left','top' ]);\n \n // Add R&L s\n var labels = [ [ 'A','P', 'S','I' ] ,\n [ 'R','L', 'S','I' ] ,\n [ 'R','L', 'A','P' ] ];\n var names = [ 'Sagittal','Coronal','Axial'];\n var axes = [ '-jk','-ik','-ij' ];\n \n var fnsize=0;\n if (this.internal.simplemode)\n fnsize=Math.round(2*webutil.getfontsize(context.canvas)/3);\n else\n fnsize=Math.round(webutil.getfontsize(context.canvas)*this.cleararea[1]);\n\n context.font=fnsize+\"px Arial\";\n\n if (this.internal.simplemode)\n context.fillStyle = \"#884400\";\n else\n context.fillStyle = \"#cc6600\";\n\n\n let arrowsize=this.createarrowbuttons($(context.canvas).parent().parent(),fnsize);\n this.createmidline(context.canvas,dw,dh);\n\n if (this.internal.showdecorations===false) {\n this.hidearrowbuttons();\n return;\n }\n \n var invorientaxis = this.internal.volume.getOrientation().invaxis;\n var orientaxis = this.internal.volume.getOrientation().axis;\n let maxpl=2;\n if (this.internal.subviewers[3])\n maxpl=3;\n\n \n for (var pl=0;pl<=maxpl;pl++) {\n var trueplane=invorientaxis[pl];\n var lab=labels[trueplane];\n var vp =this.internal.subviewers[pl].getNormViewport();\n \n //console.log('Lab=',lab,(vp.x1-vp.x0)*dw,this.minLabelWidth);\n \n if ((vp.x1-vp.x0)*dw>this.minLabelWidth) {\n if (pl<=2) {\n \n let dx=0.25*vp.shiftx*dw;\n if (dx>120)\n dx=120;\n \n let dy=0.25*vp.shifty*dh;\n if (dy>50)\n dy=50;\n \n let xshift=[ -(2+dx),dx-(arrowsize+1)];\n let xshift0=[-(2+dx),(dx+2)];\n \n let ymid=Math.round( dh*(1.0-0.5*(vp.y0+vp.y1))+6);\n let xmin=vp.x0*dw+xshift0[0];\n if (xmin<2)\n xmin=2;\n let xmax=vp.x1*dw+xshift0[1];\n if (xmax>(dw-2))\n xmax=dw-2;\n \n context.textBaseline=\"middle\";\n context.textAlign=\"start\"; context.fillText(lab[0],xmin,ymid);\n context.textAlign=\"end\"; context.fillText(lab[1],xmax,ymid);\n \n let xmid=Math.round( dw*0.5*(0.5*vp.x0+1.5*vp.x1)-6);\n let ymin=Math.round((1.0-vp.y1)*dh)-dy;\n if (ymin<(fnsize+2))\n ymin=(fnsize+2);\n let ymax=Math.round((1.0-vp.y0)*dh)+dy;\n if (ymax>0.9*dh)\n ymax=0.9*dh;\n \n if (!this.internal.simplemode) {\n context.textAlign=\"center\";\n context.textBaseline=\"top\";\n context.fillText(lab[2],xmid,ymin);\n context.textBaseline=\"alphabetic\";\n context.fillText(lab[3],xmid,ymax);\n } else {\n context.textBaseline=\"alphabetic\";\n }\n \n let name=names[trueplane]+axes[orientaxis[trueplane]];\n context.textAlign=\"start\";\n context.fillText(name,xmin,ymin);\n \n if (!this.internal.simplemode) {\n let wd=Math.round(parseInt(cdim['width']));\n let lf=Math.round(parseInt(cdim['left']));\n let left=this.internal.layoutcontroller.getviewerleft();\n let l= [ Math.round(vp.x0*wd+lf+xshift[0]+left),\n Math.round(vp.x1*wd+lf+xshift[1])+left];\n if (l[0]<0)\n l[0]=0;\n \n \n \n let h=Math.round((1-(0.75*vp.y1+0.25*vp.y0))*parseInt(cdim['height']))+parseInt(cdim['top']);\n \n for (let k=0;k<=1;k++) {\n this.internal.arrowbuttons[pl*2+k].css({ 'left' : `${l[k]}px`,\n 'top' : `${h}px`,\n 'visibility' : 'visible'});\n }\n }\n }\n if (!this.internal.layoutcontroller.isCanvasDark())\n context.strokeStyle = \"#dddddd\";\n else\n context.strokeStyle = \"#222222\";\n \n \n \n context.lineWidth=1;\n context.beginPath();\n \n if (pl===3)\n vp=this.internal.subviewers[pl].getNormViewport().old;\n \n \n context.moveTo(vp.x0*dw,(1-vp.y0)*dh);\n context.lineTo(vp.x0*dw,(1-vp.y1)*dh);\n context.lineTo(vp.x1*dw,(1-vp.y1)*dh);\n context.lineTo(vp.x1*dw,(1-vp.y0)*dh);\n context.lineTo(vp.x0*dw,(1-vp.y0)*dh);\n context.stroke();\n } else if (pl<3) {\n for (let ia=0;ia<=1;ia++)\n if (this.internal.arrowbuttons[pl*2+ia])\n this.internal.arrowbuttons[pl*2+ia].css({'visibility':'hidden'});\n }\n }\n \n\n\n // Movie Stuff\n if (!this.internal.simplemode) {\n\n //console.log(\"Checking on arrows\",this.internal.maxnumframes);\n if (this.internal.maxnumframes<2 || dw<500) {\n \n for (let ia=6;ia<=11;ia++)\n if (this.internal.arrowbuttons[ia])\n this.internal.arrowbuttons[ia].css({'visibility':'hidden'});\n \n } else {\n \n let lh=this.internal.layoutcontroller.getviewerheight();\n let left=this.internal.layoutcontroller.getviewerleft();\n let y0=0.92*lh+parseInt(cdim['top']);\n for (let k=0;k<=5;k++) {\n let extra=0;\n if (k>3)\n extra=20;\n this.internal.arrowbuttons[6+k].css({ 'left' : `${50+40*k+left+extra}px`,\n 'top' : `${y0}px`,\n 'visibility' : 'visible'});\n }\n }\n }\n \n }",
"contains(p) {\n let sp = start.getConnectionPoint(center(end.getBounds())) // StartPoint\n let ep = end.getConnectionPoint(center(start.getBounds())) // End Point\n\n console.log(Math.abs(p.y - lineFOfX(p.x, sp, ep)))\n\n return Math.abs(p.y - lineFOfX(p.x, sp, ep)) < 5\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new MultiRange object. | function MultiRange(data, options) {
if (options === void 0) { options = defaultOptions; }
function isArray(x) {
return Object.prototype.toString.call(x) === '[object Array]';
}
this.ranges = [];
this.options = {
parseNegative: !!options.parseNegative,
parseUnbounded: !!options.parseUnbounded
};
if (typeof data === 'string') {
this.parseString(data);
}
else if (typeof data === 'number') {
this.appendRange(data, data);
}
else if (data instanceof MultiRange) {
this.ranges = data.getRanges();
if (arguments[1] === undefined) {
this.options = {
parseNegative: data.options.parseNegative,
parseUnbounded: data.options.parseUnbounded
};
}
}
else if (isArray(data)) {
for (var _i = 0, _a = data; _i < _a.length; _i++) {
var item = _a[_i];
if (isArray(item)) {
if (item.length === 2) {
this.appendRange(item[0], item[1]);
}
else {
throw new TypeError('Invalid array initializer');
}
}
else if (typeof item === 'number') {
this.append(item);
}
else {
throw new TypeError('Invalid array initialzer');
}
}
}
else if (data !== undefined) {
throw new TypeError('Invalid input');
}
} | [
"function multirange(data, options) {\n return new MultiRange(data, options);\n}",
"range(from, to = from) { return Range$1.create(from, to, this); }",
"function createInputRangeMulti(slider) {\n\n var range_multi_start = JSON.parse(input_range_data(slider, \"start\"));\n var range_multi_ranges = JSON.parse(input_range_data(slider, \"ranges\"));\n \n noUiSlider.create(slider, {\n start: range_multi_start,\n connect: true,\n range: range_multi_ranges\n });\n }",
"function Range() {}",
"function create_range(start, end) {\n return RangeImpl_1.RangeImpl._create(start, end);\n}",
"range(from, to = from) { return Range.create(from, to, this); }",
"function createRange(start, end, step) {\n return new Range(Object(_utils_is_js__WEBPACK_IMPORTED_MODULE_0__[\"isBigNumber\"])(start) ? start.toNumber() : start, Object(_utils_is_js__WEBPACK_IMPORTED_MODULE_0__[\"isBigNumber\"])(end) ? end.toNumber() : end, Object(_utils_is_js__WEBPACK_IMPORTED_MODULE_0__[\"isBigNumber\"])(step) ? step.toNumber() : step);\n }",
"function createRange(start, end, step) {\n return new Range$$1(\n type.isBigNumber(start) ? start.toNumber() : start,\n type.isBigNumber(end) ? end.toNumber() : end,\n type.isBigNumber(step) ? step.toNumber() : step\n );\n }",
"function createRange(start, end, step) {\n return new Range(Object(_utils_is__WEBPACK_IMPORTED_MODULE_0__[\"isBigNumber\"])(start) ? start.toNumber() : start, Object(_utils_is__WEBPACK_IMPORTED_MODULE_0__[\"isBigNumber\"])(end) ? end.toNumber() : end, Object(_utils_is__WEBPACK_IMPORTED_MODULE_0__[\"isBigNumber\"])(step) ? step.toNumber() : step);\n }",
"range(from, to = from) { return new Range(from, to, this); }",
"function createRange(start, end, step) {\n return new Range(Object(__WEBPACK_IMPORTED_MODULE_0__utils_is_js__[\"e\" /* isBigNumber */])(start) ? start.toNumber() : start, Object(__WEBPACK_IMPORTED_MODULE_0__utils_is_js__[\"e\" /* isBigNumber */])(end) ? end.toNumber() : end, Object(__WEBPACK_IMPORTED_MODULE_0__utils_is_js__[\"e\" /* isBigNumber */])(step) ? step.toNumber() : step);\n }",
"function createRange(start, end, step) {\n return new Range(\n type.isBigNumber(start) ? start.toNumber() : start,\n type.isBigNumber(end) ? end.toNumber() : end,\n type.isBigNumber(step) ? step.toNumber() : step\n );\n }",
"function range(from, to) { // Use Object.create() to create an object that inherits from the \n\n let r = Object.create(range.methods);\n\n r.from = from;\n r.to = to;\n return r;\n}",
"constructor() {\n this.rangeList = [];\n }",
"function createRange(pos, end) {\n return { pos: pos, end: end };\n }",
"copy() {\n return new Range(this._min, this._max); // eslint-disable-line no-html-constructors\n }",
"function createRange(pos, end) {\n return { pos: pos, end: end };\n }",
"addRange(high, low, mid) {\n this.range.push({\n 'high': high,\n 'low': low,\n 'mid': mid,\n })\n //return this.range\n }",
"function createRange(start, end, step) {\n return new Range((0, _is.isBigNumber)(start) ? start.toNumber() : start, (0, _is.isBigNumber)(end) ? end.toNumber() : end, (0, _is.isBigNumber)(step) ? step.toNumber() : step);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
resize youtube player depending on window size | function ResizePlayer()
{
var newWidth = window.innerWidth * 0.45;
var newHeight = newWidth * 0.625;
if((newWidth >= playerMinSize) && (newWidth <= playerMaxSize)) {
$(".youtube-embed").width(newWidth);
$(".youtube-embed").height(newHeight);
$(".learning-content").width(newWidth + 340);
}
} | [
"function gfortYoutubeVideoSizefn() {\n jQuery('.background-video-block div[data-youtube-video-url] iframe.gfort-youtube-iframe').each(function () {\n\n var elWidth = 16,\n elHeight = 9,\n el = jQuery(this),\n elParent = el.parents('.background-video-block'),\n elParentWidth = elParent.outerWidth(true),\n elParentHeight = elParent.outerHeight(true),\n widthRatio = elParentWidth / elWidth,\n heightRatio = elParentHeight / elHeight,\n ratio = widthRatio > heightRatio\n ? widthRatio\n : heightRatio,\n elNewWidth = ratio * elWidth,\n elNewHeight = ratio * elHeight,\n elMarginLeft = (elNewWidth - elParentWidth) / -2,\n elMarginTop = (elNewHeight - elParentHeight) / -2;\n\n el.css({\n width: elNewWidth,\n height: elNewHeight,\n marginTop: elMarginTop,\n marginLeft: elMarginLeft\n });\n\n });\n }",
"function resizePlayer() {\n var isAndroid = navigator.userAgent.match(/Android/i) ? true : false;\n var $videoWindow = $(window),\n overlay = modVP.overlay(),\n overlayWidth = $videoWindow.width(),\n //Android Landscape requires reduced height\n overlayHeight = (isAndroid && window.innerWidth > window.innerHeight) ? $videoWindow.height() - 65 : $videoWindow.height();\n\n // Set video size through brightcove api call\n modExp.setSize(overlayWidth, overlayHeight);\n //Set the overlay size\n $(overlay).width(overlayWidth).height(overlayHeight);\n }",
"function setPlayerSize() {\n var xscale = window.innerWidth / currentVideo.width;\n var yscale = window.innerHeight / currentVideo.height;\n var scale = Math.min(xscale, yscale);\n var width = currentVideo.width * scale;\n var height = currentVideo.height * scale;\n var left = (window.innerWidth - width) / 2;\n var top = (window.innerHeight - height) / 2;\n player.style.width = width + 'px';\n player.style.height = height + 'px';\n player.style.left = left + 'px';\n player.style.top = top + 'px';\n }",
"function onWindowResize() {\n $embed.attr('height', $player.height());\n}",
"function smallPlayer() {\n resizePlayer(480, 295);\n}",
"function expandPlayer() {\n\n // Height of the player\n height = '520';\n\n // Change the height of MP4 and/or Flash versions\n if ($('mp4-player')) {\n $('mp4-player').height = height + 'px';\n $('watch-player-div').style.height = height + 'px';\n }\n if ($('movie_player')) {\n $('movie_player').style.height = height + 'px';\n $('movie_player').height = height + 'px';\n $('watch-player-div').style.height = height + 'px';\n }\n\n}",
"function yolox_set_mejs_player_dimensions(video, w, h) {\n\t\t\tif (mejs) {\n\t\t\t\tfor (var pl in mejs.players) {\n\t\t\t\t\tif (mejs.players[pl].media.src == video.attr( 'src' )) {\n\t\t\t\t\t\tif (mejs.players[pl].media.setVideoSize) {\n\t\t\t\t\t\t\tmejs.players[pl].media.setVideoSize( w, h );\n\t\t\t\t\t\t} else if (mejs.players[pl].media.setSize) {\n\t\t\t\t\t\t\tmejs.players[pl].media.setSize( w, h );\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmejs.players[pl].setPlayerSize( w, h );\n\t\t\t\t\t\tmejs.players[pl].setControlsSize();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}",
"function cms_auto_video_width() {\r\n\t\t$('.entry-video iframe').each(function(){\r\n\t\t\tvar v_width = $(this).width();\r\n\t\t\t\r\n\t\t\tv_width = v_width / (16/9);\r\n\t\t\t$(this).attr('height',v_width + 35);\r\n\t\t})\r\n\t}",
"function trx_addons_set_mejs_player_dimensions(video, w, h) {\n \"use strict\";\n if (mejs) {\n for (var pl in mejs.players) {\n if (mejs.players[pl].media.src == video.attr('src')) {\n if (mejs.players[pl].media.setVideoSize) {\n mejs.players[pl].media.setVideoSize(w, h);\n }\n mejs.players[pl].setPlayerSize(w, h);\n mejs.players[pl].setControlsSize();\n }\n }\n }\n}",
"function resizeVideo(){\n\t$(\"#opening-video\").width($(\"#intro-video\").innerWidth());\n\t$(\"#opening-video\").height(31*($(\"#intro-video\").innerWidth()/48));\t\t\n}",
"function largePlayer() {\n resizePlayer(640, 385);\n}",
"function setMejsPlayerDimensions(video, w, h) {\n\tif (mejs) {\n\t\tfor (var pl in mejs.players) {\n\t\t\tif (mejs.players[pl].media.src == video.attr('src')) {\n\t\t\t\tif (mejs.players[pl].media.setVideoSize) {\n\t\t\t\t\tmejs.players[pl].media.setVideoSize(w, h);\n\t\t\t\t}\n\t\t\t\tmejs.players[pl].setPlayerSize(w, h);\n\t\t\t\tmejs.players[pl].setControlsSize();\n\t\t\t\t//var mejs_cont = video.parents('.mejs-video');\n\t\t\t\t//mejs_cont.css({'width': w+'px', 'height': h+'px'}).find('.mejs-layers > div, .mejs-overlay, .mejs-poster').css({'width': w, 'height': h});\n\t\t\t}\n\t\t}\n\t}\n}",
"function setVideoPlayerConstantSize(){\n\t\t\n\t\tvar videoWidth = g_options.slider_video_constantsize_width;\n\t\tvar videoHeight = g_options.slider_video_constantsize_height;\n\t\t\n\t\tg_objVideoPlayer.setSize(videoWidth, videoHeight);\n\t\t\n\t\t//set video design\n\t\tvar videoElement = g_objVideoPlayer.getObject();\n\t\t\n\t\tsetImageDesign(videoElement, \"video\");\n\t}",
"function setPanelSize(){\n var windowHeight = $(window).height();\n var windowWidth = $(window).width();\n var windowWidthColor = $('.padd_box').height();\n var textWrap = $('.text_wrap').height();\n\n //calculate whether the video is too tall for the space\n //resize video and panel\n\n $('.menu_wrap').css({'padding-top': (windowHeight - windowWidthColor) / 2 + 'px' });\n $('.home_head').css({'height': windowHeight + 'px' });\n $('.text_wrap').css({'margin-top': - textWrap / 2 + 30 + 'px' });\n $('.how_do iframe').css({'height': windowWidth / 2 / 1920 * 1080 + 'px' });\n\n }",
"function setPlayerSize(width, height) {\n if (width < 180) {\n width = 180;\n }\n\n if (height < 180) {\n height = 180;\n }\n\n player.setSize(width, height);\n}",
"function vidRescale() {\n var w = $(window).width();\n var h = $(window).height();\n if (w / h > 16 / 9) {\n player1.setSize(w, w / 16 * 9);\n player2.setSize(w, w / 16 * 9);\n player3.setSize(w, w / 16 * 9);\n $('#player1').css({'left': '0'});\n $('#player2').css({'left': '0'});\n $('#player3').css({'left': '0'});\n } else {\n player1.setSize(h / 9 * 16, h);\n player2.setSize(h / 9 * 16, h);\n player3.setSize(h / 9 * 16, h);\n $('#player1').css({'left': -($('#player1').outerWidth() - w) / 2});\n $('#player2').css({'left': -($('#player2').outerWidth() - w) / 2});\n $('#player3').css({'left': -($('#player3').outerWidth() - w) / 2});\n }\n}",
"function size_iframes () {\n\tvar width = window.innerWidth;\n\tvar height= window.innerHeight;\t\t// need at least 200px by 200px players\n\tif (height < 400 || width < 400) {alert(\"Window is too small for multiple Youtube videos to fit.\");}\n\n\tif (height > 600) {\tvar iframeHeight = (height / 3) - 12 ;} \n\telse { iframe_height = (height / 2) - 18 ; }\t// subtract to make it fit better\n\t\n\tif (width >= 1067) {var iframeWidth = (width / 3)-10; } \n\telse { iframeWidth = (width / 2)-13 ; }\n\n\t// no concating strings, just replace after rounding\n\tvar frameText = iframe_begin.replace(\"640\", Math.floor(iframeWidth));\n\tframeText = frameText.replace(\"360\", Math.floor(iframeHeight));\n\t\n\treturn frameText;\n}",
"function updateSizeConstraints()\r\n {\r\n var video = m_item.find(\"video\");\r\n var w = video.width();\r\n var h = video.height();\r\n var ratio = w / h;\r\n\r\n var margin = low.fullscreenStatus() ? 0 : 80;\r\n var viewWidth = $(window).width() - margin;\r\n var viewHeight = $(window).height() - margin;\r\n\r\n var w2 = viewHeight * ratio;\r\n var h2 = viewHeight;\r\n if (w2 > viewWidth)\r\n {\r\n w2 = viewWidth;\r\n h2 = viewWidth / ratio;\r\n }\r\n\r\n video\r\n .css(\"min-width\", w2 + \"px\")\r\n .css(\"min-height\", h2 + \"px\")\r\n .css(\"max-width\", viewWidth + \"px\")\r\n .css(\"max-height\", viewHeight + \"px\")\r\n .css(\"margin\", low.fullscreenStatus() ? \"0\" : \"0.2rem\");\r\n\r\n if ((w2 < viewWidth || h2 < viewHeight) && low.fullscreenStatus())\r\n {\r\n video.css(\"transform\",\r\n \"translateX(\" + ((viewWidth - w2) / 2) + \"px) \" +\r\n \"translateY(\" + ((viewHeight - h2) / 2) + \"px)\");\r\n }\r\n else\r\n {\r\n video.css(\"transform\", \"initial\");\r\n }\r\n }",
"function room_set_mejs_player_dimensions(video, w, h) {\n\t\"use strict\";\n\tif (mejs) {\n\t\tfor (var pl in mejs.players) {\n\t\t\tif (mejs.players[pl].media.src == video.attr('src')) {\n\t\t\t\tif (mejs.players[pl].media.setVideoSize) {\n\t\t\t\t\tmejs.players[pl].media.setVideoSize(w, h);\n\t\t\t\t}\n\t\t\t\tmejs.players[pl].setPlayerSize(w, h);\n\t\t\t\tmejs.players[pl].setControlsSize();\n\t\t\t}\n\t\t}\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Global ID of mouse down interval | function mousedown(event) {
if(mousedownID==-1) //Prevent multimple loops!
mousedownID = setInterval(whilemousedown, 250 /*execute every 300ms*/);
} | [
"function mouseupfunc() {\n clearInterval(intervalId);\n}",
"function mousedown(event) {\n if(mousedownID==-1) //Prevent multimple loops!\n mousedownID = setInterval(function(){whilemousedown(event, this);}, 100 /*execute every 100ms*/);\n\n\n}",
"function mousedown(event) {\n\t\tif (mousedownID == -1) //Prevent multimple loops! \n\t\t{\n\t\t\tmousedownID = 1\n\t\t}\n\n\t}",
"function mousedownfunc(evt) {\n intervalId = setInterval(moveStickers, 15, evt);\n}",
"function mouseDown(event) {\n mouseIsDown = true;\n // if (drawHandle === -1) {\n // drawHandle = setInterval(mousePressed, 100);\n // }\n }",
"function markingMenuOnMouseDown(){\r\n\r\n\ttracker.startTimer();\r\n}",
"function markingMenuOnMouseDown() {\r\n\ttracker.startTimer();\r\n}",
"function markingMenuOnMouseDown() {\r\n\r\n\t\ttracker.startTimer();\r\n}",
"function incdec_mousedown_handler(e){\n\t\tvar actor = e.source;\n\t\tvar __scene = game.getScene();\n\t\tif(timer_incdec!=null){\n\t\t\ttimer_incdec.cancel();\n\t\t}\n\t\t\n\t\tgame.incDecHandler(actor);\n\t\t\n\t\t\n\t\ttimer_incdec = __scene.createTimer(\n\t\t__scene.time, //start time\n\t\tNumber.MAX_VALUE, //Duration\n\t\tfunction(scene_time, time_time, time_instance){\t//callback_timeout\n\t\t\t//\n\t\t},\n\t\tfunction(scene_time, time_time, time_instance){\t//callback_tick\n\t\t\tcounter++;\n\t\t\tif(counter%10 == 0){\n\t\t\t\tgame.incDecHandler(actor);\n\t\t\t\tcounter = 0;\n\t\t\t}\n\t\t\t//actor.mouseUp = incdec_mouseup_handler;\n\t\t},\n\t\tfunction(scene_time, time_time, time_instance){ //callback cancel\n\t\t\tif(counter > 0) incdec_mouseup_handler(window.event);\n\t\t});\n\t}",
"function mouseOut()\n{\n clearInterval(intervalo);\n}",
"mouseDown(event){\n }",
"function IMGDown(div, e) {\r\n window.addEventListener(\"mouseup\", StopClicking, false);\r\n \r\n t[t.length] = setInterval(function () { IMGClick(div, e); }, 30); \r\n\r\n }",
"function mouseDownHandler() {\n updateCoordinates(event);\n mouseDown = true;\n console.log(\"mouse down.\");\n }",
"sketchpad_mouseDown() {\n this.mouseDown = 1;\n this.drawDot(this.mouseX, this.mouseY);\n }",
"mouseDown(x, y, _isLeftButton) {}",
"function mousePressed() {\n\tstartTimer();\n}",
"_onMouseLeave(){\n this._startMouseTimer();\n }",
"function mouseDown(e) \n\t{\n\t\tvar mousecode = \"_\" + e.which;\n\t\tmouse[mousecode] = true;\n\t}",
"function mouseReleased() {\n actRandomSeed = random(100000);\n loop();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
CREATES A NEW MATCH | createMatch(matchName) {
return Match.create({ matchName });
} | [
"function createMatch() {\n var match = newMatch();\n matches.push(match);\n return match;\n}",
"function newMatch(candidate1, candidate2, match_id) {\n return {\n type: NEW_MATCH,\n candidates: [candidate1, candidate2],\n matchID: match_id,\n }\n}",
"function matchCreator(homeClub, awayClub) {\r\n let homeScore = 0,\r\n awayScore = 0,\r\n match = new FantasyMatch({\r\n _id: new mongoose.Types.ObjectId(),\r\n homeClub: homeClub._id,\r\n homeScore,\r\n awayClub: awayClub._id,\r\n awayScore,\r\n final: false\r\n });\r\n \r\n save(match);\r\n \r\n return match;\r\n}",
"_setInitialMatches(query) {\n this._matchState = {};\n const start = CodeMirror.Pos(this._cm.doc.firstLine(), 0);\n const end = CodeMirror.Pos(this._cm.doc.lastLine());\n const content = this._cm.doc.getRange(start, end);\n const lines = content.split('\\n');\n let totalMatchIndex = 0;\n lines.forEach((line, lineNumber) => {\n query.lastIndex = 0;\n let match = query.exec(line);\n while (match) {\n const col = match.index;\n const matchObj = {\n text: match[0],\n line: lineNumber,\n column: col,\n fragment: line,\n index: totalMatchIndex\n };\n if (!this._matchState[lineNumber]) {\n this._matchState[lineNumber] = {};\n }\n this._matchState[lineNumber][col] = matchObj;\n match = query.exec(line);\n }\n });\n }",
"static createMatch(category, matchNumber, match) {\n let details = {\n tournamentID: this.tournament ? this.tournament.id : undefined,\n category: category,\n matchNumber: matchNumber,\n };\n if (match) {\n details = match;\n }\n Database.matches.push(details);\n\n API.graphql(graphqlOperation(mutations.createMatch, {input: details})).then((resolve) => {\n details.id = resolve.data.createMatch.id;\n if (!details.racer1ID || !details.racer2ID || !details.winnerID) {\n for (let racer of this.racerList) {\n if (racer.racerNumber === match.racer1Number) {\n details.racer1ID = racer.id;\n }\n if (racer.racerNumber === match.racer2Number) {\n details.racer2ID = racer.id;\n }\n if (racer.racerNumber === match.winnerRacerNumber) {\n details.winnerID = racer.id;\n }\n }\n }\n }, (reject) => {\n });\n }",
"startNewSearch() {\n let b = new Block(this.currentBlock);\n this.previousBlocks[b.prevBlockHash] = this.currentBlock;\n this.currentBlock = b;\n let output = {};\n output[this.keys.id] = 1;\n let cbTrans = utils.makeTransaction(this.keys.private, output);\n this.currentBlock.addTransaction(cbTrans, true);\n this.currentBlock.proof = 0;\n }",
"function rebuildSearchIndex() {\n search = new JsSearch.Search(\"id\");\n search.tokenizer = new JsSearch.StopWordsTokenizer(\n new JsSearch.SimpleTokenizer()\n );\n search.indexStrategy = new JsSearch.AllSubstringsIndexStrategy();\n search.addIndex(\"id\");\n search.addIndex(\"title\");\n search.addIndex(\"tags\");\n search.addDocuments(index.zettels);\n}",
"static async findOrCreate(match, opts = {}) {\n\n let res = await Model.findOneBy(match);\n\n if (res) {\n res = new Model(match);\n await res.save();\n }\n\n return res;\n }",
"_updateMatches() {\n let matches = [];\n let completeList = this.words.concat(this.extraWords);\n completeList.forEach((word) => {\n word.matches.forEach((match) => {\n matches.push({\n match,\n word\n });\n });\n });\n matches.sort(function (a, b) {\n return b.match.length - a.match.length;\n });\n this.matches = matches;\n }",
"function createOrUpdateMatch(match) {\n // this retrieves the userId of the matching user\n return _uuidToUserId(match.uuid)\n .then(userId => {\n\n userId = parseInt(userId);\n match['fromUserId'] = userId;\n match.matchedUserId = parseInt(match.matchedUserId);\n\n if (userId === match.matchedUserId) {\n throw new Error('Cannot match your own userId!');\n }\n\n const matchObject = {\n 'userId1': '',\n 'userId2': ''\n };\n\n if (match.fromUserId < match.matchedUserId) {\n matchObject.userId1 = match.fromUserId;\n matchObject.userId2 = match.matchedUserId;\n } else {\n matchObject.userId2 = match.fromUserId;\n matchObject.userId1 = match.matchedUserId;\n }\n\n let currentUserString;\n if (matchObject.userId1 === match.fromUserId) {\n matchObject['opinion1'] = match.opinion;\n currentUserString = '1';\n } else {\n matchObject['opinion2'] = match.opinion;\n currentUserString = '2';\n }\n\n // this retrieves a row where from and to are the same\n return knex('matches')\n .where({ 'userId1': matchObject.userId1,\n 'userId2': matchObject.userId2 })\n .then(rows => {\n if (rows.length === 0) {\n return knex('matches')\n .insert(matchObject)\n .then(result => {\n console.log('matchRow added');\n });\n } else {\n const earlierRow = rows[0];\n // check if the row in DB already has this user's new opinion\n if (earlierRow['opinion' + currentUserString] !== match.opinion) {\n // console.log('opinion changed or missing --> update with this matchObject:');\n // console.log(matchObject);\n return knex('matches')\n .returning('id')\n .where({ 'userId1': matchObject.userId1,\n 'userId2': matchObject.userId2 })\n .update(matchObject)\n .then(updatedRows => {\n const otherUserString = currentUserString === '1' ? '2' : '1';\n const otherUserOpinion = earlierRow['opinion' + otherUserString];\n // console.log('currentUserString: ' + currentUserString);\n // console.log('currentUserOpinion: ' + match.opinion);\n // console.log('oterUserString: ' + otherUserString);\n // console.log('oterUserOpinion: ' + otherUserOpinion);\n if (match.opinion === 'UP' && otherUserOpinion === 'UP') {\n // console.log('both users have UP');\n // if the row ALREADY has firebaseChatId then the two users\n // already have a chat in Firebase -> no need to create a new one\n // this could happen if one first UPs, then the other UPs, then\n // either DOWNs and UPs again\n if (!earlierRow['firebaseChatId']) {\n return handleMatch(matchObject);\n }\n }\n })\n }\n }\n })\n })\n}",
"function create(newText, insert, replace) {\n return {\n newText: newText,\n insert: insert,\n replace: replace\n };\n }",
"function create(newText, insert, replace) {\n return { newText: newText, insert: insert, replace: replace };\n }",
"scheduleMatches() {\n matches = [];\n for (i = 0; i < this.players.length; i++) {\n for (j = i + 1; j < this.players.length; j++) {\n matches.push({\n league: this._id,\n players: [\n this.players[i], this.players[j]\n ]\n });\n }\n }\n\n Match.create(matches);\n }",
"function create(newText, insert, replace) {\n return { newText: newText, insert: insert, replace: replace };\n }",
"newDocument(state, action) {\n let newState = Automerge.init()\n\n return Automerge.change(newState, this.meta(action), (doc) => {\n let data = seedData()\n\n doc.cards = data.cards\n doc.lists = data.lists\n doc.docId = this.generateDocId()\n doc.boardTitle = this.humanize(doc.docId)\n })\n }",
"function createInitialMatches() {\n for (var i = 1; i <= num_idle_matches; i++) {\n var timeout = i * min_timeout;\n var match = new Match(timeout);\n idle_matches[match.id] = match;\n }\n}",
"function createMatchTable(eachMatch) {\n var champName = getChampNamebyID(eachMatch.champion)\n var laneInput = supportFilter(eachMatch.lane)\n var queueType = getQueueType(eachMatch.queue)\n matchRowGenerator(champName , laneInput , queueType , eachMatch.gameId)\n}",
"function initializeWordsearch(dimension){\n var WORDS = [\"home\", \"about\", \"more\", \"contact\"];\n var word_locations = {};\n wordsearch = createWordsearch(dimension);\n for(var i = 0; i < 4; i++){\n wordsearch = addWord(WORDS[i], wordsearch, word_locations);\n }\n //console.log(word_locations[\"home\"]);\n wordsearch = fillBlanks(wordsearch);\n return wordsearch;\n}",
"train(newSource) {\n check(newSource, String);\n\n var text = (this.text || '') + sanitize(newSource);\n var hash = MURMUR_HASH.murmur_2(text);\n var oldModel = this.model;\n log.info('training model, length '+text.length+', hash '+hash);\n\n this.modelDocument = markovModels.findOne({ hash });\n if (!this.modelDocument) {\n this.modelDocument = {\n model: trainMarkovModel(newSource, oldModel),\n text: text,\n hash: hash,\n createdAt: new Date()\n };\n Meteor.defer(() => markovModels.insert(this.modelDocument));\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Abre a tela do caixa | function abreCaixa() {
let mdCx = $("#md-caixa");
mdCx.on("hidden.bs.modal", function () {
onCaixaClosed();
});
caixa();
} | [
"function inviertePalabras(cad) {\r\n \r\n }",
"function PrecoArmaArmaduraEscudo(tipo, tabela, chave, material, obra_prima, bonus, invertido) {\n var entrada_tabela = tabela[chave];\n if (entrada_tabela == null || entrada_tabela.preco == null) {\n return null;\n }\n // Nao pode usar invertido aqui, pq la embaixo inverte tudo.\n var preco = LePreco(entrada_tabela.preco);\n var preco_adicional = { platina: 0, ouro: 0, prata: 0, cobre: 0 };\n if (bonus && bonus > 0) {\n switch (bonus) {\n case 1: preco.ouro += tipo == 'arma' ? 2000 : 1000; break; \n case 2: preco.ouro += tipo == 'arma' ? 8000 : 4000; break; \n case 3: preco.ouro += tipo == 'arma' ? 18000 : 9000; break; \n case 4: preco.ouro += tipo == 'arma' ? 32000 : 16000; break; \n case 5: preco.ouro += tipo == 'arma' ? 50000 : 25000; break; \n default:\n return null;\n }\n }\n if (obra_prima) {\n // Armas op custam 300 a mais, armaduras e escudos, 150.\n preco_adicional.ouro += tipo == 'arma' ? 300 : 150; \n }\n // Modificadores de materiais.\n if (material != 'nenhum') {\n var preco_material = null;\n var tabela_material = tabelas_materiais_especiais[material];\n if (tabela_material.custo_por_tipo) {\n var custo = tabela_material.custo_por_tipo[tipo];\n if (custo.por_subtipo) {\n // TODO\n } else {\n preco_material = LePreco(custo);\n }\n } else if (tabela_material.custo_por_kg) {\n var peso_kg = LePeso(entrada_tabela.peso);\n preco_material = LePreco(tabela_material.custo_por_kg);\n for (var tipo_moeda in preco_material) {\n preco_material[tipo_moeda] *= peso_kg;\n }\n } else if (material == 'couro_dragao') {\n // Preco da armadura mais obra prima.\n preco_material = SomaPrecos(LePreco(entrada_tabela.preco), { ouro: 150 });\n } else if (material == 'ferro_frio') {\n // Preço da arma normal e cada bonus custa 2000 PO a mais.\n preco_material = LePreco(entrada_tabela.preco);\n preco_material['ouro'] += bonus * 2000;\n } else if (material == 'mitral') {\n // Preco tabelado de acordo com tipo da armadura ou escudo (excluidindo custo de obra prima).\n var custo = 0; // escudo ou leve.\n if (tipo == 'escudo') {\n custo = 850;\n } else {\n var talento_relacionado = entrada_tabela.talento_relacionado;\n if (talento_relacionado == 'usar_armaduras_leves') {\n custo = 850;\n } else if (talento_relacionado == 'usar_armaduras_medias') {\n custo = 3850;\n } else if (talento_relacionado == 'usar_armaduras_pesadas') {\n custo = 8850;\n }\n }\n preco_material = { ouro: custo };\n } else if (material == 'prata_alquimica') {\n var categorias = entrada_tabela.categorias;\n var custo = 0;\n if ('cac_leve' in categorias) {\n custo = 20;\n } else if ('cac' in categorias) {\n custo = 90;\n } else if ('cac_duas_maos' in categorias) {\n custo = 180;\n }\n preco_material = { ouro: custo };\n }\n // Adiciona preco do material.\n preco_adicional = SomaPrecos(preco_adicional, preco_material);\n }\n\n // Soma e se necessario, inverte.\n preco = SomaPrecos(preco, preco_adicional);\n if (invertido) {\n for (var tipo_moeda in preco) {\n preco[tipo_moeda] = -preco[tipo_moeda];\n }\n }\n return preco;\n}",
"function vendiCasa(){\n //verifico che il terreno esista e salvo il risultato in proprietà\n var n = EsisteTerreno(props.terreni, terreno);\n if(n === -1){\n setTestoVenditaEdifici('Controlla che il nome del terreno sia scritto in modo corretto');\n setOpenVenditaEdifici(true); \n return;\n }\n var proprietà = props.terreni[n];\n //verifico che il turnoGiocatore sia proprietario di proprietà\n if((proprietà.proprietario !== props.turnoGiocatore)){\n setTestoVenditaEdifici('Non puoi vendere gli edifici se il terreno che non è tuo');\n setOpenVenditaEdifici(true); \n return;\n }\n \n //Se sul terreno non ci sono case non ho nulla da vendere\n if(proprietà.case === 0){\n setTestoVenditaEdifici(\"Su questo terreno non ci sono case\");\n setOpenVenditaEdifici(true); \n return;\n }\n //modifico l'array terreni e l'array giocatori\n proprietà.case = proprietà.case - 1;\n var nuoviTerreni = props.terreni;\n nuoviTerreni[n] = proprietà;\n props.setTerreni(nuoviTerreni);\n\n var nuoviGiocatori = props.giocatori;\n var guadagno = proprietà.valore*3/8;\n nuoviGiocatori[props.turnoGiocatore].capitale = nuoviGiocatori[props.turnoGiocatore].capitale + guadagno;\n props.setGiocatori(nuoviGiocatori);\n\n var banca = Banca.getInstance();\n banca.incrementaCase();\n\n setTestoVenditaEdifici('La vendita della casa è andata a buon fine');\n setOpenVenditaEdifici(true); \n }",
"function etapaBuscaBanco(){\n //...\n }",
"function impostaAttoAmministrativoDaCausale(attoAmministrativo) {\n var anno;\n var numero;\n var tipoAtto;\n var sac;\n var datiAttoAmministrativo;\n\n // Se ho l'atto, popolo i campi correttamente\n if(attoAmministrativo) {\n anno = attoAmministrativo.anno;\n numero = attoAmministrativo.numero;\n if(attoAmministrativo.tipoAtto) {\n tipoAtto = attoAmministrativo.tipoAtto.uid;\n }\n if(attoAmministrativo.strutturaAmmContabile) {\n sac = attoAmministrativo.strutturaAmmContabile.uid;\n }\n }\n\n $('#annoAttoAmministrativo').val(anno);\n $('#numeroAttoAmministrativo').val(numero);\n $('#tipoAtto').val(tipoAtto);\n $('#HIDDEN_StrutturaAmministrativoContabileAttoAmministrativoUid').val(sac);\n Ztree.selezionaNodoSeApplicabile('treeStruttAmmAttoAmministrativo', sac);\n $('#datiRiferimentoProvvedimentoSpan').html(datiAttoAmministrativo);\n }",
"function ClickBotaoAtributoMais(chave_atributo) {\n gEntradas.bonus_atributos.push(chave_atributo);\n AtualizaGeralSemLerEntradas();\n}",
"function alianzaMercado(){\n\t\tvar a = find(\"//tr[@class='rbg']\", XPFirst).parentNode;\n\n\t\t// Prepara la insercion de la nueva columna\n\t\tvar b = a.getElementsByTagName(\"TR\");\n\t\t// FIXME: Apaño para Firefox. FF mete nodos de tipo texto vacios\n\t\tb[0].childNodes[b[0].childNodes.length == 3 ? 1 : 0].setAttribute('colspan', '8');\n\t\tb[b.length - 1].childNodes[0].setAttribute(\"colspan\", \"8\");\n\n\t\t// Crea e inserta la columna\n\t\tvar columna = document.createElement(\"TD\");\n\t\tcolumna.innerHTML = T('ALIANZA');\n\t\tb[1].appendChild(columna);\n\n\t\t// Rellena la columna con los nombres de las alianzas\n\t\tfor(var i = 2; i < b.length - 1; i++){\n\t\t\tvar alianza = document.createElement(\"TD\");\n\t\t\t// FIXME: Apaño para Firefox. FF mete nodos de tipo texto vacios\n\t\t\tvar alianza_txt = b[i].childNodes[b[i].childNodes.length == 12 ? 8 : 4].getAttribute('title');\n\t\t\tif (alianza_txt != null) alianza.innerHTML = alianza_txt;\n\t\t\tb[i].appendChild(alianza);\n\t\t}\n\t}",
"function abrirBlancosCercanos(fila, columna, numeroFilas, numeroColumnas) {\n /*\n Se recorren en un ciclo for las 8 adyacencias (arriba, izq, der, etc etc)\n Por cada adyacencia: \n 1. Si es numero, marca destapado.\n 2. Si es un blanco y no esta destapado, marca destapado y llama a esta misma funcion\n */\n \n // Declarando variables para adyacencias\n var arribaIzq = null, arriba = null, arribaDer = null, izquierda = null;\n var abajoIzq = null, abajo = null, abajoDer = null, derecha = null;\n // Asignando Variables\n if (fila > 0 && columna > 0) {\n arribaIzq = filas[fila - 1][columna - 1];\n }\n if (columna > 0) {\n izquierda = filas[fila][columna - 1]\n if (fila < numeroFilas - 1) {\n abajoIzq = filas[fila + 1][columna - 1]\n }\n }\n if (fila > 0) {\n arriba = filas[fila - 1][columna]\n if (columna < numeroColumnas - 1) {\n arribaDer = filas[fila - 1][columna + 1]\n }\n }\n if (columna < numeroColumnas - 1) {\n derecha = filas[fila][columna + 1]\n }\n if (fila < numeroFilas - 1) {\n abajo = filas[fila + 1][columna]\n }\n if ((fila < numeroFilas - 1) && (columna < numeroColumnas - 1)) {\n abajoDer = filas[fila + 1][columna + 1]\n }\n // Verificando adyacencias\n if (arribaIzq != null) {\n if (arribaIzq.contenido == 'numero') {\n arribaIzq.estado = 'descubierto'\n }\n if (arribaIzq.contenido == 'blanco' && arribaIzq.estado != 'descubierto') {\n arribaIzq.estado = \"descubierto\";\n abrirBlancosCercanos(fila - 1, columna - 1, numeroFilas, numeroColumnas)\n }\n }\n if (arriba != null) {\n if (arriba.contenido == 'numero') {\n arriba.estado = 'descubierto'\n }\n if (arriba.contenido == 'blanco' && arriba.estado != 'descubierto') {\n arriba.estado = \"descubierto\";\n abrirBlancosCercanos(fila - 1, columna, numeroFilas, numeroColumnas)\n }\n }\n if (arribaDer != null) {\n if (arribaDer.contenido == 'numero') {\n arribaDer.estado = 'descubierto'\n }\n if (arribaDer.contenido == 'blanco' && arribaDer.estado != 'descubierto') {\n arribaDer.estado = \"descubierto\";\n abrirBlancosCercanos(fila - 1, columna + 1, numeroFilas, numeroColumnas)\n }\n }\n if (derecha != null) {\n if (derecha.contenido == 'numero') {\n derecha.estado = 'descubierto'\n }\n if (derecha.contenido == 'blanco' && derecha.estado != 'descubierto') {\n derecha.estado = \"descubierto\";\n abrirBlancosCercanos(fila, columna + 1, numeroFilas, numeroColumnas)\n }\n }\n if (abajoDer != null) {\n if (abajoDer.contenido == 'numero') {\n abajoDer.estado = 'descubierto'\n }\n if (abajoDer.contenido == 'blanco' && abajoDer.estado != 'descubierto') {\n abajoDer.estado = \"descubierto\";\n abrirBlancosCercanos(fila + 1, columna + 1, numeroFilas, numeroColumnas)\n }\n }\n if (abajo != null) {\n if (abajo.contenido == 'numero') {\n abajo.estado = 'descubierto'\n }\n if (abajo.contenido == 'blanco' && abajo.estado != 'descubierto') {\n abajo.estado = \"descubierto\";\n abrirBlancosCercanos(fila + 1, columna, numeroFilas, numeroColumnas)\n }\n }\n if (abajoIzq != null) {\n if (abajoIzq.contenido == 'numero') {\n abajoIzq.estado = 'descubierto'\n }\n if (abajoIzq.contenido == 'blanco' && abajoIzq.estado != 'descubierto') {\n abajoIzq.estado = \"descubierto\";\n abrirBlancosCercanos(fila + 1, columna - 1, numeroFilas, numeroColumnas)\n }\n }\n if (izquierda != null) {\n if (izquierda.contenido == 'numero') {\n izquierda.estado = 'descubierto'\n }\n if (izquierda.contenido == 'blanco' && izquierda.estado != 'descubierto') {\n izquierda.estado = \"descubierto\";\n abrirBlancosCercanos(fila, columna - 1, numeroFilas, numeroColumnas)\n }\n }\n}",
"descifrado(cadena, clave) {\n let claves = new Cerrajero().generarClaves(clave);\n for (let i = claves.length - 1; i >= 0; i--) {\n cadena = this.aplicarLlave(cadena, claves[i]);\n }\n return cadena;\n\n\n }",
"puedeSubir(){ \n if (this._jump && !this._martillo){//si no has saltado y no llevas un martillo\n this._sube=true; \n this._corriendo = false;\n }\n }",
"function atualizaForca(alfabeto) {\r\n const area = document.querySelector(\"#palavra\");\r\n area.innerHTML = \"\";\r\n let text = document.createTextNode(alfabeto);\r\n area.appendChild(text);\r\n}",
"function alianzaMercado(){\r\n\t\tvar a = find(\"//tr[@class='rbg']\", XPFirst).parentNode;\r\n\r\n\t\t// Prepara la insercion de la nueva columna\r\n\t\tvar b = a.getElementsByTagName(\"TR\");\r\n\t\t// FIXME: Apaño para Firefox. FF mete nodos de tipo texto vacios\r\n\t\tb[0].childNodes[b[0].childNodes.length == 3 ? 1 : 0].setAttribute('colspan', '8');\r\n\t\tb[b.length - 1].childNodes[0].setAttribute(\"colspan\", \"8\");\r\n\r\n\t\t// Crea e inserta la columna\r\n\t\tvar columna = document.createElement(\"TD\");\r\n\t\tcolumna.innerHTML = T('ALIANZA');\r\n\t\tb[1].appendChild(columna);\r\n\r\n\t\t// Rellena la columna con los nombres de las alianzas\r\n\t\tfor(var i = 2; i < b.length - 1; i++){\r\n\t\t\tvar alianza = document.createElement(\"TD\");\r\n\t\t\t// FIXME: Apaño para Firefox. FF mete nodos de tipo texto vacios\r\n\t\t\tvar alianza_txt = b[i].childNodes[b[i].childNodes.length == 12 ? 8 : 4].getAttribute('title');\r\n\t\t\tif (alianza_txt != null) alianza.innerHTML = alianza_txt;\r\n\t\t\tb[i].appendChild(alianza);\r\n\t\t}\r\n\t}",
"function impostaCapitoloDaCausale(capitolo) {\n var numeroCapitolo = '';\n var numeroArticolo = '';\n var numeroUEB = '';\n var datiCapitolo = '';\n // Se ho il capitolo, popolo i campi correttamente\n if(capitolo) {\n numeroCapitolo = capitolo.numeroCapitolo;\n numeroArticolo = capitolo.numeroArticolo;\n numeroUEB = capitolo.numeroUEB;\n }\n\n // Imposto i valori\n $('#numeroCapitolo').val(numeroCapitolo);\n $('#numeroArticolo').val(numeroArticolo);\n $('#numeroUEB').val(numeroUEB);\n $('#datiRiferimentoCapitoloSpan').html(datiCapitolo);\n }",
"function jeu_attaquerCible(me,cc,nocible,cible,cattaquante){\n\t\tif (cible!=null && cible!==\"undefined\"){\n\t\t\tmy_logger((me?PROMPT_ME:PROMPT_IA)+\"attaque cible carte \"+cible.nom);\n\t\t\n\t\t\tcible.DEF = cible.DEF-cattaquante.ATT;\n\t\t my_logger((me?PROMPT_ME:PROMPT_IA)+\" idCible = \"+cible.id+\"/\"+cible.nom);\n\t\t\n\t\t\t//SI def<0 => cimetiere\n\t\t\tif (cible.DEF<=0){\n\t\t\t\tmy_logger((me?PROMPT_ME:PROMPT_IA)+\" cible=\"+cible.nom+\" détruite, sovdef=\"+cible.sauvdef);\n\t\t\t\t//Placer la carte au cimetière\n\t\t\t\t//cible.etat= ETAT_CIM;\n\t\t\t\tcible.def=cible.sauvdef;\n\t\t\t\tposerCarteDansCimetiere(cible);\n\t\t\t\t\n\t\t\t\t//suppimer cicble du tableau\n\t\t\t\tif (cc){\n\t\t\t\t\tsupprimerCarteFromJeu(me,nocible);\n\t\t\t\t}else{\t\t\t\t\t\n\t\t\t\t\tsupprimerCarteFromAtt(me,nocible);\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\t// cibler l'ID des points de DEF\n\t\t\t\tseldef=\"#\"+cible.id+ \" #def\";\n\t\t\t\t$(seldef).html(cible.DEF);\n\t\t\t}\n\t\t} \n\t }",
"noDecidido(){ this._baja = -1; }",
"function ControlloAbbonamentoCena() {\r\n var i;\r\n\t\t\tvar AbbonamentoCena = document.getElementById(\"AbbonamentoCena\");\r\n\t\t\tvar Iscrizione = document.getElementById(\"Iscrizione\");\r\n\t\t\tif (!Iscrizione.checked && AbbonamentoCena.checked) {\r\n\t\t\t\talert(\"Non è possibile registrare l'abbonamento alle cene senza l'iscrizione, almeno come ospite\");\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n // chiedo conferma per la cancellazione dell'abbonamento\r\n if (!AbbonamentoCena.checked) {\r\n\t\t\t\t//if (!confirm(\"Attenzione! Sei sicuro di voler togliere all'iscritto l'abbonamento cene?\")) {\r\n\t\t\t\t\t//AbbonamentoCena.checked = true;\r\n\t\t\t\t//}\r\n\t\t\t} else {\r\n\t\t\t\t//if (confirm(\"Attenzione! Impostando l'abbonamento cene verranno annullati tutti le cene singole\\nVuoi proseguire?\")) {\r\n\t\t\t\t\t// annullo le cene singole se è impostato l'abbonamento\r\n\t\t\t\t\tvar Cene = document.getElementsByName(\"Cena[]\");\r\n\t\t var CeneGratis = document.getElementsByName(\"GratisCena[]\");\r\n\t\t\t\t\tfor (i=0; i < Cene.length; i++) {\r\n\t\t\t\t\t\tCene[i].checked = false;\r\n\t\t\t\t\t\tCeneGratis[i].checked = false;\r\n\t\t\t\t\t}\r\n\t\t\t\t//} else {\r\n\t\t\t\t//\tAbbonamentoCena.checked = false;\r\n\t\t\t\t//}\r\n\t\t\t}\r\n\t\t\tdocument.getElementById(\"CostoTotaleEuroCalcolato\").value = CalcolaCostoTotale().toFixed(2).replace(\".\", \",\");\r\n\t\t\treturn; \r\n } // fine funzione controllo abbonamento cena",
"function suprimeCasesCliquable(){\n\tfor(var a=0; a<9; a++){\n\t\tfor(var c=0; c<9; c++){\n\t\t\tif (plateau.children[a].children[c].classList.contains(\"caseCliquable\")) {\n\t\t\t\tplateau.children[a].children[c].classList.remove(\"caseCliquable\");\t// on supprime les cases de deplacement possible à notre joueur 1\n\t\t\t}\n\t\t}\n\t}\n}",
"function gerarBoleto(fatura) {\n \n }",
"_alteraCena(){\n if(this.text === 'reset' || this.text === 'Iniciar'){\n this.botao.remove();\n cenaAtual = 'jogo';\n totalLifes = 5;\n loop();\n }else{\n cenaAtual = 'telaInicial';\n } \n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
handles a folder expand | function toggleFolderExpand(folder) {
folder.expanded = !folder.expanded;
toggleExpand(folder.children, folder.expanded);
} | [
"expand() {\n /**\n * Only if it is a root folder meaning having children\n * we need to set the path and update the current\n * root of state.\n */\n if (this.props.root.class === \"root\") {\n this.props.setPath(calculatePath(this.props.root));\n this.props.setRoot(this.props.root);\n }\n }",
"function expandFolder(folder) {\n\tmap(folder, function(folder) {\n\t\tgraph.foldCells(false, false, [folder]);\n\t});\n}",
"function expandAllDirectories() {\n collapsedDirectoryPaths.clear();\n refreshExpandedState();\n}",
"function expand_path() {\n //TO DO \t\n}",
"function onExpandCollapse($node, node) {\n\t\tvar expanded = node.expanded(),\n\t\t\t\tempty = !hasOwnProperties(node.json()),\n\t\t\t\t$spinner;\n\t\n\t\t// acquiring sub-nodes when expanding an empty node\n\t\tif (expanded && empty) {\n\t\t\t$spinner = $node\n\t\t\t\t.closest('.w_popup')\n\t\t\t\t\t.find('.spinner')\n\t\t\t\t\t\t.show();\n\t\t\tservices.sys.dirlist(node.path().join('/'), function (json) {\n\t\t\t\t$spinner.hide();\n\t\t\t\tempty = !hasOwnProperties(json.data);\n\t\t\t\tif (empty) {\n\t\t\t\t\t// no subdirs, removing expand button\n\t\t\t\t\t$node\n\t\t\t\t\t\t.removeClass('expanded')\n\t\t\t\t\t\t.addClass('dead');\n\t\t\t\t} else {\n\t\t\t\t\t// has subdirs, creating child nodes\n\t\t\t\t\tnode\n\t\t\t\t\t\t.json(json.data)\n\t\t\t\t\t\t.build()\n\t\t\t\t\t\t.render();\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}",
"function treeExpandFirstLevel(tree) {\n if ($('#node-groups-tree li.folder').length == 1) {\n var itemId = $('#node-groups-tree li.folder').attr('id');\n tree.open_node(itemId);\n }\n}",
"function toggleSubtree($expander, show) {\n var $subtree = $expander.siblings('.folder-subtree'),\n $subtreeLinks = $subtree.find('.action-links-wrapper'),\n $description = $expander.parent().find('.s-js-folder-description'),\n $title = $expander.parent().find('.folder-title'),\n show = show || false,\n folderId = $expander.closest('.material-row-folder').attr('id').split('-')[1];\n\n var easing = 'easeInQuad',\n duration = 300;\n\n function toggleVisibility(show_subtree) {\n if (show_subtree) {\n descFunc = 'slideUp';\n subtreeFunc = 'slideDown';\n } else {\n descFunc = 'slideDown';\n subtreeFunc = 'slideUp';\n }\n $description[descFunc]({\n duration: duration,\n easing: easing\n });\n // hidding the action links wrapper since they are positioned absolutely and will appear in an unsightly manner\n // during the course of the animation\n $subtreeLinks.hide();\n $subtree[subtreeFunc]({\n duration: duration,\n easing: easing,\n done: function() {\n $subtreeLinks.show();\n }\n });\n }\n\n if (show) {\n $expander.find('.visually-hidden').text(Drupal.t('Collapse folder.'));\n // If subtree was already loaded, show it\n if ($subtree.length) {\n toggleVisibility(true);\n }\n // Load the subtree\n else {\n $loader = $('<img class=\"pending\" src=\"/sites/all/themes/schoology_theme/images/ajax-loader.gif\" alt=\"' + Drupal.t('Loading') + '\" />');\n $subtree = $('<div class=\"folder-subtree\"></div>');\n $expander.parent().append($subtree);\n\n $title.after($loader);\n\n $.ajax({\n dataType: 'json',\n url: window.location.pathname,\n data: {\n ajax: 1,\n f: folderId\n },\n success: function(contents) {\n contents = $(contents);\n\n // Do a little bit of cleanup\n // Since the helper function we use creates a form,\n // remove the form wrapper and other form artifacts\n $('form>div', contents).unwrap();\n $('[name=form_build_id], [name=form_token], [name=form_id]', contents).remove();\n $loader.remove();\n $subtree.hide().html(contents);\n toggleVisibility(true);\n Drupal.attachBehaviors($subtree);\n $('tr td.actions', $subtree).sActionLinks({\n hidden: false,\n wrapper: '.action-links-wrapper'\n });\n\n var foldersActionPush = $(document).data('sCourseMaterialsFoldersActionPush');\n if (foldersActionPush && foldersActionPush.length) {\n var fid = foldersActionPush.pop();\n var $expander = $('#f-' + fid + ' > td.folder-contents-cell > .folder-expander');\n if (!$expander.hasClass('expanded')) {\n $expander.click();\n }\n $(document).data('sCourseMaterialsFoldersActionPush', foldersActionPush);\n } else {\n refreshSortableContent($subtree);\n }\n },\n error: function() {\n $subtree.html('<div class=\"error\">' + Drupal.t('There was an error while loading the folder content. Please reload this page and try again.') + '</div>');\n refreshSortableContent($subtree);\n }\n });\n }\n } else {\n $expander.find('.visually-hidden').text(Drupal.t('Expand folder.'));\n toggleVisibility(false);\n }\n }",
"function openFolder(e) {\n e.target.classList.remove('folder-closed');\n e.target.classList.add('folder-open');\n }",
"function open_containing_folder( path, k, err ) {\n var pathclone = $.map( path, function(x) { return x; } );\n _is_leaf( path,\n function() {\n pathclone.pop();\n open_path( pathclone, true, function( spec ) { k( spec, pathclone ); }, err );\n },\n function(spec) {\n k(spec, pathclone);\n },\n err);\n }",
"function test_select_folder_expands_collapsed_account_root() {\n // Collapse the account root\n collapse_folder(rootFolder);\n assert_folder_collapsed(rootFolder);\n\n // Also collapse the smart inbox, make sure selectFolder don't expand it\n collapse_folder(smartInboxFolder);\n assert_folder_collapsed(smartInboxFolder);\n\n // Now attempt to select the folder\n mc.folderTreeView.selectFolder(inboxSubfolder);\n\n assert_folder_collapsed(smartInboxFolder);\n assert_folder_expanded(rootFolder);\n assert_folder_selected_and_displayed(inboxSubfolder);\n}",
"function expandAll (bnId, row) {\n let level = parseInt(row.dataset.level, 10);\n\n // Open and unhide all children\n // If we're opening the most visited or recent bookmarks special folders, call for a refresh\n if (bnId == mostVisitedBNId) {\n\tsendAddonMessage(\"refreshMostVisited\");\n }\n else if (bnId == recentBkmkBNId) {\n\tsendAddonMessage(\"refreshRecentBkmks\");\n } \n\n // Open twistie\n let twistie = row.firstElementChild.firstElementChild.firstElementChild;\n twistie.classList.replace(\"twistieac\", \"twistieao\");\n curFldrOpenList[bnId] = true;\n\n let cur_level, prev_level;\n let prev_row;\n prev_level = level + 1;\n while ((row = (prev_row = row).nextElementSibling) != null) {\n\tif ((cur_level = parseInt(row.dataset.level, 10)) <= level)\n\t break; // Stop when lower or same level\n\tif (cur_level > prev_level) { // We just crossed a folder in previous row ..\n\t // Check if it was open or not\n\t twistie = prev_row.firstElementChild.firstElementChild.firstElementChild;\n\t if (twistie.classList.replace(\"twistieac\", \"twistieao\")) { // We just opened the sub-folder\n\t\tbnId = prev_row.dataset.id;\n\t\tcurFldrOpenList[bnId] = true;\n\n\t\t// If we're opening the most visited or recent bookmarks special folders, call for a refresh\n\t\tif (bnId == mostVisitedBNId) {\n\t\t sendAddonMessage(\"refreshMostVisited\");\n\t\t}\n\t\telse if (bnId == recentBkmkBNId) {\n\t\t sendAddonMessage(\"refreshRecentBkmks\");\n\t\t} \n\t }\n\t}\n\tprev_level = cur_level;\n\trow.hidden = false;\n }\n saveFldrOpen();\n}",
"function browseForFolder()\n\t{\n\tvar newDirectory = dreamweaver.browseForFolderURL(MSG_PickFolder, findObject(\"destinationFolder\").value, true);\n\tif (newDirectory.length > 0 && newDirectory.charAt(newDirectory.length-1) != '/')\n\t\tnewDirectory += '/';\n\tif (newDirectory != null && newDirectory != \"\") \n\t\tfindObject(\"destinationFolder\").value = newDirectory; \n\t} //browseForFolder",
"function toggle(node, a) {\r\n var isopen = localStorage.getItem('open.' + node.id);\r\n setClass(a, node, !isopen);\r\n a.open = !isopen;\r\n if (isopen) {\r\n // close folder\r\n localStorage.removeItem('open.' + node.id);\r\n if (a.nextSibling){\r\n // auto-close child folders\r\n if (getConfig('auto_close')) {\r\n var children = (a.nextSibling.tagName == 'DIV' ? a.nextSibling.firstChild : a.nextSibling).children;\r\n for (var i=0; i<children.length; i++) {\r\n var child = children[i].firstChild;\r\n if (child.open)\r\n child.onclick();\r\n }\r\n }\r\n // close folder\r\n animate(node, a, isopen);\r\n }\r\n } else {\r\n // open folder\r\n localStorage.setItem('open.' + node.id, true);\r\n // auto-close sibling folders\r\n if (getConfig('auto_close')) {\r\n var siblings = a.parentNode.parentNode.children;\r\n for (var i=0; i<siblings.length; i++) {\r\n var sibling = siblings[i].firstChild;\r\n if (sibling != a && sibling.open)\r\n sibling.onclick();\r\n }\r\n }\r\n // open folder\r\n if (a.nextSibling)\r\n animate(node, a, isopen);\r\n else\r\n getChildrenFunction(node)(function(result) {\r\n if (!a.nextSibling && localStorage.getItem('open.' + node.id)) {\r\n renderAll(result, a.parentNode);\r\n animate(node, a, isopen);\r\n }\r\n });\r\n }\r\n}",
"function folderSelected(elem,event){\n\tvar folderName = elem.children[0].innerHTML;\n\t\n\tif (event!== null){\n\t\tevent.stopPropagation();\n\t}\n\tvar divs = document.getElementById(\"folderStructure\").children;\n\tremoveFolderIds(divs, depthOfFoldersUnderRoot);\n\telem.id = \"selectedFolder\";\n\tdocument.getElementById(\"folderName\").innerHTML = elem.children[0].innerHTML;\n\t\n\trefreshCurrentFolderPath();\n\trefreshHiddenInputFieldsFolders();\n\t\n\t//make file buttons unavailable\n\tdeactivateButton(\"icon_download\");\n\tdeactivateButton(\"icon_delete_file\");\n\t\n\t//load files of selected folder\n\tloadFiles();\n}",
"function test_select_folder_expands_collapsed_smart_inbox() {\n // Collapse the smart inbox\n collapse_folder(smartInboxFolder);\n assert_folder_collapsed(smartInboxFolder);\n\n // Also collapse the account root, make sure selectFolder don't expand it\n collapse_folder(rootFolder);\n assert_folder_collapsed(rootFolder);\n\n // Now attempt to select the folder\n mc.folderTreeView.selectFolder(inboxFolder);\n\n assert_folder_collapsed(rootFolder);\n assert_folder_expanded(smartInboxFolder);\n assert_folder_selected_and_displayed(inboxFolder);\n}",
"function expandDirectoryTreeFor(windowId, path) {\n return expandDirectoryTreeForInternal_(windowId, path.split('/'), 0);\n}",
"static openFolder() {\n\t\t$('.table-title a').mousedown(function() {\n\t\t\tlet link = $(this);\n\t\t\tlink.mouseup(function(e) {\n\t\t\t\tif (e.which === 1) link.parents('.table-title').siblings('.fa-folder').removeClass('fa-folder').addClass('fa-folder-open');\n\t\t\t});\n\t\t});\n\t}",
"function folder (args, mus, done) {\n var folder = mus.search.getFolderByNum(args[0])\n var fullPath = escapeFile(path.join(mus.config.root, folder.path))\n console.log('FOLDER', fullPath)\n\n exec('open ' + fullPath, function () {\n console.log('FOLDER', folder.title)\n done('exit')\n })\n}",
"expand() {\n const args = {\n owner: this.tree,\n node: this,\n cancel: false\n };\n this.tree.nodeExpanding.emit(args);\n if (!args.cancel) {\n this.treeService.expand(this, true);\n this.cdr.detectChanges();\n this.playOpenAnimation(this.childrenContainer);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a promise which resolves to object storing package owner changed status for each dependency. | async function getOwnerPerDependency(fromVersion, toVersion, options) {
const packageManager = (0, getPackageManager_1.default)(options, options.packageManager);
return await Object.keys(toVersion).reduce(async (accum, dep) => {
const from = fromVersion[dep] || null;
const to = toVersion[dep] || null;
const ownerChanged = await packageManager.packageAuthorChanged(dep, from, to, options);
return {
...(await accum),
[dep]: ownerChanged,
};
}, {});
} | [
"function pendingDependencies() {\n\t\tvar pending = {};\n\t\tvar key;\n\t\tvar list;\n\t\tvar i;\n\t\tvar id;\n\n\t\tfor (key in __updateOnDefine) {\n\t\t\tlist = __updateOnDefine[key];\n\n\t\t\tfor (i = 0; i < list.length; i += 2) {\n\t\t\t\tid = list[i];\n\t\t\t\t(pending[id] || (pending[id] = [])).push(key);\n\t\t\t}\n\t\t}\n\n\t\treturn pending;\n\t}",
"_resolveDependencies() {\n logger.info('Resolving dependencies...');\n\n let packageInfos = this._getPackageInfos();\n packageInfos.forEach((pkgInfo) => {\n if (!pkgInfo.processed) {\n let pkgs = pkgInfo.addDependencies(pkgInfo.pkg.dependencies);\n if (pkgs) {\n pkgInfo.dependencyPackages = pkgs;\n }\n\n // for Projects only, we also add the devDependencies\n if (pkgInfo.project) {\n pkgs = pkgInfo.addDependencies(pkgInfo.pkg.devDependencies);\n if (pkgs) {\n pkgInfo.devDependencyPackages = pkgs;\n }\n }\n\n pkgInfo.processed = true;\n }\n });\n }",
"function findChangesSync() {\n let changeFiles = [];\n let allChanges = {};\n let changesPath = path.join(process.cwd(), 'changes');\n\n console.log(`Finding changes in: ${changesPath}`);\n\n try {\n changeFiles = fs.readdirSync(changesPath).filter(filename => filename.indexOf('.json') >= 0);\n } catch (e) { }\n\n // Add the minimum changes defined by the change descriptions.\n changeFiles.forEach((file) => {\n let fullPath = path.resolve('./changes', file);\n let changeDescription = JSON.parse(fs.readFileSync(fullPath, 'utf8'));\n\n for (let i = 0; i < changeDescription.changes.length; i++) {\n let change = changeDescription.changes[i];\n\n addChange(allChanges, change);\n }\n });\n\n let packages = Object.keys(allChanges);\n let updatedDeps = {};\n\n // Update orders so that downstreams are marked to come after upstreams.\n for (let packageName in allChanges) {\n let change = allChanges[packageName];\n let pkg = _allPackages[packageName].package;\n let deps = _downstreamDeps[packageName];\n\n // Write the new version expected for the change.\n change.newVersion = (change.changeType > _changeTypes.dependency) ? semver.inc(pkg.version, _changeTypes[change.changeType]) : pkg.version;\n\n if (deps) {\n for (let depName of deps) {\n let depChange = allChanges[depName];\n\n if (depChange) {\n depChange.order = Math.max(change.order + 1, depChange.order);\n }\n }\n }\n }\n\n return allChanges;\n}",
"function getDependenciesInfo() {\n return new Promise(function (resolve, reject) {\n bower.commands.list()\n .on('end', function (results) {\n var dependencies = cint.mapObject(results.dependencies, function (key, value) {\n return cint.keyValue(key, value.pkgMeta);\n });\n resolve(results.dependencies);\n })\n .on('error', function(e) {\n console.error('Bower list error...', e);\n reject();\n });\n });\n}",
"function fetchDependencyStatus (d) {\n const handler = ['policy', 'dependency', d['metadata']['namespace'], d['metadata']['name'], 'status'].join('/')\n callAPI(handler, sync, function (data) {\n d['status'] = data['data']\n }, function (err) {\n // can't fetch dependency properties\n d['status_error'] = 'unable to fetch dependency status: ' + err\n })\n}",
"function getUpdateToolVersionsPromise(){\n\t\tvar defer = q.defer();\n\t\t\n\t\t// If the tool mapping contants versions we need to update too\n\t\tif(toolVersions){\n\t\t\tvar mergeData = {\"toolsLocal\" : {}, \"tools\" : {}};\n\t\t\tvar keys = Object.keys(toolVersions);\n\t\t\t\n\t\t\t/*\n\t\t\t * We now create records that look like this\n\t\t\t * {\n\t\t\t * \"toolsLocal\" {\n\t\t\t * \"toolname\" : {\n\t\t\t * \"clientContentVersion\" : xxxxxxxxxxxxxxxxx\n\t\t\t * },\n\t\t\t * \"toolname\" : {\n\t\t\t * \"clientContentVersion\" : xxxxxxxxxxxxxxxxx\n\t\t\t * }\n\t\t\t * }\n\t\t\t * }\n\t\t\t */\n\t\t\tfor(var idx = 0 ; idx < keys.length ; idx++){\n\t\t\t\tmergeData.toolsLocal[keys[idx]] = {\n\t\t\t\t\t\"clientContentVersion\" : toolVersions[keys[idx]]\n\t\t\t\t};\n\t\t\t\tmergeData.tools[keys[idx]] = {\n\t\t\t\t\t\"clientContentVersion\" : toolVersions[keys[idx]]\n\t\t\t\t};\n\t\t\t}\n\t\t\t// Update the file\n\t\t\tdat.mergeObjectToToolData(mergeData, \"client.base\", function(){\n\t\t\t\tdefer.resolve([]);\n\t\t\t});\n\t\t}\n\t\t// if there is not versions we are done\n\t\telse{\n\t\t\tdefer.resolve([]);\n\t\t}\n\t\treturn defer.promise;\n\t}",
"sync() {\n new Promise((resolve, reject) => {\n if (this._stateManager.syncLock)\n return resolve()\n\n this._stateManager.syncLock = true\n\n getSyncChanges()\n .then(changes => {\n return new Promise((resolve, reject) => {\n\n if (changes.length)\n console.log('Changes: ', changes)\n\n asyncjs.eachSeries(changes, (change, next) => {\n let func;\n\n switch (change.status) {\n case SyncStatus.FirstTimeConnect:\n func = () => this.backup();\n break\n\n case SyncStatus.AddPackagesFromClient:\n case SyncStatus.RemovePackagesFromClient:\n case SyncStatus.SettingsChangedFromClient:\n func = () => this.backup();\n break\n\n case SyncStatus.AddPackagesFromServer:\n func = () => this.handlePackageAdd(change.packages)\n break\n\n case SyncStatus.RemovePackagesFromServer:\n func = () => this.handlePackageRemove(change.packages)\n break\n\n case SyncStatus.PackageSettingsChangedFromServer:\n func = () => this.applySettingsFiles(change.settingsFiles)\n break\n\n case SyncStatus.NewAtomInstance:\n func = () => {\n return this.handlePackageAdd(change.packages)\n .then(() => this.applySettingsFiles(change.settingsFiles))\n .then(() => this.backup())\n }\n break\n\n\n }\n\n\n\n if (func) {\n func()\n .then(() => {\n next()\n })\n .catch(err => {\n throw err\n })\n }\n\n },\n err => {\n if (err)\n return reject(err)\n else\n resolve(changes.length)\n })\n })\n })\n .then(nbOfChanges => {\n if (nbOfChanges > 0)\n atom.notifications.addSuccess(SYNC_SUCCESS_MESSAGE)\n\n this.setupAutoUpdateCheck()\n })\n .then(() => {\n this._stateManager.syncLock = false\n resolve()\n })\n .catch(err => {\n // TODO handle error\n console.log('Error Unlock sync')\n this._stateManager.syncLock = false\n })\n })\n }",
"updateDependencies (options) {\n const current = this.getConfig('dependencies');\n const packageNames = Object.keys(current);\n\n this._findPackageVersions(packageNames, options.releasesOnly).then((fetched) => {\n const updated = Object.assign(\n {},\n ...packageNames.filter((packageName) => {\n const fetchedVersion = fetched[packageName];\n const currentVersion = current[packageName];\n const isUpdated = fetchedVersion && fetchedVersion !== currentVersion;\n\n return isUpdated;\n }).map((packageName) => {\n return {[packageName]: fetched[packageName]};\n })\n );\n\n if (!Object.keys(updated).length) {\n log('no updates found');\n return;\n }\n\n if (options.dryRun) {\n log('would update the following dependencies in package.json:');\n } else {\n log('updating package.json with new cljs versions:');\n }\n\n log(asTable(Object.keys(updated).map((packageName) => {\n return [\n '',\n packageName,\n current[packageName],\n '=>',\n fetched[packageName]\n ];\n })));\n\n if (!options.dryRun) {\n this._updatePackageJson(\n ['cljsbuild', 'dependencies'],\n Object.assign({}, current, updated)\n );\n log('done');\n }\n }).catch(logErrorAndExit);\n }",
"get dependencies() {\n let deps = [];\n\n this.packages.forEach(pkg => {\n deps.push(...Object.keys(pkg.allDependencies));\n });\n\n // Deduplicate dependencies\n return [...new Set(deps)];\n }",
"resolve () {\n let {registry, sunstone} = this\n let {dependencies} = sunstone\n let errors = []\n\n // TODO check dependencies is an object. if not, create an error condition?\n debug('resolving dependencies for \"%s\"', this.name)\n\n Object.keys(dependencies).forEach(name => {\n let range = dependencies[name]\n let dependency = registry.get(name)\n\n if (!dependency) {\n return errors.push({\n message: `${this.name} ${this.version} requires ${name} ${range} and it appears to be unavailable.`\n })\n }\n\n if (!semver.satisfies(this.version, range)) {\n return errors.push({\n message: `${this.name} ${this.version} requires ${name} ${range} and version ${dependency.version} is installed.${JSON.stringify(dependency)}`\n })\n }\n\n this.dependencies.push(dependency)\n dependency.dependents.push(this)\n })\n\n if (errors.length > 0) {\n return Promise.reject(errors)\n }\n\n return Promise.resolve(this)\n }",
"getPackageDependencies() {\n var dependencies, dependencyPath, error, filteredPackages, metadata, packageDependencies, packageDependencyPath, packageName, packageSpec, ref;\n try {\n metadata = fs.readFileSync('package.json', 'utf8');\n ({packageDependencies, dependencies} = (ref = JSON.parse(metadata)) != null ? ref : {});\n if (!packageDependencies) {\n return {};\n }\n if (!dependencies) {\n return packageDependencies;\n }\n // This code filters out any `packageDependencies` that have an equivalent\n // normalized repo-local package path entry in the `dependencies` section of\n // `package.json`. Versioned `packageDependencies` are always returned.\n filteredPackages = {};\n for (packageName in packageDependencies) {\n packageSpec = packageDependencies[packageName];\n dependencyPath = this.getRepoLocalPackagePath(dependencies[packageName]);\n packageDependencyPath = this.getRepoLocalPackagePath(packageSpec);\n if (!(packageDependencyPath && dependencyPath === packageDependencyPath)) {\n filteredPackages[packageName] = packageSpec;\n }\n }\n return filteredPackages;\n } catch (error1) {\n error = error1;\n return {};\n }\n }",
"getReducedDependencies() {\n var _a, _b;\n //versions[moduleName][dominantVersion] = highestVersionNumber\n const moduleVersions = {};\n //for each package of the same name, compute the highest version within each major version range\n for (const module of this.modules) {\n const npmModuleNameLower = module.npmModuleName.toLowerCase();\n //make the bucket if not exist\n if (!moduleVersions[npmModuleNameLower]) {\n moduleVersions[npmModuleNameLower] = {};\n }\n const dominantVersion = util_1.util.getDominantVersion(module.version);\n if (!moduleVersions[npmModuleNameLower][dominantVersion]) {\n moduleVersions[npmModuleNameLower][dominantVersion] = {\n highestVersion: module.version,\n aliases: []\n };\n }\n const previousVersion = (_a = moduleVersions[npmModuleNameLower][dominantVersion].highestVersion) !== null && _a !== void 0 ? _a : module.version;\n //if this new version is higher, keep it\n if (semver.compare(module.version, previousVersion) > 0) {\n moduleVersions[npmModuleNameLower][dominantVersion].highestVersion = module.version;\n }\n moduleVersions[npmModuleNameLower][dominantVersion].aliases.push(module.ropmModuleName);\n }\n const result = [];\n //compute the list of unique aliases\n for (const moduleName in moduleVersions) {\n const dominantVersions = Object.keys(moduleVersions[moduleName]).sort();\n for (let i = 0; i < dominantVersions.length; i++) {\n const dominantVersion = dominantVersions[i];\n const hostDependency = this.hostDependencies.find(dep => dep.npmModuleName === moduleName && util_1.util.getDominantVersion(dep.version) === dominantVersion);\n const obj = moduleVersions[moduleName][dominantVersion];\n //convert the version number into a valid roku identifier\n const dominantVersionIdentifier = util_1.util.prereleaseToRokuIdentifier(dominantVersion);\n let version;\n if (semver.prerelease(dominantVersion)) {\n //use exactly this prerelease version\n version = dominantVersion;\n }\n else {\n //use the highest version within this major range\n version = semver.maxSatisfying([obj.highestVersion, (_b = hostDependency === null || hostDependency === void 0 ? void 0 : hostDependency.version) !== null && _b !== void 0 ? _b : '0.0.0'], '*');\n }\n let ropmModuleName;\n if (hostDependency === null || hostDependency === void 0 ? void 0 : hostDependency.npmAlias) {\n ropmModuleName = util_1.util.getRopmNameFromModuleName(hostDependency.npmAlias);\n }\n else if (dominantVersions.length === 1) {\n ropmModuleName = util_1.util.getRopmNameFromModuleName(moduleName);\n }\n else {\n ropmModuleName = `${util_1.util.getRopmNameFromModuleName(moduleName)}_v${dominantVersionIdentifier}`;\n }\n result.push({\n dominantVersion: dominantVersion.toString(),\n npmModuleName: moduleName,\n //use the hosts's alias, or default to the module name\n ropmModuleName: ropmModuleName,\n version: version\n });\n }\n }\n return result;\n }",
"toDependencyGraph() {\n return _.map(\n // FIND MAX UNIQUE VERSION FIRST\n _.groupBy(this.allDependencies,\"name\"), versionGroup =>\n versionGroup.reduce((maxVersion, version) =>\n !maxVersion || getValue(() =>\n SemVer.gt(SemVer.coerce(version.version),SemVer.coerce(maxVersion.version)),\n version.version <= maxVersion.version\n ) ?\n version :\n maxVersion\n , null))\n \n // SORT BY INTER-DEPENDENCY\n .sort((depA,depB) => {\n const\n depADependencies = this.collectDependencies(depA.project),\n depBDependencies = this.collectDependencies(depB.project),\n depARequiresB = depADependencies.includes(depB.name),\n depBRequiresA = depBDependencies.includes(depA.name)\n \n if (depARequiresB && depBRequiresA)\n throw `Dependency circular requirement: ${depA.name} <~> ${depB.name}`\n \n return (!depARequiresB && !depARequiresB) ? 0 : depARequiresB ? 1 : -1\n })\n \n \n }",
"_settle() {\n if (this._state === UNSETTLED) {\n // Update the dependencies (in order) until it finds one that has changed.\n let someParentChanged = false;\n // eslint-disable-next-line no-restricted-syntax\n for (const p of this._dependencies) {\n someParentChanged = p._update();\n if (someParentChanged) break;\n }\n if (!someParentChanged) {\n // If no dependency has changed, the present constraint (this) is valid.\n this._setState(VALID);\n }\n // If one dependency has changed it should have invalidated the present\n // constraint so this._state should be \"invalid\" now.\n }\n return this._state;\n }",
"async sync() {\n let fileChanged = false;\n const ownersFilesKnown = new Set(this._fileRefs.keys());\n const ownersFiles = await this.github.searchFilename('OWNERS');\n\n for (const {filename, sha} of ownersFiles) {\n const repoPath = this.repoPath(filename);\n const fileSha = this._fileRefs.get(repoPath);\n ownersFilesKnown.delete(repoPath);\n\n if (!fileSha) {\n // File has never been fetched and should be added to the cache.\n this.logger.info(`Recording SHA for file \"${repoPath}\"`);\n fileChanged = true;\n\n this._fileRefs.set(repoPath, sha);\n } else if (fileSha !== sha) {\n // File has been updated and needs to be re-fetched.\n this.logger.info(\n `Updating SHA and clearing cache for file \"${repoPath}\"`\n );\n fileChanged = true;\n\n this._fileRefs.set(repoPath, sha);\n await this.cache.invalidate(repoPath);\n } else {\n this.logger.debug(`Ignoring unchanged file \"${repoPath}\"`);\n }\n }\n\n // Force-invalidate any files that we know should exist but didn't come back\n // in the GitHub search results.\n for (const repoPath of ownersFilesKnown) {\n // File has been updated and needs to be re-fetched.\n this.logger.info(\n `Updating SHA and clearing cache for file \"${repoPath}\"`\n );\n fileChanged = true;\n\n this._fileRefs.set(repoPath, 'UNKNOWN');\n await this.cache.invalidate(repoPath);\n }\n\n if (fileChanged) {\n const fileRefsPath = this.repoPath('__fileRefs__');\n await this.cache.invalidate(fileRefsPath);\n await this.cache.readFile(fileRefsPath, () =>\n JSON.stringify(Array.from(this._fileRefs))\n );\n }\n }",
"getChanges(packageName) {\n const changes = [];\n for (const info of this._changeFileData.changes) {\n if (info.packageName === packageName) {\n changes.push(info);\n }\n }\n return changes;\n }",
"async getDependencies() {\n\t\tvar allDeps = new Map;\n\t\t// Try to use cached dependencies if there are any or read and parse the file on spot.\n\t\tvar cached = this.cache.get(this.url);\n\t\tif (cached && cached.deps && cached.etag === this.etag) {\n\t\t\t// The file has been parsed before and it hasn't changed since. Use the cached dependency list.\n\t\t\texports.debug(this.name, 'deps up to date');\n\t\t\tthis._insertDescriptors(allDeps, cached.deps);\n\t\t} else {\n\t\t\t// The file hasn't been parsed or it has changed since.\n\t\t\texports.debug(this.name, 'parsing');\n\t\t\tvar buffer = await this.getBuffer(cached);\n\t\t\t// Parse for the first time.\n\t\t\tvar descriptors = this.parseDependencies(buffer, this);\n\t\t\t// Store the dependencies as array.\n\t\t\tthis.cache.setDeps(this, descriptors.map(desc => desc.url));\n\t\t\t// Add the dependency descriptors into a map of all deps to be pushed.\n\t\t\tdescriptors.forEach(desc => {\n\t\t\t\tallDeps.set(desc.url, desc);\n\t\t\t});\n\t\t}\n\n\t\tallDeps.forEach((desc, url) => {\n\t\t\tvar cached = this.cache.get(url);\n\t\t\tif (cached && cached.deps)\n\t\t\t\tthis._insertDescriptors(allDeps, cached.deps);\n\t\t});\n\t\t// Returns map of all of file's dependency and subdependecies in form of their descriptors.\n\t\treturn Array.from(allDeps.values())\n\t}",
"async commitAsync() {\n this.$cdIn();\n const success = this.commitActions();\n if (!success) {\n return;\n }\n /**\n * Install/uninstall dependencies\n */\n const response = await this.commitDependenciesAsync([this.getInstalls(true), this.getInstalls(false)], [this.getUninstalls(true), this.getUninstalls(false)]);\n this.$cdOut();\n return response;\n }",
"async status() {\n\n await this._init()\n\n if (!this.isOpenCollabRepo)\n throw 'Not an OpenCollab repository'\n\n const mangoRepoLib = initLib(this._opts.web3Host, this._opts.web3Port, this._contractAddress, this._account) \n\n const [name, description, issueCount, references, snapshots] = await Promise.all([ \n mangoRepoLib.mangoRepo.getName(),\n mangoRepoLib.mangoRepo.getDescription(),\n mangoRepoLib.mangoRepo.issueCount(),\n mangoRepoLib.refs(),\n mangoRepoLib.snapshots()\n ])\n\n return {\n name,\n description,\n issueCount,\n mangoAddress: this._contractAddress,\n contractAddress: this._contractAddress,\n references,\n snapshots,\n contract: mangoRepoLib\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
external logor: t > t > t Provides: ml_z_logor const Requires: bigInt, ml_z_normalize | function ml_z_logor(z1, z2) {
return ml_z_normalize(bigInt(z1).or(bigInt(z2)));
} | [
"function ml_z_lognot(z1) {\n return ml_z_normalize(bigInt(z1).not());\n}",
"function ml_z_logand(z1, z2) {\n return ml_z_normalize(bigInt(z1).and(bigInt(z2)));\n}",
"function ml_z_logxor(z1, z2) {\n return ml_z_normalize(bigInt(z1).xor(bigInt(z2)));\n}",
"static log(z) {\n z = Complex.assert(z);\n return new Complex(Math.log(z.mag()), z.arg());\n }",
"function ml_z_pred(z1) {\n return ml_z_normalize(bigInt(z1).prev());\n}",
"function logisticFunction(x) {\r\n // Short cuts the logistic function. Makes calculations go way faster\r\n if (x > NetworkMath.logisticMax / NetworkMath.alpha) {\r\n return .999;\r\n } else if (x < -NetworkMath.logisticMax / NetworkMath.alpha) {\r\n return 0.001;\r\n }\r\n return 1 / (1 + Math.pow(Math.E, -x * NetworkMath.alpha));\r\n}",
"function logisticFunction(x) {\n // Short cuts the logistic function. Makes calculations go way faster\n if (x > NetworkMath.logisticMax / NetworkMath.alpha) {\n return .999;\n } else if (x < -NetworkMath.logisticMax / NetworkMath.alpha) {\n return 0.001;\n }\n return 1 / (1 + Math.pow(Math.E, -x * NetworkMath.alpha));\n}",
"function Logarithm() {\r\n}",
"function adjust_temp(z_old, temp) {\n var z = nj.array(z_old);\n var i;\n var x;\n //console.log(\"before=\"+z_old.get(0));\n for (i=z.shape[0]-1;i>=0;i--) {\n x = z.get(i);\n x = Math.log(x) / temp;\n z.set(i, x);\n }\n x = z.max();\n z = nj.subtract(z, x);\n z = nj.exp(z);\n x = z.sum();\n z = nj.divide(z, x);\n //console.log(\"after=\"+z.get(0));\n return z;\n }",
"function logsumexp (x, y, isInit) {\n if (isInit) return y;\n var min = Math.min(x,y);\n var max = Math.max(x,y);\n if (max > min + MINUS_LOG_EPSILON) {\n\treturn max;\n } else {\n\treturn max + Math.log (Math.exp (min-max) + 1.0);\n }\n}",
"function HyperLogLog(n) {\n var bucket_count = Math.pow(2, n);\n var alpha_times_bucket_count_squared = compute_alpha_times_bucket_count_squared(bucket_count);\n var buckets = new Buffer(bucket_count);\n buckets.fill(0);\n\n // Maintain some running counts so that returning cardinality is cheap.\n\n var sum_of_inverses = bucket_count;\n var count_zero_buckets = bucket_count;\n\n var self = {\n add: function add(value) {\n if (value === undefined || value == null) {\n return; // nothing to add\n }\n var unique_hash = hash(value);\n\n var bucket = unique_hash[0] >>> (32 - n);\n var trailing_zeroes = 1;\n\n count_zeroes:\n for (var i = 3; i >= 2; --i) {\n var data = unique_hash[i];\n for (var j = 32; j; --j) {\n if (data & 0x1) {\n break count_zeroes;\n }\n\n ++trailing_zeroes;\n data = data >>> 1;\n }\n }\n\n // Maintain a running sum of inverses for quick cardinality checking.\n var old_value = buckets[bucket];\n var new_value = Math.max(trailing_zeroes, old_value);\n sum_of_inverses += Math.pow(2, -new_value) - Math.pow(2, -old_value);\n if (new_value !== 0 && old_value === 0) {\n --count_zero_buckets;\n }\n\n buckets[bucket] = new_value;\n\n return self;\n },\n\n count: function count() {\n /*var sum_of_inverses = 0;\n var count_zero_buckets = 0;\n\n for (var i = 0; i < bucket_count; ++i) {\n var bucket = buckets[i];\n if (bucket === 0) ++count_zero_buckets;\n sum_of_inverses += 1 / Math.pow(2, bucket);\n }*/\n // No longer need to compute this all every time, since we keep running counts to keep this cheap.\n\n var estimate = alpha_times_bucket_count_squared / sum_of_inverses;\n\n // Apply small cardinality correction\n if (count_zero_buckets > 0 && estimate < 5/2 * bucket_count) {\n estimate = bucket_count * Math.log(bucket_count / count_zero_buckets);\n }\n\n return Math.floor(estimate + 0.5);\n },\n\n relative_error: function relative_error() {\n // Estimate the relative error for this HLL.\n return 1.04 / Math.sqrt(bucket_count);\n },\n\n output: function output() {\n return {\n n: n,\n buckets: buckets\n }\n },\n\n merge: function merge(data) {\n if (n > data.n) {\n // Fold this HLL down to the size of the incoming one.\n var new_bucket_count = Math.pow(2, data.n);\n var old_buckets_per_new_bucket = Math.pow(2, n - data.n);\n var new_buckets = new Buffer(new_bucket_count);\n\n for (var i = 0; i < new_bucket_count; ++i) {\n var new_bucket_value = data.buckets[i];\n for (var j = 0; j < old_buckets_per_new_bucket; ++j) {\n new_bucket_value = Math.max(new_bucket_value, buckets[i * old_buckets_per_new_bucket + j]);\n }\n new_buckets[i] = new_bucket_value;\n }\n\n buckets = new_buckets;\n n = data.n;\n\n bucket_count = Math.pow(2, n);\n alpha_times_bucket_count_squared = compute_alpha_times_bucket_count_squared(bucket_count);\n } else {\n var new_buckets_per_existing = Math.pow(2, data.n - n);\n for (var i = data.buckets.length - 1; i >= 0; --i) {\n var existing_bucket_index = (i / new_buckets_per_existing) | 0;\n buckets[existing_bucket_index] = Math.max(buckets[existing_bucket_index], data.buckets[i]);\n }\n }\n\n // Recompute running totals\n sum_of_inverses = 0;\n count_zero_buckets = 0;\n for (var i = 0; i < bucket_count; ++i) {\n var bucket = buckets[i];\n if (bucket === 0) {\n ++count_zero_buckets;\n }\n sum_of_inverses += Math.pow(2, -bucket);\n }\n }\n };\n\n return self;\n}",
"log(b) {\n const denominator = b ? Math.log(b) : 1;\n return this.map((data) => Math.log(data) / denominator);\n }",
"function HyperLogLog(n) {\n var bucket_count = Math.pow(2, n);\n var alpha_times_bucket_count_squared = compute_alpha_times_bucket_count_squared(bucket_count);\n var buckets = new Buffer(bucket_count);\n buckets.fill(0);\n\n // Maintain some running counts so that returning cardinality is cheap.\n\n var sum_of_inverses = bucket_count;\n var count_zero_buckets = bucket_count;\n\n var self = {\n add: function add(unique_hash) {\n if (unique_hash === null) {\n return; // nothing to add\n }\n\n var bucket = unique_hash[0] >>> (32 - n);\n var trailing_zeroes = 1;\n\n count_zeroes:\n for (var i = 3; i >= 2; --i) {\n var data = unique_hash[i];\n for (var j = 32; j; --j) {\n if (data & 0x1) {\n break count_zeroes;\n }\n\n ++trailing_zeroes;\n data = data >>> 1;\n }\n }\n\n // Maintain a running sum of inverses for quick cardinality checking.\n var old_value = buckets[bucket];\n var new_value = Math.max(trailing_zeroes, old_value);\n sum_of_inverses += Math.pow(2, -new_value) - Math.pow(2, -old_value);\n if (new_value !== 0 && old_value === 0) {\n --count_zero_buckets;\n }\n\n buckets[bucket] = new_value;\n\n return self;\n },\n\n count: function count() {\n /*var sum_of_inverses = 0;\n var count_zero_buckets = 0;\n for (var i = 0; i < bucket_count; ++i) {\n var bucket = buckets[i];\n if (bucket === 0) ++count_zero_buckets;\n sum_of_inverses += 1 / Math.pow(2, bucket);\n }*/\n // No longer need to compute this all every time, since we keep running counts to keep this cheap.\n\n var estimate = alpha_times_bucket_count_squared / sum_of_inverses;\n\n // Apply small cardinality correction\n if (count_zero_buckets > 0 && estimate < 5/2 * bucket_count) {\n estimate = bucket_count * Math.log(bucket_count / count_zero_buckets);\n }\n\n return Math.floor(estimate + 0.5);\n },\n\n relative_error: function relative_error() {\n // Estimate the relative error for this HLL.\n return 1.04 / Math.sqrt(bucket_count);\n },\n\n output: function output() {\n return {\n n: n,\n buckets: buckets\n }\n },\n\n merge: function merge(data) {\n if (n > data.n) {\n // Fold this HLL down to the size of the incoming one.\n var new_bucket_count = Math.pow(2, data.n);\n var old_buckets_per_new_bucket = Math.pow(2, n - data.n);\n var new_buckets = new Buffer(new_bucket_count);\n\n for (var i = 0; i < new_bucket_count; ++i) {\n var new_bucket_value = data.buckets[i];\n for (var j = 0; j < old_buckets_per_new_bucket; ++j) {\n new_bucket_value = Math.max(new_bucket_value, buckets[i * old_buckets_per_new_bucket + j]);\n }\n new_buckets[i] = new_bucket_value;\n }\n\n buckets = new_buckets;\n n = data.n;\n\n bucket_count = Math.pow(2, n);\n alpha_times_bucket_count_squared = compute_alpha_times_bucket_count_squared(bucket_count);\n } else {\n var new_buckets_per_existing = Math.pow(2, data.n - n);\n for (var i = data.buckets.length - 1; i >= 0; --i) {\n var existing_bucket_index = (i / new_buckets_per_existing) | 0;\n buckets[existing_bucket_index] = Math.max(buckets[existing_bucket_index], data.buckets[i]);\n }\n }\n\n // Recompute running totals\n sum_of_inverses = 0;\n count_zero_buckets = 0;\n for (var i = 0; i < bucket_count; ++i) {\n var bucket = buckets[i];\n if (bucket === 0) {\n ++count_zero_buckets;\n }\n sum_of_inverses += Math.pow(2, -bucket);\n }\n }\n };\n\n return self;\n}",
"function caml_log10_float (x) { return Math.LOG10E * Math.log(x); }",
"function ml_z_neg(z1) {\n return ml_z_normalize(bigInt(z1).negate());\n}",
"function distmod(z) {\n\treturn 5. * log10(self.Dl(z) * 1e5);\n}",
"function czero(z) {\n return cnorm(z) < 1e-3;\n}",
"function ml_z_of_bits(z1, z2) {\n\n}",
"function ml_z_of_float(z1) {\n return bigInt(Math.floor(z1));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
recovers the table information, if the user is sitted in a table it initializes the sittedTable variable with that data. | function setTable() {
var elemT = $("#in_tableh");
if (elemT.html() == "true") {
elemT.html("false");
if ($("#is_ownerh").html() == "true")
sittedTable = new Table($("#table_idh").html(),true);
else
sittedTable = new Table($("#table_idh").html(),false);
}
} | [
"function setTable() {\n console.log('setting Table: ', current_table);\n setQueryParam('table', current_table);\n\n\n events = cache['events'];\n users = cache['users'];\n projects = cache['projects'];\n days = cache['days'];\n\n\n data = [];\n for (let id in cache[current_table]) {\n data.push(cache[current_table][id]);\n }\n\n buildTable($table, current_table, fields, data);\n}",
"function initTable () {\n let teams\n let localStorageTeams = window.localStorage.getItem(\"teams\");\n if(localStorageTeams==undefined || localStorageTeams==null ){\n // Search teams and create them\n getTeamsFromXML((teams) => {\n completeTable(teams)\n window.localStorage.setItem(\"teams\",JSON.stringify(teams));\n })\n }else{\n teams = JSON.parse(localStorageTeams)\n completeTable(teams)\n }\n}",
"function fillUpTable() {\r\n\tgetInstantValues();\r\n}",
"function initTable(){\n createTable(table, board);\n checkCombAtStart();\n render();\n moveProgressBar()\n}",
"loadTable () {\n this.loadTableSide(true)\n this.loadTableSide(false)\n }",
"function initializeSudokuTable() {\r\n\r\n getAmountToRemoveFromLocalStorage();\r\n completeTable = solvedTables[randomIndex];\r\n copyToNewTable(completeTable, gameTable);\r\n getGameTableToDisplay(gameTable);\r\n copyToNewTable(gameTable, userTable);\r\n printSudokuTableToPage();\r\n}",
"function userTable() { }",
"function createTable(table) {\n if (user.id == table.owner_id) {\n sittedTable = new Table(table.id,true);\n }\n}",
"function _waitForTable() {\n //TODO: I don't think this is worth doing at this point just for development\n // we can just create the table in production and assume it's always there\n}",
"function populateTable(searchTable, locationList, tableName) {\n\t// Bygg en ny tabell\n\tgenerateTableHeaders(searchTable, tableName);\n\tgenerateTableCells(searchTable, locationList, tableName);\n}",
"function loadTableData() {\n\t// get new table name selection from table selector list\n\tlet tableName = tableSelector.value;\n\tif (!tableName || tableName === undefined) {\n\t\t// reset to empty for default data load\n\t\tdataTable = '';\n\t} else {\n\t\t// reset view data table and config for new data load\n\t\tdataTable = tableName;\n\t\tviewData = [];\n\t\trestoringConfig = true;\n\t\tviewConfig = {};\n\t\tviewer.reset();\n\t\trestoringConfig = false;\n\t\tviewer.clear();\n\t\tif (dataViews.hasOwnProperty(dataTable)) {\n\t\t\tviewConfig = dataViews[dataTable];\n\t\t\trestoreConfig(viewConfig);\n\t\t}\n\t\tvscode.postMessage({\n\t\t\tcommand: 'config',\n\t\t\ttable: dataTable,\n\t\t\tconfig: viewConfig\n\t\t});\n\t}\n\treloadData(dataTable);\n}",
"function fillTableLocation(data) {\r\n if (data) {\r\n $('#name').html(datacenterId);\r\n $('#tableLocation').not(':first').not(':last').remove();\r\n var tableHead = '<tr class=\"thead\"><th>'+applyTrad(\"tablerack\")+'</th></tr>';\r\n // on a des objets avec noms variables. On les transforme en objet {name:name}. On ajoute un item de tri avec un 0. On tri. On accumule.\r\n var theRacks = Object.keys(data.objects).map(function(key){return {'name': data.objects[key].fields.friendlyname}}).map(sanitizeRack).sort(sortRackByName).reduce(function (accu, rack) {\r\n accu += TemplateEngine($(\"#racks_line\").html(), rack);\r\n return accu;\r\n },'');\r\n $('#tableLocation tbody').html(tableHead+theRacks);\r\n $('#LoginFormLoc').hide();\r\n }\r\n}",
"function setDemandSourcesTable(){\n\n $scope.pageData.demandSourcesTab.showFullSwitchTable = true;\n\n // get table Data \n serverAPI_service.getManageTableData(\"MANAGE / DEMAND \", 'demand_source', function(data){\n $scope.pageData.demandSourcesTab.tableData = data;\n $scope.pageData.demandSourcesTab.tableShowLoader = false;\n $scope.updateTable++;\n });\n\n }",
"function fillTableOnPage(initialData) {\n document.getElementById('main-table-body').innerHTML = buildTable(initialData);\n}",
"function loadDefaultData() {\n\n // Iterate through each row of the data, and add it to the page's data table\n tableData.forEach(sightings => {\n var tr = tableBody.append(\"tr\");\n Object.entries(sightings).forEach(function([key, value]) {\n tr.append(\"td\").text(value);\n });\n });\n \n}",
"function processCurrentTable()\n{\n\tlet firstRow = table.rows[0],\n\t\tlastRow = table.rows[table.rows.length - 1];\n\tcreateTableTags(firstRow.pos, lastRow.pos + lastRow.line.length);\n\n\taddTableHead();\n\tcreateSeparatorTag(table.rows[1]);\n\taddTableBody();\n}",
"loadTable() {\n this.sendToServer('server-open-load', this.activeTable);\n }",
"setTableLoaded() {\n\t\tsetTimeout(() => {\n\t\t\tthis.logger.debug('table-id', this.__uuid.toString(), $(`#table-${this.__uuid}`));\n\t $(`#table-${this.__uuid}`).removeClass('table--loading');\n\t\t}, 500);\n }",
"function populateTable() {\n \n // Clear any current data\n clearTable()\n\n // Loop through data and populate table rows\n tableData.forEach((ufoSighting) => {\n var row = tbody.append(\"tr\");\n Object.entries(ufoSighting).forEach(([key, value]) => {\n var cell = row.append(\"td\");\n cell.text(value);\n });\n });\n \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
! Function : CBSystemInitialize | function
CBSystemInitialize
()
{
WebSocketIFInitialize();
HideBlocker();
} | [
"async initialize() {\n // initialize system log first since it may be needed for error output\n this.onErrorMakeSystemManagerVisible = configUtil_1.ConfigUtilInstance.getDefault(this.manifest, \"manifest.finsemble.bootConfig.onErrorMakeSystemManagerVisible\", false);\n systemLog_1.default.initialize(this.onErrorMakeSystemManagerVisible);\n //make sure the essential config is available\n this.confirmConfigAndReport(this.manifest);\n // get the finsemble UUID with is unique system-wide and the same across restarts\n this.finUUID = system_1.System.Application.getCurrent().uuid;\n console.log(\"finUUID\", this.finUUID);\n // if old finsemble \"applications\" left around from when Finsemble was last running, kill then now before a fresh boot starts everything\n if (!(this.manifest.finsemble.killOrphanApplications === false)) {\n console.log(\"killing applications\");\n await common_1.killOldApplications(this.finUUID);\n }\n }",
"function initNative() {\n\tupdateAppState('divblox_config','success');\n\tupdateAppState('is_native','1');\n}",
"function bgInit() {\n\tlistenMUComm();\n\tlistenStartup();\n\tlistenMessages();\n\tchrome.runtime.onInstalled.addListener(bgSync);\n\tchrome.alarms.onAlarm.addListener(checkAlarm);\n\tbgLoadPrefs(function () {\n\t\tbgApplyPrefs();\n\t});\n}",
"function _init() {}",
"function CallInitialize(){\r\n\tif(!AlreadyInitialized){\r\n\t\tinitializeCommunication();\r\n\t\tAlreadyInitialized = true;\r\n\t}\r\n}",
"function _init() {\n }",
"_initffi(dllName) {\n return ffi.Library(dllName, \n {\n \"isVBusExist\": [\"ulong\", []],\n \"GetNumEmptyBusSlots\": [\"ulong\", [ref.refType(\"uchar\")]],\n \"PlugIn\": [\"ulong\", [\"uint\"]],\n \"PlugInNext\": [\"ulong\", [ref.refType(\"uint\")]],\n \"UnPlug\": [\"ulong\", [\"uint\"]],\n \"SetAxisLx\": [\"ulong\", [\"uint\", \"short\"]],\n \"SetAxisLy\": [\"ulong\", [\"uint\", \"short\"]],\n \"SetAxisRx\": [\"ulong\", [\"uint\", \"short\"]],\n \"SetAxisRy\": [\"ulong\", [\"uint\", \"short\"]],\n \"SetTriggerL\": [\"ulong\", [\"uint\", \"byte\"]],\n \"SetTriggerR\": [\"ulong\", [\"uint\", \"byte\"]],\n \"SetButton\": [\"ulong\", [\"uint\", \"uint16\", \"int\"]],\n \"SetDpad\": [\"ulong\", [\"uint\", \"uchar\"]],\n \"ResetController\": [\"ulong\", [\"uint\"]],\n \"isControllerPluggedIn\": [\"ulong\", [\"uint\", ref.refType(\"int\")]],\n \"isControllerOwned\": [\"ulong\", [\"uint\", ref.refType(\"int\")]]\n })\n }",
"function initialize() {\n if (initialized === true)\n return;\n initialized = true;\n log_1.logInfo(\"initializing app...\");\n admin.initializeApp();\n log_1.logInfo(\"initializing db...\");\n db = admin.firestore();\n log_1.logInfo(\"initializing mb api client...\");\n mb = messagebird_1.default(config_1.default.accessKey, undefined, [\"ENABLE_FIREBASE_PLUGIN\"]);\n log_1.logInfo(\"initialization finished successfully\");\n}",
"function initBrython() {\n if (!initialized) {\n brython(1);\n initialized = true;\n }\n }",
"function Initialize()\r\n {\r\n // Check if the gadget adapter needs to be registered\r\n if(InteropRegistered() == false)\r\n {\r\n // Register the adapter since an instance couldn't be created.\r\n RegisterGadgetInterop();\r\n }\r\n \r\n // Load an instance of the Gadget Adapter as an ActiveX object\r\n _builder = GetActiveXObject();\r\n }",
"function doLMSInitialize()\r\n{\r\n\tif (_Debug==true)\r\n\t\talert ('doLMSInitialize ()');\r\n}",
"function doLMSInitialize()\r\n{\r\n var result = \"false\";\r\n \r\n if (api == null)\r\n {\r\n api = getAPIHandle();\r\n }\r\n \r\n if ( api != null )\r\n {\r\n // Set the internal error code being tracked by the API Wrapper to 0\r\n _InternalErrorCode = API_CALL_PASSED_TO_LMS;\r\n\r\n // Invoke the Initialize(\"\") API method \r\n result = api.Initialize(\"\");\r\n }\r\n\r\n if ( result != \"true\" )\r\n {\r\n determineError();\r\n }\r\n\r\n return result;\r\n}",
"function roboxInit()\n{\n roboxAppControlInit(location.search);\n\n disableNameChange();\n \n RoBoxBrain.connectionMonitor(roboxConnectionMonitor);\n}",
"static initialize() {\n this.initializeKeyboard();\n this.initializeMouse();\n }",
"function _initBluetooth() {\n bluetooth = new Bluetooth();\n bluetooth.on('scanning', (scanning) => {\n _fbSet('state/bluetooth/scanning', scanning);\n });\n bluetooth.on('adapter_state', (adapterState) => {\n _fbSet('state/bluetooth/adapterState', adapterState);\n });\n }",
"function init(callback){\n console.log('Loading XLoBorg on bus ', busNumber);\n\n async.series([\n function(callback){\n // open the bus\n bus = i2c.open(busNumber, callback);\n },\n function(callback){\n // Check for accelerometer\n bus.readByte(addressAccelerometer, 1, function(err, res) {\n if (err){\n console.log('Missing accelerometer at 0x1C');\n callback(err);\n }\n else {\n console.log('Found accelerometer at 0x1C');\n initAccelometer(callback);\n }\n });\n },\n function(callback){\n // Check for compass\n\n bus.readByte(addressCompass,1, function(err, res) {\n if (err){\n console.log('Missing compass at 0x0E');\n callback(err);\n }\n else {\n console.log('Found compass at 0x0E');\n initCompass(callback);\n }\n });\n }\n ], function(err){\n callback(err);\n });\n}",
"function init()\n{\n\tSystem.out.println(\"-------------------------- init --------------------------------\");\n\tsetupGUI();\n\tsetupApparatusPanel();\n\tinitLogging();\n\tsetupMultimeter();\t\n\tsetupCircuitListener();\n\tsetupAnswerButton();\n\tsetupActivity();\n\tsetupAsessmentLogging();\n\tsetupCircuitAnalyzer();\n\tinitializationDone = true;\n\treturn initializationDone;\n}",
"function $core_SCORM_initialize() \n{ \n\tif ($m_bDebug) alert(\"DEBUG: initializing SCORM LMS connection\");\n\n\t$SCORM_getAPIHandle(); \n\t$m_bWarnOnExit = false;\t\t// SCORM saves in onBeforeUnload, so an exit confirmation is not permitted\n\n\ttry{\n\t\tif ($m_apiSCORM)\n\t\t{\n\t\t\t\t// Call the LMSInitialize function that should be implemented by the API\n\t\t\tvar nResult = $m_apiSCORM.LMSInitialize(\"\");\n\n\t\t\t\t// If LMSInitialize did not complete successfully.\n\t\t\tif ((nResult.toString() != \"1\") && (nResult.toString() != \"true\"))\n\t\t\t{\n\t\t\t\tif ($m_bDebug) alert(\"DEBUG: SCORM LMS initialization failed.\");\n\t\t\t\t\t// If an error was encountered, then invalidate the handle\n\t\t\t\tvar nError = $SCORM_errorHandler(\"LMSInitialize()\");\n\t\t\t\tif (nError != ERROR_NONE)\n\t\t\t\t{\n\t\t\t\t\t$m_apiSCORM = null;\n\t\t\t\t\tif ($m_bSCORMExitOnInitFail)\n\t\t\t\t\t\t$exitCourse();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if ($m_bDebug) alert(\"DEBUG: SCORM LMS initialization succeeded.\");\n\n\t\t\t\t// Start the session time\n\t\t\t$SCORM_startSessionTime();\n\t\t}\n\n\t\tif ($m_apiSCORM)\n\t\t\t$callASFunction(\"$preloadData\");\n\t\telse\n\t\t\t$callASFunction(\"$onDataError\");\n\t}\n\tcatch(err){\n\t\tif ($m_bDebug) alert(\"DEBUG: SCORM initialization failed (exception thrown)!\");\n\t\t$callASFunction(\"$onDataError\");\n\t}\n}",
"function initHbbtv (error) {\n if (hbbtvlib_initialize()) {\n if (hbbtvlib_show()) {\n\n } else if (error){\n error('Error showing HbbTV app: ' + hbbtvlib_lastError);\n } else {\n throw new Error('Error showing HbbTV app: ' + hbbtvlib_lastError);\n }\n\n } else if (error) {\n error('Error initializing HbbTV app: ' + hbbtvlib_lastError);\n } else {\n throw new Error('Error initializing HbbTV app: ' + hbbtvlib_lastError);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Proceeds with the generation given the parsed swagger object | function doGenerate(swagger, options) {
if (!options.templates) {
options.templates = path.join(__dirname, 'templates');
}
var output = path.normalize(options.output || 'src/app/api');
var prefix = options.prefix || 'Api';
if (swagger.swagger !== '2.0') {
console.error(
'Invalid swagger specification. Must be a 2.0. Currently ' +
swagger.swagger
);
process.exit(1);
}
swagger.paths = swagger.paths || {};
swagger.models = swagger.models || [];
var models = processModels(swagger, options);
var services = processServices(swagger, models, options);
// Apply the tag filter. If includeTags is null, uses all services,
// but still can remove unused models
const includeTags = options.includeTags;
if (typeof includeTags == 'string') {
options.includeTags = includeTags.split(',');
}
const excludeTags = options.excludeTags;
if (typeof excludeTags == 'string') {
options.excludeTags = excludeTags.split(',');
}
applyTagFilter(models, services, options);
// Read the templates
var templates = {};
var files = fs.readdirSync(options.templates);
files.forEach(function (file, index) {
var pos = file.indexOf('.mustache');
if (pos >= 0) {
var fullFile = path.join(options.templates, file);
templates[file.substr(0, pos)] = fs.readFileSync(fullFile, 'utf-8');
}
});
// read the fallback templates
var fallbackTemplates = path.join(__dirname, 'templates');
fs.readdirSync(fallbackTemplates)
.forEach(function (file) {
var pos = file.indexOf('.mustache');
if (pos >= 0) {
var fullFile = path.join(fallbackTemplates, file);
if (!(file.substr(0, pos) in templates)) {
templates[file.substr(0, pos)] = fs.readFileSync(fullFile, 'utf-8');
}
}
});
// Prepare the output folder
const modelsOutput = path.join(output, 'models');
const servicesOutput = path.join(output, 'services');
mkdirs(modelsOutput);
mkdirs(servicesOutput);
var removeStaleFiles = options.removeStaleFiles !== false;
var generateEnumModule = options.enumModule !== false;
// Utility function to render a template and write it to a file
var generate = function (template, model, file) {
var code = Mustache.render(template, model, templates)
.replace(/[^\S\r\n]+$/gm, '');
fs.writeFileSync(file, code, 'UTF-8');
console.info('Wrote ' + file);
};
// Calculate the globally used names
var moduleClass = toClassName(prefix + 'Module');
var moduleFile = toFileName(moduleClass);
// Angular's best practices demands xxx.module.ts, not xxx-module.ts
moduleFile = moduleFile.replace(/\-module$/, '.module');
var configurationClass = toClassName(prefix + 'Configuration');
var configurationInterface = toClassName(prefix + 'ConfigurationInterface');
var configurationFile = toFileName(configurationClass);
function applyGlobals(to) {
to.prefix = prefix;
to.moduleClass = moduleClass;
to.moduleFile = moduleFile;
to.configurationClass = configurationClass;
to.configurationInterface = configurationInterface;
to.configurationFile = configurationFile;
return to;
}
// Write the models and examples
var modelsArray = [];
for (var modelName in models) {
var model = models[normalizeModelName(modelName)];
if (model.modelIsEnum) {
model.enumModule = generateEnumModule;
}
applyGlobals(model);
// When the model name differs from the class name, it will be duplicated
// in the array. For example the-user would be TheUser, and would be twice.
if (modelsArray.includes(model)) {
continue;
}
modelsArray.push(model);
generate(
templates.model,
model,
path.join(modelsOutput, model.modelFile + '.ts')
);
if (options.generateExamples && model.modelExample) {
var value = resolveRefRecursive(model.modelExample, swagger);
var example = JSON.stringify(value, null, 2);
example = example.replace(/'/g, "\\'");
example = example.replace(/"/g, "'");
example = example.replace(/\n/g, "\n ");
model.modelExampleStr = example;
generate(
templates.example,
model,
path.join(modelsOutput, model.modelExampleFile + '.ts')
);
}
}
if (modelsArray.length > 0) {
modelsArray[modelsArray.length - 1].modelIsLast = true;
}
if (removeStaleFiles) {
var modelFiles = fs.readdirSync(modelsOutput);
modelFiles.forEach((file, index) => {
var ok = false;
var basename = path.basename(file);
for (var modelName in models) {
var model = models[normalizeModelName(modelName)];
if (basename == model.modelFile + '.ts'
|| basename == model.modelExampleFile + '.ts'
&& model.modelExampleStr != null) {
ok = true;
break;
}
}
if (!ok) {
rmIfExists(path.join(modelsOutput, file));
}
});
}
// Write the model index
var modelIndexFile = path.join(output, 'models.ts');
if (options.modelIndex !== false) {
generate(templates.models, { models: modelsArray }, modelIndexFile);
} else if (removeStaleFiles) {
rmIfExists(modelIndexFile);
}
// Write the StrictHttpResponse type
generate(templates.strictHttpResponse, {},
path.join(output, 'strict-http-response.ts'));
// Write the services
var servicesArray = [];
for (var serviceName in services) {
var service = services[serviceName];
service.generalErrorHandler = options.errorHandler !== false;
applyGlobals(service);
servicesArray.push(service);
generate(
templates.service,
service,
path.join(servicesOutput, service.serviceFile + '.ts')
);
}
if (servicesArray.length > 0) {
servicesArray[servicesArray.length - 1].serviceIsLast = true;
}
if (removeStaleFiles) {
var serviceFiles = fs.readdirSync(servicesOutput);
serviceFiles.forEach((file, index) => {
var ok = false;
var basename = path.basename(file);
for (var serviceName in services) {
var service = services[serviceName];
if (basename == service.serviceFile + '.ts') {
ok = true;
break;
}
}
if (!ok) {
rmIfExists(path.join(servicesOutput, file));
}
});
}
// Write the service index
var serviceIndexFile = path.join(output, 'services.ts');
if (options.serviceIndex !== false) {
generate(templates.services, { services: servicesArray }, serviceIndexFile);
} else if (removeStaleFiles) {
rmIfExists(serviceIndexFile);
}
// Write the module
var fullModuleFile = path.join(output, moduleFile + '.ts');
if (options.apiModule !== false) {
generate(templates.module, applyGlobals({
services: servicesArray
}),
fullModuleFile);
} else if (removeStaleFiles) {
rmIfExists(fullModuleFile);
}
// Write the configuration
{
var rootUrl = '';
if (swagger.hasOwnProperty('host') && swagger.host !== '') {
var schemes = swagger.schemes || [];
var scheme = schemes.length === 0 ? '//' : schemes[0] + '://';
rootUrl = scheme + swagger.host;
}
if (swagger.hasOwnProperty('basePath') && swagger.basePath !== ''
&& swagger.basePath !== '/') {
rootUrl += swagger.basePath;
}
generate(templates.configuration, applyGlobals({
rootUrl: rootUrl,
}),
path.join(output, configurationFile + '.ts')
);
}
// Write the BaseService
{
generate(templates.baseService, applyGlobals({}),
path.join(output, 'base-service.ts'));
}
} | [
"generate() {\n this.log(c.bold.underline('OpenAPI v3 Documentation Generator\\n\\n'));\n // Instantiate DocumentGenerator\n const generator = new DefinitionGenerator_1.DefinitionGenerator(this.customVars.documentation);\n generator.parse();\n // Map function configurations\n const funcConfigs = this.serverless.service.getAllFunctions().map((functionName) => {\n const func = this.serverless.service.getFunction(functionName);\n return utils_1.merge({ _functionName: functionName }, func);\n });\n // Add Paths to OpenAPI Output from Function Configuration\n generator.readFunctions(funcConfigs);\n // Process CLI Input options\n const config = this.processCliInput();\n this.log(`${c.bold.yellow('[VALIDATION]')} Validating OpenAPI generated output\\n`);\n const validation = generator.validate();\n if (validation.valid) {\n this.log(`${c.bold.green('[VALIDATION]')} OpenAPI valid: ${c.bold.green('true')}\\n\\n`);\n }\n else {\n this.log(`${c.bold.red('[VALIDATION]')} Failed to validate OpenAPI document: \\n\\n`);\n this.log(`${c.bold.green('Context:')} ${JSON.stringify(validation.context, null, 2)}\\n`);\n if (typeof validation.error === 'string') {\n this.log(`${validation.error}\\n\\n`);\n }\n else {\n for (const info of validation.error) {\n this.log(c.grey('\\n\\n--------\\n\\n'));\n this.log(' ', c.blue(info.dataPath), '\\n');\n this.log(' ', info.schemaPath, c.bold.yellow(info.message));\n this.log(c.grey('\\n\\n--------\\n\\n'));\n this.log(`${util_1.inspect(info, { colors: true, depth: 2 })}\\n\\n`);\n }\n }\n }\n const { definition } = generator;\n // Output the OpenAPI document to the correct format\n let output;\n switch (config.format.toLowerCase()) {\n case 'json':\n output = JSON.stringify(definition, null, config.indent);\n break;\n case 'yaml':\n default:\n output = YAML.safeDump(definition, { indent: config.indent });\n break;\n }\n fs.writeFileSync(config.file, output);\n this.log(`${c.bold.green('[OUTPUT]')} To \"${c.bold.red(config.file)}\"\\n`);\n }",
"function generateSwagger (intermediate) {\n // console.log(JSON.stringify(intermediate, null, 2))\n // require() caches its data, so we need to deep clone the template here\n var swagger = JSON.parse(JSON.stringify(SwaggerTemplate))\n // add more content to the template\n for (var host in intermediate) {\n swagger.host = host\n swagger.schemes = Object.keys(intermediate[host].schemes)\n generatePaths(swagger, intermediate[host].paths)\n }\n return swagger\n}",
"function exportIodocs(src){\n var obj = clone(src,false);\n obj.swagger = '2.0';\n obj.info = {};\n obj.info.version = obj.version || '1';\n obj.info.title = obj.name;\n obj.info.description = obj.description;\n obj.paths = {};\n\n var u = url.parse(obj.basePath+obj.publicPath);\n obj.schemes = [];\n obj.schemes.push(u.protocol.replace(':',''));\n obj.host = u.host;\n obj.basePath = u.path;\n\n delete obj.version;\n delete obj.title;\n delete obj.description;\n delete obj.publicPath;\n delete obj.privatePath; // for oauth etc\n delete obj.protocol;\n delete obj.name;\n delete obj.auth; // TODO\n delete obj.oauth; // TODO\n delete obj.headers; // TODO\n rename(obj,'schemas','definitions');\n if (obj.definitions) fixSchema(obj.definitions);\n\n for (var r in obj.resources) {\n var resource = obj.resources[r];\n // do tags\n for (var m in resource.methods) {\n var method = resource.methods[m];\n method.path = fixPathParameters(method.path);\n\n if (!obj.paths[method.path]) obj.paths[method.path] = {};\n var path = obj.paths[method.path];\n\n var httpMethod = method.httpMethod.toLowerCase();\n if (!path[httpMethod]) path[httpMethod] = {};\n\n var op = path[httpMethod];\n op.operationId = m;\n op.description = method.description;\n op.parameters = [];\n\n for (var p in method.parameters) {\n var param = method.parameters[p];\n param.name = p;\n if (param.title) rename(param,'title','name');\n if ((param.type == 'textarea') || (param.type == 'enumerated')) param.type = 'string';\n if (param.type == 'long') param.type = 'number';\n if (param.type == 'string[]') {\n param.type = 'array';\n param.items = {};\n param.items.type = 'string';\n }\n rename(param,'location','in');\n if (!param[\"in\"]) {\n if (method.path.indexOf('{'+param.name+'}')>=0) {\n param[\"in\"] = 'path';\n }\n else {\n param[\"in\"] = 'query';\n }\n }\n if ((param[\"in\"] == 'body') && (param.type != 'object')) {\n param[\"in\"] = 'formData'; // revalidate\n }\n if (param[\"in\"] == 'pathReplace') {\n param[\"in\"] = 'path';\n }\n if (param[\"in\"] == 'path') {\n param.required = true;\n }\n if (typeof param.required == 'string') {\n param.required = (param.required === 'true');\n }\n if (param.properties) {\n delete param.type;\n param.schema = {};\n param.schema.type = 'object';\n param.schema.properties = param.properties;\n delete param.properties;\n delete param[\"default\"];\n fixSchema(param.schema);\n }\n if (param.items) fixSchema(param.items);\n op.parameters.push(param);\n }\n op.tags = [];\n op.tags.push(r);\n\n op.responses = {};\n op.responses[\"200\"] = {};\n op.responses[\"200\"].description = 'Success';\n\n }\n }\n\n delete obj.resources;\n return obj;\n}",
"_createSwagger() {\n SwaggerRunner.create(this.config, (err, runner) => {\n if (err) return console.log(err);\n const sw = runner.expressMiddleware();\n sw.register(this.app);\n // create swagger docs after swagger register\n // has to be after or express routes will not overwrite\n this._createSwaggerDocs();\n });\n }",
"function generateSwaggerObject(swaggerString, name) {\n\tlogger.entry(\"swaggerUtils.generateSwaggerObject\", swaggerString, name);\n\t\n\tvar swaggerObject = null;\n\t\n\tvar lcName = name.toLowerCase();\n\tif(_endsWith(lcName, \".yaml\") || _endsWith(lcName, \".yml\")) {\n\t\t// parse yaml\n\t\ttry {\n\t\t\tswaggerObject = yaml.safeLoad(swaggerString);\n\t\t} catch(e) {\n\t\t\t// do not error, do not want this out to the console\n\t\t\tlogger.debug(e);\n\t\t\t// throw\n\t\t\tthrow e;\n\t\t}\n\t} else if(_endsWith(lcName, \".json\")) {\n\t\t// parse JSON\n\t\ttry {\n\t\t\tswaggerObject = JSON.parse(swaggerString);\n\t\t} catch(e) {\n\t\t\t// do not error, do not want this out to the console\n\t\t\tlogger.debug(e);\n\t\t\t// throw\n\t\t\tthrow e;\n\t\t}\n\t} else {\n\t\t// throw an error\n\t\tvar msg = logger.Globalize.formatMessage(\"errorUnrecognisedExtension\", lcName);\n\t\tlogger.info(msg);\n\t\tthrow new Error(msg);\n\t}\n\t\n\tlogger.exit(\"swaggerUtils.generateSwaggerObject\", swaggerObject);\n\treturn swaggerObject;\n}",
"apiDefinationGeneratorTest(obj) {\n let newProps = {};\n newProps['methods'] = {};\n newProps['properties'] = {};\n newProps['name'] = obj.constructor.name;\n\n if (obj.version) {\n newProps['version'] = obj.version;\n }\n\n newProps['events'] = {\n 'listening': [this, this.listening],\n 'wssError': [this, this.wssError],\n 'wssConnection': [this, this.wssOnConnection],\n 'wssMessage': [this, this.wssOnMessage],\n };\n\n do {\n //console.log(obj);\n for (let index of Object.getOwnPropertyNames(obj)) {\n if (obj[index]) {\n if ((typeof obj[index]) == 'function') {\n let jsDoc = ''\n\n // The constructor function contains all the code for the class,\n // including the comments between functions which is where the\n // jsDoc definition for the function lives.\n if (obj['constructor']) {\n let done = false;\n\n // The first line of this specific function will be the last line\n // in the constructor we need to look at. The relevant jsDoc\n // should be right above.\n let firstLine = obj[index].toString().split(/\\n/)[0];\n\n // We are going to parse every line of the constructor until we\n // find the first line of the function we're looking for.\n for (let line of obj['constructor'].toString().split(/\\n/)) {\n if (!done) {\n // Start of a new jsDoc segment. Anything we already have is\n // not related to this function.\n if (line.match(/\\/\\*\\*/)) {\n jsDoc = line + '\\n';\n }\n\n // There should be no lines that start with a \"}\" within the\n // jsDoc definition so if we find one we've meandered out of\n // the jsDoc definition. This makes sure that later\n // functions that have no jsDoc defition don't get jsDoc\n // definitions from earlier functions (the earlier functions\n // will end with \"}\").\n else if (line.replace(/^\\s*/g, '').match(/^}/)) {\n jsDoc = '';\n }\n\n // If this line from the constructor matches the first line\n // from this function (with leading whitespace removed), we\n // have what we came for. Don't process future lines.\n else if (line.replace(/^\\s*/g, '') == firstLine) {\n done = true;\n }\n\n // Either this line is part of the jsDoc or it's junk, Either\n // way, append it to the jsDoc we're extracting. If it's\n // junk it will be cleared by the start of the next jsDoc\n // segment or the end of a function.\n else {\n jsDoc += line + '\\n';\n }\n }\n }\n }\n\n // Now we just tidy up the jsDoc fragment we extracted. More to do\n // here.\n if (jsDoc.match(/\\/\\*\\*/)) {\n jsDoc = jsDoc.split(/\\/\\*\\*/)[1];\n }\n else {\n jsDoc = '';\n }\n if (jsDoc.match(/\\*\\//)) {\n jsDoc = jsDoc.split(/\\*\\//)[0];\n }\n\n let functionProperties = obj[index];\n functionProperties['namedArguments'] = {};\n functionProperties['numberedArguments'] = [];\n functionProperties['private'] = false;\n functionProperties['description'] = '';\n functionProperties['returns'] = '';\n if (jsDoc.length > 0) {\n jsDoc = jsDoc.replace(/^\\s*/mg, '');\n for (let line of (jsDoc.split(/\\n/))) {\n if (line.match(/^\\@private/i)) {\n functionProperties['private'] = true;\n }\n else if (line.match(/^\\@param/i)) {\n let parsedLine = this.parseJsDocLine(line);\n functionProperties['numberedArguments'].push(parsedLine)\n functionProperties['namedArguments'][parsedLine[0]] = parsedLine;\n }\n else if (line.match(/^\\@return/i)) {\n functionProperties['returns'] = line;\n }\n else {\n functionProperties['description'] += line;\n }\n }\n //console.log(index);\n //console.log(jsDoc);\n //console.log(functionProperties);\n newProps['methods'][index] = functionProperties;\n newProps['methods'][index]['uri'] = index;\n }\n }\n else if (typeof obj[index] != 'object') {\n newProps['properties'][index] = {\n 'uri': index,\n 'getter': 'TODO'\n }\n }\n else {\n //console.log(\"not a function: \", index, typeof obj[index]);\n }\n }\n }\n } while (obj = Object.getPrototypeOf(obj));\n\n return newProps;\n }",
"_bundle (schema){\n return SwaggerParser.bundle(schema);\n }",
"function convertSwagger(source){\n var apiInfo = clone(source,false);\n apiInfo.resources = {};\n for (var p in apiInfo.paths) {\n for (var m in apiInfo.paths[p]) {\n if (m != 'parameters') {\n var sMethod = apiInfo.paths[p][m];\n var ioMethod = {};\n ioMethod.path = p;\n ioMethod.op = m;\n var sMethodUniqueName = (sMethod.operationId ? sMethod.operationId : m+'_'+p).split('/').join('_');\n sMethodUniqueName = sMethodUniqueName.split(' ').join('_'); // TODO {, } and : ?\n var tagName = 'Default';\n if (sMethod.tags && sMethod.tags.length>0) {\n tagName = sMethod.tags[0];\n }\n if (!apiInfo.resources[tagName]) {\n apiInfo.resources[tagName] = {};\n if (apiInfo.tags) {\n for (var t in apiInfo.tags) {\n var tag = apiInfo.tags[t];\n if (tag.name == tagName) {\n apiInfo.resources[tagName].description = tag.description;\n apiInfo.resources[tagName].externalDocs = tag.externalDocs;\n }\n }\n }\n }\n if (!apiInfo.resources[tagName].methods) apiInfo.resources[tagName].methods = {};\n apiInfo.resources[tagName].methods[sMethodUniqueName] = ioMethod;\n }\n }\n }\n delete apiInfo.paths; // to keep size down\n delete apiInfo.definitions; // ditto\n return apiInfo;\n}",
"validate (){\n const that = this;\n return this\n ._validate(this.swaggerInput)\n .then((dereferencedSchema) => {\n that.swaggerObject = dereferencedSchema;\n return that;\n });\n }",
"function generateDocumentation() {\n // We should create a documentation file every time we start.\n // the great thing is that this documentation is self-generating based on the endpoints!\n // this is one of the key reasons I designed the endpoints the way I did.\n // ok, so to start off, we should grab the supplement. This forms the first part of the documentation, the part that can't be auto-generated.\n str = fs.readFileSync('API_documentation_supplement.md').toString();\n // once that's done, let's add the auto-gen stuff to it!\n str += '\\n';\n endpoints.forEach(function(ep, ind) {\n str +='\\n## '+ep.name+' '+ep.tgt+'\\n';\n if (ep.name=='create' || ep.name == 'history') {\n idStr = '[arbitrary/optional ID]';\n } else {\n idStr = '[id]';\n }\n str +='### '+ep.desc+'\\n';\n str +='Route: _API/'+ep.tgt+'/'+ep.name+'/'+idStr+'_\\n\\n';\n\n str +='Required JSON: \\n';\n ep.inputs.forEach(function(input, ind2) {\n str+='* '+input+'\\n';\n });\n if (ep.inputs.length == 0) {\n str += '*none*\\n';\n }\n\n if ((ep.name == 'update' || ep.name=='create') && (ep.tgt == 'routes')) {\n str += '\\n For waypoints_JSON, please use this format: '+JSON.stringify(getTestValues()['routes'].waypoints_JSON)+'. Make sure you use the quotation marks.\\n';\n }\n });\n\n // We're done. Save the str to file!\n fs.writeFileSync('../API_documentation.md', str);\n}",
"function generatePath (swagger, path, pathInfo) {\n if (!isValidObject(swagger[path])) {\n swagger[path] = {}\n }\n for (var method in pathInfo) {\n generateMethod(swagger[path], method.toLowerCase(), pathInfo[method])\n }\n}",
"function parseSwagger () {\n try {\n // Clear any previous results\n editors.clearResults();\n\n // Get all the parameters\n swaggerParser = swaggerParser || new SwaggerParser();\n let options = form.getOptions();\n let method = form.method.button.val();\n let api = form.getAPI();\n\n // Call Swagger Parser\n swaggerParser[method](api, options)\n .then(() => {\n // Show the results\n let results = swaggerParser.$refs.values();\n Object.keys(results).forEach((key) => {\n editors.showResult(key, results[key]);\n });\n })\n .catch((err) => {\n editors.showError(ono(err));\n analytics.trackError(err);\n });\n\n // Track the operation\n counters[method]++;\n analytics.trackEvent(\"button\", \"click\", method, counters[method]);\n }\n catch (err) {\n editors.showError(ono(err));\n analytics.trackError(err);\n }\n}",
"function generate(src = conf.apiFile, dest = conf.outDir) {\n let schema;\n try {\n const content = fs.readFileSync(src);\n schema = JSON.parse(content.toString());\n }\n catch (e) {\n if (e instanceof SyntaxError) {\n utils_1.out(`${src} is either not a valid JSON scheme or contains non-printable characters`, 'red');\n }\n else\n utils_1.out(`JSON scheme file '${src}' does not exist`, 'red');\n utils_1.out(`${e}`);\n return;\n }\n const header = utils_1.processHeader(schema);\n const config = { header, dest };\n if (!fs.existsSync(dest))\n fs.mkdirSync(dest);\n process_paths_1.processPaths(schema.paths, `http://${schema.host}${schema.basePath}${conf.swaggerFile}`, config);\n definitions_1.processDefinitions(schema.definitions, config);\n}",
"function parseSwagger() {\n try {\n // Clear any previous results\n editors.clearResults();\n\n // Get all the parameters\n parser = parser || new SwaggerParser();\n var options = form.getOptions();\n var method = form.method.button.val();\n var api = form.getAPI();\n\n // Call Swagger Parser\n parser[method](api, options)\n .then(function() {\n // Show the results\n var results = parser.$refs.values();\n Object.keys(results).forEach(function(key) {\n editors.showResult(key, results[key]);\n });\n })\n .catch(function(err) {\n editors.showError(ono(err));\n analytics.trackError(err);\n });\n\n // Track the operation\n counters[method]++;\n analytics.trackEvent('button', 'click', method, counters[method]);\n }\n catch (err) {\n editors.showError(ono(err));\n analytics.trackError(err);\n }\n}",
"function generateResponses (swagger, data) {\n swagger.responses = {}\n var byStatus = {}\n // group responses by status code\n for (var i = 0; i < data.length; i++) {\n const status = data[i].response.status\n const body = data[i].response.body\n if (!isValidObject(byStatus[status])) {\n byStatus[status] = {\n type: data[i].response.headers['content-type']\n }\n }\n if (isValidObject(body)) {\n if (!isValidObject(byStatus[status].data)) {\n byStatus[status].data = []\n }\n byStatus[status].data.push(body)\n }\n }\n\n // add the responses to the swagger spec\n for (var status in byStatus) {\n swagger.responses[status] = {\n 'description': 'Generated description'\n }\n // handle application/json payload\n if (isValidObject(byStatus[status].data)) {\n const schema = GenerateSchema.json(byStatus[status].data)\n swagger.responses[status].schema = schema.items\n }\n }\n}",
"function generateMethod (swagger, method, methodInfo) {\n if (typeof (swagger[method]) === 'undefined') {\n swagger[method] = {}\n }\n var thisMethod = swagger[method]\n // add description & operationId\n thisMethod.description = 'Generated description'\n thisMethod.operationId = 'GeneratedOperationId' + operationIdSuffix++\n // add produces and consumes\n const consumes = getContentTypes(methodInfo, 'request')\n const produces = getContentTypes(methodInfo, 'response')\n if (isValidObject(consumes)) {\n thisMethod.consumes = consumes\n }\n if (isValidObject(produces)) {\n thisMethod.produces = produces\n }\n // add parameters\n generateParameters(thisMethod, methodInfo, consumes)\n // add responses\n generateResponses(thisMethod, methodInfo)\n}",
"function parseSwaggerPaths(swagger) {\n var paths = swagger[\"paths\"];\n //console.log(\"organization Open API paths\", paths);\n var report = [];\n try {\n // get paths\n Object.keys(paths).forEach(function (path, index) {\n // get details for each path resource\n Object.keys(paths[path]).forEach(function (p, i) {\n var tag = paths[path][p][\"tags\"][0];\n var summary = paths[path][p][\"summary\"];\n var description = paths[path][p][\"description\"];\n var operationId = paths[path][p][\"operationId\"];\n var params = paths[path][p][\"parameters\"] || [];\n var method = Object.keys(paths[path])[i];\n var responses = __assign({}, paths[path][p][\"responses\"]);\n var example_200 = \"\";\n try {\n example_200 = JSON.stringify(responses[\"200\"][\"examples\"][\"application/json\"]).replaceAll(\",\", \";\");\n }\n catch (e) {\n }\n var example_201 = \"\";\n try {\n example_201 = JSON.stringify(responses[\"201\"][\"examples\"][\"application/json\"]).replaceAll(\",\", \";\");\n }\n catch (e) {\n }\n // pathParams\n var pathParams = [];\n var filteredPathParams = params.filter(function (p) { return p.in.includes(\"path\"); });\n filteredPathParams.forEach(function (p) { return pathParams.push(p.name); });\n //pathParams = JSON.stringify(pathParams);\n pathParams = pathParams.join(\"; \").toString();\n // queryParams\n var queryParams = [];\n var filteredQueryParams = params.filter(function (p) { return p.in.includes(\"query\"); });\n filteredQueryParams.forEach(function (p) { return queryParams.push(p.name); });\n //queryParams = JSON.stringify(queryParams);\n queryParams = queryParams.join(\"; \");\n // bodyModel\n var bodyModel = [];\n var filteredBodyModel = params.filter(function (p) { return p.in.includes(\"body\"); });\n filteredBodyModel.forEach(function (p) { return bodyModel.push(p.name); });\n //bodyModel = JSON.stringify(bodyModel);\n bodyModel = bodyModel.join(\", \");\n //summary\n summary = summary.replaceAll(\",\", \";\"); // replaces , with ; to avoid csv chaos\n // create report\n report.push({\n //tag,\n path: path,\n operationId: operationId,\n summary: summary,\n \"product tags.0\": paths[path][p][\"tags\"][0],\n \"category tags.1\": paths[path][p][\"tags\"][1],\n \"service tags.2\": paths[path][p][\"tags\"][1],\n method: method,\n pathParams: pathParams,\n queryParams: queryParams,\n example_200: example_200,\n example_201: example_201,\n //j bodyModel\n //description //this data has chararcter conflicts with the sheet\n });\n });\n // sort order based on group tag name.\n report = report.sort(function (a, b) {\n if (a.tag < b.tag)\n return -1;\n if (a.tag > b.tag)\n return 1;\n return 0;\n });\n });\n return report;\n }\n catch (error) {\n return error;\n //throw (error, \"parseSwaggerPaths\");\n }\n}",
"function convertSwagger(source){\n var apiInfo = clone(source,false);\n apiInfo.resources = {};\n\n\tif (apiInfo.servers && apiInfo.servers.length) {\n\t\tvar u = url.parse(apiInfo.servers[0].url);\n\t\tapiInfo.host = u.host;\n\t\tapiInfo.basePath = u.path;\n\t\tapiInfo.schemes = [];\n\t\tapiInfo.schemes.push(u.protocol.replace(':',''));\n\t}\n\n for (var p in apiInfo.paths) {\n for (var m in apiInfo.paths[p]) {\n if ('.get.post.put.delete.head.patch.options.trace.'.indexOf(m)>=0) {\n var sMethod = apiInfo.paths[p][m];\n var ioMethod = {};\n ioMethod.httpMethod = m.toUpperCase();\n var sMethodUniqueName = sMethod.operationId ? sMethod.operationId : m+'_'+p.split('/').join('_');\n sMethodUniqueName = sMethodUniqueName.split(' ').join('_'); // TODO {, } and : ?\n ioMethod.name = sMethodUniqueName;\n ioMethod.summary = sMethod.summary;\n ioMethod.description = sMethod.description;\n ioMethod.parameters = {};\n var sParams = sMethod.parameters ? sMethod.parameters : [];\n if (apiInfo.paths[p].parameters) {\n sParams = sParams.concat(apiInfo.paths[p].parameters);\n }\n for (var p2 in sParams) {\n var param = sParams[p2];\n var ptr = param[\"$ref\"];\n if (ptr && ptr.startsWith('#/parameters/')) {\n ptr = ptr.replace('#/parameters/','');\n param = clone(apiInfo.parameters[ptr],false);\n }\n if (ptr && ptr.startsWith('#/components/parameters/')) {\n ptr = ptr.replace('#/components/parameters/','');\n param = clone(apiInfo.components.parameters[ptr],false);\n }\n param.location = param[\"in\"];\n delete param[\"in\"];\n\t\t\t\t\tif (!param.type && param.schema && param.schema.type) {\n\t\t\t\t\t\tparam.type = param.schema.type;\n\t\t\t\t\t}\n ioMethod.parameters[param.name] = param;\n }\n ioMethod.path = p;\n ioMethod.responses = sMethod.responses;\n var tagName = 'Default';\n if (sMethod.tags && sMethod.tags.length>0) {\n tagName = sMethod.tags[0];\n }\n if (!apiInfo.resources[tagName]) {\n apiInfo.resources[tagName] = {};\n if (apiInfo.tags) {\n for (var t in apiInfo.tags) {\n var tag = apiInfo.tags[t];\n if (tag.name == tagName) {\n apiInfo.resources[tagName].description = tag.description;\n apiInfo.resources[tagName].externalDocs = tag.externalDocs;\n }\n }\n }\n }\n if (!apiInfo.resources[tagName].methods) apiInfo.resources[tagName].methods = {};\n apiInfo.resources[tagName].methods[sMethodUniqueName] = ioMethod;\n }\n }\n }\n delete apiInfo.paths; // to keep size down\n if (apiInfo.definitions) rename(apiInfo,'definitions','schemas');\n if (apiInfo.components && apiInfo.components.schemas) rename(apiInfo,'components.schemas','schemas');\n return apiInfo;\n}",
"function convertToOpenAPI(info, data) {\n const builder = new openapi3_ts_1.OpenApiBuilder();\n builder.addInfo(Object.assign(Object.assign({}, info.base), { title: info.base.title || '[untitled]', version: info.base.version || '0.0.0' }));\n info.contact && builder.addContact(info.contact);\n const tags = [];\n const paths = {};\n let typeCount = 1;\n const schemas = {};\n data.forEach(item => {\n [].concat(item.url).forEach(url => {\n if (typeof url !== 'string') {\n // TODO\n return;\n }\n url = url\n .split('/')\n .map((item) => (item.startsWith(':') ? `{${item.substr(1)}}` : item))\n .join('/');\n if (!tags.find(t => t.name === item.typeGlobalName)) {\n const ctrlMeta = controller_1.getControllerMetadata(item.typeClass);\n tags.push({\n name: item.typeGlobalName,\n description: (ctrlMeta && [ctrlMeta.name, ctrlMeta.description].filter(s => s).join(' ')) ||\n undefined,\n });\n }\n if (!paths[url]) {\n paths[url] = {};\n }\n [].concat(item.method).forEach((method) => {\n method = method.toLowerCase();\n function paramFilter(p) {\n if (p.source === 'Any') {\n return ['post', 'put'].every(m => m !== method);\n }\n return p.source !== 'Body';\n }\n function convertValidateToSchema(validateType) {\n if (validateType === 'string') {\n return {\n type: 'string',\n };\n }\n if (validateType === 'int' || validateType === 'number') {\n return {\n type: 'number',\n };\n }\n if (validateType.type === 'object' && validateType.rule) {\n let properties = {};\n const required = [];\n Object.keys(validateType.rule).forEach(key => {\n const rule = validateType.rule[key];\n properties[key] = convertValidateToSchema(rule);\n if (rule.required !== false) {\n required.push(key);\n }\n });\n const typeName = `GenType_${typeCount++}`;\n builder.addSchema(typeName, {\n type: validateType.type,\n required: required,\n properties,\n });\n return {\n $ref: `#/components/schemas/${typeName}`,\n };\n }\n if (validateType.type === 'enum') {\n return {\n type: 'string',\n };\n }\n return {\n type: validateType.type,\n items: validateType.itemType\n ? validateType.itemType === 'object'\n ? convertValidateToSchema({ type: 'object', rule: validateType.rule })\n : { type: validateType.itemType }\n : undefined,\n enum: Array.isArray(validateType.values)\n ? validateType.values.map(v => convertValidateToSchema(v))\n : undefined,\n maximum: validateType.max,\n minimum: validateType.min,\n };\n }\n function getTypeSchema(p) {\n if (p.schema) {\n return p.schema;\n }\n else if (p.validateType && p.validateType.type) {\n return convertValidateToSchema(p.validateType);\n }\n else {\n const type = utils_1.getGlobalType(p.type);\n const isSimpleType = ['array', 'boolean', 'integer', 'number', 'object', 'string'].some(t => t === type.toLowerCase());\n // TODO complex type process\n return {\n type: isSimpleType ? type.toLowerCase() : 'object',\n items: type === 'Array'\n ? {\n type: 'object',\n }\n : undefined,\n };\n }\n }\n // add schema\n const components = item.schemas.components || {};\n Object.keys(components).forEach(typeName => {\n if (schemas[typeName] && schemas[typeName].hashCode !== components[typeName].hashCode) {\n console.warn(`[egg-controller] type: [${typeName}] has multi defined!`);\n return;\n }\n schemas[typeName] = components[typeName];\n });\n // param\n const inParam = item.paramTypes.filter(paramFilter);\n // req body\n const inBody = item.paramTypes.filter(p => !paramFilter(p));\n let requestBody;\n if (inBody.length) {\n const requestBodySchema = {\n type: 'object',\n properties: {},\n };\n inBody.forEach(p => {\n if (p.required || util_1.getValue(() => p.validateType.required)) {\n if (!requestBodySchema.required) {\n requestBodySchema.required = [];\n }\n requestBodySchema.required.push(p.paramName);\n }\n requestBodySchema.properties[p.paramName] = getTypeSchema(p);\n });\n const reqMediaType = 'application/json';\n requestBody = {\n content: {\n [reqMediaType]: {\n schema: requestBodySchema,\n },\n },\n };\n }\n // res\n let responseSchema = item.schemas.response || {};\n const refTypeName = responseSchema.$ref;\n if (refTypeName) {\n const definition = item.schemas.components[refTypeName.replace('#/components/schemas/', '')];\n if (definition) {\n responseSchema = { $ref: refTypeName };\n }\n else {\n console.warn(`[egg-controller] NotFound {${refTypeName}} in components.`);\n responseSchema = { type: 'any' };\n }\n }\n const responses = {\n default: {\n description: 'default',\n content: {\n 'application/json': {\n schema: responseSchema,\n },\n },\n },\n };\n paths[url][method] = {\n operationId: item.functionName,\n tags: [item.typeGlobalName],\n summary: item.name,\n description: item.description,\n parameters: inParam.length\n ? inParam.map(p => {\n const source = p.source === 'Header' ? 'header' : p.source === 'Param' ? 'path' : 'query';\n return {\n name: p.paramName,\n in: source,\n required: source === 'path' || p.required || util_1.getValue(() => p.validateType.required),\n schema: getTypeSchema(p),\n };\n })\n : undefined,\n requestBody,\n responses,\n };\n });\n });\n });\n // add schema\n Object.keys(schemas).forEach(key => {\n delete schemas[key].hashCode;\n builder.addSchema(key, schemas[key]);\n });\n tags.forEach(tag => builder.addTag(tag));\n Object.keys(paths).forEach(path => builder.addPath(path, paths[path]));\n return JSON.parse(builder.getSpecAsJson());\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
=======================FUNCTIONS ====================== =======================FUNCTIONS ====================== deatils : handle page reset | function pageReset(){
setPage({
currPage:1,
pageLoaded:[1]
})
} | [
"resetPage() {\n let tf = this.tf;\n if (!this.isEnabled()) {\n return;\n }\n this.emitter.emit('before-reset-page', tf);\n let pgNb = tf.feature('store').getPageNb();\n if (pgNb !== '') {\n this.changePage((pgNb - 1));\n }\n this.emitter.emit('after-reset-page', tf, pgNb);\n }",
"resetPage()\n {\n this._currentDirectoryPage = 1;\n }",
"reset() {\n this.pageCollection.reset();\n this.onReset.next();\n }",
"function _resetPage($el) {\n\n var id = $el.data('page');\n\n $currPage = $el.data('currPage');\n $nextPage = $(id);\n }",
"function resetThePage () {\n localStorage.clear();\n location.reload();\n window.scrollTo(0, 0);\n}",
"function resetPage() {\n clearAllCards();\n buildAllCards();\n moveCounter = 0;\n matchedCounter = 0;\n updateMoveCounter();\n renewStars();\n isGameStarted = false;\n}",
"function resetPages(done) {\n panini.refresh()\n done()\n}",
"function resetPage () {\r\n\r\n\t\t//empty vinText\r\n\t\t// $(\"#vinText\").removeAttr(\"disabled\");\r\n\t\t// $(\"#vinText\").attr(\"value\",\"\");\r\n\t\t// //聚焦到vin输入框上\r\n\t\t// $(\"#vinText\").focus();\r\n\t\t// //to show vin input hint\r\n\t\t// toggleVinHint(true);\r\n\t\t//disable submit button\r\n\t\t// $(\"#btnSubmit\").attr(\"disabled\",\"disabled\");\r\n\t}",
"function resetPage () {\r\n\t\t//empty vinText\r\n\t\t$(\"#vinText\").removeAttr(\"disabled\");\r\n\t\t$(\"#vinText\").attr(\"value\",\"\");\r\n\t\t//聚焦到vin输入框上\r\n\t\t$(\"#vinText\").focus();\r\n\t\t//to show vin input hint\r\n\t\ttoggleVinHint(true);\r\n\t\t//disable submit button\r\n\t\t$(\"#btnSubmit\").attr(\"disabled\",\"disabled\");\r\n\t\t$(\"#tableConfirmation tbody\").text(\"\");\r\n\t}",
"function resetPage() {\n resultsPage = 1; //reset page\n $('#initialPage').val(1);\n }",
"function resetPage () {\r\n\t\t$(\"#vinText\").removeAttr(\"disabled\").val(\"\").focus();\r\n\t\ttoggleVinHint(true);\r\n\t\t$(\"#btnSubmit\").attr(\"disabled\",\"disabled\");\r\n\t\t$('#compCodeText').val(\"\").attr(\"disabled\",\"disabled\");\t\t//added by wujun\r\n\t\t$(\"#componentTable tbody\").text(\"\");\r\n\t\trecordArray = [];\r\n\t}",
"function resetPage() {\r\n resultsSection.innerHTML = \"\";\r\n backButton.innerHTML = \"\";\r\n}",
"function resetPage(){\n BREEDARRAY = [];\n clearCardDeck();\n clearBarDeck();\n main();\n}",
"function resetPageData(){\n\t\tpageData.xhr = false;\n\t\tpageData.pagination = 1;\n\t\tpageData.endofrecord = false;\n\t}",
"function resetHandler() {\n calendar.cfg.setProperty(\"pagedate\", calendar.today);\n calendar.render();\n }",
"function resetPage () {\r\n\t\t//empty vinText\r\n\t\t$(\"#vinText\").removeAttr(\"disabled\").val(\"\");\r\n\t\t$(\"#checker, #subChecker\").attr(\"value\",\"\");\r\n\t\t$(\"#checkTime\").val(window.byd.DateUtil.currentTime);\r\n\t\t//聚焦到vin输入框上\r\n\t\t$(\"#vinText\").focus();\r\n\t\t//to show vin input hint\r\n\t\ttoggleVinHint(true);\r\n\t\t//disable submit button\r\n\t\t$(\"#btnSubmit, #checker, #subChecker, #checkTime\").attr(\"disabled\",\"disabled\");\r\n\t\t$(\"#divDetail\").hide();\r\n\t\t//init all\r\n\r\n\t\t// $(\"#formBag\").hide();\r\n\t\t\r\n\t\tif (dutyOption != \"\") {\r\n\t\t\t//初始化 ‘其他’栏\r\n\t\t\t$(\"#tableOther tbody\").text(\"\");\r\n\t\t\tfor (var i = 0; i < 10; i++) {\r\n\t\t\t\tvar indexTd = \"<td>\" + (i + 1) + \"</td>\";\r\n\t\t\t\tvar nameTd = \"<td><input type='text' /></td>\";\r\n\t\t\t\tvar optionTd = \"<td>\" + '<select disabled=\"disabled\" class=\"fault-type\"><option value=\"\">-请选择故障-</option></select>' + \"</td>\";\r\n\t\t\t\t//注释掉,路试结束没有checkbox\r\n\t\t\t\t// var checkTd = '<td><input type=\"checkbox\" value=\"\" disabled=\"disabled\"></td>';\r\n\t\t\t\t$(\"#tableOther tbody\").append(\"<tr>\" + indexTd + nameTd + optionTd + dutyOption + \"</tr>\");\r\n\t\t\t\t// $(\"#tableOther tbody\").append(\"<tr>\" + indexTd + nameTd + optionTd + checkTd + \"</tr>\");\r\n\t\t\t};\r\n\t\t}\r\n\t\t$(\"#tableGeneral tbody\").text(\"\");\r\n\t}",
"function resetpagefiels(){\n document.getElementById(\"hidprevid\").value = 0;\n document.getElementById(\"hidnextid\").value = 10;\n document.getElementById(\"gotopageid\").value = \"\";\n }",
"function resetPage() {\n setTimeout(function() {\n location.reload(true);\n }, 3000);\n}",
"function pageReset (evt) {\n colour.value = '#000000';\n inputWidth.value = \"1\";\n inputHeight.value = \"1\";\n location.reload()\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
problem 4 smallest multiple | function smallestMultiple(n) {
var tmp, i;
var union = {};
var factors = {};
var product = 1;
for(i = 2; i <= n; i++) {
tmp = primeFactorization(i);
factors = {};
tmp.forEach(function(factor) {
if(!factors[factor]) {
factors[factor] = 0;
}
factors[factor] += 1;
});
_.each(factors, function(count, factor) {
if(!union[factor]) {
union[factor] = count;
}
else if(union[factor] < count){
union[factor] = count;
}
});
}
_.each(union, function(count, factor) {
product *= Math.pow(factor, count);
});
return product;
} | [
"function smallestMultiple() {\n for (var small = 2520; small>1; small++) {\n for (var i = 1; i <= 20; i++) {\n if (small % i !== 0) {\n break;\n }\n }\n if (small % i === 0) {\n return small;\n break;\n }\n }\n}",
"function smallestMult(n) {\n\n let leastCommonMultiple = n;\n let factor = n - 1;\n\n for (factor; factor > 1; --factor) {\n n = leastCommonMultiple;\n while (leastCommonMultiple % factor) {\n leastCommonMultiple += n;\n }\n }\n\n return leastCommonMultiple;\n}",
"function smallestMult(n) {\n\n // start number from the biggest\n let result = n - 1;\n\n let found;\n let counter = 0;\n\n // increase the result by one until the number is not fully divisible by the numbers\n do {\n result++;\n\n // check if number is divisible by all numbers or not\n found = true;\n for (let i = 2; i <= n; i++) {\n if (result % i !== 0) {\n found = false;\n break;\n }\n counter++;\n }\n\n } while (!found);\n\n console.log(`Iterations: ${counter}`);\n return result;\n\n}",
"function smallestMult(n) {\n // Good luck!\n let arr = new Array(n).fill(1);\n arr = arr.map((elem, i) => i + 1);\n let number;\n if (n < 5) {\n number = n * (n - 1);\n while(arr.some(elem => number % elem !== 0)) {\n number++;\n }\n } else {\n number = 20;\n while(arr.some(elem => number % elem !== 0)) {\n number = number + 10;\n }\n }\n return number;\n}",
"function smallestMult(n) {\n let result = 1;\n for (let i=2; i<=n; i++)\n result = twoLCM(result, i);\n return result;\n}",
"function smallestMultiple() {\n var acc = false;\n var n = 2520;\n while (!acc) {\n isDivisibleToY(n, 20) ? acc = true : n++\n }\n return n;\n}",
"function findSmallestMultipleOfTwenty() {\n for ( var i = 20; i <= 1000000000; i+= 20 ) {\n found = false;\n for ( var e = 2; e <= 20; e++){\n if (i % e != 0) {\n found = true;\n break; // stop testing other divisors\n }\n }\n if (!found) {\n return i;\n };\n };\n}",
"function smallestMultiple(maxMultipler) {\n let maxMultiplierFactorial = factorial(maxMultipler);\n let smallestMultiple = maxMultiplierFactorial;\n if (verbose) {\n console.log('smallestMultiple() -> maxMultipler:', maxMultipler);\n console.log('smallestMultiple() -> maxMultiplierFactorial:', maxMultiplierFactorial);\n console.log('smallestMultiple() -> smallestMultiple:', smallestMultiple);\n }\n for (let startingMultiple = (maxMultiplierFactorial - maxMultipler); startingMultiple > 1; startingMultiple -= maxMultipler) {\n if (verbose) {\n console.log('smallestMultiple() -> startingMultiple:', startingMultiple);\n }\n for (let counter = (maxMultipler - 1); counter > 1; counter--) {\n if (verbose) {\n console.log('smallestMultiple() -> counter:', counter);\n }\n if (!isEven(startingMultiple)) {\n if (verbose) {\n console.log('smallestMultiple() ->', startingMultiple, 'is not an even number');\n console.log('smallestMultiple() -> starting next iteration of outer for loop');\n }\n break;\n }\n if (startingMultiple > 5 && !multipleOfFive(startingMultiple)) {\n if (verbose) {\n console.log('smallestMultiple() ->', startingMultiple, 'is greater than 5');\n console.log('smallestMultiple() ->', startingMultiple, 'is not a multiple of 5');\n console.log('smallestMultiple() -> starting next iteration of outer for loop');\n }\n break;\n }\n if (startingMultiple % counter !== 0) {\n if (verbose) {\n console.log('smallestMultiple() ->', startingMultiple, '%', counter, '!== 0');\n console.log('smallestMultiple() -> starting next iteration of outer for loop');\n }\n break;\n }\n if (verbose) {\n console.log('smallestMultiple() ->', startingMultiple, '%', counter, '=== 0');\n }\n if (counter === 2) {\n smallestMultiple = startingMultiple;\n if (verbose) {\n console.log('smallestMultiple() -> smallestMultiple:', smallestMultiple);\n }\n }\n }\n }\n return smallestMultiple;\n}",
"_closestMultiple(n, x) {\n if (x > n)\n return x;\n n = n + x / 2;\n n = n - (n % x);\n return n;\n }",
"function solution(number){\n let multiple = 0;\n for (let i = 0; i < number; i++){\n if (i % 3 === 0 || i % 5 === 0){\n multiple += i;\n\n }\n }\n return multiple\n}",
"function smallestMultiple(maxDivisor) {\n\tvar outerIndex, innerIndex;\n\n\tfor (outerIndex = maxDivisor; 1; outerIndex ++) {\n\t\tfor (innerIndex = 2; innerIndex <= maxDivisor; innerIndex++) {\n\t\t\tif (outerIndex % innerIndex) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (innerIndex === maxDivisor) {\n\t\t\t\treturn outerIndex;\n\t\t\t}\n\t\t}\n\t}\n}",
"function multEasy(n1,n2,n3,n4) {\n console.log(n1*n2*n3*n4)\n}",
"function MultOf3And5(number){\n let sumNumbers = 0;\n if (number < 1) return 0;\n for (let i = 1; i < number; i++)\n {\n if (i % 3 == 0 || i % 5 == 0) { sumNumbers += i; }\n }\n return sumNumbers;\n}",
"function multiOf(num1,num2,num3)\r\n{\r\n if(num3 === 1)\r\n {\r\n return (num2 *num2)\r\n }\r\n multiOf(num1,num2,num3)\r\n}",
"function multiOf(number1,number2,number3){\n if(number3===0){\n return number1;\n }\n return number2 * multiOf(number1,number2,number3-1);\n }",
"function solution(number) {\n let multiples = [];\n for (let i = 1; i < number; ++i) {\n if (i % 3 === 0 || i % 5 === 0) {\n multiples.push(i);\n }\n }\n return multiples.reduce((a, b) => a + b, 0);\n}",
"function minimumMultiplcations(n) {\n let min = 10**7;\n let factors = getProperDivisors(n);\n for (const [x, y] of factors) {\n if (m[x] + m[y] < min) {\n min = m[x] + m[y];\n }\n }\n // for (let i = 1; i <= n / 2; i++) {\n // if (m[i] + m[n - i] < min) {\n // min = m[i] + m[n - i];\n // console.log(i, n - i, m[i], m[n - i], min);\n\n // }\n // }\n m[n] = min;\n}",
"function smallestCommons(arr) {\nlet max = Math.max(arr[0],arr[1]);\nlet min = Math.min(arr[0],arr[1]);\n//console.log(max + \" & \" + min);//Debugging\n\n function smallComMulti(a, b){ //find smallest Common Multiple\n for(var i = 1; i <= b; i++){ \n if((i * a) % b === 0){\n //console.log(i * a);//Debugging\n return (i * a);\n }\n } \n }; \n let myNum = smallComMulti(max, min);\n for(var ii = min + 1; ii < max; ii++) { \n myNum = smallComMulti(myNum, ii); \n }\n console.log(myNum);\n return myNum;\n}",
"function multiOf(num1,num2,num3 ){\n\n if (num3===0){\n return num1;\n\n }\n \n \n return num2*multiOf(num1, num2,num3-1);\n \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
convert mixed [ sw, ne ] object by gm.LatLngBounds | function toLatLngBounds(mixed) {
var ne, sw;
if (!mixed || mixed instanceof gm.LatLngBounds) {
return mixed || null;
}
if (isArray(mixed)) {
if (mixed.length === 2) {
ne = toLatLng(mixed[0]);
sw = toLatLng(mixed[1]);
} else if (mixed.length === 4) {
ne = toLatLng([mixed[0], mixed[1]]);
sw = toLatLng([mixed[2], mixed[3]]);
}
} else {
if (("ne" in mixed) && ("sw" in mixed)) {
ne = toLatLng(mixed.ne);
sw = toLatLng(mixed.sw);
} else if (("n" in mixed) && ("e" in mixed) && ("s" in mixed) && ("w" in mixed)) {
ne = toLatLng([mixed.n, mixed.e]);
sw = toLatLng([mixed.s, mixed.w]);
}
}
if (ne && sw) {
return new gm.LatLngBounds(sw, ne);
}
return null;
} | [
"function toLatLngBounds(mixed){\n var ne, sw;\n if (!mixed || mixed instanceof google.maps.LatLngBounds) {\n return mixed || null;\n }\n if ($.isArray(mixed)){\n if (mixed.length == 2){\n ne = toLatLng(mixed[0]);\n sw = toLatLng(mixed[1]);\n } else if (mixed.length == 4){\n ne = toLatLng([mixed[0], mixed[1]]);\n sw = toLatLng([mixed[2], mixed[3]]);\n }\n } else {\n if ( (\"ne\" in mixed) && (\"sw\" in mixed) ){\n ne = toLatLng(mixed.ne);\n sw = toLatLng(mixed.sw);\n } else if ( (\"n\" in mixed) && (\"e\" in mixed) && (\"s\" in mixed) && (\"w\" in mixed) ){\n ne = toLatLng([mixed.n, mixed.e]);\n sw = toLatLng([mixed.s, mixed.w]);\n }\n }\n if (ne && sw){\n return new google.maps.LatLngBounds(sw, ne);\n }\n return null;\n }",
"function toLatLngBounds(mixed) {\n var ne, sw;\n if (!mixed || mixed instanceof gm.LatLngBounds) {\n return mixed || null;\n }\n if (isArray(mixed)) {\n if (mixed.length === 2) {\n ne = toLatLng(mixed[0]);\n sw = toLatLng(mixed[1]);\n } else if (mixed.length === 4) {\n ne = toLatLng([mixed[0], mixed[1]]);\n sw = toLatLng([mixed[2], mixed[3]]);\n }\n } else {\n if ((\"ne\" in mixed) && (\"sw\" in mixed)) {\n ne = toLatLng(mixed.ne);\n sw = toLatLng(mixed.sw);\n } else if ((\"n\" in mixed) && (\"e\" in mixed) && (\"s\" in mixed) && (\"w\" in mixed)) {\n ne = toLatLng([mixed.n, mixed.e]);\n sw = toLatLng([mixed.s, mixed.w]);\n }\n }\n if (ne && sw) {\n return new gm.LatLngBounds(sw, ne);\n }\n return null;\n }",
"function toLatLngBounds(mixed){\r\n var ne, sw;\r\n if (!mixed || mixed instanceof google.maps.LatLngBounds) {\r\n return mixed || null;\r\n }\r\n if ($.isArray(mixed)){\r\n if (mixed.length == 2){\r\n ne = toLatLng(mixed[0]);\r\n sw = toLatLng(mixed[1]);\r\n } else if (mixed.length == 4){\r\n ne = toLatLng([mixed[0], mixed[1]]);\r\n sw = toLatLng([mixed[2], mixed[3]]);\r\n }\r\n } else {\r\n if ( (\"ne\" in mixed) && (\"sw\" in mixed) ){\r\n ne = toLatLng(mixed.ne);\r\n sw = toLatLng(mixed.sw);\r\n } else if ( (\"n\" in mixed) && (\"e\" in mixed) && (\"s\" in mixed) && (\"w\" in mixed) ){\r\n ne = toLatLng([mixed.n, mixed.e]);\r\n sw = toLatLng([mixed.s, mixed.w]);\r\n }\r\n }\r\n if (ne && sw){\r\n return new google.maps.LatLngBounds(sw, ne);\r\n }\r\n return null;\r\n }",
"function gbounds2bounds(boundsObj) {\n if(!boundsObj) return [];\n var ne = boundsObj.getNorthEast();\n var sw = boundsObj.getSouthWest();\n\n var g_loc_accuracy = 4; \n\n var lat0 = sw ? parseFloat(sw.lat()).toFixed(g_loc_accuracy) : 0;\n var lng0 = sw ? parseFloat(sw.lng()).toFixed(g_loc_accuracy) : 0;\n var lat1 = ne ? parseFloat(ne .lat()).toFixed(g_loc_accuracy) : 0;\n var lng1 = ne ? parseFloat(ne .lng()).toFixed(g_loc_accuracy) : 0;\n return [[lat0,lng0],[lat1,lng1]];\n}",
"function convertBounds(bounds){\n\t return [\n\t llToGeoJsonArray(bounds.getNorthEast()),\n\t llToGeoJsonArray(bounds.getNorthWest()),\n\t llToGeoJsonArray(bounds.getSouthWest()),\n\t llToGeoJsonArray(bounds.getSouthEast()),\n\t llToGeoJsonArray(bounds.getNorthEast())\n\t ];\n\t}",
"function getLngBoundsForSingleCoordinate(a){var b=a[0]-PADDING<GEO_BOUNDS.LNG_MIN?GEO_BOUNDS.LNG_MIN:a[0]-PADDING,c=a[1]+PADDING>GEO_BOUNDS.LNG_MAX?GEO_BOUNDS.LNG_MAX:a[1]+PADDING;return[b,c]}",
"function get_bounds(){\n\t\t\t\t\n\t\t\t\treturn {\n\t\t\t\t\t\n\t\t\t\t\tsw_lat : map.getBounds().getSouthWest().lat(),\n\t\t\t\t\t\n\t\t\t\t\tsw_lng : map.getBounds().getSouthWest().lng(),\n\t\t\t\t\t\n\t\t\t\t\tne_lat : map.getBounds().getNorthEast().lat(),\n\t\t\t\t\t\n\t\t\t\t\tne_lng : map.getBounds().getNorthEast().lng()\n\t\t\t\t\n\t\t\t\t};\n\t\t\t\n\t\t\t}",
"function constructBounds(bounds) {\n const [northeast, southwest] = Object.keys(bounds);\n return {\n northeast: { lat: bounds[northeast].j || 37.5, lng: bounds[southwest].j || -121.9 },\n southwest: { lat: bounds[northeast].i || 37.5, lng: bounds[southwest].i || -122 }\n };\n}",
"function CreateBoundsPolygon(ne, sw) {\n var x1 = ne.lng();\n var y1 = ne.lat();\n var x2 = sw.lng();\n var y2 = sw.lat();\n\n var boundCoords = [\n new google.maps.LatLng(y1, x1),\n new google.maps.LatLng(y2, x1),\n new google.maps.LatLng(y2, x2),\n new google.maps.LatLng(y1, x2),\n new google.maps.LatLng(y1, x1)\n ];\n\n //Bermuda Triangle Test\n var triangleCoords = [new google.maps.LatLng(25.774252, -80.190262), new google.maps.LatLng(18.466465, -66.118292), new google.maps.LatLng(32.321384, -64.75737), new google.maps.LatLng(25.774252, -80.190262)];\n\n return boundCoords;\n}",
"function boundsFromPairs(rect) {\n return (rect && rect.swLat)?[[rect.swLat,rect.swLon],[rect.neLat,rect.neLon]]:null\n}",
"function getBoundaryForArray(tmpArr)\n{\n var boundary = new google.maps.LatLngBounds(); \n for(i = 0; i < tmpArr.length; i++)\n boundary.extend(tmpArr[i]);\n return boundary;\n}",
"function serializeBounds (bounds) {\n var\n sw = bounds.getSouthWest(),\n ne = bounds.getNorthEast();\n return [sw.lat(), sw.lng(), ne.lat(), ne.lng()].join(',');\n }",
"function boundsToExtent (bounds) {\r\n bounds = Object(leaflet__WEBPACK_IMPORTED_MODULE_0__[\"latLngBounds\"])(bounds);\r\n return {\r\n 'xmin': bounds.getSouthWest().lng,\r\n 'ymin': bounds.getSouthWest().lat,\r\n 'xmax': bounds.getNorthEast().lng,\r\n 'ymax': bounds.getNorthEast().lat,\r\n 'spatialReference': {\r\n 'wkid': 4326\r\n }\r\n };\r\n}",
"_tileBoundsFromWGS84(boundsWGS84) {\n var sw = this._layer._world.latLonToPoint(LatLon(boundsWGS84[1], boundsWGS84[0]));\n var ne = this._layer._world.latLonToPoint(LatLon(boundsWGS84[3], boundsWGS84[2]));\n\n return [sw.x, sw.y, ne.x, ne.y];\n }",
"function boundsToExtent(bounds) {\n bounds = L.latLngBounds(bounds);\n return {\n 'xmin': bounds.getSouthWest().lng,\n 'ymin': bounds.getSouthWest().lat,\n 'xmax': bounds.getNorthEast().lng,\n 'ymax': bounds.getNorthEast().lat,\n 'spatialReference': {\n 'wkid': 4326\n }\n };\n}",
"getLatLngBounds() {\n let bounds = new google.maps.LatLngBounds();\n // If the flight is big just having the two end points will cut off part of the route\n for(let i = 0; i <= 1; i+= 0.1) {\n bounds.extend(this.getIntermediatePoint(i));\n }\n return bounds;\n }",
"getLatLngBounds (data) {\n\t\tdata = data || this._data;\n\t\tif (data.length < 1) return null;\n\t\treturn L.latLngBounds(data.map((d) => {\n\t\t\treturn [d[this._latField], d[this._lngField]];\n\t\t}));\n\t}",
"function encodeBounds(bounds) {\n\tconst southwest = bounds.southwest;\n\tconst northeast = bounds.northeast;\n\treturn `${encodeURIComponent(southwest.lat)},${encodeURIComponent(southwest.lng)}|${encodeURIComponent(northeast.lat)},${encodeURIComponent(northeast.lng)}`;\n}",
"function boundsToExtent(bounds) {\n bounds = leaflet.latLngBounds(bounds);\n return {\n 'xmin': bounds.getSouthWest().lng,\n 'ymin': bounds.getSouthWest().lat,\n 'xmax': bounds.getNorthEast().lng,\n 'ymax': bounds.getNorthEast().lat,\n 'spatialReference': {\n 'wkid': 4326\n }\n };\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
When true, the virtual paging feature is enabled because the virtual content size exceed the supported height of the browser so paging is enable. | get virtualPagingActive() { var _a, _b; return (_b = (_a = this.heightPaging) === null || _a === void 0 ? void 0 : _a.active) !== null && _b !== void 0 ? _b : false; } | [
"verticalPagingPossible() {\n return this.contentSize.height > this.height;\n }",
"get _optPhysicalSize(){return this._viewportHeight===0?Infinity:this._viewportHeight*this._maxPages;}",
"get _optPhysicalSize() {\n return this._viewportHeight === 0 ? Infinity : this._viewportHeight * this._maxPages;\n }",
"horizontalPagingPossible() {\n return this.contentSize.width > this.width;\n }",
"get _optPhysicalSize() {\n return this._viewportHeight === 0 ? Infinity : this._viewportHeight * this._maxPages;\n }",
"get _optPhysicalSize(){return 0===this._viewportHeight?1/0:this._viewportHeight*this._maxPages}",
"hasNextPage() {\n const maxPageIndex = this.getNumberOfPages() - 1;\n return this.pageIndex < maxPageIndex && this.pageSize != 0;\n }",
"checkPaginationEnabled() {\n if (this.disablePagination || this.vertical) {\n this.showPaginationControls = false;\n }\n else {\n const isEnabled = this.tabList.nativeElement.scrollWidth > this.elementRef.nativeElement.offsetWidth;\n if (!isEnabled) {\n this.scrollDistance = 0;\n }\n if (isEnabled !== this.showPaginationControls) {\n this.changeDetectorRef.markForCheck();\n }\n this.showPaginationControls = isEnabled;\n }\n }",
"shouldShowPagination() {\n return (\n this.disablePagination !== true &&\n this.resourceResponse &&\n this.hasResources\n )\n }",
"setVirtualPhantomHeight() {\n let totalHeight = 0;\n if (this.virtualScrollPositions.length) {\n totalHeight =\n this.virtualScrollPositions[\n this.virtualScrollPositions.length - 1\n ].bottom;\n }\n\n this.$refs[this.virtualPhantomRef].style.height =\n totalHeight + \"px\";\n }",
"function setPropertyPageHeight(val) {\n _pageHeight = val;\n //resizeCanvas();\n }",
"function setPropertyPageHeight(val) {\n _pageHeight = val;\n }",
"_checkPaginationEnabled() {\n if (this.disablePagination) {\n this._showPaginationControls = false;\n }\n else {\n const isEnabled = this._tabList.nativeElement.scrollWidth > this._elementRef.nativeElement.offsetWidth;\n if (!isEnabled) {\n this.scrollDistance = 0;\n }\n if (isEnabled !== this._showPaginationControls) {\n this._changeDetectorRef.markForCheck();\n }\n this._showPaginationControls = isEnabled;\n }\n }",
"function pageHeight() {\n return document.body.scrollHeight;\n}",
"virtualScrollBufferCount() {\n const { virtualScrollOption, defaultVirtualScrollBufferCount } =\n this;\n\n let result = defaultVirtualScrollBufferCount;\n if (virtualScrollOption) {\n const { bufferCount } = virtualScrollOption;\n if (\n isNumber(bufferCount) &&\n bufferCount > defaultVirtualScrollBufferCount\n ) {\n result = bufferCount;\n }\n }\n\n return result;\n }",
"_checkPaginationEnabled() {\n if (this.disablePagination) {\n this._showPaginationControls = false;\n }\n else {\n const isEnabled = this._tabListInner.nativeElement.scrollWidth > this._elementRef.nativeElement.offsetWidth;\n if (!isEnabled) {\n this.scrollDistance = 0;\n }\n if (isEnabled !== this._showPaginationControls) {\n this._changeDetectorRef.markForCheck();\n }\n this._showPaginationControls = isEnabled;\n }\n }",
"get hidePageSize() { return this._hidePageSize; }",
"function Blotter_InfiniteScrollingCheckForMoreContent()\n{\n\tif ( !g_BlotterNextLoadURL )\n\t\treturn;\n\n\tvar viewport = document.viewport.getDimensions(); // Gets the viewport as an object literal\n\tvar windowHeight = viewport.height; // Usable window height\n\n\tvar scrollOffset = document.viewport.getScrollOffsets();\n\tvar scrollTop = scrollOffset.top;\n\n\tvar bodyHeight = $('blotter_content').getHeight();\n\n\t// number of pixels from the bottom before checking for more content\n\t// this should be about two rows of content\n\tvar buffer = 600;\n\tif ( scrollTop + buffer > bodyHeight - windowHeight )\n\t{\n\t\tStartLoadingBlotter( g_BlotterNextLoadURL );\n\t}\n}",
"get virtualModeEnabled() {\n return this._getOption('virtualModeEnabled');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
OBSERVER IMPLEMENTATION // Controller will serve as the central point of contact, updating components | function Controller() {
var subject = new Subject();
this.attachObserver = function attachObserver(observer) {
subject.attachObserver(observer);
};
this.detachObserver = function detachObserver(observer) {
subject.detachObserver(observer);
};
this.updateObservers = function update(args) {
if(args === void 0) {
args = {};
}
subject.updateObservers(args);
};
} | [
"initController(event) { \n //this.controller = event.detail;\n // this.scene.add(this.controller);\n \n //these might need to be selected on type of controller\n // this.controller.standingMatrix = this.renderer.vr.getStandingMatrix();\n //this.controller.head = this.camera;\n\n this.showRecticle = false;\n \n this.dispatchEvent({ type: \"connected\"}, this.controller);\n\n //create the laser line pointer\n this.createLaserLine();\n\n //create the marker\n this.createMarker();\n\n }",
"function Controller () {}",
"_tryStartObserveContactStatus() {\n if (TypeUtils.isContact(this.get('controller.model'))) {\n // and add an observer for future changes to the status\n this.addObserver('controller.model.status', this, '_currentContactStatusObserver');\n }\n }",
"function ControllerChange(idx : int ){\n\tchrAnimator.runtimeAnimatorController = chrAnimatorController[idx];\n\tPlayClip(\"Appear\");\n}",
"function agentmapController() {\n\t//Set the tick display box to display the number of the current tick.\n\tticks_display.textContent = agentmap.state.ticks\n\n\t//Check if any of the options have been changed in the interface and update the Agentmap accordingly.\n\tif (\n\t\tagentmap.animation_interval !==\n\t\tNumber(animation_interval_map[animation_interval_input.value])\n\t) {\n\t\tagentmap.setAnimationInterval(animation_interval_map[animation_interval_input.value])\n\t}\n\tif (agentmap.speed_controller !== Number(speed_controller_input.value)) {\n\t\tagentmap.speed_controller = Number(speed_controller_input.value)\n\t\tagentmap.agents.eachLayer(function(agent) {\n\t\t\tagent.setSpeed(agentmap.speed_controller)\n\t\t})\n\t}\n\tif (agentmap.infection_probability !== Number(infection_probability_input.value)) {\n\t\tagentmap.infection_probability = Number(infection_probability_input.value)\n\t}\n}",
"function trackController(){\n\t\t\t$hostView.hide();\n\t\t\t$controllerView.show();\n\n\t\t\tnotify('successfully connected to the host computer');\n\t\t\t$instance.html(room);\n\n\t\t\tif( canHandleOrientation ){\n\t\t\t\tnotify('your device supports deviceorientation');\n\t\t\t\twindow.addEventListener(\"deviceorientation\",handleDeviceOrientation);\t\t\t\n\t\t\t}else{\n\t\t\t\tnotify('your device doesn\\'t support deviceorientation, use your keyboard to control the host');\n\t\t\t\t$(document).on('keydown',function(e){\n\t\t\t\t\tconsole.log(e.which);\n\t\t\t\t\tswitch(e.which){\n\t\t\t\t\t\tcase 37:\n\t\t\t\t\t\t\t/*left*/\n\t\t\t\t\t\t\tsendOrientatioonUpdate({gammaKeyboard:3});\n\t\t\t\t\t\t\t$debugAxisX.text( orientationState.gamma );\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 39:\n\t\t\t\t\t\t\t/*right*/\n\t\t\t\t\t\t\tsendOrientatioonUpdate({gammaKeyboard:-3});\n\t\t\t\t\t\t\t$debugAxisX.text( orientationState.gamma );\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 38:\n\t\t\t\t\t\t\t/*up*/\n\t\t\t\t\t\t\tsendOrientatioonUpdate({betaKeyboard:3});\n\t\t\t\t\t\t\t$debugAxisY.text( orientationState.beta );\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 40:\n\t\t\t\t\t\t\t/*down*/\n\t\t\t\t\t\t\tsendOrientatioonUpdate({betaKeyboard:-3});\n\t\t\t\t\t\t\t$debugAxisY.text( orientationState.beta );\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t}",
"_refreshContact(what, cont) {\n if (this.onContactUpdate) {\n this.onContactUpdate(what, cont);\n }\n }",
"function ControllerLayer() {}",
"get controller() { return this._.controller; }",
"function controllerOn() {\n\tif (gamePadActive == 0) {\n\t\t$('#cont-area').removeClass('d-none');\n\t\tresetInfo();\n\t\tjoypad.set({ axisMovementThreshold: 0.2 });\n\t\tjoypad.on('connect', e => updateInfo(e));\n\t\tjoypad.on('disconnect', e => resetInfo(e));\n\t\tjoypad.on('axis_move', e => {\n\t\t\tconsole.log(e.detail);\n\t\t\treturn moveAxis(e);\n\t\t});\n\t\tjoypad.on('button_press', e => {\n\t\t\tconsole.log(e.detail);\n\t\t\treturn pressButton(e);\n\t\t});\t\n\t\tmoveXY[0] = 0;\n\t\tmoveXY[2] = 0;\n\t\tgamePadActive = 1;\n\t}\n}",
"updateVRController() {\n //THREE.VRController.update()\n this.intersectObjects();\n }",
"function CompositeController() {\n }",
"function appController() {\n\t\n\t\n\t \n\t}",
"function FormController() {\n\t}",
"function agentmapController() {\n //Set the tick display box to display the number of the current tick.\n // ticks_display.textContent = agentmap.state.ticks;\n\n //Check if any of the options have been changed in the interface and update the Agentmap accordingly.\n if (agentmap.animation_interval !== Number(animation_interval_map[5])) {\n agentmap.setAnimationInterval(animation_interval_map[5]);\n }\n}",
"update() {\n \tthis.update_marker_ownership();\n \tthis.update_agent_velocities();\n \tthis.renderengine.update_agents(this.agents);\n \tthis.renderengine.update_markers(this.markers);\n \tthis.reset_ownership();\n }",
"function ControllerHandler() {\n}",
"function PlopController() {\n const gameEventBus = new Beerplop.GameEventBus(),\n beerBlender = new Minigames.BeerBlender(gameEventBus),\n gameState = new Beerplop.GameState(gameEventBus, beerBlender),\n beerBank = new Minigames.BeerBank(gameState, gameEventBus, beerBlender),\n achievementController = new Beerplop.AchievementController(gameState, gameEventBus, beerBank),\n stockMarket = new Minigames.StockMarket(gameState, gameEventBus),\n beerFactory = new Minigames.BeerFactory(gameState, gameEventBus),\n buffController = new Beerplop.BuffController(gameState, gameEventBus, beerBlender, beerFactory, beerBank),\n beerBankBanker = new Minigames.BeerBankBanker(gameState, gameEventBus, beerBank),\n beerwarts = new Minigames.Beerwarts(gameState, gameEventBus),\n levelController = new Beerplop.LevelController(gameState, gameEventBus),\n clickBarController = new Beerplop.ClickBarController(gameEventBus),\n upgradeController = new Beerplop.UpgradeController(gameState, gameEventBus, buffController, levelController, clickBarController, beerFactory),\n saveStateController = new Beerplop.SaveStateController(gameState, gameEventBus),\n researchProject = new Minigames.ResearchProject(gameState, gameEventBus, upgradeController, beerBankBanker, beerwarts),\n beerCloner = new BuildingMinigames.BeerCloner(gameState, gameEventBus, achievementController, researchProject),\n automatedBar = new BuildingMinigames.AutomatedBar(gameEventBus, achievementController);\n\n new Beerplop.ConsoleController(gameState, buffController, upgradeController, achievementController);\n\n gameState\n .setAchievementController(achievementController)\n .setUpgradeController(upgradeController)\n .setLevelController(levelController)\n .setSlotController(beerFactory.getSlotController())\n .setResearchProject(researchProject)\n .setBeerBank(beerBank)\n .setBeerwarts(beerwarts)\n .setBeerCloner(beerCloner)\n .setBeerFactory(beerFactory)\n .setAutomatedBar(automatedBar);\n\n new Beerplop.OverlayController();\n\n beerBlender.setAchievementController(achievementController);\n beerwarts.setAchievementController(achievementController);\n beerBankBanker\n .setAchievementController(achievementController)\n .setStockMarket(stockMarket);\n\n const gamePersistor = (new Beerplop.GamePersistor()).setEventBus(gameEventBus),\n saveStateId = $('body').data('savestateId');\n\n new Beerplop.GameOptions();\n\n assetPromises['client-templates'].then(() => {\n try {\n if (saveStateId) {\n saveStateController.loadSaveState(saveStateId, 1000);\n } else {\n gamePersistor.loadLocalSaveState();\n }\n } catch (error) {\n gamePersistor.disableSave();\n saveStateController.disableSave();\n\n alert(translator.translate('error.applySaveState') + \"\\n\\n\" + error);\n console.log(error);\n\n (new Beerplop.ErrorReporter()).reportError(\n 'SAVE STATE FATAL! [Save state version: ' + gamePersistor.saveStateVersion + '] ' + error.name,\n error.message,\n error.stack\n );\n }\n\n (new Beerplop.GameEventBus()).emit(EVENTS.CORE.INITIALIZED.GAME);\n });\n\n new Beerplop.StatisticsController(gameState, buffController, levelController);\n }",
"function processControllerStateChange() {\n addEvent(\"controllers\", e[\"controller_id\"], point, entities);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
fncDeleteCookie =============== Delete cookie value Parameters in strName string variable containing cookie name in strPath string variable containing path for which cookie is valid This must be the same as the path used to create the cookie, or null/omitted if no path was specified when creating the cookie. in strDomain string variable containing domain for which cookie is valid This must be the same as the domain used to create the cookie, or null/omitted if no domain was specified when creating the cookie. Return value | function fncDeleteCookie(strName, strPath, strDomain)
{
var strSearch = strName + "=";
// Check if there are any cookies
if (document.cookie.length > 0)
{
strStart = document.cookie.indexOf(strSearch);
// Check if specified cookie exists
if (strStart != -1)
{
document.cookie = strName + "=" + ((strPath) ? "; path=" + strPath : "") + ((strDomain) ? "; domain=" + strDomain : "") + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}
} | [
"function fDeleteCookie(name, path, domain) {\n if (GetCookie(name))\n document.cookie = name + \"=\" + ((path) ? \";path=\" + path : \"\") + ((domain) ? \";domain=\" + domain : \"\") + \";expires=Thu, 01-Jan-1970 00:00:01 GMT\";\n}",
"function DeleteCookie (name,path,domain) {\n if (GetCookie(name)) {\n document.cookie = name + \"=\" +\n ((path) ? \"; path=\" + path : \"\") +\n ((domain) ? \"; domain=\" + domain : \"\") +\n \"; expires=Thu, 01-Jan-1970 00:00:01 GMT\";\n }\n}",
"function deleteCookie(name, path, domain, alwaysDelete)\r\n{\r\n if (getCookie(name) || alwaysDelete)\r\n {\r\n document.cookie = name + \"=\" +\r\n ((path) ? \"; path=\" + path : \"\") +\r\n ((domain) ? \"; domain=\" + domain : \"\") +\r\n \"; expires=\" + new Date(1).toGMTString();\r\n }\r\n}",
"function xDeleteCookie(name, path)\r\n{\r\n if (xGetCookie(name)) {\r\n document.cookie = name + \"=\" +\r\n \"; path=\" + ((!path) ? \"/\" : path) +\r\n \"; expires=\" + new Date(0).toGMTString();\r\n }\r\n}",
"function RemoveCookie(cookie_name, path, domain)\n{\n if (GetCookie(cookie_name))\n {\n var cookie_data = \"\";\n if (path)\n {\n cookie_data += \";path=\" + path;\n }\n if (domain)\n {\n cookie_data += \";domain=\" + domain;\n }\n document.cookie = cookie_name + \"=\" + cookie_data + \";expires=Thu, 01-Jan-1970 00:00:01 GMT\";\n }\n}",
"function deleteCookie(name, path, domain, alwaysDelete)\n{\n if (getCookie(name) || alwaysDelete)\n {\n document.cookie = name + \"=\" +\n ((path) ? \"; path=\" + path : \"\") +\n ((domain) ? \"; domain=\" + domain : \"\") +\n \"; expires=\" + new Date(1).toGMTString();\n }\n}",
"function xDeleteCookie(name, path)\n{\n if (xGetCookie(name)) {\n document.cookie = name + \"=\" +\n \"; path=\" + ((!path) ? \"/\" : path) +\n \"; expires=\" + new Date(0).toGMTString();\n }\n}",
"function delCookie(sName)\n{\n\tvar sValue = arguments[1] ? arguments[1] : '';\n\tdocument.cookie = sName + \"=\" + escape(sValue) + \"; expires=Fri, 31 Dec 1999 23:59:59 GMT; \";\n}",
"function deleteCookie(szName)\n{\n \tvar tmp = \t \t\t\t \t getCookie(szName);\n\tif(tmp)\n\t{ setCookie(szName,tmp,(new Date(1))); }\n}",
"function deleteCookie(name, document, path, domain) {\n writeCookie(name, null, document, path, domain);\n}",
"function cookieDelete(name, path) {\r\n var expires = new Date();\r\n\r\n expires.setTime(expires.getTime() - 1*(1000*60*60*24));\r\n document.cookie = name + '=DUMMY; expires=' + expires.toGMTString() +\r\n\t((path == null) ? \"\" : (\"; path=\" + path));\r\n}",
"function deleteCookie(cname) { // cookie name\r\n \r\n document.cookie = cname + \"=; expires=Thu, 01 Jan 1970 00:00:00 UTC\"; // Así es como se borra una cookie\r\n \r\n}",
"function delCookie(name) {\n var exp = new Date();\n FixCookieDate (exp); // Correct for Mac bug\n exp.setTime (exp.getTime() - 1); // This cookie is history\n var cval = getCookie (name);\n (cval != null)\n document.cookie = name + \"=\" + cval + \"; expires=\" + exp.toGMTString();\n}//endFunction",
"function deleteCookie (cookieName) {\r\n\r\n if (getCookieValue (cookieName)) writePersistentCookie (cookieName,\"Pending delete\",\"years\", -1); \r\n return true; \r\n}",
"function deleteACookie(){\n var cname = window.document.getElementById('cname').value;//Get the cookie name from the cname input element\n deleteCookie(cname);//Call the deleteCookie to delete the cookie\n window.location.reload();//Reload the page\n}",
"function eliminarCookie(nombre) {\n document.cookie = nombre + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';\n}",
"remove(cookieName) {\n cookies.remove(cookieName, domain);\n }",
"function deleteCookie(name) {\n writeCookie(name, \"\");\n}",
"function deleteCookie (cookieName) {\n if (getCookieValue (cookieName)) writePersistentCookie (cookieName,\"Pending delete\",\"years\", -1); \n return true; \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes the given object and its filter (if present). | function removeObject(objectId, filter) {
if(objectId) {
var object = document.getElementById(objectId);
//if(object) object.parentNode.removeChild(object);
if(object) object.style.display = 'none';
window.dialog = null;
if(objectId == PICKER.id) window.picker = null;
}
if(filter) {
filter.DOM.parentNode.removeChild(filter.DOM);
filter = null;
window.filter = null;
}
} | [
"removeObject(object) {\n this.objects.delete(object);\n this.processResultDelta('reset', this.results.filter(result => result.object === object), []);\n }",
"remove(object) {\n\t\t//\n\t}",
"remove(object) {}",
"function removeActiveFilter(filterObject){\n console.info('ggScript: filterObject:');\n\tvar updatedFilterArray = [];\n\t//Remove active Filter from array\n\t$(activeFilters).each(function(){\n\t\tif(this.value != filterObject.value)\n\t\t{\n\t\t\tupdatedFilterArray.push(this);\n\t\t}\n\t});\n\tactiveFilters = updatedFilterArray;\n}",
"removeObject(object) {\n this.objects.delete(object);\n this.processErrorDelta('reset', this.errors.filter(error => error.object === object), []);\n }",
"function removeActiveFilterFromView(filterObject)\n{\n\t//Find filter-element and remove it\n var currentFilterElement;\n $('div#activeFilters a',sidebarLeft).each(function(){\n currentFilterElement = createFilterObject(this);\n if(createFilterObject(this).id == filterObject.id)\n {\n $(this).parent('div:first').remove();\n return false;//is like a break from loop\n }\n });\n //Remove filterObject from activeFilters-array\n removeActiveFilter(filterObject);\n //Check if activeFiltersViewContainer needs update\n updateActiveFilterViewContainer();\n}",
"function removeFilter() {\n\n}",
"remove(object) {\n THREE.Object3D.prototype.remove.call(this, object);\n\n if (object instanceof PointCloudTree) {\n var index = this.pointclouds.indexOf(object);\n if (index !== -1) {\n this.pointclouds.splice(index, 1);\n this.recalculateBoxGeometry();\n }\n }\n }",
"removeObject(object) {\n //loop goes through array and finds the object to delete it\n numObjects = this.objects.size()\n for (a = 0; a < numObjects; a++) {\n if (this.objects[a] == object) {\n this.objects.pop(a)\n }\n }\n }",
"onObjectRemoved(dest, ...filters) {\n return this.onEvent(EventType.ObjectRemoved, dest, ...filters);\n }",
"function camSafeRemoveObject(obj, flashy)\n{\n\tif (__camLevelEnded)\n\t{\n\t\treturn;\n\t}\n\tif (camIsString(obj))\n\t{\n\t\tobj = getObject(obj);\n\t}\n\tif (camDef(obj) && obj)\n\t{\n\t\tremoveObject(obj, flashy);\n\t}\n}",
"removeMatches(subject, predicate, object, graph) {\n const stream = new _readableStream.Readable({\n objectMode: true\n });\n\n stream._read = () => {\n for (const quad of this.getQuads(subject, predicate, object, graph)) stream.push(quad);\n\n stream.push(null);\n };\n\n return this.remove(stream);\n }",
"function removeObject(object) {\n\n for (var indexKeyIndex = 0, indexKeyCount = type_metaData.type_indexKeys.length;\n indexKeyIndex < indexKeyCount;\n indexKeyIndex++) {\n\n var indexKey = type_metaData.type_indexKeys[indexKeyIndex];\n var value = object[indexKey];\n var object_by_key = type_metaData.type_indexes[indexKey];\n\n if (object_by_key[value] === object) {\n\n delete object_by_key[value];\n\n } else {\n\n ERROR('defineType removeObject: object missing from object_by_key!', ['name', name, 'object', object, 'indexKey', indexKey, 'value', value, 'type_objects', type_objects, 'object_by_key', object_by_key, 'object_by_key[value]', object_by_key[value]]);\n\n }\n }\n\n var index =\n type_metaData.type_objects.indexOf(object);\n if (index >= 0) {\n\n type_metaData.type_objects.splice(index, 1);\n reindexObjects();\n\n } else {\n\n ERROR('defineType removeObject: object missing from type_objects!', ['name', name, 'object', object, 'indexKey', indexKey, 'value', value, 'type_objects', type_objects, 'object_by_key', object_by_key]);\n\n }\n\n }",
"static async remove(filter = {}) { return await this.__query().where(filter).remove(); }",
"function removeObject(object) {\n // Remove the object from the list of animated thingies, if it's there.\n removeAnimation(object.id());\n\n // If a multipart object, hide parts.\n var related = null;\n // FIXME: In LZ, not all objects are in objects_json - the lookup may fail.\n try {\n related = objects_json[object.id()].related;\n }\n catch(e) {}\n\n if (related && related.length != 0) {\n\t for (var i in related) {\n var related_part = stage.get(\"#\" + related[i])[0];\n removeAnimation(related_part.id());\n related_part.hide();\n }\n\t}\n\n object.hide();\n current_layer.draw();\n}",
"function removeFilter() {\n filter = currentFilter();\n if (hasUserAddedFilter(filter)) {\n var userSource = userSourceForSource(currentDataSource());\n var index = userSource[\"filters\"].indexOf(userFilterForFilter(filter));\n if (index > -1) {\n userSource[\"filters\"].splice(index,1);\n changedToFilter();\n\n var optionElement = document.getElementById(\"Filter-Option-\" + filter[\"id\"]);\n optionElement.innerHTML = filter[\"name\"];\n\n updateOutputText();\n }\n }\n}",
"function filterObjectValue(obj, pred = Boolean) {\n forEach(obj, (v, k) => {\n if (!pred(v)) {\n delete obj[k]\n }\n })\n return obj\n}",
"removeMatches(subject, predicate, object, graph) {\n const stream = new browser.Readable({ objectMode: true });\n\n stream._read = () => {\n for (const quad of this.readQuads(subject, predicate, object, graph))\n stream.push(quad);\n stream.push(null);\n };\n\n return this.remove(stream);\n }",
"removeCheckedObject(state, object) {\n let index = state.checkedObjects.indexOf(object)\n\n state.checkedObjects = state.checkedObjects.filter((e, i) => i != index)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Store contents of a basic template information in the TEI | function TemplateInfo() {
this.code = '';
this.type = '';
this.parent = '';
this.description = '';
} | [
"function initTemplateVars() {\n if (body.dataset.type && body.dataset.type === 'plugin') {\n loadFileContent('jira_ticket.tpl', (text) => {\n JIRA_TICKET_TEMPLATE = text\n })\n loadFileContent('gitlab_merge_request.tpl', (text) => {\n GITLAB_MERGE_REQUEST_TEMPLATE = text\n })\n loadFileContent('jira_jse.tpl', (text) => {\n JIRA_JSE_TEMPLATE = text\n })\n loadFileContent('scrum_board_choice.tpl', (text) => {\n JIRA_SCRUMB_BOARD_CHOICE_TEMPLATE = text\n })\n }\n}",
"setTemplateInfo (state, model) {\n state.title = model['title']\n state.subtitle = model['subtitle']\n state.description = model['description']\n }",
"function createTemplate(){\n\t\t\tvar vraTemplate = new File (desktop+\"\"+mdMenu+\"_import_default template.txt\") \n\t\t\tvraTemplate.encoding = \"UTF8\";\n\t\t\tvraTemplate.open (\"w\", \"TEXT\", \"ttxt\");\t\n\t\t\t// Loop through array of headers (properties) and write them to the .txt file\n\t\t\tfor (var L1 = 0; L1 < fieldsArr.length; L1++) vraTemplate.write (fieldsArr[L1].Label + \"\\t\");\n\t\t\t// Close the file \"\"+mdMenu+\"_import_template.txt\"\n\t\t\tvraTemplate.close();\n\t\t\tWindow.alert (\"A new file named:\\n\\n\"+mdMenu+\"_import_default template.txt\\n\\nhas been created on your desktop\", \"Success!\")\n\t\t\t}",
"function set_template( name ){\n\t\tdocument.body.innerHTML = fs.readFileSync('./test/templates/'+name+'.html');\n\t}",
"function newTemplate() {\n\t\tsetTemplate(publication.createDefaultTemplate());\n\t}",
"function synthesizeTechnicianPageTemplate() {\n // Bind technician-page dom template\n var page_template = templateStore.import.querySelector(TEMPLATE_ID_SELECTOR);\n var page_clone = document.importNode(page_template.content, true);\n TechnicianPageRootNode.node.appendChild(page_clone);\n }",
"function templatePage(req, res, template, block, next) {\n \n // Set any variables\n var myVariable = \"Hello World\";\n \n // Create a content item\n var item = {id:\"NA\", type:'content', meta:{variable:myVariable}};\n \n // Render the item via the template provided above\n calipso.theme.renderItem(req, res, template, block, {item:item});\n \n next();\n \n}",
"function saveTemplate() {\n\t\tvar activeLayout = getActiveLayout();\n\t\tactiveLayout.designTime = false;\n\t\tvar templateStr = JSON.stringify(getTemplate(), null, \" \");\n\t\tactiveLayout.designTime = true;\n\t\tvar uriContent = \"data:application/octet-stream,\" + encodeURIComponent(templateStr);\n\t\twindow.location.href = uriContent;\n\t\tcommandStack.clear();\t\t\n\t}",
"function templatePage(req, res, template, block, next) {\n\n // Set any variables\n var myVariable = \"Hello World\";\n\n // Create a content item\n var item = {\n id: \"NA\",\n type: 'content',\n meta: {\n variable: myVariable\n }\n };\n \n // Raise a ping\n calipso.e.custom_emit('TEMPLATE_EVENT','PING',{req:req}, function(options) {\n \n // Render the item via the template provided above\n calipso.theme.renderItem(req, res, template, block, {\n item: item\n },next);\n\n });\n\n \n}",
"function loadTemplate() {\n htmlEditor.setValue('<!DOCTYPE html>\\n<html>\\n<head>\\n<title>HTML, CSS and JavaScript demo</title>\\n</head>\\n<body>\\n<!-- Start your code here -->\\n\\n<p class=\\\"lw\\\">Hello Weaver!</p>\\n\\n<!-- End your code here -->\\n</body>\\n</html>');\n cssEditor.setValue('.lw { font-size: 60px; }');\n jsEditor.setValue('// Write JavaScript here ');\n }",
"function insertTemplate() {\n console.debug(\"insertTemplate called\");\n\n // Find the email template name\n var email_template = document.getElementById(\"emailTemplate\");\n if ( email_template )\n {\n\t dojo.xhrGet({\n\t url:window.contextPath + \"/include/response/template.jsp\",\n\t content:{templateName: email_template.value},\n\t timeout: atgXhrTimeout,\n\t load:function(response, ioArgs){\n\t FCKeditorAPI.GetInstance('RespondEditor').SetHTML(response);\n\t }\n\t });\n }\n}",
"function loadTemplates() {\n for (var template in templates) {\n templates[template] = fs.readFileSync(templatePath + template + '.html').toString();\n }\n }",
"function templateEngine () { }",
"function store(index, value) {\n // We don't store any static data for local variables, so the first time\n // we see the template, we should store as null to avoid a sparse array\n if (index >= tData.length) {\n tData[index] = null;\n }\n data[index] = value;\n}",
"editTemplate (t, nosave) {\n let self = this;\n // Make sure the editor works on a copy of the template.\n //\n let ct = this.currTemplate = new __WEBPACK_IMPORTED_MODULE_5__template_js__[\"a\" /* Template */](t, this.currMine.model);\n //\n this.root = ct.qtree\n this.root.x0 = 0;\n this.root.y0 = this.svg.height / 2;\n //\n ct.setLogicExpression();\n\n if (! nosave) this.undoMgr.saveState(ct.qtree);\n\n // Fill in the basic template information (name, title, description, etc.)\n //\n let ti = d3.select(\"#tInfo\");\n let xfer = function(name, elt){ ct[name] = elt.value; self.updateTtext(ct); };\n // Name (the internal unique name)\n ti.select('[name=\"name\"] input')\n .attr(\"value\", ct.name)\n .on(\"change\", function(){ xfer(\"name\", this) });\n // Title (what the user sees)\n ti.select('[name=\"title\"] input')\n .attr(\"value\", ct.title)\n .on(\"change\", function(){ xfer(\"title\", this) });\n // Description (what it does - a little documentation).\n ti.select('[name=\"description\"] textarea')\n .text(ct.description)\n .on(\"change\", function(){ xfer(\"description\", this) });\n // Comment - for whatever, I guess.\n ti.select('[name=\"comment\"] textarea')\n .text(ct.comment)\n .on(\"change\", function(){ xfer(\"comment\", this) });\n\n // Logic expression - which ties the individual constraints together\n d3.select('#svgContainer [name=\"logicExpression\"] input')\n .call(function(){ this[0][0].value = ct.constraintLogic })\n .on(\"change\", function(){\n ct.setLogicExpression(this.value);\n xfer(\"constraintLogic\", this)\n });\n\n // Clear the query count\n d3.select(\"#querycount span\").text(\"\");\n\n //\n this.dialog.hide();\n this.update(this.root);\n }",
"function _loadTemplate()\n {\n var memento = {\n 'templateId': pageModel.getTemplateModel().getId(),\n 'pageId': currentPageId,\n 'tabId': \"perc-tab-layout\"\n };\n $.PercNavigationManager.goToLocation($.PercNavigationManager.VIEW_EDIT_TEMPLATE, $.PercNavigationManager.getSiteName(), null, null, null, $.PercNavigationManager.getPath(), null, memento);\n }",
"function saveTemplateObject(block, name) {\n var surfaceForms = document\n .getElementById(\"surfaceForms\")\n .innerText.split(\"\\n\");\n\n var actionDict = document.getElementById(\"actionDict\").innerText;\n if (actionDict) {\n // associated with code\n actionDict = JSON.parse(actionDict);\n } else {\n actionDict = undefined;\n }\n var templateObjectsSaved = localStorage.getItem(\"templates\");\n if (templateObjectsSaved) {\n templateObjectsSaved = JSON.parse(templateObjectsSaved);\n } else {\n templateObjectsSaved = {};\n }\n\n templateObjectsSaved[name] = {};\n templateObjectsSaved[name][\"surfaceForms\"] = surfaceForms;\n templateObjectsSaved[name][\"code\"] = actionDict;\n console.log(templateObjectsSaved);\n localStorage.setItem(\"templates\", JSON.stringify(templateObjectsSaved));\n\n saveToFile(); // dump new local storage information to file\n}",
"function loadTemplate() {\n var templatePattern = /@[[a-zA-Z0-9]+]/g;\n\n templateContent = _fs.readFileSync(templatePath, fileEncoding);\n templatePlaceholders = templateContent.match(templatePattern);\n\n }",
"editTemplate (t, nosave) {\n let self = this;\n // Make sure the editor works on a copy of the template.\n //\n let ct = this.currTemplate = new Template(t, this.currMine.model);\n //\n this.root = ct.qtree\n this.root.x0 = 0;\n this.root.y0 = this.svg.height / 2;\n //\n ct.setLogicExpression();\n\n if (! nosave) this.undoMgr.saveState(ct.qtree);\n\n // Fill in the basic template information (name, title, description, etc.)\n //\n let ti = d3.select(\"#tInfo\");\n let xfer = function(name, elt){ ct[name] = elt.value; self.updateTtext(ct); };\n // Name (the internal unique name)\n ti.select('[name=\"name\"] input')\n .attr(\"value\", ct.name)\n .on(\"change\", function(){ xfer(\"name\", this) });\n // Title (what the user sees)\n ti.select('[name=\"title\"] input')\n .attr(\"value\", ct.title)\n .on(\"change\", function(){ xfer(\"title\", this) });\n // Description (what it does - a little documentation).\n ti.select('[name=\"description\"] textarea')\n .text(ct.description)\n .on(\"change\", function(){ xfer(\"description\", this) });\n // Comment - for whatever, I guess.\n ti.select('[name=\"comment\"] textarea')\n .text(ct.comment)\n .on(\"change\", function(){ xfer(\"comment\", this) });\n\n // Logic expression - which ties the individual constraints together\n d3.select('#svgContainer [name=\"logicExpression\"] input')\n .call(function(){ this[0][0].value = ct.constraintLogic })\n .on(\"change\", function(){\n ct.setLogicExpression(this.value);\n xfer(\"constraintLogic\", this)\n });\n\n // Clear the query count\n d3.select(\"#querycount span\").text(\"\");\n\n //\n this.dialog.hide();\n this.update(this.root);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads configuration from the DATAREFS_DATA_FILENAME file. | function readDataRefsFromFile(aliasName) {
let data = {}
try {
data = _readDataFromJsonFile(aliasName, DATAREFS_DATA_FILENAME)
if (data) {
_checkRequiredDataField(data, "dataRefs", DATAREFS_DATA_FILENAME)
_checkRequiredDataField(data.dataRefs, "refs", DATAREFS_DATA_FILENAME)
if (!Array.isArray(data.dataRefs.refs)) {
throw new Error(`"dataRefs.refs" data field in the "${DATAREFS_DATA_FILENAME}" config file must be an array!`)
}
data.dataRefs.refs.forEach(
function(obj) {
_checkRequiredDataField(obj, "brfcIds", DATAREFS_DATA_FILENAME)
obj.brfcIds.forEach(
function(id) {
if (!/^[A-F0-9]{12}$/i.test(id)) {
throw new Error(`"dataRefs.refs.brfcIds" data field in the "${DATAREFS_DATA_FILENAME}" config file must be a valid BRFC ID!`)
}
})
_checkRequiredDataField(obj, "txid", DATAREFS_DATA_FILENAME)
if (!/^[A-F0-9]{64}$/i.test(obj.txid)) {
throw new Error(`"dataRefs.refs.txid" data field in the "${DATAREFS_DATA_FILENAME}" config file must be a valid transaction id!`)
}
_checkRequiredDataField(obj, "vout", DATAREFS_DATA_FILENAME)
if (!/^\d+$/i.test(obj.vout)) {
throw new Error(`"dataRefs.refs.vout" data field in the "${DATAREFS_DATA_FILENAME}" config file must be a valid outpoint number!`)
}
})
}
} catch (e) {
console.error('Reading dataRefs configuration: ', e)
return null
}
return data
} | [
"function readConfig(fileRef) {\n // cspellConfigExplorerSync\n const { filename } = fileRef;\n const s = {};\n try {\n const r = cspellConfigExplorerSync.load(filename);\n if (!(r === null || r === void 0 ? void 0 : r.config))\n throw new Error(`not found: \"${filename}\"`);\n Object.assign(s, r.config);\n normalizeRawConfig(s);\n validateRawConfig(s, fileRef);\n }\n catch (err) {\n fileRef.error =\n err instanceof ImportError_1.ImportError ? err : new ImportError_1.ImportError(`Failed to read config file: \"${filename}\"`, err);\n }\n s.__importRef = fileRef;\n return s;\n}",
"function readDataRefsTxFile(aliasName) {\n try {\n const txData = _readDataFromJsonFile(aliasName, DATAREFS_TX_DATA_FILENAME)\n if (txData) {\n _checkRequiredDataField(txData, \"dataRefs\", DATAREFS_TX_DATA_FILENAME)\n _checkRequiredDataField(txData.dataRefs, \"refs\", DATAREFS_TX_DATA_FILENAME)\n if (!Array.isArray(txData.dataRefs.refs)) {\n throw new Error(`\"dataRefs.refs\" data field in the \"${DATAREFS_TX_DATA_FILENAME}\" config file must be an array!`)\n }\n txData.dataRefs.refs.forEach(\n function(obj) {\n _checkRequiredDataField(obj, \"brfcIds\", DATAREFS_TX_DATA_FILENAME)\n _checkRequiredDataField(obj, \"data\", DATAREFS_TX_DATA_FILENAME)\n if (JSON.stringify(obj.data) === '{}') {\n throw new Error(`\"dataRefs.refs.data\" data field in the \"${DATAREFS_TX_DATA_FILENAME}\" config file must be a non-empty json object!`)\n\t }\n obj.brfcIds.forEach(\n function(id) {\n if (!/^[A-F0-9]{12}$/i.test(id)) {\n throw new Error(`\"dataRefs.refs.brfcIds\" data field in the \"${DATAREFS_TX_DATA_FILENAME}\" config file must be a valid BRFC ID!`)\n\t }\n _checkRequiredDataField(obj.data, id, DATAREFS_TX_DATA_FILENAME) })\n _checkRequiredDataField(obj, \"vout\", DATAREFS_TX_DATA_FILENAME)\n if (!/^\\d+$/i.test(obj.vout)) {\n throw new Error(`\"dataRefs.refs.vout\" data field in the \"${DATAREFS_TX_DATA_FILENAME}\" config file must be a valid outpoint number!`)\n }\n })\n }\n return txData\n } catch (e) {\n console.log('Error reading dataRefsTx configuration: ', e)\n return null\n }\n}",
"readConfig(fileRef) {\n // cspellConfigExplorerSync\n const { filename, error } = fileRef;\n if (error) {\n fileRef.error =\n error instanceof ImportError_1.ImportError\n ? error\n : new ImportError_1.ImportError(`Failed to read config file: \"${filename}\"`, error);\n return { __importRef: fileRef };\n }\n const s = {};\n try {\n const r = this.cspellConfigExplorerSync.load(filename);\n if (!r?.config)\n throw new Error(`not found: \"${filename}\"`);\n Object.assign(s, r.config);\n (0, normalizeRawSettings_1.normalizeRawConfig)(s);\n validateRawConfig(s, fileRef);\n }\n catch (err) {\n fileRef.error =\n err instanceof ImportError_1.ImportError ? err : new ImportError_1.ImportError(`Failed to read config file: \"${filename}\"`, err);\n }\n s.__importRef = fileRef;\n return s;\n }",
"readConfig(fileRef) {\n const { filename, error: error2 } = fileRef;\n if (error2) {\n fileRef.error = error2 instanceof ImportError ? error2 : new ImportError(`Failed to read config file: \"${filename}\"`, error2);\n return { __importRef: fileRef };\n }\n const s = {};\n try {\n const r = this.cspellConfigExplorerSync.load(filename);\n if (!r?.config)\n throw new Error(`not found: \"${filename}\"`);\n Object.assign(s, r.config);\n normalizeRawConfig(s);\n validateRawConfig(s, fileRef);\n } catch (err) {\n fileRef.error = err instanceof ImportError ? err : new ImportError(`Failed to read config file: \"${filename}\"`, err);\n }\n s.__importRef = fileRef;\n return s;\n }",
"function readConfig () {\n let data = JSON.parse(fs.readFileSync(CONFIG_FN, 'utf8'))\n ;['exchanges', 'server', 'cache'].forEach((group) => {\n if (!data[group]) {\n return\n }\n for (let key in data[group]) {\n // consider any lines starting with '#' as comments\n if (!key.startsWith('#')) {\n config[group][key] = data[group][key]\n }\n }\n })\n}",
"function read() {\n\tconfig = JSON.parse(fs.readFileSync(CONFIG_FILE, \"utf8\"));\n}",
"function readConfigFile() {\n\treturn ini.parse(readFileSync(confFile, 'utf-8'));\n}",
"function readHttpsCreds (config, key, relName) {\n let baseName = '.'\n if (config.fileName) baseName = path.dirname(config.fileName)\n\n Logger.debug(`readHttpsCreds(config, '${key}', '${relName}'), baseName: '${baseName}'`)\n const fileName = path.resolve(baseName, relName)\n Logger.debug(`readHttpsCreds() reading '${fileName}'`)\n\n const contents = util.loadFile(fileName)\n if (contents == null) {\n Logger.error(`error reading file '${fileName}', specified in config key ${key}`)\n return null\n }\n\n return contents\n}",
"function readPrefs() {\r\ttry {\r\t\tprefsFile.open(\"r\");\r\t\tmyPrefs = eval(prefsFile.readln());\r\t\tprefsFile.close();\r\t} catch(e) {\r\t\tthrowError(\"Could not read preferences: \" + e, false, 2, prefsFile);\r\t}\r}",
"function readData() {\n //const DATA_URL = \"https://maeyler.github.io/Iqra3/data/\" in common.js\n fetch(DATA_URL + \"refs.txt\")\n .then(r => r.text()) //response\n .then(report2); //text\n}",
"function readPrefs() {\n\ttry {\n\t\tprefsFile.open(\"r\");\n\t\tfmaster = Number(prefsFile.readln());\n\t\tprefsFile.close();\n\t} catch(e) {\n\t\tthrowError(\"Could not read preferences: \" + e, false, 2, prefsFile);\n\t}\n}",
"function readConfig() {\n return toml.parse(fs.readFileSync('config.toml', 'utf8'));\n}",
"read () {\n this.configObj = JSON.parse(fs.readFileSync(this.configPath, 'utf8'))\n }",
"function readFromConfigFile() {\n\tconsole.log(\"Reading from config file\");\n\ttry {\n\t\tvar config = require('./server-config.json');\n\t\tconsole.log(JSON.parse(config));\n\t}catch (err) {\n\t\tconsole.log(err);\n\t}\n}",
"readConfig() {\n try {\n this.config = JSON.parse(fs.readFileSync(this.configFile, 'UTF-8'));\n } catch (e) {\n this.log.error('could not read the config.json');\n this.resetConfig();\n this.resetConfig();\n this.saveConfig();\n }\n }",
"function getConfigFile() {\n try {\n let raw_data = fs.readFileSync(configPath);\n let parsed_data = JSON.parse(raw_data);\n return parsed_data;\n } catch(e) {\n logger.error('Failed to get config file');\n return null;\n }\n}",
"loadLocalConfigFile() {\n let configData = {};\n try {\n configData = this.readFileSync(this.configFilePath);\n\n // validate based on config file version\n if (configData.version > 0) {\n configData = _main_Validator__WEBPACK_IMPORTED_MODULE_3__[\"validateV1ConfigData\"](configData);\n } else {\n configData = _main_Validator__WEBPACK_IMPORTED_MODULE_3__[\"validateV0ConfigData\"](configData);\n }\n if (!configData) {\n throw new Error('Provided configuration file does not validate, using defaults instead.');\n }\n } catch (e) {\n console.log('Failed to load configuration file from the filesystem. Using defaults.');\n configData = this.copy(this.defaultConfigData);\n\n // add default team to teams if one exists and there arent currently any teams\n if (!configData.teams.length && this.defaultConfigData.defaultTeam) {\n configData.teams.push(this.defaultConfigData.defaultTeam);\n }\n delete configData.defaultTeam;\n\n this.writeFileSync(this.configFilePath, configData);\n }\n return configData;\n }",
"function readConfigFile() {\n var p = new Promise(function(resolve, reject) {\n fs.readFile(configFile, function(e, data) {\n var ver = \"UNKNOWN\";\n if (e) {\n console.log(\"Error opening \" + configFile + \".\");\n reject(e);\n } else {\n console.log(\"Config file opened.\");\n var obj = JSON.parse(data);\n // get the connection token\n if (obj.token) {\n token = obj.token;\n } else {\n reject(new Error(\"Firebase connection token not found in config file.\"));\n }\n // get the firebase url\n if (obj.firebaseUrl) {\n url = obj.firebaseUrl;\n } else {\n reject(new Error(\"Firebase URL not found in config file.\"));\n }\n resolve(obj);\n }\n });\n });\n\n return p;\n}",
"function readConfigFile()\n{\n\tvar configfile=\"config.json\";\n\tvar stream_config = fs.open(configfile,'r');\n\tvar data_config = stream_config.read(); \n\tvar config_c = JSON.parse(data_config); \n\twindow.timestampFormat=config_c.timestampFormat;\n\twindow.version=config_c.version;\n\tstream_config.close();\n\treadQueries();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that a given URI parses correctly into its various components. | function do_test_uri_basic(aTest) {
var URI;
try {
URI = gIoService.newURI(aTest.spec);
} catch (e) {
var url=aTest.relativeURI ? (aTest.spec +"<"+aTest.relativeURI) : aTest.spec;
//do_info("Caught error on parse of" + aTest.spec + " Error: "+e.name+" " + e.result);
dump("\n{\"url\":\""+ url+"\", \"exception\":\""+e.name+" "+e.result+"\"}");
if (aTest.fail) {
Assert.equal(e.result, aTest.result);
return;
}
do_throw(e.result);
}
if (aTest.relativeURI) {
var relURI;
try {
relURI = gIoService.newURI(aTest.relativeURI, null, URI);
} catch (e) {
/*do_info(
"Caught error on Relative parse of " +
aTest.spec +
" + " +
aTest.relativeURI +
" Error: " +
e.result
);*/
var url=aTest.spec +"<"+aTest.relativeURI;
//do_info("Caught error on parse of" + aTest.spec + " Error: "+e.name+" " + e.result);
dump("\n{\"url\":\""+ url+"\", \"exception\":\""+e.name+" "+e.result+"\"}");
if (aTest.relativeFail) {
Assert.equal(e.result, aTest.relativeFail);
return;
}
do_throw(e.result);
}
URI=relURI;
}
// Check the various components
try {
do_check_property(aTest, URI, "scheme");
do_check_property(aTest, URI, "query");
do_check_property(aTest, URI, "ref");
do_check_property(aTest, URI, "port");
do_check_property(aTest, URI, "username");
do_check_property(aTest, URI, "password");
do_check_property(aTest, URI, "host");
do_check_property(aTest, URI, "specIgnoringRef");
do_check_property(aTest, URI, "hasRef");
do_check_property(aTest, URI, "prePath");
do_check_property(aTest, URI, "pathQueryRef");
} catch (e) {
dump("caught exception from components");
return;
}
} | [
"function parseUri(uri){\n /*jsl:ignore*/\n if(typeof Uri === undefined) throw new Error(\"URI parser not loaded\");\n return new Uri(url);\n /*jsl:end*/\n}",
"function parseUri(e){var a=parseUri.options,f=a.parser[a.strictMode?\"strict\":\"loose\"].exec(e),b={},c=14;while(c--)b[a.key[c]]=f[c]||\"\";b[a.q.name]={};b[a.key[12]].replace(a.q.parser,function(h,d,g){if(d)b[a.q.name][d]=g});return b}",
"function validateURI(uri) {\n if (!uri.match(/^https:\\/\\/(.*)/)) {\n tiny_invariant_1.default(false, `${uri} must begin with \\`https://\\``);\n }\n}",
"function isUriValid(uri){\n\t//TODO\n\tvar res = false;\n\tif(isTextValid(uri)){\n\t\t//var urlregex = new RegExp(\"^(http:\\/\\/www.|https:\\/\\/www.|ftp:\\/\\/www.|www.){1}([0-9A-Za-z]+\\.)\");\n\t\t//if (urlregex.test(uri)) {\n\t\t//TODO: Find a regular expression for URI validation\n\t\tres = true;\n\t\t//}\n\t}\n return res;\n}",
"function parseURI(uri) {\n var new_uri = uri;\n\n var replace = [\n { orig: /\\\\u002f/g, rep: \"/\" },\n { orig: /\\\\u0026/g, rep: \"&\" },\n { orig: /\\\\u00252d/g, rep: \"-\" },\n { orig: /\\\\u00257d/g, rep: \"%7d\" },\n { orig: /\\\\u00257b/g, rep: \"%7b\" }\n ];\n\n for (var i = 0; i < replace.length; i++) {\n new_uri = new_uri.replace(replace[i].orig, replace[i].rep);\n }\n\n return new_uri;\n }",
"function parseUri(str){var o=parseUri.options,m=o.parser[o.strictMode?\"strict\":\"loose\"].exec(str),uri={},i=14;while(i--){uri[o.key[i]]=m[i]||\"\"}uri[o.q.name]={};uri[o.key[12]].replace(o.q.parser,function($0,$1,$2){if($1){uri[o.q.name][$1]=$2}});return uri}",
"function parseUri(str){var o=parseUri.options,m=o.parser[o.strictMode?\"strict\":\"loose\"].exec(str||''),uri={},i=o.key.length;while(i--)uri[o.key[i]]=m[i]||\"\";uri[o.q.name]=yam.objectify(uri[\"query\"])||{};return uri;}",
"function parseUri(str){var o=parseUri.options,m=o.parser[o.strictMode?\"strict\":\"loose\"].exec(str),uri={},i=14;while(i--) {uri[o.key[i]] = m[i] || \"\";}uri[o.q.name] = {};uri[o.key[12]].replace(o.q.parser,function($0,$1,$2){if($1)uri[o.q.name][$1] = $2;});return uri;}",
"function parseUri(aUri) {\n let uri;\n try {\n // Test if the entered uri can be parsed.\n uri = makeURL(aUri);\n } catch (ex) {\n return [errorConstants.INVALID_URI, null];\n }\n\n let calManager = cal.getCalendarManager();\n let cals = calManager.getCalendars({});\n let type = document.getElementById('calendar-type').selectedItem.value;\n if (type != 'local' && cals.some(function (c) c.uri.spec == uri.spec)) {\n // If the calendar is not local, we check if there is already a calendar\n // with the same uri spec. Storage calendars all have the same uri, so\n // we have to specialcase them.\n return [errorConstants.ALREADY_EXISTS, null];\n }\n\n return [errorConstants.SUCCESS, uri];\n}",
"static parseURI(uri) {\n var a, j, len1, name, nameValue, nameValues, parse, value;\n parse = {};\n parse.params = {};\n a = document.createElement('a');\n a.href = uri;\n parse.href = a.href;\n parse.protocol = a.protocol;\n parse.hostname = a.hostname;\n parse.port = a.port;\n parse.segments = a.pathname.split('/');\n parse.fileExt = parse.segments.pop().split('.');\n parse.file = parse.fileExt[0];\n parse.ext = parse.fileExt.length === 2 ? parse.fileExt[1] : '';\n parse.dbName = parse.file;\n parse.fragment = a.hash;\n parse.query = Util.isStr(a.search) ? a.search.substring(1) : '';\n nameValues = parse.query.split('&');\n if (Util.isArray(nameValues)) {\n for (j = 0, len1 = nameValues.length; j < len1; j++) {\n nameValue = nameValues[j];\n name = '';\n value = '';\n [name, value] = nameValue.split('=');\n parse.params[name] = value;\n }\n }\n return parse;\n }",
"function testUrlComponents(parsedUrl, protocol, hostname, port, pathComponents) {\n assertEqual(parsedUrl.protocol, protocol);\n assertEqual(parsedUrl.hostname, hostname);\n assertEqual(parsedUrl.port, port);\n for (let aa = 0; aa < parsedUrl.pathComponents.length; aa++) {\n assertEqual(parsedUrl.pathComponents[aa], pathComponents[aa]);\n }\n}",
"function parseURI(str)\n{\n\tif(!str) return null;\n \n\tvar regexUri = /^([a-z0-9+.-]+):(?:\\/\\/(?:((?:[a-z0-9-._~!$&'()*+,;=:]|%[0-9A-F]{2})*)@)?((?:[a-z0-9-._~!$&'()*+,;=]|%[0-9A-F]{2})*|\\[(?:[0-9A-F:.]{2,})\\])(?::(\\d*))?(\\/(?:[a-z0-9-._~!$&'()*+,;=:@\\/]|%[0-9A-F]{2})*)?|(\\/?(?:[a-z0-9-._~!$&'()*+,;=:@]|%[0-9A-F]{2})+(?:[a-z0-9-._~!$&'()*+,;=:@\\/]|%[0-9A-F]{2})*)?)(?:\\?((?:[a-z0-9-._~!$&'()*+,;=:\\/?@]|%[0-9A-F]{2})*))?(?:#((?:[a-z0-9-._~!$&'()*+,;=:\\/?@]|%[0-9A-F]{2})*))?$/i;\n\t//'\n\t/*composed as follows:\n\t\t^\n\t\t([a-z0-9+.-]+):\t\t\t\t\t\t\t\t\t\t\t#scheme\n\t\t(?:\n\t\t\t\\/\\/\t\t\t\t\t\t\t\t\t\t\t\t#it has an authority:\n\t\t\t(?:((?:[a-z0-9-._~!$&'()*+,;=:]|%[0-9A-F]{2})*)@)?\t#userinfo\n\t\t\t((?:[a-z0-9-._~!$&'()*+,;=]|%[0-9A-F]{2})*|\\[(?:[0-9A-F:.]{2,})\\])\t#host (loose check to allow for IPv6 addresses)\n\t\t\t(?::(\\d*))?\t\t\t\t\t\t\t\t\t\t\t#port\n\t\t\t(\\/(?:[a-z0-9-._~!$&'()*+,;=:@\\/]|%[0-9A-F]{2})*)?\t#path\n\t\t\t|\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#it doesn't have an authority:\n\t\t\t(\\/?(?:[a-z0-9-._~!$&'()*+,;=:@]|%[0-9A-F]{2})+(?:[a-z0-9-._~!$&'()*+,;=:@\\/]|%[0-9A-F]{2})*)?\t#path\n\t\t)\n\t\t(?:\n\t\t\t\\?((?:[a-z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*)\t#query string\n\t\t)?\n\t\t(?:\n\t\t\t#((?:[a-z0-9-._~!$&'()*+,;=:/?@]|%[0-9A-F]{2})*)\t#fragment\n\t\t)?\n\t\t$\n\t*/\n\tif(!regexUri.test(str)) return null;\t//invalid URI\n \n\t//these extra steps are required to check for validity of the host depending on if it's a URL or not,\n\t// since URLs allow IPv6 addresses (i.e., they allow '[', ':', and ']')\n\tvar scheme = str.replace(regexUri, \"$1\").toLowerCase();\n\tvar host = str.replace(regexUri, \"$3\");\n\tif(host && (scheme == \"http\" || scheme == \"https\"))\t//if it's a URL\n\t{\n\t\tif(!normalizeURLDomain(host)) return null;\t//invalid host\n\t}\n\telse if(host)\t//host may not include '[', ':', or ']'\n\t{\n\t\tif((/[:\\[\\]]/).test(host)) return null;\t//invalid host\n\t}\n \n\tvar parts = {\n\t\turi: scheme+str.slice(scheme.length),\t//make sure scheme is lower case\n\t\tscheme: scheme,\n\t\tauthority: \"\",\t//userinfo@host:port\n\t\t\tuserinfo: str.replace(regexUri, \"$2\"),\n\t\t\thost: host,\n\t\t\tport: str.replace(regexUri, \"$4\"),\n\t\tpath: str.replace(regexUri, \"$5$6\"),\n\t\tquery: str.replace(regexUri, \"$7\"),\n\t\tfragment: str.replace(regexUri, \"$8\")\n\t};\n\tparts.authority = (parts.userinfo ? parts.userinfo+\"@\" : \"\") + parts.host + (parts.port ? \":\"+parts.port : \"\");\n \n\treturn parts;\n}",
"function uriConvertToURI()\n\t\t\t{\n\t\t\t\ttrace('\\n\\nTEST URI STATIC METHODS\\n')\n\t\t\t\ttest('convert to URIs', paths, URI.toURI);\n\t\t\t}",
"static splitURI(uri) {\nvar matches, pattern;\n// lggr.trace? \"Splitting #{uri}\"\npattern = RegExp(\"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\\\?([^#]*))?(#(.*))?\");\nmatches = uri.match(pattern);\nreturn {\nscheme: matches[2],\nauthority: matches[4],\npath: matches[5],\nquery: matches[7],\nfragment: matches[9]\n};\n}",
"function parseUri(url) {\n\t\tvar uri = \"\";\n\t\tvar token = \"://\";\n\t\tvar index = url.indexOf(token);\n\t\tvar part = \"\";\n\t\t\n\t\t/**\n\t\t * ensure to skip protocol and prepend context path for non-qualified\n\t\t * resources (ex: \"protect.html\" vs\n\t\t * \"/Owasp.CsrfGuard.Test/protect.html\").\n\t\t */\n\t\tif(index > 0) {\n\t\t\tpart = url.substring(index + token.length);\n\t\t} else if(url.charAt(0) != '/') {\n\t\t\tpart = \"%CONTEXT_PATH%/\" + url;\n\t\t} else {\n\t\t\tpart = url;\n\t\t}\n\t\t\n\t\t/** parse up to end or query string **/\n\t\tvar uriContext = (index == -1);\n\t\t\n\t\tfor(var i=0; i<part.length; i++) {\n\t\t\tvar character = part.charAt(i);\n\t\t\t\n\t\t\tif(character == '/') {\n\t\t\t\turiContext = true;\n\t\t\t} else if(uriContext == true && (character == '?' || character == '#')) {\n\t\t\t\turiContext = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tif(uriContext == true) {\n\t\t\t\turi += character;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn uri;\n\t}",
"function parseUri (str) {\n var o = {\n strictMode: false,\n key : [\"source\", \"protocol\", \"authority\", \"userInfo\", \"user\", \"password\", \"host\", \"port\", \"relative\", \"path\", \"directory\", \"file\", \"query\", \"anchor\"],\n q : {\n name : \"queryKey\",\n parser: /(?:^|&)([^&=]*)=?([^&]*)/g\n },\n parser : {\n strict: /^(?:([^:\\/?#]+):)?(?:\\/\\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\\/?#]*)(?::(\\d*))?))?((((?:[^?#\\/]*\\/)*)([^?#]*))(?:\\?([^#]*))?(?:#(.*))?)/,\n loose : /^(?:(?![^:@]+:[^:@\\/]*@)([^:\\/?#.]+):)?(?:\\/\\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\\/?#]*)(?::(\\d*))?)(((\\/(?:[^?#](?![^?#\\/]*\\.[^?#\\/.]+(?:[?#]|$)))*\\/?)?([^?#\\/]*))(?:\\?([^#]*))?(?:#(.*))?)/\n }\n },\n m = o.parser[o.strictMode ? \"strict\" : \"loose\"].exec(str),\n uri = {},\n i = 14;\n\n while (i--) {\n uri[o.key[i]] = m[i] || \"\";\n }\n\n uri[o.q.name] = {};\n uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {\n if ($1) {\n uri[o.q.name][$1] = $2;\n }\n });\n\n return uri;\n}",
"static parse(uri) {\n let path, fragment;\n [path, fragment] = uri.split(constants.ROOT_PATH_IDENTIFIER);\n if (fragment != null) {\n fragment = constants.ROOT_PATH_IDENTIFIER + fragment;\n } else {\n fragment = '';\n }\n return {path: path, fragment: fragment};\n }",
"function isURI(str) {\n return /^https?:\\/\\/(.*)/.test(str);\n}",
"function newParsingURI(aSpec) {\n let uri = Services.io.newURI(\"http://localhost\");\n if (Ci.nsIURIMutator) {\n uri = uri.mutate().setSpec(aSpec).finalize();\n } else {\n uri.spec = aSpec;\n }\n return uri;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
[BIM customize] Construct a different pack file reader, that use a different input stream implementation that use much less memory. | function PackFileReaderLess(data, usize) {
// When server side (S3 and viewing service) is configured properly,
// browser can decompress the pack file for us.
// Here the check is for backward compatibility purpose.
// ??? we actually rely on the server doesn't configure to let browser do the compress automatically.
// ??? Luckily at the moment, seems this is the case.
// ??? TODO: if we can't control the decompress on our own, then we have to
// ??? chunk fragment list to a reasonable size.
var stream;
var chunckStreamEnabled = false;
if (data[0] == 31 && data[1] == 139) {
// If usize is specified, we assume it is going to read pack file in a steaming style.
if (usize) {
// Decompress in a streaming style.
// Ok, let's use input steam less to decompress data chunck by chunck,
// so as to reduce the overall memory footprint.
// In theory, to read all the data there are 2 more times decompress needed.
// Round 1, decompress and get the first few values and then all the way to the end,
// and get toc/types offset, then throw all.
// Round 2, decompress to read content of toc and types only, then throw all.
// Round 3, decompress to each offset of fragment, and throw unused decompressed chunck.
// However, we could combine 1 and 2 together.
chunckStreamEnabled = true;
stream = new InputStreamLess(data, usize);
var len = stream.getInt32();
this.type = stream.getString(len);
this.version = stream.getInt32();
// To reduce the times for re-decompress the data, let's prepare the data
// for both round 1 and 2 cases.
var off = Math.floor(stream.byteLength * 0.9);
stream.seek(off, stream.byteLength - off);
} else {
// Decompress all at once, and use InputStream to read.
var gunzip = new Zlib.Gunzip(data);
data = gunzip.decompress();
stream = new InputStream(data);
var len = stream.getInt32();
this.type = stream.getString(len);
this.version = stream.getInt32();
}
} else {
// Already decopressed, so use InputStream.
// Input stream read data from the source that is alreay decompressed.
stream = new InputStream(data);
}
this.stream = stream;
this.types = null;
this.entryOffsets = [];
//read the table of contents
{
// Jump to file footer.
stream.seek(stream.byteLength - 8, 8, chunckStreamEnabled);
// Jump to toc.
var tocOffset = stream.getUint32();
this.typesOffset = stream.getUint32();
// Populate type sets.
stream.seek(this.typesOffset, 1, chunckStreamEnabled);
var typesCount = this.readU32V();
this.types = [];
for (var i = 0; i < typesCount; ++i) {
this.types.push({
"entryClass": this.readString(),
"entryType": this.readString(),
"version": this.readU32V() });
} // Populate data offset list.
stream.seek(tocOffset, 1, chunckStreamEnabled);
var entryCount = this.readU32V();
var dso = this.entryOffsets;
for (var i = 0; i < entryCount; ++i) {
dso.push(stream.getUint32());
} // Restore sanity of the world.
stream.seek(0);
}
} | [
"function ReaderFactory() {}",
"function Reader(input) {\n this.stream = input;\n if (input[externalBuffer]) {\n this[externalBuffer] = input[externalBuffer].slice();\n }\n let streamType = _streams2.default.isStream(input);\n if (streamType === 'node') {\n input = _streams2.default.nodeToWeb(input);\n }\n if (streamType) {\n const reader = input.getReader();\n this._read = reader.read.bind(reader);\n this._releaseLock = () => {\n reader.closed.catch(function () {});\n reader.releaseLock();\n };\n return;\n }\n let doneReading = false;\n this._read = async () => {\n if (doneReading || doneReadingSet.has(input)) {\n return { value: undefined, done: true };\n }\n doneReading = true;\n return { value: input, done: false };\n };\n this._releaseLock = () => {\n if (doneReading) {\n try {\n doneReadingSet.add(input);\n } catch (e) {}\n }\n };\n}",
"function Reader(input) {\n this.stream = input;\n if (input[externalBuffer]) {\n this[externalBuffer] = input[externalBuffer].slice();\n }\n let streamType = stream.isStream(input);\n if (streamType === 'node') {\n input = stream.nodeToWeb(input);\n }\n if (streamType) {\n const reader = input.getReader();\n this._read = reader.read.bind(reader);\n this._releaseLock = () => {\n reader.closed.catch(function() {});\n reader.releaseLock();\n };\n return;\n }\n let doneReading = false;\n this._read = async () => {\n if (doneReading || doneReadingSet.has(input)) {\n return { value: undefined, done: true };\n }\n doneReading = true;\n return { value: input, done: false };\n };\n this._releaseLock = () => {\n if (doneReading) {\n try {\n doneReadingSet.add(input);\n } catch(e) {}\n }\n };\n}",
"function createReadStreamBackpressureManager(readableStream) {\n\tconst manager = {\n\t\twaitPush: true,\n\t\tprogrammedPushs: [],\n\t\tprogramPush(chunk, encoding, isDone = () => {}) {\n\t\t\t// Store the current write\n\t\t\tmanager.programmedPushs.push([chunk, encoding, isDone]);\n\t\t\t// Need to be async to avoid nested push attempts\n\t\t\t// Programm a push attempt\n\t\t\tsetImmediate(manager.attemptPush);\n\t\t\t// Let's say we're ready for a read\n\t\t\treadableStream.emit('readable');\n\t\t\treadableStream.emit('drain');\n\t\t},\n\t\tattemptPush() {\n\t\t\tlet nextPush;\n\n\t\t\tif (manager.waitPush) {\n\t\t\t\tif (manager.programmedPushs.length > 0) {\n\t\t\t\t\tnextPush = manager.programmedPushs.shift();\n\t\t\t\t\tmanager.waitPush = readableStream.push(nextPush[0], nextPush[1]);\n\t\t\t\t\t(nextPush[2])();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsetImmediate(() => {\n\t\t\t\t\t// Need to be async to avoid nested push attempts\n\t\t\t\t\treadableStream.emit('readable');\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t};\n\n\tfunction streamFilterRestoreRead() {\n\t\tmanager.waitPush = true;\n\t\t// Need to be async to avoid nested push attempts\n\t\tsetImmediate(manager.attemptPush);\n\t}\n\n\t// Patch the readable stream to manage reads\n\treadableStream._read = streamFilterRestoreRead;\n\n\treturn manager;\n}",
"function p2FormatReader(opt_FileReader) {\n this.filereader = opt_FileReader; // Keep track of the file reader provided\n\n this.headerBufffer = null; // ArrayBuffer holding the raw data\n\n this.indexBuffer = null; // ArrayBuffer holding the raw data\n this.indexOffset = null; // Start position of the index in the file\n\n this.indexSize = null; // Size of the index in bytes\n this.index = null; // Decoded index as hash\n\n this.blockSize = null; // Blocksize for this file, set by the header (currently 2MB)\n\n this.dataOffset = null; // Where the data starts\n\n //this.readHeaderIndex(); // Load the file header and index\n\n\n this.INITIALIZING = 0;\n this.READY = 1;\n\n this.state = this.INITIALIZING;\n\n // Hash array of listeners\n this.listeners = {};\n\n}",
"static async readFrom(stream) {\n let playerIndex;\n playerIndex = await stream.readInt();\n let number;\n number = await stream.readInt();\n let departureTick;\n departureTick = await stream.readInt();\n let departurePlanet;\n departurePlanet = await stream.readInt();\n let nextPlanetArrivalTick;\n nextPlanetArrivalTick = await stream.readInt();\n let nextPlanet;\n nextPlanet = await stream.readInt();\n let targetPlanet;\n targetPlanet = await stream.readInt();\n let resource;\n if (await stream.readBool()) {\n resource = await Resource.readFrom(stream);\n } else {\n resource = null;\n }\n return new FlyingWorkerGroup(playerIndex, number, departureTick, departurePlanet, nextPlanetArrivalTick, nextPlanet, targetPlanet, resource);\n }",
"readTarball(name) {\n /**\n * Example of implementation:\n * const stream = new ReadTarball({});\n return stream;\n */\n }",
"async function listpack (stream, onData) {\n let reader = new StreamReader(stream);\n let hash = new Hash();\n let PACK = await reader.read(4);\n hash.update(PACK);\n PACK = PACK.toString('utf8');\n if (PACK !== 'PACK') {\n throw new GitError(E.InternalFail, {\n message: `Invalid PACK header '${PACK}'`\n })\n }\n\n let version = await reader.read(4);\n hash.update(version);\n version = version.readUInt32BE(0);\n if (version !== 2) {\n throw new GitError(E.InternalFail, {\n message: `Invalid packfile version: ${version}`\n })\n }\n\n let numObjects = await reader.read(4);\n hash.update(numObjects);\n numObjects = numObjects.readUInt32BE(0);\n // If (for some godforsaken reason) this is an empty packfile, abort now.\n if (numObjects < 1) return\n\n while (!reader.eof() && numObjects--) {\n let offset = reader.tell();\n let { type, length, ofs, reference } = await parseHeader(reader, hash);\n let inflator = new pako.Inflate();\n while (!inflator.result) {\n let chunk = await reader.chunk();\n if (reader.ended) break\n inflator.push(chunk, false);\n if (inflator.err) {\n throw new GitError(E.InternalFail, {\n message: `Pako error: ${inflator.msg}`\n })\n }\n if (inflator.result) {\n if (inflator.result.length !== length) {\n throw new GitError(E.InternalFail, {\n message: `Inflated object size is different from that stated in packfile.`\n })\n }\n\n // Backtrack parser to where deflated data ends\n await reader.undo();\n let buf = await reader.read(chunk.length - inflator.strm.avail_in);\n hash.update(buf);\n let end = reader.tell();\n onData({\n data: inflator.result,\n type,\n num: numObjects,\n offset,\n end,\n reference,\n ofs\n });\n } else {\n hash.update(chunk);\n }\n }\n }\n}",
"async function listpack (stream, onData) {\n const reader = new StreamReader(stream);\n let PACK = await reader.read(4);\n PACK = PACK.toString('utf8');\n if (PACK !== 'PACK') {\n throw new GitError(E.InternalFail, {\n message: `Invalid PACK header '${PACK}'`\n })\n }\n\n let version = await reader.read(4);\n version = version.readUInt32BE(0);\n if (version !== 2) {\n throw new GitError(E.InternalFail, {\n message: `Invalid packfile version: ${version}`\n })\n }\n\n let numObjects = await reader.read(4);\n numObjects = numObjects.readUInt32BE(0);\n // If (for some godforsaken reason) this is an empty packfile, abort now.\n if (numObjects < 1) return\n\n while (!reader.eof() && numObjects--) {\n const offset = reader.tell();\n const { type, length, ofs, reference } = await parseHeader(reader);\n const inflator = new pako.Inflate();\n while (!inflator.result) {\n const chunk = await reader.chunk();\n if (reader.ended) break\n inflator.push(chunk, false);\n if (inflator.err) {\n throw new GitError(E.InternalFail, {\n message: `Pako error: ${inflator.msg}`\n })\n }\n if (inflator.result) {\n if (inflator.result.length !== length) {\n throw new GitError(E.InternalFail, {\n message: `Inflated object size is different from that stated in packfile.`\n })\n }\n\n // Backtrack parser to where deflated data ends\n await reader.undo();\n await reader.read(chunk.length - inflator.strm.avail_in);\n const end = reader.tell();\n onData({\n data: inflator.result,\n type,\n num: numObjects,\n offset,\n end,\n reference,\n ofs\n });\n }\n }\n }\n}",
"async function listpack(stream, onData) {\n const reader = new StreamReader(stream);\n let PACK = await reader.read(4);\n PACK = PACK.toString('utf8');\n if (PACK !== 'PACK') {\n throw new InternalError(`Invalid PACK header '${PACK}'`)\n }\n\n let version = await reader.read(4);\n version = version.readUInt32BE(0);\n if (version !== 2) {\n throw new InternalError(`Invalid packfile version: ${version}`)\n }\n\n let numObjects = await reader.read(4);\n numObjects = numObjects.readUInt32BE(0);\n // If (for some godforsaken reason) this is an empty packfile, abort now.\n if (numObjects < 1) return\n\n while (!reader.eof() && numObjects--) {\n const offset = reader.tell();\n const { type, length, ofs, reference } = await parseHeader(reader);\n const inflator = new pako.Inflate();\n while (!inflator.result) {\n const chunk = await reader.chunk();\n if (!chunk) break\n inflator.push(chunk, false);\n if (inflator.err) {\n throw new InternalError(`Pako error: ${inflator.msg}`)\n }\n if (inflator.result) {\n if (inflator.result.length !== length) {\n throw new InternalError(\n `Inflated object size is different from that stated in packfile.`\n )\n }\n\n // Backtrack parser to where deflated data ends\n await reader.undo();\n await reader.read(chunk.length - inflator.strm.avail_in);\n const end = reader.tell();\n await onData({\n data: inflator.result,\n type,\n num: numObjects,\n offset,\n end,\n reference,\n ofs,\n });\n }\n }\n }\n}",
"function createReader (src, options) {\n // create a reader for the DXF\n let reader = dxf.reader(options)\n\n // setup event handling from the reader\n reader.on('error', handleError)\n reader.on('start', handleStart)\n reader.on('end', handleEnd)\n\n // setup group handling\n reader.absorb(0, handleEntity)\n reader.absorb(1, handleString)\n reader.absorb(2, handleName)\n reader.absorb(3, handleName)\n reader.absorb(6, handleString)\n reader.absorb(7, handleString)\n reader.absorb(8, handleString)\n reader.absorb(9, handleVariable)\n reader.absorb(10, handleXcoord)\n reader.absorb(11, handleDouble)\n reader.absorb(12, handleDouble)\n reader.absorb(13, handleDouble)\n reader.absorb(20, handleYcoord)\n reader.absorb(21, handleDouble)\n reader.absorb(22, handleDouble)\n reader.absorb(23, handleDouble)\n reader.absorb(30, handleZcoord)\n reader.absorb(31, handleDouble)\n reader.absorb(32, handleDouble)\n reader.absorb(33, handleDouble)\n reader.absorb(39, handleDouble)\n reader.absorb(40, handleDouble)\n reader.absorb(41, handleDouble)\n reader.absorb(42, handleBulge)\n reader.absorb(50, handleDouble)\n reader.absorb(51, handleDouble)\n reader.absorb(62, handleInt)\n reader.absorb(70, handleInt)\n reader.absorb(71, handleInt)\n reader.absorb(72, handleInt)\n reader.absorb(73, handleInt)\n reader.absorb(74, handleInt)\n reader.absorb(75, handleInt)\n reader.absorb(90, handleValue)\n reader.absorb(91, handleLen) // MESH\n reader.absorb(92, handleLen) // MESH\n reader.absorb(93, handleLen) // MESH\n reader.absorb(94, handleLen) // MESH\n reader.absorb(95, handleLen) // MESH\n reader.absorb(210, handleInt)\n reader.absorb(220, handleInt)\n reader.absorb(230, handleInt)\n\n // initial state\n reader.objstack = []\n reader.objstack.push({type: 'dxf'})\n\n // start the reader\n reader.write(src).close()\n return reader\n}",
"loadStream( stream, blockSize ) {\n\n let me = this;\n\n return new Promise( function( resolve, reject ) {\n\n me.blockSize = blockSize;\n me.blocks = []; \n me.linesInFile = 0;\n\n let errors = 0;\n let complete = 0;\n let errorText = '';\n\n // when done for any reason, close out the promise\n function done() {\n \n if( errors > 0 ){\n\n reject( new Error( 'Error(s) occured reading the HEX file: ' + errorText ));\n\n }\n else if( complete ) {\n\n resolve( me.blocks );\n }\n else {\n reject(new Error( 'Incomplete file'));\n }\n }\n\n let lineReader = require('readline').createInterface({\n input: stream\n });\n\n stream.on('error', function () {\n errors = 1;\n errorText = 'File read error';\n done();\n });\n\n\n\n lineReader.on('line', function (line) {\n me.linesInFile++;\n\n line = line.trim();\n\n if( line > '' ) {\n\n try {\n let record = me.parseHexLine( line );\n\n if( record.type === END_OF_FILE ) {\n complete = 1;\n }\n else {\n me.processRecord( record );\n }\n }\n catch( e ) {\n\n if( errorText === '' ) {\n errorText = e.message;\n }\n\n errors++;\n }\n\n }\n });\n\n // End of file\n lineReader.on('close', done );\n\n });\n \n }",
"read() {\n\n\t\t// If the entry was already read, don't read it again. Note that it's \n\t\t// possible to dispose the entry to free up some memory if required.\n\t\tif (this.file) {\n\t\t\treturn this.file;\n\t\t}\n\n\t\t// Before reading the entry, we'll emit an event on the owning DBPF. \n\t\t// As such a cache can keep track of which DBPF files are read from \n\t\t// most often.\n\t\tthis.dbpf.emit('read');\n\n\t\t// If the entry is compressed, decompress it.\n\t\tthis.readRaw();\n\t\tlet buff = this.decompress();\n\n\t\t// Now check for known file types.\n\t\t// TODO: We should change this and allow custom file types to be \n\t\t// registered!\n\t\tlet Klass = DBPF.FileTypes[this.type];\n\t\tif (!Klass) {\n\t\t\treturn buff;\n\t\t} else {\n\t\t\tlet file = this.file = new Klass();\n\t\t\tfile.parse(buff, { entry: this });\n\t\t\treturn file;\n\t\t}\n\n\t}",
"function createReaderSync()\n{\n return new FileReaderSync();\n}",
"function Reader(name) {\n\tif (this instanceof Reader) {\n\t\tthis.javaFile = new java.io.BufferedReader(new java.io.InputStreamReader(name ? new java.io.FileInputStream(name) : java.System[\"in\"]));\n\t}\n\telse {\n\t\treturn new Reader(name);\n\t}\n}",
"static async readFrom(stream) {\n let id;\n id = await stream.readInt();\n let x;\n x = await stream.readInt();\n let y;\n y = await stream.readInt();\n let harvestableResource;\n if (await stream.readBool()) {\n harvestableResource = await Resource.readFrom(stream);\n } else {\n harvestableResource = null;\n }\n let workerGroups;\n workerGroups = [];\n for (let workerGroupsCount = await stream.readInt(); workerGroupsCount > 0; workerGroupsCount--) {\n let workerGroupsElement;\n workerGroupsElement = await WorkerGroup.readFrom(stream);\n workerGroups.push(workerGroupsElement);\n }\n let resources;\n resources = new Map();\n for (let resourcesCount = await stream.readInt(); resourcesCount > 0; resourcesCount--) {\n let resourcesKey;\n let resourcesValue;\n resourcesKey = await Resource.readFrom(stream);\n resourcesValue = await stream.readInt();\n resources.set(resourcesKey, resourcesValue)\n }\n let building;\n if (await stream.readBool()) {\n building = await Building.readFrom(stream);\n } else {\n building = null;\n }\n return new Planet(id, x, y, harvestableResource, workerGroups, resources, building);\n }",
"function ReadTarball(options) {\n var self = new Stream.PassThrough(options)\n Object.setPrototypeOf(self, ReadTarball.prototype)\n\n // called when data is not needed anymore\n add_abstract_method(self, 'abort')\n\n return self\n}",
"function streamFactory( size ){\n size = size || 100;\n return batchify.obj({ batchSize: size, highWaterMark: 2 }, function( batch, _, next ){\n this.push( batch );\n next();\n });\n}",
"function PDFRStreamForFile(inPath)\n{\n this.rs = fs.openSync(inPath,'r');\n this.path = inPath;\n this.rposition = 0;\n this.fileSize = fs.statSync(inPath)[\"size\"];\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.